Documentation ¶
Index ¶
- Constants
- Variables
- func AddLocalAddress(addrMgr *addrmgr.AddrManager, addr string, services wire.ServiceFlag) error
- func AddrStringToNetAddr(config *pod.Config, stateCfg *state.Config, addr string) (net.Addr, error)
- func BigToLEUint256(n *big.Int) [Uint256Size]byte
- func BlockDetails(block *util.Block, txIndex int) *btcjson.BlockDetails
- func BuilderScript(builder *txscript.ScriptBuilder) []byte
- func ChainErrToGBTErrString(err error) string
- func CheckAddressValidity(addrs []string, params *netparams.Params) error
- func CreateMarshalledReply(id, result interface{}, replyErr error) ([]byte, error)
- func CreateTxRawResult(chainParams *netparams.Params, mtx *wire.MsgTx, txHash string, ...) (*btcjson.TxRawResult, error)
- func CreateVinList(mtx *wire.MsgTx) []btcjson.Vin
- func CreateVinListPrevOut(s *Server, mtx *wire.MsgTx, chainParams *netparams.Params, vinExtra bool, ...) ([]btcjson.VinPrevOut, error)
- func CreateVoutList(mtx *wire.MsgTx, chainParams *netparams.Params, ...) []btcjson.Vout
- func DecodeHexError(gotHex string) *btcjson.RPCError
- func DecodeTemplateID(templateID string) (*chainhash.Hash, int64, error)
- func DescendantBlock(prevHash *chainhash.Hash, curBlock *util.Block) error
- func DeserializeOutpoints(serializedOuts []btcjson.OutPoint) ([]*wire.OutPoint, error)
- func DisconnectPeer(peerList map[int32]*NodePeer, compareFunc func(*NodePeer) bool, ...) bool
- func DynamicTickDuration(remaining time.Duration) time.Duration
- func EncodeTemplateID(prevHash *chainhash.Hash, lastGenerated time.Time) string
- func FetchInputTxos(s *Server, tx *wire.MsgTx) (map[wire.OutPoint]wire.TxOut, error)
- func FetchMempoolTxnsForAddress(s *Server, addr util.Address, numToSkip, numRequested uint32) ([]*util.Tx, uint32)
- func FileExists(name string) bool
- func GenCertPair(certFile, keyFile string) error
- func GetDifficultyRatio(bits uint32, params *netparams.Params, algo int32) float64
- func GetHasServices(advertised, desired wire.ServiceFlag) bool
- func GetIsWhitelisted(statecfg *state.Config, addr net.Addr) bool
- func HandleAddNode(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleAskWallet(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleCreateRawTransaction(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleDecodeRawTransaction(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleDecodeScript(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleEstimateFee(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGenerate(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetAddedNodeInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetBestBlock(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetBestBlockHash(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetBlock(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetBlockChainInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetBlockCount(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetBlockHash(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetBlockHeader(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetBlockTemplate(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetBlockTemplateLongPoll(s *Server, longPollID string, useCoinbaseValue bool, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetBlockTemplateProposal(s *Server, request *btcjson.TemplateRequest) (interface{}, error)
- func HandleGetBlockTemplateRequest(s *Server, request *btcjson.TemplateRequest, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetCFilter(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetCFilterHeader(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetConnectionCount(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetCurrentNet(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetDifficulty(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetGenerate(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetHashesPerSec(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetHeaders(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (ret interface{}, err error)
- func HandleGetMempoolInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetMiningInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (ret interface{}, err error)
- func HandleGetNetTotals(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetNetworkHashPS(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetPeerInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetRawMempool(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetRawTransaction(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetTxOut(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetWork(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleGetWorkSubmission(s *Server, hexData string) (interface{}, error)
- func HandleHelp(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleLoadTxFilter(wsc *WSClient, icmd interface{}) (interface{}, error)
- func HandleNode(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleNotifyBlocks(wsc *WSClient, icmd interface{}) (interface{}, error)
- func HandleNotifyNewTransactions(wsc *WSClient, icmd interface{}) (interface{}, error)
- func HandleNotifyReceived(wsc *WSClient, icmd interface{}) (interface{}, error)
- func HandleNotifySpent(wsc *WSClient, icmd interface{}) (interface{}, error)
- func HandlePing(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleRescan(wsc *WSClient, icmd interface{}) (interface{}, error)
- func HandleRescanBlocks(wsc *WSClient, icmd interface{}) (interface{}, error)
- func HandleRestart(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleSearchRawTransactions(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleSendRawTransaction(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleSession(wsc *WSClient, icmd interface{}) (interface{}, error)
- func HandleSetGenerate(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleStop(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleStopNotifyBlocks(wsc *WSClient, icmd interface{}) (interface{}, error)
- func HandleStopNotifyNewTransactions(wsc *WSClient, icmd interface{}) (interface{}, error)
- func HandleStopNotifyReceived(wsc *WSClient, icmd interface{}) (interface{}, error)
- func HandleStopNotifySpent(wsc *WSClient, icmd interface{}) (interface{}, error)
- func HandleSubmitBlock(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleUnimplemented(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleUptime(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleValidateAddress(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleVerifyChain(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleVerifyMessage(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleVersion(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
- func HandleWebsocketHelp(wsc *WSClient, icmd interface{}) (interface{}, error)
- func InitListeners(config *pod.Config, activeNet *netparams.Params, aMgr *addrmgr.AddrManager, ...) ([]net.Listener, upnp.NAT, error)
- func InternalRPCError(errStr, context string) *btcjson.RPCError
- func JSONAuthFail(w http.ResponseWriter)
- func MergeCheckpoints(defaultCheckpoints, additional []chaincfg.Checkpoint) []chaincfg.Checkpoint
- func MessageToHex(msg wire.Message) (string, error)
- func NewPeerConfig(sp *NodePeer) *peer.Config
- func NewRedeemingTxNotification(txHex string, index int, block *util.Block) ([]byte, error)
- func NoTxInfoError(txHash *chainhash.Hash) *btcjson.RPCError
- func NormalizeAddress(addr, defaultPort string) string
- func ParseListeners(addrs []string) ([]net.Addr, error)
- func PeerExists(connMgr ServerConnManager, addr string, nodeID int32) bool
- func QueueHandler(in <-chan interface{}, out chan<- interface{}, quit <-chan struct{})
- func RandomUint16Number(max uint16) uint16
- func RecoverFromReorg(chain *blockchain.BlockChain, minBlock, maxBlock int32, ...) ([]chainhash.Hash, error)
- func RescanBlock(wsc *WSClient, lookups *RescanKeys, blk *util.Block)
- func RescanBlockFilter(filter *WSClientFilter, block *util.Block, params *netparams.Params) []string
- func ReverseUint32Array(b []byte)
- func SetupRPCListeners(config *pod.Config, urls []string) ([]net.Listener, error)
- func SoftForkStatus(state blockchain.ThresholdState) (string, error)
- func TxHexString(tx *wire.MsgTx) string
- func VerifyChain(s *Server, level, depth int32) error
- func WitnessToHex(witness wire.TxWitness) []string
- type BroadcastInventoryAdd
- type BroadcastInventoryDel
- type BroadcastMsg
- type CFHeaderKV
- type CheckpointSorter
- type CommandHandler
- type ConnManager
- func (cm *ConnManager) AddRebroadcastInventory(iv *wire.InvVect, data interface{})
- func (cm *ConnManager) BroadcastMessage(msg wire.Message)
- func (cm *ConnManager) Connect(addr string, permanent bool) error
- func (cm *ConnManager) ConnectedCount() int32
- func (cm *ConnManager) ConnectedPeers() []ServerPeer
- func (cm *ConnManager) DisconnectByAddr(addr string) error
- func (cm *ConnManager) DisconnectByID(id int32) error
- func (cm *ConnManager) NetTotals() (uint64, uint64)
- func (cm *ConnManager) PersistentPeers() []ServerPeer
- func (cm *ConnManager) RelayTransactions(txns []*mempool.TxDesc)
- func (cm *ConnManager) RemoveByAddr(addr string) error
- func (cm *ConnManager) RemoveByID(id int32) error
- type ConnectNodeMsg
- type DisconnectNodeMsg
- type GBTWorkState
- func (state *GBTWorkState) BlockTemplateResult(useCoinbaseValue bool, submitOld *bool) (*btcjson.GetBlockTemplateResult, error)
- func (state *GBTWorkState) NotifyBlockConnected(blockHash *chainhash.Hash)
- func (state *GBTWorkState) NotifyLongPollers(latestHash *chainhash.Hash, lastGenerated time.Time)
- func (state *GBTWorkState) NotifyMempoolTx(lastUpdated time.Time)
- func (state *GBTWorkState) TemplateUpdateChan(prevHash *chainhash.Hash, lastGenerated int64) chan struct{}
- func (state *GBTWorkState) UpdateBlockTemplate(s *Server, useCoinbaseValue bool) error
- type GetAddedNodesMsg
- type GetConnCountMsg
- type GetOutboundGroup
- type GetPeersMsg
- type HelpCacher
- type Node
- func (s *Node) AddBytesReceived(bytesReceived uint64)
- func (s *Node) AddBytesSent(bytesSent uint64)
- func (s *Node) AddPeer(sp *NodePeer)
- func (s *Node) AddRebroadcastInventory(iv *wire.InvVect, data interface{})
- func (s *Node) AnnounceNewTransactions(txns []*mempool.TxDesc)
- func (s *Node) BanPeer(sp *NodePeer)
- func (s *Node) BroadcastMessage(msg wire.Message, exclPeers ...*NodePeer)
- func (s *Node) ConnectedCount() int32
- func (s *Node) HandleAddPeerMsg(state *PeerState, sp *NodePeer) bool
- func (s *Node) HandleBanPeerMsg(state *PeerState, sp *NodePeer)
- func (s *Node) HandleBroadcastMsg(state *PeerState, bmsg *BroadcastMsg)
- func (s *Node) HandleDonePeerMsg(state *PeerState, sp *NodePeer)
- func (s *Node) HandleQuery(state *PeerState, querymsg interface{})
- func (s *Node) HandleRelayInvMsg(state *PeerState, msg RelayMsg)
- func (s *Node) HandleUpdatePeerHeights(state *PeerState, umsg UpdatePeerHeightsMsg)
- func (s *Node) InboundPeerConnected(conn net.Conn)
- func (s *Node) NetTotals() (uint64, uint64)
- func (s *Node) OutboundGroupCount(key string) int
- func (s *Node) OutboundPeerConnected(c *connmgr.ConnReq, conn net.Conn)
- func (s *Node) PeerDoneHandler(sp *NodePeer)
- func (s *Node) PeerHandler()
- func (s *Node) PushBlockMsg(sp *NodePeer, hash *chainhash.Hash, doneChan chan<- struct{}, ...) error
- func (s *Node) PushMerkleBlockMsg(sp *NodePeer, hash *chainhash.Hash, doneChan chan<- struct{}, ...) error
- func (s *Node) PushTxMsg(sp *NodePeer, hash *chainhash.Hash, doneChan chan<- struct{}, ...) error
- func (s *Node) RebroadcastHandler()
- func (s *Node) RelayInventory(invVect *wire.InvVect, data interface{})
- func (s *Node) RelayTransactions(txns []*mempool.TxDesc)
- func (s *Node) RemoveRebroadcastInventory(iv *wire.InvVect)
- func (s *Node) ScheduleShutdown(duration time.Duration)
- func (s *Node) Start()
- func (s *Node) Stop() error
- func (s *Node) TransactionConfirmed(tx *util.Tx)
- func (s *Node) UPNPUpdateThread()
- func (s *Node) UpdatePeerHeights(latestBlkHash *chainhash.Hash, latestHeight int32, updateSource *peer.Peer)
- func (s *Node) WaitForShutdown()
- type NodePeer
- func (sp *NodePeer) AddBanScore(persistent, transient uint32, reason string)
- func (sp *NodePeer) AddKnownAddresses(addresses []*wire.NetAddress)
- func (sp *NodePeer) EnforceNodeBloomFlag(cmd string) bool
- func (sp *NodePeer) GetNewestBlock() (*chainhash.Hash, int32, error)
- func (sp *NodePeer) IsAddressKnown(na *wire.NetAddress) bool
- func (sp *NodePeer) IsRelayTxDisabled() bool
- func (sp *NodePeer) OnAddr(_ *peer.Peer, msg *wire.MsgAddr)
- func (sp *NodePeer) OnBlock(_ *peer.Peer, msg *wire.MsgBlock, buf []byte)
- func (sp *NodePeer) OnFeeFilter(_ *peer.Peer, msg *wire.MsgFeeFilter)
- func (sp *NodePeer) OnFilterAdd(_ *peer.Peer, msg *wire.MsgFilterAdd)
- func (sp *NodePeer) OnFilterClear(_ *peer.Peer, msg *wire.MsgFilterClear)
- func (sp *NodePeer) OnFilterLoad(_ *peer.Peer, msg *wire.MsgFilterLoad)
- func (sp *NodePeer) OnGetAddr(_ *peer.Peer, msg *wire.MsgGetAddr)
- func (sp *NodePeer) OnGetBlocks(_ *peer.Peer, msg *wire.MsgGetBlocks)
- func (sp *NodePeer) OnGetCFCheckpt(_ *peer.Peer, msg *wire.MsgGetCFCheckpt)
- func (sp *NodePeer) OnGetCFHeaders(_ *peer.Peer, msg *wire.MsgGetCFHeaders)
- func (sp *NodePeer) OnGetCFilters(_ *peer.Peer, msg *wire.MsgGetCFilters)
- func (sp *NodePeer) OnGetData(_ *peer.Peer, msg *wire.MsgGetData)
- func (sp *NodePeer) OnGetHeaders(_ *peer.Peer, msg *wire.MsgGetHeaders)
- func (sp *NodePeer) OnHeaders(_ *peer.Peer, msg *wire.MsgHeaders)
- func (sp *NodePeer) OnInv(_ *peer.Peer, msg *wire.MsgInv)
- func (sp *NodePeer) OnMemPool(_ *peer.Peer, msg *wire.MsgMemPool)
- func (sp *NodePeer) OnRead(_ *peer.Peer, bytesRead int, msg wire.Message, err error)
- func (sp *NodePeer) OnTx(_ *peer.Peer, msg *wire.MsgTx)
- func (sp *NodePeer) OnVersion(_ *peer.Peer, msg *wire.MsgVersion) *wire.MsgReject
- func (sp *NodePeer) OnWrite(_ *peer.Peer, bytesWritten int, msg wire.Message, err error)
- func (sp *NodePeer) PreparePushAddrMsg(addresses []*wire.NetAddress)
- func (sp *NodePeer) SetDisableRelayTx(disable bool)
- type NotificationBlockConnected
- type NotificationBlockDisconnected
- type NotificationRegisterAddr
- type NotificationRegisterBlocks
- type NotificationRegisterClient
- type NotificationRegisterNewMempoolTxs
- type NotificationRegisterSpent
- type NotificationTxAcceptedByMempool
- type NotificationUnregisterAddr
- type NotificationUnregisterBlocks
- type NotificationUnregisterClient
- type NotificationUnregisterNewMempoolTxs
- type NotificationUnregisterSpent
- type OnionAddr
- type ParsedRPCCmd
- type Peer
- type PeerState
- type RelayMsg
- type RemoveNodeMsg
- type RescanKeys
- type RetrievedTx
- type Semaphore
- type Server
- func (s *Server) CheckAuth(r *http.Request, require bool) (bool, bool, error)
- func (s *Server) DecrementClients()
- func (s *Server) HTTPStatusLine(req *http.Request, code int) string
- func (s *Server) HandleBlockchainNotification(notification *blockchain.Notification)
- func (s *Server) IncrementClients()
- func (s *Server) JSONRPCRead(w http.ResponseWriter, r *http.Request, isAdmin bool)
- func (s *Server) LimitConnections(w http.ResponseWriter, remoteAddr string) bool
- func (s *Server) NotifyNewTransactions(txns []*mempool.TxDesc)
- func (s *Server) RequestedProcessShutdown() <-chan struct{}
- func (s *Server) StandardCmdResult(cmd *ParsedRPCCmd, closeChan <-chan struct{}) (interface{}, error)
- func (s *Server) Start()
- func (s *Server) Stop() error
- func (s *Server) WebsocketHandler(conn *websocket.Conn, remoteAddr string, authenticated bool, isAdmin bool)
- func (s *Server) WriteHTTPResponseHeaders(req *http.Request, headers http.Header, code int, w io.Writer) error
- type ServerConfig
- type ServerConnManager
- type ServerPeer
- type ServerSyncManager
- type SimpleAddr
- type SyncManager
- func (b *SyncManager) IsCurrent() bool
- func (b *SyncManager) LocateHeaders(locators []*chainhash.Hash, hashStop *chainhash.Hash) []wire.BlockHeader
- func (b *SyncManager) Pause() chan<- struct{}
- func (b *SyncManager) SubmitBlock(block *util.Block, flags blockchain.BehaviorFlags) (bool, error)
- func (b *SyncManager) SyncPeerID() int32
- type UpdatePeerHeightsMsg
- type WSClient
- func (c *WSClient) Disconnect()
- func (c *WSClient) InHandler()
- func (c *WSClient) IsDisconnected() bool
- func (c *WSClient) NotificationQueueHandler()
- func (c *WSClient) OutHandler()
- func (c *WSClient) QueueNotification(marshalledJSON []byte) error
- func (c *WSClient) SendMessage(marshalledJSON []byte, doneChan chan bool)
- func (c *WSClient) ServiceRequest(r *ParsedRPCCmd)
- func (c *WSClient) Start()
- func (c *WSClient) WaitForShutdown()
- type WSClientFilter
- func (f *WSClientFilter) AddAddress(a util.Address)
- func (f *WSClientFilter) AddAddressStr(s string, params *netparams.Params)
- func (f *WSClientFilter) AddUnspentOutPoint(op *wire.OutPoint)
- func (f *WSClientFilter) ExistsAddress(a util.Address) bool
- func (f *WSClientFilter) ExistsUnspentOutPoint(op *wire.OutPoint) bool
- type WSCommandHandler
- type WSNtfnMgr
- func (*WSNtfnMgr) AddAddrRequests(addrMap map[string]map[chan struct{}]*WSClient, wsc *WSClient, addrs []string)
- func (m *WSNtfnMgr) AddClient(wsc *WSClient)
- func (m *WSNtfnMgr) AddSpentRequests(opMap map[...]map[chan struct{}]*WSClient, wsc *WSClient, ops []*wire.OutPoint)
- func (m *WSNtfnMgr) GetNumClients() (n int)
- func (m *WSNtfnMgr) GetSubscribedClients(tx *util.Tx, clients map[chan struct{}]*WSClient) map[chan struct{}]struct{}
- func (m *WSNtfnMgr) NotificationHandler()
- func (*WSNtfnMgr) NotifyBlockConnected(clients map[chan struct{}]*WSClient, block *util.Block)
- func (*WSNtfnMgr) NotifyBlockDisconnected(clients map[chan struct{}]*WSClient, block *util.Block)
- func (m *WSNtfnMgr) NotifyFilteredBlockConnected(clients map[chan struct{}]*WSClient, block *util.Block)
- func (*WSNtfnMgr) NotifyFilteredBlockDisconnected(clients map[chan struct{}]*WSClient, block *util.Block)
- func (m *WSNtfnMgr) NotifyForNewTx(clients map[chan struct{}]*WSClient, tx *util.Tx)
- func (m *WSNtfnMgr) NotifyForTx(ops map[wire.OutPoint]map[chan struct{}]*WSClient, ...)
- func (m *WSNtfnMgr) NotifyForTxIns(ops map[...]map[chan struct{}]*WSClient, tx *util.Tx, block *util.Block)
- func (m *WSNtfnMgr) NotifyForTxOuts(ops map[wire.OutPoint]map[chan struct{}]*WSClient, ...)
- func (m *WSNtfnMgr) NotifyRelevantTxAccepted(tx *util.Tx, clients map[chan struct{}]*WSClient)
- func (m *WSNtfnMgr) QueueHandler()
- func (m *WSNtfnMgr) RegisterBlockUpdates(wsc *WSClient)
- func (m *WSNtfnMgr) RegisterNewMempoolTxsUpdates(wsc *WSClient)
- func (m *WSNtfnMgr) RegisterSpentRequests(wsc *WSClient, ops []*wire.OutPoint)
- func (m *WSNtfnMgr) RegisterTxOutAddressRequests(wsc *WSClient, addrs []string)
- func (*WSNtfnMgr) RemoveAddrRequest(addrs map[string]map[chan struct{}]*WSClient, wsc *WSClient, addr string)
- func (m *WSNtfnMgr) RemoveClient(wsc *WSClient)
- func (*WSNtfnMgr) RemoveSpentRequest(ops map[...]map[chan struct{}]*WSClient, wsc *WSClient, op *wire.OutPoint)
- func (m *WSNtfnMgr) SendNotifyBlockConnected(block *util.Block)
- func (m *WSNtfnMgr) SendNotifyBlockDisconnected(block *util.Block)
- func (m *WSNtfnMgr) SendNotifyMempoolTx(tx *util.Tx, isNew bool)
- func (m *WSNtfnMgr) Shutdown()
- func (m *WSNtfnMgr) Start()
- func (m *WSNtfnMgr) UnregisterBlockUpdates(wsc *WSClient)
- func (m *WSNtfnMgr) UnregisterNewMempoolTxsUpdates(wsc *WSClient)
- func (m *WSNtfnMgr) UnregisterSpentRequest(wsc *WSClient, op *wire.OutPoint)
- func (m *WSNtfnMgr) UnregisterTxOutAddressRequest(wsc *WSClient, addr string)
- func (m *WSNtfnMgr) WaitForShutdown()
- type WSResponse
Constants ¶
const ( JSONRPCSemverString = "1.3.0" JSONRPCSemverMajor = 1 JSONRPCSemverMinor = 3 JSONRPCSemverPatch = 0 // RPCAuthTimeoutSeconds is the number of seconds a connection to the RPC // server is allowed to stay open without authenticating before it is // closed. RPCAuthTimeoutSeconds = 10 // GBTNonceRange is two 32-bit big-endian hexadecimal integers which // represent the valid ranges of nonces returned by the getblocktemplate // RPC. GBTNonceRange = "00000000ffffffff" // GBTRegenerateSeconds is the number of seconds that must pass before a // new template is generated when the previous block hash has not changed // and there have been changes to the available transactions in the // memory pool. GBTRegenerateSeconds = 60 // MaxProtocolVersion is the max protocol version the server supports. MaxProtocolVersion = 70002 )
API version constants
const ( // DefaultServices describes the default services that are supported by // the server. DefaultServices = wire.SFNodeNetwork | wire.SFNodeBloom | wire.SFNodeWitness | wire.SFNodeCF // DefaultRequiredServices describes the default services that are required // to be supported by outbound peers. DefaultRequiredServices = wire.SFNodeNetwork // DefaultTargetOutbound is the default number of outbound peers to target. DefaultTargetOutbound = 125 // ConnectionRetryInterval is the base amount of time to wait in between // retries when connecting to persistent peers. It is adjusted by the // number of retries such that there is a retry backoff. ConnectionRetryInterval = time.Second )
const DefaultMaxOrphanTxSize = 100000
const Uint256Size = 32
Uint256Size is the number of bytes needed to represent an unsigned 256-bit integer.
const ( // WebsocketSendBufferSize is the number of elements the send channel can // queue before blocking. Note that this only applies to requests handled // directly in the websocket client input handler or the async handler since // notifications have their own queuing mechanism independent of the send // channel buffer. WebsocketSendBufferSize = 50 )
Variables ¶
var ( // ErrRPCNoWallet is an error returned to RPC clients when the provided // command is recognized as a wallet command. ErrRPCNoWallet = &btcjson.RPCError{ Code: btcjson.ErrRPCNoWallet, Message: "This implementation does not implement wallet commands", } // ErrRPCUnimplemented is an error returned to RPC clients when the // provided command is recognized, but not implemented. ErrRPCUnimplemented = &btcjson.RPCError{ Code: btcjson.ErrRPCUnimplemented, Message: "Command unimplemented", } // GBTCapabilities describes additional capabilities returned with a // block template generated by the getblocktemplate RPC. // It is declared here to avoid the overhead of creating the slice on // every invocation for constant data. GBTCapabilities = []string{"proposal"} // GBTCoinbaseAux describes additional data that miners should include in // the coinbase signature script. // It is declared here to avoid the overhead of creating a new object on // every invocation for constant data. GBTCoinbaseAux = &btcjson.GetBlockTemplateResultAux{ Flags: hex.EncodeToString(BuilderScript(txscript. NewScriptBuilder(). AddData([]byte(mining.CoinbaseFlags)))), } // GBTMutableFields are the manipulations the server allows to be made to // block templates generated by the getblocktemplate RPC. // It is declared here to avoid the overhead of creating the slice on // every invocation for constant data. GBTMutableFields = []string{ "time", "transactions/add", "prevblock", "coinbase/append", } // RPCAskWallet is list of commands that we recognize, // but for which pod has no support because it lacks support for wallet // functionality. For these commands the user should ask a connected // instance of btcwallet. RPCAskWallet = map[string]struct{}{ "addmultisigaddress": {}, "backupwallet": {}, "createencryptedwallet": {}, "createmultisig": {}, "dumpprivkey": {}, "dumpwallet": {}, "encryptwallet": {}, "getaccount": {}, "getaccountaddress": {}, "getaddressesbyaccount": {}, "getbalance": {}, "getnewaddress": {}, "getrawchangeaddress": {}, "getreceivedbyaccount": {}, "getreceivedbyaddress": {}, "gettransaction": {}, "gettxoutsetinfo": {}, "getunconfirmedbalance": {}, "getwalletinfo": {}, "importprivkey": {}, "importwallet": {}, "keypoolrefill": {}, "listaccounts": {}, "listaddressgroupings": {}, "listlockunspent": {}, "listreceivedbyaccount": {}, "listreceivedbyaddress": {}, "listsinceblock": {}, "listtransactions": {}, "listunspent": {}, "lockunspent": {}, "move": {}, "sendfrom": {}, "sendmany": {}, "sendtoaddress": {}, "setaccount": {}, "settxfee": {}, "signmessage": {}, "signrawtransaction": {}, "walletlock": {}, "walletpassphrase": {}, "walletpassphrasechange": {}, } // RPCHandlers maps RPC command strings to appropriate handler functions. // This is set by init because help references RPCHandlers and thus // causes a dependency loop. RPCHandlers map[string]CommandHandler // RPCHandlersBeforeInit is RPCHandlersBeforeInit = map[string]CommandHandler{ "addnode": HandleAddNode, "createrawtransaction": HandleCreateRawTransaction, "decoderawtransaction": HandleDecodeRawTransaction, "decodescript": HandleDecodeScript, "estimatefee": HandleEstimateFee, "generate": HandleGenerate, "getaddednodeinfo": HandleGetAddedNodeInfo, "getbestblock": HandleGetBestBlock, "getbestblockhash": HandleGetBestBlockHash, "getblock": HandleGetBlock, "getblockchaininfo": HandleGetBlockChainInfo, "getblockcount": HandleGetBlockCount, "getblockhash": HandleGetBlockHash, "getblockheader": HandleGetBlockHeader, "getblocktemplate": HandleGetBlockTemplate, "getcfilter": HandleGetCFilter, "getcfilterheader": HandleGetCFilterHeader, "getconnectioncount": HandleGetConnectionCount, "getcurrentnet": HandleGetCurrentNet, "getdifficulty": HandleGetDifficulty, "getgenerate": HandleGetGenerate, "gethashespersec": HandleGetHashesPerSec, "getheaders": HandleGetHeaders, "getinfo": HandleGetInfo, "getmempoolinfo": HandleGetMempoolInfo, "getmininginfo": HandleGetMiningInfo, "getnettotals": HandleGetNetTotals, "getnetworkhashps": HandleGetNetworkHashPS, "getpeerinfo": HandleGetPeerInfo, "getrawmempool": HandleGetRawMempool, "getrawtransaction": HandleGetRawTransaction, "gettxout": HandleGetTxOut, "getwork": HandleGetWork, "help": HandleHelp, "node": HandleNode, "ping": HandlePing, "searchrawtransactions": HandleSearchRawTransactions, "sendrawtransaction": HandleSendRawTransaction, "setgenerate": HandleSetGenerate, "stop": HandleStop, "restart": HandleRestart, "submitblock": HandleSubmitBlock, "uptime": HandleUptime, "validateaddress": HandleValidateAddress, "verifychain": HandleVerifyChain, "verifymessage": HandleVerifyMessage, "version": HandleVersion, } // RPCLimited isCommands that are available to a limited user RPCLimited = map[string]struct{}{ "loadtxfilter": {}, "notifyblocks": {}, "notifynewtransactions": {}, "notifyreceived": {}, "notifyspent": {}, "rescan": {}, "rescanblocks": {}, "session": {}, "help": {}, "createrawtransaction": {}, "decoderawtransaction": {}, "decodescript": {}, "estimatefee": {}, "getbestblock": {}, "getbestblockhash": {}, "getblock": {}, "getblockcount": {}, "getblockhash": {}, "getblockheader": {}, "getcfilter": {}, "getcfilterheader": {}, "getcurrentnet": {}, "getdifficulty": {}, "getheaders": {}, "getinfo": {}, "getnettotals": {}, "getnetworkhashps": {}, "getrawmempool": {}, "getrawtransaction": {}, "gettxout": {}, "searchrawtransactions": {}, "sendrawtransaction": {}, "submitblock": {}, "uptime": {}, "validateaddress": {}, "verifymessage": {}, "version": {}, } // RPCUnimplemented is commands that are currently unimplemented, // but should ultimately be. RPCUnimplemented = map[string]struct{}{ "estimatepriority": {}, "getchaintips": {}, "getmempoolentry": {}, "getnetworkinfo": {}, "getwork": {}, "invalidateblock": {}, "preciousblock": {}, "reconsiderblock": {}, } )
var ( // UserAgentName is the user agent name and is used to help identify // ourselves to peers. // nolint UserAgentName = "pod" // UserAgentVersion is the user agent version and is used to help identify // ourselves to peers. // nolint UserAgentVersion = fmt.Sprintf("%d.%d.%d", version.AppMajor, version.AppMinor, version.AppPatch) )
var DefaultConnectTimeout = time.Second * 30
DefaultConnectTimeout is a reasonable 30 seconds
var Dial = func(stateCfg *state.Config) func(addr net.Addr) (net.Conn, error) { return func(addr net.Addr) (net.Conn, error) { if strings.Contains(addr.String(), ".onion:") { return stateCfg.Oniondial(addr.Network(), addr.String(), DefaultConnectTimeout) } log.TRACE("StateCfg.Dial", addr.Network(), addr.String(), DefaultConnectTimeout) conn, er := stateCfg.Dial(addr.Network(), addr.String(), DefaultConnectTimeout) if er != nil { log.TRACE("connection error:", conn, er) } return conn, er } }
Dial connects to the address on the named network using the appropriate dial function depending on the address and configuration options. For example .onion addresses will be dialed using the onion specific proxy if one was specified, but will otherwise use the normal dial function ( which could itself use a proxy or not).
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.
var ErrRescanReorg = btcjson.RPCError{ Code: btcjson.ErrRPCDatabase, Message: "Reorganize", }
ErrRescanReorg defines the error that is returned when an unrecoverable reorganize is detected during a rescan.
var GetworkDataLen = (1 + ((wire.MaxBlockHeaderPayload + 8) / fastsha256. BlockSize)) * fastsha256.BlockSize
GetworkDataLen is the length of the data field of the getwork RPC. It consists of the serialized block header plus the internal sha256 padding. The internal sha256 padding consists of a single 1 bit followed by enough zeros to pad the message out to 56 bytes followed by length of the message in bits encoded as a big-endian uint64 (8 bytes). Thus, the resulting length is a multiple of the sha256 block size (64 bytes).
var Hash1Len = (1 + ((chainhash.HashSize + 8) / fastsha256. BlockSize)) * fastsha256.BlockSize
Hash1Len is the length of the hash1 field of the getwork RPC. It consists of a zero hash plus the internal sha256 padding. See the getworkDataLen comment for details about the internal sha256 padding format.
var HelpDescsEnUS = map[string]string{}/* 442 elements not displayed */
HelpDescsEnUS defines the English descriptions used for the help strings. nolint
var Lookup = func(stateCfg *state.Config) func(host string) ([]net.IP, error) { return func(host string) ([]net.IP, error) { if strings.HasSuffix(host, ".onion") { return nil, fmt.Errorf("attempt to resolve tor address %s", host) } return stateCfg.Lookup(host) } }
Lookup resolves the IP of the given host using the correct DNS lookup function depending on the configuration options. For example, addresses will be resolved using tor when the --proxy flag was specified unless --noonion was also specified in which case the normal system DNS resolver will be used. Any attempt to resolve a tor address (. onion) will return an error since they are not intended to be resolved outside of the tor proxy.
var ResultTypes = map[string][]interface{}{ "addnode": nil, "createrawtransaction": {(*string)(nil)}, "debuglevel": {(*string)(nil), (*string)(nil)}, "decoderawtransaction": {(*btcjson.TxRawDecodeResult)(nil)}, "decodescript": {(*btcjson.DecodeScriptResult)(nil)}, "estimatefee": {(*float64)(nil)}, "generate": {(*[]string)(nil)}, "getaddednodeinfo": {(*[]string)(nil), (*[]btcjson.GetAddedNodeInfoResult)(nil)}, "getbestblock": {(*btcjson.GetBestBlockResult)(nil)}, "getbestblockhash": {(*string)(nil)}, "getblock": {(*string)(nil), (*btcjson.GetBlockVerboseResult)(nil)}, "getblockcount": {(*int64)(nil)}, "getblockhash": {(*string)(nil)}, "getblockheader": {(*string)(nil), (*btcjson.GetBlockHeaderVerboseResult)(nil)}, "getblocktemplate": {(*btcjson.GetBlockTemplateResult)(nil), (*string)(nil), nil}, "getblockchaininfo": {(*btcjson.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": {(*btcjson.InfoChainResult)(nil)}, "getmempoolinfo": {(*btcjson.GetMempoolInfoResult)(nil)}, "getmininginfo": {(*btcjson.GetMiningInfoResult)(nil)}, "getnettotals": {(*btcjson.GetNetTotalsResult)(nil)}, "getnetworkhashps": {(*int64)(nil)}, "getpeerinfo": {(*[]btcjson.GetPeerInfoResult)(nil)}, "getrawmempool": {(*[]string)(nil), (*btcjson.GetRawMempoolVerboseResult)(nil)}, "getrawtransaction": {(*string)(nil), (*btcjson.TxRawResult)(nil)}, "gettxout": {(*btcjson.GetTxOutResult)(nil)}, "node": nil, "help": {(*string)(nil), (*string)(nil)}, "ping": nil, "searchrawtransactions": {(*string)(nil), (*[]btcjson.SearchRawTransactionsResult)(nil)}, "sendrawtransaction": {(*string)(nil)}, "setgenerate": nil, "stop": {(*string)(nil)}, "restart": {(*string)(nil)}, "submitblock": {nil, (*string)(nil)}, "uptime": {(*int64)(nil)}, "validateaddress": {(*btcjson.ValidateAddressChainResult)(nil)}, "verifychain": {(*bool)(nil)}, "verifymessage": {(*bool)(nil)}, "version": {(*map[string]btcjson.VersionResult)(nil)}, "loadtxfilter": nil, "session": {(*btcjson.SessionResult)(nil)}, "notifyblocks": nil, "stopnotifyblocks": nil, "notifynewtransactions": nil, "stopnotifynewtransactions": nil, "notifyreceived": nil, "stopnotifyreceived": nil, "notifyspent": nil, "stopnotifyspent": nil, "rescan": nil, "rescanblocks": {(*[]btcjson.RescannedBlock)(nil)}, }
ResultTypes specifies the result types that each RPC command can return. This information is used to generate the help. Each result type must be a pointer to the type (or nil to indicate no return value). nolint
var TimeZeroVal = time.Time{}
TimeZeroVal is simply the zero value for a time.Time and is used to avoid creating multiple instances. nolint
var WSHandlers map[string]WSCommandHandler
WSHandlers maps RPC command strings to appropriate websocket handler functions. This is set by init because help references WSHandlers and thus causes a dependency loop. nolint
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, }
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 ¶
AddrStringToNetAddr takes an address in the form of 'host:port' and returns a net.Addr which maps to the original address with any host names resolved to IP addresses. It also handles tor addresses properly by returning a net.Addr that encapsulates the address.
func BigToLEUint256 ¶
func BigToLEUint256(n *big.Int) [Uint256Size]byte
BigToLEUint256 returns the passed big integer as an unsigned 256-bit integer encoded as little-endian bytes. Numbers which are larger than the max unsigned 256-bit integer are truncated.
func BlockDetails ¶
func BlockDetails(block *util.Block, txIndex int) *btcjson.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 ¶
ChainErrToGBTErrString converts an error returned from btcchain to a string which matches the reasons and format described in BIP0022 for rejection reasons. nolint
func CheckAddressValidity ¶
CheckAddressValidity checks the validity of each address in the passed string slice. It does this by attempting to decode each address using the current active network parameters. If any single address fails to decode properly, the function returns an error. Otherwise, nil is returned.
func CreateMarshalledReply ¶
CreateMarshalledReply returns a new marshalled JSON-RPC response given the passed parameters. It will automatically convert errors that are not of the type *json.RPCError to the appropriate type as needed.
func CreateTxRawResult ¶
func CreateTxRawResult(chainParams *netparams.Params, mtx *wire.MsgTx, txHash string, blkHeader *wire.BlockHeader, blkHash string, blkHeight int32, chainHeight int32) (*btcjson.TxRawResult, error)
CreateTxRawResult converts the passed transaction and associated parameters to a raw transaction JSON object.
func CreateVinList ¶
CreateVinList returns a slice of JSON objects for the inputs of the passed transaction.
func CreateVinListPrevOut ¶
func CreateVinListPrevOut(s *Server, mtx *wire.MsgTx, chainParams *netparams.Params, vinExtra bool, filterAddrMap map[string]struct{}) ([]btcjson.VinPrevOut, error)
CreateVinListPrevOut returns a slice of JSON objects for the inputs of the passed transaction.
func CreateVoutList ¶
func CreateVoutList(mtx *wire.MsgTx, chainParams *netparams.Params, filterAddrMap map[string]struct{}) []btcjson.Vout
CreateVoutList returns a slice of JSON objects for the outputs of the passed transaction.
func DecodeHexError ¶
DecodeHexError is a convenience function for returning a nicely formatted RPC error which indicates the provided hex string failed to decode.
func DecodeTemplateID ¶
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 ¶
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 ¶
DeserializeOutpoints deserializes each serialized outpoint.
func DisconnectPeer ¶
func DisconnectPeer(peerList map[int32]*NodePeer, compareFunc func(*NodePeer) bool, whenFound func(*NodePeer)) bool
DisconnectPeer attempts to drop the connection of a targeted peer in the passed peer list. Targets are identified via usage of the passed `compareFunc`, which should return `true` if the passed peer is the target peer. This function returns true on success and false if the peer is unable to be located. If the peer is found, and the passed callback: `whenFound' isn't nil, we call it with the peer as the argument before it is removed from the peerList, and is disconnected from the server.
func DynamicTickDuration ¶
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 ¶
EncodeTemplateID encodes the passed details into an ID that can be used to uniquely identify a block template.
func FetchInputTxos ¶
FetchInputTxos fetches the outpoints from all transactions referenced by the inputs to the passed transaction by checking the transaction mempool first then the transaction index for those already mined into blocks.
func FetchMempoolTxnsForAddress ¶
func FetchMempoolTxnsForAddress(s *Server, addr util.Address, numToSkip, numRequested uint32) ([]*util.Tx, uint32)
FetchMempoolTxnsForAddress queries the address index for all unconfirmed transactions that involve the provided address. The results will be limited by the number to skip and the number requested.
func FileExists ¶
FileExists reports whether the named file or directory exists.
func GenCertPair ¶
GenCertPair generates a key/cert pair to the paths provided.
func GetDifficultyRatio ¶
GetDifficultyRatio returns the proof-of-work difficulty as a multiple of the minimum difficulty using the passed bits field from the header of a block.
func GetHasServices ¶
func GetHasServices(advertised, desired wire.ServiceFlag) bool
GetHasServices returns whether or not the provided advertised service flags have all of the provided desired service flags set.
func GetIsWhitelisted ¶
GetIsWhitelisted returns whether the IP address is included in the whitelisted networks and IPs.
func HandleAddNode ¶
HandleAddNode handles addnode commands.
func HandleAskWallet ¶
HandleAskWallet is the handler for commands that are recognized as valid, but are unable to answer correctly since it involves wallet state. These commands will be implemented in btcwallet.
func HandleCreateRawTransaction ¶
func HandleCreateRawTransaction(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleCreateRawTransaction handles createrawtransaction commands.
func HandleDecodeRawTransaction ¶
func HandleDecodeRawTransaction(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleDecodeRawTransaction handles decoderawtransaction commands.
func HandleDecodeScript ¶
HandleDecodeScript handles decodescript commands.
func HandleEstimateFee ¶
HandleEstimateFee handles estimatefee commands.
func HandleGenerate ¶
HandleGenerate handles generate commands.
func HandleGetAddedNodeInfo ¶
func HandleGetAddedNodeInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleGetAddedNodeInfo handles getaddednodeinfo commands.
func HandleGetBestBlock ¶
HandleGetBestBlock implements the getbestblock command.
func HandleGetBestBlockHash ¶
func HandleGetBestBlockHash(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleGetBestBlockHash implements the getbestblockhash command.
func HandleGetBlock ¶
HandleGetBlock implements the getblock command.
func HandleGetBlockChainInfo ¶
func HandleGetBlockChainInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleGetBlockChainInfo implements the getblockchaininfo command.
func HandleGetBlockCount ¶
func HandleGetBlockCount(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleGetBlockCount implements the getblockcount command.
func HandleGetBlockHash ¶
HandleGetBlockHash implements the getblockhash command.
func HandleGetBlockHeader ¶
func HandleGetBlockHeader(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleGetBlockHeader implements the getblockheader command.
func HandleGetBlockTemplate ¶
func HandleGetBlockTemplate(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleGetBlockTemplate implements the getblocktemplate command. See https:// en.bitcoin.it/wiki/BIP_0022 and https://en.bitcoin.it/wiki/BIP_0023 for more details.
func HandleGetBlockTemplateLongPoll ¶
func HandleGetBlockTemplateLongPoll(s *Server, longPollID string, useCoinbaseValue bool, closeChan <-chan struct{}) (interface{}, error)
HandleGetBlockTemplateLongPoll is a helper for handleGetBlockTemplateRequest which deals with handling long polling for block templates. When a caller sends a request with a long poll ID that was previously returned, a response is not sent until the caller should stop working on the previous block template in favor of the new one. In particular, this is the case when the old block template is no longer valid due to a solution already being found and added to the block chain, or new transactions have shown up and some time has passed without finding a solution. See https://en.bitcoin.it/wiki/ BIP_0022 for more details.
func HandleGetBlockTemplateProposal ¶
func HandleGetBlockTemplateProposal(s *Server, request *btcjson.TemplateRequest) (interface{}, error)
HandleGetBlockTemplateProposal is a helper for handleGetBlockTemplate which deals with block proposals. See https://en.bitcoin.it/wiki/BIP_0023 for more details.
func HandleGetBlockTemplateRequest ¶
func HandleGetBlockTemplateRequest(s *Server, request *btcjson.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 ¶
HandleGetCFilter implements the getcfilter command.
func HandleGetCFilterHeader ¶
func HandleGetCFilterHeader(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleGetCFilterHeader implements the getcfilterheader command.
func HandleGetConnectionCount ¶
func HandleGetConnectionCount(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleGetConnectionCount implements the getconnectioncount command.
func HandleGetCurrentNet ¶
func HandleGetCurrentNet(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleGetCurrentNet implements the getcurrentnet command.
func HandleGetDifficulty ¶
func HandleGetDifficulty(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleGetDifficulty implements the getdifficulty command. TODO: This command should default to the configured algo for cpu mining
and take an optional parameter to query by algo
func HandleGetGenerate ¶
HandleGetGenerate implements the getgenerate command.
func HandleGetHashesPerSec ¶
func HandleGetHashesPerSec(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleGetHashesPerSec implements the gethashespersec command.
func HandleGetHeaders ¶
HandleGetHeaders implements the getheaders command. NOTE: This is a btcsuite extension originally ported from github.com/decred/dcrd.
func HandleGetInfo ¶
func HandleGetInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (ret interface{}, err error)
HandleGetInfo implements the getinfo command. We only return the fields that are not related to wallet functionality. TODO: simplify this, break it up
func HandleGetMempoolInfo ¶
func HandleGetMempoolInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleGetMempoolInfo implements the getmempoolinfo command.
func HandleGetMiningInfo ¶
func HandleGetMiningInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (ret interface{}, err error)
HandleGetMiningInfo implements the getmininginfo command. We only return the fields that are not related to wallet functionality. This function returns more information than parallelcoind. TODO: simplify this, break it up
func HandleGetNetTotals ¶
HandleGetNetTotals implements the getnettotals command.
func HandleGetNetworkHashPS ¶
func HandleGetNetworkHashPS(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleGetNetworkHashPS implements the getnetworkhashps command. This command does not default to the same end block as the parallelcoind. TODO: Really this needs to be expanded to show per-algorithm hashrates
func HandleGetPeerInfo ¶
HandleGetPeerInfo implements the getpeerinfo command.
func HandleGetRawMempool ¶
func HandleGetRawMempool(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleGetRawMempool implements the getrawmempool command.
func HandleGetRawTransaction ¶
func HandleGetRawTransaction(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleGetRawTransaction implements the getrawtransaction command.
func HandleGetTxOut ¶
HandleGetTxOut handles gettxout commands.
func HandleGetWork ¶
HandleGetWork handles the getwork call
func HandleGetWorkSubmission ¶
HandleGetWorkSubmission is a helper for handleGetWork which deals with the
calling submitting work to be verified and processed. This function MUST be called with the RPC workstate locked.
func HandleHelp ¶
HandleHelp implements the help command.
func HandleLoadTxFilter ¶
HandleLoadTxFilter implements the loadtxfilter command extension for websocket connections. NOTE: This extension is ported from github.com/decred/dcrd
func HandleNode ¶
HandleNode handles node commands.
func HandleNotifyBlocks ¶
HandleNotifyBlocks implements the notifyblocks command extension for websocket connections.
func HandleNotifyNewTransactions ¶
handleNotifyNewTransations implements the notifynewtransactions command extension for websocket connections.
func HandleNotifyReceived ¶
HandleNotifyReceived implements the notifyreceived command extension for websocket connections.
func HandleNotifySpent ¶
HandleNotifySpent implements the notifyspent command extension for websocket connections.
func HandlePing ¶
HandlePing implements the ping command.
func HandleRescan ¶
HandleRescan implements the rescan command extension for websocket connections. NOTE: This does not smartly handle reorgs, and fixing requires database changes (for safe, concurrent access to full block ranges, and support for other chains than the best chain). It will, however, detect whether a reorg removed a block that was previously processed, and result in the handler erroring. Clients must handle this by finding a block still in the chain (perhaps from a rescanprogress notification) to resume their rescan. TODO: simplify, modularise this
func HandleRescanBlocks ¶
HandleRescanBlocks implements the rescanblocks command extension for websocket connections. NOTE: This extension is ported from github.com/decred/dcrd
func HandleRestart ¶
HandleRestart implements the restart command.
func HandleSearchRawTransactions ¶
func HandleSearchRawTransactions(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleSearchRawTransactions implements the searchrawtransactions command. TODO: simplify this, break it up
func HandleSendRawTransaction ¶
func HandleSendRawTransaction(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleSendRawTransaction implements the sendrawtransaction command.
func HandleSession ¶
HandleSession implements the session command extension for websocket connections.
func HandleSetGenerate ¶
HandleSetGenerate implements the setgenerate command.
func HandleStop ¶
HandleStop implements the stop command.
func HandleStopNotifyBlocks ¶
HandleStopNotifyBlocks implements the stopnotifyblocks command extension for websocket connections.
func HandleStopNotifyNewTransactions ¶
handleStopNotifyNewTransations implements the stopnotifynewtransactions command extension for websocket connections.
func HandleStopNotifyReceived ¶
HandleStopNotifyReceived implements the stopnotifyreceived command extension for websocket connections.
func HandleStopNotifySpent ¶
HandleStopNotifySpent implements the stopnotifyspent command extension for websocket connections.
func HandleSubmitBlock ¶
HandleSubmitBlock implements the submitblock command.
func HandleUnimplemented ¶
func HandleUnimplemented(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleUnimplemented is the handler for commands that should ultimately be supported but are not yet implemented.
func HandleUptime ¶
HandleUptime implements the uptime command.
func HandleValidateAddress ¶
func HandleValidateAddress(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleValidateAddress implements the validateaddress command.
func HandleVerifyChain ¶
HandleVerifyChain implements the verifychain command.
func HandleVerifyMessage ¶
func HandleVerifyMessage(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
HandleVerifyMessage implements the verifymessage command.
func HandleVersion ¶
HandleVersion implements the version command. NOTE: This is a btcsuite extension ported from github.com/decred/dcrd.
func HandleWebsocketHelp ¶
HandleWebsocketHelp implements the help command for websocket connections.
func InitListeners ¶
func InitListeners(config *pod.Config, activeNet *netparams.Params, aMgr *addrmgr.AddrManager, listenAddrs []string, services wire.ServiceFlag) ([]net.Listener, upnp.NAT, error)
InitListeners initializes the configured net listeners and adds any bound addresses to the address manager. Returns the listeners and a upnp.NAT interface, which is non-nil if UPnP is in use.
func InternalRPCError ¶
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 l mayo be empty if it's not needed.
func JSONAuthFail ¶
func JSONAuthFail(w http.ResponseWriter)
JSONAuthFail sends a message back to the client if the http auth is rejected.
func MergeCheckpoints ¶
func MergeCheckpoints(defaultCheckpoints, additional []chaincfg.Checkpoint) []chaincfg.Checkpoint
func MessageToHex ¶
MessageToHex serializes a message to the wire protocol encoding using the latest protocol version and returns a hex-encoded string of the result.
func NewPeerConfig ¶
func NewRedeemingTxNotification ¶
NewRedeemingTxNotification returns a new marshalled redeemingtx notification with the passed parameters.
func NoTxInfoError ¶
NoTxInfoError is a convenience function for returning a nicely formatted RPC error which indicates there is no information available for the provided transaction hash.
func NormalizeAddress ¶
NormalizeAddress returns addr with the passed default port appended if there is not already a port specified.
func ParseListeners ¶
ParseListeners determines whether each listen address is IPv4 and IPv6 and returns a slice of appropriate net.Addrs to listen on with TCP. It also properly detects addresses which apply to "all interfaces" and adds the address as both IPv4 and IPv6.
func PeerExists ¶
func PeerExists(connMgr ServerConnManager, addr string, nodeID int32) bool
PeerExists determines if a certain peer is currently connected given information about all currently connected peers. Peer existence is determined using either a target address or node id.
func QueueHandler ¶
func QueueHandler(in <-chan interface{}, out chan<- interface{}, quit <-chan struct{})
QueueHandler manages a queue of empty interfaces, reading from in and sending the oldest unsent to out. This handler stops when either of the in or quit channels are closed, and closes out before returning, without waiting to send any variables still remaining in the queue.
func RandomUint16Number ¶
RandomUint16Number returns a random uint16 in a specified input range. Note that the range is in zeroth ordering; if you pass it 1800, you will get values from 0 to 1800.
func RecoverFromReorg ¶
func RecoverFromReorg(chain *blockchain.BlockChain, minBlock, maxBlock int32, lastBlock *chainhash.Hash) ([]chainhash.Hash, error)
RecoverFromReorg attempts to recover from a detected reorganize during a rescan. It fetches a new range of block shas from the database and verifies that the new range of blocks is on the same fork as a previous range of blocks. If this condition does not hold true, the JSON-RPC error for an unrecoverable reorganize is returned.
func RescanBlock ¶
func RescanBlock(wsc *WSClient, lookups *RescanKeys, blk *util.Block)
RescanBlock rescans all transactions in a single block. This is a helper function for handleRescan.
func RescanBlockFilter ¶
func RescanBlockFilter(filter *WSClientFilter, block *util.Block, params *netparams.Params) []string
RescanBlockFilter rescans a block for any relevant transactions for the passed lookup keys. Any discovered transactions are returned hex encoded as a string slice. NOTE: This extension is ported from github.com/decred/dcrd
func ReverseUint32Array ¶
func ReverseUint32Array(b []byte)
ReverseUint32Array treats the passed bytes as a series of uint32s and reverses the byte order of each uint32. The passed byte slice must be a multiple of 4 for a correct result. The passed bytes slice is modified.
func SetupRPCListeners ¶
SetupRPCListeners returns a slice of listeners that are configured for use with the RPC server depending on the configuration settings for listen addresses and TLS.
func SoftForkStatus ¶
func SoftForkStatus(state blockchain.ThresholdState) (string, error)
SoftForkStatus converts a ThresholdState state into a human readable string corresponding to the particular state.
func TxHexString ¶
TxHexString returns the serialized transaction encoded in hexadecimal.
func WitnessToHex ¶
// handleDebugLevel handles debuglevel commands.
func handleDebugLevel( s *RPCServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*json.DebugLevelCmd) // Special show command to list supported subsystems. if c.LevelSpec == "show" { return fmt.Sprintf("Supported subsystems %v", supportedSubsystems()), nil } err := parseAndSetDebugLevels(c.LevelSpec) if err != nil { return nil, &json.RPCError{ Code: json.ErrRPCInvalidParams.Code, Message: err.Error(), } } return "Done.", nil }
WitnessToHex formats the passed witness stack as a slice of hex-encoded strings to be used in a JSON response.
Types ¶
type BroadcastInventoryAdd ¶
type BroadcastInventoryAdd RelayMsg
BroadcastInventoryAdd is a type used to declare that the InvVect it contains needs to be added to the rebroadcast map
type BroadcastInventoryDel ¶
BroadcastInventoryDel is a type used to declare that the InvVect it contains needs to be removed from the rebroadcast map
type BroadcastMsg ¶
BroadcastMsg provides the ability to house a bitcoin message to be broadcast to all connected peers except specified excluded peers.
type CFHeaderKV ¶
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 ConnManager ¶
type ConnManager struct {
// contains filtered or unexported fields
}
ConnManager provides a connection manager for use with the RPC server and implements the rpcserver ConnManager interface.
func (*ConnManager) AddRebroadcastInventory ¶
func (cm *ConnManager) AddRebroadcastInventory(iv *wire.InvVect, data interface{})
AddRebroadcastInventory adds the provided inventory to the list of inventories to be rebroadcast at random intervals until they show up in a block. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.
func (*ConnManager) BroadcastMessage ¶
func (cm *ConnManager) BroadcastMessage(msg wire.Message)
BroadcastMessage sends the provided message to all currently connected peers. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.
func (*ConnManager) Connect ¶
func (cm *ConnManager) Connect(addr string, permanent bool) error
Connect adds the provided address as a new outbound peer. The permanent flag indicates whether or not to make the peer persistent and reconnect if the connection is lost. Attempting to connect to an already existing peer will return an error. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.
func (*ConnManager) ConnectedCount ¶
func (cm *ConnManager) ConnectedCount() int32
ConnectedCount returns the number of currently connected peers. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.
func (*ConnManager) ConnectedPeers ¶
func (cm *ConnManager) ConnectedPeers() []ServerPeer
ConnectedPeers returns an array consisting of all connected peers. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.
func (*ConnManager) DisconnectByAddr ¶
func (cm *ConnManager) DisconnectByAddr(addr string) error
DisconnectByAddr disconnects the peer associated with the provided address. This applies to both inbound and outbound peers. Attempting to remove an address that does not exist will return an error. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.
func (*ConnManager) DisconnectByID ¶
func (cm *ConnManager) DisconnectByID(id int32) error
DisconnectByID disconnects the peer associated with the provided id. This applies to both inbound and outbound peers. Attempting to remove an id that does not exist will return an error. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.
func (*ConnManager) NetTotals ¶
func (cm *ConnManager) NetTotals() (uint64, uint64)
NetTotals returns the sum of all bytes received and sent across the network for all peers. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.
func (*ConnManager) PersistentPeers ¶
func (cm *ConnManager) PersistentPeers() []ServerPeer
PersistentPeers returns an array consisting of all the added persistent peers. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.
func (*ConnManager) RelayTransactions ¶
func (cm *ConnManager) RelayTransactions(txns []*mempool.TxDesc)
RelayTransactions generates and relays inventory vectors for all of the passed transactions to all connected peers.
func (*ConnManager) RemoveByAddr ¶
func (cm *ConnManager) RemoveByAddr(addr string) error
RemoveByAddr removes the peer associated with the provided address from the list of persistent peers. Attempting to remove an address that does not exist will return an error. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.
func (*ConnManager) RemoveByID ¶
func (cm *ConnManager) RemoveByID(id int32) error
RemoveByID removes the peer associated with the provided id from the list of persistent peers. Attempting to remove an id that does not exist will return an error. This function is safe for concurrent access and is part of the RPCServerConnManager interface implementation.
type ConnectNodeMsg ¶
type DisconnectNodeMsg ¶
type GBTWorkState ¶
type GBTWorkState struct { sync.Mutex LastTxUpdate time.Time LastGenerated time.Time MinTimestamp time.Time Template *mining.BlockTemplate NotifyMap map[chainhash.Hash]map[int64]chan struct{} TimeSource blockchain.MedianTimeSource Algo string StateCfg *state.Config Config *pod.Config // contains filtered or unexported fields }
GBTWorkState houses state that is used in between multiple RPC invocations to getblocktemplate.
func NewGbtWorkState ¶
func NewGbtWorkState(timeSource blockchain.MedianTimeSource, algoName string) *GBTWorkState
NewGbtWorkState returns a new instance of a GBTWorkState with all internal fields initialized and ready to use.
func (*GBTWorkState) BlockTemplateResult ¶
func (state *GBTWorkState) BlockTemplateResult(useCoinbaseValue bool, submitOld *bool) ( *btcjson.GetBlockTemplateResult, error, )
BlockTemplateResult returns the current block template associated with the state as a json.GetBlockTemplateResult that is ready to be encoded to JSON and returned to the caller. This function MUST be called with the state locked.
func (*GBTWorkState) NotifyBlockConnected ¶
func (state *GBTWorkState) NotifyBlockConnected(blockHash *chainhash.Hash)
NotifyBlockConnected uses the newly-connected block to notify any long poll clients with a new block template when their existing block template is stale due to the newly connected block.
func (*GBTWorkState) NotifyLongPollers ¶
func (state *GBTWorkState) NotifyLongPollers(latestHash *chainhash.Hash, lastGenerated time.Time)
NotifyLongPollers notifies any channels that have been registered to be notified when block templates are stale. This function MUST be called with the state locked.
func (*GBTWorkState) NotifyMempoolTx ¶
func (state *GBTWorkState) NotifyMempoolTx(lastUpdated time.Time)
NotifyMempoolTx uses the new last updated time for the transaction memory pool to notify any long poll clients with a new block template when their existing block template is stale due to enough time passing and the contents of the memory pool changing.
func (*GBTWorkState) TemplateUpdateChan ¶
func (state *GBTWorkState) TemplateUpdateChan(prevHash *chainhash.Hash, lastGenerated int64) chan struct{}
TemplateUpdateChan returns a channel that will be closed once the block template associated with the passed previous hash and last generated time is stale. The function will return existing channels for duplicate parameters which allows to wait for the same block template without requiring a different channel for each client. This function MUST be called with the state locked.
func (*GBTWorkState) UpdateBlockTemplate ¶
func (state *GBTWorkState) UpdateBlockTemplate(s *Server, useCoinbaseValue bool) error
UpdateBlockTemplate creates or updates a block template for the work state. A new block template will be generated when the current best block has changed or the transactions in the memory pool have been updated and it has been long enough since the last template was generated. Otherwise, the timestamp for the existing block template is updated (and possibly the difficulty on testnet per the consesus rules). Finally, if the useCoinbaseValue flag is false and the existing block template does not already contain a valid payment address, the block template will be updated with a randomly selected payment address from the list of configured addresses. This function MUST be called with the state locked.
type GetAddedNodesMsg ¶
type GetAddedNodesMsg struct {
Reply chan []*NodePeer
}
type GetConnCountMsg ¶
type GetConnCountMsg struct {
Reply chan int32
}
type GetOutboundGroup ¶
type GetPeersMsg ¶
type GetPeersMsg struct {
Reply chan []*NodePeer
}
type HelpCacher ¶
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.
type Node ¶
type Node struct { // The following variables must only be used atomically. Putting the // uint64s first makes them 64-bit aligned for 32-bit systems. BytesReceived uint64 // Total bytes received from all peers since start. BytesSent uint64 // Total bytes sent by all peers since start. StartupTime int64 ChainParams *netparams.Params AddrManager *addrmgr.AddrManager ConnManager *connmgr.ConnManager SigCache *txscript.SigCache HashCache *txscript.HashCache RPCServers []*Server SyncManager *netsync.SyncManager Chain *blockchain.BlockChain TxMemPool *mempool.TxPool CPUMiner *cpuminer.CPUMiner ModifyRebroadcastInv chan interface{} NewPeers chan *NodePeer DonePeers chan *NodePeer BanPeers chan *NodePeer Query chan interface{} RelayInv chan RelayMsg Broadcast chan BroadcastMsg PeerHeightsUpdate chan UpdatePeerHeightsMsg WG sync.WaitGroup Quit chan struct{} NAT upnp.NAT DB database.DB TimeSource blockchain.MedianTimeSource Services wire.ServiceFlag // The following fields are used for optional indexes. They will be nil // if the associated index is not enabled. These fields are set during // initial creation of the server and never changed afterwards, so they // do not need to be protected for concurrent access. TxIndex *indexers.TxIndex AddrIndex *indexers.AddrIndex CFIndex *indexers.CFIndex // The fee estimator keeps track of how long transactions are left in // the mempool before they are mined into blocks. FeeEstimator *mempool.FeeEstimator // CFCheckptCaches stores a cached slice of filter headers for // cfcheckpt messages for each filter type. CFCheckptCaches map[wire.FilterType][]CFHeaderKV CFCheckptCachesMtx sync.RWMutex Algo string Config *pod.Config ActiveNet *netparams.Params StateCfg *state.Config GenThreads uint32 Started int32 Shutdown int32 ShutdownSched int32 }
Node provides a bitcoin Node for handling communications to and from bitcoin peers.
func (*Node) AddBytesReceived ¶
AddBytesReceived adds the passed number of bytes to the total bytes received counter for the server. It is safe for concurrent access.
func (*Node) AddBytesSent ¶
AddBytesSent adds the passed number of bytes to the total bytes sent counter for the server. It is safe for concurrent access.
func (*Node) AddRebroadcastInventory ¶
AddRebroadcastInventory adds 'iv' to the list of inventories to be rebroadcasted at random intervals until they show up in a block.
func (*Node) AnnounceNewTransactions ¶
AnnounceNewTransactions generates and relays inventory vectors and notifies both websocket and getblocktemplate long poll clients of the passed transactions. This function should be called whenever new transactions are added to the mempool.
func (*Node) BroadcastMessage ¶
BroadcastMessage sends msg to all peers currently connected to the server except those in the passed peers to exclude.
func (*Node) ConnectedCount ¶
ConnectedCount returns the number of currently connected peers.
func (*Node) HandleAddPeerMsg ¶
HandleAddPeerMsg deals with adding new peers. It is invoked from the peerHandler goroutine.
func (*Node) HandleBanPeerMsg ¶
HandleBanPeerMsg deals with banning peers. It is invoked from the peerHandler goroutine.
func (*Node) HandleBroadcastMsg ¶
func (s *Node) HandleBroadcastMsg(state *PeerState, bmsg *BroadcastMsg)
HandleBroadcastMsg deals with broadcasting messages to peers. It is invoked from the peerHandler goroutine.
func (*Node) HandleDonePeerMsg ¶
HandleDonePeerMsg deals with peers that have signalled they are done. It is invoked from the peerHandler goroutine.
func (*Node) HandleQuery ¶
HandleQuery is the central handler for all queries and commands from other goroutines related to peer state.
func (*Node) HandleRelayInvMsg ¶
HandleRelayInvMsg deals with relaying inventory to peers that are not already known to have it. It is invoked from the peerHandler goroutine.
func (*Node) HandleUpdatePeerHeights ¶
func (s *Node) HandleUpdatePeerHeights(state *PeerState, umsg UpdatePeerHeightsMsg)
handleUpdatePeerHeight updates the heights of all peers who were known to announce a block we recently accepted.
func (*Node) InboundPeerConnected ¶
InboundPeerConnected is invoked by the connection manager when a new inbound connection is established. It initializes a new inbound server peer instance, associates it with the connection, and starts a goroutine to wait for disconnection.
func (*Node) NetTotals ¶
NetTotals returns the sum of all bytes received and sent across the network for all peers. It is safe for concurrent access.
func (*Node) OutboundGroupCount ¶
OutboundGroupCount returns the number of peers connected to the given outbound group key.
func (*Node) OutboundPeerConnected ¶
OutboundPeerConnected is invoked by the connection manager when a new outbound connection is established. It initializes a new outbound server peer instance, associates it with the relevant state such as the connection request instance and the connection itself, and finally notifies the address manager of the attempt.
func (*Node) PeerDoneHandler ¶
PeerDoneHandler handles peer disconnects by notifiying the server that it's done along with other performing other desirable cleanup.
func (*Node) PeerHandler ¶
func (s *Node) PeerHandler()
PeerHandler is used to handle peer operations such as adding and removing peers to and from the server, banning peers, and broadcasting messages to peers. It must be run in a goroutine.
func (*Node) PushBlockMsg ¶
func (s *Node) PushBlockMsg(sp *NodePeer, hash *chainhash.Hash, doneChan chan<- struct{}, waitChan <-chan struct{}, encoding wire.MessageEncoding) error
PushBlockMsg sends a block message for the provided block hash to the connected peer. An error is returned if the block hash is not known.
func (*Node) PushMerkleBlockMsg ¶
func (s *Node) PushMerkleBlockMsg(sp *NodePeer, hash *chainhash.Hash, doneChan chan<- struct{}, waitChan <-chan struct{}, encoding wire.MessageEncoding) error
PushMerkleBlockMsg sends a merkleblock message for the provided block hash to the connected peer. Since a merkle block requires the peer to have a filter loaded, this call will simply be ignored if there is no filter loaded. An error is returned if the block hash is not known.
func (*Node) PushTxMsg ¶
func (s *Node) PushTxMsg(sp *NodePeer, hash *chainhash.Hash, doneChan chan<- struct{}, waitChan <-chan struct{}, encoding wire.MessageEncoding) error
PushTxMsg sends a tx message for the provided transaction hash to the connected peer. An error is returned if the transaction hash is not known.
func (*Node) RebroadcastHandler ¶
func (s *Node) RebroadcastHandler()
RebroadcastHandler keeps track of user submitted inventories that we have sent out but have not yet made it into a block. We periodically rebroadcast them in case our peers restarted or otherwise lost track of them.
func (*Node) RelayInventory ¶
RelayInventory relays the passed inventory vector to all connected peers that are not already known to have it.
func (*Node) RelayTransactions ¶
RelayTransactions generates and relays inventory vectors for all of the passed transactions to all connected peers.
func (*Node) RemoveRebroadcastInventory ¶
RemoveRebroadcastInventory removes 'iv' from the list of items to be rebroadcasted if present.
func (*Node) ScheduleShutdown ¶
ScheduleShutdown schedules a server shutdown after the specified duration. It also dynamically adjusts how often to warn the server is going down based on remaining duration.
func (*Node) Stop ¶
Stop gracefully shuts down the server by stopping and disconnecting all peers and the main listener.
func (*Node) TransactionConfirmed ¶
Transaction has one confirmation on the main chain. Now we can mark it as no longer needing rebroadcasting.
func (*Node) UPNPUpdateThread ¶
func (s *Node) UPNPUpdateThread()
func (*Node) UpdatePeerHeights ¶
func (s *Node) UpdatePeerHeights(latestBlkHash *chainhash.Hash, latestHeight int32, updateSource *peer.Peer)
UpdatePeerHeights updates the heights of all peers who have have announced the latest connected main chain block, or a recognized orphan. These height updates allow us to dynamically refresh peer heights, ensuring sync peer selection has access to the latest block heights for each peer.
func (*Node) WaitForShutdown ¶
func (s *Node) WaitForShutdown()
WaitForShutdown blocks until the main listener and peer handlers are stopped.
type NodePeer ¶
type NodePeer struct { *peer.Peer // The following variables must only be used atomically FeeFilter int64 ConnReq *connmgr.ConnReq Server *Node ContinueHash *chainhash.Hash RelayMtx sync.Mutex Filter *bloom.Filter KnownAddresses map[string]struct{} BanScore connmgr.DynamicBanScore Quit chan struct{} // The following chans are used to sync blockmanager and server. TxProcessed chan struct{} BlockProcessed chan struct{} SentAddrs bool IsWhitelisted bool Persistent bool DisableRelayTx bool }
NodePeer extends the peer to maintain state shared by the server and the blockmanager.
func NewServerPeer ¶
NewServerPeer returns a new ServerPeer instance. The peer needs to be set by the caller.
func (*NodePeer) AddBanScore ¶
AddBanScore increases the persistent and decaying ban score fields by the values passed as parameters. If the resulting score exceeds half of the ban threshold, a warning is logged including the reason provided. Further, if the score is above the ban threshold, the peer will be banned and disconnected.
func (*NodePeer) AddKnownAddresses ¶
func (sp *NodePeer) AddKnownAddresses(addresses []*wire.NetAddress)
AddKnownAddresses adds the given addresses to the set of known addresses to the peer to prevent sending duplicate addresses.
func (*NodePeer) EnforceNodeBloomFlag ¶
EnforceNodeBloomFlag disconnects the peer if the server is not configured to allow bloom filters. Additionally, if the peer has negotiated to a protocol version that is high enough to observe the bloom filter service support bit, it will be banned since it is intentionally violating the protocol.
func (*NodePeer) GetNewestBlock ¶
GetNewestBlock returns the current best block hash and height using the format required by the configuration for the peer package.
func (*NodePeer) IsAddressKnown ¶
func (sp *NodePeer) IsAddressKnown(na *wire.NetAddress) bool
IsAddressKnown true if the given address is already known to the peer.
func (*NodePeer) IsRelayTxDisabled ¶
IsRelayTxDisabled returns whether or not relaying of transactions for the given peer is disabled. It is safe for concurrent access.
func (*NodePeer) OnAddr ¶
OnAddr is invoked when a peer receives an addr bitcoin message and is used to notify the server about advertised addresses.
func (*NodePeer) OnBlock ¶
OnBlock is invoked when a peer receives a block bitcoin message. It blocks until the bitcoin block has been fully processed.
func (*NodePeer) OnFeeFilter ¶
func (sp *NodePeer) OnFeeFilter(_ *peer.Peer, msg *wire.MsgFeeFilter)
OnFeeFilter is invoked when a peer receives a feefilter bitcoin message and is used by remote peers to request that no transactions which have a fee rate lower than provided value are inventoried to them. The peer will be disconnected if an invalid fee filter value is provided.
func (*NodePeer) OnFilterAdd ¶
func (sp *NodePeer) OnFilterAdd(_ *peer.Peer, msg *wire.MsgFilterAdd)
OnFilterAdd is invoked when a peer receives a filteradd bitcoin message and is used by remote peers to add data to an already loaded bloom filter. The peer will be disconnected if a filter is not loaded when this message is received or the server is not configured to allow bloom filters.
func (*NodePeer) OnFilterClear ¶
func (sp *NodePeer) OnFilterClear(_ *peer.Peer, msg *wire.MsgFilterClear)
OnFilterClear is invoked when a peer receives a filterclear bitcoin message and is used by remote peers to clear an already loaded bloom filter. The peer will be disconnected if a filter is not loaded when this message is received or the server is not configured to allow bloom filters.
func (*NodePeer) OnFilterLoad ¶
func (sp *NodePeer) OnFilterLoad(_ *peer.Peer, msg *wire.MsgFilterLoad)
OnFilterLoad is invoked when a peer receives a filterload bitcoin message and it used to load a bloom filter that should be used for delivering merkle blocks and associated transactions that match the filter. The peer will be disconnected if the server is not configured to allow bloom filters.
func (*NodePeer) OnGetAddr ¶
func (sp *NodePeer) OnGetAddr(_ *peer.Peer, msg *wire.MsgGetAddr)
OnGetAddr is invoked when a peer receives a getaddr bitcoin message and is used to provide the peer with known addresses from the address manager.
func (*NodePeer) OnGetBlocks ¶
func (sp *NodePeer) OnGetBlocks(_ *peer.Peer, msg *wire.MsgGetBlocks)
OnGetBlocks is invoked when a peer receives a getblocks bitcoin message.
func (*NodePeer) OnGetCFCheckpt ¶
func (sp *NodePeer) OnGetCFCheckpt(_ *peer.Peer, msg *wire.MsgGetCFCheckpt)
OnGetCFCheckpt is invoked when a peer receives a getcfcheckpt bitcoin message.
func (*NodePeer) OnGetCFHeaders ¶
func (sp *NodePeer) OnGetCFHeaders(_ *peer.Peer, msg *wire.MsgGetCFHeaders)
OnGetCFHeaders is invoked when a peer receives a getcfheader bitcoin message.
func (*NodePeer) OnGetCFilters ¶
func (sp *NodePeer) OnGetCFilters(_ *peer.Peer, msg *wire.MsgGetCFilters)
OnGetCFilters is invoked when a peer receives a getcfilters bitcoin message.
func (*NodePeer) OnGetData ¶
func (sp *NodePeer) OnGetData(_ *peer.Peer, msg *wire.MsgGetData)
handleGetData is invoked when a peer receives a getdata bitcoin message and is used to deliver block and transaction information.
func (*NodePeer) OnGetHeaders ¶
func (sp *NodePeer) OnGetHeaders(_ *peer.Peer, msg *wire.MsgGetHeaders)
OnGetHeaders is invoked when a peer receives a getheaders bitcoin message.
func (*NodePeer) OnHeaders ¶
func (sp *NodePeer) OnHeaders(_ *peer.Peer, msg *wire.MsgHeaders)
OnHeaders is invoked when a peer receives a headers bitcoin message. The message is passed down to the sync manager.
func (*NodePeer) OnInv ¶
OnInv is invoked when a peer receives an inv bitcoin message and is used to examine the inventory being advertised by the remote peer and react accordingly. We pass the message down to blockmanager which will call QueueMessage with any appropriate responses.
func (*NodePeer) OnMemPool ¶
func (sp *NodePeer) OnMemPool(_ *peer.Peer, msg *wire.MsgMemPool)
OnMemPool is invoked when a peer receives a mempool bitcoin message. It creates and sends an inventory message with the contents of the memory pool up to the maximum inventory allowed per message. When the peer has a bloom filter loaded, the contents are filtered accordingly.
func (*NodePeer) OnRead ¶
OnRead is invoked when a peer receives a message and it is used to update the bytes received by the server.
func (*NodePeer) OnTx ¶
OnTx is invoked when a peer receives a tx bitcoin message. It blocks until the bitcoin transaction has been fully processed. Unlock the block handler this does not serialize all transactions through a single thread transactions don't rely on the previous one in a linear fashion like blocks.
func (*NodePeer) OnVersion ¶
OnVersion is invoked when a peer receives a version bitcoin message and is used to negotiate the protocol version details as well as kick start the communications.
func (*NodePeer) OnWrite ¶
OnWrite is invoked when a peer sends a message and it is used to update the bytes sent by the server.
func (*NodePeer) PreparePushAddrMsg ¶
func (sp *NodePeer) PreparePushAddrMsg(addresses []*wire.NetAddress)
PreparePushAddrMsg sends an addr message to the connected peer using the provided addresses.
func (*NodePeer) SetDisableRelayTx ¶
SetDisableRelayTx toggles relaying of transactions for the given peer. It is safe for concurrent access.
type NotificationRegisterBlocks ¶
type NotificationRegisterBlocks WSClient
type NotificationRegisterClient ¶
type NotificationRegisterClient WSClient
Notification control requests
type NotificationRegisterNewMempoolTxs ¶
type NotificationRegisterNewMempoolTxs WSClient
type NotificationUnregisterBlocks ¶
type NotificationUnregisterBlocks WSClient
type NotificationUnregisterClient ¶
type NotificationUnregisterClient WSClient
type NotificationUnregisterNewMempoolTxs ¶
type NotificationUnregisterNewMempoolTxs WSClient
type OnionAddr ¶
type OnionAddr struct {
Addr string
}
OnionAddr implements the net.Addr interface and represents a tor address.
type ParsedRPCCmd ¶
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 *btcjson.Request) *ParsedRPCCmd
ParseCmd parses a JSON-RPC request object into known concrete command. The err field of the returned ParsedRPCCmd struct will contain an RPC error that is suitable for use in replies if the command is invalid in some way such as an unregistered command or invalid parameters.
type Peer ¶
type Peer NodePeer
Peer provides a peer for use with the RPC server and implements the RPCServerPeer interface.
func (*Peer) GetBanScore ¶
GetBanScore returns the current integer value that represents how close the peer is to being banned. This function is safe for concurrent access and is part of the RPCServerPeer interface implementation.
func (*Peer) GetFeeFilter ¶
GetFeeFilter returns the requested current minimum fee rate for which transactions should be announced. This function is safe for concurrent access and is part of the RPCServerPeer interface implementation.
func (*Peer) IsTxRelayDisabled ¶
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.
type PeerState ¶
type PeerState struct { InboundPeers map[int32]*NodePeer OutboundPeers map[int32]*NodePeer PersistentPeers map[int32]*NodePeer Banned map[string]time.Time OutboundGroups map[string]int }
PeerState maintains state of inbound, persistent, outbound peers as well as banned peers and outbound groups.
func (*PeerState) ForAllOutboundPeers ¶
ForAllOutboundPeers is a helper function that runs closure on all outbound peers known to peerState.
func (*PeerState) ForAllPeers ¶
ForAllPeers is a helper function that runs closure on all peers known to peerState.
type RelayMsg ¶
RelayMsg packages an inventory vector along with the newly discovered inventory so the relay has access to that information.
type RemoveNodeMsg ¶
type RescanKeys ¶
type RescanKeys struct { Fallbacks map[string]struct{} PubKeyHashes map[[ripemd160.Size]byte]struct{} ScriptHashes map[[ripemd160.Size]byte]struct{} CompressedPubKeys map[[33]byte]struct{} UncompressedPubKeys map[[65]byte]struct{} Unspent map[wire.OutPoint]struct{} }
func (*RescanKeys) UnspentSlice ¶
func (r *RescanKeys) UnspentSlice() []*wire.OutPoint
UnspentSlice returns a slice of currently-unspent outpoints for the rescan lookup keys. This is primarily intended to be used to register outpoints for continuous notifications after a rescan has completed.
type RetrievedTx ¶
type RetrievedTx struct { TxBytes []byte BlkHash *chainhash.Hash // Only set when transaction is in a block. Tx *util.Tx }
RetrievedTx represents a transaction that was either loaded from the transaction memory pool or from the database. When a transaction is loaded from the database, it is loaded with the raw serialized bytes while the mempool has the fully deserialized structure. This structure therefore will have one of the two fields set depending on where is was retrieved from. This is mainly done for efficiency to avoid extra serialization steps when possible.
type Server ¶
type Server struct { Cfg ServerConfig StateCfg *state.Config Config *pod.Config NtfnMgr *WSNtfnMgr StatusLines map[int]string StatusLock sync.RWMutex WG sync.WaitGroup GBTWorkState *GBTWorkState HelpCacher *HelpCacher RequestProcessShutdown chan struct{} Quit chan int Started int32 Shutdown int32 NumClients int32 AuthSHA [sha256.Size]byte LimitAuthSHA [sha256.Size]byte }
Server provides a concurrent safe RPC server to a chain server.
func NewRPCServer ¶
func NewRPCServer(config *ServerConfig, statecfg *state.Config, podcfg *pod.Config) (*Server, error)
NewRPCServer returns a new instance of the RPCServer struct.
func (*Server) CheckAuth ¶
CheckAuth checks the HTTP Basic authentication supplied by a wallet or RPC client in the HTTP request r. If the supplied authentication does not match the username and password expected, a non-nil error is returned. This check is time-constant. The first bool return value signifies auth success ( true if successful) and the second bool return value specifies whether the user can change the state of the server (true) or whether the user is limited (false). The second is always false if the first is.
func (*Server) DecrementClients ¶
func (s *Server) DecrementClients()
DecrementClients subtracts one from the number of connected RPC clients. Note this only applies to standard clients. Websocket clients have their own limits and are tracked separately. This function is safe for concurrent access.
func (*Server) HTTPStatusLine ¶
HTTPStatusLine returns a response Status-Line (RFC 2616 Section 6.1) for the given request and response status code. This function was lifted and adapted from the standard library HTTP server code since it's not exported.
func (*Server) HandleBlockchainNotification ¶
func (s *Server) HandleBlockchainNotification(notification *blockchain.Notification)
Callback for notifications from blockchain. It notifies clients that are long polling for changes or subscribed to websockets notifications.
func (*Server) IncrementClients ¶
func (s *Server) IncrementClients()
IncrementClients adds one to the number of connected RPC clients. Note this only applies to standard clients. Websocket clients have their own limits and are tracked separately. This function is safe for concurrent access.
func (*Server) JSONRPCRead ¶
JSONRPCRead handles reading and responding to RPC messages.
func (*Server) LimitConnections ¶
func (s *Server) LimitConnections(w http.ResponseWriter, remoteAddr string) bool
LimitConnections responds with a 503 service unavailable and returns true if adding another client would exceed the maximum allow RPC clients. This function is safe for concurrent access.
func (*Server) NotifyNewTransactions ¶
NotifyNewTransactions notifies both websocket and getblocktemplate long poll clients of the passed transactions. This function should be called whenever new transactions are added to the mempool.
func (*Server) RequestedProcessShutdown ¶
func (s *Server) RequestedProcessShutdown() <-chan struct{}
RequestedProcessShutdown returns a channel that is sent to when an authorized RPC client requests the process to shutdown. If the request can not be read immediately, it is dropped.
func (*Server) StandardCmdResult ¶
func (s *Server) StandardCmdResult(cmd *ParsedRPCCmd, closeChan <-chan struct{}) (interface{}, error)
StandardCmdResult checks that a parsed command is a standard Bitcoin JSON-RPC command and runs the appropriate handler to reply to the command. Any commands which are not recognized or not implemented will return an error suitable for use in replies.
func (*Server) Start ¶
func (s *Server) Start()
Start is used by server.go to start the rpc listener.
func (*Server) WebsocketHandler ¶
func (s *Server) WebsocketHandler(conn *websocket.Conn, remoteAddr string, authenticated bool, isAdmin bool)
WebsocketHandler handles a new websocket client by creating a new wsClient, starting it, and blocking until the connection closes. Since it blocks, it must be run in a separate goroutine. It should be invoked from the websocket server handler which runs each new connection in a new goroutine thereby satisfying the requirement.
func (*Server) WriteHTTPResponseHeaders ¶
func (s *Server) WriteHTTPResponseHeaders(req *http.Request, headers http.Header, code int, w io.Writer) error
WriteHTTPResponseHeaders writes the necessary response headers prior to writing an HTTP body given a request to use for protocol negotiation, headers to write, a status code, and a writer.
type ServerConfig ¶
type ServerConfig struct { // Listeners defines a slice of listeners for which the RPC server will // take ownership of and accept connections. // Since the RPC server takes ownership of these listeners, // they will be closed when the RPC server is stopped. Listeners []net.Listener // StartupTime is the unix timestamp for when the server that is hosting // the RPC server started. StartupTime int64 // ConnMgr defines the connection manager for the RPC server to use. // It provides the RPC server with a means to do things such as add, // remove, connect, disconnect, // and query peers as well as other connection-related data and tasks. ConnMgr ServerConnManager // SyncMgr defines the sync manager for the RPC server to use. SyncMgr ServerSyncManager // These fields allow the RPC server to interface with the local block // chain data and state. TimeSource blockchain.MedianTimeSource Chain *blockchain.BlockChain ChainParams *netparams.Params DB database.DB // TxMemPool defines the transaction memory pool to interact with. TxMemPool *mempool.TxPool // These fields allow the RPC server to interface with mining. // Generator produces block templates and the CPUMiner solves them using // the CPU. // CPU mining is typically only useful for test purposes when doing // regression or simulation testing. Generator *mining.BlkTmplGenerator CPUMiner *cpuminer.CPUMiner // These fields define any optional indexes the RPC server can make use // of to provide additional data when queried. TxIndex *indexers.TxIndex AddrIndex *indexers.AddrIndex CfIndex *indexers.CFIndex // The fee estimator keeps track of how long transactions are left in the // mempool before they are mined into blocks. FeeEstimator *mempool.FeeEstimator // Algo sets the algorithm expected from the RPC endpoint. This allows // multiple ports to serve multiple types of miners with one main node per // algorithm. Currently 514 for scrypt and anything else passes for sha256d. Algo string }
ServerConfig is a descriptor containing the RPC server configuration.
type ServerConnManager ¶
type ServerConnManager interface { // Connect adds the provided address as a new outbound peer. // The permanent flag indicates whether or not to make the peer // persistent and reconnect if the connection is lost. // Attempting to connect to an already existing peer will return an error. Connect(addr string, permanent bool) error // RemoveByID removes the peer associated with the provided id from the // list of persistent peers. // Attempting to remove an id that does not exist will return an error. RemoveByID(id int32) error // RemoveByAddr removes the peer associated with the provided address // from the list of persistent peers. // Attempting to remove an address that does not exist will return an error. RemoveByAddr(addr string) error // DisconnectByID disconnects the peer associated with the provided id. // This applies to both inbound and outbound peers. // Attempting to remove an id that does not exist will return an error. DisconnectByID(id int32) error // DisconnectByAddr disconnects the peer associated with the provided // address. This applies to both inbound and outbound peers. // Attempting to remove an address that does not exist will return an error. DisconnectByAddr(addr string) error // ConnectedCount returns the number of currently connected peers. ConnectedCount() int32 // NetTotals returns the sum of all bytes received and sent across the // network for all peers. NetTotals() (uint64, uint64) // ConnectedPeers returns an array consisting of all connected peers. ConnectedPeers() []ServerPeer // PersistentPeers returns an array consisting of all the persistent peers. PersistentPeers() []ServerPeer // BroadcastMessage sends the provided message to all currently connected // peers. BroadcastMessage(msg wire.Message) // AddRebroadcastInventory adds the provided inventory to the list of // inventories to be rebroadcast at random intervals until they show up // in a block. AddRebroadcastInventory(iv *wire.InvVect, data interface{}) // RelayTransactions generates and relays inventory vectors for all of // the passed transactions to all connected peers. RelayTransactions(txns []*mempool.TxDesc) }
ServerConnManager represents a connection manager for use with the RPC server. The interface contract requires that all of these methods are safe for concurrent access.
type ServerPeer ¶
type ServerPeer interface { // ToPeer returns the underlying peer instance. ToPeer() *p.Peer // IsTxRelayDisabled returns whether or not the peer has disabled // transaction relay. IsTxRelayDisabled() bool // GetBanScore returns the current integer value that represents how // close the peer is to being banned. GetBanScore() uint32 // GetFeeFilter returns the requested current minimum fee rate for which // transactions should be announced. GetFeeFilter() int64 }
ServerPeer represents a peer for use with the RPC server. The interface contract requires that all of these methods are safe for concurrent access.
type ServerSyncManager ¶
type ServerSyncManager interface { // IsCurrent returns whether or not the sync manager believes the chain // is current as compared to the rest of the network. IsCurrent() bool // SubmitBlock submits the provided block to the network after processing // it locally. SubmitBlock(block *util.Block, flags blockchain.BehaviorFlags) (bool, error) // pause pauses the sync manager until the returned channel is closed. Pause() chan<- struct{} // SyncPeerID returns the ID of the peer that is currently the peer being // used to sync from or 0 if there is none. SyncPeerID() int32 // LocateHeaders returns the headers of the blocks after the first known // block in the provided locators until the provided stop hash or the // current tip is reached, up to a max of wire.MaxBlockHeadersPerMsg hashes. LocateHeaders(locators []*chainhash.Hash, hashStop *chainhash.Hash) []wire.BlockHeader }
ServerSyncManager represents a sync manager for use with the RPC server. The interface contract requires that all of these methods are safe for concurrent access.
type SimpleAddr ¶
type SimpleAddr struct {
Net, Addr string
}
SimpleAddr implements the net.Addr interface with two struct fields
func (SimpleAddr) Network ¶
func (a SimpleAddr) Network() string
Network returns the network. This is part of the net.Addr interface.
func (SimpleAddr) String ¶
func (a SimpleAddr) String() string
String returns the address. This is part of the net.Addr interface.
type SyncManager ¶
type SyncManager struct {
// contains filtered or unexported fields
}
SyncManager provides a block manager for use with the RPC server and implements the RPCServerSyncManager interface.
func (*SyncManager) IsCurrent ¶
func (b *SyncManager) IsCurrent() bool
IsCurrent returns whether or not the sync manager believes the chain is current as compared to the rest of the network. This function is safe for concurrent access and is part of the RPCServerSyncManager interface implementation.
func (*SyncManager) LocateHeaders ¶
func (b *SyncManager) LocateHeaders(locators []*chainhash.Hash, hashStop *chainhash.Hash) []wire.BlockHeader
LocateBlocks returns the hashes of the blocks after the first known block in the provided locators until the provided stop hash or the current tip is reached, up to a max of wire.MaxBlockHeadersPerMsg hashes. This function is safe for concurrent access and is part of the RPCServerSyncManager interface implementation.
func (*SyncManager) Pause ¶
func (b *SyncManager) Pause() chan<- struct{}
pause pauses the sync manager until the returned channel is closed. This function is safe for concurrent access and is part of the RPCServerSyncManager interface implementation.
func (*SyncManager) SubmitBlock ¶
func (b *SyncManager) SubmitBlock(block *util.Block, flags blockchain.BehaviorFlags) (bool, error)
SubmitBlock submits the provided block to the network after processing it locally. This function is safe for concurrent access and is part of the RPCServerSyncManager interface implementation.
func (*SyncManager) SyncPeerID ¶
func (b *SyncManager) SyncPeerID() int32
SyncPeerID returns the peer that is currently the peer being used to sync from. This function is safe for concurrent access and is part of the RPCServerSyncManager interface implementation.
type UpdatePeerHeightsMsg ¶
UpdatePeerHeightsMsg is a message sent from the blockmanager to the server after a new block has been accepted. The purpose of the message is to update the heights of peers that were known to announce the block before we connected it to the main chain or recognized it as an orphan. With these updates, peer heights will be kept up to date, allowing for fresh data when selecting sync peer candidacy.
type WSClient ¶
type WSClient struct { // ws client requires a mutex lock for access sync.Mutex // Server is the RPC Server that is servicing the client. Server *Server // Conn is the underlying websocket connection. Conn *websocket.Conn // Addr is the remote address of the client. Addr string // SessionID is a random ID generated for each client when connected. These // IDs may be queried by a client using the session RPC. A change to the // session ID indicates that the client reconnected. SessionID uint64 AddrRequests map[string]struct{} // SpentRequests is a set of unspent Outpoints a wallet has requested // notifications for when they are spent by a processed transaction. Owned // by the notification manager. SpentRequests map[wire.OutPoint]struct{} // FilterData is the new generation transaction filter backported from // github.com/decred/dcrd for the new backported `loadtxfilter` and // `rescanblocks` methods. FilterData *WSClientFilter // Networking infrastructure. ServiceRequestSem Semaphore NtfnChan chan []byte SendChan chan WSResponse Quit chan struct{} WG sync.WaitGroup // Disconnected indicated whether or not the websocket client is // Disconnected. Disconnected bool // Authenticated specifies whether a client has been Authenticated and // therefore is allowed to communicated over the websocket. Authenticated bool // IsAdmin specifies whether a client may change the state of the server; // false means its access is only to the limited set of RPC calls. IsAdmin bool // VerboseTxUpdates specifies whether a client has requested verbose // information about all new transactions. VerboseTxUpdates bool }
WSClient provides an abstraction for handling a websocket client. The overall data flow is split into 3 main goroutines, a possible 4th goroutine for long-running operations (only started if request is made), and a websocket manager which is used to allow things such as broadcasting requested notifications to all connected websocket clients. Inbound messages are read via the inHandler goroutine and generally dispatched to their own handler. However, certain potentially long-running operations such as rescans, are sent to the asyncHander goroutine and are limited to one at a time. There are two outbound message types - one for responding to client requests and another for async notifications. Responses to client requests use SendMessage which employs a buffered channel thereby limiting the number of outstanding requests that can be made. Notifications are sent via QueueNotification which implements a queue via notificationQueueHandler to ensure sending notifications from other subsystems can't block. Ultimately, all messages are sent via the outHandler.
func NewWebsocketClient ¶
func NewWebsocketClient(server *Server, conn *websocket.Conn, remoteAddr string, authenticated bool, isAdmin bool) (*WSClient, error)
NewWebsocketClient returns a new websocket client given the notification manager, websocket connection, remote address, and whether or not the client has already been authenticated (via HTTP Basic access authentication). The returned client is ready to start. Once started, the client will process incoming and outgoing messages in separate goroutines complete with queuing and asynchrous handling for long-running operations.
func (*WSClient) Disconnect ¶
func (c *WSClient) Disconnect()
Disconnect disconnects the websocket client.
func (*WSClient) InHandler ¶
func (c *WSClient) InHandler()
InHandler handles all incoming messages for the websocket connection. It must be run as a goroutine.
func (*WSClient) IsDisconnected ¶
IsDisconnected returns whether or not the websocket client is disconnected.
func (*WSClient) NotificationQueueHandler ¶
func (c *WSClient) NotificationQueueHandler()
NotificationQueueHandler handles the queuing of outgoing notifications for the websocket client. This runs as a muxer for various sources of input to ensure that queuing up notifications to be sent will not block. Otherwise, slow clients could bog down the other systems (such as the mempool or block manager) which are queuing the data. The data is passed on to outHandler to actually be written. It must be run as a goroutine.
func (*WSClient) OutHandler ¶
func (c *WSClient) OutHandler()
OutHandler handles all outgoing messages for the websocket connection. It must be run as a goroutine. It uses a buffered channel to serialize output messages while allowing the sender to continue running asynchronously. It must be run as a goroutine.
func (*WSClient) QueueNotification ¶
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 ¶
SendMessage sends the passed json to the websocket client. It is backed by a buffered channel, so it will not block until the send channel is full. Note however that QueueNotification must be used for sending async notifications instead of the this function. This approach allows a limit to the number of outstanding requests a client can make without preventing or blocking on async notifications.
func (*WSClient) ServiceRequest ¶
func (c *WSClient) ServiceRequest(r *ParsedRPCCmd)
ServiceRequest services a parsed RPC request by looking up and executing the appropriate RPC handler. The response is marshalled and sent to the websocket client.
func (*WSClient) Start ¶
func (c *WSClient) Start()
Start begins processing input and output messages.
func (*WSClient) WaitForShutdown ¶
func (c *WSClient) WaitForShutdown()
WaitForShutdown blocks until the websocket client goroutines are stopped and the connection is closed.
type WSClientFilter ¶
type WSClientFilter struct { // Implemented fast paths for address lookup. PubKeyHashes map[[ripemd160.Size]byte]struct{} ScriptHashes map[[ripemd160.Size]byte]struct{} CompressedPubKeys map[[33]byte]struct{} UncompressedPubKeys map[[65]byte]struct{} // A fallback address lookup map in case a fast path doesn't exist. Only // exists for completeness. If using this shows up in a profile, there's a // good chance a fast path should be added. OtherAddresses map[string]struct{} // Outpoints of Unspent outputs. Unspent map[wire.OutPoint]struct{} // contains filtered or unexported fields }
WSClientFilter tracks relevant addresses for each websocket client for the `rescanblocks` extension. It is modified by the `loadtxfilter` command. NOTE: This extension was ported from github.com/decred/dcrd
func NewWSClientFilter ¶
func NewWSClientFilter(addresses []string, unspentOutPoints []wire.OutPoint, params *netparams.Params) *WSClientFilter
NewWSClientFilter creates a new, empty wsClientFilter struct to be used for a websocket client. NOTE: This extension was ported from github.com/decred/ dcrd
func (*WSClientFilter) AddAddress ¶
func (f *WSClientFilter) AddAddress(a util.Address)
AddAddress adds an address to a wsClientFilter, treating it correctly based on the type of address passed as an argument. NOTE: This extension was ported from github.com/decred/dcrd
func (*WSClientFilter) AddAddressStr ¶
func (f *WSClientFilter) AddAddressStr(s string, params *netparams.Params)
AddAddressStr parses an address from a string and then adds it to the wsClientFilter using addAddress. NOTE: This extension was ported from github.com/decred/dcrd
func (*WSClientFilter) AddUnspentOutPoint ¶
func (f *WSClientFilter) AddUnspentOutPoint(op *wire.OutPoint)
AddUnspentOutPoint adds an outpoint to the wsClientFilter. NOTE: This extension was ported from github.com/decred/dcrd
func (*WSClientFilter) ExistsAddress ¶
func (f *WSClientFilter) ExistsAddress(a util.Address) bool
ExistsAddress returns true if the passed address has been added to the wsClientFilter. NOTE: This extension was ported from github.com/decred/dcrd
func (*WSClientFilter) ExistsUnspentOutPoint ¶
func (f *WSClientFilter) ExistsUnspentOutPoint(op *wire.OutPoint) bool
ExistsUnspentOutPoint returns true if the passed outpoint has been added to the wsClientFilter. NOTE: This extension was ported from github.com/decred/dcrd
type WSCommandHandler ¶
WSCommandHandler describes a callback function used to handle a specific command.
type WSNtfnMgr ¶
type WSNtfnMgr struct { // Server is the RPC Server the notification manager is associated with. Server *Server // QueueNotification queues a notification for handling. QueueNotification chan interface{} // NotificationMsgs feeds notificationHandler with notifications and client // (un)registeration requests from a queue as well as registeration and // unregisteration requests from clients. NotificationMsgs chan interface{} // Access channel for current number of connected clients. NumClients chan int // Shutdown handling WG sync.WaitGroup Quit chan struct{} }
WSNtfnMgr is a connection and notification manager used for websockets. It allows websocket clients to register for notifications they are interested in. When an event happens elsewhere in the code such as transactions being added to the memory pool or block connects/disconnects, the notification manager is provided with the relevant details needed to figure out which websocket clients need to be notified based on what they have registered for and notifies them accordingly. It is also used to keep track of all connected websocket clients.
func NewWSNotificationManager ¶
NewWSNotificationManager returns a new notification manager ready for use. See wsNotificationManager for more details.
func (*WSNtfnMgr) AddAddrRequests ¶
func (*WSNtfnMgr) AddAddrRequests( addrMap map[string]map[chan struct{}]*WSClient, wsc *WSClient, addrs []string)
AddAddrRequests adds the websocket client wsc to the address to client set addrMap so wsc will be notified for any mempool or block transaction outputs spending to any of the addresses in addrs.
func (*WSNtfnMgr) AddClient ¶
// removeAddress removes the passed address, if it exists, from the wsClientFilter. NOTE: This extension was ported from github.com/decred/dcrd
func (f *wsClientFilter) removeAddress(a util.Address) { switch a := a.(type) { case *util.AddressPubKeyHash: delete(f.pubKeyHashes, *a.Hash160()) return case *util.AddressScriptHash: delete(f.scriptHashes, *a.Hash160()) return case *util.AddressPubKey: serializedPubKey := a.ScriptAddress() switch len(serializedPubKey) { case 33: // compressed var compressedPubKey [33]byte copy(compressedPubKey[:], serializedPubKey) delete(f.compressedPubKeys, compressedPubKey) return case 65: // uncompressed var uncompressedPubKey [65]byte copy(uncompressedPubKey[:], serializedPubKey) delete(f.uncompressedPubKeys, uncompressedPubKey) return } } delete(f.otherAddresses, a.EncodeAddress()) }
// removeAddressStr parses an address from a string and then removes it from // the wsClientFilter using removeAddress. NOTE: This extension was ported // from github.com/decred/dcrd
func (f *wsClientFilter) removeAddressStr(s string, netparams *netparams.Params) { a, err := util.DecodeAddress(s, netparams) if err == nil { f.removeAddress(a) } else { delete(f.otherAddresses, s) } }
// removeUnspentOutPoint removes the passed outpoint, if it exists, from the wsClientFilter. NOTE: This extension was ported from github.com/decred/dcrd
func (f *wsClientFilter) removeUnspentOutPoint(op *wire.OutPoint) { delete(f.unspent, *op) }
AddClient adds the passed websocket client to the notification manager.
func (*WSNtfnMgr) AddSpentRequests ¶
func (m *WSNtfnMgr) AddSpentRequests(opMap map[wire. OutPoint]map[chan struct{}]*WSClient, wsc *WSClient, ops []*wire.OutPoint)
AddSpentRequests modifies a map of watched outpoints to sets of websocket clients to add a new request watch all of the outpoints in ops and create and send a notification when spent to the websocket client wsc.
func (*WSNtfnMgr) GetNumClients ¶
GetNumClients returns the number of clients actively being served.
func (*WSNtfnMgr) GetSubscribedClients ¶
func (m *WSNtfnMgr) GetSubscribedClients(tx *util.Tx, clients map[chan struct{}]*WSClient) map[chan struct{}]struct{}
GetSubscribedClients returns the set of all websocket client quit channels that are registered to receive notifications regarding tx, either due to tx spending a watched output or outputting to a watched address. Matching client's filters are updated based on this transaction's outputs and output addresses that may be relevant for a client.
func (*WSNtfnMgr) NotificationHandler ¶
func (m *WSNtfnMgr) NotificationHandler()
NotificationHandler reads notifications and control messages from the queue handler and processes one at a time.
func (*WSNtfnMgr) NotifyBlockConnected ¶
NotifyBlockConnected notifies websocket clients that have registered for block updates when a block is connected to the main chain.
func (*WSNtfnMgr) NotifyBlockDisconnected ¶
NotifyBlockDisconnected notifies websocket clients that have registered for block updates when a block is disconnected from the main chain (due to a reorganize).
func (*WSNtfnMgr) NotifyFilteredBlockConnected ¶
func (m *WSNtfnMgr) NotifyFilteredBlockConnected( clients map[chan struct{}]*WSClient, block *util.Block)
NotifyFilteredBlockConnected notifies websocket clients that have registered for block updates when a block is connected to the main chain.
func (*WSNtfnMgr) NotifyFilteredBlockDisconnected ¶
func (*WSNtfnMgr) NotifyFilteredBlockDisconnected( clients map[chan struct{}]*WSClient, block *util.Block)
NotifyFilteredBlockDisconnected notifies websocket clients that have registered for block updates when a block is disconnected from the main chain (due to a reorganize).
func (*WSNtfnMgr) NotifyForNewTx ¶
NotifyForNewTx notifies websocket clients that have registered for updates when a new transaction is added to the memory pool.
func (*WSNtfnMgr) NotifyForTx ¶
func (m *WSNtfnMgr) NotifyForTx(ops map[wire.OutPoint]map[chan struct{}]*WSClient, addrs map[string]map[chan struct{}]*WSClient, tx *util.Tx, block *util.Block)
NotifyForTx examines the inputs and outputs of the passed transaction, notifying websocket clients of outputs spending to a watched address and inputs spending a watched outpoint.
func (*WSNtfnMgr) NotifyForTxIns ¶
func (m *WSNtfnMgr) NotifyForTxIns(ops map[wire. OutPoint]map[chan struct{}]*WSClient, tx *util.Tx, block *util.Block)
NotifyForTxIns examines the inputs of the passed transaction and sends interested websocket clients a redeemingtx notification if any inputs spend a watched output. If block is non-nil, any matching spent requests are removed.
func (*WSNtfnMgr) NotifyForTxOuts ¶
func (m *WSNtfnMgr) NotifyForTxOuts(ops map[wire.OutPoint]map[chan struct{}]*WSClient, addrs map[string]map[chan struct{}]*WSClient, tx *util.Tx, block *util.Block)
NotifyForTxOuts examines each transaction output, notifying interested websocket clients of the transaction if an output spends to a watched address. A spent notification request is automatically registered for the client for each matching output.
func (*WSNtfnMgr) NotifyRelevantTxAccepted ¶
NotifyRelevantTxAccepted examines the inputs and outputs of the passed transaction, notifying websocket clients of outputs spending to a watched address and inputs spending a watched outpoint. Any outputs paying to a watched address result in the output being watched as well for future notifications.
func (*WSNtfnMgr) QueueHandler ¶
func (m *WSNtfnMgr) QueueHandler()
QueueHandler maintains a queue of notifications and notification handler control messages.
func (*WSNtfnMgr) RegisterBlockUpdates ¶
RegisterBlockUpdates requests block update notifications to the passed websocket client.
func (*WSNtfnMgr) RegisterNewMempoolTxsUpdates ¶
RegisterNewMempoolTxsUpdates requests notifications to the passed websocket client when new transactions are added to the memory pool.
func (*WSNtfnMgr) RegisterSpentRequests ¶
RegisterSpentRequests requests a notification when each of the passed outpoints is confirmed spent (contained in a block connected to the main chain) for the passed websocket client. The request is automatically removed once the notification has been sent.
func (*WSNtfnMgr) RegisterTxOutAddressRequests ¶
RegisterTxOutAddressRequests requests notifications to the passed websocket client when a transaction output spends to the passed address.
func (*WSNtfnMgr) RemoveAddrRequest ¶
func (*WSNtfnMgr) RemoveAddrRequest( addrs map[string]map[chan struct{}]*WSClient, wsc *WSClient, addr string)
RemoveAddrRequest removes the websocket client wsc from the address to client set addrs so it will no longer receive notification updates for any transaction outputs send to addr.
func (*WSNtfnMgr) RemoveClient ¶
RemoveClient removes the passed websocket client and all notifications registered for it.
func (*WSNtfnMgr) RemoveSpentRequest ¶
func (*WSNtfnMgr) RemoveSpentRequest(ops map[wire. OutPoint]map[chan struct{}]*WSClient, wsc *WSClient, op *wire.OutPoint)
RemoveSpentRequest modifies a map of watched outpoints to remove the websocket client wsc from the set of clients to be notified when a watched outpoint is spent. If wsc is the last client, the outpoint key is removed from the map.
func (*WSNtfnMgr) SendNotifyBlockConnected ¶
SendNotifyBlockConnected passes a block newly-connected to the best chain to the notification manager for block and transaction notification processing.
func (*WSNtfnMgr) SendNotifyBlockDisconnected ¶
SendNotifyBlockDisconnected passes a block disconnected from the best chain to the notification manager for block notification processing.
func (*WSNtfnMgr) SendNotifyMempoolTx ¶
SendNotifyMempoolTx passes a transaction accepted by mempool to the notification manager for transaction notification processing. If isNew is true, the tx is is a new transaction, rather than one added to the mempool during a reorg.
func (*WSNtfnMgr) Shutdown ¶
func (m *WSNtfnMgr) Shutdown()
Shutdown shuts down the manager, stopping the notification queue and notification handler goroutines.
func (*WSNtfnMgr) Start ¶
func (m *WSNtfnMgr) Start()
Start starts the goroutines required for the manager to queue and process websocket client notifications.
func (*WSNtfnMgr) UnregisterBlockUpdates ¶
UnregisterBlockUpdates removes block update notifications for the passed websocket client.
func (*WSNtfnMgr) UnregisterNewMempoolTxsUpdates ¶
UnregisterNewMempoolTxsUpdates removes notifications to the passed websocket client when new transaction are added to the memory pool.
func (*WSNtfnMgr) UnregisterSpentRequest ¶
UnregisterSpentRequest removes a request from the passed websocket client to be notified when the passed outpoint is confirmed spent (contained in a block connected to the main chain).
func (*WSNtfnMgr) UnregisterTxOutAddressRequest ¶
UnregisterTxOutAddressRequest removes a request from the passed websocket client to be notified when a transaction spends to the passed address.
func (*WSNtfnMgr) WaitForShutdown ¶
func (m *WSNtfnMgr) WaitForShutdown()
WaitForShutdown blocks until all notification manager goroutines have finished.
type WSResponse ¶
WSResponse houses a message to send to a connected websocket client as well as a channel to reply on when the message is sent.