Golang --Merkle tree

Golang Merkle tree

Personal blog:https://www.huixinyixiao.xn–6qq986b3xl/

Golang implements Merkle tree

To implement a Merkle tree, you need to use:
"github.com/cbergoon/merkletree"

This package contains constructors and interface functions. Therefore, it is very good to implement Merkle tree-related operations through this package.
Official example code

// 在这里编写代码
package main

import (
	"crypto/sha256"
	"github.com/cbergoon/merkletree"
	"log"
)

//TestContent implements the Content interface provided by merkletree and represents the content stored in the tree.
type TestContent struct {
    
    
	x string
}

//CalculateHash hashes the values of a TestContent
func (t TestContent) CalculateHash() ([]byte, error) {
    
    
	h := sha256.New()
	if _, err := h.Write([]byte(t.x)); err != nil {
    
    
		return nil, err
	}

	return h.Sum(nil), nil
}

//Equals tests for equality of two Contents
func (t TestContent) Equals(other merkletree.Content) (bool, error) {
    
    
	return t.x == other.(TestContent).x, nil
}

func main() {
    
    
	//Build list of Content to build tree
	var list []merkletree.Content
	/*测试文件*/
	var list02 []merkletree.Content
	list02 = append(list02, TestContent{
    
    "shan"})

	list = append(list, TestContent{
    
    x: "Hello"})
	list = append(list, TestContent{
    
    x: "Hi"})
	list = append(list, TestContent{
    
    x: "Hey"})
	list = append(list, TestContent{
    
    x: "Hola"})

	//Create a new Merkle Tree from the list of Content
	t, err := merkletree.NewTree(list)
	if err != nil {
    
    
		log.Fatal(err)
	}

	//Get the Merkle Root of the tree
	mr := t.MerkleRoot()
	log.Println("Merkle Root:", mr)

	//Verify the entire tree (hashes for each node) is valid
	vt, err := t.VerifyTree()
	if err != nil {
    
    
		log.Fatal(err)
	}
	log.Println("Verify Tree: ", vt)

	//Verify a specific content in in the tree
	vc, err := t.VerifyContent(list02[0])
	if err != nil {
    
    
		log.Fatal(err)
	}

	log.Println("Verify Content: ", vc)

	//String representation
	log.Println(t)
}

Note: I changed the verification information content (list02) in order to verify the availability of this package.

1. Source package interpretation

In the interface in the package, two functions need to be implemented

//Content represents the data that is stored and verified by the tree. A type that
//implements this interface can be used as an item in the tree.
type Content interface {
    
    
	CalculateHash() ([]byte, error)
	Equals(other Content) (bool, error)
}

Insert image description here

is something you need to pay attention to in code implementation. You can add your own algorithm, such as changing sha256, etc.
There is no need to make any changes when calling other functions, just call them directly.

It can be seen from the above figure that all transaction data are leaves, and if the number of added transactions is an odd number, as indicated by the yellow area, then the last transaction will be copied to form an even number of transactions. That is to say, the last two transactions are actually the same.

2. Query the data path and reconstruct the Merkle tree to see if it is the same as we thought.

By inserting four data:

func appendListData(number int) {
    
    

	//	随机产生数据
	for i := 0; i < number; i++ {
    
    
		nodeId := "hello" + strconv.Itoa(i)
		list = append(list, TestContent{
    
    nodeId})
	}

}

The above code implements the function of inserting data.
Called directly in the main function. In addition, the list needs to be declared globally. We query the paths of two data hello0 and hello1. At this time, set number to 4:
Insert image description here
From the red area, we can know that the parent nodes of the two leaf nodes are the same, that is, hello0 and hello1 The leaves are hashed together.
We query the paths of the two data hello2 and hello3 again. At this time, we also set the number to 4:
Insert image description here
Look, the result is as we said.
If we hash the red data in the two figures above, it must be the root hash.

Guess you like

Origin blog.csdn.net/YSS_33521/article/details/111474199