1 package relay
2 3 import (
4 "bufio"
5 "bytes"
6 "context"
7 "encoding/binary"
8 "errors"
9 "fmt"
10 "io"
11 "net"
12 "sync"
13 "time"
14 15 chainhash2 "github.com/btcsuite/btcd/chainhash/v2"
16 17 "git.smesh.lol/nostrino/pkg/btcwire"
18 "git.smesh.lol/nostrino/pkg/chain"
19 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
20 21 btcdwire "github.com/btcsuite/btcd/wire/v2"
22 23 "git.smesh.lol/btcd-lite/internal/chains"
24 "git.smesh.lol/btcd-lite/internal/v2peer"
25 "git.smesh.lol/btcd-lite/internal/wire"
26 )
27 28 // MaxTxSize is the largest transaction the relay takes. It is the block
29 // ceiling: no transaction can be larger and be mined.
30 const MaxTxSize = wire.MaxBlockPayload
31 32 // Relay carries transactions from a window to peers by announcing their txid
33 // and serving the bytes to whoever asks.
34 //
35 // The bytes go out on a getdata, not on the announcement: a peer answers an
36 // inv with getdata when it wants the transaction, and sending a tx nobody asked
37 // for is a way to be dropped. Each peer has its own connection and its own
38 // reader, because the relay has to answer requests that arrive while it is not
39 // asking for anything.
40 type Relay struct {
41 cfg RelayConfig
42 43 mu sync.Mutex
44 conns map[string]*peer
45 // served is every transaction the relay may serve by txid. It is the
46 // window's map, not a copy: a txid that has aged out is not served.
47 window *Window
48 }
49 50 // RelayConfig is what a relay is made of.
51 type RelayConfig struct {
52 // Profile is the chain, for the magic.
53 Profile *chain.Profile
54 // Window is where relayed transactions and their state live.
55 Window *Window
56 // Peers are the full nodes to announce to.
57 Peers []string
58 // V2 asks for BIP324. Plaintext v1 is the default for the same reason the
59 // fill defaults to it.
60 V2 bool
61 // UserAgent is advertised in version.
62 UserAgent string
63 // Logf receives diagnostics; nil discards them.
64 Logf func(string, ...any)
65 // Dial opens a connection to an address. Nil means TCP.
66 Dial func(ctx context.Context, addr string) (net.Conn, error)
67 // ReadTimeout bounds one frame read.
68 ReadTimeout time.Duration
69 }
70 71 // peer is one relay connection. The framing, the BIP324 handshake and the
72 // version exchange are v2peer's, the same code the instance syncs over: a relay
73 // with its own wire framing cannot negotiate with a node that has v1 off, which
74 // is every node this project targets.
75 type peer struct {
76 addr string
77 p *v2peer.Peer
78 }
79 80 // New returns a relay. It does not dial.
81 func New(cfg RelayConfig) (*Relay, error) {
82 if cfg.Profile == nil || cfg.Window == nil {
83 return nil, errors.New("relay: profile and window are required")
84 }
85 if len(cfg.Peers) == 0 {
86 return nil, errors.New("relay: no peers")
87 }
88 if cfg.UserAgent == "" {
89 cfg.UserAgent = "/btcd-lite:0.1.0/"
90 }
91 if cfg.ReadTimeout == 0 {
92 cfg.ReadTimeout = 2 * time.Minute
93 }
94 if cfg.Logf == nil {
95 cfg.Logf = func(string, ...any) {}
96 }
97 return &Relay{cfg: cfg, conns: map[string]*peer{}, window: cfg.Window}, nil
98 }
99 100 // Start dials every peer it can and begins serving their requests. It returns
101 // when ctx ends; connections that fail are logged and not retried here, which
102 // is the supervisor's job.
103 func (r *Relay) Start(ctx context.Context) {
104 var wg sync.WaitGroup
105 for _, addr := range r.cfg.Peers {
106 wg.Add(1)
107 go func(addr string) {
108 defer wg.Done()
109 r.servePeer(ctx, addr)
110 }(addr)
111 }
112 wg.Wait()
113 }
114 115 func (r *Relay) servePeer(ctx context.Context, addr string) {
116 var nc net.Conn
117 var err error
118 if r.cfg.Dial != nil {
119 nc, err = r.cfg.Dial(ctx, addr)
120 } else {
121 var d net.Dialer
122 nc, err = d.DialContext(ctx, "tcp", addr)
123 }
124 if err != nil {
125 r.cfg.Logf("relay: %s: %v", addr, err)
126 return
127 }
128 // The deadline covers the dial and the negotiation, and is cleared once the
129 // peer is live: a peer kept on the dial's clock is a peer that closes
130 // itself after two silent minutes, which is an idle node, not a dead one.
131 _ = nc.SetDeadline(time.Now().Add(r.cfg.ReadTimeout))
132 conn, err := v2peer.Dial(v2peer.Config{
133 Conn: nc, Net: chains.WireMagic(r.cfg.Profile),
134 UserAgent: r.cfg.UserAgent, Services: btcdwire.SFNodeNetwork,
135 V2: r.cfg.V2, Timeout: r.cfg.ReadTimeout, Remote: addr, Logf: r.cfg.Logf,
136 })
137 if err != nil {
138 r.cfg.Logf("relay: %s: %v", addr, err)
139 _ = nc.Close()
140 return
141 }
142 _ = nc.SetDeadline(time.Time{})
143 r.cfg.Logf("relay: %s: connected, %s", addr, conn.Agent())
144 p := &peer{addr: addr, p: conn}
145 r.mu.Lock()
146 r.conns[addr] = p
147 r.mu.Unlock()
148 defer func() {
149 r.mu.Lock()
150 delete(r.conns, addr)
151 r.mu.Unlock()
152 _ = conn.Close()
153 }()
154 r.serveLoop(ctx, p)
155 }
156 157 // serveLoop reads frames and answers the ones that ask for a transaction. A
158 // peer that closes is a peer that closed: it ends this connection and no more.
159 func (r *Relay) serveLoop(ctx context.Context, p *peer) {
160 for {
161 select {
162 case <-ctx.Done():
163 return
164 case msg, ok := <-p.p.Messages():
165 if !ok {
166 if ctx.Err() == nil {
167 r.cfg.Logf("relay: %s: %v", p.addr, p.p.Err())
168 }
169 return
170 }
171 switch m := msg.Message.(type) {
172 case *btcdwire.MsgGetData:
173 r.serveGetData(p, m)
174 case *btcdwire.MsgPing:
175 _ = p.p.Write(btcdwire.NewMsgPong(m.Nonce))
176 }
177 }
178 }
179 }
180 181 // serveGetData answers the transactions a peer asked for, and says which it does
182 // not have, which is what a relayed peer expects rather than silence.
183 func (r *Relay) serveGetData(p *peer, gd *btcdwire.MsgGetData) {
184 for _, inv := range gd.InvList {
185 if inv.Type != btcdwire.InvTypeTx && inv.Type != btcdwire.InvTypeWitnessTx {
186 continue
187 }
188 id := chainhash.Hash(inv.Hash)
189 e, ok := r.window.Get(id)
190 if !ok {
191 nf := &btcdwire.MsgNotFound{}
192 nf.AddInvVect(btcdwire.NewInvVect(inv.Type, &inv.Hash))
193 _ = p.p.Write(nf)
194 continue
195 }
196 // The transaction goes out as the bytes that were relayed, decoded by
197 // the same wire package the peer reads with.
198 var m btcdwire.MsgTx
199 if err := m.Deserialize(bytes.NewReader(e.Raw)); err != nil {
200 r.cfg.Logf("relay: %s: window tx %s does not parse: %v", p.addr, inv.Hash, err)
201 continue
202 }
203 _ = p.p.Write(&m)
204 }
205 }
206 207 // Announce sends the window's txids to every connected peer. It returns how
208 // many peers took the announcement, which is the number of peers a client's
209 // transaction reached, not the number that accepted it.
210 func (r *Relay) Announce(ctx context.Context, ids []chainhash.Hash) (int, error) {
211 if len(ids) == 0 {
212 return 0, nil
213 }
214 inv := &btcwire.Inv{}
215 for _, id := range ids {
216 inv.InvList = append(inv.InvList, btcwire.InvVect{Type: btcwire.InvVectTypeTx, Hash: id})
217 }
218 _ = inv
219 r.mu.Lock()
220 peers := make([]*peer, 0, len(r.conns))
221 for _, p := range r.conns {
222 peers = append(peers, p)
223 }
224 r.mu.Unlock()
225 sent := 0
226 var errs []error
227 var invm btcdwire.MsgInv
228 for _, id := range ids {
229 // The two hash types hold the same bytes; only the display order
230 // differs, so the conversion is a copy and not a reformat.
231 var ch chainhash2.Hash
232 copy(ch[:], id[:])
233 invm.AddInvVect(btcdwire.NewInvVect(btcdwire.InvTypeTx, &ch))
234 }
235 for _, p := range peers {
236 if err := p.p.Write(&invm); err != nil {
237 errs = append(errs, fmt.Errorf("%s: %w", p.addr, err))
238 continue
239 }
240 sent++
241 }
242 return sent, errors.Join(errs...)
243 }
244 245 // Peers is how many relay peers are connected.
246 func (r *Relay) Peers() int {
247 r.mu.Lock()
248 defer r.mu.Unlock()
249 return len(r.conns)
250 }
251 252 // conn is one peer connection: the handshake, a frame writer, and a frame
253 // reader. It is the same wire the filler speaks, with the announcement and
254 // the serve in place of the block request.
255 type conn struct {
256 nc net.Conn
257 r *bufio.Reader
258 magic uint32
259 ua string
260 timeout time.Duration
261 }
262 263 func (c *conn) setDeadline(ctx context.Context) error {
264 d := time.Now().Add(c.timeout)
265 if t, ok := ctx.Deadline(); ok && t.Before(d) {
266 d = t
267 }
268 return c.nc.SetReadDeadline(d)
269 }
270 271 func (c *conn) handshake(lastBlock int32) error {
272 c.r = bufio.NewReaderSize(c.nc, 64*1024)
273 our := &btcwire.Version{
274 ProtocolVersion: 70016,
275 Timestamp: time.Now().Unix(),
276 Nonce: 0x72656c61796c6974,
277 UserAgent: c.ua,
278 LastBlock: lastBlock,
279 }
280 payload, err := our.EncodePayload()
281 if err != nil {
282 return err
283 }
284 if err := c.write(btcwire.CmdVersion, payload); err != nil {
285 return err
286 }
287 var gotVersion, gotVerAck bool
288 _ = c.nc.SetDeadline(time.Now().Add(c.timeout))
289 for !gotVersion || !gotVerAck {
290 cmd, body, err := c.readFrame()
291 if err != nil {
292 return err
293 }
294 switch cmd {
295 case btcwire.CmdVersion:
296 var v btcwire.Version
297 if err := v.DecodePayload(body); err != nil {
298 return err
299 }
300 // relay=1 asks a node to relay transactions to us; the relay
301 // serves what it is asked for either way.
302 gotVersion = true
303 if err := c.write(btcwire.CmdVerAck, nil); err != nil {
304 return err
305 }
306 case btcwire.CmdVerAck:
307 gotVerAck = true
308 case btcwire.CmdPing:
309 var p btcwire.Ping
310 _ = p.DecodePayload(body)
311 if err := c.pong(p.Nonce); err != nil {
312 return err
313 }
314 }
315 }
316 return c.nc.SetDeadline(time.Time{})
317 }
318 319 func (c *conn) pong(nonce uint64) error {
320 payload, err := (&btcwire.Pong{Nonce: nonce}).EncodePayload()
321 if err != nil {
322 return err
323 }
324 return c.write(btcwire.CmdPong, payload)
325 }
326 327 func (c *conn) write(cmd string, payload []byte) error {
328 var magic [4]byte
329 binary.BigEndian.PutUint32(magic[:], c.magic)
330 var header [24]byte
331 copy(header[0:4], magic[:])
332 copy(header[4:16], cmd)
333 binary.LittleEndian.PutUint32(header[16:20], uint32(len(payload)))
334 sum := btcwire.Checksum(payload)
335 copy(header[20:24], sum[:])
336 _ = c.nc.SetWriteDeadline(time.Now().Add(30 * time.Second))
337 buf := make([]byte, 0, 24+len(payload))
338 buf = append(buf, header[:]...)
339 buf = append(buf, payload...)
340 _, err := c.nc.Write(buf)
341 return err
342 }
343 344 func (c *conn) readFrame() (string, []byte, error) {
345 var header [24]byte
346 if _, err := io.ReadFull(c.r, header[:]); err != nil {
347 return "", nil, err
348 }
349 if got := binary.BigEndian.Uint32(header[0:4]); got != c.magic {
350 return "", nil, fmt.Errorf("%w: %#08x", btcwire.ErrBadMagic, got)
351 }
352 cmd := string(header[4:16])
353 for i, ch := range header[4:16] {
354 if ch == 0 {
355 cmd = string(header[4 : 4+i])
356 break
357 }
358 }
359 n := binary.LittleEndian.Uint32(header[16:20])
360 if n > btcwire.MaxPayload {
361 return "", nil, btcwire.ErrPayloadTooLarge
362 }
363 body := make([]byte, n)
364 if _, err := io.ReadFull(c.r, body); err != nil {
365 return "", nil, err
366 }
367 sum := btcwire.Checksum(body)
368 if string(header[20:24]) != string(sum[:]) {
369 return "", nil, btcwire.ErrBadChecksum
370 }
371 return cmd, body, nil
372 }
373 374 // ParseAndCheck is admission: the bytes must parse as a transaction of this
375 // chain's wire form, and nothing else is decided here. It returns the parsed
376 // transaction and its txid.
377 func ParseAndCheck(raw []byte) (*wire.Tx, chainhash.Hash, error) {
378 if len(raw) == 0 {
379 return nil, chainhash.Hash{}, errors.New("relay: empty transaction")
380 }
381 if len(raw) > MaxTxSize {
382 return nil, chainhash.Hash{}, fmt.Errorf("relay: transaction is %d bytes, maximum is %d", len(raw), MaxTxSize)
383 }
384 tx, err := wire.ParseTx(raw)
385 if err != nil {
386 return nil, chainhash.Hash{}, err
387 }
388 return tx, tx.TxID(), nil
389 }
390