# Golang blockchain: Merkle tree

Xinyuan follows fate 2022-04-05 07:06:00 阅读数:759

golang blockchain merkle tree

## Generate the Merkel tree

``````type MerkleTree struct {

RootNode *MerkleNode
}
type MerkleNode struct {

Left *MerkleNode
Right *MerkleNode
Data []byte
}
/* Analyze the Merkel node hash256 */
func hashMerkleNodes(isLeaf bool ,merkleNodes []*MerkleNode) (returnMerkleNodes []*MerkleNode) {

// If it's not a leaf , And only one node passes in , This is the root node , return
if !isLeaf && len(merkleNodes) == 1 {

return merkleNodes
}
var nodeLen = len(merkleNodes)
// Judge node parity , Odd copy the last copy
var isHaveCopy = false
if nodeLen % 2 != 0 {

copyNode := *merkleNodes[nodeLen - 1]
merkleNodes = append(merkleNodes, &copyNode)
nodeLen = nodeLen + 1
isHaveCopy = true
}
for i:=0; i<nodeLen; i=i+2 {

// two-node data Add up , After the hash256
data := append(merkleNodes[i].Data, merkleNodes[i+1].Data...)
//sha256Bytes := sha256.Sum256(data)
// Generate a new merkleNode, Add a value to
//node := MerkleNode{merkleNodes[i],merkleNodes[i+1],data}
node := MerkleNode{
merkleNodes[i],merkleNodes[i+1],sha256Bytes[:]}
returnMerkleNodes = append(returnMerkleNodes, &node)
}
// Deal with the last （ If you copy the previous one , Then the child node is set to null ）
if isHaveCopy {

merkleNodes[nodeLen - 1].Right = nil
merkleNodes[nodeLen - 1].Left = nil
}
// Recursively
return hashMerkleNodes(false,returnMerkleNodes)
}
``````

## Whether the test is correct or not

``````func TestMerkle(t *testing.T) {

// Generate leaves
n1 := &MerkleNode{
nil,nil,[]byte("1")}
n2 := &MerkleNode{
nil,nil,[]byte("2")}
n3 := &MerkleNode{
nil,nil,[]byte("3")}
n4 := &MerkleNode{
nil,nil,[]byte("4")}
n5 := &MerkleNode{
nil,nil,[]byte("5")}
// Generate tree
nodes := []*MerkleNode{
n1,n2,n3,n4,n5}
tree := NewMerkleTree(true,nodes)
// Print
printTree(tree)
}
func printTree(tree *MerkleNode) {

if tree == nil {

return
}
fmt.Printf("%s\n",tree.Data)
if tree.Left != nil {

printTree(tree.Left)
}
if tree.Right != nil {

printTree(tree.Right)
}
}
``````