Comments (0)

Transcript of Session 7

SCRIPTFoundational MathSession 7 ObjectivesLearn Merkle TreesLearn Network MessagingLearn Node CommunicationLearn Merkle BlocksMerkle TreesMerkle BlocksNode CommunicationNetwork MessagingWhat is a Merkle Tree?Structured as a full binary tree.Computer Science structure useful for proving something belongs in a set without knowing the whole set.An efficient way to combine a lot of things into a single hash.Calculating a Merkle TreeGiven a list of items, hash them all using a hash function (bitcoin uses double-SHA256)Continue until you only have a single hashYou should have half the number of hashes as before.Pair them and if there’s an odd number, duplicate the last one so it has a pair.Hash the pair together to get the parent.Calculating the Merkle ParentTake each hash and concatenate them. Hash the result to get the parent.from helper import double_sha256

Pair up the hashesThe list of Merkle Parents is the Merkle Parent LevelCalculate the Merkle Parent for each pairMerkle Parent Level Duplicate the last elementIf there is an odd number of elements on a level:Append to end of the listExamplefrom helper import double_sha256, flip_endian, merkle_parenthex_hashes = [ 'c117ea8ec828342f4dfb0ad6bd140e03a50720ece40169ee38bdc15d9eb64cf5', ... '2e6d722e5e4dbdf2447ddecc9f7dabb8e299bae921c99ad5b0184cd9eb8e5908',]hashes = [bytes.fromhex(x) for x in hex_hashes]if len(hashes) % 2 == 1: hashes.append(hashes[-1])parent_level = []for i in range(0, len(hex_hashes), 2): parent = merkle_parent(hashes[i], hashes[i+1]) print(parent.hex()) parent_level.append(parent)Exercise 71. Calculate the parent level given these hashes

Why is a Merkle Tree useful?SPV is very useful where you don’t have room for the entire blockchain (100 GB+ and counting)You can prove a hash is in the tree without knowing the whole tree!Very useful for thin-clients using something called Simplified Payment Verification (SPV)Merkle ParentMerkle Parent LevelMerkle RootMerkle Root in BlocksMerkle BlocksWhat is a Merkle Block?Depth First Ordering of hashesExample Creating a Merkle TreeMerkle Block ProcessingExample of Populating and Navigating a Merkle Treefrom helper import merkle_parent_level

How do you process the Merkle Block Proof?If flag is 1 and is a leaf node, this is a hash the block is proving is included (green box)Flag Bits[1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0] and 7 hashesimport math