├── .gitignore ├── go.mod ├── go.sum ├── .github └── workflows │ └── go.yml ├── example_test.go ├── LICENSE ├── Readme.md ├── merkle_test.go ├── merkle.go └── testdata └── udhr.txt /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/bobg/merkle/v2 2 | 3 | go 1.20 4 | 5 | require golang.org/x/crypto v0.25.0 6 | 7 | require golang.org/x/sys v0.22.0 // indirect 8 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30= 2 | golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M= 3 | golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI= 4 | golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 5 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | 15 | - name: Set up Go 16 | uses: actions/setup-go@v2 17 | with: 18 | go-version: 1.22 19 | 20 | - name: Unit tests 21 | run: go test -v -coverprofile=cover.out ./... 22 | 23 | - name: Send coverage 24 | uses: shogo82148/actions-goveralls@v1 25 | with: 26 | path-to-profile: cover.out 27 | 28 | - name: Modver 29 | if: ${{ github.event_name == 'pull_request' }} 30 | uses: bobg/modver@v2.11.0 31 | with: 32 | github_token: ${{ secrets.GITHUB_TOKEN }} 33 | pull_request_url: https://github.com/${{ github.repository }}/pull/${{ github.event.number }} 34 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | package merkle_test 2 | 3 | import ( 4 | "crypto/sha256" 5 | 6 | "github.com/bobg/merkle/v2" 7 | ) 8 | 9 | func Example_computeMerkleRoot() { 10 | var ch <-chan []byte // Represents a sequence of byte strings 11 | 12 | tree := merkle.NewTree(sha256.New()) 13 | for str := range ch { 14 | tree.Add(str) 15 | } 16 | // The Merkle root hash of the sequence of strings is now tree.Root() 17 | } 18 | 19 | func Example_produceMerkleProof() { 20 | var ( 21 | ch <-chan []byte // Represents a sequence of byte strings 22 | ref []byte // Represents the string you will later want to prove is a member of the tree we're about to build 23 | ) 24 | 25 | tree := merkle.NewProofTree(sha256.New(), ref) 26 | for str := range ch { 27 | tree.Add(str) 28 | } 29 | proof := tree.Proof() 30 | // A verifier with only the Merkle root hash r, 31 | // and this proof, 32 | // can verify ref belongs in the tree by checking: 33 | // bytes.Equal(r, proof.Hash(sha256.New(), ref)) 34 | _ = proof 35 | } 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Bob Glickstein 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Merkle - Efficient calculation of merkle roots and proofs 2 | 3 | [![Go Reference](https://pkg.go.dev/badge/github.com/bobg/merkle/v2.svg)](https://pkg.go.dev/github.com/bobg/merkle/v2) 4 | [![Go Report Card](https://goreportcard.com/badge/github.com/bobg/merkle/v2)](https://goreportcard.com/report/github.com/bobg/merkle) 5 | [![Tests](https://github.com/bobg/merkle/actions/workflows/go.yml/badge.svg)](https://github.com/bobg/merkle/actions/workflows/go.yml) 6 | [![Coverage Status](https://coveralls.io/repos/github/bobg/merkle/badge.svg?branch=master)](https://coveralls.io/github/bobg/merkle?branch=master) 7 | [![Mentioned in Awesome Go](https://awesome.re/mentioned-badge.svg)](https://github.com/avelino/awesome-go) 8 | 9 | This is merkle, 10 | a Go package for computing the Merkle root hash of a sequence of byte strings, 11 | or of their hashes. 12 | It can also produce a compact proof that a given string belongs in a Merkle tree with a given root hash. 13 | 14 | This implementation does not require holding all of the input in memory while computing a root hash or a proof. 15 | Instead, it is able to operate on a stream of input strings of unbounded length, 16 | holding incremental state that is only logarithmic [O(log N)] in the size of the input. 17 | 18 | For more about Merkle trees, 19 | see [the Wikipedia article](https://en.wikipedia.org/wiki/Merkle_tree). 20 | 21 | Creating a merkle root hash: 22 | 23 | ```go 24 | var ch <-chan []byte // Represents some source of byte strings 25 | tree := merkle.NewTree(sha256.New()) 26 | for str := range ch { 27 | tree.Add(str) 28 | } 29 | fmt.Printf("merkle root hash is %x\n", tree.Root()) 30 | ``` 31 | 32 | Creating a merkle proof that `ref` belongs in the tree, 33 | then verifying the proof: 34 | 35 | ```go 36 | var ( 37 | ch <-chan []byte // Represents some source of byte strings 38 | rootHash []byte // Represents a previously computed merkle root hash (held by someone wishing to verify that ref is in the tree) 39 | ref []byte // Represents the string to prove is a member of the tree with the given root hash 40 | ) 41 | tree := merkle.NewProofTree(sha256.New(), ref) 42 | for str := range ch { 43 | tree.Add(str) 44 | } 45 | proof := tree.Proof() // This is a compact object. For verification purposes, tree can now be discarded. 46 | 47 | // Verification: 48 | if bytes.Equal(rootHash, proof.Hash(sha256.New(), ref)) { 49 | fmt.Println("Verified!") 50 | } 51 | ``` 52 | -------------------------------------------------------------------------------- /merkle_test.go: -------------------------------------------------------------------------------- 1 | package merkle 2 | 3 | import ( 4 | "crypto/sha256" 5 | "encoding/hex" 6 | "errors" 7 | "io" 8 | "os" 9 | "testing" 10 | 11 | "golang.org/x/crypto/sha3" 12 | ) 13 | 14 | // TestMerkleRoot uses SHA3-256 for historical reasons 15 | // (to wit, verifying that the implementation agrees with the one in github.com/chain/txvm). 16 | func TestMerkleRoot(t *testing.T) { 17 | cases := []struct { 18 | input [][]byte 19 | wantHex string 20 | }{ 21 | {nil, "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a"}, 22 | {[][]byte{{1}}, "76ab70dc46775b641a8e71507b07145aed11ae5efc0baa94ac06876af2b3bf5c"}, 23 | {[][]byte{{1}, {2}}, "1dad5e07e988e0e446e2cce0b77d2ea44a1801efea272d2e2bc374037a5bc1a8"}, 24 | {[][]byte{{1}, {2}, {3}}, "4f554b3aea550c2f7a86917c8c02a0ee842a813fadec1f4c87569cff27bccd14"}, 25 | {[][]byte{{1}, {2}, {3}, {4}}, "c39898712f54df7e2ace99e3829c100c1aaff45c65312a674ba9e24b37c46bf4"}, 26 | {[][]byte{{1}, {2}, {3}, {4}, {5}}, "49b61513bcc94c883a410c372f7dfa93456aed3c3c23223b0e5962bc44954c92"}, 27 | {[][]byte{{1}, {2}, {3}, {4}, {5}, {6}}, "61811c47bfd7e41e52cd7421ec9b4d39ceac28fabdfc6a45f74eb36e173fd1b2"}, 28 | {[][]byte{{1}, {2}, {3}, {4}, {5}, {6}, {7}}, "dd2545905846f83c3265ca731c2789235f349ac2c3a2b3ab07fcd3cffb498b0d"}, 29 | } 30 | 31 | for _, c := range cases { 32 | m := NewTree(sha3.New256()) 33 | for _, inp := range c.input { 34 | m.Add(inp) 35 | } 36 | got := m.Root() 37 | gotHex := hex.EncodeToString(got[:]) 38 | if gotHex != c.wantHex { 39 | t.Errorf("on input %v, got %s, want %s", c.input, gotHex, c.wantHex) 40 | } 41 | } 42 | } 43 | 44 | func TestText(t *testing.T) { 45 | f, err := os.Open("testdata/udhr.txt") 46 | if err != nil { 47 | t.Fatal(err) 48 | } 49 | defer f.Close() 50 | 51 | const chunksize = 256 52 | 53 | tree := NewTree(sha256.New()) 54 | 55 | for { 56 | var buf [chunksize]byte 57 | n, err := io.ReadFull(f, buf[:]) 58 | if err == io.EOF { 59 | // "The error is EOF only if no bytes were read." 60 | break 61 | } 62 | if err != nil && err != io.ErrUnexpectedEOF { 63 | t.Fatal(err) 64 | } 65 | tree.Add(buf[:n]) 66 | } 67 | 68 | const treeWantHex = "8acc3ef309961457bde157842e2a9d7b403294c30172b497372c19acecc622e5" 69 | treeRoot := tree.Root() 70 | treeRootHex := hex.EncodeToString(treeRoot) 71 | if treeRootHex != treeWantHex { 72 | t.Errorf("Merkle tree: got %s, want %s", treeRootHex, treeWantHex) 73 | } 74 | } 75 | 76 | func TestTreeProof(t *testing.T) { 77 | f, err := os.Open("testdata/udhr.txt") 78 | if err != nil { 79 | t.Fatal(err) 80 | } 81 | defer f.Close() 82 | 83 | const chunksize = 256 84 | var chunks [][]byte 85 | for { 86 | var buf [chunksize]byte 87 | n, err := io.ReadFull(f, buf[:]) 88 | if err == io.EOF { 89 | // "The error is EOF only if no bytes were read." 90 | break 91 | } 92 | if err != nil && err != io.ErrUnexpectedEOF { 93 | t.Fatal(err) 94 | } 95 | chunks = append(chunks, buf[:n]) 96 | } 97 | 98 | const wantHex = "8acc3ef309961457bde157842e2a9d7b403294c30172b497372c19acecc622e5" 99 | hasher := sha256.New() 100 | for _, refchunk := range chunks { 101 | tree := NewProofTree(hasher, refchunk) 102 | for _, chunk := range chunks { 103 | tree.Add(chunk) 104 | } 105 | root := tree.Root() 106 | rootHex := hex.EncodeToString(root) 107 | if rootHex != wantHex { 108 | t.Errorf("got tree root %s, want %s", rootHex, wantHex) 109 | } 110 | proof := tree.Proof() 111 | proofHash := proof.Hash(hasher, refchunk) 112 | proofHashHex := hex.EncodeToString(proofHash) 113 | if proofHashHex != wantHex { 114 | t.Errorf("got proof hash %s, want %s", proofHashHex, wantHex) 115 | } 116 | 117 | wrongchunk := refchunk[1:] 118 | tree = NewProofTree(hasher, wrongchunk) 119 | for _, chunk := range chunks { 120 | tree.Add(chunk) 121 | } 122 | proof = tree.Proof() 123 | proofHash = proof.Hash(hasher, wrongchunk) 124 | proofHashHex = hex.EncodeToString(proofHash) 125 | if proofHashHex == wantHex { 126 | t.Error("unexpected proof hash match!") 127 | } 128 | } 129 | } 130 | 131 | func TestHTreeProof(t *testing.T) { 132 | f, err := os.Open("testdata/udhr.txt") 133 | if err != nil { 134 | t.Fatal(err) 135 | } 136 | defer f.Close() 137 | 138 | const chunksize = 256 139 | var chunks [][]byte 140 | for { 141 | var buf [chunksize]byte 142 | n, err := io.ReadFull(f, buf[:]) 143 | if err == io.EOF { 144 | // "The error is EOF only if no bytes were read." 145 | break 146 | } 147 | if err != nil && err != io.ErrUnexpectedEOF { 148 | t.Fatal(err) 149 | } 150 | chunks = append(chunks, buf[:n]) 151 | } 152 | 153 | const wantHex = "8acc3ef309961457bde157842e2a9d7b403294c30172b497372c19acecc622e5" 154 | hasher := sha256.New() 155 | for _, refchunk := range chunks { 156 | tree := NewProofHTree(hasher, LeafHash(hasher, nil, refchunk)) 157 | for _, chunk := range chunks { 158 | tree.Add(LeafHash(hasher, nil, chunk)) 159 | } 160 | root := tree.Root() 161 | rootHex := hex.EncodeToString(root) 162 | if rootHex != wantHex { 163 | t.Errorf("got tree root %s, want %s", rootHex, wantHex) 164 | } 165 | proof := tree.Proof() 166 | proofHash := proof.Hash(hasher, LeafHash(hasher, nil, refchunk)) 167 | proofHashHex := hex.EncodeToString(proofHash) 168 | if proofHashHex != wantHex { 169 | t.Errorf("got proof hash %s, want %s", proofHashHex, wantHex) 170 | } 171 | 172 | wrongchunk := refchunk[1:] 173 | tree = NewProofHTree(hasher, LeafHash(hasher, nil, wrongchunk)) 174 | for _, chunk := range chunks { 175 | tree.Add(LeafHash(hasher, nil, chunk)) 176 | } 177 | proof = tree.Proof() 178 | proofHash = proof.Hash(hasher, LeafHash(hasher, nil, wrongchunk)) 179 | proofHashHex = hex.EncodeToString(proofHash) 180 | if proofHashHex == wantHex { 181 | t.Error("unexpected proof hash match!") 182 | } 183 | } 184 | } 185 | 186 | func BenchmarkTextMerkleTree(b *testing.B) { 187 | var chunks [][]byte 188 | f, err := os.Open("testdata/udhr.txt") 189 | if err != nil { 190 | b.Fatal(err) 191 | } 192 | defer f.Close() 193 | 194 | var buf [256]byte 195 | for { 196 | n, err := io.ReadFull(f, buf[:]) 197 | if errors.Is(err, io.EOF) { 198 | break 199 | } 200 | chunk := make([]byte, n) 201 | copy(chunk, buf[:n]) 202 | chunks = append(chunks, chunk) 203 | } 204 | 205 | b.ResetTimer() 206 | 207 | for i := 0; i < b.N; i++ { 208 | tree := NewTree(sha256.New()) 209 | for _, chunk := range chunks { 210 | tree.Add(chunk) 211 | } 212 | tree.Root() 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /merkle.go: -------------------------------------------------------------------------------- 1 | package merkle 2 | 3 | import ( 4 | "bytes" 5 | "hash" 6 | ) 7 | 8 | // Tree accepts a sequence of strings via its Add method. 9 | // It builds a Merkle hash tree from them. 10 | // After adding all strings in the sequence, 11 | // their Merkle root hash may be read via the Root method. 12 | type Tree struct { 13 | htree *HTree 14 | } 15 | 16 | type ( 17 | // ProofStep is one step in a Merkle proof. 18 | ProofStep struct { 19 | H []byte 20 | Left bool 21 | } 22 | 23 | // Proof is a Merkle proof. 24 | Proof struct { 25 | Steps []ProofStep 26 | 27 | // This is true for Tree Proofs and false for HTree Proofs. 28 | // It indicates that the argument to Proof.Hash has to be leaf-hashed first. 29 | needsLeafHashing bool 30 | } 31 | ) 32 | 33 | // NewTree produces a new Tree. 34 | func NewTree(hasher hash.Hash) *Tree { 35 | return &Tree{htree: NewHTree(hasher)} 36 | } 37 | 38 | // NewProofTree produces a new Tree that can compactly prove a given string is in it. 39 | // After adding elements to the tree, call Proof to get the proof. 40 | func NewProofTree(hasher hash.Hash, ref []byte) *Tree { 41 | return &Tree{htree: NewProofHTree(hasher, LeafHash(hasher, nil, ref))} 42 | } 43 | 44 | // Add adds a string to the sequence in m. 45 | // The caller may reuse the space in str. 46 | // It is an error to call Add after a call to Root or Proof. 47 | func (m *Tree) Add(str []byte) { 48 | hasher := m.htree.hasher 49 | lh := make([]byte, hasher.Size()) 50 | LeafHash(hasher, lh[:0], str) 51 | m.htree.Add(lh) 52 | } 53 | 54 | // Root returns the Merkle root hash 55 | // for the sequence of strings that have been added to m with Add. 56 | // It is an error to call Add after a call to Root. 57 | func (m *Tree) Root() []byte { 58 | return m.htree.Root() 59 | } 60 | 61 | // Proof returns the Merkle inclusion proof for the reference string given to NewProofTree. 62 | // It is an error to call Add after a call to Proof. 63 | func (m *Tree) Proof() Proof { 64 | proof := m.htree.Proof() 65 | proof.needsLeafHashing = true 66 | return proof 67 | } 68 | 69 | // HTree accepts a sequence of leaf hashes via its Add method. 70 | // A leaf hash is the result of calling LeafHash on a string. 71 | // After adding all leaf hashes in the sequence, 72 | // their Merkle root hash may be read via the Root method. 73 | // 74 | // Note that a Tree works by converting its input from a sequence of strings 75 | // to the corresponding sequence of leaf hashes and feeding those to an HTree. 76 | type HTree struct { 77 | hashes [][]byte 78 | root *[]byte 79 | ref *[]byte 80 | proof *Proof 81 | hasher hash.Hash 82 | } 83 | 84 | // NewHTree produces a new HTree. 85 | func NewHTree(hasher hash.Hash) *HTree { 86 | return newHTree(hasher, nil) 87 | } 88 | 89 | // NewProofHTree produces a new HTree that can compactly prove a given reference hash is in it. 90 | // After adding elements to the tree, call Proof to get the proof. 91 | func NewProofHTree(hasher hash.Hash, ref []byte) *HTree { 92 | return newHTree(hasher, ref) 93 | } 94 | 95 | func newHTree(hasher hash.Hash, ref []byte) *HTree { 96 | htree := &HTree{hasher: hasher} 97 | if ref != nil { 98 | htree.ref = &ref 99 | htree.proof = new(Proof) 100 | } 101 | return htree 102 | } 103 | 104 | // Add adds a leaf hash to the sequence in h. 105 | // The caller must not reuse the space in item. 106 | // It is an error to call Add after a call to Root or Proof. 107 | func (h *HTree) Add(item []byte) { 108 | // Find the lowest height in hashes where this hash fits. 109 | // For each level where it does not fit, 110 | // compute a combined hash, empty that level, 111 | // and continue searching one level higher with the new hash. 112 | for height := 0; ; height++ { 113 | if height == len(h.hashes) { 114 | // All levels filled. Add a new level. 115 | h.hashes = append(h.hashes, item) 116 | break 117 | } 118 | if h.hashes[height] == nil { 119 | // This level is vacant. Fill it. 120 | h.hashes[height] = item 121 | break 122 | } 123 | 124 | // This level is full. Compute a combined hash and keep searching. 125 | interiorHash(h.hasher, item[:0], h.hashes[height], item, h.ref, h.proof) 126 | 127 | // Also vacate this level. 128 | h.hashes[height] = nil 129 | } 130 | } 131 | 132 | func (h *HTree) finish() { 133 | if h.root != nil { 134 | return 135 | } 136 | if len(h.hashes) == 0 { 137 | h.hasher.Reset() 138 | root := h.hasher.Sum(nil) 139 | h.root = &root 140 | return 141 | } 142 | 143 | // Combine hashes upward toward the highest level in hashes. 144 | for _, hh := range h.hashes { 145 | if hh == nil { 146 | continue 147 | } 148 | hh := hh 149 | if h.root == nil { 150 | h.root = &hh 151 | continue 152 | } 153 | interiorHash(h.hasher, (*h.root)[:0], hh, *h.root, h.ref, h.proof) 154 | } 155 | } 156 | 157 | // Root returns the Merkle root hash 158 | // for the sequence of leaf hashes that have been added to h with Add. 159 | // It is an error to call Add after a call to Root. 160 | func (h *HTree) Root() []byte { 161 | h.finish() 162 | return *h.root 163 | } 164 | 165 | // Proof returns the Merkle inclusion proof for the reference hash given to NewProofHTree. 166 | // It is an error to call Add after a call to Proof. 167 | func (h *HTree) Proof() Proof { 168 | h.finish() 169 | return *h.proof 170 | } 171 | 172 | // LeafHash produces the hash of a leaf of a Tree. 173 | func LeafHash(h hash.Hash, out, in []byte) []byte { 174 | h.Reset() 175 | 176 | // Domain separator to prevent second-preimage attacks. 177 | // https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack 178 | h.Write([]byte{0}) 179 | 180 | h.Write(in) 181 | 182 | return h.Sum(out) 183 | } 184 | 185 | // interiorHash produces the hash of an interior node. 186 | func interiorHash(h hash.Hash, out, left, right []byte, ref *[]byte, proof *Proof) { 187 | lcopy := make([]byte, len(left)) 188 | copy(lcopy, left) 189 | rcopy := make([]byte, len(right)) 190 | copy(rcopy, right) 191 | 192 | var step *ProofStep 193 | if ref != nil { 194 | if bytes.Equal(*ref, left) { 195 | dup := make([]byte, len(right)) 196 | copy(dup, right) 197 | step = &ProofStep{H: dup, Left: false} 198 | } else if bytes.Equal(*ref, right) { 199 | dup := make([]byte, len(left)) 200 | copy(dup, left) 201 | step = &ProofStep{H: dup, Left: true} 202 | } 203 | if step != nil { 204 | proof.Steps = append(proof.Steps, *step) 205 | } 206 | } 207 | 208 | h.Reset() 209 | 210 | // Domain separator to prevent second-preimage attacks. 211 | // https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack 212 | h.Write([]byte{1}) 213 | 214 | h.Write(left) 215 | h.Write(right) 216 | 217 | out = h.Sum(out) 218 | 219 | if step != nil { 220 | *ref = out 221 | } 222 | } 223 | 224 | // Hash computes the hash of a Merkle proof. 225 | // A valid Merkle proof hash matches the root hash of the Merkle tree it came from. 226 | // 227 | // To prove that x is in a tree, create a tree t with NewProofTree(h, x). 228 | // Then fill the tree with calls to t.Add. 229 | // Then get the proof p with t.Proof(). 230 | // Then check that p.Hash(h, x) is the same as t.Root(). 231 | // This will be true only if there was a call t.Add(x) in the proper sequence. 232 | func (p Proof) Hash(hasher hash.Hash, ref []byte) []byte { 233 | result := make([]byte, hasher.Size()) 234 | 235 | if p.needsLeafHashing { 236 | LeafHash(hasher, result[:0], ref) 237 | } else { 238 | copy(result, ref) 239 | } 240 | 241 | for _, step := range p.Steps { 242 | if step.Left { 243 | interiorHash(hasher, result[:0], step.H, result, nil, nil) 244 | } else { 245 | interiorHash(hasher, result[:0], result, step.H, nil, nil) 246 | } 247 | } 248 | 249 | return result 250 | } 251 | -------------------------------------------------------------------------------- /testdata/udhr.txt: -------------------------------------------------------------------------------- 1 | Preamble 2 | 3 | Whereas recognition of the inherent dignity and of the equal and 4 | inalienable rights of all members of the human family is the 5 | foundation of freedom, justice and peace in the world, 6 | 7 | Whereas disregard and contempt for human rights have resulted in 8 | barbarous acts which have outraged the conscience of mankind, and the 9 | advent of a world in which human beings shall enjoy freedom of speech 10 | and belief and freedom from fear and want has been proclaimed as the 11 | highest aspiration of the common people, 12 | 13 | Whereas it is essential, if man is not to be compelled to have 14 | recourse, as a last resort, to rebellion against tyranny and 15 | oppression, that human rights should be protected by the rule of law, 16 | 17 | Whereas it is essential to promote the development of friendly 18 | relations between nations, 19 | 20 | Whereas the peoples of the United Nations have in the Charter 21 | reaffirmed their faith in fundamental human rights, in the dignity and 22 | worth of the human person and in the equal rights of men and women and 23 | have determined to promote social progress and better standards of 24 | life in larger freedom, 25 | 26 | Whereas Member States have pledged themselves to achieve, in 27 | co-operation with the United Nations, the promotion of universal 28 | respect for and observance of human rights and fundamental freedoms, 29 | 30 | Whereas a common understanding of these rights and freedoms is of the 31 | greatest importance for the full realization of this pledge, 32 | 33 | Now, Therefore THE GENERAL ASSEMBLY proclaims THIS UNIVERSAL 34 | DECLARATION OF HUMAN RIGHTS as a common standard of achievement for 35 | all peoples and all nations, to the end that every individual and 36 | every organ of society, keeping this Declaration constantly in mind, 37 | shall strive by teaching and education to promote respect for these 38 | rights and freedoms and by progressive measures, national and 39 | international, to secure their universal and effective recognition and 40 | observance, both among the peoples of Member States themselves and 41 | among the peoples of territories under their jurisdiction. 42 | 43 | Article 1. 44 | 45 | All human beings are born free and equal in dignity and rights. They 46 | are endowed with reason and conscience and should act towards one 47 | another in a spirit of brotherhood. 48 | 49 | Article 2. 50 | 51 | Everyone is entitled to all the rights and freedoms set forth in this 52 | Declaration, without distinction of any kind, such as race, colour, 53 | sex, language, religion, political or other opinion, national or 54 | social origin, property, birth or other status. Furthermore, no 55 | distinction shall be made on the basis of the political, 56 | jurisdictional or international status of the country or territory to 57 | which a person belongs, whether it be independent, trust, 58 | non-self-governing or under any other limitation of sovereignty. 59 | 60 | Article 3. 61 | 62 | Everyone has the right to life, liberty and security of person. 63 | 64 | Article 4. 65 | 66 | No one shall be held in slavery or servitude; slavery and the slave 67 | trade shall be prohibited in all their forms. 68 | 69 | Article 5. 70 | 71 | No one shall be subjected to torture or to cruel, inhuman or degrading 72 | treatment or punishment. 73 | 74 | Article 6. 75 | 76 | Everyone has the right to recognition everywhere as a person before 77 | the law. 78 | 79 | Article 7. 80 | 81 | All are equal before the law and are entitled without any 82 | discrimination to equal protection of the law. All are entitled to 83 | equal protection against any discrimination in violation of this 84 | Declaration and against any incitement to such discrimination. 85 | 86 | Article 8. 87 | 88 | Everyone has the right to an effective remedy by the competent 89 | national tribunals for acts violating the fundamental rights granted 90 | him by the constitution or by law. 91 | 92 | Article 9. 93 | 94 | No one shall be subjected to arbitrary arrest, detention or exile. 95 | 96 | Article 10. 97 | 98 | Everyone is entitled in full equality to a fair and public hearing by 99 | an independent and impartial tribunal, in the determination of his 100 | rights and obligations and of any criminal charge against him. 101 | 102 | Article 11. 103 | 104 | (1) Everyone charged with a penal offence has the right to be presumed 105 | innocent until proved guilty according to law in a public trial at 106 | which he has had all the guarantees necessary for his defence. 107 | 108 | (2) No one shall be held guilty of any penal offence on account of any 109 | act or omission which did not constitute a penal offence, under 110 | national or international law, at the time when it was committed. Nor 111 | shall a heavier penalty be imposed than the one that was applicable at 112 | the time the penal offence was committed. 113 | 114 | Article 12. 115 | 116 | No one shall be subjected to arbitrary interference with his privacy, 117 | family, home or correspondence, nor to attacks upon his honour and 118 | reputation. Everyone has the right to the protection of the law 119 | against such interference or attacks. 120 | 121 | Article 13. 122 | 123 | (1) Everyone has the right to freedom of movement and residence within 124 | the borders of each state. 125 | 126 | (2) Everyone has the right to leave any country, including his own, 127 | and to return to his country. 128 | 129 | Article 14. 130 | 131 | (1) Everyone has the right to seek and to enjoy in other countries 132 | asylum from persecution. 133 | 134 | (2) This right may not be invoked in the case of prosecutions 135 | genuinely arising from non-political crimes or from acts contrary to 136 | the purposes and principles of the United Nations. 137 | 138 | Article 15. 139 | 140 | (1) Everyone has the right to a nationality. 141 | 142 | (2) No one shall be arbitrarily deprived of his nationality nor denied 143 | the right to change his nationality. 144 | 145 | Article 16. 146 | 147 | (1) Men and women of full age, without any limitation due to race, 148 | nationality or religion, have the right to marry and to found a 149 | family. They are entitled to equal rights as to marriage, during 150 | marriage and at its dissolution. 151 | 152 | (2) Marriage shall be entered into only with the free and full consent 153 | of the intending spouses. 154 | 155 | (3) The family is the natural and fundamental group unit of society 156 | and is entitled to protection by society and the State. 157 | 158 | Article 17. 159 | 160 | (1) Everyone has the right to own property alone as well as in 161 | association with others. 162 | 163 | (2) No one shall be arbitrarily deprived of his property. 164 | 165 | Article 18. 166 | 167 | Everyone has the right to freedom of thought, conscience and religion; 168 | this right includes freedom to change his religion or belief, and 169 | freedom, either alone or in community with others and in public or 170 | private, to manifest his religion or belief in teaching, practice, 171 | worship and observance. 172 | 173 | Article 19. 174 | 175 | Everyone has the right to freedom of opinion and expression; this 176 | right includes freedom to hold opinions without interference and to 177 | seek, receive and impart information and ideas through any media and 178 | regardless of frontiers. 179 | 180 | Article 20. 181 | 182 | (1) Everyone has the right to freedom of peaceful assembly and 183 | association. 184 | 185 | (2) No one may be compelled to belong to an association. 186 | 187 | Article 21. 188 | 189 | (1) Everyone has the right to take part in the government of his 190 | country, directly or through freely chosen representatives. 191 | 192 | (2) Everyone has the right of equal access to public service in his 193 | country. 194 | 195 | (3) The will of the people shall be the basis of the authority of 196 | government; this will shall be expressed in periodic and genuine 197 | elections which shall be by universal and equal suffrage and shall be 198 | held by secret vote or by equivalent free voting procedures. 199 | 200 | Article 22. 201 | 202 | Everyone, as a member of society, has the right to social security and 203 | is entitled to realization, through national effort and international 204 | co-operation and in accordance with the organization and resources of 205 | each State, of the economic, social and cultural rights indispensable 206 | for his dignity and the free development of his personality. 207 | 208 | Article 23. 209 | 210 | (1) Everyone has the right to work, to free choice of employment, to 211 | just and favourable conditions of work and to protection against 212 | unemployment. 213 | 214 | (2) Everyone, without any discrimination, has the right to equal pay 215 | for equal work. 216 | 217 | (3) Everyone who works has the right to just and favourable 218 | remuneration ensuring for himself and his family an existence worthy 219 | of human dignity, and supplemented, if necessary, by other means of 220 | social protection. 221 | 222 | (4) Everyone has the right to form and to join trade unions for the 223 | protection of his interests. 224 | 225 | Article 24. 226 | 227 | Everyone has the right to rest and leisure, including reasonable 228 | limitation of working hours and periodic holidays with pay. 229 | 230 | Article 25. 231 | 232 | (1) Everyone has the right to a standard of living adequate for the 233 | health and well-being of himself and of his family, including food, 234 | clothing, housing and medical care and necessary social services, and 235 | the right to security in the event of unemployment, sickness, 236 | disability, widowhood, old age or other lack of livelihood in 237 | circumstances beyond his control. 238 | 239 | (2) Motherhood and childhood are entitled to special care and 240 | assistance. All children, whether born in or out of wedlock, shall 241 | enjoy the same social protection. 242 | 243 | Article 26. 244 | 245 | (1) Everyone has the right to education. Education shall be free, at 246 | least in the elementary and fundamental stages. Elementary education 247 | shall be compulsory. Technical and professional education shall be 248 | made generally available and higher education shall be equally 249 | accessible to all on the basis of merit. 250 | 251 | (2) Education shall be directed to the full development of the human 252 | personality and to the strengthening of respect for human rights and 253 | fundamental freedoms. It shall promote understanding, tolerance and 254 | friendship among all nations, racial or religious groups, and shall 255 | further the activities of the United Nations for the maintenance of 256 | peace. 257 | 258 | (3) Parents have a prior right to choose the kind of education that 259 | shall be given to their children. 260 | 261 | Article 27. 262 | 263 | (1) Everyone has the right freely to participate in the cultural life 264 | of the community, to enjoy the arts and to share in scientific 265 | advancement and its benefits. 266 | 267 | (2) Everyone has the right to the protection of the moral and material 268 | interests resulting from any scientific, literary or artistic 269 | production of which he is the author. 270 | 271 | Article 28. 272 | 273 | Everyone is entitled to a social and international order in which the 274 | rights and freedoms set forth in this Declaration can be fully 275 | realized. 276 | 277 | Article 29. 278 | 279 | (1) Everyone has duties to the community in which alone the free and 280 | full development of his personality is possible. 281 | 282 | (2) In the exercise of his rights and freedoms, everyone shall be 283 | subject only to such limitations as are determined by law solely for 284 | the purpose of securing due recognition and respect for the rights and 285 | freedoms of others and of meeting the just requirements of morality, 286 | public order and the general welfare in a democratic society. 287 | 288 | (3) These rights and freedoms may in no case be exercised contrary to 289 | the purposes and principles of the United Nations. 290 | 291 | Article 30. 292 | 293 | Nothing in this Declaration may be interpreted as implying for any 294 | State, group or person any right to engage in any activity or to 295 | perform any act aimed at the destruction of any of the rights and 296 | freedoms set forth herein. 297 | --------------------------------------------------------------------------------