Skip to content
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

optimize NewMerkleTree #31

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 17 additions & 13 deletions merkle_tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"crypto/sha256"
"log"
)

// MerkleTree represent a Merkle tree
Expand All @@ -19,29 +20,32 @@ type MerkleNode struct {
// NewMerkleTree creates a new Merkle tree from a sequence of data
func NewMerkleTree(data [][]byte) *MerkleTree {
var nodes []MerkleNode

if len(data)%2 != 0 {
data = append(data, data[len(data)-1])
}


for _, datum := range data {
node := NewMerkleNode(nil, nil, datum)
nodes = append(nodes, *node)
}

for i := 0; i < len(data)/2; i++ {

if len(nodes) == 0 {
log.Panic("No merkel nodes")
}

for len(nodes) > 1 {
if len(nodes)%2 != 0 {
nodes = append(nodes, nodes[len(nodes)-1])
}

var newLevel []MerkleNode

for j := 0; j < len(nodes); j += 2 {
node := NewMerkleNode(&nodes[j], &nodes[j+1], nil)
for i := 0; i < len(nodes); i += 2 {
node := NewMerkleNode(&nodes[i], &nodes[i+1], nil)
newLevel = append(newLevel, *node)
}

nodes = newLevel
}

mTree := MerkleTree{&nodes[0]}

return &mTree
}

Expand Down