model

package
v0.6.4-rc3 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2020 License: ISC Imports: 12 Imported by: 0

README

rpcmodel

ISC License GoDoc

Package rpcmodel implements concrete types for marshalling to and from the kaspa JSON-RPC API. A comprehensive suite of tests is provided to ensure proper functionality.

Note that although it's possible to use this package directly to implement an RPC client, it is not recommended since it is only intended as an infrastructure package. Instead, RPC clients should use the rpcclient package which provides a full blown RPC client with many features such as automatic connection management, websocket support, automatic notification re-registration on reconnect, and conversion from the raw underlying RPC types (strings, floats, ints, etc) to higher-level types with many nice and useful properties.

Examples

  • Marshal Command Demonstrates how to create and marshal a command into a JSON-RPC request.

  • Unmarshal Command Demonstrates how to unmarshal a JSON-RPC request and then unmarshal the concrete request into a concrete command.

  • Marshal Response Demonstrates how to marshal a JSON-RPC response.

  • Unmarshal Response Demonstrates how to unmarshal a JSON-RPC response and then unmarshal the result field in the response to a concrete type.

Documentation

Overview

Package model provides primitives for working with the kaspa JSON-RPC API.

Overview

When communicating via the JSON-RPC protocol, all of the commands need to be marshalled to and from the the appmessage in the appropriate format. This package provides data structures and primitives to ease this process.

In addition, it also provides some additional features such as custom command registration, command categorization, and reflection-based help generation.

JSON-RPC Protocol Overview

This information is not necessary in order to use this package, but it does provide some intuition into what the marshalling and unmarshalling that is discussed below is doing under the hood.

As defined by the JSON-RPC spec, there are effectively two forms of messages on the appmessage:

  • Request Objects {"jsonrpc":"1.0","id":"SOMEID","method":"SOMEMETHOD","params":[SOMEPARAMS]} NOTE: Notifications are the same format except the id field is null.

  • Response Objects {"result":SOMETHING,"error":null,"id":"SOMEID"} {"result":null,"error":{"code":SOMEINT,"message":SOMESTRING},"id":"SOMEID"}

For requests, the params field can vary in what it contains depending on the method (a.k.a. command) being sent. Each parameter can be as simple as an int or a complex structure containing many nested fields. The id field is used to identify a request and will be included in the associated response.

When working with asynchronous transports, such as websockets, spontaneous notifications are also possible. As indicated, they are the same as a request object, except they have the id field set to null. Therefore, servers will ignore requests with the id field set to null, while clients can choose to consume or ignore them.

Marshalling and Unmarshalling

Based upon the discussion above, it should be easy to see how the types of this package map into the required parts of the protocol

  • Request Objects (type Request)
  • Commands (type <Foo>Cmd)
  • Notifications (type <Foo>Ntfn)
  • Response Objects (type Response)
  • Result (type <Foo>Result)

To simplify the marshalling of the requests and responses, the MarshalCommand and MarshalResponse functions are provided. They return the raw bytes ready to be sent across the appmessage.

Unmarshalling a received Request object is a two step process:

  1. Unmarshal the raw bytes into a Request struct instance via json.Unmarshal
  2. Use UnmarshalCommand on the Result field of the unmarshalled Request to create a concrete command or notification instance with all struct fields set accordingly

This approach is used since it provides the caller with access to the additional fields in the request that are not part of the command such as the ID.

Unmarshalling a received Response object is also a two step process:

  1. Unmarhsal the raw bytes into a Response struct instance via json.Unmarshal
  2. Depending on the ID, unmarshal the Result field of the unmarshalled Response to create a concrete type instance

As above, this approach is used since it provides the caller with access to the fields in the response such as the ID and Error.

Command Creation

This package provides two approaches for creating a new command. This first, and preferred, method is to use one of the New<Foo>Cmd functions. This allows static compile-time checking to help ensure the parameters stay in sync with the struct definitions.

The second approach is the NewCommand function which takes a method (command) name and variable arguments. The function includes full checking to ensure the parameters are accurate according to provided method, however these checks are, obviously, run-time which means any mistakes won't be found until the code is actually executed. However, it is quite useful for user-supplied commands that are intentionally dynamic.

Custom Command Registration

The command handling of this package is built around the concept of registered commands. This is true for the wide variety of commands already provided by the package, but it also means caller can easily provide custom commands with all of the same functionality as the built-in commands. Use the RegisterCmd function for this purpose.

A list of all registered methods can be obtained with the RegisteredCmdMethods function.

Command Inspection

All registered commands are registered with flags that identify information such as whether the command applies to a kaspa rpc server or is a notification along with the method name to use. These flags can be obtained with the MethodUsageFlags flags, and the method can be obtained with the CommandMethod function.

Help Generation

To facilitate providing consistent help to users of the RPC server, this package exposes the GenerateHelp and function which uses reflection on registered commands or notifications, as well as the provided expected result types, to generate the final help text.

In addition, the MethodUsageText function is provided to generate consistent one-line usage for registered commands and notifications using reflection.

Errors

There are 2 distinct type of errors supported by this package:

  • General errors related to marshalling or unmarshalling or improper use of the package (type Error)
  • RPC errors which are intended to be returned across the appmessage as a part of the JSON-RPC response (type RPCError)

The first category of errors (type Error) typically indicates a programmer error and can be avoided by properly using the API. Errors of this type will be returned from the various functions available in this package. They identify issues such as unsupported field types, attempts to register malformed commands, and attempting to create a new command with an improper number of parameters. The specific reason for the error can be detected by type asserting it to a *model.Error and accessing the ErrorCode field.

The second category of errors (type RPCError), on the other hand, are useful for returning errors to RPC clients. Consequently, they are used in the previously described Response type.

Example (UnmarshalResponse)

This example demonstrates how to unmarshal a JSON-RPC response and then unmarshal the result field in the response to a concrete type.

package main

import (
	"encoding/json"
	"fmt"

	"github.com/kaspanet/kaspad/infrastructure/network/rpc/model"
)

func main() {
	// Ordinarily this would be read from the appmessage, but for this example,
	// it is hard coded here for clarity. This is an example response to a
	// getblockheight request.
	data := []byte(`{"result":350001,"error":null,"id":1}`)

	// Unmarshal the raw bytes from the appmessage into a JSON-RPC response.
	var response model.Response
	if err := json.Unmarshal(data, &response); err != nil {
		fmt.Println("Malformed JSON-RPC response:", err)
		return
	}

	// Check the response for an error from the server. For example, the
	// server might return an error if an invalid/unknown block hash is
	// requested.
	if response.Error != nil {
		fmt.Println(response.Error)
		return
	}

	// Unmarshal the result into the expected type for the response.
	var blockHeight int32
	if err := json.Unmarshal(response.Result, &blockHeight); err != nil {
		fmt.Printf("Unexpected result type: %T\n", response.Result)
		return
	}
	fmt.Println("Block height:", blockHeight)

}
Output:

Block height: 350001

Index

Examples

Constants

View Source
const (
	// FilteredBlockAddedNtfnMethod is the new method used for
	// notifications from the kaspa rpc server that a block has been connected.
	FilteredBlockAddedNtfnMethod = "filteredBlockAdded"

	// TxAcceptedNtfnMethod is the method used for notifications from the
	// kaspa rpc server that a transaction has been accepted into the mempool.
	TxAcceptedNtfnMethod = "txAccepted"

	// TxAcceptedVerboseNtfnMethod is the method used for notifications from
	// the kaspa rpc server that a transaction has been accepted into the
	// mempool. This differs from TxAcceptedNtfnMethod in that it provides
	// more details in the notification.
	TxAcceptedVerboseNtfnMethod = "txAcceptedVerbose"

	// RelevantTxAcceptedNtfnMethod is the new method used for notifications
	// from the kaspa rpc server that inform a client that a transaction that
	// matches the loaded filter was accepted by the mempool.
	RelevantTxAcceptedNtfnMethod = "relevantTxAccepted"

	// ChainChangedNtfnMethod is the new method used for notifications
	// from the kaspa rpc server that inform a client that the selected chain
	// has changed.
	ChainChangedNtfnMethod = "chainChanged"
)

Variables

View Source
var (
	ErrRPCInvalidRequest = &RPCError{
		Code:    -32600,
		Message: "Invalid request",
	}
	ErrRPCMethodNotFound = &RPCError{
		Code:    -32601,
		Message: "Method not found",
	}
	ErrRPCInvalidParams = &RPCError{
		Code:    -32602,
		Message: "Invalid parameters",
	}
	ErrRPCInternal = &RPCError{
		Code:    -32603,
		Message: "Internal error",
	}
	ErrRPCParse = &RPCError{
		Code:    -32700,
		Message: "Parse error",
	}
)

Standard JSON-RPC 2.0 errors.

Functions

func CommandMethod

