server

package
v0.1.2-alpha Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2018 License: ISC Imports: 57 Imported by: 0

Documentation

Index

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 = 8

	// 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 * 5
)
View Source
const (
	AppMajor uint = 0
	AppMinor uint = 1
	AppPatch uint = 2

	// AppPreRelease MUST only contain characters from SemanticAlphabet
	// per the semantic versioning spec.
	AppPreRelease = "alpha"
)

These constants define the application version and follow the semantic versioning 2.0.0 spec (http://semver.org/).

View Source
const (
	// BlockDbNamePrefix is the prefix for the block database name.  The
	// database type is appended to this value to form the full block
	// database name.
	BlockDbNamePrefix = "blocks"
)
View Source
const SemanticAlphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-"

SemanticAlphabet is

Variables

View Source
var (
	// BackendLog is the logging backend used to create all subsystem loggers.
	// The backend must not be used before the log rotator has been initialized,
	// or data races and/or nil pointer dereferences will occur.
	BackendLog = Log.NewBackend(LogWriter{})

	// logRotator is one of the logging outputs.  It should be closed on
	// application shutdown.
	LogRotator *rotator.Rotator

	AdxrLog = BackendLog.Logger("ADXR")
	AmgrLog = BackendLog.Logger("AMGR")
	CmgrLog = BackendLog.Logger("CMGR")
	BcdbLog = BackendLog.Logger("BCDB")
	PodLog  = BackendLog.Logger(" POD")
	ChanLog = BackendLog.Logger("CHAN")
	DiscLog = BackendLog.Logger("DISC")
	IndxLog = BackendLog.Logger("INDX")
	MinrLog = BackendLog.Logger("MINR")
	PeerLog = BackendLog.Logger("PEER")
	RPCsLog = BackendLog.Logger("RPCS")
	ScrpLog = BackendLog.Logger("SCRP")
	SrvrLog = BackendLog.Logger("SRVR")
	SyncLog = BackendLog.Logger("SYNC")
	TxmpLog = BackendLog.Logger("TXMP")
)

Loggers per subsystem. A single backend logger is created and all subsytem loggers created from it will write to the backend. When adding new subsystems, add the subsystem logger variable here and to the

map.

Loggers can not be used before the log rotator has been initialized with a log file. This must be performed early during application startup by calling InitLogRotator.

View Source
var (
	// 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",
	}

	// 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",
	}
)

Errors

View Source
var (
	// UserAgentName is the user agent name and is used to help identify
	// ourselves to other bitcoin peers.
	UserAgentName = "pod"

	// UserAgentVersion is the user agent version and is used to help
	// identify ourselves to other bitcoin peers.
	UserAgentVersion = fmt.Sprintf("%d.%d.%d", AppMajor, AppMinor, AppPatch)
)
View Source
var ActiveNetParams = &MainNetParams

ActiveNetParams is a pointer to the parameters specific to the currently active bitcoin network.

View Source
var (
	// AlgoIDs are a list of the algorithms and their ID codes and related block version number
	AlgoIDs = []string{
		"sha256d",
		"scrypt",
	}
)
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 HelpDescsEnUS = map[string]string{}/* 439 elements not displayed */

HelpDescsEnUS defines the English descriptions used for the help strings.

View Source
var InterruptSignals = []os.Signal{os.Interrupt}

InterruptSignals defines the default signals to catch in order to do a proper shutdown. This may be modified during init depending on the platform.

View Source
var MainNetParams = Params{
	Params:        &chaincfg.MainNetParams,
	RPCPort:       "11048",
	ScryptRPCPort: "11049",
}

MainNetParams contains parameters specific to the main network (wire.MainNet). NOTE: The RPC port is intentionally different than the reference implementation because btcd does not handle wallet requests. The separate wallet process listens on the well-known port and forwards requests it does not handle on to btcd. This approach allows the wallet process to emulate the full reference implementation RPC API.

View Source
var 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": {},
}

RPCAskWallet is list of commands that we recognize, but for which btcd has no support because it lacks support for wallet functionality. For these commands the user should ask a connected instance of btcwallet.

View Source
var RPCHandlers map[string]CommandHandler

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

View Source
var RPCHandlersBeforeInit = map[string]CommandHandler{
	"addnode":               HandleAddNode,
	"createrawtransaction":  HandleCreateRawTransaction,
	"debuglevel":            HandleDebugLevel,
	"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,
	"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,
}

RPCHandlersBeforeInit is

View Source
var RPCResultTypes = 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)},
}

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

View Source
var RegressionNetParams = Params{
	Params:        &chaincfg.RegressionNetParams,
	RPCPort:       "31048",
	ScryptRPCPort: "31049",
}

RegressionNetParams contains parameters specific to the regression test network (wire.TestNet). NOTE: The RPC port is intentionally different than the reference implementation - see the MainNetParams comment for details.

View Source
var ShutdownRequestChannel = make(chan struct{})

ShutdownRequestChannel is used to initiate shutdown from one of the subsystems using the same code paths as when an interrupt signal is received.

View Source
var SimNetParams = Params{
	Params:        &chaincfg.SimNetParams,
	RPCPort:       "41048",
	ScryptRPCPort: "41049",
}

SimNetParams contains parameters specific to the simulation test network (wire.SimNet).

View Source
var SubsystemLoggers = map[string]Log.Logger{
	"ADXR": AdxrLog,
	"AMGR": AmgrLog,
	"CMGR": CmgrLog,
	"BCDB": BcdbLog,
	"BTCD": PodLog,
	"CHAN": ChanLog,
	"DISC": DiscLog,
	"INDX": IndxLog,
	"MINR": MinrLog,
	"PEER": PeerLog,
	"RPCS": RPCsLog,
	"SCRP": ScrpLog,
	"SRVR": SrvrLog,
	"SYNC": SyncLog,
	"TXMP": TxmpLog,
}

