// Package authored is btcd's peer handshake sequence, copied from // github.com/btcsuite/btcd/peer at commit 2c467023f0cb, with btcd's listener // interface removed. // // The messages, the transport's version-2 handshake and the encodings are // btcd's throughout. What was taken out is the peer's message-dispatch and // message-queue machinery, which this project does not use: it is not a // bitcoin node and has nothing to do with blocks or transactions across the // interface. What is left is the order in which the four handshake messages // go out and what may arrive between them, including the sendaddrv2 // exchange that bitcoind requires to happen before verack. package authored import ( "bytes" "errors" "fmt" "io" "net" "time" "github.com/btcsuite/btcd/v2transport" "github.com/btcsuite/btcd/wire/v2" "git.smesh.lol/btcd-lite/internal/wirefmt" ) // Conn is one connection in the middle of a handshake. type Conn struct { RW io.ReadWriter Net wire.BitcoinNet Pver uint32 V2 *v2transport.Peer UserAgent string Services wire.ServiceFlag LastBlock int32 Nonce uint64 Relay bool // RemoteAgent is the user agent the peer sent, recorded as btcd records // it for a listener. RemoteAgent string // RemoteServices and RemoteLastBlock are what the peer's version message // claimed: what it says it serves and how far its chain was. They are // diagnosis, not trust. RemoteServices wire.ServiceFlag RemoteLastBlock int32 } // UpgradeV2 runs btcd's initiating side of the BIP324 handshake. It returns // false and no error when the peer does not speak v2, which is btcd's cue to // carry on in v1 on the same connection. func (c *Conn) UpgradeV2(garbageLen int) (bool, error) { if err := c.V2.InitiateV2Handshake(garbageLen); err != nil { return false, err } err := c.V2.CompleteHandshake(true, nil, v2transport.BitcoinNet(c.Net)) switch { case errors.Is(err, v2transport.ErrShouldDowngradeToV1), errors.Is(err, v2transport.ErrUseV1Protocol): return false, nil case err != nil: return false, err } return true, nil } // write sends with btcd's encoder for the transport that is live, and speaks // the protocol version the peer gave, as btcd does after it has read version. func (c *Conn) write(msg wire.Message) error { if c.V2 != nil { // btcd writes with wire.LatestEncoding: a transaction or block on the // wire carries its witnesses, and a base encoding decode of a block // leaves the witnesses in the stream as extra bytes. var buf bytes.Buffer if _, err := wire.WriteV2MessageN(&buf, msg, c.Pver, wire.LatestEncoding); err != nil { return err } _, _, err := c.V2.V2EncPacket(buf.Bytes(), nil, false) return err } _, err := wirefmt.Write(c.RW, msg, c.Pver, c.Net) return err } func (c *Conn) read() (wire.Message, []byte, error) { if c.V2 != nil { plaintext, err := c.V2.V2ReceivePacket(nil) if err != nil { return nil, nil, err } return wire.ReadV2MessageN(plaintext, c.Pver, wire.LatestEncoding) } return wirefmt.Read(c.RW, c.Pver, c.Net) } // writeLocalVersionMsg is btcd's. func (c *Conn) writeLocalVersionMsg() error { ourNA := wire.NewNetAddressIPPort(net.IPv4zero, 0, c.Services) theirNA := wire.NewNetAddressIPPort(net.IPv4zero, 0, 0) msg := wire.NewMsgVersion(ourNA, theirNA, c.Nonce, c.LastBlock) msg.AddUserAgent(c.UserAgent, "") msg.Services = c.Services msg.ProtocolVersion = int32(wire.ProtocolVersion) msg.DisableRelayTx = !c.Relay return c.write(msg) } // writeSendAddrV2Msg is btcd's: the message is the sender's declaration that // it understands addrV2 addresses in a preferred format, and bitcoind // disconnects a peer that sends it after verack. func (c *Conn) writeSendAddrV2Msg(pver uint32) error { if pver < wire.AddrV2Version { return nil } return c.write(wire.NewMsgSendAddrV2()) } // readRemoteVersionMsg is btcd's: the first message has to be version, and it // fixes the protocol version for everything after it. func (c *Conn) readRemoteVersionMsg() error { msg, _, err := c.read() if err != nil { return err } remote, ok := msg.(*wire.MsgVersion) if !ok { return fmt.Errorf("authored: first message is %q, not version", msg.Command()) } if remote.ProtocolVersion > 0 && uint32(remote.ProtocolVersion) < c.Pver { c.Pver = uint32(remote.ProtocolVersion) } c.RemoteAgent = remote.UserAgent c.RemoteServices = remote.Services c.RemoteLastBlock = remote.LastBlock return nil } // waitToFinishNegotiation is btcd's outbound tail: sendaddrv2 or any message // btcd does not know may arrive, verack ends it. func (c *Conn) waitToFinishNegotiation(pver uint32) error { for { msg, _, err := c.read() if errors.Is(err, wire.ErrUnknownMessage) { continue } else if err != nil { return err } switch msg.(type) { case *wire.MsgSendAddrV2: if pver < wire.AddrV2Version { continue } case *wire.MsgVerAck: return nil default: return wire.ErrInvalidHandshake } } } // OutboundNegotiate is btcd's negotiateOutboundProtocol, message for message. func (c *Conn) OutboundNegotiate() error { if err := c.writeLocalVersionMsg(); err != nil { return err } if err := c.readRemoteVersionMsg(); err != nil { return err } if err := c.writeSendAddrV2Msg(c.Pver); err != nil { return err } if err := c.write(wire.NewMsgVerAck()); err != nil { return err } return c.waitToFinishNegotiation(c.Pver) } // Settle is the deadline btcd leaves off once a peer is live. func (c *Conn) Settle() error { if s, ok := c.RW.(interface{ SetDeadline(time.Time) error }); ok { return s.SetDeadline(time.Time{}) } return nil }