peer.go raw

   1  // Package v2peer is the peer connection this project uses.
   2  //
   3  // The message framing, the version negotiation, the ping/pong and the BIP324
   4  // transport are btcd's, not a reimplementation: btcd's v2transport module owns
   5  // the handshake, its ciphers and its packet layer, and btcd's wire package owns
   6  // the v2 message framing that sits inside a packet. What is here is the
   7  // connection those two are fitted together on, a loop that hands the caller
   8  // btcd messages as they arrive, and a write that never blocks the caller.
   9  //
  10  // A v1 connection is a v2 transport that the peer refused: v2transport reports
  11  // that as ErrUseV1Protocol or ErrShouldDowngradeToV1 and the same connection
  12  // then carries plaintext frames, which is what a node without BIP324 expects
  13  // and what btcd's own peer does.
  14  package v2peer
  15  
  16  import (
  17  	"bytes"
  18  	"context"
  19  	"crypto/rand"
  20  	"encoding/binary"
  21  	"errors"
  22  	"fmt"
  23  	"net"
  24  	"sync"
  25  	"time"
  26  
  27  	"github.com/btcsuite/btcd/v2transport"
  28  	"github.com/btcsuite/btcd/wire/v2"
  29  
  30  	"git.smesh.lol/btcd-lite/internal/v2peer/authored"
  31  	"git.smesh.lol/btcd-lite/internal/wirefmt"
  32  )
  33  
  34  // Config is what a connection needs to come up.
  35  type Config struct {
  36  	Conn      net.Conn
  37  	Net       wire.BitcoinNet
  38  	UserAgent string
  39  	// Services advertised in version.
  40  	Services wire.ServiceFlag
  41  	// LastBlock is the height the version message claims.
  42  	LastBlock int32
  43  	// V2 asks for the BIP324 handshake. A peer that refuses falls back to v1
  44  	// on the same connection.
  45  	V2 bool
  46  	// Timeout bounds the handshake and every read.
  47  	Timeout time.Duration
  48  	// Remote names the peer in the log lines: an address, or an address and
  49  	// whatever a caller wants to see beside it.
  50  	Remote string
  51  	// Logf receives the connection's lifecycle lines; nil discards them.
  52  	Logf func(string, ...any)
  53  }
  54  
  55  // Peer is a live connection: a reader goroutine, a caller-shaped channel of
  56  // messages, and a writer that a caller may use from any goroutine.
  57  type Peer struct {
  58  	cfg       Config
  59  	t         *v2transport.Peer
  60  	v2        bool
  61  	writeMu   sync.Mutex
  62  	recv      chan Msg
  63  	done      chan struct{}
  64  	err       error
  65  	errMu     sync.Mutex
  66  	protocol  uint32
  67  	agent     string
  68  	services  wire.ServiceFlag
  69  	lastBlock int32
  70  	opened    time.Time
  71  }
  72  
  73  // vtrace, when set, sees every plaintext message before it is decoded, for
  74  // the tests that have to look at a frame no btcd type covers.
  75  var vtrace func(format string, args ...any)
  76  
  77  // SetTrace installs a trace for the v2 handshake and every message after it,
  78  // for a process that is being diagnosed from outside. Nil turns it off.
  79  func SetTrace(f func(format string, args ...any)) { vtrace = f }
  80  
  81  func min(a, b int) int {
  82  	if a < b {
  83  		return a
  84  	}
  85  	return b
  86  }
  87  
  88  // traceConn records what goes out and comes in on the connection under the v2
  89  // handshake, which is the one exchange that reports nothing but an EOF when it
  90  // fails.
  91  type traceConn struct {
  92  	net.Conn
  93  }
  94  
  95  func (c *traceConn) Read(p []byte) (int, error) {
  96  	n, err := c.Conn.Read(p)
  97  	if vtrace != nil {
  98  		vtrace("transport asked for %d bytes, got %d (err %v)", len(p), n, err)
  99  	}
 100  	return n, err
 101  }
 102  
 103  func (c *traceConn) Write(p []byte) (int, error) {
 104  	n, err := c.Conn.Write(p)
 105  	if vtrace != nil {
 106  		vtrace("transport wrote %d bytes (err %v): %x", n, err, p[:min(n, 32)])
 107  	}
 108  	return n, err
 109  }
 110  
 111  // Msg is a message as the reader saw it, with its raw payload when the caller
 112  // wants the bytes.
 113  type Msg struct {
 114  	Message wire.Message
 115  	Command string
 116  	Payload []byte
 117  }
 118  
 119  // Dial connects, negotiates and returns a peer whose reader is running.
 120  func Dial(cfg Config) (*Peer, error) {
 121  	if cfg.Timeout == 0 {
 122  		cfg.Timeout = 2 * time.Minute
 123  	}
 124  	if cfg.Logf == nil {
 125  		cfg.Logf = func(string, ...any) {}
 126  	}
 127  	p := &Peer{cfg: cfg, recv: make(chan Msg, 64), done: make(chan struct{}), opened: time.Now()}
 128  	// The handshake gets a deadline on the socket itself. negotiate sets one
 129  	// too, but the BIP324 exchange runs before negotiate, and a node that
 130  	// accepts TCP and then says nothing would otherwise hold the dial for as
 131  	// long as it keeps the socket open: a public node that does not speak v2
 132  	// answers nothing and closes sixty seconds later, which is a minute spent
 133  	// before a fallback that could have started in ten.
 134  	_ = cfg.Conn.SetDeadline(time.Now().Add(cfg.Timeout))
 135  	p.t = v2transport.NewPeer()
 136  	// The transport reads and writes the connection through this, and the
 137  	// handshake is the first thing that does. A transport with no reader
 138  	// writer is a nil dereference inside btcd's Send, not an error this
 139  	// package could return.
 140  	p.t.UseReadWriter(&traceConn{Conn: cfg.Conn})
 141  	if cfg.V2 {
 142  		tracef := func(f string, a ...any) {
 143  			if vtrace != nil {
 144  				cfg.Logf("v2peer: "+f, a...)
 145  			}
 146  		}
 147  		tracef("v2 handshake started; transport has a connection: %v", p.t != nil)
 148  		up, err := (&authored.Conn{V2: p.t, RW: cfg.Conn, Net: cfg.Net}).UpgradeV2(1000)
 149  		tracef("v2 handshake finished: up=%v err=%v", up, err)
 150  		if err != nil {
 151  			return nil, fmt.Errorf("v2peer: v2 handshake: %w", err)
 152  		}
 153  		if up {
 154  			p.v2 = true
 155  		} else {
 156  			// btcd carries on in v1 on the same connection, and so does this.
 157  			p.cfg.V2 = false
 158  			p.t = nil
 159  		}
 160  	}
 161  	started := time.Now()
 162  	if err := p.negotiate(); err != nil {
 163  		return nil, err
 164  	}
 165  	// One line per connection, with everything a diagnosis needs about the
 166  	// peer before the first request: which protocol it settled on, what it
 167  	// calls itself, what it claims to serve, and how far it says its chain is.
 168  	// The height is a claim and the header sync is what finds out.
 169  	p.cfg.Logf("v2peer: up: remote=%s protocol=%d v2=%v agent=%q services=%#x height=%d handshake_ms=%d",
 170  		p.cfg.Remote, p.protocol, p.v2, p.agent, uint64(p.services), p.lastBlock, time.Since(started).Milliseconds())
 171  	// The handshake's deadline is cleared before the reader takes the socket:
 172  	// the reader sets its own read deadline each turn and nothing sets a write
 173  	// one, so a leftover would expire the first write after ten seconds.
 174  	_ = cfg.Conn.SetDeadline(time.Time{})
 175  	go p.readLoop()
 176  	return p, nil
 177  }
 178  
 179  // DialWithFallback dials addr, tries BIP324, and if that fails redials and
 180  // negotiates v1.
 181  //
 182  // A node that does not speak v2 answers the ellswift with nothing and closes,
 183  // which reads as EOF sixty seconds later, and the same connection cannot be
 184  // reused for v1 because the peer has already decided what it was. So the
 185  // fallback is a second connection, and the v2 attempt gets a short deadline of
 186  // its own: a listening socket that is not a node at all is a minute not worth
 187  // spending before the fallback.
 188  func DialWithFallback(ctx context.Context, dial func(context.Context, string) (net.Conn, error), addr string, cfg Config) (*Peer, error) {
 189  	if cfg.Logf == nil {
 190  		cfg.Logf = func(string, ...any) {}
 191  	}
 192  	nc, err := dial(ctx, addr)
 193  	if err != nil {
 194  		return nil, err
 195  	}
 196  	first := cfg
 197  	first.Conn, first.V2, first.Remote = nc, true, addr
 198  	if first.Timeout > v2Attempt {
 199  		first.Timeout = v2Attempt
 200  	}
 201  	p, v2err := Dial(first)
 202  	if v2err == nil {
 203  		return p, nil
 204  	}
 205  	_ = nc.Close()
 206  	cfg.Logf("v2peer: %s: v2 failed (%v), retrying in v1", addr, v2err)
 207  	nc, err = dial(ctx, addr)
 208  	if err != nil {
 209  		return nil, fmt.Errorf("v2peer: %s: v2 failed (%v) and the retry dial failed: %w", addr, v2err, err)
 210  	}
 211  	cfg.Conn, cfg.V2, cfg.Remote = nc, false, addr
 212  	p, err = Dial(cfg)
 213  	if err != nil {
 214  		_ = nc.Close()
 215  		return nil, fmt.Errorf("v2peer: %s: v2 failed (%v), v1 failed: %w", addr, v2err, err)
 216  	}
 217  	return p, nil
 218  }
 219  
 220  // v2Attempt bounds the BIP324 attempt inside DialWithFallback.
 221  const v2Attempt = 10 * time.Second
 222  
 223  // V2 reports whether the connection carried the BIP324 handshake.
 224  func (p *Peer) V2() bool { return p.v2 }
 225  
 226  // Messages is the channel the reader delivers on. It closes when the
 227  // connection ends.
 228  func (p *Peer) Messages() <-chan Msg { return p.recv }
 229  
 230  // Err is the reason the connection ended, after Messages has closed.
 231  func (p *Peer) Err() error {
 232  	p.errMu.Lock()
 233  	defer p.errMu.Unlock()
 234  	return p.err
 235  }
 236  
 237  // peerNonce is a random nonce for the version message, which is how a node
 238  // notices a connection to itself.
 239  func peerNonce() uint64 {
 240  	var b [8]byte
 241  	if _, err := rand.Read(b[:]); err != nil {
 242  		return uint64(time.Now().UnixNano())
 243  	}
 244  	return binary.LittleEndian.Uint64(b[:])
 245  }
 246  
 247  // Agent is the user agent string the peer sent in its version message.
 248  // Services is what the peer's version message said it serves.
 249  func (p *Peer) Services() uint64 { return uint64(p.services) }
 250  
 251  // LastBlock is the height the peer's version message claimed when the
 252  // connection was made. It is a claim: the header sync is what finds out.
 253  func (p *Peer) LastBlock() int32 { return p.lastBlock }
 254  
 255  // Agent is the user agent string the peer sent in its version message.
 256  func (p *Peer) Agent() string {
 257  	if p.agent != "" {
 258  		return p.agent
 259  	}
 260  	return p.cfg.UserAgent
 261  }
 262  
 263  // Protocol is the negotiated protocol version.
 264  func (p *Peer) Protocol() uint32 { return p.protocol }
 265  
 266  // Write sends a message: btcd's encoding for the transport that is live,
 267  // serialised under one lock so two goroutines never interleave halves of a
 268  // frame.
 269  func (p *Peer) Write(msg wire.Message) error {
 270  	var buf bytes.Buffer
 271  	// btcd writes and reads with wire.LatestEncoding: a block on the wire
 272  	// carries its witnesses.
 273  	enc := wire.LatestEncoding
 274  	if p.v2 {
 275  		if _, err := wire.WriteV2MessageN(&buf, msg, p.Protocol(), enc); err != nil {
 276  			return err
 277  		}
 278  		if vtrace != nil {
 279  			vtrace("send %s: %x", msg.Command(), buf.Bytes())
 280  		}
 281  	} else {
 282  		frame, err := wirefmt.Encode(msg, p.Protocol(), p.cfg.Net)
 283  		if err != nil {
 284  			return err
 285  		}
 286  		if vtrace != nil {
 287  			vtrace("send v1 %s: %x", msg.Command(), frame)
 288  		}
 289  		buf.Write(frame)
 290  	}
 291  	p.writeMu.Lock()
 292  	defer p.writeMu.Unlock()
 293  	_ = p.cfg.Conn.SetWriteDeadline(time.Now().Add(30 * time.Second))
 294  	if p.v2 {
 295  		// V2EncPacket encrypts and writes through the transport's reader
 296  		// writer, which is the connection.
 297  		if _, _, err := p.t.V2EncPacket(buf.Bytes(), nil, false); err != nil {
 298  			return err
 299  		}
 300  		return nil
 301  	}
 302  	_, err := p.cfg.Conn.Write(buf.Bytes())
 303  	return err
 304  }
 305  
 306  // negotiate runs btcd's outbound handshake, after the transport has been
 307  // chosen: version, version, sendaddrv2, verack, verack.
 308  func (p *Peer) negotiate() error {
 309  	_ = p.cfg.Conn.SetDeadline(time.Now().Add(p.cfg.Timeout))
 310  	c := &authored.Conn{
 311  		RW: p.cfg.Conn, Net: p.cfg.Net, Pver: wire.ProtocolVersion,
 312  		UserAgent: p.cfg.UserAgent, Services: p.cfg.Services,
 313  		LastBlock: p.cfg.LastBlock, Nonce: peerNonce(), Relay: true,
 314  	}
 315  	if p.v2 {
 316  		c.V2 = p.t
 317  	}
 318  	if err := c.OutboundNegotiate(); err != nil {
 319  		return fmt.Errorf("v2peer: %w", err)
 320  	}
 321  	p.protocol = c.Pver
 322  	p.agent = c.RemoteAgent
 323  	p.services = c.RemoteServices
 324  	p.lastBlock = c.RemoteLastBlock
 325  	return c.Settle()
 326  }
 327  
 328  // readOne reads one message in whatever framing is live.
 329  func (p *Peer) readOne() (wire.Message, []byte, error) {
 330  	if p.v2 {
 331  		plaintext, err := p.t.V2ReceivePacket(nil)
 332  		if err != nil {
 333  			return nil, nil, err
 334  		}
 335  		if vtrace != nil {
 336  			vtrace("recv %d bytes: %x", len(plaintext), plaintext[:min(len(plaintext), 48)])
 337  		}
 338  		return wire.ReadV2MessageN(plaintext, p.Protocol(), wire.LatestEncoding)
 339  	}
 340  	msg, payload, err := wirefmt.Read(p.cfg.Conn, p.Protocol(), p.cfg.Net)
 341  	if vtrace != nil && err == nil {
 342  		vtrace("recv v1 %s: %d bytes", msg.Command(), len(payload))
 343  	}
 344  	return msg, payload, err
 345  }
 346  
 347  func (p *Peer) readLoop() {
 348  	defer close(p.recv)
 349  	for {
 350  		_ = p.cfg.Conn.SetReadDeadline(time.Now().Add(24 * time.Hour))
 351  		msg, payload, err := p.readOne()
 352  		if err != nil {
 353  			if errors.Is(err, wire.ErrUnknownMessage) {
 354  				continue
 355  			}
 356  			p.errMu.Lock()
 357  			p.err = err
 358  			p.errMu.Unlock()
 359  			// The end of the connection, with the reason the reader got. A
 360  			// close this side asked for is logged by Close, on the caller's
 361  			// goroutine, so that a caller which has already returned never
 362  			// sees a log line from here: the reader is the last thing to
 363  			// notice a close and it may notice it after the caller is gone.
 364  			select {
 365  			case <-p.done:
 366  				return
 367  			default:
 368  				p.cfg.Logf("v2peer: down: remote=%s after=%s err=%v", p.cfg.Remote, time.Since(p.opened).Round(time.Millisecond), err)
 369  			}
 370  			return
 371  		}
 372  		if ping, ok := msg.(*wire.MsgPing); ok {
 373  			_ = p.Write(wire.NewMsgPong(ping.Nonce))
 374  			continue
 375  		}
 376  		select {
 377  		case p.recv <- Msg{Message: msg, Command: msg.Command(), Payload: payload}:
 378  		case <-p.done:
 379  			return
 380  		}
 381  	}
 382  }
 383  
 384  // Close ends the connection. The first call writes the line that says the
 385  // instance closed it, on the caller's goroutine, so a caller that logs to a
 386  // test never has the reader logging after the test has ended.
 387  func (p *Peer) Close() error {
 388  	first := false
 389  	select {
 390  	case <-p.done:
 391  	default:
 392  		close(p.done)
 393  		first = true
 394  	}
 395  	if first {
 396  		p.cfg.Logf("v2peer: down: remote=%s after=%s closed=local", p.cfg.Remote, time.Since(p.opened).Round(time.Millisecond))
 397  	}
 398  	return p.cfg.Conn.Close()
 399  }
 400