nkn

package module
v1.4.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 29, 2024 License: Apache-2.0 Imports: 45 Imported by: 41

README

nkn-sdk-go

GoDoc GitHub license Go Report Card Build Status PRs Welcome

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

  • 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.

  • 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.

  • NKN Wallet: Wallet SDK for NKN blockchain. It can be used to create wallet, transfer token to NKN wallet address, register name, subscribe to topic, etc.

Advantages of using NKN client/multiclient for data transmission:

  • 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.

  • 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.

  • 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.

  • 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.)

Documentation

Full documentation can be found at GoDoc.

Usage

Client

NKN Client provides low level p2p messaging through NKN network. For most applications, it's more suitable to use multiclient (see multiclient section below) for better reliability, lower latency, and session mode support.

Create a client with a generated key pair:

account, err := NewAccount(nil)
client, err := NewClient(account, "", nil)

Or with an identifier (used to distinguish different clients sharing the same key pair):

client, err := NewClient(account, "any string", nil)

Get client key pair:

fmt.Println(account.Seed(), account.PubKey())

Create a client using an existing secret seed:

seed, err := hex.DecodeStrings("039e481266e5a05168c1d834a94db512dbc235877f150c5a3cc1e3903672c673")
account, err := NewAccount(seed)
client, err := NewClient(account, "any string", nil)

Secret seed should be kept SECRET! Never put it in version control system like here.

By default the client will use bootstrap RPC server (for getting node address) provided by NKN. Any NKN full node can serve as a bootstrap RPC server. To create a client using customized bootstrap RPC server:

conf := &ClientConfig{SeedRPCServerAddr: NewStringArray("https://ip:port", "https://ip:port", ...)}
client, err := NewClient(account, "any string", conf)

Get client NKN address, which is used to receive data from other clients:

fmt.Println(client.Address())

Listen for connection established:

<- client.OnConnect.C
fmt.Println("Connection opened.")

Send text message to other clients:

response, err := client.Send(NewStringArray("another client address"), []byte("hello world!"), nil)

You can also send byte array directly:

response, err := client.Send(NewStringArray("another client address"), []byte{1, 2, 3, 4, 5}, nil)

Or publish a message to a specified topic (see wallet section for subscribing to topics):

client.Publish("topic", []byte("hello world!"), nil)

Receive data from other clients:

msg := <- client.OnMessage.C
fmt.Println("Receive message from", msg.Src + ":", string(msg.Payload))
msg.Reply([]byte("response"))

Get 100 subscribers of specified topic starting from 0 offset, including those in tx pool (fetch meta):

subscribers, err := client.GetSubscribers("topic", 0, 100, true, true)
fmt.Println(subscribers.Subscribers, subscribers.SubscribersInTxPool)

Get subscription:

subscription, err := client.GetSubscription("topic", "identifier.publickey")
fmt.Printf("%+v\n", subscription) // &{Meta:meta ExpiresAt:100000}
Multiclient

Multiclient creates multiple client instances by adding identifier prefix (__0__., __1__., __2__., ...) to a nkn address and send/receive packets concurrently. This will greatly increase reliability and reduce latency at the cost of more bandwidth usage (proportional to the number of clients).

Multiclient basically has the same API as client, except for a few more initial configurations:

numSubClients := 3
originalClient := false
multiclient, err := NewMultiClient(account, identifier, numSubClient, originalClient)

where originalClient controls whether a client with original identifier (without adding any additional identifier prefix) will be created, and numSubClients controls how many sub-clients to create by adding prefix __0__., __1__., __2__., etc. Using originalClient == true and numSubClients == 0 is equivalent to using a standard client without any modification to the identifier. Note that if you use originalClient == true and numSubClients is greater than 0, your identifier should not starts with __X__ where X is any number, otherwise you may end up with identifier collision.

Any additional options will be passed to NKN client.

multiclient instance shares the same API as regular NKN client, see above for usage and examples. If you need low-level property or API, you can use multiclient.DefaultClient to get the default client and multiclient.Clients to get all clients.

Session

Multiclient supports a reliable transmit protocol called session. It will be responsible for retransmission and ordering just like TCP. It uses multiple clients to send and receive data in multiple path to achieve better throughput. Unlike regular multiclient message, no redundant data is sent unless packet loss.

Any multiclient can start listening for incoming session where the remote address match any of the given regexp:

multiclient, err := NewMultiClient(...)
// Accepting any address, equivalent to multiclient.Listen(NewStringArray(".*"))
err = multiclient.Listen(nil)
// Only accepting pubkey 25d660916021ab1d182fb6b52d666b47a0f181ed68cf52a056041bdcf4faaf99 but with any identifiers
err = multiclient.Listen(NewStringArray("25d660916021ab1d182fb6b52d666b47a0f181ed68cf52a056041bdcf4faaf99$"))
// Only accepting address alice.25d660916021ab1d182fb6b52d666b47a0f181ed68cf52a056041bdcf4faaf99
err = multiclient.Listen(NewStringArray("^alice\\.25d660916021ab1d182fb6b52d666b47a0f181ed68cf52a056041bdcf4faaf99$"))

Then it can start accepting sessions:

session, err := multiclient.Accept()

Multiclient implements net.Listener interface, so one can use it as a drop-in replacement when net.Listener is needed, e.g. http.Serve.

On the other hand, any multiclient can dial a session to a remote NKN address:

session, err := multiclient.Dial("another nkn address")

Session implements net.Conn interface, so it can be used as a drop-in replacement when net.Conn is needed:

buf := make([]byte, 1024)
n, err := session.Read(buf)
n, err := session.Write(buf)
Wallet

Create wallet SDK:

account, err := NewAccount(nil)
wallet, err := NewWallet(account, &nkn.WalletConfig{Password: "password"})

By default the wallet will use RPC server provided by nkn.org. Any NKN full node can serve as a RPC server. To create a wallet using customized RPC server:

conf := &WalletConfig{
  Password: "password",
  SeedRPCServerAddr: NewStringArray("https://ip:port", "https://ip:port", ...),
}
wallet, err := NewWallet(account, conf)

Export wallet to JSON string, where sensitive contents are encrypted by password provided in config:

walletJSON, err := wallet.ToJSON()

Load wallet from JSON string, note that the password needs to be the same as the one provided when creating wallet:

walletFromJSON, err := nkn.WalletFromJSON(walletJSON, &nkn.WalletConfig{Password: "password"})

Verify whether an address is a valid NKN wallet address:

err := nkn.VerifyWalletAddress(wallet.Address())

Verify password of the wallet:

err := wallet.VerifyPassword("password")

Query asset balance for this wallet:

balance, err := wallet.Balance()
if err == nil {
    log.Println("asset balance:", balance.String())
} else {
    log.Println("query balance fail:", err)
}

Query asset balance for address:

