def test_transactions_validate_invalid_rewards(): miner_wallet = Wallet() reward_transaction = Transactions.transaction_reward(miner_wallet) reward_transaction.output[miner_wallet.address] = 100 reward_transaction.output['recp1'] = 100 with pytest.raises(Exception, match="Invalid transaction reward"): Transactions.verify_transaction(reward_transaction)
def is_chain_transaction_valid(chain): """ Method to verify if each of the transactions in the chain is valid. Transaction is valid if: 1. Each transation appears only once in the blockchain. 2. There is only one reward transaction. 3. The transaction is valid. """ transaction_ids = set() for index, block in enumerate(chain): if index == 0: continue has_reward_transaction = False for transaction_json in block.data: transaction = Transactions.from_json(transaction_json) if transaction.input == MINING_REWARD_INPUT: if has_reward_transaction is True: raise Exception( "Transaction with id %s has multiple rewards" % (transaction.id)) has_reward_transaction = True else: #calculate historical balance using a historical balance historical_chain = chain[:index] historical_blockchain = Blockchain() historical_blockchain.chain = historical_chain #get the balance amount of the address balance = Wallet.calculate_balance( historical_blockchain, transaction.input['address']) if balance != transaction.input['amount']: raise Exception( "Transaction id %s did not have the correct balance" % (transaction.id)) if transaction.id in transaction_ids: raise Exception("Transaction with id %s is not unique" % (transaction.id)) transaction_ids.add(transaction.id) Transactions.verify_transaction(transaction)
def test_transactions_validate_reward(): miner_wallet = Wallet() reward_transaction = Transactions.transaction_reward(miner_wallet) Transactions.verify_transaction(reward_transaction)
def test_verify_transactions_invalid_signature(): wallet = Wallet() transactions = Transactions(wallet, 'recp1', 100) transactions.input['signature'] = Wallet().sign(transactions.output) with pytest.raises(Exception, match="Invalid Signature"): Transactions.verify_transaction(transactions)
def test_verify_transactions_output_values_wrong(): wallet = Wallet() transactions = Transactions(wallet, 'recp1', 100) transactions.input['amount'] = 78 with pytest.raises(Exception, match="Invalid output values"): Transactions.verify_transaction(transactions)
def test_verify_transactions(): wallet = Wallet() transactions = Transactions(wallet, 'recp1', 100) Transactions.verify_transaction(transactions)