Open jizhouli opened 6 years ago
@jizhouli you may try this one.
// 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++ {
var newLevel []MerkleNode
for j := 0; j < len(nodes); j += 2 {
node := NewMerkleNode(&nodes[j], &nodes[j+1], nil)
newLevel = append(newLevel, *node)
}
nodes = newLevel
if len(newLevel) == 1 {
break
}
}
mTree := MerkleTree{&nodes[0]}
return &mTree
}
codes above may not fix the issue, solution here looks fine : https://github.com/Jeiwan/blockchain_go/pull/31/files
https://github.com/Jeiwan/blockchain_go/blob/fee9bfd3afeef02e237e93335fa2076c30b9d6d6/merkle_tree.go#L36
Please forgive my English is not very good, I want to report a issue when constructs the merkle tree. I think, the leaves number of merkle tree should be power of 2, not even, or the program will stack overflow. For example 6, when i = 1, j = 2, the index of nodes[j+1] will be out of bounds.