balance, err := wallet.BalanceByAddress("NKNxxxxx")

Transfer asset to some address:

txnHash, err := wallet.Transfer(account.WalletAddress(), "100", nil)

Open nano pay channel to specified address:

// you can pass channel duration (in unit of blocks) after address and txn fee
// after expired new channel (with new id) will be created under-the-hood
// this means that receiver need to claim old channel and reset amount calculation
np, err := wallet.NewNanoPay(address, "0", 4320)

Increment channel balance by 100 NKN:

txn, err := np.IncrementAmount("100")

Then you can pass the transaction to receiver, who can send transaction to on-chain later:

txnHash, err := wallet.SendRawTransaction(txn)

Register name for this wallet:

txnHash, err = wallet.RegisterName("somename", nil)

Delete name for this wallet:

txnHash, err = wallet.DeleteName("somename", nil)

Subscribe to specified topic for this wallet for next 100 blocks:

txnHash, err = wallet.Subscribe("identifier", "topic", 100, "meta", nil)

Unsubscribe from specified topic:

txnHash, err = wallet.Unsubscribe("identifier", "topic", nil)

Compiling to iOS/Android native library

This library is designed to work with gomobile and run natively on iOS/Android without any modification. You can use gomobile bind 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 github.com/nknorg/nkngomobile

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 github.com/nknorg/nkngomobile

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

Contributing

Can I submit a bug, suggestion or feature request?

Yes. Please open an issue for that.

Can I contribute patches?

Yes, we appreciate your help! To make contributions, please fork the repo, push your changes to the forked repo with signed-off commits, and open a pull request here.

Please sign off your commit. This means adding a line "Signed-off-by: Name " at the end of each commit, indicating that you wrote the code and have the right to pass it on as an open source patch. This can be done automatically by adding -s when committing:

git commit -s

Community

Documentation

Overview

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 github.com/nknorg/nkngomobile

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 github.com/nknorg/nkngomobile

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

Index

Constants

Payload type alias for gomobile compatibility.

View Source
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
)
View Source
const (
	// AmountUnit is the inverse of the NKN precision
	AmountUnit = common.StorageFactor
)
View Source
const (
	// MessageIDSize is the default message id size in bytes
	MessageIDSize = 8
)

Variables

View Source
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)
	ErrUnencryptedMessage   = errors.New("message is unencrypted")
	ErrResolveLimit         = errors.New("resolve depth exceeded")
	ErrInvalidResolver      = errors.New("resolver doesn't implement Resolver interface")
)

Error definitions.

View Source
var DefaultClientConfig = ClientConfig{
	SeedRPCServerAddr:       nil,
	RPCTimeout:              10000,
	RPCConcurrency:          1,
	MsgChanLen:              1024,
	ConnectRetries:          3,
	MsgCacheExpiration:      300000,
	MsgCacheCleanupInterval: 60000,
	WsHandshakeTimeout:      5000,
	WsWriteTimeout:          10000,
	MinReconnectInterval:    1000,
	MaxReconnectInterval:    64000,
	AllowUnencrypted:        false,
	MessageConfig:           nil,
	SessionConfig:           nil,
	HttpDialContext:         nil,
	WsDialContext:           nil,
	Resolvers:               nil,
	ResolverDepth:           16,
	ResolverTimeout:         10000,
	WebRTC:                  false,
	StunServerAddr:          nil,
	WebRTCConnectTimeout:    10000,
}

DefaultClientConfig is the default client config.

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

DefaultDialConfig is the default dial config.

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

DefaultMessageConfig is the default message config.

View Source
var DefaultRPCConfig = RPCConfig{
	SeedRPCServerAddr: nil,
	RPCTimeout:        10000,
	RPCConcurrency:    1,
	HttpDialContext:   nil,
}

DefaultRPCConfig is the default rpc configuration.

View Source
var DefaultSeedRPCServerAddr = []string{
	"http://seed.nkn.org:30003",
	"http://mainnet-seed-0001.nkn.org:30003",
	"http://mainnet-seed-0002.nkn.org:30003",
	"http://mainnet-seed-0003.nkn.org:30003",
	"http://mainnet-seed-0004.nkn.org:30003",
	"http://mainnet-seed-0005.nkn.org:30003",
	"http://mainnet-seed-0006.nkn.org:30003",
	"http://mainnet-seed-0007.nkn.org:30003",
	"http://mainnet-seed-0008.nkn.org:30003",
}

DefaultSeedRPCServerAddr is the default seed rpc server address list.

View Source
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.

View Source
var DefaultStunServerAddr = []string{
	"stun:stun.l.google.com:19302",
	"stun:stun.cloudflare.com:3478",
	"stun:stunserver.stunprotocol.org:3478",
}
View Source
var DefaultTransactionConfig = TransactionConfig{
	Fee:        "0",
	Nonce:      0,
	FixNonce:   false,
	Attributes: nil,
}

DefaultTransactionConfig is the default TransactionConfig.

View Source
var DefaultWalletConfig = WalletConfig{
	SeedRPCServerAddr: nil,
	RPCTimeout:        10000,
	RPCConcurrency:    1,
	IV:                nil,
	MasterKey:         nil,
	ScryptConfig:      nil,
	HttpDialContext:   nil,
}

DefaultWalletConfig is the default wallet configuration.

View Source
var NewStringArray = nkngomobile.NewStringArray

NewStringArray creates a StringArray from a list of string elements.

View Source
var NewStringArrayFromString = nkngomobile.NewStringArrayFromString

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

View Source
var NewStringMap = nkngomobile.NewStringMap

NewStringMap creates a StringMap from a map.

View Source
var NewStringMapWithSize = nkngomobile.NewStringMapWithSize

NewStringMapWithSize creates an empty StringMap with a given size.

Functions

func ClientAddrToPubKey

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

ClientAddrToPubKey converts a NKN client address to its public key.

func ClientAddrToWalletAddr

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 added in v1.2.4

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

DeleteName wraps DeleteNameContext with background context.

func DeleteNameContext added in v1.3.5

func DeleteNameContext(ctx context.Context, s signerRPCClient, name string, config *TransactionConfig) (string, error)

DeleteNameContext 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 added in v1.2.3

func GetDefaultSessionConfig() *ncp.Config

GetDefaultSessionConfig returns the default session config.

func GetHeight added in v1.2.3

func GetHeight(config RPCConfigInterface) (int32, error)

GetHeight wraps GetHeightContext with background context.

func GetHeightContext added in v1.3.5

func GetHeightContext(ctx context.Context, config RPCConfigInterface) (int32, error)

GetHeightContext RPC returns the latest block height.

func GetNonce added in v1.2.3

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

GetNonce wraps GetNonceContext with background context.

func GetNonceContext added in v1.3.5

func GetNonceContext(ctx context.Context, address string, txPool bool, config RPCConfigInterface) (int64, error)