SubsystemLoggers maps each subsystem identifier to its associated logger.

View Source
var TestNet3Params = Params{
	Params:        &chaincfg.TestNet3Params,
	RPCPort:       "21048",
	ScryptRPCPort: "21049",
}

TestNet3Params contains parameters specific to the test network (version 3) (wire.TestNet3). NOTE: The RPC port is intentionally different than the reference implementation - see the MainNetParams comment for details.

View Source
var WinServiceMain func() (bool, error)

WinServiceMain is only invoked on Windows. It detects when btcd is running as a service and reacts accordingly.

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.

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,
}

WsHandlersBeforeInit is

View Source
var ZeroHash chainhash.Hash

ZeroHash is the zero value hash (all zeros). It is defined as a convenience.

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(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 BlockDetails

func BlockDetails(block *utils.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.

func CheckAddressValidity

func CheckAddressValidity(addrs []string, params *chaincfg.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 CleanAndExpandPath

func CleanAndExpandPath(path string) string

CleanAndExpandPath expands environment variables and leading ~ in the passed path, cleans the result, and returns it.

func CreateDefaultConfigFile

func CreateDefaultConfigFile(destinationPath string) error

CreateDefaultConfigFile copies the file sample-pod.conf to the given destination path, and populates it with some randomly generated RPC username and password.

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 *chaincfg.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 *RPCServer, mtx *wire.MsgTx, chainParams *chaincfg.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 *chaincfg.Params, filterAddrMap map[string]struct{}) []JSON.Vout

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

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 *utils.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 Dial

func Dial(addr net.Addr) (net.Conn, error)

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

func DirEmpty

func DirEmpty(dirPath string) (bool, error)

DirEmpty returns whether or not the specified directory path is empty.

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]*Peer, compareFunc func(*Peer) bool, whenFound func(*Peer)) 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 DoUpgrades

func DoUpgrades() error

DoUpgrades performs upgrades to btcd as new versions require it.

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 *RPCServer, 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 *RPCServer, addr utils.Address, numToSkip, numRequested uint32) ([]*utils.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 *chaincfg.Params, algo uint32) 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 HandleAddNode

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

HandleAddNode handles addnode commands.

func HandleAskWallet

func HandleAskWallet(s *RPCServer, 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 *RPCServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)

HandleCreateRawTransaction handles createrawtransaction commands.

func HandleDebugLevel

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

HandleDebugLevel handles debuglevel commands.

func HandleDecodeRawTransaction

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

HandleDecodeRawTransaction handles decoderawtransaction commands.

func HandleDecodeScript

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

HandleDecodeScript handles decodescript commands.

func HandleEstimateFee

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

HandleEstimateFee handles estimatefee commands.

func HandleGenerate

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

HandleGenerate handles generate commands.

func HandleGetAddedNodeInfo

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

HandleGetAddedNodeInfo handles getaddednodeinfo commands.

func HandleGetBestBlock

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

HandleGetBestBlock implements the getbestblock command.

func HandleGetBestBlockHash

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

HandleGetBestBlockHash implements the getbestblockhash command.

func HandleGetBlock

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

HandleGetBlock implements the getblock command.

func HandleGetBlockChainInfo

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

HandleGetBlockChainInfo implements the getblockchaininfo command.

func HandleGetBlockCount

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

HandleGetBlockCount implements the getblockcount command.

func HandleGetBlockHash

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

HandleGetBlockHash implements the getblockhash command.

func HandleGetBlockHeader

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

HandleGetBlockHeader implements the getblockheader command.

func HandleGetBlockTemplate

func HandleGetBlockTemplate(s *RPCServer, 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 *RPCServer, 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 *RPCServer, 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 *RPCServer, 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 *RPCServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)

HandleGetCFilter implements the getcfilter command.

func HandleGetCFilterHeader

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

HandleGetCFilterHeader implements the getcfilterheader command.

func HandleGetConnectionCount

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

HandleGetConnectionCount implements the getconnectioncount command.

func HandleGetCurrentNet

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

HandleGetCurrentNet implements the getcurrentnet command.

func HandleGetDifficulty

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

HandleGetDifficulty implements the getdifficulty command.

func HandleGetGenerate

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

HandleGetGenerate implements the getgenerate command.

func HandleGetHashesPerSec

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

HandleGetHashesPerSec implements the gethashespersec command.

func HandleGetHeaders

func HandleGetHeaders(s *RPCServer, 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 *RPCServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)

HandleGetInfo implements the getinfo command. We only return the fields that are not related to wallet functionality.

func HandleGetMempoolInfo

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

HandleGetMempoolInfo implements the getmempoolinfo command.

func HandleGetMiningInfo

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

HandleGetMiningInfo implements the getmininginfo command. We only return the fields that are not related to wallet functionality.

func HandleGetNetTotals

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

HandleGetNetTotals implements the getnettotals command.

func HandleGetNetworkHashPs

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

HandleGetNetworkHashPs implements the getnetworkhashps command.

func HandleGetPeerInfo

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

HandleGetPeerInfo implements the getpeerinfo command.

func HandleGetRawMempool

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

HandleGetRawMempool implements the getrawmempool command.

func HandleGetRawTransaction

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

HandleGetRawTransaction implements the getrawtransaction command.

func HandleGetTxOut

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

HandleGetTxOut handles gettxout commands.

func HandleHelp

func HandleHelp(s *RPCServer, 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 *RPCServer, 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)

HandleNotifyNewTransactions 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 *RPCServer, 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.

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 *RPCServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)

HandleSearchRawTransactions implements the searchrawtransactions command.

func HandleSendRawTransaction

func HandleSendRawTransaction(s *RPCServer, 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 *RPCServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)

HandleSetGenerate implements the setgenerate command.

func HandleStop

