1 // Package manifest is the document a client reads before it downloads anything.
2 //
3 // It names what an instance holds, in what ranges, and the name (double
4 // SHA-256) of each chunk that carries it. The document is signed, and the
5 // client's configuration pins the key, so a serving instance can add or
6 // withhold entries but cannot invent a chunk name that verifies.
7 //
8 // The manifest is canonical: the same content always encodes to the same bytes
9 // and the same signature, so two instances holding the same chunks publish the
10 // same manifest and a client can compare them.
11 package manifest
12 13 import (
14 "crypto/ed25519"
15 "encoding/json"
16 "errors"
17 "fmt"
18 "sort"
19 20 "git.smesh.lol/btcd-lite/internal/chunk"
21 )
22 23 // Version is the manifest format this package writes.
24 const Version = 1
25 26 // Manifest is one instance's inventory.
27 type Manifest struct {
28 Version int `json:"version"`
29 // Instance names the instance, human-readable, not trusted.
30 Instance string `json:"instance"`
31 // Chains maps a chain name to its coverage.
32 Chains map[string]Coverage `json:"chains"`
33 // Runs lists every contiguous range the instance can serve.
34 Runs []Run `json:"runs"`
35 // Key is the public key the manifest is signed with, hex.
36 Key string `json:"key"`
37 // Signature is the signature over Canonical() without the signature, hex.
38 Signature string `json:"signature,omitempty"`
39 }
40 41 // Coverage is one chain's heights.
42 type Coverage struct {
43 Start uint32 `json:"start"`
44 Tip uint32 `json:"tip"`
45 }
46 47 // Run is one contiguous range of one kind for one chain.
48 type Run struct {
49 Kind string `json:"kind"`
50 Chain string `json:"chain"`
51 From uint32 `json:"from"`
52 To uint32 `json:"to"`
53 // Chunks are the names of the chunks that tile the run, in height order.
54 Chunks []string `json:"chunks"`
55 }
56 57 // New returns an empty manifest signed with key. A nil key makes an unsigned
58 // manifest, which a client that pins no key accepts and a client that pins one
59 // refuses.
60 func New(instance string, key ed25519.PrivateKey) (*Manifest, error) {
61 m := &Manifest{Version: Version, Instance: instance, Chains: map[string]Coverage{}}
62 if key != nil {
63 pub, ok := key.Public().(ed25519.PublicKey)
64 if !ok {
65 return nil, errors.New("manifest: key is not an Ed25519 private key")
66 }
67 m.Key = fmt.Sprintf("%x", pub)
68 }
69 return m, nil
70 }
71 72 // Add files a run of chunks and widens the chain's coverage to hold it.
73 func (m *Manifest) Add(kind chunk.Kind, chainName string, from, to uint32, names []string) error {
74 if len(names) == 0 {
75 return errors.New("manifest: a run with no chunks")
76 }
77 m.Runs = append(m.Runs, Run{Kind: kind.String(), Chain: chainName, From: from, To: to, Chunks: names})
78 c, ok := m.Chains[chainName]
79 if !ok {
80 m.Chains[chainName] = Coverage{Start: from, Tip: to}
81 return nil
82 }
83 if from < c.Start {
84 c.Start = from
85 }
86 if to > c.Tip {
87 c.Tip = to
88 }
89 m.Chains[chainName] = c
90 return nil
91 }
92 93 // Canonical returns the bytes that are signed: the manifest with its signature
94 // cleared, every map flattened and every list sorted, so the encoding does not
95 // depend on insertion order.
96 func (m *Manifest) Canonical() ([]byte, error) {
97 cp := Manifest{
98 Version: m.Version,
99 Instance: m.Instance,
100 Key: m.Key,
101 Chains: m.Chains,
102 }
103 cp.Runs = append([]Run(nil), m.Runs...)
104 sort.Slice(cp.Runs, func(i, j int) bool {
105 a, b := cp.Runs[i], cp.Runs[j]
106 if a.Chain != b.Chain {
107 return a.Chain < b.Chain
108 }
109 if a.Kind != b.Kind {
110 return a.Kind < b.Kind
111 }
112 if a.From != b.From {
113 return a.From < b.From
114 }
115 return a.To < b.To
116 })
117 for i := range cp.Runs {
118 names := append([]string(nil), cp.Runs[i].Chunks...)
119 sort.Strings(names)
120 cp.Runs[i].Chunks = names
121 }
122 // Chains is a map, and encoding/json sorts map keys, so it is canonical as
123 // it stands.
124 b, err := json.Marshal(cp)
125 if err != nil {
126 return nil, fmt.Errorf("manifest: canonical encoding: %w", err)
127 }
128 return b, nil
129 }
130 131 // Sign fills in the signature with key.
132 func (m *Manifest) Sign(key ed25519.PrivateKey) error {
133 canon, err := m.Canonical()
134 if err != nil {
135 return err
136 }
137 m.Signature = fmt.Sprintf("%x", ed25519.Sign(key, canon))
138 return nil
139 }
140 141 // Encode is the document as the service publishes it: every run in a fixed
142 // order and every chunk list sorted, so two instances holding the same chunks
143 // publish an identical document.
144 func (m *Manifest) Encode() ([]byte, error) {
145 // The runs go through the canonical ordering in place: the published
146 // document is the one that was signed, byte for byte, with the signature
147 // field in it.
148 canon, err := m.Canonical()
149 if err == nil {
150 var ordered Manifest
151 if err = json.Unmarshal(canon, &ordered); err == nil {
152 ordered.Signature = m.Signature
153 return json.Marshal(ordered)
154 }
155 }
156 return nil, err
157 }
158 159 // Verify checks the manifest against pub. A manifest with a different key than
160 // pub is refused, so a client that pins one key cannot be redirected to
161 // another by a serving instance.
162 func Verify(raw []byte, pub ed25519.PublicKey) (*Manifest, error) {
163 var m Manifest
164 if err := json.Unmarshal(raw, &m); err != nil {
165 return nil, fmt.Errorf("manifest: %w", err)
166 }
167 if m.Version != Version {
168 return nil, fmt.Errorf("manifest: version %d, this client speaks %d", m.Version, Version)
169 }
170 if m.Key != fmt.Sprintf("%x", pub) {
171 return nil, fmt.Errorf("manifest: signed by %s, the pinned key is %x", m.Key, pub)
172 }
173 sig, err := hexDecode(m.Signature)
174 if err != nil || len(sig) != ed25519.SignatureSize {
175 return nil, errors.New("manifest: signature is not 64 bytes of hex")
176 }
177 canon, err := m.Canonical()
178 if err != nil {
179 return nil, err
180 }
181 if !ed25519.Verify(pub, canon, sig) {
182 return nil, errors.New("manifest: signature does not verify")
183 }
184 return &m, nil
185 }
186 187 // Run finds the run of a kind and chain that covers [from,to).
188 func (m *Manifest) Run(kind chunk.Kind, chainName string, from, to uint32) (Run, bool) {
189 for _, r := range m.Runs {
190 if r.Kind == kind.String() && r.Chain == chainName && r.From <= from && to <= r.To {
191 return r, true
192 }
193 }
194 return Run{}, false
195 }
196 197 // ChainTip is the highest tip the manifest reports for a chain.
198 func (m *Manifest) ChainTip(chainName string) (Coverage, bool) {
199 c, ok := m.Chains[chainName]
200 return c, ok
201 }
202 203 func hexDecode(s string) ([]byte, error) {
204 if len(s)%2 != 0 {
205 return nil, errors.New("odd hex")
206 }
207 out := make([]byte, len(s)/2)
208 for i := range out {
209 hi, err := hexNibble(s[i*2])
210 if err != nil {
211 return nil, err
212 }
213 lo, err := hexNibble(s[i*2+1])
214 if err != nil {
215 return nil, err
216 }
217 out[i] = hi<<4 | lo
218 }
219 return out, nil
220 }
221 222 func hexNibble(c byte) (byte, error) {
223 switch {
224 case c >= '0' && c <= '9':
225 return c - '0', nil
226 case c >= 'a' && c <= 'f':
227 return c - 'a' + 10, nil
228 }
229 return 0, fmt.Errorf("manifest: %q is not hex", c)
230 }
231