GetNonceContext 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 added in v1.2.3

func GetSubscribersCount(topic string, subscriberHashPrefix []byte, config RPCConfigInterface) (int, error)

GetSubscribersCount wraps GetSubscribersCountContext with background context.

func GetSubscribersCountContext added in v1.3.5

func GetSubscribersCountContext(ctx context.Context, topic string, subscriberHashPrefix []byte, config RPCConfigInterface) (int, error)

GetSubscribersCountContext RPC returns the number of subscribers of a topic (not including txPool). If subscriberHashPrefix is not empty, only subscriber whose sha256(pubkey+identifier) contains this prefix will be counted. Each prefix byte will reduce result count to about 1/256, and also reduce response time to about 1/256 if there are a lot of subscribers. This is a good way to sample subscribers randomly with low cost.

Count is changed to signed int for gomobile compatibility

func MeasureSeedRPCServer added in v1.3.6

func MeasureSeedRPCServer(seedRPCList *nkngomobile.StringArray, timeout int32, dialContext func(ctx context.Context, network, addr string) (net.Conn, error)) (*nkngomobile.StringArray, error)

MeasureSeedRPCServer wraps MeasureSeedRPCServerContext with background context.

func MeasureSeedRPCServerContext added in v1.3.6

func MeasureSeedRPCServerContext(ctx context.Context, seedRPCList *nkngomobile.StringArray, timeout int32, dialContext func(ctx context.Context, network, addr string) (net.Conn, error)) (*nkngomobile.StringArray, error)

MeasureSeedRPCServerContext measures the latency to seed rpc node list, only select the ones in persist finished state, and sort them by latency (from low to high). If none of the given seed rpc node is accessable or in persist finished state, returned string array will contain zero elements. Timeout is in millisecond.

func NewReplyPayload added in v1.4.2

func NewReplyPayload(data interface{}, replyToID []byte) (*payloads.Payload, error)

func PubKeyToWalletAddr

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

PubKeyToWalletAddr converts a public key to its NKN wallet address.

func RPCCall added in v1.2.3

func RPCCall(parentCtx context.Context, method string, params interface{}, result interface{}, config RPCConfigInterface) error

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

func RandomBytes

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

RandomBytes return cryptographically secure random bytes with given size.

func RegisterName added in v1.2.4

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

RegisterName wraps RegisterNameContext with background context.

func RegisterNameContext added in v1.3.5

func RegisterNameContext(ctx context.Context, s signerRPCClient, name string, config *TransactionConfig) (string, error)

RegisterNameContext 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 ResolveDest added in v1.4.2

func ResolveDest(ctx context.Context, dest string, resolvers []Resolver) (string, bool, error)

func ResolveDestN added in v1.4.2

func ResolveDestN(ctx context.Context, dest string, resolvers []Resolver, depth int32) (string, error)

func ResolveDests added in v1.4.2

func ResolveDests(ctx context.Context, dests []string, resolvers []Resolver, depth int32) ([]string, error)

func SendRawTransaction added in v1.2.3

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

SendRawTransaction wraps SendRawTransactionContext with background context.

func SendRawTransactionContext added in v1.3.5

func SendRawTransactionContext(ctx context.Context, txn *transaction.Transaction, config RPCConfigInterface) (string, error)

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

func Subscribe added in v1.2.4

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

Subscribe wraps SubscribeContext with background context.

func SubscribeContext added in v1.3.5

func SubscribeContext(ctx context.Context, s signerRPCClient, identifier, topic string, duration int, meta string, config *TransactionConfig) (string, error)

SubscribeContext 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 added in v1.2.4

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

Transfer wraps TransferContext with background context.

func TransferContext added in v1.3.5

func TransferContext(ctx context.Context, s signerRPCClient, address, amount string, config *TransactionConfig) (string, error)

TransferContext 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 added in v1.2.4

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

TransferName wraps TransferNameContext with background context.

func TransferNameContext added in v1.3.5

func TransferNameContext(ctx context.Context, s signerRPCClient, name string, recipientPubKey []byte, config *TransactionConfig) (string, error)

TransferNameContext 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 added in v1.2.4

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

Unsubscribe wraps UnsubscribeContext with background context.

func UnsubscribeContext added in v1.3.5

func UnsubscribeContext(ctx context.Context, s signerRPCClient, identifier, topic string, config *TransactionConfig) (string, error)

UnsubscribeContext 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

func VerifyWalletAddress(address string) error

VerifyWalletAddress returns error if the given wallet address is invalid.

Types

type Account

type Account struct{ *vault.Account }

Account is a wrapper type for gomobile compatibility.

func NewAccount

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

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

PubKey returns the public key of the account.

func (*Account) Seed

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

func (account *Account) WalletAddress() string

WalletAddress returns the wallet address of the account.

type Amount

type Amount struct{ common.Fixed64 }

Amount is a wrapper type for gomobile compatibility.

func GetBalance added in v1.2.3

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

GetBalance wraps GetBalanceContext with background context.

func GetBalanceContext added in v1.3.5

func GetBalanceContext(ctx context.Context, address string, config RPCConfigInterface) (*Amount, error)

GetBalanceContext RPC returns the balance of a wallet address.

func NewAmount

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

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

ToFixed64 returns amount as Fixed64 type.

type Client

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

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 added in v1.2.9

func (c *Client) Account() *Account

Account returns the account of the client.

func (*Client) Address

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 added in v1.2.4

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

Balance wraps BalanceContext with background context.

func (*Client) BalanceByAddress added in v1.2.4

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

BalanceByAddress wraps BalanceByAddressContext with background context.

func (*Client) BalanceByAddressContext added in v1.3.5

func (c *Client) BalanceByAddressContext(ctx context.Context, address string) (*Amount, error)

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

func (*Client) BalanceContext added in v1.3.5

func (c *Client) BalanceContext(ctx context.Context) (*Amount, error)

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

func (*Client) Close

func (c *Client) Close() error

Close closes the client.

func (*Client) DeleteName added in v1.2.4

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

DeleteName wraps DeleteNameContext with background context.

func (*Client) DeleteNameContext added in v1.3.5

func (c *Client) DeleteNameContext(ctx context.Context, name string, config *TransactionConfig) (string, error)

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

func (*Client) GetConn

func (c *Client) GetConn() wsConn

GetConn returns the current websocket connection client is using.

func (*Client) GetHeight added in v1.2.4

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

GetHeight wraps GetHeightContext with background context.

func (*Client) GetHeightContext added in v1.3.5

func (c *Client) GetHeightContext(ctx context.Context) (int32, error)

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

func (*Client) GetNode added in v1.2.3

func (c *Client) GetNode() *Node

GetNode returns the node that client is currently connected to.

func (*Client) GetNonce added in v1.2.4

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

