0% found this document useful (0 votes)
11 views9 pages

Merkle Tree

A Merkle tree is a data structure used for verifying the integrity of large datasets by hashing data chunks and combining them into a single root hash. It consists of a hierarchical structure with a root hash, non-leaf nodes, and leaf nodes, enabling efficient data verification and tamper-proof transactions. Merkle trees are particularly useful in blockchain technology for ensuring data accuracy, saving disk space, and facilitating quick verification.

Uploaded by

dhruvthakar644
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views9 pages

Merkle Tree

A Merkle tree is a data structure used for verifying the integrity of large datasets by hashing data chunks and combining them into a single root hash. It consists of a hierarchical structure with a root hash, non-leaf nodes, and leaf nodes, enabling efficient data verification and tamper-proof transactions. Merkle trees are particularly useful in blockchain technology for ensuring data accuracy, saving disk space, and facilitating quick verification.

Uploaded by

dhruvthakar644
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Merkle tree

A Merkle tree (also hash tree) is a fundamental data structure employed in efficient
verification of integrity of large datasets. By breaking down the data into smaller chunks,
hashing them, and then combining these hashes iteratively a single root hash is obtained for
this purpose.

Visualiazation
The structure of a Merkle Tree is a hierarchical way to represent hashes of the
transactions.

• Merkle Root (or Root Hash): Top node of the tree

• Non-Leaf Nodes: Child hash nodes of transactions in between

• Leaf Nodes: Child nodes or Transactions nodes

Here we have a root hash, we have 4 data elements, data1, data2,data3 and data4. The root
hash represents the complete merkel tree, we also have hash 1 and hash2 so if any of the data
change the hash value at that level will also change, which leads to the change in the root
hash. This enables you to validate the data integrity.

Algorithm

• Start by defining a structure for the Merkle tree node.

• Create a function for the computation of hash of a given data chunk.

• Build leaf nodes from data chunks and calculate their respective hashes.

• Pair up and combine hashes iteratively for creating the parent nodes.

• Continue with the merging of nodes until a single root hash is obtained.

Why are Merkle trees used in blockchain?

• Data integrity: Merkle trees ensure that data is accurate and has not been tampered
with.
• Efficient verification: Merkle trees are efficient and can verify data quickly.

• Saves disk space: Merkle trees use hashes to encode files, which takes up less disk
space than storing the entire files.

• Tamper-proof: Merkle trees make it difficult to tamper with transactions because the
hash of a transaction would change if it were altered.

Program 1:

Program 2:

from typing import List

import hashlib
class Node:

def __init__(self, left, right, value: str, content, is_copied=False) -> None:

self.left: Node = left

self.right: Node = right

self.value = value

self.content = content

self.is_copied = is_copied

@staticmethod

def hash(val: str) -> str:

return hashlib.sha1(val.encode('utf-8')).hexdigest()

def __str__(self):

return (str(self.value))

def copy(self):

"""

class copy function

"""

return Node(self.left, self.right, self.value, self.content, True)

class MerkleTree:

def __init__(self, values: List[str]) -> None:

self.__buildTree(values)

def __buildTree(self, values: List[str]) -> None:


leaves: List[Node] = [Node(None, None, Node.hash(e), e)

for e in values]

if len(leaves) % 2 == 1:

# duplicate last elem if odd number of elements

leaves.append(leaves[-1].copy())

self.root: Node = self.__buildTreeRec(leaves)

def __buildTreeRec(self, nodes: List[Node]) -> Node:

if len(nodes) % 2 == 1:

# duplicate last elem if odd number of elements

nodes.append(nodes[-1].copy())

half: int = len(nodes) // 2

if len(nodes) == 2:

return Node(nodes[0], nodes[1], Node.hash(nodes[0].value + nodes[1].value),


nodes[0].content+"+"+nodes[1].content)

left: Node = self.__buildTreeRec(nodes[:half])

right: Node = self.__buildTreeRec(nodes[half:])