func CommandMethod(cmd interface{}) (string, error)

CommandMethod returns the method for the passed command. The provided command type must be a registered type. All commands provided by this package are registered by default.

func GenerateHelp

func GenerateHelp(method string, descs map[string]string, resultTypes ...interface{}) (string, error)

GenerateHelp generates and returns help output for the provided method and result types given a map to provide the appropriate keys for the method synopsis, field descriptions, conditions, and result descriptions. The method must be associated with a registered type. All commands provided by this package are registered by default.

The resultTypes must be pointer-to-types which represent the specific types of values the command returns. For example, if the command only returns a boolean value, there should only be a single entry of (*bool)(nil). Note that each type must be a single pointer to the type. Therefore, it is recommended to simply pass a nil pointer cast to the appropriate type as previously shown.

The provided descriptions map must contain all of the keys or an error will be returned which includes the missing key, or the final missing key when there is more than one key missing. The generated help in the case of such an error will use the key in place of the description.

The following outlines the required keys:

"<method>--synopsis"             Synopsis for the command
"<method>-<lowerfieldname>"      Description for each command argument
"<typename>-<lowerfieldname>"    Description for each object field
"<method>--condition<#>"         Description for each result condition
"<method>--result<#>"            Description for each primitive result num

Notice that the "special" keys synopsis, condition<#>, and result<#> are preceded by a double dash to ensure they don't conflict with field names.

The condition keys are only required when there is more than on result type, and the result key for a given result type is only required if it's not an object.

For example, consider the 'help' command itself. There are two possible returns depending on the provided parameters. So, the help would be generated by calling the function as follows:

GenerateHelp("help", descs, (*string)(nil), (*string)(nil)).

The following keys would then be required in the provided descriptions map:

"help--synopsis":   "Returns a list of all commands or help for ...."
"help-command":     "The command to retrieve help for",
"help--condition0": "no command provided"
"help--condition1": "command specified"
"help--result0":    "List of commands"
"help--result1":    "Help for specified command"

func IsValidIDType

func IsValidIDType(id interface{}) bool

IsValidIDType checks that the ID field (which can go in any of the JSON-RPC requests, responses, or notifications) is valid. JSON-RPC 1.0 allows any valid JSON type. JSON-RPC 2.0 (which kaspad follows for some parts) only allows string, number, or null, so this function restricts the allowed types to that list. This function is only provided in case the caller is manually marshalling for some reason. The functions which accept an ID in this package already call this function to ensure the provided id is valid.

func MarshalCommand

func MarshalCommand(id interface{}, cmd interface{}) ([]byte, error)

MarshalCommand marshals the passed command to a JSON-RPC request byte slice that is suitable for transmission to an RPC server. The provided command type must be a registered type. All commands provided by this package are registered by default.

Example

This example demonstrates how to create and marshal a command into a JSON-RPC request.

package main

import (
	"fmt"
	"github.com/kaspanet/kaspad/util/pointers"

	"github.com/kaspanet/kaspad/infrastructure/network/rpc/model"
)

func main() {
	// Create a new getblock command. Notice the nil parameter indicates
	// to use the default parameter for that fields. This is a common
	// pattern used in all of the New<Foo>Cmd functions in this package for
	// optional fields. Also, notice the call to pointers.Bool which is a
	// convenience function for creating a pointer out of a primitive for
	// optional parameters.
	blockHash := "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"
	gbCmd := model.NewGetBlockCmd(blockHash, pointers.Bool(false), nil, nil)

	// Marshal the command to the format suitable for sending to the RPC
	// server. Typically the client would increment the id here which is
	// request so the response can be identified.
	id := 1
	marshalledBytes, err := model.MarshalCommand(id, gbCmd)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Display the marshalled command. Ordinarily this would be sent across
	// the appmessage to the RPC server, but for this example, just display it.
	fmt.Printf("%s\n", marshalledBytes)

}
Output:

{"jsonrpc":"1.0","method":"getBlock","params":["000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",false],"id":1}

func MarshalResponse

func MarshalResponse(id interface{}, result interface{}, rpcErr *RPCError) ([]byte, error)

MarshalResponse marshals the passed id, result, and RPCError to a JSON-RPC response byte slice that is suitable for transmission to a JSON-RPC client.

Example

This example demonstrates how to marshal a JSON-RPC response.

package main

import (
	"fmt"

	"github.com/kaspanet/kaspad/infrastructure/network/rpc/model"
)

func main() {
	// Marshal a new JSON-RPC response. For example, this is a response
	// to a getblockheight request.
	marshalledBytes, err := model.MarshalResponse(1, 350001, nil)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Display the marshalled response. Ordinarily this would be sent
	// across the appmessage to the RPC client, but for this example, just display
	// it.
	fmt.Printf("%s\n", marshalledBytes)

}
Output:

{"result":350001,"error":null,"id":1}

func MethodUsageText

func MethodUsageText(method string) (string, error)

MethodUsageText returns a one-line usage string for the provided method. The provided method must be associated with a registered type. All commands provided by this package are registered by default.

func MustRegisterCommand

func MustRegisterCommand(method string, cmd interface{}, flags UsageFlag)

MustRegisterCommand performs the same function as RegisterCmd except it panics if there is an error. This should only be called from package init functions.

func NewCommand

func NewCommand(method string, args ...interface{}) (interface{}, error)

NewCommand provides a generic mechanism to create a new command that can marshal to a JSON-RPC request while respecting the requirements of the provided method. The method must have been registered with the package already along with its type definition. All methods associated with the commands exported by this package are already registered by default.

The arguments are most efficient when they are the exact same type as the underlying field in the command struct associated with the the method, however this function also will perform a variety of conversions to make it more flexible. This allows, for example, command line args which are strings to be passed unaltered. In particular, the following conversions are supported:

  • Conversion between any size signed or unsigned integer so long as the value does not overflow the destination type
  • Conversion between float32 and float64 so long as the value does not overflow the destination type
  • Conversion from string to boolean for everything strconv.ParseBool recognizes
  • Conversion from string to any size integer for everything strconv.ParseInt and strconv.ParseUint recognizes
  • Conversion from string to any size float for everything strconv.ParseFloat recognizes
  • Conversion from string to arrays, slices, structs, and maps by treating the string as marshalled JSON and calling json.Unmarshal into the destination field

func RegisterCmd

func RegisterCmd(method string, cmd interface{}, flags UsageFlag) error

RegisterCmd registers a new command that will automatically marshal to and from JSON-RPC with full type checking and positional parameter support. It also accepts usage flags which identify the circumstances under which the command can be used.

This package automatically registers all of the exported commands by default using this function, however it is also exported so callers can easily register custom types.

The type format is very strict since it needs to be able to automatically marshal to and from JSON-RPC 1.0. The following enumerates the requirements:

  • The provided command must be a single pointer to a struct
  • All fields must be exported
  • The order of the positional parameters in the marshalled JSON will be in the same order as declared in the struct definition
  • Struct embedding is not supported
  • Struct fields may NOT be channels, functions, complex, or interface
  • A field in the provided struct with a pointer is treated as optional
  • Multiple indirections (i.e **int) are not supported
  • Once the first optional field (pointer) is encountered, the remaining fields must also be optional fields (pointers) as required by positional params
  • A field that has a 'jsonrpcdefault' struct tag must be an optional field (pointer)

NOTE: This function only needs to be able to examine the structure of the passed struct, so it does not need to be an actual instance. Therefore, it is recommended to simply pass a nil pointer cast to the appropriate type. For example, (*FooCmd)(nil).

func RegisteredCmdMethods

func RegisteredCmdMethods() []string

RegisteredCmdMethods returns a sorted list of methods for all registered commands.

func UnmarshalCommand

func UnmarshalCommand(r *Request) (interface{}, error)

UnmarshalCommand unmarshals a JSON-RPC request into a suitable concrete command so long as the method type contained within the marshalled request is registered.

Example

This example demonstrates how to unmarshal a JSON-RPC request and then unmarshal the concrete request into a concrete command.

package main

import (
	"encoding/json"
	"fmt"

	"github.com/kaspanet/kaspad/infrastructure/network/rpc/model"
)

