// Command nostrino-harvest dumps the raw material a forked chain's light client needs: the // headers around the fork and the filter header at the fork boundary. // // It exists because the BLAKE fork reuses Bitcoin's magic, genesis and port, so the ordinary // transport profile reaches its node, but the headers above the fork are a format the client // cannot decode yet. This tool does not need to decode them: it writes the bytes, and it infers // the layout from the payload sizes, which is exactly what a first implementation needs. // // It also folds the compact filter hashes from genesis up to the boundary block, because a // checkpoint pins a filter header and that value cannot be derived from anything smaller. package main import ( "context" "encoding/hex" "encoding/json" "errors" "flag" "fmt" "net" "os" "path/filepath" "strings" "time" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/chain" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/nostrino/pkg/discovery" "git.smesh.lol/nostrino/pkg/p2p" "git.smesh.lol/nostrino/pkg/relay" "git.smesh.lol/nostrino/pkg/tunnel" ) // forkHeaderLen is one version 2 header: the usual 80 bytes plus 84 bytes of fork fields. const forkHeaderLen = 164 // v1HeaderLen is the Bitcoin header every pre-fork block carries. const v1HeaderLen = 80 func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, "nostrino-harvest:", err) os.Exit(1) } } type options struct { relays string gateway string tcp string chainName string transport string out string stopHeight uint fromHash string filterStopHash string filterStop uint wantHeight uint foldOnly bool v2Count int timeout time.Duration verbose bool } // report is what the run writes to manifest.json: everything a later test needs to know where a // byte came from. type report struct { Chain string `json:"chain"` Transport string `json:"transport"` Gateway string `json:"gateway"` PeerTip int32 `json:"peer_tip"` PeerUserAgent string `json:"peer_user_agent"` BoundaryHeight uint32 `json:"boundary_height"` PreForkFirst uint32 `json:"pre_fork_first"` PreForkLast uint32 `json:"pre_fork_last"` PreForkHeaders []string `json:"pre_fork_headers"` V2Headers []string `json:"v2_headers"` V2Heights []int32 `json:"v2_heights"` CheckpointHash string `json:"checkpoint_block_hash"` CheckpointFH string `json:"checkpoint_filter_header"` FilterHashes int `json:"filter_hashes_folded"` StopHeight uint32 `json:"stop_height"` FirstBatchBytes int `json:"first_batch_bytes"` } func run() error { var o options fs := flag.NewFlagSet("nostrino-harvest", flag.ContinueOnError) fs.StringVar(&o.relays, "relay", "", "relay URL; repeat or comma-separate (with no -gateway it discovers)") fs.StringVar(&o.gateway, "gateway", "", "gateway pubkey (with -relay) instead of discovery") fs.StringVar(&o.tcp, "tcp", "", "dial this node directly instead of the tunnel (host:port)") fs.StringVar(&o.chainName, "chain", "blake", "chain the gateway serves (the tunnel's chain name)") fs.StringVar(&o.transport, "transport", "btc", "profile that supplies the P2P magic: the fork reuses Bitcoin's") fs.StringVar(&o.out, "out", "docs/fixtures/blake", "directory to write the harvest into") fs.UintVar(&o.stopHeight, "stop-height", 0, "last pre-fork height (0 = stop at the first v2 header)") fs.StringVar(&o.fromHash, "from-hash", "", "block hash to start from (display order); skips the walk up to it") fs.StringVar(&o.filterStopHash, "filter-stop-hash", "", "fold filter headers up to this block hash and stop") fs.UintVar(&o.filterStop, "filter-stop-height", 0, "height of -filter-stop-hash") fs.UintVar(&o.wantHeight, "want-height", 0, "report the filter header at this height (default the stop height)") fs.IntVar(&o.v2Count, "v2-count", 24, "how many v2 headers to keep after the boundary") fs.DurationVar(&o.timeout, "timeout", 45*time.Minute, "overall timeout") fs.BoolVar(&o.verbose, "v", false, "verbose logging") if err := fs.Parse(os.Args[1:]); err != nil { return err } ctx, cancel := context.WithTimeout(context.Background(), o.timeout) defer cancel() logf := func(string, ...any) {} if o.verbose { logf = func(format string, args ...any) { fmt.Fprintf(os.Stderr, "harvest: "+format+"\n", args...) } } transport, err := chain.ByName(o.transport) if err != nil { return fmt.Errorf("transport profile: %w", err) } uri := &tunnel.URI{} if o.tcp == "" { var err error uri, err = connectionURI(ctx, o) if err != nil { return err } } logf("chain %s, transport %s, gateway %x, relays %v", o.chainName, transport.Name, uri.Gateway, uri.Relays) var conn net.Conn if o.tcp != "" { var dialer net.Dialer conn, err = dialer.DialContext(ctx, "tcp", o.tcp) if err != nil { return fmt.Errorf("tcp %s: %w", o.tcp, err) } logf("direct node %s", o.tcp) } else { var key [32]byte conn, err = tunnel.Dial(ctx, tunnel.DialConfig{ URI: uri, Key: key, Chain: o.chainName, Logf: logf, }) if err != nil { return fmt.Errorf("tunnel: %w", err) } } defer conn.Close() peer := p2p.New(conn, p2p.Config{ Magic: transport.Magic, UserAgent: "/nostrino-harvest:0.2/", // Core serves compact filters only to a peer that advertises the service, and // disconnects one that asks without it. Services: btcwire.ServiceNodeCompactFilters | btcwire.ServiceNodeWitness, ReadTimeout: 120 * time.Second, Logf: logf, }) version, err := peer.Handshake(ctx) if err != nil { return fmt.Errorf("handshake: %w", err) } logf("peer tip %d user %s", version.LastBlock, version.UserAgent) rep := report{ Chain: o.chainName, Transport: transport.Name, Gateway: fmt.Sprintf("%x", uri.Gateway), PeerTip: version.LastBlock, PeerUserAgent: version.UserAgent, StopHeight: uint32(o.stopHeight), } if o.filterStopHash != "" { // A fold-only run: the caller already knows the block hash it wants to anchor on, // which is the only thing the header walk produced. rep.CheckpointHash = o.filterStopHash rep.StopHeight = uint32(o.filterStop) o.foldOnly = true } else if err := harvestHeaders(ctx, peer, transport, o, &rep, logf); err != nil { return err } if err := harvestFilterHeaders(ctx, peer, o, &rep, logf); err != nil { return err } if err := os.MkdirAll(o.out, 0o755); err != nil { return err } out, err := json.MarshalIndent(rep, "", " ") if err != nil { return err } path := filepath.Join(o.out, "manifest.json") if err := os.WriteFile(path, append(out, '\n'), 0o644); err != nil { return err } fmt.Println("wrote", path) return nil } // connectionURI turns the flags into a gateway URI, discovering one from the relay when only a // relay is given. The discovery chain is the chain being served, not the transport profile. func connectionURI(ctx context.Context, o options) (*tunnel.URI, error) { relays := splitList(o.relays) if o.gateway != "" { pub, err := parseHex32(o.gateway) if err != nil { return nil, err } return &tunnel.URI{Gateway: pub, Relays: relays, Version: 1}, nil } if len(relays) == 0 { return nil, errors.New("one of -gateway or -relay is required") } return discovery.Lookup(ctx, relay.DialTransport, relays, o.chainName, 0) } func splitList(value string) []string { var out []string for _, part := range strings.Split(value, ",") { if part = strings.TrimSpace(part); part != "" { out = append(out, part) } } return out } func parseHex32(s string) ([32]byte, error) { var out [32]byte b, err := hex.DecodeString(strings.TrimSpace(s)) if err != nil || len(b) != len(out) { return out, errors.New("pubkey must be 64 hex characters") } copy(out[:], b) return out, nil } // batch is one headers message split into its pre-fork and fork parts. // // Each entry is followed by a zero transaction count, as the protocol requires, so a pre-fork // entry is 81 bytes and a fork entry is 165. The 84 extra fork bytes are what makes the split // solvable: only one number of pre-fork entries makes both parts line up. type batch struct { count int pre [][v1HeaderLen]byte fork [][forkHeaderLen]byte } // v1Unit and v2Unit are one entry as it appears in a headers message. const ( v1Unit = v1HeaderLen + 1 v2Unit = forkHeaderLen + 1 ) // splitBatch reads the count, then decides the layout from the size, because that is the one // thing a decoder that predates the fork can still do correctly. func splitBatch(payload []byte) (*batch, error) { d := btcwire.NewDecoder(payload) count, err := d.CompactSize() if err != nil { return nil, fmt.Errorf("headers count: %w", err) } rest := payload[d.Offset():] out := &batch{count: int(count)} pre := out.count if len(rest) != v1Unit*out.count { numerator := v2Unit*out.count - len(rest) if numerator < 0 || numerator%84 != 0 { return nil, fmt.Errorf("headers payload of %d bytes with count %d is neither all v1 nor a mixed batch", len(rest), out.count) } pre = numerator / 84 if pre < 0 || pre > out.count { return nil, fmt.Errorf("mixed batch has %d v1 entries of %d", pre, out.count) } if len(rest) != pre*v1Unit+(out.count-pre)*v2Unit { return nil, fmt.Errorf("mixed batch does not line up") } } for i := 0; i < pre; i++ { unit := rest[i*v1Unit : (i+1)*v1Unit] if unit[v1HeaderLen] != 0 { return nil, fmt.Errorf("pre-fork entry %d has a non-zero transaction count", i) } var h [v1HeaderLen]byte copy(h[:], unit[:v1HeaderLen]) out.pre = append(out.pre, h) } for i := 0; i < out.count-pre; i++ { off := pre*v1Unit + i*v2Unit unit := rest[off : off+v2Unit] if unit[forkHeaderLen] != 0 { return nil, fmt.Errorf("fork entry %d has a non-zero transaction count", i) } var h [forkHeaderLen]byte copy(h[:], unit[:forkHeaderLen]) out.fork = append(out.fork, h) } return out, nil } // hashV1 is the block hash of a pre-fork header: SHA256d over its 80 bytes, display order. func hashV1(raw [v1HeaderLen]byte) chainhash.Hash { return chainhash.DoubleHashH(raw[:]) } // v2Height reads the height a version 2 header carries about itself (int32, wire order). func v2Height(raw [forkHeaderLen]byte) int32 { // version(4) prev(32) merkle(32) time(4) bits(4) nonce(4) nonce2(4) nonce3(4) // extranonce(16) time_offset(4) txcount(2) flags(1) clear_bits(1) xor_key(16) height(4) const off = 4 + 32 + 32 + 4 + 4 + 4 + 4 + 4 + 16 + 4 + 2 + 1 + 1 + 16 return int32(uint32(raw[off]) | uint32(raw[off+1])<<8 | uint32(raw[off+2])<<16 | uint32(raw[off+3])<<24) } // v2Prev reads the previous block hash a version 2 header links to, display order. func v2Prev(raw [forkHeaderLen]byte) chainhash.Hash { var h chainhash.Hash // The hash type keeps the wire order, so the link compares directly. copy(h[:], raw[4:36]) return h } func harvestHeaders(ctx context.Context, peer *p2p.Conn, transport *chain.Profile, o options, rep *report, logf func(string, ...any)) error { prev := transport.GenesisHash height := uint32(0) batches := 0 boundary := uint32(0) if err := os.MkdirAll(o.out, 0o755); err != nil { return err } hashes := map[uint32]chainhash.Hash{0: transport.GenesisHash} if o.fromHash != "" { start, err := chainhash.NewHashFromStr(o.fromHash) if err != nil { return fmt.Errorf("from-hash: %w", err) } prev = *start hashes[0] = *start hex0 := start.String() logf("starting from %s", hex0) } for { req := &btcwire.GetHeaders{ ProtocolVersion: btcwire.ProtocolVersion, LocatorHashes: []chainhash.Hash{prev}, } if err := peer.Send(btcwire.CmdGetHeaders, req); err != nil { return fmt.Errorf("getheaders: %w", err) } msg, err := peer.ReadUntil(ctx, btcwire.CmdHeaders) if err != nil { return fmt.Errorf("headers at %d: %w", height, err) } sep, err := splitBatch(msg.Payload) if err != nil { return fmt.Errorf("headers at %d: %w", height, err) } if sep.count == 0 { logf("peer has no headers after %d", height) break } if batches == 0 { rep.FirstBatchBytes = len(msg.Payload) } batches++ // Every pre-fork header must link to the previous one; that is the only check this // tool can do and it is enough to know the batch is aligned. for i, raw := range sep.pre { hash := hashV1(raw) if i == 0 { if got := v1Prev(raw); got != prev { return fmt.Errorf("pre-fork header %d links to %s, want %s", height+1, got, prev) } } height++ prev = hash hashes[height] = hash } if len(sep.fork) == 0 { logf("headers %d..%d all v1", height-uint32(len(sep.pre))+1, height) if len(sep.pre) < btcwire.MaxBlockHeadersPerMsg { return errors.New("peer sent a short all-v1 batch: the fork was not reached") } continue } // The first fork header must link to the last pre-fork one. if got := v2Prev(sep.fork[0]); got != prev { return fmt.Errorf("first v2 header links to %s, want %s", got, prev) } boundary = height + 1 rep.BoundaryHeight = boundary rep.PreForkFirst = boundary - uint32(len(sep.pre)) rep.PreForkLast = height for _, raw := range sep.pre { rep.PreForkHeaders = append(rep.PreForkHeaders, hex.EncodeToString(raw[:])) } keep := o.v2Count if keep > len(sep.fork) { keep = len(sep.fork) } for _, raw := range sep.fork[:keep] { rep.V2Headers = append(rep.V2Headers, hex.EncodeToString(raw[:])) rep.V2Heights = append(rep.V2Heights, v2Height(raw)) } rep.StopHeight = height if stop, ok := hashes[uint32(o.stopHeight)]; ok { rep.CheckpointHash = stop.String() } logf("boundary at %d: %d pre-fork + %d v2 headers (kept %d)", boundary, len(sep.pre), len(sep.fork), keep) break } if rep.BoundaryHeight == 0 { return errors.New("never saw a v2 header") } if rep.CheckpointHash == "" { return fmt.Errorf("no hash harvested at the stop height %d", o.stopHeight) } return nil } // v1Prev reads the previous block hash of an 80-byte header, display order. func v1Prev(raw [v1HeaderLen]byte) chainhash.Hash { var h chainhash.Hash copy(h[:], raw[4:36]) return h } func harvestFilterHeaders(ctx context.Context, peer *p2p.Conn, o options, rep *report, logf func(string, ...any)) error { if o.filterStopHash != "" { return foldFilterHeaders(ctx, peer, o.filterStop, o.filterStopHash, o.wantHeight, rep, logf) } if o.stopHeight == 0 { return nil } parsed, err := chainhash.NewHashFromStr(rep.CheckpointHash) if err != nil { return fmt.Errorf("stop hash: %w", err) } stopHash := *parsed // The server sends the filter hash of the block before the range, so the fold is anchored // on its value, not on a guess about height zero. prev := chainhash.Hash{} height := uint32(0) folded := 0 stop := uint32(o.stopHeight) for height <= stop { req := &btcwire.GetCFHeaders{ FilterType: btcwire.FilterTypeBasic, StartHeight: height, StopHash: stopHash, } if err := peer.Send(btcwire.CmdGetCFHeaders, req); err != nil { return fmt.Errorf("getcfheaders at %d: %w", height, err) } msg, err := peer.ReadUntil(ctx, btcwire.CmdCFHeaders) if err != nil { return fmt.Errorf("cfheaders at %d: %w", height, err) } var resp btcwire.CFHeaders if err := resp.DecodePayload(msg.Payload); err != nil { return fmt.Errorf("cfheaders at %d: %w", height, err) } if len(resp.FilterHashes) == 0 { return fmt.Errorf("cfheaders at %d returned nothing", height) } if height > 0 && resp.PrevFilterHeader != prev { return fmt.Errorf("cfheaders at %d: previous filter header %s, want %s", height, resp.PrevFilterHeader, prev) } prev = resp.PrevFilterHeader for _, fh := range resp.FilterHashes { prev = btcwire.FilterHeader(fh, prev) folded++ height++ } if folded%100000 == 0 { logf("filter headers folded to %d", height-1) } } // The loop overshoots only by the server's batch size; the checked value is the one at the // stop height, which is the last hash in the range that ends there. if height != stop+1 { logf("cfheaders overshot to %d; recomputing the stop-height value is not possible in one pass", height-1) } rep.FilterHashes = folded rep.CheckpointFH = prev.String() return nil } // foldFilterHeaders walks the compact filter hashes from genesis to stopHeight, because a filter // header is the fold of every filter hash below it and nothing smaller can substitute. func foldFilterHeaders(ctx context.Context, peer *p2p.Conn, stopHeight uint, stopText string, want uint, rep *report, logf func(string, ...any)) error { parsed, err := chainhash.NewHashFromStr(stopText) if err != nil { return fmt.Errorf("stop hash: %w", err) } stop := uint32(stopHeight) var stopHash chainhash.Hash = *parsed if want == 0 { want = stopHeight } if uint32(want) > stop { return fmt.Errorf("want height %d is above the stop height %d", want, stop) } prev := chainhash.Hash{} height := uint32(0) var atWant chainhash.Hash for height <= stop { req := &btcwire.GetCFHeaders{ FilterType: btcwire.FilterTypeBasic, StartHeight: height, StopHash: stopHash, } if err := peer.Send(btcwire.CmdGetCFHeaders, req); err != nil { return fmt.Errorf("getcfheaders at %d: %w", height, err) } msg, err := peer.ReadUntil(ctx, btcwire.CmdCFHeaders) if err != nil { return fmt.Errorf("cfheaders at %d: %w", height, err) } var resp btcwire.CFHeaders if err := resp.DecodePayload(msg.Payload); err != nil { return fmt.Errorf("cfheaders at %d: %w", height, err) } if len(resp.FilterHashes) == 0 { return fmt.Errorf("cfheaders at %d returned nothing", height) } if height > 0 && resp.PrevFilterHeader != prev { return fmt.Errorf("cfheaders at %d: previous filter header %s, want %s", height, resp.PrevFilterHeader, prev) } prev = resp.PrevFilterHeader for _, fh := range resp.FilterHashes { prev = btcwire.FilterHeader(fh, prev) if height == uint32(want) { atWant = prev } height++ } if height%200000 < 2000 { logf("folded to %d", height-1) } } if atWant == (chainhash.Hash{}) { return fmt.Errorf("never reached height %d", want) } rep.FilterHashes = int(height) rep.CheckpointFH = atWant.String() rep.StopHeight = stop return nil }