peer.go raw

   1  // Package authored is btcd's peer handshake sequence, copied from
   2  // github.com/btcsuite/btcd/peer at commit 2c467023f0cb, with btcd's listener
   3  // interface removed.
   4  //
   5  // The messages, the transport's version-2 handshake and the encodings are
   6  // btcd's throughout. What was taken out is the peer's message-dispatch and
   7  // message-queue machinery, which this project does not use: it is not a
   8  // bitcoin node and has nothing to do with blocks or transactions across the
   9  // interface. What is left is the order in which the four handshake messages
  10  // go out and what may arrive between them, including the sendaddrv2
  11  // exchange that bitcoind requires to happen before verack.
  12  package authored
  13  
  14  import (
  15  	"bytes"
  16  	"errors"
  17  	"fmt"
  18  	"io"
  19  	"net"
  20  	"time"
  21  
  22  	"github.com/btcsuite/btcd/v2transport"
  23  	"github.com/btcsuite/btcd/wire/v2"
  24  
  25  	"git.smesh.lol/btcd-lite/internal/wirefmt"
  26  )
  27  
  28  // Conn is one connection in the middle of a handshake.
  29  type Conn struct {
  30  	RW   io.ReadWriter
  31  	Net  wire.BitcoinNet
  32  	Pver uint32
  33  	V2   *v2transport.Peer
  34  
  35  	UserAgent string
  36  	Services  wire.ServiceFlag
  37  	LastBlock int32
  38  	Nonce     uint64
  39  	Relay     bool
  40  
  41  	// RemoteAgent is the user agent the peer sent, recorded as btcd records
  42  	// it for a listener.
  43  	RemoteAgent string
  44  	// RemoteServices and RemoteLastBlock are what the peer's version message
  45  	// claimed: what it says it serves and how far its chain was. They are
  46  	// diagnosis, not trust.
  47  	RemoteServices  wire.ServiceFlag
  48  	RemoteLastBlock int32
  49  }
  50  
  51  // UpgradeV2 runs btcd's initiating side of the BIP324 handshake. It returns
  52  // false and no error when the peer does not speak v2, which is btcd's cue to
  53  // carry on in v1 on the same connection.
  54  func (c *Conn) UpgradeV2(garbageLen int) (bool, error) {
  55  	if err := c.V2.InitiateV2Handshake(garbageLen); err != nil {
  56  		return false, err
  57  	}
  58  	err := c.V2.CompleteHandshake(true, nil, v2transport.BitcoinNet(c.Net))
  59  	switch {
  60  	case errors.Is(err, v2transport.ErrShouldDowngradeToV1),
  61  		errors.Is(err, v2transport.ErrUseV1Protocol):
  62  		return false, nil
  63  	case err != nil:
  64  		return false, err
  65  	}
  66  	return true, nil
  67  }
  68  
  69  // write sends with btcd's encoder for the transport that is live, and speaks
  70  // the protocol version the peer gave, as btcd does after it has read version.
  71  func (c *Conn) write(msg wire.Message) error {
  72  	if c.V2 != nil {
  73  		// btcd writes with wire.LatestEncoding: a transaction or block on the
  74  		// wire carries its witnesses, and a base encoding decode of a block
  75  		// leaves the witnesses in the stream as extra bytes.
  76  		var buf bytes.Buffer
  77  		if _, err := wire.WriteV2MessageN(&buf, msg, c.Pver, wire.LatestEncoding); err != nil {
  78  			return err
  79  		}
  80  		_, _, err := c.V2.V2EncPacket(buf.Bytes(), nil, false)
  81  		return err
  82  	}
  83  	_, err := wirefmt.Write(c.RW, msg, c.Pver, c.Net)
  84  	return err
  85  }
  86  
  87  func (c *Conn) read() (wire.Message, []byte, error) {
  88  	if c.V2 != nil {
  89  		plaintext, err := c.V2.V2ReceivePacket(nil)
  90  		if err != nil {
  91  			return nil, nil, err
  92  		}
  93  		return wire.ReadV2MessageN(plaintext, c.Pver, wire.LatestEncoding)
  94  	}
  95  	return wirefmt.Read(c.RW, c.Pver, c.Net)
  96  }
  97  
  98  // writeLocalVersionMsg is btcd's.
  99  func (c *Conn) writeLocalVersionMsg() error {
 100  	ourNA := wire.NewNetAddressIPPort(net.IPv4zero, 0, c.Services)
 101  	theirNA := wire.NewNetAddressIPPort(net.IPv4zero, 0, 0)
 102  	msg := wire.NewMsgVersion(ourNA, theirNA, c.Nonce, c.LastBlock)
 103  	msg.AddUserAgent(c.UserAgent, "")
 104  	msg.Services = c.Services
 105  	msg.ProtocolVersion = int32(wire.ProtocolVersion)
 106  	msg.DisableRelayTx = !c.Relay
 107  	return c.write(msg)
 108  }
 109  
 110  // writeSendAddrV2Msg is btcd's: the message is the sender's declaration that
 111  // it understands addrV2 addresses in a preferred format, and bitcoind
 112  // disconnects a peer that sends it after verack.
 113  func (c *Conn) writeSendAddrV2Msg(pver uint32) error {
 114  	if pver < wire.AddrV2Version {
 115  		return nil
 116  	}
 117  	return c.write(wire.NewMsgSendAddrV2())
 118  }
 119  
 120  // readRemoteVersionMsg is btcd's: the first message has to be version, and it
 121  // fixes the protocol version for everything after it.
 122  func (c *Conn) readRemoteVersionMsg() error {
 123  	msg, _, err := c.read()
 124  	if err != nil {
 125  		return err
 126  	}
 127  	remote, ok := msg.(*wire.MsgVersion)
 128  	if !ok {
 129  		return fmt.Errorf("authored: first message is %q, not version", msg.Command())
 130  	}
 131  	if remote.ProtocolVersion > 0 && uint32(remote.ProtocolVersion) < c.Pver {
 132  		c.Pver = uint32(remote.ProtocolVersion)
 133  	}
 134  	c.RemoteAgent = remote.UserAgent
 135  	c.RemoteServices = remote.Services
 136  	c.RemoteLastBlock = remote.LastBlock
 137  	return nil
 138  }
 139  
 140  // waitToFinishNegotiation is btcd's outbound tail: sendaddrv2 or any message
 141  // btcd does not know may arrive, verack ends it.
 142  func (c *Conn) waitToFinishNegotiation(pver uint32) error {
 143  	for {
 144  		msg, _, err := c.read()
 145  		if errors.Is(err, wire.ErrUnknownMessage) {
 146  			continue
 147  		} else if err != nil {
 148  			return err
 149  		}
 150  		switch msg.(type) {
 151  		case *wire.MsgSendAddrV2:
 152  			if pver < wire.AddrV2Version {
 153  				continue
 154  			}
 155  		case *wire.MsgVerAck:
 156  			return nil
 157  		default:
 158  			return wire.ErrInvalidHandshake
 159  		}
 160  	}
 161  }
 162  
 163  // OutboundNegotiate is btcd's negotiateOutboundProtocol, message for message.
 164  func (c *Conn) OutboundNegotiate() error {
 165  	if err := c.writeLocalVersionMsg(); err != nil {
 166  		return err
 167  	}
 168  	if err := c.readRemoteVersionMsg(); err != nil {
 169  		return err
 170  	}
 171  	if err := c.writeSendAddrV2Msg(c.Pver); err != nil {
 172  		return err
 173  	}
 174  	if err := c.write(wire.NewMsgVerAck()); err != nil {
 175  		return err
 176  	}
 177  	return c.waitToFinishNegotiation(c.Pver)
 178  }
 179  
 180  // Settle is the deadline btcd leaves off once a peer is live.
 181  func (c *Conn) Settle() error {
 182  	if s, ok := c.RW.(interface{ SetDeadline(time.Time) error }); ok {
 183  		return s.SetDeadline(time.Time{})
 184  	}
 185  	return nil
 186  }
 187