// Package v2peer is the peer connection this project uses. // // The message framing, the version negotiation, the ping/pong and the BIP324 // transport are btcd's, not a reimplementation: btcd's v2transport module owns // the handshake, its ciphers and its packet layer, and btcd's wire package owns // the v2 message framing that sits inside a packet. What is here is the // connection those two are fitted together on, a loop that hands the caller // btcd messages as they arrive, and a write that never blocks the caller. // // A v1 connection is a v2 transport that the peer refused: v2transport reports // that as ErrUseV1Protocol or ErrShouldDowngradeToV1 and the same connection // then carries plaintext frames, which is what a node without BIP324 expects // and what btcd's own peer does. package v2peer import ( "bytes" "context" "crypto/rand" "encoding/binary" "errors" "fmt" "net" "sync" "time" "github.com/btcsuite/btcd/v2transport" "github.com/btcsuite/btcd/wire/v2" "git.smesh.lol/btcd-lite/internal/v2peer/authored" "git.smesh.lol/btcd-lite/internal/wirefmt" ) // Config is what a connection needs to come up. type Config struct { Conn net.Conn Net wire.BitcoinNet UserAgent string // Services advertised in version. Services wire.ServiceFlag // LastBlock is the height the version message claims. LastBlock int32 // V2 asks for the BIP324 handshake. A peer that refuses falls back to v1 // on the same connection. V2 bool // Timeout bounds the handshake and every read. Timeout time.Duration // Remote names the peer in the log lines: an address, or an address and // whatever a caller wants to see beside it. Remote string // Logf receives the connection's lifecycle lines; nil discards them. Logf func(string, ...any) } // Peer is a live connection: a reader goroutine, a caller-shaped channel of // messages, and a writer that a caller may use from any goroutine. type Peer struct { cfg Config t *v2transport.Peer v2 bool writeMu sync.Mutex recv chan Msg done chan struct{} err error errMu sync.Mutex protocol uint32 agent string services wire.ServiceFlag lastBlock int32 opened time.Time } // vtrace, when set, sees every plaintext message before it is decoded, for // the tests that have to look at a frame no btcd type covers. var vtrace func(format string, args ...any) // SetTrace installs a trace for the v2 handshake and every message after it, // for a process that is being diagnosed from outside. Nil turns it off. func SetTrace(f func(format string, args ...any)) { vtrace = f } func min(a, b int) int { if a < b { return a } return b } // traceConn records what goes out and comes in on the connection under the v2 // handshake, which is the one exchange that reports nothing but an EOF when it // fails. type traceConn struct { net.Conn } func (c *traceConn) Read(p []byte) (int, error) { n, err := c.Conn.Read(p) if vtrace != nil { vtrace("transport asked for %d bytes, got %d (err %v)", len(p), n, err) } return n, err } func (c *traceConn) Write(p []byte) (int, error) { n, err := c.Conn.Write(p) if vtrace != nil { vtrace("transport wrote %d bytes (err %v): %x", n, err, p[:min(n, 32)]) } return n, err } // Msg is a message as the reader saw it, with its raw payload when the caller // wants the bytes. type Msg struct { Message wire.Message Command string Payload []byte } // Dial connects, negotiates and returns a peer whose reader is running. func Dial(cfg Config) (*Peer, error) { if cfg.Timeout == 0 { cfg.Timeout = 2 * time.Minute } if cfg.Logf == nil { cfg.Logf = func(string, ...any) {} } p := &Peer{cfg: cfg, recv: make(chan Msg, 64), done: make(chan struct{}), opened: time.Now()} // The handshake gets a deadline on the socket itself. negotiate sets one // too, but the BIP324 exchange runs before negotiate, and a node that // accepts TCP and then says nothing would otherwise hold the dial for as // long as it keeps the socket open: a public node that does not speak v2 // answers nothing and closes sixty seconds later, which is a minute spent // before a fallback that could have started in ten. _ = cfg.Conn.SetDeadline(time.Now().Add(cfg.Timeout)) p.t = v2transport.NewPeer() // The transport reads and writes the connection through this, and the // handshake is the first thing that does. A transport with no reader // writer is a nil dereference inside btcd's Send, not an error this // package could return. p.t.UseReadWriter(&traceConn{Conn: cfg.Conn}) if cfg.V2 { tracef := func(f string, a ...any) { if vtrace != nil { cfg.Logf("v2peer: "+f, a...) } } tracef("v2 handshake started; transport has a connection: %v", p.t != nil) up, err := (&authored.Conn{V2: p.t, RW: cfg.Conn, Net: cfg.Net}).UpgradeV2(1000) tracef("v2 handshake finished: up=%v err=%v", up, err) if err != nil { return nil, fmt.Errorf("v2peer: v2 handshake: %w", err) } if up { p.v2 = true } else { // btcd carries on in v1 on the same connection, and so does this. p.cfg.V2 = false p.t = nil } } started := time.Now() if err := p.negotiate(); err != nil { return nil, err } // One line per connection, with everything a diagnosis needs about the // peer before the first request: which protocol it settled on, what it // calls itself, what it claims to serve, and how far it says its chain is. // The height is a claim and the header sync is what finds out. p.cfg.Logf("v2peer: up: remote=%s protocol=%d v2=%v agent=%q services=%#x height=%d handshake_ms=%d", p.cfg.Remote, p.protocol, p.v2, p.agent, uint64(p.services), p.lastBlock, time.Since(started).Milliseconds()) // The handshake's deadline is cleared before the reader takes the socket: // the reader sets its own read deadline each turn and nothing sets a write // one, so a leftover would expire the first write after ten seconds. _ = cfg.Conn.SetDeadline(time.Time{}) go p.readLoop() return p, nil } // DialWithFallback dials addr, tries BIP324, and if that fails redials and // negotiates v1. // // A node that does not speak v2 answers the ellswift with nothing and closes, // which reads as EOF sixty seconds later, and the same connection cannot be // reused for v1 because the peer has already decided what it was. So the // fallback is a second connection, and the v2 attempt gets a short deadline of // its own: a listening socket that is not a node at all is a minute not worth // spending before the fallback. func DialWithFallback(ctx context.Context, dial func(context.Context, string) (net.Conn, error), addr string, cfg Config) (*Peer, error) { if cfg.Logf == nil { cfg.Logf = func(string, ...any) {} } nc, err := dial(ctx, addr) if err != nil { return nil, err } first := cfg first.Conn, first.V2, first.Remote = nc, true, addr if first.Timeout > v2Attempt { first.Timeout = v2Attempt } p, v2err := Dial(first) if v2err == nil { return p, nil } _ = nc.Close() cfg.Logf("v2peer: %s: v2 failed (%v), retrying in v1", addr, v2err) nc, err = dial(ctx, addr) if err != nil { return nil, fmt.Errorf("v2peer: %s: v2 failed (%v) and the retry dial failed: %w", addr, v2err, err) } cfg.Conn, cfg.V2, cfg.Remote = nc, false, addr p, err = Dial(cfg) if err != nil { _ = nc.Close() return nil, fmt.Errorf("v2peer: %s: v2 failed (%v), v1 failed: %w", addr, v2err, err) } return p, nil } // v2Attempt bounds the BIP324 attempt inside DialWithFallback. const v2Attempt = 10 * time.Second // V2 reports whether the connection carried the BIP324 handshake. func (p *Peer) V2() bool { return p.v2 } // Messages is the channel the reader delivers on. It closes when the // connection ends. func (p *Peer) Messages() <-chan Msg { return p.recv } // Err is the reason the connection ended, after Messages has closed. func (p *Peer) Err() error { p.errMu.Lock() defer p.errMu.Unlock() return p.err } // peerNonce is a random nonce for the version message, which is how a node // notices a connection to itself. func peerNonce() uint64 { var b [8]byte if _, err := rand.Read(b[:]); err != nil { return uint64(time.Now().UnixNano()) } return binary.LittleEndian.Uint64(b[:]) } // Agent is the user agent string the peer sent in its version message. // Services is what the peer's version message said it serves. func (p *Peer) Services() uint64 { return uint64(p.services) } // LastBlock is the height the peer's version message claimed when the // connection was made. It is a claim: the header sync is what finds out. func (p *Peer) LastBlock() int32 { return p.lastBlock } // Agent is the user agent string the peer sent in its version message. func (p *Peer) Agent() string { if p.agent != "" { return p.agent } return p.cfg.UserAgent } // Protocol is the negotiated protocol version. func (p *Peer) Protocol() uint32 { return p.protocol } // Write sends a message: btcd's encoding for the transport that is live, // serialised under one lock so two goroutines never interleave halves of a // frame. func (p *Peer) Write(msg wire.Message) error { var buf bytes.Buffer // btcd writes and reads with wire.LatestEncoding: a block on the wire // carries its witnesses. enc := wire.LatestEncoding if p.v2 { if _, err := wire.WriteV2MessageN(&buf, msg, p.Protocol(), enc); err != nil { return err } if vtrace != nil { vtrace("send %s: %x", msg.Command(), buf.Bytes()) } } else { frame, err := wirefmt.Encode(msg, p.Protocol(), p.cfg.Net) if err != nil { return err } if vtrace != nil { vtrace("send v1 %s: %x", msg.Command(), frame) } buf.Write(frame) } p.writeMu.Lock() defer p.writeMu.Unlock() _ = p.cfg.Conn.SetWriteDeadline(time.Now().Add(30 * time.Second)) if p.v2 { // V2EncPacket encrypts and writes through the transport's reader // writer, which is the connection. if _, _, err := p.t.V2EncPacket(buf.Bytes(), nil, false); err != nil { return err } return nil } _, err := p.cfg.Conn.Write(buf.Bytes()) return err } // negotiate runs btcd's outbound handshake, after the transport has been // chosen: version, version, sendaddrv2, verack, verack. func (p *Peer) negotiate() error { _ = p.cfg.Conn.SetDeadline(time.Now().Add(p.cfg.Timeout)) c := &authored.Conn{ RW: p.cfg.Conn, Net: p.cfg.Net, Pver: wire.ProtocolVersion, UserAgent: p.cfg.UserAgent, Services: p.cfg.Services, LastBlock: p.cfg.LastBlock, Nonce: peerNonce(), Relay: true, } if p.v2 { c.V2 = p.t } if err := c.OutboundNegotiate(); err != nil { return fmt.Errorf("v2peer: %w", err) } p.protocol = c.Pver p.agent = c.RemoteAgent p.services = c.RemoteServices p.lastBlock = c.RemoteLastBlock return c.Settle() } // readOne reads one message in whatever framing is live. func (p *Peer) readOne() (wire.Message, []byte, error) { if p.v2 { plaintext, err := p.t.V2ReceivePacket(nil) if err != nil { return nil, nil, err } if vtrace != nil { vtrace("recv %d bytes: %x", len(plaintext), plaintext[:min(len(plaintext), 48)]) } return wire.ReadV2MessageN(plaintext, p.Protocol(), wire.LatestEncoding) } msg, payload, err := wirefmt.Read(p.cfg.Conn, p.Protocol(), p.cfg.Net) if vtrace != nil && err == nil { vtrace("recv v1 %s: %d bytes", msg.Command(), len(payload)) } return msg, payload, err } func (p *Peer) readLoop() { defer close(p.recv) for { _ = p.cfg.Conn.SetReadDeadline(time.Now().Add(24 * time.Hour)) msg, payload, err := p.readOne() if err != nil { if errors.Is(err, wire.ErrUnknownMessage) { continue } p.errMu.Lock() p.err = err p.errMu.Unlock() // The end of the connection, with the reason the reader got. A // close this side asked for is logged by Close, on the caller's // goroutine, so that a caller which has already returned never // sees a log line from here: the reader is the last thing to // notice a close and it may notice it after the caller is gone. select { case <-p.done: return default: p.cfg.Logf("v2peer: down: remote=%s after=%s err=%v", p.cfg.Remote, time.Since(p.opened).Round(time.Millisecond), err) } return } if ping, ok := msg.(*wire.MsgPing); ok { _ = p.Write(wire.NewMsgPong(ping.Nonce)) continue } select { case p.recv <- Msg{Message: msg, Command: msg.Command(), Payload: payload}: case <-p.done: return } } } // Close ends the connection. The first call writes the line that says the // instance closed it, on the caller's goroutine, so a caller that logs to a // test never has the reader logging after the test has ended. func (p *Peer) Close() error { first := false select { case <-p.done: default: close(p.done) first = true } if first { p.cfg.Logf("v2peer: down: remote=%s after=%s closed=local", p.cfg.Remote, time.Since(p.opened).Round(time.Millisecond)) } return p.cfg.Conn.Close() }