Debian Codegraph @

sumdb/internal/tlog/tlog.go

raw symbols SCIP
1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package tlog implements a tamper-evident log
6 // used in the Go module go.sum database server.
7 //
8 // This package is part of a DRAFT of what the go.sum database server will look like.
9 // Do not assume the details here are final!
10 //
11 // This package follows the design of Certificate Transparency (RFC 6962)
12 // and its proofs are compatible with that system.
13 // See TestCertificateTransparency.
14 package tlog
15
16 import (
17 "crypto/sha256"
18 "encoding/base64"
19 "errors"
20 "fmt"
21 "math/bits"
22 )
23
24 // A Hash is a hash identifying a log record or tree root.
25 type Hash [HashSize]byte
26
27 // HashSize is the size of a Hash in bytes.
28 const HashSize = 32
29
30 // String returns a base64 representation of the hash for printing.
31 func (h Hash) String() string {
32 return base64.StdEncoding.EncodeToString(h[:])
33 }
34
35 // MarshalJSON marshals the hash as a JSON string containing the base64-encoded hash.
36 func (h Hash) MarshalJSON() ([]byte, error) {
37 return []byte(`"` + h.String() + `"`), nil
38 }
39
40 // UnmarshalJSON unmarshals a hash from JSON string containing the a base64-encoded hash.
41 func (h *Hash) UnmarshalJSON(data []byte) error {
42 if len(data) != 1+44+1 || data[0] != '"' || data[len(data)-2] != '=' || data[len(data)-1] != '"' {
43 return errors.New("cannot decode hash")
44 }
45
46 // As of Go 1.12, base64.StdEncoding.Decode insists on
47 // slicing into target[33:] even when it only writes 32 bytes.
48 // Since we already checked that the hash ends in = above,
49 // we can use base64.RawStdEncoding with the = removed;
50 // RawStdEncoding does not exhibit the same bug.
51 // We decode into a temporary to avoid writing anything to *h
52 // unless the entire input is well-formed.
53 var tmp Hash
54 n, err := base64.RawStdEncoding.Decode(tmp[:], data[1:len(data)-2])
55 if err != nil || n != HashSize {
56 return errors.New("cannot decode hash")
57 }
58 *h = tmp
59 return nil
60 }
61
62 // ParseHash parses the base64-encoded string form of a hash.
63 func ParseHash(s string) (Hash, error) {
64 data, err := base64.StdEncoding.DecodeString(s)
65 if err != nil || len(data) != HashSize {
66 return Hash{}, fmt.Errorf("malformed hash")
67 }
68 var h Hash
69 copy(h[:], data)
70 return h, nil
71 }
72
73 // maxpow2 returns k, the maximum power of 2 smaller than n,
74 // as well as l = log₂ k (so k = 1<<l).
75 func maxpow2(n int64) (k int64, l int) {
76 l = 0
77 for 1<<uint(l+1) < n {
78 l++
79 }
80 return 1 << uint(l), l
81 }
82
83 var zeroPrefix = []byte{0x00}
84
85 // RecordHash returns the content hash for the given record data.
86 func RecordHash(data []byte) Hash {
87 // SHA256(0x00 || data)
88 // https://tools.ietf.org/html/rfc6962#section-2.1
89 h := sha256.New()
90 h.Write(zeroPrefix)
91 h.Write(data)
92 var h1 Hash
93 h.Sum(h1[:0])
94 return h1
95 }
96
97 // NodeHash returns the hash for an interior tree node with the given left and right hashes.
98 func NodeHash(left, right Hash) Hash {
99 // SHA256(0x01 || left || right)
100 // https://tools.ietf.org/html/rfc6962#section-2.1
101 // We use a stack buffer to assemble the hash input
102 // to avoid allocating a hash struct with sha256.New.
103 var buf [1 + HashSize + HashSize]byte
104 buf[0] = 0x01
105 copy(buf[1:], left[:])
106 copy(buf[1+HashSize:], right[:])
107 return sha256.Sum256(buf[:])
108 }
109
110 // For information about the stored hash index ordering,
111 // see section 3.3 of Crosby and Wallach's paper
112 // "Efficient Data Structures for Tamper-Evident Logging".
113 // https://www.usenix.org/legacy/event/sec09/tech/full_papers/crosby.pdf
114
115 // StoredHashIndex maps the tree coordinates (level, n)
116 // to a dense linear ordering that can be used for hash storage.
117 // Hash storage implementations that store hashes in sequential
118 // storage can use this function to compute where to read or write
119 // a given hash.
120 func StoredHashIndex(level int, n int64) int64 {
121 // Level L's n'th hash is written right after level L+1's 2n+1'th hash.
122 // Work our way down to the level 0 ordering.
123 // We'll add back the orignal level count at the end.
124 for l := level; l > 0; l-- {
125 n = 2*n + 1
126 }
127
128 // Level 0's n'th hash is written at n+n/2+n/4+... (eventually n/2ⁱ hits zero).
129 i := int64(0)
130 for ; n > 0; n >>= 1 {
131 i += n
132 }
133
134 return i + int64(level)
135 }
136
137 // SplitStoredHashIndex is the inverse of StoredHashIndex.
138 // That is, SplitStoredHashIndex(StoredHashIndex(level, n)) == level, n.
139 func SplitStoredHashIndex(index int64) (level int, n int64) {
140 // Determine level 0 record before index.
141 // StoredHashIndex(0, n) < 2*n,
142 // so the n we want is in [index/2, index/2+log₂(index)].
143 n = index / 2
144 indexN := StoredHashIndex(0, n)
145 if indexN > index {
146 panic("bad math")
147 }
148 for {
149 // Each new record n adds 1 + trailingZeros(n) hashes.
150 x := indexN + 1 + int64(bits.TrailingZeros64(uint64(n+1)))
151 if x > index {
152 break
153 }
154 n++
155 indexN = x
156 }
157 // The hash we want was committed with record n,
158 // meaning it is one of (0, n), (1, n/2), (2, n/4), ...
159 level = int(index - indexN)
160 return level, n >> uint(level)
161 }
162
163 // StoredHashCount returns the number of stored hashes
164 // that are expected for a tree with n records.
165 func StoredHashCount(n int64) int64 {
166 if n == 0 {
167 return 0
168 }
169 // The tree will have the hashes up to the last leaf hash.
170 numHash := StoredHashIndex(0, n-1) + 1
171 // And it will have any hashes for subtrees completed by that leaf.
172 for i := uint64(n - 1); i&1 != 0; i >>= 1 {
173 numHash++
174 }
175 return numHash
176 }
177
178 // StoredHashes returns the hashes that must be stored when writing
179 // record n with the given data. The hashes should be stored starting
180 // at StoredHashIndex(0, n). The result will have at most 1 + log₂ n hashes,
181 // but it will average just under two per call for a sequence of calls for n=1..k.
182 //
183 // StoredHashes may read up to log n earlier hashes from r
184 // in order to compute hashes for completed subtrees.
185 func StoredHashes(n int64, data []byte, r HashReader) ([]Hash, error) {
186 return StoredHashesForRecordHash(n, RecordHash(data), r)
187 }
188
189 // StoredHashesForRecordHash is like StoredHashes but takes
190 // as its second argument RecordHash(data) instead of data itself.
191 func StoredHashesForRecordHash(n int64, h Hash, r HashReader) ([]Hash, error) {
192 // Start with the record hash.
193 hashes := []Hash{h}
194
195 // Build list of indexes needed for hashes for completed subtrees.
196 // Each trailing 1 bit in the binary representation of n completes a subtree
197 // and consumes a hash from an adjacent subtree.
198 m := int(bits.TrailingZeros64(uint64(n + 1)))
199 indexes := make([]int64, m)
200 for i := 0; i < m; i++ {
201 // We arrange indexes in sorted order.
202 // Note that n>>i is always odd.
203 indexes[m-1-i] = StoredHashIndex(i, n>>uint(i)-1)
204 }
205
206 // Fetch hashes.
207 old, err := r.ReadHashes(indexes)
208 if err != nil {
209 return nil, err
210 }
211 if len(old) != len(indexes) {
212 return nil, fmt.Errorf("tlog: ReadHashes(%d indexes) = %d hashes", len(indexes), len(old))
213 }
214
215 // Build new hashes.
216 for i := 0; i < m; i++ {
217 h = NodeHash(old[m-1-i], h)
218 hashes = append(hashes, h)
219 }
220 return hashes, nil
221 }
222
223 // A HashReader can read hashes for nodes in the log's tree structure.
224 type HashReader interface {
225 // ReadHashes returns the hashes with the given stored hash indexes
226 // (see StoredHashIndex and SplitStoredHashIndex).
227 // ReadHashes must return a slice of hashes the same length as indexes,
228 // or else it must return a non-nil error.
229 // ReadHashes may run faster if indexes is sorted in increasing order.
230 ReadHashes(indexes []int64) ([]Hash, error)
231 }
232
233 // A HashReaderFunc is a function implementing HashReader.
234 type HashReaderFunc func([]int64) ([]Hash, error)
235
236 func (f HashReaderFunc) ReadHashes(indexes []int64) ([]Hash, error) {
237 return f(indexes)
238 }
239
240 // TreeHash computes the hash for the root of the tree with n records,
241 // using the HashReader to obtain previously stored hashes
242 // (those returned by StoredHashes during the writes of those n records).
243 // TreeHash makes a single call to ReadHash requesting at most 1 + log₂ n hashes.
244 // The tree of size zero is defined to have an all-zero Hash.
245 func TreeHash(n int64, r HashReader) (Hash, error) {
246 if n == 0 {
247 return Hash{}, nil
248 }
249 indexes := subTreeIndex(0, n, nil)
250 hashes, err := r.ReadHashes(indexes)
251 if err != nil {
252 return Hash{}, err
253 }
254 if len(hashes) != len(indexes) {
255 return Hash{}, fmt.Errorf("tlog: ReadHashes(%d indexes) = %d hashes", len(indexes), len(hashes))
256 }
257 hash, hashes := subTreeHash(0, n, hashes)
258 if len(hashes) != 0 {
259 panic("tlog: bad index math in TreeHash")
260 }
261 return hash, nil
262 }
263
264 // subTreeIndex returns the storage indexes needed to compute
265 // the hash for the subtree containing records [lo, hi),
266 // appending them to need and returning the result.
267 // See https://tools.ietf.org/html/rfc6962#section-2.1
268 func subTreeIndex(lo, hi int64, need []int64) []int64 {
269 // See subTreeHash below for commentary.
270 for lo < hi {
271 k, level := maxpow2(hi - lo + 1)
272 if lo&(k-1) != 0 {
273 panic("tlog: bad math in subTreeIndex")
274 }
275 need = append(need, StoredHashIndex(level, lo>>uint(level)))
276 lo += k
277 }
278 return need
279 }
280
281 // subTreeHash computes the hash for the subtree containing records [lo, hi),
282 // assuming that hashes are the hashes corresponding to the indexes
283 // returned by subTreeIndex(lo, hi).
284 // It returns any leftover hashes.
285 func subTreeHash(lo, hi int64, hashes []Hash) (Hash, []Hash) {
286 // Repeatedly partition the tree into a left side with 2^level nodes,
287 // for as large a level as possible, and a right side with the fringe.
288 // The left hash is stored directly and can be read from storage.
289 // The right side needs further computation.
290 numTree := 0
291 for lo < hi {
292 k, _ := maxpow2(hi - lo + 1)
293 if lo&(k-1) != 0 || lo >= hi {
294 panic("tlog: bad math in subTreeHash")
295 }
296 numTree++
297 lo += k
298 }
299
300 if len(hashes) < numTree {
301 panic("tlog: bad index math in subTreeHash")
302 }
303
304 // Reconstruct hash.
305 h := hashes[numTree-1]
306 for i := numTree - 2; i >= 0; i-- {
307 h = NodeHash(hashes[i], h)
308 }
309 return h, hashes[numTree:]
310 }
311
312 // A RecordProof is a verifiable proof that a particular log root contains a particular record.
313 // RFC 6962 calls this a “Merkle audit path.”
314 type RecordProof []Hash
315
316 // ProveRecord returns the proof that the tree of size t contains the record with index n.
317 func ProveRecord(t, n int64, r HashReader) (RecordProof, error) {
318 if t < 0 || n < 0 || n >= t {
319 return nil, fmt.Errorf("tlog: invalid inputs in ProveRecord")
320 }
321 indexes := leafProofIndex(0, t, n, nil)
322 if len(indexes) == 0 {
323 return RecordProof{}, nil
324 }
325 hashes, err := r.ReadHashes(indexes)
326 if err != nil {
327 return nil, err
328 }
329 if len(hashes) != len(indexes) {
330 return nil, fmt.Errorf("tlog: ReadHashes(%d indexes) = %d hashes", len(indexes), len(hashes))
331 }
332
333 p, hashes := leafProof(0, t, n, hashes)
334 if len(hashes) != 0 {
335 panic("tlog: bad index math in ProveRecord")
336 }
337 return p, nil
338 }
339
340 // leafProofIndex builds the list of indexes needed to construct the proof
341 // that leaf n is contained in the subtree with leaves [lo, hi).
342 // It appends those indexes to need and returns the result.
343 // See https://tools.ietf.org/html/rfc6962#section-2.1.1
344 func leafProofIndex(lo, hi, n int64, need []int64) []int64 {
345 // See leafProof below for commentary.
346 if !(lo <= n && n < hi) {
347 panic("tlog: bad math in leafProofIndex")
348 }
349 if lo+1 == hi {
350 return need
351 }
352 if k, _ := maxpow2(hi - lo); n < lo+k {
353 need = leafProofIndex(lo, lo+k, n, need)
354 need = subTreeIndex(lo+k, hi, need)
355 } else {
356 need = subTreeIndex(lo, lo+k, need)
357 need = leafProofIndex(lo+k, hi, n, need)
358 }
359 return need
360 }
361
362 // leafProof constructs the proof that leaf n is contained in the subtree with leaves [lo, hi).
363 // It returns any leftover hashes as well.
364 // See https://tools.ietf.org/html/rfc6962#section-2.1.1
365 func leafProof(lo, hi, n int64, hashes []Hash) (RecordProof, []Hash) {
366 // We must have lo <= n < hi or else the code here has a bug.
367 if !(lo <= n && n < hi) {
368 panic("tlog: bad math in leafProof")
369 }
370
371 if lo+1 == hi { // n == lo
372 // Reached the leaf node.
373 // The verifier knows what the leaf hash is, so we don't need to send it.
374 return RecordProof{}, hashes
375 }
376
377 // Walk down the tree toward n.
378 // Record the hash of the path not taken (needed for verifying the proof).
379 var p RecordProof
380 var th Hash
381 if k, _ := maxpow2(hi - lo); n < lo+k {
382 // n is on left side
383 p, hashes = leafProof(lo, lo+k, n, hashes)
384 th, hashes = subTreeHash(lo+k, hi, hashes)
385 } else {
386 // n is on right side
387 th, hashes = subTreeHash(lo, lo+k, hashes)
388 p, hashes = leafProof(lo+k, hi, n, hashes)
389 }
390 return append(p, th), hashes
391 }
392
393 var errProofFailed = errors.New("invalid transparency proof")
394
395 // CheckRecord verifies that p is a valid proof that the tree of size t
396 // with hash th has an n'th record with hash h.
397 func CheckRecord(p RecordProof, t int64, th Hash, n int64, h Hash) error {
398 if t < 0 || n < 0 || n >= t {
399 return fmt.Errorf("tlog: invalid inputs in CheckRecord")
400 }
401 th2, err := runRecordProof(p, 0, t, n, h)
402 if err != nil {
403 return err
404 }
405 if th2 == th {
406 return nil
407 }
408 return errProofFailed
409 }
410
411 // runRecordProof runs the proof p that leaf n is contained in the subtree with leaves [lo, hi).
412 // Running the proof means constructing and returning the implied hash of that
413 // subtree.
414 func runRecordProof(p RecordProof, lo, hi, n int64, leafHash Hash) (Hash, error) {
415 // We must have lo <= n < hi or else the code here has a bug.
416 if !(lo <= n && n < hi) {
417 panic("tlog: bad math in runRecordProof")
418 }
419
420 if lo+1 == hi { // m == lo
421 // Reached the leaf node.
422 // The proof must not have any unnecessary hashes.
423 if len(p) != 0 {
424 return Hash{}, errProofFailed
425 }
426 return leafHash, nil
427 }
428
429 if len(p) == 0 {
430 return Hash{}, errProofFailed
431 }
432
433 k, _ := maxpow2(hi - lo)
434 if n < lo+k {
435 th, err := runRecordProof(p[:len(p)-1], lo, lo+k, n, leafHash)
436 if err != nil {
437 return Hash{}, err
438 }
439 return NodeHash(th, p[len(p)-1]), nil
440 } else {
441 th, err := runRecordProof(p[:len(p)-1], lo+k, hi, n, leafHash)
442 if err != nil {
443 return Hash{}, err
444 }
445 return NodeHash(p[len(p)-1], th), nil
446 }
447 }
448
449 // A TreeProof is a verifiable proof that a particular log tree contains
450 // as a prefix all records present in an earlier tree.
451 // RFC 6962 calls this a “Merkle consistency proof.”
452 type TreeProof []Hash
453
454 // ProveTree returns the proof that the tree of size t contains
455 // as a prefix all the records from the tree of smaller size n.
456 func ProveTree(t, n int64, h HashReader) (TreeProof, error) {
457 if t < 1 || n < 1 || n > t {
458 return nil, fmt.Errorf("tlog: invalid inputs in ProveTree")
459 }
460 indexes := treeProofIndex(0, t, n, nil)
461 if len(indexes) == 0 {
462 return TreeProof{}, nil
463 }
464 hashes, err := h.ReadHashes(indexes)
465 if err != nil {
466 return nil, err
467 }
468 if len(hashes) != len(indexes) {
469 return nil, fmt.Errorf("tlog: ReadHashes(%d indexes) = %d hashes", len(indexes), len(hashes))
470 }
471
472 p, hashes := treeProof(0, t, n, hashes)
473 if len(hashes) != 0 {
474 panic("tlog: bad index math in ProveTree")
475 }
476 return p, nil
477 }
478
479 // treeProofIndex builds the list of indexes needed to construct
480 // the sub-proof related to the subtree containing records [lo, hi).
481 // See https://tools.ietf.org/html/rfc6962#section-2.1.2.
482 func treeProofIndex(lo, hi, n int64, need []int64) []int64 {
483 // See treeProof below for commentary.
484 if !(lo < n && n <= hi) {
485 panic("tlog: bad math in treeProofIndex")
486 }
487
488 if n == hi {
489 if lo == 0 {
490 return need
491 }
492 return subTreeIndex(lo, hi, need)
493 }
494
495 if k, _ := maxpow2(hi - lo); n <= lo+k {
496 need = treeProofIndex(lo, lo+k, n, need)
497 need = subTreeIndex(lo+k, hi, need)
498 } else {
499 need = subTreeIndex(lo, lo+k, need)
500 need = treeProofIndex(lo+k, hi, n, need)
501 }
502 return need
503 }
504
505 // treeProof constructs the sub-proof related to the subtree containing records [lo, hi).
506 // It returns any leftover hashes as well.
507 // See https://tools.ietf.org/html/rfc6962#section-2.1.2.
508 func treeProof(lo, hi, n int64, hashes []Hash) (TreeProof, []Hash) {
509 // We must have lo < n <= hi or else the code here has a bug.
510 if !(lo < n && n <= hi) {
511 panic("tlog: bad math in treeProof")
512 }
513
514 // Reached common ground.
515 if n == hi {
516 if lo == 0 {
517 // This subtree corresponds exactly to the old tree.
518 // The verifier knows that hash, so we don't need to send it.
519 return TreeProof{}, hashes
520 }
521 th, hashes := subTreeHash(lo, hi, hashes)
522 return TreeProof{th}, hashes
523 }
524
525 // Interior node for the proof.
526 // Decide whether to walk down the left or right side.
527 var p TreeProof
528 var th Hash
529 if k, _ := maxpow2(hi - lo); n <= lo+k {
530 // m is on left side
531 p, hashes = treeProof(lo, lo+k, n, hashes)
532 th, hashes = subTreeHash(lo+k, hi, hashes)
533 } else {
534 // m is on right side
535 th, hashes = subTreeHash(lo, lo+k, hashes)
536 p, hashes = treeProof(lo+k, hi, n, hashes)
537 }
538 return append(p, th), hashes
539 }
540
541 // CheckTree verifies that p is a valid proof that the tree of size t with hash th
542 // contains as a prefix the tree of size n with hash h.
543 func CheckTree(p TreeProof, t int64, th Hash, n int64, h Hash) error {
544 if t < 1 || n < 1 || n > t {
545 return fmt.Errorf("tlog: invalid inputs in CheckTree")
546 }
547 h2, th2, err := runTreeProof(p, 0, t, n, h)
548 if err != nil {
549 return err
550 }
551 if th2 == th && h2 == h {
552 return nil
553 }
554 return errProofFailed
555 }
556
557 // runTreeProof runs the sub-proof p related to the subtree containing records [lo, hi),
558 // where old is the hash of the old tree with n records.
559 // Running the proof means constructing and returning the implied hashes of that
560 // subtree in both the old and new tree.
561 func runTreeProof(p TreeProof, lo, hi, n int64, old Hash) (Hash, Hash, error) {
562 // We must have lo < n <= hi or else the code here has a bug.
563 if !(lo < n && n <= hi) {
564 panic("tlog: bad math in runTreeProof")
565 }
566
567 // Reached common ground.
568 if n == hi {
569 if lo == 0 {
570 if len(p) != 0 {
571 return Hash{}, Hash{}, errProofFailed
572 }
573 return old, old, nil
574 }
575 if len(p) != 1 {
576 return Hash{}, Hash{}, errProofFailed
577 }
578 return p[0], p[0], nil
579 }
580
581 if len(p) == 0 {
582 return Hash{}, Hash{}, errProofFailed
583 }
584
585 // Interior node for the proof.
586 k, _ := maxpow2(hi - lo)
587 if n <= lo+k {
588 oh, th, err := runTreeProof(p[:len(p)-1], lo, lo+k, n, old)
589 if err != nil {
590 return Hash{}, Hash{}, err
591 }
592 return oh, NodeHash(th, p[len(p)-1]), nil
593 } else {
594 oh, th, err := runTreeProof(p[:len(p)-1], lo+k, hi, n, old)
595 if err != nil {
596 return Hash{}, Hash{}, err
597 }
598 return NodeHash(p[len(p)-1], oh), NodeHash(p[len(p)-1], th), nil
599 }
600 }