func HandleStop(s *RPCServer, 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)

HandleStopNotifyNewTransactions 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 *RPCServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)

HandleSubmitBlock implements the submitblock command.

func HandleUnimplemented

func HandleUnimplemented(s *RPCServer, 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 *RPCServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)

HandleUptime implements the uptime command.

func HandleValidateAddress

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

HandleValidateAddress implements the validateaddress command.

func HandleVerifyChain

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

HandleVerifyChain implements the verifychain command.

func HandleVerifyMessage

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

HandleVerifyMessage implements the verifymessage command.

func HandleVersion

func HandleVersion(s *RPCServer, 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 HasServices

func HasServices(advertised, desired wire.ServiceFlag) bool

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

func InitListeners

func InitListeners(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 NAT interface, which is non-nil if UPnP is in use.

func InitLogRotator

func InitLogRotator(logFile string)

InitLogRotator initializes the logging rotater to write logs to logFile and create roll files in the same directory. It must be called before the package-global log rotater variables are used.

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 InterruptListener

func InterruptListener() <-chan struct{}

InterruptListener listens for OS Signals such as SIGINT (Ctrl+C) and shutdown requests from ShutdownRequestChannel. It returns a channel that is closed when either signal is received.

func InterruptRequested

func InterruptRequested(interrupted <-chan struct{}) bool

InterruptRequested returns true when the channel returned by InterruptListener was closed. This simplifies early shutdown slightly since the caller can just use an if statement instead of a select.

func IsWhitelisted

func IsWhitelisted(addr net.Addr) bool

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

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 MinUint32

func MinUint32(a, b uint32) uint32

MinUint32 is a helper function to return the minimum of two uint32s. This avoids a math import and the need to cast to floats.

func NetName

func NetName(chainParams *Params) string

NetName returns the name used when referring to a bitcoin network. At the time of writing, btcd currently places blocks for testnet version 3 in the data and log directory "testnet", which does not match the Name field of the chaincfg parameters. This function can be used to override this directory name as "testnet" when the passed active network matches wire.TestNet3.

A proper upgrade to move the data and log directories for this network to "testnet3" is planned for the future, at which point this function can be removed and the network parameter's name used instead.

func NewCheckpointFromStr

func NewCheckpointFromStr(checkpoint string) (chaincfg.Checkpoint, error)

NewCheckpointFromStr parses checkpoints in the '<height>:<hash>' format.

func NewConfigParser

func NewConfigParser(cfg *Config, so *ServiceOptions, options flags.Options) *flags.Parser

NewConfigParser returns a new command line flags parser.

func NewRedeemingTxNotification

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

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

func NewServerPeerConfig

func NewServerPeerConfig(sp *Peer) *peer.Config

NewServerPeerConfig returns the configuration for the given Peer.

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 NormalizeAddresses

func NormalizeAddresses(addrs []string, defaultPort string) []string

NormalizeAddresses returns a new slice with all the passed peer addresses normalized with the given default port, and all duplicates removed.

func NormalizeVerString

func NormalizeVerString(str string) string

NormalizeVerString returns the passed string stripped of all characters which are not valid according to the semantic versioning guidelines for pre-release version and build metadata strings. In particular they MUST only contain characters in SemanticAlphabet.

func OldBtcdHomeDir

func OldBtcdHomeDir() string

OldBtcdHomeDir returns the OS specific home directory btcd used prior to version 0.3.3. This has since been replaced with utils.AppDataDir, but this function is still provided for the automatic upgrade path.

func ParseAndSetDebugLevels

func ParseAndSetDebugLevels(debugLevel string) error

ParseAndSetDebugLevels attempts to parse the specified debug level and set the levels accordingly. An appropriate error is returned if anything is invalid.

func ParseCheckpoints

func ParseCheckpoints(checkpointStrings []string) ([]chaincfg.Checkpoint, error)

ParseCheckpoints checks the checkpoint strings for valid syntax ('<height>:<hash>') and parses them to chaincfg.Checkpoint instances.

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 RPCServerConnManager, 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 PodLookup

func PodLookup(host string) ([]net.IP, error)

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

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 RPCDecodeHexError

func RPCDecodeHexError(gotHex string) *JSON.RPCError

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

func RPCNoTxInfoError

func RPCNoTxInfoError(txHash *chainhash.Hash) *JSON.RPCError

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

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 *chain.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 RemoveDuplicateAddresses

func RemoveDuplicateAddresses(addrs []string) []string

RemoveDuplicateAddresses returns a new slice with all duplicate entries in addrs removed.

func RescanBlock

func RescanBlock(wsc *WsClient, lookups *RescanKeys, blk *utils.Block)

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

func RescanBlockFilter

func RescanBlockFilter(filter *WsClientFilter, block *utils.Block, params *chaincfg.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 SetLogLevel

func SetLogLevel(subsystemID string, logLevel string)

SetLogLevel sets the logging level for provided subsystem. Invalid subsystems are ignored. Uninitialized subsystems are dynamically created as needed.

func SetLogLevels

func SetLogLevels(logLevel string)

SetLogLevels sets the log level for all subsystem loggers to the passed level. It also dynamically creates the subsystem loggers as needed, so it can be used to initialize the logging system.

func SetupRPCListeners

func SetupRPCListeners() ([]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 SetupScryptRPCListeners

func SetupScryptRPCListeners() ([]net.Listener, error)

SetupScryptRPCListeners 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 chain.ThresholdState) (string, error)

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

func SupportedSubsystems

func SupportedSubsystems() []string

SupportedSubsystems returns a sorted slice of the supported subsystems for logging purposes.

func TxHexString

func TxHexString(tx *wire.MsgTx) string

TxHexString returns the serialized transaction encoded in hexadecimal.

func UpgradeDataPaths

func UpgradeDataPaths() error

UpgradeDataPaths moves the application data from its location prior to btcd version 0.3.3 to its new location.

func UpgradeDbPathNet

func UpgradeDbPathNet(oldDbPath, netName string) error

UpgradeDbPathNet moves the database for a specific network from its location prior to btcd version 0.2.0 and uses heuristics to ascertain the old database type to rename to the new format.

func UpgradeDbPaths

func UpgradeDbPaths() error

UpgradeDbPaths moves the databases from their locations prior to btcd version 0.2.0 to their new locations.

func ValidDbType

func ValidDbType(dbType string) bool

ValidDbType returns whether or not dbType is a supported database type.

func ValidLogLevel

func ValidLogLevel(logLevel string) bool

ValidLogLevel returns whether or not logLevel is a valid debug log level.

func VerifyChain

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

VerifyChain is

func Version

func Version() string

Version returns the application version as a properly formed string per the semantic versioning 2.0.0 spec (http://semver.org/).

func WitnessToHex

func WitnessToHex(witness wire.TxWitness) []string

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 {
	// contains filtered or unexported fields
}

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 {
	// contains filtered or unexported fields
}

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(*RPCServer, interface{}, <-chan struct{}) (interface{}, error)

CommandHandler is

type Config

type Config struct {
	ShowVersion          bool          `short:"V" long:"version" description:"Display version information and exit"`
	ConfigFile           string        `short:"C" long:"configfile" description:"Path to configuration file"`
	DataDir              string        `short:"b" long:"datadir" description:"Directory to store data"`
	LogDir               string        `long:"logdir" description:"Directory to log output."`
	AddPeers             []string      `short:"a" long:"addpeer" description:"Add a peer to connect with at startup"`
	ConnectPeers         []string      `long:"connect" description:"Connect only to the specified peers at startup"`
	DisableListen        bool          `` /* 217-byte string literal not displayed */
	Listeners            []string      `` /* 127-byte string literal not displayed */
	MaxPeers             int           `long:"maxpeers" description:"Max number of inbound and outbound peers"`
	DisableBanning       bool          `long:"nobanning" description:"Disable banning of misbehaving peers"`
	BanDuration          time.Duration `long:"banduration" description:"How long to ban misbehaving peers.  Valid time units are {s, m, h}.  Minimum 1 second"`
	BanThreshold         uint32        `long:"banthreshold" description:"Maximum allowed ban score before disconnecting and banning misbehaving peers."`
	Whitelists           []string      `long:"whitelist" description:"Add an IP network or IP that will not be banned. (eg. 192.168.1.0/24 or ::1)"`
	RPCUser              string        `short:"u" long:"rpcuser" description:"Username for RPC connections"`
	RPCPass              string        `short:"P" long:"rpcpass" default-mask:"-" description:"Password for RPC connections"`
	RPCLimitUser         string        `long:"rpclimituser" description:"Username for limited RPC connections"`
	RPCLimitPass         string        `long:"rpclimitpass" default-mask:"-" description:"Password for limited RPC connections"`
	RPCListeners         []string      `long:"rpclisten" description:"Add an interface/port to listen for RPC connections (default port: 11048, testnet: 21048)"`
	ScryptListeners      []string      `long:"scryptlisten" description:"Secondary RPC port that delivers scrypt versioned block templates"`
	RPCCert              string        `long:"rpccert" description:"File containing the certificate file"`
	RPCKey               string        `long:"rpckey" description:"File containing the certificate key"`
	RPCMaxClients        int           `long:"rpcmaxclients" description:"Max number of RPC clients for standard connections"`
	RPCMaxWebsockets     int           `long:"rpcmaxwebsockets" description:"Max number of RPC websocket connections"`
	RPCMaxConcurrentReqs int           `long:"rpcmaxconcurrentreqs" description:"Max number of concurrent RPC requests that may be processed concurrently"`
	RPCQuirks            bool          `` /* 151-byte string literal not displayed */
	DisableRPC           bool          `` /* 165-byte string literal not displayed */
	DisableTLS           bool          `` /* 127-byte string literal not displayed */
	DisableDNSSeed       bool          `long:"nodnsseed" description:"Disable DNS seeding for peers"`
	ExternalIPs          []string      `long:"externalip" description:"Add an ip to the list of local addresses we claim to listen on to peers"`
	Proxy                string        `long:"proxy" description:"Connect via SOCKS5 proxy (eg. 127.0.0.1:9050)"`
	ProxyUser            string        `long:"proxyuser" description:"Username for proxy server"`
	ProxyPass            string        `long:"proxypass" default-mask:"-" description:"Password for proxy server"`
	OnionProxy           string        `long:"onion" description:"Connect to tor hidden services via SOCKS5 proxy (eg. 127.0.0.1:9050)"`
	OnionProxyUser       string        `long:"onionuser" description:"Username for onion proxy server"`
	OnionProxyPass       string        `long:"onionpass" default-mask:"-" description:"Password for onion proxy server"`
	NoOnion              bool          `long:"noonion" description:"Disable connecting to tor hidden services"`
	TorIsolation         bool          `long:"torisolation" description:"Enable Tor stream isolation by randomizing user credentials for each connection."`
	TestNet3             bool          `long:"testnet" description:"Use the test network"`
	RegressionTest       bool          `long:"regtest" description:"Use the regression test network"`
	SimNet               bool          `long:"simnet" description:"Use the simulation test network"`
	AddCheckpoints       []string      `long:"addcheckpoint" description:"Add a custom checkpoint.  Format: '<height>:<hash>'"`
	DisableCheckpoints   bool          `long:"nocheckpoints" description:"Disable built-in checkpoints.  Don't do this unless you know what you're doing."`
	DbType               string        `long:"dbtype" description:"Database backend to use for the Block Chain"`
	Profile              string        `long:"profile" description:"Enable HTTP profiling on given port -- NOTE port must be between 1024 and 65536"`
	CPUProfile           string        `long:"cpuprofile" description:"Write CPU profile to the specified file"`
	DebugLevel           string        `` /* 275-byte string literal not displayed */
	Upnp                 bool          `long:"upnp" description:"Use UPnP to map our listening port outside of NAT"`
	MinRelayTxFee        float64       `long:"minrelaytxfee" description:"The minimum transaction fee in BTC/kB to be considered a non-zero fee."`
	FreeTxRelayLimit     float64       `` /* 140-byte string literal not displayed */
	NoRelayPriority      bool          `long:"norelaypriority" description:"Do not require free or low-fee transactions to have high priority for relaying"`
	TrickleInterval      time.Duration `long:"trickleinterval" description:"Minimum time between attempts to send new inventory to a connected peer"`
	MaxOrphanTxs         int           `long:"maxorphantx" description:"Max number of orphan transactions to keep in memory"`
	Algo                 string        `long:"algo" description:"Set the mining algorithm which will be stored in the block version field"`
	Generate             bool          `long:"generate" description:"Generate (mine) bitcoins using the CPU"`
	MiningAddrs          []string      `` /* 184-byte string literal not displayed */
	BlockMinSize         uint32        `long:"blockminsize" description:"Mininum block size in bytes to be used when creating a block"`
	BlockMaxSize         uint32        `long:"blockmaxsize" description:"Maximum block size in bytes to be used when creating a block"`
	BlockMinWeight       uint32        `long:"blockminweight" description:"Mininum block weight to be used when creating a block"`
	BlockMaxWeight       uint32        `long:"blockmaxweight" description:"Maximum block weight to be used when creating a block"`
	BlockPrioritySize    uint32        `long:"blockprioritysize" description:"Size in bytes for high-priority/low-fee transactions when creating a block"`
	UserAgentComments    []string      `long:"uacomment" description:"Comment to add to the user agent -- See BIP 14 for more information."`
	NoPeerBloomFilters   bool          `long:"nopeerbloomfilters" description:"Disable bloom filtering support"`
	NoCFilters           bool          `long:"nocfilters" description:"Disable committed filtering (CF) support"`
	DropCfIndex          bool          `` /* 138-byte string literal not displayed */
	SigCacheMaxSize      uint          `long:"sigcachemaxsize" description:"The maximum number of entries in the signature verification cache"`
	BlocksOnly           bool          `long:"blocksonly" description:"Do not accept transactions from remote peers."`
	TxIndex              bool          `` /* 142-byte string literal not displayed */
	DropTxIndex          bool          `long:"droptxindex" description:"Deletes the hash-based transaction index from the database on start up and then exits."`
	AddrIndex            bool          `` /* 130-byte string literal not displayed */
	DropAddrIndex        bool          `long:"dropaddrindex" description:"Deletes the address-based transaction index from the database on start up and then exits."`
	RelayNonStd          bool          `long:"relaynonstd" description:"Relay non-standard transactions regardless of the default settings for the active network."`
	RejectNonStd         bool          `long:"rejectnonstd" description:"Reject non-standard transactions regardless of the default settings for the active network."`
	Lookup               func(string) ([]net.IP, error)
	Oniondial            func(string, string, time.Duration) (net.Conn, error)
	Dial                 func(string, string, time.Duration) (net.Conn, error)
	// contains filtered or unexported fields
}

Config defines the configuration options for btcd.

See LoadConfig for details on the configuration load process.

var (
	// Cfg is
	Cfg *Config
)

func LoadConfig

func LoadConfig() (*Config, []string, error)

LoadConfig initializes and parses the config using a config file and command line options.

The configuration proceeds as follows:

  1. Start with a default config with sane settings
  2. Pre-parse the command line to check for an alternative config file
  3. Load configuration file overwriting defaults with any specified options
  4. Parse CLI options and overwrite/add any specified options

The above results in btcd functioning properly without any config settings while still allowing the user to override settings with config files and command line options. Command line options always take precedence.

type ConnectNodeMsg

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

ConnectNodeMsg is

type DisconnectNodeMsg

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

DisconnectNodeMsg is

type GbtWorkState

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

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

func NewGbtWorkState

func NewGbtWorkState(timeSource chain.MedianTimeSource, algo uint32) *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 multiple clients 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 *RPCServer, 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 {
	// contains filtered or unexported fields
}

GetAddedNodesMsg is

type GetConnCountMsg

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

GetConnCountMsg is

type GetOutboundGroup

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

GetOutboundGroup is

type GetPeersMsg

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

GetPeersMsg is

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 LogWriter

type LogWriter struct{}

LogWriter implements an io.Writer that outputs to both standard output and the write-end pipe of an initialized log rotator.

func (LogWriter) Write

func (LogWriter) Write(p []byte) (n int, err error)

type NotificationBlockConnected

type NotificationBlockConnected utils.Block

NotificationBlockConnected is

type NotificationBlockDisconnected

type NotificationBlockDisconnected utils.Block

NotificationBlockDisconnected is

type NotificationRegisterAddr

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

NotificationRegisterAddr is

type NotificationRegisterBlocks

type NotificationRegisterBlocks WsClient

NotificationRegisterBlocks is

type NotificationRegisterClient

type NotificationRegisterClient WsClient

NotificationRegisterClient is

type NotificationRegisterNewMempoolTxs

type NotificationRegisterNewMempoolTxs WsClient

NotificationRegisterNewMempoolTxs is

type NotificationRegisterSpent

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

NotificationRegisterSpent is

type NotificationTxAcceptedByMempool

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

NotificationTxAcceptedByMempool is

type NotificationUnregisterAddr

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

NotificationUnregisterAddr is

type NotificationUnregisterBlocks

type NotificationUnregisterBlocks WsClient

NotificationUnregisterBlocks is

type NotificationUnregisterClient

type NotificationUnregisterClient WsClient

NotificationUnregisterClient is

type NotificationUnregisterNewMempoolTxs

type NotificationUnregisterNewMempoolTxs WsClient

NotificationUnregisterNewMempoolTxs is

type NotificationUnregisterSpent

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

NotificationUnregisterSpent is

type OnionAddr

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

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 Params

type Params struct {
	*chaincfg.Params
	RPCPort       string
	ScryptRPCPort string
}

Params is used to group parameters for various networks such as the main network and test networks.

type ParsedRPCCmd

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

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 struct {
	*peer.Peer
	// contains filtered or unexported fields
}

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

func NewServerPeer

func NewServerPeer(s *Server, isPersistent bool) *Peer

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

func (*Peer) AddBanScore

func (sp *Peer) 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 (*Peer) AddKnownAddresses

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

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

func (*Peer) AddressKnown

func (sp *Peer) AddressKnown(na *wire.NetAddress) bool

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

func (*Peer) EnforceNodeBloomFlag

func (sp *Peer) 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 (*Peer) NewestBlock

func (sp *Peer) NewestBlock() (*chainhash.Hash, int32, error)

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

func (*Peer) OnAddr

func (sp *Peer) 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 (*Peer) OnBlock

func (sp *Peer) 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 (*Peer) OnFeeFilter

func (sp *Peer) 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 (*Peer) OnFilterAdd

func (sp *Peer) 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 (*Peer) OnFilterClear

func (sp *Peer) 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 (*Peer) OnFilterLoad

func (sp *Peer) 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 (*Peer) OnGetAddr

func (sp *Peer) 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 (*Peer) OnGetBlocks

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

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

func (*Peer) OnGetCFCheckpt

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

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

func (*Peer) OnGetCFHeaders

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

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

func (*Peer) OnGetCFilters

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

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

func (*Peer) OnGetData

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

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

func (*Peer) OnGetHeaders

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

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

func (*Peer) OnHeaders

func (sp *Peer) 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 (*Peer) OnInv

func (sp *Peer) 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 (*Peer) OnMemPool

func (sp *Peer) 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 (*Peer) OnRead

func (sp *Peer) 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 (*Peer) OnTx

func (sp *Peer) 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 (*Peer) OnVersion

func (sp *Peer) 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 (*Peer) OnWrite

func (sp *Peer) 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 (*Peer) RelayTxDisabled

func (sp *Peer) RelayTxDisabled() bool

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

func (*Peer) SetDisableRelayTx

func (sp *Peer) SetDisableRelayTx(disable bool)

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

type PeerState

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

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 *Peer))

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 *Peer))

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

