Introduction to Merkle Tree

What is the structure of Merkle tree?

A Merkle tree is also called a hash tree. It is a binary tree consisting of a root node, a set of intermediate nodes and a set of leaf nodes. The bottom leaf node contains stored data and hash values, and each intermediate node has Contains the hashes of the content of its two children, and the root node also contains the hashes of its two children.

Merkle Tree Features

1. Any data change of the underlying leaf node will be transmitted to its parent node and passed to the root node.
2. In the blockchain system, the Merkle tree is usually used for the transaction proof of the blockchain.

Typical application scenarios of Merkle tree

(1) Quickly compare a large amount of data
(2) Quickly locate and modify
(3) Zero-knowledge proof

How to encrypt a character with md5 and generate a hexadecimal digital digest ()

First, I imported the hashlib package, called md5() from the package, then encoded a character with encode(), and encrypted the character with md5.update and hedigest

import hashlib
md5 = hashlib.md5()
print(type(md5))
#<class '_hashlib.HASH'>
str = "123"
str = str.encode()
print(str)
print(type(str))
#b'123'
#<class 'bytes'>
md5.update(str)
d = md5.hexdigest()
print(d)
#202cb962ac59075b964b07152d234b70

code idea

1. Create a series of nodes, change the data in the nodes into a digital abstract
2. Create a Merk book class, and use the list of digital abstracts to generate a Merk book
3. Use breadth-first search from the root node, output

Merkle tree code

Main function and number digest generation

if __name__ ==  "__main__":
    #4个节点的数据
    blocks = ['node1', 'node2', 'node3', 'node4']
    #存放数字摘要的列表
    nodes = []
    print("节点哈希值:")
    for element in blocks:
        md5 = hashlib.md5()
        md5.update(element.encode())
        d = md5.hexdigest()
        #printf(d)
        # 节点哈希值:
        # 164546f60261c7e4be0c5f5f9aaeec86
        # 78882aaeb08e9a4c81687b5de2add74f
        # 1315e07dc5ecfdcec39f54ec16f564b7
        # 9e22b2ee283109ab44b3ddeb56f9ed7a
        #将数据默尔克树类中,随后放入节点中
        nodes.append(MerkleNode(data = d))
        print(element+":",d)
    #将数字摘要列表放入creatTree生成一个默尔克书
    root = createTree(nodes)

Definition of Merkle tree data

A Merkle tree is defined here, which consists of an initial method, left node, right node, and its own data. This Merkle tree class is generated to put some digital summaries into the Merkle tree

class MerkleNode(object):
    def __init__(self,left = None,right = None, data = None):
        self.left = left
        self.right = right
        self.data = data

Merkle tree construction

Guess you like

Origin blog.csdn.net/SDSsdsSDsSSSDDDS/article/details/127138644