Documentation ¶
Index ¶
- Constants
- type AddrFunc
- type Config
- type HashFunc
- type HostToNetAddrFunc
- type MessageListeners
- type Peer
- func (p *Peer) AcceptBlockHeight(newHeight int32)
- func (p *Peer) AddBanScore(persistent, transient uint32, reason string)
- func (p *Peer) AddKnownInventory(invVect *protos.InvVect)
- func (p *Peer) Addr() string
- func (p *Peer) AssociateConnection(conn net.Conn)
- func (p *Peer) BanScore() uint32
- func (p *Peer) BytesReceived() uint64
- func (p *Peer) BytesSent() uint64
- func (p *Peer) Connected() bool
- func (p *Peer) Disconnect()
- func (p *Peer) ID() int32
- func (p *Peer) Inbound() bool
- func (p *Peer) IsWhitelisted() bool
- func (p *Peer) LastAcceptBlock() int32
- func (p *Peer) LastAnnouncedBlock() *common.Hash
- func (p *Peer) LastBlock() int32
- func (p *Peer) LastPingMicros() int64
- func (p *Peer) LastPingNonce() uint64
- func (p *Peer) LastPingTime() time.Time
- func (p *Peer) LastRecv() time.Time
- func (p *Peer) LastSend() time.Time
- func (p *Peer) LocalAddr() net.Addr
- func (p *Peer) NA() *protos.NetAddress
- func (p *Peer) ProtocolVersion() uint32
- func (p *Peer) PushAddrMsg(addresses []*protos.NetAddress) ([]*protos.NetAddress, error)
- func (p *Peer) PushGetBlocksMsg(locator blockchain.BlockLocator, stopHash *common.Hash) error
- func (p *Peer) PushGetHeadersMsg(locator blockchain.BlockLocator, stopHash *common.Hash) error
- func (p *Peer) PushRejectMsg(command string, code protos.RejectCode, reason string, hash *common.Hash, ...)
- func (p *Peer) QueueInventory(invVect *protos.InvVect)
- func (p *Peer) QueueMessage(msg protos.Message, doneChan chan<- struct{})
- func (p *Peer) QueueMessageWithEncoding(msg protos.Message, doneChan chan<- struct{}, encoding protos.MessageEncoding)
- func (p *Peer) Services() common.ServiceFlag
- func (p *Peer) StartingHeight() int32
- func (p *Peer) StatsSnapshot() *StatsSnap
- func (p *Peer) String() string
- func (p *Peer) TimeConnected() time.Time
- func (p *Peer) TimeOffset() int64
- func (p *Peer) UpdateLastAnnouncedBlock(blkHash *common.Hash)
- func (p *Peer) UpdateLastBlockHeight(newHeight int32)
- func (p *Peer) UserAgent() string
- func (p *Peer) VerAckReceived() bool
- func (p *Peer) VersionKnown() bool
- func (p *Peer) WaitForDisconnect()
- func (p *Peer) WantsHeaders() bool
- type StatsSnap
Constants ¶
const ( // MaxProtocolVersion is the max protocol version the peer supports. MaxProtocolVersion = common.MaxRequestVersion // MinAcceptableProtocolVersion is the lowest protocol version that a // connected peer may support. MinAcceptableProtocolVersion = common.MinRequestVersion )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AddrFunc ¶
type AddrFunc func(remoteAddr *protos.NetAddress) *protos.NetAddress
AddrFunc is a func which takes an address and returns a related address.
type Config ¶
type Config struct { // NewestBlock specifies a callback which provides the newest block // details to the peer as needed. This can be nil in which case the // peer will report a block height of 0, however it is good practice for // peers to specify this so their currently best known is accurately // reported. NewestBlock HashFunc // HostToNetAddress returns the netaddress for the given host. This can be // nil in which case the host will be parsed as an IP address. HostToNetAddress HostToNetAddrFunc // Proxy indicates a proxy is being used for connections. The only // effect this has is to prevent leaking the tor proxy address, so it // only needs to specified if using a tor proxy. Proxy string // UserAgentName specifies the user agent name to advertise. It is // highly recommended to specify this value. UserAgentName string // UserAgentVersion specifies the user agent version to advertise. It // is highly recommended to specify this value and that it follows the // form "major.minor.revision" e.g. "2.6.41". UserAgentVersion string // UserAgentComments specify the user agent comments to advertise. These // values must not contain the illegal characters specified in BIP 14: // '/', ':', '(', ')'. UserAgentComments []string // ChainParams identifies which chain parameters the peer is associated // with. It is highly recommended to specify this field, however it can // be omitted in which case the test network will be used. ChainParams *chaincfg.Params // Services specifies which services to advertise as supported by the // local peer. This field can be omitted in which case it will be 0 // and therefore advertise no supported services. Services common.ServiceFlag // ProtocolVersion specifies the maximum protocol version to use and // advertise. This field can be omitted in which case // peer.MaxProtocolVersion will be used. ProtocolVersion uint32 // DisableRelayTx specifies if the remote peer should be informed to // not send inv messages for transactions. DisableRelayTx bool // Listeners houses callback functions to be invoked on receiving peer // messages. Listeners MessageListeners }
Config is the struct to hold configuration options useful to Peer.
type HashFunc ¶
HashFunc is a function which returns a block hash, height, weight and error It is used as a callback to get newest block details.
type HostToNetAddrFunc ¶
type HostToNetAddrFunc func(host string, port uint16, services common.ServiceFlag) (*protos.NetAddress, error)
HostToNetAddrFunc is a func which takes a host, port, services and returns the netaddress.
type MessageListeners ¶
type MessageListeners struct { // OnGetAddr is invoked when a peer receives a getaddr bitcoin message. OnGetAddr func(p *Peer, msg *protos.MsgGetAddr) // OnAddr is invoked when a peer receives an addr bitcoin message. OnAddr func(p *Peer, msg *protos.MsgAddr) // OnPing is invoked when a peer receives a ping bitcoin message. OnPing func(p *Peer, msg *protos.MsgPing) // OnPong is invoked when a peer receives a pong bitcoin message. OnPong func(p *Peer, msg *protos.MsgPong) // OnMemPool is invoked when a peer receives a mempool bitcoin message. OnMemPool func(p *Peer, msg *protos.MsgMemPool) // OnTx is invoked when a peer receives a tx bitcoin message. OnTx func(p *Peer, msg *protos.MsgTx) // OnSig is invoked when a peer receives a signature bitcoin message. OnSig func(p *Peer, msg *protos.MsgBlockSign) // OnBlock is invoked when a peer receives a block bitcoin message. OnBlock func(p *Peer, msg *protos.MsgBlock, buf []byte) // OnCFilter is invoked when a peer receives a cfilter bitcoin message. OnCFilter func(p *Peer, msg *protos.MsgCFilter) // OnCFHeaders is invoked when a peer receives a cfheaders bitcoin // message. OnCFHeaders func(p *Peer, msg *protos.MsgCFHeaders) // OnCFCheckpt is invoked when a peer receives a cfcheckpt bitcoin // message. OnCFCheckpt func(p *Peer, msg *protos.MsgCFCheckpt) // OnInv is invoked when a peer receives an inv bitcoin message. OnInv func(p *Peer, msg *protos.MsgInv) // OnHeaders is invoked when a peer receives a headers bitcoin message. OnHeaders func(p *Peer, msg *protos.MsgHeaders) // OnNotFound is invoked when a peer receives a notfound bitcoin // message. OnNotFound func(p *Peer, msg *protos.MsgNotFound) // OnGetData is invoked when a peer receives a getdata bitcoin message. OnGetData func(p *Peer, msg *protos.MsgGetData) // OnGetBlocks is invoked when a peer receives a getblocks bitcoin // message. OnGetBlocks func(p *Peer, msg *protos.MsgGetBlocks) // OnGetHeaders is invoked when a peer receives a getheaders bitcoin // message. OnGetHeaders func(p *Peer, msg *protos.MsgGetHeaders) // OnGetCFilters is invoked when a peer receives a getcfilters bitcoin // message. OnGetCFilters func(p *Peer, msg *protos.MsgGetCFilters) // OnGetCFHeaders is invoked when a peer receives a getcfheaders // bitcoin message. OnGetCFHeaders func(p *Peer, msg *protos.MsgGetCFHeaders) // OnGetCFCheckpt is invoked when a peer receives a getcfcheckpt // bitcoin message. OnGetCFCheckpt func(p *Peer, msg *protos.MsgGetCFCheckpt) // OnFeeFilter is invoked when a peer receives a feefilter bitcoin message. OnFeeFilter func(p *Peer, msg *protos.MsgFeeFilter) // OnFilterAdd is invoked when a peer receives a filteradd bitcoin message. OnFilterAdd func(p *Peer, msg *protos.MsgFilterAdd) // OnFilterClear is invoked when a peer receives a filterclear bitcoin // message. OnFilterClear func(p *Peer, msg *protos.MsgFilterClear) // OnFilterLoad is invoked when a peer receives a filterload bitcoin // message. OnFilterLoad func(p *Peer, msg *protos.MsgFilterLoad) // OnMerkleBlock is invoked when a peer receives a merkleblock bitcoin // message. OnMerkleBlock func(p *Peer, msg *protos.MsgMerkleBlock) // OnVersion is invoked when a peer receives a version bitcoin message. OnVersion func(p *Peer, msg *protos.MsgVersion) *protos.MsgReject // OnVerAck is invoked when a peer receives a verack bitcoin message. OnVerAck func(p *Peer, msg *protos.MsgVerAck) // OnReject is invoked when a peer receives a reject bitcoin message. OnReject func(p *Peer, msg *protos.MsgReject) // OnSendHeaders is invoked when a peer receives a sendheaders bitcoin // message. OnSendHeaders func(p *Peer, msg *protos.MsgSendHeaders) // OnRead is invoked when a peer receives a bitcoin message. It // consists of the number of bytes read, the message, and whether or not // an error in the read occurred. Typically, callers will opt to use // the callbacks for the specific message types, however this can be // useful for circumstances such as keeping track of server-wide byte // counts or working with custom message types for which the peer does // not directly provide a callback. OnRead func(p *Peer, bytesRead int, msg protos.Message, err error) // OnWrite is invoked when we write a bitcoin message to a peer. It // consists of the number of bytes written, the message, and whether or // not an error in the write occurred. This can be useful for // circumstances such as keeping track of server-wide byte counts. OnWrite func(p *Peer, bytesWritten int, msg protos.Message, err error) // OnBan is invoked when ban a misbehaving peer. OnBan func(p *Peer) }
MessageListeners defines callback function pointers to invoke with message listeners for a peer. Any listener which is not set to a concrete callback during peer initialization is ignored. Execution of multiple message listeners occurs serially, so one callback blocks the execution of the next.
NOTE: Unless otherwise documented, these listeners must NOT directly call any blocking calls (such as WaitForShutdown) on the peer instance since the input handler goroutine blocks until the callback has completed. Doing so will result in a deadlock.
type Peer ¶
type Peer struct {
// contains filtered or unexported fields
}
Peer provides a basic concurrent safe bitcoin peer for handling bitcoin communications via the peer-to-peer protocol. It provides full duplex reading and writing, automatic handling of the initial handshake process, querying of usage statistics and other information about the remote peer such as its address, user agent, and protocol version, output message queuing, inventory trickling, and the ability to dynamically register and unregister callbacks for handling bitcoin protocol messages.
Outbound messages are typically queued via QueueMessage or QueueInventory. QueueMessage is intended for all messages, including responses to data such as blocks and transactions. QueueInventory, on the other hand, is only intended for relaying inventory as it employs a trickling mechanism to batch the inventory together. However, some helper functions for pushing messages of specific types that typically require common special handling are provided as a convenience.
func NewInboundPeer ¶
NewInboundPeer returns a new inbound bitcoin peer. Use Start to begin processing incoming and outgoing messages.
func NewOutboundPeer ¶
NewOutboundPeer returns a new outbound bitcoin peer.
func (*Peer) AcceptBlockHeight ¶
AcceptBlockHeight updates the last known block for the peer.
This function is safe for concurrent access.
func (*Peer) 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 (*Peer) AddKnownInventory ¶
AddKnownInventory adds the passed inventory to the cache of known inventory for the peer.
This function is safe for concurrent access.
func (*Peer) AssociateConnection ¶
AssociateConnection associates the given conn to the peer. Calling this function when the peer is already connected will have no effect.
func (*Peer) BanScore ¶
BanScore returns the current integer value that represents how close the peer is to being banned.
This function is safe for concurrent access and is part of the rpcserverPeer interface implementation.
func (*Peer) BytesReceived ¶
BytesReceived returns the total number of bytes received by the peer.
This function is safe for concurrent access.
func (*Peer) BytesSent ¶
BytesSent returns the total number of bytes sent by the peer.
This function is safe for concurrent access.
func (*Peer) Connected ¶
Connected returns whether or not the peer is currently connected.
This function is safe for concurrent access.
func (*Peer) Disconnect ¶
func (p *Peer) Disconnect()
Disconnect disconnects the peer by closing the connection. Calling this function when the peer is already disconnected or in the process of disconnecting will have no effect.
func (*Peer) Inbound ¶
Inbound returns whether the peer is inbound.
This function is safe for concurrent access.
func (*Peer) IsWhitelisted ¶
func (*Peer) LastAcceptBlock ¶
LastAcceptBlock returns the last accept block of the peer.
This function is safe for concurrent access.
func (*Peer) LastAnnouncedBlock ¶
LastAnnouncedBlock returns the last announced block of the remote peer.
This function is safe for concurrent access.
func (*Peer) LastBlock ¶
LastBlock returns the last block of the peer.
This function is safe for concurrent access.
func (*Peer) LastPingMicros ¶
LastPingMicros returns the last ping micros of the remote peer.
This function is safe for concurrent access.
func (*Peer) LastPingNonce ¶
LastPingNonce returns the last ping nonce of the remote peer.
This function is safe for concurrent access.
func (*Peer) LastPingTime ¶
LastPingTime returns the last ping time of the remote peer.
This function is safe for concurrent access.
func (*Peer) LastRecv ¶
LastRecv returns the last recv time of the peer.
This function is safe for concurrent access.
func (*Peer) LastSend ¶
LastSend returns the last send time of the peer.
This function is safe for concurrent access.
func (*Peer) LocalAddr ¶
LocalAddr returns the local address of the connection.
This function is safe fo concurrent access.
func (*Peer) NA ¶
func (p *Peer) NA() *protos.NetAddress
NA returns the peer network address.
This function is safe for concurrent access.
func (*Peer) ProtocolVersion ¶
ProtocolVersion returns the negotiated peer protocol version.
This function is safe for concurrent access.
func (*Peer) PushAddrMsg ¶
func (p *Peer) PushAddrMsg(addresses []*protos.NetAddress) ([]*protos.NetAddress, error)
PushAddrMsg sends an addr message to the connected peer using the provided addresses. This function is useful over manually sending the message via QueueMessage since it automatically limits the addresses to the maximum number allowed by the message and randomizes the chosen addresses when there are too many. It returns the addresses that were actually sent and no message will be sent if there are no entries in the provided addresses slice.
This function is safe for concurrent access.
func (*Peer) PushGetBlocksMsg ¶
func (p *Peer) PushGetBlocksMsg(locator blockchain.BlockLocator, stopHash *common.Hash) error
PushGetBlocksMsg sends a getblocks message for the provided block locator and stop hash. It will ignore back-to-back duplicate requests.
This function is safe for concurrent access.
func (*Peer) PushGetHeadersMsg ¶
func (p *Peer) PushGetHeadersMsg(locator blockchain.BlockLocator, stopHash *common.Hash) error
PushGetHeadersMsg sends a getblocks message for the provided block locator and stop hash. It will ignore back-to-back duplicate requests.
This function is safe for concurrent access.
func (*Peer) PushRejectMsg ¶
func (p *Peer) PushRejectMsg(command string, code protos.RejectCode, reason string, hash *common.Hash, wait bool)
PushRejectMsg sends a reject message for the provided command, reject code, reject reason, and hash. The hash will only be used when the command is a tx or block and should be nil in other cases. The wait parameter will cause the function to block until the reject message has actually been sent.
This function is safe for concurrent access.
func (*Peer) QueueInventory ¶
QueueInventory adds the passed inventory to the inventory send queue which might not be sent right away, rather it is trickled to the peer in batches. Inventory that the peer is already known to have is ignored.
This function is safe for concurrent access.
func (*Peer) QueueMessage ¶
QueueMessage adds the passed bitcoin message to the peer send queue.
This function is safe for concurrent access.
func (*Peer) QueueMessageWithEncoding ¶
func (p *Peer) QueueMessageWithEncoding(msg protos.Message, doneChan chan<- struct{}, encoding protos.MessageEncoding)
QueueMessageWithEncoding adds the passed bitcoin message to the peer send queue. This function is identical to QueueMessage, however it allows the caller to specify the protos encoding type that should be used when encoding/decoding blocks and transactions.
This function is safe for concurrent access.
func (*Peer) Services ¶
func (p *Peer) Services() common.ServiceFlag
Services returns the services flag of the remote peer.
This function is safe for concurrent access.
func (*Peer) StartingHeight ¶
StartingHeight returns the last known height the peer reported during the initial negotiation phase.
This function is safe for concurrent access.
func (*Peer) StatsSnapshot ¶
StatsSnapshot returns a snapshot of the current peer flags and statistics.
This function is safe for concurrent access.
func (*Peer) String ¶
String returns the peer's address and directionality as a human-readable string.
This function is safe for concurrent access.
func (*Peer) TimeConnected ¶
TimeConnected returns the time at which the peer connected.
This function is safe for concurrent access.
func (*Peer) TimeOffset ¶
TimeOffset returns the number of seconds the local time was offset from the time the peer reported during the initial negotiation phase. Negative values indicate the remote peer's time is before the local time.
This function is safe for concurrent access.
func (*Peer) UpdateLastAnnouncedBlock ¶
UpdateLastAnnouncedBlock updates meta-data about the last block hash this peer is known to have announced.
This function is safe for concurrent access.
func (*Peer) UpdateLastBlockHeight ¶
UpdateLastBlockHeight updates the last known block for the peer.
This function is safe for concurrent access.
func (*Peer) UserAgent ¶
UserAgent returns the user agent of the remote peer.
This function is safe for concurrent access.
func (*Peer) VerAckReceived ¶
VerAckReceived returns whether or not a verack message was received by the peer.
This function is safe for concurrent access.
func (*Peer) VersionKnown ¶
VersionKnown returns the whether or not the version of a peer is known locally.
This function is safe for concurrent access.
func (*Peer) WaitForDisconnect ¶
func (p *Peer) WaitForDisconnect()
WaitForDisconnect waits until the peer has completely disconnected and all resources are cleaned up. This will happen if either the local or remote side has been disconnected or the peer is forcibly disconnected via Disconnect.
func (*Peer) WantsHeaders ¶
WantsHeaders returns if the peer wants header messages instead of inventory vectors for blocks.
This function is safe for concurrent access.
type StatsSnap ¶
type StatsSnap struct { ID int32 Addr string Services common.ServiceFlag LastSend time.Time LastRecv time.Time BytesSent uint64 BytesRecv uint64 ConnTime time.Time TimeOffset int64 Version uint32 UserAgent string Inbound bool StartingHeight int32 LastBlock int32 LastPingNonce uint64 LastPingTime time.Time LastPingMicros int64 }
StatsSnap is a snapshot of peer stats at a point in time.