diff --git a/contrib/signet/miner b/contrib/signet/miner index b9a01080f14..c6ce7f92730 100755 --- a/contrib/signet/miner +++ b/contrib/signet/miner @@ -40,8 +40,7 @@ def signet_txs(block, challenge): txs[0].vout[-1].scriptPubKey += CScriptOp.encode_op_pushdata(SIGNET_HEADER) hashes = [] for tx in txs: - tx.rehash() - hashes.append(ser_uint256(tx.sha256)) + hashes.append(ser_uint256(tx.txid_int)) mroot = block.get_merkle_root(hashes) sd = b"" @@ -55,12 +54,11 @@ def signet_txs(block, challenge): to_spend.nLockTime = 0 to_spend.vin = [CTxIn(COutPoint(0, 0xFFFFFFFF), b"\x00" + CScriptOp.encode_op_pushdata(sd), 0)] to_spend.vout = [CTxOut(0, challenge)] - to_spend.rehash() spend = CTransaction() spend.version = 0 spend.nLockTime = 0 - spend.vin = [CTxIn(COutPoint(to_spend.sha256, 0), b"", 0)] + spend.vin = [CTxIn(COutPoint(to_spend.txid_int, 0), b"", 0)] spend.vout = [CTxOut(0, b"\x6a")] return spend, to_spend @@ -88,7 +86,6 @@ def finish_block(block, signet_solution, grind_cmd): pass # Don't need to add a signet commitment if there's no signet signature needed else: block.vtx[0].vout[-1].scriptPubKey += CScriptOp.encode_op_pushdata(SIGNET_HEADER + signet_solution) - block.vtx[0].rehash() block.hashMerkleRoot = block.calc_merkle_root() if grind_cmd is None: block.solve() @@ -111,7 +108,6 @@ def new_block(tmpl, reward_spk, *, blocktime=None, poolid=None): cbtx.vin = [CTxIn(COutPoint(0, 0xffffffff), scriptSig, MAX_SEQUENCE_NONFINAL)] cbtx.vout = [CTxOut(tmpl["coinbasevalue"], reward_spk)] cbtx.vin[0].nSequence = 2**32-2 - cbtx.rehash() block = CBlock() block.nVersion = tmpl["version"] @@ -130,7 +126,6 @@ def new_block(tmpl, reward_spk, *, blocktime=None, poolid=None): block.vtx[0].wit.vtxinwit = [cbwit] block.vtx[0].vout.append(CTxOut(0, bytes(get_witness_script(witroot, witnonce)))) - block.vtx[0].rehash() block.hashMerkleRoot = block.calc_merkle_root() return block diff --git a/test/functional/data/invalid_txs.py b/test/functional/data/invalid_txs.py index 99c01abb2f1..36b274efc27 100644 --- a/test/functional/data/invalid_txs.py +++ b/test/functional/data/invalid_txs.py @@ -83,7 +83,7 @@ class BadTxTemplate: def __init__(self, *, spend_tx=None, spend_block=None): self.spend_tx = spend_block.vtx[0] if spend_block else spend_tx self.spend_avail = sum(o.nValue for o in self.spend_tx.vout) - self.valid_txin = CTxIn(COutPoint(self.spend_tx.sha256, 0), b"", SEQUENCE_FINAL) + self.valid_txin = CTxIn(COutPoint(self.spend_tx.txid_int, 0), b"", SEQUENCE_FINAL) @abc.abstractmethod def get_tx(self, *args, **kwargs): @@ -98,7 +98,6 @@ class OutputMissing(BadTxTemplate): def get_tx(self): tx = CTransaction() tx.vin.append(self.valid_txin) - tx.calc_sha256() return tx @@ -113,7 +112,6 @@ class InputMissing(BadTxTemplate): # rather than the input count check. def get_tx(self): tx = CTransaction() - tx.calc_sha256() return tx @@ -130,7 +128,6 @@ class SizeTooSmall(BadTxTemplate): tx.vout.append(CTxOut(0, CScript([OP_RETURN] + ([OP_0] * (MIN_PADDING - 2))))) assert len(tx.serialize_without_witness()) == 64 assert MIN_STANDARD_TX_NONWITNESS_SIZE - 1 == 64 - tx.calc_sha256() return tx @@ -147,9 +144,8 @@ class BadInputOutpointIndex(BadTxTemplate): bad_idx = num_indices + 100 tx = CTransaction() - tx.vin.append(CTxIn(COutPoint(self.spend_tx.sha256, bad_idx), b"", SEQUENCE_FINAL)) + tx.vin.append(CTxIn(COutPoint(self.spend_tx.txid_int, bad_idx), b"", SEQUENCE_FINAL)) tx.vout.append(CTxOut(0, basic_p2sh)) - tx.calc_sha256() return tx @@ -162,7 +158,6 @@ class DuplicateInput(BadTxTemplate): tx.vin.append(self.valid_txin) tx.vin.append(self.valid_txin) tx.vout.append(CTxOut(1, basic_p2sh)) - tx.calc_sha256() return tx @@ -175,7 +170,6 @@ class PrevoutNullInput(BadTxTemplate): tx.vin.append(self.valid_txin) tx.vin.append(CTxIn(COutPoint(hash=0, n=0xffffffff))) tx.vout.append(CTxOut(1, basic_p2sh)) - tx.calc_sha256() return tx @@ -187,10 +181,9 @@ class NonexistentInput(BadTxTemplate): def get_tx(self): tx = CTransaction() - tx.vin.append(CTxIn(COutPoint(self.spend_tx.sha256 + 1, 0), b"", SEQUENCE_FINAL)) + tx.vin.append(CTxIn(COutPoint(self.spend_tx.txid_int + 1, 0), b"", SEQUENCE_FINAL)) tx.vin.append(self.valid_txin) tx.vout.append(CTxOut(1, basic_p2sh)) - tx.calc_sha256() return tx @@ -226,7 +219,6 @@ class CreateSumTooLarge(BadTxTemplate): def get_tx(self): tx = create_tx_with_script(self.spend_tx, 0, amount=MAX_MONEY) tx.vout = [tx.vout[0]] * 2 - tx.calc_sha256() return tx @@ -274,7 +266,6 @@ def getDisabledOpcodeTemplate(opcode): vin.scriptSig = CScript([opcode]) tx.vin.append(vin) tx.vout.append(CTxOut(1, basic_p2sh)) - tx.calc_sha256() return tx return type('DisabledOpcode_' + str(opcode), (BadTxTemplate,), { diff --git a/test/functional/feature_assumeutxo.py b/test/functional/feature_assumeutxo.py index 094e8549c31..3309a6d21ed 100755 --- a/test/functional/feature_assumeutxo.py +++ b/test/functional/feature_assumeutxo.py @@ -605,7 +605,7 @@ class AssumeutxoTest(BitcoinTestFramework): privkey = n0.get_deterministic_priv_key().key raw_tx = n1.createrawtransaction([prevout], {getnewdestination()[2]: 24.99}) signed_tx = n1.signrawtransactionwithkey(raw_tx, [privkey], [prevout])['hex'] - signed_txid = tx_from_hex(signed_tx).rehash() + signed_txid = tx_from_hex(signed_tx).txid_hex assert n1.gettxout(prev_tx['txid'], 0) is not None n1.sendrawtransaction(signed_tx) diff --git a/test/functional/feature_assumevalid.py b/test/functional/feature_assumevalid.py index 2f67ef85365..7fd9c11c7dc 100755 --- a/test/functional/feature_assumevalid.py +++ b/test/functional/feature_assumevalid.py @@ -117,9 +117,8 @@ class AssumeValidTest(BitcoinTestFramework): # Create a transaction spending the coinbase output with an invalid (null) signature tx = CTransaction() - tx.vin.append(CTxIn(COutPoint(self.block1.vtx[0].sha256, 0), scriptSig=b"")) + tx.vin.append(CTxIn(COutPoint(self.block1.vtx[0].txid_int, 0), scriptSig=b"")) tx.vout.append(CTxOut(49 * 100000000, CScript([OP_TRUE]))) - tx.calc_sha256() block102 = create_block(self.tip, create_coinbase(height), self.block_time, txlist=[tx]) self.block_time += 1 diff --git a/test/functional/feature_bip68_sequence.py b/test/functional/feature_bip68_sequence.py index d8c28c72031..fc2e699f456 100755 --- a/test/functional/feature_bip68_sequence.py +++ b/test/functional/feature_bip68_sequence.py @@ -110,7 +110,6 @@ class BIP68Test(BitcoinTestFramework): tx2.wit.vtxinwit = [CTxInWitness()] tx2.wit.vtxinwit[0].scriptWitness.stack = [CScript([OP_TRUE])] tx2.vout = [CTxOut(int(value - self.relayfee * COIN), SCRIPT_W0_SH_OP_TRUE)] - tx2.rehash() assert_raises_rpc_error(-26, NOT_FINAL_ERROR, self.wallet.sendrawtransaction, from_node=self.nodes[0], tx_hex=tx2.serialize().hex()) @@ -220,17 +219,15 @@ class BIP68Test(BitcoinTestFramework): # Create a mempool tx. self.wallet.rescan_utxos() tx1 = self.wallet.send_self_transfer(from_node=self.nodes[0])["tx"] - tx1.rehash() # Anyone-can-spend mempool tx. # Sequence lock of 0 should pass. tx2 = CTransaction() tx2.version = 2 - tx2.vin = [CTxIn(COutPoint(tx1.sha256, 0), nSequence=0)] + tx2.vin = [CTxIn(COutPoint(tx1.txid_int, 0), nSequence=0)] tx2.vout = [CTxOut(int(tx1.vout[0].nValue - self.relayfee * COIN), SCRIPT_W0_SH_OP_TRUE)] self.wallet.sign_tx(tx=tx2) tx2_raw = tx2.serialize().hex() - tx2.rehash() self.wallet.sendrawtransaction(from_node=self.nodes[0], tx_hex=tx2_raw) @@ -244,13 +241,12 @@ class BIP68Test(BitcoinTestFramework): tx = CTransaction() tx.version = 2 - tx.vin = [CTxIn(COutPoint(orig_tx.sha256, 0), nSequence=sequence_value)] + tx.vin = [CTxIn(COutPoint(orig_tx.txid_int, 0), nSequence=sequence_value)] tx.wit.vtxinwit = [CTxInWitness()] tx.wit.vtxinwit[0].scriptWitness.stack = [CScript([OP_TRUE])] tx.vout = [CTxOut(int(orig_tx.vout[0].nValue - relayfee * COIN), SCRIPT_W0_SH_OP_TRUE)] - tx.rehash() - if (orig_tx.hash in node.getrawmempool()): + if (orig_tx.txid_hex in node.getrawmempool()): # sendrawtransaction should fail if the tx is in the mempool assert_raises_rpc_error(-26, NOT_FINAL_ERROR, self.wallet.sendrawtransaction, from_node=node, tx_hex=tx.serialize().hex()) else: @@ -264,43 +260,43 @@ class BIP68Test(BitcoinTestFramework): # Now mine some blocks, but make sure tx2 doesn't get mined. # Use prioritisetransaction to lower the effective feerate to 0 - self.nodes[0].prioritisetransaction(txid=tx2.hash, fee_delta=int(-self.relayfee*COIN)) + self.nodes[0].prioritisetransaction(txid=tx2.txid_hex, fee_delta=int(-self.relayfee*COIN)) cur_time = int(time.time()) for _ in range(10): self.nodes[0].setmocktime(cur_time + 600) self.generate(self.wallet, 1, sync_fun=self.no_op) cur_time += 600 - assert tx2.hash in self.nodes[0].getrawmempool() + assert tx2.txid_hex in self.nodes[0].getrawmempool() test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=True) test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=False) # Mine tx2, and then try again - self.nodes[0].prioritisetransaction(txid=tx2.hash, fee_delta=int(self.relayfee*COIN)) + self.nodes[0].prioritisetransaction(txid=tx2.txid_hex, fee_delta=int(self.relayfee*COIN)) # Advance the time on the node so that we can test timelocks self.nodes[0].setmocktime(cur_time+600) # Save block template now to use for the reorg later tmpl = self.nodes[0].getblocktemplate(NORMAL_GBT_REQUEST_PARAMS) self.generate(self.nodes[0], 1) - assert tx2.hash not in self.nodes[0].getrawmempool() + assert tx2.txid_hex not in self.nodes[0].getrawmempool() # Now that tx2 is not in the mempool, a sequence locked spend should # succeed tx3 = test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=False) - assert tx3.hash in self.nodes[0].getrawmempool() + assert tx3.txid_hex in self.nodes[0].getrawmempool() self.generate(self.nodes[0], 1) - assert tx3.hash not in self.nodes[0].getrawmempool() + assert tx3.txid_hex not in self.nodes[0].getrawmempool() # One more test, this time using height locks tx4 = test_nonzero_locks(tx3, self.nodes[0], self.relayfee, use_height_lock=True) - assert tx4.hash in self.nodes[0].getrawmempool() + assert tx4.txid_hex in self.nodes[0].getrawmempool() # Now try combining confirmed and unconfirmed inputs tx5 = test_nonzero_locks(tx4, self.nodes[0], self.relayfee, use_height_lock=True) - assert tx5.hash not in self.nodes[0].getrawmempool() + assert tx5.txid_hex not in self.nodes[0].getrawmempool() utxo = self.wallet.get_utxo() tx5.vin.append(CTxIn(COutPoint(int(utxo["txid"], 16), utxo["vout"]), nSequence=1)) @@ -319,8 +315,8 @@ class BIP68Test(BitcoinTestFramework): # If we invalidate the tip, tx3 should get added to the mempool, causing # tx4 to be removed (fails sequence-lock). self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) - assert tx4.hash not in self.nodes[0].getrawmempool() - assert tx3.hash in self.nodes[0].getrawmempool() + assert tx4.txid_hex not in self.nodes[0].getrawmempool() + assert tx3.txid_hex in self.nodes[0].getrawmempool() # Now mine 2 empty blocks to reorg out the current tip (labeled tip-1 in # diagram above). @@ -337,8 +333,8 @@ class BIP68Test(BitcoinTestFramework): cur_time += 1 mempool = self.nodes[0].getrawmempool() - assert tx3.hash not in mempool - assert tx2.hash in mempool + assert tx3.txid_hex not in mempool + assert tx2.txid_hex in mempool # Reset the chain and get rid of the mocktimed-blocks self.nodes[0].setmocktime(0) @@ -353,19 +349,17 @@ class BIP68Test(BitcoinTestFramework): assert not softfork_active(self.nodes[0], 'csv') tx1 = self.wallet.send_self_transfer(from_node=self.nodes[0])["tx"] - tx1.rehash() # Make an anyone-can-spend transaction tx2 = CTransaction() tx2.version = 1 - tx2.vin = [CTxIn(COutPoint(tx1.sha256, 0), nSequence=0)] + tx2.vin = [CTxIn(COutPoint(tx1.txid_int, 0), nSequence=0)] tx2.vout = [CTxOut(int(tx1.vout[0].nValue - self.relayfee * COIN), SCRIPT_W0_SH_OP_TRUE)] # sign tx2 self.wallet.sign_tx(tx=tx2) tx2_raw = tx2.serialize().hex() tx2 = tx_from_hex(tx2_raw) - tx2.rehash() self.wallet.sendrawtransaction(from_node=self.nodes[0], tx_hex=tx2_raw) @@ -374,11 +368,10 @@ class BIP68Test(BitcoinTestFramework): tx3 = CTransaction() tx3.version = 2 - tx3.vin = [CTxIn(COutPoint(tx2.sha256, 0), nSequence=sequence_value)] + tx3.vin = [CTxIn(COutPoint(tx2.txid_int, 0), nSequence=sequence_value)] tx3.wit.vtxinwit = [CTxInWitness()] tx3.wit.vtxinwit[0].scriptWitness.stack = [CScript([OP_TRUE])] tx3.vout = [CTxOut(int(tx2.vout[0].nValue - self.relayfee * COIN), SCRIPT_W0_SH_OP_TRUE)] - tx3.rehash() assert_raises_rpc_error(-26, NOT_FINAL_ERROR, self.wallet.sendrawtransaction, from_node=self.nodes[0], tx_hex=tx3.serialize().hex()) diff --git a/test/functional/feature_block.py b/test/functional/feature_block.py index e00bd7dda14..0e2e685247f 100755 --- a/test/functional/feature_block.py +++ b/test/functional/feature_block.py @@ -109,7 +109,6 @@ class FullBlockTest(BitcoinTestFramework): # Create a new block b_dup_cb = self.next_block('dup_cb') b_dup_cb.vtx[0].vin[0].scriptSig = DUPLICATE_COINBASE_SCRIPT_SIG - b_dup_cb.vtx[0].rehash() duplicate_tx = b_dup_cb.vtx[0] b_dup_cb = self.update_block('dup_cb', []) self.send_blocks([b_dup_cb]) @@ -125,8 +124,8 @@ class FullBlockTest(BitcoinTestFramework): self.send_blocks([b0]) # Will test spending once possibly-mature - max_size_spendable_output = CTxIn(COutPoint(b0.vtx[0].sha256, 1)) - min_size_unspendable_output = CTxIn(COutPoint(b0.vtx[0].sha256, 2)) + max_size_spendable_output = CTxIn(COutPoint(b0.vtx[0].txid_int, 1)) + min_size_unspendable_output = CTxIn(COutPoint(b0.vtx[0].txid_int, 2)) # These constants chosen specifically to trigger an immature coinbase spend # at a certain time below. @@ -151,7 +150,7 @@ class FullBlockTest(BitcoinTestFramework): # MAX_SCRIPT_SIZE + 1 wasn't added to the utxo set tx.vin[0] = min_size_unspendable_output - assert_raises_rpc_error(-25, f'TestBlockValidity failed: bad-txns-inputs-missingorspent, CheckTxInputs: inputs missing/spent in transaction {tx.rehash()}', self.generateblock, self.nodes[0], output="raw(55)", transactions=[tx.serialize().hex()]) + assert_raises_rpc_error(-25, f'TestBlockValidity failed: bad-txns-inputs-missingorspent, CheckTxInputs: inputs missing/spent in transaction {tx.txid_hex}', self.generateblock, self.nodes[0], output="raw(55)", transactions=[tx.serialize().hex()]) # collect spendable outputs now to avoid cluttering the code later on out = [] @@ -194,7 +193,6 @@ class FullBlockTest(BitcoinTestFramework): badtx = template.get_tx() if TxTemplate != invalid_txs.InputMissing: self.sign_tx(badtx, attempt_spend_tx) - badtx.rehash() badblock = self.update_block(blockname, [badtx]) self.send_blocks( [badblock], success=False, @@ -356,7 +354,7 @@ class FullBlockTest(BitcoinTestFramework): script_length = (MAX_BLOCK_WEIGHT - b23.get_weight() - 276) // 4 script_output = CScript([b'\x00' * script_length]) tx.vout.append(CTxOut(0, script_output)) - tx.vin.append(CTxIn(COutPoint(b23.vtx[1].sha256, 0))) + tx.vin.append(CTxIn(COutPoint(b23.vtx[1].txid_int, 0))) b23 = self.update_block(23, [tx]) # Make sure the math above worked out to produce a max-weighted block assert_equal(b23.get_weight(), MAX_BLOCK_WEIGHT) @@ -385,7 +383,6 @@ class FullBlockTest(BitcoinTestFramework): self.move_tip(15) b26 = self.next_block(26, spend=out[6]) b26.vtx[0].vin[0].scriptSig = b'\x00' - b26.vtx[0].rehash() # update_block causes the merkle root to get updated, even with no new # transactions, and updates the required state. b26 = self.update_block(26, []) @@ -399,7 +396,6 @@ class FullBlockTest(BitcoinTestFramework): self.move_tip(15) b28 = self.next_block(28, spend=out[6]) b28.vtx[0].vin[0].scriptSig = b'\x00' * 101 - b28.vtx[0].rehash() b28 = self.update_block(28, []) self.send_blocks([b28], success=False, reject_reason='bad-cb-length', reconnect=True) @@ -413,7 +409,6 @@ class FullBlockTest(BitcoinTestFramework): b30.vtx[0].vin[0].scriptSig = bytes(b30.vtx[0].vin[0].scriptSig) # Convert CScript to raw bytes b30.vtx[0].vin[0].scriptSig += b'\x00' * (100 - len(b30.vtx[0].vin[0].scriptSig)) # Fill with 0s assert_equal(len(b30.vtx[0].vin[0].scriptSig), 100) - b30.vtx[0].rehash() b30 = self.update_block(30, []) self.send_blocks([b30], True) self.save_spendable_output() @@ -516,7 +511,6 @@ class FullBlockTest(BitcoinTestFramework): tx = self.create_tx(spend, 0, 1, p2sh_script) tx.vout.append(CTxOut(spend.vout[0].nValue - 1, CScript([OP_TRUE]))) self.sign_tx(tx, spend) - tx.rehash() b39 = self.update_block(39, [tx]) b39_outputs += 1 @@ -527,7 +521,6 @@ class FullBlockTest(BitcoinTestFramework): while total_weight < MAX_BLOCK_WEIGHT: tx_new = self.create_tx(tx_last, 1, 1, p2sh_script) tx_new.vout.append(CTxOut(tx_last.vout[1].nValue - 1, CScript([OP_TRUE]))) - tx_new.rehash() total_weight += tx_new.get_weight() if total_weight >= MAX_BLOCK_WEIGHT: break @@ -561,25 +554,24 @@ class FullBlockTest(BitcoinTestFramework): numTxes = (MAX_BLOCK_SIGOPS - sigops) // b39_sigops_per_output assert_equal(numTxes <= b39_outputs, True) - lastOutpoint = COutPoint(b40.vtx[1].sha256, 0) + lastOutpoint = COutPoint(b40.vtx[1].txid_int, 0) new_txs = [] for i in range(1, numTxes + 1): tx = CTransaction() tx.vout.append(CTxOut(1, CScript([OP_TRUE]))) tx.vin.append(CTxIn(lastOutpoint, b'')) # second input is corresponding P2SH output from b39 - tx.vin.append(CTxIn(COutPoint(b39.vtx[i].sha256, 0), b'')) + tx.vin.append(CTxIn(COutPoint(b39.vtx[i].txid_int, 0), b'')) # Note: must pass the redeem_script (not p2sh_script) to the signature hash function tx.vin[1].scriptSig = CScript([redeem_script]) sign_input_legacy(tx, 1, redeem_script, self.coinbase_key) new_txs.append(tx) - lastOutpoint = COutPoint(tx.sha256, 0) + lastOutpoint = COutPoint(tx.txid_int, 0) b40_sigops_to_fill = MAX_BLOCK_SIGOPS - (numTxes * b39_sigops_per_output + sigops) + 1 tx = CTransaction() tx.vin.append(CTxIn(lastOutpoint, b'')) tx.vout.append(CTxOut(1, CScript([OP_CHECKSIG] * b40_sigops_to_fill))) - tx.rehash() new_txs.append(tx) self.update_block(40, new_txs) self.send_blocks([b40], success=False, reject_reason='bad-blk-sigops', reconnect=True) @@ -593,7 +585,6 @@ class FullBlockTest(BitcoinTestFramework): tx = CTransaction() tx.vin.append(CTxIn(lastOutpoint, b'')) tx.vout.append(CTxOut(1, CScript([OP_CHECKSIG] * b41_sigops_to_fill))) - tx.rehash() self.update_block(41, [tx]) self.send_blocks([b41], True) @@ -831,9 +822,8 @@ class FullBlockTest(BitcoinTestFramework): self.next_block(58, spend=out[17]) tx = CTransaction() assert len(out[17].vout) < 42 - tx.vin.append(CTxIn(COutPoint(out[17].sha256, 42), CScript([OP_TRUE]), SEQUENCE_FINAL)) + tx.vin.append(CTxIn(COutPoint(out[17].txid_int, 42), CScript([OP_TRUE]), SEQUENCE_FINAL)) tx.vout.append(CTxOut(0, b"")) - tx.calc_sha256() b58 = self.update_block(58, [tx]) self.send_blocks([b58], success=False, reject_reason='bad-txns-inputs-missingorspent', reconnect=True) @@ -865,7 +855,6 @@ class FullBlockTest(BitcoinTestFramework): b61 = self.next_block(61) b61.vtx[0].nLockTime = 0 b61.vtx[0].vin[0].scriptSig = DUPLICATE_COINBASE_SCRIPT_SIG - b61.vtx[0].rehash() b61 = self.update_block(61, []) assert_equal(duplicate_tx.serialize(), b61.vtx[0].serialize()) # BIP30 is always checked on regtest, regardless of the BIP34 activation height @@ -879,22 +868,20 @@ class FullBlockTest(BitcoinTestFramework): self.move_tip(57) self.next_block('spend_dup_cb') tx = CTransaction() - tx.vin.append(CTxIn(COutPoint(duplicate_tx.sha256, 0))) + tx.vin.append(CTxIn(COutPoint(duplicate_tx.txid_int, 0))) tx.vout.append(CTxOut(0, CScript([OP_TRUE]))) self.sign_tx(tx, duplicate_tx) - tx.rehash() b_spend_dup_cb = self.update_block('spend_dup_cb', [tx]) b_dup_2 = self.next_block('dup_2') b_dup_2.vtx[0].nLockTime = 0 b_dup_2.vtx[0].vin[0].scriptSig = DUPLICATE_COINBASE_SCRIPT_SIG - b_dup_2.vtx[0].rehash() b_dup_2 = self.update_block('dup_2', []) assert_equal(duplicate_tx.serialize(), b_dup_2.vtx[0].serialize()) - assert_equal(self.nodes[0].gettxout(txid=duplicate_tx.hash, n=0)['confirmations'], 119) + assert_equal(self.nodes[0].gettxout(txid=duplicate_tx.txid_hex, n=0)['confirmations'], 119) self.send_blocks([b_spend_dup_cb, b_dup_2], success=True) # The duplicate has less confirmations - assert_equal(self.nodes[0].gettxout(txid=duplicate_tx.hash, n=0)['confirmations'], 1) + assert_equal(self.nodes[0].gettxout(txid=duplicate_tx.txid_hex, n=0)['confirmations'], 1) # Test tx.isFinal is properly rejected (not an exhaustive tx.isFinal test, that should be in data-driven transaction tests) # @@ -906,10 +893,9 @@ class FullBlockTest(BitcoinTestFramework): self.next_block(62) tx = CTransaction() tx.nLockTime = 0xffffffff # this locktime is non-final - tx.vin.append(CTxIn(COutPoint(out[18].sha256, 0))) # don't set nSequence + tx.vin.append(CTxIn(COutPoint(out[18].txid_int, 0))) # don't set nSequence tx.vout.append(CTxOut(0, CScript([OP_TRUE]))) assert_greater_than(SEQUENCE_FINAL, tx.vin[0].nSequence) - tx.calc_sha256() b62 = self.update_block(62, [tx]) self.send_blocks([b62], success=False, reject_reason='bad-txns-nonfinal', reconnect=True) @@ -923,7 +909,6 @@ class FullBlockTest(BitcoinTestFramework): b63 = self.next_block(63) b63.vtx[0].nLockTime = 0xffffffff b63.vtx[0].vin[0].nSequence = 0xDEADBEEF - b63.vtx[0].rehash() b63 = self.update_block(63, []) self.send_blocks([b63], success=False, reject_reason='bad-txns-nonfinal', reconnect=True) @@ -956,7 +941,7 @@ class FullBlockTest(BitcoinTestFramework): script_length = (MAX_BLOCK_WEIGHT - 4 * len(b64a.normal_serialize()) - 276) // 4 script_output = CScript([b'\x00' * script_length]) tx.vout.append(CTxOut(0, script_output)) - tx.vin.append(CTxIn(COutPoint(b64a.vtx[1].sha256, 0))) + tx.vin.append(CTxIn(COutPoint(b64a.vtx[1].txid_int, 0))) b64a = self.update_block("64a", [tx]) assert_equal(b64a.get_weight(), MAX_BLOCK_WEIGHT + 8 * 4) self.send_blocks([b64a], success=False, reject_reason='non-canonical ReadCompactSize()') @@ -1053,10 +1038,9 @@ class FullBlockTest(BitcoinTestFramework): self.log.info("Reject a block containing a transaction spending from a non-existent input") self.move_tip(69) self.next_block(70, spend=out[21]) - bogus_tx = CTransaction() - bogus_tx.sha256 = uint256_from_str(b"23c70ed7c0506e9178fc1a987f40a33946d4ad4c962b5ae3a52546da53af0c5c") + bogus_txid_int = uint256_from_str(b"23c70ed7c0506e9178fc1a987f40a33946d4ad4c962b5ae3a52546da53af0c5c") tx = CTransaction() - tx.vin.append(CTxIn(COutPoint(bogus_tx.sha256, 0), b"", SEQUENCE_FINAL)) + tx.vin.append(CTxIn(COutPoint(bogus_txid_int, 0), b"", SEQUENCE_FINAL)) tx.vout.append(CTxOut(1, b"")) b70 = self.update_block(70, [tx]) self.send_blocks([b70], success=False, reject_reason='bad-txns-inputs-missingorspent', reconnect=True) @@ -1227,8 +1211,8 @@ class FullBlockTest(BitcoinTestFramework): # now check that tx78 and tx79 have been put back into the peer's mempool mempool = self.nodes[0].getrawmempool() assert_equal(len(mempool), 2) - assert tx78.hash in mempool - assert tx79.hash in mempool + assert tx78.txid_hex in mempool + assert tx79.txid_hex in mempool # Test invalid opcodes in dead execution paths. # @@ -1242,7 +1226,6 @@ class FullBlockTest(BitcoinTestFramework): tx2 = self.create_and_sign_transaction(tx1, 0, CScript([OP_TRUE])) tx2.vin[0].scriptSig = CScript([OP_FALSE]) - tx2.rehash() b83 = self.update_block(83, [tx1, tx2]) self.send_blocks([b83], True) @@ -1260,9 +1243,7 @@ class FullBlockTest(BitcoinTestFramework): tx1.vout.append(CTxOut(0, CScript([OP_TRUE]))) tx1.vout.append(CTxOut(0, CScript([OP_TRUE]))) tx1.vout.append(CTxOut(0, CScript([OP_TRUE]))) - tx1.calc_sha256() self.sign_tx(tx1, out[29]) - tx1.rehash() tx2 = self.create_tx(tx1, 1, 0, CScript([OP_RETURN])) tx2.vout.append(CTxOut(0, CScript([OP_RETURN]))) tx3 = self.create_tx(tx1, 2, 0, CScript([OP_RETURN])) @@ -1313,7 +1294,7 @@ class FullBlockTest(BitcoinTestFramework): script_length = (MAX_BLOCK_WEIGHT - b.get_weight() - 276) // 4 script_output = CScript([b'\x00' * script_length]) tx.vout.append(CTxOut(0, script_output)) - tx.vin.append(CTxIn(COutPoint(b.vtx[1].sha256, 0))) + tx.vin.append(CTxIn(COutPoint(b.vtx[1].txid_int, 0))) b = self.update_block(i, [tx]) assert_equal(b.get_weight(), MAX_BLOCK_WEIGHT) blocks.append(b) @@ -1348,7 +1329,6 @@ class FullBlockTest(BitcoinTestFramework): self.move_tip(chain1_tip + 2) b_cb34 = self.next_block('b_cb34') b_cb34.vtx[0].vin[0].scriptSig = b_cb34.vtx[0].vin[0].scriptSig[:-1] - b_cb34.vtx[0].rehash() b_cb34.hashMerkleRoot = b_cb34.calc_merkle_root() b_cb34.solve() self.send_blocks([b_cb34], success=False, reject_reason='bad-cb-height', reconnect=True) @@ -1357,7 +1337,6 @@ class FullBlockTest(BitcoinTestFramework): ################ def add_transactions_to_block(self, block, tx_list): - [tx.rehash() for tx in tx_list] block.vtx.extend(tx_list) # this is a little handier to use than the version in blocktools.py @@ -1380,7 +1359,6 @@ class FullBlockTest(BitcoinTestFramework): output_script = CScript([OP_TRUE]) tx = self.create_tx(spend_tx, 0, value, output_script=output_script) self.sign_tx(tx, spend_tx) - tx.rehash() return tx def next_block(self, number, spend=None, additional_coinbase_value=0, *, script=None, version=4, additional_output_scripts=None): @@ -1400,15 +1378,12 @@ class FullBlockTest(BitcoinTestFramework): coinbase.vout[0].nValue += additional_coinbase_value for additional_script in additional_output_scripts: coinbase.vout.append(CTxOut(0, additional_script)) - coinbase.rehash() if spend is None: block = create_block(base_block_hash, coinbase, block_time, version=version) else: coinbase.vout[0].nValue += spend.vout[0].nValue - 1 # all but one satoshi to fees - coinbase.rehash() tx = self.create_tx(spend, 0, 1, output_script=script) # spend 1 satoshi self.sign_tx(tx, spend) - tx.rehash() block = create_block(base_block_hash, coinbase, block_time, version=version, txlist=[tx]) # Block is created. Find a valid nonce. block.solve() diff --git a/test/functional/feature_cltv.py b/test/functional/feature_cltv.py index 60b3fb4e20b..06b5bf9698d 100755 --- a/test/functional/feature_cltv.py +++ b/test/functional/feature_cltv.py @@ -43,7 +43,6 @@ def cltv_modify_tx(tx, prepend_scriptsig, nsequence=None, nlocktime=None): tx.nLockTime = nlocktime tx.vin[0].scriptSig = CScript(prepend_scriptsig + list(CScript(tx.vin[0].scriptSig))) - tx.rehash() def cltv_invalidate(tx, failure_reason): @@ -163,8 +162,8 @@ class BIP65Test(BitcoinTestFramework): ][i] # First we show that this tx is valid except for CLTV by getting it # rejected from the mempool for exactly that reason. - spendtx_txid = spendtx.hash - spendtx_wtxid = spendtx.getwtxid() + spendtx_txid = spendtx.txid_hex + spendtx_wtxid = spendtx.wtxid_hex assert_equal( [{ 'txid': spendtx_txid, diff --git a/test/functional/feature_coinstatsindex.py b/test/functional/feature_coinstatsindex.py index a2363c4acfd..7d43d066491 100755 --- a/test/functional/feature_coinstatsindex.py +++ b/test/functional/feature_coinstatsindex.py @@ -191,7 +191,6 @@ class CoinStatsIndexTest(BitcoinTestFramework): # has two outputs cb = create_coinbase(109, nValue=35) cb.vout.append(CTxOut(5 * COIN, CScript([OP_FALSE]))) - cb.rehash() # Generate a block that includes previous coinbase tip = self.nodes[0].getbestblockhash() diff --git a/test/functional/feature_csv_activation.py b/test/functional/feature_csv_activation.py index d5b6d0dba9d..b6f16eedf51 100755 --- a/test/functional/feature_csv_activation.py +++ b/test/functional/feature_csv_activation.py @@ -103,7 +103,7 @@ class BIP68_112_113Test(BitcoinTestFramework): self.supports_cli = False def create_self_transfer_from_utxo(self, input_tx): - utxo = self.miniwallet.get_utxo(txid=input_tx.rehash(), mark_as_spent=False) + utxo = self.miniwallet.get_utxo(txid=input_tx.txid_hex, mark_as_spent=False) tx = self.miniwallet.create_self_transfer(utxo_to_spend=utxo)['tx'] return tx @@ -112,7 +112,6 @@ class BIP68_112_113Test(BitcoinTestFramework): tx.version = txversion self.miniwallet.sign_tx(tx) tx.vin[0].scriptSig = CScript([-1, OP_CHECKSEQUENCEVERIFY, OP_DROP] + list(CScript(tx.vin[0].scriptSig))) - tx.rehash() return tx def create_bip112emptystack(self, input, txversion): @@ -120,7 +119,6 @@ class BIP68_112_113Test(BitcoinTestFramework): tx.version = txversion self.miniwallet.sign_tx(tx) tx.vin[0].scriptSig = CScript([OP_CHECKSEQUENCEVERIFY] + list(CScript(tx.vin[0].scriptSig))) - tx.rehash() return tx def send_generic_input_tx(self, coinbases): @@ -159,7 +157,6 @@ class BIP68_112_113Test(BitcoinTestFramework): tx.vin[0].scriptSig = CScript([locktime, OP_CHECKSEQUENCEVERIFY, OP_DROP] + list(CScript(tx.vin[0].scriptSig))) else: tx.vin[0].scriptSig = CScript([BASE_RELATIVE_LOCKTIME, OP_CHECKSEQUENCEVERIFY, OP_DROP] + list(CScript(tx.vin[0].scriptSig))) - tx.rehash() txs.append({'tx': tx, 'sdf': sdf, 'stf': stf}) return txs diff --git a/test/functional/feature_dersig.py b/test/functional/feature_dersig.py index 0c3b0f12243..9687b80de9d 100755 --- a/test/functional/feature_dersig.py +++ b/test/functional/feature_dersig.py @@ -81,7 +81,6 @@ class BIP66Test(BitcoinTestFramework): spendtx = self.create_tx(self.coinbase_txids[0]) unDERify(spendtx) - spendtx.rehash() tip = self.nodes[0].getbestblockhash() block_time = self.nodes[0].getblockheader(tip)['mediantime'] + 1 @@ -112,12 +111,11 @@ class BIP66Test(BitcoinTestFramework): coin_txid = self.coinbase_txids[1] spendtx = self.create_tx(coin_txid) unDERify(spendtx) - spendtx.rehash() # First we show that this tx is valid except for DERSIG by getting it # rejected from the mempool for exactly that reason. - spendtx_txid = spendtx.hash - spendtx_wtxid = spendtx.getwtxid() + spendtx_txid = spendtx.txid_hex + spendtx_wtxid = spendtx.wtxid_hex assert_equal( [{ 'txid': spendtx_txid, diff --git a/test/functional/feature_fee_estimation.py b/test/functional/feature_fee_estimation.py index 61db186de17..34399c8c5fe 100755 --- a/test/functional/feature_fee_estimation.py +++ b/test/functional/feature_fee_estimation.py @@ -61,8 +61,7 @@ def small_txpuzzle_randfee( tx.vout[0].nValue = int((total_in - amount - fee) * COIN) tx.vout.append(deepcopy(tx.vout[0])) tx.vout[1].nValue = int(amount * COIN) - tx.rehash() - txid = tx.hash + txid = tx.txid_hex tx_hex = tx.serialize().hex() batch_reqs.append(from_node.sendrawtransaction.get_request(hexstring=tx_hex, maxfeerate=0)) diff --git a/test/functional/feature_nulldummy.py b/test/functional/feature_nulldummy.py index 885bc4855b0..e04412f3b2d 100755 --- a/test/functional/feature_nulldummy.py +++ b/test/functional/feature_nulldummy.py @@ -45,7 +45,6 @@ def invalidate_nulldummy_tx(tx): to be non-NULLDUMMY compliant by replacing the dummy with OP_TRUE""" assert_equal(tx.vin[0].scriptSig[0], OP_0) tx.vin[0].scriptSig = bytes([OP_TRUE]) + tx.vin[0].scriptSig[1:] - tx.rehash() class NULLDUMMYTest(BitcoinTestFramework): @@ -111,7 +110,7 @@ class NULLDUMMYTest(BitcoinTestFramework): self.block_submit(self.nodes[0], [test2tx], accept=True) self.log.info("Test 4: Non-NULLDUMMY base multisig transaction is invalid after activation") - test4tx = self.create_transaction(txid=test2tx.hash, input_details=ms_unlock_details, + test4tx = self.create_transaction(txid=test2tx.txid_hex, input_details=ms_unlock_details, addr=getnewdestination()[2], amount=46, privkey=self.privkey) test6txs = [CTransaction(test4tx)] diff --git a/test/functional/feature_rbf.py b/test/functional/feature_rbf.py index ee79a273928..324dfa08171 100755 --- a/test/functional/feature_rbf.py +++ b/test/functional/feature_rbf.py @@ -106,12 +106,11 @@ class ReplaceByFeeTest(BitcoinTestFramework): # Should fail because we haven't changed the fee tx.vout[0].scriptPubKey[-1] ^= 1 - tx.rehash() tx_hex = tx.serialize().hex() # This will raise an exception due to insufficient fee reject_reason = "insufficient fee" - reject_details = f"{reject_reason}, rejecting replacement {tx.hash}; new feerate 0.00300000 BTC/kvB <= old feerate 0.00300000 BTC/kvB" + reject_details = f"{reject_reason}, rejecting replacement {tx.txid_hex}; new feerate 0.00300000 BTC/kvB <= old feerate 0.00300000 BTC/kvB" res = self.nodes[0].testmempoolaccept(rawtxs=[tx_hex])[0] assert_equal(res["reject-reason"], reject_reason) assert_equal(res["reject-details"], reject_details) @@ -161,7 +160,7 @@ class ReplaceByFeeTest(BitcoinTestFramework): # This will raise an exception due to insufficient fee reject_reason = "insufficient fee" - reject_details = f"{reject_reason}, rejecting replacement {dbl_tx.hash}, less fees than conflicting txs; 3.00 < 4.00" + reject_details = f"{reject_reason}, rejecting replacement {dbl_tx.txid_hex}, less fees than conflicting txs; 3.00 < 4.00" res = self.nodes[0].testmempoolaccept(rawtxs=[dbl_tx_hex])[0] assert_equal(res["reject-reason"], reject_reason) assert_equal(res["reject-details"], reject_details) @@ -304,7 +303,7 @@ class ReplaceByFeeTest(BitcoinTestFramework): # This will raise an exception reject_reason = "bad-txns-spends-conflicting-tx" - reject_details = f"{reject_reason}, {tx2.hash} spends conflicting transaction {tx1a['tx'].hash}" + reject_details = f"{reject_reason}, {tx2.txid_hex} spends conflicting transaction {tx1a['tx'].txid_hex}" res = self.nodes[0].testmempoolaccept(rawtxs=[tx2_hex])[0] assert_equal(res["reject-reason"], reject_reason) assert_equal(res["reject-details"], reject_details) @@ -349,7 +348,7 @@ class ReplaceByFeeTest(BitcoinTestFramework): # This will raise an exception reject_reason = "replacement-adds-unconfirmed" - reject_details = f"{reject_reason}, replacement {tx2.hash} adds unconfirmed input, idx 1" + reject_details = f"{reject_reason}, replacement {tx2.txid_hex} adds unconfirmed input, idx 1" res = self.nodes[0].testmempoolaccept(rawtxs=[tx2_hex])[0] assert_equal(res["reject-reason"], reject_reason) assert_equal(res["reject-details"], reject_details) @@ -397,7 +396,7 @@ class ReplaceByFeeTest(BitcoinTestFramework): # This will raise an exception reject_reason = "too many potential replacements" - reject_details = f"{reject_reason}, rejecting replacement {double_tx.hash}; too many potential replacements ({MAX_REPLACEMENT_LIMIT + 1} > {MAX_REPLACEMENT_LIMIT})" + reject_details = f"{reject_reason}, rejecting replacement {double_tx.txid_hex}; too many potential replacements ({MAX_REPLACEMENT_LIMIT + 1} > {MAX_REPLACEMENT_LIMIT})" res = self.nodes[0].testmempoolaccept(rawtxs=[double_tx_hex])[0] assert_equal(res["reject-reason"], reject_reason) assert_equal(res["reject-details"], reject_details) diff --git a/test/functional/feature_segwit.py b/test/functional/feature_segwit.py index d1316976f8c..967b9e1e6eb 100755 --- a/test/functional/feature_segwit.py +++ b/test/functional/feature_segwit.py @@ -251,7 +251,7 @@ class SegWitTest(BitcoinTestFramework): tx1 = tx_from_hex(tx1_hex) # Check that wtxid is properly reported in mempool entry (txid1) - assert_equal(self.nodes[0].getmempoolentry(txid1)["wtxid"], tx1.getwtxid()) + assert_equal(self.nodes[0].getmempoolentry(txid1)["wtxid"], tx1.wtxid_hex) # Check that weight and vsize are properly reported in mempool entry (txid1) assert_equal(self.nodes[0].getmempoolentry(txid1)["vsize"], tx1.get_vsize()) @@ -267,7 +267,7 @@ class SegWitTest(BitcoinTestFramework): assert not tx.wit.is_null() # Check that wtxid is properly reported in mempool entry (txid2) - assert_equal(self.nodes[0].getmempoolentry(txid2)["wtxid"], tx.getwtxid()) + assert_equal(self.nodes[0].getmempoolentry(txid2)["wtxid"], tx.wtxid_hex) # Check that weight and vsize are properly reported in mempool entry (txid2) assert_equal(self.nodes[0].getmempoolentry(txid2)["vsize"], tx.get_vsize()) @@ -277,7 +277,6 @@ class SegWitTest(BitcoinTestFramework): tx = CTransaction() tx.vin.append(CTxIn(COutPoint(int(txid2, 16), 0), b"")) tx.vout.append(CTxOut(int(49.95 * COIN), CScript([OP_TRUE, OP_DROP] * 15 + [OP_TRUE]))) # Huge fee - tx.calc_sha256() txid3 = self.nodes[0].sendrawtransaction(hexstring=tx.serialize().hex(), maxfeerate=0) assert tx.wit.is_null() assert txid3 in self.nodes[0].getrawmempool() @@ -290,7 +289,7 @@ class SegWitTest(BitcoinTestFramework): assert txid3 in template_txids # Check that wtxid is properly reported in mempool entry (txid3) - assert_equal(self.nodes[0].getmempoolentry(txid3)["wtxid"], tx.getwtxid()) + assert_equal(self.nodes[0].getmempoolentry(txid3)["wtxid"], tx.wtxid_hex) # Check that weight and vsize are properly reported in mempool entry (txid3) assert_equal(self.nodes[0].getmempoolentry(txid3)["vsize"], tx.get_vsize()) @@ -305,7 +304,6 @@ class SegWitTest(BitcoinTestFramework): tx.vin.append(CTxIn(COutPoint(int('0x' + utxo['txid'], 0), utxo['vout']))) for i in script_list: tx.vout.append(CTxOut(10000000, i)) - tx.rehash() signresults = self.nodes[0].signrawtransactionwithwallet(tx.serialize_without_witness().hex())['hex'] txid = self.nodes[0].sendrawtransaction(hexstring=signresults, maxfeerate=0) txs_mined[txid] = self.generate(self.nodes[0], 1)[0] @@ -354,7 +352,6 @@ class SegWitTest(BitcoinTestFramework): for j in range(len(txtmp.vout)): tx.vin.append(CTxIn(COutPoint(int('0x' + i, 0), j))) tx.vout.append(CTxOut(0, CScript())) - tx.rehash() signresults = self.nodes[0].signrawtransactionwithwallet(tx.serialize_without_witness().hex())['hex'] self.nodes[0].sendrawtransaction(hexstring=signresults, maxfeerate=0) self.generate(self.nodes[0], 1) diff --git a/test/functional/feature_taproot.py b/test/functional/feature_taproot.py index 1911e75dc8b..04c2c951ca9 100755 --- a/test/functional/feature_taproot.py +++ b/test/functional/feature_taproot.py @@ -1423,9 +1423,8 @@ class TaprootTest(BitcoinTestFramework): # Ask the wallet to sign fund_tx = tx_from_hex(node.signrawtransactionwithwallet(fund_tx.serialize().hex())["hex"]) # Construct UTXOData entries - fund_tx.rehash() for i in range(count_this_tx): - utxodata = UTXOData(outpoint=COutPoint(fund_tx.sha256, i), output=fund_tx.vout[i], spender=spenders[done]) + utxodata = UTXOData(outpoint=COutPoint(fund_tx.txid_int, i), output=fund_tx.vout[i], spender=spenders[done]) if utxodata.spender.need_vin_vout_mismatch: mismatching_utxos.append(utxodata) else: @@ -1538,11 +1537,10 @@ class TaprootTest(BitcoinTestFramework): and (all(utxo.spender.is_standard for utxo in input_utxos)) # All inputs must be standard and tx.version >= 1 # The tx version must be standard and tx.version <= 2) - tx.rehash() msg = ','.join(utxo.spender.comment + ("*" if n == fail_input else "") for n, utxo in enumerate(input_utxos)) if is_standard_tx: node.sendrawtransaction(tx.serialize().hex(), 0) - assert node.getmempoolentry(tx.hash) is not None, "Failed to accept into mempool: " + msg + assert node.getmempoolentry(tx.txid_hex) is not None, "Failed to accept into mempool: " + msg else: assert_raises_rpc_error(-26, None, node.sendrawtransaction, tx.serialize().hex(), 0) # Submit in a block @@ -1568,8 +1566,7 @@ class TaprootTest(BitcoinTestFramework): coinbase.vin = [CTxIn(COutPoint(0, 0xffffffff), CScript([OP_1, OP_1]), SEQUENCE_FINAL)] coinbase.vout = [CTxOut(5000000000, CScript([OP_1]))] coinbase.nLockTime = 0 - coinbase.rehash() - assert coinbase.hash == "f60c73405d499a956d3162e3483c395526ef78286458a4cb17b125aa92e49b20" + assert coinbase.txid_hex == "f60c73405d499a956d3162e3483c395526ef78286458a4cb17b125aa92e49b20" # Mine it block = create_block(hashprev=int(self.nodes[0].getbestblockhash(), 16), coinbase=coinbase) block.rehash() @@ -1651,7 +1648,7 @@ class TaprootTest(BitcoinTestFramework): # Construct a deterministic chain of transactions creating UTXOs to the test's spk's (so that they # come from distinct txids). txn = [] - lasttxid = coinbase.sha256 + lasttxid = coinbase.txid_int amount = 5000000000 for i, spk in enumerate(old_spks + tap_spks): val = 42000000 * (i + 7) @@ -1662,11 +1659,10 @@ class TaprootTest(BitcoinTestFramework): if i & 1: tx.vout = list(reversed(tx.vout)) tx.nLockTime = 0 - tx.rehash() amount -= val - lasttxid = tx.sha256 + lasttxid = tx.txid_int txn.append(tx) - spend_info[spk]['prevout'] = COutPoint(tx.sha256, i & 1) + spend_info[spk]['prevout'] = COutPoint(tx.txid_int, i & 1) spend_info[spk]['utxo'] = CTxOut(val, spk) # Mine those transactions self.init_blockinfo(self.nodes[0]) diff --git a/test/functional/feature_utxo_set_hash.py b/test/functional/feature_utxo_set_hash.py index 21a3c13f7e4..1b49a7d855f 100755 --- a/test/functional/feature_utxo_set_hash.py +++ b/test/functional/feature_utxo_set_hash.py @@ -55,7 +55,7 @@ class UTXOSetHashTest(BitcoinTestFramework): if (coinbase and n > 0): continue - data = COutPoint(int(tx.rehash(), 16), n).serialize() + data = COutPoint(tx.txid_int, n).serialize() data += (height * 2 + coinbase).to_bytes(4, "little") data += tx_out.serialize() diff --git a/test/functional/interface_usdt_mempool.py b/test/functional/interface_usdt_mempool.py index 0ffae66752b..b69dd2df114 100755 --- a/test/functional/interface_usdt_mempool.py +++ b/test/functional/interface_usdt_mempool.py @@ -323,7 +323,7 @@ class MempoolTracepointTest(BitcoinTestFramework): self.log.info("Ensuring mempool:rejected event was handled successfully...") assert_equal(1, len(events)) event = events[0] - assert_equal(bytes(event.hash)[::-1].hex(), tx["tx"].hash) + assert_equal(bytes(event.hash)[::-1].hex(), tx["tx"].txid_hex) assert_equal(event.reason.decode("UTF-8"), "min relay fee not met") bpf.cleanup() diff --git a/test/functional/interface_zmq.py b/test/functional/interface_zmq.py index 96e701a7fd0..01b3f763259 100755 --- a/test/functional/interface_zmq.py +++ b/test/functional/interface_zmq.py @@ -212,15 +212,14 @@ class ZMQTest (BitcoinTestFramework): # Should receive the coinbase raw transaction. tx = tx_from_hex(rawtx.receive().hex()) - tx.calc_sha256() - assert_equal(tx.hash, txid.hex()) + assert_equal(tx.txid_hex, txid.hex()) # Should receive the generated raw block. hex = rawblock.receive() block = CBlock() block.deserialize(BytesIO(hex)) assert block.is_valid() - assert_equal(block.vtx[0].hash, tx.hash) + assert_equal(block.vtx[0].txid_hex, tx.txid_hex) assert_equal(len(block.vtx), 1) assert_equal(genhashes[x], hash256_reversed(hex[:80]).hex()) diff --git a/test/functional/mempool_accept.py b/test/functional/mempool_accept.py index d9c01161869..81c6ea3e5d2 100755 --- a/test/functional/mempool_accept.py +++ b/test/functional/mempool_accept.py @@ -123,7 +123,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx = self.wallet.create_self_transfer(utxo_to_spend=utxo_to_spend, sequence=MAX_BIP125_RBF_SEQUENCE)['tx'] tx.vout[0].nValue = int((Decimal('0.3') - fee) * COIN) raw_tx_0 = tx.serialize().hex() - txid_0 = tx.rehash() + txid_0 = tx.txid_hex self.check_mempool_result( result_expected=[{'txid': txid_0, 'allowed': True, 'vsize': tx.get_vsize(), 'fees': {'base': fee}}], rawtxs=[raw_tx_0], @@ -140,7 +140,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx = tx_from_hex(raw_tx_final) fee_expected = Decimal('50.0') - output_amount self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': True, 'vsize': tx.get_vsize(), 'fees': {'base': fee_expected}}], + result_expected=[{'txid': tx.txid_hex, 'allowed': True, 'vsize': tx.get_vsize(), 'fees': {'base': fee_expected}}], rawtxs=[tx.serialize().hex()], maxfeerate=0, ) @@ -159,7 +159,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx = tx_from_hex(raw_tx_0) tx.vout[0].nValue -= int(fee * COIN) # Double the fee raw_tx_0 = tx.serialize().hex() - txid_0 = tx.rehash() + txid_0 = tx.txid_hex self.check_mempool_result( result_expected=[{'txid': txid_0, 'allowed': True, 'vsize': tx.get_vsize(), 'fees': {'base': (2 * fee)}}], rawtxs=[raw_tx_0], @@ -170,7 +170,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx = tx_from_hex(raw_tx_0) tx.vin[0].prevout = COutPoint(hash=int('ff' * 32, 16), n=14) self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'missing-inputs'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'missing-inputs'}], rawtxs=[tx.serialize().hex()], ) @@ -207,7 +207,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): raw_tx_reference = tx.serialize().hex() # Reference tx should be valid on itself self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': True, 'vsize': tx.get_vsize(), 'fees': { 'base': Decimal('0.1') - Decimal('0.05')}}], + result_expected=[{'txid': tx.txid_hex, 'allowed': True, 'vsize': tx.get_vsize(), 'fees': { 'base': Decimal('0.1') - Decimal('0.05')}}], rawtxs=[tx.serialize().hex()], maxfeerate=0, ) @@ -216,7 +216,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx = tx_from_hex(raw_tx_reference) tx.vout = [] self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'bad-txns-vout-empty'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'bad-txns-vout-empty'}], rawtxs=[tx.serialize().hex()], ) @@ -224,7 +224,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx = tx_from_hex(raw_tx_reference) tx.vin = [tx.vin[0]] * math.ceil((MAX_BLOCK_WEIGHT // WITNESS_SCALE_FACTOR) / len(tx.vin[0].serialize())) self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'bad-txns-oversize'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'bad-txns-oversize'}], rawtxs=[tx.serialize().hex()], ) @@ -232,7 +232,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx = tx_from_hex(raw_tx_reference) tx.vout[0].nValue *= -1 self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'bad-txns-vout-negative'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'bad-txns-vout-negative'}], rawtxs=[tx.serialize().hex()], ) @@ -241,7 +241,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx = tx_from_hex(raw_tx_reference) tx.vout[0].nValue = MAX_MONEY + 1 self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'bad-txns-vout-toolarge'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'bad-txns-vout-toolarge'}], rawtxs=[tx.serialize().hex()], ) @@ -250,7 +250,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.vout = [tx.vout[0]] * 2 tx.vout[0].nValue = MAX_MONEY self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'bad-txns-txouttotal-toolarge'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'bad-txns-txouttotal-toolarge'}], rawtxs=[tx.serialize().hex()], ) @@ -258,7 +258,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx = tx_from_hex(raw_tx_reference) tx.vin = [tx.vin[0]] * 2 self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'bad-txns-inputs-duplicate'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'bad-txns-inputs-duplicate'}], rawtxs=[tx.serialize().hex()], ) @@ -266,7 +266,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx = tx_from_hex(raw_tx_reference) tx.vin.append(CTxIn(COutPoint(hash=0, n=0xffffffff))) self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'bad-txns-prevout-null'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'bad-txns-prevout-null'}], rawtxs=[tx.serialize().hex()], ) @@ -276,7 +276,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): raw_tx_coinbase_spent = node.getrawtransaction(txid=node.decoderawtransaction(hexstring=raw_tx_in_block)['vin'][0]['txid']) tx = tx_from_hex(raw_tx_coinbase_spent) self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'coinbase'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'coinbase'}], rawtxs=[tx.serialize().hex()], ) @@ -284,32 +284,32 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx = tx_from_hex(raw_tx_reference) tx.version = 4 # A version currently non-standard self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'version'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'version'}], rawtxs=[tx.serialize().hex()], ) tx = tx_from_hex(raw_tx_reference) tx.vout[0].scriptPubKey = CScript([OP_0]) # Some non-standard script self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'scriptpubkey'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'scriptpubkey'}], rawtxs=[tx.serialize().hex()], ) tx = tx_from_hex(raw_tx_reference) _, pubkey = generate_keypair() tx.vout[0].scriptPubKey = keys_to_multisig_script([pubkey] * 3, k=2) # Some bare multisig script (2-of-3) self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'bare-multisig'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'bare-multisig'}], rawtxs=[tx.serialize().hex()], ) tx = tx_from_hex(raw_tx_reference) tx.vin[0].scriptSig = CScript([OP_HASH160]) # Some not-pushonly scriptSig self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'scriptsig-not-pushonly'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'scriptsig-not-pushonly'}], rawtxs=[tx.serialize().hex()], ) tx = tx_from_hex(raw_tx_reference) tx.vin[0].scriptSig = CScript([b'a' * 1648]) # Some too large scriptSig (>1650 bytes) self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'scriptsig-size'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'scriptsig-size'}], rawtxs=[tx.serialize().hex()], ) tx = tx_from_hex(raw_tx_reference) @@ -317,14 +317,14 @@ class MempoolAcceptanceTest(BitcoinTestFramework): num_scripts = 100000 // len(output_p2sh_burn.serialize()) # Use enough outputs to make the tx too large for our policy tx.vout = [output_p2sh_burn] * num_scripts self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'tx-size'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'tx-size'}], rawtxs=[tx.serialize().hex()], ) tx = tx_from_hex(raw_tx_reference) tx.vout[0] = output_p2sh_burn tx.vout[0].nValue -= 1 # Make output smaller, such that it is dust for our policy self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'dust'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'dust'}], rawtxs=[tx.serialize().hex()], ) @@ -332,7 +332,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx = tx_from_hex(raw_tx_reference) tx.vout[0].scriptPubKey = CScript([OP_RETURN, OP_HASH160]) self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'scriptpubkey'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'scriptpubkey'}], rawtxs=[tx.serialize().hex()], ) @@ -343,7 +343,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.vout.append(CTxOut(0, CScript([OP_RETURN, b'\xff' * 50000]))) self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': True, 'vsize': tx.get_vsize(), 'fees': {'base': Decimal('0.05')}}], + result_expected=[{'txid': tx.txid_hex, 'allowed': True, 'vsize': tx.get_vsize(), 'fees': {'base': Decimal('0.05')}}], rawtxs=[tx.serialize().hex()], maxfeerate=0 ) @@ -355,7 +355,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.vout[0].scriptPubKey = CScript([OP_RETURN, b'\xff']) tx.vout = [tx.vout[0]] * op_return_count self.check_mempool_result( - result_expected=[{"txid": tx.rehash(), "allowed": True, "vsize": tx.get_vsize(), "fees": {"base": Decimal("0.05000026")}}], + result_expected=[{"txid": tx.txid_hex, "allowed": True, "vsize": tx.get_vsize(), "fees": {"base": Decimal("0.05000026")}}], rawtxs=[tx.serialize().hex()], ) @@ -366,13 +366,13 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.vout[0].scriptPubKey = CScript([OP_RETURN, b"\xff" * (data_len)]) assert_equal(tx.get_vsize(), int(MAX_STANDARD_TX_WEIGHT / 4)) self.check_mempool_result( - result_expected=[{"txid": tx.rehash(), "allowed": True, "vsize": tx.get_vsize(), "fees": {"base": Decimal("0.1") - Decimal("0.05")}}], + result_expected=[{"txid": tx.txid_hex, "allowed": True, "vsize": tx.get_vsize(), "fees": {"base": Decimal("0.1") - Decimal("0.05")}}], rawtxs=[tx.serialize().hex()], ) tx.vout[0].scriptPubKey = CScript([OP_RETURN, b"\xff" * (data_len + 1)]) assert_greater_than(tx.get_vsize(), int(MAX_STANDARD_TX_WEIGHT / 4)) self.check_mempool_result( - result_expected=[{"txid": tx.rehash(), "allowed": False, "reject-reason": "tx-size"}], + result_expected=[{"txid": tx.txid_hex, "allowed": False, "reject-reason": "tx-size"}], rawtxs=[tx.serialize().hex()], ) @@ -381,7 +381,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.vin[0].nSequence -= 1 # Should be non-max, so locktime is not ignored tx.nLockTime = node.getblockcount() + 1 self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'non-final'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'non-final'}], rawtxs=[tx.serialize().hex()], ) @@ -389,7 +389,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx = tx_from_hex(raw_tx_reference) tx.vin[0].nSequence = 2 # We could include it in the second block mined from now, but not the very next one self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'non-BIP68-final'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'non-BIP68-final'}], rawtxs=[tx.serialize().hex()], maxfeerate=0, ) @@ -410,7 +410,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): assert_greater_than(len(tx.serialize()), 64) self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'tx-size-small'}], + result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'tx-size-small'}], rawtxs=[tx.serialize().hex()], maxfeerate=0, ) @@ -419,7 +419,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.vout[0] = CTxOut(COIN - 1000, DUMMY_MIN_OP_RETURN_SCRIPT) assert_equal(len(tx.serialize_without_witness()), MIN_STANDARD_TX_NONWITNESS_SIZE) self.check_mempool_result( - result_expected=[{'txid': tx.rehash(), 'allowed': True, 'vsize': tx.get_vsize(), 'fees': { 'base': Decimal('0.00001000')}}], + result_expected=[{'txid': tx.txid_hex, 'allowed': True, 'vsize': tx.get_vsize(), 'fees': { 'base': Decimal('0.00001000')}}], rawtxs=[tx.serialize().hex()], maxfeerate=0, ) @@ -435,10 +435,9 @@ class MempoolAcceptanceTest(BitcoinTestFramework): anchor_nonempty_wit_spend.vout.append(CTxOut(anchor_value - int(fee*COIN), script_to_p2wsh_script(CScript([OP_TRUE])))) anchor_nonempty_wit_spend.wit.vtxinwit.append(CTxInWitness()) anchor_nonempty_wit_spend.wit.vtxinwit[0].scriptWitness.stack.append(b"f") - anchor_nonempty_wit_spend.rehash() self.check_mempool_result( - result_expected=[{'txid': anchor_nonempty_wit_spend.rehash(), 'allowed': False, 'reject-reason': 'bad-witness-nonstandard'}], + result_expected=[{'txid': anchor_nonempty_wit_spend.txid_hex, 'allowed': False, 'reject-reason': 'bad-witness-nonstandard'}], rawtxs=[anchor_nonempty_wit_spend.serialize().hex()], maxfeerate=0, ) @@ -455,10 +454,10 @@ class MempoolAcceptanceTest(BitcoinTestFramework): anchor_spend.vout.append(CTxOut(anchor_value - int(fee*COIN), script_to_p2wsh_script(CScript([OP_TRUE])))) anchor_spend.wit.vtxinwit.append(CTxInWitness()) # It's "segwit" but txid == wtxid since there is no witness data - assert_equal(anchor_spend.rehash(), anchor_spend.getwtxid()) + assert_equal(anchor_spend.txid_hex, anchor_spend.wtxid_hex) self.check_mempool_result( - result_expected=[{'txid': anchor_spend.rehash(), 'allowed': True, 'vsize': anchor_spend.get_vsize(), 'fees': { 'base': Decimal('0.00000700')}}], + result_expected=[{'txid': anchor_spend.txid_hex, 'allowed': True, 'vsize': anchor_spend.get_vsize(), 'fees': { 'base': Decimal('0.00000700')}}], rawtxs=[anchor_spend.serialize().hex()], maxfeerate=0, ) @@ -466,17 +465,15 @@ class MempoolAcceptanceTest(BitcoinTestFramework): self.log.info('But cannot be spent if nested sh()') nested_anchor_tx = self.wallet.create_self_transfer(sequence=SEQUENCE_FINAL)['tx'] nested_anchor_tx.vout[0].scriptPubKey = script_to_p2sh_script(PAY_TO_ANCHOR) - nested_anchor_tx.rehash() self.generateblock(node, self.wallet.get_address(), [nested_anchor_tx.serialize().hex()]) nested_anchor_spend = CTransaction() - nested_anchor_spend.vin.append(CTxIn(COutPoint(nested_anchor_tx.sha256, 0), b"")) + nested_anchor_spend.vin.append(CTxIn(COutPoint(nested_anchor_tx.txid_int, 0), b"")) nested_anchor_spend.vin[0].scriptSig = CScript([bytes(PAY_TO_ANCHOR)]) nested_anchor_spend.vout.append(CTxOut(nested_anchor_tx.vout[0].nValue - int(fee*COIN), script_to_p2wsh_script(CScript([OP_TRUE])))) - nested_anchor_spend.rehash() self.check_mempool_result( - result_expected=[{'txid': nested_anchor_spend.rehash(), 'allowed': False, 'reject-reason': 'non-mandatory-script-verify-flag (Witness version reserved for soft-fork upgrades)'}], + result_expected=[{'txid': nested_anchor_spend.txid_hex, 'allowed': False, 'reject-reason': 'non-mandatory-script-verify-flag (Witness version reserved for soft-fork upgrades)'}], rawtxs=[nested_anchor_spend.serialize().hex()], maxfeerate=0, ) @@ -488,16 +485,14 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx = tx_from_hex(raw_tx_reference) privkey, pubkey = generate_keypair() tx.vout[0].scriptPubKey = keys_to_multisig_script([pubkey] * 3, k=1) # Some bare multisig script (1-of-3) - tx.rehash() self.generateblock(node, address, [tx.serialize().hex()]) tx_spend = CTransaction() - tx_spend.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) + tx_spend.vin.append(CTxIn(COutPoint(tx.txid_int, 0), b"")) tx_spend.vout.append(CTxOut(tx.vout[0].nValue - int(fee*COIN), script_to_p2wsh_script(CScript([OP_TRUE])))) - tx_spend.rehash() sign_input_legacy(tx_spend, 0, tx.vout[0].scriptPubKey, privkey, sighash_type=SIGHASH_ALL) tx_spend.vin[0].scriptSig = bytes(CScript([OP_0])) + tx_spend.vin[0].scriptSig self.check_mempool_result( - result_expected=[{'txid': tx_spend.rehash(), 'allowed': True, 'vsize': tx_spend.get_vsize(), 'fees': { 'base': Decimal('0.00000700')}}], + result_expected=[{'txid': tx_spend.txid_hex, 'allowed': True, 'vsize': tx_spend.get_vsize(), 'fees': { 'base': Decimal('0.00000700')}}], rawtxs=[tx_spend.serialize().hex()], maxfeerate=0, ) diff --git a/test/functional/mempool_accept_wtxid.py b/test/functional/mempool_accept_wtxid.py index 87fd436e527..35983d8eb48 100755 --- a/test/functional/mempool_accept_wtxid.py +++ b/test/functional/mempool_accept_wtxid.py @@ -58,7 +58,6 @@ class MempoolWtxidTest(BitcoinTestFramework): parent = CTransaction() parent.vin.append(CTxIn(COutPoint(int(txid, 16), 0), b"")) parent.vout.append(CTxOut(int(9.99998 * COIN), script_pubkey)) - parent.rehash() privkeys = [node.get_deterministic_priv_key().key] raw_parent = node.signrawtransactionwithkey(hexstring=parent.serialize().hex(), privkeys=privkeys)['hex'] @@ -77,14 +76,14 @@ class MempoolWtxidTest(BitcoinTestFramework): child_one.vout.append(CTxOut(int(9.99996 * COIN), child_script_pubkey)) child_one.wit.vtxinwit.append(CTxInWitness()) child_one.wit.vtxinwit[0].scriptWitness.stack = [b'Preimage', b'\x01', witness_script] - child_one_wtxid = child_one.getwtxid() - child_one_txid = child_one.rehash() + child_one_wtxid = child_one.wtxid_hex + child_one_txid = child_one.txid_hex # Create another identical transaction with witness solving second branch child_two = deepcopy(child_one) child_two.wit.vtxinwit[0].scriptWitness.stack = [b'', witness_script] - child_two_wtxid = child_two.getwtxid() - child_two_txid = child_two.rehash() + child_two_wtxid = child_two.wtxid_hex + child_two_txid = child_two.txid_hex assert_equal(child_one_txid, child_two_txid) assert_not_equal(child_one_wtxid, child_two_wtxid) diff --git a/test/functional/mempool_datacarrier.py b/test/functional/mempool_datacarrier.py index 8eab4ce6b28..47dd7ecbc26 100755 --- a/test/functional/mempool_datacarrier.py +++ b/test/functional/mempool_datacarrier.py @@ -41,7 +41,7 @@ class DataCarrierTest(BitcoinTestFramework): if success: self.wallet.sendrawtransaction(from_node=node, tx_hex=tx_hex) - assert tx.rehash() in node.getrawmempool(True), f'{tx_hex} not in mempool' + assert tx.txid_hex in node.getrawmempool(True), f'{tx_hex} not in mempool' else: assert_raises_rpc_error(-26, "datacarrier", self.wallet.sendrawtransaction, from_node=node, tx_hex=tx_hex) diff --git a/test/functional/mempool_ephemeral_dust.py b/test/functional/mempool_ephemeral_dust.py index 59314139145..fd77eac3e2b 100755 --- a/test/functional/mempool_ephemeral_dust.py +++ b/test/functional/mempool_ephemeral_dust.py @@ -38,13 +38,13 @@ class EphemeralDustTest(BitcoinTestFramework): # Take value from first output result["tx"].vout[0].nValue -= output_value result["new_utxos"][0]["value"] = Decimal(result["tx"].vout[0].nValue) / COIN - new_txid = result["tx"].rehash() + new_txid = result["tx"].txid_hex result["txid"] = new_txid - result["wtxid"] = result["tx"].getwtxid() + result["wtxid"] = result["tx"].wtxid_hex result["hex"] = result["tx"].serialize().hex() for new_utxo in result["new_utxos"]: new_utxo["txid"] = new_txid - new_utxo["wtxid"] = result["tx"].getwtxid() + new_utxo["wtxid"] = result["tx"].wtxid_hex result["new_utxos"].append({"txid": new_txid, "vout": len(result["tx"].vout) - 1, "value": Decimal(output_value) / COIN, "height": 0, "coinbase": False, "confirmations": 0}) diff --git a/test/functional/mempool_limit.py b/test/functional/mempool_limit.py index 791654a8c04..b9ee6a0a102 100755 --- a/test/functional/mempool_limit.py +++ b/test/functional/mempool_limit.py @@ -379,7 +379,7 @@ class MempoolLimitTest(BitcoinTestFramework): rich_parent_result = submitpackage_result["tx-results"][tx_rich["wtxid"]] poor_parent_result = submitpackage_result["tx-results"][tx_poor["wtxid"]] - child_result = submitpackage_result["tx-results"][tx_child["tx"].getwtxid()] + child_result = submitpackage_result["tx-results"][tx_child["tx"].wtxid_hex] assert_fee_amount(poor_parent_result["fees"]["base"], tx_poor["tx"].get_vsize(), relayfee) assert_equal(rich_parent_result["fees"]["base"], 0) assert_equal(child_result["fees"]["base"], DEFAULT_FEE) @@ -392,11 +392,11 @@ class MempoolLimitTest(BitcoinTestFramework): package_vsize = tx_poor["tx"].get_vsize() + tx_child["tx"].get_vsize() assert_fee_amount(package_fees, package_vsize, poor_parent_result["fees"]["effective-feerate"]) assert_fee_amount(package_fees, package_vsize, child_result["fees"]["effective-feerate"]) - assert_equal([tx_poor["wtxid"], tx_child["tx"].getwtxid()], poor_parent_result["fees"]["effective-includes"]) - assert_equal([tx_poor["wtxid"], tx_child["tx"].getwtxid()], child_result["fees"]["effective-includes"]) + assert_equal([tx_poor["wtxid"], tx_child["tx"].wtxid_hex], poor_parent_result["fees"]["effective-includes"]) + assert_equal([tx_poor["wtxid"], tx_child["tx"].wtxid_hex], child_result["fees"]["effective-includes"]) # The node will broadcast each transaction, still abiding by its peer's fee filter - peer.wait_for_broadcast([tx["tx"].getwtxid() for tx in package_txns]) + peer.wait_for_broadcast([tx["tx"].wtxid_hex for tx in package_txns]) self.log.info("Check a package that passes mempoolminfee but is evicted immediately after submission") mempoolmin_feerate = node.getmempoolinfo()["mempoolminfee"] diff --git a/test/functional/mempool_package_onemore.py b/test/functional/mempool_package_onemore.py index fd54a8c3e1c..74c5e345202 100755 --- a/test/functional/mempool_package_onemore.py +++ b/test/functional/mempool_package_onemore.py @@ -60,8 +60,8 @@ class MempoolPackagesTest(BitcoinTestFramework): txns_hex = [tx.serialize().hex() for tx in txns] assert_equal(self.nodes[0].testmempoolaccept(txns_hex)[0]["reject-reason"], "too-long-mempool-chain") pkg_result = self.nodes[0].submitpackage(txns_hex) - assert "too-long-mempool-chain" in pkg_result["tx-results"][txns[0].getwtxid()]["error"] - assert_equal(pkg_result["tx-results"][txns[1].getwtxid()]["error"], "bad-txns-inputs-missingorspent") + assert "too-long-mempool-chain" in pkg_result["tx-results"][txns[0].wtxid_hex]["error"] + assert_equal(pkg_result["tx-results"][txns[1].wtxid_hex]["error"], "bad-txns-inputs-missingorspent") # But not if it chains directly off the first transaction self.nodes[0].sendrawtransaction(replaceable_tx["hex"]) # and the second chain should work just fine diff --git a/test/functional/mempool_package_rbf.py b/test/functional/mempool_package_rbf.py index f760e427fe9..ca56bdf8c5f 100755 --- a/test/functional/mempool_package_rbf.py +++ b/test/functional/mempool_package_rbf.py @@ -114,7 +114,7 @@ class PackageRBFTest(BitcoinTestFramework): # But accepted during normal submission submitres = node.submitpackage(package_hex2) - assert_equal(set(submitres["replaced-transactions"]), set([tx.rehash() for tx in package_txns1])) + assert_equal(set(submitres["replaced-transactions"]), set([tx.txid_hex for tx in package_txns1])) self.assert_mempool_contents(expected=package_txns2) # Make sure 2nd node gets a basic package RBF over p2p @@ -135,7 +135,7 @@ class PackageRBFTest(BitcoinTestFramework): package_hex, package_txns = self.create_simple_package(singleton_coin, DEFAULT_FEE, singleton_tx["fee"] * 2) submitres = node.submitpackage(package_hex) - assert_equal(submitres["replaced-transactions"], [singleton_tx["tx"].rehash()]) + assert_equal(submitres["replaced-transactions"], [singleton_tx["tx"].txid_hex]) self.assert_mempool_contents(expected=package_txns) self.generate(node, 1) @@ -156,7 +156,7 @@ class PackageRBFTest(BitcoinTestFramework): # Package 2 has a higher feerate but lower absolute fee package_hex2, package_txns2 = self.create_simple_package(coin, parent_fee=DEFAULT_FEE, child_fee=DEFAULT_CHILD_FEE - Decimal("0.00000001")) pkg_results2 = node.submitpackage(package_hex2) - assert_equal(f"package RBF failed: insufficient anti-DoS fees, rejecting replacement {package_txns2[1].rehash()}, less fees than conflicting txs; {PACKAGE_FEE_MINUS_ONE} < {PACKAGE_FEE}", pkg_results2["package_msg"]) + assert_equal(f"package RBF failed: insufficient anti-DoS fees, rejecting replacement {package_txns2[1].txid_hex}, less fees than conflicting txs; {PACKAGE_FEE_MINUS_ONE} < {PACKAGE_FEE}", pkg_results2["package_msg"]) self.assert_mempool_contents(expected=package_txns1) self.log.info("Check replacement pays for incremental bandwidth") @@ -168,7 +168,7 @@ class PackageRBFTest(BitcoinTestFramework): failure_package_hex3, failure_package_txns3 = self.create_simple_package(coin, parent_fee=DEFAULT_FEE, child_fee=DEFAULT_CHILD_FEE + incremental_sats_short) assert_equal(package_3_size, sum([tx.get_vsize() for tx in failure_package_txns3])) pkg_results3 = node.submitpackage(failure_package_hex3) - assert_equal(f"package RBF failed: insufficient anti-DoS fees, rejecting replacement {failure_package_txns3[1].rehash()}, not enough additional fees to relay; {incremental_sats_short} < {incremental_sats_required}", pkg_results3["package_msg"]) + assert_equal(f"package RBF failed: insufficient anti-DoS fees, rejecting replacement {failure_package_txns3[1].txid_hex}, not enough additional fees to relay; {incremental_sats_short} < {incremental_sats_required}", pkg_results3["package_msg"]) self.assert_mempool_contents(expected=package_txns1) success_package_hex3, success_package_txns3 = self.create_simple_package(coin, parent_fee=DEFAULT_FEE, child_fee=DEFAULT_CHILD_FEE + incremental_sats_required) @@ -218,7 +218,7 @@ class PackageRBFTest(BitcoinTestFramework): package_child = self.wallet.create_self_transfer(fee_rate=child_feerate, utxo_to_spend=package_parent["new_utxos"][0]) pkg_results = node.submitpackage([package_parent["hex"], package_child["hex"]], maxfeerate=0) - assert_equal(f"package RBF failed: too many potential replacements, rejecting replacement {package_child['tx'].rehash()}; too many potential replacements (102 > 100)", pkg_results["package_msg"]) + assert_equal(f"package RBF failed: too many potential replacements, rejecting replacement {package_child['tx'].txid_hex}; too many potential replacements (102 > 100)", pkg_results["package_msg"]) self.assert_mempool_contents(expected=expected_txns) # Make singleton tx to conflict with in next batch @@ -233,7 +233,7 @@ class PackageRBFTest(BitcoinTestFramework): package_parent = self.wallet.create_self_transfer_multi(utxos_to_spend=double_spending_coins, fee_per_output=parent_fee_per_conflict) package_child = self.wallet.create_self_transfer(fee_rate=child_feerate, utxo_to_spend=package_parent["new_utxos"][0]) pkg_results = node.submitpackage([package_parent["hex"], package_child["hex"]], maxfeerate=0) - assert_equal(f"package RBF failed: too many potential replacements, rejecting replacement {package_child['tx'].rehash()}; too many potential replacements (101 > 100)", pkg_results["package_msg"]) + assert_equal(f"package RBF failed: too many potential replacements, rejecting replacement {package_child['tx'].txid_hex}; too many potential replacements (101 > 100)", pkg_results["package_msg"]) self.assert_mempool_contents(expected=expected_txns) # Finally, evict MAX_REPLACEMENT_CANDIDATES @@ -331,15 +331,15 @@ class PackageRBFTest(BitcoinTestFramework): package_hex1, _package_txns1 = self.create_simple_package(coin1, DEFAULT_FEE, DEFAULT_CHILD_FEE) package_result = node.submitpackage(package_hex1) - assert_equal(f"package RBF failed: {parent_result['tx'].rehash()} has 2 descendants, max 1 allowed", package_result["package_msg"]) + assert_equal(f"package RBF failed: {parent_result['tx'].txid_hex} has 2 descendants, max 1 allowed", package_result["package_msg"]) package_hex2, _package_txns2 = self.create_simple_package(coin2, DEFAULT_FEE, DEFAULT_CHILD_FEE) package_result = node.submitpackage(package_hex2) - assert_equal(f"package RBF failed: {child_result['tx'].rehash()} has both ancestor and descendant, exceeding cluster limit of 2", package_result["package_msg"]) + assert_equal(f"package RBF failed: {child_result['tx'].txid_hex} has both ancestor and descendant, exceeding cluster limit of 2", package_result["package_msg"]) package_hex3, _package_txns3 = self.create_simple_package(coin3, DEFAULT_FEE, DEFAULT_CHILD_FEE) package_result = node.submitpackage(package_hex3) - assert_equal(f"package RBF failed: {grandchild_result['tx'].rehash()} has 2 ancestors, max 1 allowed", package_result["package_msg"]) + assert_equal(f"package RBF failed: {grandchild_result['tx'].txid_hex} has 2 ancestors, max 1 allowed", package_result["package_msg"]) # Check that replacements were actually rejected self.assert_mempool_contents(expected=expected_txns) @@ -383,15 +383,15 @@ class PackageRBFTest(BitcoinTestFramework): # Now make conflicting packages for each coin package_hex1, _package_txns1 = self.create_simple_package(coin1, DEFAULT_FEE, DEFAULT_CHILD_FEE) package_result = node.submitpackage(package_hex1) - assert_equal(f"package RBF failed: {parent1_result['tx'].rehash()} is not the only parent of child {child_result['tx'].rehash()}", package_result["package_msg"]) + assert_equal(f"package RBF failed: {parent1_result['tx'].txid_hex} is not the only parent of child {child_result['tx'].txid_hex}", package_result["package_msg"]) package_hex2, _package_txns2 = self.create_simple_package(coin2, DEFAULT_FEE, DEFAULT_CHILD_FEE) package_result = node.submitpackage(package_hex2) - assert_equal(f"package RBF failed: {child_result['tx'].rehash()} has 2 ancestors, max 1 allowed", package_result["package_msg"]) + assert_equal(f"package RBF failed: {child_result['tx'].txid_hex} has 2 ancestors, max 1 allowed", package_result["package_msg"]) package_hex3, _package_txns3 = self.create_simple_package(coin3, DEFAULT_FEE, DEFAULT_CHILD_FEE) package_result = node.submitpackage(package_hex3) - assert_equal(f"package RBF failed: {child_result['tx'].rehash()} has 2 ancestors, max 1 allowed", package_result["package_msg"]) + assert_equal(f"package RBF failed: {child_result['tx'].txid_hex} has 2 ancestors, max 1 allowed", package_result["package_msg"]) # Check that replacements were actually rejected self.assert_mempool_contents(expected=expected_txns) @@ -437,15 +437,15 @@ class PackageRBFTest(BitcoinTestFramework): # Now make conflicting packages for each coin package_hex1, _package_txns1 = self.create_simple_package(coin1, DEFAULT_FEE, DEFAULT_CHILD_FEE) package_result = node.submitpackage(package_hex1) - assert_equal(f"package RBF failed: {child1_result['tx'].rehash()} is not the only child of parent {parent_result['tx'].rehash()}", package_result["package_msg"]) + assert_equal(f"package RBF failed: {child1_result['tx'].txid_hex} is not the only child of parent {parent_result['tx'].txid_hex}", package_result["package_msg"]) package_hex2, _package_txns2 = self.create_simple_package(coin2, DEFAULT_FEE, DEFAULT_CHILD_FEE) package_result = node.submitpackage(package_hex2) - assert_equal(f"package RBF failed: {child1_result['tx'].rehash()} is not the only child of parent {parent_result['tx'].rehash()}", package_result["package_msg"]) + assert_equal(f"package RBF failed: {child1_result['tx'].txid_hex} is not the only child of parent {parent_result['tx'].txid_hex}", package_result["package_msg"]) package_hex3, _package_txns3 = self.create_simple_package(coin3, DEFAULT_FEE, DEFAULT_CHILD_FEE) package_result = node.submitpackage(package_hex3) - assert_equal(f"package RBF failed: {child2_result['tx'].rehash()} is not the only child of parent {parent_result['tx'].rehash()}", package_result["package_msg"]) + assert_equal(f"package RBF failed: {child2_result['tx'].txid_hex} is not the only child of parent {parent_result['tx'].txid_hex}", package_result["package_msg"]) # Check that replacements were actually rejected self.assert_mempool_contents(expected=expected_txns) diff --git a/test/functional/mempool_reorg.py b/test/functional/mempool_reorg.py index 74a353ab014..818dd2cae86 100755 --- a/test/functional/mempool_reorg.py +++ b/test/functional/mempool_reorg.py @@ -73,7 +73,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework): # request very recent, unanounced transactions. assert_equal(len(peer1.get_invs()), 0) # It's too early to request these two transactions - requests_too_recent = msg_getdata([CInv(t=MSG_WTX, h=int(tx["tx"].getwtxid(), 16)) for tx in [tx_before_reorg, tx_child]]) + requests_too_recent = msg_getdata([CInv(t=MSG_WTX, h=tx["tx"].wtxid_int) for tx in [tx_before_reorg, tx_child]]) peer1.send_and_ping(requests_too_recent) for _ in range(len(requests_too_recent.inv)): peer1.sync_with_ping() @@ -82,7 +82,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework): assert "notfound" in peer1.last_message # Request the tx from the disconnected block - request_disconnected_tx = msg_getdata([CInv(t=MSG_WTX, h=int(tx_disconnected["tx"].getwtxid(), 16))]) + request_disconnected_tx = msg_getdata([CInv(t=MSG_WTX, h=tx_disconnected["tx"].wtxid_int)]) peer1.send_and_ping(request_disconnected_tx) # The tx from the disconnected block was never announced, and it entered the mempool later @@ -90,7 +90,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework): assert_equal(len(peer1.get_invs()), 0) with p2p_lock: # However, the node will answer requests for the tx from the recently-disconnected block. - assert_equal(peer1.last_message["tx"].tx.getwtxid(),tx_disconnected["tx"].getwtxid()) + assert_equal(peer1.last_message["tx"].tx.wtxid_hex,tx_disconnected["tx"].wtxid_hex) self.nodes[1].setmocktime(int(time.time()) + 300) peer1.sync_with_ping() @@ -102,7 +102,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework): last_tx_received = peer1.last_message["tx"] tx_after_reorg = self.wallet.send_self_transfer(from_node=self.nodes[1]) - request_after_reorg = msg_getdata([CInv(t=MSG_WTX, h=int(tx_after_reorg["tx"].getwtxid(), 16))]) + request_after_reorg = msg_getdata([CInv(t=MSG_WTX, h=tx_after_reorg["tx"].wtxid_int)]) assert tx_after_reorg["txid"] in self.nodes[1].getrawmempool() peer1.send_and_ping(request_after_reorg) with p2p_lock: diff --git a/test/functional/mempool_sigoplimit.py b/test/functional/mempool_sigoplimit.py index 94c13f62a21..23ddf0bac9c 100755 --- a/test/functional/mempool_sigoplimit.py +++ b/test/functional/mempool_sigoplimit.py @@ -121,13 +121,13 @@ class BytesPerSigOpTest(BitcoinTestFramework): parent_txid = tx.vin[0].prevout.hash.to_bytes(32, 'big').hex() parent_tx = tx_from_hex(self.nodes[0].getrawtransaction(txid=parent_txid)) - entry_child = self.nodes[0].getmempoolentry(tx.rehash()) + entry_child = self.nodes[0].getmempoolentry(tx.txid_hex) assert_equal(entry_child['descendantcount'], 1) assert_equal(entry_child['descendantsize'], sigop_equivalent_vsize) assert_equal(entry_child['ancestorcount'], 2) assert_equal(entry_child['ancestorsize'], sigop_equivalent_vsize + parent_tx.get_vsize()) - entry_parent = self.nodes[0].getmempoolentry(parent_tx.rehash()) + entry_parent = self.nodes[0].getmempoolentry(parent_tx.txid_hex) assert_equal(entry_parent['ancestorcount'], 1) assert_equal(entry_parent['ancestorsize'], parent_tx.get_vsize()) assert_equal(entry_parent['descendantcount'], 2) @@ -147,7 +147,7 @@ class BytesPerSigOpTest(BitcoinTestFramework): tx = tx_dict["tx"] tx.vout.append(CTxOut(amount_for_bare, keys_to_multisig_script([pubkey], k=1))) tx.vout[0].nValue -= amount_for_bare - tx_utxo["txid"] = tx.rehash() + tx_utxo["txid"] = tx.txid_hex tx_utxo["value"] -= Decimal("0.00005000") return (tx_utxo, tx) @@ -168,8 +168,8 @@ class BytesPerSigOpTest(BitcoinTestFramework): # When we actually try to submit, the parent makes it into the mempool, but the child would exceed ancestor vsize limits res = self.nodes[0].submitpackage([tx_parent.serialize().hex(), tx_child.serialize().hex()]) - assert "too-long-mempool-chain" in res["tx-results"][tx_child.getwtxid()]["error"] - assert tx_parent.rehash() in self.nodes[0].getrawmempool() + assert "too-long-mempool-chain" in res["tx-results"][tx_child.wtxid_hex]["error"] + assert tx_parent.txid_hex in self.nodes[0].getrawmempool() # Transactions are tiny in weight assert_greater_than(2000, tx_parent.get_weight() + tx_child.get_weight()) diff --git a/test/functional/mining_basic.py b/test/functional/mining_basic.py index 12f1a4ddf5b..2807ef01b84 100755 --- a/test/functional/mining_basic.py +++ b/test/functional/mining_basic.py @@ -425,7 +425,6 @@ class MiningTest(BitcoinTestFramework): coinbase_tx = create_coinbase(height=next_height) # sequence numbers must not be max for nLockTime to have effect coinbase_tx.vin[0].nSequence = 2**32 - 2 - coinbase_tx.rehash() block = CBlock() block.nVersion = tmpl["version"] @@ -447,7 +446,6 @@ class MiningTest(BitcoinTestFramework): self.log.info("getblocktemplate: Test bad input hash for coinbase transaction") bad_block = copy.deepcopy(block) bad_block.vtx[0].vin[0].prevout.hash += 1 - bad_block.vtx[0].rehash() assert_template(node, bad_block, 'bad-cb-missing') self.log.info("submitblock: Test bad input hash for coinbase transaction") @@ -481,7 +479,6 @@ class MiningTest(BitcoinTestFramework): bad_block = copy.deepcopy(block) bad_tx = copy.deepcopy(bad_block.vtx[0]) bad_tx.vin[0].prevout.hash = 255 - bad_tx.rehash() bad_block.vtx.append(bad_tx) assert_template(node, bad_block, 'bad-txns-inputs-missingorspent') assert_submitblock(bad_block, 'bad-txns-inputs-missingorspent') @@ -489,7 +486,6 @@ class MiningTest(BitcoinTestFramework): self.log.info("getblocktemplate: Test nonfinal transaction") bad_block = copy.deepcopy(block) bad_block.vtx[0].nLockTime = 2**32 - 1 - bad_block.vtx[0].rehash() assert_template(node, bad_block, 'bad-txns-nonfinal') assert_submitblock(bad_block, 'bad-txns-nonfinal') @@ -563,7 +559,6 @@ class MiningTest(BitcoinTestFramework): bad_block_lock = copy.deepcopy(block) bad_block_lock.vtx[0].nLockTime = 2**32 - 1 - bad_block_lock.vtx[0].rehash() bad_block_lock.hashMerkleRoot = bad_block_lock.calc_merkle_root() bad_block_lock.solve() assert_equal(node.submitblock(hexdata=bad_block_lock.serialize().hex()), 'bad-txns-nonfinal') diff --git a/test/functional/mining_mainnet.py b/test/functional/mining_mainnet.py index 4f95696f78c..25632fbc8e7 100755 --- a/test/functional/mining_mainnet.py +++ b/test/functional/mining_mainnet.py @@ -65,7 +65,6 @@ class MiningMainnetTest(BitcoinTestFramework): # The alternate mainnet chain was mined with non-timelocked coinbase txs. block.vtx[0].nLockTime = 0 block.vtx[0].vin[0].nSequence = SEQUENCE_FINAL - block.vtx[0].rehash() block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block_hex = block.serialize(with_witness=False).hex() diff --git a/test/functional/p2p_compactblocks.py b/test/functional/p2p_compactblocks.py index c207515d28f..7b816fe2720 100755 --- a/test/functional/p2p_compactblocks.py +++ b/test/functional/p2p_compactblocks.py @@ -166,10 +166,9 @@ class CompactBlocksTest(BitcoinTestFramework): total_value = block.vtx[0].vout[0].nValue out_value = total_value // 10 tx = CTransaction() - tx.vin.append(CTxIn(COutPoint(block.vtx[0].sha256, 0), b'')) + tx.vin.append(CTxIn(COutPoint(block.vtx[0].txid_int, 0), b'')) for _ in range(10): tx.vout.append(CTxOut(out_value, CScript([OP_TRUE]))) - tx.rehash() block2 = self.build_block_on_tip(self.nodes[0]) block2.vtx.append(tx) @@ -177,7 +176,7 @@ class CompactBlocksTest(BitcoinTestFramework): block2.solve() self.segwit_node.send_and_ping(msg_no_witness_block(block2)) assert_equal(int(self.nodes[0].getbestblockhash(), 16), block2.sha256) - self.utxos.extend([[tx.sha256, i, out_value] for i in range(10)]) + self.utxos.extend([[tx.txid_int, i, out_value] for i in range(10)]) # Test "sendcmpct" (between peers preferring the same version): @@ -309,8 +308,6 @@ class CompactBlocksTest(BitcoinTestFramework): # Store the raw block in our internal format. block = from_hex(CBlock(), node.getblock("%064x" % block_hash, False)) - for tx in block.vtx: - tx.calc_sha256() block.rehash() # Wait until the block was announced (via compact blocks) @@ -349,10 +346,10 @@ class CompactBlocksTest(BitcoinTestFramework): # Check that all prefilled_txn entries match what's in the block. for entry in header_and_shortids.prefilled_txn: # This checks the non-witness parts of the tx agree - assert_equal(entry.tx.rehash(), block.vtx[entry.index].rehash()) + assert_equal(entry.tx.txid_hex, block.vtx[entry.index].txid_hex) # And this checks the witness - assert_equal(entry.tx.getwtxid(), block.vtx[entry.index].getwtxid()) + assert_equal(entry.tx.wtxid_hex, block.vtx[entry.index].wtxid_hex) # Check that the cmpctblock message announced all the transactions. assert_equal(len(header_and_shortids.prefilled_txn) + len(header_and_shortids.shortids), len(block.vtx)) @@ -368,7 +365,7 @@ class CompactBlocksTest(BitcoinTestFramework): # Already checked prefilled transactions above header_and_shortids.prefilled_txn.pop(0) else: - tx_hash = block.vtx[index].calc_sha256(True) + tx_hash = block.vtx[index].wtxid_int shortid = calculate_shortid(k0, k1, tx_hash) assert_equal(shortid, header_and_shortids.shortids[0]) header_and_shortids.shortids.pop(0) @@ -398,7 +395,7 @@ class CompactBlocksTest(BitcoinTestFramework): comp_block.header = CBlockHeader(block) comp_block.nonce = 0 [k0, k1] = comp_block.get_siphash_keys() - coinbase_hash = block.vtx[0].calc_sha256(True) + coinbase_hash = block.vtx[0].wtxid_int comp_block.shortids = [calculate_shortid(k0, k1, coinbase_hash)] test_node.send_and_ping(msg_cmpctblock(comp_block.to_p2p())) assert_equal(int(node.getbestblockhash(), 16), block.hashPrevBlock) @@ -423,8 +420,7 @@ class CompactBlocksTest(BitcoinTestFramework): tx = CTransaction() tx.vin.append(CTxIn(COutPoint(utxo[0], utxo[1]), b'')) tx.vout.append(CTxOut(utxo[2] - 1000, CScript([OP_TRUE, OP_DROP] * 15 + [OP_TRUE]))) - tx.rehash() - utxo = [tx.sha256, 0, tx.vout[0].nValue] + utxo = [tx.txid_int, 0, tx.vout[0].nValue] block.vtx.append(tx) block.hashMerkleRoot = block.calc_merkle_root() @@ -454,7 +450,7 @@ class CompactBlocksTest(BitcoinTestFramework): utxo = self.utxos.pop(0) block = self.build_block_with_transactions(node, utxo, 5) - self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue]) + self.utxos.append([block.vtx[-1].txid_int, 0, block.vtx[-1].vout[0].nValue]) comp_block = HeaderAndShortIDs() comp_block.initialize_from_block(block, use_witness=True) @@ -467,7 +463,7 @@ class CompactBlocksTest(BitcoinTestFramework): utxo = self.utxos.pop(0) block = self.build_block_with_transactions(node, utxo, 5) - self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue]) + self.utxos.append([block.vtx[-1].txid_int, 0, block.vtx[-1].vout[0].nValue]) # Now try interspersing the prefilled transactions comp_block.initialize_from_block(block, prefill_list=[0, 1, 5], use_witness=True) @@ -478,9 +474,9 @@ class CompactBlocksTest(BitcoinTestFramework): # Now try giving one transaction ahead of time. utxo = self.utxos.pop(0) block = self.build_block_with_transactions(node, utxo, 5) - self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue]) + self.utxos.append([block.vtx[-1].txid_int, 0, block.vtx[-1].vout[0].nValue]) test_node.send_and_ping(msg_tx(block.vtx[1])) - assert block.vtx[1].hash in node.getrawmempool() + assert block.vtx[1].txid_hex in node.getrawmempool() # Prefill 4 out of the 6 transactions, and verify that only the one # that was not in the mempool is requested. @@ -494,14 +490,14 @@ class CompactBlocksTest(BitcoinTestFramework): # announced and verify reconstruction happens immediately. utxo = self.utxos.pop(0) block = self.build_block_with_transactions(node, utxo, 10) - self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue]) + self.utxos.append([block.vtx[-1].txid_int, 0, block.vtx[-1].vout[0].nValue]) for tx in block.vtx[1:]: test_node.send_without_ping(msg_tx(tx)) test_node.sync_with_ping() # Make sure all transactions were accepted. mempool = node.getrawmempool() for tx in block.vtx[1:]: - assert tx.hash in mempool + assert tx.txid_hex in mempool # Clear out last request. with p2p_lock: @@ -521,7 +517,7 @@ class CompactBlocksTest(BitcoinTestFramework): utxo = self.utxos.pop(0) block = self.build_block_with_transactions(node, utxo, 10) - self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue]) + self.utxos.append([block.vtx[-1].txid_int, 0, block.vtx[-1].vout[0].nValue]) # Relay the first 5 transactions from the block in advance for tx in block.vtx[1:6]: test_node.send_without_ping(msg_tx(tx)) @@ -529,7 +525,7 @@ class CompactBlocksTest(BitcoinTestFramework): # Make sure all transactions were accepted. mempool = node.getrawmempool() for tx in block.vtx[1:6]: - assert tx.hash in mempool + assert tx.txid_hex in mempool # Send compact block comp_block = HeaderAndShortIDs() @@ -583,15 +579,14 @@ class CompactBlocksTest(BitcoinTestFramework): test_node.send_without_ping(msg) test_node.wait_until(lambda: "blocktxn" in test_node.last_message, timeout=10) - [tx.calc_sha256() for tx in block.vtx] with p2p_lock: assert_equal(test_node.last_message["blocktxn"].block_transactions.blockhash, int(block_hash, 16)) all_indices = msg.block_txn_request.to_absolute() for index in all_indices: tx = test_node.last_message["blocktxn"].block_transactions.transactions.pop(0) - assert_equal(tx.rehash(), block.vtx[index].rehash()) + assert_equal(tx.txid_hex, block.vtx[index].txid_hex) # Check that the witness matches - assert_equal(tx.getwtxid(), block.vtx[index].getwtxid()) + assert_equal(tx.wtxid_hex, block.vtx[index].wtxid_hex) test_node.last_message.pop("blocktxn", None) current_height -= 1 @@ -770,12 +765,12 @@ class CompactBlocksTest(BitcoinTestFramework): delivery_peer.sync_with_ping() mempool = node.getrawmempool() for tx in block.vtx[1:]: - assert tx.hash in mempool + assert tx.txid_hex in mempool delivery_peer.send_and_ping(msg_cmpctblock(cmpct_block.to_p2p())) assert_equal(int(node.getbestblockhash(), 16), block.sha256) - self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue]) + self.utxos.append([block.vtx[-1].txid_int, 0, block.vtx[-1].vout[0].nValue]) # Now test that delivering an invalid compact block won't break relay @@ -889,7 +884,7 @@ class CompactBlocksTest(BitcoinTestFramework): # Nothing bad should happen if we get a late fill from the first peer... stalling_peer.send_and_ping(msg) - self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue]) + self.utxos.append([block.vtx[-1].txid_int, 0, block.vtx[-1].vout[0].nValue]) delivery_peer.clear_getblocktxn() inbound_peer.clear_getblocktxn() diff --git a/test/functional/p2p_invalid_block.py b/test/functional/p2p_invalid_block.py index c28ee47f9ce..8b177542dcc 100755 --- a/test/functional/p2p_invalid_block.py +++ b/test/functional/p2p_invalid_block.py @@ -93,7 +93,6 @@ class InvalidBlockRequestTest(BitcoinTestFramework): block2_dup = copy.deepcopy(block2_orig) block2_dup.vtx[2].vin.append(block2_dup.vtx[2].vin[0]) - block2_dup.vtx[2].rehash() block2_dup.hashMerkleRoot = block2_dup.calc_merkle_root() block2_dup.solve() peer.send_blocks_and_test([block2_dup], node, success=False, reject_reason='bad-txns-inputs-duplicate') @@ -122,7 +121,6 @@ class InvalidBlockRequestTest(BitcoinTestFramework): # Create a block that spends the output of a tx in a previous block. tx3 = create_tx_with_script(tx2, 0, script_sig=bytes([OP_TRUE]), amount=50 * COIN) tx3.vin.append(tx3.vin[0]) # Duplicates input - tx3.rehash() block4 = create_block(tip, create_coinbase(height), block_time, txlist=[tx3]) block4.solve() self.log.info("Test inflation by duplicating input") diff --git a/test/functional/p2p_invalid_tx.py b/test/functional/p2p_invalid_tx.py index ee8c6c16ca3..ae9771e7cb4 100755 --- a/test/functional/p2p_invalid_tx.py +++ b/test/functional/p2p_invalid_tx.py @@ -91,32 +91,28 @@ class InvalidTxRequestTest(BitcoinTestFramework): # are sent out and in the orphan cache SCRIPT_PUB_KEY_OP_TRUE = b'\x51\x75' * 15 + b'\x51' tx_withhold = CTransaction() - tx_withhold.vin.append(CTxIn(outpoint=COutPoint(block1.vtx[0].sha256, 0))) + tx_withhold.vin.append(CTxIn(outpoint=COutPoint(block1.vtx[0].txid_int, 0))) tx_withhold.vout = [CTxOut(nValue=25 * COIN - 12000, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE)] * 2 - tx_withhold.calc_sha256() # Our first orphan tx with some outputs to create further orphan txs tx_orphan_1 = CTransaction() - tx_orphan_1.vin.append(CTxIn(outpoint=COutPoint(tx_withhold.sha256, 0))) + tx_orphan_1.vin.append(CTxIn(outpoint=COutPoint(tx_withhold.txid_int, 0))) tx_orphan_1.vout = [CTxOut(nValue=8 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE)] * 3 - tx_orphan_1.calc_sha256() # A valid transaction with low fee tx_orphan_2_no_fee = CTransaction() - tx_orphan_2_no_fee.vin.append(CTxIn(outpoint=COutPoint(tx_orphan_1.sha256, 0))) + tx_orphan_2_no_fee.vin.append(CTxIn(outpoint=COutPoint(tx_orphan_1.txid_int, 0))) tx_orphan_2_no_fee.vout.append(CTxOut(nValue=8 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE)) # A valid transaction with sufficient fee tx_orphan_2_valid = CTransaction() - tx_orphan_2_valid.vin.append(CTxIn(outpoint=COutPoint(tx_orphan_1.sha256, 1))) + tx_orphan_2_valid.vin.append(CTxIn(outpoint=COutPoint(tx_orphan_1.txid_int, 1))) tx_orphan_2_valid.vout.append(CTxOut(nValue=8 * COIN - 12000, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE)) - tx_orphan_2_valid.calc_sha256() # An invalid transaction with negative fee tx_orphan_2_invalid = CTransaction() - tx_orphan_2_invalid.vin.append(CTxIn(outpoint=COutPoint(tx_orphan_1.sha256, 2))) + tx_orphan_2_invalid.vin.append(CTxIn(outpoint=COutPoint(tx_orphan_1.txid_int, 2))) tx_orphan_2_invalid.vout.append(CTxOut(nValue=11 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE)) - tx_orphan_2_invalid.calc_sha256() self.log.info('Send the orphans ... ') # Send valid orphan txs from p2ps[0] @@ -133,7 +129,7 @@ class InvalidTxRequestTest(BitcoinTestFramework): # Transactions that should end up in the mempool expected_mempool = { - t.hash + t.txid_hex for t in [ tx_withhold, # The transaction that is the root for all orphans tx_orphan_1, # The orphan transaction that splits the coins @@ -158,10 +154,9 @@ class InvalidTxRequestTest(BitcoinTestFramework): self.log.info('Test orphan with rejected parents') rejected_parent = CTransaction() - rejected_parent.vin.append(CTxIn(outpoint=COutPoint(tx_orphan_2_invalid.sha256, 0))) + rejected_parent.vin.append(CTxIn(outpoint=COutPoint(tx_orphan_2_invalid.txid_int, 0))) rejected_parent.vout.append(CTxOut(nValue=11 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE)) - rejected_parent.rehash() - with node.assert_debug_log(['not keeping orphan with rejected parents {}'.format(rejected_parent.hash)]): + with node.assert_debug_log(['not keeping orphan with rejected parents {}'.format(rejected_parent.txid_hex)]): node.p2ps[0].send_txs_and_test([rejected_parent], node, success=False) self.log.info('Test that a peer disconnection causes erase its transactions from the orphan pool') @@ -170,14 +165,12 @@ class InvalidTxRequestTest(BitcoinTestFramework): self.log.info('Test that a transaction in the orphan pool is included in a new tip block causes erase this transaction from the orphan pool') tx_withhold_until_block_A = CTransaction() - tx_withhold_until_block_A.vin.append(CTxIn(outpoint=COutPoint(tx_withhold.sha256, 1))) + tx_withhold_until_block_A.vin.append(CTxIn(outpoint=COutPoint(tx_withhold.txid_int, 1))) tx_withhold_until_block_A.vout = [CTxOut(nValue=12 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE)] * 2 - tx_withhold_until_block_A.calc_sha256() tx_orphan_include_by_block_A = CTransaction() - tx_orphan_include_by_block_A.vin.append(CTxIn(outpoint=COutPoint(tx_withhold_until_block_A.sha256, 0))) + tx_orphan_include_by_block_A.vin.append(CTxIn(outpoint=COutPoint(tx_withhold_until_block_A.txid_int, 0))) tx_orphan_include_by_block_A.vout.append(CTxOut(nValue=12 * COIN - 12000, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE)) - tx_orphan_include_by_block_A.calc_sha256() self.log.info('Send the orphan ... ') node.p2ps[0].send_txs_and_test([tx_orphan_include_by_block_A], node, success=False) @@ -195,19 +188,16 @@ class InvalidTxRequestTest(BitcoinTestFramework): self.log.info('Test that a transaction in the orphan pool conflicts with a new tip block causes erase this transaction from the orphan pool') tx_withhold_until_block_B = CTransaction() - tx_withhold_until_block_B.vin.append(CTxIn(outpoint=COutPoint(tx_withhold_until_block_A.sha256, 1))) + tx_withhold_until_block_B.vin.append(CTxIn(outpoint=COutPoint(tx_withhold_until_block_A.txid_int, 1))) tx_withhold_until_block_B.vout.append(CTxOut(nValue=11 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE)) - tx_withhold_until_block_B.calc_sha256() tx_orphan_include_by_block_B = CTransaction() - tx_orphan_include_by_block_B.vin.append(CTxIn(outpoint=COutPoint(tx_withhold_until_block_B.sha256, 0))) + tx_orphan_include_by_block_B.vin.append(CTxIn(outpoint=COutPoint(tx_withhold_until_block_B.txid_int, 0))) tx_orphan_include_by_block_B.vout.append(CTxOut(nValue=10 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE)) - tx_orphan_include_by_block_B.calc_sha256() tx_orphan_conflict_by_block_B = CTransaction() - tx_orphan_conflict_by_block_B.vin.append(CTxIn(outpoint=COutPoint(tx_withhold_until_block_B.sha256, 0))) + tx_orphan_conflict_by_block_B.vin.append(CTxIn(outpoint=COutPoint(tx_withhold_until_block_B.txid_int, 0))) tx_orphan_conflict_by_block_B.vout.append(CTxOut(nValue=9 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE)) - tx_orphan_conflict_by_block_B.calc_sha256() self.log.info('Send the orphan ... ') node.p2ps[0].send_txs_and_test([tx_orphan_conflict_by_block_B], node, success=False) diff --git a/test/functional/p2p_leak_tx.py b/test/functional/p2p_leak_tx.py index a2eec49b727..a1a00751d12 100755 --- a/test/functional/p2p_leak_tx.py +++ b/test/functional/p2p_leak_tx.py @@ -44,7 +44,7 @@ class P2PLeakTxTest(BitcoinTestFramework): self.log.debug("Request transaction") inbound_peer.last_message.pop("tx", None) inbound_peer.send_and_ping(want_tx) - assert_equal(inbound_peer.last_message.get("tx").tx.getwtxid(), wtxid) + assert_equal(inbound_peer.last_message.get("tx").tx.wtxid_hex, wtxid) def test_notfound_on_replaced_tx(self): self.gen_node.disconnect_p2ps() @@ -57,7 +57,7 @@ class P2PLeakTxTest(BitcoinTestFramework): tx_b = tx_a["tx"] tx_b.vout[0].nValue -= 9000 self.gen_node.sendrawtransaction(tx_b.serialize().hex()) - inbound_peer.wait_until(lambda: "tx" in inbound_peer.last_message and inbound_peer.last_message.get("tx").tx.getwtxid() == tx_b.getwtxid()) + inbound_peer.wait_until(lambda: "tx" in inbound_peer.last_message and inbound_peer.last_message.get("tx").tx.wtxid_hex == tx_b.wtxid_hex) self.log.info("Re-request of tx_a after replacement is answered with notfound") req_vec = [ diff --git a/test/functional/p2p_opportunistic_1p1c.py b/test/functional/p2p_opportunistic_1p1c.py index 0cdec4275fd..267a878323d 100755 --- a/test/functional/p2p_opportunistic_1p1c.py +++ b/test/functional/p2p_opportunistic_1p1c.py @@ -83,7 +83,7 @@ class PackageRelayTest(BitcoinTestFramework): peer_sender = node.add_p2p_connection(P2PInterface()) # 1. Child is received first (perhaps the low feerate parent didn't meet feefilter or the requests were sent to different nodes). It is missing an input. - high_child_wtxid_int = int(high_fee_child["tx"].getwtxid(), 16) + high_child_wtxid_int = high_fee_child["tx"].wtxid_int peer_sender.send_and_ping(msg_inv([CInv(t=MSG_WTX, h=high_child_wtxid_int)])) peer_sender.wait_for_getdata([high_child_wtxid_int]) peer_sender.send_and_ping(msg_tx(high_fee_child["tx"])) @@ -112,7 +112,7 @@ class PackageRelayTest(BitcoinTestFramework): peer_ignored = node.add_outbound_p2p_connection(P2PInterface(), p2p_idx=2, connection_type="outbound-full-relay") # 1. Parent is relayed first. It is too low feerate. - parent_wtxid_int = int(low_fee_parent["tx"].getwtxid(), 16) + parent_wtxid_int = low_fee_parent["tx"].wtxid_int peer_sender.send_and_ping(msg_inv([CInv(t=MSG_WTX, h=parent_wtxid_int)])) peer_sender.wait_for_getdata([parent_wtxid_int]) peer_sender.send_and_ping(msg_tx(low_fee_parent["tx"])) @@ -123,7 +123,7 @@ class PackageRelayTest(BitcoinTestFramework): assert "getdata" not in peer_ignored.last_message # 2. Child is relayed next. It is missing an input. - high_child_wtxid_int = int(high_fee_child["tx"].getwtxid(), 16) + high_child_wtxid_int = high_fee_child["tx"].wtxid_int peer_sender.send_and_ping(msg_inv([CInv(t=MSG_WTX, h=high_child_wtxid_int)])) peer_sender.wait_for_getdata([high_child_wtxid_int]) peer_sender.send_and_ping(msg_tx(high_fee_child["tx"])) @@ -156,7 +156,7 @@ class PackageRelayTest(BitcoinTestFramework): self.log.info("Check that tx caches low fee parent + low fee child package rejections") # 1. Send parent, rejected for being low feerate. - parent_wtxid_int = int(low_fee_parent["tx"].getwtxid(), 16) + parent_wtxid_int = low_fee_parent["tx"].wtxid_int peer_sender.send_and_ping(msg_inv([CInv(t=MSG_WTX, h=parent_wtxid_int)])) peer_sender.wait_for_getdata([parent_wtxid_int]) peer_sender.send_and_ping(msg_tx(low_fee_parent["tx"])) @@ -167,7 +167,7 @@ class PackageRelayTest(BitcoinTestFramework): assert "getdata" not in peer_ignored.last_message # 2. Send an (orphan) child that has a higher feerate, but not enough to bump the parent. - med_child_wtxid_int = int(med_fee_child["tx"].getwtxid(), 16) + med_child_wtxid_int = med_fee_child["tx"].wtxid_int peer_sender.send_and_ping(msg_inv([CInv(t=MSG_WTX, h=med_child_wtxid_int)])) peer_sender.wait_for_getdata([med_child_wtxid_int]) peer_sender.send_and_ping(msg_tx(med_fee_child["tx"])) @@ -193,7 +193,7 @@ class PackageRelayTest(BitcoinTestFramework): assert med_fee_child["txid"] not in node.getrawmempool() # 5. Send the high feerate (orphan) child - high_child_wtxid_int = int(high_fee_child["tx"].getwtxid(), 16) + high_child_wtxid_int = high_fee_child["tx"].wtxid_int peer_sender.send_and_ping(msg_inv([CInv(t=MSG_WTX, h=high_child_wtxid_int)])) peer_sender.wait_for_getdata([high_child_wtxid_int]) peer_sender.send_and_ping(msg_tx(high_fee_child["tx"])) @@ -229,7 +229,7 @@ class PackageRelayTest(BitcoinTestFramework): parent_sender = node.add_p2p_connection(P2PInterface()) # 1. Child is received first. It is missing an input. - child_wtxid_int = int(tx_orphan_bad_wit.getwtxid(), 16) + child_wtxid_int = tx_orphan_bad_wit.wtxid_int bad_orphan_sender.send_and_ping(msg_inv([CInv(t=MSG_WTX, h=child_wtxid_int)])) bad_orphan_sender.wait_for_getdata([child_wtxid_int]) bad_orphan_sender.send_and_ping(msg_tx(tx_orphan_bad_wit)) @@ -245,7 +245,7 @@ class PackageRelayTest(BitcoinTestFramework): # 4. Transactions should not be in mempool. node_mempool = node.getrawmempool() assert low_fee_parent["txid"] not in node_mempool - assert tx_orphan_bad_wit.rehash() not in node_mempool + assert tx_orphan_bad_wit.txid_hex not in node_mempool # 5. Have the other peer send the tx too, so that tx_orphan_bad_wit package is attempted. bad_orphan_sender.send_without_ping(msg_tx(low_fee_parent["tx"])) @@ -270,13 +270,13 @@ class PackageRelayTest(BitcoinTestFramework): fake_parent_sender = node.add_p2p_connection(P2PInterface()) # 1. Child is received first. It is missing an input. - child_wtxid_int = int(high_fee_child["tx"].getwtxid(), 16) + child_wtxid_int = high_fee_child["tx"].wtxid_int package_sender.send_and_ping(msg_inv([CInv(t=MSG_WTX, h=child_wtxid_int)])) package_sender.wait_for_getdata([child_wtxid_int]) package_sender.send_and_ping(msg_tx(high_fee_child["tx"])) # 2. Node requests the missing parent by txid. - parent_txid_int = int(tx_parent_bad_wit.rehash(), 16) + parent_txid_int = tx_parent_bad_wit.txid_int package_sender.wait_for_getdata([parent_txid_int]) # 3. A different node relays the parent. The parent is first evaluated by itself and @@ -286,13 +286,13 @@ class PackageRelayTest(BitcoinTestFramework): # 4. Transactions should not be in mempool. node_mempool = node.getrawmempool() - assert tx_parent_bad_wit.rehash() not in node_mempool + assert tx_parent_bad_wit.txid_hex not in node_mempool assert high_fee_child["txid"] not in node_mempool self.log.info("Check that fake parent does not cause orphan to be deleted and real package can still be submitted") # 5. Child-sending should not have been punished and the orphan should remain in orphanage. # It can send the "real" parent transaction, and the package is accepted. - parent_wtxid_int = int(low_fee_parent["tx"].getwtxid(), 16) + parent_wtxid_int = low_fee_parent["tx"].wtxid_int package_sender.send_and_ping(msg_inv([CInv(t=MSG_WTX, h=parent_wtxid_int)])) package_sender.wait_for_getdata([parent_wtxid_int]) package_sender.send_and_ping(msg_tx(low_fee_parent["tx"])) diff --git a/test/functional/p2p_orphan_handling.py b/test/functional/p2p_orphan_handling.py index b40ea0e6a12..d10c796acf7 100755 --- a/test/functional/p2p_orphan_handling.py +++ b/test/functional/p2p_orphan_handling.py @@ -128,11 +128,11 @@ class OrphanHandlingTest(BitcoinTestFramework): """Create package with 1 parent and 1 child, normal fees (no cpfp).""" parent = self.wallet.create_self_transfer() child = self.wallet.create_self_transfer(utxo_to_spend=parent['new_utxo']) - return child["tx"].getwtxid(), child["tx"], parent["tx"] + return child["tx"].wtxid_hex, child["tx"], parent["tx"] def relay_transaction(self, peer, tx): """Relay transaction using MSG_WTX""" - wtxid = int(tx.getwtxid(), 16) + wtxid = tx.wtxid_int peer.send_and_ping(msg_inv([CInv(t=MSG_WTX, h=wtxid)])) self.nodes[0].bumpmocktime(TXREQUEST_TIME_SKIP) peer.wait_for_getdata([wtxid]) @@ -149,8 +149,8 @@ class OrphanHandlingTest(BitcoinTestFramework): # classify it as a transaction in which the witness was missing rather than wrong. tx_bad_wit.wit.vtxinwit[0].scriptWitness.stack = [b'garbage'] - assert_equal(tx["txid"], tx_bad_wit.rehash()) - assert_not_equal(tx["wtxid"], tx_bad_wit.getwtxid()) + assert_equal(tx["txid"], tx_bad_wit.txid_hex) + assert_not_equal(tx["wtxid"], tx_bad_wit.wtxid_hex) return tx_bad_wit @@ -184,7 +184,7 @@ class OrphanHandlingTest(BitcoinTestFramework): # Spy peer should not be able to query the node for the parent yet, since it hasn't been # announced / insufficient time has elapsed. - parent_inv = CInv(t=MSG_WTX, h=int(tx_parent_arrives["tx"].getwtxid(), 16)) + parent_inv = CInv(t=MSG_WTX, h=tx_parent_arrives["tx"].wtxid_int) assert_equal(len(peer_spy.get_invs()), 0) peer_spy.assert_no_immediate_response(msg_getdata([parent_inv])) @@ -205,7 +205,7 @@ class OrphanHandlingTest(BitcoinTestFramework): self.log.info("Test orphan handling when a nonsegwit parent is known to be invalid") parent_low_fee_nonsegwit = self.wallet_nonsegwit.create_self_transfer(fee_rate=0) - assert_equal(parent_low_fee_nonsegwit["txid"], parent_low_fee_nonsegwit["tx"].getwtxid()) + assert_equal(parent_low_fee_nonsegwit["txid"], parent_low_fee_nonsegwit["tx"].wtxid_hex) parent_other = self.wallet_nonsegwit.create_self_transfer() child_nonsegwit = self.wallet_nonsegwit.create_self_transfer_multi( utxos_to_spend=[parent_other["new_utxo"], parent_low_fee_nonsegwit["new_utxo"]]) @@ -242,7 +242,7 @@ class OrphanHandlingTest(BitcoinTestFramework): # The parent should be requested because even though the txid commits to the fee, it doesn't # commit to the feerate. Delayed because it's by txid and this is not a preferred relay peer. self.nodes[0].bumpmocktime(NONPREF_PEER_TX_DELAY + TXID_RELAY_DELAY) - peer2.wait_for_getdata([int(parent_low_fee["tx"].rehash(), 16)]) + peer2.wait_for_getdata([parent_low_fee["tx"].txid_int]) self.log.info("Test orphan handling when a parent was previously downloaded with witness stripped") parent_normal = self.wallet.create_self_transfer() @@ -251,8 +251,8 @@ class OrphanHandlingTest(BitcoinTestFramework): # Relay the parent with witness stripped. It should not be accepted. self.relay_transaction(peer1, parent1_witness_stripped) - assert_equal(parent_normal["txid"], parent1_witness_stripped.rehash()) - assert parent1_witness_stripped.rehash() not in node.getrawmempool() + assert_equal(parent_normal["txid"], parent1_witness_stripped.txid_hex) + assert parent1_witness_stripped.txid_hex not in node.getrawmempool() # Relay the child. It should not be accepted because it has missing inputs. self.relay_transaction(peer2, child_invalid_witness["tx"]) @@ -262,7 +262,7 @@ class OrphanHandlingTest(BitcoinTestFramework): # The parent should be requested since the unstripped wtxid would differ. Delayed because # it's by txid and this is not a preferred relay peer. self.nodes[0].bumpmocktime(NONPREF_PEER_TX_DELAY + TXID_RELAY_DELAY) - peer2.wait_for_getdata([int(parent_normal["tx"].rehash(), 16)]) + peer2.wait_for_getdata([parent_normal["tx"].txid_int]) # parent_normal can be relayed again even though parent1_witness_stripped was rejected self.relay_transaction(peer1, parent_normal["tx"]) @@ -348,9 +348,9 @@ class OrphanHandlingTest(BitcoinTestFramework): assert_equal(inflight_parent_AB["txid"], inflight_parent_AB["wtxid"]) # Announce inflight_parent_AB and wait for getdata - peer_txrequest.send_and_ping(msg_inv([CInv(t=MSG_WTX, h=int(inflight_parent_AB["tx"].getwtxid(), 16))])) + peer_txrequest.send_and_ping(msg_inv([CInv(t=MSG_WTX, h=inflight_parent_AB["tx"].wtxid_int)])) self.nodes[0].bumpmocktime(NONPREF_PEER_TX_DELAY) - peer_txrequest.wait_for_getdata([int(inflight_parent_AB["tx"].getwtxid(), 16)]) + peer_txrequest.wait_for_getdata([inflight_parent_AB["tx"].wtxid_int]) self.log.info("Test that the node does not request a parent if it has an in-flight txrequest") # Relay orphan child_A @@ -408,11 +408,11 @@ class OrphanHandlingTest(BitcoinTestFramework): self.log.info("Test that an orphan with rejected parents, along with any descendants, cannot be retried with an alternate witness") parent_low_fee_nonsegwit = self.wallet_nonsegwit.create_self_transfer(fee_rate=0) - assert_equal(parent_low_fee_nonsegwit["txid"], parent_low_fee_nonsegwit["tx"].getwtxid()) + assert_equal(parent_low_fee_nonsegwit["txid"], parent_low_fee_nonsegwit["tx"].wtxid_hex) child = self.wallet.create_self_transfer(utxo_to_spend=parent_low_fee_nonsegwit["new_utxo"]) grandchild = self.wallet.create_self_transfer(utxo_to_spend=child["new_utxo"]) - assert_not_equal(child["txid"], child["tx"].getwtxid()) - assert_not_equal(grandchild["txid"], grandchild["tx"].getwtxid()) + assert_not_equal(child["txid"], child["tx"].wtxid_hex) + assert_not_equal(grandchild["txid"], grandchild["tx"].wtxid_hex) # Relay the parent. It should be rejected because it pays 0 fees. self.relay_transaction(peer1, parent_low_fee_nonsegwit["tx"]) @@ -430,7 +430,7 @@ class OrphanHandlingTest(BitcoinTestFramework): assert_equal(0, len(node.getrawmempool())) assert not tx_in_orphanage(node, grandchild["tx"]) peer2.assert_never_requested(child["txid"]) - peer2.assert_never_requested(child["tx"].getwtxid()) + peer2.assert_never_requested(child["tx"].wtxid_hex) # The child should never be requested, even if announced again with potentially different witness. # Sync with ping to ensure orphans are reconsidered @@ -661,15 +661,15 @@ class OrphanHandlingTest(BitcoinTestFramework): # The outbound peer should be preferred for getting orphan parents self.nodes[0].bumpmocktime(TXID_RELAY_DELAY) - peer_outbound.wait_for_parent_requests([int(parent_tx.rehash(), 16)]) + peer_outbound.wait_for_parent_requests([parent_tx.txid_int]) # There should be no request to the inbound peer - peer_inbound.assert_never_requested(int(parent_tx.rehash(), 16)) + peer_inbound.assert_never_requested(parent_tx.txid_int) self.log.info("Test that, if the preferred peer doesn't respond, the node sends another request") self.nodes[0].bumpmocktime(GETDATA_TX_INTERVAL) peer_inbound.sync_with_ping() - peer_inbound.wait_for_parent_requests([int(parent_tx.rehash(), 16)]) + peer_inbound.wait_for_parent_requests([parent_tx.txid_int]) @cleanup def test_announcers_before_and_after(self): @@ -701,7 +701,7 @@ class OrphanHandlingTest(BitcoinTestFramework): # Peer disconnects before responding to request self.nodes[0].bumpmocktime(TXID_RELAY_DELAY) - peer_early_disconnected.wait_for_parent_requests([int(parent_tx.rehash(), 16)]) + peer_early_disconnected.wait_for_parent_requests([parent_tx.txid_int]) peer_early_disconnected.peer_disconnect() # The orphan should have 1 announcer left after the node finishes disconnecting peer_early_disconnected. @@ -710,7 +710,7 @@ class OrphanHandlingTest(BitcoinTestFramework): # The node should retry with the other peer that announced the orphan earlier. # This node's request was additionally delayed because it's an inbound peer. self.nodes[0].bumpmocktime(NONPREF_PEER_TX_DELAY) - peer_early_unresponsive.wait_for_parent_requests([int(parent_tx.rehash(), 16)]) + peer_early_unresponsive.wait_for_parent_requests([parent_tx.txid_int]) self.log.info("Test that the node uses peers who announce the tx after realizing it's an orphan") peer_late_announcer.send_and_ping(msg_inv([orphan_inv])) @@ -721,7 +721,7 @@ class OrphanHandlingTest(BitcoinTestFramework): assert_equal(len(orphanage[0]["from"]), 2) self.nodes[0].bumpmocktime(GETDATA_TX_INTERVAL) - peer_late_announcer.wait_for_parent_requests([int(parent_tx.rehash(), 16)]) + peer_late_announcer.wait_for_parent_requests([parent_tx.txid_int]) @cleanup def test_parents_change(self): diff --git a/test/functional/p2p_permissions.py b/test/functional/p2p_permissions.py index c37061c307c..543cd3194b4 100755 --- a/test/functional/p2p_permissions.py +++ b/test/functional/p2p_permissions.py @@ -111,14 +111,14 @@ class P2PPermissionsTests(BitcoinTestFramework): self.log.debug("Send a tx from the wallet initially") tx = self.wallet.create_self_transfer(sequence=SEQUENCE_FINAL)['tx'] - txid = tx.rehash() + txid = tx.txid_hex self.log.debug("Wait until tx is in node[1]'s mempool") p2p_rebroadcast_wallet.send_txs_and_test([tx], self.nodes[1]) self.log.debug("Check that node[1] will send the tx to node[0] even though it is already in the mempool") self.connect_nodes(1, 0) - with self.nodes[1].assert_debug_log(["Force relaying tx {} (wtxid={}) from peer=0".format(txid, tx.getwtxid())]): + with self.nodes[1].assert_debug_log(["Force relaying tx {} (wtxid={}) from peer=0".format(txid, tx.wtxid_hex)]): p2p_rebroadcast_wallet.send_txs_and_test([tx], self.nodes[1]) self.wait_until(lambda: txid in self.nodes[0].getrawmempool()) @@ -127,21 +127,21 @@ class P2PPermissionsTests(BitcoinTestFramework): # add dust to cause policy rejection but no disconnection tx.vout.append(tx.vout[0]) tx.vout[-1].nValue = 0 - txid = tx.rehash() + txid = tx.txid_hex # Send the transaction twice. The first time, it'll be rejected by ATMP because it conflicts # with a mempool transaction. The second time, it'll be in the m_lazy_recent_rejects filter. p2p_rebroadcast_wallet.send_txs_and_test( [tx], self.nodes[1], success=False, - reject_reason='{} (wtxid={}) from peer=0 was not accepted: dust'.format(txid, tx.getwtxid()) + reject_reason='{} (wtxid={}) from peer=0 was not accepted: dust'.format(txid, tx.wtxid_hex) ) p2p_rebroadcast_wallet.send_txs_and_test( [tx], self.nodes[1], success=False, - reject_reason='Not relaying non-mempool transaction {} (wtxid={}) from forcerelay peer=0'.format(txid, tx.getwtxid()) + reject_reason='Not relaying non-mempool transaction {} (wtxid={}) from forcerelay peer=0'.format(txid, tx.wtxid_hex) ) def checkpermission(self, args, expectedPermissions): diff --git a/test/functional/p2p_segwit.py b/test/functional/p2p_segwit.py index 37c2827ba61..0892d9d1a48 100755 --- a/test/functional/p2p_segwit.py +++ b/test/functional/p2p_segwit.py @@ -132,7 +132,7 @@ def test_transaction_acceptance(node, p2p, tx, with_witness, accepted, reason=No reason = [reason] if reason else [] with node.assert_debug_log(expected_msgs=reason): p2p.send_and_ping(msg_tx(tx) if with_witness else msg_no_witness_tx(tx)) - assert_equal(tx.hash in node.getrawmempool(), accepted) + assert_equal(tx.txid_hex in node.getrawmempool(), accepted) def test_witness_block(node, p2p, block, accepted, with_witness=True, reason=None): @@ -174,16 +174,16 @@ class TestP2PConn(P2PInterface): with p2p_lock: self.last_message.pop("getdata", None) if use_wtxid: - wtxid = tx.calc_sha256(True) + wtxid = tx.wtxid_int self.send_without_ping(msg_inv(inv=[CInv(MSG_WTX, wtxid)])) else: - self.send_without_ping(msg_inv(inv=[CInv(MSG_TX, tx.sha256)])) + self.send_without_ping(msg_inv(inv=[CInv(MSG_TX, tx.txid_int)])) if success: if use_wtxid: self.wait_for_getdata([wtxid]) else: - self.wait_for_getdata([tx.sha256]) + self.wait_for_getdata([tx.txid_int]) else: ensure_for(duration=5, f=lambda: not self.last_message.get("getdata")) @@ -305,7 +305,7 @@ class SegWitTest(BitcoinTestFramework): block = self.build_next_block() block.solve() self.test_node.send_and_ping(msg_no_witness_block(block)) # make sure the block was processed - txid = block.vtx[0].sha256 + txid = block.vtx[0].txid_int self.generate(self.wallet, 99) # let the block mature @@ -313,16 +313,15 @@ class SegWitTest(BitcoinTestFramework): tx = CTransaction() tx.vin.append(CTxIn(COutPoint(txid, 0), b"")) tx.vout.append(CTxOut(49 * 100000000, CScript([OP_TRUE, OP_DROP] * 15 + [OP_TRUE]))) - tx.calc_sha256() # Check that serializing it with or without witness is the same # This is a sanity check of our testing framework. assert_equal(msg_no_witness_tx(tx).serialize(), msg_tx(tx).serialize()) self.test_node.send_and_ping(msg_tx(tx)) # make sure the block was processed - assert tx.hash in self.nodes[0].getrawmempool() + assert tx.txid_hex in self.nodes[0].getrawmempool() # Save this transaction for later - self.utxo.append(UTXO(tx.sha256, 0, 49 * 100000000)) + self.utxo.append(UTXO(tx.txid_int, 0, 49 * 100000000)) self.generate(self.nodes[0], 1) @subtest @@ -337,7 +336,7 @@ class SegWitTest(BitcoinTestFramework): # Verify the hash with witness differs from the txid # (otherwise our testing framework must be broken!) - assert_not_equal(tx.rehash(), tx.getwtxid()) + assert_not_equal(tx.txid_hex, tx.wtxid_hex) # Construct a block that includes the transaction. block = self.build_next_block() @@ -353,7 +352,7 @@ class SegWitTest(BitcoinTestFramework): # Update our utxo list; we spent the first entry. self.utxo.pop(0) - self.utxo.append(UTXO(tx.sha256, 0, tx.vout[0].nValue)) + self.utxo.append(UTXO(tx.txid_int, 0, tx.vout[0].nValue)) @subtest def test_block_relay(self): @@ -471,8 +470,7 @@ class SegWitTest(BitcoinTestFramework): tx.vin = [CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b'')] tx.vout = [CTxOut(value, script_pubkey), CTxOut(value, p2sh_script_pubkey)] tx.vout.append(CTxOut(value, CScript([OP_TRUE]))) - tx.rehash() - txid = tx.sha256 + txid = tx.txid_int # Add it to a block block = self.build_next_block() @@ -489,14 +487,12 @@ class SegWitTest(BitcoinTestFramework): p2wsh_tx.vout = [CTxOut(value, CScript([OP_TRUE]))] p2wsh_tx.wit.vtxinwit.append(CTxInWitness()) p2wsh_tx.wit.vtxinwit[0].scriptWitness.stack = [CScript([OP_TRUE])] - p2wsh_tx.rehash() p2sh_p2wsh_tx = CTransaction() p2sh_p2wsh_tx.vin = [CTxIn(COutPoint(txid, 1), CScript([script_pubkey]))] p2sh_p2wsh_tx.vout = [CTxOut(value, CScript([OP_TRUE]))] p2sh_p2wsh_tx.wit.vtxinwit.append(CTxInWitness()) p2sh_p2wsh_tx.wit.vtxinwit[0].scriptWitness.stack = [CScript([OP_TRUE])] - p2sh_p2wsh_tx.rehash() for tx in [p2wsh_tx, p2sh_p2wsh_tx]: @@ -527,9 +523,8 @@ class SegWitTest(BitcoinTestFramework): tx.vout.append(CTxOut(self.utxo[0].nValue - 1000, CScript([OP_TRUE, OP_DROP] * 15 + [OP_TRUE]))) tx.wit.vtxinwit.append(CTxInWitness()) tx.wit.vtxinwit[0].scriptWitness.stack = [b'a'] - tx.rehash() - tx_hash = tx.sha256 + tx_hash = tx.txid_int tx_value = tx.vout[0].nValue # Verify that if a peer doesn't set nServices to include NODE_WITNESS, @@ -573,7 +568,6 @@ class SegWitTest(BitcoinTestFramework): p2sh_tx = CTransaction() p2sh_tx.vin = [CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")] p2sh_tx.vout = [CTxOut(self.utxo[0].nValue - 1000, p2sh_script_pubkey)] - p2sh_tx.rehash() # Mine it on test_node to create the confirmed output. test_transaction_acceptance(self.nodes[0], self.test_node, p2sh_tx, with_witness=True, accepted=True) @@ -582,11 +576,10 @@ class SegWitTest(BitcoinTestFramework): # Now test standardness of v0 P2WSH outputs. # Start by creating a transaction with two outputs. tx = CTransaction() - tx.vin = [CTxIn(COutPoint(p2sh_tx.sha256, 0), CScript([witness_script]))] + tx.vin = [CTxIn(COutPoint(p2sh_tx.txid_int, 0), CScript([witness_script]))] tx.vout = [CTxOut(p2sh_tx.vout[0].nValue - 10000, script_pubkey)] tx.vout.append(CTxOut(8000, script_pubkey)) # Might burn this later tx.vin[0].nSequence = MAX_BIP125_RBF_SEQUENCE # Just to have the option to bump this tx from the mempool - tx.rehash() # This is always accepted, since the mempool policy is to consider segwit as always active # and thus allow segwit outputs @@ -597,11 +590,10 @@ class SegWitTest(BitcoinTestFramework): script_pubkey = CScript([OP_0, hash160(witness_hash)]) tx2 = CTransaction() # tx was accepted, so we spend the second output. - tx2.vin = [CTxIn(COutPoint(tx.sha256, 1), b"")] + tx2.vin = [CTxIn(COutPoint(tx.txid_int, 1), b"")] tx2.vout = [CTxOut(7000, script_pubkey)] tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [witness_script] - tx2.rehash() test_transaction_acceptance(self.nodes[1], self.std_node, tx2, with_witness=True, accepted=True) @@ -610,11 +602,10 @@ class SegWitTest(BitcoinTestFramework): # tx and tx2 were both accepted. Don't bother trying to reclaim the # P2PKH output; just send tx's first output back to an anyone-can-spend. self.sync_mempools([self.nodes[0], self.nodes[1]]) - tx3.vin = [CTxIn(COutPoint(tx.sha256, 0), b"")] + tx3.vin = [CTxIn(COutPoint(tx.txid_int, 0), b"")] tx3.vout = [CTxOut(tx.vout[0].nValue - 1000, CScript([OP_TRUE, OP_DROP] * 15 + [OP_TRUE]))] tx3.wit.vtxinwit.append(CTxInWitness()) tx3.wit.vtxinwit[0].scriptWitness.stack = [witness_script] - tx3.rehash() if not self.segwit_active: # Just check mempool acceptance, but don't add the transaction to the mempool, since witness is disallowed # in blocks and the tx is impossible to mine right now. @@ -623,8 +614,8 @@ class SegWitTest(BitcoinTestFramework): testres3[0]["fees"].pop("effective-includes") assert_equal(testres3, [{ - 'txid': tx3.hash, - 'wtxid': tx3.getwtxid(), + 'txid': tx3.txid_hex, + 'wtxid': tx3.wtxid_hex, 'allowed': True, 'vsize': tx3.get_vsize(), 'fees': { @@ -636,14 +627,13 @@ class SegWitTest(BitcoinTestFramework): tx3_out = tx3.vout[0] tx3 = tx tx3.vout = [tx3_out] - tx3.rehash() testres3_replaced = self.nodes[0].testmempoolaccept([tx3.serialize_with_witness().hex()]) testres3_replaced[0]["fees"].pop("effective-feerate") testres3_replaced[0]["fees"].pop("effective-includes") assert_equal(testres3_replaced, [{ - 'txid': tx3.hash, - 'wtxid': tx3.getwtxid(), + 'txid': tx3.txid_hex, + 'wtxid': tx3.wtxid_hex, 'allowed': True, 'vsize': tx3.get_vsize(), 'fees': { @@ -655,7 +645,7 @@ class SegWitTest(BitcoinTestFramework): self.generate(self.nodes[0], 1) self.utxo.pop(0) - self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) + self.utxo.append(UTXO(tx3.txid_int, 0, tx3.vout[0].nValue)) assert_equal(len(self.nodes[1].getrawmempool()), 0) @subtest @@ -683,7 +673,6 @@ class SegWitTest(BitcoinTestFramework): tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue - 1000, script_pubkey)) - tx.rehash() # Verify mempool acceptance and block validity test_transaction_acceptance(self.nodes[0], self.test_node, tx, with_witness=False, accepted=True) @@ -694,9 +683,8 @@ class SegWitTest(BitcoinTestFramework): # Now test attempts to spend the output. spend_tx = CTransaction() - spend_tx.vin.append(CTxIn(COutPoint(tx.sha256, 0), script_sig)) + spend_tx.vin.append(CTxIn(COutPoint(tx.txid_int, 0), script_sig)) spend_tx.vout.append(CTxOut(tx.vout[0].nValue - 1000, CScript([OP_TRUE]))) - spend_tx.rehash() # This transaction should not be accepted into the mempool pre- or # post-segwit. Mempool acceptance will use SCRIPT_VERIFY_WITNESS which @@ -704,20 +692,18 @@ class SegWitTest(BitcoinTestFramework): # segwit activation. Note that older bitcoind's that are not # segwit-aware would also reject this for failing CLEANSTACK. with self.nodes[0].assert_debug_log( - expected_msgs=[spend_tx.hash, 'was not accepted: mandatory-script-verify-flag-failed (Witness program was passed an empty witness)']): + expected_msgs=[spend_tx.txid_hex, 'was not accepted: mandatory-script-verify-flag-failed (Witness program was passed an empty witness)']): test_transaction_acceptance(self.nodes[0], self.test_node, spend_tx, with_witness=False, accepted=False) # Try to put the witness script in the scriptSig, should also fail. spend_tx.vin[0].scriptSig = CScript([p2wsh_pubkey, b'a']) - spend_tx.rehash() with self.nodes[0].assert_debug_log( - expected_msgs=[spend_tx.hash, 'was not accepted: mandatory-script-verify-flag-failed (Script evaluated without error but finished with a false/empty top stack element)']): + expected_msgs=[spend_tx.txid_hex, 'was not accepted: mandatory-script-verify-flag-failed (Script evaluated without error but finished with a false/empty top stack element)']): test_transaction_acceptance(self.nodes[0], self.test_node, spend_tx, with_witness=False, accepted=False) # Now put the witness script in the witness, should succeed after # segwit activates. spend_tx.vin[0].scriptSig = script_sig - spend_tx.rehash() spend_tx.wit.vtxinwit.append(CTxInWitness()) spend_tx.wit.vtxinwit[0].scriptWitness.stack = [b'a', witness_script] @@ -734,7 +720,7 @@ class SegWitTest(BitcoinTestFramework): # Update self.utxo self.utxo.pop(0) - self.utxo.append(UTXO(spend_tx.sha256, 0, spend_tx.vout[0].nValue)) + self.utxo.append(UTXO(spend_tx.txid_int, 0, spend_tx.vout[0].nValue)) @subtest def test_witness_commitments(self): @@ -772,15 +758,13 @@ class SegWitTest(BitcoinTestFramework): witness_script = CScript([OP_TRUE]) script_pubkey = script_to_p2wsh_script(witness_script) tx.vout.append(CTxOut(self.utxo[0].nValue - 1000, script_pubkey)) - tx.rehash() # tx2 will spend tx1, and send back to a regular anyone-can-spend address tx2 = CTransaction() - tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) + tx2.vin.append(CTxIn(COutPoint(tx.txid_int, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue - 1000, witness_script)) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [witness_script] - tx2.rehash() block_3 = self.build_next_block() self.update_witness_block_with_transactions(block_3, [tx, tx2], nonce=1) @@ -788,7 +772,6 @@ class SegWitTest(BitcoinTestFramework): # even though it has extra data after the incorrect commitment. # This block should fail. block_3.vtx[0].vout.append(CTxOut(0, CScript([OP_RETURN, WITNESS_COMMITMENT_HEADER + ser_uint256(2), 10]))) - block_3.vtx[0].rehash() block_3.hashMerkleRoot = block_3.calc_merkle_root() block_3.solve() @@ -801,7 +784,6 @@ class SegWitTest(BitcoinTestFramework): add_witness_commitment(block_3, nonce=0) block_3.vtx[0].vout[0].nValue -= 1 block_3.vtx[0].vout[-1].nValue += 1 - block_3.vtx[0].rehash() block_3.hashMerkleRoot = block_3.calc_merkle_root() assert len(block_3.vtx[0].vout) == 4 # 3 OP_returns block_3.solve() @@ -811,9 +793,8 @@ class SegWitTest(BitcoinTestFramework): # omit the commitment. block_4 = self.build_next_block() tx3 = CTransaction() - tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), b"")) + tx3.vin.append(CTxIn(COutPoint(tx2.txid_int, 0), b"")) tx3.vout.append(CTxOut(tx.vout[0].nValue - 1000, witness_script)) - tx3.rehash() block_4.vtx.append(tx3) block_4.hashMerkleRoot = block_4.calc_merkle_root() block_4.solve() @@ -821,7 +802,7 @@ class SegWitTest(BitcoinTestFramework): # Update available utxo's for use in later test. self.utxo.pop(0) - self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) + self.utxo.append(UTXO(tx3.txid_int, 0, tx3.vout[0].nValue)) @subtest def test_block_malleability(self): @@ -893,16 +874,14 @@ class SegWitTest(BitcoinTestFramework): parent_tx.vout.append(CTxOut(child_value, script_pubkey)) parent_tx.vout[0].nValue -= 50000 assert parent_tx.vout[0].nValue > 0 - parent_tx.rehash() child_tx = CTransaction() for i in range(NUM_OUTPUTS): - child_tx.vin.append(CTxIn(COutPoint(parent_tx.sha256, i), b"")) + child_tx.vin.append(CTxIn(COutPoint(parent_tx.txid_int, i), b"")) child_tx.vout = [CTxOut(value - 100000, CScript([OP_TRUE]))] for _ in range(NUM_OUTPUTS): child_tx.wit.vtxinwit.append(CTxInWitness()) child_tx.wit.vtxinwit[-1].scriptWitness.stack = [b'a' * 195] * (2 * NUM_DROPS) + [witness_script] - child_tx.rehash() self.update_witness_block_with_transactions(block, [parent_tx, child_tx]) additional_bytes = MAX_BLOCK_WEIGHT - block.get_weight() @@ -936,7 +915,7 @@ class SegWitTest(BitcoinTestFramework): # Update available utxo's self.utxo.pop(0) - self.utxo.append(UTXO(block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue)) + self.utxo.append(UTXO(block.vtx[-1].txid_int, 0, block.vtx[-1].vout[0].nValue)) @subtest def test_submit_block(self): @@ -990,7 +969,6 @@ class SegWitTest(BitcoinTestFramework): tx.vout.append(CTxOut(1000, CScript([OP_TRUE]))) # non-witness output tx.wit.vtxinwit.append(CTxInWitness()) tx.wit.vtxinwit[0].scriptWitness.stack = [CScript([])] - tx.rehash() self.update_witness_block_with_transactions(block, [tx]) # Extra witness data should not be allowed. @@ -1000,7 +978,6 @@ class SegWitTest(BitcoinTestFramework): # Try extra signature data. Ok if we're not spending a witness output. block.vtx[1].wit.vtxinwit = [] block.vtx[1].vin[0].scriptSig = CScript([OP_0]) - block.vtx[1].rehash() add_witness_commitment(block) block.solve() @@ -1009,8 +986,8 @@ class SegWitTest(BitcoinTestFramework): # Now try extra witness/signature data on an input that DOES require a # witness tx2 = CTransaction() - tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) # witness output - tx2.vin.append(CTxIn(COutPoint(tx.sha256, 1), b"")) # non-witness + tx2.vin.append(CTxIn(COutPoint(tx.txid_int, 0), b"")) # witness output + tx2.vin.append(CTxIn(COutPoint(tx.txid_int, 1), b"")) # non-witness tx2.vout.append(CTxOut(tx.vout[0].nValue, CScript([OP_TRUE]))) tx2.wit.vtxinwit.extend([CTxInWitness(), CTxInWitness()]) tx2.wit.vtxinwit[0].scriptWitness.stack = [CScript([CScriptNum(1)]), CScript([CScriptNum(1)]), witness_script] @@ -1028,7 +1005,6 @@ class SegWitTest(BitcoinTestFramework): tx2.vin[1].scriptSig = CScript([OP_TRUE]) tx2.wit.vtxinwit[0].scriptWitness.stack.pop(0) tx2.wit.vtxinwit[1].scriptWitness.stack = [] - tx2.rehash() add_witness_commitment(block) block.solve() @@ -1039,7 +1015,6 @@ class SegWitTest(BitcoinTestFramework): # Now get rid of the extra scriptsig on the witness input, and verify # success (even with extra scriptsig data in the non-witness input) tx2.vin[0].scriptSig = b"" - tx2.rehash() add_witness_commitment(block) block.solve() @@ -1047,7 +1022,7 @@ class SegWitTest(BitcoinTestFramework): # Update utxo for later tests self.utxo.pop(0) - self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) + self.utxo.append(UTXO(tx2.txid_int, 0, tx2.vout[0].nValue)) @subtest def test_max_witness_push_length(self): @@ -1061,15 +1036,13 @@ class SegWitTest(BitcoinTestFramework): tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue - 1000, script_pubkey)) - tx.rehash() tx2 = CTransaction() - tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) + tx2.vin.append(CTxIn(COutPoint(tx.txid_int, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue - 1000, CScript([OP_TRUE]))) tx2.wit.vtxinwit.append(CTxInWitness()) # First try a 521-byte stack element tx2.wit.vtxinwit[0].scriptWitness.stack = [b'a' * (MAX_SCRIPT_ELEMENT_SIZE + 1), witness_script] - tx2.rehash() self.update_witness_block_with_transactions(block, [tx, tx2]) test_witness_block(self.nodes[0], self.test_node, block, accepted=False, @@ -1084,7 +1057,7 @@ class SegWitTest(BitcoinTestFramework): # Update the utxo for later tests self.utxo.pop() - self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) + self.utxo.append(UTXO(tx2.txid_int, 0, tx2.vout[0].nValue)) @subtest def test_max_witness_script_length(self): @@ -1102,14 +1075,12 @@ class SegWitTest(BitcoinTestFramework): tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue - 1000, long_script_pubkey)) - tx.rehash() tx2 = CTransaction() - tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) + tx2.vin.append(CTxIn(COutPoint(tx.txid_int, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue - 1000, CScript([OP_TRUE]))) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [b'a'] * 44 + [long_witness_script] - tx2.rehash() self.update_witness_block_with_transactions(block, [tx, tx2]) @@ -1122,16 +1093,14 @@ class SegWitTest(BitcoinTestFramework): script_pubkey = script_to_p2wsh_script(witness_script) tx.vout[0] = CTxOut(tx.vout[0].nValue, script_pubkey) - tx.rehash() - tx2.vin[0].prevout.hash = tx.sha256 + tx2.vin[0].prevout.hash = tx.txid_int tx2.wit.vtxinwit[0].scriptWitness.stack = [b'a'] * 43 + [witness_script] - tx2.rehash() block.vtx = [block.vtx[0]] self.update_witness_block_with_transactions(block, [tx, tx2]) test_witness_block(self.nodes[0], self.test_node, block, accepted=True) self.utxo.pop() - self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) + self.utxo.append(UTXO(tx2.txid_int, 0, tx2.vout[0].nValue)) @subtest def test_witness_input_length(self): @@ -1176,7 +1145,7 @@ class SegWitTest(BitcoinTestFramework): tx2 = BrokenCTransaction() for i in range(10): - tx2.vin.append(CTxIn(COutPoint(tx.sha256, i), b"")) + tx2.vin.append(CTxIn(COutPoint(tx.txid_int, i), b"")) tx2.vout.append(CTxOut(value - 3000, CScript([OP_TRUE]))) # First try using a too long vtxinwit @@ -1215,7 +1184,7 @@ class SegWitTest(BitcoinTestFramework): test_witness_block(self.nodes[0], self.test_node, block, accepted=True) self.utxo.pop() - self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) + self.utxo.append(UTXO(tx2.txid_int, 0, tx2.vout[0].nValue)) @subtest def test_tx_relay_after_segwit_activation(self): @@ -1234,9 +1203,8 @@ class SegWitTest(BitcoinTestFramework): tx.vout.append(CTxOut(self.utxo[0].nValue - 1000, CScript([OP_TRUE, OP_DROP] * 15 + [OP_TRUE]))) tx.wit.vtxinwit.append(CTxInWitness()) tx.wit.vtxinwit[0].scriptWitness.stack = [b'a'] - tx.rehash() - tx_hash = tx.sha256 + tx_hash = tx.txid_int # Verify that unnecessary witnesses are rejected. self.test_node.announce_tx_and_wait_for_getdata(tx) @@ -1252,10 +1220,9 @@ class SegWitTest(BitcoinTestFramework): tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx_hash, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue - 1000, script_pubkey)) - tx2.rehash() tx3 = CTransaction() - tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), b"")) + tx3.vin.append(CTxIn(COutPoint(tx2.txid_int, 0), b"")) tx3.wit.vtxinwit.append(CTxInWitness()) # Add too-large for IsStandard witness and check that it does not enter reject filter @@ -1263,7 +1230,6 @@ class SegWitTest(BitcoinTestFramework): witness_script2 = CScript([b'a' * 400000]) tx3.vout.append(CTxOut(tx2.vout[0].nValue - 1000, script_to_p2sh_script(p2sh_script))) tx3.wit.vtxinwit[0].scriptWitness.stack = [witness_script2] - tx3.rehash() # Node will not be blinded to the transaction, requesting it any number of times # if it is being announced via txid relay. @@ -1277,7 +1243,6 @@ class SegWitTest(BitcoinTestFramework): # Remove witness stuffing, instead add extra witness push on stack tx3.vout[0] = CTxOut(tx2.vout[0].nValue - 1000, CScript([OP_TRUE, OP_DROP] * 15 + [OP_TRUE])) tx3.wit.vtxinwit[0].scriptWitness.stack = [CScript([CScriptNum(1)]), witness_script] - tx3.rehash() test_transaction_acceptance(self.nodes[0], self.test_node, tx2, with_witness=True, accepted=True) test_transaction_acceptance(self.nodes[0], self.test_node, tx3, with_witness=True, accepted=False) @@ -1286,14 +1251,14 @@ class SegWitTest(BitcoinTestFramework): tx3.wit.vtxinwit[0].scriptWitness.stack = [witness_script] # Also check that old_node gets a tx announcement, even though this is # a witness transaction. - self.old_node.wait_for_inv([CInv(MSG_TX, tx2.sha256)]) # wait until tx2 was inv'ed + self.old_node.wait_for_inv([CInv(MSG_TX, tx2.txid_int)]) # wait until tx2 was inv'ed test_transaction_acceptance(self.nodes[0], self.test_node, tx3, with_witness=True, accepted=True) - self.old_node.wait_for_inv([CInv(MSG_TX, tx3.sha256)]) + self.old_node.wait_for_inv([CInv(MSG_TX, tx3.txid_int)]) # Test that getrawtransaction returns correct witness information # hash, size, vsize - raw_tx = self.nodes[0].getrawtransaction(tx3.hash, 1) - assert_equal(raw_tx["hash"], tx3.getwtxid()) + raw_tx = self.nodes[0].getrawtransaction(tx3.txid_hex, 1) + assert_equal(raw_tx["hash"], tx3.wtxid_hex) assert_equal(raw_tx["size"], len(tx3.serialize_with_witness())) vsize = tx3.get_vsize() assert_equal(raw_tx["vsize"], vsize) @@ -1307,7 +1272,7 @@ class SegWitTest(BitcoinTestFramework): assert_equal(len(self.nodes[0].getrawmempool()), 0) self.utxo.pop(0) - self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) + self.utxo.append(UTXO(tx3.txid_int, 0, tx3.vout[0].nValue)) @subtest def test_segwit_versions(self): @@ -1324,13 +1289,12 @@ class SegWitTest(BitcoinTestFramework): split_value = (self.utxo[0].nValue - 4000) // NUM_SEGWIT_VERSIONS for _ in range(NUM_SEGWIT_VERSIONS): tx.vout.append(CTxOut(split_value, CScript([OP_TRUE]))) - tx.rehash() block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) test_witness_block(self.nodes[0], self.test_node, block, accepted=True) self.utxo.pop(0) for i in range(NUM_SEGWIT_VERSIONS): - self.utxo.append(UTXO(tx.sha256, i, split_value)) + self.utxo.append(UTXO(tx.txid_int, i, split_value)) self.sync_blocks() temp_utxo = [] @@ -1347,11 +1311,10 @@ class SegWitTest(BitcoinTestFramework): script_pubkey = CScript([CScriptOp(version), witness_hash]) tx.vin = [CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")] tx.vout = [CTxOut(self.utxo[0].nValue - 1000, script_pubkey)] - tx.rehash() test_transaction_acceptance(self.nodes[1], self.std_node, tx, with_witness=True, accepted=False) test_transaction_acceptance(self.nodes[0], self.test_node, tx, with_witness=True, accepted=True) self.utxo.pop(0) - temp_utxo.append(UTXO(tx.sha256, 0, tx.vout[0].nValue)) + temp_utxo.append(UTXO(tx.txid_int, 0, tx.vout[0].nValue)) self.generate(self.nodes[0], 1) # Mine all the transactions assert len(self.nodes[0].getrawmempool()) == 0 @@ -1360,16 +1323,15 @@ class SegWitTest(BitcoinTestFramework): # are standard script_pubkey = CScript([CScriptOp(OP_2), witness_hash]) tx2 = CTransaction() - tx2.vin = [CTxIn(COutPoint(tx.sha256, 0), b"")] + tx2.vin = [CTxIn(COutPoint(tx.txid_int, 0), b"")] tx2.vout = [CTxOut(tx.vout[0].nValue - 1000, script_pubkey)] tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [witness_script] - tx2.rehash() # Gets accepted to both policy-enforcing nodes and others. test_transaction_acceptance(self.nodes[0], self.test_node, tx2, with_witness=True, accepted=True) test_transaction_acceptance(self.nodes[1], self.std_node, tx2, with_witness=True, accepted=True) temp_utxo.pop() # last entry in temp_utxo was the output we just spent - temp_utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) + temp_utxo.append(UTXO(tx2.txid_int, 0, tx2.vout[0].nValue)) # Spend everything in temp_utxo into an segwit v1 output. tx3 = CTransaction() @@ -1380,7 +1342,6 @@ class SegWitTest(BitcoinTestFramework): total_value += i.nValue tx3.wit.vtxinwit[-1].scriptWitness.stack = [witness_script] tx3.vout.append(CTxOut(total_value - 1000, script_pubkey)) - tx3.rehash() # First we test this transaction against std_node # making sure the txid is added to the reject filter @@ -1400,7 +1361,7 @@ class SegWitTest(BitcoinTestFramework): self.sync_blocks() # Add utxo to our list - self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) + self.utxo.append(UTXO(tx3.txid_int, 0, tx3.vout[0].nValue)) @subtest def test_premature_coinbase_witness_spend(self): @@ -1416,11 +1377,10 @@ class SegWitTest(BitcoinTestFramework): test_witness_block(self.nodes[0], self.test_node, block, accepted=True) spend_tx = CTransaction() - spend_tx.vin = [CTxIn(COutPoint(block.vtx[0].sha256, 0), b"")] + spend_tx.vin = [CTxIn(COutPoint(block.vtx[0].txid_int, 0), b"")] spend_tx.vout = [CTxOut(block.vtx[0].vout[0].nValue, witness_script)] spend_tx.wit.vtxinwit.append(CTxInWitness()) spend_tx.wit.vtxinwit[0].scriptWitness.stack = [witness_script] - spend_tx.rehash() # Now test a premature spend. self.generate(self.nodes[0], 98) @@ -1456,7 +1416,6 @@ class SegWitTest(BitcoinTestFramework): tx = CTransaction() tx.vin.append(CTxIn(COutPoint(utxo.sha256, utxo.n), b"")) tx.vout.append(CTxOut(utxo.nValue - 1000, script_pkh)) - tx.rehash() # Confirm it in a block. block = self.build_next_block() @@ -1469,7 +1428,7 @@ class SegWitTest(BitcoinTestFramework): script_wsh = script_to_p2wsh_script(witness_script) tx2 = CTransaction() - tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) + tx2.vin.append(CTxIn(COutPoint(tx.txid_int, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue - 1000, script_wsh)) script = keyhash_to_p2pkh_script(pubkeyhash) tx2.wit.vtxinwit.append(CTxInWitness()) @@ -1490,7 +1449,7 @@ class SegWitTest(BitcoinTestFramework): script_sig = CScript([script_wsh]) tx3 = CTransaction() - tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), b"")) + tx3.vin.append(CTxIn(COutPoint(tx2.txid_int, 0), b"")) tx3.vout.append(CTxOut(tx2.vout[0].nValue - 1000, script_p2sh)) tx3.wit.vtxinwit.append(CTxInWitness()) sign_p2pk_witness_input(witness_script, tx3, 0, SIGHASH_ALL, tx2.vout[0].nValue, key) @@ -1507,7 +1466,7 @@ class SegWitTest(BitcoinTestFramework): # Send it to a P2PKH output, which we'll use in the next test. script_pubkey = keyhash_to_p2pkh_script(pubkeyhash) tx4 = CTransaction() - tx4.vin.append(CTxIn(COutPoint(tx3.sha256, 0), script_sig)) + tx4.vin.append(CTxIn(COutPoint(tx3.txid_int, 0), script_sig)) tx4.vout.append(CTxOut(tx3.vout[0].nValue - 1000, script_pubkey)) tx4.wit.vtxinwit.append(CTxInWitness()) sign_p2pk_witness_input(witness_script, tx4, 0, SIGHASH_ALL, tx3.vout[0].nValue, key) @@ -1521,7 +1480,7 @@ class SegWitTest(BitcoinTestFramework): # Test 4: Uncompressed pubkeys should still be valid in non-segwit # transactions. tx5 = CTransaction() - tx5.vin.append(CTxIn(COutPoint(tx4.sha256, 0), b"")) + tx5.vin.append(CTxIn(COutPoint(tx4.txid_int, 0), b"")) tx5.vout.append(CTxOut(tx4.vout[0].nValue - 1000, CScript([OP_TRUE]))) tx5.vin[0].scriptSig = CScript([pubkey]) sign_input_legacy(tx5, 0, script_pubkey, key) @@ -1530,7 +1489,7 @@ class SegWitTest(BitcoinTestFramework): block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx5]) test_witness_block(self.nodes[0], self.test_node, block, accepted=True) - self.utxo.append(UTXO(tx5.sha256, 0, tx5.vout[0].nValue)) + self.utxo.append(UTXO(tx5.txid_int, 0, tx5.vout[0].nValue)) @subtest def test_signature_version_1(self): @@ -1542,7 +1501,6 @@ class SegWitTest(BitcoinTestFramework): tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue - 1000, script_pubkey)) - tx.rehash() test_transaction_acceptance(self.nodes[0], self.test_node, tx, with_witness=True, accepted=True) # Mine this transaction in preparation for following tests. @@ -1553,7 +1511,7 @@ class SegWitTest(BitcoinTestFramework): self.utxo.pop(0) # Test each hashtype - prev_utxo = UTXO(tx.sha256, 0, tx.vout[0].nValue) + prev_utxo = UTXO(tx.txid_int, 0, tx.vout[0].nValue) for sigflag in [0, SIGHASH_ANYONECANPAY]: for hashtype in [SIGHASH_ALL, SIGHASH_NONE, SIGHASH_SINGLE]: hashtype |= sigflag @@ -1583,7 +1541,7 @@ class SegWitTest(BitcoinTestFramework): self.update_witness_block_with_transactions(block, [tx]) test_witness_block(self.nodes[0], self.test_node, block, accepted=True) - prev_utxo = UTXO(tx.sha256, 0, tx.vout[0].nValue) + prev_utxo = UTXO(tx.txid_int, 0, tx.vout[0].nValue) # Test combinations of signature hashes. # Split the utxo into a lot of outputs. @@ -1601,7 +1559,7 @@ class SegWitTest(BitcoinTestFramework): tx.wit.vtxinwit.append(CTxInWitness()) sign_p2pk_witness_input(witness_script, tx, 0, SIGHASH_ALL, prev_utxo.nValue, key) for i in range(NUM_SIGHASH_TESTS): - temp_utxos.append(UTXO(tx.sha256, i, split_value)) + temp_utxos.append(UTXO(tx.txid_int, i, split_value)) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) @@ -1637,9 +1595,8 @@ class SegWitTest(BitcoinTestFramework): sign_p2pk_witness_input(witness_script, tx, i, hashtype, temp_utxos[i].nValue, key) if (hashtype == SIGHASH_SINGLE and i >= num_outputs): used_sighash_single_out_of_bounds = True - tx.rehash() for i in range(num_outputs): - temp_utxos.append(UTXO(tx.sha256, i, split_value)) + temp_utxos.append(UTXO(tx.txid_int, i, split_value)) temp_utxos = temp_utxos[num_inputs:] block.vtx.append(tx) @@ -1666,7 +1623,7 @@ class SegWitTest(BitcoinTestFramework): tx.wit.vtxinwit.append(CTxInWitness()) sign_p2pk_witness_input(witness_script, tx, 0, SIGHASH_ALL, temp_utxos[0].nValue, key) tx2 = CTransaction() - tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) + tx2.vin.append(CTxIn(COutPoint(tx.txid_int, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue, CScript([OP_TRUE]))) script = keyhash_to_p2pkh_script(pubkeyhash) @@ -1676,7 +1633,6 @@ class SegWitTest(BitcoinTestFramework): # Check that we can't have a scriptSig tx2.vin[0].scriptSig = CScript([signature, pubkey]) - tx2.rehash() block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx, tx2]) test_witness_block(self.nodes[0], self.test_node, block, accepted=False, @@ -1687,7 +1643,6 @@ class SegWitTest(BitcoinTestFramework): tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [signature, pubkey] tx2.vin[0].scriptSig = b"" - tx2.rehash() self.update_witness_block_with_transactions(block, [tx2]) test_witness_block(self.nodes[0], self.test_node, block, accepted=True) @@ -1714,7 +1669,7 @@ class SegWitTest(BitcoinTestFramework): test_witness_block(self.nodes[0], self.test_node, block, accepted=True) for i in range(len(tx.vout)): - self.utxo.append(UTXO(tx.sha256, i, tx.vout[i].nValue)) + self.utxo.append(UTXO(tx.txid_int, i, tx.vout[i].nValue)) @subtest def test_non_standard_witness_blinding(self): @@ -1731,7 +1686,6 @@ class SegWitTest(BitcoinTestFramework): tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue - 1000, script_pubkey)) - tx.rehash() test_transaction_acceptance(self.nodes[0], self.test_node, tx, False, True) self.generate(self.nodes[0], 1) @@ -1741,11 +1695,10 @@ class SegWitTest(BitcoinTestFramework): # rejected for having a witness shouldn't be added # to the rejection cache. tx2 = CTransaction() - tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), CScript([p2sh_program]))) + tx2.vin.append(CTxIn(COutPoint(tx.txid_int, 0), CScript([p2sh_program]))) tx2.vout.append(CTxOut(tx.vout[0].nValue - 1000, script_pubkey)) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [b'a' * 400] - tx2.rehash() # This will be rejected due to a policy check: # No witness is allowed, since it is not a witness program but a p2sh program test_transaction_acceptance(self.nodes[1], self.std_node, tx2, True, False, 'bad-witness-nonstandard') @@ -1755,9 +1708,8 @@ class SegWitTest(BitcoinTestFramework): # Now create a new anyone-can-spend utxo for the next test. tx3 = CTransaction() - tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), CScript([p2sh_program]))) + tx3.vin.append(CTxIn(COutPoint(tx2.txid_int, 0), CScript([p2sh_program]))) tx3.vout.append(CTxOut(tx2.vout[0].nValue - 1000, CScript([OP_TRUE, OP_DROP] * 15 + [OP_TRUE]))) - tx3.rehash() test_transaction_acceptance(self.nodes[0], self.test_node, tx2, False, True) test_transaction_acceptance(self.nodes[0], self.test_node, tx3, False, True) @@ -1765,7 +1717,7 @@ class SegWitTest(BitcoinTestFramework): # Update our utxo list; we spent the first entry. self.utxo.pop(0) - self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) + self.utxo.append(UTXO(tx3.txid_int, 0, tx3.vout[0].nValue)) @subtest def test_non_standard_witness(self): @@ -1791,8 +1743,7 @@ class SegWitTest(BitcoinTestFramework): p2wsh_scripts.append(p2wsh) tx.vout.append(CTxOut(outputvalue, p2wsh)) tx.vout.append(CTxOut(outputvalue, script_to_p2sh_script(p2wsh))) - tx.rehash() - txid = tx.sha256 + txid = tx.txid_int test_transaction_acceptance(self.nodes[0], self.test_node, tx, with_witness=False, accepted=True) self.generate(self.nodes[0], 1) @@ -1805,13 +1756,11 @@ class SegWitTest(BitcoinTestFramework): p2wsh_tx.vin.append(CTxIn(COutPoint(txid, i * 2))) p2wsh_tx.vout.append(CTxOut(outputvalue - 5000, CScript([OP_0, hash160(b"")]))) p2wsh_tx.wit.vtxinwit.append(CTxInWitness()) - p2wsh_tx.rehash() p2wsh_txs.append(p2wsh_tx) p2sh_tx = CTransaction() p2sh_tx.vin.append(CTxIn(COutPoint(txid, i * 2 + 1), CScript([p2wsh_scripts[i]]))) p2sh_tx.vout.append(CTxOut(outputvalue - 5000, CScript([OP_0, hash160(b"")]))) p2sh_tx.wit.vtxinwit.append(CTxInWitness()) - p2sh_tx.rehash() p2sh_txs.append(p2sh_tx) # Testing native P2WSH @@ -1902,7 +1851,6 @@ class SegWitTest(BitcoinTestFramework): tx.vout.append(CTxOut(split_value, script_pubkey)) tx.vout[-2].scriptPubKey = script_pubkey_toomany tx.vout[-1].scriptPubKey = script_pubkey_justright - tx.rehash() block_1 = self.build_next_block() self.update_witness_block_with_transactions(block_1, [tx]) @@ -1913,13 +1861,12 @@ class SegWitTest(BitcoinTestFramework): # too many sigops. total_value = 0 for i in range(outputs - 1): - tx2.vin.append(CTxIn(COutPoint(tx.sha256, i), b"")) + tx2.vin.append(CTxIn(COutPoint(tx.txid_int, i), b"")) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[-1].scriptWitness.stack = [witness_script] total_value += tx.vout[i].nValue tx2.wit.vtxinwit[-1].scriptWitness.stack = [witness_script_toomany] tx2.vout.append(CTxOut(total_value, CScript([OP_TRUE]))) - tx2.rehash() block_2 = self.build_next_block() self.update_witness_block_with_transactions(block_2, [tx2]) @@ -1933,7 +1880,6 @@ class SegWitTest(BitcoinTestFramework): tx2.vin.pop() tx2.wit.vtxinwit.pop() tx2.vout[0].nValue -= tx.vout[-2].nValue - tx2.rehash() block_3 = self.build_next_block() self.update_witness_block_with_transactions(block_3, [tx2]) test_witness_block(self.nodes[0], self.test_node, block_3, accepted=False, reason='bad-blk-sigops') @@ -1941,7 +1887,6 @@ class SegWitTest(BitcoinTestFramework): # If we drop the last checksig in this output, the tx should succeed. block_4 = self.build_next_block() tx2.vout[-1].scriptPubKey = CScript([OP_CHECKSIG] * (checksig_count - 1)) - tx2.rehash() self.update_witness_block_with_transactions(block_4, [tx2]) test_witness_block(self.nodes[0], self.test_node, block_4, accepted=True) @@ -1954,10 +1899,9 @@ class SegWitTest(BitcoinTestFramework): # output of tx block_5 = self.build_next_block() tx2.vout.pop() - tx2.vin.append(CTxIn(COutPoint(tx.sha256, outputs - 1), b"")) + tx2.vin.append(CTxIn(COutPoint(tx.txid_int, outputs - 1), b"")) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[-1].scriptWitness.stack = [witness_script_justright] - tx2.rehash() self.update_witness_block_with_transactions(block_5, [tx2]) test_witness_block(self.nodes[0], self.test_node, block_5, accepted=True) @@ -1965,7 +1909,7 @@ class SegWitTest(BitcoinTestFramework): # Cleanup and prep for next test self.utxo.pop(0) - self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) + self.utxo.append(UTXO(tx2.txid_int, 0, tx2.vout[0].nValue)) @subtest def test_superfluous_witness(self): @@ -2022,29 +1966,27 @@ class SegWitTest(BitcoinTestFramework): tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue - 1000, script_pubkey)) - tx.rehash() # Create a Segwit transaction tx2 = CTransaction() - tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) + tx2.vin.append(CTxIn(COutPoint(tx.txid_int, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue - 1000, script_pubkey)) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [witness_script] - tx2.rehash() # Announce Segwit transaction with wtxid # and wait for getdata self.wtx_node.announce_tx_and_wait_for_getdata(tx2, use_wtxid=True) with p2p_lock: lgd = self.wtx_node.lastgetdata[:] - assert_equal(lgd, [CInv(MSG_WTX, tx2.calc_sha256(True))]) + assert_equal(lgd, [CInv(MSG_WTX, tx2.wtxid_int)]) # Announce Segwit transaction from non wtxidrelay peer # and wait for getdata self.tx_node.announce_tx_and_wait_for_getdata(tx2, use_wtxid=False) with p2p_lock: lgd = self.tx_node.lastgetdata[:] - assert_equal(lgd, [CInv(MSG_TX|MSG_WITNESS_FLAG, tx2.sha256)]) + assert_equal(lgd, [CInv(MSG_TX|MSG_WITNESS_FLAG, tx2.txid_int)]) # Send tx2 through; it's an orphan so won't be accepted with p2p_lock: @@ -2055,16 +1997,16 @@ class SegWitTest(BitcoinTestFramework): self.tx_node.peer_disconnect() # Expect a request for parent (tx) by txid despite use of WTX peer - self.wtx_node.wait_for_getdata([tx.sha256], timeout=60) + self.wtx_node.wait_for_getdata([tx.txid_int], timeout=60) with p2p_lock: lgd = self.wtx_node.lastgetdata[:] - assert_equal(lgd, [CInv(MSG_WITNESS_TX, tx.sha256)]) + assert_equal(lgd, [CInv(MSG_WITNESS_TX, tx.txid_int)]) # Send tx through test_transaction_acceptance(self.nodes[0], self.wtx_node, tx, with_witness=False, accepted=True) # Check tx2 is there now - assert_equal(tx2.hash in self.nodes[0].getrawmempool(), True) + assert_equal(tx2.txid_hex in self.nodes[0].getrawmempool(), True) if __name__ == '__main__': diff --git a/test/functional/p2p_tx_privacy.py b/test/functional/p2p_tx_privacy.py index 688f27f5820..7b56c58065d 100755 --- a/test/functional/p2p_tx_privacy.py +++ b/test/functional/p2p_tx_privacy.py @@ -71,7 +71,7 @@ class TxPrivacyTest(BitcoinTestFramework): # Spy should only get an inv for the second transaction as the first # one was received pre-verack with the spy - spy.wait_for_inv_match(CInv(MSG_WTX, tx2.calc_sha256(True))) + spy.wait_for_inv_match(CInv(MSG_WTX, tx2.wtxid_int)) if __name__ == '__main__': TxPrivacyTest(__file__).main() diff --git a/test/functional/rpc_packages.py b/test/functional/rpc_packages.py index 119268213f4..3947053c41e 100755 --- a/test/functional/rpc_packages.py +++ b/test/functional/rpc_packages.py @@ -106,7 +106,7 @@ class RPCPackagesTest(BitcoinTestFramework): # Package validation is atomic: if the node cannot find a UTXO for any single tx in the package, # it terminates immediately to avoid unnecessary, expensive signature verification. package_bad = self.independent_txns_hex + [garbage_tx] - testres_bad = self.independent_txns_testres_blank + [{"txid": tx.rehash(), "wtxid": tx.getwtxid(), "allowed": False, "reject-reason": "missing-inputs"}] + testres_bad = self.independent_txns_testres_blank + [{"txid": tx.txid_hex, "wtxid": tx.wtxid_hex, "allowed": False, "reject-reason": "missing-inputs"}] self.assert_testres_equal(package_bad, testres_bad) self.log.info("Check testmempoolaccept tells us when some transactions completed validation successfully") @@ -117,8 +117,8 @@ class RPCPackagesTest(BitcoinTestFramework): # By the time the signature for the last transaction is checked, all the other transactions # have been fully validated, which is why the node returns full validation results for all # transactions here but empty results in other cases. - tx_bad_sig_txid = tx_bad_sig.rehash() - tx_bad_sig_wtxid = tx_bad_sig.getwtxid() + tx_bad_sig_txid = tx_bad_sig.txid_hex + tx_bad_sig_wtxid = tx_bad_sig.wtxid_hex assert_equal(testres_bad_sig, self.independent_txns_testres + [{ "txid": tx_bad_sig_txid, "wtxid": tx_bad_sig_wtxid, "allowed": False, @@ -146,7 +146,7 @@ class RPCPackagesTest(BitcoinTestFramework): self.log.info("Check that testmempoolaccept requires packages to be sorted by dependency") assert_equal(node.testmempoolaccept(rawtxs=chain_hex[::-1]), - [{"txid": tx.rehash(), "wtxid": tx.getwtxid(), "package-error": "package-not-sorted"} for tx in chain_txns[::-1]]) + [{"txid": tx.txid_hex, "wtxid": tx.wtxid_hex, "package-error": "package-not-sorted"} for tx in chain_txns[::-1]]) self.log.info("Testmempoolaccept a chain of 25 transactions") testres_multiple = node.testmempoolaccept(rawtxs=chain_hex) @@ -353,11 +353,11 @@ class RPCPackagesTest(BitcoinTestFramework): assert_equal(submitpackage_result["package_msg"], "success") for package_txn in package_txns: tx = package_txn["tx"] - assert tx.getwtxid() in submitpackage_result["tx-results"] - wtxid = tx.getwtxid() + assert tx.wtxid_hex in submitpackage_result["tx-results"] + wtxid = tx.wtxid_hex assert wtxid in submitpackage_result["tx-results"] tx_result = submitpackage_result["tx-results"][wtxid] - assert_equal(tx_result["txid"], tx.rehash()) + assert_equal(tx_result["txid"], tx.txid_hex) assert_equal(tx_result["vsize"], tx.get_vsize()) assert_equal(tx_result["fees"]["base"], DEFAULT_FEE) if wtxid not in presubmitted_wtxids: @@ -368,7 +368,7 @@ class RPCPackagesTest(BitcoinTestFramework): self.assert_equal_package_results(node, testmempoolaccept_result, submitpackage_result) # The node should announce each transaction. No guarantees for propagation. - peer.wait_for_broadcast([tx["tx"].getwtxid() for tx in package_txns]) + peer.wait_for_broadcast([tx["tx"].wtxid_hex for tx in package_txns]) self.generate(node, 1) def test_submitpackage(self): @@ -410,9 +410,9 @@ class RPCPackagesTest(BitcoinTestFramework): hex_partial_acceptance = [txs[0]["hex"], bad_child.serialize().hex()] res = node.submitpackage(hex_partial_acceptance) assert_equal(res["package_msg"], "transaction failed") - first_wtxid = txs[0]["tx"].getwtxid() + first_wtxid = txs[0]["tx"].wtxid_hex assert "error" not in res["tx-results"][first_wtxid] - sec_wtxid = bad_child.getwtxid() + sec_wtxid = bad_child.wtxid_hex assert_equal(res["tx-results"][sec_wtxid]["error"], "version") peer.wait_for_broadcast([first_wtxid]) @@ -496,7 +496,7 @@ class RPCPackagesTest(BitcoinTestFramework): # Relax the restrictions for both and send it; parent gets through as own subpackage pkg_result = node.submitpackage(chained_burn_hex, maxfeerate=minrate_btc_kvb_burn, maxburnamount=chained_txns_burn[1]["new_utxo"]["value"]) assert "error" not in pkg_result["tx-results"][chained_txns_burn[0]["wtxid"]] - assert_equal(pkg_result["tx-results"][tx.getwtxid()]["error"], "scriptpubkey") + assert_equal(pkg_result["tx-results"][tx.wtxid_hex]["error"], "scriptpubkey") assert_equal(node.getrawmempool(), [chained_txns_burn[0]["txid"]]) if __name__ == "__main__": diff --git a/test/functional/test_framework/blocktools.py b/test/functional/test_framework/blocktools.py index 182befd59cd..70bd5190c47 100644 --- a/test/functional/test_framework/blocktools.py +++ b/test/functional/test_framework/blocktools.py @@ -107,7 +107,7 @@ def create_block(hashprev=None, coinbase=None, ntime=None, *, version=None, tmpl block.vtx.append(coinbase) if txlist: for tx in txlist: - if not hasattr(tx, 'calc_sha256'): + if type(tx) is str: tx = tx_from_hex(tx) block.vtx.append(tx) block.hashMerkleRoot = block.calc_merkle_root() @@ -134,7 +134,6 @@ def add_witness_commitment(block, nonce=0): # witness commitment is the last OP_RETURN output in coinbase block.vtx[0].vout.append(CTxOut(0, get_witness_script(witness_root, witness_nonce))) - block.vtx[0].rehash() block.hashMerkleRoot = block.calc_merkle_root() block.rehash() @@ -176,7 +175,6 @@ def create_coinbase(height, pubkey=None, *, script_pubkey=None, extra_output_scr coinbaseoutput2.nValue = 0 coinbaseoutput2.scriptPubKey = extra_output_script coinbase.vout.append(coinbaseoutput2) - coinbase.calc_sha256() return coinbase def create_tx_with_script(prevtx, n, script_sig=b"", *, amount, output_script=None): @@ -189,9 +187,8 @@ def create_tx_with_script(prevtx, n, script_sig=b"", *, amount, output_script=No output_script = CScript() tx = CTransaction() assert n < len(prevtx.vout) - tx.vin.append(CTxIn(COutPoint(prevtx.sha256, n), script_sig, SEQUENCE_FINAL)) + tx.vin.append(CTxIn(COutPoint(prevtx.txid_int, n), script_sig, SEQUENCE_FINAL)) tx.vout.append(CTxOut(amount, output_script)) - tx.calc_sha256() return tx def get_legacy_sigopcount_block(block, accurate=True): diff --git a/test/functional/test_framework/mempool_util.py b/test/functional/test_framework/mempool_util.py index ef30b31b249..1955b2637ea 100644 --- a/test/functional/test_framework/mempool_util.py +++ b/test/functional/test_framework/mempool_util.py @@ -34,7 +34,7 @@ def assert_mempool_contents(test_framework, node, expected=None, sync=True): mempool = node.getrawmempool(verbose=False) assert_equal(len(mempool), len(expected)) for tx in expected: - assert tx.rehash() in mempool + assert tx.txid_hex in mempool def fill_mempool(test_framework, node, *, tx_sync_fun=None): @@ -104,5 +104,5 @@ def fill_mempool(test_framework, node, *, tx_sync_fun=None): def tx_in_orphanage(node, tx: CTransaction) -> bool: """Returns true if the transaction is in the orphanage.""" - found = [o for o in node.getorphantxs(verbosity=1) if o["txid"] == tx.rehash() and o["wtxid"] == tx.getwtxid()] + found = [o for o in node.getorphantxs(verbosity=1) if o["txid"] == tx.txid_hex and o["wtxid"] == tx.wtxid_hex] return len(found) == 1 diff --git a/test/functional/test_framework/messages.py b/test/functional/test_framework/messages.py index 5549d8f753c..b107fa1574f 100755 --- a/test/functional/test_framework/messages.py +++ b/test/functional/test_framework/messages.py @@ -585,8 +585,7 @@ class CTxWitness: class CTransaction: - __slots__ = ("hash", "nLockTime", "version", "sha256", "vin", "vout", - "wit") + __slots__ = ("nLockTime", "version", "vin", "vout", "wit") def __init__(self, tx=None): if tx is None: @@ -595,15 +594,11 @@ class CTransaction: self.vout = [] self.wit = CTxWitness() self.nLockTime = 0 - self.sha256 = None - self.hash = None else: self.version = tx.version self.vin = copy.deepcopy(tx.vin) self.vout = copy.deepcopy(tx.vout) self.nLockTime = tx.nLockTime - self.sha256 = tx.sha256 - self.hash = tx.hash self.wit = copy.deepcopy(tx.wit) def deserialize(self, f): @@ -625,8 +620,6 @@ class CTransaction: else: self.wit = CTxWitness() self.nLockTime = int.from_bytes(f.read(4), "little") - self.sha256 = None - self.hash = None def serialize_without_witness(self): r = b"" @@ -664,28 +657,27 @@ class CTransaction: def serialize(self): return self.serialize_with_witness() - def getwtxid(self): + @property + def wtxid_hex(self): + """Return wtxid (transaction hash with witness) as hex string.""" return hash256(self.serialize())[::-1].hex() - # Recalculate the txid (transaction hash without witness) - def rehash(self): - self.sha256 = None - self.calc_sha256() - return self.hash + @property + def wtxid_int(self): + """Return wtxid (transaction hash with witness) as integer.""" + return uint256_from_str(hash256(self.serialize_with_witness())) - # We will only cache the serialization without witness in - # self.sha256 and self.hash -- those are expected to be the txid. - def calc_sha256(self, with_witness=False): - if with_witness: - # Don't cache the result, just return it - return uint256_from_str(hash256(self.serialize_with_witness())) + @property + def txid_hex(self): + """Return txid (transaction hash without witness) as hex string.""" + return hash256(self.serialize_without_witness())[::-1].hex() - if self.sha256 is None: - self.sha256 = uint256_from_str(hash256(self.serialize_without_witness())) - self.hash = hash256(self.serialize_without_witness())[::-1].hex() + @property + def txid_int(self): + """Return txid (transaction hash without witness) as integer.""" + return uint256_from_str(hash256(self.serialize_without_witness())) def is_valid(self): - self.calc_sha256() for tout in self.vout: if tout.nValue < 0 or tout.nValue > 21000000 * COIN: return False @@ -813,8 +805,7 @@ class CBlock(CBlockHeader): def calc_merkle_root(self): hashes = [] for tx in self.vtx: - tx.calc_sha256() - hashes.append(ser_uint256(tx.sha256)) + hashes.append(ser_uint256(tx.txid_int)) return self.get_merkle_root(hashes) def calc_witness_merkle_root(self): @@ -824,7 +815,7 @@ class CBlock(CBlockHeader): for tx in self.vtx[1:]: # Calculate the hashes with witness data - hashes.append(ser_uint256(tx.calc_sha256(True))) + hashes.append(ser_uint256(tx.wtxid_int)) return self.get_merkle_root(hashes) @@ -1006,9 +997,9 @@ class HeaderAndShortIDs: [k0, k1] = self.get_siphash_keys() for i in range(len(block.vtx)): if i not in prefill_list: - tx_hash = block.vtx[i].sha256 + tx_hash = block.vtx[i].txid_int if use_witness: - tx_hash = block.vtx[i].calc_sha256(with_witness=True) + tx_hash = block.vtx[i].wtxid_int self.shortids.append(calculate_shortid(k0, k1, tx_hash)) def __repr__(self): diff --git a/test/functional/test_framework/p2p.py b/test/functional/test_framework/p2p.py index 811ab45fd02..e7064e386f2 100755 --- a/test/functional/test_framework/p2p.py +++ b/test/functional/test_framework/p2p.py @@ -619,7 +619,7 @@ class P2PInterface(P2PConnection): def test_function(): if not self.last_message.get('tx'): return False - return self.last_message['tx'].tx.rehash() == txid + return self.last_message['tx'].tx.txid_hex == txid self.wait_until(test_function, timeout=timeout) @@ -911,7 +911,7 @@ class P2PDataStore(P2PInterface): with p2p_lock: for tx in txs: - self.tx_store[tx.sha256] = tx + self.tx_store[tx.txid_int] = tx reject_reason = [reject_reason] if reject_reason else [] with node.assert_debug_log(expected_msgs=reject_reason): @@ -927,11 +927,11 @@ class P2PDataStore(P2PInterface): if success: # Check that all txs are now in the mempool for tx in txs: - assert tx.hash in raw_mempool, "{} not found in mempool".format(tx.hash) + assert tx.txid_hex in raw_mempool, "{} not found in mempool".format(tx.txid_hex) else: # Check that none of the txs are now in the mempool for tx in txs: - assert tx.hash not in raw_mempool, "{} tx found in mempool".format(tx.hash) + assert tx.txid_hex not in raw_mempool, "{} tx found in mempool".format(tx.txid_hex) class P2PTxInvStore(P2PInterface): """A P2PInterface which stores a count of how many times each txid has been announced.""" diff --git a/test/functional/test_framework/script.py b/test/functional/test_framework/script.py index b7783eb3a8c..f3cee7c66d4 100644 --- a/test/functional/test_framework/script.py +++ b/test/functional/test_framework/script.py @@ -694,7 +694,6 @@ def sign_input_legacy(tx, input_index, input_scriptpubkey, privkey, sighash_type assert err is None der_sig = privkey.sign_ecdsa(sighash) tx.vin[input_index].scriptSig = bytes(CScript([der_sig + bytes([sighash_type])])) + tx.vin[input_index].scriptSig - tx.rehash() def sign_input_segwitv0(tx, input_index, input_scriptpubkey, input_amount, privkey, sighash_type=SIGHASH_ALL): """Add segwitv0 ECDSA signature for a given transaction input. Note that the signature @@ -703,7 +702,6 @@ def sign_input_segwitv0(tx, input_index, input_scriptpubkey, input_amount, privk sighash = SegwitV0SignatureHash(input_scriptpubkey, tx, input_index, sighash_type, input_amount) der_sig = privkey.sign_ecdsa(sighash) tx.wit.vtxinwit[input_index].scriptWitness.stack.insert(0, der_sig + bytes([sighash_type])) - tx.rehash() # TODO: Allow cached hashPrevouts/hashSequence/hashOutputs to be provided. # Performance optimization probably not necessary for python tests, however. diff --git a/test/functional/test_framework/wallet.py b/test/functional/test_framework/wallet.py index dee90f9fd6c..ab462f79a2e 100644 --- a/test/functional/test_framework/wallet.py +++ b/test/functional/test_framework/wallet.py @@ -287,7 +287,7 @@ class MiniWallet: return { "sent_vout": 1, "txid": txid, - "wtxid": tx.getwtxid(), + "wtxid": tx.wtxid_hex, "hex": tx.serialize().hex(), "tx": tx, } @@ -340,7 +340,7 @@ class MiniWallet: if target_vsize: self._bulk_tx(tx, target_vsize) - txid = tx.rehash() + txid = tx.txid_hex return { "new_utxos": [self._create_utxo( txid=txid, @@ -352,7 +352,7 @@ class MiniWallet: ) for i in range(len(tx.vout))], "fee": fee, "txid": txid, - "wtxid": tx.getwtxid(), + "wtxid": tx.wtxid_hex, "hex": tx.serialize().hex(), "tx": tx, }