type RPCConnManager

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

RPCConnManager provides a connection manager for use with the RPC server and implements the RPCServerConnManager interface.

func (*RPCConnManager) AddRebroadcastInventory

func (cm *RPCConnManager) 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 (*RPCConnManager) BroadcastMessage

func (cm *RPCConnManager) 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 (*RPCConnManager) Connect

func (cm *RPCConnManager) 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 (*RPCConnManager) ConnectedCount

func (cm *RPCConnManager) 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 (*RPCConnManager) ConnectedPeers

func (cm *RPCConnManager) ConnectedPeers() []RPCServerPeer

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 (*RPCConnManager) DisconnectByAddr

func (cm *RPCConnManager) 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 (*RPCConnManager) DisconnectByID

func (cm *RPCConnManager) 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 (*RPCConnManager) NetTotals

func (cm *RPCConnManager) 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 (*RPCConnManager) PersistentPeers

func (cm *RPCConnManager) PersistentPeers() []RPCServerPeer

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 (*RPCConnManager) RelayTransactions

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

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

func (*RPCConnManager) RemoveByAddr

func (cm *RPCConnManager) 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 (*RPCConnManager) RemoveByID

func (cm *RPCConnManager) 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 RPCPeer

type RPCPeer Peer

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

func (*RPCPeer) BanScore

