2014-01-01 17:16:15 +01:00
|
|
|
// Copyright (c) 2013-2014 Conformal Systems LLC.
|
2013-08-06 23:55:22 +02:00
|
|
|
// Use of this source code is governed by an ISC
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2013-08-29 21:44:43 +02:00
|
|
|
"container/list"
|
2013-08-08 17:11:03 +02:00
|
|
|
"fmt"
|
2014-07-09 05:01:13 +02:00
|
|
|
"io"
|
2013-08-06 23:55:22 +02:00
|
|
|
"net"
|
2013-08-07 20:17:29 +02:00
|
|
|
"strconv"
|
2013-08-06 23:55:22 +02:00
|
|
|
"sync"
|
2013-10-02 02:45:21 +02:00
|
|
|
"sync/atomic"
|
2013-08-06 23:55:22 +02:00
|
|
|
"time"
|
2014-07-02 15:50:08 +02:00
|
|
|
|
|
|
|
"github.com/conformal/btcchain"
|
2014-07-06 08:04:24 +02:00
|
|
|
"github.com/conformal/btcd/addrmgr"
|
2014-07-02 15:50:08 +02:00
|
|
|
"github.com/conformal/btcdb"
|
|
|
|
"github.com/conformal/btcutil"
|
2014-07-09 03:44:21 +02:00
|
|
|
"github.com/conformal/btcutil/bloom"
|
2014-07-02 15:50:08 +02:00
|
|
|
"github.com/conformal/btcwire"
|
|
|
|
socks "github.com/conformal/go-socks"
|
|
|
|
"github.com/davecgh/go-spew/spew"
|
2013-08-06 23:55:22 +02:00
|
|
|
)
|
|
|
|
|
2013-09-09 17:58:56 +02:00
|
|
|
const (
|
2014-03-28 20:50:02 +01:00
|
|
|
// maxProtocolVersion is the max protocol version the peer supports.
|
2014-07-09 05:01:13 +02:00
|
|
|
maxProtocolVersion = 70002
|
2014-03-28 20:50:02 +01:00
|
|
|
|
2013-09-12 19:11:22 +02:00
|
|
|
// outputBufferSize is the number of elements the output channels use.
|
2013-09-09 17:58:56 +02:00
|
|
|
outputBufferSize = 50
|
|
|
|
|
|
|
|
// invTrickleSize is the maximum amount of inventory to send in a single
|
|
|
|
// message when trickling inventory to remote peers.
|
|
|
|
maxInvTrickleSize = 1000
|
|
|
|
|
|
|
|
// maxKnownInventory is the maximum number of items to keep in the known
|
|
|
|
// inventory cache.
|
2014-04-23 13:48:52 +02:00
|
|
|
maxKnownInventory = 1000
|
2013-10-16 16:49:09 +02:00
|
|
|
|
2014-01-18 08:39:31 +01:00
|
|
|
// negotiateTimeoutSeconds is the number of seconds of inactivity before
|
|
|
|
// we timeout a peer that hasn't completed the initial version
|
|
|
|
// negotiation.
|
|
|
|
negotiateTimeoutSeconds = 30
|
|
|
|
|
2013-10-16 16:49:09 +02:00
|
|
|
// idleTimeoutMinutes is the number of minutes of inactivity before
|
|
|
|
// we time out a peer.
|
|
|
|
idleTimeoutMinutes = 5
|
|
|
|
|
|
|
|
// pingTimeoutMinutes is the number of minutes since we last sent a
|
|
|
|
// message requiring a reply before we will ping a host.
|
|
|
|
pingTimeoutMinutes = 2
|
2013-09-09 17:58:56 +02:00
|
|
|
)
|
2013-08-06 23:55:22 +02:00
|
|
|
|
2014-04-20 21:15:01 +02:00
|
|
|
var (
|
|
|
|
// userAgentName is the user agent name and is used to help identify
|
|
|
|
// ourselves to other bitcoin peers.
|
|
|
|
userAgentName = "btcd"
|
|
|
|
|
|
|
|
// userAgentVersion is the user agent version and is used to help
|
|
|
|
// identify ourselves to other bitcoin peers.
|
|
|
|
userAgentVersion = fmt.Sprintf("%d.%d.%d", appMajor, appMinor, appPatch)
|
|
|
|
)
|
2013-08-08 16:26:18 +02:00
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
// zeroHash is the zero value hash (all zeros). It is defined as a convenience.
|
|
|
|
var zeroHash btcwire.ShaHash
|
|
|
|
|
|
|
|
// minUint32 is a helper function to return the minimum of two uint32s.
|
|
|
|
// This avoids a math import and the need to cast to floats.
|
|
|
|
func minUint32(a, b uint32) uint32 {
|
|
|
|
if a < b {
|
|
|
|
return a
|
|
|
|
}
|
|
|
|
return b
|
|
|
|
}
|
|
|
|
|
2013-08-07 20:17:29 +02:00
|
|
|
// newNetAddress attempts to extract the IP address and port from the passed
|
|
|
|
// net.Addr interface and create a bitcoin NetAddress structure using that
|
|
|
|
// information.
|
|
|
|
func newNetAddress(addr net.Addr, services btcwire.ServiceFlag) (*btcwire.NetAddress, error) {
|
|
|
|
// addr will be a net.TCPAddr when not using a proxy.
|
|
|
|
if tcpAddr, ok := addr.(*net.TCPAddr); ok {
|
|
|
|
ip := tcpAddr.IP
|
|
|
|
port := uint16(tcpAddr.Port)
|
|
|
|
na := btcwire.NewNetAddressIPPort(ip, port, services)
|
|
|
|
return na, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// addr will be a socks.ProxiedAddr when using a proxy.
|
|
|
|
if proxiedAddr, ok := addr.(*socks.ProxiedAddr); ok {
|
|
|
|
ip := net.ParseIP(proxiedAddr.Host)
|
|
|
|
if ip == nil {
|
|
|
|
ip = net.ParseIP("0.0.0.0")
|
|
|
|
}
|
|
|
|
port := uint16(proxiedAddr.Port)
|
|
|
|
na := btcwire.NewNetAddressIPPort(ip, port, services)
|
|
|
|
return na, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// For the most part, addr should be one of the two above cases, but
|
|
|
|
// to be safe, fall back to trying to parse the information from the
|
|
|
|
// address string as a last resort.
|
|
|
|
host, portStr, err := net.SplitHostPort(addr.String())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
ip := net.ParseIP(host)
|
|
|
|
port, err := strconv.ParseUint(portStr, 10, 16)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
na := btcwire.NewNetAddressIPPort(ip, uint16(port), services)
|
|
|
|
return na, nil
|
|
|
|
}
|
|
|
|
|
2014-07-11 05:40:53 +02:00
|
|
|
// outMsg is used to house a message to be sent along with a channel to signal
|
|
|
|
// when the message has been sent (or won't be sent due to tings such as
|
|
|
|
// shutdown)
|
2013-10-11 19:30:14 +02:00
|
|
|
type outMsg struct {
|
|
|
|
msg btcwire.Message
|
2014-07-11 05:40:53 +02:00
|
|
|
doneChan chan struct{}
|
2013-10-11 19:30:14 +02:00
|
|
|
}
|
|
|
|
|
2013-12-24 17:32:20 +01:00
|
|
|
// peer provides a bitcoin peer for handling bitcoin communications. The
|
|
|
|
// overall data flow is split into 3 goroutines and a separate block manager.
|
|
|
|
// Inbound messages are read via the inHandler goroutine and generally
|
|
|
|
// dispatched to their own handler. For inbound data-related messages such as
|
|
|
|
// blocks, transactions, and inventory, the data is pased on to the block
|
|
|
|
// manager to handle it. Outbound messages are 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. The data flow for outbound
|
|
|
|
// messages uses two goroutines, queueHandler and outHandler. The first,
|
|
|
|
// queueHandler, is used as a way for external entities (mainly block manager)
|
|
|
|
// to queue messages quickly regardless of whether the peer is currently
|
|
|
|
// sending or not. It acts as the traffic cop between the external world and
|
|
|
|
// the actual goroutine which writes to the network socket. In addition, the
|
|
|
|
// peer contains several functions which are of the form pushX, that are used
|
|
|
|
// to push messages to the peer. Internally they use QueueMessage.
|
2013-08-06 23:55:22 +02:00
|
|
|
type peer struct {
|
2013-09-18 20:33:54 +02:00
|
|
|
server *server
|
|
|
|
btcnet btcwire.BitcoinNet
|
2013-10-03 01:33:42 +02:00
|
|
|
started int32
|
2014-07-23 21:12:06 +02:00
|
|
|
connected int32
|
|
|
|
disconnect int32 // only to be used atomically
|
2013-09-18 20:33:54 +02:00
|
|
|
conn net.Conn
|
|
|
|
addr string
|
|
|
|
na *btcwire.NetAddress
|
|
|
|
inbound bool
|
|
|
|
persistent bool
|
2014-07-02 16:45:17 +02:00
|
|
|
knownAddresses map[string]struct{}
|
2013-09-18 20:33:54 +02:00
|
|
|
knownInventory *MruInventoryMap
|
|
|
|
knownInvMutex sync.Mutex
|
2014-07-02 16:45:17 +02:00
|
|
|
requestedTxns map[btcwire.ShaHash]struct{} // owned by blockmanager
|
|
|
|
requestedBlocks map[btcwire.ShaHash]struct{} // owned by blockmanager
|
2013-12-24 17:32:20 +01:00
|
|
|
retryCount int64
|
|
|
|
prevGetBlocksBegin *btcwire.ShaHash // owned by blockmanager
|
|
|
|
prevGetBlocksStop *btcwire.ShaHash // owned by blockmanager
|
Rework and improve headers-first mode.
This commit improves how the headers-first mode works in several ways.
The previous headers-first code was an initial implementation that did not
have all of the bells and whistles and a few less than ideal
characteristics. This commit improves the heaers-first code to resolve
the issues discussed next.
- The previous code only used headers-first mode when starting out from
block height 0 rather than allowing it to work starting at any height
before the final checkpoint. This means if you stopped the chain
download at any point before the final checkpoint and restarted, it
would not resume and you therefore would not have the benefit of the
faster processing offered by headers-first mode.
- Previously all headers (even those after the final checkpoint) were
downloaded and only the final checkpoint was verified. This resulted in
the following issues:
- As the block chain grew, increasingly larger numbers of headers were
downloaded and kept in memory
- If the node the node serving up the headers was serving an invalid
chain, it wouldn't be detected until downloading a large number of
headers
- When an invalid checkpoint was detected, no action was taken to
recover which meant the chain download would essentially be stalled
- The headers were kept in memory even though they didn't need to be as
merely keeping track of the hashes and heights is enough to provde they
properly link together and checkpoints match
- There was no logging when headers were being downloaded so it could
appear like nothing was happening
- Duplicate requests for the same headers weren't being filtered which
meant is was possible to inadvertently download the same headers twice
only to throw them away.
This commit resolves these issues with the following changes:
- The current height is now examined at startup and prior each sync peer
selection to allow it to resume headers-first mode starting from the
known height to the next checkpoint
- All checkpoints are now verified and the headers are only downloaded
from the current known block height up to the next checkpoint. This has
several desirable properties:
- The amount of memory required is bounded by the maximum distance
between to checkpoints rather than the entire length of the chain
- A node serving up an invalid chain is detected very quickly and with
little work
- When an invalid checkpoint is detected, the headers are simply
discarded and the peer is disconnected for serving an invalid chain
- When the sync peer disconnets, all current headers are thrown away
and, due to the new aforementioned resume code, when a new sync peer
is selected, headers-first mode will continue from the last known good
block
- In addition to reduced memory usage from only keeping information about
headers between two checkpoints, the only information now kept in memory
about the headers is the hash and height rather than the entire header
- There is now logging information about what is happening with headers
- Duplicate header requests are now filtered
2014-01-30 18:29:02 +01:00
|
|
|
prevGetHdrsBegin *btcwire.ShaHash // owned by blockmanager
|
|
|
|
prevGetHdrsStop *btcwire.ShaHash // owned by blockmanager
|
2013-09-18 20:33:54 +02:00
|
|
|
requestQueue *list.List
|
2014-07-09 03:44:21 +02:00
|
|
|
filter *bloom.Filter
|
|
|
|
relayMtx sync.Mutex
|
|
|
|
disableRelayTx bool
|
2013-09-18 20:33:54 +02:00
|
|
|
continueHash *btcwire.ShaHash
|
2013-10-11 19:30:14 +02:00
|
|
|
outputQueue chan outMsg
|
2013-12-20 14:06:37 +01:00
|
|
|
sendQueue chan outMsg
|
2014-07-02 17:31:10 +02:00
|
|
|
sendDoneQueue chan struct{}
|
2013-12-20 14:06:37 +01:00
|
|
|
queueWg sync.WaitGroup // TODO(oga) wg -> single use channel?
|
2013-12-24 17:32:20 +01:00
|
|
|
outputInvChan chan *btcwire.InvVect
|
2014-07-11 05:28:22 +02:00
|
|
|
txProcessed chan struct{}
|
|
|
|
blockProcessed chan struct{}
|
2014-07-02 17:31:10 +02:00
|
|
|
quit chan struct{}
|
2014-04-23 18:36:33 +02:00
|
|
|
StatsMtx sync.Mutex // protects all statistics below here.
|
|
|
|
versionKnown bool
|
|
|
|
protocolVersion uint32
|
|
|
|
services btcwire.ServiceFlag
|
|
|
|
timeConnected time.Time
|
|
|
|
lastSend time.Time
|
|
|
|
lastRecv time.Time
|
|
|
|
bytesReceived uint64
|
|
|
|
bytesSent uint64
|
2013-12-24 17:32:20 +01:00
|
|
|
userAgent string
|
2014-04-23 18:36:33 +02:00
|
|
|
lastBlock int32
|
|
|
|
lastPingNonce uint64 // Set to nonce if we have a pending ping.
|
|
|
|
lastPingTime time.Time // Time we sent last ping.
|
|
|
|
lastPingMicros int64 // Time for last ping to return.
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2013-10-03 03:05:10 +02:00
|
|
|
// String returns the peer's address and directionality as a human-readable
|
|
|
|
// string.
|
|
|
|
func (p *peer) String() string {
|
|
|
|
return fmt.Sprintf("%s (%s)", p.addr, directionString(p.inbound))
|
|
|
|
}
|
|
|
|
|
2013-09-09 17:58:56 +02:00
|
|
|
// isKnownInventory returns whether or not the peer is known to have the passed
|
|
|
|
// inventory. It is safe for concurrent access.
|
|
|
|
func (p *peer) isKnownInventory(invVect *btcwire.InvVect) bool {
|
|
|
|
p.knownInvMutex.Lock()
|
|
|
|
defer p.knownInvMutex.Unlock()
|
|
|
|
|
|
|
|
if p.knownInventory.Exists(invVect) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2013-12-24 17:32:20 +01:00
|
|
|
// AddKnownInventory adds the passed inventory to the cache of known inventory
|
2013-09-09 17:58:56 +02:00
|
|
|
// for the peer. It is safe for concurrent access.
|
2013-12-24 17:32:20 +01:00
|
|
|
func (p *peer) AddKnownInventory(invVect *btcwire.InvVect) {
|
2013-09-09 17:58:56 +02:00
|
|
|
p.knownInvMutex.Lock()
|
|
|
|
defer p.knownInvMutex.Unlock()
|
|
|
|
|
|
|
|
p.knownInventory.Add(invVect)
|
|
|
|
}
|
|
|
|
|
2014-03-19 23:04:10 +01:00
|
|
|
// VersionKnown returns the whether or not the version of a peer is known locally.
|
|
|
|
// It is safe for concurrent access.
|
|
|
|
func (p *peer) VersionKnown() bool {
|
2014-04-23 18:36:33 +02:00
|
|
|
p.StatsMtx.Lock()
|
|
|
|
defer p.StatsMtx.Unlock()
|
2014-03-19 23:04:10 +01:00
|
|
|
|
|
|
|
return p.versionKnown
|
|
|
|
}
|
|
|
|
|
2014-04-23 18:36:33 +02:00
|
|
|
// ProtocolVersion returns the peer protocol version in a manner that is safe
|
|
|
|
// for concurrent access.
|
|
|
|
func (p *peer) ProtocolVersion() uint32 {
|
|
|
|
p.StatsMtx.Lock()
|
|
|
|
defer p.StatsMtx.Unlock()
|
|
|
|
|
|
|
|
return p.protocolVersion
|
|
|
|
}
|
|
|
|
|
2014-07-09 03:44:21 +02:00
|
|
|
// RelayTxDisabled returns whether or not relaying of transactions is disabled.
|
|
|
|
// It is safe for concurrent access.
|
|
|
|
func (p *peer) RelayTxDisabled() bool {
|
|
|
|
p.relayMtx.Lock()
|
|
|
|
defer p.relayMtx.Unlock()
|
|
|
|
|
|
|
|
return p.disableRelayTx
|
|
|
|
}
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
// pushVersionMsg sends a version message to the connected peer using the
|
|
|
|
// current state.
|
|
|
|
func (p *peer) pushVersionMsg() error {
|
|
|
|
_, blockNum, err := p.server.db.NewestSha()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2013-11-28 18:06:54 +01:00
|
|
|
theirNa := p.na
|
|
|
|
|
|
|
|
// If we are behind a proxy and the connection comes from the proxy then
|
|
|
|
// we return an unroutable address as their address. This is to prevent
|
|
|
|
// leaking the tor proxy address.
|
|
|
|
if cfg.Proxy != "" {
|
|
|
|
proxyaddress, _, err := net.SplitHostPort(cfg.Proxy)
|
|
|
|
// invalid proxy means poorly configured, be on the safe side.
|
|
|
|
if err != nil || p.na.IP.String() == proxyaddress {
|
|
|
|
theirNa = &btcwire.NetAddress{
|
|
|
|
Timestamp: time.Now(),
|
|
|
|
IP: net.IP([]byte{0, 0, 0, 0}),
|
|
|
|
}
|
|
|
|
}
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2013-08-07 20:17:29 +02:00
|
|
|
// Version message.
|
2013-11-28 18:06:54 +01:00
|
|
|
msg := btcwire.NewMsgVersion(
|
2014-07-06 08:04:24 +02:00
|
|
|
p.server.addrManager.GetBestLocalAddress(p.na), theirNa,
|
2014-04-20 21:15:01 +02:00
|
|
|
p.server.nonce, int32(blockNum))
|
|
|
|
msg.AddUserAgent(userAgentName, userAgentVersion)
|
2013-08-07 20:17:29 +02:00
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
// XXX: bitcoind appears to always enable the full node services flag
|
|
|
|
// of the remote peer netaddress field in the version message regardless
|
|
|
|
// of whether it knows it supports it or not. Also, bitcoind sets
|
|
|
|
// the services field of the local peer to 0 regardless of support.
|
|
|
|
//
|
|
|
|
// Realistically, this should be set as follows:
|
|
|
|
// - For outgoing connections:
|
|
|
|
// - Set the local netaddress services to what the local peer
|
|
|
|
// actually supports
|
|
|
|
// - Set the remote netaddress services to 0 to indicate no services
|
|
|
|
// as they are still unknown
|
|
|
|
// - For incoming connections:
|
|
|
|
// - Set the local netaddress services to what the local peer
|
|
|
|
// actually supports
|
|
|
|
// - Set the remote netaddress services to the what was advertised by
|
|
|
|
// by the remote peer in its version message
|
|
|
|
msg.AddrYou.Services = btcwire.SFNodeNetwork
|
|
|
|
|
|
|
|
// Advertise that we're a full node.
|
|
|
|
msg.Services = btcwire.SFNodeNetwork
|
|
|
|
|
2014-03-28 20:50:02 +01:00
|
|
|
// Advertise our max supported protocol version.
|
|
|
|
msg.ProtocolVersion = maxProtocolVersion
|
|
|
|
|
2013-10-16 16:49:09 +02:00
|
|
|
p.QueueMessage(msg, nil)
|
2013-08-06 23:55:22 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-05-28 22:19:38 +02:00
|
|
|
// updateAddresses potentially adds addresses to the address manager and
|
|
|
|
// requests known addresses from the remote peer depending on whether the peer
|
|
|
|
// is an inbound or outbound peer and other factors such as address routability
|
|
|
|
// and the negotiated protocol version.
|
|
|
|
func (p *peer) updateAddresses(msg *btcwire.MsgVersion) {
|
|
|
|
// Outbound connections.
|
|
|
|
if !p.inbound {
|
|
|
|
// TODO(davec): Only do this if not doing the initial block
|
|
|
|
// download and the local address is routable.
|
|
|
|
if !cfg.DisableListen /* && isCurrent? */ {
|
|
|
|
// Get address that best matches.
|
2014-07-06 08:04:24 +02:00
|
|
|
lna := p.server.addrManager.GetBestLocalAddress(p.na)
|
2014-07-06 15:47:42 +02:00
|
|
|
if addrmgr.IsRoutable(lna) {
|
2014-05-28 22:19:38 +02:00
|
|
|
addresses := []*btcwire.NetAddress{lna}
|
|
|
|
p.pushAddrMsg(addresses)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Request known addresses if the server address manager needs
|
|
|
|
// more and the peer has a protocol version new enough to
|
|
|
|
// include a timestamp with addresses.
|
|
|
|
hasTimestamp := p.ProtocolVersion() >=
|
|
|
|
btcwire.NetAddressTimeVersion
|
|
|
|
if p.server.addrManager.NeedMoreAddresses() && hasTimestamp {
|
|
|
|
p.QueueMessage(btcwire.NewMsgGetAddr(), nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Mark the address as a known good address.
|
|
|
|
p.server.addrManager.Good(p.na)
|
|
|
|
} else {
|
|
|
|
// A peer might not be advertising the same address that it
|
|
|
|
// actually connected from. One example of why this can happen
|
|
|
|
// is with NAT. Only add the address to the address manager if
|
|
|
|
// the addresses agree.
|
2014-07-06 08:04:24 +02:00
|
|
|
if addrmgr.NetAddressKey(&msg.AddrMe) == addrmgr.NetAddressKey(p.na) {
|
2014-05-28 22:19:38 +02:00
|
|
|
p.server.addrManager.AddAddress(p.na, p.na)
|
|
|
|
p.server.addrManager.Good(p.na)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
// handleVersionMsg 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 (p *peer) handleVersionMsg(msg *btcwire.MsgVersion) {
|
|
|
|
// Detect self connections.
|
|
|
|
if msg.Nonce == p.server.nonce {
|
2014-03-04 16:43:32 +01:00
|
|
|
peerLog.Debugf("Disconnecting peer connected to self %s", p)
|
2013-08-09 22:47:06 +02:00
|
|
|
p.Disconnect()
|
2013-08-06 23:55:22 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-07-09 05:01:13 +02:00
|
|
|
// Notify and disconnect clients that have a protocol version that is
|
|
|
|
// too old.
|
|
|
|
if msg.ProtocolVersion < int32(btcwire.MultipleAddressVersion) {
|
|
|
|
// Send a reject message indicating the protocol version is
|
|
|
|
// obsolete and wait for the message to be sent before
|
|
|
|
// disconnecting.
|
|
|
|
reason := fmt.Sprintf("protocol version must be %d or greater",
|
|
|
|
btcwire.MultipleAddressVersion)
|
|
|
|
p.PushRejectMsg(msg.Command(), btcwire.RejectObsolete, reason,
|
|
|
|
nil, true)
|
|
|
|
p.Disconnect()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Updating a bunch of stats.
|
|
|
|
p.StatsMtx.Lock()
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
// Limit to one version message per peer.
|
|
|
|
if p.versionKnown {
|
2014-02-14 19:44:53 +01:00
|
|
|
p.logError("Only one version message per peer is allowed %s.",
|
2014-03-04 16:43:32 +01:00
|
|
|
p)
|
2014-04-23 18:36:33 +02:00
|
|
|
p.StatsMtx.Unlock()
|
2014-07-09 05:01:13 +02:00
|
|
|
|
|
|
|
// Send an reject message indicating the version message was
|
|
|
|
// incorrectly sent twice and wait for the message to be sent
|
|
|
|
// before disconnecting.
|
|
|
|
p.PushRejectMsg(msg.Command(), btcwire.RejectDuplicate,
|
|
|
|
"duplicate version message", nil, true)
|
|
|
|
|
2013-08-09 22:47:06 +02:00
|
|
|
p.Disconnect()
|
2013-08-06 23:55:22 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Negotiate the protocol version.
|
|
|
|
p.protocolVersion = minUint32(p.protocolVersion, uint32(msg.ProtocolVersion))
|
|
|
|
p.versionKnown = true
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Debugf("Negotiated protocol version %d for peer %s",
|
2014-03-04 16:43:32 +01:00
|
|
|
p.protocolVersion, p)
|
2013-08-06 23:55:22 +02:00
|
|
|
p.lastBlock = msg.LastBlock
|
|
|
|
|
2013-09-03 23:55:14 +02:00
|
|
|
// Set the supported services for the peer to what the remote peer
|
|
|
|
// advertised.
|
2013-09-03 20:34:27 +02:00
|
|
|
p.services = msg.Services
|
|
|
|
|
2013-10-29 21:25:08 +01:00
|
|
|
// Set the remote peer's user agent.
|
|
|
|
p.userAgent = msg.UserAgent
|
|
|
|
|
2014-04-23 18:36:33 +02:00
|
|
|
p.StatsMtx.Unlock()
|
|
|
|
|
2014-07-09 03:44:21 +02:00
|
|
|
// Choose whether or not to relay transactions before a filter command
|
|
|
|
// is received.
|
|
|
|
p.relayMtx.Lock()
|
|
|
|
p.disableRelayTx = msg.DisableRelayTx
|
|
|
|
p.relayMtx.Unlock()
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
// Inbound connections.
|
|
|
|
if p.inbound {
|
2013-11-21 20:05:14 +01:00
|
|
|
// Set up a NetAddress for the peer to be used with AddrManager.
|
|
|
|
// We only do this inbound because outbound set this up
|
|
|
|
// at connection time and no point recomputing.
|
|
|
|
na, err := newNetAddress(p.conn.RemoteAddr(), p.services)
|
|
|
|
if err != nil {
|
2013-11-21 19:03:56 +01:00
|
|
|
p.logError("Can't get remote address: %v", err)
|
2013-11-21 20:05:14 +01:00
|
|
|
p.Disconnect()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
p.na = na
|
2013-11-28 18:04:56 +01:00
|
|
|
|
|
|
|
// Send version.
|
|
|
|
err = p.pushVersionMsg()
|
|
|
|
if err != nil {
|
2014-02-28 17:59:21 +01:00
|
|
|
p.logError("Can't send version message to %s: %v",
|
2014-03-04 16:43:32 +01:00
|
|
|
p, err)
|
2013-11-28 18:04:56 +01:00
|
|
|
p.Disconnect()
|
|
|
|
return
|
|
|
|
}
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Send verack.
|
2013-10-16 16:49:09 +02:00
|
|
|
p.QueueMessage(btcwire.NewMsgVerAck(), nil)
|
2013-08-06 23:55:22 +02:00
|
|
|
|
2014-05-28 22:19:38 +02:00
|
|
|
// Update the address manager and request known addresses from the
|
|
|
|
// remote peer for outbound connections. This is skipped when running
|
|
|
|
// on the simulation test network since it is only intended to connect
|
|
|
|
// to specified peers and actively avoids advertising and connecting to
|
|
|
|
// discovered peers.
|
|
|
|
if !cfg.SimNet {
|
|
|
|
p.updateAddresses(msg)
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2013-09-03 23:55:14 +02:00
|
|
|
// Signal the block manager this peer is a new sync candidate.
|
2013-10-01 00:53:21 +02:00
|
|
|
p.server.blockManager.NewPeer(p)
|
2013-08-06 23:55:22 +02:00
|
|
|
|
|
|
|
// TODO: Relay alerts.
|
|
|
|
}
|
|
|
|
|
|
|
|
// pushTxMsg sends a tx message for the provided transaction hash to the
|
2013-10-11 21:12:40 +02:00
|
|
|
// connected peer. An error is returned if the transaction hash is not known.
|
2014-07-11 05:40:53 +02:00
|
|
|
func (p *peer) pushTxMsg(sha *btcwire.ShaHash, doneChan, waitChan chan struct{}) error {
|
2013-10-11 21:12:40 +02:00
|
|
|
// Attempt to fetch the requested transaction from the pool. A
|
|
|
|
// call could be made to check for existence first, but simply trying
|
|
|
|
// to fetch a missing transaction results in the same behavior.
|
|
|
|
tx, err := p.server.txMemPool.FetchTransaction(sha)
|
|
|
|
if err != nil {
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Tracef("Unable to fetch tx %v from transaction "+
|
2013-10-11 21:12:40 +02:00
|
|
|
"pool: %v", sha, err)
|
2014-07-03 23:57:06 +02:00
|
|
|
|
|
|
|
if doneChan != nil {
|
2014-07-11 05:40:53 +02:00
|
|
|
doneChan <- struct{}{}
|
2014-07-03 23:57:06 +02:00
|
|
|
}
|
2013-10-11 21:12:40 +02:00
|
|
|
return err
|
|
|
|
}
|
2013-12-20 14:06:37 +01:00
|
|
|
|
|
|
|
// Once we have fetched data wait for any previous operation to finish.
|
|
|
|
if waitChan != nil {
|
|
|
|
<-waitChan
|
|
|
|
}
|
|
|
|
|
2013-10-28 21:44:38 +01:00
|
|
|
p.QueueMessage(tx.MsgTx(), doneChan)
|
2013-10-11 21:12:40 +02:00
|
|
|
|
|
|
|
return nil
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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.
|
2014-07-11 05:40:53 +02:00
|
|
|
func (p *peer) pushBlockMsg(sha *btcwire.ShaHash, doneChan, waitChan chan struct{}) error {
|
2013-10-11 21:12:40 +02:00
|
|
|
blk, err := p.server.db.FetchBlockBySha(sha)
|
2013-08-06 23:55:22 +02:00
|
|
|
if err != nil {
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Tracef("Unable to fetch requested block sha %v: %v",
|
2013-10-11 21:12:40 +02:00
|
|
|
sha, err)
|
2014-07-03 23:57:06 +02:00
|
|
|
|
|
|
|
if doneChan != nil {
|
2014-07-11 05:40:53 +02:00
|
|
|
doneChan <- struct{}{}
|
2014-07-03 23:57:06 +02:00
|
|
|
}
|
2013-08-06 23:55:22 +02:00
|
|
|
return err
|
|
|
|
}
|
2013-10-16 16:49:09 +02:00
|
|
|
|
2013-12-20 14:06:37 +01:00
|
|
|
// Once we have fetched data wait for any previous operation to finish.
|
|
|
|
if waitChan != nil {
|
|
|
|
<-waitChan
|
|
|
|
}
|
|
|
|
|
2013-10-16 16:49:09 +02:00
|
|
|
// We only send the channel for this message if we aren't sending
|
|
|
|
// an inv straight after.
|
2014-07-11 05:40:53 +02:00
|
|
|
var dc chan struct{}
|
2013-10-16 16:49:09 +02:00
|
|
|
sendInv := p.continueHash != nil && p.continueHash.IsEqual(sha)
|
|
|
|
if !sendInv {
|
|
|
|
dc = doneChan
|
|
|
|
}
|
|
|
|
p.QueueMessage(blk.MsgBlock(), dc)
|
2013-09-05 08:20:48 +02:00
|
|
|
|
|
|
|
// When the peer requests the final block that was advertised in
|
|
|
|
// response to a getblocks message which requested more blocks than
|
|
|
|
// would fit into a single message, send it a new inventory message
|
|
|
|
// to trigger it to issue another getblocks message for the next
|
|
|
|
// batch of inventory.
|
2013-10-11 21:12:40 +02:00
|
|
|
if p.continueHash != nil && p.continueHash.IsEqual(sha) {
|
2013-09-05 08:20:48 +02:00
|
|
|
hash, _, err := p.server.db.NewestSha()
|
|
|
|
if err == nil {
|
2014-04-20 02:05:35 +02:00
|
|
|
invMsg := btcwire.NewMsgInvSizeHint(1)
|
2013-10-08 22:55:07 +02:00
|
|
|
iv := btcwire.NewInvVect(btcwire.InvTypeBlock, hash)
|
2013-09-05 08:20:48 +02:00
|
|
|
invMsg.AddInvVect(iv)
|
2013-10-16 16:49:09 +02:00
|
|
|
p.QueueMessage(invMsg, doneChan)
|
2013-09-05 08:20:48 +02:00
|
|
|
p.continueHash = nil
|
2013-10-16 16:49:09 +02:00
|
|
|
} else if doneChan != nil {
|
2014-07-11 05:40:53 +02:00
|
|
|
doneChan <- struct{}{}
|
2013-09-05 08:20:48 +02:00
|
|
|
}
|
|
|
|
}
|
2013-08-06 23:55:22 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-07-09 03:44:21 +02:00
|
|
|
// 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 laoded. An
|
|
|
|
// error is returned if the block hash is not known.
|
2014-07-11 05:40:53 +02:00
|
|
|
func (p *peer) pushMerkleBlockMsg(sha *btcwire.ShaHash, doneChan, waitChan chan struct{}) error {
|
2014-07-09 03:44:21 +02:00
|
|
|
// Do not send a response if the peer doesn't have a filter loaded.
|
|
|
|
if !p.filter.IsLoaded() {
|
|
|
|
if doneChan != nil {
|
2014-07-11 05:40:53 +02:00
|
|
|
doneChan <- struct{}{}
|
2014-07-09 03:44:21 +02:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
blk, err := p.server.db.FetchBlockBySha(sha)
|
|
|
|
if err != nil {
|
|
|
|
peerLog.Tracef("Unable to fetch requested block sha %v: %v",
|
|
|
|
sha, err)
|
|
|
|
|
|
|
|
if doneChan != nil {
|
2014-07-11 05:40:53 +02:00
|
|
|
doneChan <- struct{}{}
|
2014-07-09 03:44:21 +02:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Generate a merkle block by filtering the requested block according
|
|
|
|
// to the filter for the peer and fetch any matched transactions from
|
|
|
|
// the database.
|
|
|
|
merkle, matchedHashes := bloom.NewMerkleBlock(blk, p.filter)
|
|
|
|
txList := p.server.db.FetchTxByShaList(matchedHashes)
|
|
|
|
|
|
|
|
// Warn on any missing transactions which should not happen since the
|
|
|
|
// matched transactions come from an existing block. Also, find the
|
|
|
|
// final valid transaction index for later.
|
|
|
|
finalValidTxIndex := -1
|
|
|
|
for i, txR := range txList {
|
|
|
|
if txR.Err != nil || txR.Tx == nil {
|
|
|
|
warnMsg := fmt.Sprintf("Failed to fetch transaction "+
|
|
|
|
"%v which was matched by merkle block %v",
|
|
|
|
txR.Sha, sha)
|
|
|
|
if txR.Err != nil {
|
|
|
|
warnMsg += ": " + err.Error()
|
|
|
|
}
|
|
|
|
peerLog.Warnf(warnMsg)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
finalValidTxIndex = i
|
|
|
|
}
|
|
|
|
|
|
|
|
// Once we have fetched data wait for any previous operation to finish.
|
|
|
|
if waitChan != nil {
|
|
|
|
<-waitChan
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send the merkleblock. Only send the done channel with this message
|
|
|
|
// if no transactions will be sent afterwards.
|
2014-07-11 05:40:53 +02:00
|
|
|
var dc chan struct{}
|
2014-07-11 04:41:33 +02:00
|
|
|
if finalValidTxIndex == -1 {
|
2014-07-09 03:44:21 +02:00
|
|
|
dc = doneChan
|
|
|
|
}
|
|
|
|
p.QueueMessage(merkle, dc)
|
|
|
|
|
|
|
|
// Finally, send any matched transactions.
|
|
|
|
for i, txR := range txList {
|
|
|
|
// Only send the done channel on the final transaction.
|
2014-07-11 05:40:53 +02:00
|
|
|
var dc chan struct{}
|
2014-07-09 03:44:21 +02:00
|
|
|
if i == finalValidTxIndex {
|
|
|
|
dc = doneChan
|
|
|
|
}
|
|
|
|
if txR.Err == nil && txR.Tx != nil {
|
|
|
|
p.QueueMessage(txR.Tx, dc)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2013-10-08 20:34:04 +02:00
|
|
|
// PushGetBlocksMsg sends a getblocks message for the provided block locator
|
2013-09-18 20:33:54 +02:00
|
|
|
// and stop hash. It will ignore back-to-back duplicate requests.
|
2013-09-27 02:41:02 +02:00
|
|
|
func (p *peer) PushGetBlocksMsg(locator btcchain.BlockLocator, stopHash *btcwire.ShaHash) error {
|
2013-09-18 20:33:54 +02:00
|
|
|
// Extract the begin hash from the block locator, if one was specified,
|
|
|
|
// to use for filtering duplicate getblocks requests.
|
|
|
|
// request.
|
|
|
|
var beginHash *btcwire.ShaHash
|
|
|
|
if len(locator) > 0 {
|
|
|
|
beginHash = locator[0]
|
|
|
|
}
|
|
|
|
|
|
|
|
// Filter duplicate getblocks requests.
|
|
|
|
if p.prevGetBlocksStop != nil && p.prevGetBlocksBegin != nil &&
|
|
|
|
beginHash != nil && stopHash.IsEqual(p.prevGetBlocksStop) &&
|
|
|
|
beginHash.IsEqual(p.prevGetBlocksBegin) {
|
|
|
|
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Tracef("Filtering duplicate [getblocks] with begin "+
|
2013-09-18 20:33:54 +02:00
|
|
|
"hash %v, stop hash %v", beginHash, stopHash)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Construct the getblocks request and queue it to be sent.
|
2013-08-29 21:44:43 +02:00
|
|
|
msg := btcwire.NewMsgGetBlocks(stopHash)
|
|
|
|
for _, hash := range locator {
|
|
|
|
err := msg.AddBlockLocatorHash(hash)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2013-10-16 16:49:09 +02:00
|
|
|
p.QueueMessage(msg, nil)
|
2013-09-18 20:33:54 +02:00
|
|
|
|
|
|
|
// Update the previous getblocks request information for filtering
|
|
|
|
// duplicates.
|
|
|
|
p.prevGetBlocksBegin = beginHash
|
|
|
|
p.prevGetBlocksStop = stopHash
|
2013-08-29 21:44:43 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2013-11-16 00:16:51 +01:00
|
|
|
// PushGetHeadersMsg sends a getblocks message for the provided block locator
|
|
|
|
// and stop hash. It will ignore back-to-back duplicate requests.
|
Rework and improve headers-first mode.
This commit improves how the headers-first mode works in several ways.
The previous headers-first code was an initial implementation that did not
have all of the bells and whistles and a few less than ideal
characteristics. This commit improves the heaers-first code to resolve
the issues discussed next.
- The previous code only used headers-first mode when starting out from
block height 0 rather than allowing it to work starting at any height
before the final checkpoint. This means if you stopped the chain
download at any point before the final checkpoint and restarted, it
would not resume and you therefore would not have the benefit of the
faster processing offered by headers-first mode.
- Previously all headers (even those after the final checkpoint) were
downloaded and only the final checkpoint was verified. This resulted in
the following issues:
- As the block chain grew, increasingly larger numbers of headers were
downloaded and kept in memory
- If the node the node serving up the headers was serving an invalid
chain, it wouldn't be detected until downloading a large number of
headers
- When an invalid checkpoint was detected, no action was taken to
recover which meant the chain download would essentially be stalled
- The headers were kept in memory even though they didn't need to be as
merely keeping track of the hashes and heights is enough to provde they
properly link together and checkpoints match
- There was no logging when headers were being downloaded so it could
appear like nothing was happening
- Duplicate requests for the same headers weren't being filtered which
meant is was possible to inadvertently download the same headers twice
only to throw them away.
This commit resolves these issues with the following changes:
- The current height is now examined at startup and prior each sync peer
selection to allow it to resume headers-first mode starting from the
known height to the next checkpoint
- All checkpoints are now verified and the headers are only downloaded
from the current known block height up to the next checkpoint. This has
several desirable properties:
- The amount of memory required is bounded by the maximum distance
between to checkpoints rather than the entire length of the chain
- A node serving up an invalid chain is detected very quickly and with
little work
- When an invalid checkpoint is detected, the headers are simply
discarded and the peer is disconnected for serving an invalid chain
- When the sync peer disconnets, all current headers are thrown away
and, due to the new aforementioned resume code, when a new sync peer
is selected, headers-first mode will continue from the last known good
block
- In addition to reduced memory usage from only keeping information about
headers between two checkpoints, the only information now kept in memory
about the headers is the hash and height rather than the entire header
- There is now logging information about what is happening with headers
- Duplicate header requests are now filtered
2014-01-30 18:29:02 +01:00
|
|
|
func (p *peer) PushGetHeadersMsg(locator btcchain.BlockLocator, stopHash *btcwire.ShaHash) error {
|
2013-11-16 00:16:51 +01:00
|
|
|
// Extract the begin hash from the block locator, if one was specified,
|
2014-01-29 01:53:25 +01:00
|
|
|
// to use for filtering duplicate getheaders requests.
|
2013-11-16 00:16:51 +01:00
|
|
|
var beginHash *btcwire.ShaHash
|
|
|
|
if len(locator) > 0 {
|
|
|
|
beginHash = locator[0]
|
|
|
|
}
|
|
|
|
|
2014-01-29 01:53:25 +01:00
|
|
|
// Filter duplicate getheaders requests.
|
Rework and improve headers-first mode.
This commit improves how the headers-first mode works in several ways.
The previous headers-first code was an initial implementation that did not
have all of the bells and whistles and a few less than ideal
characteristics. This commit improves the heaers-first code to resolve
the issues discussed next.
- The previous code only used headers-first mode when starting out from
block height 0 rather than allowing it to work starting at any height
before the final checkpoint. This means if you stopped the chain
download at any point before the final checkpoint and restarted, it
would not resume and you therefore would not have the benefit of the
faster processing offered by headers-first mode.
- Previously all headers (even those after the final checkpoint) were
downloaded and only the final checkpoint was verified. This resulted in
the following issues:
- As the block chain grew, increasingly larger numbers of headers were
downloaded and kept in memory
- If the node the node serving up the headers was serving an invalid
chain, it wouldn't be detected until downloading a large number of
headers
- When an invalid checkpoint was detected, no action was taken to
recover which meant the chain download would essentially be stalled
- The headers were kept in memory even though they didn't need to be as
merely keeping track of the hashes and heights is enough to provde they
properly link together and checkpoints match
- There was no logging when headers were being downloaded so it could
appear like nothing was happening
- Duplicate requests for the same headers weren't being filtered which
meant is was possible to inadvertently download the same headers twice
only to throw them away.
This commit resolves these issues with the following changes:
- The current height is now examined at startup and prior each sync peer
selection to allow it to resume headers-first mode starting from the
known height to the next checkpoint
- All checkpoints are now verified and the headers are only downloaded
from the current known block height up to the next checkpoint. This has
several desirable properties:
- The amount of memory required is bounded by the maximum distance
between to checkpoints rather than the entire length of the chain
- A node serving up an invalid chain is detected very quickly and with
little work
- When an invalid checkpoint is detected, the headers are simply
discarded and the peer is disconnected for serving an invalid chain
- When the sync peer disconnets, all current headers are thrown away
and, due to the new aforementioned resume code, when a new sync peer
is selected, headers-first mode will continue from the last known good
block
- In addition to reduced memory usage from only keeping information about
headers between two checkpoints, the only information now kept in memory
about the headers is the hash and height rather than the entire header
- There is now logging information about what is happening with headers
- Duplicate header requests are now filtered
2014-01-30 18:29:02 +01:00
|
|
|
if p.prevGetHdrsStop != nil && p.prevGetHdrsBegin != nil &&
|
|
|
|
beginHash != nil && stopHash.IsEqual(p.prevGetHdrsStop) &&
|
|
|
|
beginHash.IsEqual(p.prevGetHdrsBegin) {
|
2013-11-16 00:16:51 +01:00
|
|
|
|
2014-02-14 19:44:53 +01:00
|
|
|
peerLog.Tracef("Filtering duplicate [getheaders] with begin "+
|
|
|
|
"hash %v", beginHash)
|
2013-11-16 00:16:51 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Construct the getheaders request and queue it to be sent.
|
|
|
|
msg := btcwire.NewMsgGetHeaders()
|
Rework and improve headers-first mode.
This commit improves how the headers-first mode works in several ways.
The previous headers-first code was an initial implementation that did not
have all of the bells and whistles and a few less than ideal
characteristics. This commit improves the heaers-first code to resolve
the issues discussed next.
- The previous code only used headers-first mode when starting out from
block height 0 rather than allowing it to work starting at any height
before the final checkpoint. This means if you stopped the chain
download at any point before the final checkpoint and restarted, it
would not resume and you therefore would not have the benefit of the
faster processing offered by headers-first mode.
- Previously all headers (even those after the final checkpoint) were
downloaded and only the final checkpoint was verified. This resulted in
the following issues:
- As the block chain grew, increasingly larger numbers of headers were
downloaded and kept in memory
- If the node the node serving up the headers was serving an invalid
chain, it wouldn't be detected until downloading a large number of
headers
- When an invalid checkpoint was detected, no action was taken to
recover which meant the chain download would essentially be stalled
- The headers were kept in memory even though they didn't need to be as
merely keeping track of the hashes and heights is enough to provde they
properly link together and checkpoints match
- There was no logging when headers were being downloaded so it could
appear like nothing was happening
- Duplicate requests for the same headers weren't being filtered which
meant is was possible to inadvertently download the same headers twice
only to throw them away.
This commit resolves these issues with the following changes:
- The current height is now examined at startup and prior each sync peer
selection to allow it to resume headers-first mode starting from the
known height to the next checkpoint
- All checkpoints are now verified and the headers are only downloaded
from the current known block height up to the next checkpoint. This has
several desirable properties:
- The amount of memory required is bounded by the maximum distance
between to checkpoints rather than the entire length of the chain
- A node serving up an invalid chain is detected very quickly and with
little work
- When an invalid checkpoint is detected, the headers are simply
discarded and the peer is disconnected for serving an invalid chain
- When the sync peer disconnets, all current headers are thrown away
and, due to the new aforementioned resume code, when a new sync peer
is selected, headers-first mode will continue from the last known good
block
- In addition to reduced memory usage from only keeping information about
headers between two checkpoints, the only information now kept in memory
about the headers is the hash and height rather than the entire header
- There is now logging information about what is happening with headers
- Duplicate header requests are now filtered
2014-01-30 18:29:02 +01:00
|
|
|
msg.HashStop = *stopHash
|
2013-11-16 00:16:51 +01:00
|
|
|
for _, hash := range locator {
|
|
|
|
err := msg.AddBlockLocatorHash(hash)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
p.QueueMessage(msg, nil)
|
|
|
|
|
2014-01-29 01:53:25 +01:00
|
|
|
// Update the previous getheaders request information for filtering
|
2013-11-16 00:16:51 +01:00
|
|
|
// duplicates.
|
Rework and improve headers-first mode.
This commit improves how the headers-first mode works in several ways.
The previous headers-first code was an initial implementation that did not
have all of the bells and whistles and a few less than ideal
characteristics. This commit improves the heaers-first code to resolve
the issues discussed next.
- The previous code only used headers-first mode when starting out from
block height 0 rather than allowing it to work starting at any height
before the final checkpoint. This means if you stopped the chain
download at any point before the final checkpoint and restarted, it
would not resume and you therefore would not have the benefit of the
faster processing offered by headers-first mode.
- Previously all headers (even those after the final checkpoint) were
downloaded and only the final checkpoint was verified. This resulted in
the following issues:
- As the block chain grew, increasingly larger numbers of headers were
downloaded and kept in memory
- If the node the node serving up the headers was serving an invalid
chain, it wouldn't be detected until downloading a large number of
headers
- When an invalid checkpoint was detected, no action was taken to
recover which meant the chain download would essentially be stalled
- The headers were kept in memory even though they didn't need to be as
merely keeping track of the hashes and heights is enough to provde they
properly link together and checkpoints match
- There was no logging when headers were being downloaded so it could
appear like nothing was happening
- Duplicate requests for the same headers weren't being filtered which
meant is was possible to inadvertently download the same headers twice
only to throw them away.
This commit resolves these issues with the following changes:
- The current height is now examined at startup and prior each sync peer
selection to allow it to resume headers-first mode starting from the
known height to the next checkpoint
- All checkpoints are now verified and the headers are only downloaded
from the current known block height up to the next checkpoint. This has
several desirable properties:
- The amount of memory required is bounded by the maximum distance
between to checkpoints rather than the entire length of the chain
- A node serving up an invalid chain is detected very quickly and with
little work
- When an invalid checkpoint is detected, the headers are simply
discarded and the peer is disconnected for serving an invalid chain
- When the sync peer disconnets, all current headers are thrown away
and, due to the new aforementioned resume code, when a new sync peer
is selected, headers-first mode will continue from the last known good
block
- In addition to reduced memory usage from only keeping information about
headers between two checkpoints, the only information now kept in memory
about the headers is the hash and height rather than the entire header
- There is now logging information about what is happening with headers
- Duplicate header requests are now filtered
2014-01-30 18:29:02 +01:00
|
|
|
p.prevGetHdrsBegin = beginHash
|
|
|
|
p.prevGetHdrsStop = stopHash
|
2013-11-16 00:16:51 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-07-09 05:01:13 +02:00
|
|
|
// PushRejectMsg sends a reject message for the provided command, reject code,
|
|
|
|
// and 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.
|
|
|
|
func (p *peer) PushRejectMsg(command string, code btcwire.RejectCode, reason string, hash *btcwire.ShaHash, wait bool) {
|
|
|
|
// Don't bother sending the reject message if the protocol version
|
|
|
|
// is too low.
|
|
|
|
if p.VersionKnown() && p.ProtocolVersion() < btcwire.RejectVersion {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
msg := btcwire.NewMsgReject(command, code, reason)
|
|
|
|
if command == btcwire.CmdTx || command == btcwire.CmdBlock {
|
|
|
|
if hash == nil {
|
|
|
|
peerLog.Warnf("Sending a reject message for command "+
|
|
|
|
"type %v which should have specified a hash "+
|
|
|
|
"but does not", command)
|
|
|
|
hash = &zeroHash
|
|
|
|
}
|
|
|
|
msg.Hash = *hash
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send the message without waiting if the caller has not requested it.
|
|
|
|
if !wait {
|
|
|
|
p.QueueMessage(msg, nil)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send the message and block until it has been sent before returning.
|
|
|
|
doneChan := make(chan struct{}, 1)
|
|
|
|
p.QueueMessage(msg, doneChan)
|
|
|
|
<-doneChan
|
|
|
|
}
|
|
|
|
|
2013-10-08 07:04:51 +02:00
|
|
|
// handleMemPoolMsg is invoked when a peer receives a mempool bitcoin message.
|
|
|
|
// It creates and sends an inventory message with the contents of the memory
|
2014-07-09 03:44:21 +02:00
|
|
|
// pool up to the maximum inventory allowed per message. When the peer has a
|
|
|
|
// bloom filter loaded, the contents are filtered accordingly.
|
2013-10-08 07:04:51 +02:00
|
|
|
func (p *peer) handleMemPoolMsg(msg *btcwire.MsgMemPool) {
|
|
|
|
// Generate inventory message with the available transactions in the
|
|
|
|
// transaction memory pool. Limit it to the max allowed inventory
|
2014-01-09 00:46:59 +01:00
|
|
|
// per message. The the NewMsgInvSizeHint function automatically limits
|
|
|
|
// the passed hint to the maximum allowed, so it's safe to pass it
|
|
|
|
// without double checking it here.
|
2014-07-09 03:44:21 +02:00
|
|
|
txDescs := p.server.txMemPool.TxDescs()
|
|
|
|
invMsg := btcwire.NewMsgInvSizeHint(uint(len(txDescs)))
|
|
|
|
|
|
|
|
for i, txDesc := range txDescs {
|
2013-11-15 23:12:23 +01:00
|
|
|
// Another thread might have removed the transaction from the
|
|
|
|
// pool since the initial query.
|
2014-07-09 03:44:21 +02:00
|
|
|
hash := txDesc.Tx.Sha()
|
2013-11-15 23:12:23 +01:00
|
|
|
if !p.server.txMemPool.IsTransactionInPool(hash) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2014-07-09 03:44:21 +02:00
|
|
|
// Either add all transactions when there is no bloom filter,
|
|
|
|
// or only the transactions that match the filter when there is
|
|
|
|
// one.
|
|
|
|
if !p.filter.IsLoaded() || p.filter.MatchTxAndUpdate(txDesc.Tx) {
|
|
|
|
iv := btcwire.NewInvVect(btcwire.InvTypeTx, hash)
|
|
|
|
invMsg.AddInvVect(iv)
|
|
|
|
if i+1 >= btcwire.MaxInvPerMsg {
|
|
|
|
break
|
|
|
|
}
|
2013-10-08 07:04:51 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send the inventory message if there is anything to send.
|
|
|
|
if len(invMsg.InvList) > 0 {
|
2013-10-16 16:49:09 +02:00
|
|
|
p.QueueMessage(invMsg, nil)
|
2013-10-08 07:04:51 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-09-20 19:55:27 +02:00
|
|
|
// handleTxMsg 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 (p *peer) handleTxMsg(msg *btcwire.MsgTx) {
|
|
|
|
// Add the transaction to the known inventory for the peer.
|
2013-10-28 21:44:38 +01:00
|
|
|
// Convert the raw MsgTx to a btcutil.Tx which provides some convenience
|
|
|
|
// methods and things such as hash caching.
|
|
|
|
tx := btcutil.NewTx(msg)
|
|
|
|
iv := btcwire.NewInvVect(btcwire.InvTypeTx, tx.Sha())
|
2013-12-24 17:32:20 +01:00
|
|
|
p.AddKnownInventory(iv)
|
2013-09-20 19:55:27 +02:00
|
|
|
|
2013-10-08 17:47:00 +02:00
|
|
|
// Queue the transaction up to be handled by the block manager and
|
|
|
|
// intentionally block further receives until the transaction is fully
|
|
|
|
// processed and known good or bad. This helps prevent a malicious peer
|
|
|
|
// from queueing up a bunch of bad transactions before disconnecting (or
|
|
|
|
// being disconnected) and wasting memory.
|
2013-10-28 21:44:38 +01:00
|
|
|
p.server.blockManager.QueueTx(tx, p)
|
2013-10-08 17:47:00 +02:00
|
|
|
<-p.txProcessed
|
2013-09-20 19:55:27 +02:00
|
|
|
}
|
|
|
|
|
2013-09-09 17:58:56 +02:00
|
|
|
// handleBlockMsg is invoked when a peer receives a block bitcoin message. It
|
|
|
|
// blocks until the bitcoin block has been fully processed.
|
|
|
|
func (p *peer) handleBlockMsg(msg *btcwire.MsgBlock, buf []byte) {
|
2013-10-28 21:44:38 +01:00
|
|
|
// Convert the raw MsgBlock to a btcutil.Block which provides some
|
|
|
|
// convenience methods and things such as hash caching.
|
2013-09-09 17:58:56 +02:00
|
|
|
block := btcutil.NewBlockFromBlockAndBytes(msg, buf)
|
|
|
|
|
|
|
|
// Add the block to the known inventory for the peer.
|
|
|
|
hash, err := block.Sha()
|
|
|
|
if err != nil {
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Errorf("Unable to get block hash: %v", err)
|
2013-09-09 17:58:56 +02:00
|
|
|
return
|
|
|
|
}
|
2013-10-08 22:55:07 +02:00
|
|
|
iv := btcwire.NewInvVect(btcwire.InvTypeBlock, hash)
|
2013-12-24 17:32:20 +01:00
|
|
|
p.AddKnownInventory(iv)
|
2013-09-09 17:58:56 +02:00
|
|
|
|
|
|
|
// Queue the block up to be handled by the block
|
|
|
|
// manager and intentionally block further receives
|
|
|
|
// until the bitcoin block is fully processed and known
|
|
|
|
// good or bad. This helps prevent a malicious peer
|
|
|
|
// from queueing up a bunch of bad blocks before
|
|
|
|
// disconnecting (or being disconnected) and wasting
|
|
|
|
// memory. Additionally, this behavior is depended on
|
|
|
|
// by at least the block acceptance test tool as the
|
|
|
|
// reference implementation processes blocks in the same
|
|
|
|
// thread and therefore blocks further messages until
|
|
|
|
// the bitcoin block has been fully processed.
|
|
|
|
p.server.blockManager.QueueBlock(block, p)
|
|
|
|
<-p.blockProcessed
|
|
|
|
}
|
|
|
|
|
2013-08-29 21:44:43 +02:00
|
|
|
// handleInvMsg 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
|
2014-01-29 01:53:25 +01:00
|
|
|
// accordingly. We pass the message down to blockmanager which will call
|
2013-10-11 19:23:56 +02:00
|
|
|
// QueueMessage with any appropriate responses.
|
2013-08-29 21:44:43 +02:00
|
|
|
func (p *peer) handleInvMsg(msg *btcwire.MsgInv) {
|
2013-09-27 02:41:02 +02:00
|
|
|
p.server.blockManager.QueueInv(msg, p)
|
2013-08-29 21:44:43 +02:00
|
|
|
}
|
|
|
|
|
2014-01-29 01:53:25 +01:00
|
|
|
// handleHeadersMsg is invoked when a peer receives a headers bitcoin message.
|
|
|
|
// The message is passed down to the block manager.
|
2013-11-16 00:16:51 +01:00
|
|
|
func (p *peer) handleHeadersMsg(msg *btcwire.MsgHeaders) {
|
|
|
|
p.server.blockManager.QueueHeaders(msg, p)
|
|
|
|
}
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
// handleGetData is invoked when a peer receives a getdata bitcoin message and
|
|
|
|
// is used to deliver block and transaction information.
|
|
|
|
func (p *peer) handleGetDataMsg(msg *btcwire.MsgGetData) {
|
2014-04-21 20:52:02 +02:00
|
|
|
numAdded := 0
|
2013-08-06 23:55:22 +02:00
|
|
|
notFound := btcwire.NewMsgNotFound()
|
|
|
|
|
2013-12-20 14:06:37 +01:00
|
|
|
// We wait on the this wait channel periodically to prevent queueing
|
|
|
|
// far more data than we can send in a reasonable time, wasting memory.
|
|
|
|
// The waiting occurs after the database fetch for the next one to
|
|
|
|
// provide a little pipelining.
|
2014-07-11 05:40:53 +02:00
|
|
|
var waitChan chan struct{}
|
|
|
|
doneChan := make(chan struct{}, 1)
|
2014-04-21 20:52:02 +02:00
|
|
|
|
2013-10-16 16:49:09 +02:00
|
|
|
for i, iv := range msg.InvList {
|
2014-07-11 05:40:53 +02:00
|
|
|
var c chan struct{}
|
2013-10-16 16:49:09 +02:00
|
|
|
// If this will be the last message we send.
|
|
|
|
if i == len(msg.InvList)-1 && len(notFound.InvList) == 0 {
|
|
|
|
c = doneChan
|
2014-07-03 23:57:06 +02:00
|
|
|
} else if (i+1)%3 == 0 {
|
|
|
|
// Buffered so as to not make the send goroutine block.
|
2014-07-11 05:40:53 +02:00
|
|
|
c = make(chan struct{}, 1)
|
2013-10-16 16:49:09 +02:00
|
|
|
}
|
2013-08-06 23:55:22 +02:00
|
|
|
var err error
|
|
|
|
switch iv.Type {
|
2013-10-08 22:55:07 +02:00
|
|
|
case btcwire.InvTypeTx:
|
2013-12-20 14:06:37 +01:00
|
|
|
err = p.pushTxMsg(&iv.Hash, c, waitChan)
|
2013-10-08 22:55:07 +02:00
|
|
|
case btcwire.InvTypeBlock:
|
2013-12-20 14:06:37 +01:00
|
|
|
err = p.pushBlockMsg(&iv.Hash, c, waitChan)
|
2014-07-09 03:44:21 +02:00
|
|
|
case btcwire.InvTypeFilteredBlock:
|
|
|
|
err = p.pushMerkleBlockMsg(&iv.Hash, c, waitChan)
|
2013-08-06 23:55:22 +02:00
|
|
|
default:
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Warnf("Unknown type in inventory request %d",
|
2013-08-06 23:55:22 +02:00
|
|
|
iv.Type)
|
2014-04-21 20:52:02 +02:00
|
|
|
continue
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
notFound.AddInvVect(iv)
|
2014-07-03 23:57:06 +02:00
|
|
|
|
|
|
|
// When there is a failure fetching the final entry
|
|
|
|
// and the done channel was sent in due to there
|
|
|
|
// being no outstanding not found inventory, consume
|
|
|
|
// it here because there is now not found inventory
|
|
|
|
// that will use the channel momentarily.
|
|
|
|
if i == len(msg.InvList)-1 && c != nil {
|
|
|
|
<-c
|
|
|
|
}
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
2014-04-21 20:52:02 +02:00
|
|
|
numAdded++
|
2013-12-20 14:06:37 +01:00
|
|
|
waitChan = c
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
if len(notFound.InvList) != 0 {
|
2013-10-16 16:49:09 +02:00
|
|
|
p.QueueMessage(notFound, doneChan)
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
2013-10-16 16:49:09 +02:00
|
|
|
|
|
|
|
// Wait for messages to be sent. We can send quite a lot of data at this
|
|
|
|
// point and this will keep the peer busy for a decent amount of time.
|
|
|
|
// We don't process anything else by them in this time so that we
|
|
|
|
// have an idea of when we should hear back from them - else the idle
|
|
|
|
// timeout could fire when we were only half done sending the blocks.
|
2014-04-21 20:52:02 +02:00
|
|
|
if numAdded > 0 {
|
|
|
|
<-doneChan
|
|
|
|
}
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2014-07-09 03:44:21 +02:00
|
|
|
// handleGetBlocksMsg is invoked when a peer receives a getblocks bitcoin message.
|
2013-08-06 23:55:22 +02:00
|
|
|
func (p *peer) handleGetBlocksMsg(msg *btcwire.MsgGetBlocks) {
|
|
|
|
// Return all block hashes to the latest one (up to max per message) if
|
|
|
|
// no stop hash was specified.
|
|
|
|
// Attempt to find the ending index of the stop hash if specified.
|
2013-09-05 08:20:48 +02:00
|
|
|
endIdx := btcdb.AllShas
|
2013-08-06 23:55:22 +02:00
|
|
|
if !msg.HashStop.IsEqual(&zeroHash) {
|
2014-01-29 02:24:05 +01:00
|
|
|
height, err := p.server.db.FetchBlockHeightBySha(&msg.HashStop)
|
2013-09-05 08:20:48 +02:00
|
|
|
if err == nil {
|
2014-01-29 02:24:05 +01:00
|
|
|
endIdx = height + 1
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-09-05 08:20:48 +02:00
|
|
|
// Find the most recent known block based on the block locator.
|
|
|
|
// Use the block after the genesis block if no other blocks in the
|
|
|
|
// provided locator are known. This does mean the client will start
|
|
|
|
// over with the genesis block if unknown block locators are provided.
|
|
|
|
// This mirrors the behavior in the reference implementation.
|
|
|
|
startIdx := int64(1)
|
2013-08-06 23:55:22 +02:00
|
|
|
for _, hash := range msg.BlockLocatorHashes {
|
2014-01-29 02:24:05 +01:00
|
|
|
height, err := p.server.db.FetchBlockHeightBySha(hash)
|
2013-08-06 23:55:22 +02:00
|
|
|
if err == nil {
|
|
|
|
// Start with the next hash since we know this one.
|
2014-01-29 02:24:05 +01:00
|
|
|
startIdx = height + 1
|
2013-08-06 23:55:22 +02:00
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Don't attempt to fetch more than we can put into a single message.
|
2013-09-05 08:20:48 +02:00
|
|
|
autoContinue := false
|
2013-08-29 21:44:43 +02:00
|
|
|
if endIdx-startIdx > btcwire.MaxBlocksPerMsg {
|
|
|
|
endIdx = startIdx + btcwire.MaxBlocksPerMsg
|
2013-09-05 08:20:48 +02:00
|
|
|
autoContinue = true
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2013-09-05 08:20:48 +02:00
|
|
|
// Generate inventory message.
|
|
|
|
//
|
|
|
|
// The FetchBlockBySha call is limited to a maximum number of hashes
|
|
|
|
// per invocation. Since the maximum number of inventory per message
|
|
|
|
// might be larger, call it multiple times with the appropriate indices
|
|
|
|
// as needed.
|
|
|
|
invMsg := btcwire.NewMsgInv()
|
|
|
|
for start := startIdx; start < endIdx; {
|
|
|
|
// Fetch the inventory from the block database.
|
|
|
|
hashList, err := p.server.db.FetchHeightRange(start, endIdx)
|
|
|
|
if err != nil {
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Warnf("Block lookup failed: %v", err)
|
2013-09-05 08:20:48 +02:00
|
|
|
return
|
|
|
|
}
|
2013-08-06 23:55:22 +02:00
|
|
|
|
2013-09-05 08:20:48 +02:00
|
|
|
// The database did not return any further hashes. Break out of
|
|
|
|
// the loop now.
|
|
|
|
if len(hashList) == 0 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add block inventory to the message.
|
|
|
|
for _, hash := range hashList {
|
|
|
|
hashCopy := hash
|
2013-10-08 22:55:07 +02:00
|
|
|
iv := btcwire.NewInvVect(btcwire.InvTypeBlock, &hashCopy)
|
2013-09-05 08:20:48 +02:00
|
|
|
invMsg.AddInvVect(iv)
|
|
|
|
}
|
|
|
|
start += int64(len(hashList))
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2013-09-05 08:20:48 +02:00
|
|
|
// Send the inventory message if there is anything to send.
|
|
|
|
if len(invMsg.InvList) > 0 {
|
|
|
|
invListLen := len(invMsg.InvList)
|
|
|
|
if autoContinue && invListLen == btcwire.MaxBlocksPerMsg {
|
|
|
|
// Intentionally use a copy of the final hash so there
|
|
|
|
// is not a reference into the inventory slice which
|
|
|
|
// would prevent the entire slice from being eligible
|
|
|
|
// for GC as soon as it's sent.
|
|
|
|
continueHash := invMsg.InvList[invListLen-1].Hash
|
|
|
|
p.continueHash = &continueHash
|
|
|
|
}
|
2013-10-16 16:49:09 +02:00
|
|
|
p.QueueMessage(invMsg, nil)
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-10-16 16:49:09 +02:00
|
|
|
// handleGetHeadersMsg is invoked when a peer receives a getheaders bitcoin
|
2013-08-06 23:55:22 +02:00
|
|
|
// message.
|
|
|
|
func (p *peer) handleGetHeadersMsg(msg *btcwire.MsgGetHeaders) {
|
2013-09-05 01:17:42 +02:00
|
|
|
// Attempt to look up the height of the provided stop hash.
|
2013-08-06 23:55:22 +02:00
|
|
|
endIdx := btcdb.AllShas
|
2014-01-19 04:11:35 +01:00
|
|
|
height, err := p.server.db.FetchBlockHeightBySha(&msg.HashStop)
|
2013-09-05 01:17:42 +02:00
|
|
|
if err == nil {
|
2014-01-19 04:11:35 +01:00
|
|
|
endIdx = height + 1
|
2013-09-05 01:17:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// There are no block locators so a specific header is being requested
|
|
|
|
// as identified by the stop hash.
|
|
|
|
if len(msg.BlockLocatorHashes) == 0 {
|
|
|
|
// No blocks with the stop hash were found so there is nothing
|
|
|
|
// to do. Just return. This behavior mirrors the reference
|
|
|
|
// implementation.
|
|
|
|
if endIdx == btcdb.AllShas {
|
|
|
|
return
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
2013-09-05 01:17:42 +02:00
|
|
|
|
2014-01-19 04:11:35 +01:00
|
|
|
// Fetch and send the requested block header.
|
|
|
|
header, err := p.server.db.FetchBlockHeaderBySha(&msg.HashStop)
|
|
|
|
if err != nil {
|
|
|
|
peerLog.Warnf("Lookup of known block hash failed: %v",
|
|
|
|
err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-09-05 01:17:42 +02:00
|
|
|
headersMsg := btcwire.NewMsgHeaders()
|
2014-01-19 04:11:35 +01:00
|
|
|
headersMsg.AddBlockHeader(header)
|
2013-10-16 16:49:09 +02:00
|
|
|
p.QueueMessage(headersMsg, nil)
|
2013-09-05 01:17:42 +02:00
|
|
|
return
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2013-09-05 01:17:42 +02:00
|
|
|
// Find the most recent known block based on the block locator.
|
2013-09-05 08:20:48 +02:00
|
|
|
// Use the block after the genesis block if no other blocks in the
|
2013-09-05 03:24:58 +02:00
|
|
|
// provided locator are known. This does mean the client will start
|
|
|
|
// over with the genesis block if unknown block locators are provided.
|
2013-09-05 08:20:48 +02:00
|
|
|
// This mirrors the behavior in the reference implementation.
|
2013-09-05 03:24:58 +02:00
|
|
|
startIdx := int64(1)
|
2013-08-06 23:55:22 +02:00
|
|
|
for _, hash := range msg.BlockLocatorHashes {
|
2014-01-19 04:11:35 +01:00
|
|
|
height, err := p.server.db.FetchBlockHeightBySha(hash)
|
2013-08-06 23:55:22 +02:00
|
|
|
if err == nil {
|
|
|
|
// Start with the next hash since we know this one.
|
2014-01-19 04:11:35 +01:00
|
|
|
startIdx = height + 1
|
2013-08-06 23:55:22 +02:00
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-09-05 01:17:42 +02:00
|
|
|
// Don't attempt to fetch more than we can put into a single message.
|
|
|
|
if endIdx-startIdx > btcwire.MaxBlockHeadersPerMsg {
|
|
|
|
endIdx = startIdx + btcwire.MaxBlockHeadersPerMsg
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2013-09-05 01:17:42 +02:00
|
|
|
// Generate headers message and send it.
|
|
|
|
//
|
2014-01-19 04:11:35 +01:00
|
|
|
// The FetchHeightRange call is limited to a maximum number of hashes
|
2013-09-05 01:17:42 +02:00
|
|
|
// per invocation. Since the maximum number of headers per message
|
|
|
|
// might be larger, call it multiple times with the appropriate indices
|
|
|
|
// as needed.
|
2013-08-06 23:55:22 +02:00
|
|
|
headersMsg := btcwire.NewMsgHeaders()
|
2013-09-05 01:17:42 +02:00
|
|
|
for start := startIdx; start < endIdx; {
|
|
|
|
// Fetch the inventory from the block database.
|
|
|
|
hashList, err := p.server.db.FetchHeightRange(start, endIdx)
|
2013-08-06 23:55:22 +02:00
|
|
|
if err != nil {
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Warnf("Header lookup failed: %v", err)
|
2013-09-05 01:17:42 +02:00
|
|
|
return
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
2013-09-05 01:17:42 +02:00
|
|
|
|
|
|
|
// The database did not return any further hashes. Break out of
|
|
|
|
// the loop now.
|
|
|
|
if len(hashList) == 0 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add headers to the message.
|
|
|
|
for _, hash := range hashList {
|
2014-01-19 04:11:35 +01:00
|
|
|
header, err := p.server.db.FetchBlockHeaderBySha(&hash)
|
2013-09-05 01:17:42 +02:00
|
|
|
if err != nil {
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Warnf("Lookup of known block hash "+
|
2013-09-05 01:17:42 +02:00
|
|
|
"failed: %v", err)
|
|
|
|
continue
|
|
|
|
}
|
2014-01-19 04:11:35 +01:00
|
|
|
headersMsg.AddBlockHeader(header)
|
2013-09-05 01:17:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Start at the next block header after the latest one on the
|
|
|
|
// next loop iteration.
|
|
|
|
start += int64(len(hashList))
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
2013-10-16 16:49:09 +02:00
|
|
|
p.QueueMessage(headersMsg, nil)
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2014-07-09 03:44:21 +02:00
|
|
|
// handleFilterAddMsg 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 disonnected if a filter is not loaded when this
|
|
|
|
// message is received.
|
|
|
|
func (p *peer) handleFilterAddMsg(msg *btcwire.MsgFilterAdd) {
|
|
|
|
if !p.filter.IsLoaded() {
|
|
|
|
peerLog.Debugf("%s sent a filteradd request with no filter "+
|
|
|
|
"loaded -- disconnecting", p)
|
|
|
|
p.Disconnect()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
p.filter.Add(msg.Data)
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleFilterClearMsg 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 disonnected if a filter is not loaded when this message is
|
|
|
|
// received.
|
|
|
|
func (p *peer) handleFilterClearMsg(msg *btcwire.MsgFilterClear) {
|
|
|
|
if !p.filter.IsLoaded() {
|
|
|
|
peerLog.Debugf("%s sent a filterclear request with no "+
|
|
|
|
"filter loaded -- disconnecting", p)
|
|
|
|
p.Disconnect()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
p.filter.Unload()
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleFilterLoadMsg 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.
|
|
|
|
func (p *peer) handleFilterLoadMsg(msg *btcwire.MsgFilterLoad) {
|
|
|
|
// Transaction relay is no longer disabled once a filterload message is
|
|
|
|
// received regardless of its original state.
|
|
|
|
p.relayMtx.Lock()
|
|
|
|
p.disableRelayTx = false
|
|
|
|
p.relayMtx.Unlock()
|
|
|
|
|
2014-08-30 18:14:56 +02:00
|
|
|
p.filter.Reload(msg)
|
2014-07-09 03:44:21 +02:00
|
|
|
}
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
// handleGetAddrMsg 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 (p *peer) handleGetAddrMsg(msg *btcwire.MsgGetAddr) {
|
2014-05-28 22:19:38 +02:00
|
|
|
// Don't return any addresses when running on the simulation test
|
|
|
|
// network. This helps prevent the network from becoming another
|
|
|
|
// public test network since it will not be able to learn about other
|
|
|
|
// peers that have not specifically been provided.
|
|
|
|
if cfg.SimNet {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
// Get the current known addresses from the address manager.
|
|
|
|
addrCache := p.server.addrManager.AddressCache()
|
|
|
|
|
|
|
|
// Push the addresses.
|
|
|
|
err := p.pushAddrMsg(addrCache)
|
|
|
|
if err != nil {
|
2014-03-04 16:43:32 +01:00
|
|
|
p.logError("Can't push address message to %s: %v", p, err)
|
2013-08-09 22:47:06 +02:00
|
|
|
p.Disconnect()
|
2013-08-06 23:55:22 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// pushAddrMsg sends one, or more, addr message(s) to the connected peer using
|
|
|
|
// the provided addresses.
|
2013-09-17 18:24:15 +02:00
|
|
|
func (p *peer) pushAddrMsg(addresses []*btcwire.NetAddress) error {
|
2013-08-06 23:55:22 +02:00
|
|
|
// Nothing to send.
|
|
|
|
if len(addresses) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
numAdded := 0
|
|
|
|
msg := btcwire.NewMsgAddr()
|
|
|
|
for _, na := range addresses {
|
|
|
|
// Filter addresses the peer already knows about.
|
2014-07-06 08:04:24 +02:00
|
|
|
if _, ok := p.knownAddresses[addrmgr.NetAddressKey(na)]; ok {
|
2013-08-06 23:55:22 +02:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add the address to the message.
|
|
|
|
err := msg.AddAddress(na)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
numAdded++
|
|
|
|
|
|
|
|
// Split into multiple messages as needed.
|
|
|
|
if numAdded > 0 && numAdded%btcwire.MaxAddrPerMsg == 0 {
|
2013-10-16 16:49:09 +02:00
|
|
|
p.QueueMessage(msg, nil)
|
2013-12-10 16:05:26 +01:00
|
|
|
|
|
|
|
// NOTE: This needs to be a new address message and not
|
|
|
|
// simply call ClearAddresses since the message is a
|
|
|
|
// pointer and queueing it does not make a copy.
|
|
|
|
msg = btcwire.NewMsgAddr()
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send message with remaining addresses if needed.
|
|
|
|
if numAdded%btcwire.MaxAddrPerMsg != 0 {
|
2013-10-16 16:49:09 +02:00
|
|
|
p.QueueMessage(msg, nil)
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleAddrMsg is invoked when a peer receives an addr bitcoin message and
|
|
|
|
// is used to notify the server about advertised addresses.
|
|
|
|
func (p *peer) handleAddrMsg(msg *btcwire.MsgAddr) {
|
2014-05-28 22:19:38 +02:00
|
|
|
// Ignore addresses when running on the simulation test network. This
|
|
|
|
// helps prevent the network from becoming another public test network
|
|
|
|
// since it will not be able to learn about other peers that have not
|
|
|
|
// specifically been provided.
|
|
|
|
if cfg.SimNet {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
// Ignore old style addresses which don't include a timestamp.
|
2014-04-23 18:36:33 +02:00
|
|
|
if p.ProtocolVersion() < btcwire.NetAddressTimeVersion {
|
2013-08-06 23:55:22 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// A message that has no addresses is invalid.
|
|
|
|
if len(msg.AddrList) == 0 {
|
2013-11-21 19:03:56 +01:00
|
|
|
p.logError("Command [%s] from %s does not contain any addresses",
|
2014-03-04 16:43:32 +01:00
|
|
|
msg.Command(), p)
|
2013-08-09 22:47:06 +02:00
|
|
|
p.Disconnect()
|
2013-08-06 23:55:22 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, na := range msg.AddrList {
|
|
|
|
// Don't add more address if we're disconnecting.
|
2013-10-02 02:45:21 +02:00
|
|
|
if atomic.LoadInt32(&p.disconnect) != 0 {
|
2013-08-06 23:55:22 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set the timestamp to 5 days ago if it's more than 24 hours
|
|
|
|
// in the future so this address is one of the first to be
|
|
|
|
// removed when space is needed.
|
|
|
|
now := time.Now()
|
|
|
|
if na.Timestamp.After(now.Add(time.Minute * 10)) {
|
|
|
|
na.Timestamp = now.Add(-1 * time.Hour * 24 * 5)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add address to known addresses for this peer.
|
2014-07-06 08:04:24 +02:00
|
|
|
p.knownAddresses[addrmgr.NetAddressKey(na)] = struct{}{}
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Add addresses to server address manager. The address manager handles
|
|
|
|
// the details of things such as preventing duplicate addresses, max
|
|
|
|
// addresses, and last seen updates.
|
2013-09-17 18:24:15 +02:00
|
|
|
// XXX bitcoind gives a 2 hour time penalty here, do we want to do the
|
|
|
|
// same?
|
2013-08-01 19:00:14 +02:00
|
|
|
p.server.addrManager.AddAddresses(msg.AddrList, p.na)
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// handlePingMsg is invoked when a peer receives a ping bitcoin message. For
|
|
|
|
// recent clients (protocol version > BIP0031Version), it replies with a pong
|
|
|
|
// message. For older clients, it does nothing and anything other than failure
|
|
|
|
// is considered a successful ping.
|
|
|
|
func (p *peer) handlePingMsg(msg *btcwire.MsgPing) {
|
|
|
|
// Only Reply with pong is message comes from a new enough client.
|
2014-04-23 18:36:33 +02:00
|
|
|
if p.ProtocolVersion() > btcwire.BIP0031Version {
|
2013-08-06 23:55:22 +02:00
|
|
|
// Include nonce from ping so pong can be identified.
|
2013-10-16 16:49:09 +02:00
|
|
|
p.QueueMessage(btcwire.NewMsgPong(msg.Nonce), nil)
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-03-02 19:28:29 +01:00
|
|
|
// handlePongMsg is invoked when a peer received a pong bitcoin message.
|
2014-01-21 16:03:15 +01:00
|
|
|
// recent clients (protocol version > BIP0031Version), and if we had send a ping
|
|
|
|
// previosuly we update our ping time statistics. If the client is too old or
|
|
|
|
// we had not send a ping we ignore it.
|
|
|
|
func (p *peer) handlePongMsg(msg *btcwire.MsgPong) {
|
2014-04-23 18:36:33 +02:00
|
|
|
p.StatsMtx.Lock()
|
|
|
|
defer p.StatsMtx.Unlock()
|
2014-01-21 16:03:15 +01:00
|
|
|
|
|
|
|
// Arguably we could use a buffered channel here sending data
|
|
|
|
// in a fifo manner whenever we send a ping, or a list keeping track of
|
|
|
|
// the times of each ping. For now we just make a best effort and
|
|
|
|
// only record stats if it was for the last ping sent. Any preceding
|
|
|
|
// and overlapping pings will be ignored. It is unlikely to occur
|
|
|
|
// without large usage of the ping rpc call since we ping
|
|
|
|
// infrequently enough that if they overlap we would have timed out
|
|
|
|
// the peer.
|
|
|
|
if p.protocolVersion > btcwire.BIP0031Version &&
|
|
|
|
p.lastPingNonce != 0 && msg.Nonce == p.lastPingNonce {
|
|
|
|
p.lastPingMicros = time.Now().Sub(p.lastPingTime).Nanoseconds()
|
|
|
|
p.lastPingMicros /= 1000 // convert to usec.
|
|
|
|
p.lastPingNonce = 0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
// readMessage reads the next bitcoin message from the peer with logging.
|
2014-02-04 06:47:57 +01:00
|
|
|
func (p *peer) readMessage() (btcwire.Message, []byte, error) {
|
2014-04-23 18:36:33 +02:00
|
|
|
n, msg, buf, err := btcwire.ReadMessageN(p.conn, p.ProtocolVersion(),
|
|
|
|
p.btcnet)
|
|
|
|
p.StatsMtx.Lock()
|
2014-02-05 18:50:15 +01:00
|
|
|
p.bytesReceived += uint64(n)
|
2014-04-23 18:36:33 +02:00
|
|
|
p.StatsMtx.Unlock()
|
2014-02-13 16:53:25 +01:00
|
|
|
p.server.AddBytesReceived(uint64(n))
|
2013-08-06 23:55:22 +02:00
|
|
|
if err != nil {
|
2014-02-04 06:47:57 +01:00
|
|
|
return nil, nil, err
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Use closures to log expensive operations so they are only run when
|
|
|
|
// the logging level requires it.
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Debugf("%v", newLogClosure(func() string {
|
2013-10-10 21:13:54 +02:00
|
|
|
// Debug summary of message.
|
|
|
|
summary := messageSummary(msg)
|
|
|
|
if len(summary) > 0 {
|
|
|
|
summary = " (" + summary + ")"
|
|
|
|
}
|
2013-11-21 19:03:56 +01:00
|
|
|
return fmt.Sprintf("Received %v%s from %s",
|
2014-03-04 16:43:32 +01:00
|
|
|
msg.Command(), summary, p)
|
2013-10-10 21:13:54 +02:00
|
|
|
}))
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Tracef("%v", newLogClosure(func() string {
|
|
|
|
return spew.Sdump(msg)
|
2013-08-06 23:55:22 +02:00
|
|
|
}))
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Tracef("%v", newLogClosure(func() string {
|
|
|
|
return spew.Sdump(buf)
|
2013-08-06 23:55:22 +02:00
|
|
|
}))
|
|
|
|
|
2014-02-04 06:47:57 +01:00
|
|
|
return msg, buf, nil
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// writeMessage sends a bitcoin Message to the peer with logging.
|
2013-09-09 17:58:56 +02:00
|
|
|
func (p *peer) writeMessage(msg btcwire.Message) {
|
|
|
|
// Don't do anything if we're disconnecting.
|
2013-10-02 02:45:21 +02:00
|
|
|
if atomic.LoadInt32(&p.disconnect) != 0 {
|
2013-09-09 17:58:56 +02:00
|
|
|
return
|
|
|
|
}
|
2014-03-19 23:04:10 +01:00
|
|
|
if !p.VersionKnown() {
|
2013-10-14 23:02:59 +02:00
|
|
|
switch msg.(type) {
|
|
|
|
case *btcwire.MsgVersion:
|
|
|
|
// This is OK.
|
2014-07-09 05:01:13 +02:00
|
|
|
case *btcwire.MsgReject:
|
|
|
|
// This is OK.
|
2013-10-14 23:02:59 +02:00
|
|
|
default:
|
2014-07-09 05:01:13 +02:00
|
|
|
// Drop all messages other than version and reject if
|
|
|
|
// the handshake has not already been done.
|
2013-10-14 23:02:59 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2013-09-09 17:58:56 +02:00
|
|
|
|
2013-10-10 21:13:54 +02:00
|
|
|
// Use closures to log expensive operations so they are only run when
|
|
|
|
// the logging level requires it.
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Debugf("%v", newLogClosure(func() string {
|
2013-10-10 21:13:54 +02:00
|
|
|
// Debug summary of message.
|
|
|
|
summary := messageSummary(msg)
|
|
|
|
if len(summary) > 0 {
|
|
|
|
summary = " (" + summary + ")"
|
|
|
|
}
|
2013-11-21 19:03:56 +01:00
|
|
|
return fmt.Sprintf("Sending %v%s to %s", msg.Command(),
|
2014-03-04 16:43:32 +01:00
|
|
|
summary, p)
|
2013-10-10 21:13:54 +02:00
|
|
|
}))
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Tracef("%v", newLogClosure(func() string {
|
|
|
|
return spew.Sdump(msg)
|
2013-08-06 23:55:22 +02:00
|
|
|
}))
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Tracef("%v", newLogClosure(func() string {
|
2013-08-06 23:55:22 +02:00
|
|
|
var buf bytes.Buffer
|
2014-04-23 18:36:33 +02:00
|
|
|
err := btcwire.WriteMessage(&buf, msg, p.ProtocolVersion(),
|
|
|
|
p.btcnet)
|
2013-08-06 23:55:22 +02:00
|
|
|
if err != nil {
|
|
|
|
return err.Error()
|
|
|
|
}
|
2013-11-21 19:03:56 +01:00
|
|
|
return spew.Sdump(buf.Bytes())
|
2013-08-06 23:55:22 +02:00
|
|
|
}))
|
|
|
|
|
|
|
|
// Write the message to the peer.
|
2014-04-23 18:36:33 +02:00
|
|
|
n, err := btcwire.WriteMessageN(p.conn, msg, p.ProtocolVersion(),
|
|
|
|
p.btcnet)
|
|
|
|
p.StatsMtx.Lock()
|
2014-02-05 18:50:15 +01:00
|
|
|
p.bytesSent += uint64(n)
|
2014-04-23 18:36:33 +02:00
|
|
|
p.StatsMtx.Unlock()
|
2014-02-13 16:53:25 +01:00
|
|
|
p.server.AddBytesSent(uint64(n))
|
2013-08-06 23:55:22 +02:00
|
|
|
if err != nil {
|
2013-09-09 17:58:56 +02:00
|
|
|
p.Disconnect()
|
2014-03-04 16:43:32 +01:00
|
|
|
p.logError("Can't send message to %s: %v", p, err)
|
2013-09-09 17:58:56 +02:00
|
|
|
return
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// isAllowedByRegression returns whether or not the passed error is allowed by
|
|
|
|
// regression tests without disconnecting the peer. In particular, regression
|
|
|
|
// tests need to be allowed to send malformed messages without the peer being
|
|
|
|
// disconnected.
|
|
|
|
func (p *peer) isAllowedByRegression(err error) bool {
|
|
|
|
// Don't allow the error if it's not specifically a malformed message
|
|
|
|
// error.
|
|
|
|
if _, ok := err.(*btcwire.MessageError); !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Don't allow the error if it's not coming from localhost or the
|
|
|
|
// hostname can't be determined for some reason.
|
2013-10-03 00:06:29 +02:00
|
|
|
host, _, err := net.SplitHostPort(p.addr)
|
2013-08-06 23:55:22 +02:00
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
if host != "127.0.0.1" && host != "localhost" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Allowed if all checks passed.
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// inHandler handles all incoming messages for the peer. It must be run as a
|
|
|
|
// goroutine.
|
|
|
|
func (p *peer) inHandler() {
|
2014-01-18 08:39:31 +01:00
|
|
|
// Peers must complete the initial version negotiation within a shorter
|
|
|
|
// timeframe than a general idle timeout. The timer is then reset below
|
|
|
|
// to idleTimeoutMinutes for all future messages.
|
|
|
|
idleTimer := time.AfterFunc(negotiateTimeoutSeconds*time.Second, func() {
|
2014-03-19 23:04:10 +01:00
|
|
|
if p.VersionKnown() {
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Warnf("Peer %s no answer for %d minutes, "+
|
2013-10-17 22:58:57 +02:00
|
|
|
"disconnecting", p, idleTimeoutMinutes)
|
2013-10-16 16:49:09 +02:00
|
|
|
}
|
|
|
|
p.Disconnect()
|
|
|
|
})
|
2013-08-06 23:55:22 +02:00
|
|
|
out:
|
2013-10-02 02:45:21 +02:00
|
|
|
for atomic.LoadInt32(&p.disconnect) == 0 {
|
2013-08-06 23:55:22 +02:00
|
|
|
rmsg, buf, err := p.readMessage()
|
2013-10-16 16:49:09 +02:00
|
|
|
// Stop the timer now, if we go around again we will reset it.
|
|
|
|
idleTimer.Stop()
|
2013-08-06 23:55:22 +02:00
|
|
|
if err != nil {
|
|
|
|
// In order to allow regression tests with malformed
|
|
|
|
// messages, don't disconnect the peer when we're in
|
|
|
|
// regression test mode and the error is one of the
|
|
|
|
// allowed errors.
|
|
|
|
if cfg.RegressionTest && p.isAllowedByRegression(err) {
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Errorf("Allowed regression test "+
|
2014-03-04 16:43:32 +01:00
|
|
|
"error from %s: %v", p, err)
|
2013-10-16 16:49:09 +02:00
|
|
|
idleTimer.Reset(idleTimeoutMinutes * time.Minute)
|
2013-08-06 23:55:22 +02:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2014-07-09 05:01:13 +02:00
|
|
|
// Only log the error and possibly send reject message
|
|
|
|
// if we're not forcibly disconnecting.
|
2013-10-02 02:45:21 +02:00
|
|
|
if atomic.LoadInt32(&p.disconnect) == 0 {
|
2014-07-09 05:01:13 +02:00
|
|
|
errMsg := fmt.Sprintf("Can't read message "+
|
|
|
|
"from %s: %v", p, err)
|
|
|
|
p.logError(errMsg)
|
|
|
|
|
|
|
|
// Only send the reject message if it's not
|
|
|
|
// because the remote client disconnected.
|
|
|
|
if err != io.EOF {
|
|
|
|
// Push a reject message for the
|
|
|
|
// malformed message and wait for the
|
|
|
|
// message to be sent before
|
|
|
|
// disconnecting.
|
|
|
|
//
|
|
|
|
// NOTE: Ideally this would include the
|
|
|
|
// command in the header if at least
|
|
|
|
// that much of the message was valid,
|
|
|
|
// but that is not currently exposed by
|
|
|
|
// btcwire, so just used malformed for
|
|
|
|
// the command.
|
|
|
|
p.PushRejectMsg("malformed",
|
|
|
|
btcwire.RejectMalformed, errMsg,
|
|
|
|
nil, true)
|
|
|
|
}
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
break out
|
|
|
|
}
|
2014-04-23 18:36:33 +02:00
|
|
|
p.StatsMtx.Lock()
|
2013-10-18 19:50:43 +02:00
|
|
|
p.lastRecv = time.Now()
|
2014-04-23 18:36:33 +02:00
|
|
|
p.StatsMtx.Unlock()
|
2013-08-06 23:55:22 +02:00
|
|
|
|
|
|
|
// Ensure version message comes first.
|
2014-07-09 05:01:13 +02:00
|
|
|
if vmsg, ok := rmsg.(*btcwire.MsgVersion); !ok && !p.VersionKnown() {
|
|
|
|
errStr := "A version message must precede all others"
|
|
|
|
p.logError(errStr)
|
|
|
|
|
|
|
|
// Push a reject message and wait for the message to be
|
|
|
|
// sent before disconnecting.
|
|
|
|
p.PushRejectMsg(vmsg.Command(), btcwire.RejectMalformed,
|
|
|
|
errStr, nil, true)
|
2013-08-06 23:55:22 +02:00
|
|
|
break out
|
|
|
|
}
|
|
|
|
|
2013-08-16 20:35:38 +02:00
|
|
|
// Handle each supported message type.
|
2013-09-12 21:19:10 +02:00
|
|
|
markConnected := false
|
2013-08-06 23:55:22 +02:00
|
|
|
switch msg := rmsg.(type) {
|
|
|
|
case *btcwire.MsgVersion:
|
|
|
|
p.handleVersionMsg(msg)
|
2013-08-01 19:00:14 +02:00
|
|
|
markConnected = true
|
2013-08-06 23:55:22 +02:00
|
|
|
|
|
|
|
case *btcwire.MsgVerAck:
|
|
|
|
// Do nothing.
|
|
|
|
|
|
|
|
case *btcwire.MsgGetAddr:
|
|
|
|
p.handleGetAddrMsg(msg)
|
|
|
|
|
|
|
|
case *btcwire.MsgAddr:
|
|
|
|
p.handleAddrMsg(msg)
|
2013-08-01 19:00:14 +02:00
|
|
|
markConnected = true
|
2013-08-06 23:55:22 +02:00
|
|
|
|
|
|
|
case *btcwire.MsgPing:
|
|
|
|
p.handlePingMsg(msg)
|
2013-08-01 19:00:14 +02:00
|
|
|
markConnected = true
|
2013-08-06 23:55:22 +02:00
|
|
|
|
|
|
|
case *btcwire.MsgPong:
|
2014-01-21 16:03:15 +01:00
|
|
|
p.handlePongMsg(msg)
|
2013-08-06 23:55:22 +02:00
|
|
|
|
|
|
|
case *btcwire.MsgAlert:
|
|
|
|
p.server.BroadcastMessage(msg, p)
|
|
|
|
|
2013-10-08 07:04:51 +02:00
|
|
|
case *btcwire.MsgMemPool:
|
|
|
|
p.handleMemPoolMsg(msg)
|
|
|
|
|
2013-09-20 19:55:27 +02:00
|
|
|
case *btcwire.MsgTx:
|
|
|
|
p.handleTxMsg(msg)
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
case *btcwire.MsgBlock:
|
2013-09-09 17:58:56 +02:00
|
|
|
p.handleBlockMsg(msg, buf)
|
2013-08-06 23:55:22 +02:00
|
|
|
|
|
|
|
case *btcwire.MsgInv:
|
2013-08-29 21:44:43 +02:00
|
|
|
p.handleInvMsg(msg)
|
2013-08-01 19:00:14 +02:00
|
|
|
markConnected = true
|
2013-08-06 23:55:22 +02:00
|
|
|
|
2014-01-29 01:53:25 +01:00
|
|
|
case *btcwire.MsgHeaders:
|
|
|
|
p.handleHeadersMsg(msg)
|
|
|
|
|
2013-10-15 17:35:42 +02:00
|
|
|
case *btcwire.MsgNotFound:
|
|
|
|
// TODO(davec): Ignore this for now, but ultimately
|
|
|
|
// it should probably be used to detect when something
|
|
|
|
// we requested needs to be re-requested from another
|
|
|
|
// peer.
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
case *btcwire.MsgGetData:
|
|
|
|
p.handleGetDataMsg(msg)
|
2013-08-01 19:00:14 +02:00
|
|
|
markConnected = true
|
2013-08-06 23:55:22 +02:00
|
|
|
|
|
|
|
case *btcwire.MsgGetBlocks:
|
|
|
|
p.handleGetBlocksMsg(msg)
|
|
|
|
|
|
|
|
case *btcwire.MsgGetHeaders:
|
|
|
|
p.handleGetHeadersMsg(msg)
|
|
|
|
|
2014-07-09 03:44:21 +02:00
|
|
|
case *btcwire.MsgFilterAdd:
|
|
|
|
p.handleFilterAddMsg(msg)
|
|
|
|
|
|
|
|
case *btcwire.MsgFilterClear:
|
|
|
|
p.handleFilterClearMsg(msg)
|
|
|
|
|
|
|
|
case *btcwire.MsgFilterLoad:
|
|
|
|
p.handleFilterLoadMsg(msg)
|
|
|
|
|
2014-07-09 05:01:13 +02:00
|
|
|
case *btcwire.MsgReject:
|
|
|
|
// Nothing to do currently. Logging of the rejected
|
|
|
|
// message is handled already in readMessage.
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
default:
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Debugf("Received unhandled message of type %v: Fix Me",
|
2013-08-06 23:55:22 +02:00
|
|
|
rmsg.Command())
|
|
|
|
}
|
2013-09-12 21:19:10 +02:00
|
|
|
|
|
|
|
// Mark the address as currently connected and working as of
|
2013-09-20 19:55:27 +02:00
|
|
|
// now if one of the messages that trigger it was processed.
|
2013-10-02 02:45:21 +02:00
|
|
|
if markConnected && atomic.LoadInt32(&p.disconnect) == 0 {
|
2013-08-01 19:00:14 +02:00
|
|
|
if p.na == nil {
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Warnf("we're getting stuff before we " +
|
2013-08-01 19:00:14 +02:00
|
|
|
"got a version message. that's bad")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
p.server.addrManager.Connected(p.na)
|
|
|
|
}
|
2013-10-16 16:49:09 +02:00
|
|
|
// ok we got a message, reset the timer.
|
|
|
|
// timer just calls p.Disconnect() after logging.
|
|
|
|
idleTimer.Reset(idleTimeoutMinutes * time.Minute)
|
2014-07-22 22:58:24 +02:00
|
|
|
p.retryCount = 0
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2013-10-16 16:49:09 +02:00
|
|
|
idleTimer.Stop()
|
|
|
|
|
2013-12-24 17:32:20 +01:00
|
|
|
// Ensure connection is closed and notify the server that the peer is
|
|
|
|
// done.
|
2013-08-09 22:47:06 +02:00
|
|
|
p.Disconnect()
|
2013-08-06 23:55:22 +02:00
|
|
|
p.server.donePeers <- p
|
2013-12-24 17:32:20 +01:00
|
|
|
|
|
|
|
// Only tell block manager we are gone if we ever told it we existed.
|
2014-03-19 23:04:10 +01:00
|
|
|
if p.VersionKnown() {
|
2013-10-02 23:49:31 +02:00
|
|
|
p.server.blockManager.DonePeer(p)
|
|
|
|
}
|
2013-08-06 23:55:22 +02:00
|
|
|
|
2014-03-04 16:43:32 +01:00
|
|
|
peerLog.Tracef("Peer input handler done for %s", p)
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2013-12-20 14:06:37 +01:00
|
|
|
// queueHandler handles the queueing of outgoing data for the peer. This runs
|
|
|
|
// as a muxer for various sources of input so we can ensure that blockmanager
|
|
|
|
// and the server goroutine both will not block on us sending a message.
|
|
|
|
// We then pass the data on to outHandler to be actually written.
|
|
|
|
func (p *peer) queueHandler() {
|
|
|
|
pendingMsgs := list.New()
|
|
|
|
invSendQueue := list.New()
|
|
|
|
trickleTicker := time.NewTicker(time.Second * 10)
|
|
|
|
|
|
|
|
// We keep the waiting flag so that we know if we have a message queued
|
2013-12-24 17:32:20 +01:00
|
|
|
// to the outHandler or not. We could use the presence of a head of
|
|
|
|
// the list for this but then we have rather racy concerns about whether
|
|
|
|
// it has gotten it at cleanup time - and thus who sends on the
|
|
|
|
// message's done channel. To avoid such confusion we keep a different
|
2013-12-20 14:06:37 +01:00
|
|
|
// flag and pendingMsgs only contains messages that we have not yet
|
|
|
|
// passed to outHandler.
|
|
|
|
waiting := false
|
|
|
|
|
|
|
|
// To avoid duplication below.
|
|
|
|
queuePacket := func(msg outMsg, list *list.List, waiting bool) bool {
|
|
|
|
if !waiting {
|
|
|
|
peerLog.Tracef("%s: sending to outHandler", p)
|
|
|
|
p.sendQueue <- msg
|
|
|
|
peerLog.Tracef("%s: sent to outHandler", p)
|
|
|
|
} else {
|
|
|
|
list.PushBack(msg)
|
|
|
|
}
|
|
|
|
// we are always waiting now.
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
out:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case msg := <-p.outputQueue:
|
|
|
|
waiting = queuePacket(msg, pendingMsgs, waiting)
|
|
|
|
|
2013-12-24 17:32:20 +01:00
|
|
|
// This channel is notified when a message has been sent across
|
|
|
|
// the network socket.
|
2013-12-20 14:06:37 +01:00
|
|
|
case <-p.sendDoneQueue:
|
|
|
|
peerLog.Tracef("%s: acked by outhandler", p)
|
2013-12-24 17:32:20 +01:00
|
|
|
|
|
|
|
// No longer waiting if there are no more messages
|
|
|
|
// in the pending messages queue.
|
2013-12-20 14:06:37 +01:00
|
|
|
next := pendingMsgs.Front()
|
2013-12-24 17:32:20 +01:00
|
|
|
if next == nil {
|
2013-12-20 14:06:37 +01:00
|
|
|
waiting = false
|
2013-12-24 17:32:20 +01:00
|
|
|
continue
|
2013-12-20 14:06:37 +01:00
|
|
|
}
|
|
|
|
|
2013-12-24 17:32:20 +01:00
|
|
|
// Notify the outHandler about the next item to
|
|
|
|
// asynchronously send.
|
|
|
|
val := pendingMsgs.Remove(next)
|
|
|
|
peerLog.Tracef("%s: sending to outHandler", p)
|
|
|
|
p.sendQueue <- val.(outMsg)
|
|
|
|
peerLog.Tracef("%s: sent to outHandler", p)
|
|
|
|
|
2013-12-20 14:06:37 +01:00
|
|
|
case iv := <-p.outputInvChan:
|
2013-12-24 17:32:20 +01:00
|
|
|
// No handshake? They'll find out soon enough.
|
2014-03-19 23:04:10 +01:00
|
|
|
if p.VersionKnown() {
|
2013-12-20 14:06:37 +01:00
|
|
|
invSendQueue.PushBack(iv)
|
|
|
|
}
|
|
|
|
|
|
|
|
case <-trickleTicker.C:
|
|
|
|
// Don't send anything if we're disconnecting or there
|
|
|
|
// is no queued inventory.
|
|
|
|
// version is known if send queue has any entries.
|
|
|
|
if atomic.LoadInt32(&p.disconnect) != 0 ||
|
|
|
|
invSendQueue.Len() == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create and send as many inv messages as needed to
|
|
|
|
// drain the inventory send queue.
|
|
|
|
invMsg := btcwire.NewMsgInv()
|
|
|
|
for e := invSendQueue.Front(); e != nil; e = invSendQueue.Front() {
|
|
|
|
iv := invSendQueue.Remove(e).(*btcwire.InvVect)
|
|
|
|
|
|
|
|
// Don't send inventory that became known after
|
|
|
|
// the initial check.
|
|
|
|
if p.isKnownInventory(iv) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
invMsg.AddInvVect(iv)
|
|
|
|
if len(invMsg.InvList) >= maxInvTrickleSize {
|
|
|
|
waiting = queuePacket(
|
|
|
|
outMsg{msg: invMsg},
|
|
|
|
pendingMsgs, waiting)
|
|
|
|
invMsg = btcwire.NewMsgInv()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add the inventory that is being relayed to
|
|
|
|
// the known inventory for the peer.
|
2013-12-24 17:32:20 +01:00
|
|
|
p.AddKnownInventory(iv)
|
2013-12-20 14:06:37 +01:00
|
|
|
}
|
|
|
|
if len(invMsg.InvList) > 0 {
|
|
|
|
waiting = queuePacket(outMsg{msg: invMsg},
|
|
|
|
pendingMsgs, waiting)
|
|
|
|
}
|
|
|
|
|
|
|
|
case <-p.quit:
|
|
|
|
break out
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Drain any wait channels before we go away so we don't leave something
|
|
|
|
// waiting for us.
|
|
|
|
for e := pendingMsgs.Front(); e != nil; e = pendingMsgs.Front() {
|
|
|
|
val := pendingMsgs.Remove(e)
|
|
|
|
msg := val.(outMsg)
|
|
|
|
if msg.doneChan != nil {
|
2014-07-11 05:40:53 +02:00
|
|
|
msg.doneChan <- struct{}{}
|
2013-12-20 14:06:37 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
cleanup:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case msg := <-p.outputQueue:
|
|
|
|
if msg.doneChan != nil {
|
2014-07-11 05:40:53 +02:00
|
|
|
msg.doneChan <- struct{}{}
|
2013-12-20 14:06:37 +01:00
|
|
|
}
|
|
|
|
case <-p.outputInvChan:
|
|
|
|
// Just drain channel
|
|
|
|
// sendDoneQueue is buffered so doesn't need draining.
|
|
|
|
default:
|
|
|
|
break cleanup
|
|
|
|
}
|
|
|
|
}
|
|
|
|
p.queueWg.Done()
|
2014-03-04 16:43:32 +01:00
|
|
|
peerLog.Tracef("Peer queue handler done for %s", p)
|
2013-12-20 14:06:37 +01:00
|
|
|
}
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
// outHandler handles all outgoing messages for the peer. It must be run as a
|
|
|
|
// goroutine. It uses a buffered channel to serialize output messages while
|
|
|
|
// allowing the sender to continue running asynchronously.
|
|
|
|
func (p *peer) outHandler() {
|
2013-10-16 16:49:09 +02:00
|
|
|
pingTimer := time.AfterFunc(pingTimeoutMinutes*time.Minute, func() {
|
|
|
|
nonce, err := btcwire.RandomUint64()
|
|
|
|
if err != nil {
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Errorf("Not sending ping on timeout to %s: %v",
|
2013-10-16 16:49:09 +02:00
|
|
|
p, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
p.QueueMessage(btcwire.NewMsgPing(nonce), nil)
|
|
|
|
})
|
2013-08-06 23:55:22 +02:00
|
|
|
out:
|
|
|
|
for {
|
|
|
|
select {
|
2013-12-20 14:06:37 +01:00
|
|
|
case msg := <-p.sendQueue:
|
2013-10-16 16:49:09 +02:00
|
|
|
// If the message is one we should get a reply for
|
|
|
|
// then reset the timer, we only want to send pings
|
2014-03-02 19:28:29 +01:00
|
|
|
// when otherwise we would not receive a reply from
|
2013-10-16 16:49:09 +02:00
|
|
|
// the peer. We specifically do not count block or inv
|
|
|
|
// messages here since they are not sure of a reply if
|
|
|
|
// the inv is of no interest explicitly solicited invs
|
|
|
|
// should elicit a reply but we don't track them
|
|
|
|
// specially.
|
2014-03-02 19:28:29 +01:00
|
|
|
peerLog.Tracef("%s: received from queuehandler", p)
|
2013-10-16 16:49:09 +02:00
|
|
|
reset := true
|
2014-01-21 16:03:15 +01:00
|
|
|
switch m := msg.msg.(type) {
|
2013-10-16 16:49:09 +02:00
|
|
|
case *btcwire.MsgVersion:
|
|
|
|
// should get an ack
|
|
|
|
case *btcwire.MsgGetAddr:
|
|
|
|
// should get addresses
|
|
|
|
case *btcwire.MsgPing:
|
|
|
|
// expects pong
|
2014-01-21 16:03:15 +01:00
|
|
|
// Also set up statistics.
|
2014-04-23 18:36:33 +02:00
|
|
|
p.StatsMtx.Lock()
|
2014-01-21 16:03:15 +01:00
|
|
|
if p.protocolVersion > btcwire.BIP0031Version {
|
|
|
|
p.lastPingNonce = m.Nonce
|
|
|
|
p.lastPingTime = time.Now()
|
|
|
|
}
|
2014-04-23 18:36:33 +02:00
|
|
|
p.StatsMtx.Unlock()
|
2013-10-16 16:49:09 +02:00
|
|
|
case *btcwire.MsgMemPool:
|
|
|
|
// Should return an inv.
|
|
|
|
case *btcwire.MsgGetData:
|
|
|
|
// Should get us block, tx, or not found.
|
|
|
|
case *btcwire.MsgGetHeaders:
|
|
|
|
// Should get us headers back.
|
|
|
|
|
|
|
|
default:
|
|
|
|
// Not one of the above, no sure reply.
|
|
|
|
// We want to ping if nothing else
|
|
|
|
// interesting happens.
|
|
|
|
reset = false
|
|
|
|
}
|
|
|
|
if reset {
|
|
|
|
pingTimer.Reset(pingTimeoutMinutes * time.Minute)
|
|
|
|
}
|
2013-10-11 19:30:14 +02:00
|
|
|
p.writeMessage(msg.msg)
|
2014-04-23 18:36:33 +02:00
|
|
|
p.StatsMtx.Lock()
|
2013-10-18 19:50:43 +02:00
|
|
|
p.lastSend = time.Now()
|
2014-04-23 18:36:33 +02:00
|
|
|
p.StatsMtx.Unlock()
|
2013-10-11 19:30:14 +02:00
|
|
|
if msg.doneChan != nil {
|
2014-07-11 05:40:53 +02:00
|
|
|
msg.doneChan <- struct{}{}
|
2013-10-11 19:30:14 +02:00
|
|
|
}
|
2013-12-20 14:06:37 +01:00
|
|
|
peerLog.Tracef("%s: acking queuehandler", p)
|
2014-07-02 17:31:10 +02:00
|
|
|
p.sendDoneQueue <- struct{}{}
|
2013-12-20 14:06:37 +01:00
|
|
|
peerLog.Tracef("%s: acked queuehandler", p)
|
2013-08-06 23:55:22 +02:00
|
|
|
|
|
|
|
case <-p.quit:
|
|
|
|
break out
|
|
|
|
}
|
|
|
|
}
|
2013-10-11 19:30:14 +02:00
|
|
|
|
2013-10-16 16:49:09 +02:00
|
|
|
pingTimer.Stop()
|
|
|
|
|
2013-12-20 14:06:37 +01:00
|
|
|
p.queueWg.Wait()
|
|
|
|
|
2013-10-11 19:30:14 +02:00
|
|
|
// Drain any wait channels before we go away so we don't leave something
|
2013-12-20 14:06:37 +01:00
|
|
|
// waiting for us. We have waited on queueWg and thus we can be sure
|
|
|
|
// that we will not miss anything sent on sendQueue.
|
2013-10-11 19:30:14 +02:00
|
|
|
cleanup:
|
|
|
|
for {
|
|
|
|
select {
|
2013-12-20 14:06:37 +01:00
|
|
|
case msg := <-p.sendQueue:
|
2013-10-11 19:30:14 +02:00
|
|
|
if msg.doneChan != nil {
|
2014-07-11 05:40:53 +02:00
|
|
|
msg.doneChan <- struct{}{}
|
2013-10-11 19:30:14 +02:00
|
|
|
}
|
2013-12-20 14:06:37 +01:00
|
|
|
// no need to send on sendDoneQueue since queueHandler
|
|
|
|
// has been waited on and already exited.
|
2013-10-11 19:30:14 +02:00
|
|
|
default:
|
|
|
|
break cleanup
|
|
|
|
}
|
|
|
|
}
|
2014-03-04 16:43:32 +01:00
|
|
|
peerLog.Tracef("Peer output handler done for %s", p)
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// QueueMessage adds the passed bitcoin message to the peer send queue. It
|
|
|
|
// uses a buffered channel to communicate with the output handler goroutine so
|
|
|
|
// it is automatically rate limited and safe for concurrent access.
|
2014-07-11 05:40:53 +02:00
|
|
|
func (p *peer) QueueMessage(msg btcwire.Message, doneChan chan struct{}) {
|
2013-12-20 14:06:37 +01:00
|
|
|
// Avoid risk of deadlock if goroutine already exited. The goroutine
|
|
|
|
// we will be sending to hangs around until it knows for a fact that
|
|
|
|
// it is marked as disconnected. *then* it drains the channels.
|
|
|
|
if !p.Connected() {
|
|
|
|
// avoid deadlock...
|
|
|
|
if doneChan != nil {
|
|
|
|
go func() {
|
2014-07-11 05:40:53 +02:00
|
|
|
doneChan <- struct{}{}
|
2013-12-20 14:06:37 +01:00
|
|
|
}()
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2013-10-16 16:49:09 +02:00
|
|
|
p.outputQueue <- outMsg{msg: msg, doneChan: doneChan}
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2013-09-09 17:58:56 +02:00
|
|
|
// 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. It is safe for
|
|
|
|
// concurrent access.
|
|
|
|
func (p *peer) QueueInventory(invVect *btcwire.InvVect) {
|
|
|
|
// Don't add the inventory to the send queue if the peer is
|
|
|
|
// already known to have it.
|
|
|
|
if p.isKnownInventory(invVect) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-12-20 14:06:37 +01:00
|
|
|
// Avoid risk of deadlock if goroutine already exited. The goroutine
|
|
|
|
// we will be sending to hangs around until it knows for a fact that
|
|
|
|
// it is marked as disconnected. *then* it drains the channels.
|
|
|
|
if !p.Connected() {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-09-09 17:58:56 +02:00
|
|
|
p.outputInvChan <- invVect
|
|
|
|
}
|
|
|
|
|
2013-10-04 17:44:36 +02:00
|
|
|
// Connected returns whether or not the peer is currently connected.
|
|
|
|
func (p *peer) Connected() bool {
|
|
|
|
return atomic.LoadInt32(&p.connected) != 0 &&
|
|
|
|
atomic.LoadInt32(&p.disconnect) == 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// Disconnect disconnects the peer by closing the connection. It also sets
|
|
|
|
// a flag so the impending shutdown can be detected.
|
|
|
|
func (p *peer) Disconnect() {
|
|
|
|
// did we win the race?
|
|
|
|
if atomic.AddInt32(&p.disconnect, 1) != 1 {
|
|
|
|
return
|
|
|
|
}
|
2014-03-04 16:43:32 +01:00
|
|
|
peerLog.Tracef("disconnecting %s", p)
|
2013-10-04 17:44:36 +02:00
|
|
|
close(p.quit)
|
|
|
|
if atomic.LoadInt32(&p.connected) != 0 {
|
|
|
|
p.conn.Close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
// Start begins processing input and output messages. It also sends the initial
|
|
|
|
// version message for outbound connections to start the negotiation process.
|
|
|
|
func (p *peer) Start() error {
|
|
|
|
// Already started?
|
2013-10-03 01:33:42 +02:00
|
|
|
if atomic.AddInt32(&p.started, 1) != 1 {
|
2013-08-06 23:55:22 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-03-04 16:43:32 +01:00
|
|
|
peerLog.Tracef("Starting peer %s", p)
|
2013-08-06 23:55:22 +02:00
|
|
|
|
|
|
|
// Send an initial version message if this is an outbound connection.
|
|
|
|
if !p.inbound {
|
|
|
|
err := p.pushVersionMsg()
|
|
|
|
if err != nil {
|
2014-02-14 19:44:53 +01:00
|
|
|
p.logError("Can't send outbound version message %v", err)
|
2013-10-03 00:06:29 +02:00
|
|
|
p.Disconnect()
|
2013-08-06 23:55:22 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start processing input and output.
|
|
|
|
go p.inHandler()
|
2013-12-20 14:06:37 +01:00
|
|
|
// queueWg is kept so that outHandler knows when the queue has exited so
|
|
|
|
// it can drain correctly.
|
|
|
|
p.queueWg.Add(1)
|
|
|
|
go p.queueHandler()
|
2013-08-06 23:55:22 +02:00
|
|
|
go p.outHandler()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2013-10-06 00:40:54 +02:00
|
|
|
// Shutdown gracefully shuts down the peer by disconnecting it.
|
2013-08-09 22:47:06 +02:00
|
|
|
func (p *peer) Shutdown() {
|
2014-03-04 16:43:32 +01:00
|
|
|
peerLog.Tracef("Shutdown peer %s", p)
|
2013-08-09 22:47:06 +02:00
|
|
|
p.Disconnect()
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2013-09-12 21:19:10 +02:00
|
|
|
// newPeerBase returns a new base bitcoin peer for the provided server and
|
|
|
|
// inbound flag. This is used by the newInboundPeer and newOutboundPeer
|
|
|
|
// functions to perform base setup needed by both types of peers.
|
|
|
|
func newPeerBase(s *server, inbound bool) *peer {
|
2013-08-01 19:00:14 +02:00
|
|
|
p := peer{
|
|
|
|
server: s,
|
2014-03-28 20:50:02 +01:00
|
|
|
protocolVersion: maxProtocolVersion,
|
2014-05-28 00:44:55 +02:00
|
|
|
btcnet: s.netParams.Net,
|
2013-08-01 19:00:14 +02:00
|
|
|
services: btcwire.SFNodeNetwork,
|
2013-09-12 21:19:10 +02:00
|
|
|
inbound: inbound,
|
2014-07-02 16:45:17 +02:00
|
|
|
knownAddresses: make(map[string]struct{}),
|
2013-09-09 17:58:56 +02:00
|
|
|
knownInventory: NewMruInventoryMap(maxKnownInventory),
|
2014-07-02 16:45:17 +02:00
|
|
|
requestedTxns: make(map[btcwire.ShaHash]struct{}),
|
|
|
|
requestedBlocks: make(map[btcwire.ShaHash]struct{}),
|
2013-08-29 21:44:43 +02:00
|
|
|
requestQueue: list.New(),
|
2014-07-09 03:44:21 +02:00
|
|
|
filter: bloom.LoadFilter(nil),
|
2013-10-11 19:30:14 +02:00
|
|
|
outputQueue: make(chan outMsg, outputBufferSize),
|
2014-07-02 17:31:10 +02:00
|
|
|
sendQueue: make(chan outMsg, 1), // nonblocking sync
|
|
|
|
sendDoneQueue: make(chan struct{}, 1), // nonblocking sync
|
2013-09-09 17:58:56 +02:00
|
|
|
outputInvChan: make(chan *btcwire.InvVect, outputBufferSize),
|
2014-07-11 05:28:22 +02:00
|
|
|
txProcessed: make(chan struct{}, 1),
|
|
|
|
blockProcessed: make(chan struct{}, 1),
|
2014-07-02 17:31:10 +02:00
|
|
|
quit: make(chan struct{}),
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
2013-09-12 21:19:10 +02:00
|
|
|
return &p
|
|
|
|
}
|
|
|
|
|
2014-06-12 03:13:44 +02:00
|
|
|
// newInboundPeer returns a new inbound bitcoin peer for the provided server and
|
2013-09-12 21:19:10 +02:00
|
|
|
// connection. Use Start to begin processing incoming and outgoing messages.
|
|
|
|
func newInboundPeer(s *server, conn net.Conn) *peer {
|
|
|
|
p := newPeerBase(s, true)
|
|
|
|
p.conn = conn
|
|
|
|
p.addr = conn.RemoteAddr().String()
|
2013-10-18 19:48:51 +02:00
|
|
|
p.timeConnected = time.Now()
|
2013-10-03 00:06:29 +02:00
|
|
|
atomic.AddInt32(&p.connected, 1)
|
2013-09-12 21:19:10 +02:00
|
|
|
return p
|
|
|
|
}
|
|
|
|
|
|
|
|
// newOutbountPeer returns a new outbound bitcoin peer for the provided server and
|
|
|
|
// address and connects to it asynchronously. If the connection is successful
|
|
|
|
// then the peer will also be started.
|
2014-07-22 22:58:24 +02:00
|
|
|
func newOutboundPeer(s *server, addr string, persistent bool, retryCount int64) *peer {
|
2013-09-12 21:19:10 +02:00
|
|
|
p := newPeerBase(s, false)
|
|
|
|
p.addr = addr
|
|
|
|
p.persistent = persistent
|
2014-07-22 22:58:24 +02:00
|
|
|
p.retryCount = retryCount
|
2013-09-12 21:19:10 +02:00
|
|
|
|
|
|
|
// Setup p.na with a temporary address that we are connecting to with
|
|
|
|
// faked up service flags. We will replace this with the real one after
|
|
|
|
// version negotiation is successful. The only failure case here would
|
2013-08-01 19:00:14 +02:00
|
|
|
// be if the string was incomplete for connection so can't be split
|
2013-09-12 21:19:10 +02:00
|
|
|
// into address and port, and thus this would be invalid anyway. In
|
|
|
|
// which case we return nil to be handled by the caller. This must be
|
|
|
|
// done before we fork off the goroutine because as soon as this
|
|
|
|
// function returns the peer must have a valid netaddress.
|
2013-11-28 01:11:16 +01:00
|
|
|
host, portStr, err := net.SplitHostPort(addr)
|
2013-08-01 19:00:14 +02:00
|
|
|
if err != nil {
|
2013-10-02 23:49:31 +02:00
|
|
|
p.logError("Tried to create a new outbound peer with invalid "+
|
2013-08-01 19:00:14 +02:00
|
|
|
"address %s: %v", addr, err)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
port, err := strconv.ParseUint(portStr, 10, 16)
|
|
|
|
if err != nil {
|
2013-10-02 23:49:31 +02:00
|
|
|
p.logError("Tried to create a new outbound peer with invalid "+
|
2013-08-01 19:00:14 +02:00
|
|
|
"port %s: %v", portStr, err)
|
|
|
|
return nil
|
|
|
|
}
|
2013-11-28 01:11:16 +01:00
|
|
|
|
2014-07-06 08:04:24 +02:00
|
|
|
p.na, err = s.addrManager.HostToNetAddress(host, uint16(port), 0)
|
2013-11-28 01:11:16 +01:00
|
|
|
if err != nil {
|
|
|
|
p.logError("Can not turn host %s into netaddress: %v",
|
|
|
|
host, err)
|
|
|
|
return nil
|
|
|
|
}
|
2013-08-01 19:00:14 +02:00
|
|
|
|
|
|
|
go func() {
|
2014-07-22 22:58:24 +02:00
|
|
|
if atomic.LoadInt32(&p.disconnect) != 0 {
|
2013-08-01 19:00:14 +02:00
|
|
|
return
|
|
|
|
}
|
2014-07-22 22:58:24 +02:00
|
|
|
if p.retryCount > 0 {
|
|
|
|
scaledInterval := connectionRetryInterval.Nanoseconds() * p.retryCount / 2
|
|
|
|
scaledDuration := time.Duration(scaledInterval)
|
|
|
|
srvrLog.Debugf("Retrying connection to %s in %s", addr, scaledDuration)
|
|
|
|
time.Sleep(scaledDuration)
|
|
|
|
}
|
|
|
|
srvrLog.Debugf("Attempting to connect to %s", addr)
|
|
|
|
conn, err := btcdDial("tcp", addr)
|
|
|
|
if err != nil {
|
|
|
|
srvrLog.Debugf("Failed to connect to %s: %v", addr, err)
|
|
|
|
p.server.donePeers <- p
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// We may have slept and the server may have scheduled a shutdown. In that
|
|
|
|
// case ditch the peer immediately.
|
|
|
|
if atomic.LoadInt32(&p.disconnect) == 0 {
|
|
|
|
p.timeConnected = time.Now()
|
|
|
|
p.server.addrManager.Attempt(p.na)
|
|
|
|
|
|
|
|
// Connection was successful so log it and start peer.
|
|
|
|
srvrLog.Debugf("Connected to %s", conn.RemoteAddr())
|
|
|
|
p.conn = conn
|
|
|
|
atomic.AddInt32(&p.connected, 1)
|
|
|
|
p.Start()
|
|
|
|
}
|
2013-08-01 19:00:14 +02:00
|
|
|
}()
|
2013-09-12 21:19:10 +02:00
|
|
|
return p
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
2013-10-02 23:49:31 +02:00
|
|
|
|
|
|
|
// logError makes sure that we only log errors loudly on user peers.
|
2013-10-03 02:44:07 +02:00
|
|
|
func (p *peer) logError(fmt string, args ...interface{}) {
|
2013-10-02 23:49:31 +02:00
|
|
|
if p.persistent {
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Errorf(fmt, args...)
|
2013-10-02 23:49:31 +02:00
|
|
|
} else {
|
2013-11-21 19:03:56 +01:00
|
|
|
peerLog.Debugf(fmt, args...)
|
2013-10-02 23:49:31 +02:00
|
|
|
}
|
|
|
|
}
|