peer

package
v0.0.0-...-c4a92bc Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2016 License: ISC Imports: 19 Imported by: 0

README

peer

[Build Status] (https://travis-ci.org/btcsuite/btcd) ![ISC License] (http://img.shields.io/badge/license-ISC-blue.svg) [GoDoc] (http://godoc.org/github.com/btcsuite/btcd/peer)

Package peer provides a common base for creating and managing bitcoin network peers.

This package has intentionally been designed so it can be used as a standalone package for any projects needing a full featured bitcoin peer base to build on.

Overview

This package builds upon the wire package, which provides the fundamental primitives necessary to speak the bitcoin wire protocol, in order to simplify the process of creating fully functional peers. In essence, it provides a common base for creating concurrent safe fully validating nodes, Simplified Payment Verification (SPV) nodes, proxies, etc.

A quick overview of the major features peer provides are as follows:

  • Provides a basic concurrent safe bitcoin peer for handling bitcoin communications via the peer-to-peer protocol
  • Full duplex reading and writing of bitcoin protocol messages
  • Automatic handling of the initial handshake process including protocol version negotiation
  • Asynchronous message queueing of outbound messages with optional channel for notification when the message is actually sent
  • Flexible peer configuration
    • Caller is responsible for creating outgoing connections and listening for incoming connections so they have flexibility to establish connections as they see fit (proxies, etc)
    • User agent name and version
    • Bitcoin network
    • Service support signalling (full nodes, bloom filters, etc)
    • Maximum supported protocol version
    • Ability to register callbacks for handling bitcoin protocol messages
  • Inventory message batching and send trickling with known inventory detection and avoidance
  • Automatic periodic keep-alive pinging and pong responses
  • Random nonce generation and self connection detection
  • Proper handling of bloom filter related commands when the caller does not specify the related flag to signal support
    • Disconnects the peer when the protocol version is high enough
    • Does not invoke the related callbacks for older protocol versions
  • Snapshottable peer statistics such as the total number of bytes read and written, the remote address, user agent, and negotiated protocol version
  • Helper functions pushing addresses, getblocks, getheaders, and reject messages
    • These could all be sent manually via the standard message output function, but the helpers provide additional nice functionality such as duplicate filtering and address randomization
  • Ability to wait for shutdown/disconnect
  • Comprehensive test coverage

Installation and Updating

$ go get -u github.com/btcsuite/btcd/peer

Examples

License

Package peer is licensed under the copyfree ISC License.

Documentation

Overview

Package peer provides a common base for creating and managing Bitcoin network peers.

Overview

This package builds upon the wire package, which provides the fundamental primitives necessary to speak the bitcoin wire protocol, in order to simplify the process of creating fully functional peers. In essence, it provides a common base for creating concurrent safe fully validating nodes, Simplified Payment Verification (SPV) nodes, proxies, etc.

A quick overview of the major features peer provides are as follows:

  • Provides a basic concurrent safe bitcoin peer for handling bitcoin communications via the peer-to-peer protocol
  • Full duplex reading and writing of bitcoin protocol messages
  • Automatic handling of the initial handshake process including protocol version negotiation
  • Asynchronous message queueing of outbound messages with optional channel for notification when the message is actually sent
  • Flexible peer configuration
  • Caller is responsible for creating outgoing connections and listening for incoming connections so they have flexibility to establish connections as they see fit (proxies, etc)
  • User agent name and version
  • Bitcoin network
  • Service support signalling (full nodes, bloom filters, etc)
  • Maximum supported protocol version
  • Ability to register callbacks for handling bitcoin protocol messages
  • Inventory message batching and send trickling with known inventory detection and avoidance
  • Automatic periodic keep-alive pinging and pong responses
  • Random nonce generation and self connection detection
  • Proper handling of bloom filter related commands when the caller does not specify the related flag to signal support
  • Disconnects the peer when the protocol version is high enough
  • Does not invoke the related callbacks for older protocol versions
  • Snapshottable peer statistics such as the total number of bytes read and written, the remote address, user agent, and negotiated protocol version
  • Helper functions pushing addresses, getblocks, getheaders, and reject messages
  • These could all be sent manually via the standard message output function, but the helpers provide additional nice functionality such as duplicate filtering and address randomization
  • Ability to wait for shutdown/disconnect
  • Comprehensive test coverage

Peer Configuration

All peer configuration is handled with the Config struct. This allows the caller to specify things such as the user agent name and version, the bitcoin network to use, which services it supports, and callbacks to invoke when bitcoin messages are received. See the documentation for each field of the Config struct for more details.

Inbound and Outbound Peers

A peer can either be inbound or outbound. The caller is responsible for establishing the connection to remote peers and listening for incoming peers. This provides high flexibility for things such as connecting via proxies, acting as a proxy, creating bridge peers, choosing whether to listen for inbound peers, etc.

For outgoing peers, the NewOutboundPeer function must be used to specify the configuration followed by invoking Connect with the net.Conn instance. This

will start all async I/O goroutines and initiate the initial negotiation

process. Once that has been completed, the peer is fully functional.

For inbound peers, the NewInboundPeer function must be used to specify the configuration and net.Conn instance followed by invoking Start. This will start all async I/O goroutines and listen for the initial negotiation process. Once that has been completed, the peer is fully functional.

Callbacks

In order to do anything useful with a peer, it is necessary to react to bitcoin messages. This is accomplished by creating an instance of the MessageListeners struct with the callbacks to be invoke specified and setting the Listeners field of the Config struct specified when creating a peer to it.

For convenience, a callback hook for all of the currently supported bitcoin messages is exposed which receives the peer instance and the concrete message type. In addition, a hook for OnRead is provided so even custom messages types for which this package does not directly provide a hook, as long as they implement the wire.Message interface, can be used. Finally, the OnWrite hook is provided, which in conjunction with OnRead, can be used to track server-wide byte counts.

It is often useful to use closures which encapsulate state when specifying the callback handlers. This provides a clean method for accessing that state when callbacks are invoked.

Queuing Messages and Inventory

The QueueMessage function provides the fundamental means to send messages to the remote peer. As the name implies, this employs a non-blocking queue. A done channel which will be notified when the message is actually sent can optionally be specified. There are certain message types which are better sent using other functions which provide additional functionality.

Of special interest are inventory messages. Rather than manually sending MsgInv messages via Queuemessage, the inventory vectors should be queued using the QueueInventory function. It employs batching and trickling along with intelligent known remote peer inventory detection and avoidance through the use of a most-recently used algorithm.

Message Sending Helper Functions

In addition to the bare QueueMessage function previously described, the PushAddrMsg, PushGetBlocksMsg, PushGetHeadersMsg, and PushRejectMsg functions are provided as a convenience. While it is of course possible to create and send these message manually via QueueMessage, these helper functions provided additional useful functionality that is typically desired.

For example, the PushAddrMsg function automatically limits the addresses to the maximum number allowed by the message and randomizes the chosen addresses when there are too many. This allows the caller to simply provide a slice of known addresses, such as that returned by the addrmgr package, without having to worry about the details.

Next, the PushGetBlocksMsg and PushGetHeadersMsg functions will construct proper messages using a block locator and ignore back to back duplicate requests.

Finally, the PushRejectMsg function can be used to easily create and send an appropriate reject message based on the provided parameters as well as optionally provides a flag to cause it to block until the message is actually sent.

Peer Statistics

A snapshot of the current peer statistics can be obtained with the StatsSnapshot function. This includes statistics such as the total number of bytes read and written, the remote address, user agent, and negotiated protocol version.

Logging

This package provides extensive logging capabilities through the UseLogger function which allows a btclog.Logger to be specified. For example, logging at the debug level provides summaries of every message sent and received, and logging at the trace level provides full dumps of parsed messages as well as the raw message bytes using a format similar to hexdump -C.

Bitcoin Improvement Proposals

This package supports all BIPS supported by the wire packge. (https://godoc.org/github.com/btcsuite/btcd/wire#hdr-Bitcoin_Improvement_Proposals)

Example (NewOutboundPeer)

This example demonstrates the basic process for initializing and creating an outbound peer. Peers negotiate by exchanging version and verack messages. For demonstration, a simple handler for version message is attached to the peer.

package main

import (
	"fmt"
	"net"
	"time"

	"github.com/alecalve/btcd/chaincfg"
	"github.com/alecalve/btcd/peer"
	"github.com/alecalve/btcd/wire"
)

// mockRemotePeer creates a basic inbound peer listening on the simnet port for
// use with Example_peerConnection.  It does not return until the listner is
// active.
func mockRemotePeer() error {
	// Configure peer to act as a simnet node that offers no services.
	peerCfg := &peer.Config{
		UserAgentName:    "peer",  // User agent name to advertise.
		UserAgentVersion: "1.0.0", // User agent version to advertise.
		ChainParams:      &chaincfg.SimNetParams,
	}

	// Accept connections on the simnet port.
	listener, err := net.Listen("tcp", "127.0.0.1:18555")
	if err != nil {
		return err
	}
	go func() {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Printf("Accept: error %v\n", err)
			return
		}

		// Create and start the inbound peer.
		p := peer.NewInboundPeer(peerCfg, conn)
		if err := p.Start(); err != nil {
			fmt.Printf("Start: error %v\n", err)
			return
		}
	}()

	return nil
}

// This example demonstrates the basic process for initializing and creating an
// outbound peer.  Peers negotiate by exchanging version and verack messages.
// For demonstration, a simple handler for version message is attached to the
// peer.
func main() {
	// Ordinarily this will not be needed since the outbound peer will be
	// connecting to a remote peer, however, since this example is executed
	// and tested, a mock remote peer is needed to listen for the outbound
	// peer.
	if err := mockRemotePeer(); err != nil {
		fmt.Printf("mockRemotePeer: unexpected error %v\n", err)
		return
	}

	// Create an outbound peer that is configured to act as a simnet node
	// that offers no services and has listeners for the version and verack
	// messages.  The verack listener is used here to signal the code below
	// when the handshake has been finished by signalling a channel.
	verack := make(chan struct{})
	peerCfg := &peer.Config{
		UserAgentName:    "peer",  // User agent name to advertise.
		UserAgentVersion: "1.0.0", // User agent version to advertise.
		ChainParams:      &chaincfg.SimNetParams,
		Services:         0,
		Listeners: peer.MessageListeners{
			OnVersion: func(p *peer.Peer, msg *wire.MsgVersion) {
				fmt.Println("outbound: received version")
			},
			OnVerAck: func(p *peer.Peer, msg *wire.MsgVerAck) {
				verack <- struct{}{}
			},
		},
	}
	p, err := peer.NewOutboundPeer(peerCfg, "127.0.0.1:18555")
	if err != nil {
		fmt.Printf("NewOutboundPeer: error %v\n", err)
		return
	}

	// Establish the connection to the peer address and mark it connected.
	conn, err := net.Dial("tcp", p.Addr())
	if err != nil {
		fmt.Printf("net.Dial: error %v\n", err)
		return
	}
	if err := p.Connect(conn); err != nil {
		fmt.Printf("Connect: error %v\n", err)
		return
	}

	// Wait for the verack message or timeout in case of failure.
	select {
	case <-verack:
	case <-time.After(time.Second * 1):
		fmt.Printf("Example_peerConnection: verack timeout")
	}

	// Shutdown the peer.
	p.Shutdown()

}
Output:

outbound: received version

Index

Examples

Constants

View Source
const (
	// MaxProtocolVersion is the max protocol version the peer supports.
	MaxProtocolVersion = 70011
)

Variables

This section is empty.

Functions

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until either UseLogger or SetLogWriter are called.

func SetLogWriter

func SetLogWriter(w io.Writer, level string) error

SetLogWriter uses a specified io.Writer to output package logging info. This allows a caller to direct package logging output without needing a dependency on seelog. If the caller is also using btclog, UseLogger should be used instead.

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger uses a specified Logger to output package logging info. This should be used in preference to SetLogWriter if the caller is also using btclog.

Types

type AddrFunc

type AddrFunc func(remoteAddr *wire.NetAddress) *wire.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 ShaFunc

	// BestLocalAddress returns the best local address for a given address.
	BestLocalAddress AddrFunc

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

	// 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 wire.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

	// 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 HostToNetAddrFunc

type HostToNetAddrFunc func(host string, port uint16,
	services wire.ServiceFlag) (*wire.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 *wire.MsgGetAddr)

	// OnAddr is invoked when a peer receives an addr bitcoin message.
	OnAddr func(p *Peer, msg *wire.MsgAddr)

	// OnPing is invoked when a peer receives a ping bitcoin message.
	OnPing func(p *Peer, msg *wire.MsgPing)

	// OnPong is invoked when a peer receives a pong bitcoin message.
	OnPong func(p *Peer, msg *wire.MsgPong)

	// OnAlert is invoked when a peer receives an alert bitcoin message.
	OnAlert func(p *Peer, msg *wire.MsgAlert)

	// OnMemPool is invoked when a peer receives a mempool bitcoin message.
	OnMemPool func(p *Peer, msg *wire.MsgMemPool)

	// OnTx is invoked when a peer receives a tx bitcoin message.
	OnTx func(p *Peer, msg *wire.MsgTx)

	// OnBlock is invoked when a peer receives a block bitcoin message.
	OnBlock func(p *Peer, msg *wire.MsgBlock, buf []byte)

	// OnInv is invoked when a peer receives an inv bitcoin message.
	OnInv func(p *Peer, msg *wire.MsgInv)

	// OnHeaders is invoked when a peer receives a headers bitcoin message.
	OnHeaders func(p *Peer, msg *wire.MsgHeaders)

	// OnNotFound is invoked when a peer receives a notfound bitcoin
	// message.
	OnNotFound func(p *Peer, msg *wire.MsgNotFound)

	// OnGetData is invoked when a peer receives a getdata bitcoin message.
	OnGetData func(p *Peer, msg *wire.MsgGetData)

	// OnGetBlocks is invoked when a peer receives a getblocks bitcoin
	// message.
	OnGetBlocks func(p *Peer, msg *wire.MsgGetBlocks)

	// OnGetHeaders is invoked when a peer receives a getheaders bitcoin
	// message.
	OnGetHeaders func(p *Peer, msg *wire.MsgGetHeaders)

	// OnFilterAdd is invoked when a peer receives a filteradd bitcoin message.
	// Peers that do not advertise support for bloom filters and negotiate to a
	// protocol version before BIP0111 will simply ignore the message while
	// those that negotiate to the BIP0111 protocol version or higher will be
	// immediately disconnected.
	OnFilterAdd func(p *Peer, msg *wire.MsgFilterAdd)

	// OnFilterClear is invoked when a peer receives a filterclear bitcoin
	// message.
	// Peers that do not advertise support for bloom filters and negotiate to a
	// protocol version before BIP0111 will simply ignore the message while
	// those that negotiate to the BIP0111 protocol version or higher will be
	// immediately disconnected.
	OnFilterClear func(p *Peer, msg *wire.MsgFilterClear)

	// OnFilterLoad is invoked when a peer receives a filterload bitcoin
	// message.
	// Peers that do not advertise support for bloom filters and negotiate to a
	// protocol version before BIP0111 will simply ignore the message while
	// those that negotiate to the BIP0111 protocol version or higher will be
	// immediately disconnected.
	OnFilterLoad func(p *Peer, msg *wire.MsgFilterLoad)

	// OnMerkleBlock  is invoked when a peer receives a merkleblock bitcoin
	// message.
	OnMerkleBlock func(p *Peer, msg *wire.MsgMerkleBlock)

	// OnVersion is invoked when a peer receives a version bitcoin message.
	OnVersion func(p *Peer, msg *wire.MsgVersion)

	// OnVerAck is invoked when a peer receives a verack bitcoin message.
	OnVerAck func(p *Peer, msg *wire.MsgVerAck)

	// OnReject is invoked when a peer receives a reject bitcoin message.
	OnReject func(p *Peer, msg *wire.MsgReject)

	// 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 wire.Message, err error)

	// OnWrite is invoked when a peer receives a bitcoin message.  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 wire.Message, err error)
}

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 excution 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 MruInventoryMap

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

