def test_calculate_balance(): blockchain = Blockchain() wallet = Wallet() # NEW: new Wallet() `wallet` should have initial balance assert Wallet.calculate_balance(blockchain, wallet.address) == INITIAL_BALANCE sent_amt = 50 outgoing_transaction = Transaction( wallet, "a13b2bf4", sent_amt) # send to `wallet` from "a13b2bf4" blockchain.add_block([outgoing_transaction.serialize_to_json()]) # SEND: `wallet` should have initial balance sans amt assert Wallet.calculate_balance( blockchain, wallet.address) == INITIAL_BALANCE - sent_amt received_amt_1 = 25 incoming_transaction_1 = Transaction( Wallet(), wallet.address, received_amt_1) # receive by `wallet` from new Wallet() received_amt_2 = 77 incoming_transaction_2 = Transaction(Wallet(), wallet.address, received_amt_2) blockchain.add_block([ incoming_transaction_1.serialize_to_json(), incoming_transaction_2.serialize_to_json() ]) # RECEIVE: `wallet` should have initial balance plus incoming amt(s) assert Wallet.calculate_balance( blockchain, wallet.address ) == INITIAL_BALANCE - sent_amt + received_amt_1 + received_amt_2
def test_purge(): tx_pool = TransactionPool() tx_1 = Transaction(Wallet(), "adc193bd", 1) tx_2 = Transaction(Wallet(), "adc193bd", 2) tx_pool.set_transaction(tx_1) tx_pool.set_transaction(tx_2) blockchain = Blockchain() blockchain.add_block([tx_1.serialize_to_json(), tx_2.serialize_to_json()]) assert tx_1.id in tx_pool.transaction_map assert tx_2.id in tx_pool.transaction_map # purge from Pool instance any Txs written to blockchain tx_pool.purge(blockchain) assert not tx_1.id in tx_pool.transaction_map assert not tx_2.id in tx_pool.transaction_map
def test_transaction_chain_when_tx_malformatted(clone_blockchain): malformed_tx_instance = Transaction(Wallet(), "b13b2bf4", 1) # sign with different wallet malformed_tx_instance.input["signature"] = Wallet().gen_signature( malformed_tx_instance.output) clone_blockchain.add_block([malformed_tx_instance.serialize_to_json()]) with pytest.raises(Exception): Blockchain.is_tx_chain_valid(clone_blockchain.chain)
def test_transaction_chain_when_invalid_balance_provenance(clone_blockchain): wallet = Wallet() malformed_tx_instance = Transaction(Wallet(), "b13b2bf4", 1) malformed_tx_instance.output[wallet.address] = 9000 malformed_tx_instance.input["amount"] = 9001 malformed_tx_instance.input["signature"] = wallet.gen_signature( malformed_tx_instance.output) clone_blockchain.add_block([malformed_tx_instance.serialize_to_json()]) with pytest.raises(Exception, match="contains an invalid input amount"): Blockchain.is_tx_chain_valid(clone_blockchain.chain)
def wallet_transaction_route(): tx_data = request.get_json() transaction = transaction_pool.existing_transaction(wallet.address) if transaction: transaction.tx_update( wallet, tx_data["recipient"], tx_data["amount"] ) else: transaction = Transaction( wallet, tx_data["recipient"], tx_data["amount"] ) pubsub.broadcast_transaction(transaction) return jsonify(transaction.serialize_to_json())