nkn-sdk-go: github.com/nknorg/nkn-sdk-go Index | Files | Directories

package nkn

import "github.com/nknorg/nkn-sdk-go"

Package nkn provides Go implementation of NKN client and wallet SDK. The SDK consists of a few components:

1. NKN Client: Send and receive data for free between any NKN clients regardless their network condition without setting up a server or relying on any third party services. Data are end to end encrypted by default. Typically you might want to use multiclient instead of using client directly.

2. NKN MultiClient: Send and receive data using multiple NKN clients concurrently to improve reliability and latency. In addition, it supports session mode, a reliable streaming protocol similar to TCP based on ncp (https://github.com/nknorg/ncp-go).

3. NKN Wallet: Wallet SDK for NKN blockchain (https://github.com/nknorg/nkn). It can be used to create wallet, transfer token to NKN wallet address, register name, subscribe to topic, etc.

Feature Highlights

Advantages of using NKN client/multiclient for data transmission:

1. Network agnostic: Neither sender nor receiver needs to have public IP address or port forwarding. NKN clients only establish outbound (websocket) connections, so Internet access is all they need. This is ideal for client side peer to peer communication.

2. Top level security: All data are end to end authenticated and encrypted. No one else in the world except sender and receiver can see or modify the content of the data. The same public key is used for both routing and encryption, eliminating the possibility of man in the middle attack.

3. Decent performance: By aggregating multiple overlay paths concurrently, multiclient can get ~100ms end to end latency and 10+mbps end to end session throughput between international devices.

4. Everything is free, open source and decentralized. (If you are curious, node relay traffic for clients for free to earn mining rewards in NKN blockchain.)

Gomobile

This library is designed to work with gomobile (https://godoc.org/golang.org/x/mobile/cmd/gomobile) and run natively on iOS/Android without any modification. You can use gomobile to compile it to Objective-C framework for iOS:

gomobile bind -target=ios -ldflags "-s -w" github.com/nknorg/nkn-sdk-go github.com/nknorg/ncp-go github.com/nknorg/nkn/v2/transaction

and Java AAR for Android:

gomobile bind -target=android -ldflags "-s -w" github.com/nknorg/nkn-sdk-go github.com/nknorg/ncp-go github.com/nknorg/nkn/v2/transaction

It's recommended to use the latest version of gomobile that supports go modules.

Index

Package Files

client.go config.go doc.go error.go message.go multiclient.go nanopay.go rpc.go util.go wallet.go

Constants

const (
    BinaryType  = int32(payloads.BINARY)
    TextType    = int32(payloads.TEXT)
    AckType     = int32(payloads.ACK)
    SessionType = int32(payloads.SESSION)
)

Payload type alias for gomobile compatibility.

const (
    // MultiClientIdentifierRe is the regular expression to check whether an
    // identifier is a multiclient protocol identifier.
    MultiClientIdentifierRe = "^__\\d+__$"

    // DefaultSessionAllowAddr is the default session allow address if none is
    // provided when calling listen.
    DefaultSessionAllowAddr = ".*"

    // SessionIDSize is the default session id size in bytes.
    SessionIDSize = MessageIDSize
)
const (
    // AmountUnit is the inverse of the NKN precision
    AmountUnit = common.StorageFactor
)
const (
    // MessageIDSize is the default message id size in bytes
    MessageIDSize = 8
)

Variables

var (
    ErrClosed               = ncp.NewGenericError("use of closed network connection", true, true) // The error message is meant to be identical to error returned by net package.
    ErrKeyNotInMap          = errors.New("key not in map")                                        // for gomobile
    ErrInvalidPayloadType   = errors.New("invalid payload type")
    ErrConnectFailed        = errors.New("connect failed")
    ErrNoDestination        = errors.New("no destination")
    ErrInvalidDestination   = errors.New("invalid destination")
    ErrInvalidPubkeyOrName  = errors.New("invalid public key or name")
    ErrInvalidPubkeySize    = errors.New("invalid public key size")
    ErrInvalidPubkey        = errors.New("invalid public key")
    ErrMessageOversize      = fmt.Errorf("encoded message is greater than %v bytes", maxClientMessageSize)
    ErrNilWebsocketConn     = errors.New("nil websocket connection")
    ErrDecryptFailed        = errors.New("decrypt message failed")
    ErrAddrNotAllowed       = errors.New("address not allowed")
    ErrCreateClientFailed   = errors.New("failed to create client")
    ErrNilClient            = errors.New("client is nil")
    ErrNotNanoPay           = errors.New("not nano pay transaction")
    ErrWrongRecipient       = errors.New("wrong nano pay recipient")
    ErrNanoPayClosed        = errors.New("use of closed nano pay claimer")
    ErrInsufficientBalance  = errors.New("insufficient balance")
    ErrInvalidAmount        = errors.New("invalid amount")
    ErrExpiredNanoPay       = errors.New("nanopay expired")
    ErrExpiredNanoPayTxn    = errors.New("nanopay transaction expired")
    ErrWrongPassword        = errors.New("wrong password")
    ErrInvalidWalletVersion = fmt.Errorf("invalid wallet version, should be between %v and %v", vault.MinCompatibleWalletVersion, vault.MaxCompatibleWalletVersion)
)

Error definitions.

var DefaultClientConfig = ClientConfig{
    SeedRPCServerAddr:       nil,
    MsgChanLen:              1024,
    ConnectRetries:          3,
    MsgCacheExpiration:      300000,
    MsgCacheCleanupInterval: 60000,
    WsHandshakeTimeout:      5000,
    WsWriteTimeout:          10000,
    MinReconnectInterval:    1000,
    MaxReconnectInterval:    64000,
    MessageConfig:           nil,
    SessionConfig:           nil,
}

DefaultClientConfig is the default client config.

var DefaultDialConfig = DialConfig{
    DialTimeout:   0,
    SessionConfig: nil,
}

DefaultDialConfig is the default dial config.

var DefaultMessageConfig = MessageConfig{
    Unencrypted:       false,
    NoReply:           false,
    MaxHoldingSeconds: 0,
    MessageID:         nil,
    TxPool:            false,
    Offset:            0,
    Limit:             1000,
}

DefaultMessageConfig is the default message config.

var DefaultRPCConfig = RPCConfig{
    SeedRPCServerAddr: nil,
}

DefaultRPCConfig is the default rpc configuration.

var DefaultSeedRPCServerAddr = []string{
    "http://seed.nkn.org:30003",
}

DefaultSeedRPCServerAddr is the default seed rpc server address list.

var DefaultSessionConfig = ncp.Config{
    MTU: 1024,
}

DefaultSessionConfig is the default session config. Unspecific fields here will use the default config in https://github.com/nknorg/ncp-go.

var DefaultTransactionConfig = TransactionConfig{
    Fee:        "0",
    Nonce:      0,
    Attributes: nil,
}

DefaultTransactionConfig is the default TransactionConfig.

var DefaultWalletConfig = WalletConfig{
    SeedRPCServerAddr: nil,
    IV:                nil,
    MasterKey:         nil,
    ScryptConfig:      nil,
}

DefaultWalletConfig is the default wallet configuration.

func ClientAddrToPubKey Uses

func ClientAddrToPubKey(clientAddr string) ([]byte, error)

ClientAddrToPubKey converts a NKN client address to its public key.

func ClientAddrToWalletAddr Uses

func ClientAddrToWalletAddr(clientAddr string) (string, error)

ClientAddrToWalletAddr converts a NKN client address to its NKN wallet address. It's a shortcut for calling ClientAddrToPubKey followed by PubKeyToWalletAddr.

func DeleteName Uses

func DeleteName(s signerRPCClient, name string, config *TransactionConfig) (string, error)

DeleteName deletes a name owned by this signer's pubkey with a given transaction fee. The signerRPCClient can be a client, multiclient or wallet.

func GetDefaultSessionConfig Uses

func GetDefaultSessionConfig() *ncp.Config

GetDefaultSessionConfig returns the default session config.

func GetHeight Uses

func GetHeight(config RPCConfigInterface) (int32, error)

GetHeight RPC returns the latest block height.

func GetNonce Uses

func GetNonce(address string, txPool bool, config RPCConfigInterface) (int64, error)

GetNonce RPC gets the next nonce to use of an address. If txPool is false, result only counts transactions in ledger; if txPool is true, transactions in txPool are also counted.

Nonce is changed to signed int for gomobile compatibility.

func GetSubscribersCount Uses

func GetSubscribersCount(topic string, config RPCConfigInterface) (int, error)

GetSubscribersCount RPC returns the number of subscribers of a topic (not including txPool).

Count is changed to signed int for gomobile compatibility

func PubKeyToWalletAddr Uses

func PubKeyToWalletAddr(pubKey []byte) (string, error)

PubKeyToWalletAddr converts a public key to its NKN wallet address.

func RPCCall Uses

func RPCCall(action string, params map[string]interface{}, result interface{}, config RPCConfigInterface) error

RPCCall makes a RPC call and put results to result passed in.

func RandomBytes Uses

func RandomBytes(numBytes int) ([]byte, error)

RandomBytes return cryptographically secure random bytes with given size.

func RegisterName Uses

func RegisterName(s signerRPCClient, name string, config *TransactionConfig) (string, error)

RegisterName registers a name for this signer's public key at the cost of 10 NKN with a given transaction fee. The name will be valid for 1,576,800 blocks (around 1 year). Register name currently owned by this pubkey will extend the duration of the name to current block height + 1,576,800. Registration will fail if the name is currently owned by another account. The signerRPCClient can be a client, multiclient or wallet.

func SendRawTransaction Uses

func SendRawTransaction(txn *transaction.Transaction, config RPCConfigInterface) (string, error)

SendRawTransaction RPC sends a signed transaction to chain and returns txn hash hex string.

func Subscribe Uses

func Subscribe(s signerRPCClient, identifier, topic string, duration int, meta string, config *TransactionConfig) (string, error)

Subscribe to a topic with an identifier for a number of blocks. Client using the same key pair and identifier will be able to receive messages from this topic. If this (identifier, public key) pair is already subscribed to this topic, the subscription expiration will be extended to current block height + duration. The signerRPCClient can be a client, multiclient or wallet.

Duration is changed to signed int for gomobile compatibility.

func Transfer Uses

func Transfer(s signerRPCClient, address, amount string, config *TransactionConfig) (string, error)

Transfer sends asset to a wallet address with a transaction fee. Amount is the string representation of the amount in unit of NKN to avoid precision loss. For example, "0.1" will be parsed as 0.1 NKN. The signerRPCClient can be a client, multiclient or wallet.

func TransferName Uses

func TransferName(s signerRPCClient, name string, recipientPubKey []byte, config *TransactionConfig) (string, error)

TransferName transfers a name owned by this signer's pubkey to another public key with a transaction fee. The expiration height of the name will not be changed. The signerRPCClient can be a client, multiclient or wallet.

func Unsubscribe Uses

func Unsubscribe(s signerRPCClient, identifier, topic string, config *TransactionConfig) (string, error)

Unsubscribe from a topic for an identifier. Client using the same key pair and identifier will no longer receive messages from this topic. The signerRPCClient can be a client, multiclient or wallet.

func VerifyWalletAddress Uses

func VerifyWalletAddress(address string) error

VerifyWalletAddress returns error if the given wallet address is invalid.

type Account Uses

type Account struct{ *vault.Account }

Account is a wrapper type for gomobile compatibility.

func NewAccount Uses

func NewAccount(seed []byte) (*Account, error)

NewAccount creates an account from secret seed. Seed length should be 32 or 0. If seed has zero length (including nil), a random seed will be generated.

func (*Account) PubKey Uses

func (account *Account) PubKey() []byte

PubKey returns the public key of the account.

func (*Account) Seed Uses

func (account *Account) Seed() []byte

Seed returns the secret seed of the account. Secret seed can be used to create client/wallet with the same key pair and should be kept secret and safe.

func (*Account) WalletAddress Uses

func (account *Account) WalletAddress() string

WalletAddress returns the wallet address of the account.

type Amount Uses

type Amount struct{ common.Fixed64 }

Amount is a wrapper type for gomobile compatibility.

func GetBalance Uses

func GetBalance(address string, config RPCConfigInterface) (*Amount, error)

GetBalance RPC returns the balance of a wallet address.

func NewAmount Uses

func NewAmount(s string) (*Amount, error)

NewAmount creates an amount from string in unit of NKN. For example, "0.1" will be parsed as 0.1 NKN.

func (*Amount) ToFixed64 Uses

func (amount *Amount) ToFixed64() common.Fixed64

ToFixed64 returns amount as Fixed64 type.

type Client Uses

type Client struct {
    OnConnect *OnConnect // Event emitting channel when client connects to node and becomes ready to send messages. One should only use the first event of the channel.
    OnMessage *OnMessage // Event emitting channel when client receives a message (not including reply or ACK).
    // contains filtered or unexported fields
}

Client sends and receives data between any NKN clients regardless their network condition without setting up a server or relying on any third party services. Data are end to end encrypted by default. Typically you might want to use multiclient instead of using client directly.

func NewClient Uses

func NewClient(account *Account, identifier string, config *ClientConfig) (*Client, error)

NewClient creates a client with an account, an optional identifier, and a optional client config. For any zero value field in config, the default client config value will be used. If config is nil, the default client config will be used.

func (*Client) Account Uses

func (c *Client) Account() *Account

Account returns the account of the client.

func (*Client) Address Uses

func (c *Client) Address() string

Address returns the NKN client address of the client. Client address is in the form of

identifier.pubKeyHex

if identifier is not an empty string, or

pubKeyHex

if identifier is an empty string.

Note that client address is different from wallet address using the same key pair (account). Wallet address can be computed from client address, but NOT vice versa.

func (*Client) Balance Uses

func (c *Client) Balance() (*Amount, error)

Balance is the same as package level GetBalance, but using connected node as the RPC server, followed by this client's SeedRPCServerAddr if failed.

func (*Client) BalanceByAddress Uses

func (c *Client) BalanceByAddress(address string) (*Amount, error)

BalanceByAddress is the same as package level GetBalance, but using connected node as the RPC server, followed by this client's SeedRPCServerAddr if failed.

func (*Client) Close Uses

func (c *Client) Close() error

Close closes the client.

func (*Client) DeleteName Uses

func (c *Client) DeleteName(name string, config *TransactionConfig) (string, error)

DeleteName is a shortcut for DeleteName using this client as SignerRPCClient.

func (*Client) GetConn Uses

func (c *Client) GetConn() *websocket.Conn

GetConn returns the current websocket connection client is using.

func (*Client) GetHeight Uses

func (c *Client) GetHeight() (int32, error)

GetHeight is the same as package level GetHeight, but using connected node as the RPC server, followed by this client's SeedRPCServerAddr if failed.

func (*Client) GetNode Uses

func (c *Client) GetNode() *Node

GetNode returns the node that client is currently connected to.

func (*Client) GetNonce Uses

func (c *Client) GetNonce(txPool bool) (int64, error)

GetNonce is the same as package level GetNonce, but using connected node as the RPC server, followed by this client's SeedRPCServerAddr if failed.

func (*Client) GetNonceByAddress Uses

func (c *Client) GetNonceByAddress(address string, txPool bool) (int64, error)

GetNonceByAddress is the same as package level GetNonce, but using connected node as the RPC server, followed by this client's SeedRPCServerAddr if failed.

func (*Client) GetRegistrant Uses

func (c *Client) GetRegistrant(name string) (*Registrant, error)

GetRegistrant is the same as package level GetRegistrant, but using connected node as the RPC server, followed by this client's SeedRPCServerAddr if failed.

func (*Client) GetSubscribers Uses

func (c *Client) GetSubscribers(topic string, offset, limit int, meta, txPool bool) (*Subscribers, error)

GetSubscribers is the same as package level GetSubscribers, but using connected node as the RPC server, followed by this client's SeedRPCServerAddr if failed.

func (*Client) GetSubscribersCount Uses

func (c *Client) GetSubscribersCount(topic string) (int, error)

GetSubscribersCount is the same as package level GetSubscribersCount, but using connected node as the RPC server, followed by this client's SeedRPCServerAddr if failed.

func (*Client) GetSubscription Uses

func (c *Client) GetSubscription(topic string, subscriber string) (*Subscription, error)

GetSubscription is the same as package level GetSubscription, but using connected node as the RPC server, followed by this client's SeedRPCServerAddr if failed.

func (*Client) IsClosed Uses

func (c *Client) IsClosed() bool

IsClosed returns whether the client is closed and should not be used anymore.

func (*Client) NewNanoPay Uses

func (c *Client) NewNanoPay(recipientAddress, fee string, duration int) (*NanoPay, error)

NewNanoPay is a shortcut for NewNanoPay using this client's wallet address as sender.

Duration is changed to signed int for gomobile compatibility.

func (*Client) NewNanoPayClaimer Uses

func (c *Client) NewNanoPayClaimer(recipientAddress string, claimIntervalMs int32, onError *OnError) (*NanoPayClaimer, error)

NewNanoPayClaimer is a shortcut for NewNanoPayClaimer using this client as RPC client.

func (*Client) PubKey Uses

func (c *Client) PubKey() []byte

PubKey returns the public key of the client.

func (*Client) Publish Uses

func (c *Client) Publish(topic string, data interface{}, config *MessageConfig) error

Publish sends bytes or string data to all subscribers of a topic with an optional config.

func (*Client) PublishBinary Uses

func (c *Client) PublishBinary(topic string, data []byte, config *MessageConfig) error

PublishBinary is a wrapper of Publish without interface type for gomobile compatibility.

func (*Client) PublishText Uses

func (c *Client) PublishText(topic string, data string, config *MessageConfig) error

PublishText is a wrapper of Publish without interface type for gomobile compatibility.

func (*Client) Reconnect Uses

func (c *Client) Reconnect()

Reconnect forces the client to find node and connect again.

func (*Client) RegisterName Uses

func (c *Client) RegisterName(name string, config *TransactionConfig) (string, error)

RegisterName is a shortcut for RegisterName using this client as SignerRPCClient.

func (*Client) Seed Uses

func (c *Client) Seed() []byte

Seed returns the secret seed of the client. Secret seed can be used to create client/wallet with the same key pair and should be kept secret and safe.

func (*Client) Send Uses

func (c *Client) Send(dests *StringArray, data interface{}, config *MessageConfig) (*OnMessage, error)

Send sends bytes or string data to one or multiple destinations with an optional config. Returned OnMessage channel will emit if a reply or ACK for this message is received.

func (*Client) SendBinary Uses

func (c *Client) SendBinary(dests *StringArray, data []byte, config *MessageConfig) (*OnMessage, error)

SendBinary is a wrapper of Send without interface type for gomobile compatibility.

func (*Client) SendRawTransaction Uses

func (c *Client) SendRawTransaction(txn *transaction.Transaction) (string, error)

SendRawTransaction is the same as package level SendRawTransaction, but using connected node as the RPC server, followed by this client's SeedRPCServerAddr if failed.

func (*Client) SendText Uses

func (c *Client) SendText(dests *StringArray, data string, config *MessageConfig) (*OnMessage, error)

SendText is a wrapper of Send without interface type for gomobile compatibility.

func (*Client) SetWriteDeadline Uses

func (c *Client) SetWriteDeadline(deadline time.Time) error

SetWriteDeadline sets the write deadline of the websocket connection.

func (*Client) SignTransaction Uses

func (c *Client) SignTransaction(tx *transaction.Transaction) error

SignTransaction signs an unsigned transaction using this client's key pair.

func (*Client) Subscribe Uses

func (c *Client) Subscribe(identifier, topic string, duration int, meta string, config *TransactionConfig) (string, error)

Subscribe is a shortcut for Subscribe using this client as SignerRPCClient.

Duration is changed to signed int for gomobile compatibility.

func (*Client) Transfer Uses

func (c *Client) Transfer(address, amount string, config *TransactionConfig) (string, error)

Transfer is a shortcut for Transfer using this client as SignerRPCClient.

func (*Client) TransferName Uses

func (c *Client) TransferName(name string, recipientPubKey []byte, config *TransactionConfig) (string, error)

TransferName is a shortcut for TransferName using this client as SignerRPCClient.

func (*Client) Unsubscribe Uses

func (c *Client) Unsubscribe(identifier, topic string, config *TransactionConfig) (string, error)

Unsubscribe is a shortcut for Unsubscribe using this client as SignerRPCClient.

type ClientAddr Uses

type ClientAddr struct {
    // contains filtered or unexported fields
}

ClientAddr represents NKN client address. It implements net.Addr interface.

func NewClientAddr Uses

func NewClientAddr(addr string) *ClientAddr

NewClientAddr creates a ClientAddr from a client address string.

func (ClientAddr) Network Uses

func (addr ClientAddr) Network() string

Network returns "nkn"

func (ClientAddr) String Uses

func (addr ClientAddr) String() string

String returns the NKN client address string.

type ClientConfig Uses

type ClientConfig struct {
    SeedRPCServerAddr       *StringArray   // Seed RPC server address that client uses to find its node and make RPC requests (e.g. get subscribers).
    MsgChanLen              int32          // Channel length for received but unproccessed messages.
    ConnectRetries          int32          // Connnect to node retries (including the initial connect). 0 means unlimited retries.
    MsgCacheExpiration      int32          // Message cache expiration in millisecond for response channel, multiclient message id deduplicate, etc.
    MsgCacheCleanupInterval int32          // Message cache cleanup interval in millisecond.
    WsHandshakeTimeout      int32          // WebSocket handshake timeout in millisecond.
    WsWriteTimeout          int32          // WebSocket write timeout in millisecond.
    MinReconnectInterval    int32          // Min reconnect interval in millisecond.
    MaxReconnectInterval    int32          // Max reconnect interval in millisecond.
    MessageConfig           *MessageConfig // Default message config of the client if per-message config is not provided.
    SessionConfig           *ncp.Config    // Default session config of the client if per-session config is not provided.
}

ClientConfig is the client configuration.

func GetDefaultClientConfig Uses

func GetDefaultClientConfig() *ClientConfig

GetDefaultClientConfig returns the default client config with nil pointer fields set to default.

func MergeClientConfig Uses

func MergeClientConfig(conf *ClientConfig) (*ClientConfig, error)

MergeClientConfig merges a given client config with the default client config recursively. Any non zero value fields will override the default config.

func (*ClientConfig) GetRandomSeedRPCServerAddr Uses

func (config *ClientConfig) GetRandomSeedRPCServerAddr() string

GetRandomSeedRPCServerAddr returns a random seed rpc server address from the client config.

type DialConfig Uses

type DialConfig struct {
    DialTimeout   int32       // Dial timeout in millisecond
    SessionConfig *ncp.Config // Per-session session config that will override client session config.
}

DialConfig is the dial config for session.

func GetDefaultDialConfig Uses

func GetDefaultDialConfig(baseSessionConfig *ncp.Config) *DialConfig

GetDefaultDialConfig returns the default dial config with nil pointer fields set to default.

func MergeDialConfig Uses

func MergeDialConfig(baseSessionConfig *ncp.Config, conf *DialConfig) (*DialConfig, error)

MergeDialConfig merges a given dial config with the default dial config recursively. Any non zero value fields will override the default config.

type ErrorWithCode Uses

type ErrorWithCode interface {
    error
    Code() int32
}

ErrorWithCode is an error interface that implements error and Code()

type Message Uses

type Message struct {
    Src       string // Sender's NKN client address.
    Data      []byte // Message data. If data type is string, one can call string() to convert it to original string data.
    Type      int32  // Message data type.
    Encrypted bool   // Whether message is encrypted.
    MessageID []byte // Message ID.
    NoReply   bool   // Indicating no reply or ACK should be sent.
    // contains filtered or unexported fields
}

Message contains the info of received message.

func (*Message) Reply Uses

func (msg *Message) Reply(data interface{}) error

Reply sends bytes or string data as reply to message sender.

func (*Message) ReplyBinary Uses

func (msg *Message) ReplyBinary(data []byte) error

ReplyBinary is a wrapper of Reply without interface type for gomobile compatibility.

func (*Message) ReplyText Uses

func (msg *Message) ReplyText(data string) error

ReplyText is a wrapper of Reply without interface type for gomobile compatibility.

type MessageConfig Uses

type MessageConfig struct {
    Unencrypted       bool   // Whether message body should be unencrypted. It is not recommended to send unencrypted message as anyone in the middle can see the message content.
    NoReply           bool   // Indicating the message will not have any reply or ACK, so client will not allocate any resources waiting for it.
    MaxHoldingSeconds int32  // Message will be held at node for at most this time if the destination client is not online. Note that message might be released earlier than this time if node runs out of resources.
    MessageID         []byte // Message ID. If nil, a random ID will be generated for each message. MessageID should be unique per message and has size MessageIDSize.

    // for publish
    TxPool bool  // Whether to include subscribers in txpool when publishing.
    Offset int32 // Offset for getting subscribers.
    Limit  int32 // Single request limit for getting subscribers
}

MessageConfig is the config for sending messages.

func GetDefaultMessageConfig Uses

func GetDefaultMessageConfig() *MessageConfig

GetDefaultMessageConfig returns the default message config.

func MergeMessageConfig Uses

func MergeMessageConfig(base, conf *MessageConfig) (*MessageConfig, error)

MergeMessageConfig merges a given message config with the default message config recursively. Any non zero value fields will override the default config.

type MultiClient Uses

type MultiClient struct {
    OnConnect *OnConnect // Event emitting channel when at least one client connects to node and becomes ready to send messages. One should only use the first event of the channel.
    OnMessage *OnMessage // Event emitting channel when at least one client receives a message (not including reply or ACK).
    // contains filtered or unexported fields
}

MultiClient sends and receives data using multiple NKN clients concurrently to improve reliability and latency. In addition, it supports session mode, a reliable streaming protocol similar to TCP based on ncp (https://github.com/nknorg/ncp-go).

func NewMultiClient Uses

func NewMultiClient(account *Account, baseIdentifier string, numSubClients int, originalClient bool, config *ClientConfig) (*MultiClient, error)

NewMultiClient creates a multiclient with an account, an optional identifier, number of sub clients to create, whether to create original client without identifier prefix, and a optional client config that will be applied to all clients created. For any zero value field in config, the default client config value will be used. If config is nil, the default client config will be used.

func (*MultiClient) Accept Uses

func (m *MultiClient) Accept() (net.Conn, error)

Accept is the same as AcceptSession, but the return type is net.Conn interface.

func (*MultiClient) AcceptSession Uses

func (m *MultiClient) AcceptSession() (*ncp.Session, error)

AcceptSession will wait and return the first incoming session from allowed remote addresses. If multiclient is closed, it will return immediately with ErrClosed.

func (*MultiClient) Account Uses

func (m *MultiClient) Account() *Account

Account returns the account of the multiclient.

func (*MultiClient) Addr Uses

func (m *MultiClient) Addr() net.Addr

Addr returns the NKN client address of the multiclient as net.Addr interface, with Network() returns "nkn" and String() returns the same value as multiclient.Address().

func (*MultiClient) Address Uses

func (m *MultiClient) Address() string

Address returns the NKN client address of the multiclient. Client address is in the form of

identifier.pubKeyHex

if identifier is not an empty string, or

pubKeyHex

if identifier is an empty string.

Note that client address is different from wallet address using the same key pair (account). Wallet address can be computed from client address, but NOT vice versa.

func (*MultiClient) Balance Uses

func (m *MultiClient) Balance() (*Amount, error)

Balance is the same as package level GetBalance, but using connected node as the RPC server, followed by this multiclient's SeedRPCServerAddr if failed.

func (*MultiClient) BalanceByAddress Uses

func (m *MultiClient) BalanceByAddress(address string) (*Amount, error)

BalanceByAddress is the same as package level GetBalance, but using connected node as the RPC server, followed by this multiclient's SeedRPCServerAddr if failed.

func (*MultiClient) Close Uses

func (m *MultiClient) Close() error

Close closes the multiclient, including all clients it created and all sessions dialed and accepted. Calling close multiple times is allowed and will not have any effect.

func (*MultiClient) DeleteName Uses

func (m *MultiClient) DeleteName(name string, config *TransactionConfig) (string, error)

DeleteName is a shortcut for DeleteName using this multiclient as SignerRPCClient.

func (*MultiClient) Dial Uses

func (m *MultiClient) Dial(remoteAddr string) (net.Conn, error)

Dial is the same as DialSession, but return type is net.Conn interface.

func (*MultiClient) DialSession Uses

func (m *MultiClient) DialSession(remoteAddr string) (*ncp.Session, error)

DialSession dials a session to a remote client address using this multiclient's dial config.

func (*MultiClient) DialWithConfig Uses

func (m *MultiClient) DialWithConfig(remoteAddr string, config *DialConfig) (*ncp.Session, error)

DialWithConfig dials a session with a dial config. For any zero value field in config, this default dial config value of this multiclient will be used. If config is nil, the default dial config of this multiclient will be used.

func (*MultiClient) GetClient Uses

func (m *MultiClient) GetClient(i int) *Client

GetClient returns a client with a given index.

func (*MultiClient) GetClients Uses

func (m *MultiClient) GetClients() map[int]*Client

GetClients returns all clients of the multiclient with client index as key. Subclients index starts from 0, and original client (if created) has index -1.

func (*MultiClient) GetDefaultClient Uses

func (m *MultiClient) GetDefaultClient() *Client

GetDefaultClient returns the default client, which is the client with smallest index.

func (*MultiClient) GetHeight Uses

func (m *MultiClient) GetHeight() (int32, error)

GetHeight is the same as package level GetHeight, but using connected node as the RPC server, followed by this multiclient's SeedRPCServerAddr if failed.

func (*MultiClient) GetNonce Uses

func (m *MultiClient) GetNonce(txPool bool) (int64, error)

GetNonce is the same as package level GetNonce, but using connected node as the RPC server, followed by this multiclient's SeedRPCServerAddr if failed.

func (*MultiClient) GetNonceByAddress Uses

func (m *MultiClient) GetNonceByAddress(address string, txPool bool) (int64, error)

GetNonceByAddress is the same as package level GetNonce, but using connected node as the RPC server, followed by this multiclient's SeedRPCServerAddr if failed.

func (*MultiClient) GetRegistrant Uses

func (m *MultiClient) GetRegistrant(name string) (*Registrant, error)

GetRegistrant is the same as package level GetRegistrant, but using connected node as the RPC server, followed by this multiclient's SeedRPCServerAddr if failed.

func (*MultiClient) GetSubscribers Uses

func (m *MultiClient) GetSubscribers(topic string, offset, limit int, meta, txPool bool) (*Subscribers, error)

GetSubscribers is the same as package level GetSubscribers, but using connected node as the RPC server, followed by this multiclient's SeedRPCServerAddr if failed.

func (*MultiClient) GetSubscribersCount Uses

func (m *MultiClient) GetSubscribersCount(topic string) (int, error)

GetSubscribersCount is the same as package level GetSubscribersCount, but using connected node as the RPC server, followed by this multiclient's SeedRPCServerAddr if failed.

func (*MultiClient) GetSubscription Uses

func (m *MultiClient) GetSubscription(topic string, subscriber string) (*Subscription, error)

GetSubscription is the same as package level GetSubscription, but using connected node as the RPC server, followed by this multiclient's SeedRPCServerAddr if failed.

func (*MultiClient) IsClosed Uses

func (m *MultiClient) IsClosed() bool

IsClosed returns whether this multiclient is closed.

func (*MultiClient) Listen Uses

func (m *MultiClient) Listen(addrsRe *StringArray) error

Listen will make multiclient start accepting sessions from address that matches any of the given regular expressions. If addrsRe is nil, any address will be accepted. Each function call will overwrite previous listening addresses.

func (*MultiClient) NewNanoPay Uses

func (m *MultiClient) NewNanoPay(recipientAddress, fee string, duration int) (*NanoPay, error)

NewNanoPay is a shortcut for NewNanoPay using this multiclient's wallet address as sender.

Duration is changed to signed int for gomobile compatibility.

func (*MultiClient) NewNanoPayClaimer Uses

func (m *MultiClient) NewNanoPayClaimer(recipientAddress string, claimIntervalMs int32, onError *OnError) (*NanoPayClaimer, error)

NewNanoPayClaimer is a shortcut for NewNanoPayClaimer using this multiclient as RPC client.

func (*MultiClient) PubKey Uses

func (m *MultiClient) PubKey() []byte

PubKey returns the public key of the multiclient.

func (*MultiClient) Publish Uses

func (m *MultiClient) Publish(topic string, data interface{}, config *MessageConfig) error

Publish sends bytes or string data to all subscribers of a topic with an optional config.

func (*MultiClient) PublishBinary Uses

func (m *MultiClient) PublishBinary(topic string, data []byte, config *MessageConfig) error

PublishBinary is a wrapper of Publish without interface type for gomobile compatibility.

func (*MultiClient) PublishText Uses

func (m *MultiClient) PublishText(topic string, data string, config *MessageConfig) error

PublishText is a wrapper of Publish without interface type for gomobile compatibility.

func (*MultiClient) Reconnect Uses

func (m *MultiClient) Reconnect()

Reconnect forces all clients to find node and connect again.

func (*MultiClient) RegisterName Uses

func (m *MultiClient) RegisterName(name string, config *TransactionConfig) (string, error)

RegisterName is a shortcut for RegisterName using this multiclient as SignerRPCClient.

func (*MultiClient) Seed Uses

func (m *MultiClient) Seed() []byte

Seed returns the secret seed of the multiclient. Secret seed can be used to create client/wallet with the same key pair and should be kept secret and safe.

func (*MultiClient) Send Uses

func (m *MultiClient) Send(dests *StringArray, data interface{}, config *MessageConfig) (*OnMessage, error)

Send sends bytes or string data to one or multiple destinations with an optional config. Returned OnMessage channel will emit if a reply or ACK for this message is received.

func (*MultiClient) SendBinary Uses

func (m *MultiClient) SendBinary(dests *StringArray, data []byte, config *MessageConfig) (*OnMessage, error)

SendBinary is a wrapper of Send without interface type for gomobile compatibility.

func (*MultiClient) SendBinaryWithClient Uses

func (m *MultiClient) SendBinaryWithClient(clientID int, dests *StringArray, data []byte, config *MessageConfig) (*OnMessage, error)

SendBinaryWithClient is a wrapper of SendWithClient without interface type for gomobile compatibility.

func (*MultiClient) SendRawTransaction Uses

func (m *MultiClient) SendRawTransaction(txn *transaction.Transaction) (string, error)

SendRawTransaction is the same as package level SendRawTransaction, but using connected node as the RPC server, followed by this multiclient's SeedRPCServerAddr if failed.

func (*MultiClient) SendText Uses

func (m *MultiClient) SendText(dests *StringArray, data string, config *MessageConfig) (*OnMessage, error)

SendText is a wrapper of Send without interface type for gomobile compatibility.

func (*MultiClient) SendTextWithClient Uses

func (m *MultiClient) SendTextWithClient(clientID int, dests *StringArray, data string, config *MessageConfig) (*OnMessage, error)

SendTextWithClient is a wrapper of SendWithClient without interface type for gomobile compatibility.

func (*MultiClient) SendWithClient Uses

func (m *MultiClient) SendWithClient(clientID int, dests *StringArray, data interface{}, config *MessageConfig) (*OnMessage, error)

SendWithClient sends bytes or string data to one or multiple destinations using a specific client with given index.

func (*MultiClient) SignTransaction Uses

func (m *MultiClient) SignTransaction(tx *transaction.Transaction) error

SignTransaction signs an unsigned transaction using this multiclient's key pair.

func (*MultiClient) Subscribe Uses

func (m *MultiClient) Subscribe(identifier, topic string, duration int, meta string, config *TransactionConfig) (string, error)

Subscribe is a shortcut for Subscribe using this multiclient as SignerRPCClient.

Duration is changed to signed int for gomobile compatibility.

func (*MultiClient) Transfer Uses

func (m *MultiClient) Transfer(address, amount string, config *TransactionConfig) (string, error)

Transfer is a shortcut for Transfer using this multiclient as SignerRPCClient.

func (*MultiClient) TransferName Uses

func (m *MultiClient) TransferName(name string, recipientPubKey []byte, config *TransactionConfig) (string, error)

TransferName is a shortcut for TransferName using this multiclient as SignerRPCClient.

func (*MultiClient) Unsubscribe Uses

func (m *MultiClient) Unsubscribe(identifier, topic string, config *TransactionConfig) (string, error)

Unsubscribe is a shortcut for Unsubscribe using this multiclient as SignerRPCClient.

type NanoPay Uses

type NanoPay struct {
    // contains filtered or unexported fields
}

NanoPay is a nano payment channel between a payer and recipient where the payment amount can increase monotonically.

func NewNanoPay Uses

func NewNanoPay(rpcClient rpcClient, senderWallet *Wallet, recipientAddress, fee string, duration int) (*NanoPay, error)

NewNanoPay creates a NanoPay with a rpcClient (client, multiclient or wallet), payer wallet, recipient wallet address, txn fee, duration in unit of blocks, and an optional rpc client.

func (*NanoPay) IncrementAmount Uses

func (np *NanoPay) IncrementAmount(delta string) (*transaction.Transaction, error)

IncrementAmount increments the NanoPay amount by delta and returns the signed NanoPay transaction. Delta is the string representation of the amount in unit of NKN to avoid precision loss. For example, "0.1" will be parsed as 0.1 NKN.

func (*NanoPay) Recipient Uses

func (np *NanoPay) Recipient() string

Recipient returns the recipient wallet address.

type NanoPayClaimer Uses

type NanoPayClaimer struct {
    // contains filtered or unexported fields
}

NanoPayClaimer accepts NanoPay updates and send the latest state to blockchain periodically.

func NewNanoPayClaimer Uses

func NewNanoPayClaimer(rpcClient rpcClient, recipientAddress string, claimIntervalMs int32, onError *OnError) (*NanoPayClaimer, error)

NewNanoPayClaimer creates a NanoPayClaimer with a given rpcClient (client, multiclient or wallet), recipient wallet address, claim interval in millisecond, onError channel.

func (*NanoPayClaimer) Amount Uses

func (npc *NanoPayClaimer) Amount() *Amount

Amount returns the total amount (including previously claimed and pending amount) of this NanoPayClaimer.

func (*NanoPayClaimer) Claim Uses

func (npc *NanoPayClaimer) Claim(tx *transaction.Transaction) (*Amount, error)

Claim accepts a NanoPay transaction and update NanoPay state. If the NanoPay in transaction has the same ID as before, it will be considered as an update to the previous NanoPay. If it has a different ID, it will be considered a new NanoPay, and previous NanoPay state will be flushed and sent to chain before accepting new one.

func (*NanoPayClaimer) Close Uses

func (npc *NanoPayClaimer) Close() error

Close closes the NanoPayClaimer.

func (*NanoPayClaimer) Flush Uses

func (npc *NanoPayClaimer) Flush() error

Flush sends the current latest NanoPay state to chain.

func (*NanoPayClaimer) IsClosed Uses

func (npc *NanoPayClaimer) IsClosed() bool

IsClosed returns whether the NanoPayClaimer is closed.

func (*NanoPayClaimer) Recipient Uses

func (npc *NanoPayClaimer) Recipient() string

Recipient returns the NanoPayClaimer's recipient wallet address.

type Node Uses

type Node struct {
    Addr    string `json:"addr"`
    RPCAddr string `json:"rpcAddr"`
    PubKey  string `json:"pubkey"`
    ID      string `json:"id"`
}

Node struct contains the information of the node that a client connects to.

func GetWsAddr Uses

func GetWsAddr(clientAddr string, config RPCConfigInterface) (*Node, error)

GetWsAddr RPC gets the node that a client address should connect to using ws.

func GetWssAddr Uses

func GetWssAddr(clientAddr string, config RPCConfigInterface) (*Node, error)

GetWssAddr RPC gets the node that a client address should connect to using wss.

type OnConnect Uses

type OnConnect struct {
    C        chan *Node
    Callback OnConnectFunc
}

OnConnect is a wrapper type for gomobile compatibility.

func NewOnConnect Uses

func NewOnConnect(size int, cb OnConnectFunc) *OnConnect

NewOnConnect creates an OnConnect channel with a channel size and callback function.

func (*OnConnect) Next Uses

func (c *OnConnect) Next() *Node

Next waits and returns the next element from the channel.

type OnConnectFunc Uses

type OnConnectFunc interface{ OnConnect(*Node) }

OnConnectFunc is a wrapper type for gomobile compatibility.

type OnError Uses

type OnError struct {
    C        chan error
    Callback OnErrorFunc
}

OnError is a wrapper type for gomobile compatibility.

func NewOnError Uses

func NewOnError(size int, cb OnErrorFunc) *OnError

NewOnError creates an OnError channel with a channel size and callback function.

func (*OnError) Next Uses

func (c *OnError) Next() error

Next waits and returns the next element from the channel.

type OnErrorFunc Uses

type OnErrorFunc interface{ OnError(error) }

OnErrorFunc is a wrapper type for gomobile compatibility.

type OnMessage Uses

type OnMessage struct {
    C        chan *Message
    Callback OnMessageFunc
}

OnMessage is a wrapper type for gomobile compatibility.

func NewOnMessage Uses

func NewOnMessage(size int, cb OnMessageFunc) *OnMessage

NewOnMessage creates an OnMessage channel with a channel size and callback function.

func (*OnMessage) Next Uses

func (c *OnMessage) Next() *Message

Next waits and returns the next element from the channel.

type OnMessageFunc Uses

type OnMessageFunc interface{ OnMessage(*Message) }

OnMessageFunc is a wrapper type for gomobile compatibility.

type RPCConfig Uses

type RPCConfig struct {
    SeedRPCServerAddr *StringArray
}

RPCConfig is the rpc call configuration.

func GetDefaultRPCConfig Uses

func GetDefaultRPCConfig() *RPCConfig

GetDefaultRPCConfig returns the default rpc config with nil pointer fields set to default.

func (*RPCConfig) GetRandomSeedRPCServerAddr Uses

func (config *RPCConfig) GetRandomSeedRPCServerAddr() string

GetRandomSeedRPCServerAddr returns a random seed rpc server address from the rpc config.

type RPCConfigInterface Uses

type RPCConfigInterface interface {
    GetRandomSeedRPCServerAddr() string
}

RPCConfigInterface is the config interface for making rpc call. ClientConfig, WalletConfig and RPCConfig all implement this interface and thus can be used directly.

type Registrant Uses

type Registrant struct {
    Registrant string `json:"registrant"`
    ExpiresAt  int32  `json:"expiresAt"` // Changed to signed int for gomobile compatibility
}

Registrant contains the information of a name registrant

func GetRegistrant Uses

func GetRegistrant(name string, config RPCConfigInterface) (*Registrant, error)

GetRegistrant RPC gets the registrant of a name.

type ScryptConfig Uses

type ScryptConfig struct {
    Salt []byte
    N    int
    R    int
    P    int
}

ScryptConfig is the scrypt configuration.

type StringArray Uses

type StringArray struct {
    // contains filtered or unexported fields
}

StringArray is a wrapper type for gomobile compatibility. StringArray is not protected by lock and should not be read and write at the same time.

func NewStringArray Uses

func NewStringArray(elems ...string) *StringArray

NewStringArray creates a StringArray from a list of string elements.

func NewStringArrayFromString Uses

func NewStringArrayFromString(s string) *StringArray

NewStringArrayFromString creates a StringArray from a single string input. The input string will be split to string array by whitespace.

func (*StringArray) Append Uses

func (sa *StringArray) Append(s string)

Append adds an element to the string array.

func (*StringArray) Elems Uses

func (sa *StringArray) Elems() []string

Elems returns the string array elements.

func (*StringArray) Len Uses

func (sa *StringArray) Len() int

Len returns the string array length.

type StringMap Uses

type StringMap struct{ Map map[string]string }

StringMap is a wrapper type for gomobile compatibility. StringMap is not protected by lock and should not be read and write at the same time.

func NewStringMap Uses

func NewStringMap(m map[string]string) *StringMap

NewStringMap creates a StringMap from a map.

func NewStringMapWithSize Uses

func NewStringMapWithSize(size int) *StringMap

NewStringMapWithSize creates an empty StringMap with a given size.

func (*StringMap) Delete Uses

func (sm *StringMap) Delete(key string)

Delete deletes a key and its value from the map.

func (*StringMap) Get Uses

func (sm *StringMap) Get(key string) (string, error)

Get returns the value of a key, or ErrKeyNotInMap if key does not exist.

func (*StringMap) Len Uses

func (sm *StringMap) Len() int

Len returns the number of elements in the map.

func (*StringMap) Range Uses

func (sm *StringMap) Range(cb StringMapFunc)

Range iterates over the StringMap and call the OnVisit callback function with each element in the map. If the OnVisit function returns false, the iterator will stop and no longer visit the rest elements.

func (*StringMap) Set Uses

func (sm *StringMap) Set(key, value string)

Set sets the value of a key to a value.

type StringMapFunc Uses

type StringMapFunc interface{ OnVisit(string, string) bool }

StringMapFunc is a wrapper type for gomobile compatibility.

type Subscribers Uses

type Subscribers struct{ Subscribers, SubscribersInTxPool *StringMap }

Subscribers is a wrapper type for gomobile compatibility.

func GetSubscribers Uses

func GetSubscribers(topic string, offset, limit int, meta, txPool bool, config RPCConfigInterface) (*Subscribers, error)

GetSubscribers gets the subscribers of a topic with a offset and max number of results (limit). If meta is true, results contain each subscriber's metadata. If txPool is true, results contain subscribers in txPool. Enabling this will get subscribers sooner after they send subscribe transactions, but might affect the correctness of subscribers because transactions in txpool is not guaranteed to be packed into a block.

Offset and limit are changed to signed int for gomobile compatibility

type Subscription Uses

type Subscription struct {
    Meta      string `json:"meta"`
    ExpiresAt int32  `json:"expiresAt"` // Changed to signed int for gomobile compatibility
}

Subscription contains the information of a subscriber to a topic.

func GetSubscription Uses

func GetSubscription(topic string, subscriber string, config RPCConfigInterface) (*Subscription, error)

GetSubscription RPC gets the subscription details of a subscriber in a topic.

type TransactionConfig Uses

type TransactionConfig struct {
    Fee        string
    Nonce      int64 // nonce is changed to signed int for gomobile compatibility
    Attributes []byte
}

TransactionConfig is the config for making a transaction.

func GetDefaultTransactionConfig Uses

func GetDefaultTransactionConfig() *TransactionConfig

GetDefaultTransactionConfig returns the default rpc config with nil pointer fields set to default.

func MergeTransactionConfig Uses

func MergeTransactionConfig(conf *TransactionConfig) (*TransactionConfig, error)

MergeTransactionConfig merges a given transaction config with the default transaction config recursively. Any non zero value fields will override the default config.

type Wallet Uses

type Wallet struct {
    // contains filtered or unexported fields
}

Wallet manages assets, query state from blockchain, and send transactions to blockchain.

func NewWallet Uses

func NewWallet(account *Account, config *WalletConfig) (*Wallet, error)

NewWallet creates a wallet from an account and an optional config. For any zero value field in config, the default wallet config value will be used. If config is nil, the default wallet config will be used. However, it is strongly recommended to use non-empty password in config to protect the wallet, otherwise anyone can recover the wallet and control all assets in the wallet from the generated wallet JSON.

func WalletFromJSON Uses

func WalletFromJSON(walletJSON string, config *WalletConfig) (*Wallet, error)

WalletFromJSON recovers a wallet from wallet JSON and wallet config. The password in config must match the password used to create the wallet.

func (*Wallet) Account Uses

func (w *Wallet) Account() *Account

Account returns the account of the wallet.

func (*Wallet) Address Uses

func (w *Wallet) Address() string

Address returns the NKN wallet address of the wallet.

func (*Wallet) Balance Uses

func (w *Wallet) Balance() (*Amount, error)

Balance is the same as package level GetBalance, but using this wallet's SeedRPCServerAddr.

func (*Wallet) BalanceByAddress Uses

func (w *Wallet) BalanceByAddress(address string) (*Amount, error)

BalanceByAddress is the same as package level GetBalance, but using this wallet's SeedRPCServerAddr.

func (*Wallet) DeleteName Uses

func (w *Wallet) DeleteName(name string, config *TransactionConfig) (string, error)

DeleteName is a shortcut for DeleteName using this wallet as SignerRPCClient.

func (*Wallet) GetHeight Uses

func (w *Wallet) GetHeight() (int32, error)

GetHeight is the same as package level GetHeight, but using this wallet's SeedRPCServerAddr.

func (*Wallet) GetNonce Uses

func (w *Wallet) GetNonce(txPool bool) (int64, error)

GetNonce is the same as package level GetNonce, but using this wallet's SeedRPCServerAddr.

func (*Wallet) GetNonceByAddress Uses

func (w *Wallet) GetNonceByAddress(address string, txPool bool) (int64, error)

GetNonceByAddress is the same as package level GetNonce, but using this wallet's SeedRPCServerAddr.

func (*Wallet) GetRegistrant Uses

func (w *Wallet) GetRegistrant(name string) (*Registrant, error)

GetRegistrant is the same as package level GetRegistrant, but this wallet's SeedRPCServerAddr.

func (*Wallet) GetSubscribers Uses

func (w *Wallet) GetSubscribers(topic string, offset, limit int, meta, txPool bool) (*Subscribers, error)

GetSubscribers is the same as package level GetSubscribers, but using this wallet's SeedRPCServerAddr.

func (*Wallet) GetSubscribersCount Uses

func (w *Wallet) GetSubscribersCount(topic string) (int, error)

GetSubscribersCount is the same as package level GetSubscribersCount, but this wallet's SeedRPCServerAddr.

func (*Wallet) GetSubscription Uses

func (w *Wallet) GetSubscription(topic string, subscriber string) (*Subscription, error)

GetSubscription is the same as package level GetSubscription, but using this wallet's SeedRPCServerAddr.

func (*Wallet) MarshalJSON Uses

func (w *Wallet) MarshalJSON() ([]byte, error)

MarshalJSON serialize the wallet to JSON string encrypted by password used to create the wallet. The same password must be used to recover the wallet from JSON string.

func (*Wallet) NewNanoPay Uses

func (w *Wallet) NewNanoPay(recipientAddress, fee string, duration int) (*NanoPay, error)

NewNanoPay is a shortcut for NewNanoPay using this wallet as sender.

Duration is changed to signed int for gomobile compatibility.

func (*Wallet) NewNanoPayClaimer Uses

func (w *Wallet) NewNanoPayClaimer(recipientAddress string, claimIntervalMs int32, onError *OnError) (*NanoPayClaimer, error)

NewNanoPayClaimer is a shortcut for NewNanoPayClaimer using this wallet as RPC client.

func (*Wallet) ProgramHash Uses

func (w *Wallet) ProgramHash() common.Uint160

ProgramHash returns the program hash of this wallet's account.

func (*Wallet) PubKey Uses

func (w *Wallet) PubKey() []byte

PubKey returns the public key of the wallet.

func (*Wallet) RegisterName Uses

func (w *Wallet) RegisterName(name string, config *TransactionConfig) (string, error)

RegisterName is a shortcut for RegisterName using this wallet as SignerRPCClient.

func (*Wallet) Seed Uses

func (w *Wallet) Seed() []byte

Seed returns the secret seed of the wallet. Secret seed can be used to create client/wallet with the same key pair and should be kept secret and safe.

func (*Wallet) SendRawTransaction Uses

func (w *Wallet) SendRawTransaction(txn *transaction.Transaction) (string, error)

SendRawTransaction is the same as package level SendRawTransaction, but using this wallet's SeedRPCServerAddr.

func (*Wallet) SignTransaction Uses

func (w *Wallet) SignTransaction(tx *transaction.Transaction) error

SignTransaction signs an unsigned transaction using this wallet's key pair.

func (*Wallet) Subscribe Uses

func (w *Wallet) Subscribe(identifier, topic string, duration int, meta string, config *TransactionConfig) (string, error)

Subscribe is a shortcut for Subscribe using this wallet as SignerRPCClient.

Duration is changed to signed int for gomobile compatibility.

func (*Wallet) ToJSON Uses

func (w *Wallet) ToJSON() (string, error)

ToJSON is a shortcut for wallet.MarshalJSON, but returns string instead of bytes.

func (*Wallet) Transfer Uses

func (w *Wallet) Transfer(address, amount string, config *TransactionConfig) (string, error)

Transfer is a shortcut for Transfer using this wallet as SignerRPCClient.

func (*Wallet) TransferName Uses

func (w *Wallet) TransferName(name string, recipientPubKey []byte, config *TransactionConfig) (string, error)

TransferName is a shortcut for TransferName using this wallet as SignerRPCClient.

func (*Wallet) Unsubscribe Uses

func (w *Wallet) Unsubscribe(identifier, topic string, config *TransactionConfig) (string, error)

Unsubscribe is a shortcut for Unsubscribe using this wallet as SignerRPCClient.

func (*Wallet) VerifyPassword Uses

func (w *Wallet) VerifyPassword(password string) error

VerifyPassword returns nil if provided password is the correct password of this wallet.

type WalletConfig Uses

type WalletConfig struct {
    SeedRPCServerAddr *StringArray
    Password          string
    IV                []byte
    MasterKey         []byte
    ScryptConfig      *ScryptConfig
}

WalletConfig is the wallet configuration.

func GetDefaultWalletConfig Uses

func GetDefaultWalletConfig() *WalletConfig

GetDefaultWalletConfig returns the default wallet config with nil pointer fields set to default.

func MergeWalletConfig Uses

func MergeWalletConfig(conf *WalletConfig) (*WalletConfig, error)

MergeWalletConfig merges a given wallet config with the default wallet config recursively. Any non zero value fields will override the default config.

func (*WalletConfig) GetRandomSeedRPCServerAddr Uses

func (config *WalletConfig) GetRandomSeedRPCServerAddr() string

GetRandomSeedRPCServerAddr returns a random seed rpc server address from the wallet config.

Directories

PathSynopsis
payloads

Package nkn imports 41 packages (graph). Updated 2020-09-16. Refresh now. Tools for package owners.