GetNonce wraps GetNonceContext with background context.

func (*Client) GetNonceByAddress added in v1.2.4

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

GetNonceByAddress wraps GetNonceByAddressContext with background context.

func (*Client) GetNonceByAddressContext added in v1.3.5

func (c *Client) GetNonceByAddressContext(ctx context.Context, address string, txPool bool) (int64, error)

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

func (*Client) GetNonceContext added in v1.3.5

func (c *Client) GetNonceContext(ctx context.Context, txPool bool) (int64, error)

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

func (*Client) GetRegistrant added in v1.2.4

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

GetRegistrant wraps GetRegistrantContext with background context.

func (*Client) GetRegistrantContext added in v1.3.5

func (c *Client) GetRegistrantContext(ctx context.Context, name string) (*Registrant, error)

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

func (*Client) GetSubscribers added in v1.2.3

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

GetSubscribers wraps GetSubscribersContext with background context.

func (*Client) GetSubscribersContext added in v1.3.5

func (c *Client) GetSubscribersContext(ctx context.Context, topic string, offset, limit int, meta, txPool bool, subscriberHashPrefix []byte) (*Subscribers, error)

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

func (*Client) GetSubscribersCount added in v1.2.3

func (c *Client) GetSubscribersCount(topic string, subscriberHashPrefix []byte) (int, error)

GetSubscribersCount wraps GetSubscribersCountContext with background context.

func (*Client) GetSubscribersCountContext added in v1.3.5

func (c *Client) GetSubscribersCountContext(ctx context.Context, topic string, subscriberHashPrefix []byte) (int, error)

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

func (*Client) GetSubscription added in v1.2.3

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

GetSubscription wraps GetSubscriptionContext with background context.

func (*Client) GetSubscriptionContext added in v1.3.5

func (c *Client) GetSubscriptionContext(ctx context.Context, topic string, subscriber string) (*Subscription, error)

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

func (*Client) IsClosed

func (c *Client) IsClosed() bool

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

func (*Client) NewNanoPay added in v1.2.4

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 added in v1.2.4

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

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

func (*Client) PubKey

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

PubKey returns the public key of the client.

func (*Client) Publish

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

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

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 added in v1.2.9

func (c *Client) Reconnect(node *Node)

Reconnect forces the client to find node and connect again.

func (*Client) RegisterName added in v1.2.4

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

RegisterName wraps RegisterNameContext with background context.

func (*Client) RegisterNameContext added in v1.3.5

func (c *Client) RegisterNameContext(ctx context.Context, name string, config *TransactionConfig) (string, error)

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

func (*Client) ResolveDest added in v1.4.6

func (c *Client) ResolveDest(dest string) (string, error)

ResolveDest wraps ResolveDestContext with background context

func (*Client) ResolveDestContext added in v1.4.6

func (c *Client) ResolveDestContext(ctx context.Context, dest string) (string, error)

ResolveDestContext resolvers an address, returns NKN address

func (*Client) ResolveDests added in v1.4.6

func (c *Client) ResolveDests(dests *nkngomobile.StringArray) (*nkngomobile.StringArray, error)

ResolveDests wraps ResolveDestsContext with background context

func (*Client) ResolveDestsContext added in v1.4.6

func (c *Client) ResolveDestsContext(ctx context.Context, dests *nkngomobile.StringArray) (*nkngomobile.StringArray, error)

ResolveDestsContext resolvers multiple addresses

func (*Client) Seed

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

func (c *Client) Send(dests *nkngomobile.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

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

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

func (*Client) SendPayload added in v1.4.2

func (c *Client) SendPayload(dests *nkngomobile.StringArray, payload *payloads.Payload, config *MessageConfig) (*OnMessage, error)

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

func (*Client) SendRawTransaction added in v1.2.4

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

SendRawTransaction wraps SendRawTransactionContext with background context.

func (*Client) SendRawTransactionContext added in v1.3.5

func (c *Client) SendRawTransactionContext(ctx context.Context, txn *transaction.Transaction) (string, error)

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

func (*Client) SendText

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

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

func (*Client) SetWriteDeadline

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

SetWriteDeadline sets the write deadline of the websocket connection.

func (*Client) SignTransaction added in v1.2.4

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

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

func (*Client) Subscribe added in v1.2.4

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

Subscribe wraps SubscribeContext with background context.

func (*Client) SubscribeContext added in v1.3.5

func (c *Client) SubscribeContext(ctx context.Context, identifier, topic string, duration int, meta string, config *TransactionConfig) (string, error)

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

Duration is changed to signed int for gomobile compatibility.

func (*Client) Transfer added in v1.2.4

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

Transfer wraps TransferContext with background context.

func (*Client) TransferContext added in v1.3.5

func (c *Client) TransferContext(ctx context.Context, address, amount string, config *TransactionConfig) (string, error)

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

func (*Client) TransferName added in v1.2.4

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

TransferName wraps TransferNameContext with background context.

func (*Client) TransferNameContext added in v1.3.5

func (c *Client) TransferNameContext(ctx context.Context, name string, recipientPubKey []byte, config *TransactionConfig) (string, error)

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

func (*Client) Unsubscribe added in v1.2.4

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

Unsubscribe wraps UnsubscribeContext with background context.

func (*Client) UnsubscribeContext added in v1.3.5

func (c *Client) UnsubscribeContext(ctx context.Context, identifier, topic string, config *TransactionConfig) (string, error)

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

type ClientAddr

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

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

func NewClientAddr

func NewClientAddr(addr string) *ClientAddr

NewClientAddr creates a ClientAddr from a client address string.

func (ClientAddr) Network

func (addr ClientAddr) Network() string

Network returns "nkn"

func (ClientAddr) String

func (addr ClientAddr) String() string

String returns the NKN client address string.

type ClientConfig

type ClientConfig struct {
	SeedRPCServerAddr       *nkngomobile.StringArray // Seed RPC server address that client uses to find its node and make RPC requests (e.g. get subscribers).
	RPCTimeout              int32                    // Timeout for each RPC call in millisecond
	RPCConcurrency          int32                    // If greater than 1, the same rpc request will be concurrently sent to multiple seed rpc nodes
	MsgChanLen              int32                    // Channel length for received but unproccessed messages.
	ConnectRetries          int32                    // Connnect to node retries (including the initial connect). A negative value 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.
	AllowUnencrypted        bool                     // Allow receiving unencrypted message. Unencrypted message might have sender or body viewed/modified by middleman or forged by sender.
	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.

	HttpDialContext func(ctx context.Context, network, addr string) (net.Conn, error) // Customized http dialcontext function
	WsDialContext   func(ctx context.Context, network, addr string) (net.Conn, error) // Customized websocket dialcontext function

	Resolvers       *nkngomobile.ResolverArray // Resolvers resolve a string to a NKN address
	ResolverDepth   int32                      // Max recursive resolve calls
	ResolverTimeout int32                      // Timeout for the whole resolving process

	WebRTC               bool                     // Whether to use webrtc for data channel
	StunServerAddr       *nkngomobile.StringArray // Stun server address that client uses to find its node
	WebRTCConnectTimeout int32                    // Timeout for webrtc connection in milliseconds
}

ClientConfig is the client configuration.

func GetDefaultClientConfig added in v1.2.3

func GetDefaultClientConfig() *ClientConfig

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

func MergeClientConfig

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) RPCGetConcurrency added in v1.3.5