func (p *RPCPeer) BanScore() uint32

BanScore 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 (*RPCPeer) FeeFilter

func (p *RPCPeer) FeeFilter() int64

FeeFilter 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 (*RPCPeer) IsTxRelayDisabled

func (p *RPCPeer) 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 (*RPCPeer) ToPeer

func (p *RPCPeer) 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 RPCServer

type RPCServer struct {
	GbtWorkState *GbtWorkState
	HelpCacher   *HelpCacher
	// contains filtered or unexported fields
}

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

func NewRPCServer

func NewRPCServer(config *RPCServerConfig) (*RPCServer, error)

NewRPCServer returns a new instance of the RPCServer struct.

func (*RPCServer) CheckAuth

func (s *RPCServer) 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 (*RPCServer) DecrementClients

func (s *RPCServer) 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 (*RPCServer) HTTPStatusLine

func (s *RPCServer) 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 (*RPCServer) HandleBlockchainNotification

func (s *RPCServer) HandleBlockchainNotification(notification *chain.Notification)

HandleBlockchainNotification is a callback for notifications from chain. It notifies clients that are long polling for changes or subscribed to websockets notifications.

func (*RPCServer) IncrementClients

func (s *RPCServer) 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 (*RPCServer) JSONRPCRead

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

JSONRPCRead handles reading and responding to RPC messages.

