fix the logic of merkle tree

pull/61/head
Minh Doan 6 years ago
parent aa3e2a49a7
commit fbee5d821c
  1. 22
      blockchain/merkle_tree.go

@ -18,29 +18,29 @@ 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])
}
var nodes []*MerkleNode
for _, datum := range data {
node := NewMerkleNode(nil, nil, datum)
nodes = append(nodes, *node)
nodes = append(nodes, node)
}
for i := 0; i < len(data)/2; i++ {
var newLevel []MerkleNode
for len(nodes) > 1 {
var newLevel []*MerkleNode
if len(nodes)%2 != 0 {
nodes = append(nodes, nodes[len(nodes)-1])
}
for j := 0; j < len(nodes); j += 2 {
node := NewMerkleNode(&nodes[j], &nodes[j+1], nil)
newLevel = append(newLevel, *node)
node := NewMerkleNode(nodes[j], nodes[j+1], nil)
newLevel = append(newLevel, node)
}
nodes = newLevel
}
mTree := MerkleTree{&nodes[0]}
mTree := MerkleTree{nodes[0]}
return &mTree
}

Loading…
Cancel
Save