func main() {
	// Ordinarily this would be read from the appmessage, but for this example,
	// it is hard coded here for clarity.
	data := []byte(`{"jsonrpc":"1.0","method":"getBlock","params":["000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",false],"id":1}`)

	// Unmarshal the raw bytes from the appmessage into a JSON-RPC request.
	var request model.Request
	if err := json.Unmarshal(data, &request); err != nil {
		fmt.Println(err)
		return
	}

	// Typically there isn't any need to examine the request fields directly
	// like this as the caller already knows what response to expect based
	// on the command it sent. However, this is done here to demonstrate
	// why the unmarshal process is two steps.
	if request.ID == nil {
		fmt.Println("Unexpected notification")
		return
	}
	if request.Method != "getBlock" {
		fmt.Println("Unexpected method")
		return
	}

	// Unmarshal the request into a concrete command.
	cmd, err := model.UnmarshalCommand(&request)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Type assert the command to the appropriate type.
	gbCmd, ok := cmd.(*model.GetBlockCmd)
	if !ok {
		fmt.Printf("Incorrect command type: %T\n", cmd)
		return
	}

	// Display the fields in the concrete command.
	fmt.Println("Hash:", gbCmd.Hash)
	fmt.Println("Verbose:", *gbCmd.Verbose)
	fmt.Println("VerboseTx:", *gbCmd.VerboseTx)
	if gbCmd.Subnetwork != nil {
		fmt.Println("Subnetwork:", *gbCmd.Subnetwork)
	}

}
Output:

Hash: 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
Verbose: false
VerboseTx: false

Types

type AcceptedBlock

type AcceptedBlock struct {
	Hash          string   `json:"hash"`
	AcceptedTxIDs []string `json:"acceptedTxIds"`
}

AcceptedBlock models a block that is included in the blues of a selected chain block.

type AuthenticateCmd

type AuthenticateCmd struct {
	Username   string
	Passphrase string
}

AuthenticateCmd defines the authenticate JSON-RPC command.

func NewAuthenticateCmd

func NewAuthenticateCmd(username, passphrase string) *AuthenticateCmd

NewAuthenticateCmd returns a new instance which can be used to issue an authenticate JSON-RPC command.

type Bip9SoftForkDescription

type Bip9SoftForkDescription struct {
	Status    string `json:"status"`
	Bit       uint8  `json:"bit"`
	StartTime int64  `json:"startTime"`
	Timeout   int64  `json:"timeout"`
	Since     int32  `json:"since"`
}

Bip9SoftForkDescription describes the current state of a defined BIP0009 version bits soft-fork.

type BlockDetails

type BlockDetails struct {
	Height uint64 `json:"height"`
	Hash   string `json:"hash"`
	Index  int    `json:"index"`
	Time   int64  `json:"time"`
}

BlockDetails describes details of a tx in a block.

type ChainBlock

type ChainBlock struct {
	Hash           string          `json:"hash"`
	AcceptedBlocks []AcceptedBlock `json:"acceptedBlocks"`
}

ChainBlock models a block that is part of the selected parent chain.

type ChainChangedNtfn

type ChainChangedNtfn struct {
	ChainChangedRawParam ChainChangedRawParam
}

ChainChangedNtfn defines the chainChanged JSON-RPC notification.

func NewChainChangedNtfn

func NewChainChangedNtfn(removedChainBlockHashes []string,
	addedChainBlocks []ChainBlock) *ChainChangedNtfn

NewChainChangedNtfn returns a new instance which can be used to issue a chainChanged JSON-RPC notification.

type ChainChangedRawParam

type ChainChangedRawParam struct {
	RemovedChainBlockHashes []string     `json:"removedChainBlockHashes"`
	AddedChainBlocks        []ChainBlock `json:"addedChainBlocks"`
}

ChainChangedRawParam is the first parameter of ChainChangedNtfn which contains all the remove chain block hashes and the added chain blocks.

type ConnectCmd

type ConnectCmd struct {
	Address     string
	IsPermanent *bool `jsonrpcdefault:"false"`
}

ConnectCmd defines the connect JSON-RPC command.

func NewConnectCmd

func NewConnectCmd(address string, isPermanent *bool) *ConnectCmd

NewConnectCmd returns a new instance which can be used to issue a connection JSON-RPC command.

type CreateMultiSigResult

type CreateMultiSigResult struct {
	Address      string `json:"address"`
	RedeemScript string `json:"redeemScript"`
}

CreateMultiSigResult models the data returned from the createmultisig command.

type DebugLevelCmd

type DebugLevelCmd struct {
	LevelSpec string
}

DebugLevelCmd defines the debugLevel JSON-RPC command.

func NewDebugLevelCmd

func NewDebugLevelCmd(levelSpec string) *DebugLevelCmd

NewDebugLevelCmd returns a new DebugLevelCmd which can be used to issue a debugLevel JSON-RPC command.

type DecodeScriptResult

type DecodeScriptResult struct {
	Asm     string  `json:"asm"`
	Type    string  `json:"type"`
	Address *string `json:"address,omitempty"`
	P2sh    string  `json:"p2sh,omitempty"`
}

DecodeScriptResult models the data returned from the decodescript command.

type DisconnectCmd

type DisconnectCmd struct {
	Address string
}

DisconnectCmd defines the disconnect JSON-RPC command.

func NewDisconnectCmd

func NewDisconnectCmd(address string) *DisconnectCmd

NewDisconnectCmd returns a new instance which can be used to issue an disconnect JSON-RPC command.

type Error

type Error struct {
	ErrorCode   ErrorCode // Describes the kind of error
	Description string    // Human readable description of the issue
}

Error identifies a general error. This differs from an RPCError in that this error typically is used more by the consumers of the package as opposed to RPCErrors which are intended to be returned to the client across the appmessage via a JSON-RPC Response. The caller can use type assertions to determine the specific error and access the ErrorCode field.

func (Error) Error

func (e Error) Error() string

Error satisfies the error interface and prints human-readable errors.

type ErrorCode

type ErrorCode int

ErrorCode identifies a kind of error. These error codes are NOT used for JSON-RPC response errors.

const (
	// ErrDuplicateMethod indicates a command with the specified method
	// already exists.
	ErrDuplicateMethod ErrorCode = iota

	// ErrInvalidUsageFlags indicates one or more unrecognized flag bits
	// were specified.
	ErrInvalidUsageFlags

	// ErrInvalidType indicates a type was passed that is not the required
	// type.
	ErrInvalidType

	// ErrEmbeddedType indicates the provided command struct contains an
	// embedded type which is not not supported.
	ErrEmbeddedType

	// ErrUnexportedField indiciates the provided command struct contains an
	// unexported field which is not supported.
	ErrUnexportedField

	// ErrUnsupportedFieldType indicates the type of a field in the provided
	// command struct is not one of the supported types.
	ErrUnsupportedFieldType

	// ErrNonOptionalField indicates a non-optional field was specified
	// after an optional field.
	ErrNonOptionalField

	// ErrNonOptionalDefault indicates a 'jsonrpcdefault' struct tag was
	// specified for a non-optional field.
	ErrNonOptionalDefault

	// ErrMismatchedDefault indicates a 'jsonrpcdefault' struct tag contains
	// a value that doesn't match the type of the field.
	ErrMismatchedDefault

	// ErrUnregisteredMethod indicates a method was specified that has not
	// been registered.
	ErrUnregisteredMethod

	// ErrMissingDescription indicates a description required to generate
	// help is missing.
	ErrMissingDescription

	// ErrNumParams inidcates the number of params supplied do not
	// match the requirements of the associated command.
	ErrNumParams
)

These constants are used to identify a specific RuleError.

func (ErrorCode) String

func (e ErrorCode) String() string

String returns the ErrorCode as a human-readable name.

type FilteredBlockAddedNtfn

type FilteredBlockAddedNtfn struct {
	BlueScore     uint64
	Header        string
	SubscribedTxs []string
}

FilteredBlockAddedNtfn defines the filteredBlockAdded JSON-RPC notification.

func NewFilteredBlockAddedNtfn

func NewFilteredBlockAddedNtfn(blueScore uint64, header string, subscribedTxs []string) *FilteredBlockAddedNtfn

NewFilteredBlockAddedNtfn returns a new instance which can be used to issue a filteredBlockAdded JSON-RPC notification.

type GetBlockCmd

type GetBlockCmd struct {
	Hash       string
	Verbose    *bool `jsonrpcdefault:"true"`
	VerboseTx  *bool `jsonrpcdefault:"false"`
	Subnetwork *string
}

GetBlockCmd defines the getBlock JSON-RPC command.

func NewGetBlockCmd

func NewGetBlockCmd(hash string, verbose, verboseTx *bool, subnetworkID *string) *GetBlockCmd

NewGetBlockCmd returns a new instance which can be used to issue a getBlock JSON-RPC command.

The parameters which are pointers indicate they are optional. Passing nil for optional parameters will use the default value.

type GetBlockCountCmd

type GetBlockCountCmd struct{}

GetBlockCountCmd defines the getBlockCount JSON-RPC command.

func NewGetBlockCountCmd

func NewGetBlockCountCmd() *GetBlockCountCmd

NewGetBlockCountCmd returns a new instance which can be used to issue a getBlockCount JSON-RPC command.

type GetBlockDAGInfoCmd

type GetBlockDAGInfoCmd struct{}

GetBlockDAGInfoCmd defines the getBlockDagInfo JSON-RPC command.

func NewGetBlockDAGInfoCmd

func NewGetBlockDAGInfoCmd() *GetBlockDAGInfoCmd

