rpc

package
v0.0.0-...-a838072 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2019 License: Unlicense, ISC Imports: 58 Imported by: 0

Documentation

Index

Constants

View Source
const (
	JSONRPCSemverString = "1.3.0"
	JSONRPCSemverMajor  = 1
	JSONRPCSemverMinor  = 3
	JSONRPCSemverPatch  = 0
	// RPCAuthTimeoutSeconds is the number of seconds a connection to the RPC
	// server is allowed to stay open without authenticating before it is
	// closed.
	RPCAuthTimeoutSeconds = 10
	// GBTNonceRange is two 32-bit big-endian hexadecimal integers which
	// represent the valid ranges of nonces returned by the getblocktemplate
	// RPC.
	GBTNonceRange = "00000000ffffffff"
	// GBTRegenerateSeconds is the number of seconds that must pass before a
	// new template is generated when the previous block hash has not changed
	// and there have been changes to the available transactions in the
	// memory pool.
	GBTRegenerateSeconds = 60
	// MaxProtocolVersion is the max protocol version the server supports.
	MaxProtocolVersion = 70002
)

API version constants

View Source
const (
	// DefaultServices describes the default services that are supported by
	// the server.
	DefaultServices = wire.SFNodeNetwork | wire.SFNodeBloom |
		wire.SFNodeWitness | wire.SFNodeCF
	// DefaultRequiredServices describes the default services that are required
	// to be supported by outbound peers.
	DefaultRequiredServices = wire.SFNodeNetwork
	// DefaultTargetOutbound is the default number of outbound peers to target.
	DefaultTargetOutbound = 125
	// ConnectionRetryInterval is the base amount of time to wait in between
	// retries when connecting to persistent peers.  It is adjusted by the
	// number of retries such that there is a retry backoff.
	ConnectionRetryInterval = time.Second
)
View Source
const DefaultMaxOrphanTxSize = 100000
View Source
const Uint256Size = 32

Uint256Size is the number of bytes needed to represent an unsigned 256-bit integer.

View Source
const (
	// WebsocketSendBufferSize is the number of elements the send channel can
	// queue before blocking.  Note that this only applies to requests handled
	// directly in the websocket client input handler or the async handler since
	// notifications have their own queuing mechanism independent of the send
	// channel buffer.
	WebsocketSendBufferSize = 50
)

Variables

View Source
var (
	// ErrRPCNoWallet is an error returned to RPC clients when the provided
	// command is recognized as a wallet command.
	ErrRPCNoWallet = &json.RPCError{
		Code:    json.ErrRPCNoWallet,
		Message: "This implementation does not implement wallet commands",
	}
	// ErrRPCUnimplemented is an error returned to RPC clients when the
	// provided command is recognized, but not implemented.
	ErrRPCUnimplemented = &json.RPCError{
		Code:    json.ErrRPCUnimplemented,
		Message: "Command unimplemented",
	}
	// GBTCapabilities describes additional capabilities returned with a
	// block template generated by the getblocktemplate RPC.
	// It is declared here to avoid the overhead of creating the slice on
	// every invocation for constant data.
	GBTCapabilities = []string{"proposal"}
	// GBTCoinbaseAux describes additional data that miners should include in
	// the coinbase signature script.
	// It is declared here to avoid the overhead of creating a new object on
	// every invocation for constant data.
	GBTCoinbaseAux = &json.GetBlockTemplateResultAux{
		Flags: hex.EncodeToString(BuilderScript(txscript.
			NewScriptBuilder().
			AddData([]byte(mining.CoinbaseFlags)))),
	}
	// GBTMutableFields are the manipulations the server allows to be made to
	// block templates generated by the getblocktemplate RPC.
	// It is declared here to avoid the overhead of creating the slice on
	// every invocation for constant data.
	GBTMutableFields = []string{
		"time", "transactions/add", "prevblock", "coinbase/append",
	}

	// RPCAskWallet is list of commands that we recognize,
	// but for which pod has no support because it lacks support for wallet
	// functionality. For these commands the user should ask a connected
	// instance of btcwallet.
	RPCAskWallet = map[string]struct{}{
		"addmultisigaddress":     {},
		"backupwallet":           {},
		"createencryptedwallet":  {},
		"createmultisig":         {},
		"dumpprivkey":            {},
		"dumpwallet":             {},
		"encryptwallet":          {},
		"getaccount":             {},
		"getaccountaddress":      {},
		"getaddressesbyaccount":  {},
		"getbalance":             {},
		"getnewaddress":          {},
		"getrawchangeaddress":    {},
		"getreceivedbyaccount":   {},
		"getreceivedbyaddress":   {},
		"gettransaction":         {},
		"gettxoutsetinfo":        {},
		"getunconfirmedbalance":  {},
		"getwalletinfo":          {},
		"importprivkey":          {},
		"importwallet":           {},
		"keypoolrefill":          {},
		"listaccounts":           {},
		"listaddressgroupings":   {},
		"listlockunspent":        {},
		"listreceivedbyaccount":  {},
		"listreceivedbyaddress":  {},
		"listsinceblock":         {},
		"listtransactions":       {},
		"listunspent":            {},
		"lockunspent":            {},
		"move":                   {},
		"sendfrom":               {},
		"sendmany":               {},
		"sendtoaddress":          {},
		"setaccount":             {},
		"settxfee":               {},
		"signmessage":            {},
		"signrawtransaction":     {},
		"walletlock":             {},
		"walletpassphrase":       {},
		"walletpassphrasechange": {},
	}
	// RPCHandlers maps RPC command strings to appropriate handler functions.
	// This is set by init because help references RPCHandlers and thus
	// causes a dependency loop.
	RPCHandlers map[string]CommandHandler
	// RPCHandlersBeforeInit is
	RPCHandlersBeforeInit = map[string]CommandHandler{
		"addnode":              HandleAddNode,
		"createrawtransaction": HandleCreateRawTransaction,

		"decoderawtransaction":  HandleDecodeRawTransaction,
		"decodescript":          HandleDecodeScript,
		"estimatefee":           HandleEstimateFee,
		"generate":              HandleGenerate,
		"getaddednodeinfo":      HandleGetAddedNodeInfo,
		"getbestblock":          HandleGetBestBlock,
		"getbestblockhash":      HandleGetBestBlockHash,
		"getblock":              HandleGetBlock,
		"getblockchaininfo":     HandleGetBlockChainInfo,
		"getblockcount":         HandleGetBlockCount,
		"getblockhash":          HandleGetBlockHash,
		"getblockheader":        HandleGetBlockHeader,
		"getblocktemplate":      HandleGetBlockTemplate,
		"getcfilter":            HandleGetCFilter,
		"getcfilterheader":      HandleGetCFilterHeader,
		"getconnectioncount":    HandleGetConnectionCount,
		"getcurrentnet":         HandleGetCurrentNet,
		"getdifficulty":         HandleGetDifficulty,
		"getgenerate":           HandleGetGenerate,
		"gethashespersec":       HandleGetHashesPerSec,
		"getheaders":            HandleGetHeaders,
		"getinfo":               HandleGetInfo,
		"getmempoolinfo":        HandleGetMempoolInfo,
		"getmininginfo":         HandleGetMiningInfo,
		"getnettotals":          HandleGetNetTotals,
		"getnetworkhashps":      HandleGetNetworkHashPS,
		"getpeerinfo":           HandleGetPeerInfo,
		"getrawmempool":         HandleGetRawMempool,
		"getrawtransaction":     HandleGetRawTransaction,
		"gettxout":              HandleGetTxOut,
		"getwork":               HandleGetWork,
		"help":                  HandleHelp,
		"node":                  HandleNode,
		"ping":                  HandlePing,
		"searchrawtransactions": HandleSearchRawTransactions,
		"sendrawtransaction":    HandleSendRawTransaction,
		"setgenerate":           HandleSetGenerate,
		"stop":                  HandleStop,
		"submitblock":           HandleSubmitBlock,
		"uptime":                HandleUptime,
		"validateaddress":       HandleValidateAddress,
		"verifychain":           HandleVerifyChain,
		"verifymessage":         HandleVerifyMessage,
		"version":               HandleVersion,
	}

	// RPCLimited isCommands that are available to a limited user
	RPCLimited = map[string]struct{}{

		"loadtxfilter":          {},
		"notifyblocks":          {},
		"notifynewtransactions": {},
		"notifyreceived":        {},
		"notifyspent":           {},
		"rescan":                {},
		"rescanblocks":          {},
		"session":               {},

		"help": {},

		"createrawtransaction":  {},
		"decoderawtransaction":  {},
		"decodescript":          {},
		"estimatefee":           {},
		"getbestblock":          {},
		"getbestblockhash":      {},
		"getblock":              {},
		"getblockcount":         {},
		"getblockhash":          {},
		"getblockheader":        {},
		"getcfilter":            {},
		"getcfilterheader":      {},
		"getcurrentnet":         {},
		"getdifficulty":         {},
		"getheaders":            {},
		"getinfo":               {},
		"getnettotals":          {},
		"getnetworkhashps":      {},
		"getrawmempool":         {},
		"getrawtransaction":     {},
		"gettxout":              {},
		"searchrawtransactions": {},
		"sendrawtransaction":    {},
		"submitblock":           {},
		"uptime":                {},
		"validateaddress":       {},
		"verifymessage":         {},
		"version":               {},
	}
	// RPCUnimplemented is commands that are currently unimplemented,
	// but should ultimately be.
	RPCUnimplemented = map[string]struct{}{
		"estimatepriority": {},
		"getchaintips":     {},
		"getmempoolentry":  {},
		"getnetworkinfo":   {},
		"getwork":          {},
		"invalidateblock":  {},
		"preciousblock":    {},
		"reconsiderblock":  {},
	}
)
View Source
var (

	// UserAgentName is the user agent name and is used to help identify
	// ourselves to peers.
	// nolint
	UserAgentName = "pod"
	// UserAgentVersion is the user agent version and is used to help identify
	// ourselves to peers.
	// nolint
	UserAgentVersion = fmt.Sprintf("%d.%d.%d", version.AppMajor,
		version.AppMinor, version.AppPatch)
)
View Source
var DefaultConnectTimeout = time.Second * 30

DefaultConnectTimeout is a reasonable 30 seconds

View Source
var Dial = func(statecfg *state.Config) func(addr net.Addr) (net.Conn, error) {
	return func(addr net.Addr) (net.Conn, error) {
		if strings.Contains(addr.String(), ".onion:") {
			return statecfg.Oniondial(addr.Network(), addr.String(),
				DefaultConnectTimeout)
		}
		log <- cl.Trace{"StateCfg.Dial", addr.Network(), addr.String(), DefaultConnectTimeout}
		con, er := statecfg.Dial(addr.Network(), addr.String(), DefaultConnectTimeout)
		if er != nil {
			log <- cl.Trace{con, er}
		}
		return con, er
	}
}

Dial connects to the address on the named network using the appropriate dial function depending on the address and configuration options. For example .onion addresses will be dialed using the onion specific proxy if one was specified, but will otherwise use the normal dial function ( which could itself use a proxy or not).

View Source
var ErrClientQuit = errors.New("client quit")

ErrClientQuit describes the error where a client send is not processed due to the client having already been disconnected or dropped.

View Source
var ErrRescanReorg = json.RPCError{
	Code:    json.ErrRPCDatabase,
	Message: "Reorganize",
}

ErrRescanReorg defines the error that is returned when an unrecoverable reorganize is detected during a rescan.

View Source
var GetworkDataLen = (1 + ((wire.MaxBlockHeaderPayload + 8) / fastsha256.BlockSize)) * fastsha256.BlockSize

GetworkDataLen is the length of the data field of the getwork RPC. It consists of the serialized block header plus the internal sha256 padding. The internal sha256 padding consists of a single 1 bit followed by enough zeros to pad the message out to 56 bytes followed by length of the message in bits encoded as a big-endian uint64 (8 bytes). Thus, the resulting length is a multiple of the sha256 block size (64 bytes).

View Source
var Hash1Len = (1 + ((chainhash.HashSize + 8) / fastsha256.BlockSize)) * fastsha256.BlockSize

Hash1Len is the length of the hash1 field of the getwork RPC. It consists of a zero hash plus the internal sha256 padding. See the getworkDataLen comment for details about the internal sha256 padding format.

View Source
var HelpDescsEnUS = map[string]string{}/* 442 elements not displayed */

HelpDescsEnUS defines the English descriptions used for the help strings. nolint

View Source
var Log = cl.NewSubSystem(pkgs.Name(_d), "info")
View Source
var Lookup = func(statecfg *state.Config) func(host string) ([]net.IP, error) {
	return func(host string) ([]net.IP, error) {
		if strings.HasSuffix(host, ".onion") {
			return nil, fmt.Errorf("attempt to resolve tor address %s", host)
		}
		return statecfg.Lookup(host)
	}
}

Lookup resolves the IP of the given host using the correct DNS lookup function depending on the configuration options. For example, addresses will be resolved using tor when the --proxy flag was specified unless --noonion was also specified in which case the normal system DNS resolver will be used. Any attempt to resolve a tor address (. onion) will return an error since they are not intended to be resolved outside of the tor proxy.

