-
Notifications
You must be signed in to change notification settings - Fork 389
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(examples): add merkle tree package #631
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
e7061d9
chore: add p/merkle
albttx 6a8741e
chore: whitelist sha256 and encoding/hex
albttx e34222c
chore: update tests
albttx 3235818
chore: optimize memory consumption
albttx 55bc6cc
fix: remove math
albttx 60e3b9c
chore: use same bytes.Buffer
albttx f2c8329
chore: add some comments
albttx File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
# p/demo/merkle | ||
|
||
This package implement a merkle tree that is complient with [merkletreejs](https://github.com/merkletreejs/merkletreejs) | ||
|
||
## [merkletreejs](https://github.com/merkletreejs/merkletreejs) | ||
|
||
```javascript | ||
const { MerkleTree } = require("merkletreejs"); | ||
const SHA256 = require("crypto-js/sha256"); | ||
|
||
let leaves = []; | ||
for (let i = 0; i < 10; i++) { | ||
leaves.push(SHA256(`node_${i}`)); | ||
} | ||
|
||
const tree = new MerkleTree(leaves, SHA256); | ||
const root = tree.getRoot().toString("hex"); | ||
|
||
console.log(root); // cd8a40502b0b92bf58e7432a5abb2d8b60121cf2b7966d6ebaf103f907a1bc21 | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
package merkle | ||
|
||
import ( | ||
"bytes" | ||
"crypto/sha256" | ||
thehowl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"encoding/hex" | ||
"errors" | ||
) | ||
|
||
type Hashable interface { | ||
Bytes() []byte | ||
} | ||
|
||
type nodes []Node | ||
|
||
type Node struct { | ||
hash []byte | ||
|
||
position uint8 | ||
} | ||
|
||
func (n Node) Hash() string { | ||
return hex.EncodeToString(n.hash[:]) | ||
} | ||
|
||
type Tree struct { | ||
layers []nodes | ||
} | ||
|
||
// Root return the merkle root of the tree | ||
func (t *Tree) Root() string { | ||
for _, l := range t.layers { | ||
if len(l) == 1 { | ||
return l[0].Hash() | ||
} | ||
} | ||
return "" | ||
} | ||
|
||
// NewTree create a new Merkle Tree | ||
func NewTree(data []Hashable) *Tree { | ||
tree := &Tree{} | ||
|
||
leaves := make([]Node, len(data)) | ||
|
||
for i, d := range data { | ||
hash := sha256.Sum256(d.Bytes()) | ||
leaves[i] = Node{hash: hash[:]} | ||
} | ||
|
||
tree.layers = []nodes{nodes(leaves)} | ||
|
||
var buff bytes.Buffer | ||
for len(leaves) > 1 { | ||
level := make([]Node, 0, len(leaves)/2+1) | ||
for i := 0; i < len(leaves); i += 2 { | ||
buff.Reset() | ||
|
||
if i < len(leaves)-1 { | ||
buff.Write(leaves[i].hash) | ||
buff.Write(leaves[i+1].hash) | ||
hash := sha256.Sum256(buff.Bytes()) | ||
level = append(level, Node{ | ||
hash: hash[:], | ||
}) | ||
} else { | ||
level = append(level, leaves[i]) | ||
} | ||
} | ||
leaves = level | ||
tree.layers = append(tree.layers, level) | ||
} | ||
return tree | ||
} | ||
|
||
// Proof return a MerkleProof | ||
func (t *Tree) Proof(data Hashable) ([]Node, error) { | ||
targetHash := sha256.Sum256(data.Bytes()) | ||
targetIndex := -1 | ||
|
||
for i, layer := range t.layers[0] { | ||
if bytes.Equal(targetHash[:], layer.hash) { | ||
targetIndex = i | ||
break | ||
} | ||
} | ||
|
||
if targetIndex == -1 { | ||
return nil, errors.New("target not found") | ||
} | ||
|
||
proofs := make([]Node, 0, len(t.layers)) | ||
|
||
for _, layer := range t.layers { | ||
var pairIndex int | ||
|
||
if targetIndex%2 == 0 { | ||
pairIndex = targetIndex + 1 | ||
} else { | ||
pairIndex = targetIndex - 1 | ||
} | ||
if pairIndex < len(layer) { | ||
proofs = append(proofs, Node{ | ||
hash: layer[pairIndex].hash, | ||
position: uint8(targetIndex) % 2, | ||
}) | ||
} | ||
targetIndex /= 2 | ||
} | ||
return proofs, nil | ||
} | ||
|
||
// Verify if a merkle proof is valid | ||
func (t *Tree) Verify(leaf Hashable, proofs []Node) bool { | ||
return Verify(t.Root(), leaf, proofs) | ||
} | ||
|
||
// Verify if a merkle proof is valid | ||
func Verify(root string, leaf Hashable, proofs []Node) bool { | ||
hash := sha256.Sum256(leaf.Bytes()) | ||
|
||
for i := 0; i < len(proofs); i += 1 { | ||
var h []byte | ||
if proofs[i].position == 0 { | ||
h = append(hash[:], proofs[i].hash...) | ||
} else { | ||
h = append(proofs[i].hash, hash[:]...) | ||
} | ||
hash = sha256.Sum256(h) | ||
} | ||
return hex.EncodeToString(hash[:]) == root | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
package merkle | ||
|
||
import ( | ||
"fmt" | ||
"testing" | ||
"time" | ||
) | ||
|
||
type testData struct { | ||
content string | ||
} | ||
|
||
func (d testData) Bytes() []byte { | ||
return []byte(d.content) | ||
} | ||
|
||
func TestMerkleTree(t *testing.T) { | ||
tests := []struct { | ||
size int | ||
expected string | ||
}{ | ||
{ | ||
size: 1, | ||
expected: "cf9f824bce7f5bc63d557b23591f58577f53fe29f974a615bdddbd0140f912f4", | ||
}, | ||
{ | ||
size: 3, | ||
expected: "1a4a5f0fa267244bf9f74a63fdf2a87eed5e97e4bd104a9e94728c8fb5442177", | ||
}, | ||
{ | ||
size: 10, | ||
expected: "cd8a40502b0b92bf58e7432a5abb2d8b60121cf2b7966d6ebaf103f907a1bc21", | ||
}, | ||
{ | ||
size: 1000, | ||
expected: "fa533d2efdf12be26bc410dfa42936ac63361324e35e9b1ff54d422a1dd2388b", | ||
}, | ||
} | ||
|
||
for _, test := range tests { | ||
var leaves []Hashable | ||
for i := 0; i < test.size; i++ { | ||
leaves = append(leaves, testData{fmt.Sprintf("node_%d", i)}) | ||
} | ||
|
||
tree := NewTree(leaves) | ||
|
||
if tree == nil { | ||
t.Error("Merkle tree creation failed") | ||
} | ||
|
||
root := tree.Root() | ||
|
||
if root != test.expected { | ||
t.Fatalf("merkle.Tree.Root(), expected: %s; got: %s", test.expected, root) | ||
} | ||
|
||
for _, leaf := range leaves { | ||
proofs, err := tree.Proof(leaf) | ||
if err != nil { | ||
t.Fatal("failed to proof leaf: %v, on tree: %v", leaf, test) | ||
} | ||
|
||
ok := Verify(root, leaf, proofs) | ||
if !ok { | ||
t.Fatal("failed to verify leaf: %v, on tree: %v", leaf, tree) | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
maybe add a go equivalent to the js code?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the merkle.gno is 100% go compatible.. with a quick look at the gno code, you can have the go code... is it really mendatory ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No, not necessarily. But it seems weird then that there is an example of JS code inside of the directory of a gno package :)