From b3e0fa817562723f444bf0ad58b5c848e3d0c0e7 Mon Sep 17 00:00:00 2001 From: bboyjing Date: Thu, 19 Apr 2018 13:54:38 +0800 Subject: [PATCH] optimize NewMerkleTree --- merkle_tree.go | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/merkle_tree.go b/merkle_tree.go index 7a4156bd..e0714178 100644 --- a/merkle_tree.go +++ b/merkle_tree.go @@ -2,6 +2,7 @@ package main import ( "crypto/sha256" + "log" ) // MerkleTree represent a Merkle tree @@ -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 }