func (*RPCServer) LimitConnections

func (s *RPCServer) 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 (*RPCServer) NotifyNewTransactions

func (s *RPCServer) 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 (*RPCServer) RequestedProcessShutdown

func (s *RPCServer) 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 (*RPCServer) StandardCmdResult

func (s *RPCServer) 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 (*RPCServer) Start

func (s *RPCServer) Start()

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

func (*RPCServer) Stop

func (s *RPCServer) Stop() error

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

func (*RPCServer) WebsocketHandler

func (s *RPCServer) 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 (*RPCServer) WriteHTTPResponseHeaders

func (s *RPCServer) 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 RPCServerConfig

type RPCServerConfig 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 RPCServerConnManager

	// SyncMgr defines the sync manager for the RPC server to use.
	SyncMgr RPCServerSyncManager

	// These fields allow the RPC server to interface with the local block
	// chain data and state.
	TimeSource  chain.MedianTimeSource
	Chain       *chain.BlockChain
	ChainParams *chaincfg.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 uint32
}

RPCServerConfig is a descriptor containing the RPC server configuration.

type RPCServerConnManager

type RPCServerConnManager 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() []RPCServerPeer

	// PersistentPeers returns an array consisting of all the persistent
	// peers.
	PersistentPeers() []RPCServerPeer

	// 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)
}

