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.
1#!/usr/bin/env python32# Copyright (c) 2015-present The Bitcoin Core developers3# Distributed under the MIT software license, see the accompanying4# file COPYING or http://www.opensource.org/licenses/mit-license.php.5"""Test BIP66 (DER SIG).7Test the DERSIG soft-fork activation on regtest.8"""10from test_framework.blocktools import (11create_block,12)13from test_framework.messages import msg_block14from test_framework.p2p import P2PInterface15from test_framework.script import CScript16from test_framework.test_framework import BitcoinTestFramework17from test_framework.util import (18assert_equal,19)20from test_framework.wallet import (21MiniWallet,22MiniWalletMode,23)26# A canonical signature consists of:27# <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>28def unDERify(tx):29"""30Make the signature in vin 0 of a tx non-DER-compliant,31by adding padding after the S-value.32"""33scriptSig = CScript(tx.vin[0].scriptSig)34newscript = []35for i in scriptSig:36if (len(newscript) == 0):37newscript.append(i[0:-1] + b'\0' + i[-1:])38else:39newscript.append(i)40tx.vin[0].scriptSig = CScript(newscript)43DERSIG_HEIGHT = 10246class BIP66Test(BitcoinTestFramework):47def set_test_params(self):48self.num_nodes = 149# whitelist peers to speed up tx relay / mempool sync50self.noban_tx_relay = True51self.extra_args = [[52f'-testactivationheight=dersig@{DERSIG_HEIGHT}',53]]54self.setup_clean_chain = True55self.rpc_timeout = 24057def create_tx(self, input_txid):58utxo_to_spend = self.miniwallet.get_utxo(txid=input_txid, mark_as_spent=False)59return self.miniwallet.create_self_transfer(utxo_to_spend=utxo_to_spend)['tx']61def test_dersig_info(self, *, is_active):62assert_equal(self.nodes[0].getdeploymentinfo()['deployments']['bip66'],63{64"active": is_active,65"height": DERSIG_HEIGHT,66"type": "buried",67},68)70def run_test(self):71peer = self.nodes[0].add_p2p_connection(P2PInterface())72self.miniwallet = MiniWallet(self.nodes[0], mode=MiniWalletMode.RAW_P2PK)74self.test_dersig_info(is_active=False)76self.log.info("Mining %d blocks", DERSIG_HEIGHT - 2)77self.coinbase_txids = [self.nodes[0].getblock(b)['tx'][0] for b in self.generate(self.miniwallet, DERSIG_HEIGHT - 2)]79self.log.info("Test that a transaction with non-DER signature can still appear in a block")81spendtx = self.create_tx(self.coinbase_txids[0])82unDERify(spendtx)84tip = self.nodes[0].getbestblockhash()85block_time = self.nodes[0].getblockheader(tip)['mediantime'] + 186block = create_block(int(tip, 16), height=DERSIG_HEIGHT - 1, ntime=block_time, txlist=[spendtx])87block.solve()89assert_equal(self.nodes[0].getblockcount(), DERSIG_HEIGHT - 2)90self.test_dersig_info(is_active=False) # Not active as of current tip and next block does not need to obey rules91peer.send_and_ping(msg_block(block))92assert_equal(self.nodes[0].getblockcount(), DERSIG_HEIGHT - 1)93self.test_dersig_info(is_active=True) # Not active as of current tip, but next block must obey rules94assert_equal(self.nodes[0].getbestblockhash(), block.hash_hex)96self.log.info("Test that blocks must now be at least version 3")97tip = block.hash_int98block_time += 199block = create_block(tip, height=DERSIG_HEIGHT, ntime=block_time, version=2)100block.solve()102with self.nodes[0].assert_debug_log(expected_msgs=[f'{block.hash_hex}, bad-version(0x00000002)']):103peer.send_and_ping(msg_block(block))104assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip)105peer.sync_with_ping()107self.log.info("Test that transactions with non-DER signatures cannot appear in a block")108block.nVersion = 4110coin_txid = self.coinbase_txids[1]111spendtx = self.create_tx(coin_txid)112unDERify(spendtx)114# First we show that this tx is valid except for DERSIG by getting it115# rejected from the mempool for exactly that reason.116spendtx_txid = spendtx.txid_hex117spendtx_wtxid = spendtx.wtxid_hex118assert_equal(119[{120'txid': spendtx_txid,121'wtxid': spendtx_wtxid,122'allowed': False,123'reject-reason': 'mempool-script-verify-flag-failed (Non-canonical DER signature)',124'reject-details': 'mempool-script-verify-flag-failed (Non-canonical DER signature), ' +125f"input 0 of {spendtx_txid} (wtxid {spendtx_wtxid}), spending {coin_txid}:0"126}],127self.nodes[0].testmempoolaccept(rawtxs=[spendtx.serialize().hex()], maxfeerate=0),128)130# Now we verify that a block with this transaction is also invalid.131block.vtx.append(spendtx)132block.hashMerkleRoot = block.calc_merkle_root()133block.solve()135with self.nodes[0].assert_debug_log(expected_msgs=['Block validation error: block-script-verify-flag-failed (Non-canonical DER signature)']):136peer.send_and_ping(msg_block(block))137assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip)138peer.sync_with_ping()140self.log.info("Test that a block with a DERSIG-compliant transaction is accepted")141block.vtx[1] = self.create_tx(self.coinbase_txids[1])142block.hashMerkleRoot = block.calc_merkle_root()143block.solve()145self.test_dersig_info(is_active=True) # Not active as of current tip, but next block must obey rules146peer.send_and_ping(msg_block(block))147self.test_dersig_info(is_active=True) # Active as of current tip148assert_equal(self.nodes[0].getbestblockhash(), block.hash_hex)151if __name__ == '__main__':152BIP66Test(__file__).main()
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.