def on_post(self, req, resp): req_data = req.media or {} resp_data, valid = Status_Request_Schema(method=HTTP_Method.POST) \ .validate(data=req_data) if valid: now = datetime_to_str() id = req_data.get('id') username = req_data.get('username', None) password = req_data.get('password', None) self.data['id'] = id self.data['last_heartbeat'] = now if username and self.auth_db.get(username, None) != hash(password): msg = f'Credentials from CB {req.host}:{req.port} not valid.' self.log.warning(msg) username = generate_username() password = generate_password() self.auth_db[username] = hash(password) self.log.notice(f'hearbeating from CB at {now}') data = dict(**self.data, username=username, password=password) resp_data, valid = Status_Response_Schema(method=HTTP_Method.POST) \ .validate(data=data) if valid: Content_Response(data).apply(resp) else: resp_data.apply(resp) else: resp_data.apply(resp)
def merkleize(chunks): tree = chunks[::] while not is_power_of_two(len(tree)): tree.append(ZERO_CHUNK) tree = [ZERO_CHUNK] * len(tree) + tree for i in range(len(tree) // 2 - 1, 0, -1): tree[i] = hash(tree[i * 2] + tree[i * 2 + 1]) return tree[1]
def __auth(self, username, password): auth_data = [(self.dev_username, self.dev_password)] auth_data.extend( zip(Status_Resource.auth_db.keys(), Status_Resource.auth_db.values())) if (username, hash(password)) in auth_data: return dict(username=username) else: return False
def calc_merkle_tree_from_leaves(values): values = list(values) tree = [values[::]] for h in range(32): if len(values) % 2 == 1: values.append(zerohashes[h]) values = [ hash(values[i] + values[i + 1]) for i in range(0, len(values), 2) ] tree.append(values[::]) return tree
def mix_in_length(root, length): return hash(root + length.to_bytes(32, 'little'))
from utils.hash import hash zerohashes = [b'\x00' * 32] for i in range(1, 32): zerohashes.append(hash(zerohashes[i - 1] + zerohashes[i - 1])) # Compute a Merkle root of a right-zerobyte-padded 2**32 sized tree def calc_merkle_tree_from_leaves(values): values = list(values) tree = [values[::]] for h in range(32): if len(values) % 2 == 1: values.append(zerohashes[h]) values = [ hash(values[i] + values[i + 1]) for i in range(0, len(values), 2) ] tree.append(values[::]) return tree def get_merkle_root(values): return calc_merkle_tree_from_leaves(values)[-1][0] def get_merkle_proof(tree, item_index): proof = [] for i in range(32): subindex = (item_index // 2**i) ^ 1 proof.append( tree[i][subindex] if subindex < len(tree[i]) else zerohashes[i])