NewGetBlockDAGInfoCmd returns a new instance which can be used to issue a getBlockDagInfo JSON-RPC command.

type GetBlockDAGInfoResult

type GetBlockDAGInfoResult struct {
	DAG                  string                              `json:"dag"`
	Blocks               uint64                              `json:"blocks"`
	Headers              uint64                              `json:"headers"`
	TipHashes            []string                            `json:"tipHashes"`
	Difficulty           float64                             `json:"difficulty"`
	MedianTime           int64                               `json:"medianTime"`
	VerificationProgress float64                             `json:"verificationProgress,omitempty"`
	Pruned               bool                                `json:"pruned"`
	PruneHeight          uint64                              `json:"pruneHeight,omitempty"`
	DAGWork              string                              `json:"dagWork,omitempty"`
	SoftForks            []*SoftForkDescription              `json:"softForks"`
	Bip9SoftForks        map[string]*Bip9SoftForkDescription `json:"bip9SoftForks"`
}

GetBlockDAGInfoResult models the data returned from the getblockdaginfo command.

type GetBlockHeaderCmd

type GetBlockHeaderCmd struct {
	Hash    string
	Verbose *bool `jsonrpcdefault:"true"`
}

GetBlockHeaderCmd defines the getBlockHeader JSON-RPC command.

func NewGetBlockHeaderCmd

func NewGetBlockHeaderCmd(hash string, verbose *bool) *GetBlockHeaderCmd

NewGetBlockHeaderCmd returns a new instance which can be used to issue a getBlockHeader JSON-RPC command.

type GetBlockHeaderVerboseResult

type GetBlockHeaderVerboseResult struct {
	Hash                 string   `json:"hash"`
	Confirmations        uint64   `json:"confirmations"`
	Version              int32    `json:"version"`
	VersionHex           string   `json:"versionHex"`
	HashMerkleRoot       string   `json:"hashMerkleRoot"`
	AcceptedIDMerkleRoot string   `json:"acceptedIdMerkleRoot"`
	Time                 int64    `json:"time"`
	Nonce                uint64   `json:"nonce"`
	Bits                 string   `json:"bits"`
	Difficulty           float64  `json:"difficulty"`
	ParentHashes         []string `json:"parentHashes,omitempty"`
	SelectedParentHash   string   `json:"selectedParentHash"`
	ChildHashes          []string `json:"childHashes,omitempty"`
}

GetBlockHeaderVerboseResult models the data from the getblockheader command when the verbose flag is set. When the verbose flag is not set, getblockheader returns a hex-encoded string.

type GetBlockTemplateCmd

type GetBlockTemplateCmd struct {
	Request *TemplateRequest
}

GetBlockTemplateCmd defines the getBlockTemplate JSON-RPC command.

func NewGetBlockTemplateCmd

func NewGetBlockTemplateCmd(request *TemplateRequest) *GetBlockTemplateCmd

NewGetBlockTemplateCmd returns a new instance which can be used to issue a getBlockTemplate JSON-RPC command.

The parameters which are pointers indicate they are optional. Passing nil for optional parameters will use the default value.

type GetBlockTemplateResult

type GetBlockTemplateResult struct {
	// Base fields from BIP 0022. CoinbaseAux is optional. One of
	// CoinbaseTxn or CoinbaseValue must be specified, but not both.
	Bits                 string                     `json:"bits"`
	CurTime              int64                      `json:"curTime"`
	Height               uint64                     `json:"height"`
	ParentHashes         []string                   `json:"parentHashes"`
	MassLimit            int64                      `json:"massLimit,omitempty"`
	Transactions         []GetBlockTemplateResultTx `json:"transactions"`
	HashMerkleRoot       string                     `json:"hashMerkleRoot"`
	AcceptedIDMerkleRoot string                     `json:"acceptedIdMerkleRoot"`
	UTXOCommitment       string                     `json:"utxoCommitment"`
	Version              int32                      `json:"version"`
	WorkID               string                     `json:"workId,omitempty"`
	IsSynced             bool                       `json:"isSynced"`

	// Optional long polling from BIP 0022.
	LongPollID  string `json:"longPollId,omitempty"`
	LongPollURI string `json:"longPollUri,omitempty"`

	// Basic pool extension from BIP 0023.
	Target  string `json:"target,omitempty"`
	Expires int64  `json:"expires,omitempty"`

	// Mutations from BIP 0023.
	MaxTime    int64    `json:"maxTime,omitempty"`
	MinTime    int64    `json:"minTime,omitempty"`
	Mutable    []string `json:"mutable,omitempty"`
	NonceRange string   `json:"nonceRange,omitempty"`

	// Block proposal from BIP 0023.
	Capabilities []string `json:"capabilities,omitempty"`
	RejectReason string   `json:"rejectReason,omitempty"`
}

GetBlockTemplateResult models the data returned from the getblocktemplate command.

type GetBlockTemplateResultTx

type GetBlockTemplateResultTx struct {
	Data    string  `json:"data"`
	ID      string  `json:"id"`
	Depends []int64 `json:"depends"`
	Mass    uint64  `json:"mass"`
	Fee     uint64  `json:"fee"`
}

GetBlockTemplateResultTx models the transactions field of the getblocktemplate command.

type GetBlockVerboseResult

type GetBlockVerboseResult struct {
	Hash                 string        `json:"hash"`
	Confirmations        uint64        `json:"confirmations"`
	Size                 int32         `json:"size"`
	BlueScore            uint64        `json:"blueScore"`
	IsChainBlock         bool          `json:"isChainBlock"`
	Version              int32         `json:"version"`
	VersionHex           string        `json:"versionHex"`
	HashMerkleRoot       string        `json:"hashMerkleRoot"`
	AcceptedIDMerkleRoot string        `json:"acceptedIdMerkleRoot"`
	UTXOCommitment       string        `json:"utxoCommitment"`
	Tx                   []string      `json:"tx,omitempty"`
	RawTx                []TxRawResult `json:"rawRx,omitempty"`
	Time                 int64         `json:"time"`
	Nonce                uint64        `json:"nonce"`
	Bits                 string        `json:"bits"`
	Difficulty           float64       `json:"difficulty"`
	ParentHashes         []string      `json:"parentHashes"`
	SelectedParentHash   string        `json:"selectedParentHash"`
	ChildHashes          []string      `json:"childHashes"`
	AcceptedBlockHashes  []string      `json:"acceptedBlockHashes"`
}

GetBlockVerboseResult models the data from the getblock command when the verbose flag is set. When the verbose flag is not set, getblock returns a hex-encoded string.

type GetBlocksCmd

type GetBlocksCmd struct {
	IncludeRawBlockData     bool    `json:"includeRawBlockData"`
	IncludeVerboseBlockData bool    `json:"includeVerboseBlockData"`
	LowHash                 *string `json:"lowHash"`
}

GetBlocksCmd defines the getBlocks JSON-RPC command.

func NewGetBlocksCmd

func NewGetBlocksCmd(includeRawBlockData bool, includeVerboseBlockData bool, lowHash *string) *GetBlocksCmd

NewGetBlocksCmd returns a new instance which can be used to issue a GetGetBlocks JSON-RPC command.

type GetBlocksResult

type GetBlocksResult struct {
	Hashes        []string                `json:"hashes"`
	RawBlocks     []string                `json:"rawBlocks"`
	VerboseBlocks []GetBlockVerboseResult `json:"verboseBlocks"`
}

GetBlocksResult models the data from the getBlocks command.

type GetChainFromBlockCmd

type GetChainFromBlockCmd struct {
	IncludeBlocks bool    `json:"includeBlocks"`
	StartHash     *string `json:"startHash"`
}

GetChainFromBlockCmd defines the getChainFromBlock JSON-RPC command.

func NewGetChainFromBlockCmd

func NewGetChainFromBlockCmd(includeBlocks bool, startHash *string) *GetChainFromBlockCmd

NewGetChainFromBlockCmd returns a new instance which can be used to issue a GetChainFromBlock JSON-RPC command.

type GetChainFromBlockResult

type GetChainFromBlockResult struct {
	RemovedChainBlockHashes []string                `json:"removedChainBlockHashes"`
	AddedChainBlocks        []ChainBlock            `json:"addedChainBlocks"`
	Blocks                  []GetBlockVerboseResult `json:"blocks"`
}

GetChainFromBlockResult models the data from the getChainFromBlock command.

type GetConnectedPeerInfoCmd

type GetConnectedPeerInfoCmd struct{}

GetConnectedPeerInfoCmd defines the getConnectedPeerInfo JSON-RPC command.

func NewGetConnectedPeerInfoCmd

func NewGetConnectedPeerInfoCmd() *GetConnectedPeerInfoCmd

NewGetConnectedPeerInfoCmd returns a new instance which can be used to issue a getpeer JSON-RPC command.

