def verify(self): '''Returns whether this proof is valid''' current = self.tx_hash[::-1] path = merkle_path(self.index, 2**len(self.merkle_proof)) for i, proof_hash in enumerate(self.merkle_proof): if path[i] % 2 == 1: current = merkle_parent(proof_hash, current) else: current = merkle_parent(current, proof_hash) return current[::-1] == self.merkle_root
def verify(self): '''Returns whether this proof is valid''' # current hash starts with self.tx_hash, reversed current = self.tx_hash[::-1] # Get the Merkle Path for the index and 2**len(merkle_proof) path = merkle_path(self.index, 2**len(self.merkle_proof)) # Loop through Merkle Path and proof hashes for proof_hash, index_at_level in zip(self.merkle_proof, path): # if index_at_level is odd, proof_hash goes on left if index_at_level % 2 == 1: # current hash becomes merkle parent of proof_hash and current current = merkle_parent(proof_hash, current) # if index_at_level is even, proof_hash goes on right else: # current hash becomes merkle parent of current and proof_hash current = merkle_parent(current, proof_hash) # if final result reversed is equal to merkle_root, return True return current[::-1] == self.merkle_root
def create_merkle_proof(self, tx_hash): # if self.merkle_tree is empty, go and calculate the merkle tree if self.merkle_tree is None: self.calculate_merkle_tree() # find the index of this tx_hash index = self.tx_hashes.index(tx_hash) # Get the Merkle Path path = merkle_path(index, len(self.tx_hashes)) # initialize merkle_proof list proof_hashes = [] # Loop over the items in the Merkle Path for level, index_at_level in enumerate(path): # Find the partner index (-1 for odd, +1 for even) if index_at_level % 2 == 1: partner_index = index_at_level - 1 else: partner_index = index_at_level + 1 # add partner to merkle_proof list proof_hashes.append(self.merkle_tree[level][partner_index]) # Return a Proof instance return Proof(self.merkle_root, tx_hash, index, proof_hashes)
def create_merkle_proof(self, tx_hash): if self.tx_hashes is None: return None elif self.merkle_tree is None: self.calculate_merkle_tree() index = self.merkle_tree[0].index(tx_hash[::-1]) current = self.merkle_tree[0][index] proof_hashes = [] for level, level_index in enumerate( merkle_path(index, len(self.tx_hashes))): if level_index % 2 == 0: partner = self.merkle_tree[level][level_index + 1] current = merkle_parent(current, partner) else: partner = self.merkle_tree[level][level_index - 1] current = merkle_parent(partner, current) proof_hashes.append(partner) # sanity check if current != self.merkle_tree[-1][0]: raise RuntimeError('merkle tree looks invalid') return Proof(self.merkle_root, tx_hash, index, proof_hashes)
def test_merkle_path(self): i = 7 total = 11 want = [7, 3, 1, 0] self.assertEqual(merkle_path(i, total), want)