import.go raw

   1  package backup
   2  
   3  import (
   4  	"fmt"
   5  
   6  	"git.smesh.lol/nostrino/pkg/btcwire"
   7  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
   8  )
   9  
  10  // Applier is the verified side of a restore: a light client that checks a chunk against the
  11  // chain it already holds before storing it.
  12  //
  13  // It is an interface so the format does not depend on the client, and so the thing that applies
  14  // a chunk is visibly the thing that verifies it. There is no "put without checking" here on
  15  // purpose: a backup is a copy of data somebody already verified, not a licence to skip it.
  16  type Applier interface {
  17  	ApplyHeaders(from uint32, headers []btcwire.BlockHeader) (int, error)
  18  	ApplyFilterHeaders(from uint32, filterHashes, filterHeaders []chainhash.Hash) (int, error)
  19  	ApplyFilters(records []FilterRecord) (int, error)
  20  }
  21  
  22  // ImportChunk verifies a chunk's shape and hands its records to the applier, which verifies them
  23  // against the chain. It returns how many records the store accepted.
  24  func ImportChunk(applier Applier, chunk Chunk) (int, error) {
  25  	if err := chunk.Check(); err != nil {
  26  		return 0, err
  27  	}
  28  
  29  	switch chunk.Kind {
  30  	case Headers:
  31  		headers := make([]btcwire.BlockHeader, 0, chunk.Count)
  32  
  33  		for at := 0; at < len(chunk.Payload); at += HeaderSize {
  34  			var header btcwire.BlockHeader
  35  
  36  			if err := header.Deserialize(chunk.Payload[at : at+HeaderSize]); err != nil {
  37  				return 0, fmt.Errorf("backup: header %d: %w", chunk.From+uint32(len(headers)), err)
  38  			}
  39  
  40  			headers = append(headers, header)
  41  		}
  42  
  43  		return applier.ApplyHeaders(chunk.From, headers)
  44  	case FilterHeaders:
  45  		hashes := make([]chainhash.Hash, 0, chunk.Count)
  46  		headers := make([]chainhash.Hash, 0, chunk.Count)
  47  
  48  		for at := 0; at < len(chunk.Payload); at += FilterHeaderSize {
  49  			var filterHash, filterHeader chainhash.Hash
  50  
  51  			copy(filterHash[:], chunk.Payload[at:])
  52  			copy(filterHeader[:], chunk.Payload[at+32:])
  53  
  54  			hashes = append(hashes, filterHash)
  55  			headers = append(headers, filterHeader)
  56  		}
  57  
  58  		return applier.ApplyFilterHeaders(chunk.From, hashes, headers)
  59  	case Filters:
  60  		records, err := ReadFilters(chunk.Payload)
  61  
  62  		if err != nil {
  63  			return 0, err
  64  		}
  65  
  66  		return applier.ApplyFilters(records)
  67  	}
  68  
  69  	return 0, fmt.Errorf("backup: %s is not a chunk kind", chunk.Kind)
  70  }
  71