type GetConnectedPeerInfoResult

type GetConnectedPeerInfoResult struct {
	ID                        string `json:"id"`
	Address                   string `json:"address"`
	LastPingDuration          int64  `json:"lastPingDuration"`
	SelectedTipHash           string `json:"selectedTipHash"`
	IsSyncNode                bool   `json:"isSyncNode"`
	IsOutbound                bool   `json:"isOutbound"`
	TimeOffset                int64  `json:"timeOffset"`
	UserAgent                 string `json:"userAgent"`
	AdvertisedProtocolVersion uint32 `json:"advertisedProtocolVersion"`
	TimeConnected             int64  `json:"timeConnected"`
}

GetConnectedPeerInfoResult models the data returned from the getConnectedPeerInfo command.

type GetConnectionCountCmd

type GetConnectionCountCmd struct{}

GetConnectionCountCmd defines the getConnectionCount JSON-RPC command.

func NewGetConnectionCountCmd

func NewGetConnectionCountCmd() *GetConnectionCountCmd

NewGetConnectionCountCmd returns a new instance which can be used to issue a getConnectionCount JSON-RPC command.

type GetCurrentNetCmd

type GetCurrentNetCmd struct{}

GetCurrentNetCmd defines the getCurrentNet JSON-RPC command.

func NewGetCurrentNetCmd

func NewGetCurrentNetCmd() *GetCurrentNetCmd

NewGetCurrentNetCmd returns a new instance which can be used to issue a getCurrentNet JSON-RPC command.

type GetDAGTipsCmd

type GetDAGTipsCmd struct{}

GetDAGTipsCmd defines the getDagTips JSON-RPC command.

func NewGetDAGTipsCmd

func NewGetDAGTipsCmd() *GetDAGTipsCmd

NewGetDAGTipsCmd returns a new instance which can be used to issue a getDagTips JSON-RPC command.

type GetDifficultyCmd

type GetDifficultyCmd struct{}

GetDifficultyCmd defines the getDifficulty JSON-RPC command.

func NewGetDifficultyCmd

func NewGetDifficultyCmd() *GetDifficultyCmd

NewGetDifficultyCmd returns a new instance which can be used to issue a getDifficulty JSON-RPC command.

type GetHeadersCmd

type GetHeadersCmd struct {
	LowHash  string `json:"lowHash"`
	HighHash string `json:"highHash"`
}

GetHeadersCmd defines the getHeaders JSON-RPC command.

func NewGetHeadersCmd

func NewGetHeadersCmd(lowHash, highHash string) *GetHeadersCmd

NewGetHeadersCmd returns a new instance which can be used to issue a getHeaders JSON-RPC command.

type GetInfoCmd

type GetInfoCmd struct{}

GetInfoCmd defines the getInfo JSON-RPC command.

func NewGetInfoCmd

func NewGetInfoCmd() *GetInfoCmd

NewGetInfoCmd returns a new instance which can be used to issue a getInfo JSON-RPC command.

type GetMempoolEntryCmd

type GetMempoolEntryCmd struct {
	TxID string
}

GetMempoolEntryCmd defines the getMempoolEntry JSON-RPC command.

func NewGetMempoolEntryCmd

func NewGetMempoolEntryCmd(txHash string) *GetMempoolEntryCmd

NewGetMempoolEntryCmd returns a new instance which can be used to issue a getMempoolEntry JSON-RPC command.

type GetMempoolEntryResult

type GetMempoolEntryResult struct {
	Fee   uint64      `json:"fee"`
	Time  int64       `json:"time"`
	RawTx TxRawResult `json:"rawTx"`
}

GetMempoolEntryResult models the data returned from the getMempoolEntry command.

type GetMempoolInfoCmd

type GetMempoolInfoCmd struct{}

GetMempoolInfoCmd defines the getMempoolInfo JSON-RPC command.

func NewGetMempoolInfoCmd

func NewGetMempoolInfoCmd() *GetMempoolInfoCmd

NewGetMempoolInfoCmd returns a new instance which can be used to issue a getmempool JSON-RPC command.

type GetMempoolInfoResult

type GetMempoolInfoResult struct {
	Size  int64 `json:"size"`
	Bytes int64 `json:"bytes"`
}

GetMempoolInfoResult models the data returned from the getmempoolinfo command.

type GetNetTotalsCmd

type GetNetTotalsCmd struct{}

GetNetTotalsCmd defines the getNetTotals JSON-RPC command.

func NewGetNetTotalsCmd

func NewGetNetTotalsCmd() *GetNetTotalsCmd

NewGetNetTotalsCmd returns a new instance which can be used to issue a getNetTotals JSON-RPC command.

type GetNetTotalsResult

type GetNetTotalsResult struct {
	TotalBytesRecv uint64 `json:"totalBytesRecv"`
	TotalBytesSent uint64 `json:"totalBytesSent"`
	TimeMillis     int64  `json:"timeMillis"`
}

GetNetTotalsResult models the data returned from the getnettotals command.

type GetNetworkInfoCmd

type GetNetworkInfoCmd struct{}

GetNetworkInfoCmd defines the getNetworkInfo JSON-RPC command.

func NewGetNetworkInfoCmd

func NewGetNetworkInfoCmd() *GetNetworkInfoCmd

NewGetNetworkInfoCmd returns a new instance which can be used to issue a getNetworkInfo JSON-RPC command.

type GetNetworkInfoResult

type GetNetworkInfoResult struct {
	Version         int32                  `json:"version"`
	SubVersion      string                 `json:"subVersion"`
	ProtocolVersion int32                  `json:"protocolVersion"`
	LocalServices   string                 `json:"localServices"`
	LocalRelay      bool                   `json:"localRelay"`
	TimeOffset      int64                  `json:"timeOffset"`
	Connections     int32                  `json:"connections"`
	NetworkActive   bool                   `json:"networkActive"`
	Networks        []NetworksResult       `json:"networks"`
	RelayFee        float64                `json:"relayFee"`
	IncrementalFee  float64                `json:"incrementalFee"`
	LocalAddresses  []LocalAddressesResult `json:"localAddresses"`
	Warnings        string                 `json:"warnings"`
}

GetNetworkInfoResult models the data returned from the getnetworkinfo command.

type GetPeerAddressesCmd

type GetPeerAddressesCmd struct {
}

GetPeerAddressesCmd defines the getPeerAddresses JSON-RPC command.

func NewGetPeerAddressesCmd

func NewGetPeerAddressesCmd() *GetPeerAddressesCmd

NewGetPeerAddressesCmd returns a new instance which can be used to issue a JSON-RPC getPeerAddresses command.

type GetPeerAddressesKnownAddressResult

type GetPeerAddressesKnownAddressResult struct {
	Addr         string
	Src          string
	SubnetworkID string
	Attempts     int
	TimeStamp    int64
	LastAttempt  int64
	LastSuccess  int64
	IsBanned     bool
	BannedTime   int64
}

GetPeerAddressesKnownAddressResult models a GetPeerAddressesResult known address.

type GetPeerAddressesNewBucketResult

type GetPeerAddressesNewBucketResult [addressmanager.NewBucketCount][]string

GetPeerAddressesNewBucketResult models a GetPeerAddressesResult new bucket.

type GetPeerAddressesResult

type GetPeerAddressesResult struct {
	Version              int
	Key                  [32]byte
	Addresses            []*GetPeerAddressesKnownAddressResult
	NewBuckets           map[string]*GetPeerAddressesNewBucketResult // string is Subnetwork ID
	NewBucketFullNodes   GetPeerAddressesNewBucketResult
	TriedBuckets         map[string]*GetPeerAddressesTriedBucketResult // string is Subnetwork ID
	TriedBucketFullNodes GetPeerAddressesTriedBucketResult
}

GetPeerAddressesResult models the data returned from the getPeerAddresses command.

type GetPeerAddressesTriedBucketResult

type GetPeerAddressesTriedBucketResult [addressmanager.TriedBucketCount][]string

GetPeerAddressesTriedBucketResult models a GetPeerAddressesResult tried bucket.

type GetRawMempoolCmd

type GetRawMempoolCmd struct {
	Verbose *bool `jsonrpcdefault:"false"`
}

GetRawMempoolCmd defines the getmempool JSON-RPC command.

func NewGetRawMempoolCmd

func NewGetRawMempoolCmd(verbose *bool) *GetRawMempoolCmd

NewGetRawMempoolCmd returns a new instance which can be used to issue a getRawMempool JSON-RPC command.

The parameters which are pointers indicate they are optional. Passing nil for optional parameters will use the default value.

type GetRawMempoolVerboseResult

type GetRawMempoolVerboseResult struct {
	Size    int32    `json:"size"`
	Fee     float64  `json:"fee"`
	Time    int64    `json:"time"`
	Depends []string `json:"depends"`
}

