示例#1
0
def test_crypto_hash():
    """
    Test that produced hash is equal the actual value
    """
    assert crypto_hash(
        'foo'
    ) == 'b2213295d564916f89a6a42455567c87c3f480fcd7a1c15e220f17d7169a790b'
示例#2
0
    def mine_block(last_block, data):
        """
        Mine a block based on the given last_block and data. Until a block hash
        is found that meets the leading 0's proof of work requirement.
        """
        timestamp = time.time_ns()
        last_hash = last_block.hash
        difficulty = Block.adjust_difficulty(last_block, timestamp)
        nonce = 0
        hash = crypto_hash(timestamp, last_hash, data, difficulty, nonce)

        while hex_to_binary(hash)[0:difficulty] != '0' * difficulty:
            nonce += 1
            timestamp = time.time_ns()
            hash = crypto_hash(timestamp, last_hash, data, difficulty, nonce)

        return Block(timestamp, last_hash, hash, data, difficulty, nonce)
示例#3
0
def main():
    number = 888
    hex_number = hex(number)[2:]
    print(f'hex_number: {hex_number}')

    binary_number = hex_to_binary(hex_number)
    print(f'binary_number: {binary_number}')

    original_number = int(binary_number, 2)
    print(f'original_number: {original_number}')

    hex_to_binary_crypto_hash = hex_to_binary(crypto_hash('test-data'))
    print(f'hex_to_binary_crypto_hash: {hex_to_binary_crypto_hash}')
示例#4
0
    def is_valid_block(last_block, block):
        """
        Validate block by enforcing the following rules:
        - the block must have the proper last_hash reference.
        - the block must meet the proof of work requirement.
        - the difficulty must only adjust by 1.
        - the block hash must be a valid combination of the block fields.
        """
        if block.last_hash != last_block.hash:
            raise Exception('last_hash must be correct')

        if hex_to_binary(
                block.hash)[0:block.difficulty] != '0' * block.difficulty:
            raise Exception('The proof of requirement was not met.')

        if abs(last_block.difficulty - block.difficulty) > 1:
            raise Exception('The block difficulty must only adjust by 1.')

        reconstructed_hash = crypto_hash(block.timestamp, block.last_hash,
                                         block.data, block.nonce,
                                         block.difficulty)

        if block.hash != reconstructed_hash:
            raise Exception('The block hash must be correct.')
示例#5
0
def test_crypto_hash_order():
    """
    test that crypto_hash function outputs same hash
    for different arguments order.
    """
    assert crypto_hash(1, [2], 'three') == crypto_hash('three', 1, [2])