MruInventoryMap provides a concurrency safe map that is limited to a maximum number of items with eviction for the oldest entry when the limit is exceeded.

func NewMruInventoryMap

func NewMruInventoryMap(limit uint) *MruInventoryMap

NewMruInventoryMap returns a new inventory map that is limited to the number of entries specified by limit. When the number of entries exceeds the limit, the oldest (least recently used) entry will be removed to make room for the new entry.

func (*MruInventoryMap) Add

func (m *MruInventoryMap) Add(iv *wire.InvVect)

Add adds the passed inventory to the map and handles eviction of the oldest item if adding the new item would exceed the max limit. Adding an existing item makes it the most recently used item.

This function is safe for concurrent access.

func (*MruInventoryMap) Delete

func (m *MruInventoryMap) Delete(iv *wire.InvVect)

Delete deletes the passed inventory item from the map (if it exists).

This function is safe for concurrent access.

func (*MruInventoryMap) Exists

func (m *MruInventoryMap) Exists(iv *wire.InvVect) bool

Exists returns whether or not the passed inventory item is in the map.

This function is safe for concurrent access.

func (*MruInventoryMap) String

func (m *MruInventoryMap) String() string

String returns the map as a human-readable string.

This function is safe for concurrent access.

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

func NewInboundPeer(cfg *Config, conn net.Conn) *Peer

