package relay import ( "bufio" "bytes" "context" "encoding/binary" "errors" "fmt" "io" "net" "sync" "time" chainhash2 "github.com/btcsuite/btcd/chainhash/v2" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/chain" "git.smesh.lol/nostrino/pkg/crypto/chainhash" btcdwire "github.com/btcsuite/btcd/wire/v2" "git.smesh.lol/btcd-lite/internal/chains" "git.smesh.lol/btcd-lite/internal/v2peer" "git.smesh.lol/btcd-lite/internal/wire" ) // MaxTxSize is the largest transaction the relay takes. It is the block // ceiling: no transaction can be larger and be mined. const MaxTxSize = wire.MaxBlockPayload // Relay carries transactions from a window to peers by announcing their txid // and serving the bytes to whoever asks. // // The bytes go out on a getdata, not on the announcement: a peer answers an // inv with getdata when it wants the transaction, and sending a tx nobody asked // for is a way to be dropped. Each peer has its own connection and its own // reader, because the relay has to answer requests that arrive while it is not // asking for anything. type Relay struct { cfg RelayConfig mu sync.Mutex conns map[string]*peer // served is every transaction the relay may serve by txid. It is the // window's map, not a copy: a txid that has aged out is not served. window *Window } // RelayConfig is what a relay is made of. type RelayConfig struct { // Profile is the chain, for the magic. Profile *chain.Profile // Window is where relayed transactions and their state live. Window *Window // Peers are the full nodes to announce to. Peers []string // V2 asks for BIP324. Plaintext v1 is the default for the same reason the // fill defaults to it. V2 bool // UserAgent is advertised in version. UserAgent string // Logf receives diagnostics; nil discards them. Logf func(string, ...any) // Dial opens a connection to an address. Nil means TCP. Dial func(ctx context.Context, addr string) (net.Conn, error) // ReadTimeout bounds one frame read. ReadTimeout time.Duration } // peer is one relay connection. The framing, the BIP324 handshake and the // version exchange are v2peer's, the same code the instance syncs over: a relay // with its own wire framing cannot negotiate with a node that has v1 off, which // is every node this project targets. type peer struct { addr string p *v2peer.Peer } // New returns a relay. It does not dial. func New(cfg RelayConfig) (*Relay, error) { if cfg.Profile == nil || cfg.Window == nil { return nil, errors.New("relay: profile and window are required") } if len(cfg.Peers) == 0 { return nil, errors.New("relay: no peers") } if cfg.UserAgent == "" { cfg.UserAgent = "/btcd-lite:0.1.0/" } if cfg.ReadTimeout == 0 { cfg.ReadTimeout = 2 * time.Minute } if cfg.Logf == nil { cfg.Logf = func(string, ...any) {} } return &Relay{cfg: cfg, conns: map[string]*peer{}, window: cfg.Window}, nil } // Start dials every peer it can and begins serving their requests. It returns // when ctx ends; connections that fail are logged and not retried here, which // is the supervisor's job. func (r *Relay) Start(ctx context.Context) { var wg sync.WaitGroup for _, addr := range r.cfg.Peers { wg.Add(1) go func(addr string) { defer wg.Done() r.servePeer(ctx, addr) }(addr) } wg.Wait() } func (r *Relay) servePeer(ctx context.Context, addr string) { var nc net.Conn var err error if r.cfg.Dial != nil { nc, err = r.cfg.Dial(ctx, addr) } else { var d net.Dialer nc, err = d.DialContext(ctx, "tcp", addr) } if err != nil { r.cfg.Logf("relay: %s: %v", addr, err) return } // The deadline covers the dial and the negotiation, and is cleared once the // peer is live: a peer kept on the dial's clock is a peer that closes // itself after two silent minutes, which is an idle node, not a dead one. _ = nc.SetDeadline(time.Now().Add(r.cfg.ReadTimeout)) conn, err := v2peer.Dial(v2peer.Config{ Conn: nc, Net: chains.WireMagic(r.cfg.Profile), UserAgent: r.cfg.UserAgent, Services: btcdwire.SFNodeNetwork, V2: r.cfg.V2, Timeout: r.cfg.ReadTimeout, Remote: addr, Logf: r.cfg.Logf, }) if err != nil { r.cfg.Logf("relay: %s: %v", addr, err) _ = nc.Close() return } _ = nc.SetDeadline(time.Time{}) r.cfg.Logf("relay: %s: connected, %s", addr, conn.Agent()) p := &peer{addr: addr, p: conn} r.mu.Lock() r.conns[addr] = p r.mu.Unlock() defer func() { r.mu.Lock() delete(r.conns, addr) r.mu.Unlock() _ = conn.Close() }() r.serveLoop(ctx, p) } // serveLoop reads frames and answers the ones that ask for a transaction. A // peer that closes is a peer that closed: it ends this connection and no more. func (r *Relay) serveLoop(ctx context.Context, p *peer) { for { select { case <-ctx.Done(): return case msg, ok := <-p.p.Messages(): if !ok { if ctx.Err() == nil { r.cfg.Logf("relay: %s: %v", p.addr, p.p.Err()) } return } switch m := msg.Message.(type) { case *btcdwire.MsgGetData: r.serveGetData(p, m) case *btcdwire.MsgPing: _ = p.p.Write(btcdwire.NewMsgPong(m.Nonce)) } } } } // serveGetData answers the transactions a peer asked for, and says which it does // not have, which is what a relayed peer expects rather than silence. func (r *Relay) serveGetData(p *peer, gd *btcdwire.MsgGetData) { for _, inv := range gd.InvList { if inv.Type != btcdwire.InvTypeTx && inv.Type != btcdwire.InvTypeWitnessTx { continue } id := chainhash.Hash(inv.Hash) e, ok := r.window.Get(id) if !ok { nf := &btcdwire.MsgNotFound{} nf.AddInvVect(btcdwire.NewInvVect(inv.Type, &inv.Hash)) _ = p.p.Write(nf) continue } // The transaction goes out as the bytes that were relayed, decoded by // the same wire package the peer reads with. var m btcdwire.MsgTx if err := m.Deserialize(bytes.NewReader(e.Raw)); err != nil { r.cfg.Logf("relay: %s: window tx %s does not parse: %v", p.addr, inv.Hash, err) continue } _ = p.p.Write(&m) } } // Announce sends the window's txids to every connected peer. It returns how // many peers took the announcement, which is the number of peers a client's // transaction reached, not the number that accepted it. func (r *Relay) Announce(ctx context.Context, ids []chainhash.Hash) (int, error) { if len(ids) == 0 { return 0, nil } inv := &btcwire.Inv{} for _, id := range ids { inv.InvList = append(inv.InvList, btcwire.InvVect{Type: btcwire.InvVectTypeTx, Hash: id}) } _ = inv r.mu.Lock() peers := make([]*peer, 0, len(r.conns)) for _, p := range r.conns { peers = append(peers, p) } r.mu.Unlock() sent := 0 var errs []error var invm btcdwire.MsgInv for _, id := range ids { // The two hash types hold the same bytes; only the display order // differs, so the conversion is a copy and not a reformat. var ch chainhash2.Hash copy(ch[:], id[:]) invm.AddInvVect(btcdwire.NewInvVect(btcdwire.InvTypeTx, &ch)) } for _, p := range peers { if err := p.p.Write(&invm); err != nil { errs = append(errs, fmt.Errorf("%s: %w", p.addr, err)) continue } sent++ } return sent, errors.Join(errs...) } // Peers is how many relay peers are connected. func (r *Relay) Peers() int { r.mu.Lock() defer r.mu.Unlock() return len(r.conns) } // conn is one peer connection: the handshake, a frame writer, and a frame // reader. It is the same wire the filler speaks, with the announcement and // the serve in place of the block request. type conn struct { nc net.Conn r *bufio.Reader magic uint32 ua string timeout time.Duration } func (c *conn) setDeadline(ctx context.Context) error { d := time.Now().Add(c.timeout) if t, ok := ctx.Deadline(); ok && t.Before(d) { d = t } return c.nc.SetReadDeadline(d) } func (c *conn) handshake(lastBlock int32) error { c.r = bufio.NewReaderSize(c.nc, 64*1024) our := &btcwire.Version{ ProtocolVersion: 70016, Timestamp: time.Now().Unix(), Nonce: 0x72656c61796c6974, UserAgent: c.ua, LastBlock: lastBlock, } payload, err := our.EncodePayload() if err != nil { return err } if err := c.write(btcwire.CmdVersion, payload); err != nil { return err } var gotVersion, gotVerAck bool _ = c.nc.SetDeadline(time.Now().Add(c.timeout)) for !gotVersion || !gotVerAck { cmd, body, err := c.readFrame() if err != nil { return err } switch cmd { case btcwire.CmdVersion: var v btcwire.Version if err := v.DecodePayload(body); err != nil { return err } // relay=1 asks a node to relay transactions to us; the relay // serves what it is asked for either way. gotVersion = true if err := c.write(btcwire.CmdVerAck, nil); err != nil { return err } case btcwire.CmdVerAck: gotVerAck = true case btcwire.CmdPing: var p btcwire.Ping _ = p.DecodePayload(body) if err := c.pong(p.Nonce); err != nil { return err } } } return c.nc.SetDeadline(time.Time{}) } func (c *conn) pong(nonce uint64) error { payload, err := (&btcwire.Pong{Nonce: nonce}).EncodePayload() if err != nil { return err } return c.write(btcwire.CmdPong, payload) } func (c *conn) write(cmd string, payload []byte) error { var magic [4]byte binary.BigEndian.PutUint32(magic[:], c.magic) var header [24]byte copy(header[0:4], magic[:]) copy(header[4:16], cmd) binary.LittleEndian.PutUint32(header[16:20], uint32(len(payload))) sum := btcwire.Checksum(payload) copy(header[20:24], sum[:]) _ = c.nc.SetWriteDeadline(time.Now().Add(30 * time.Second)) buf := make([]byte, 0, 24+len(payload)) buf = append(buf, header[:]...) buf = append(buf, payload...) _, err := c.nc.Write(buf) return err } func (c *conn) readFrame() (string, []byte, error) { var header [24]byte if _, err := io.ReadFull(c.r, header[:]); err != nil { return "", nil, err } if got := binary.BigEndian.Uint32(header[0:4]); got != c.magic { return "", nil, fmt.Errorf("%w: %#08x", btcwire.ErrBadMagic, got) } cmd := string(header[4:16]) for i, ch := range header[4:16] { if ch == 0 { cmd = string(header[4 : 4+i]) break } } n := binary.LittleEndian.Uint32(header[16:20]) if n > btcwire.MaxPayload { return "", nil, btcwire.ErrPayloadTooLarge } body := make([]byte, n) if _, err := io.ReadFull(c.r, body); err != nil { return "", nil, err } sum := btcwire.Checksum(body) if string(header[20:24]) != string(sum[:]) { return "", nil, btcwire.ErrBadChecksum } return cmd, body, nil } // ParseAndCheck is admission: the bytes must parse as a transaction of this // chain's wire form, and nothing else is decided here. It returns the parsed // transaction and its txid. func ParseAndCheck(raw []byte) (*wire.Tx, chainhash.Hash, error) { if len(raw) == 0 { return nil, chainhash.Hash{}, errors.New("relay: empty transaction") } if len(raw) > MaxTxSize { return nil, chainhash.Hash{}, fmt.Errorf("relay: transaction is %d bytes, maximum is %d", len(raw), MaxTxSize) } tx, err := wire.ParseTx(raw) if err != nil { return nil, chainhash.Hash{}, err } return tx, tx.TxID(), nil }