def create_new_block(self): """ Create a fresh new block that contains all valid pending transactions. """ newb = Block(self.blockchain.top().hash) newb.index = self.blockchain.top().index + 1 newb.transactions.extend(self.blockchain.get_pending_transactions()) tx = Transaction(None, txtype=TxType.COINBASE) tx.add_out(MINING_REWARD, self.reward_addr) tx.finalize() newb.transactions.append(tx) return newb
def _test_fraudulent_tx(self, victim, blockchain): """ Try transaction from somebody else's "wallet" """ miner_key = generate_key() perpetrator = generate_key() utxo = blockchain.scan_unspent_transactions(victim.publickey()) perpetrator_owns = blockchain.scan_unspent_transactions( perpetrator.publickey()) self.assertEqual(len(perpetrator_owns), 0) # Sanity check # Let's handcraft tx that tries to steal victim's coins. tx = Transaction(perpetrator) # Sign it with random key utxo = blockchain.scan_unspent_transactions( victim.publickey()) # Get victim's utxo debit = sum(map(lambda x: x['value'], utxo)) for credit in utxo: tx.add_in(credit['hash'], sign(perpetrator, credit['hash']), victim.publickey(), credit['value']) tx.add_out(debit, perpetrator.publickey()) try: blockchain.add(tx) self.fail("Should've thrown UnauthorizedTxException") except UnauthorizedTxException: pass miner = Miner(blockchain) miner.reward_addr = miner_key.publickey() _ = miner._mine() perpetrator_owns = blockchain.scan_unspent_transactions( perpetrator.publickey()) # Should own nothing. This tx should've failed. self.assertEqual(len(perpetrator_owns), 0)
def test_pending_transactions(self): receiver = generate_key() tx = Transaction(None, txtype=TxType.COINBASE) tx.add_out(10, receiver.publickey()) blockchain = Blockchain() blockchain.add(tx) pending_tx = blockchain.get_pending_transactions() self.assertEqual(len(filter(lambda x: tx.hash, pending_tx)), 1) miner = Miner(blockchain) miner.reward_addr = receiver.publickey() newb = miner._mine() pending_tx = blockchain.get_pending_transactions() self.assertEqual(len(filter(lambda x: tx.hash, pending_tx)), 0) self.assertEqual(len(filter(lambda x: tx.hash, newb.transactions)), 2)