def test_valid_block_invalid_hash(last_block, block): ''' Purpose: Test that the block must have a valid hash. Corrupt the block's hash and validate. ''' block.hash = '0000000000000000bbbabc' with pytest.raises(Exception, match='must have a proper hash reference.'): Block.is_valid(last_block, block)
def test_invalid_block(last_block, block): ''' Purpose: Test that a block is invalid by corrupting its last_hash value and then validating. ''' block.last_hash = 'test-bad-hash' with pytest.raises(Exception, match="must have a proper last_hash reference."): Block.is_valid(last_block, block)
def test_valid_block_jumped_difficulty(last_block, block): ''' Purpose: Test that the a valid block cannot adjust its diffuclty any more or less than 1. Set block difficulty to greater than 1 and validate. ''' jumped_difficulty = 10 block.difficulty = jumped_difficulty block.hash = f'{"0" * jumped_difficulty}111abc' with pytest.raises(Exception, match='difficulty must only adjust by 1.'): Block.is_valid(last_block, block)
def test_valid_block_invalid_proof_of_work(last_block, block): ''' Purpose: Test that a block is not valid if the Proof-of-Work requirement is not met. Invalidate the Proof-of-Work by corrupting the block's hash value. ''' block.hash = 'fff' with pytest.raises(Exception, match='did not meet the Proof of Work Requirement.'): Block.is_valid(last_block, block)
def is_valid(chain): ''' Validate a block-chain by enforcing the following rules: - The chain must start with the genesis block. - Each block in the chain must be formatted correctly. ''' if chain[0] != Block.genesis(): raise Exception('The genesis block must be valid.') for i in range(1, len(chain)): block = chain[i] last_block = chain[i - 1] Block.is_valid(last_block, block) Blockchain.is_valid_trans_chain(chain)
def test_valid_block(last_block, block): ''' Purpose: Test that a block is valid. ''' Block.is_valid(last_block, block)