// Package manifest is the document a client reads before it downloads anything. // // It names what an instance holds, in what ranges, and the name (double // SHA-256) of each chunk that carries it. The document is signed, and the // client's configuration pins the key, so a serving instance can add or // withhold entries but cannot invent a chunk name that verifies. // // The manifest is canonical: the same content always encodes to the same bytes // and the same signature, so two instances holding the same chunks publish the // same manifest and a client can compare them. package manifest import ( "crypto/ed25519" "encoding/json" "errors" "fmt" "sort" "git.smesh.lol/btcd-lite/internal/chunk" ) // Version is the manifest format this package writes. const Version = 1 // Manifest is one instance's inventory. type Manifest struct { Version int `json:"version"` // Instance names the instance, human-readable, not trusted. Instance string `json:"instance"` // Chains maps a chain name to its coverage. Chains map[string]Coverage `json:"chains"` // Runs lists every contiguous range the instance can serve. Runs []Run `json:"runs"` // Key is the public key the manifest is signed with, hex. Key string `json:"key"` // Signature is the signature over Canonical() without the signature, hex. Signature string `json:"signature,omitempty"` } // Coverage is one chain's heights. type Coverage struct { Start uint32 `json:"start"` Tip uint32 `json:"tip"` } // Run is one contiguous range of one kind for one chain. type Run struct { Kind string `json:"kind"` Chain string `json:"chain"` From uint32 `json:"from"` To uint32 `json:"to"` // Chunks are the names of the chunks that tile the run, in height order. Chunks []string `json:"chunks"` } // New returns an empty manifest signed with key. A nil key makes an unsigned // manifest, which a client that pins no key accepts and a client that pins one // refuses. func New(instance string, key ed25519.PrivateKey) (*Manifest, error) { m := &Manifest{Version: Version, Instance: instance, Chains: map[string]Coverage{}} if key != nil { pub, ok := key.Public().(ed25519.PublicKey) if !ok { return nil, errors.New("manifest: key is not an Ed25519 private key") } m.Key = fmt.Sprintf("%x", pub) } return m, nil } // Add files a run of chunks and widens the chain's coverage to hold it. func (m *Manifest) Add(kind chunk.Kind, chainName string, from, to uint32, names []string) error { if len(names) == 0 { return errors.New("manifest: a run with no chunks") } m.Runs = append(m.Runs, Run{Kind: kind.String(), Chain: chainName, From: from, To: to, Chunks: names}) c, ok := m.Chains[chainName] if !ok { m.Chains[chainName] = Coverage{Start: from, Tip: to} return nil } if from < c.Start { c.Start = from } if to > c.Tip { c.Tip = to } m.Chains[chainName] = c return nil } // Canonical returns the bytes that are signed: the manifest with its signature // cleared, every map flattened and every list sorted, so the encoding does not // depend on insertion order. func (m *Manifest) Canonical() ([]byte, error) { cp := Manifest{ Version: m.Version, Instance: m.Instance, Key: m.Key, Chains: m.Chains, } cp.Runs = append([]Run(nil), m.Runs...) sort.Slice(cp.Runs, func(i, j int) bool { a, b := cp.Runs[i], cp.Runs[j] if a.Chain != b.Chain { return a.Chain < b.Chain } if a.Kind != b.Kind { return a.Kind < b.Kind } if a.From != b.From { return a.From < b.From } return a.To < b.To }) for i := range cp.Runs { names := append([]string(nil), cp.Runs[i].Chunks...) sort.Strings(names) cp.Runs[i].Chunks = names } // Chains is a map, and encoding/json sorts map keys, so it is canonical as // it stands. b, err := json.Marshal(cp) if err != nil { return nil, fmt.Errorf("manifest: canonical encoding: %w", err) } return b, nil } // Sign fills in the signature with key. func (m *Manifest) Sign(key ed25519.PrivateKey) error { canon, err := m.Canonical() if err != nil { return err } m.Signature = fmt.Sprintf("%x", ed25519.Sign(key, canon)) return nil } // Encode is the document as the service publishes it: every run in a fixed // order and every chunk list sorted, so two instances holding the same chunks // publish an identical document. func (m *Manifest) Encode() ([]byte, error) { // The runs go through the canonical ordering in place: the published // document is the one that was signed, byte for byte, with the signature // field in it. canon, err := m.Canonical() if err == nil { var ordered Manifest if err = json.Unmarshal(canon, &ordered); err == nil { ordered.Signature = m.Signature return json.Marshal(ordered) } } return nil, err } // Verify checks the manifest against pub. A manifest with a different key than // pub is refused, so a client that pins one key cannot be redirected to // another by a serving instance. func Verify(raw []byte, pub ed25519.PublicKey) (*Manifest, error) { var m Manifest if err := json.Unmarshal(raw, &m); err != nil { return nil, fmt.Errorf("manifest: %w", err) } if m.Version != Version { return nil, fmt.Errorf("manifest: version %d, this client speaks %d", m.Version, Version) } if m.Key != fmt.Sprintf("%x", pub) { return nil, fmt.Errorf("manifest: signed by %s, the pinned key is %x", m.Key, pub) } sig, err := hexDecode(m.Signature) if err != nil || len(sig) != ed25519.SignatureSize { return nil, errors.New("manifest: signature is not 64 bytes of hex") } canon, err := m.Canonical() if err != nil { return nil, err } if !ed25519.Verify(pub, canon, sig) { return nil, errors.New("manifest: signature does not verify") } return &m, nil } // Run finds the run of a kind and chain that covers [from,to). func (m *Manifest) Run(kind chunk.Kind, chainName string, from, to uint32) (Run, bool) { for _, r := range m.Runs { if r.Kind == kind.String() && r.Chain == chainName && r.From <= from && to <= r.To { return r, true } } return Run{}, false } // ChainTip is the highest tip the manifest reports for a chain. func (m *Manifest) ChainTip(chainName string) (Coverage, bool) { c, ok := m.Chains[chainName] return c, ok } func hexDecode(s string) ([]byte, error) { if len(s)%2 != 0 { return nil, errors.New("odd hex") } out := make([]byte, len(s)/2) for i := range out { hi, err := hexNibble(s[i*2]) if err != nil { return nil, err } lo, err := hexNibble(s[i*2+1]) if err != nil { return nil, err } out[i] = hi<<4 | lo } return out, nil } func hexNibble(c byte) (byte, error) { switch { case c >= '0' && c <= '9': return c - '0', nil case c >= 'a' && c <= 'f': return c - 'a' + 10, nil } return 0, fmt.Errorf("manifest: %q is not hex", c) }