RPCServerConnManager 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 RPCServerPeer

type RPCServerPeer interface {
	// ToPeer returns the underlying peer instance.
	ToPeer() *peer.Peer

	// IsTxRelayDisabled returns whether or not the peer has disabled
	// transaction relay.
	IsTxRelayDisabled() bool

	// BanScore returns the current integer value that represents how close
	// the peer is to being banned.
	BanScore() uint32

	// FeeFilter returns the requested current minimum fee rate for which
	// transactions should be announced.
	FeeFilter() int64
}

RPCServerPeer represents a peer for use with the RPC server.

The interface contract requires that all of these methods are safe for concurrent access.

type RPCServerSyncManager

type RPCServerSyncManager 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 *utils.Block, flags chain.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
}

RPCServerSyncManager 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 RelayMsg

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

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

type RemoveNodeMsg

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

RemoveNodeMsg is

type RescanKeys

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

RescanKeys is

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 {
	// contains filtered or unexported fields
}

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{}

Semaphore is

func MakeSemaphore

func MakeSemaphore(n int) Semaphore

MakeSemaphore is

func (Semaphore) Acquire

func (s Semaphore) Acquire()

Acquire is

func (Semaphore) Release

func (s Semaphore) Release()

Release is

type Server

type Server struct {
	RPCServer       *RPCServer
	ScryptRPCServer *RPCServer
	// contains filtered or unexported fields
}

Server provides a bitcoin server for handling communications to and from bitcoin peers.

func New

func New(listenAddrs []string, scryptAddrs []string, db database.DB, chainParams *chaincfg.Params, interrupt <-chan struct{}) (*Server, error)

New returns a new btcd server configured to listen on addr for the bitcoin network type specified by chainParams. Use start to begin accepting connections from peers.

func (*Server) AddBytesReceived

func (s *Server) 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 (*Server) AddBytesSent

func (s *Server) 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 (*Server) AddPeer

func (s *Server) AddPeer(sp *Peer)

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

func (*Server) AddRebroadcastInventory

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

AddRebroadcastInventory is

func (*Server) AnnounceNewTransactions

func (s *Server) 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 (*Server) BanPeer

func (s *Server) BanPeer(sp *Peer)

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

func (*Server) BroadcastMessage

func (s *Server) BroadcastMessage(msg wire.Message, exclPeers ...*Peer)

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

func (*Server) ConnectedCount

func (s *Server) ConnectedCount() int32

ConnectedCount returns the number of currently connected peers.

func (*Server) HandleAddPeerMsg

func (s *Server) HandleAddPeerMsg(state *PeerState, sp *Peer) bool

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

func (*Server) HandleBanPeerMsg

func (s *Server) HandleBanPeerMsg(state *PeerState, sp *Peer)

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

func (*Server) HandleBroadcastMsg

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

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

func (*Server) HandleDonePeerMsg

func (s *Server) HandleDonePeerMsg(state *PeerState, sp *Peer)

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

func (*Server) HandleQuery

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

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

func (*Server) HandleRelayInvMsg

func (s *Server) 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 (*Server) HandleUpdatePeerHeights

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

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

func (*Server) InboundPeerConnected

func (s *Server) 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 (*Server) NetTotals

func (s *Server) 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 (*Server) OutboundGroupCount

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

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

func (*Server) OutboundPeerConnected

func (s *Server) 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 (*Server) PeerDoneHandler

func (s *Server) PeerDoneHandler(sp *Peer)

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

func (*Server) PeerHandler

func (s *Server) 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 (*Server) PushBlockMsg

