package fetch import ( "context" "encoding/binary" "encoding/json" "errors" "fmt" "os" "path/filepath" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/utxo" utxostore "git.smesh.lol/btcd-lite/internal/utxo/store" ) // UTXOSnapshot is one boundary of a checkpoint chain as the service lists it, // with the name of the set at that height. type UTXOSnapshot struct { Height uint32 `json:"height"` Name string `json:"name,omitempty"` } // UTXOManifest is the checkpoint chain a service lists. type UTXOManifest struct { Chain string `json:"chain"` Base uint32 `json:"base"` Tip uint32 `json:"tip"` Interval uint32 `json:"interval"` Snapshots []UTXOSnapshot `json:"snapshots"` } // DiffsPerRequest is how many per-block diffs one request carries. It is the // chunk of a hundred the plan names. const DiffsPerRequest = 100 // UTXO fetches one chain's checkpoint chain into dir and returns how many // snapshots it reached, counting the base. // // It fetches the base set, then the per-block diffs in chunks, applying each one // and writing the set at every snapshot height. The names it computes are // checked against the manifest's, so a diff the server got wrong is caught at // the next boundary rather than trusted. // // The set is held in memory between snapshots. That is the bound on this side of // the contract: a client that wants a height between two snapshots applies at // most one epoch's diffs, and an epoch of a large chain's set is not small. func (c *Client) UTXO(ctx context.Context, chainName, dir string) (int, error) { urlBase := c.Base + "/v1/utxo/" + chainName body, err := c.get(ctx, urlBase+"/manifest") if err != nil { return 0, err } var m UTXOManifest if err := json.Unmarshal(body, &m); err != nil { return 0, fmt.Errorf("fetch: utxo manifest: %w", err) } if len(m.Snapshots) == 0 { return 0, errors.New("fetch: the manifest lists no snapshots") } if err := os.MkdirAll(dir, 0o755); err != nil { return 0, err } base := m.Snapshots[0] raw, err := c.get(ctx, fmt.Sprintf("%s/snapshot/%d", urlBase, base.Height)) if err != nil { return 0, err } if base.Name != "" { if got := chainhash.DoubleHashH(raw).String(); got != base.Name { return 0, fmt.Errorf("fetch: the base set hashes to %s, the manifest says %s", got, base.Name) } } if len(raw)%utxostore.EntrySize != 0 { return 0, fmt.Errorf("fetch: the base set is %d bytes, not a whole number of entries", len(raw)) } set := decodeEntries(raw) if err := os.WriteFile(filepath.Join(dir, utxostore.SetFile(base.Height)), raw, 0o644); err != nil { return 0, err } reached := 1 // One epoch at a time, in chunks of a hundred diffs: a run cannot cross a // snapshot, and the snapshot is where the name is checked. for i := 1; i < len(m.Snapshots); i++ { prev, next := m.Snapshots[i-1], m.Snapshots[i] for from := prev.Height + 1; from <= next.Height; from += DiffsPerRequest { to := min(from+DiffsPerRequest, next.Height+1) run, err := c.get(ctx, fmt.Sprintf("%s/diffs/%d-%d", urlBase, from, to)) if err != nil { return reached, err } if set, err = applyRun(set, run); err != nil { return reached, err } } got := utxostore.NameOf(set) if next.Name != "" && got.String() != next.Name { return reached, fmt.Errorf("fetch: the set at %d hashes to %s, the manifest says %s", next.Height, got, next.Name) } if _, err := utxostore.WriteSetFile(dir, next.Height, set); err != nil { return reached, err } reached++ } return reached, nil } // applyRun applies one run of length-prefixed per-block diffs to a set. func applyRun(set []utxo.Entry, run []byte) ([]utxo.Entry, error) { at := 0 for at < len(run) { if at+4 > len(run) { return nil, errors.New("fetch: a diff length runs past its run") } n := int(binary.LittleEndian.Uint32(run[at:])) if at+4+n > len(run) { return nil, fmt.Errorf("fetch: a diff of %d bytes runs past its run", n) } d, err := utxo.DecodeDiff(run[at+4 : at+4+n]) if err != nil { return nil, fmt.Errorf("fetch: diff at %d: %w", at, err) } at += 4 + n if set, err = d.ApplyTo(set); err != nil { return nil, fmt.Errorf("fetch: diff %d..%d: %w", d.From, d.To, err) } } return set, nil } // decodeEntries reads a set file's entries. func decodeEntries(raw []byte) []utxo.Entry { out := make([]utxo.Entry, 0, len(raw)/utxostore.EntrySize) buf := make([]byte, utxostore.EntrySize) for i := 0; i+utxostore.EntrySize <= len(raw); i += utxostore.EntrySize { copy(buf, raw[i:i+utxostore.EntrySize]) out = append(out, utxo.Decode(buf)) } return out }