// Package chunk defines the content-addressed artifacts the service serves, // and the chunker that cuts a range into them. // // A chunk is bytes with a name: double SHA-256 of its content. Two instances // holding the same bytes produce the same name, so a client checks a download // against the name it asked for, and a serving instance is never trusted for // more than withholding. // // Cutting is deterministic. A range [from,to) of a kind is cut by the same // rules on every instance, so the same range gives the same boundaries and the // same hashes, and a chunk a client has from one instance is a chunk the other // instance will recognise. package chunk import ( "crypto/sha256" "encoding/binary" "errors" "fmt" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // Kind is what a chunk carries. type Kind uint8 const ( // Headers is a run of raw headers for one chain, 80 or 164 bytes each. Headers Kind = 1 // FilterHeaders is a run of filter hashes and their folded filter headers. FilterHeaders Kind = 2 // Filters is a run of BIP158 filters, each length-prefixed. Filters Kind = 3 // Blocks is a run of raw blocks in height order, each length-prefixed. Blocks Kind = 4 // UTXODiff is one checkpoint diff: from, to, touches. UTXODiff Kind = 5 // UTXOBase is a full canonical set at one height, length-prefixed entries. UTXOBase Kind = 6 // UTXOKnown is a known set for a branch range: the created and spent // bitvectors. UTXOKnown Kind = 7 ) // String names a kind as the HTTP paths and manifests do. func (k Kind) String() string { switch k { case Headers: return "hdrs" case FilterHeaders: return "fh" case Filters: return "flt" case Blocks: return "blk" case UTXODiff: return "utxo.diff" case UTXOBase: return "utxo.base" case UTXOKnown: return "utxo.known" } return fmt.Sprintf("unknown(%d)", uint8(k)) } // ParseKind is String's inverse. func ParseKind(s string) (Kind, bool) { for k := Headers; k <= UTXOKnown; k++ { if k.String() == s { return k, true } } return 0, false } // Name is a chunk's content address: double SHA-256 of its bytes. func Name(raw []byte) chainhash.Hash { return chainhash.DoubleHashH(raw) } // Chunk is one artifact. type Chunk struct { Kind Kind Chain string // "btc", "xbt", or empty for a chain-neutral kind From uint32 To uint32 Raw []byte } // Name is the chunk's content address. func (c Chunk) Name() chainhash.Hash { return Name(c.Raw) } // header carries what a chunk's index needs without its bytes. // // A chunk's bytes are what the manifest hashes; its header names the range and // the kind so an index can answer "which chunks cover 100..200" without // reading a byte of them. type header struct { Kind Kind From uint32 To uint32 Len uint32 Chain [4]byte } // EncodeHeader writes a 21-byte chunk header. func EncodeHeader(c Chunk) []byte { b := make([]byte, 0, 21) b = append(b, byte(c.Kind)) b = binary.LittleEndian.AppendUint32(b, c.From) b = binary.LittleEndian.AppendUint32(b, c.To) b = binary.LittleEndian.AppendUint32(b, uint32(len(c.Raw))) var ch [4]byte copy(ch[:], c.Chain) b = append(b, ch[:]...) return b } // ErrShortHeader is a chunk header that does not have its 21 bytes. var ErrShortHeader = errors.New("chunk: header is short") // DecodeHeader reads a chunk header. func DecodeHeader(b []byte) (Kind, uint32, uint32, uint32, string, error) { if len(b) < 21 { return 0, 0, 0, 0, "", ErrShortHeader } kind := Kind(b[0]) from := binary.LittleEndian.Uint32(b[1:5]) to := binary.LittleEndian.Uint32(b[5:9]) n := binary.LittleEndian.Uint32(b[9:13]) var ch [4]byte copy(ch[:], b[13:17]) return kind, from, to, n, string(ch[:]), nil } // Recorder is where cuts go. type Recorder func(c Chunk) error // CutHeaders splits a header stream into chunks of at most step headers each. // A 164-byte header makes a 10,000-header chunk 1.6 MB, which is the plan's // budget. func CutHeaders(chain string, raw []byte, headerSize int, from uint32, perChunk int, rec Recorder) (int, error) { if headerSize != 80 && headerSize != 164 { return 0, fmt.Errorf("chunk: header size %d", headerSize) } if len(raw)%headerSize != 0 { return 0, fmt.Errorf("chunk: %d bytes is not a whole number of %d-byte headers", len(raw), headerSize) } n := len(raw) / headerSize perChunk = max(perChunk, 1) count := 0 for i := 0; i < n; i += perChunk { end := min(i+perChunk, n) c := Chunk{Kind: Headers, Chain: chain, From: from + uint32(i), To: from + uint32(end), Raw: raw[i*headerSize : end*headerSize]} if err := rec(c); err != nil { return count, err } count++ } return count, nil } // CutLengthPrefixed splits a stream of var-length records (a u32 length then // the record) into chunks of at most budget bytes, or maxRecords records. // // It is the cutter for filters, filter headers in pairs, and blocks: the // records are opaque and only their boundaries matter. func CutLengthPrefixed(chain string, kind Kind, raw []byte, from uint32, budget int64, maxRecords int, rec Recorder) (int, error) { at := 0 height := from count := 0 for at < len(raw) { start := at startHeight := height records := 0 for at < len(raw) { if at+4 > len(raw) { return count, errors.New("chunk: a length prefix runs past the stream") } n := int(binary.LittleEndian.Uint32(raw[at : at+4])) if n < 0 || at+4+n > len(raw) { return count, fmt.Errorf("chunk: a record of %d bytes runs past the stream", n) } next := at + 4 + n if records > 0 && (next-start > int(budget) || records >= maxRecords) { break } at = next records++ height++ } if records == 0 { return count, errors.New("chunk: a record larger than a whole chunk") } c := Chunk{Kind: kind, Chain: chain, From: startHeight, To: startHeight + uint32(records), Raw: raw[start:at]} if err := rec(c); err != nil { return count, err } count++ } return count, nil } // PackLengthPrefixed is the inverse of the cut: it prefixes each record with // its length. func PackLengthPrefixed(records [][]byte) []byte { var out []byte for _, r := range records { out = binary.LittleEndian.AppendUint32(out, uint32(len(r))) out = append(out, r...) } return out } // Sum is a compact summary of a chunk's bytes, for a manifest that lists many. func Sum(raw []byte) [8]byte { sum := sha256.Sum256(raw) var out [8]byte copy(out[:], sum[:8]) return out }