NewInboundPeer returns a new inbound bitcoin peer. Use Start to begin processing incoming and outgoing messages.

func NewOutboundPeer

func NewOutboundPeer(cfg *Config, addr string) (*Peer, error)

NewOutboundPeer returns a new outbound bitcoin peer.

func (*Peer) AddKnownInventory

func (p *Peer) AddKnownInventory(invVect *wire.InvVect)

AddKnownInventory adds the passed inventory to the cache of known inventory for the peer.

This function is safe for concurrent access.

func (*Peer) Addr

func (p *Peer) Addr() string

Addr returns the peer address.

This function is safe for concurrent access.

func (*Peer) BytesReceived

func (p *Peer) BytesReceived() uint64

BytesReceived returns the total number of bytes received by the peer.

This function is safe for concurrent access.

func (*Peer) BytesSent

func (p *Peer) BytesSent() uint64

BytesSent returns the total number of bytes sent by the peer.

This function is safe for concurrent access.

func (*Peer) Connect

func (p *Peer) Connect(conn net.Conn) error

Connect uses the given conn to connect to the peer. Calling this function when the peer is already connected will have no effect.

func (*Peer) Connected

func (p *Peer) Connected() bool

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

func (p *Peer) ID() int32

ID returns the peer id.

This function is safe for concurrent access.