GetRawMempoolVerboseResult models the data returned from the getrawmempool command when the verbose flag is set. When the verbose flag is not set, getrawmempool returns an array of transaction hashes.

type GetSelectedTipCmd

type GetSelectedTipCmd struct {
	Verbose   *bool `jsonrpcdefault:"true"`
	VerboseTx *bool `jsonrpcdefault:"false"`
}

GetSelectedTipCmd defines the getSelectedTip JSON-RPC command.

func NewGetSelectedTipCmd

func NewGetSelectedTipCmd(verbose, verboseTx *bool) *GetSelectedTipCmd

NewGetSelectedTipCmd returns a new instance which can be used to issue a getSelectedTip JSON-RPC command.

type GetSelectedTipHashCmd

type GetSelectedTipHashCmd struct{}

GetSelectedTipHashCmd defines the getSelectedTipHash JSON-RPC command.

func NewGetSelectedTipHashCmd

func NewGetSelectedTipHashCmd() *GetSelectedTipHashCmd

NewGetSelectedTipHashCmd returns a new instance which can be used to issue a getSelectedTipHash JSON-RPC command.

type GetSubnetworkCmd

type GetSubnetworkCmd struct {
	SubnetworkID string
}

GetSubnetworkCmd defines the getSubnetwork JSON-RPC command.

func NewGetSubnetworkCmd

func NewGetSubnetworkCmd(subnetworkID string) *GetSubnetworkCmd

NewGetSubnetworkCmd returns a new instance which can be used to issue a getSubnetworkCmd command.

type GetSubnetworkResult

type GetSubnetworkResult struct {
	GasLimit *uint64 `json:"gasLimit"`
}

GetSubnetworkResult models the data from the getSubnetwork command.

type GetTopHeadersCmd

type GetTopHeadersCmd struct {
	HighHash *string `json:"highHash"`
}

GetTopHeadersCmd defined the getTopHeaders JSON-RPC command.

func NewGetTopHeadersCmd

func NewGetTopHeadersCmd(highHash *string) *GetTopHeadersCmd

NewGetTopHeadersCmd returns a new instance which can be used to issue a getTopHeaders JSON-RPC command.

type GetTxOutCmd

type GetTxOutCmd struct {
	TxID           string
	Vout           uint32
	IncludeMempool *bool `jsonrpcdefault:"true"`
}

GetTxOutCmd defines the getTxOut JSON-RPC command.

func NewGetTxOutCmd

func NewGetTxOutCmd(txHash string, vout uint32, includeMempool *bool) *GetTxOutCmd

NewGetTxOutCmd returns a new instance which can be used to issue a getTxOut JSON-RPC command.

The parameters which are pointers indicate they are optional. Passing nil for optional parameters will use the default value.

type GetTxOutResult

type GetTxOutResult struct {
	SelectedTip   string             `json:"selectedTip"`
	Confirmations *uint64            `json:"confirmations,omitempty"`
	IsInMempool   bool               `json:"isInMempool"`
	Value         float64            `json:"value"`
	ScriptPubKey  ScriptPubKeyResult `json:"scriptPubKey"`
	Coinbase      bool               `json:"coinbase"`
}

GetTxOutResult models the data from the gettxout command.

type GetTxOutSetInfoCmd

type GetTxOutSetInfoCmd struct{}

GetTxOutSetInfoCmd defines the getTxOutSetInfo JSON-RPC command.

func NewGetTxOutSetInfoCmd

func NewGetTxOutSetInfoCmd() *GetTxOutSetInfoCmd

NewGetTxOutSetInfoCmd returns a new instance which can be used to issue a getTxOutSetInfo JSON-RPC command.

type GetWorkResult

type GetWorkResult struct {
	Data     string `json:"data"`
	Hash1    string `json:"hash1"`
	Midstate string `json:"midstate"`
	Target   string `json:"target"`
}

GetWorkResult models the data from the getwork command.

type HelpCmd

type HelpCmd struct {
	Command *string
}

HelpCmd defines the help JSON-RPC command.

func NewHelpCmd

func NewHelpCmd(command *string) *HelpCmd

NewHelpCmd returns a new instance which can be used to issue a help JSON-RPC command.

The parameters which are pointers indicate they are optional. Passing nil for optional parameters will use the default value.

type InfoDAGResult

type InfoDAGResult struct {
	Version         string  `json:"version"`
	ProtocolVersion int32   `json:"protocolVersion"`
	Blocks          uint64  `json:"blocks"`
	Connections     int32   `json:"connections"`
	Proxy           string  `json:"proxy"`
	Difficulty      float64 `json:"difficulty"`
	Testnet         bool    `json:"testnet"`
	Devnet          bool    `json:"devnet"`
	RelayFee        float64 `json:"relayFee"`
	Errors          string  `json:"errors"`
}

InfoDAGResult models the data returned by the kaspa rpc server getinfo command.

type LoadTxFilterCmd

type LoadTxFilterCmd struct {
	Reload    bool
	Addresses []string
	Outpoints []Outpoint
}

LoadTxFilterCmd defines the loadTxFilter request parameters to load or reload a transaction filter.

func NewLoadTxFilterCmd

func NewLoadTxFilterCmd(reload bool, addresses []string, outpoints []Outpoint) *LoadTxFilterCmd

NewLoadTxFilterCmd returns a new instance which can be used to issue a loadTxFilter JSON-RPC command.

type LocalAddressesResult

type LocalAddressesResult struct {
	Address string `json:"address"`
	Port    uint16 `json:"port"`
	Score   int32  `json:"score"`
}

LocalAddressesResult models the localaddresses data from the getnetworkinfo command.

type NetworksResult

type NetworksResult struct {
	Name                      string `json:"name"`
	Limited                   bool   `json:"limited"`
	Reachable                 bool   `json:"reachable"`
	Proxy                     string `json:"proxy"`
	ProxyRandomizeCredentials bool   `json:"proxyRandomizeCredentials"`
}

NetworksResult models the networks data from the getnetworkinfo command.

type NodeCmd

type NodeCmd struct {
	SubCmd        NodeSubCmd `jsonrpcusage:"\"connect|remove|disconnect\""`
	Target        string
	ConnectSubCmd *string `jsonrpcusage:"\"perm|temp\""`
}

NodeCmd defines the node JSON-RPC command.

func NewNodeCmd

func NewNodeCmd(subCmd NodeSubCmd, target string, connectSubCmd *string) *NodeCmd

NewNodeCmd returns a new instance which can be used to issue a `node` JSON-RPC command.

The parameters which are pointers indicate they are optional. Passing nil for optional parameters will use the default value.

type NodeSubCmd

type NodeSubCmd string

NodeSubCmd defines the type used in the `node` JSON-RPC command for the sub command field.

const (
	// NConnect indicates the specified host that should be connected to.
	NConnect NodeSubCmd = "connect"

	// NRemove indicates the specified peer that should be removed as a
	// persistent peer.
	NRemove NodeSubCmd = "remove"

	// NDisconnect indicates the specified peer should be disconnected.
	NDisconnect NodeSubCmd = "disconnect"
)

type NotifyBlocksCmd

type NotifyBlocksCmd struct{}

NotifyBlocksCmd defines the notifyBlocks JSON-RPC command.

func NewNotifyBlocksCmd

func NewNotifyBlocksCmd() *NotifyBlocksCmd

NewNotifyBlocksCmd returns a new instance which can be used to issue a notifyBlocks JSON-RPC command.

type NotifyChainChangesCmd

type NotifyChainChangesCmd struct{}

NotifyChainChangesCmd defines the notifyChainChanges JSON-RPC command.

func NewNotifyChainChangesCmd

func NewNotifyChainChangesCmd() *NotifyChainChangesCmd

NewNotifyChainChangesCmd returns a new instance which can be used to issue a notifyChainChanges JSON-RPC command.

type NotifyNewTransactionsCmd

type NotifyNewTransactionsCmd struct {
	Verbose    *bool `jsonrpcdefault:"false"`
	Subnetwork *string
}

NotifyNewTransactionsCmd defines the notifyNewTransactions JSON-RPC command.

func NewNotifyNewTransactionsCmd

func NewNotifyNewTransactionsCmd(verbose *bool, subnetworkID *string) *NotifyNewTransactionsCmd

NewNotifyNewTransactionsCmd returns a new instance which can be used to issue a notifyNewTransactions JSON-RPC command.

The parameters which are pointers indicate they are optional. Passing nil for optional parameters will use the default value.

type Outpoint

type Outpoint struct {
	TxID  string `json:"txid"`
	Index uint32 `json:"index"`
}

Outpoint describes a transaction outpoint that will be marshalled to and from JSON.

type PingCmd

type PingCmd struct{}

PingCmd defines the ping JSON-RPC command.

func NewPingCmd

func NewPingCmd() *PingCmd

NewPingCmd returns a new instance which can be used to issue a ping JSON-RPC command.

