Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
501# When the block is serialized with a witness, the block will be rejected because witness502# data isn't allowed in blocks that don't commit to witness data.503test_witness_block(self.nodes[0], self.test_node, block, accepted=False, with_witness=True, reason='unexpected-witness')505# When the block is serialized without witness, validation fails because the transaction is506# invalid (transactions are always validated with SCRIPT_VERIFY_WITNESS so a segwit v0 transaction507# without a witness is invalid).508test_witness_block(self.nodes[0], self.test_node, block, accepted=False, with_witness=False,509reason='block-script-verify-flag-failed (Witness program was passed an empty witness)')511self.utxo.pop(0)512self.utxo.append(UTXO(txid, 2, value))514@subtest515def test_witness_tx_relay_before_segwit_activation(self):517# Generate a transaction that doesn't require a witness, but send it518# with a witness. Should be rejected for premature-witness, but should519# not be added to recently rejected list.520tx = CTransaction()521tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b""))522tx.vout.append(CTxOut(self.utxo[0].nValue - 1000, CScript([OP_TRUE, OP_DROP] * 15 + [OP_TRUE])))523tx.wit.vtxinwit.append(CTxInWitness())524tx.wit.vtxinwit[0].scriptWitness.stack = [b'a']526tx_hash = tx.txid_int527tx_value = tx.vout[0].nValue529# Verify that if a peer doesn't set nServices to include NODE_WITNESS,530# the getdata is just for the non-witness portion.531self.old_node.announce_tx_and_wait_for_getdata(tx)532assert_equal(self.old_node.last_message["getdata"].inv[0].type, MSG_TX)534# Since we haven't delivered the tx yet, inv'ing the same tx from535# a witness transaction ought not result in a getdata.536self.test_node.announce_tx_and_wait_for_getdata(tx, success=False)538# Delivering this transaction with witness should fail (no matter who539# its from)540assert_equal(len(self.nodes[0].getrawmempool()), 0)541assert_equal(len(self.nodes[1].getrawmempool()), 0)542test_transaction_acceptance(self.nodes[0], self.old_node, tx, with_witness=True, accepted=False)543test_transaction_acceptance(self.nodes[0], self.test_node, tx, with_witness=True, accepted=False)545# But eliminating the witness should fix it546test_transaction_acceptance(self.nodes[0], self.test_node, tx, with_witness=False, accepted=True)548# Cleanup: mine the first transaction and update utxo549self.generate(self.nodes[0], 1)550assert_equal(len(self.nodes[0].getrawmempool()), 0)552self.utxo.pop(0)553self.utxo.append(UTXO(tx_hash, 0, tx_value))555@subtest556def test_standardness_v0(self):557"""Test V0 txout standardness.559V0 segwit outputs and inputs are always standard.560V0 segwit inputs may only be mined after activation, but not before."""562witness_script = CScript([OP_TRUE])563script_pubkey = script_to_p2wsh_script(witness_script)564p2sh_script_pubkey = script_to_p2sh_script(witness_script)566# First prepare a p2sh output (so that spending it will pass standardness)567p2sh_tx = CTransaction()568p2sh_tx.vin = [CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")]569p2sh_tx.vout = [CTxOut(self.utxo[0].nValue - 1000, p2sh_script_pubkey)]571# Mine it on test_node to create the confirmed output.572test_transaction_acceptance(self.nodes[0], self.test_node, p2sh_tx, with_witness=True, accepted=True)573self.generate(self.nodes[0], 1)575# Now test standardness of v0 P2WSH outputs.576# Start by creating a transaction with two outputs.577tx = CTransaction()578tx.vin = [CTxIn(COutPoint(p2sh_tx.txid_int, 0), CScript([witness_script]))]579tx.vout = [CTxOut(p2sh_tx.vout[0].nValue - 10000, script_pubkey)]580tx.vout.append(CTxOut(8000, script_pubkey)) # Might burn this later581tx.vin[0].nSequence = MAX_BIP125_RBF_SEQUENCE # Just to have the option to bump this tx from the mempool583# This is always accepted, since the mempool policy is to consider segwit as always active584# and thus allow segwit outputs585test_transaction_acceptance(self.nodes[1], self.std_node, tx, with_witness=True, accepted=True)587# Now create something that looks like a P2PKH output. This won't be spendable.588witness_hash = sha256(witness_script)589script_pubkey = CScript([OP_0, hash160(witness_hash)])590tx2 = CTransaction()591# tx was accepted, so we spend the second output.592tx2.vin = [CTxIn(COutPoint(tx.txid_int, 1), b"")]593tx2.vout = [CTxOut(7000, script_pubkey)]594tx2.wit.vtxinwit.append(CTxInWitness())595tx2.wit.vtxinwit[0].scriptWitness.stack = [witness_script]597test_transaction_acceptance(self.nodes[1], self.std_node, tx2, with_witness=True, accepted=True)599# Now update self.utxo for later tests.600tx3 = CTransaction()601# tx and tx2 were both accepted. Don't bother trying to reclaim the602# P2PKH output; just send tx's first output back to an anyone-can-spend.603self.sync_mempools([self.nodes[0], self.nodes[1]])604tx3.vin = [CTxIn(COutPoint(tx.txid_int, 0), b"")]605tx3.vout = [CTxOut(tx.vout[0].nValue - 1000, CScript([OP_TRUE, OP_DROP] * 15 + [OP_TRUE]))]606tx3.wit.vtxinwit.append(CTxInWitness())607tx3.wit.vtxinwit[0].scriptWitness.stack = [witness_script]608if not self.segwit_active:609# Just check mempool acceptance, but don't add the transaction to the mempool, since witness is disallowed610# in blocks and the tx is impossible to mine right now.611testres3 = self.nodes[0].testmempoolaccept([tx3.serialize_with_witness().hex()])612testres3[0]["fees"].pop("effective-feerate")613testres3[0]["fees"].pop("effective-includes")614assert_equal(testres3,615[{616'txid': tx3.txid_hex,617'wtxid': tx3.wtxid_hex,618'allowed': True,619'vsize_adjusted': tx3.get_vsize(),620'vsize': tx3.get_vsize(),621'vsize_bip141': tx3.get_vsize(),622'fees': {623'base': Decimal('0.00001000'),624},625}],626)627# Create the same output as tx3, but by replacing tx628tx3_out = tx3.vout[0]629tx3 = tx630tx3.vout = [tx3_out]631testres3_replaced = self.nodes[0].testmempoolaccept([tx3.serialize_with_witness().hex()])632testres3_replaced[0]["fees"].pop("effective-feerate")633testres3_replaced[0]["fees"].pop("effective-includes")634assert_equal(testres3_replaced,635[{636'txid': tx3.txid_hex,637'wtxid': tx3.wtxid_hex,638'allowed': True,639'vsize_adjusted': tx3.get_vsize(),640'vsize': tx3.get_vsize(),641'vsize_bip141': tx3.get_vsize(),642'fees': {643'base': Decimal('0.00011000'),644},645}],646)647test_transaction_acceptance(self.nodes[0], self.test_node, tx3, with_witness=True, accepted=True)649self.generate(self.nodes[0], 1)650self.utxo.pop(0)651self.utxo.append(UTXO(tx3.txid_int, 0, tx3.vout[0].nValue))652assert_equal(len(self.nodes[1].getrawmempool()), 0)654@subtest655def advance_to_segwit_active(self):656"""Mine enough blocks to activate segwit."""657assert not softfork_active(self.nodes[0], 'segwit')658height = self.nodes[0].getblockcount()659self.generate(self.nodes[0], SEGWIT_HEIGHT - height - 2)660assert not softfork_active(self.nodes[0], 'segwit')661self.generate(self.nodes[0], 1)662assert softfork_active(self.nodes[0], 'segwit')663self.segwit_active = True665@subtest666def test_p2sh_witness(self):667"""Test P2SH wrapped witness programs."""669# Prepare the p2sh-wrapped witness output670witness_script = CScript([OP_DROP, OP_TRUE])671p2wsh_pubkey = script_to_p2wsh_script(witness_script)672script_pubkey = script_to_p2sh_script(p2wsh_pubkey)673script_sig = CScript([p2wsh_pubkey]) # a push of the redeem script675# Fund the P2SH output676tx = CTransaction()677tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b""))678tx.vout.append(CTxOut(self.utxo[0].nValue - 1000, script_pubkey))680# Verify mempool acceptance and block validity681test_transaction_acceptance(self.nodes[0], self.test_node, tx, with_witness=False, accepted=True)682block = self.build_next_block()683self.update_witness_block_with_transactions(block, [tx])684test_witness_block(self.nodes[0], self.test_node, block, accepted=True, with_witness=True)685self.sync_blocks()687# Now test attempts to spend the output.688spend_tx = CTransaction()689spend_tx.vin.append(CTxIn(COutPoint(tx.txid_int, 0), script_sig))690spend_tx.vout.append(CTxOut(tx.vout[0].nValue - 1000, CScript([OP_TRUE])))692# This transaction should not be accepted into the mempool pre- or693# post-segwit. Mempool acceptance will use SCRIPT_VERIFY_WITNESS which694# will require a witness to spend a witness program regardless of695# segwit activation. Note that older bitcoind's that are not696# segwit-aware would also reject this for failing CLEANSTACK.697with self.nodes[0].assert_debug_log(698expected_msgs=[spend_tx.txid_hex, 'was not accepted: mempool-script-verify-flag-failed (Witness program was passed an empty witness)']):699test_transaction_acceptance(self.nodes[0], self.test_node, spend_tx, with_witness=False, accepted=False)701# The transaction was detected as witness stripped above and not added to the reject702# filter. Trying again will check it again and result in the same error.703with self.nodes[0].assert_debug_log(704expected_msgs=[spend_tx.txid_hex, 'was not accepted: mempool-script-verify-flag-failed (Witness program was passed an empty witness)']):705test_transaction_acceptance(self.nodes[0], self.test_node, spend_tx, with_witness=False, accepted=False)707# Try to put the witness script in the scriptSig, should also fail.708spend_tx.vin[0].scriptSig = CScript([p2wsh_pubkey, b'a'])709with self.nodes[0].assert_debug_log(710expected_msgs=[spend_tx.txid_hex, 'was not accepted: mempool-script-verify-flag-failed (Script evaluated without error but finished with a false/empty top stack element)']):711test_transaction_acceptance(self.nodes[0], self.test_node, spend_tx, with_witness=False, accepted=False)713# Now put the witness script in the witness, should succeed after714# segwit activates.715spend_tx.vin[0].scriptSig = script_sig716spend_tx.wit.vtxinwit.append(CTxInWitness())717spend_tx.wit.vtxinwit[0].scriptWitness.stack = [b'a', witness_script]719# Verify mempool acceptance720test_transaction_acceptance(self.nodes[0], self.test_node, spend_tx, with_witness=True, accepted=True)721block = self.build_next_block()722self.update_witness_block_with_transactions(block, [spend_tx])724# If we're after activation, then sending this with witnesses should be valid.725# This no longer works before activation, because SCRIPT_VERIFY_WITNESS726# is always set.727# TODO: rewrite this test to make clear that it only works after activation.728test_witness_block(self.nodes[0], self.test_node, block, accepted=True)730# Update self.utxo731self.utxo.pop(0)732self.utxo.append(UTXO(spend_tx.txid_int, 0, spend_tx.vout[0].nValue))734@subtest735def test_witness_commitments(self):736"""Test witness commitments.738This test can only be run after segwit has activated."""740# First try a correct witness commitment.741block = self.build_next_block()742add_witness_commitment(block)743block.solve()745# Test the test -- witness serialization should be different746assert_not_equal(msg_block(block).serialize(), msg_no_witness_block(block).serialize())748# This empty block should be valid.749test_witness_block(self.nodes[0], self.test_node, block, accepted=True)
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.