package backup import ( "fmt" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // Applier is the verified side of a restore: a light client that checks a chunk against the // chain it already holds before storing it. // // It is an interface so the format does not depend on the client, and so the thing that applies // a chunk is visibly the thing that verifies it. There is no "put without checking" here on // purpose: a backup is a copy of data somebody already verified, not a licence to skip it. type Applier interface { ApplyHeaders(from uint32, headers []btcwire.BlockHeader) (int, error) ApplyFilterHeaders(from uint32, filterHashes, filterHeaders []chainhash.Hash) (int, error) ApplyFilters(records []FilterRecord) (int, error) } // ImportChunk verifies a chunk's shape and hands its records to the applier, which verifies them // against the chain. It returns how many records the store accepted. func ImportChunk(applier Applier, chunk Chunk) (int, error) { if err := chunk.Check(); err != nil { return 0, err } switch chunk.Kind { case Headers: headers := make([]btcwire.BlockHeader, 0, chunk.Count) for at := 0; at < len(chunk.Payload); at += HeaderSize { var header btcwire.BlockHeader if err := header.Deserialize(chunk.Payload[at : at+HeaderSize]); err != nil { return 0, fmt.Errorf("backup: header %d: %w", chunk.From+uint32(len(headers)), err) } headers = append(headers, header) } return applier.ApplyHeaders(chunk.From, headers) case FilterHeaders: hashes := make([]chainhash.Hash, 0, chunk.Count) headers := make([]chainhash.Hash, 0, chunk.Count) for at := 0; at < len(chunk.Payload); at += FilterHeaderSize { var filterHash, filterHeader chainhash.Hash copy(filterHash[:], chunk.Payload[at:]) copy(filterHeader[:], chunk.Payload[at+32:]) hashes = append(hashes, filterHash) headers = append(headers, filterHeader) } return applier.ApplyFilterHeaders(chunk.From, hashes, headers) case Filters: records, err := ReadFilters(chunk.Payload) if err != nil { return 0, err } return applier.ApplyFilters(records) } return 0, fmt.Errorf("backup: %s is not a chunk kind", chunk.Kind) }