type PrevOut

type PrevOut struct {
	Address *string `json:"address,omitempty"`
	Value   float64 `json:"value"`
}

PrevOut represents previous output for an input Vin.

type RPCError

type RPCError struct {
	Code    RPCErrorCode `json:"code,omitempty"`
	Message string       `json:"message,omitempty"`
}

RPCError represents an error that is used as a part of a JSON-RPC Response object.

func NewRPCError

func NewRPCError(code RPCErrorCode, message string) *RPCError

NewRPCError constructs and returns a new JSON-RPC error that is suitable for use in a JSON-RPC Response object.

func (RPCError) Error

func (e RPCError) Error() string

Error returns a string describing the RPC error. This satisifies the builtin error interface.

type RPCErrorCode

type RPCErrorCode int

RPCErrorCode represents an error code to be used as a part of an RPCError which is in turn used in a JSON-RPC Response object.

A specific type is used to help ensure the wrong errors aren't used.

const (
	ErrRPCMisc                RPCErrorCode = -1
	ErrRPCForbiddenBySafeMode RPCErrorCode = -2
	ErrRPCType                RPCErrorCode = -3
	ErrRPCInvalidAddressOrKey RPCErrorCode = -5
	ErrRPCOutOfMemory         RPCErrorCode = -7
	ErrRPCInvalidParameter    RPCErrorCode = -8
	ErrRPCDatabase            RPCErrorCode = -20
	ErrRPCDeserialization     RPCErrorCode = -22
	ErrRPCVerify              RPCErrorCode = -25
)

General application defined JSON errors.

const (
	ErrRPCClientNotConnected      RPCErrorCode = -9
	ErrRPCClientInInitialDownload RPCErrorCode = -10
	ErrRPCClientNodeNotAdded      RPCErrorCode = -24
)

Peer-to-peer client errors.

const (
	ErrRPCBlockNotFound      RPCErrorCode = -5
	ErrRPCBlockCount         RPCErrorCode = -5
	ErrRPCSelectedTipHash    RPCErrorCode = -5
	ErrRPCDifficulty         RPCErrorCode = -5
	ErrRPCOutOfRange         RPCErrorCode = -1
	ErrRPCNoTxInfo           RPCErrorCode = -5
	ErrRPCNoAcceptanceIndex  RPCErrorCode = -5
	ErrRPCNoNewestBlockInfo  RPCErrorCode = -5
	ErrRPCInvalidTxVout      RPCErrorCode = -5
	ErrRPCSubnetworkNotFound RPCErrorCode = -5
	ErrRPCRawTxString        RPCErrorCode = -32602
	ErrRPCDecodeHexString    RPCErrorCode = -22
	ErrRPCOrphanBlock        RPCErrorCode = -6
	ErrRPCBlockInvalid       RPCErrorCode = -5
)

Specific Errors related to commands. These are the ones a user of the RPC server are most likely to see. Generally, the codes should match one of the more general errors above.

const (
	ErrRPCUnimplemented RPCErrorCode = -1
)

Errors that are specific to kaspad.

type RelevantTxAcceptedNtfn

type RelevantTxAcceptedNtfn struct {
	Transaction string `json:"transaction"`
}

RelevantTxAcceptedNtfn defines the parameters to the relevantTxAccepted JSON-RPC notification.

func NewRelevantTxAcceptedNtfn

func NewRelevantTxAcceptedNtfn(txHex string) *RelevantTxAcceptedNtfn

NewRelevantTxAcceptedNtfn returns a new instance which can be used to issue a relevantxaccepted JSON-RPC notification.

type Request

type Request struct {
	JSONRPC string            `json:"jsonrpc"`
	Method  string            `json:"method"`
	Params  []json.RawMessage `json:"params"`
	ID      interface{}       `json:"id"`
}

Request is a type for raw JSON-RPC 1.0 requests. The Method field identifies the specific command type which in turns leads to different parameters. Callers typically will not use this directly since this package provides a statically typed command infrastructure which handles creation of these requests, however this struct it being exported in case the caller wants to construct raw requests for some reason.

func NewRequest

func NewRequest(id interface{}, method string, params []interface{}) (*Request, error)

NewRequest returns a new JSON-RPC 1.0 request object given the provided id, method, and parameters. The parameters are marshalled into a json.RawMessage for the Params field of the returned request object. This function is only provided in case the caller wants to construct raw requests for some reason.

Typically callers will instead want to create a registered concrete command type with the NewCommand or New<Foo>Cmd functions and call the MarshalCommand function with that command to generate the marshalled JSON-RPC request.

type RescanBlocksCmd

type RescanBlocksCmd struct {
	// Block hashes as a string array.
	BlockHashes []string
}

RescanBlocksCmd defines the rescan JSON-RPC command.

func NewRescanBlocksCmd

func NewRescanBlocksCmd(blockHashes []string) *RescanBlocksCmd

NewRescanBlocksCmd returns a new instance which can be used to issue a rescan JSON-RPC command.

type RescannedBlock

type RescannedBlock struct {
	Hash         string   `json:"hash"`
	Transactions []string `json:"transactions"`
}

RescannedBlock contains the hash and all discovered transactions of a single rescanned block.

type Response

type Response struct {
	Result json.RawMessage `json:"result"`
	Error  *RPCError       `json:"error"`
	ID     *interface{}    `json:"id"`
}

Response is the general form of a JSON-RPC response. The type of the Result field varies from one command to the next, so it is implemented as an interface. The ID field has to be a pointer for Go to put a null in it when empty.

func NewResponse

func NewResponse(id interface{}, marshalledResult []byte, rpcErr *RPCError) (*Response, error)

NewResponse returns a new JSON-RPC response object given the provided id, marshalled result, and RPC error. This function is only provided in case the caller wants to construct raw responses for some reason.

Typically callers will instead want to create the fully marshalled JSON-RPC response to send over the appmessage with the MarshalResponse function.

type ScriptPubKeyResult

type ScriptPubKeyResult struct {
	Asm     string  `json:"asm"`
	Hex     string  `json:"hex,omitempty"`
	Type    string  `json:"type"`
	Address *string `json:"address,omitempty"`
}

ScriptPubKeyResult models the scriptPubKey data of a tx script. It is defined separately since it is used by multiple commands.

type ScriptSig

type ScriptSig struct {
	Asm string `json:"asm"`
	Hex string `json:"hex"`
}

ScriptSig models a signature script. It is defined separately since it only applies to non-coinbase. Therefore the field in the Vin structure needs to be a pointer.

type SendRawTransactionCmd

type SendRawTransactionCmd struct {
	HexTx         string
	AllowHighFees *bool `jsonrpcdefault:"false"`
}

SendRawTransactionCmd defines the sendRawTransaction JSON-RPC command.

func NewSendRawTransactionCmd

func NewSendRawTransactionCmd(hexTx string, allowHighFees *bool) *SendRawTransactionCmd

NewSendRawTransactionCmd returns a new instance which can be used to issue a sendRawTransaction JSON-RPC command.

The parameters which are pointers indicate they are optional. Passing nil for optional parameters will use the default value.

type SessionCmd

type SessionCmd struct{}

SessionCmd defines the session JSON-RPC command.

func NewSessionCmd

func NewSessionCmd() *SessionCmd

NewSessionCmd returns a new instance which can be used to issue a session JSON-RPC command.

type SessionResult

type SessionResult struct {
	SessionID uint64 `json:"sessionId"`
}

SessionResult models the data from the session command.

type SoftForkDescription

type SoftForkDescription struct {
	ID      string `json:"id"`
	Version uint32 `json:"version"`
	Reject  struct {
		Status bool `json:"status"`
	} `json:"reject"`
}

SoftForkDescription describes the current state of a soft-fork which was deployed using a super-majority block signalling.

type StopCmd

type StopCmd struct{}

StopCmd defines the stop JSON-RPC command.

func NewStopCmd

func NewStopCmd() *StopCmd

NewStopCmd returns a new instance which can be used to issue a stop JSON-RPC command.

type StopNotifyBlocksCmd

type StopNotifyBlocksCmd struct{}

StopNotifyBlocksCmd defines the stopNotifyBlocks JSON-RPC command.

func NewStopNotifyBlocksCmd

func NewStopNotifyBlocksCmd() *StopNotifyBlocksCmd

NewStopNotifyBlocksCmd returns a new instance which can be used to issue a stopNotifyBlocks JSON-RPC command.

type StopNotifyChainChangesCmd

type StopNotifyChainChangesCmd struct{}

StopNotifyChainChangesCmd defines the stopNotifyChainChanges JSON-RPC command.

func NewStopNotifyChainChangesCmd

func NewStopNotifyChainChangesCmd() *StopNotifyChainChangesCmd

NewStopNotifyChainChangesCmd returns a new instance which can be used to issue a stopNotifyChainChanges JSON-RPC command.