View Source
var ResultTypes = map[string][]interface{}{
	"addnode":               nil,
	"createrawtransaction":  {(*string)(nil)},
	"debuglevel":            {(*string)(nil), (*string)(nil)},
	"decoderawtransaction":  {(*json.TxRawDecodeResult)(nil)},
	"decodescript":          {(*json.DecodeScriptResult)(nil)},
	"estimatefee":           {(*float64)(nil)},
	"generate":              {(*[]string)(nil)},
	"getaddednodeinfo":      {(*[]string)(nil), (*[]json.GetAddedNodeInfoResult)(nil)},
	"getbestblock":          {(*json.GetBestBlockResult)(nil)},
	"getbestblockhash":      {(*string)(nil)},
	"getblock":              {(*string)(nil), (*json.GetBlockVerboseResult)(nil)},
	"getblockcount":         {(*int64)(nil)},
	"getblockhash":          {(*string)(nil)},
	"getblockheader":        {(*string)(nil), (*json.GetBlockHeaderVerboseResult)(nil)},
	"getblocktemplate":      {(*json.GetBlockTemplateResult)(nil), (*string)(nil), nil},
	"getblockchaininfo":     {(*json.GetBlockChainInfoResult)(nil)},
	"getcfilter":            {(*string)(nil)},
	"getcfilterheader":      {(*string)(nil)},
	"getconnectioncount":    {(*int32)(nil)},
	"getcurrentnet":         {(*uint32)(nil)},
	"getdifficulty":         {(*float64)(nil)},
	"getgenerate":           {(*bool)(nil)},
	"gethashespersec":       {(*float64)(nil)},
	"getheaders":            {(*[]string)(nil)},
	"getinfo":               {(*json.InfoChainResult)(nil)},
	"getmempoolinfo":        {(*json.GetMempoolInfoResult)(nil)},
	"getmininginfo":         {(*json.GetMiningInfoResult)(nil)},
	"getnettotals":          {(*json.GetNetTotalsResult)(nil)},
	"getnetworkhashps":      {(*int64)(nil)},
	"getpeerinfo":           {(*[]json.GetPeerInfoResult)(nil)},
	"getrawmempool":         {(*[]string)(nil), (*json.GetRawMempoolVerboseResult)(nil)},
	"getrawtransaction":     {(*string)(nil), (*json.TxRawResult)(nil)},
	"gettxout":              {(*json.GetTxOutResult)(nil)},
	"node":                  nil,
	"help":                  {(*string)(nil), (*string)(nil)},
	"ping":                  nil,
	"searchrawtransactions": {(*string)(nil), (*[]json.SearchRawTransactionsResult)(nil)},
	"sendrawtransaction":    {(*string)(nil)},
	"setgenerate":           nil,
	"stop":                  {(*string)(nil)},
	"submitblock":           {nil, (*string)(nil)},
	"uptime":                {(*int64)(nil)},
	"validateaddress":       {(*json.ValidateAddressChainResult)(nil)},
	"verifychain":           {(*bool)(nil)},
	"verifymessage":         {(*bool)(nil)},
	"version":               {(*map[string]json.VersionResult)(nil)},

	"loadtxfilter":              nil,
	"session":                   {(*json.SessionResult)(nil)},
	"notifyblocks":              nil,
	"stopnotifyblocks":          nil,
	"notifynewtransactions":     nil,
	"stopnotifynewtransactions": nil,
	"notifyreceived":            nil,
	"stopnotifyreceived":        nil,
	"notifyspent":               nil,
	"stopnotifyspent":           nil,
	"rescan":                    nil,
	"rescanblocks":              {(*[]json.RescannedBlock)(nil)},
}

ResultTypes specifies the result types that each RPC command can return. This information is used to generate the help. Each result type must be a pointer to the type (or nil to indicate no return value). nolint

View Source
var TimeZeroVal = time.Time{}

TimeZeroVal is simply the zero value for a time.Time and is used to avoid creating multiple instances. nolint

View Source
var WSHandlers map[string]WSCommandHandler

WSHandlers maps RPC command strings to appropriate websocket handler functions. This is set by init because help references WSHandlers and thus causes a dependency loop. nolint

View Source
var WSHandlersBeforeInit = map[string]WSCommandHandler{
	"loadtxfilter":              HandleLoadTxFilter,
	"help":                      HandleWebsocketHelp,
	"notifyblocks":              HandleNotifyBlocks,
	"notifynewtransactions":     HandleNotifyNewTransactions,
	"notifyreceived":            HandleNotifyReceived,
	"notifyspent":               HandleNotifySpent,
	"session":                   HandleSession,
	"stopnotifyblocks":          HandleStopNotifyBlocks,
	"stopnotifynewtransactions": HandleStopNotifyNewTransactions,
	"stopnotifyspent":           HandleStopNotifySpent,
	"stopnotifyreceived":        HandleStopNotifyReceived,
	"rescan":                    HandleRescan,
	"rescanblocks":              HandleRescanBlocks,
}

nolint

Functions

func AddLocalAddress

func AddLocalAddress(addrMgr *addrmgr.AddrManager, addr string,
	services wire.ServiceFlag) error
AddLocalAddress adds an address that this node is listening on to the

address manager so that it may be relayed to peers.

func AddrStringToNetAddr

func AddrStringToNetAddr(config *pod.Config, stateCfg *state.Config,
	addr string) (net.Addr, error)

AddrStringToNetAddr takes an address in the form of 'host:port' and returns a net.Addr which maps to the original address with any host names resolved to IP addresses. It also handles tor addresses properly by returning a net.Addr that encapsulates the address.

func BigToLEUint256

func BigToLEUint256(n *big.Int) [Uint256Size]byte

BigToLEUint256 returns the passed big integer as an unsigned 256-bit integer encoded as little-endian bytes. Numbers which are larger than the max unsigned 256-bit integer are truncated.

func BlockDetails

func BlockDetails(block *util.Block, txIndex int) *json.BlockDetails

BlockDetails creates a BlockDetails struct to include in btcws notifications from a block and a transaction's block index.

func BuilderScript

func BuilderScript(builder *txscript.ScriptBuilder) []byte

BuilderScript is a convenience function which is used for hard-coded scripts built with the script builder. Any errors are converted to a panic since it is only, and must only, be used with hard-coded, and therefore, known good, scripts.

func ChainErrToGBTErrString

func ChainErrToGBTErrString(err error) string

ChainErrToGBTErrString converts an error returned from btcchain to a string which matches the reasons and format described in BIP0022 for rejection reasons. nolint

func CheckAddressValidity

func CheckAddressValidity(addrs []string, params *netparams.Params) error

CheckAddressValidity checks the validity of each address in the passed string slice. It does this by attempting to decode each address using the current active network parameters. If any single address fails to decode properly, the function returns an error. Otherwise, nil is returned.

func CreateMarshalledReply

func CreateMarshalledReply(id, result interface{}, replyErr error) ([]byte, error)

CreateMarshalledReply returns a new marshalled JSON-RPC response given the passed parameters. It will automatically convert errors that are not of the type *json.RPCError to the appropriate type as needed.

func CreateTxRawResult

func CreateTxRawResult(chainParams *netparams.Params, mtx *wire.MsgTx,
	txHash string, blkHeader *wire.BlockHeader, blkHash string, blkHeight int32,
	chainHeight int32) (*json.TxRawResult, error)

CreateTxRawResult converts the passed transaction and associated parameters to a raw transaction JSON object.

func CreateVinList

func CreateVinList(mtx *wire.MsgTx) []json.Vin

CreateVinList returns a slice of JSON objects for the inputs of the passed transaction.

func CreateVinListPrevOut

func CreateVinListPrevOut(s *Server, mtx *wire.MsgTx,
	chainParams *netparams.Params, vinExtra bool,
	filterAddrMap map[string]struct{}) ([]json.VinPrevOut, error)

CreateVinListPrevOut returns a slice of JSON objects for the inputs of the passed transaction.

func CreateVoutList

func CreateVoutList(mtx *wire.MsgTx, chainParams *netparams.Params,
	filterAddrMap map[string]struct{}) []json.Vout

CreateVoutList returns a slice of JSON objects for the outputs of the passed transaction.

func DecodeHexError

func DecodeHexError(gotHex string) *json.RPCError

DecodeHexError is a convenience function for returning a nicely formatted RPC error which indicates the provided hex string failed to decode.

func DecodeTemplateID

func DecodeTemplateID(templateID string) (*chainhash.Hash, int64, error)

DecodeTemplateID decodes an ID that is used to uniquely identify a block template. This is mainly used as a mechanism to track when to update clients that are using long polling for block templates. The ID consists of the previous block hash for the associated template and the time the associated template was generated.

func DescendantBlock

func DescendantBlock(prevHash *chainhash.Hash, curBlock *util.Block) error

DescendantBlock returns the appropriate JSON-RPC error if a current block fetched during a reorganize is not a direct child of the parent block hash.

func DeserializeOutpoints

func DeserializeOutpoints(serializedOuts []json.OutPoint) ([]*wire.OutPoint,
	error)

DeserializeOutpoints deserializes each serialized outpoint.

func DirectionString

func DirectionString(inbound bool) string

DirectionString is a helper function that returns a string that represents the direction of a connection (inbound or outbound).

func DisconnectPeer

func DisconnectPeer(peerList map[int32]*NodePeer,
	compareFunc func(*NodePeer) bool, whenFound func(*NodePeer)) bool