func (c *ClientConfig) RPCGetConcurrency() int32

RPCGetConcurrency returns RPC concurrency. RPC prefix is added to avoid gomobile compile error.

func (*ClientConfig) RPCGetHttpDialContext added in v1.4.2

func (c *ClientConfig) RPCGetHttpDialContext() func(ctx context.Context, network, addr string) (net.Conn, error)

func (*ClientConfig) RPCGetRPCTimeout added in v1.3.5

func (c *ClientConfig) RPCGetRPCTimeout() int32

RPCGetRPCTimeout returns RPC timeout in millisecond. RPC prefix is added to avoid gomobile compile error.

func (*ClientConfig) RPCGetSeedRPCServerAddr added in v1.3.5

func (c *ClientConfig) RPCGetSeedRPCServerAddr() *nkngomobile.StringArray

RPCGetSeedRPCServerAddr returns all seed rpc server addresses. RPC prefix is added to avoid gomobile compile error.

type DialConfig

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 added in v1.2.3

func GetDefaultDialConfig(baseSessionConfig *ncp.Config) *DialConfig

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

func MergeDialConfig

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 added in v1.2.3

type ErrorWithCode interface {
	error
	Code() int32
}

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

type Message

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

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

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

func (*Message) ReplyBinary

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

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

func (*Message) ReplyText

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

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

type MessageConfig

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 added in v1.2.3

func GetDefaultMessageConfig() *MessageConfig

GetDefaultMessageConfig returns the default message config.

func MergeMessageConfig

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

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

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 an 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

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

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

func (*MultiClient) AcceptSession

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 added in v1.2.9

func (m *MultiClient) Account() *Account

Account returns the account of the multiclient.

func (*MultiClient) Addr

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

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 added in v1.2.4

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

Balance wraps BalanceContext with background context.

func (*MultiClient) BalanceByAddress added in v1.2.4

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

BalanceByAddress wraps BalanceByAddressContext with background context.

func (*MultiClient) BalanceByAddressContext added in v1.3.5

func (m *MultiClient) BalanceByAddressContext(ctx context.Context, address string) (*Amount, error)

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

func (*MultiClient) BalanceContext added in v1.3.5

func (m *MultiClient) BalanceContext(ctx context.Context) (*Amount, error)

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

func (*MultiClient) Close

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 added in v1.2.4

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

DeleteName wraps DeleteNameContext with background context.

func (*MultiClient) DeleteNameContext added in v1.3.5

func (m *MultiClient) DeleteNameContext(ctx context.Context, name string, config *TransactionConfig) (string, error)

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

func (*MultiClient) Dial

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

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

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 added in v1.2.2

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

GetClient returns a client with a given index.

func (*MultiClient) GetClients added in v1.2.2

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 added in v1.2.2

func (m *MultiClient) GetDefaultClient() *Client

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

func (*MultiClient) GetHeight added in v1.2.4

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

GetHeight wraps GetHeightContext with background context.

func (*MultiClient) GetHeightContext added in v1.3.5

func (m *MultiClient) GetHeightContext(ctx context.Context) (int32, error)

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

func (*MultiClient) GetNonce added in v1.2.4

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

GetNonce wraps GetNonceContext with background context.

func (*MultiClient) GetNonceByAddress added in v1.2.4

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

GetNonceByAddress wraps GetNonceByAddressContext with background context.

func (*MultiClient) GetNonceByAddressContext added in v1.3.5

func (m *MultiClient) GetNonceByAddressContext(ctx context.Context, address string, txPool bool) (int64, error)

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

func (*MultiClient) GetNonceContext added in v1.3.5

func (m *MultiClient) GetNonceContext(ctx context.Context, txPool bool) (int64, error)

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

func (*MultiClient) GetRegistrant added in v1.2.4

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

GetRegistrant wraps GetRegistrantContext with background context.

func (*MultiClient) GetRegistrantContext added in v1.3.5

func (m *MultiClient) GetRegistrantContext(ctx context.Context, name string) (*Registrant, error)

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

func (*MultiClient) GetSubscribers added in v1.2.4

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

GetSubscribers wraps GetSubscribersContext with background context.

func (*MultiClient) GetSubscribersContext added in v1.3.5

func (m *MultiClient) GetSubscribersContext(ctx context.Context, topic string, offset, limit int, meta, txPool bool, subscriberHashPrefix []byte) (*Subscribers, error)

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

func (*MultiClient) GetSubscribersCount added in v1.2.4

func (m *MultiClient) GetSubscribersCount(topic string, subscriberHashPrefix []byte) (int, error)

GetSubscribersCount wraps GetSubscribersCountContext with background context.

func (*MultiClient) GetSubscribersCountContext added in v1.3.5

func (m *MultiClient) GetSubscribersCountContext(ctx context.Context, topic string, subscriberHashPrefix []byte) (int, error)

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

func (*MultiClient) GetSubscription added in v1.2.4

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

GetSubscription wraps GetSubscriptionContext with background context.

func (*MultiClient) GetSubscriptionContext added in v1.3.5

func (m *MultiClient) GetSubscriptionContext(ctx context.Context, topic string, subscriber string) (*Subscription, error)

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

func (*MultiClient) IsClosed

func (m *MultiClient) IsClosed() bool

IsClosed returns whether this multiclient is closed.

func (*MultiClient) Listen

