def main(): data = [] tree = MerkleTree(data, hashfunc) for i in ascii_lowercase: tree.append(i) beautify(tree) print("Original verify_leaf_inclusion") original_proof = tree.get_proof('a') print(tree.verify_leaf_inclusion('a', original_proof)) print("Proof to lists/ Lists to proof verify_leaf_inclusion") root = tree._root proof_hashs, proof_types = proof_to_lists(original_proof) remade_proof = lists_to_proof(proof_hashs, proof_types) print( merklelib.verify_leaf_inclusion('a', remade_proof, hashfunc, utils.to_hex(root.hash))) print("Proof to string test") string_proof = proof_to_string(original_proof) print(type(string_proof) == type("hello")) print("Proof to string/ String to proof verify_leaf_inclusion") new_proof = string_to_proof(string_proof) print( merklelib.verify_leaf_inclusion('a', remade_proof, hashfunc, utils.to_hex(root.hash)))
import string import hashlib from merklelib import MerkleTree, beautify data = ('A','B','C','D') # build a Merkle tree for the data tree = MerkleTree(data) # generate an audit proof for the element 'C' proof = tree.get_proof('C') # now verify that C is in the tree if tree.verify_leaf_inclusion('C', proof): print('C is in the tree') else: print('C is not in the tree') # generate an audit proof for the element 'E' proof = tree.get_proof('E') # now verify that E is not in the tree if tree.verify_leaf_inclusion('E', proof): print('E is in the tree') else: print('E is not in the tree') # perform a consistency check by checking if the new tree # contains the same items and in the same order as the old one
def main(): parser = argparse.ArgumentParser() parser.add_argument( '-s', '--size', help='Initial number of leaves', dest='size', default=2 ** 8 ) parser.add_argument( '-a', '--additional', help='Number of leaves that we need to append', dest='additional', default=2 ** 1 ) parser.add_argument( '-p', '--print', help=''' Beautify the whole tree. Recommended to use when the size of the tree is less than 10. ''', action='store_true', dest='printable' ) args = parser.parse_args() start, end = int(args.size), int(args.additional) count = start + end start_t = datetime.now() tree = MerkleTree(value for value in range(start)) print(f'Building: {_get_seconds(start_t)} seconds.') start_t = datetime.now() # appending for v in range(start, start + end): tree.append(v) print(f'Appending: {_get_seconds(start_t)} seconds.') print(f'Tree size: {getsize(tree)}') print(f'Number of leaves: {len(tree)}') if args.printable: beautify(tree) start_t = datetime.now() total, start_t = 0.0, datetime.now() max_t = min_t = None for leaf in range(count): cycle_t = datetime.now() proof = tree.get_proof(leaf) if not tree.verify_leaf_inclusion(leaf, proof): exit(f'Failed audit proof: {leaf}') seconds = _get_seconds(cycle_t) if max_t is None: max_t = min_t = seconds else: max_t = max(max_t, seconds) min_t = min(min_t, seconds) total += seconds print(f'Audit proof verification times:') _print_times( average=(total / float(count)), total=_get_seconds(start_t), max_t=max_t, min_t=min_t ) total, start_t = 0.0, datetime.now() max_t = min_t = None for limit in range(1, count): cycle_t = datetime.now() test = MerkleTree([value for value in range(limit)]) if tree < test: exit(f'Failed consistency proof: {limit}') seconds = _get_seconds(cycle_t) if max_t is None: max_t = min_t = seconds else: max_t = max(max_t, seconds) min_t = min(min_t, seconds) total += seconds print(f'Consitency proof verification times ({count} trees):') _print_times( average=(total / float(count)), total=_get_seconds(start_t), max_t=max_t, min_t=min_t )
@author: galan """ import string import hashlib import merklelib from merklelib import MerkleTree def hashfunc(value): return hashlib.sha256(value).hexdigest() data = list(string.ascii_letters) tree = MerkleTree(data, hashfunc) proof = tree.get_proof('A') if tree.verify_leaf_inclusion('A', proof): print('A is in the tree') else: print('A is not in the tree') MR = tree.merkle_root kappa = merklelib.verify_leaf_inclusion('A', proof, hashfunc, MR) from merklelib import utils
return hashlib.sha256(value).hexdigest() dom_name = sys.argv[1] day_num = sys.argv[2] file_name = "../../CA-middle-daemon-storage/Hashlists/" + dom_name + "/hashlist.txt" hash_file = open(file_name, 'r') hash_list = [] for line in hash_file: hash_list.append(line[:-1]) hash_file.close() tree = MerkleTree(hash_list, hashfunc) # Write root root = tree.merkle_root root_file = "../../middle-daemon-website-daemon-storage/Daily Cert Verification/merkleroot.txt" text_file = open(root_file, "w+") n = text_file.write(root) text_file.close() proof = tree.get_proof(hash_list[int(day_num)]) filename = "../../middle-daemon-website-daemon-storage/Daily Cert Verification/proof.pickle" with open(filename, 'wb') as f: pickle.dump(proof, f)
# Add all ASCII characters to Merkle tree for i in ascii_lowercase: asciiTree.append(i.encode('utf-8')) # Print MerkleTree print("\nPrinting Merkle Tree") beautify(asciiTree) print("\nPrinting root") print(asciiTree.merkle_root) print("\nPrinting leaves") print(asciiTree.leaves) # Generate an audit proof the letter a print("\nGenerating audit proof for a") proof = asciiTree.get_proof('a') print("\nProof: ") print(proof) # Verify that a is in the tree if asciiTree.verify_leaf_inclusion('a', proof): print('\na is in the tree') else: exit('a is not in the tree') # Add in longer string hash to test new_hash = "rgie3948guhiev" asciiTree.append(new_hash) # Generate an audit proof for the string print("\nGenerating audit proof for rgie3948guhiev")
async def get(self): """This method handles the GET requests for Tenant verifiers to talk with Provider verifiers """ rest_params = common.get_restful_params(self.request.uri) global tree if rest_params is None: common.echo_json_response( self, 405, "Not Implemented: Use /agents/interface") return if "agents" in rest_params: agent_id = rest_params["agents"] if agent_id is not None: agent = self.db.get_agent(agent_id) if agent != None: response = cloud_verifier_common.process_get_status(agent) common.echo_json_response(self, 200, "Success", response) else: #logger.info('GET returning 404 response. agent id: ' + agent_id + ' not found.') common.echo_json_response(self, 404, "agent id not found") else: # return the available keys in the DB json_response = self.db.get_agent_ids() common.echo_json_response(self, 200, "Success", {'uuids': json_response}) logger.info('GET returning 200 response for agent_id list') elif "verifier" in rest_params: partial_req = "1" # don't need a pub key agent = self.db.get_agent_ids() new_agent = self.db.get_agent(agent[0]) try: await nonce_col.put(rest_params["nonce"]) except Exception as e: print('error: ', e) new_agent['quote_col'].append(rest_params["nonce"]) self.db.update_all_agents('quote_col', new_agent['quote_col']) #Simulate busy TPM with async sleep function to allow testing of quote batching functionality await asyncio.sleep(10) try: agent = self.db.get_agent_ids() new_agent2 = self.db.get_agent(agent[0]) tree = MerkleTree([], hashfunc) logger.info("Concurrent Nonces: " + str(nonce_col.qsize())) for nonce in range(nonce_col.qsize()): temp = nonce_col.get() t = await temp logger.debug(t) tree.append(t) await nonce_col.put(t) logger.info("Making Merkle Tree in Provider Verifier") logger.info(beautify(tree)) nonce_proof = tree.get_proof(rest_params['nonce']) except Exception as e: print('error: ', e) rest_params['nonce'] = tree.merkle_root url = "http://%s:%d/quotes/integrity?nonce=%s&mask=%s&vmask=%s&partial=%s" % ( new_agent['ip'], new_agent['port'], rest_params["nonce"], rest_params["mask"], rest_params['vmask'], partial_req) res = tornado_requests.request("GET", url, context=None) response = await res json_response = json.loads(response.body) json_response_result = json_response["results"] json_response_result['nonce_proof'] = proof_to_string(nonce_proof) json_response_result['merkle_head'] = tree.merkle_root logger.debug("To string of Nonce Proof", json_response_result['merkle_head']) common.echo_json_response(self, 200, "Success", json_response_result) else: common.echo_json_response(self, 400, "uri not supported") logger.warning('GET returning 400 response. uri not supported: ' + self.request.path)