Documentation ¶
Overview ¶
Package nimiqrpc provides a Nimiq RPC client library in Go.
This client library implements the Nimiq RPC specification Which can be found here: https://github.com/nimiq/core-js/wiki/JSON-RPC-API#remotejs-client This package provides a Client and all the necessary types to interact with the Nimiq RPC server.
This client uses the jsonrpc library to handle JSON-RPC 2.0 requests and responses. For more information about this library see the documentation https://godoc.org/github.com/ybbus/jsonrpc
How to use this package:
// Initialise a new client nimiqClient := nimiqrpc.NewClient("address.to.nimiqnode.com") // Do an RPC call. For example retrieve the balance of a Nimiq account: balance, err := nimiqClient.GetBalance("NQ52 V4BF 52J3 0PM6 BG4M 9QY1 RUYS UAL6 CJD2") if err != nil { panic(err) } fmt.Printf("Balance: %v\n", balance)
Index ¶
- Constants
- Variables
- func NewRequest(method string, params ...interface{}) *jsonrpc.RPCRequest
- type Account
- type AddressObject
- type Block
- type BlockTemplate
- type BlockTemplateBody
- type BlockTemplateHeader
- type Client
- func (nc *Client) Accounts() (accounts []Account, err error)
- func (nc *Client) BlockNumber() (blockHeight int, err error)
- func (nc *Client) Call(method string, params interface{}) (*jsonrpc.RPCResponse, error)
- func (nc *Client) CallBatch(reqs ...*jsonrpc.RPCRequest) (jsonrpc.RPCResponses, error)
- func (nc *Client) Consensus() (consensus string, err error)
- func (nc *Client) CreateAccount() (wallet *Wallet, err error)
- func (nc *Client) CreateRawTransaction(trn OutgoingTransaction) (transactionHex string, err error)
- func (nc *Client) GetAccount(address string) (account *Account, err error)
- func (nc *Client) GetBalance(address string) (balance Luna, err error)
- func (nc *Client) GetBlockByHash(blockHash string, fullTransactions bool) (block *Block, err error)
- func (nc *Client) GetBlockByNumber(blockNumber int, fullTransactions bool) (block *Block, err error)
- func (nc *Client) GetBlockTemplate(params ...interface{}) (template *BlockTemplate, err error)
- func (nc *Client) GetBlockTransactionCountByHash(blockHash string) (transactionCount int, err error)
- func (nc *Client) GetBlockTransactionCountByNumber(blockNumber int) (transactionCount int, err error)
- func (nc *Client) GetTransactionByBlockHashAndIndex(blockHash string, index int) (transaction *Transaction, err error)
- func (nc *Client) GetTransactionByBlockNumberAndIndex(blockNumber int, index int) (transaction *Transaction, err error)
- func (nc *Client) GetTransactionByHash(transactionHash string) (transaction *Transaction, err error)
- func (nc *Client) GetTransactionReceipt(transactionHash string) (transactionReceipt *TransactionReceipt, err error)
- func (nc *Client) GetTransactionsByAddress(address string, maxEntries int) (transactions []Transaction, err error)
- func (nc *Client) GetWork(params ...interface{}) (work *Work, err error)
- func (nc *Client) Hashrate() (hashrate float64, err error)
- func (nc *Client) Log(tag string, level LogLevel) (succes bool, err error)
- func (nc *Client) Mempool() (mempool *Mempool, err error)
- func (nc *Client) MempoolContent(fullTransactions bool) (transactions interface{}, err error)
- func (nc *Client) MinFeePerByte(newFee ...int64) (fee int64, err error)
- func (nc *Client) MinerAddress() (address string, err error)
- func (nc *Client) MinerThreads(number ...int) (threads int, err error)
- func (nc *Client) Mining(state ...bool) (status bool, err error)
- func (nc *Client) PeerCount() (peers int, err error)
- func (nc *Client) PeerList() (peers []Peer, err error)
- func (nc *Client) PeerState(peerAddress string, update ...string) (peer *Peer, err error)
- func (nc *Client) Pool(newAddress ...string) (address string, err error)
- func (nc *Client) PoolConfirmedBalance() (balance Luna, err error)
- func (nc *Client) PoolConnectionState() (state int, err error)
- func (nc *Client) SendRawTransaction(signedTransaction string) (transactionHash string, err error)
- func (nc *Client) SendTransaction(trn OutgoingTransaction) (transactionHash string, err error)
- func (nc *Client) SubmitBlock(fullBlock string) (err error)
- func (nc *Client) Syncing() (syncing bool, syncStatus *SyncStatus, err error)
- type LogLevel
- type Luna
- type Mempool
- type NIM
- type OutgoingTransaction
- type Peer
- type SyncStatus
- type Transaction
- type TransactionReceipt
- type Wallet
- type Work
Constants ¶
const ( AccountTypeBasic = 0 AccountTypeVesting = 1 AccountTypeHTLC = 2 )
Account types on the blockchain
Variables ¶
var ( // ErrRespBodyEmpty is returned when the underlying HTTP response body is empty ErrRespBodyEmpty = errors.New("the HTTP response body was empty") // ErrResultUnexpected is returned when the expected result could not be read ErrResultUnexpected = errors.New("unexpected result") ErrUnauthorized = errors.New("unauthorized") // ErrNotAuthenticated is returned when the user is required to be authenticated ErrNotAuthenticated = errors.New("not authenticated") )
Functions ¶
func NewRequest ¶
func NewRequest(method string, params ...interface{}) *jsonrpc.RPCRequest
NewRequest returns a *jsonrpc.RPCRequest that can be used as a parameter to the CallBatch function.
Types ¶
type Account ¶
type Account struct { ID string `json:"id"` // hex-encoded address bytes Address string `json:"address"` // user friendly address (NQ-address). Balance Luna `json:"balance"` // Balance of the account in Luna Type int `json:"type"` // see AccountType const block // Additional fields for AccountTypeVesting Owner string `json:"owner,omitempty"` // hex-encoded address of contract owner OwnerAddress string `json:"ownerAddress,omitempty"` // user friendly address of contract owner VestingStart int `json:"vestingStart,omitempty"` // the block that the vesting contracted commenced VestingStepBlocks int `json:"vestingStepBlocks,omitempty"` // no. of blocks after which some part of the vested funds is released VestingStepAmount int `json:"vestingStepAmount,omitempty"` // amount in Luna released every VestingStepBlocks blocks VestingTotalAmount int `json:"vestingTotalAmount,omitempty"` // total amount in Luna that was provided at the contract creation // Additional fields for AccountTypeHTLC Sender string `json:"sender,omitempty"` // hex-encoded address of HTLC sender SenderAddress string `json:"senderAddress,omitempty"` // user friendly address of HTLC sender Recipient string `json:"recipient,omitempty"` // hex-encoded address of HTLC recipient RecipientAddress string `json:"recipientAddress,omitempty"` // user friendly address of HTLC recipient HashRoot string `json:"hashRoot,omitempty"` // hex-encoded 32 byte hash root HashCount int `json:"hashCount,omitempty"` // no. of hashes this HTLC is split into Timeout int `json:"timeout,omitempty"` // block at which the HTLC times out TotalAmount int `json:"totalAmount,omitempty"` // total amount in Luna provided at contract creation }
Account holds the details on an account
type AddressObject ¶
type AddressObject struct { ID string `json:"id"` // hex-encoded 20 byte address Address string `json:"address"` // user friendly address (NQ-address) }
AddressObject holds the representation of a Nimiq address in two formats.
type Block ¶
type Block struct { Number int `json:"number"` // height of the block Hash string `json:"hash"` // block hash POW string `json:"pow"` // proof-of-work hash ParentHash string `json:"parentHash"` // hash of the predecessor block Nonce int `json:"nonce"` // nonce of the block used to fulfill the proof-of-work BodyHash string `json:"bodyHash"` // hash of the block body Merkle root AccountHash string `json:"accountHash"` // hash of the accounts tree root Miner string `json:"miner"` // hex-encoded address of the miner MinerAddress string `json:"minerAddress"` // user friendly address of the miner Difficulty json.Number `json:"difficulty"` // block difficulty ExtraData string `json:"extraData"` // hex-encoded value of the extra data field Size int `json:"size"` // block size in bytes Timestamp int `json:"timestamp"` // UNIX timestamp of the block // Transactions contains either an array of transaction hashes or transaction objects, // depending on request parameters. // Depending on the result, the TransactionHashes or TransactionObjects fields are set. Transactions json.RawMessage `json:"transactions"` TransactionHashes []string // hashes of the transactions in the block TransactionObjects []Transaction // detailed transaction objects }
Block holds the details on a block
type BlockTemplate ¶
type BlockTemplate struct { Header BlockTemplateHeader `json:"header"` Interlink string `json:"interlink"` // hex-encoded interlink Body BlockTemplateBody `json:"body"` Target int `json:"target"` // compact form of hash target to submit a block }
BlockTemplate contains details on a block template
type BlockTemplateBody ¶
type BlockTemplateBody struct { Hash string `json:"hash"` // hash of the block body MinerAddr string `json:"minerAddr"` // hex-encoded miner address ExtraData string `json:"extraData"` // hex-encoded value of the extra data field Transactions []string `json:"transactions"` // hex-encoded transactions for this block PrunedAccounts []string `json:"prunedAccounts"` // hex-encoded pruned accounts for this block // MerkleHashes contains hex-encoded hashes that verify the path of the miner // address in the merkle tree. This can be used to change the miner address easily. MerkleHashes []string `json:"merkleHashes"` }
BlockTemplateBody describes the block body of a template
type BlockTemplateHeader ¶
type BlockTemplateHeader struct { Version int `json:"version"` // block version PrevHash string `json:"prevHash"` // hash of the predecessor block InterlinkHash string `json:"interlinkHash"` // hash of the interlink AccountHash string `json:"accountHash"` // hash of the accounts tree root NBits int `json:"nBits"` // compact form of hash target for this block Height int `json:"height"` // block number }
BlockTemplateHeader describes the block header of a template
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client contains a Nimiq RPC client
func NewClientWithAuth ¶
NewClientWithAuth returns a RPC client with the given username and password set for authentication
func (*Client) BlockNumber ¶
BlockNumber returns the height of most recent block.
func (*Client) Call ¶
func (nc *Client) Call(method string, params interface{}) (*jsonrpc.RPCResponse, error)
Call can be used to send a JSON-RPC request by setting the method and the parameters.
This function is used internally to handle all the RPC functions provided by the client. Therefore this function should generally not be used. It does however provide the functionality to do RPC requests that are (not yet) implemented by this client.
This function returns a *jsonrpc.RPCResponse. Please see the documentation for more information on how to unmarshall this RPCResponse. https://godoc.org/github.com/ybbus/jsonrpc#RPCResponse
func (*Client) CallBatch ¶
func (nc *Client) CallBatch(reqs ...*jsonrpc.RPCRequest) (jsonrpc.RPCResponses, error)
CallBatch invokes a list of RPCRequests in a single batch request. This function is for more advanced use cases.
Most convenient is to use the following form:
CallBatch( NewRequest("hashrate"), NewRequest("accounts"), })
Returns jsonrpc.RPCResponses that is of type []*jsonrpc.RPCResponse - note that a list of RPCResponses can be received unordered so it can happen that: responses[i] != responses[i].ID - RPCPersponses is enriched with helper functions e.g.: responses.HasError() returns true if one of the responses holds an RPCError Please see the documentation on how to handle jsonrpc.RPCResonses: https://godoc.org/github.com/ybbus/jsonrpc#RPCResponses
func (*Client) CreateAccount ¶
CreateAccount creates a new account and stores its private key in the client store.
func (*Client) CreateRawTransaction ¶
func (nc *Client) CreateRawTransaction(trn OutgoingTransaction) (transactionHex string, err error)
CreateRawTransaction creates and signs a transaction without sending it. The transaction can then be send via sendRawTransaction without accidentally replaying it.
func (*Client) GetAccount ¶
GetAccount returns details for the account of given address.
func (*Client) GetBalance ¶
GetBalance returns the balance of the account of given address.
func (*Client) GetBlockByHash ¶
GetBlockByHash returns information about a block by block hash. If fullTransactions is true it returns a block with the full transaction objects, if false only the hashes of the transactions will be returned.
func (*Client) GetBlockByNumber ¶
func (nc *Client) GetBlockByNumber(blockNumber int, fullTransactions bool) (block *Block, err error)
GetBlockByNumber returns information about a block by block number. If fullTransactions is true it returns a block with the full transaction objects, if false only the hashes of the transactions will be returned.
func (*Client) GetBlockTemplate ¶
func (nc *Client) GetBlockTemplate(params ...interface{}) (template *BlockTemplate, err error)
GetBlockTemplate returns a template to build the next block for mining. This will consider pool instructions when connected to a pool. Optional parameters: (1) The address to use as a miner for this block. This overrides the address provided during startup or from the pool. and (2) Hex-encoded value for the extra data field. This overrides the address provided during startup or from the pool.
func (*Client) GetBlockTransactionCountByHash ¶
func (nc *Client) GetBlockTransactionCountByHash(blockHash string) (transactionCount int, err error)
GetBlockTransactionCountByHash returns the number of transactions in a block from a block matching the given block hash.
func (*Client) GetBlockTransactionCountByNumber ¶
func (nc *Client) GetBlockTransactionCountByNumber(blockNumber int) (transactionCount int, err error)
GetBlockTransactionCountByNumber returns the number of transactions in a block from a block matching the given block number.
func (*Client) GetTransactionByBlockHashAndIndex ¶
func (nc *Client) GetTransactionByBlockHashAndIndex(blockHash string, index int) (transaction *Transaction, err error)
GetTransactionByBlockHashAndIndex returns information about a transaction by block hash and transaction index position.
func (*Client) GetTransactionByBlockNumberAndIndex ¶
func (nc *Client) GetTransactionByBlockNumberAndIndex(blockNumber int, index int) (transaction *Transaction, err error)
GetTransactionByBlockNumberAndIndex returns information about a transaction by block hash and transaction index position.
func (*Client) GetTransactionByHash ¶
func (nc *Client) GetTransactionByHash(transactionHash string) (transaction *Transaction, err error)
GetTransactionByHash Returns the information about a transaction requested by transaction hash.
func (*Client) GetTransactionReceipt ¶
func (nc *Client) GetTransactionReceipt(transactionHash string) (transactionReceipt *TransactionReceipt, err error)
GetTransactionReceipt returns the receipt of a transaction by transaction hash.
func (*Client) GetTransactionsByAddress ¶
func (nc *Client) GetTransactionsByAddress(address string, maxEntries int) (transactions []Transaction, err error)
GetTransactionsByAddress returns the latest transactions successfully performed by or for an address. The array will not contain more than maxEntries, but might contain less, even when more transactions happened. Any interpretation of the length of this array might result in worng assumptions.
func (*Client) GetWork ¶
GetWork returns instructions to mine the next block. This will consider pool instructions when connected to a pool. Optional arameters: (1) The address to use as a miner for this block. This overrides the address provided during startup or from the pool. and (2) Hex-encoded value for the extra data field. This overrides the address provided during startup or from the pool
func (*Client) Hashrate ¶
Hashrate returns the number of hashes per second that the node is mining with.
func (*Client) Mempool ¶
Mempool Returns information on the current mempool situation. This will provide an overview of the number of transactions sorted into buckets based on their fee per byte (in smallest unit).
func (*Client) MempoolContent ¶
MempoolContent Returns all transactions currently in the mempool. If fullTransactions is true it returns a block with the full transaction objects, if false only the hashes of the transactions will be returned.
func (*Client) MinFeePerByte ¶
MinFeePerByte returns the minimum fee per byte Optionally newFee can be given as a parameter, which sets the minimum fee per byte to the value of newFee
func (*Client) MinerAddress ¶
MinerAddress returns the user friendly miner address.
func (*Client) MinerThreads ¶
MinerThreads returns the number of CPU threads the miner is using Optionally number can be given as a parameter which sets the threads of the miner to the given number.
func (*Client) Mining ¶
Mining returns if client is actively mining new blocks. Optionally state can be given as a parameter which enables or disables mining.
func (*Client) PeerState ¶
PeerState returns the state for the given peer address. If update is set, the state of the peer will be set to the given update parameter
func (*Client) Pool ¶
Pool returns the current pool address. Optionally newAddress can be given as a parameter, which sets the address to the value of newAddress.
func (*Client) PoolConfirmedBalance ¶
PoolConfirmedBalance returns the miner balance confirmed by the pool.
func (*Client) PoolConnectionState ¶
PoolConnectionState returns the pool connection state. Possible connection states: 0 - connected, 1 - connecting, 2 - closed
func (*Client) SendRawTransaction ¶
SendRawTransaction sends a signed message call transaction or a contract creation, if the data field contains code.
func (*Client) SendTransaction ¶
func (nc *Client) SendTransaction(trn OutgoingTransaction) (transactionHash string, err error)
SendTransaction creates new message call transaction or a contract creation, if the data field contains code.
func (*Client) SubmitBlock ¶
SubmitBlock submits a block to the node. When the block is valid, the node will forward it to other nodes in the network. The argument is a hex-encoded full block (including header, interlink and body). When submitting work from getWork, remember to include the suffix.
type Luna ¶
type Luna int64
Luna is the smallest unit of NIM and 100’000 (1e5) Luna equals 1 NIM
func FormatLuna ¶
FormatLuna is a function to format NIM to Luna
type Mempool ¶
type Mempool struct { // Total number of pending transactions in mempool. Total int `json:"total,omitempty"` // Buckets is the subset of fee per byte buckets from // [10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1, 0] // that currently have more than one transaction. Buckets []int `json:"buckets,omitempty"` // any of the numbers present in buckets: Integer - Number of transaction in the bucket. // A transaction is assigned to the highest bucket of a value lower than its fee per byte value. Bucket0 int `json:"0,omitempty"` Bucket1 int `json:"1,omitempty"` Bucket2 int `json:"2,omitempty"` Bucket5 int `json:"5,omitempty"` Bucket10 int `json:"10,omitempty"` Bucket20 int `json:"20,omitempty"` Bucket50 int `json:"50,omitempty"` Bucket100 int `json:"100,omitempty"` Bucket200 int `json:"200,omitempty"` Bucket500 int `json:"500,omitempty"` Bucket1000 int `json:"1000,omitempty"` Bucket2000 int `json:"2000,omitempty"` Bucket5000 int `json:"5000,omitempty"` }
Mempool holds the details on a mempool.
type NIM ¶
type NIM string
NIM is the token transacted within Nimiq as a store and transfer of value: it acts as digital cash
type OutgoingTransaction ¶
type OutgoingTransaction struct { From string `json:"from"` // address of sending account FromType int `json:"fromType,omitempty"` // AccountType of sending address (default AccountTypeBasic) To string `json:"to"` // address of recipient account ToType int `json:"toType,omitempty"` // AccountType of recipient address (default AccountTypeBasic) Value Luna `json:"value"` Fee Luna `json:"fee"` Data string `json:"data,omitempty"` // hex-encoded contract parameters or a message }
OutgoingTransaction holds the details on a transaction that is not yet sent.
type Peer ¶
type Peer struct { ID string `json:"id,omitempty"` Address string `json:"address,omitempty"` AddressState int `json:"addressState,omitempty"` ConnectionState int `json:"connectionState,omitempty"` Version int `json:"version,omitempty"` TimeOffset int `json:"timeOffset,omitempty"` HeadHash string `json:"headHash,omitempty"` Latency int `json:"latency,omitempty"` RX int `json:"rx,omitempty"` TX int `json:"tx,omitempty"` }
Peer holds the details of a peer
type SyncStatus ¶
type SyncStatus struct { StartingBlock int `json:"startingBlock"` // block at which import started CurrentBlock int `json:"currentBlock"` HighestBlock int `json:"highestBlock"` // estimated }
SyncStatus holds information about the sync status.
type Transaction ¶
type Transaction struct { Hash string `json:"hash"` // hash of transaction BlockHash string `json:"blockHash"` // hash of containing block BlockNumber int `json:"blockNumber,omitempty"` // number of containing block Timestamp int `json:"timestamp,omitempty"` // UNIX timestamp of containing block Confirmations int `json:"confirmations"` // number of blocks since transaction was mined (0 if not mined) TransactionIndex int `json:"transactionIndex,omitempty"` // index of transaction within block From string `json:"from"` // hex-encoded address of sending account FromAddress string `json:"fromAddress"` // user friendly address of sending account To string `json:"to"` // hex-encoded address of recipient account ToAddress string `json:"toAddress,omitempty"` // user friendly address of recipient account Value Luna `json:"value"` Fee Luna `json:"fee"` Data string `json:"data"` // hex-encoded contract parameters or a message Flags int `json:"flags"` // bit-encoded transaction flags }
Transaction holds the details on a transaction
type TransactionReceipt ¶
type TransactionReceipt struct { TransactionHash string `json:"transactionHash"` // hash of transaction TransactionIndex int `json:"transactionIndex"` // transaction index within block BlockHash string `json:"blockHash"` // hash of containing block BlockNumber int `json:"blockNumber"` // number of containing block Confirmations int `json:"confirmations"` // number of blocks since transaction was mined Timestamp int `json:"timestamp,omitempty"` // timestamp of containing block }
TransactionReceipt holds the details on a transaction receipt.
type Wallet ¶
type Wallet struct { ID string `json:"id"` // hex-encoded 20 byte address Address string `json:"address"` // user friendly address (NQ-address) PublicKey string `json:"publicKey"` // hex-encoded Ed25519 public key PrivateKey string `json:"privateKey,omitempty"` // hex-encoded Ed25519 private key (optional) }
Wallet holds the details on a wallet.
type Work ¶
type Work struct { Data string `json:"data"` // hex-encoded block header Suffix string `json:"suffix"` // block without header Target int `json:"target"` // compact form of hash target Algorithm string `json:"algorithm"` // hash algorithm. always "nimiq-argon2" for now }
Work holds the instructions to mine the next block For instructions on how to use, see https://github.com/nimiq/core-js/wiki/JSON-RPC-API#getwork