func (m *MultiClient) Listen(addrsRe *nkngomobile.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 added in v1.2.4

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 added in v1.2.4

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

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

func (*MultiClient) PubKey added in v1.2.3

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

PubKey returns the public key of the multiclient.

func (*MultiClient) Publish

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

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

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 added in v1.2.9

func (m *MultiClient) Reconnect()

Reconnect forces all clients to find node and connect again.

func (*MultiClient) RegisterName added in v1.2.4

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

RegisterName wraps RegisterNameContext with background context.

func (*MultiClient) RegisterNameContext added in v1.3.5

func (m *MultiClient) RegisterNameContext(ctx context.Context, name string, config *TransactionConfig) (string, error)

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

func (*MultiClient) ResolveDest added in v1.4.6

func (m *MultiClient) ResolveDest(dest string) (string, error)

ResolveDest wraps ResolveDestContext with background context

func (*MultiClient) ResolveDestContext added in v1.4.6

func (m *MultiClient) ResolveDestContext(ctx context.Context, dest string) (string, error)

ResolveDestContext resolvers an address, returns NKN address

func (*MultiClient) ResolveDests added in v1.4.6

func (m *MultiClient) ResolveDests(dests *nkngomobile.StringArray) (*nkngomobile.StringArray, error)

ResolveDests wraps ResolveDestsContext with background context

func (*MultiClient) ResolveDestsContext added in v1.4.6

func (m *MultiClient) ResolveDestsContext(ctx context.Context, dests *nkngomobile.StringArray) (*nkngomobile.StringArray, error)

ResolveDestsContext resolvers multiple addresses

func (*MultiClient) Seed added in v1.2.3

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

func (m *MultiClient) Send(dests *nkngomobile.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

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

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

func (*MultiClient) SendBinaryWithClient

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

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

func (*MultiClient) SendPayload added in v1.4.2

func (m *MultiClient) SendPayload(dests *nkngomobile.StringArray, payload *payloads.Payload, config *MessageConfig) (*OnMessage, error)

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

func (*MultiClient) SendRawTransaction added in v1.2.4

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

SendRawTransaction wraps SendRawTransactionContext with background context.

func (*MultiClient) SendRawTransactionContext added in v1.3.5

func (m *MultiClient) SendRawTransactionContext(ctx context.Context, txn *transaction.Transaction) (string, error)

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

func (*MultiClient) SendText

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

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

func (*MultiClient) SendTextWithClient

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

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

func (*MultiClient) SendWithClient

func (m *MultiClient) SendWithClient(clientID int, dests *nkngomobile.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 added in v1.2.4

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

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

func (*MultiClient) Subscribe added in v1.2.4

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

Subscribe wraps SubscribeContext with background context.

func (*MultiClient) SubscribeContext added in v1.3.5

func (m *MultiClient) SubscribeContext(ctx context.Context, identifier, topic string, duration int, meta string, config *TransactionConfig) (string, error)

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

Duration is changed to signed int for gomobile compatibility.

func (*MultiClient) Transfer added in v1.2.4

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

Transfer wraps TransferContext with background context.

func (*MultiClient) TransferContext added in v1.3.5

func (m *MultiClient) TransferContext(ctx context.Context, address, amount string, config *TransactionConfig) (string, error)

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

func (*MultiClient) TransferName added in v1.2.4

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

TransferName wraps TransferNameContext with background context.

func (*MultiClient) TransferNameContext added in v1.3.5

func (m *MultiClient) TransferNameContext(ctx context.Context, name string, recipientPubKey []byte, config *TransactionConfig) (string, error)

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

func (*MultiClient) Unsubscribe added in v1.2.4

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

Unsubscribe wraps UnsubscribeContext with background context.

func (*MultiClient) UnsubscribeContext added in v1.3.5

func (m *MultiClient) UnsubscribeContext(ctx context.Context, identifier, topic string, config *TransactionConfig) (string, error)

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

type NanoPay

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

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

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

IncrementAmount increments the NanoPay amount by delta and returns the signed NanoPay transaction. If length of fee is greater than zero, it will parsed as transaction fee, otherwise the default transaction fee (passed when creating nanopay) will be used. Delta and fee are 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 added in v1.2.3

func (np *NanoPay) Recipient() string

Recipient returns the recipient wallet address.

type NanoPayClaimer

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

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

func NewNanoPayClaimer

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

NewNanoPayClaimer creates a NanoPayClaimer with a given rpcClient (client, multiclient or wallet), recipient wallet address, claim interval in millisecond, flush linger after close in millisecond, minimal flush amount, onError channel. It is recommended to use a positive minFlushAmount.

func (*NanoPayClaimer) Amount

func (npc *NanoPayClaimer) Amount() *Amount

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

func (*NanoPayClaimer) Claim

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

func (npc *NanoPayClaimer) Close() error

Close closes the NanoPayClaimer.

func (*NanoPayClaimer) Flush

func (npc *NanoPayClaimer) Flush() error

Flush sends the current latest NanoPay state to chain.

func (*NanoPayClaimer) IsClosed

func (npc *NanoPayClaimer) IsClosed() bool

IsClosed returns whether the NanoPayClaimer is closed.

func (*NanoPayClaimer) Recipient added in v1.2.3

func (npc *NanoPayClaimer) Recipient() string

Recipient returns the NanoPayClaimer's recipient wallet address.

type Node added in v1.2.3

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

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

func GetPeerAddr added in v1.4.8

func GetPeerAddr(clientAddr string, offer string, config RPCConfigInterface) (*Node, error)

GetWsAddr wraps GetWsAddrContext with background context.

func GetPeerAddrContext added in v1.4.8

func GetPeerAddrContext(ctx context.Context, clientAddr string, offer string, config RPCConfigInterface) (*Node, error)

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

func GetWsAddr added in v1.2.3

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

GetWsAddr wraps GetWsAddrContext with background context.

func GetWsAddrContext added in v1.3.5

func GetWsAddrContext(ctx context.Context, clientAddr string, config RPCConfigInterface) (*Node, error)

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

func GetWssAddr added in v1.2.3

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

GetWssAddr wraps GetWssAddrContext with background context.

func GetWssAddrContext added in v1.3.5

func GetWssAddrContext(ctx context.Context, clientAddr string, config RPCConfigInterface) (*Node, error)

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

type NodeState added in v1.3.5

type NodeState struct {
	Addr               string `json:"addr"`
	CurrTimeStamp      int64  `json:"currTimeStamp"`
	Height             int32  `json:"height"` // Changed to signed int for gomobile compatibility
	ID                 string `json:"id"`
	JSONRPCPort        int32  `json:"jsonRpcPort"`
	ProposalSubmitted  int32  `json:"proposalSubmitted"`
	ProtocolVersion    int32  `json:"protocolVersion"`
	PublicKey          string `json:"publicKey"`
	RelayMessageCount  int64  `json:"relayMessageCount"`
	SyncState          string `json:"syncState"`
	TLSJSONRpcDomain   string `json:"tlsJsonRpcDomain"`
	TLSJSONRpcPort     int32  `json:"tlsJsonRpcPort"`
	TLSWebsocketDomain string `json:"tlsWebsocketDomain"`
	TLSWebsocketPort   int32  `json:"tlsWebsocketPort"`
	Uptime             int64  `json:"uptime"`
	Version            string `json:"version"`
	WebsocketPort      int32  `json:"websocketPort"`
}

NodeState struct contains the state of a NKN full node.

func GetNodeState added in v1.3.5

func GetNodeState(config RPCConfigInterface) (*NodeState, error)

GetNodeState wraps GetNodeStateContext with background context.

func GetNodeStateContext added in v1.3.5

func GetNodeStateContext(ctx context.Context, config RPCConfigInterface) (*NodeState, error)

GetNodeStateContext returns the state of the RPC node.

type OnConnect

type OnConnect struct {
	C        chan *Node
	Callback OnConnectFunc
}

OnConnect is a wrapper type for gomobile compatibility.

func NewOnConnect

func NewOnConnect(size int, cb OnConnectFunc) *OnConnect

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

func (*OnConnect) MaybeNext added in v1.4.7

func (c *OnConnect) MaybeNext() *Node

MaybeNext returns the next element in the channel, or nil if channel is empty.

func (*OnConnect) Next

func (c *OnConnect) Next() *Node

Next waits and returns the next element from the channel.

type OnConnectFunc

type OnConnectFunc interface{ OnConnect(*Node) }

OnConnectFunc is a wrapper type for gomobile compatibility.

type OnError

type OnError struct {
	C        chan error
	Callback OnErrorFunc
}

OnError is a wrapper type for gomobile compatibility.

func NewOnError

func NewOnError(size int, cb OnErrorFunc) *OnError

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

func (*OnError) MaybeNext added in v1.4.7

func (c *OnError) MaybeNext() error

MaybeNext returns the next element in the channel, or nil if channel is empty.

func (*OnError) Next

func (c *OnError) Next() error

Next waits and returns the next element from the channel.

type OnErrorFunc

type OnErrorFunc interface{ OnError(error) }

OnErrorFunc is a wrapper type for gomobile compatibility.

type OnMessage

type OnMessage struct {
	C        chan *Message
	Callback OnMessageFunc
}

OnMessage is a wrapper type for gomobile compatibility.

func NewOnMessage

func NewOnMessage(size int, cb OnMessageFunc) *OnMessage

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

func (*OnMessage) MaybeNext added in v1.4.7

func (c *OnMessage) MaybeNext() *Message

MaybeNext returns the next element in the channel, or nil if channel is empty.

func (*OnMessage) Next

func (c *OnMessage) Next() *Message

Next waits and returns the next element from the channel.

func (*OnMessage) NextWithTimeout added in v1.3.3

func (c *OnMessage) NextWithTimeout(timeout int32) *Message

NextWithTimeout waits and returns the next element from the channel, timeout in millisecond.

type OnMessageFunc

type OnMessageFunc interface{ OnMessage(*Message) }

OnMessageFunc is a wrapper type for gomobile compatibility.

type RPCConfig added in v1.2.3

type RPCConfig struct {
	SeedRPCServerAddr *nkngomobile.StringArray
	RPCTimeout        int32 // Timeout for each RPC call in millisecond
	RPCConcurrency    int32 // If greater than 1, the same rpc request will be concurrently sent to multiple seed rpc nodes
	HttpDialContext   func(ctx context.Context, network, addr string) (net.Conn, error)
}

RPCConfig is the rpc call configuration.

func GetDefaultRPCConfig added in v1.2.3

func GetDefaultRPCConfig() *RPCConfig

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

func (*RPCConfig) RPCGetConcurrency added in v1.3.5

func (c *RPCConfig) RPCGetConcurrency() int32

RPCGetConcurrency returns RPC concurrency. RPC prefix is added to avoid gomobile compile error.

func (*RPCConfig) RPCGetHttpDialContext added in v1.4.2

func (c *RPCConfig) RPCGetHttpDialContext() func(ctx context.Context, network, addr string) (net.Conn, error)

func (*RPCConfig) RPCGetRPCTimeout added in v1.3.5

func (c *RPCConfig) RPCGetRPCTimeout() int32

RPCGetRPCTimeout returns RPC timeout in millisecond. RPC prefix is added to avoid gomobile compile error.

func (*RPCConfig) RPCGetSeedRPCServerAddr added in v1.3.5

func (c *RPCConfig) RPCGetSeedRPCServerAddr() *nkngomobile.StringArray

RPCGetSeedRPCServerAddr returns all seed rpc server addresses. RPC prefix is added to avoid gomobile compile error.

type RPCConfigInterface added in v1.2.3

type RPCConfigInterface interface {
	RPCGetSeedRPCServerAddr() *nkngomobile.StringArray
	RPCGetRPCTimeout() int32
	RPCGetConcurrency() int32
}

RPCConfigInterface is the config interface for making rpc call. ClientConfig, WalletConfig and RPCConfig all implement this interface and thus can be used directly. RPC prefix is added to all public methods to avoid gomobile compile error.

type Registrant added in v1.2.3

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 added in v1.2.3

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

GetRegistrant wraps GetRegistrantContext with background context.

func GetRegistrantContext added in v1.3.5

func GetRegistrantContext(ctx context.Context, name string, config RPCConfigInterface) (*Registrant, error)

GetRegistrantContext RPC gets the registrant of a name.

type Resolver added in v1.4.6

type Resolver interface {
	nkngomobile.Resolver
	ResolveContext(ctx context.Context, address string) (string, error)
}

type ScryptConfig added in v1.2.6

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

ScryptConfig is the scrypt configuration.

type Subscribers

type Subscribers struct{ Subscribers, SubscribersInTxPool *nkngomobile.StringMap }

Subscribers is a wrapper type for gomobile compatibility.

func GetSubscribers added in v1.2.3

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

GetSubscribers wraps GetSubscribersContext with background context.

func GetSubscribersContext added in v1.3.5

func GetSubscribersContext(ctx context.Context, topic string, offset, limit int, meta, txPool bool, subscriberHashPrefix []byte, config RPCConfigInterface) (*Subscribers, error)

GetSubscribersContext 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. If subscriberHashPrefix is not empty, only subscriber whose sha256(pubkey+identifier) contains this prefix will be returned. Each prefix byte will reduce result count to about 1/256, and also reduce response time to about 1/256 if there are a lot of subscribers. This is a good way to sample subscribers randomly with low cost.

Offset and limit are changed to signed int for gomobile compatibility

type Subscription

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 added in v1.2.3

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

GetSubscription wraps GetSubscriptionContext with background context.

func GetSubscriptionContext added in v1.3.5

func GetSubscriptionContext(ctx context.Context, topic string, subscriber string, config RPCConfigInterface) (*Subscription, error)

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

type TransactionConfig added in v1.2.4

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

TransactionConfig is the config for making a transaction. If Nonce is 0 and FixNonce is false, then nonce will be fetched from RPC call.

func GetDefaultTransactionConfig added in v1.2.4

func GetDefaultTransactionConfig() *TransactionConfig

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

func MergeTransactionConfig added in v1.2.4

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

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

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

func NewWallet

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

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 added in v1.2.9

func (w *Wallet) Account() *Account

Account returns the account of the wallet.

func (*Wallet) Address

func (w *Wallet) Address() string

Address returns the NKN wallet address of the wallet.

func (*Wallet) Balance

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

Balance wraps BalanceContext with background context.

func (*Wallet) BalanceByAddress

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

BalanceByAddress wraps BalanceByAddressContext with background context.

func (*Wallet) BalanceByAddressContext added in v1.3.5

func (w *Wallet) BalanceByAddressContext(ctx context.Context, address string) (*Amount, error)

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

func (*Wallet) BalanceContext added in v1.3.5

func (w *Wallet) BalanceContext(ctx context.Context) (*Amount, error)

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

func (*Wallet) DeleteName

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

DeleteName wraps DeleteNameContext with background context.

func (*Wallet) DeleteNameContext added in v1.3.5

func (w *Wallet) DeleteNameContext(ctx context.Context, name string, config *TransactionConfig) (string, error)

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

func (*Wallet) GetHeight added in v1.2.3

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

GetHeight wraps GetHeightContext with background context.

func (*Wallet) GetHeightContext added in v1.3.5

func (w *Wallet) GetHeightContext(ctx context.Context) (int32, error)

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

func (*Wallet) GetNonce

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

GetNonce wraps GetNonceContext with background context.

func (*Wallet) GetNonceByAddress added in v1.2.4

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

GetNonceByAddress wraps GetNonceByAddressContext with background context.

func (*Wallet) GetNonceByAddressContext added in v1.3.5

func (w *Wallet) GetNonceByAddressContext(ctx context.Context, address string, txPool bool) (int64, error)

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

func (*Wallet) GetNonceContext added in v1.3.5

func (w *Wallet) GetNonceContext(ctx context.Context, txPool bool) (int64, error)

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

func (*Wallet) GetRegistrant added in v1.2.4

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

GetRegistrant wraps GetRegistrantContext with background context.

func (*Wallet) GetRegistrantContext added in v1.3.5

func (w *Wallet) GetRegistrantContext(ctx context.Context, name string) (*Registrant, error)

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

func (*Wallet) GetSubscribers

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

GetSubscribers wraps GetSubscribersContext with background context.

func (*Wallet) GetSubscribersContext added in v1.3.5

func (w *Wallet) GetSubscribersContext(ctx context.Context, topic string, offset, limit int, meta, txPool bool, subscriberHashPrefix []byte) (*Subscribers, error)

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

func (*Wallet) GetSubscribersCount

func (w *Wallet) GetSubscribersCount(topic string, subscriberHashPrefix []byte) (int, error)

GetSubscribersCount wraps GetSubscribersCountContext with background context.

func (*Wallet) GetSubscribersCountContext added in v1.3.5

func (w *Wallet) GetSubscribersCountContext(ctx context.Context, topic string, subscriberHashPrefix []byte) (int, error)

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

func (*Wallet) GetSubscription

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

GetSubscription wraps GetSubscriptionContext with background context.

func (*Wallet) GetSubscriptionContext added in v1.3.5

func (w *Wallet) GetSubscriptionContext(ctx context.Context, topic string, subscriber string) (*Subscription, error)

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

func (*Wallet) MarshalJSON added in v1.2.6

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

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

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

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

func (*Wallet) ProgramHash added in v1.2.4

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

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

func (*Wallet) PubKey

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

PubKey returns the public key of the wallet.

func (*Wallet) RegisterName

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

RegisterName wraps RegisterNameContext with background context.

func (*Wallet) RegisterNameContext added in v1.3.5

func (w *Wallet) RegisterNameContext(ctx context.Context, name string, config *TransactionConfig) (string, error)

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

func (*Wallet) Seed

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

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

SendRawTransaction wraps SendRawTransactionContext with background context.

func (*Wallet) SendRawTransactionContext added in v1.3.5

func (w *Wallet) SendRawTransactionContext(ctx context.Context, txn *transaction.Transaction) (string, error)

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

func (*Wallet) SignTransaction added in v1.2.4

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

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

func (*Wallet) Subscribe

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

Subscribe wraps SubscribeContext with background context.

func (*Wallet) SubscribeContext added in v1.3.5

func (w *Wallet) SubscribeContext(ctx context.Context, identifier, topic string, duration int, meta string, config *TransactionConfig) (string, error)

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

Duration is changed to signed int for gomobile compatibility.

func (*Wallet) ToJSON

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

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

func (*Wallet) Transfer

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

Transfer wraps TransferContext with background context.

func (*Wallet) TransferContext added in v1.3.5

func (w *Wallet) TransferContext(ctx context.Context, address, amount string, config *TransactionConfig) (string, error)

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

func (*Wallet) TransferName

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

TransferName wraps TransferNameContext with background context.

func (*Wallet) TransferNameContext added in v1.3.5

func (w *Wallet) TransferNameContext(ctx context.Context, name string, recipientPubKey []byte, config *TransactionConfig) (string, error)

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

func (*Wallet) Unsubscribe

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

Unsubscribe wraps UnsubscribeContext with background context.

func (*Wallet) UnsubscribeContext added in v1.3.5

func (w *Wallet) UnsubscribeContext(ctx context.Context, identifier, topic string, config *TransactionConfig) (string, error)

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

func (*Wallet) VerifyPassword

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

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

type WalletConfig

type WalletConfig struct {
	SeedRPCServerAddr *nkngomobile.StringArray
	RPCTimeout        int32 // Timeout for each RPC call in millisecond
	RPCConcurrency    int32 // If greater than 1, the same rpc request will be concurrently sent to multiple seed rpc nodes
	Password          string
	IV                []byte
	MasterKey         []byte
	ScryptConfig      *ScryptConfig
	HttpDialContext   func(ctx context.Context, network, addr string) (net.Conn, error)
}

WalletConfig is the wallet configuration.

func GetDefaultWalletConfig added in v1.2.3

func GetDefaultWalletConfig() *WalletConfig

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

func MergeWalletConfig

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) RPCGetConcurrency added in v1.3.5

func (c *WalletConfig) RPCGetConcurrency() int32

RPCGetConcurrency returns RPC concurrency. RPC prefix is added to avoid gomobile compile error.

func (*WalletConfig) RPCGetHttpDialContext added in v1.4.2

func (c *WalletConfig) RPCGetHttpDialContext() func(ctx context.Context, network, addr string) (net.Conn, error)

func (*WalletConfig) RPCGetRPCTimeout added in v1.3.5

func (c *WalletConfig) RPCGetRPCTimeout() int32

RPCGetRPCTimeout returns RPC timeout in millisecond. RPC prefix is added to avoid gomobile compile error.

func (*WalletConfig) RPCGetSeedRPCServerAddr added in v1.3.5

func (c *WalletConfig) RPCGetSeedRPCServerAddr() *nkngomobile.StringArray

RPCGetSeedRPCServerAddr returns all seed rpc server addresses. RPC prefix is added to avoid gomobile compile error.

Directories

Path Synopsis
examples
session/grpc Module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL