1 package backup
2 3 import (
4 "bytes"
5 "encoding/hex"
6 "encoding/json"
7 "fmt"
8 "strings"
9 "time"
10 )
11 12 // ManifestName is the file that describes a backup directory.
13 const ManifestName = "manifest.json"
14 15 // Manifest is one backup: which chains it holds, from which anchor to which tip, and the chunks
16 // that carry the records between them.
17 type Manifest struct {
18 // Version is the format's, and matches the chunks'.
19 Version int `json:"version"`
20 // Created is when the backup was taken.
21 Created time.Time `json:"created"`
22 // Chains are the backups of the independent chains.
23 Chains []Chain `json:"chains"`
24 }
25 26 // Chain is one chain's part of a backup.
27 type Chain struct {
28 // Name is the wallet's chain name: "btc" or "blake".
29 Name string `json:"name"`
30 // Network is the chain profile's name, which a restoring client must match.
31 Network string `json:"network"`
32 // Anchor is the trusted starting point the backup begins above.
33 Anchor Anchor `json:"anchor"`
34 // HeaderFrom is the first height the header chunks cover: the anchor plus one.
35 HeaderFrom uint32 `json:"header_from"`
36 // FilterFrom is the first height the filter header and filter chunks cover. A checkpoint
37 // trusts a filter header at its own height, so this equals HeaderFrom. A genesis anchor
38 // trusts no filter header, and the rolling chain then starts at height zero, which is one
39 // below HeaderFrom.
40 FilterFrom uint32 `json:"filter_from"`
41 // Tip is the last height the backup covers: header, filter header and filter alike.
42 Tip uint32 `json:"tip"`
43 // Headers, FilterHeaders and Filters are the record counts.
44 Headers uint32 `json:"headers"`
45 FilterHeaders uint32 `json:"filter_headers"`
46 Filters uint32 `json:"filters"`
47 // FilterBytes is the space the filter chunks take: their file bytes, which is what a
48 // person copying the directory is deciding about.
49 FilterBytes uint64 `json:"filter_bytes"`
50 // Chunks are the files, in ascending height within each kind.
51 Chunks []ChunkInfo `json:"chunks"`
52 }
53 54 // Anchor is the trusted starting point a backup continues from.
55 type Anchor struct {
56 Height uint32 `json:"height"`
57 BlockHash string `json:"block_hash"`
58 FilterHeader string `json:"filter_header"`
59 }
60 61 // ChunkInfo names one chunk file and what it covers.
62 type ChunkInfo struct {
63 File string `json:"file"`
64 Kind Kind `json:"kind"`
65 From uint32 `json:"from"`
66 Count uint32 `json:"count"`
67 Bytes uint64 `json:"bytes"`
68 SHA256 string `json:"sha256"`
69 }
70 71 // Marshal encodes a manifest, refusing one whose own numbers do not add up. A manifest that
72 // describes a hole is worse than no backup: it is a promise a restore would believe.
73 func Marshal(manifest Manifest) ([]byte, error) {
74 if manifest.Version == 0 {
75 manifest.Version = Version
76 }
77 78 if manifest.Created.IsZero() {
79 manifest.Created = time.Now().UTC()
80 }
81 82 if err := manifest.Validate(); err != nil {
83 return nil, err
84 }
85 86 raw, err := json.MarshalIndent(manifest, "", " ")
87 88 if err != nil {
89 return nil, fmt.Errorf("backup: manifest: %w", err)
90 }
91 92 return append(raw, '\n'), nil
93 }
94 95 // Parse reads a manifest and checks it.
96 func Parse(raw []byte) (Manifest, error) {
97 var manifest Manifest
98 99 decoder := json.NewDecoder(bytes.NewReader(raw))
100 decoder.DisallowUnknownFields()
101 102 if err := decoder.Decode(&manifest); err != nil {
103 return Manifest{}, fmt.Errorf("backup: manifest json: %w", err)
104 }
105 106 if err := manifest.Validate(); err != nil {
107 return Manifest{}, err
108 }
109 110 return manifest, nil
111 }
112 113 // Validate checks that the manifest describes a complete, contiguous backup.
114 func (m Manifest) Validate() error {
115 if m.Version != Version {
116 return fmt.Errorf("backup: manifest version %d, this tree reads %d", m.Version, Version)
117 }
118 119 if len(m.Chains) == 0 {
120 return fmt.Errorf("backup: the manifest holds no chains")
121 }
122 123 for _, chain := range m.Chains {
124 if err := chain.Validate(); err != nil {
125 return err
126 }
127 }
128 129 return nil
130 }
131 132 // Validate checks one chain's part of a manifest.
133 func (c Chain) Validate() error {
134 if strings.TrimSpace(c.Name) == "" || strings.TrimSpace(c.Network) == "" {
135 return fmt.Errorf("backup: a chain entry needs a name and a network")
136 }
137 138 if err := c.Anchor.validate(); err != nil {
139 return fmt.Errorf("backup: %s: %w", c.Name, err)
140 }
141 142 if c.Tip <= c.Anchor.Height {
143 return fmt.Errorf("backup: %s: the tip %d is not above the anchor %d", c.Name, c.Tip, c.Anchor.Height)
144 }
145 146 if c.HeaderFrom != c.Anchor.Height+1 {
147 return fmt.Errorf("backup: %s: headers begin at %d, the anchor is %d",
148 c.Name, c.HeaderFrom, c.Anchor.Height)
149 }
150 151 if c.FilterFrom > c.HeaderFrom || c.FilterFrom < c.Anchor.Height {
152 return fmt.Errorf("backup: %s: filters begin at %d, which is not the anchor or above it",
153 c.Name, c.FilterFrom)
154 }
155 156 if c.Headers != c.Tip-c.HeaderFrom+1 {
157 return fmt.Errorf("backup: %s: %d headers for %d..%d", c.Name, c.Headers, c.HeaderFrom, c.Tip)
158 }
159 160 if c.FilterHeaders != c.Tip-c.FilterFrom+1 {
161 return fmt.Errorf("backup: %s: %d filter headers for %d..%d",
162 c.Name, c.FilterHeaders, c.FilterFrom, c.Tip)
163 }
164 165 if c.Filters == 0 || c.Filters > c.Tip-c.FilterFrom+1 {
166 // The backup's tip is the last height all three kinds cover, so a store whose
167 // filters lag its headers simply backs up to where the filters reach.
168 return fmt.Errorf("backup: %s: %d filters for %d..%d", c.Name, c.Filters, c.FilterFrom, c.Tip)
169 }
170 171 next := map[Kind]uint32{}
172 seen := map[string]bool{}
173 filterBytes := uint64(0)
174 filters := uint32(0)
175 176 for _, chunk := range c.Chunks {
177 if !chunk.Kind.Valid() {
178 return fmt.Errorf("backup: %s: %s is not a chunk kind", c.Name, chunk.Kind)
179 }
180 181 if strings.TrimSpace(chunk.File) == "" || seen[chunk.File] {
182 return fmt.Errorf("backup: %s: the chunk file %q is empty or repeated", c.Name, chunk.File)
183 }
184 185 seen[chunk.File] = true
186 187 if want := ChunkFile(chunk.Kind, chunk.From); chunk.File != want {
188 return fmt.Errorf("backup: %s: %q should be called %q", c.Name, chunk.File, want)
189 }
190 191 if chunk.Count == 0 || chunk.Bytes == 0 {
192 return fmt.Errorf("backup: %s: %s is empty", c.Name, chunk.File)
193 }
194 195 if len(chunk.SHA256) != 64 {
196 return fmt.Errorf("backup: %s: %s has no SHA-256", c.Name, chunk.File)
197 }
198 199 if _, err := hex.DecodeString(chunk.SHA256); err != nil {
200 return fmt.Errorf("backup: %s: %s: %w", c.Name, chunk.File, err)
201 }
202 203 at, ok := next[chunk.Kind]
204 205 if !ok {
206 at = c.HeaderFrom
207 208 if chunk.Kind != Headers {
209 at = c.FilterFrom
210 }
211 212 // A wallet that scans recent history may have no filters below its birth
213 // height, so the first filter chunk says where filters begin.
214 if chunk.Kind == Filters && chunk.From > at {
215 at = chunk.From
216 }
217 }
218 219 if chunk.From != at {
220 return fmt.Errorf("backup: %s: %s begins at %d, the previous chunk ended at %d",
221 c.Name, chunk.File, chunk.From, at)
222 }
223 224 next[chunk.Kind] = chunk.From + chunk.Count
225 226 // A filter chunk's records are variable length, so its count is a promise the
227 // chunk itself keeps; the manifest only sums them.
228 if chunk.Kind == Filters {
229 filters += chunk.Count
230 filterBytes += chunk.Bytes
231 }
232 }
233 234 for _, kind := range []Kind{Headers, FilterHeaders} {
235 if next[kind] != c.Tip+1 {
236 return fmt.Errorf("backup: %s: %s end at %d, the tip is %d", c.Name, kind, next[kind]-1, c.Tip)
237 }
238 }
239 240 if next[Filters] != c.Tip+1 {
241 return fmt.Errorf("backup: %s: filters end at %d, the tip is %d", c.Name, next[Filters]-1, c.Tip)
242 }
243 244 if filters != c.Filters || filterBytes != c.FilterBytes {
245 return fmt.Errorf(
246 "backup: %s: chunks hold %d filters in %d bytes, the manifest says %d in %d",
247 c.Name, filters, filterBytes, c.Filters, c.FilterBytes,
248 )
249 }
250 251 return nil
252 }
253 254 // validate checks an anchor's three values.
255 func (a Anchor) validate() error {
256 if a.BlockHash == "" || a.FilterHeader == "" {
257 return fmt.Errorf("the anchor needs a block hash and a filter header")
258 }
259 260 for _, value := range []string{a.BlockHash, a.FilterHeader} {
261 if len(value) != 64 {
262 return fmt.Errorf("the anchor hashes are not 32 bytes of hex")
263 }
264 265 if _, err := hex.DecodeString(value); err != nil {
266 return fmt.Errorf("the anchor hashes are not hex: %w", err)
267 }
268 }
269 270 return nil
271 }
272 273 // ChunkFiles lists every file a manifest names, in manifest order.
274 func (m Manifest) ChunkFiles() []string {
275 var files []string
276 277 for _, chain := range m.Chains {
278 for _, chunk := range chain.Chunks {
279 files = append(files, chunk.File)
280 }
281 }
282 283 return files
284 }
285 286 // VerifyChunk checks one chunk file against the manifest entry that describes it.
287 //
288 // The digest is checked too, because the two failures are different: a digest mismatch is a
289 // copy that did not survive the trip, and a kind or height mismatch is a file from another
290 // backup.
291 func VerifyChunk(info ChunkInfo, raw []byte) (Chunk, error) {
292 if got := Sum(raw); got != strings.ToLower(info.SHA256) {
293 return Chunk{}, fmt.Errorf("backup: %s: sha256 %s, the manifest says %s",
294 info.File, got, info.SHA256)
295 }
296 297 chunk, err := Decode(raw)
298 299 if err != nil {
300 return Chunk{}, fmt.Errorf("backup: %s: %w", info.File, err)
301 }
302 303 if chunk.Kind != info.Kind || chunk.From != info.From || chunk.Count != info.Count {
304 return Chunk{}, fmt.Errorf(
305 "backup: %s holds %s from %d (%d), the manifest says %s from %d (%d)",
306 info.File, chunk.Kind, chunk.From, chunk.Count, info.Kind, info.From, info.Count,
307 )
308 }
309 310 if uint64(len(raw)) != info.Bytes {
311 return Chunk{}, fmt.Errorf("backup: %s is %d bytes, the manifest says %d",
312 info.File, len(raw), info.Bytes)
313 }
314 315 return chunk, nil
316 }
317