chunk.go raw

   1  // Package chunk defines the content-addressed artifacts the service serves,
   2  // and the chunker that cuts a range into them.
   3  //
   4  // A chunk is bytes with a name: double SHA-256 of its content. Two instances
   5  // holding the same bytes produce the same name, so a client checks a download
   6  // against the name it asked for, and a serving instance is never trusted for
   7  // more than withholding.
   8  //
   9  // Cutting is deterministic. A range [from,to) of a kind is cut by the same
  10  // rules on every instance, so the same range gives the same boundaries and the
  11  // same hashes, and a chunk a client has from one instance is a chunk the other
  12  // instance will recognise.
  13  package chunk
  14  
  15  import (
  16  	"crypto/sha256"
  17  	"encoding/binary"
  18  	"errors"
  19  	"fmt"
  20  
  21  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  22  )
  23  
  24  // Kind is what a chunk carries.
  25  type Kind uint8
  26  
  27  const (
  28  	// Headers is a run of raw headers for one chain, 80 or 164 bytes each.
  29  	Headers Kind = 1
  30  	// FilterHeaders is a run of filter hashes and their folded filter headers.
  31  	FilterHeaders Kind = 2
  32  	// Filters is a run of BIP158 filters, each length-prefixed.
  33  	Filters Kind = 3
  34  	// Blocks is a run of raw blocks in height order, each length-prefixed.
  35  	Blocks Kind = 4
  36  	// UTXODiff is one checkpoint diff: from, to, touches.
  37  	UTXODiff Kind = 5
  38  	// UTXOBase is a full canonical set at one height, length-prefixed entries.
  39  	UTXOBase Kind = 6
  40  	// UTXOKnown is a known set for a branch range: the created and spent
  41  	// bitvectors.
  42  	UTXOKnown Kind = 7
  43  )
  44  
  45  // String names a kind as the HTTP paths and manifests do.
  46  func (k Kind) String() string {
  47  	switch k {
  48  	case Headers:
  49  		return "hdrs"
  50  	case FilterHeaders:
  51  		return "fh"
  52  	case Filters:
  53  		return "flt"
  54  	case Blocks:
  55  		return "blk"
  56  	case UTXODiff:
  57  		return "utxo.diff"
  58  	case UTXOBase:
  59  		return "utxo.base"
  60  	case UTXOKnown:
  61  		return "utxo.known"
  62  	}
  63  	return fmt.Sprintf("unknown(%d)", uint8(k))
  64  }
  65  
  66  // ParseKind is String's inverse.
  67  func ParseKind(s string) (Kind, bool) {
  68  	for k := Headers; k <= UTXOKnown; k++ {
  69  		if k.String() == s {
  70  			return k, true
  71  		}
  72  	}
  73  	return 0, false
  74  }
  75  
  76  // Name is a chunk's content address: double SHA-256 of its bytes.
  77  func Name(raw []byte) chainhash.Hash { return chainhash.DoubleHashH(raw) }
  78  
  79  // Chunk is one artifact.
  80  type Chunk struct {
  81  	Kind  Kind
  82  	Chain string // "btc", "xbt", or empty for a chain-neutral kind
  83  	From  uint32
  84  	To    uint32
  85  	Raw   []byte
  86  }
  87  
  88  // Name is the chunk's content address.
  89  func (c Chunk) Name() chainhash.Hash { return Name(c.Raw) }
  90  
  91  // header carries what a chunk's index needs without its bytes.
  92  //
  93  // A chunk's bytes are what the manifest hashes; its header names the range and
  94  // the kind so an index can answer "which chunks cover 100..200" without
  95  // reading a byte of them.
  96  type header struct {
  97  	Kind  Kind
  98  	From  uint32
  99  	To    uint32
 100  	Len   uint32
 101  	Chain [4]byte
 102  }
 103  
 104  // EncodeHeader writes a 21-byte chunk header.
 105  func EncodeHeader(c Chunk) []byte {
 106  	b := make([]byte, 0, 21)
 107  	b = append(b, byte(c.Kind))
 108  	b = binary.LittleEndian.AppendUint32(b, c.From)
 109  	b = binary.LittleEndian.AppendUint32(b, c.To)
 110  	b = binary.LittleEndian.AppendUint32(b, uint32(len(c.Raw)))
 111  	var ch [4]byte
 112  	copy(ch[:], c.Chain)
 113  	b = append(b, ch[:]...)
 114  	return b
 115  }
 116  
 117  // ErrShortHeader is a chunk header that does not have its 21 bytes.
 118  var ErrShortHeader = errors.New("chunk: header is short")
 119  
 120  // DecodeHeader reads a chunk header.
 121  func DecodeHeader(b []byte) (Kind, uint32, uint32, uint32, string, error) {
 122  	if len(b) < 21 {
 123  		return 0, 0, 0, 0, "", ErrShortHeader
 124  	}
 125  	kind := Kind(b[0])
 126  	from := binary.LittleEndian.Uint32(b[1:5])
 127  	to := binary.LittleEndian.Uint32(b[5:9])
 128  	n := binary.LittleEndian.Uint32(b[9:13])
 129  	var ch [4]byte
 130  	copy(ch[:], b[13:17])
 131  	return kind, from, to, n, string(ch[:]), nil
 132  }
 133  
 134  // Recorder is where cuts go.
 135  type Recorder func(c Chunk) error
 136  
 137  // CutHeaders splits a header stream into chunks of at most step headers each.
 138  // A 164-byte header makes a 10,000-header chunk 1.6 MB, which is the plan's
 139  // budget.
 140  func CutHeaders(chain string, raw []byte, headerSize int, from uint32, perChunk int, rec Recorder) (int, error) {
 141  	if headerSize != 80 && headerSize != 164 {
 142  		return 0, fmt.Errorf("chunk: header size %d", headerSize)
 143  	}
 144  	if len(raw)%headerSize != 0 {
 145  		return 0, fmt.Errorf("chunk: %d bytes is not a whole number of %d-byte headers", len(raw), headerSize)
 146  	}
 147  	n := len(raw) / headerSize
 148  	perChunk = max(perChunk, 1)
 149  	count := 0
 150  	for i := 0; i < n; i += perChunk {
 151  		end := min(i+perChunk, n)
 152  		c := Chunk{Kind: Headers, Chain: chain, From: from + uint32(i), To: from + uint32(end),
 153  			Raw: raw[i*headerSize : end*headerSize]}
 154  		if err := rec(c); err != nil {
 155  			return count, err
 156  		}
 157  		count++
 158  	}
 159  	return count, nil
 160  }
 161  
 162  // CutLengthPrefixed splits a stream of var-length records (a u32 length then
 163  // the record) into chunks of at most budget bytes, or maxRecords records.
 164  //
 165  // It is the cutter for filters, filter headers in pairs, and blocks: the
 166  // records are opaque and only their boundaries matter.
 167  func CutLengthPrefixed(chain string, kind Kind, raw []byte, from uint32, budget int64, maxRecords int, rec Recorder) (int, error) {
 168  	at := 0
 169  	height := from
 170  	count := 0
 171  	for at < len(raw) {
 172  		start := at
 173  		startHeight := height
 174  		records := 0
 175  		for at < len(raw) {
 176  			if at+4 > len(raw) {
 177  				return count, errors.New("chunk: a length prefix runs past the stream")
 178  			}
 179  			n := int(binary.LittleEndian.Uint32(raw[at : at+4]))
 180  			if n < 0 || at+4+n > len(raw) {
 181  				return count, fmt.Errorf("chunk: a record of %d bytes runs past the stream", n)
 182  			}
 183  			next := at + 4 + n
 184  			if records > 0 && (next-start > int(budget) || records >= maxRecords) {
 185  				break
 186  			}
 187  			at = next
 188  			records++
 189  			height++
 190  		}
 191  		if records == 0 {
 192  			return count, errors.New("chunk: a record larger than a whole chunk")
 193  		}
 194  		c := Chunk{Kind: kind, Chain: chain, From: startHeight, To: startHeight + uint32(records),
 195  			Raw: raw[start:at]}
 196  		if err := rec(c); err != nil {
 197  			return count, err
 198  		}
 199  		count++
 200  	}
 201  	return count, nil
 202  }
 203  
 204  // PackLengthPrefixed is the inverse of the cut: it prefixes each record with
 205  // its length.
 206  func PackLengthPrefixed(records [][]byte) []byte {
 207  	var out []byte
 208  	for _, r := range records {
 209  		out = binary.LittleEndian.AppendUint32(out, uint32(len(r)))
 210  		out = append(out, r...)
 211  	}
 212  	return out
 213  }
 214  
 215  // Sum is a compact summary of a chunk's bytes, for a manifest that lists many.
 216  func Sum(raw []byte) [8]byte {
 217  	sum := sha256.Sum256(raw)
 218  	var out [8]byte
 219  	copy(out[:], sum[:8])
 220  	return out
 221  }
 222