nimiqrpc

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2020 License: Apache-2.0 Imports: 7 Imported by: 0

README

go-nimiq-rpc

Report card GoDoc

A Nimiq RPC client library in Go. This client library implements the Nimiq RPC specification. This client uses the jsonrpc library to handle JSON-RPC 2.0 requests and responses. For more information about this library see the jsonrpc documentation

What is Nimiq?

A blockchain technology inspired by Bitcoin but designed to run in your browser. It is money by nature but capable to do much more. See the Nimiq website for more information.

How to use this library?

This library is fully Go module compatible. See the full documentation on GoDoc

Contributing

Questions or issues can be filled in the issue tracker.

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

View Source
const (
	AccountTypeBasic   = 0
	AccountTypeVesting = 1
	AccountTypeHTLC    = 2
)

Account types on the blockchain

Variables

View Source
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 is returned when the user is not authorized to call the function
	ErrUnauthorized = errors.New("unauthorized")

	// ErrNotAuthenticated is returned when the user is required to be authenticated
	ErrNotAuthenticated = errors.New("not authenticated")
)

Functions

func NewRequest added in v1.1.0

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

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

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 NewClient

func NewClient(address string) *Client

NewClient returns a new Nimiq RPC client

func NewClientWithAuth added in v1.1.0

func NewClientWithAuth(address, username, password string) *Client

NewClientWithAuth returns a RPC client with the given username and password set for authentication

func (*Client) Accounts

func (nc *Client) Accounts() (accounts []Account, err error)

Accounts returns a list of addresses owned by client.

func (*Client) BlockNumber

func (nc *Client) BlockNumber() (blockHeight int, err error)

BlockNumber returns the height of most recent block.

func (*Client) Call added in v1.1.0

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

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 documenation on how to handle jsonrpc.RPCResonses: https://godoc.org/github.com/ybbus/jsonrpc#RPCResponses

func (*Client) Consensus

func (nc *Client) Consensus() (consensus string, err error)

Consensus returns information on the current consensus state.

func (*Client) CreateAccount

func (nc *Client) CreateAccount() (wallet *Wallet, err error)

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

func (nc *Client) GetAccount(address string) (account *Account, err error)

GetAccount returns details for the account of given address.

func (*Client) GetBalance

func (nc *Client) GetBalance(address string) (balance Luna, err error)

GetBalance returns the balance of the account of given address.

func (*Client) GetBlockByHash

func (nc *Client) GetBlockByHash(blockHash string, fullTransactions bool) (block *Block, err error)

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

func (nc *Client) GetWork(params ...interface{}) (work *Work, err error)

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

func (nc *Client) Hashrate() (hashrate float64, err error)

Hashrate returns the number of hashes per second that the node is mining with.

func (*Client) Log

func (nc *Client) Log(tag string, level LogLevel) (succes bool, err error)

Log sets the log level of the node.

func (*Client) Mempool

func (nc *Client) Mempool() (mempool *Mempool, err error)

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) Mining

func (nc *Client) Mining() (status bool, err error)

Mining returns if client is actively mining new blocks.

func (*Client) PeerCount

func (nc *Client) PeerCount() (peers int, err error)

PeerCount returns number of peers currently connected to the client.

func (*Client) PeerList added in v1.1.0

func (nc *Client) PeerList() (peers []Peer, err error)

PeerList returns a list of peers currently connected to the client

func (*Client) PeerState added in v1.1.0

func (nc *Client) PeerState(peerAddress string, update ...string) (peer *Peer, err error)

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) SendRawTransaction

func (nc *Client) SendRawTransaction(signedTransaction string) (transactionHash string, err error)

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

func (nc *Client) SubmitBlock(fullBlock string) (err error)

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.

func (*Client) Syncing

func (nc *Client) Syncing() (syncing bool, syncStatus *SyncStatus, err error)

Syncing returns whether the node is syncing and when it is syncing, data about the sync status.

type LogLevel

type LogLevel string

LogLevel is the level of logging that is enabled on a node

const (
	LogLevelTrace   LogLevel = "trace"
	LogLevelVerbose LogLevel = "verbose"
	LogLevelDebug   LogLevel = "debug"
	LogLevelInfo    LogLevel = "info"
	LogLevelWarn    LogLevel = "warn"
	LogLevelError   LogLevel = "error"
	LogLevelAssert  LogLevel = "assert"
)

Available LogLevels

type Luna

type Luna int64

Luna is the smallest unit of NIM and 100’000 (1e5) Luna equals 1 NIM

func FormatLuna added in v1.1.0

func FormatLuna(n NIM) (Luna, error)

FormatLuna is a function to format NIM to Luna

func (*Luna) ToNIM

func (l *Luna) ToNIM() NIM

ToNIM converts Luna to NIM

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

func FormatNIM added in v1.1.0

func FormatNIM(l Luna) NIM

FormatNIM is a function to format Luna to NIM

func (*NIM) ToLuna

func (n *NIM) ToLuna() (Luna, error)

ToLuna converts NIM to Luna

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

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

Jump to

Keyboard shortcuts

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