func (s *Server) PushBlockMsg(sp *Peer, 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 (*Server) PushMerkleBlockMsg

func (s *Server) PushMerkleBlockMsg(sp *Peer, 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 (*Server) PushTxMsg

func (s *Server) PushTxMsg(sp *Peer, 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 (*Server) RebroadcastHandler

func (s *Server) 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 (*Server) RelayInventory

func (s *Server) 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 (*Server) RelayTransactions

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

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

func (*Server) RemoveRebroadcastInventory

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

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

func (*Server) ScheduleShutdown

func (s *Server) 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 (*Server) Start

func (s *Server) Start()

Start begins accepting connections from peers.

func (*Server) Stop

func (s *Server) Stop() error

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

func (*Server) TransactionConfirmed

func (s *Server) TransactionConfirmed(tx *utils.Tx)

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

func (*Server) UPNPUpdateThread

func (s *Server) UPNPUpdateThread()

UPNPUpdateThread is

func (*Server) UpdatePeerHeights

func (s *Server) 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 (*Server) WaitForShutdown

func (s *Server) WaitForShutdown()

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

type ServiceOptions

type ServiceOptions struct {
	ServiceCommand string `short:"s" long:"service" description:"Service command {install, remove, start, stop}"`
}

ServiceOptions defines the configuration options for the daemon as a service on Windows.

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 UpdatePeerHeightsMsg

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

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 {
	sync.Mutex
	// contains filtered or unexported fields
}

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 *RPCServer, 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) Disconnected

func (c *WsClient) Disconnected() bool

Disconnected returns whether or not the websocket client is disconnected.

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) 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 {
	// 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 *chaincfg.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 utils.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 *chaincfg.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 utils.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

func (*WsClientFilter) RemoveAddress

func (f *WsClientFilter) RemoveAddress(a utils.Address)

RemoveAddress removes the passed address, if it exists, from the WsClientFilter.

NOTE: This extension was ported from github.com/decred/dcrd

func (*WsClientFilter) RemoveAddressStr

func (f *WsClientFilter) RemoveAddressStr(s string, params *chaincfg.Params)

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 (*WsClientFilter) RemoveUnspentOutPoint

func (f *WsClientFilter) RemoveUnspentOutPoint(op *wire.OutPoint)

RemoveUnspentOutPoint removes the passed outpoint, if it exists, from 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 WsNotificationManager

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

WsNotificationManager 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 *RPCServer) *WsNotificationManager

NewWsNotificationManager returns a new notification manager ready for use. See WsNotificationManager for more details.

func (*WsNotificationManager) AddAddrRequests

func (*WsNotificationManager) 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 (*WsNotificationManager) AddClient

func (m *WsNotificationManager) AddClient(wsc *WsClient)

AddClient adds the passed websocket client to the notification manager.

func (*WsNotificationManager) AddSpentRequests

func (m *WsNotificationManager) 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 (*WsNotificationManager) NotificationHandler

func (m *WsNotificationManager) NotificationHandler()

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

func (*WsNotificationManager) NotifyBlockConnected

func (m *WsNotificationManager) NotifyBlockConnected(block *utils.Block)

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

func (*WsNotificationManager) NotifyBlockDisconnected

func (m *WsNotificationManager) NotifyBlockDisconnected(block *utils.Block)

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

func (*WsNotificationManager) NotifyFilteredBlockConnected

func (m *WsNotificationManager) NotifyFilteredBlockConnected(clients map[chan struct{}]*WsClient,
	block *utils.Block)

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

func (*WsNotificationManager) NotifyForNewTx

func (m *WsNotificationManager) NotifyForNewTx(clients map[chan struct{}]*WsClient, tx *utils.Tx)

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

func (*WsNotificationManager) NotifyForTx

func (m *WsNotificationManager) NotifyForTx(ops map[wire.OutPoint]map[chan struct{}]*WsClient,
	addrs map[string]map[chan struct{}]*WsClient, tx *utils.Tx, block *utils.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 (*WsNotificationManager) NotifyForTxIns

func (m *WsNotificationManager) NotifyForTxIns(ops map[wire.OutPoint]map[chan struct{}]*WsClient,
	tx *utils.Tx, block *utils.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 (*WsNotificationManager) NotifyForTxOuts

func (m *WsNotificationManager) NotifyForTxOuts(ops map[wire.OutPoint]map[chan struct{}]*WsClient,
	addrs map[string]map[chan struct{}]*WsClient, tx *utils.Tx, block *utils.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 (*WsNotificationManager) NotifyMempoolTx

func (m *WsNotificationManager) NotifyMempoolTx(tx *utils.Tx, isNew bool)

NotifyMempoolTx 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 (*WsNotificationManager) NotifyRelevantTxAccepted

func (m *WsNotificationManager) NotifyRelevantTxAccepted(tx *utils.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 (*WsNotificationManager) NumClients

func (m *WsNotificationManager) NumClients() (n int)

NumClients returns the number of clients actively being served.

func (*WsNotificationManager) QueueHandler

func (m *WsNotificationManager) QueueHandler()

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

func (*WsNotificationManager) RegisterBlockUpdates

func (m *WsNotificationManager) RegisterBlockUpdates(wsc *WsClient)

RegisterBlockUpdates requests block update notifications to the passed websocket client.

func (*WsNotificationManager) RegisterNewMempoolTxsUpdates

func (m *WsNotificationManager) RegisterNewMempoolTxsUpdates(wsc *WsClient)

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

func (*WsNotificationManager) RegisterSpentRequests

func (m *WsNotificationManager) 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 (*WsNotificationManager) RegisterTxOutAddressRequests

func (m *WsNotificationManager) RegisterTxOutAddressRequests(wsc *WsClient, addrs []string)

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

func (*WsNotificationManager) RemoveAddrRequest

func (*WsNotificationManager) 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 (*WsNotificationManager) RemoveClient

func (m *WsNotificationManager) RemoveClient(wsc *WsClient)

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

func (*WsNotificationManager) RemoveSpentRequest

func (*WsNotificationManager) 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 (*WsNotificationManager) Shutdown

func (m *WsNotificationManager) Shutdown()

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

func (*WsNotificationManager) Start

func (m *WsNotificationManager) Start()

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

func (*WsNotificationManager) SubscribedClients

func (m *WsNotificationManager) SubscribedClients(tx *utils.Tx,
	clients map[chan struct{}]*WsClient) map[chan struct{}]struct{}

SubscribedClients 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 (*WsNotificationManager) UnregisterBlockUpdates

func (m *WsNotificationManager) UnregisterBlockUpdates(wsc *WsClient)

UnregisterBlockUpdates removes block update notifications for the passed websocket client.

func (*WsNotificationManager) UnregisterNewMempoolTxsUpdates

func (m *WsNotificationManager) UnregisterNewMempoolTxsUpdates(wsc *WsClient)

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

func (*WsNotificationManager) UnregisterSpentRequest

func (m *WsNotificationManager) 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 (*WsNotificationManager) UnregisterTxOutAddressRequest

func (m *WsNotificationManager) 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 (*WsNotificationManager) WaitForShutdown

func (m *WsNotificationManager) WaitForShutdown()

WaitForShutdown blocks until all notification manager goroutines have finished.

type WsResponse

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

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