From fbee5d821c337e4f41d8263ddaed2d9f1c389b35 Mon Sep 17 00:00:00 2001 From: Minh Doan Date: Wed, 22 Aug 2018 13:53:07 -0700 Subject: [PATCH] fix the logic of merkle tree --- blockchain/merkle_tree.go | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/blockchain/merkle_tree.go b/blockchain/merkle_tree.go index c4ffa4c9d..0061520c3 100644 --- a/blockchain/merkle_tree.go +++ b/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 }