type StopNotifyNewTransactionsCmd

type StopNotifyNewTransactionsCmd struct{}

StopNotifyNewTransactionsCmd defines the stopNotifyNewTransactions JSON-RPC command.

func NewStopNotifyNewTransactionsCmd

func NewStopNotifyNewTransactionsCmd() *StopNotifyNewTransactionsCmd

NewStopNotifyNewTransactionsCmd returns a new instance which can be used to issue a stopNotifyNewTransactions JSON-RPC command.

The parameters which are pointers indicate they are optional. Passing nil for optional parameters will use the default value.

type SubmitBlockCmd

type SubmitBlockCmd struct {
	HexBlock string
	Options  *SubmitBlockOptions
}

SubmitBlockCmd defines the submitBlock JSON-RPC command.

func NewSubmitBlockCmd

func NewSubmitBlockCmd(hexBlock string, options *SubmitBlockOptions) *SubmitBlockCmd

NewSubmitBlockCmd returns a new instance which can be used to issue a submitBlock JSON-RPC command.

The parameters which are pointers indicate they are optional. Passing nil for optional parameters will use the default value.

type SubmitBlockOptions

type SubmitBlockOptions struct {
	// must be provided if server provided a workid with template.
	WorkID string `json:"workId,omitempty"`
}

SubmitBlockOptions represents the optional options struct provided with a SubmitBlockCmd command.

type TemplateRequest

type TemplateRequest struct {
	Mode string `json:"mode,omitempty"`

	// Optional long polling.
	LongPollID string `json:"longPollId,omitempty"`

	// Optional template tweaking. SigOpLimit and MassLimit can be int64
	// or bool.
	SigOpLimit interface{} `json:"sigOpLimit,omitempty"`
	MassLimit  interface{} `json:"massLimit,omitempty"`
	MaxVersion uint32      `json:"maxVersion,omitempty"`

	// Basic pool extension from BIP 0023.
	Target string `json:"target,omitempty"`

	// Block proposal from BIP 0023. Data is only provided when Mode is
	// "proposal".
	Data   string `json:"data,omitempty"`
	WorkID string `json:"workId,omitempty"`

	PayAddress string `json:"payAddress"`
}

TemplateRequest is a request object as defined in BIP22. It is optionally provided as an pointer argument to GetBlockTemplateCmd.

func (*TemplateRequest) UnmarshalJSON

func (t *TemplateRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON provides a custom Unmarshal method for TemplateRequest. This is necessary because the SigOpLimit and MassLimit fields can only be specific types.

type TransactionInput

type TransactionInput struct {
	TxID string `json:"txId"`
	Vout uint32 `json:"vout"`
}

TransactionInput represents the inputs to a transaction. Specifically a transaction hash and output number pair.

type TxAcceptedNtfn

type TxAcceptedNtfn struct {
	TxID   string
	Amount float64
}

TxAcceptedNtfn defines the txAccepted JSON-RPC notification.

func NewTxAcceptedNtfn

func NewTxAcceptedNtfn(txHash string, amount float64) *TxAcceptedNtfn

NewTxAcceptedNtfn returns a new instance which can be used to issue a txAccepted JSON-RPC notification.

type TxAcceptedVerboseNtfn

type TxAcceptedVerboseNtfn struct {
	RawTx TxRawResult
}

TxAcceptedVerboseNtfn defines the txAcceptedVerbose JSON-RPC notification.

func NewTxAcceptedVerboseNtfn

func NewTxAcceptedVerboseNtfn(rawTx TxRawResult) *TxAcceptedVerboseNtfn

NewTxAcceptedVerboseNtfn returns a new instance which can be used to issue a txAcceptedVerbose JSON-RPC notification.

type TxRawDecodeResult

type TxRawDecodeResult struct {
	TxID     string `json:"txId"`
	Version  int32  `json:"version"`
	Locktime uint64 `json:"lockTime"`
	Vin      []Vin  `json:"vin"`
	Vout     []Vout `json:"vout"`
}

TxRawDecodeResult models the data from the decoderawtransaction command.

type TxRawResult

type TxRawResult struct {
	Hex         string  `json:"hex"`
	TxID        string  `json:"txId"`
	Hash        string  `json:"hash,omitempty"`
	Size        int32   `json:"size,omitempty"`
	Version     int32   `json:"version"`
	LockTime    uint64  `json:"lockTime"`
	Subnetwork  string  `json:"subnetwork"`
	Gas         uint64  `json:"gas"`
	PayloadHash string  `json:"payloadHash"`
	Payload     string  `json:"payload"`
	Vin         []Vin   `json:"vin"`
	Vout        []Vout  `json:"vout"`
	BlockHash   string  `json:"blockHash,omitempty"`
	AcceptedBy  *string `json:"acceptedBy,omitempty"`
	IsInMempool bool    `json:"isInMempool"`
	Time        uint64  `json:"time,omitempty"`
	BlockTime   uint64  `json:"blockTime,omitempty"`
}

TxRawResult models transaction result data.

type UptimeCmd

type UptimeCmd struct{}

UptimeCmd defines the uptime JSON-RPC command.

func NewUptimeCmd

func NewUptimeCmd() *UptimeCmd

NewUptimeCmd returns a new instance which can be used to issue an uptime JSON-RPC command.

type UsageFlag

type UsageFlag uint32

UsageFlag define flags that specify additional properties about the circumstances under which a command can be used.

const (
	// UFWebsocketOnly indicates that the command can only be used when
	// communicating with an RPC server over websockets. This typically
	// applies to notifications and notification registration functions
	// since neiher makes since when using a single-shot HTTP-POST request.
	UFWebsocketOnly UsageFlag = 1 << iota

	// UFNotification indicates that the command is actually a notification.
	// This means when it is marshalled, the ID must be nil.
	UFNotification
)

func MethodUsageFlags

func MethodUsageFlags(method string) (UsageFlag, error)

MethodUsageFlags returns the usage flags for the passed command method. The provided method must be associated with a registered type. All commands provided by this package are registered by default.

func (UsageFlag) String

func (fl UsageFlag) String() string

String returns the UsageFlag in human-readable form.

type ValidateAddressCmd

type ValidateAddressCmd struct {
	Address string
}

ValidateAddressCmd defines the validateAddress JSON-RPC command.

func NewValidateAddressCmd

func NewValidateAddressCmd(address string) *ValidateAddressCmd

NewValidateAddressCmd returns a new instance which can be used to issue a validateAddress JSON-RPC command.

type ValidateAddressResult

type ValidateAddressResult struct {
	IsValid bool   `json:"isValid"`
	Address string `json:"address,omitempty"`
}

ValidateAddressResult models the data returned by the kaspa rpc server validateaddress command.

type VersionCmd

type VersionCmd struct{}

VersionCmd defines the version JSON-RPC command.

func NewVersionCmd

func NewVersionCmd() *VersionCmd

NewVersionCmd returns a new instance which can be used to issue a JSON-RPC version command.

type VersionResult

type VersionResult struct {
	VersionString string `json:"versionString"`
	Major         uint32 `json:"major"`
	Minor         uint32 `json:"minor"`
	Patch         uint32 `json:"patch"`
	Prerelease    string `json:"prerelease"`
	BuildMetadata string `json:"buildMetadata"`
}

VersionResult models objects included in the version response. In the actual result, these objects are keyed by the program or API name.

type Vin

type Vin struct {
	TxID      string     `json:"txId"`
	Vout      uint32     `json:"vout"`
	ScriptSig *ScriptSig `json:"scriptSig"`
	Sequence  uint64     `json:"sequence"`
}

Vin models parts of the tx data.

func (*Vin) MarshalJSON

func (v *Vin) MarshalJSON() ([]byte, error)

MarshalJSON provides a custom Marshal method for Vin.

type VinPrevOut

type VinPrevOut struct {
	Coinbase  string     `json:"coinbase"`
	TxID      string     `json:"txId"`
	Vout      uint32     `json:"vout"`
	ScriptSig *ScriptSig `json:"scriptSig"`
	PrevOut   *PrevOut   `json:"prevOut"`
	Sequence  uint64     `json:"sequence"`
}

VinPrevOut is like Vin except it includes PrevOut.

func (*VinPrevOut) IsCoinBase

func (v *VinPrevOut) IsCoinBase() bool

IsCoinBase returns a bool to show if a Vin is a Coinbase one or not.

func (*VinPrevOut) MarshalJSON

func (v *VinPrevOut) MarshalJSON() ([]byte, error)

MarshalJSON provides a custom Marshal method for VinPrevOut.

type Vout

type Vout struct {
	Value        uint64             `json:"value"`
	N            uint32             `json:"n"`
	ScriptPubKey ScriptPubKeyResult `json:"scriptPubKey"`
}

Vout models parts of the tx data

Jump to

Keyboard shortcuts

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