main.go raw
1 // Command nostrino-harvest dumps the raw material a forked chain's light client needs: the
2 // headers around the fork and the filter header at the fork boundary.
3 //
4 // It exists because the BLAKE fork reuses Bitcoin's magic, genesis and port, so the ordinary
5 // transport profile reaches its node, but the headers above the fork are a format the client
6 // cannot decode yet. This tool does not need to decode them: it writes the bytes, and it infers
7 // the layout from the payload sizes, which is exactly what a first implementation needs.
8 //
9 // It also folds the compact filter hashes from genesis up to the boundary block, because a
10 // checkpoint pins a filter header and that value cannot be derived from anything smaller.
11 package main
12
13 import (
14 "context"
15 "encoding/hex"
16 "encoding/json"
17 "errors"
18 "flag"
19 "fmt"
20 "net"
21 "os"
22 "path/filepath"
23 "strings"
24 "time"
25
26 "git.smesh.lol/nostrino/pkg/btcwire"
27 "git.smesh.lol/nostrino/pkg/chain"
28 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
29 "git.smesh.lol/nostrino/pkg/discovery"
30 "git.smesh.lol/nostrino/pkg/p2p"
31 "git.smesh.lol/nostrino/pkg/relay"
32 "git.smesh.lol/nostrino/pkg/tunnel"
33 )
34
35 // forkHeaderLen is one version 2 header: the usual 80 bytes plus 84 bytes of fork fields.
36 const forkHeaderLen = 164
37
38 // v1HeaderLen is the Bitcoin header every pre-fork block carries.
39 const v1HeaderLen = 80
40
41 func main() {
42 if err := run(); err != nil {
43 fmt.Fprintln(os.Stderr, "nostrino-harvest:", err)
44 os.Exit(1)
45 }
46 }
47
48 type options struct {
49 relays string
50 gateway string
51 tcp string
52 chainName string
53 transport string
54 out string
55 stopHeight uint
56 fromHash string
57 filterStopHash string
58 filterStop uint
59 wantHeight uint
60 foldOnly bool
61 v2Count int
62 timeout time.Duration
63 verbose bool
64 }
65
66 // report is what the run writes to manifest.json: everything a later test needs to know where a
67 // byte came from.
68 type report struct {
69 Chain string `json:"chain"`
70 Transport string `json:"transport"`
71 Gateway string `json:"gateway"`
72 PeerTip int32 `json:"peer_tip"`
73 PeerUserAgent string `json:"peer_user_agent"`
74 BoundaryHeight uint32 `json:"boundary_height"`
75 PreForkFirst uint32 `json:"pre_fork_first"`
76 PreForkLast uint32 `json:"pre_fork_last"`
77 PreForkHeaders []string `json:"pre_fork_headers"`
78 V2Headers []string `json:"v2_headers"`
79 V2Heights []int32 `json:"v2_heights"`
80 CheckpointHash string `json:"checkpoint_block_hash"`
81 CheckpointFH string `json:"checkpoint_filter_header"`
82 FilterHashes int `json:"filter_hashes_folded"`
83 StopHeight uint32 `json:"stop_height"`
84 FirstBatchBytes int `json:"first_batch_bytes"`
85 }
86
87 func run() error {
88 var o options
89
90 fs := flag.NewFlagSet("nostrino-harvest", flag.ContinueOnError)
91 fs.StringVar(&o.relays, "relay", "", "relay URL; repeat or comma-separate (with no -gateway it discovers)")
92 fs.StringVar(&o.gateway, "gateway", "", "gateway pubkey (with -relay) instead of discovery")
93 fs.StringVar(&o.tcp, "tcp", "", "dial this node directly instead of the tunnel (host:port)")
94 fs.StringVar(&o.chainName, "chain", "blake", "chain the gateway serves (the tunnel's chain name)")
95 fs.StringVar(&o.transport, "transport", "btc", "profile that supplies the P2P magic: the fork reuses Bitcoin's")
96 fs.StringVar(&o.out, "out", "docs/fixtures/blake", "directory to write the harvest into")
97 fs.UintVar(&o.stopHeight, "stop-height", 0, "last pre-fork height (0 = stop at the first v2 header)")
98 fs.StringVar(&o.fromHash, "from-hash", "", "block hash to start from (display order); skips the walk up to it")
99 fs.StringVar(&o.filterStopHash, "filter-stop-hash", "", "fold filter headers up to this block hash and stop")
100 fs.UintVar(&o.filterStop, "filter-stop-height", 0, "height of -filter-stop-hash")
101 fs.UintVar(&o.wantHeight, "want-height", 0, "report the filter header at this height (default the stop height)")
102 fs.IntVar(&o.v2Count, "v2-count", 24, "how many v2 headers to keep after the boundary")
103 fs.DurationVar(&o.timeout, "timeout", 45*time.Minute, "overall timeout")
104 fs.BoolVar(&o.verbose, "v", false, "verbose logging")
105
106 if err := fs.Parse(os.Args[1:]); err != nil {
107 return err
108 }
109
110 ctx, cancel := context.WithTimeout(context.Background(), o.timeout)
111 defer cancel()
112
113 logf := func(string, ...any) {}
114
115 if o.verbose {
116 logf = func(format string, args ...any) {
117 fmt.Fprintf(os.Stderr, "harvest: "+format+"\n", args...)
118 }
119 }
120
121 transport, err := chain.ByName(o.transport)
122
123 if err != nil {
124 return fmt.Errorf("transport profile: %w", err)
125 }
126
127 uri := &tunnel.URI{}
128
129 if o.tcp == "" {
130 var err error
131
132 uri, err = connectionURI(ctx, o)
133
134 if err != nil {
135 return err
136 }
137 }
138
139 logf("chain %s, transport %s, gateway %x, relays %v", o.chainName, transport.Name, uri.Gateway, uri.Relays)
140
141 var conn net.Conn
142
143 if o.tcp != "" {
144 var dialer net.Dialer
145
146 conn, err = dialer.DialContext(ctx, "tcp", o.tcp)
147
148 if err != nil {
149 return fmt.Errorf("tcp %s: %w", o.tcp, err)
150 }
151
152 logf("direct node %s", o.tcp)
153 } else {
154 var key [32]byte
155
156 conn, err = tunnel.Dial(ctx, tunnel.DialConfig{
157 URI: uri,
158 Key: key,
159 Chain: o.chainName,
160 Logf: logf,
161 })
162
163 if err != nil {
164 return fmt.Errorf("tunnel: %w", err)
165 }
166 }
167
168 defer conn.Close()
169
170 peer := p2p.New(conn, p2p.Config{
171 Magic: transport.Magic,
172 UserAgent: "/nostrino-harvest:0.2/",
173 // Core serves compact filters only to a peer that advertises the service, and
174 // disconnects one that asks without it.
175 Services: btcwire.ServiceNodeCompactFilters | btcwire.ServiceNodeWitness,
176 ReadTimeout: 120 * time.Second,
177 Logf: logf,
178 })
179
180 version, err := peer.Handshake(ctx)
181
182 if err != nil {
183 return fmt.Errorf("handshake: %w", err)
184 }
185
186 logf("peer tip %d user %s", version.LastBlock, version.UserAgent)
187
188 rep := report{
189 Chain: o.chainName,
190 Transport: transport.Name,
191 Gateway: fmt.Sprintf("%x", uri.Gateway),
192 PeerTip: version.LastBlock,
193 PeerUserAgent: version.UserAgent,
194 StopHeight: uint32(o.stopHeight),
195 }
196
197 if o.filterStopHash != "" {
198 // A fold-only run: the caller already knows the block hash it wants to anchor on,
199 // which is the only thing the header walk produced.
200 rep.CheckpointHash = o.filterStopHash
201 rep.StopHeight = uint32(o.filterStop)
202 o.foldOnly = true
203 } else if err := harvestHeaders(ctx, peer, transport, o, &rep, logf); err != nil {
204 return err
205 }
206
207 if err := harvestFilterHeaders(ctx, peer, o, &rep, logf); err != nil {
208 return err
209 }
210
211 if err := os.MkdirAll(o.out, 0o755); err != nil {
212 return err
213 }
214
215 out, err := json.MarshalIndent(rep, "", " ")
216
217 if err != nil {
218 return err
219 }
220
221 path := filepath.Join(o.out, "manifest.json")
222
223 if err := os.WriteFile(path, append(out, '\n'), 0o644); err != nil {
224 return err
225 }
226
227 fmt.Println("wrote", path)
228
229 return nil
230 }
231
232 // connectionURI turns the flags into a gateway URI, discovering one from the relay when only a
233 // relay is given. The discovery chain is the chain being served, not the transport profile.
234 func connectionURI(ctx context.Context, o options) (*tunnel.URI, error) {
235 relays := splitList(o.relays)
236
237 if o.gateway != "" {
238 pub, err := parseHex32(o.gateway)
239
240 if err != nil {
241 return nil, err
242 }
243
244 return &tunnel.URI{Gateway: pub, Relays: relays, Version: 1}, nil
245 }
246
247 if len(relays) == 0 {
248 return nil, errors.New("one of -gateway or -relay is required")
249 }
250
251 return discovery.Lookup(ctx, relay.DialTransport, relays, o.chainName, 0)
252 }
253
254 func splitList(value string) []string {
255 var out []string
256
257 for _, part := range strings.Split(value, ",") {
258 if part = strings.TrimSpace(part); part != "" {
259 out = append(out, part)
260 }
261 }
262
263 return out
264 }
265
266 func parseHex32(s string) ([32]byte, error) {
267 var out [32]byte
268
269 b, err := hex.DecodeString(strings.TrimSpace(s))
270
271 if err != nil || len(b) != len(out) {
272 return out, errors.New("pubkey must be 64 hex characters")
273 }
274
275 copy(out[:], b)
276
277 return out, nil
278 }
279
280 // batch is one headers message split into its pre-fork and fork parts.
281 //
282 // Each entry is followed by a zero transaction count, as the protocol requires, so a pre-fork
283 // entry is 81 bytes and a fork entry is 165. The 84 extra fork bytes are what makes the split
284 // solvable: only one number of pre-fork entries makes both parts line up.
285 type batch struct {
286 count int
287 pre [][v1HeaderLen]byte
288 fork [][forkHeaderLen]byte
289 }
290
291 // v1Unit and v2Unit are one entry as it appears in a headers message.
292 const (
293 v1Unit = v1HeaderLen + 1
294 v2Unit = forkHeaderLen + 1
295 )
296
297 // splitBatch reads the count, then decides the layout from the size, because that is the one
298 // thing a decoder that predates the fork can still do correctly.
299 func splitBatch(payload []byte) (*batch, error) {
300 d := btcwire.NewDecoder(payload)
301
302 count, err := d.CompactSize()
303
304 if err != nil {
305 return nil, fmt.Errorf("headers count: %w", err)
306 }
307
308 rest := payload[d.Offset():]
309 out := &batch{count: int(count)}
310
311 pre := out.count
312
313 if len(rest) != v1Unit*out.count {
314 numerator := v2Unit*out.count - len(rest)
315
316 if numerator < 0 || numerator%84 != 0 {
317 return nil, fmt.Errorf("headers payload of %d bytes with count %d is neither all v1 nor a mixed batch",
318 len(rest), out.count)
319 }
320
321 pre = numerator / 84
322
323 if pre < 0 || pre > out.count {
324 return nil, fmt.Errorf("mixed batch has %d v1 entries of %d", pre, out.count)
325 }
326
327 if len(rest) != pre*v1Unit+(out.count-pre)*v2Unit {
328 return nil, fmt.Errorf("mixed batch does not line up")
329 }
330 }
331
332 for i := 0; i < pre; i++ {
333 unit := rest[i*v1Unit : (i+1)*v1Unit]
334
335 if unit[v1HeaderLen] != 0 {
336 return nil, fmt.Errorf("pre-fork entry %d has a non-zero transaction count", i)
337 }
338
339 var h [v1HeaderLen]byte
340 copy(h[:], unit[:v1HeaderLen])
341 out.pre = append(out.pre, h)
342 }
343
344 for i := 0; i < out.count-pre; i++ {
345 off := pre*v1Unit + i*v2Unit
346 unit := rest[off : off+v2Unit]
347
348 if unit[forkHeaderLen] != 0 {
349 return nil, fmt.Errorf("fork entry %d has a non-zero transaction count", i)
350 }
351
352 var h [forkHeaderLen]byte
353 copy(h[:], unit[:forkHeaderLen])
354 out.fork = append(out.fork, h)
355 }
356
357 return out, nil
358 }
359
360 // hashV1 is the block hash of a pre-fork header: SHA256d over its 80 bytes, display order.
361 func hashV1(raw [v1HeaderLen]byte) chainhash.Hash {
362 return chainhash.DoubleHashH(raw[:])
363 }
364
365 // v2Height reads the height a version 2 header carries about itself (int32, wire order).
366 func v2Height(raw [forkHeaderLen]byte) int32 {
367 // version(4) prev(32) merkle(32) time(4) bits(4) nonce(4) nonce2(4) nonce3(4)
368 // extranonce(16) time_offset(4) txcount(2) flags(1) clear_bits(1) xor_key(16) height(4)
369 const off = 4 + 32 + 32 + 4 + 4 + 4 + 4 + 4 + 16 + 4 + 2 + 1 + 1 + 16
370
371 return int32(uint32(raw[off]) | uint32(raw[off+1])<<8 | uint32(raw[off+2])<<16 | uint32(raw[off+3])<<24)
372 }
373
374 // v2Prev reads the previous block hash a version 2 header links to, display order.
375 func v2Prev(raw [forkHeaderLen]byte) chainhash.Hash {
376 var h chainhash.Hash
377
378 // The hash type keeps the wire order, so the link compares directly.
379 copy(h[:], raw[4:36])
380
381 return h
382 }
383
384 func harvestHeaders(ctx context.Context, peer *p2p.Conn, transport *chain.Profile, o options, rep *report, logf func(string, ...any)) error {
385 prev := transport.GenesisHash
386 height := uint32(0)
387 batches := 0
388 boundary := uint32(0)
389
390 if err := os.MkdirAll(o.out, 0o755); err != nil {
391 return err
392 }
393
394 hashes := map[uint32]chainhash.Hash{0: transport.GenesisHash}
395
396 if o.fromHash != "" {
397 start, err := chainhash.NewHashFromStr(o.fromHash)
398
399 if err != nil {
400 return fmt.Errorf("from-hash: %w", err)
401 }
402
403 prev = *start
404 hashes[0] = *start
405 hex0 := start.String()
406 logf("starting from %s", hex0)
407 }
408
409 for {
410 req := &btcwire.GetHeaders{
411 ProtocolVersion: btcwire.ProtocolVersion,
412 LocatorHashes: []chainhash.Hash{prev},
413 }
414
415 if err := peer.Send(btcwire.CmdGetHeaders, req); err != nil {
416 return fmt.Errorf("getheaders: %w", err)
417 }
418
419 msg, err := peer.ReadUntil(ctx, btcwire.CmdHeaders)
420
421 if err != nil {
422 return fmt.Errorf("headers at %d: %w", height, err)
423 }
424
425 sep, err := splitBatch(msg.Payload)
426
427 if err != nil {
428 return fmt.Errorf("headers at %d: %w", height, err)
429 }
430
431 if sep.count == 0 {
432 logf("peer has no headers after %d", height)
433 break
434 }
435
436 if batches == 0 {
437 rep.FirstBatchBytes = len(msg.Payload)
438 }
439
440 batches++
441
442 // Every pre-fork header must link to the previous one; that is the only check this
443 // tool can do and it is enough to know the batch is aligned.
444 for i, raw := range sep.pre {
445 hash := hashV1(raw)
446
447 if i == 0 {
448 if got := v1Prev(raw); got != prev {
449 return fmt.Errorf("pre-fork header %d links to %s, want %s", height+1, got, prev)
450 }
451 }
452
453 height++
454 prev = hash
455 hashes[height] = hash
456 }
457
458 if len(sep.fork) == 0 {
459 logf("headers %d..%d all v1", height-uint32(len(sep.pre))+1, height)
460
461 if len(sep.pre) < btcwire.MaxBlockHeadersPerMsg {
462 return errors.New("peer sent a short all-v1 batch: the fork was not reached")
463 }
464
465 continue
466 }
467
468 // The first fork header must link to the last pre-fork one.
469 if got := v2Prev(sep.fork[0]); got != prev {
470 return fmt.Errorf("first v2 header links to %s, want %s", got, prev)
471 }
472
473 boundary = height + 1
474 rep.BoundaryHeight = boundary
475 rep.PreForkFirst = boundary - uint32(len(sep.pre))
476 rep.PreForkLast = height
477
478 for _, raw := range sep.pre {
479 rep.PreForkHeaders = append(rep.PreForkHeaders, hex.EncodeToString(raw[:]))
480 }
481
482 keep := o.v2Count
483
484 if keep > len(sep.fork) {
485 keep = len(sep.fork)
486 }
487
488 for _, raw := range sep.fork[:keep] {
489 rep.V2Headers = append(rep.V2Headers, hex.EncodeToString(raw[:]))
490 rep.V2Heights = append(rep.V2Heights, v2Height(raw))
491 }
492
493 rep.StopHeight = height
494
495 if stop, ok := hashes[uint32(o.stopHeight)]; ok {
496 rep.CheckpointHash = stop.String()
497 }
498
499 logf("boundary at %d: %d pre-fork + %d v2 headers (kept %d)", boundary, len(sep.pre), len(sep.fork), keep)
500
501 break
502 }
503
504 if rep.BoundaryHeight == 0 {
505 return errors.New("never saw a v2 header")
506 }
507
508 if rep.CheckpointHash == "" {
509 return fmt.Errorf("no hash harvested at the stop height %d", o.stopHeight)
510 }
511
512 return nil
513 }
514
515 // v1Prev reads the previous block hash of an 80-byte header, display order.
516 func v1Prev(raw [v1HeaderLen]byte) chainhash.Hash {
517 var h chainhash.Hash
518
519 copy(h[:], raw[4:36])
520
521 return h
522 }
523
524 func harvestFilterHeaders(ctx context.Context, peer *p2p.Conn, o options, rep *report, logf func(string, ...any)) error {
525 if o.filterStopHash != "" {
526 return foldFilterHeaders(ctx, peer, o.filterStop, o.filterStopHash, o.wantHeight, rep, logf)
527 }
528
529 if o.stopHeight == 0 {
530 return nil
531 }
532
533 parsed, err := chainhash.NewHashFromStr(rep.CheckpointHash)
534
535 if err != nil {
536 return fmt.Errorf("stop hash: %w", err)
537 }
538
539 stopHash := *parsed
540
541 // The server sends the filter hash of the block before the range, so the fold is anchored
542 // on its value, not on a guess about height zero.
543 prev := chainhash.Hash{}
544 height := uint32(0)
545 folded := 0
546
547 stop := uint32(o.stopHeight)
548
549 for height <= stop {
550 req := &btcwire.GetCFHeaders{
551 FilterType: btcwire.FilterTypeBasic,
552 StartHeight: height,
553 StopHash: stopHash,
554 }
555
556 if err := peer.Send(btcwire.CmdGetCFHeaders, req); err != nil {
557 return fmt.Errorf("getcfheaders at %d: %w", height, err)
558 }
559
560 msg, err := peer.ReadUntil(ctx, btcwire.CmdCFHeaders)
561
562 if err != nil {
563 return fmt.Errorf("cfheaders at %d: %w", height, err)
564 }
565
566 var resp btcwire.CFHeaders
567
568 if err := resp.DecodePayload(msg.Payload); err != nil {
569 return fmt.Errorf("cfheaders at %d: %w", height, err)
570 }
571
572 if len(resp.FilterHashes) == 0 {
573 return fmt.Errorf("cfheaders at %d returned nothing", height)
574 }
575
576 if height > 0 && resp.PrevFilterHeader != prev {
577 return fmt.Errorf("cfheaders at %d: previous filter header %s, want %s", height, resp.PrevFilterHeader, prev)
578 }
579
580 prev = resp.PrevFilterHeader
581
582 for _, fh := range resp.FilterHashes {
583 prev = btcwire.FilterHeader(fh, prev)
584 folded++
585 height++
586 }
587
588 if folded%100000 == 0 {
589 logf("filter headers folded to %d", height-1)
590 }
591 }
592
593 // The loop overshoots only by the server's batch size; the checked value is the one at the
594 // stop height, which is the last hash in the range that ends there.
595 if height != stop+1 {
596 logf("cfheaders overshot to %d; recomputing the stop-height value is not possible in one pass", height-1)
597 }
598
599 rep.FilterHashes = folded
600 rep.CheckpointFH = prev.String()
601
602 return nil
603 }
604
605 // foldFilterHeaders walks the compact filter hashes from genesis to stopHeight, because a filter
606 // header is the fold of every filter hash below it and nothing smaller can substitute.
607 func foldFilterHeaders(ctx context.Context, peer *p2p.Conn, stopHeight uint, stopText string, want uint, rep *report, logf func(string, ...any)) error {
608 parsed, err := chainhash.NewHashFromStr(stopText)
609
610 if err != nil {
611 return fmt.Errorf("stop hash: %w", err)
612 }
613
614 stop := uint32(stopHeight)
615
616 var stopHash chainhash.Hash = *parsed
617
618 if want == 0 {
619 want = stopHeight
620 }
621
622 if uint32(want) > stop {
623 return fmt.Errorf("want height %d is above the stop height %d", want, stop)
624 }
625
626 prev := chainhash.Hash{}
627 height := uint32(0)
628 var atWant chainhash.Hash
629
630 for height <= stop {
631 req := &btcwire.GetCFHeaders{
632 FilterType: btcwire.FilterTypeBasic,
633 StartHeight: height,
634 StopHash: stopHash,
635 }
636
637 if err := peer.Send(btcwire.CmdGetCFHeaders, req); err != nil {
638 return fmt.Errorf("getcfheaders at %d: %w", height, err)
639 }
640
641 msg, err := peer.ReadUntil(ctx, btcwire.CmdCFHeaders)
642
643 if err != nil {
644 return fmt.Errorf("cfheaders at %d: %w", height, err)
645 }
646
647 var resp btcwire.CFHeaders
648
649 if err := resp.DecodePayload(msg.Payload); err != nil {
650 return fmt.Errorf("cfheaders at %d: %w", height, err)
651 }
652
653 if len(resp.FilterHashes) == 0 {
654 return fmt.Errorf("cfheaders at %d returned nothing", height)
655 }
656
657 if height > 0 && resp.PrevFilterHeader != prev {
658 return fmt.Errorf("cfheaders at %d: previous filter header %s, want %s", height, resp.PrevFilterHeader, prev)
659 }
660
661 prev = resp.PrevFilterHeader
662
663 for _, fh := range resp.FilterHashes {
664 prev = btcwire.FilterHeader(fh, prev)
665
666 if height == uint32(want) {
667 atWant = prev
668 }
669
670 height++
671 }
672
673 if height%200000 < 2000 {
674 logf("folded to %d", height-1)
675 }
676 }
677
678 if atWant == (chainhash.Hash{}) {
679 return fmt.Errorf("never reached height %d", want)
680 }
681
682 rep.FilterHashes = int(height)
683 rep.CheckpointFH = atWant.String()
684 rep.StopHeight = stop
685
686 return nil
687 }
688