value: str = Node.hash(left.value + right.value)

content: str = f'{left.content}+{right.content}'

return Node(left, right, value, content)

def printTree(self) -> None:

self.__printTreeRec(self.root)

def __printTreeRec(self, node: Node) -> None:

if node != None:
if node.left != None:

print("Left: "+str(node.left))

print("Right: "+str(node.right))

else:

print("Input")

if node.is_copied:

print('(Padding)')

print("Value: "+str(node.value))

print("Content: "+str(node.content))

print("")

self.__printTreeRec(node.left)

self.__printTreeRec(node.right)

def getRootHash(self) -> str:

return self.root.value

def mixmerkletree() -> None:

elems = ["A", "B", "C",

"D", "E", "F", "G"]

# as there are odd number of inputs, the last input is repeated

print("Inputs: ")

print(*elems, sep=" | ")

print("")

mtree = MerkleTree(elems)

print("Root Hash: "+mtree.getRootHash()+"\n")

mtree.printTree()
mixmerkletree()

Output

= RESTART: C:\Users\Amisha\AppData\Local\Programs\Python\Python311\Scripts\Block
chain\markel tree1.py

Inputs:

A|B|C|D|E|F|G

Root Hash: d323c3b477812088181392fbb5f3e95e14b0b635

Left: c4d69c96bd6d57986a96e95b77ceb96049b3dd8b

Right: 6589ed1a99ca3101afbba3e0b478aa9a44564b88

Value: d323c3b477812088181392fbb5f3e95e14b0b635

Content: A+B+C+D+E+F+G+G

Left: 859572ac3bd09bc4f777a4ce6cb326e3251ee29a

Right: 51c4bf96a12d0d298977eb7849ad2082f43ec14f

Value: c4d69c96bd6d57986a96e95b77ceb96049b3dd8b

Content: A+B+C+D

Left: 6dcd4ce23d88e2ee9568ba546c007c63d9131c1b

Right: ae4f281df5a5d0ff3cad6371f76d5c29b6d953ec

Value: 859572ac3bd09bc4f777a4ce6cb326e3251ee29a

Content: A+B

Input

Value: 6dcd4ce23d88e2ee9568ba546c007c63d9131c1b
Content: A

Input

Value: ae4f281df5a5d0ff3cad6371f76d5c29b6d953ec

Content: B

Left: 32096c2e0eff33d844ee6d675407ace18289357d

Right: 50c9e8d5fc98727b4bbc93cf5d64a68db647f04f

Value: 51c4bf96a12d0d298977eb7849ad2082f43ec14f

Content: C+D

Input

Value: 32096c2e0eff33d844ee6d675407ace18289357d

Content: C

Input

Value: 50c9e8d5fc98727b4bbc93cf5d64a68db647f04f

Content: D

Left: f66aec75d4c38a4a09c1e5e5db9afa2d906fb555

Right: 05c67a54f41b79e3272ecd4c41ec86b13758319f

Value: 6589ed1a99ca3101afbba3e0b478aa9a44564b88

Content: E+F+G+G

Left: e0184adedf913b076626646d3f52c3b49c39ad6d

Right: e69f20e9f683920d3fb4329abd951e878b1f9372

Value: f66aec75d4c38a4a09c1e5e5db9afa2d906fb555

Content: E+F
Input

Value: e0184adedf913b076626646d3f52c3b49c39ad6d

Content: E

Input

Value: e69f20e9f683920d3fb4329abd951e878b1f9372

Content: F

Left: a36a6718f54524d846894fb04b5b885b4e43e63b

Right: a36a6718f54524d846894fb04b5b885b4e43e63b

Value: 05c67a54f41b79e3272ecd4c41ec86b13758319f

Content: G+G

Input

Value: a36a6718f54524d846894fb04b5b885b4e43e63b

Content: G

Input

(Padding)

Value: a36a6718f54524d846894fb04b5b885b4e43e63b

Content: G

You might also like