def test_compute_block_hash(self): # NOTE -- this implicitly tests Hasher.hash_iterable bd = self._build_valid_block_data() # Correct order of keys should be: # ['block_contender', # 'masternode_signature', # 'masternode_vk', # 'merkle_leaves', # 'merkle_root', # 'prev_block_hash', # 'timestamp'] binary_data = bd['block_contender'].serialize() binary_data += bd['masternode_signature'].encode() binary_data += bd['masternode_vk'].encode() binary_data += bd['merkle_leaves'].encode() binary_data += bd['merkle_root'].encode() binary_data += bd['prev_block_hash'].encode() binary_data += int_to_bytes(bd['timestamp']) expected_hash = Hasher.hash(binary_data) actual_hash = BlockStorageDriver._compute_block_hash(bd) self.assertEqual(expected_hash, actual_hash)
def _cast_to_bytes(data) -> bytes: """ Attempts to auto-cast the data to bytes, raising an error if not possible :param data: The data to attempt to cast to bytes :return: Bytes :raises: An assertion if data is a non-trivial type that could not be casted to bytes """ # MessageBase imported here to fix cyclic imports...TODO -- fix dependencies from cilantro.messages import MessageBase from cilantro.utils import int_to_bytes t = type(data) if t is str: data = data.encode() elif t is int: data = int_to_bytes(data) # try: # data = bytes.fromhex(hex(data)[2:]) # except: # data = bytes.fromhex('0' + hex(data)[2:]) elif issubclass(t, MessageBase): data = data.serialize() assert type(data) is bytes, "Unable to cast data of original type {} into bytes".format(t) return data
def test_inverse_operations(self): # We loop hella times cuz ya boy is paranoid it may not work for odds/integers in different ranges for _ in range(100): i = random.randint(0, MAX_INT) clone = bytes_to_int(int_to_bytes(i)) self.assertEqual(i, clone)
def test_int_to_bytes(self): b = int_to_bytes(12351) self.assertTrue(type(b) is bytes)