DisconnectPeer attempts to drop the connection of a targeted peer in the passed peer list. Targets are identified via usage of the passed `compareFunc`, which should return `true` if the passed peer is the target peer. This function returns true on success and false if the peer is unable to be located. If the peer is found, and the passed callback: `whenFound' isn't nil, we call it with the peer as the argument before it is removed from the peerList, and is disconnected from the server.

func DynamicTickDuration

func DynamicTickDuration(remaining time.Duration) time.Duration
DynamicTickDuration is a convenience function used to dynamically choose a

tick duration based on remaining time. It is primarily used during server shutdown to make shutdown warnings more frequent as the shutdown time approaches.

func EncodeTemplateID

func EncodeTemplateID(prevHash *chainhash.Hash, lastGenerated time.Time) string

EncodeTemplateID encodes the passed details into an ID that can be used to uniquely identify a block template.

func FetchInputTxos

func FetchInputTxos(s *Server, tx *wire.MsgTx) (map[wire.OutPoint]wire.TxOut, error)

FetchInputTxos fetches the outpoints from all transactions referenced by the inputs to the passed transaction by checking the transaction mempool first then the transaction index for those already mined into blocks.

func FetchMempoolTxnsForAddress

func FetchMempoolTxnsForAddress(s *Server, addr util.Address, numToSkip,
	numRequested uint32) ([]*util.Tx, uint32)

FetchMempoolTxnsForAddress queries the address index for all unconfirmed transactions that involve the provided address. The results will be limited by the number to skip and the number requested.

func FileExists

func FileExists(name string) bool

FileExists reports whether the named file or directory exists.

func GenCertPair

func GenCertPair(certFile, keyFile string) error

GenCertPair generates a key/cert pair to the paths provided.

func GetDifficultyRatio

func GetDifficultyRatio(bits uint32, params *netparams.Params,
	algo int32) float64

GetDifficultyRatio returns the proof-of-work difficulty as a multiple of the minimum difficulty using the passed bits field from the header of a block.

func GetHasServices

func GetHasServices(advertised, desired wire.ServiceFlag) bool

GetHasServices returns whether or not the provided advertised service flags have all of the provided desired service flags set.

func GetIsWhitelisted

func GetIsWhitelisted(config *pod.Config, statecfg *state.Config, addr net.Addr) bool

GetIsWhitelisted returns whether the IP address is included in the whitelisted networks and IPs.

func HandleAddNode

func HandleAddNode(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleAddNode handles addnode commands.

func HandleAskWallet

func HandleAskWallet(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleAskWallet is the handler for commands that are recognized as valid, but are unable to answer correctly since it involves wallet state. These commands will be implemented in btcwallet.

func HandleCreateRawTransaction

func HandleCreateRawTransaction(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleCreateRawTransaction handles createrawtransaction commands.

func HandleDecodeRawTransaction

func HandleDecodeRawTransaction(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleDecodeRawTransaction handles decoderawtransaction commands.

func HandleDecodeScript

func HandleDecodeScript(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleDecodeScript handles decodescript commands.

func HandleEstimateFee

func HandleEstimateFee(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleEstimateFee handles estimatefee commands.

func HandleGenerate

func HandleGenerate(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGenerate handles generate commands.

func HandleGetAddedNodeInfo

func HandleGetAddedNodeInfo(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetAddedNodeInfo handles getaddednodeinfo commands.

func HandleGetBestBlock

func HandleGetBestBlock(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetBestBlock implements the getbestblock command.

func HandleGetBestBlockHash

func HandleGetBestBlockHash(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetBestBlockHash implements the getbestblockhash command.

func HandleGetBlock

func HandleGetBlock(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetBlock implements the getblock command.

func HandleGetBlockChainInfo

func HandleGetBlockChainInfo(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetBlockChainInfo implements the getblockchaininfo command.

func HandleGetBlockCount

func HandleGetBlockCount(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetBlockCount implements the getblockcount command.

func HandleGetBlockHash

func HandleGetBlockHash(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetBlockHash implements the getblockhash command.

func HandleGetBlockHeader

func HandleGetBlockHeader(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetBlockHeader implements the getblockheader command.

func HandleGetBlockTemplate

func HandleGetBlockTemplate(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetBlockTemplate implements the getblocktemplate command. See https:// en.bitcoin.it/wiki/BIP_0022 and https://en.bitcoin.it/wiki/BIP_0023 for more details.

func HandleGetBlockTemplateLongPoll

func HandleGetBlockTemplateLongPoll(s *Server, longPollID string,
	useCoinbaseValue bool, closeChan <-chan struct{}) (interface{}, error)

HandleGetBlockTemplateLongPoll is a helper for handleGetBlockTemplateRequest which deals with handling long polling for block templates. When a caller sends a request with a long poll ID that was previously returned, a response is not sent until the caller should stop working on the previous block template in favor of the new one. In particular, this is the case when the old block template is no longer valid due to a solution already being found and added to the block chain, or new transactions have shown up and some time has passed without finding a solution. See https://en.bitcoin.it/wiki/ BIP_0022 for more details.

func HandleGetBlockTemplateProposal

func HandleGetBlockTemplateProposal(s *Server,
	request *json.TemplateRequest) (interface{}, error)

HandleGetBlockTemplateProposal is a helper for handleGetBlockTemplate which deals with block proposals. See https://en.bitcoin.it/wiki/BIP_0023 for more details.

func HandleGetBlockTemplateRequest

func HandleGetBlockTemplateRequest(s *Server, request *json.TemplateRequest,
	closeChan <-chan struct{}) (interface{}, error)

HandleGetBlockTemplateRequest is a helper for handleGetBlockTemplate which deals with generating and returning block templates to the caller. It handles both long poll requests as specified by BIP 0022 as well as regular requests. In addition, it detects the capabilities reported by the caller in regards to whether or not it supports creating its own coinbase (the coinbasetxn and coinbasevalue capabilities) and modifies the returned block template accordingly.

func HandleGetCFilter

func HandleGetCFilter(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetCFilter implements the getcfilter command.

func HandleGetCFilterHeader

func HandleGetCFilterHeader(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetCFilterHeader implements the getcfilterheader command.

func HandleGetConnectionCount

func HandleGetConnectionCount(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetConnectionCount implements the getconnectioncount command.

func HandleGetCurrentNet

func HandleGetCurrentNet(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetCurrentNet implements the getcurrentnet command.

func HandleGetDifficulty

func HandleGetDifficulty(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetDifficulty implements the getdifficulty command. TODO: This command should default to the configured algo for cpu mining

and take an optional parameter to query by algo

func HandleGetGenerate

func HandleGetGenerate(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetGenerate implements the getgenerate command.

func HandleGetHashesPerSec

func HandleGetHashesPerSec(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetHashesPerSec implements the gethashespersec command.

func HandleGetHeaders

func HandleGetHeaders(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetHeaders implements the getheaders command. NOTE: This is a btcsuite extension originally ported from github.com/decred/dcrd.

func HandleGetInfo

func HandleGetInfo(s *Server, cmd interface{},
	closeChan <-chan struct{}) (ret interface{}, err error)

HandleGetInfo implements the getinfo command. We only return the fields that are not related to wallet functionality. TODO: simplify this, break it up

func HandleGetMempoolInfo

func HandleGetMempoolInfo(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetMempoolInfo implements the getmempoolinfo command.

func HandleGetMiningInfo

func HandleGetMiningInfo(s *Server, cmd interface{},
	closeChan <-chan struct{}) (ret interface{}, err error)

HandleGetMiningInfo implements the getmininginfo command. We only return the fields that are not related to wallet functionality. This function returns more information than parallelcoind. TODO: simplify this, break it up

func HandleGetNetTotals

func HandleGetNetTotals(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetNetTotals implements the getnettotals command.

func HandleGetNetworkHashPS

func HandleGetNetworkHashPS(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetNetworkHashPS implements the getnetworkhashps command. This command does not default to the same end block as the parallelcoind. TODO: Really this needs to be expanded to show per-algorithm hashrates

func HandleGetPeerInfo

func HandleGetPeerInfo(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetPeerInfo implements the getpeerinfo command.

func HandleGetRawMempool

func HandleGetRawMempool(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetRawMempool implements the getrawmempool command.

func HandleGetRawTransaction

func HandleGetRawTransaction(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetRawTransaction implements the getrawtransaction command.

func HandleGetTxOut

func HandleGetTxOut(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleGetTxOut handles gettxout commands.

func HandleGetWork

func HandleGetWork(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)

HandleGetWork handles the getwork call

func HandleGetWorkSubmission

func HandleGetWorkSubmission(s *Server, hexData string) (interface{}, error)
HandleGetWorkSubmission is a helper for handleGetWork which deals with the

calling submitting work to be verified and processed. This function MUST be called with the RPC workstate locked.

func HandleHelp

func HandleHelp(s *Server, cmd interface{}, closeChan <-chan struct{}) (
	interface{}, error)

HandleHelp implements the help command.

func HandleLoadTxFilter

func HandleLoadTxFilter(wsc *WSClient, icmd interface{}) (interface{}, error)

HandleLoadTxFilter implements the loadtxfilter command extension for websocket connections. NOTE: This extension is ported from github.com/decred/dcrd

func HandleNode

func HandleNode(s *Server, cmd interface{}, closeChan <-chan struct{}) (
	interface{}, error)

HandleNode handles node commands.

func HandleNotifyBlocks

func HandleNotifyBlocks(wsc *WSClient, icmd interface{}) (interface{}, error)

HandleNotifyBlocks implements the notifyblocks command extension for websocket connections.

func HandleNotifyNewTransactions

func HandleNotifyNewTransactions(wsc *WSClient,
	icmd interface{}) (interface{}, error)

handleNotifyNewTransations implements the notifynewtransactions command extension for websocket connections.

func HandleNotifyReceived

func HandleNotifyReceived(wsc *WSClient, icmd interface{}) (interface{},
	error)

HandleNotifyReceived implements the notifyreceived command extension for websocket connections.

func HandleNotifySpent

func HandleNotifySpent(wsc *WSClient, icmd interface{}) (interface{}, error)

HandleNotifySpent implements the notifyspent command extension for websocket connections.

func HandlePing

func HandlePing(s *Server, cmd interface{}, closeChan <-chan struct{}) (
	interface{}, error)

HandlePing implements the ping command.

func HandleRescan

func HandleRescan(wsc *WSClient, icmd interface{}) (interface{}, error)

HandleRescan implements the rescan command extension for websocket connections. NOTE: This does not smartly handle reorgs, and fixing requires database changes (for safe, concurrent access to full block ranges, and support for other chains than the best chain). It will, however, detect whether a reorg removed a block that was previously processed, and result in the handler erroring. Clients must handle this by finding a block still in the chain (perhaps from a rescanprogress notification) to resume their rescan. TODO: simplify, modularise this

func HandleRescanBlocks

func HandleRescanBlocks(wsc *WSClient, icmd interface{}) (interface{}, error)

HandleRescanBlocks implements the rescanblocks command extension for websocket connections. NOTE: This extension is ported from github.com/decred/dcrd

func HandleSearchRawTransactions

func HandleSearchRawTransactions(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleSearchRawTransactions implements the searchrawtransactions command. TODO: simplify this, break it up

func HandleSendRawTransaction

func HandleSendRawTransaction(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleSendRawTransaction implements the sendrawtransaction command.

func HandleSession

func HandleSession(wsc *WSClient, icmd interface{}) (interface{}, error)

HandleSession implements the session command extension for websocket connections.

func HandleSetGenerate

func HandleSetGenerate(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleSetGenerate implements the setgenerate command.

func HandleStop

func HandleStop(s *Server, cmd interface{}, closeChan <-chan struct{}) (
	interface{}, error)

HandleStop implements the stop command.

func HandleStopNotifyBlocks

func HandleStopNotifyBlocks(wsc *WSClient, icmd interface{}) (interface{},
	error)

HandleStopNotifyBlocks implements the stopnotifyblocks command extension for websocket connections.

func HandleStopNotifyNewTransactions

func HandleStopNotifyNewTransactions(wsc *WSClient, icmd interface{}) (interface{}, error)

handleStopNotifyNewTransations implements the stopnotifynewtransactions command extension for websocket connections.

func HandleStopNotifyReceived

func HandleStopNotifyReceived(wsc *WSClient, icmd interface{}) (interface{},
	error)

HandleStopNotifyReceived implements the stopnotifyreceived command extension for websocket connections.

func HandleStopNotifySpent

func HandleStopNotifySpent(wsc *WSClient, icmd interface{}) (interface{}, error)

HandleStopNotifySpent implements the stopnotifyspent command extension for websocket connections.

func HandleSubmitBlock

func HandleSubmitBlock(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleSubmitBlock implements the submitblock command.

func HandleUnimplemented

func HandleUnimplemented(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleUnimplemented is the handler for commands that should ultimately be supported but are not yet implemented.

func HandleUptime

func HandleUptime(s *Server, cmd interface{}, closeChan <-chan struct{}) (
	interface{}, error)

HandleUptime implements the uptime command.

func HandleValidateAddress

func HandleValidateAddress(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleValidateAddress implements the validateaddress command.

func HandleVerifyChain

func HandleVerifyChain(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleVerifyChain implements the verifychain command.

func HandleVerifyMessage

func HandleVerifyMessage(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleVerifyMessage implements the verifymessage command.

func HandleVersion

func HandleVersion(s *Server, cmd interface{},
	closeChan <-chan struct{}) (interface{}, error)

HandleVersion implements the version command. NOTE: This is a btcsuite extension ported from github.com/decred/dcrd.

func HandleWebsocketHelp

func HandleWebsocketHelp(wsc *WSClient, icmd interface{}) (interface{}, error)

HandleWebsocketHelp implements the help command for websocket connections.

func InitListeners

func InitListeners(config *pod.Config, activeNet *netparams.Params,
	aMgr *addrmgr.AddrManager, listenAddrs []string,
	services wire.ServiceFlag) ([]net.Listener, upnp.NAT, error)

InitListeners initializes the configured net listeners and adds any bound addresses to the address manager. Returns the listeners and a upnp.NAT interface, which is non-nil if UPnP is in use.

func InternalRPCError

func InternalRPCError(errStr, context string) *json.RPCError

InternalRPCError is a convenience function to convert an internal error to an RPC error with the appropriate code set. It also logs the error to the RPC server subsystem since internal errors really should not occur. The context parameter is only used in the log message and may be empty if it's not needed.

func JSONAuthFail

func JSONAuthFail(w http.ResponseWriter)

JSONAuthFail sends a message back to the client if the http auth is rejected.

func MergeCheckpoints

func MergeCheckpoints(defaultCheckpoints, additional []chaincfg.Checkpoint) []chaincfg.Checkpoint

MergeCheckpoints returns two slices of checkpoints merged into one slice such that the checkpoints are sorted by height. In the case the additional checkpoints contain a checkpoint with the same height as a checkpoint in the default checkpoints, the additional checkpoint will take precedence and overwrite the default one.

func MessageToHex

func MessageToHex(msg wire.Message) (string, error)

MessageToHex serializes a message to the wire protocol encoding using the latest protocol version and returns a hex-encoded string of the result.

func NewPeerConfig

func NewPeerConfig(sp *NodePeer) *peer.Config

NewPeerConfig returns the configuration for the given ServerPeer.

func NewRedeemingTxNotification

func NewRedeemingTxNotification(txHex string, index int,
	block *util.Block) ([]byte, error)

NewRedeemingTxNotification returns a new marshalled redeemingtx notification with the passed parameters.

func NoTxInfoError

func NoTxInfoError(txHash *chainhash.Hash) *json.RPCError

NoTxInfoError is a convenience function for returning a nicely formatted RPC error which indicates there is no information available for the provided transaction hash.

func NormalizeAddress

func NormalizeAddress(addr, defaultPort string) string

NormalizeAddress returns addr with the passed default port appended if there is not already a port specified.

func ParseListeners

func ParseListeners(addrs []string) ([]net.Addr, error)

ParseListeners determines whether each listen address is IPv4 and IPv6 and returns a slice of appropriate net.Addrs to listen on with TCP. It also properly detects addresses which apply to "all interfaces" and adds the address as both IPv4 and IPv6.

func PeerExists

func PeerExists(connMgr ServerConnManager, addr string, nodeID int32) bool

PeerExists determines if a certain peer is currently connected given information about all currently connected peers. Peer existence is determined using either a target address or node id.

func PickNoun

func PickNoun(n uint64, singular, plural string) string

PickNoun returns the singular or plural form of a noun depending on the count n.

func QueueHandler

func QueueHandler(in <-chan interface{}, out chan<- interface{},
	quit <-chan struct{})

QueueHandler manages a queue of empty interfaces, reading from in and sending the oldest unsent to out. This handler stops when either of the in or quit channels are closed, and closes out before returning, without waiting to send any variables still remaining in the queue.

func RandomUint16Number

func RandomUint16Number(max uint16) uint16

RandomUint16Number returns a random uint16 in a specified input range. Note that the range is in zeroth ordering; if you pass it 1800, you will get values from 0 to 1800.

func RecoverFromReorg

func RecoverFromReorg(chain *blockchain.BlockChain, minBlock, maxBlock int32,
	lastBlock *chainhash.Hash) ([]chainhash.Hash, error)

RecoverFromReorg attempts to recover from a detected reorganize during a rescan. It fetches a new range of block shas from the database and verifies that the new range of blocks is on the same fork as a previous range of blocks. If this condition does not hold true, the JSON-RPC error for an unrecoverable reorganize is returned.

func RescanBlock

func RescanBlock(wsc *WSClient, lookups *RescanKeys, blk *util.Block)

RescanBlock rescans all transactions in a single block. This is a helper function for handleRescan.

func RescanBlockFilter

func RescanBlockFilter(filter *WSClientFilter, block *util.Block,
	params *netparams.Params) []string

RescanBlockFilter rescans a block for any relevant transactions for the passed lookup keys. Any discovered transactions are returned hex encoded as a string slice. NOTE: This extension is ported from github.com/decred/dcrd

func ReverseUint32Array

func ReverseUint32Array(b []byte)

ReverseUint32Array treats the passed bytes as a series of uint32s and reverses the byte order of each uint32. The passed byte slice must be a multiple of 4 for a correct result. The passed bytes slice is modified.

func SetupRPCListeners

func SetupRPCListeners(config *pod.Config, urls []string) ([]net.Listener,
	error)

SetupRPCListeners returns a slice of listeners that are configured for use with the RPC server depending on the configuration settings for listen addresses and TLS.

func SoftForkStatus

func SoftForkStatus(state blockchain.ThresholdState) (string, error)

SoftForkStatus converts a ThresholdState state into a human readable string corresponding to the particular state.

func TxHexString

func TxHexString(tx *wire.MsgTx) string

TxHexString returns the serialized transaction encoded in hexadecimal.

func VerifyChain

func VerifyChain(s *Server, level, depth int32) error

VerifyChain does?

func WitnessToHex

func WitnessToHex(witness wire.TxWitness) []string

// handleDebugLevel handles debuglevel commands.

func handleDebugLevel(	s *RPCServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	c := cmd.(*json.DebugLevelCmd)
	// Special show command to list supported subsystems.
	if c.LevelSpec == "show" {
		return fmt.Sprintf("Supported subsystems %v",
			supportedSubsystems()), nil
	}
	err := parseAndSetDebugLevels(c.LevelSpec)
	if err != nil {
		return nil, &json.RPCError{
			Code:    json.ErrRPCInvalidParams.Code,
			Message: err.Error(),
		}
	}
	return "Done.", nil
}

WitnessToHex formats the passed witness stack as a slice of hex-encoded strings to be used in a JSON response.

Types

type BroadcastInventoryAdd

type BroadcastInventoryAdd RelayMsg

BroadcastInventoryAdd is a type used to declare that the InvVect it contains needs to be added to the rebroadcast map

type BroadcastInventoryDel

type BroadcastInventoryDel *wire.InvVect

BroadcastInventoryDel is a type used to declare that the InvVect it contains needs to be removed from the rebroadcast map

type BroadcastMsg

type BroadcastMsg struct {
	Message      wire.Message
	ExcludePeers []*NodePeer
}

BroadcastMsg provides the ability to house a bitcoin message to be broadcast to all connected peers except specified excluded peers.

type CFHeaderKV

type CFHeaderKV struct {
	BlockHash    chainhash.Hash
	FilterHeader chainhash.Hash
}

CFHeaderKV is a tuple of a filter header and its associated block hash. The struct is used to cache cfcheckpt responses.

type CheckpointSorter

type CheckpointSorter []chaincfg.Checkpoint

CheckpointSorter implements sort.Interface to allow a slice of checkpoints to be sorted.

func (CheckpointSorter) Len

func (s CheckpointSorter) Len() int

Len returns the number of checkpoints in the slice. It is part of the sort.Interface implementation.

func (CheckpointSorter) Less

func (s CheckpointSorter) Less(i, j int) bool
Less returns whether the checkpoint with index i should sort before the

checkpoint with index j. It is part of the sort.Interface implementation.

func (CheckpointSorter) Swap

func (s CheckpointSorter) Swap(i, j int)

Swap swaps the checkpoints at the passed indices. It is part of the sort.Interface implementation.

type CommandHandler

type CommandHandler func(*Server, interface{}, <-chan struct{}) (interface{}, error)

type ConnManager

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

ConnManager provides a connection manager for use with the RPC server and implements the rpcserver ConnManager interface.

func (*ConnManager) AddRebroadcastInventory

func (cm *ConnManager) AddRebroadcastInventory(iv *wire.InvVect,
	data interface{})

AddRebroadcastInventory adds the provided inventory to the list of inventories to be rebroadcast at random intervals until they show up in a block. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.

func (*ConnManager) BroadcastMessage

func (cm *ConnManager) BroadcastMessage(msg wire.Message)

BroadcastMessage sends the provided message to all currently connected peers. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.

func (*ConnManager) Connect

func (cm *ConnManager) Connect(addr string, permanent bool) error

Connect adds the provided address as a new outbound peer. The permanent flag indicates whether or not to make the peer persistent and reconnect if the connection is lost. Attempting to connect to an already existing peer will return an error. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.

func (*ConnManager) ConnectedCount

func (cm *ConnManager) ConnectedCount() int32

ConnectedCount returns the number of currently connected peers. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.

func (*ConnManager) ConnectedPeers

func (cm *ConnManager) ConnectedPeers() []ServerPeer

ConnectedPeers returns an array consisting of all connected peers. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.

func (*ConnManager) DisconnectByAddr

func (cm *ConnManager) DisconnectByAddr(addr string) error

DisconnectByAddr disconnects the peer associated with the provided address. This applies to both inbound and outbound peers. Attempting to remove an address that does not exist will return an error. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.

func (*ConnManager) DisconnectByID

func (cm *ConnManager) DisconnectByID(id int32) error

DisconnectByID disconnects the peer associated with the provided id. This applies to both inbound and outbound peers. Attempting to remove an id that does not exist will return an error. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.

func (*ConnManager) NetTotals

func (cm *ConnManager) NetTotals() (uint64, uint64)

NetTotals returns the sum of all bytes received and sent across the network for all peers. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.

func (*ConnManager) PersistentPeers

func (cm *ConnManager) PersistentPeers() []ServerPeer

PersistentPeers returns an array consisting of all the added persistent peers. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.

func (*ConnManager) RelayTransactions

func (cm *ConnManager) RelayTransactions(txns []*mempool.TxDesc)

RelayTransactions generates and relays inventory vectors for all of the passed transactions to all connected peers.

func (*ConnManager) RemoveByAddr

func (cm *ConnManager) RemoveByAddr(addr string) error

RemoveByAddr removes the peer associated with the provided address from the list of persistent peers. Attempting to remove an address that does not exist will return an error. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.

func (*ConnManager) RemoveByID

func (cm *ConnManager) RemoveByID(id int32) error

RemoveByID removes the peer associated with the provided id from the list of persistent peers. Attempting to remove an id that does not exist will return an error. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.

type ConnectNodeMsg

type ConnectNodeMsg struct {
	Addr      string
	Permanent bool
	Reply     chan error
}

type DisconnectNodeMsg

type DisconnectNodeMsg struct {
	Cmp   func(*NodePeer) bool
	Reply chan error
}

type GBTWorkState

type GBTWorkState struct {
	sync.Mutex
	LastTxUpdate  time.Time
	LastGenerated time.Time

	MinTimestamp time.Time
	Template     *mining.BlockTemplate
	NotifyMap    map[chainhash.Hash]map[int64]chan struct{}
	TimeSource   blockchain.MedianTimeSource
	Algo         string
	StateCfg     *state.Config
	Config       *pod.Config
	// contains filtered or unexported fields
}

GBTWorkState houses state that is used in between multiple RPC invocations to getblocktemplate.

func NewGbtWorkState

func NewGbtWorkState(timeSource blockchain.MedianTimeSource,
	algoName string) *GBTWorkState

NewGbtWorkState returns a new instance of a GBTWorkState with all internal fields initialized and ready to use.

func (*GBTWorkState) BlockTemplateResult

func (state *GBTWorkState) BlockTemplateResult(useCoinbaseValue bool, submitOld *bool) (
	*json.GetBlockTemplateResult,
	error,
)

BlockTemplateResult returns the current block template associated with the state as a json.GetBlockTemplateResult that is ready to be encoded to JSON and returned to the caller. This function MUST be called with the state locked.

func (*GBTWorkState) NotifyBlockConnected

func (state *GBTWorkState) NotifyBlockConnected(blockHash *chainhash.Hash)

NotifyBlockConnected uses the newly-connected block to notify any long poll clients with a new block template when their existing block template is stale due to the newly connected block.

func (*GBTWorkState) NotifyLongPollers

func (state *GBTWorkState) NotifyLongPollers(latestHash *chainhash.Hash,
	lastGenerated time.Time)

NotifyLongPollers notifies any channels that have been registered to be notified when block templates are stale. This function MUST be called with the state locked.

func (*GBTWorkState) NotifyMempoolTx

func (state *GBTWorkState) NotifyMempoolTx(lastUpdated time.Time)

NotifyMempoolTx uses the new last updated time for the transaction memory pool to notify any long poll clients with a new block template when their existing block template is stale due to enough time passing and the contents of the memory pool changing.

func (*GBTWorkState) TemplateUpdateChan

func (state *GBTWorkState) TemplateUpdateChan(prevHash *chainhash.Hash, lastGenerated int64) chan struct{}

TemplateUpdateChan returns a channel that will be closed once the block template associated with the passed previous hash and last generated time is stale. The function will return existing channels for duplicate parameters which allows to wait for the same block template without requiring a different channel for each client. This function MUST be called with the state locked.

func (*GBTWorkState) UpdateBlockTemplate

func (state *GBTWorkState) UpdateBlockTemplate(s *Server,
	useCoinbaseValue bool) error

UpdateBlockTemplate creates or updates a block template for the work state. A new block template will be generated when the current best block has changed or the transactions in the memory pool have been updated and it has been long enough since the last template was generated. Otherwise, the timestamp for the existing block template is updated (and possibly the difficulty on testnet per the consesus rules). Finally, if the useCoinbaseValue flag is false and the existing block template does not already contain a valid payment address, the block template will be updated with a randomly selected payment address from the list of configured addresses. This function MUST be called with the state locked.

type GetAddedNodesMsg

type GetAddedNodesMsg struct {
	Reply chan []*NodePeer
}

type GetConnCountMsg

type GetConnCountMsg struct {
	Reply chan int32
}

type GetOutboundGroup

type GetOutboundGroup struct {
	Key   string
	Reply chan int
}

type GetPeersMsg

type GetPeersMsg struct {
	Reply chan []*NodePeer
}

type HelpCacher

type HelpCacher struct {
	sync.Mutex
	// contains filtered or unexported fields
}

HelpCacher provides a concurrent safe type that provides help and usage for the RPC server commands and caches the results for future calls.

func NewHelpCacher

func NewHelpCacher() *HelpCacher

NewHelpCacher returns a new instance of a help cacher which provides help and usage for the RPC server commands and caches the results for future calls.

func (*HelpCacher) RPCMethodHelp

func (c *HelpCacher) RPCMethodHelp(method string) (string, error)

RPCMethodHelp returns an RPC help string for the provided method. This function is safe for concurrent access.

func (*HelpCacher) RPCUsage

func (c *HelpCacher) RPCUsage(includeWebsockets bool) (string, error)

RPCUsage returns one-line usage for all support RPC commands. This function is safe for concurrent access.

type Node

type Node struct {
	// The following variables must only be used atomically. Putting the
	// uint64s first makes them 64-bit aligned for 32-bit systems.
	BytesReceived        uint64 // Total bytes received from all peers since start.
	BytesSent            uint64 // Total bytes sent by all peers since start.
	StartupTime          int64
	ChainParams          *netparams.Params
	AddrManager          *addrmgr.AddrManager
	ConnManager          *connmgr.ConnManager
	SigCache             *txscript.SigCache
	HashCache            *txscript.HashCache
	RPCServers           []*Server
	SyncManager          *netsync.SyncManager
	Chain                *blockchain.BlockChain
	TxMemPool            *mempool.TxPool
	CPUMiner             *cpuminer.CPUMiner
	ModifyRebroadcastInv chan interface{}
	NewPeers             chan *NodePeer
	DonePeers            chan *NodePeer
	BanPeers             chan *NodePeer
	Query                chan interface{}
	RelayInv             chan RelayMsg
	Broadcast            chan BroadcastMsg
	PeerHeightsUpdate    chan UpdatePeerHeightsMsg
	WG                   sync.WaitGroup
	Quit                 chan struct{}
	NAT                  upnp.NAT
	DB                   database.DB
	TimeSource           blockchain.MedianTimeSource
	Services             wire.ServiceFlag
	// The following fields are used for optional indexes.  They will be nil
	// if the associated index is not enabled.  These fields are set during
	// initial creation of the server and never changed afterwards, so they
	// do not need to be protected for concurrent access.
	TxIndex   *indexers.TxIndex
	AddrIndex *indexers.AddrIndex
	CFIndex   *indexers.CFIndex
	// The fee estimator keeps track of how long transactions are left in
	// the mempool before they are mined into blocks.
	FeeEstimator *mempool.FeeEstimator
	// CFCheckptCaches stores a cached slice of filter headers for
	// cfcheckpt messages for each filter type.
	CFCheckptCaches    map[wire.FilterType][]CFHeaderKV
	CFCheckptCachesMtx sync.RWMutex
	Algo               string
	Config             *pod.Config
	ActiveNet          *netparams.Params
	StateCfg           *state.Config
	GenThreads         uint32
	Started            int32
	Shutdown           int32
	ShutdownSched      int32
}

Node provides a bitcoin Node for handling communications to and from bitcoin peers.

func NewNode

func NewNode(config *pod.Config, stateCfg *state.Config,
	activeNet *netparams.Params, listenAddrs []string, db database.DB,
	chainParams *netparams.Params, interruptChan <-chan struct{},
	algo string) (*Node, error)

NewNode returns a new pod server configured to listen on addr for the bitcoin network type specified by chainParams. Use start to begin accepting connections from peers. TODO: simplify/modularise this nolint

func (*Node) AddBytesReceived

func (s *Node) AddBytesReceived(bytesReceived uint64)

AddBytesReceived adds the passed number of bytes to the total bytes received counter for the server. It is safe for concurrent access.

func (*Node) AddBytesSent

func (s *Node) AddBytesSent(bytesSent uint64)

AddBytesSent adds the passed number of bytes to the total bytes sent counter for the server. It is safe for concurrent access.

func (*Node) AddPeer

func (s *Node) AddPeer(sp *NodePeer)

AddPeer adds a new peer that has already been connected to the server.

func (*Node) AddRebroadcastInventory

func (s *Node) AddRebroadcastInventory(iv *wire.InvVect, data interface{})

AddRebroadcastInventory adds 'iv' to the list of inventories to be rebroadcasted at random intervals until they show up in a block.

func (*Node) AnnounceNewTransactions

func (s *Node) AnnounceNewTransactions(txns []*mempool.TxDesc)

AnnounceNewTransactions generates and relays inventory vectors and notifies both websocket and getblocktemplate long poll clients of the passed transactions. This function should be called whenever new transactions are added to the mempool.

func (*Node) BanPeer

func (s *Node) BanPeer(sp *NodePeer)

BanPeer bans a peer that has already been connected to the server by ip.

func (*Node) BroadcastMessage

func (s *Node) BroadcastMessage(msg wire.Message, exclPeers ...*NodePeer)

BroadcastMessage sends msg to all peers currently connected to the server except those in the passed peers to exclude.

func (*Node) ConnectedCount

func (s *Node) ConnectedCount() int32

ConnectedCount returns the number of currently connected peers.

func (*Node) HandleAddPeerMsg

func (s *Node) HandleAddPeerMsg(state *PeerState, sp *NodePeer) bool

HandleAddPeerMsg deals with adding new peers. It is invoked from the peerHandler goroutine.

func (*Node) HandleBanPeerMsg

func (s *Node) HandleBanPeerMsg(state *PeerState, sp *NodePeer)

HandleBanPeerMsg deals with banning peers. It is invoked from the peerHandler goroutine.

func (*Node) HandleBroadcastMsg

func (s *Node) HandleBroadcastMsg(state *PeerState, bmsg *BroadcastMsg)

HandleBroadcastMsg deals with broadcasting messages to peers. It is invoked from the peerHandler goroutine.

func (*Node) HandleDonePeerMsg

func (s *Node) HandleDonePeerMsg(state *PeerState, sp *NodePeer)

HandleDonePeerMsg deals with peers that have signalled they are done. It is invoked from the peerHandler goroutine.

func (*Node) HandleQuery

func (s *Node) HandleQuery(state *PeerState, querymsg interface{})

HandleQuery is the central handler for all queries and commands from other goroutines related to peer state.

func (*Node) HandleRelayInvMsg

func (s *Node) HandleRelayInvMsg(state *PeerState, msg RelayMsg)

HandleRelayInvMsg deals with relaying inventory to peers that are not already known to have it. It is invoked from the peerHandler goroutine.

func (*Node) HandleUpdatePeerHeights

func (s *Node) HandleUpdatePeerHeights(state *PeerState,
	umsg UpdatePeerHeightsMsg)

handleUpdatePeerHeight updates the heights of all peers who were known to announce a block we recently accepted.

func (*Node) InboundPeerConnected

func (s *Node) InboundPeerConnected(conn net.Conn)

InboundPeerConnected is invoked by the connection manager when a new inbound connection is established. It initializes a new inbound server peer instance, associates it with the connection, and starts a goroutine to wait for disconnection.

func (*Node) NetTotals

func (s *Node) NetTotals() (uint64, uint64)

NetTotals returns the sum of all bytes received and sent across the network for all peers. It is safe for concurrent access.

func (*Node) OutboundGroupCount

func (s *Node) OutboundGroupCount(
	key string) int

OutboundGroupCount returns the number of peers connected to the given outbound group key.

func (*Node) OutboundPeerConnected

func (s *Node) OutboundPeerConnected(c *connmgr.ConnReq, conn net.Conn)

OutboundPeerConnected is invoked by the connection manager when a new outbound connection is established. It initializes a new outbound server peer instance, associates it with the relevant state such as the connection request instance and the connection itself, and finally notifies the address manager of the attempt.

func (*Node) PeerDoneHandler

func (s *Node) PeerDoneHandler(sp *NodePeer)

PeerDoneHandler handles peer disconnects by notifiying the server that it's done along with other performing other desirable cleanup.

func (*Node) PeerHandler

func (s *Node) PeerHandler()

PeerHandler is used to handle peer operations such as adding and removing peers to and from the server, banning peers, and broadcasting messages to peers. It must be run in a goroutine.

func (*Node) PushBlockMsg

func (s *Node) PushBlockMsg(sp *NodePeer, hash *chainhash.Hash,
	doneChan chan<- struct{}, waitChan <-chan struct{},
	encoding wire.MessageEncoding) error

PushBlockMsg sends a block message for the provided block hash to the connected peer. An error is returned if the block hash is not known.

func (*Node) PushMerkleBlockMsg

func (s *Node) PushMerkleBlockMsg(sp *NodePeer, hash *chainhash.Hash,
	doneChan chan<- struct{}, waitChan <-chan struct{},
	encoding wire.MessageEncoding) error

PushMerkleBlockMsg sends a merkleblock message for the provided block hash to the connected peer. Since a merkle block requires the peer to have a filter loaded, this call will simply be ignored if there is no filter loaded. An error is returned if the block hash is not known.

func (*Node) PushTxMsg

func (s *Node) PushTxMsg(sp *NodePeer, hash *chainhash.Hash,
	doneChan chan<- struct{}, waitChan <-chan struct{},
	encoding wire.MessageEncoding) error

PushTxMsg sends a tx message for the provided transaction hash to the connected peer. An error is returned if the transaction hash is not known.

func (*Node) RebroadcastHandler

func (s *Node) RebroadcastHandler()

RebroadcastHandler keeps track of user submitted inventories that we have sent out but have not yet made it into a block. We periodically rebroadcast them in case our peers restarted or otherwise lost track of them.

func (*Node) RelayInventory

func (s *Node) RelayInventory(invVect *wire.InvVect, data interface{})

RelayInventory relays the passed inventory vector to all connected peers that are not already known to have it.

func (*Node) RelayTransactions

func (s *Node) RelayTransactions(txns []*mempool.TxDesc)

RelayTransactions generates and relays inventory vectors for all of the passed transactions to all connected peers.

func (*Node) RemoveRebroadcastInventory

func (s *Node) RemoveRebroadcastInventory(iv *wire.InvVect)

RemoveRebroadcastInventory removes 'iv' from the list of items to be rebroadcasted if present.

func (*Node) ScheduleShutdown

func (s *Node) ScheduleShutdown(duration time.Duration)

ScheduleShutdown schedules a server shutdown after the specified duration. It also dynamically adjusts how often to warn the server is going down based on remaining duration.

func (*Node) Start

func (s *Node) Start()

Start begins accepting connections from peers.

func (*Node) Stop

func (s *Node) Stop() error

Stop gracefully shuts down the server by stopping and disconnecting all peers and the main listener.

func (*Node) TransactionConfirmed

func (s *Node) TransactionConfirmed(tx *util.Tx)

Transaction has one confirmation on the main chain. Now we can mark it as no longer needing rebroadcasting.

func (*Node) UPNPUpdateThread

func (s *Node) UPNPUpdateThread()

func (*Node) UpdatePeerHeights

func (s *Node) UpdatePeerHeights(latestBlkHash *chainhash.Hash,
	latestHeight int32, updateSource *peer.Peer)

UpdatePeerHeights updates the heights of all peers who have have announced the latest connected main chain block, or a recognized orphan. These height updates allow us to dynamically refresh peer heights, ensuring sync peer selection has access to the latest block heights for each peer.

func (*Node) WaitForShutdown

func (s *Node) WaitForShutdown()

WaitForShutdown blocks until the main listener and peer handlers are stopped.

type NodePeer

type NodePeer struct {
	*peer.Peer
	// The following variables must only be used atomically
	FeeFilter      int64
	ConnReq        *connmgr.ConnReq
	Server         *Node
	ContinueHash   *chainhash.Hash
	RelayMtx       sync.Mutex
	Filter         *bloom.Filter
	KnownAddresses map[string]struct{}
	BanScore       connmgr.DynamicBanScore
	Quit           chan struct{}
	// The following chans are used to sync blockmanager and server.
	TxProcessed    chan struct{}
	BlockProcessed chan struct{}
	SentAddrs      bool
	IsWhitelisted  bool
	Persistent     bool
	DisableRelayTx bool
}

NodePeer extends the peer to maintain state shared by the server and the blockmanager.

func NewServerPeer

func NewServerPeer(s *Node, isPersistent bool) *NodePeer

NewServerPeer returns a new ServerPeer instance. The peer needs to be set by the caller.

func (*NodePeer) AddBanScore

func (sp *NodePeer) AddBanScore(persistent, transient uint32, reason string)

AddBanScore increases the persistent and decaying ban score fields by the values passed as parameters. If the resulting score exceeds half of the ban threshold, a warning is logged including the reason provided. Further, if the score is above the ban threshold, the peer will be banned and disconnected.

func (*NodePeer) AddKnownAddresses

func (sp *NodePeer) AddKnownAddresses(addresses []*wire.NetAddress)

AddKnownAddresses adds the given addresses to the set of known addresses to the peer to prevent sending duplicate addresses.

func (*NodePeer) EnforceNodeBloomFlag

func (sp *NodePeer) EnforceNodeBloomFlag(cmd string) bool

EnforceNodeBloomFlag disconnects the peer if the server is not configured to allow bloom filters. Additionally, if the peer has negotiated to a protocol version that is high enough to observe the bloom filter service support bit, it will be banned since it is intentionally violating the protocol.

func (*NodePeer) GetNewestBlock

func (sp *NodePeer) GetNewestBlock() (*chainhash.Hash, int32, error)

GetNewestBlock returns the current best block hash and height using the format required by the configuration for the peer package.

func (*NodePeer) IsAddressKnown

func (sp *NodePeer) IsAddressKnown(na *wire.NetAddress) bool

IsAddressKnown true if the given address is already known to the peer.

func (*NodePeer) IsRelayTxDisabled

func (sp *NodePeer) IsRelayTxDisabled() bool

IsRelayTxDisabled returns whether or not relaying of transactions for the given peer is disabled. It is safe for concurrent access.

func (*NodePeer) OnAddr

func (sp *NodePeer) OnAddr(_ *peer.Peer, msg *wire.MsgAddr)

OnAddr is invoked when a peer receives an addr bitcoin message and is used to notify the server about advertised addresses.

func (*NodePeer) OnBlock

func (sp *NodePeer) OnBlock(_ *peer.Peer, msg *wire.MsgBlock, buf []byte)

OnBlock is invoked when a peer receives a block bitcoin message. It blocks until the bitcoin block has been fully processed.

func (*NodePeer) OnFeeFilter

func (sp *NodePeer) OnFeeFilter(_ *peer.Peer, msg *wire.MsgFeeFilter)

OnFeeFilter is invoked when a peer receives a feefilter bitcoin message and is used by remote peers to request that no transactions which have a fee rate lower than provided value are inventoried to them. The peer will be disconnected if an invalid fee filter value is provided.

func (*NodePeer) OnFilterAdd

func (sp *NodePeer) OnFilterAdd(_ *peer.Peer, msg *wire.MsgFilterAdd)

OnFilterAdd is invoked when a peer receives a filteradd bitcoin message and is used by remote peers to add data to an already loaded bloom filter. The peer will be disconnected if a filter is not loaded when this message is received or the server is not configured to allow bloom filters.

func (*NodePeer) OnFilterClear

func (sp *NodePeer) OnFilterClear(_ *peer.Peer, msg *wire.MsgFilterClear)

OnFilterClear is invoked when a peer receives a filterclear bitcoin message and is used by remote peers to clear an already loaded bloom filter. The peer will be disconnected if a filter is not loaded when this message is received or the server is not configured to allow bloom filters.

func (*NodePeer) OnFilterLoad

func (sp *NodePeer) OnFilterLoad(_ *peer.Peer, msg *wire.MsgFilterLoad)

OnFilterLoad is invoked when a peer receives a filterload bitcoin message and it used to load a bloom filter that should be used for delivering merkle blocks and associated transactions that match the filter. The peer will be disconnected if the server is not configured to allow bloom filters.

func (*NodePeer) OnGetAddr

func (sp *NodePeer) OnGetAddr(_ *peer.Peer, msg *wire.MsgGetAddr)

OnGetAddr is invoked when a peer receives a getaddr bitcoin message and is used to provide the peer with known addresses from the address manager.

func (*NodePeer) OnGetBlocks

func (sp *NodePeer) OnGetBlocks(_ *peer.Peer, msg *wire.MsgGetBlocks)

OnGetBlocks is invoked when a peer receives a getblocks bitcoin message.

func (*NodePeer) OnGetCFCheckpt

func (sp *NodePeer) OnGetCFCheckpt(_ *peer.Peer, msg *wire.MsgGetCFCheckpt)

OnGetCFCheckpt is invoked when a peer receives a getcfcheckpt bitcoin message.

func (*NodePeer) OnGetCFHeaders

func (sp *NodePeer) OnGetCFHeaders(_ *peer.Peer, msg *wire.MsgGetCFHeaders)

OnGetCFHeaders is invoked when a peer receives a getcfheader bitcoin message.

func (*NodePeer) OnGetCFilters

func (sp *NodePeer) OnGetCFilters(_ *peer.Peer, msg *wire.MsgGetCFilters)

OnGetCFilters is invoked when a peer receives a getcfilters bitcoin message.

func (*NodePeer) OnGetData

func (sp *NodePeer) OnGetData(_ *peer.Peer, msg *wire.MsgGetData)

handleGetData is invoked when a peer receives a getdata bitcoin message and is used to deliver block and transaction information.

func (*NodePeer) OnGetHeaders

func (sp *NodePeer) OnGetHeaders(_ *peer.Peer, msg *wire.MsgGetHeaders)

OnGetHeaders is invoked when a peer receives a getheaders bitcoin message.

func (*NodePeer) OnHeaders

func (sp *NodePeer) OnHeaders(_ *peer.Peer, msg *wire.MsgHeaders)

OnHeaders is invoked when a peer receives a headers bitcoin message. The message is passed down to the sync manager.

func (*NodePeer) OnInv

func (sp *NodePeer) OnInv(
	_ *peer.Peer, msg *wire.MsgInv)

OnInv is invoked when a peer receives an inv bitcoin message and is used to examine the inventory being advertised by the remote peer and react accordingly. We pass the message down to blockmanager which will call QueueMessage with any appropriate responses.

func (*NodePeer) OnMemPool

func (sp *NodePeer) OnMemPool(_ *peer.Peer, msg *wire.MsgMemPool)

OnMemPool is invoked when a peer receives a mempool bitcoin message. It creates and sends an inventory message with the contents of the memory pool up to the maximum inventory allowed per message. When the peer has a bloom filter loaded, the contents are filtered accordingly.

func (*NodePeer) OnRead

func (sp *NodePeer) OnRead(_ *peer.Peer, bytesRead int, msg wire.Message,
	err error)

OnRead is invoked when a peer receives a message and it is used to update the bytes received by the server.

func (*NodePeer) OnTx

func (sp *NodePeer) OnTx(
	_ *peer.Peer, msg *wire.MsgTx)

OnTx is invoked when a peer receives a tx bitcoin message. It blocks until the bitcoin transaction has been fully processed. Unlock the block handler this does not serialize all transactions through a single thread transactions don't rely on the previous one in a linear fashion like blocks.

func (*NodePeer) OnVersion

func (sp *NodePeer) OnVersion(
	_ *peer.Peer, msg *wire.MsgVersion) *wire.MsgReject

OnVersion is invoked when a peer receives a version bitcoin message and is used to negotiate the protocol version details as well as kick start the communications.

func (*NodePeer) OnWrite

func (sp *NodePeer) OnWrite(_ *peer.Peer, bytesWritten int, msg wire.Message,
	err error)

OnWrite is invoked when a peer sends a message and it is used to update the bytes sent by the server.

func (*NodePeer) PreparePushAddrMsg

func (sp *NodePeer) PreparePushAddrMsg(addresses []*wire.NetAddress)

PreparePushAddrMsg sends an addr message to the connected peer using the provided addresses.

func (*NodePeer) SetDisableRelayTx

func (sp *NodePeer) SetDisableRelayTx(disable bool)

SetDisableRelayTx toggles relaying of transactions for the given peer. It is safe for concurrent access.

type NotificationBlockConnected

type NotificationBlockConnected util.Block

Notification types

type NotificationBlockDisconnected

type NotificationBlockDisconnected util.Block

type NotificationRegisterAddr

type NotificationRegisterAddr struct {
	WSC   *WSClient
	Addrs []string
}

type NotificationRegisterBlocks

type NotificationRegisterBlocks WSClient

type NotificationRegisterClient

type NotificationRegisterClient WSClient

Notification control requests

type NotificationRegisterNewMempoolTxs

type NotificationRegisterNewMempoolTxs WSClient

type NotificationRegisterSpent

type NotificationRegisterSpent struct {
	WSC *WSClient
	OPs []*wire.OutPoint
}

type NotificationTxAcceptedByMempool

type NotificationTxAcceptedByMempool struct {
	IsNew bool
	Tx    *util.Tx
}

type NotificationUnregisterAddr

type NotificationUnregisterAddr struct {
	WSC  *WSClient
	Addr string
}

type NotificationUnregisterBlocks

type NotificationUnregisterBlocks WSClient

type NotificationUnregisterClient

type NotificationUnregisterClient WSClient

type NotificationUnregisterNewMempoolTxs

type NotificationUnregisterNewMempoolTxs WSClient

type NotificationUnregisterSpent

type NotificationUnregisterSpent struct {
	WSC *WSClient
	OP  *wire.OutPoint
}

type OnionAddr

type OnionAddr struct {
	Addr string
}

OnionAddr implements the net.Addr interface and represents a tor address.

func (*OnionAddr) Network

func (oa *OnionAddr) Network() string

Network returns "onion". This is part of the net.Addr interface.

func (*OnionAddr) String

func (oa *OnionAddr) String() string

String returns the onion address. This is part of the net.Addr interface.

type ParsedRPCCmd

type ParsedRPCCmd struct {
	ID     interface{}
	Method string
	Cmd    interface{}
	Err    *json.RPCError
}

ParsedRPCCmd represents a JSON-RPC request object that has been parsed into a known concrete command along with any error that might have happened while parsing it.

func ParseCmd

func ParseCmd(request *json.Request) *ParsedRPCCmd

ParseCmd parses a JSON-RPC request object into known concrete command. The err field of the returned ParsedRPCCmd struct will contain an RPC error that is suitable for use in replies if the command is invalid in some way such as an unregistered command or invalid parameters.

type Peer

type Peer NodePeer

Peer provides a peer for use with the RPC server and implements the RPCServerPeer interface.

func (*Peer) GetBanScore

func (p *Peer) GetBanScore() uint32

GetBanScore returns the current integer value that represents how close the peer is to being banned. This function is safe for concurrent access and is part of the RPCServerPeer interface implementation.

func (*Peer) GetFeeFilter

func (p *Peer) GetFeeFilter() int64

GetFeeFilter returns the requested current minimum fee rate for which transactions should be announced. This function is safe for concurrent access and is part of the RPCServerPeer interface implementation.

func (*Peer) IsTxRelayDisabled

func (p *Peer) IsTxRelayDisabled() bool

IsTxRelayDisabled returns whether or not the peer has disabled transaction relay. This function is safe for concurrent access and is part of the RPCServerPeer interface implementation.

func (*Peer) ToPeer

func (p *Peer) ToPeer() *peer.Peer

ToPeer returns the underlying peer instance. This function is safe for concurrent access and is part of the RPCServerPeer interface implementation.

type PeerState

type PeerState struct {
	InboundPeers    map[int32]*NodePeer
	OutboundPeers   map[int32]*NodePeer
	PersistentPeers map[int32]*NodePeer
	Banned          map[string]time.Time
	OutboundGroups  map[string]int
}

PeerState maintains state of inbound, persistent, outbound peers as well as banned peers and outbound groups.

func (*PeerState) Count

func (ps *PeerState) Count() int

Count returns the count of all known peers.

func (*PeerState) ForAllOutboundPeers

func (ps *PeerState) ForAllOutboundPeers(closure func(sp *NodePeer))

ForAllOutboundPeers is a helper function that runs closure on all outbound peers known to peerState.

func (*PeerState) ForAllPeers

func (ps *PeerState) ForAllPeers(closure func(sp *NodePeer))

ForAllPeers is a helper function that runs closure on all peers known to peerState.

type RelayMsg

type RelayMsg struct {
	InvVect *wire.InvVect
	Data    interface{}
}

RelayMsg packages an inventory vector along with the newly discovered inventory so the relay has access to that information.

type RemoveNodeMsg

type RemoveNodeMsg struct {
	Cmp   func(*NodePeer) bool
	Reply chan error
}

type RescanKeys

type RescanKeys struct {
	Fallbacks           map[string]struct{}
	PubKeyHashes        map[[ripemd160.Size]byte]struct{}
	ScriptHashes        map[[ripemd160.Size]byte]struct{}
	CompressedPubKeys   map[[33]byte]struct{}
	UncompressedPubKeys map[[65]byte]struct{}
	Unspent             map[wire.OutPoint]struct{}
}

func (*RescanKeys) UnspentSlice

func (r *RescanKeys) UnspentSlice() []*wire.OutPoint

UnspentSlice returns a slice of currently-unspent outpoints for the rescan lookup keys. This is primarily intended to be used to register outpoints for continuous notifications after a rescan has completed.

type RetrievedTx

type RetrievedTx struct {
	TxBytes []byte
	BlkHash *chainhash.Hash // Only set when transaction is in a block.
	Tx      *util.Tx
}

RetrievedTx represents a transaction that was either loaded from the transaction memory pool or from the database. When a transaction is loaded from the database, it is loaded with the raw serialized bytes while the mempool has the fully deserialized structure. This structure therefore will have one of the two fields set depending on where is was retrieved from. This is mainly done for efficiency to avoid extra serialization steps when possible.

type Semaphore

type Semaphore chan struct{}

func MakeSemaphore

func MakeSemaphore(n int) Semaphore

func (Semaphore) Acquire

func (s Semaphore) Acquire()

func (Semaphore) Release

func (s Semaphore) Release()

type Server

type Server struct {
	Cfg                    ServerConfig
	StateCfg               *state.Config
	Config                 *pod.Config
	NtfnMgr                *WSNtfnMgr
	StatusLines            map[int]string
	StatusLock             sync.RWMutex
	WG                     sync.WaitGroup
	GBTWorkState           *GBTWorkState
	HelpCacher             *HelpCacher
	RequestProcessShutdown chan struct{}
	Quit                   chan int
	Started                int32
	Shutdown               int32
	NumClients             int32
	AuthSHA                [sha256.Size]byte
	LimitAuthSHA           [sha256.Size]byte
}

Server provides a concurrent safe RPC server to a chain server.

func NewRPCServer

func NewRPCServer(config *ServerConfig, statecfg *state.Config,
	podcfg *pod.Config) (*Server, error)

NewRPCServer returns a new instance of the RPCServer struct.

func (*Server) CheckAuth

func (s *Server) CheckAuth(r *http.Request, require bool) (bool, bool, error)

CheckAuth checks the HTTP Basic authentication supplied by a wallet or RPC client in the HTTP request r. If the supplied authentication does not match the username and password expected, a non-nil error is returned. This check is time-constant. The first bool return value signifies auth success ( true if successful) and the second bool return value specifies whether the user can change the state of the server (true) or whether the user is limited (false). The second is always false if the first is.

func (*Server) DecrementClients

func (s *Server) DecrementClients()

DecrementClients subtracts one from the number of connected RPC clients. Note this only applies to standard clients. Websocket clients have their own limits and are tracked separately. This function is safe for concurrent access.

func (*Server) HTTPStatusLine

func (s *Server) HTTPStatusLine(req *http.Request, code int) string

HTTPStatusLine returns a response Status-Line (RFC 2616 Section 6.1) for the given request and response status code. This function was lifted and adapted from the standard library HTTP server code since it's not exported.

func (*Server) HandleBlockchainNotification

func (s *Server) HandleBlockchainNotification(notification *blockchain.Notification)

Callback for notifications from blockchain. It notifies clients that are long polling for changes or subscribed to websockets notifications.

func (*Server) IncrementClients

func (s *Server) IncrementClients()

IncrementClients adds one to the number of connected RPC clients. Note this only applies to standard clients. Websocket clients have their own limits and are tracked separately. This function is safe for concurrent access.

func (*Server) JSONRPCRead

func (s *Server) JSONRPCRead(w http.ResponseWriter, r *http.Request, isAdmin bool)

JSONRPCRead handles reading and responding to RPC messages.

func (*Server) LimitConnections

func (s *Server) LimitConnections(w http.ResponseWriter, remoteAddr string) bool

LimitConnections responds with a 503 service unavailable and returns true if adding another client would exceed the maximum allow RPC clients. This function is safe for concurrent access.

func (*Server) NotifyNewTransactions

func (s *Server) NotifyNewTransactions(txns []*mempool.TxDesc)

NotifyNewTransactions notifies both websocket and getblocktemplate long poll clients of the passed transactions. This function should be called whenever new transactions are added to the mempool.

func (*Server) RequestedProcessShutdown

func (s *Server) RequestedProcessShutdown() <-chan struct{}

RequestedProcessShutdown returns a channel that is sent to when an authorized RPC client requests the process to shutdown. If the request can not be read immediately, it is dropped.

func (*Server) StandardCmdResult

func (s *Server) StandardCmdResult(cmd *ParsedRPCCmd,
	closeChan <-chan struct{}) (interface{}, error)

StandardCmdResult checks that a parsed command is a standard Bitcoin JSON-RPC command and runs the appropriate handler to reply to the command. Any commands which are not recognized or not implemented will return an error suitable for use in replies.

func (*Server) Start

func (s *Server) Start()

Start is used by server.go to start the rpc listener.

func (*Server) Stop

func (s *Server) Stop() error

Stop is used by server.go to stop the rpc listener.

func (*Server) WebsocketHandler

func (s *Server) WebsocketHandler(conn *websocket.Conn, remoteAddr string,
	authenticated bool, isAdmin bool)

WebsocketHandler handles a new websocket client by creating a new wsClient, starting it, and blocking until the connection closes. Since it blocks, it must be run in a separate goroutine. It should be invoked from the websocket server handler which runs each new connection in a new goroutine thereby satisfying the requirement.

func (*Server) WriteHTTPResponseHeaders

func (s *Server) WriteHTTPResponseHeaders(req *http.Request,
	headers http.Header, code int, w io.Writer) error

WriteHTTPResponseHeaders writes the necessary response headers prior to writing an HTTP body given a request to use for protocol negotiation, headers to write, a status code, and a writer.

type ServerConfig

type ServerConfig struct {
	// Listeners defines a slice of listeners for which the RPC server will
	// take ownership of and accept connections.
	// Since the RPC server takes ownership of these listeners,
	// they will be closed when the RPC server is stopped.
	Listeners []net.Listener
	// StartupTime is the unix timestamp for when the server that is hosting
	// the RPC server started.
	StartupTime int64
	// ConnMgr defines the connection manager for the RPC server to use.
	// It provides the RPC server with a means to do things such as add,
	// remove, connect, disconnect,
	// and query peers as well as other connection-related data and tasks.
	ConnMgr ServerConnManager
	// SyncMgr defines the sync manager for the RPC server to use.
	SyncMgr ServerSyncManager
	// These fields allow the RPC server to interface with the local block
	// chain data and state.
	TimeSource  blockchain.MedianTimeSource
	Chain       *blockchain.BlockChain
	ChainParams *netparams.Params
	DB          database.DB
	// TxMemPool defines the transaction memory pool to interact with.
	TxMemPool *mempool.TxPool
	// These fields allow the RPC server to interface with mining.
	// Generator produces block templates and the CPUMiner solves them using
	// the CPU.
	// CPU mining is typically only useful for test purposes when doing
	// regression or simulation testing.
	Generator *mining.BlkTmplGenerator
	CPUMiner  *cpuminer.CPUMiner
	// These fields define any optional indexes the RPC server can make use
	// of to provide additional data when queried.
	TxIndex   *indexers.TxIndex
	AddrIndex *indexers.AddrIndex
	CfIndex   *indexers.CFIndex
	// The fee estimator keeps track of how long transactions are left in the
	// mempool before they are mined into blocks.
	FeeEstimator *mempool.FeeEstimator
	// Algo sets the algorithm expected from the RPC endpoint. This allows
	// multiple ports to serve multiple types of miners with one main node per
	// algorithm. Currently 514 for scrypt and anything else passes for sha256d.
	Algo string
}

ServerConfig is a descriptor containing the RPC server configuration.

type ServerConnManager

type ServerConnManager interface {
	// Connect adds the provided address as a new outbound peer.
	// The permanent flag indicates whether or not to make the peer
	// persistent and reconnect if the connection is lost.
	// Attempting to connect to an already existing peer will return an error.
	Connect(addr string, permanent bool) error
	// RemoveByID removes the peer associated with the provided id from the
	// list of persistent peers.
	// Attempting to remove an id that does not exist will return an error.
	RemoveByID(id int32) error
	// RemoveByAddr removes the peer associated with the provided address
	// from the list of persistent peers.
	// Attempting to remove an address that does not exist will return an error.
	RemoveByAddr(addr string) error
	// DisconnectByID disconnects the peer associated with the provided id.
	// This applies to both inbound and outbound peers.
	// Attempting to remove an id that does not exist will return an error.
	DisconnectByID(id int32) error
	// DisconnectByAddr disconnects the peer associated with the provided
	// address.  This applies to both inbound and outbound peers.
	// Attempting to remove an address that does not exist will return an error.
	DisconnectByAddr(addr string) error
	// ConnectedCount returns the number of currently connected peers.
	ConnectedCount() int32
	// NetTotals returns the sum of all bytes received and sent across the
	// network for all peers.
	NetTotals() (uint64, uint64)
	// ConnectedPeers returns an array consisting of all connected peers.
	ConnectedPeers() []ServerPeer
	// PersistentPeers returns an array consisting of all the persistent peers.
	PersistentPeers() []ServerPeer
	// BroadcastMessage sends the provided message to all currently connected
	// peers.
	BroadcastMessage(msg wire.Message)
	// AddRebroadcastInventory adds the provided inventory to the list of
	// inventories to be rebroadcast at random intervals until they show up
	// in a block.
	AddRebroadcastInventory(iv *wire.InvVect, data interface{})
	// RelayTransactions generates and relays inventory vectors for all of
	// the passed transactions to all connected peers.
	RelayTransactions(txns []*mempool.TxDesc)
}

ServerConnManager represents a connection manager for use with the RPC server. The interface contract requires that all of these methods are safe for concurrent access.

type ServerPeer

type ServerPeer interface {
	// ToPeer returns the underlying peer instance.
	ToPeer() *p.Peer
	// IsTxRelayDisabled returns whether or not the peer has disabled
	// transaction relay.
	IsTxRelayDisabled() bool
	// GetBanScore returns the current integer value that represents how
	// close the peer is to being banned.
	GetBanScore() uint32
	// GetFeeFilter returns the requested current minimum fee rate for which
	// transactions should be announced.
	GetFeeFilter() int64
}

ServerPeer represents a peer for use with the RPC server. The interface contract requires that all of these methods are safe for concurrent access.

type ServerSyncManager

type ServerSyncManager interface {
	// IsCurrent returns whether or not the sync manager believes the chain
	// is current as compared to the rest of the network.
	IsCurrent() bool
	// SubmitBlock submits the provided block to the network after processing
	// it locally.
	SubmitBlock(block *util.Block, flags blockchain.BehaviorFlags) (bool, error)
	// pause pauses the sync manager until the returned channel is closed.
	Pause() chan<- struct{}
	// SyncPeerID returns the ID of the peer that is currently the peer being
	// used to sync from or 0 if there is none.
	SyncPeerID() int32
	// LocateHeaders returns the headers of the blocks after the first known
	// block in the provided locators until the provided stop hash or the
	// current tip is reached, up to a max of wire.MaxBlockHeadersPerMsg hashes.
	LocateHeaders(locators []*chainhash.Hash, hashStop *chainhash.Hash) []wire.BlockHeader
}

ServerSyncManager represents a sync manager for use with the RPC server. The interface contract requires that all of these methods are safe for concurrent access.

type SimpleAddr

type SimpleAddr struct {
	Net, Addr string
}

SimpleAddr implements the net.Addr interface with two struct fields

func (SimpleAddr) Network

func (a SimpleAddr) Network() string

Network returns the network. This is part of the net.Addr interface.

func (SimpleAddr) String

func (a SimpleAddr) String() string

String returns the address. This is part of the net.Addr interface.

type SyncManager

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

SyncManager provides a block manager for use with the RPC server and implements the RPCServerSyncManager interface.

func (*SyncManager) IsCurrent

func (b *SyncManager) IsCurrent() bool

IsCurrent returns whether or not the sync manager believes the chain is current as compared to the rest of the network. This function is safe for concurrent access and is part of the RPCServerSyncManager interface implementation.

func (*SyncManager) LocateHeaders

func (b *SyncManager) LocateHeaders(locators []*chainhash.Hash,
	hashStop *chainhash.Hash) []wire.BlockHeader

LocateBlocks returns the hashes of the blocks after the first known block in the provided locators until the provided stop hash or the current tip is reached, up to a max of wire.MaxBlockHeadersPerMsg hashes. This function is safe for concurrent access and is part of the RPCServerSyncManager interface implementation.

func (*SyncManager) Pause

func (b *SyncManager) Pause() chan<- struct{}

pause pauses the sync manager until the returned channel is closed. This function is safe for concurrent access and is part of the RPCServerSyncManager interface implementation.

func (*SyncManager) SubmitBlock

func (b *SyncManager) SubmitBlock(block *util.Block,
	flags blockchain.BehaviorFlags) (bool, error)

SubmitBlock submits the provided block to the network after processing it locally. This function is safe for concurrent access and is part of the RPCServerSyncManager interface implementation.

func (*SyncManager) SyncPeerID

func (b *SyncManager) SyncPeerID() int32

SyncPeerID returns the peer that is currently the peer being used to sync from. This function is safe for concurrent access and is part of the RPCServerSyncManager interface implementation.

type UpdatePeerHeightsMsg

type UpdatePeerHeightsMsg struct {
	NewHash    *chainhash.Hash
	NewHeight  int32
	OriginPeer *peer.Peer
}

UpdatePeerHeightsMsg is a message sent from the blockmanager to the server after a new block has been accepted. The purpose of the message is to update the heights of peers that were known to announce the block before we connected it to the main chain or recognized it as an orphan. With these updates, peer heights will be kept up to date, allowing for fresh data when selecting sync peer candidacy.

type WSClient

type WSClient struct {
	// ws client requires a mutex lock for access
	sync.Mutex
	// Server is the RPC Server that is servicing the client.
	Server *Server
	// Conn is the underlying websocket connection.
	Conn *websocket.Conn
	// Addr is the remote address of the client.
	Addr string
	// SessionID is a random ID generated for each client when connected. These
	// IDs may be queried by a client using the session RPC.  A change to the
	// session ID indicates that the client reconnected.
	SessionID    uint64
	AddrRequests map[string]struct{}
	// SpentRequests is a set of unspent Outpoints a wallet has requested
	// notifications for when they are spent by a processed transaction. Owned
	// by the notification manager.
	SpentRequests map[wire.OutPoint]struct{}
	// FilterData is the new generation transaction filter backported from
	// github.com/decred/dcrd for the new backported `loadtxfilter` and
	// `rescanblocks` methods.
	FilterData *WSClientFilter
	// Networking infrastructure.
	ServiceRequestSem Semaphore
	NtfnChan          chan []byte
	SendChan          chan WSResponse
	Quit              chan struct{}
	WG                sync.WaitGroup
	// Disconnected indicated whether or not the websocket client is
	// Disconnected.
	Disconnected bool
	// Authenticated specifies whether a client has been Authenticated and
	// therefore is allowed to communicated over the websocket.
	Authenticated bool
	// IsAdmin specifies whether a client may change the state of the server;
	// false means its access is only to the limited set of RPC calls.
	IsAdmin bool
	// VerboseTxUpdates specifies whether a client has requested verbose
	// information about all new transactions.
	VerboseTxUpdates bool
}

WSClient provides an abstraction for handling a websocket client. The overall data flow is split into 3 main goroutines, a possible 4th goroutine for long-running operations (only started if request is made), and a websocket manager which is used to allow things such as broadcasting requested notifications to all connected websocket clients. Inbound messages are read via the inHandler goroutine and generally dispatched to their own handler. However, certain potentially long-running operations such as rescans, are sent to the asyncHander goroutine and are limited to one at a time. There are two outbound message types - one for responding to client requests and another for async notifications. Responses to client requests use SendMessage which employs a buffered channel thereby limiting the number of outstanding requests that can be made. Notifications are sent via QueueNotification which implements a queue via notificationQueueHandler to ensure sending notifications from other subsystems can't block. Ultimately, all messages are sent via the outHandler.

func NewWebsocketClient

func NewWebsocketClient(server *Server, conn *websocket.Conn,
	remoteAddr string, authenticated bool, isAdmin bool) (*WSClient, error)

NewWebsocketClient returns a new websocket client given the notification manager, websocket connection, remote address, and whether or not the client has already been authenticated (via HTTP Basic access authentication). The returned client is ready to start. Once started, the client will process incoming and outgoing messages in separate goroutines complete with queuing and asynchrous handling for long-running operations.

func (*WSClient) Disconnect

func (c *WSClient) Disconnect()

Disconnect disconnects the websocket client.

func (*WSClient) InHandler

func (c *WSClient) InHandler()

InHandler handles all incoming messages for the websocket connection. It must be run as a goroutine.

func (*WSClient) IsDisconnected

func (c *WSClient) IsDisconnected() bool

IsDisconnected returns whether or not the websocket client is disconnected.

func (*WSClient) NotificationQueueHandler

func (c *WSClient) NotificationQueueHandler()

NotificationQueueHandler handles the queuing of outgoing notifications for the websocket client. This runs as a muxer for various sources of input to ensure that queuing up notifications to be sent will not block. Otherwise, slow clients could bog down the other systems (such as the mempool or block manager) which are queuing the data. The data is passed on to outHandler to actually be written. It must be run as a goroutine.

func (*WSClient) OutHandler

func (c *WSClient) OutHandler()

OutHandler handles all outgoing messages for the websocket connection. It must be run as a goroutine. It uses a buffered channel to serialize output messages while allowing the sender to continue running asynchronously. It must be run as a goroutine.

func (*WSClient) QueueNotification

func (c *WSClient) QueueNotification(marshalledJSON []byte) error

QueueNotification queues the passed notification to be sent to the websocket client. This function, as the name implies, is only intended for notifications since it has additional logic to prevent other subsystems, such as the memory pool and block manager, from blocking even when the send channel is full. If the client is in the process of shutting down, this function returns ErrClientQuit. This is intended to be checked by long-running notification handlers to stop processing if there is no more work needed to be done.

func (*WSClient) SendMessage

func (c *WSClient) SendMessage(marshalledJSON []byte, doneChan chan bool)

SendMessage sends the passed json to the websocket client. It is backed by a buffered channel, so it will not block until the send channel is full. Note however that QueueNotification must be used for sending async notifications instead of the this function. This approach allows a limit to the number of outstanding requests a client can make without preventing or blocking on async notifications.

func (*WSClient) ServiceRequest

func (c *WSClient) ServiceRequest(r *ParsedRPCCmd)

ServiceRequest services a parsed RPC request by looking up and executing the appropriate RPC handler. The response is marshalled and sent to the websocket client.

func (*WSClient) Start

func (c *WSClient) Start()

Start begins processing input and output messages.

func (*WSClient) WaitForShutdown

func (c *WSClient) WaitForShutdown()

WaitForShutdown blocks until the websocket client goroutines are stopped and the connection is closed.

type WSClientFilter

type WSClientFilter struct {

	// Implemented fast paths for address lookup.
	PubKeyHashes        map[[ripemd160.Size]byte]struct{}
	ScriptHashes        map[[ripemd160.Size]byte]struct{}
	CompressedPubKeys   map[[33]byte]struct{}
	UncompressedPubKeys map[[65]byte]struct{}
	// A fallback address lookup map in case a fast path doesn't exist. Only
	// exists for completeness.  If using this shows up in a profile, there's a
	// good chance a fast path should be added.
	OtherAddresses map[string]struct{}
	// Outpoints of Unspent outputs.
	Unspent map[wire.OutPoint]struct{}
	// contains filtered or unexported fields
}

WSClientFilter tracks relevant addresses for each websocket client for the `rescanblocks` extension. It is modified by the `loadtxfilter` command. NOTE: This extension was ported from github.com/decred/dcrd

func NewWSClientFilter

func NewWSClientFilter(addresses []string, unspentOutPoints []wire.OutPoint,
	params *netparams.Params) *WSClientFilter

NewWSClientFilter creates a new, empty wsClientFilter struct to be used for a websocket client. NOTE: This extension was ported from github.com/decred/ dcrd

func (*WSClientFilter) AddAddress

func (f *WSClientFilter) AddAddress(a util.Address)

AddAddress adds an address to a wsClientFilter, treating it correctly based on the type of address passed as an argument. NOTE: This extension was ported from github.com/decred/dcrd

func (*WSClientFilter) AddAddressStr

func (f *WSClientFilter) AddAddressStr(s string, params *netparams.Params)

AddAddressStr parses an address from a string and then adds it to the wsClientFilter using addAddress. NOTE: This extension was ported from github.com/decred/dcrd

func (*WSClientFilter) AddUnspentOutPoint

func (f *WSClientFilter) AddUnspentOutPoint(op *wire.OutPoint)

AddUnspentOutPoint adds an outpoint to the wsClientFilter. NOTE: This extension was ported from github.com/decred/dcrd

func (*WSClientFilter) ExistsAddress

func (f *WSClientFilter) ExistsAddress(a util.Address) bool

ExistsAddress returns true if the passed address has been added to the wsClientFilter. NOTE: This extension was ported from github.com/decred/dcrd

func (*WSClientFilter) ExistsUnspentOutPoint

func (f *WSClientFilter) ExistsUnspentOutPoint(op *wire.OutPoint) bool

ExistsUnspentOutPoint returns true if the passed outpoint has been added to the wsClientFilter. NOTE: This extension was ported from github.com/decred/dcrd

type WSCommandHandler

type WSCommandHandler func(*WSClient, interface{}) (interface{}, error)

WSCommandHandler describes a callback function used to handle a specific command.

type WSNtfnMgr

type WSNtfnMgr struct {
	// Server is the RPC Server the notification manager is associated with.
	Server *Server
	// QueueNotification queues a notification for handling.
	QueueNotification chan interface{}
	// NotificationMsgs feeds notificationHandler with notifications and client
	// (un)registeration requests from a queue as well as registeration and
	// unregisteration requests from clients.
	NotificationMsgs chan interface{}
	// Access channel for current number of connected clients.
	NumClients chan int
	// Shutdown handling
	WG   sync.WaitGroup
	Quit chan struct{}
}

WSNtfnMgr is a connection and notification manager used for websockets. It allows websocket clients to register for notifications they are interested in. When an event happens elsewhere in the code such as transactions being added to the memory pool or block connects/disconnects, the notification manager is provided with the relevant details needed to figure out which websocket clients need to be notified based on what they have registered for and notifies them accordingly. It is also used to keep track of all connected websocket clients.

func NewWSNotificationManager

func NewWSNotificationManager(server *Server) *WSNtfnMgr

NewWSNotificationManager returns a new notification manager ready for use. See wsNotificationManager for more details.

func (*WSNtfnMgr) AddAddrRequests

func (*WSNtfnMgr) AddAddrRequests(
	addrMap map[string]map[chan struct{}]*WSClient, wsc *WSClient, addrs []string)

AddAddrRequests adds the websocket client wsc to the address to client set addrMap so wsc will be notified for any mempool or block transaction outputs spending to any of the addresses in addrs.

func (*WSNtfnMgr) AddClient

func (m *WSNtfnMgr) AddClient(wsc *WSClient)

// removeAddress removes the passed address, if it exists, from the wsClientFilter. NOTE: This extension was ported from github.com/decred/dcrd

func (f *wsClientFilter) removeAddress(a util.Address) {
	switch a := a.(type) {
	case *util.AddressPubKeyHash:
		delete(f.pubKeyHashes, *a.Hash160())
		return
	case *util.AddressScriptHash:
		delete(f.scriptHashes, *a.Hash160())
		return
	case *util.AddressPubKey:
		serializedPubKey := a.ScriptAddress()
		switch len(serializedPubKey) {
		case 33: // compressed
			var compressedPubKey [33]byte
			copy(compressedPubKey[:], serializedPubKey)
			delete(f.compressedPubKeys, compressedPubKey)
			return
		case 65: // uncompressed
			var uncompressedPubKey [65]byte
			copy(uncompressedPubKey[:], serializedPubKey)
			delete(f.uncompressedPubKeys, uncompressedPubKey)
			return
		}
	}
	delete(f.otherAddresses, a.EncodeAddress())
}

// removeAddressStr parses an address from a string and then removes it from // the wsClientFilter using removeAddress. NOTE: This extension was ported // from github.com/decred/dcrd

func (f *wsClientFilter) removeAddressStr(s string, netparams *netparams.Params) {
	a, err := util.DecodeAddress(s, netparams)
	if err == nil {
		f.removeAddress(a)
	} else {
		delete(f.otherAddresses, s)
	}
}

// removeUnspentOutPoint removes the passed outpoint, if it exists, from the wsClientFilter. NOTE: This extension was ported from github.com/decred/dcrd

func (f *wsClientFilter) removeUnspentOutPoint(op *wire.OutPoint) {
	delete(f.unspent, *op)
}

AddClient adds the passed websocket client to the notification manager.

func (*WSNtfnMgr) AddSpentRequests

func (m *WSNtfnMgr) AddSpentRequests(opMap map[wire.
	OutPoint]map[chan struct{}]*WSClient,
	wsc *WSClient, ops []*wire.OutPoint)

AddSpentRequests modifies a map of watched outpoints to sets of websocket clients to add a new request watch all of the outpoints in ops and create and send a notification when spent to the websocket client wsc.

func (*WSNtfnMgr) GetNumClients

func (m *WSNtfnMgr) GetNumClients() (n int)

GetNumClients returns the number of clients actively being served.

func (*WSNtfnMgr) GetSubscribedClients

func (m *WSNtfnMgr) GetSubscribedClients(tx *util.Tx,
	clients map[chan struct{}]*WSClient) map[chan struct{}]struct{}

GetSubscribedClients returns the set of all websocket client quit channels that are registered to receive notifications regarding tx, either due to tx spending a watched output or outputting to a watched address. Matching client's filters are updated based on this transaction's outputs and output addresses that may be relevant for a client.

func (*WSNtfnMgr) NotificationHandler

func (m *WSNtfnMgr) NotificationHandler()

NotificationHandler reads notifications and control messages from the queue handler and processes one at a time.

func (*WSNtfnMgr) NotifyBlockConnected

func (*WSNtfnMgr) NotifyBlockConnected(clients map[chan struct{}]*WSClient,
	block *util.Block)

NotifyBlockConnected notifies websocket clients that have registered for block updates when a block is connected to the main chain.

func (*WSNtfnMgr) NotifyBlockDisconnected

func (*WSNtfnMgr) NotifyBlockDisconnected(
	clients map[chan struct{}]*WSClient, block *util.Block)

NotifyBlockDisconnected notifies websocket clients that have registered for block updates when a block is disconnected from the main chain (due to a reorganize).

func (*WSNtfnMgr) NotifyFilteredBlockConnected

func (m *WSNtfnMgr) NotifyFilteredBlockConnected(
	clients map[chan struct{}]*WSClient, block *util.Block)

NotifyFilteredBlockConnected notifies websocket clients that have registered for block updates when a block is connected to the main chain.

func (*WSNtfnMgr) NotifyFilteredBlockDisconnected

func (*WSNtfnMgr) NotifyFilteredBlockDisconnected(
	clients map[chan struct{}]*WSClient, block *util.Block)

NotifyFilteredBlockDisconnected notifies websocket clients that have registered for block updates when a block is disconnected from the main chain (due to a reorganize).

func (*WSNtfnMgr) NotifyForNewTx

func (m *WSNtfnMgr) NotifyForNewTx(clients map[chan struct{}]*WSClient,
	tx *util.Tx)

NotifyForNewTx notifies websocket clients that have registered for updates when a new transaction is added to the memory pool.

func (*WSNtfnMgr) NotifyForTx

func (m *WSNtfnMgr) NotifyForTx(ops map[wire.
	OutPoint]map[chan struct{}]*WSClient,
	addrs map[string]map[chan struct{}]*WSClient, tx *util.Tx, block *util.Block)

NotifyForTx examines the inputs and outputs of the passed transaction, notifying websocket clients of outputs spending to a watched address and inputs spending a watched outpoint.

func (*WSNtfnMgr) NotifyForTxIns

func (m *WSNtfnMgr) NotifyForTxIns(ops map[wire.
	OutPoint]map[chan struct{}]*WSClient,
	tx *util.Tx, block *util.Block)

NotifyForTxIns examines the inputs of the passed transaction and sends interested websocket clients a redeemingtx notification if any inputs spend a watched output. If block is non-nil, any matching spent requests are removed.

func (*WSNtfnMgr) NotifyForTxOuts

func (m *WSNtfnMgr) NotifyForTxOuts(ops map[wire.
	OutPoint]map[chan struct{}]*WSClient,
	addrs map[string]map[chan struct{}]*WSClient, tx *util.Tx, block *util.Block)

NotifyForTxOuts examines each transaction output, notifying interested websocket clients of the transaction if an output spends to a watched address. A spent notification request is automatically registered for the client for each matching output.

func (*WSNtfnMgr) NotifyRelevantTxAccepted

func (m *WSNtfnMgr) NotifyRelevantTxAccepted(tx *util.Tx,
	clients map[chan struct{}]*WSClient)

NotifyRelevantTxAccepted examines the inputs and outputs of the passed transaction, notifying websocket clients of outputs spending to a watched address and inputs spending a watched outpoint. Any outputs paying to a watched address result in the output being watched as well for future notifications.

func (*WSNtfnMgr) QueueHandler

func (m *WSNtfnMgr) QueueHandler()

QueueHandler maintains a queue of notifications and notification handler control messages.

func (*WSNtfnMgr) RegisterBlockUpdates

func (m *WSNtfnMgr) RegisterBlockUpdates(wsc *WSClient)

RegisterBlockUpdates requests block update notifications to the passed websocket client.

func (*WSNtfnMgr) RegisterNewMempoolTxsUpdates

func (m *WSNtfnMgr) RegisterNewMempoolTxsUpdates(wsc *WSClient)

RegisterNewMempoolTxsUpdates requests notifications to the passed websocket client when new transactions are added to the memory pool.

func (*WSNtfnMgr) RegisterSpentRequests

func (m *WSNtfnMgr) RegisterSpentRequests(wsc *WSClient, ops []*wire.OutPoint)

RegisterSpentRequests requests a notification when each of the passed outpoints is confirmed spent (contained in a block connected to the main chain) for the passed websocket client. The request is automatically removed once the notification has been sent.

func (*WSNtfnMgr) RegisterTxOutAddressRequests

func (m *WSNtfnMgr) RegisterTxOutAddressRequests(wsc *WSClient, addrs []string)

RegisterTxOutAddressRequests requests notifications to the passed websocket client when a transaction output spends to the passed address.

func (*WSNtfnMgr) RemoveAddrRequest

func (*WSNtfnMgr) RemoveAddrRequest(
	addrs map[string]map[chan struct{}]*WSClient, wsc *WSClient, addr string)

RemoveAddrRequest removes the websocket client wsc from the address to client set addrs so it will no longer receive notification updates for any transaction outputs send to addr.

func (*WSNtfnMgr) RemoveClient

func (m *WSNtfnMgr) RemoveClient(wsc *WSClient)

RemoveClient removes the passed websocket client and all notifications registered for it.

func (*WSNtfnMgr) RemoveSpentRequest

func (*WSNtfnMgr) RemoveSpentRequest(ops map[wire.
	OutPoint]map[chan struct{}]*WSClient,
	wsc *WSClient, op *wire.OutPoint)

RemoveSpentRequest modifies a map of watched outpoints to remove the websocket client wsc from the set of clients to be notified when a watched outpoint is spent. If wsc is the last client, the outpoint key is removed from the map.

func (*WSNtfnMgr) SendNotifyBlockConnected

func (m *WSNtfnMgr) SendNotifyBlockConnected(block *util.Block)

SendNotifyBlockConnected passes a block newly-connected to the best chain to the notification manager for block and transaction notification processing.

func (*WSNtfnMgr) SendNotifyBlockDisconnected

func (m *WSNtfnMgr) SendNotifyBlockDisconnected(block *util.Block)

SendNotifyBlockDisconnected passes a block disconnected from the best chain to the notification manager for block notification processing.

func (*WSNtfnMgr) SendNotifyMempoolTx

func (m *WSNtfnMgr) SendNotifyMempoolTx(tx *util.Tx, isNew bool)

SendNotifyMempoolTx passes a transaction accepted by mempool to the notification manager for transaction notification processing. If isNew is true, the tx is is a new transaction, rather than one added to the mempool during a reorg.

func (*WSNtfnMgr) Shutdown

func (m *WSNtfnMgr) Shutdown()

Shutdown shuts down the manager, stopping the notification queue and notification handler goroutines.

func (*WSNtfnMgr) Start

func (m *WSNtfnMgr) Start()

Start starts the goroutines required for the manager to queue and process websocket client notifications.

func (*WSNtfnMgr) UnregisterBlockUpdates

func (m *WSNtfnMgr) UnregisterBlockUpdates(wsc *WSClient)

UnregisterBlockUpdates removes block update notifications for the passed websocket client.

func (*WSNtfnMgr) UnregisterNewMempoolTxsUpdates

func (m *WSNtfnMgr) UnregisterNewMempoolTxsUpdates(wsc *WSClient)

UnregisterNewMempoolTxsUpdates removes notifications to the passed websocket client when new transaction are added to the memory pool.

func (*WSNtfnMgr) UnregisterSpentRequest

func (m *WSNtfnMgr) UnregisterSpentRequest(wsc *WSClient, op *wire.OutPoint)

UnregisterSpentRequest removes a request from the passed websocket client to be notified when the passed outpoint is confirmed spent (contained in a block connected to the main chain).

func (*WSNtfnMgr) UnregisterTxOutAddressRequest

func (m *WSNtfnMgr) UnregisterTxOutAddressRequest(wsc *WSClient, addr string)

UnregisterTxOutAddressRequest removes a request from the passed websocket client to be notified when a transaction spends to the passed address.

func (*WSNtfnMgr) WaitForShutdown

func (m *WSNtfnMgr) WaitForShutdown()

WaitForShutdown blocks until all notification manager goroutines have finished.

type WSResponse

type WSResponse struct {
	Msg      []byte
	DoneChan chan bool
}

WSResponse houses a message to send to a connected websocket client as well as a channel to reply on when the message is sent.

Jump to

Keyboard shortcuts

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