func (*Peer) Inbound

func (p *Peer) Inbound() bool

Inbound returns whether the peer is inbound.

This function is safe for concurrent access.

func (*Peer) LastAnnouncedBlock

func (p *Peer) LastAnnouncedBlock() *wire.ShaHash

LastAnnouncedBlock returns the last announced block of the remote peer.

This function is safe for concurrent access.

func (*Peer) LastBlock

func (p *Peer) LastBlock() int32

LastBlock returns the last block of the peer.

This function is safe for concurrent access.

func (*Peer) LastPingMicros

func (p *Peer) LastPingMicros() int64

LastPingMicros returns the last ping micros of the remote peer.

This function is safe for concurrent access.

func (*Peer) LastPingNonce

func (p *Peer) LastPingNonce() uint64

LastPingNonce returns the last ping nonce of the remote peer.

This function is safe for concurrent access.

func (*Peer) LastPingTime

func (p *Peer) LastPingTime() time.Time

LastPingTime returns the last ping time of the remote peer.

This function is safe for concurrent access.

func (*Peer) LastRecv

func (p *Peer) LastRecv() time.Time

LastRecv returns the last recv time of the peer.

This function is safe for concurrent access.

func (*Peer) LastSend

func (p *Peer) LastSend() time.Time

LastSend returns the last send time of the peer.

