1 // Package backup encodes a light client's verified chain data as portable, checksummed chunks.
2 //
3 // A mainnet filter set is measured in gigabytes, so a backup is not one file: it is a directory
4 // of chunks bounded by size, plus a manifest that names each chunk, the heights it covers and
5 // its SHA-256. The manifest is what makes a partial copy a detectable failure instead of a
6 // wallet that silently verified less than it thought.
7 //
8 // Two properties are deliberate:
9 //
10 // - A chunk is self-describing. It carries its kind and its first height, so a file that was
11 // renamed or separated from its manifest still says what it is.
12 // - Nothing here trusts the manifest for content. Import verifies each chunk against the
13 // store it is going into — headers by proof of work and linkage, filters by their committed
14 // hashes — and the manifest's digests catch the copy that was truncated on the way.
15 //
16 // The records themselves are the store's, byte for byte: an 80-byte block header, a filter hash
17 // paired with its rolling filter header, a filter with the block and filter hashes it belongs
18 // to. Re-encoding them would be a second format to keep in step with the chain.
19 package backup
20 21 import (
22 "bytes"
23 "crypto/sha256"
24 "encoding/binary"
25 "encoding/hex"
26 "fmt"
27 )
28 29 // Magic starts every chunk file.
30 var Magic = [4]byte{'N', 'S', 'B', 'K'}
31 32 // Version is the chunk format this tree writes and the only one it reads.
33 const Version = 1
34 35 // chunkHeader is magic, version, kind, from, count and payload length.
36 const chunkHeader = 4 + 1 + 1 + 4 + 4 + 4
37 38 // Kind is what one chunk carries.
39 type Kind uint8
40 41 // The three kinds a backup contains. Headers and filter headers are per height; filters are the
42 // payload.
43 const (
44 // Headers is a run of 80-byte block headers.
45 Headers Kind = 1
46 // FilterHeaders is a run of filter hash and filter header pairs.
47 FilterHeaders Kind = 2
48 // Filters is a run of compact filters with the hashes they are committed to.
49 Filters Kind = 3
50 )
51 52 // String names a kind the way a file name or a log line does.
53 func (k Kind) String() string {
54 switch k {
55 case Headers:
56 return "headers"
57 case FilterHeaders:
58 return "filter_headers"
59 case Filters:
60 return "filters"
61 }
62 63 return fmt.Sprintf("kind(%d)", uint8(k))
64 }
65 66 // Valid reports whether k is a kind this tree writes.
67 func (k Kind) Valid() bool { return k >= Headers && k <= Filters }
68 69 // Chunk is one encoded run of records.
70 type Chunk struct {
71 // Kind is what the payload holds.
72 Kind Kind
73 // From is the first record's height.
74 From uint32
75 // Count is the number of records.
76 Count uint32
77 // Payload is the records, in the layout Encode documents.
78 Payload []byte
79 }
80 81 // Record sizes the payloads are built from.
82 const (
83 // HeaderSize is one serialised block header.
84 HeaderSize = 80
85 // FilterHeaderSize is a filter hash and its rolling filter header.
86 FilterHeaderSize = 64
87 // filterRecordFixed is height, block hash, filter hash and length.
88 filterRecordFixed = 4 + 32 + 32 + 4
89 )
90 91 // Encode writes a chunk file: magic, version, kind, first height, count, payload length, payload.
92 func Encode(chunk Chunk) ([]byte, error) {
93 if !chunk.Kind.Valid() {
94 return nil, fmt.Errorf("backup: %s is not a chunk kind", chunk.Kind)
95 }
96 97 if uint64(len(chunk.Payload)) > 0xffffffff {
98 return nil, fmt.Errorf("backup: a %d-byte chunk is too large", len(chunk.Payload))
99 }
100 101 out := make([]byte, chunkHeader+len(chunk.Payload))
102 103 copy(out, Magic[:])
104 105 out[4] = Version
106 out[5] = byte(chunk.Kind)
107 binary.LittleEndian.PutUint32(out[6:], chunk.From)
108 binary.LittleEndian.PutUint32(out[10:], chunk.Count)
109 binary.LittleEndian.PutUint32(out[14:], uint32(len(chunk.Payload)))
110 111 copy(out[chunkHeader:], chunk.Payload)
112 113 return out, nil
114 }
115 116 // Decode reads a chunk file and checks that its payload is exactly the records it claims.
117 func Decode(raw []byte) (Chunk, error) {
118 var chunk Chunk
119 120 if len(raw) < chunkHeader {
121 return chunk, fmt.Errorf("backup: %d bytes is shorter than a chunk header", len(raw))
122 }
123 124 if !bytes.Equal(raw[:4], Magic[:]) {
125 return chunk, fmt.Errorf("backup: %q is not a chunk", raw[:4])
126 }
127 128 if raw[4] != Version {
129 return chunk, fmt.Errorf("backup: chunk version %d, this tree reads %d", raw[4], Version)
130 }
131 132 chunk.Kind = Kind(raw[5])
133 134 if !chunk.Kind.Valid() {
135 return chunk, fmt.Errorf("backup: %s is not a chunk kind", chunk.Kind)
136 }
137 138 chunk.From = binary.LittleEndian.Uint32(raw[6:])
139 chunk.Count = binary.LittleEndian.Uint32(raw[10:])
140 length := binary.LittleEndian.Uint32(raw[14:])
141 142 if int(length) != len(raw)-chunkHeader {
143 return chunk, fmt.Errorf("backup: chunk says %d payload bytes, it has %d", length, len(raw)-chunkHeader)
144 }
145 146 chunk.Payload = raw[chunkHeader:]
147 148 if err := chunk.Check(); err != nil {
149 return Chunk{}, err
150 }
151 152 return chunk, nil
153 }
154 155 // Check verifies that the payload is a whole number of records of the chunk's kind, and that
156 // the count agrees with it.
157 func (c Chunk) Check() error {
158 switch c.Kind {
159 case Headers:
160 if len(c.Payload)%HeaderSize != 0 {
161 return fmt.Errorf("backup: %d header bytes is not a run of %d", len(c.Payload), HeaderSize)
162 }
163 164 if got := uint32(len(c.Payload) / HeaderSize); got != c.Count {
165 return fmt.Errorf("backup: %d headers, the chunk says %d", got, c.Count)
166 }
167 case FilterHeaders:
168 if len(c.Payload)%FilterHeaderSize != 0 {
169 return fmt.Errorf("backup: %d filter header bytes is not a run of %d",
170 len(c.Payload), FilterHeaderSize)
171 }
172 173 if got := uint32(len(c.Payload) / FilterHeaderSize); got != c.Count {
174 return fmt.Errorf("backup: %d filter headers, the chunk says %d", got, c.Count)
175 }
176 case Filters:
177 count, err := countFilters(c.Payload)
178 179 if err != nil {
180 return err
181 }
182 183 if count != c.Count {
184 return fmt.Errorf("backup: %d filters, the chunk says %d", count, c.Count)
185 }
186 default:
187 return fmt.Errorf("backup: %s is not a chunk kind", c.Kind)
188 }
189 190 return nil
191 }
192 193 // countFilters walks the filter records and returns how many whole records there are.
194 func countFilters(payload []byte) (uint32, error) {
195 var (
196 at int
197 count uint32
198 )
199 200 for at < len(payload) {
201 if at+filterRecordFixed > len(payload) {
202 return 0, fmt.Errorf("backup: a filter record ends inside its header")
203 }
204 205 length := int(binary.LittleEndian.Uint32(payload[at+68:]))
206 at += filterRecordFixed
207 208 if at+length > len(payload) {
209 return 0, fmt.Errorf("backup: a filter of %d bytes runs past the chunk", length)
210 }
211 212 at += length
213 count++
214 }
215 216 return count, nil
217 }
218 219 // FilterRecord is one compact filter and the two hashes that place it.
220 type FilterRecord struct {
221 // Height is the block it belongs to.
222 Height uint32
223 // BlockHash is that block's hash.
224 BlockHash [32]byte
225 // FilterHash is the hash committed to by the filter header chain.
226 FilterHash [32]byte
227 // Filter is the compact filter's bytes.
228 Filter []byte
229 }
230 231 // AppendFilters appends filter records to a payload.
232 func AppendFilters(payload []byte, records []FilterRecord) ([]byte, error) {
233 for _, record := range records {
234 if uint64(len(record.Filter)) > 0xffffffff {
235 return nil, fmt.Errorf("backup: a %d-byte filter", len(record.Filter))
236 }
237 238 payload = binary.LittleEndian.AppendUint32(payload, record.Height)
239 payload = append(payload, record.BlockHash[:]...)
240 payload = append(payload, record.FilterHash[:]...)
241 payload = binary.LittleEndian.AppendUint32(payload, uint32(len(record.Filter)))
242 payload = append(payload, record.Filter...)
243 }
244 245 return payload, nil
246 }
247 248 // ReadFilters reads filter records out of a payload.
249 func ReadFilters(payload []byte) ([]FilterRecord, error) {
250 count, err := countFilters(payload)
251 252 if err != nil {
253 return nil, err
254 }
255 256 records := make([]FilterRecord, 0, count)
257 258 for at := 0; at < len(payload); {
259 var record FilterRecord
260 261 record.Height = binary.LittleEndian.Uint32(payload[at:])
262 copy(record.BlockHash[:], payload[at+4:])
263 copy(record.FilterHash[:], payload[at+36:])
264 length := int(binary.LittleEndian.Uint32(payload[at+68:]))
265 266 at += filterRecordFixed
267 record.Filter = append([]byte(nil), payload[at:at+length]...)
268 at += length
269 270 records = append(records, record)
271 }
272 273 return records, nil
274 }
275 276 // Sum is a chunk's SHA-256, as the manifest stores it.
277 func Sum(raw []byte) string {
278 sum := sha256.Sum256(raw)
279 280 return hex.EncodeToString(sum[:])
281 }
282 283 // ChunkFile names one chunk's file: kind and first height, so a directory is readable without
284 // the manifest and a file cannot be mistaken for another range.
285 func ChunkFile(kind Kind, from uint32) string {
286 return fmt.Sprintf("%s-%08d.nsbk", kind, from)
287 }
288