| 1 | package merkletree |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "hash" |
| 6 | "io" |
| 7 | ) |
| 8 | |
| 9 | // ReadAll will read segments of size 'segmentSize' and push them into the tree |
| 10 | // until EOF is reached. Success will return 'err == nil', not 'err == EOF'. No |
| 11 | // padding is added to the data, so the last element may be smaller than |
| 12 | // 'segmentSize'. |
| 13 | func (t *Tree) ReadAll(r io.Reader, segmentSize int) error { |
| 14 | for { |
| 15 | segment := make([]byte, segmentSize) |
| 16 | n, readErr := io.ReadFull(r, segment) |
| 17 | if readErr == io.EOF { |
| 18 | // All data has been read. |
| 19 | break |
| 20 | } else if readErr == io.ErrUnexpectedEOF { |
| 21 | // This is the last segment, and there aren't enough bytes to fill |
| 22 | // the entire segment. Note that the next call will return io.EOF. |
| 23 | segment = segment[:n] |
| 24 | } else if readErr != nil { |
| 25 | return readErr |
| 26 | } |
| 27 | t.Push(segment) |
| 28 | } |
| 29 | return nil |
| 30 | } |
| 31 | |
| 32 | // ReaderRoot returns the Merkle root of the data read from the reader, where |
| 33 | // each leaf is 'segmentSize' long and 'h' is used as the hashing function. All |
| 34 | // leaves will be 'segmentSize' bytes except the last leaf, which will not be |
| 35 | // padded out if there are not enough bytes remaining in the reader. |
| 36 | func ReaderRoot(r io.Reader, h hash.Hash, segmentSize int) (root []byte, err error) { |
| 37 | tree := New(h) |
| 38 | err = tree.ReadAll(r, segmentSize) |
| 39 | if err != nil { |
| 40 | return |
| 41 | } |
| 42 | root = tree.Root() |
| 43 | return |
| 44 | } |
| 45 | |
| 46 | // BuildReaderProof returns a proof that certain data is in the merkle tree |
| 47 | // created by the data in the reader. The merkle root, set of proofs, and the |
| 48 | // number of leaves in the Merkle tree are all returned. All leaves will we |
| 49 | // 'segmentSize' bytes except the last leaf, which will not be padded out if |
| 50 | // there are not enough bytes remaining in the reader. |
| 51 | func BuildReaderProof(r io.Reader, h hash.Hash, segmentSize int, index uint64) (root []byte, proofSet [][]byte, numLeaves uint64, err error) { |
| 52 | tree := New(h) |
| 53 | err = tree.SetIndex(index) |
| 54 | if err != nil { |
| 55 | // This code should be unreachable - SetIndex will only return an error |
| 56 | // if the tree is not empty, and yet the tree should be empty at this |
| 57 | // point. |
| 58 | panic(err) |
| 59 | } |
| 60 | err = tree.ReadAll(r, segmentSize) |
| 61 | if err != nil { |
| 62 | return |
| 63 | } |
| 64 | root, proofSet, _, numLeaves = tree.Prove() |
| 65 | if len(proofSet) == 0 { |
| 66 | err = errors.New("index was not reached while creating proof") |
| 67 | return |
| 68 | } |
| 69 | return |
| 70 | } |