This function is safe for concurrent access.

func (*Peer) NA

func (p *Peer) NA() *wire.NetAddress

NA returns the peer network address.

This function is safe for concurrent access.

func (*Peer) ProtocolVersion

func (p *Peer) ProtocolVersion() uint32

ProtocolVersion returns the peer protocol version.

This function is safe for concurrent access.

func (*Peer) PushAddrMsg

func (p *Peer) PushAddrMsg(addresses []*wire.NetAddress) ([]*wire.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. No message will be sent if there are no entries in the provided addresses slice. It is safe for concurrent access.

func (*Peer) PushGetBlocksMsg

func (p *Peer) PushGetBlocksMsg(locator blockchain.BlockLocator, stopHash *wire.ShaHash) 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 *wire.ShaHash) 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 wire.RejectCode, reason string, hash *wire.ShaHash, 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

func (p *Peer) QueueInventory(invVect *wire.InvVect)

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

func (p *Peer) QueueMessage(msg wire.Message, doneChan chan struct{})

QueueMessage adds the passed bitcoin message to the peer send queue.

This function is safe for concurrent access.

func (*Peer) Services

func (p *Peer) Services() wire.ServiceFlag

Services returns the services flag of the remote peer.

This function is safe for concurrent access.

func (*Peer) Shutdown

