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 // NewMerkleTree creates a new Merkle tree from a sequence of data
func NewMerkleTree(data [][]byte) *MerkleTree { func NewMerkleTree(data [][]byte) *MerkleTree {
var nodes []MerkleNode var nodes []*MerkleNode
if len(data)%2 != 0 {
data = append(data, data[len(data)-1])
}
for _, datum := range data { for _, datum := range data {
node := NewMerkleNode(nil, nil, datum) node := NewMerkleNode(nil, nil, datum)
nodes = append(nodes, *node) nodes = append(nodes, node)
} }
for i := 0; i < len(data)/2; i++ { for len(nodes) > 1 {
var newLevel []MerkleNode var newLevel []*MerkleNode
if len(nodes)%2 != 0 {
nodes = append(nodes, nodes[len(nodes)-1])
}
for j := 0; j < len(nodes); j += 2 { for j := 0; j < len(nodes); j += 2 {
node := NewMerkleNode(&nodes[j], &nodes[j+1], nil) node := NewMerkleNode(nodes[j], nodes[j+1], nil)
newLevel = append(newLevel, *node) newLevel = append(newLevel, node)
} }
nodes = newLevel nodes = newLevel
} }
mTree := MerkleTree{&nodes[0]} mTree := MerkleTree{nodes[0]}
return &mTree return &mTree
} }

Loading…
Cancel
Save