// Package backup encodes a light client's verified chain data as portable, checksummed chunks. // // A mainnet filter set is measured in gigabytes, so a backup is not one file: it is a directory // of chunks bounded by size, plus a manifest that names each chunk, the heights it covers and // its SHA-256. The manifest is what makes a partial copy a detectable failure instead of a // wallet that silently verified less than it thought. // // Two properties are deliberate: // // - A chunk is self-describing. It carries its kind and its first height, so a file that was // renamed or separated from its manifest still says what it is. // - Nothing here trusts the manifest for content. Import verifies each chunk against the // store it is going into — headers by proof of work and linkage, filters by their committed // hashes — and the manifest's digests catch the copy that was truncated on the way. // // The records themselves are the store's, byte for byte: an 80-byte block header, a filter hash // paired with its rolling filter header, a filter with the block and filter hashes it belongs // to. Re-encoding them would be a second format to keep in step with the chain. package backup import ( "bytes" "crypto/sha256" "encoding/binary" "encoding/hex" "fmt" ) // Magic starts every chunk file. var Magic = [4]byte{'N', 'S', 'B', 'K'} // Version is the chunk format this tree writes and the only one it reads. const Version = 1 // chunkHeader is magic, version, kind, from, count and payload length. const chunkHeader = 4 + 1 + 1 + 4 + 4 + 4 // Kind is what one chunk carries. type Kind uint8 // The three kinds a backup contains. Headers and filter headers are per height; filters are the // payload. const ( // Headers is a run of 80-byte block headers. Headers Kind = 1 // FilterHeaders is a run of filter hash and filter header pairs. FilterHeaders Kind = 2 // Filters is a run of compact filters with the hashes they are committed to. Filters Kind = 3 ) // String names a kind the way a file name or a log line does. func (k Kind) String() string { switch k { case Headers: return "headers" case FilterHeaders: return "filter_headers" case Filters: return "filters" } return fmt.Sprintf("kind(%d)", uint8(k)) } // Valid reports whether k is a kind this tree writes. func (k Kind) Valid() bool { return k >= Headers && k <= Filters } // Chunk is one encoded run of records. type Chunk struct { // Kind is what the payload holds. Kind Kind // From is the first record's height. From uint32 // Count is the number of records. Count uint32 // Payload is the records, in the layout Encode documents. Payload []byte } // Record sizes the payloads are built from. const ( // HeaderSize is one serialised block header. HeaderSize = 80 // FilterHeaderSize is a filter hash and its rolling filter header. FilterHeaderSize = 64 // filterRecordFixed is height, block hash, filter hash and length. filterRecordFixed = 4 + 32 + 32 + 4 ) // Encode writes a chunk file: magic, version, kind, first height, count, payload length, payload. func Encode(chunk Chunk) ([]byte, error) { if !chunk.Kind.Valid() { return nil, fmt.Errorf("backup: %s is not a chunk kind", chunk.Kind) } if uint64(len(chunk.Payload)) > 0xffffffff { return nil, fmt.Errorf("backup: a %d-byte chunk is too large", len(chunk.Payload)) } out := make([]byte, chunkHeader+len(chunk.Payload)) copy(out, Magic[:]) out[4] = Version out[5] = byte(chunk.Kind) binary.LittleEndian.PutUint32(out[6:], chunk.From) binary.LittleEndian.PutUint32(out[10:], chunk.Count) binary.LittleEndian.PutUint32(out[14:], uint32(len(chunk.Payload))) copy(out[chunkHeader:], chunk.Payload) return out, nil } // Decode reads a chunk file and checks that its payload is exactly the records it claims. func Decode(raw []byte) (Chunk, error) { var chunk Chunk if len(raw) < chunkHeader { return chunk, fmt.Errorf("backup: %d bytes is shorter than a chunk header", len(raw)) } if !bytes.Equal(raw[:4], Magic[:]) { return chunk, fmt.Errorf("backup: %q is not a chunk", raw[:4]) } if raw[4] != Version { return chunk, fmt.Errorf("backup: chunk version %d, this tree reads %d", raw[4], Version) } chunk.Kind = Kind(raw[5]) if !chunk.Kind.Valid() { return chunk, fmt.Errorf("backup: %s is not a chunk kind", chunk.Kind) } chunk.From = binary.LittleEndian.Uint32(raw[6:]) chunk.Count = binary.LittleEndian.Uint32(raw[10:]) length := binary.LittleEndian.Uint32(raw[14:]) if int(length) != len(raw)-chunkHeader { return chunk, fmt.Errorf("backup: chunk says %d payload bytes, it has %d", length, len(raw)-chunkHeader) } chunk.Payload = raw[chunkHeader:] if err := chunk.Check(); err != nil { return Chunk{}, err } return chunk, nil } // Check verifies that the payload is a whole number of records of the chunk's kind, and that // the count agrees with it. func (c Chunk) Check() error { switch c.Kind { case Headers: if len(c.Payload)%HeaderSize != 0 { return fmt.Errorf("backup: %d header bytes is not a run of %d", len(c.Payload), HeaderSize) } if got := uint32(len(c.Payload) / HeaderSize); got != c.Count { return fmt.Errorf("backup: %d headers, the chunk says %d", got, c.Count) } case FilterHeaders: if len(c.Payload)%FilterHeaderSize != 0 { return fmt.Errorf("backup: %d filter header bytes is not a run of %d", len(c.Payload), FilterHeaderSize) } if got := uint32(len(c.Payload) / FilterHeaderSize); got != c.Count { return fmt.Errorf("backup: %d filter headers, the chunk says %d", got, c.Count) } case Filters: count, err := countFilters(c.Payload) if err != nil { return err } if count != c.Count { return fmt.Errorf("backup: %d filters, the chunk says %d", count, c.Count) } default: return fmt.Errorf("backup: %s is not a chunk kind", c.Kind) } return nil } // countFilters walks the filter records and returns how many whole records there are. func countFilters(payload []byte) (uint32, error) { var ( at int count uint32 ) for at < len(payload) { if at+filterRecordFixed > len(payload) { return 0, fmt.Errorf("backup: a filter record ends inside its header") } length := int(binary.LittleEndian.Uint32(payload[at+68:])) at += filterRecordFixed if at+length > len(payload) { return 0, fmt.Errorf("backup: a filter of %d bytes runs past the chunk", length) } at += length count++ } return count, nil } // FilterRecord is one compact filter and the two hashes that place it. type FilterRecord struct { // Height is the block it belongs to. Height uint32 // BlockHash is that block's hash. BlockHash [32]byte // FilterHash is the hash committed to by the filter header chain. FilterHash [32]byte // Filter is the compact filter's bytes. Filter []byte } // AppendFilters appends filter records to a payload. func AppendFilters(payload []byte, records []FilterRecord) ([]byte, error) { for _, record := range records { if uint64(len(record.Filter)) > 0xffffffff { return nil, fmt.Errorf("backup: a %d-byte filter", len(record.Filter)) } payload = binary.LittleEndian.AppendUint32(payload, record.Height) payload = append(payload, record.BlockHash[:]...) payload = append(payload, record.FilterHash[:]...) payload = binary.LittleEndian.AppendUint32(payload, uint32(len(record.Filter))) payload = append(payload, record.Filter...) } return payload, nil } // ReadFilters reads filter records out of a payload. func ReadFilters(payload []byte) ([]FilterRecord, error) { count, err := countFilters(payload) if err != nil { return nil, err } records := make([]FilterRecord, 0, count) for at := 0; at < len(payload); { var record FilterRecord record.Height = binary.LittleEndian.Uint32(payload[at:]) copy(record.BlockHash[:], payload[at+4:]) copy(record.FilterHash[:], payload[at+36:]) length := int(binary.LittleEndian.Uint32(payload[at+68:])) at += filterRecordFixed record.Filter = append([]byte(nil), payload[at:at+length]...) at += length records = append(records, record) } return records, nil } // Sum is a chunk's SHA-256, as the manifest stores it. func Sum(raw []byte) string { sum := sha256.Sum256(raw) return hex.EncodeToString(sum[:]) } // ChunkFile names one chunk's file: kind and first height, so a directory is readable without // the manifest and a file cannot be mistaken for another range. func ChunkFile(kind Kind, from uint32) string { return fmt.Sprintf("%s-%08d.nsbk", kind, from) }