package backup import ( "bytes" "encoding/hex" "encoding/json" "fmt" "strings" "time" ) // ManifestName is the file that describes a backup directory. const ManifestName = "manifest.json" // Manifest is one backup: which chains it holds, from which anchor to which tip, and the chunks // that carry the records between them. type Manifest struct { // Version is the format's, and matches the chunks'. Version int `json:"version"` // Created is when the backup was taken. Created time.Time `json:"created"` // Chains are the backups of the independent chains. Chains []Chain `json:"chains"` } // Chain is one chain's part of a backup. type Chain struct { // Name is the wallet's chain name: "btc" or "blake". Name string `json:"name"` // Network is the chain profile's name, which a restoring client must match. Network string `json:"network"` // Anchor is the trusted starting point the backup begins above. Anchor Anchor `json:"anchor"` // HeaderFrom is the first height the header chunks cover: the anchor plus one. HeaderFrom uint32 `json:"header_from"` // FilterFrom is the first height the filter header and filter chunks cover. A checkpoint // trusts a filter header at its own height, so this equals HeaderFrom. A genesis anchor // trusts no filter header, and the rolling chain then starts at height zero, which is one // below HeaderFrom. FilterFrom uint32 `json:"filter_from"` // Tip is the last height the backup covers: header, filter header and filter alike. Tip uint32 `json:"tip"` // Headers, FilterHeaders and Filters are the record counts. Headers uint32 `json:"headers"` FilterHeaders uint32 `json:"filter_headers"` Filters uint32 `json:"filters"` // FilterBytes is the space the filter chunks take: their file bytes, which is what a // person copying the directory is deciding about. FilterBytes uint64 `json:"filter_bytes"` // Chunks are the files, in ascending height within each kind. Chunks []ChunkInfo `json:"chunks"` } // Anchor is the trusted starting point a backup continues from. type Anchor struct { Height uint32 `json:"height"` BlockHash string `json:"block_hash"` FilterHeader string `json:"filter_header"` } // ChunkInfo names one chunk file and what it covers. type ChunkInfo struct { File string `json:"file"` Kind Kind `json:"kind"` From uint32 `json:"from"` Count uint32 `json:"count"` Bytes uint64 `json:"bytes"` SHA256 string `json:"sha256"` } // Marshal encodes a manifest, refusing one whose own numbers do not add up. A manifest that // describes a hole is worse than no backup: it is a promise a restore would believe. func Marshal(manifest Manifest) ([]byte, error) { if manifest.Version == 0 { manifest.Version = Version } if manifest.Created.IsZero() { manifest.Created = time.Now().UTC() } if err := manifest.Validate(); err != nil { return nil, err } raw, err := json.MarshalIndent(manifest, "", " ") if err != nil { return nil, fmt.Errorf("backup: manifest: %w", err) } return append(raw, '\n'), nil } // Parse reads a manifest and checks it. func Parse(raw []byte) (Manifest, error) { var manifest Manifest decoder := json.NewDecoder(bytes.NewReader(raw)) decoder.DisallowUnknownFields() if err := decoder.Decode(&manifest); err != nil { return Manifest{}, fmt.Errorf("backup: manifest json: %w", err) } if err := manifest.Validate(); err != nil { return Manifest{}, err } return manifest, nil } // Validate checks that the manifest describes a complete, contiguous backup. func (m Manifest) Validate() error { if m.Version != Version { return fmt.Errorf("backup: manifest version %d, this tree reads %d", m.Version, Version) } if len(m.Chains) == 0 { return fmt.Errorf("backup: the manifest holds no chains") } for _, chain := range m.Chains { if err := chain.Validate(); err != nil { return err } } return nil } // Validate checks one chain's part of a manifest. func (c Chain) Validate() error { if strings.TrimSpace(c.Name) == "" || strings.TrimSpace(c.Network) == "" { return fmt.Errorf("backup: a chain entry needs a name and a network") } if err := c.Anchor.validate(); err != nil { return fmt.Errorf("backup: %s: %w", c.Name, err) } if c.Tip <= c.Anchor.Height { return fmt.Errorf("backup: %s: the tip %d is not above the anchor %d", c.Name, c.Tip, c.Anchor.Height) } if c.HeaderFrom != c.Anchor.Height+1 { return fmt.Errorf("backup: %s: headers begin at %d, the anchor is %d", c.Name, c.HeaderFrom, c.Anchor.Height) } if c.FilterFrom > c.HeaderFrom || c.FilterFrom < c.Anchor.Height { return fmt.Errorf("backup: %s: filters begin at %d, which is not the anchor or above it", c.Name, c.FilterFrom) } if c.Headers != c.Tip-c.HeaderFrom+1 { return fmt.Errorf("backup: %s: %d headers for %d..%d", c.Name, c.Headers, c.HeaderFrom, c.Tip) } if c.FilterHeaders != c.Tip-c.FilterFrom+1 { return fmt.Errorf("backup: %s: %d filter headers for %d..%d", c.Name, c.FilterHeaders, c.FilterFrom, c.Tip) } if c.Filters == 0 || c.Filters > c.Tip-c.FilterFrom+1 { // The backup's tip is the last height all three kinds cover, so a store whose // filters lag its headers simply backs up to where the filters reach. return fmt.Errorf("backup: %s: %d filters for %d..%d", c.Name, c.Filters, c.FilterFrom, c.Tip) } next := map[Kind]uint32{} seen := map[string]bool{} filterBytes := uint64(0) filters := uint32(0) for _, chunk := range c.Chunks { if !chunk.Kind.Valid() { return fmt.Errorf("backup: %s: %s is not a chunk kind", c.Name, chunk.Kind) } if strings.TrimSpace(chunk.File) == "" || seen[chunk.File] { return fmt.Errorf("backup: %s: the chunk file %q is empty or repeated", c.Name, chunk.File) } seen[chunk.File] = true if want := ChunkFile(chunk.Kind, chunk.From); chunk.File != want { return fmt.Errorf("backup: %s: %q should be called %q", c.Name, chunk.File, want) } if chunk.Count == 0 || chunk.Bytes == 0 { return fmt.Errorf("backup: %s: %s is empty", c.Name, chunk.File) } if len(chunk.SHA256) != 64 { return fmt.Errorf("backup: %s: %s has no SHA-256", c.Name, chunk.File) } if _, err := hex.DecodeString(chunk.SHA256); err != nil { return fmt.Errorf("backup: %s: %s: %w", c.Name, chunk.File, err) } at, ok := next[chunk.Kind] if !ok { at = c.HeaderFrom if chunk.Kind != Headers { at = c.FilterFrom } // A wallet that scans recent history may have no filters below its birth // height, so the first filter chunk says where filters begin. if chunk.Kind == Filters && chunk.From > at { at = chunk.From } } if chunk.From != at { return fmt.Errorf("backup: %s: %s begins at %d, the previous chunk ended at %d", c.Name, chunk.File, chunk.From, at) } next[chunk.Kind] = chunk.From + chunk.Count // A filter chunk's records are variable length, so its count is a promise the // chunk itself keeps; the manifest only sums them. if chunk.Kind == Filters { filters += chunk.Count filterBytes += chunk.Bytes } } for _, kind := range []Kind{Headers, FilterHeaders} { if next[kind] != c.Tip+1 { return fmt.Errorf("backup: %s: %s end at %d, the tip is %d", c.Name, kind, next[kind]-1, c.Tip) } } if next[Filters] != c.Tip+1 { return fmt.Errorf("backup: %s: filters end at %d, the tip is %d", c.Name, next[Filters]-1, c.Tip) } if filters != c.Filters || filterBytes != c.FilterBytes { return fmt.Errorf( "backup: %s: chunks hold %d filters in %d bytes, the manifest says %d in %d", c.Name, filters, filterBytes, c.Filters, c.FilterBytes, ) } return nil } // validate checks an anchor's three values. func (a Anchor) validate() error { if a.BlockHash == "" || a.FilterHeader == "" { return fmt.Errorf("the anchor needs a block hash and a filter header") } for _, value := range []string{a.BlockHash, a.FilterHeader} { if len(value) != 64 { return fmt.Errorf("the anchor hashes are not 32 bytes of hex") } if _, err := hex.DecodeString(value); err != nil { return fmt.Errorf("the anchor hashes are not hex: %w", err) } } return nil } // ChunkFiles lists every file a manifest names, in manifest order. func (m Manifest) ChunkFiles() []string { var files []string for _, chain := range m.Chains { for _, chunk := range chain.Chunks { files = append(files, chunk.File) } } return files } // VerifyChunk checks one chunk file against the manifest entry that describes it. // // The digest is checked too, because the two failures are different: a digest mismatch is a // copy that did not survive the trip, and a kind or height mismatch is a file from another // backup. func VerifyChunk(info ChunkInfo, raw []byte) (Chunk, error) { if got := Sum(raw); got != strings.ToLower(info.SHA256) { return Chunk{}, fmt.Errorf("backup: %s: sha256 %s, the manifest says %s", info.File, got, info.SHA256) } chunk, err := Decode(raw) if err != nil { return Chunk{}, fmt.Errorf("backup: %s: %w", info.File, err) } if chunk.Kind != info.Kind || chunk.From != info.From || chunk.Count != info.Count { return Chunk{}, fmt.Errorf( "backup: %s holds %s from %d (%d), the manifest says %s from %d (%d)", info.File, chunk.Kind, chunk.From, chunk.Count, info.Kind, info.From, info.Count, ) } if uint64(len(raw)) != info.Bytes { return Chunk{}, fmt.Errorf("backup: %s is %d bytes, the manifest says %d", info.File, len(raw), info.Bytes) } return chunk, nil }