package neutrino import ( "errors" "fmt" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // This file is the import side of a light client's store: the same checks the network sync // makes, applied to bytes that came from a backup instead of a peer. // // The distinction matters for what a backup is allowed to mean. A backup is a copy of verified // data, so it may skip the *download*; it may not skip the *verification*, because a file can be // edited, truncated or assembled by somebody else. Everything here validates before it stores, // and the errors name the height, so a damaged backup fails at the record that is wrong. // ImportBatch bounds how many headers are validated and stored as one run. // // It is smaller than a headers message on purpose: the median-time-past and difficulty checks // read the store, so a header may only be checked against headers already stored. A single // header at a time would make a million-header import a million store writes; a thousand keeps // the context gap to a thousandth of the chain instead of a whole message. const ImportBatch = 1000 // ApplyHeaders validates a contiguous run of block headers against the stored chain and stores // it. from is the height of headers[0]. // // Heights the store already holds are skipped, so importing the same backup twice is a no-op, // and an import that overlaps the store's tip continues from the tip rather than refusing. func (c *Client) ApplyHeaders(from uint32, headers []btcwire.BlockHeader) (int, error) { if len(headers) == 0 { return 0, nil } // An import into a fresh store installs the profile's anchor the same way a first sync // does: the backup begins above it, and the chain of headers has to start somewhere the // operator trusts. if err := c.ensureAnchor(); err != nil { return 0, err } tip, tipHash, ok := c.store.HeaderTip() if !ok { return 0, errors.New("neutrino: the store has no anchor to import onto") } height := from at := 0 if height <= tip { covered := tip + 1 - height if covered >= uint32(len(headers)) { return 0, nil } at = int(covered) height = tip + 1 } else if height != tip+1 { return 0, fmt.Errorf( "neutrino: the import begins at %d but the store ends at %d", height, tip, ) } prev := tipHash stored := 0 for at < len(headers) { size := ImportBatch // The first heights after the tip have no stored context for the median-time-past // rule; store them one at a time until there is. if height < tip+11 && size > 1 { size = 1 } if at+size > len(headers) { size = len(headers) - at } for i := at; i < at+size; i++ { level := height + uint32(i-at) if err := c.validateHeader(level, &headers[i], prev); err != nil { // A checkpoint that is not on this chain shows up here first: the block above // it does not link. Naming the checkpoint says which deployment value is // wrong, instead of only which header. if anchor, ok := c.store.Anchor(); ok && anchor.Height > 0 && level == anchor.Height+1 { return stored, fmt.Errorf( "neutrino: the checkpoint at %d (%s) is not this chain's block %d: %w", anchor.Height, anchor.BlockHash, level, err, ) } return stored, err } prev = headers[i].BlockHash() } if err := c.store.PutHeaders(height, headers[at:at+size]); err != nil { return stored, fmt.Errorf("neutrino: store headers %d..%d: %w", height, height+uint32(size)-1, err) } stored += size at += size height += uint32(size) } return stored, nil } // ApplyFilterHeaders validates a run of filter hashes and their rolling filter headers against // the stored chain and stores it. from is the height of hashes[0]; the two slices are parallel. func (c *Client) ApplyFilterHeaders(from uint32, hashes, headers []chainhash.Hash) (int, error) { if len(hashes) != len(headers) { return 0, fmt.Errorf("neutrino: %d filter hashes for %d filter headers", len(hashes), len(headers)) } if len(hashes) == 0 { return 0, nil } if err := c.ensureAnchor(); err != nil { return 0, err } tip, _, ok := c.store.HeaderTip() if !ok { return 0, errors.New("neutrino: the store has no headers to attach filter headers to") } start := from at := 0 prev := chainhash.Hash{} if fTip, fHash, ok := c.store.FilterHeaderTip(); ok { if start <= fTip { covered := fTip + 1 - start if covered >= uint32(len(hashes)) { return 0, nil } at = int(covered) start = fTip + 1 } else if start != fTip+1 { return 0, fmt.Errorf( "neutrino: the filter header import begins at %d but the store ends at %d", start, fTip, ) } prev = fHash } if start+uint32(len(hashes)-at)-1 > tip { return 0, fmt.Errorf( "neutrino: filter headers to %d are above the header tip %d", start+uint32(len(hashes)-at)-1, tip, ) } stored := 0 for at < len(hashes) { size := ImportBatch if at+size > len(hashes) { size = len(hashes) - at } chain := make([]chainhash.Hash, size) for i := 0; i < size; i++ { chain[i] = btcwire.FilterHeader(hashes[at+i], prev) if chain[i] != headers[at+i] { return stored, fmt.Errorf( "neutrino: filter header %d is %s, the filter hash computes %s", start+uint32(at+i), headers[at+i], chain[i], ) } prev = chain[i] } if err := c.store.PutFilterHeaders(start, hashes[at:at+size], chain); err != nil { return stored, fmt.Errorf("neutrino: store filter headers %d..%d: %w", start, start+uint32(size)-1, err) } stored += size at += size start += uint32(size) } return stored, nil } // FilterProof is one compact filter and the two hashes that place it. type FilterProof struct { // Height is the block it belongs to. Height uint32 // BlockHash is that block's hash. BlockHash chainhash.Hash // FilterHash is the hash the filter header chain commits to. FilterHash chainhash.Hash // Filter is the compact filter's bytes. Filter []byte } // ApplyFilters verifies compact filters against the stored headers and filter headers and stores // them. Filters the store already holds are skipped. // // A filter is not trusted from a backup: its bytes must hash to the value the filter header // chain commits to, and its block hash must be the stored header's. That is the same pair of // checks the network sync makes, for the same reason — the filter is what the wallet matches its // own scripts against, so a forged one would hide or invent coins. func (c *Client) ApplyFilters(records []FilterProof) (int, error) { if err := c.ensureAnchor(); err != nil { return 0, err } stored := 0 for _, record := range records { header, ok := c.store.Header(record.Height) if !ok { return stored, fmt.Errorf("neutrino: filter %d has no header", record.Height) } if blockHash := header.BlockHash(); blockHash != record.BlockHash { return stored, fmt.Errorf( "neutrino: filter %d is for block %s, the store has %s", record.Height, record.BlockHash, blockHash, ) } committed, ok := c.store.FilterHash(record.Height) if !ok { return stored, fmt.Errorf("neutrino: filter %d has no committed filter hash", record.Height) } if got := chainhash.DoubleHashH(record.Filter); got != record.FilterHash { return stored, fmt.Errorf( "neutrino: filter %d hashes to %s, the backup says %s", record.Height, got, record.FilterHash, ) } if committed != record.FilterHash { return stored, fmt.Errorf( "neutrino: filter %d is %s, the filter header commits to %s", record.Height, record.FilterHash, committed, ) } if _, already := c.store.Filter(record.Height); already { continue } if err := c.store.PutFilter(record.Height, record.BlockHash, record.FilterHash, record.Filter); err != nil { return stored, fmt.Errorf("neutrino: store filter %d: %w", record.Height, err) } stored++ } return stored, nil }