func (p *Peer) Shutdown()

Shutdown gracefully shuts down the peer by disconnecting it.

func (*Peer) Start

func (p *Peer) Start() error

Start begins processing input and output messages. It also sends the initial version message for outbound connections to start the negotiation process.

func (*Peer) StartingHeight

func (p *Peer) StartingHeight() int32

StartingHeight returns the last known height the peer reported during the initial negotiation phase.

This function is safe for concurrent access.

func (*Peer) StatsSnapshot

func (p *Peer) StatsSnapshot() *StatsSnap

StatsSnapshot returns a snapshot of the current peer flags and statistics.

This function is safe for concurrent access.

func (*Peer) String

func (p *Peer) String() string

String returns the peer's address and directionality as a human-readable string.

This function is safe for concurrent access.

func (*Peer) TimeConnected

func (p *Peer) TimeConnected() time.Time

TimeConnected returns the time at which the peer connected.

This function is safe for concurrent access.

func (*Peer) TimeOffset

func (p *Peer) TimeOffset() int64

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

func (p *Peer) UpdateLastAnnouncedBlock(blkSha *wire.ShaHash)

UpdateLastAnnouncedBlock updates meta-data about the last block sha this peer is known to have announced.

This function is safe for concurrent access.

func (*Peer) UpdateLastBlockHeight

func (p *Peer) UpdateLastBlockHeight(newHeight int32)

UpdateLastBlockHeight updates the last known block for the peer.

This function is safe for concurrent access.

func (*Peer) UserAgent

func (p *Peer) UserAgent() string

UserAgent returns the user agent of the remote peer.

This function is safe for concurrent access.

func (*Peer) VerAckReceived

func (p *Peer) VerAckReceived() bool

VerAckReceived returns whether or not a verack message was received by the peer.

This function is safe for concurrent access.

func (*Peer) VersionKnown

func (p *Peer) VersionKnown() bool

VersionKnown returns the whether or not the version of a peer is known locally.

This function is safe for concurrent access.

func (*Peer) WaitForShutdown

func (p *Peer) WaitForShutdown()

WaitForShutdown waits until the peer has completely shutdown. This will happen if either the local or remote side has been disconnected or the peer is forcibly shutdown via Shutdown.

type ShaFunc

type ShaFunc func() (sha *wire.ShaHash, height int32, err error)

ShaFunc is a function which returns a block sha, height and error It is used as a callback to get newest block details.

type StatsSnap

type StatsSnap struct {
	ID             int32
	Addr           string
	Services       wire.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.

Jump to

Keyboard shortcuts

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