import.go raw

   1  package neutrino
   2  
   3  import (
   4  	"errors"
   5  	"fmt"
   6  
   7  	"git.smesh.lol/nostrino/pkg/btcwire"
   8  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
   9  )
  10  
  11  // This file is the import side of a light client's store: the same checks the network sync
  12  // makes, applied to bytes that came from a backup instead of a peer.
  13  //
  14  // The distinction matters for what a backup is allowed to mean. A backup is a copy of verified
  15  // data, so it may skip the *download*; it may not skip the *verification*, because a file can be
  16  // edited, truncated or assembled by somebody else. Everything here validates before it stores,
  17  // and the errors name the height, so a damaged backup fails at the record that is wrong.
  18  
  19  // ImportBatch bounds how many headers are validated and stored as one run.
  20  //
  21  // It is smaller than a headers message on purpose: the median-time-past and difficulty checks
  22  // read the store, so a header may only be checked against headers already stored. A single
  23  // header at a time would make a million-header import a million store writes; a thousand keeps
  24  // the context gap to a thousandth of the chain instead of a whole message.
  25  const ImportBatch = 1000
  26  
  27  // ApplyHeaders validates a contiguous run of block headers against the stored chain and stores
  28  // it. from is the height of headers[0].
  29  //
  30  // Heights the store already holds are skipped, so importing the same backup twice is a no-op,
  31  // and an import that overlaps the store's tip continues from the tip rather than refusing.
  32  func (c *Client) ApplyHeaders(from uint32, headers []btcwire.BlockHeader) (int, error) {
  33  	if len(headers) == 0 {
  34  		return 0, nil
  35  	}
  36  
  37  	// An import into a fresh store installs the profile's anchor the same way a first sync
  38  	// does: the backup begins above it, and the chain of headers has to start somewhere the
  39  	// operator trusts.
  40  	if err := c.ensureAnchor(); err != nil {
  41  		return 0, err
  42  	}
  43  
  44  	tip, tipHash, ok := c.store.HeaderTip()
  45  
  46  	if !ok {
  47  		return 0, errors.New("neutrino: the store has no anchor to import onto")
  48  	}
  49  
  50  	height := from
  51  	at := 0
  52  
  53  	if height <= tip {
  54  		covered := tip + 1 - height
  55  
  56  		if covered >= uint32(len(headers)) {
  57  			return 0, nil
  58  		}
  59  
  60  		at = int(covered)
  61  		height = tip + 1
  62  	} else if height != tip+1 {
  63  		return 0, fmt.Errorf(
  64  			"neutrino: the import begins at %d but the store ends at %d", height, tip,
  65  		)
  66  	}
  67  
  68  	prev := tipHash
  69  	stored := 0
  70  
  71  	for at < len(headers) {
  72  		size := ImportBatch
  73  
  74  		// The first heights after the tip have no stored context for the median-time-past
  75  		// rule; store them one at a time until there is.
  76  		if height < tip+11 && size > 1 {
  77  			size = 1
  78  		}
  79  
  80  		if at+size > len(headers) {
  81  			size = len(headers) - at
  82  		}
  83  
  84  		for i := at; i < at+size; i++ {
  85  			level := height + uint32(i-at)
  86  
  87  			if err := c.validateHeader(level, &headers[i], prev); err != nil {
  88  				// A checkpoint that is not on this chain shows up here first: the block above
  89  				// it does not link. Naming the checkpoint says which deployment value is
  90  				// wrong, instead of only which header.
  91  				if anchor, ok := c.store.Anchor(); ok && anchor.Height > 0 && level == anchor.Height+1 {
  92  					return stored, fmt.Errorf(
  93  						"neutrino: the checkpoint at %d (%s) is not this chain's block %d: %w",
  94  						anchor.Height, anchor.BlockHash, level, err,
  95  					)
  96  				}
  97  
  98  				return stored, err
  99  			}
 100  
 101  			prev = headers[i].BlockHash()
 102  		}
 103  
 104  		if err := c.store.PutHeaders(height, headers[at:at+size]); err != nil {
 105  			return stored, fmt.Errorf("neutrino: store headers %d..%d: %w",
 106  				height, height+uint32(size)-1, err)
 107  		}
 108  
 109  		stored += size
 110  		at += size
 111  		height += uint32(size)
 112  	}
 113  
 114  	return stored, nil
 115  }
 116  
 117  // ApplyFilterHeaders validates a run of filter hashes and their rolling filter headers against
 118  // the stored chain and stores it. from is the height of hashes[0]; the two slices are parallel.
 119  func (c *Client) ApplyFilterHeaders(from uint32, hashes, headers []chainhash.Hash) (int, error) {
 120  	if len(hashes) != len(headers) {
 121  		return 0, fmt.Errorf("neutrino: %d filter hashes for %d filter headers", len(hashes), len(headers))
 122  	}
 123  
 124  	if len(hashes) == 0 {
 125  		return 0, nil
 126  	}
 127  
 128  	if err := c.ensureAnchor(); err != nil {
 129  		return 0, err
 130  	}
 131  
 132  	tip, _, ok := c.store.HeaderTip()
 133  
 134  	if !ok {
 135  		return 0, errors.New("neutrino: the store has no headers to attach filter headers to")
 136  	}
 137  
 138  	start := from
 139  	at := 0
 140  	prev := chainhash.Hash{}
 141  
 142  	if fTip, fHash, ok := c.store.FilterHeaderTip(); ok {
 143  		if start <= fTip {
 144  			covered := fTip + 1 - start
 145  
 146  			if covered >= uint32(len(hashes)) {
 147  				return 0, nil
 148  			}
 149  
 150  			at = int(covered)
 151  			start = fTip + 1
 152  		} else if start != fTip+1 {
 153  			return 0, fmt.Errorf(
 154  				"neutrino: the filter header import begins at %d but the store ends at %d",
 155  				start, fTip,
 156  			)
 157  		}
 158  
 159  		prev = fHash
 160  	}
 161  
 162  	if start+uint32(len(hashes)-at)-1 > tip {
 163  		return 0, fmt.Errorf(
 164  			"neutrino: filter headers to %d are above the header tip %d",
 165  			start+uint32(len(hashes)-at)-1, tip,
 166  		)
 167  	}
 168  
 169  	stored := 0
 170  
 171  	for at < len(hashes) {
 172  		size := ImportBatch
 173  
 174  		if at+size > len(hashes) {
 175  			size = len(hashes) - at
 176  		}
 177  
 178  		chain := make([]chainhash.Hash, size)
 179  
 180  		for i := 0; i < size; i++ {
 181  			chain[i] = btcwire.FilterHeader(hashes[at+i], prev)
 182  
 183  			if chain[i] != headers[at+i] {
 184  				return stored, fmt.Errorf(
 185  					"neutrino: filter header %d is %s, the filter hash computes %s",
 186  					start+uint32(at+i), headers[at+i], chain[i],
 187  				)
 188  			}
 189  
 190  			prev = chain[i]
 191  		}
 192  
 193  		if err := c.store.PutFilterHeaders(start, hashes[at:at+size], chain); err != nil {
 194  			return stored, fmt.Errorf("neutrino: store filter headers %d..%d: %w",
 195  				start, start+uint32(size)-1, err)
 196  		}
 197  
 198  		stored += size
 199  		at += size
 200  		start += uint32(size)
 201  	}
 202  
 203  	return stored, nil
 204  }
 205  
 206  // FilterProof is one compact filter and the two hashes that place it.
 207  type FilterProof struct {
 208  	// Height is the block it belongs to.
 209  	Height uint32
 210  	// BlockHash is that block's hash.
 211  	BlockHash chainhash.Hash
 212  	// FilterHash is the hash the filter header chain commits to.
 213  	FilterHash chainhash.Hash
 214  	// Filter is the compact filter's bytes.
 215  	Filter []byte
 216  }
 217  
 218  // ApplyFilters verifies compact filters against the stored headers and filter headers and stores
 219  // them. Filters the store already holds are skipped.
 220  //
 221  // A filter is not trusted from a backup: its bytes must hash to the value the filter header
 222  // chain commits to, and its block hash must be the stored header's. That is the same pair of
 223  // checks the network sync makes, for the same reason — the filter is what the wallet matches its
 224  // own scripts against, so a forged one would hide or invent coins.
 225  func (c *Client) ApplyFilters(records []FilterProof) (int, error) {
 226  	if err := c.ensureAnchor(); err != nil {
 227  		return 0, err
 228  	}
 229  
 230  	stored := 0
 231  
 232  	for _, record := range records {
 233  		header, ok := c.store.Header(record.Height)
 234  
 235  		if !ok {
 236  			return stored, fmt.Errorf("neutrino: filter %d has no header", record.Height)
 237  		}
 238  
 239  		if blockHash := header.BlockHash(); blockHash != record.BlockHash {
 240  			return stored, fmt.Errorf(
 241  				"neutrino: filter %d is for block %s, the store has %s",
 242  				record.Height, record.BlockHash, blockHash,
 243  			)
 244  		}
 245  
 246  		committed, ok := c.store.FilterHash(record.Height)
 247  
 248  		if !ok {
 249  			return stored, fmt.Errorf("neutrino: filter %d has no committed filter hash", record.Height)
 250  		}
 251  
 252  		if got := chainhash.DoubleHashH(record.Filter); got != record.FilterHash {
 253  			return stored, fmt.Errorf(
 254  				"neutrino: filter %d hashes to %s, the backup says %s",
 255  				record.Height, got, record.FilterHash,
 256  			)
 257  		}
 258  
 259  		if committed != record.FilterHash {
 260  			return stored, fmt.Errorf(
 261  				"neutrino: filter %d is %s, the filter header commits to %s",
 262  				record.Height, record.FilterHash, committed,
 263  			)
 264  		}
 265  
 266  		if _, already := c.store.Filter(record.Height); already {
 267  			continue
 268  		}
 269  
 270  		if err := c.store.PutFilter(record.Height, record.BlockHash, record.FilterHash, record.Filter); err != nil {
 271  			return stored, fmt.Errorf("neutrino: store filter %d: %w", record.Height, err)
 272  		}
 273  
 274  		stored++
 275  	}
 276  
 277  	return stored, nil
 278  }
 279