Release notes¶
What a user has to act on, and nothing else: a breaking change, a migration, a default that moved under them. Everything a reader would merely notice is in CHANGELOG.md, which is the record behind this file.
Release names follow calendar versioning: full year, short month, short day (YYYY-M-D)
v2026.11.14¶
btclib requires
base58-bech322026.11.12 (closes #3086). Act on it if you pinbase58-bech32below 2026.11.12. The floor brings base58-bech32’s changed refusal texts: if you match on the text of a refusal, read its v2026.11.12 release notes.
Breaking changes¶
Every btclib module reads a value by its own class (closes #3080), as
btclib.utilsdoes since v2026.11.13. An object whose__class__claims a type it is not, such asMock(spec=int), is refused or answered as the object it is, where it was read as that type.to_script_flagsrefuses aMock(spec=ScriptFlag)where it returned it, andScriptPubKeyandTxcompare unequal to a Mock claiming their class where they raisedAttributeError. The__eq__and the ordering that@dataclassgenerates are the exception, as_has_type’s docstring says (closes #3091):TxOut(...) == Mock(spec=TxOut)still raisesAttributeError, or answersTruewhere the Mock’s fields match. Act on it if you pass a stand-in: pass the object itself.to_script_flagsrefuses, withBTClibTypeError, a value other thanNonewhose class is not acollections.abc.Iterablesubclass, and a name that is not a str (closes #3088). Before, such a value, or such a name, got what its own attributes led to, such as a plainTypeErrorfor an int, its names for a sequence with__getitem__alone, itself back for aMock(spec=ScriptFlag), andBTClibValueErrorfor a name that is an int. Act on it if you pass a sequence whose class is not anIterablesubclass, such as one with__getitem__alone: pass a list, or register its class withcollections.abc.Iterable. Act on it too if you catchValueErrorfor a name that is not a str: catchTypeError.TxOut.to_dict(check_validity=False)refuses a network that is neither a str nor aNetworkwithBTClibTypeError(closes #3093). Before, there, such a network raised what its own attributes led to, such asAttributeErrorfor an int andBTClibValueErrorfor an object whoseto_dictreturns mainnet’s dict, both on a nulldata script. On a p2pkh script, and in the defaultto_dict(), an int already raisedBTClibTypeError. Act on it if you catchAttributeErrororBTClibValueErrorthere: catchTypeError.message_verifyrefuses a memoryview that is not C-contiguous, or whose format is not"B", as the address or the signature, withBTClibValueError(closes #3085). Before, it read the bytesbytes()of the view yields. Act on it if you pass such a view: passbytes(view).
v2026.11.13¶
btclib requires
ecc2026.11.11 (closes #3065). Act on it if you pineccbelow 2026.11.11.
Breaking changes¶
ellswift.xdhrefuses a party that is not an int withBTClibTypeError(closes #3073). Before, a party equal to 0 or 1 was read as that int:Trueas 1, the responder, whereecc.ellswift.xdh’sinitiating=Truemeans the initiator, and1.0, aDecimalor aFractionlikewise. ANoneor astrraisedBTClibValueError, which anexcept ValueErrorcaught. An int, anIntEnumincluded, is still accepted. Act on it if you pass anything but an int: pass 0 for the initiator and 1 for the responder.btclib’s type checks and coercions read an argument by its real type (closes #3076) (closes #3078) (closes #3081). A bytes or bytearray subclass is read by its base type in
btclib.utilsandmessage_verify, so its own__bytes__or__buffer__no longer decides the octets. An object whose__class__claims a type it is not, such asMagicMock(spec=bytes)or awrapt.ObjectProxy, is refused withBTClibTypeErrorby the type checks ofbtclib.utils,assert_typeincluded, and by the parameters that pass through them, andis_integeranswersFalsefor it. Before, it was read as that type or failed with a plainTypeError. Act on it if you pass a proxy: unwrap it, or convert it withbytes()orint(), before the call.
v2026.11.12¶
Breaking changes¶
Headers.parsereads a nonzero transaction count after a header and ignores it, as Core does, where it refused the payload (closes #2992). Two payloads differing only in their counts parse to equal objects, andserializewrites a zero after every header. Act on it if you relied on the refusal: passround_trip=True.sig_hash.from_txrefuses a prevout of a witness v0 program of neither 20 nor 32 bytes, bare or wrapped in p2sh, withBTClibValueError(closes #2997), where it returned the legacy hash. Consensus fails every spend of such an output.script.read_op_coderefuses a negative start offset, andscript_op_codes.read_push_dataan op code outside 0 to 78, withBTClibValueError(closes #3034). A start at or past the end still answersNone.A non-integer, a
boolincluded, is refused by its type withBTClibTypeError, aTypeError, in the script engine’sassert_pub_key_num,assert_signature_num,script_op_count,read_push_dataandread_op_code(closes #3023), and inop_int,push_int,sig_hash.legacy, the hash types ofsegwit_v0andtaproot,from_tx’scodesep_index,bms.Sig’s recovery flag andbuild_coinbase’s fees (closes #3008). Some of them took abool, afloator aDecimalas a number. Act on it if you catchBTClibValueErroraround these calls: some of them raised it for a value they now refuse withBTClibTypeError, astaprootdid for astrhash type, so catchBTClibTypeErrorthere too.The op count refusal no longer prints the count (closes #3037): it names the bound alone. Act on it if you match an error message’s text.
v2026.11.10¶
btclib requires
ecc2026.11.8 (closes #2954), which removesecc.ecc: writefrom ecc import dsawhere you wrotefrom ecc.ecc import dsa. Act on it if you pineccbelow 2026.11.8.btclib requires
base58-bech322026.10.23, a new dependency (closes #2725). Act on it if you install btclib with--no-depsor pin its dependencies.
Breaking changes¶
btclib.eccis gone, with no alias (closes #2937). Writefrom btclib import bmsandfrom btclib import ellswift; a dotted name such asbtclib.ecc.bms.signisbtclib.bms.sign.btclib.base58andbtclib.bech32are gone, with no alias (issue #2712) (closes #2725). Import the codecs frombase58_bech32:base58.encode(v, n)andbase58.decode(v, n)arebase58.b58encode_check(v, in_size=n)andbase58.b58decode_check(v, out_size=n);bech32.encode(hrp, data, m)andbech32.decode(s, m)arebech32.bech32_encode(hrp, data, m=m)andbech32.bech32_decode(s, m=m), which returns the constant as a third value. WithmNone,bech32.decodetook the constant from the witness version;bech32_decodeaccepts either and returns it, so check it against the witness version, as BIP350 says. The two bech32 functions refuse a string longer than 1023 characters by default. The codecs raisebase58_bech32’s exceptions, not btclib’s.bech32.assert_valid_hrphas no equivalent.policy.are_inputs_standardispolicy.validate_inputs_standardness, Core’sValidateInputsStandardness(closes #2939). It returnsNoneand refuses withBTClibValueError, whose message is Core’s reject details. Act on it where you read abool: catch the error where you readFalse.p2p.limits.PROTOCOL_VERSIONis Core v32.1’s, 70017 (closes #2995), soVersion()announces 70017 where it announced 70016. To write Core’s octets in front of agetblocksorgetheaderslocator, write the newDUMMY_VERSION, notPROTOCOL_VERSION.p2p.bip324.MESSAGE_IDSfollows Core v32.1’s table (closes #2938): short id 37 isfeature, and the ids after 32 up to 36 read as command"". A v2featuremessage is written and read by its short id.sig_hash.from_txrefuses a prevout of a witness program it has no rule for, any witness version from 2 to 16 and a version 1 program that is not 32 bytes, withBTClibValueError(closes #2989), where it returned the legacy hash.bms.signtakes a WIF as astr(closes #2936): astrthat fails base58check or carries no network’s WIF prefix raisesNotAPrvKeyError, and one with a WIF prefix but a wrong size, a missing compression byte or a key out of range raisesInvalidPrvKeyError, where everystrraisedBTClibTypeError.A refused argument of the wrong type raises
BTClibTypeErrorinb32.bytes_from_witness_program, for a witness version that is noint(closes #2965), and innetwork’s xkey version lookups, for a version that is notbytes(closes #2985), abytearrayor amemoryviewincluded.A refusal no longer writes a value a key could stand in for (closes #2998) (closes #3002) (closes #3005): it names the value’s type, size or bound, and quotes a name only up to 16 characters (closes #3014). Act on it if you match an error message’s text. The
PrvKeyData,PubKeyDataandScriptPubKeyreprs, nested in aTxOutor aTxtoo, show...for a field that does not have the shape it takes (closes #3006) (closes #3017).
v2026.11.7¶
btclib requires
ecc2026.11.2 (closes #2896). Act on it if you pineccbelow 2026.11.2.
Breaking changes¶
ScriptFlag.DISCOURAGE_UPGRADABLE_TAPROOT_VERSIONis1 << 18andScriptFlag.DISCOURAGE_UPGRADABLE_PUBKEYTYPEis1 << 20, Bitcoin Core’s bits, where each held the other’s (closes #2770).ScriptFlag(n)for a Core masknreads them as Core does. Act on it if you build aScriptFlagfrom an integer built from btclib’s old values, or unpickle one pickled by an earlier release: build it from the member names.
v2026.11.2¶
btclib-wallet 2026.10.29 breaks against this release. Its
wallet,fetch,hwiandpsbt_signermodules, among others, import what this release removes, and it sets no ceiling on btclib. Act on it if you install btclib-wallet: upgrade it to 2026.11.2 with btclib.btclib.consensusfollows Core v32.1 (closes #2845).HEADERS_SYNC_PARAMSand theminimum_chain_workofCONSENSUS_PARAMStake v32.1’s values on mainnet, testnet3, signet and testnet4. Act on it if you compare against Core v31.1’s.wif_from_prv_key,prv_key_data_from_wif,address_from_h160,b58.p2sh,p2wsh_p2sh,address_from_witness,b32.p2wsh,b32.p2tr,addressandaddressestake aNetworkas well as a name, and so doScriptPubKey’s constructor,p2sh,p2wshandp2tr(closes #2714).h160_from_address,witness_from_addressandnetwork_from_xkeyversiontake an optionalNetwork, and given one accept only its prefixes, hrp and versions. Nothing to act on.
Breaking changes¶
FetchError,HttpError,RpcError,SignerError,SignerNotFoundError,NoDescriptorErrorandInconclusiveErrorleavebtclib.exceptions, andbtclib.electrumleaves btclib (closes #2709). btclib-wallet 2026.11.2 declares them, inbtclib_wallet.exceptionsandbtclib_wallet.electrum. Act on it if you import any of them from btclib: import them from btclib-wallet.btclib.aliasno longer definesHashObject,HashF,CipherF,INF,JacPointandINFJ(closes #2710). Act on it if you import one of them frombtclib.alias: import it fromecc.alias.BinaryData,Integer,Octets,PointandStringstay, the same objects asecc.alias’s.The network of a
PubKeyData, aPrvKeyDataand aScriptPubKeyis typedstr | Network, and so is the networkh160_from_address,witness_from_addressandnetwork_from_xkeyversionreturn (closes #2714). A key or a script built with aNetworkthatNETWORKSdoes not hold keeps thatNetwork, and a decoder given aNetworkreturns it. Otherwise each is aNETWORKSname, as before. Act on it if your type checker reads the network asstr: narrow it.engine.verify_inputrefuses an index naming no input withBTClibValueError, and a prevouts list that is not one entry per input (closes #2672). A negative index verified another input, an index past the end raisedIndexError, and a longer prevouts list was accepted. Act on it if you pass either.assert_p2wpkhandassert_p2wshname the op code they read against OP_0, asinvalid witness version op code: 0x51 instead of OP_0 (0x00), where they saidinvalid witness version: 81 instead of 0(closes #2842). Act on it if you match the message.
v2026.10.30¶
btclib requires
ecc2026.10.30 (closes #2864). Itsnegateandnegate_jacraiseEccValueError, notEccTypeError, for a point of the wrong length; btclib calls neither. Act on it if you pineccbelow 2026.10.30, or catchTypeErrorfrom either.taproot.parsereads 0xff asUNKNOWN_OP_CODE_255(closes #2731), asscript.parsedoes, andtaproot.serializewrites it back. Core refuses the byte only where it executes. Act on it if you relied on the parse refusing it.
Breaking changes¶
The dataclass field of a
Witnessis its serialization,_serialized, notstack(closes #2748).Witness.stackis a tuple of bytes, read from the serialization. Act on it if you usedataclasses.fieldsorreplaceon aWitness,asdictorastupleon aWitnessor on aTxInorTxholding one, or matchWitness(x)positionally:replaceraisesTypeError, so build a newWitness(stack)instead.Witness.parsebuilds withcls.__new__, so a subclass’s own__init__does not run on parse. Act on it if your subclass’s__init__does work a parsed instance needs.A script tree with an odd leaf version or 0x50 is refused with
BTClibValueError(closes #2766), as BIP341 requires, bytree_helper,output_pubkey,output_prvkey,input_script_sigandScriptPubKey.p2tr. v2026.10.28 built an odd version’s leaf as the even version below it, and built a 0x50 leaf. Act on it if you pass such a tree: use the even version. 0x50 has no replacement.b32.power_of_2_base_conversionrefuses a width above 64 withBTClibValueError(closes #2720), where it converted or raisedOverflowErrororMemoryError. Act on it if you pass such a width.var_int.serializerefuses a negative integer asnegative integer, without printing it (closes #2645). Act on it if you match the message.b32.witness_from_addressrefuses an address under the wrong checksum constant asinvalid checksum (bech32m instead of bech32)orinvalid checksum (bech32 instead of bech32m), where it saidinvalid checksum(issue #2725). Act on it if you match the message.b32.witness_from_addressrefuses an address with an empty data part and a wrong checksum, such asbc1qqqqqq, asinvalid checksum, where it saidempty data in bech32 address(issue #2725). Act on it if you match the message.taproot.check_output_pubkeyrefuses a one-octet control block asinvalid control block length, where it saidinvalid size: 0 bytes instead of (32, 33, 65)(closes #2703). Act on it if you match the message.
v2026.10.28¶
btclib requires
ecc2026.10.28 (closes #2851). Act on it if you pineccbelow it.Block.assert_valid_contextualaccepts a block of any version below the BIP34, BIP66 and BIP65 heights (closes #2833). Bitcoin Core sets no version floor there, and btclib refused a version of 0 or below. Act on it if you relied on that refusal.This release is signed by
reusable-build.ymlat a commit of btclib-org/.github, not atrefs/heads/main(issue btclib-org/.github#1870). Agh attestation verifywhose--signer-workflowends in@refs/heads/mainrefuses it. Act on it if you verify releases that way: run SECURITY.md’s command, which names the workflow with no ref and checks the repository by its id (closes #2773).
Breaking changes¶
BlockContext.min_versionisint | None(closes #2833). It isNonebelow the BIP34, BIP66 and BIP65 heights. Act on it if you compare it: check forNonefirst.A
STACK_SIZErefusal raised while a script runs names the command after which the stack and the altstack together are overMAX_STACK_SIZE, in a legacy script and in tapscript alike, and the legacy engine does not size the stack a script starts on (closes #2801), as Core’sEvalScriptdoes. A script v2026.10.24 refused can be refused with another code or at another index, and a legacy script that brings its starting stack within the limit can run to its end. Act on it if you relied on the refusal or match its code or index.A refused tapscript signature check leaves its operands on the stack (closes #2800), as Core does. The verdict does not change. In tapscript, OP_CHECKSIG and OP_CHECKSIGVERIFY on a stack of fewer than two elements refuse as
OP_CHECKSIG on a stack of less than 2 elementsandOP_CHECKSIGVERIFY on a stack of less than 2 elements, where they saidstack underflow. Act on it if you read the stack of a refused script or match either message.Network.assert_validrefuses an hrp thatbech32.encoderefuses: an empty, out-of-range or not-lowercase one (closes #2822). Act on it if you build aNetworkwith such an hrp.Refusals read differently (closes #2727, closes #2820).
base58.decoderefuses a bad checksum asinvalid checksum, quoting neither checksum. For a first byte other than OP_1,assert_p2trnames the op code it read against OP_1, asinvalid witness version op code: 0x52 instead of OP_1 (0x51). Act on it if you match either message.
v2026.10.24¶
btclib requires
ecc2026.10.23, which replaces btclib-ecc (issue btclib-org/ecc#306). Act on it if you pin btclib-ecc, importbtclib_ecc, catch aBTClibEcc*exception or setBTCLIB_ECC_NO_LIBSECP256K1:ecc’s own release notes give the new names, and there is no alias.
Breaking changes¶
btclib[secp256k1]installsecc[secp256k1](issue btclib-org/ecc#306). Its btclib-secp256k1 floor isecc’s, 0.8.0.12. btclib no longer importsbtclib_secp256k1. Act on it if you pin btclib-secp256k1 through btclib: pin it yourself.output_pubkey_from_merkle_rootofscript.taprootand ofbtclib.scriptisoutput_pubkey_from_merkle_root_var, and the private_tweaked_pubkeyis_tweaked_pubkey_var(closes #2726). There is no alias. Act on it if you call either: rename it.Taproot refuses in other words and in more cases (closes #2726). An uncompressed internal key whose y is not its x’s raises
BTClibValueError("point not on curve"), where, with the bindings, it raised “invalid internal public key: …”. A tweak that sums to infinity or zero makescheck_output_pubkey,output_pubkeyandoutput_prvkeyraiseBTClibValueError;check_output_pubkeyansweredFalse;output_pubkeyraised “invalid x-coordinate” with the bindings and returned a key without;output_prvkeyraised the bindings’ValueErroror returned 0. Act on it if you match the message or catch the old error.Names that run in variable time take
_var, with no alias (closes #2687):PubKeyData.point,assert_p2pk,is_p2pk,assert_p2ms,is_p2msandp2ms_m_and_keys(ofscript.script_pub_keyand ofbtclib.script),MuHash3072.digestandCoinStats.digestarePubKeyData.point_var,assert_p2pk_var,is_p2pk_var,assert_p2ms_var,is_p2ms_var,p2ms_m_and_keys_var,MuHash3072.digest_varandCoinStats.digest_var. Act on it if you call one: add the suffix.BlockContext’sbip34_heightfield, anint, isconsensus, aConsensusParams, andblock_context.BIP34_HEIGHTis gone (issue #2705). Act on it if you build one: passconsensus=NETWORKS[name].consensuswhere you passedbip34_height=…, and readctx.consensus.bip34_heightfor the height andCONSENSUS_PARAMS["mainnet"].bip34_heightfor the constant.Block.assert_valid_contextualrefuses blocks it accepted (issue #2705): an outdated version, a non-final transaction, a witness below the segwit height, a commitment without its nonce, and a block over the weight cap. Act on it if you call it on blocks of those kinds.bitcoin-core-rpc is no longer a dependency of btclib (issue #2707). Nothing in btclib imports it. Act on it if you relied on btclib to install it: require it yourself.
v2026.10.17¶
btclib requires btclib-ecc 2026.10.17 and bitcoin-core-rpc 2026.10.17, and its
secp256k1extra btclib-secp256k1 0.8.0.12 (closes #2702). Act on it if you pin any of them lower. btclib-ecc’s own breaking changes, inrangeproofand in the low-R grind ofdsa, are in its release notes.
Breaking changes¶
PartialMerkleTree.serializewithcheck_validity=Falserefuses a transaction count that is not an int, or that four octets do not hold (closes #2668). It raisesBTClibTypeErrororBTClibValueError, where it raisedAttributeErrororOverflowError;MerkleBlock.serializedoes the same. Act on it if you catchAttributeErrororOverflowErrorthere: catch the btclib errors, which are aTypeErrorand aValueError.
v2026.10.16¶
btclib 2026.9.29 to 2026.10.9 fail at import beside btclib-ecc 2026.10.16 (issue btclib-org/.github#1742). Importing
btclib.keyorbtclib.scriptraisesImportError: btclib-ecc 2026.10.16 renamespoint_from_octetsandssa.point_from_bip340pub_keytopoint_from_octets_varandpoint_from_bip340pub_key_var, with no alias. Upgrade to this release, or keep btclib-ecc below 2026.10.16.
Breaking changes¶
btclib requires btclib-ecc 2026.10.16 (issue btclib-org/.github#1742). Act on it if you pin btclib-ecc lower, or import either renamed function from it: use the
_varname.hex_string,str_from_stringandbase58.decoderefuse in other words (issue #2625).hex_stringdoes not quote a negative integer. The other two name the position of a non-ASCII character, not the character, and so do their callers,b58.prv_key_data_from_wifincluded. Act on it if you match the message.int_from_integerrefuses an empty string or empty bytes (closes #2671). It returned 0. Act on it if you pass an empty value: pass 0.script.parseandtaproot.parsereturnOP_0for the empty pushes4c00,4d0000and4e00000000(closes #2607). They returned"", and so didScript.asmand the asm ofscript_to_dict.script_from_dictrefuses a dict an older btclib wrote with"asm": ""beside such a hex. Act on it if you test a command against"", or read stored dicts: test against"OP_0", and drop the asm, the hex alone being read.Serializers with
check_validity=Falserefuse an int field, or a header’s time, of the wrong type or range withBTClibTypeErrororBTClibValueError(issues #2640, #2644, #2654, #2655, #2656, #2658, #2663, #2664, #2665, #2666). They raisedAttributeError,OverflowError,TypeErrororValueError, and some p2p fields wrote a float or a str thatintreads. This holds forTx,TxIn,OutPoint,TxOut,BlockHeaderand the p2p payloads. Act on it if you catchAttributeErrororOverflowErrorthere: catch the btclib errors, which are aTypeErrorand aValueError.TxOutrefuses a value that is not an int (issue #2654). It built the output from a str,None, or a float orDecimalof whole value; it raisesBTClibTypeError. Act on it if you pass one: pass an int of satoshis.The signature hashes refuse a bool or a float in the sequence, vout, version, lock time and amount (closes #2627, closes #2640).
legacy,segwit_v0and the taprootfrom_txraiseBTClibTypeError, where a bool was hashed as 0 or 1. Act on it if you pass a bool: pass an int.verify_amountsrefuses a prevout value outside 0..MAX_MONEY, or a total past MAX_MONEY (closes #2670), as Core’sConsensus::CheckTxInputsdoes. It passed them. Act on it if you relied on that: Core refuses such a transaction.encode_requesttakes only a list or a tuple asparams, and the Electrum request builders refuse a malformed argument (closes #2629). A string, a set or a generator asparamsraisesBTClibTypeError; it was read as a list of its items.block_header_requestrefuses a negative height, every builder refuses a bool as an integer, and atx_idmust be 64 hex characters. Act on it if you pass another iterable asparams: pass a list.
v2026.10.9¶
Breaking changes¶
Tx.parse,Tx.parse_without_witnessandBlock.parsewithcheck_validity=Falsereturn a transaction pastMAX_TX_IN_COUNTinputs orMAX_TX_OUT_COUNToutputs (closes #2592). They raised.assert_validrefuses such a transaction as oversize.TxPayload.parse,BlockPayload.parseand the compact-block parsers withcheck_validity=Falsedo the same. Act on it if you relied on that refusal: callassert_valid, or parse withcheck_validity.
v2026.10.8¶
A key passed as the network, or a non-ASCII WIF, is no longer echoed in an error or a repr (GHSA-c6h8-5hv5-3gv7). Releases from 2020.3.20 can echo one. Upgrade, and treat a key such an error or repr may have recorded as exposed.
Breaking changes¶
A refused network name reads differently (GHSA-c6h8-5hv5-3gv7). A non-string is named by its type, a long name is not quoted. Act on it if you match the message.
reconstructraisesShortIdCollisionErrorwhere short ids collide (closes #2570). It raisedBTClibValueError;ShortIdCollisionErroris aBTClibRuntimeError. Act on it if you catchBTClibValueErrorthere: catch the new error and ask for the whole block, as Core does.PrefilledTransaction.parseandCmpctBlock.parsewithcheck_validity=Falsereturn an index past 65535 (closes #2572). They raised.PrefilledTransaction.serializethere no longer raises for aprevious_indexpast 65535, andCmpctBlock.parseraises on short ids plus prefilled transactions past 65535 where it returned. Act on it if you relied on those refusals: check the index yourself or usecheck_validity.
v2026.10.7¶
The attestation bundle is attached as
v<version>.intoto.jsonlfrom v2026.9.30 on, in place ofv<version>.attestation.jsonl. A script that downloads it by name, or passes it togh attestation verify --bundle, uses the new name.
Breaking changes¶
bip324.message_from_contentsrefuses a long message type holding 0x7F (closes #2553). It raisesBTClibValueErrorwhere it returned the command, as Core’s v2 reader does since bitcoin/bitcoin#35958. Act on it if you read v2 messages from peers: drop the message, as Core does.
v2026.10.5¶
Verifying a transaction takes time linear in its inputs (GHSA-9r97-9x22-2pp4). It took time quadratic in them, even with
PrecomputedTxData. Upgrade if you verify transactions you did not build.Signature checks of an input with one script code and hash type class share one hash (GHSA-rw95-w37r-537w). Each check of a legacy input hashed the whole transaction. Upgrade if you verify transactions you did not build.
v2026.10.4¶
btclib requires btclib-secp256k1 0.8.0.10, which fixes GHSA-8h6f-34jj-7p6c. Upgrading btclib with its
secp256k1extra installs it.
Breaking changes¶
op_if,op_notif,op_else,op_endifandassert_balanced_ifofbtclib.script.engine.script_op_codestake aConditionStack, andbtclib.script.engine.tapscript.op_checksigandop_checksigaddtake the tapleaf hash (GHSA-9fr5-46w5-5f9r). They took alist[bool]starting as[True], and the script bytes. Act on it if you call them: passConditionStack()where you passed[True], andleaf_hash(0xC0, script_bytes), frombtclib.script.taproot, where you passedscript_bytes.
v2026.10.3¶
Breaking changes¶
b58.prv_key_data_from_wifdoes not quote the checksum it refuses (closes #2436). It raisesNotAPrvKeyError: not a WIF (invalid checksum)where it raisednot a WIF (invalid checksum: 0x<found> instead of 0x<expected>). Act on it if you match on the text of the refusal: matchinvalid checksumalone. It is still aNotAPrvKeyError, so anexcepton that class is unaffected.next_bits_requiredno longer raisesinvalid timestamp (timewarp attack)(closes #2465). On a network withenforce_bip94, a header opening a difficulty period more thanMAX_TIMEWARPseconds behind its parent now gets its target back, where it raisedBTClibValueError. Act on it if you relied on that refusal: callassert_not_timewarp(header, parent, parent_height, consensus), frombtclib.blockorbtclib.block.header_context, after the median-time-past check, which is Core’s order. Without the call the bound is not checked.Tx.parserefuses a transaction with no input and two or more outputs (closes #2503). It raisesBTClibValueError: unknown transaction optional datawhere it returned the transaction, which Core’s extended reading refuses. Act on it if you parse such a transaction, a PSBT’s unsigned one (Core reads it asTX_NO_WITNESS): callTx.parse_without_witness(data, check_validity=False).op_checkmultisigverifyis gone, andbtclib.script.engine.script.OPERATIONShas noOP_CHECKSIGVERIFY,OP_EQUALVERIFY,OP_NUMEQUALVERIFYorOP_CHECKMULTISIGVERIFY(closes #2489). The loop runs the plain op code, then tests its result, so those four are no longer expansions to look up. Act on it if you callop_checkmultisigverifyor look up those keys: run the plain op code and thenop_verify, which now leaves a false element on the stack.op_equalverify,op_numequalverifyandop_checksigverifyare gone fromscript_op_codes, andbtclib.script.engine.tapscript.OPERATIONShas noOP_EQUALVERIFY,OP_NUMEQUALVERIFYorOP_CHECKSIGVERIFY(closes #2509). The tapscript loop runs the plain op code, then tests its result, as the legacy loop does. Act on it if you call any of them: runop_equal,op_numequalor the signature check, thenop_verify.btclib.script.engine.tapscript.op_checksigaddtakesop_checksig’s arguments and returns the sigops budget, andScriptOpreturnsNone(closes #2513). It was an expansion taking(stack, altstack, flags)and returning["OP_CHECKSIG", "OP_ADD"]. Act on it if you call it: pass whatop_checksigtakes, and use the budget it returns.
v2026.10.2¶
Breaking changes¶
Network.from_dictrefuses a non-stringnetwork_typewithBTClibTypeError(closes #2434). A number, a bool ornullleft asBTClibValueError, whichexcept ValueErrorno longer catches; an array or an object left as the built-inTypeError, nowBTClibTypeError. Act on it by catchingBTClibTypeErrororTypeErrorbesideValueError.taproot.output_pubkey,output_pubkey_from_merkle_rootandcheck_output_pubkeydo not quote the x-coordinate they refuse. They raiseinvalid x-coordinatefor an x below p andx-coordinate not in 0..p-1for one at or above it.output_pubkeyandoutput_pubkey_from_merkle_rootraisedinvalid x-coordinate: '<x>'for both, andcheck_output_pubkeyadded: <x>to each message. Act on it if you match on the text of these refusals: match it without the x. It is still aBTClibValueError, so anexcepton that class is unaffected.
Worth knowing, though nothing raises¶
Verifying a release’s attestation names a new signer and the tag.
gh attestation verifytakes--signer-workflow btclib-org/.github/.github/workflows/reusable-build.yml@refs/heads/mainand--source-ref refs/tags/v<version>; SECURITY.md names the signer of an earlier release.btclib requires btclib-ecc 2026.10.2, which fixes GHSA-r5pw-9wrg-m3mj and GHSA-m38m-987v-j55h. Upgrading btclib installs it.
v2026.9.30¶
Breaking changes¶
btclib.curvesisbtclib_ecc.curves(closes #2404), andimport btclib.curvesraisesModuleNotFoundError. v2023.7.12 has it asbtclib.ec. Act on it by importingbtclib_ecc.curvesin its place.btclib.curves.curveisbtclib_ecc.curves.curve(closes #2404), andimport btclib.curves.curveraisesModuleNotFoundError. v2023.7.12 has it asbtclib.ec.curve. Act on it by importingbtclib_ecc.curves.curvein its place.btclib.curves.curve_groupisbtclib_ecc.curves.curve_group(closes #2404), andimport btclib.curves.curve_groupraisesModuleNotFoundError. v2023.7.12 has it asbtclib.ec.curve_group. Act on it by importingbtclib_ecc.curves.curve_groupin its place.btclib.curves.curve_group_2isbtclib_ecc.curves.curve_group_2(closes #2404), andimport btclib.curves.curve_group_2raisesModuleNotFoundError. v2023.7.12 has it asbtclib.ec.curve_group_2. Act on it by importingbtclib_ecc.curves.curve_group_2in its place.btclib.curves.curve_group_fisbtclib_ecc.curves.curve_group_f(closes #2404), andimport btclib.curves.curve_group_fraisesModuleNotFoundError. v2023.7.12 has it asbtclib.ec.curve_group_f. Act on it by importingbtclib_ecc.curves.curve_group_fin its place.btclib.curves.sec_pointisbtclib_ecc.curves.sec_point(closes #2404), andimport btclib.curves.sec_pointraisesModuleNotFoundError. v2023.7.12 has it asbtclib.ec.sec_point. Act on it by importingbtclib_ecc.curves.sec_pointin its place.btclib.kdfisbtclib_ecc.kdf(closes #2404), andimport btclib.kdfraisesModuleNotFoundError. v2023.7.12 has nobtclib.kdf. Act on it by importingbtclib_ecc.kdfin its place.btclib.number_theoryisbtclib_ecc.number_theory(closes #2404), andimport btclib.number_theoryraisesModuleNotFoundError. v2023.7.12 hasbtclib.number_theory. Act on it by importingbtclib_ecc.number_theoryin its place.btclib.ecc.bip340_nonceisbtclib_ecc.ecc.bip340_nonce(closes #2404), andimport btclib.ecc.bip340_nonceraisesModuleNotFoundError. v2023.7.12 hasbtclib.ecc.bip340_nonce. Act on it by importingbtclib_ecc.ecc.bip340_noncein its place.btclib.ecc.borromeanisbtclib_ecc.ecc.borromean(closes #2404), andimport btclib.ecc.borromeanraisesModuleNotFoundError. v2023.7.12 hasbtclib.ecc.borromean. Act on it by importingbtclib_ecc.ecc.borromeanin its place.btclib.ecc.commit_nonceisbtclib_ecc.ecc.commit_nonce(closes #2404), andimport btclib.ecc.commit_nonceraisesModuleNotFoundError. v2023.7.12 has nobtclib.ecc.commit_nonce, its sign-to-contract module beingbtclib.ecc.sign_to_contract, which an earlier bullet records as gone. Act on it by importingbtclib_ecc.ecc.commit_noncein its place.btclib.ecc.dhisbtclib_ecc.ecc.dh(closes #2404), andimport btclib.ecc.dhraisesModuleNotFoundError. v2023.7.12 hasbtclib.ecc.dh. Act on it by importingbtclib_ecc.ecc.dhin its place.btclib.ecc.dleqisbtclib_ecc.ecc.dleq(closes #2404), andimport btclib.ecc.dleqraisesModuleNotFoundError. v2023.7.12 has nobtclib.ecc.dleq. Act on it by importingbtclib_ecc.ecc.dleqin its place.btclib.ecc.dsaisbtclib_ecc.ecc.dsa(closes #2404), andimport btclib.ecc.dsaraisesModuleNotFoundError. v2023.7.12 hasbtclib.ecc.dsa. Act on it by importingbtclib_ecc.ecc.dsain its place.btclib.ecc.eciesisbtclib_ecc.ecc.ecies(closes #2404), andimport btclib.ecc.eciesraisesModuleNotFoundError. v2023.7.12 has nobtclib.ecc.ecies. Act on it by importingbtclib_ecc.ecc.eciesin its place.btclib.ecc.frostisbtclib_ecc.ecc.frost(closes #2404), andimport btclib.ecc.frostraisesModuleNotFoundError. v2023.7.12 has nobtclib.ecc.frost. Act on it by importingbtclib_ecc.ecc.frostin its place.btclib.ecc.musig2isbtclib_ecc.ecc.musig2(closes #2404), andimport btclib.ecc.musig2raisesModuleNotFoundError. v2023.7.12 has nobtclib.ecc.musig2. Act on it by importingbtclib_ecc.ecc.musig2in its place.btclib.ecc.pedersenisbtclib_ecc.ecc.pedersen(closes #2404), andimport btclib.ecc.pedersenraisesModuleNotFoundError. v2023.7.12 hasbtclib.ecc.pedersen. Act on it by importingbtclib_ecc.ecc.pedersenin its place.btclib.ecc.rangeproofisbtclib_ecc.ecc.rangeproof(closes #2404), andimport btclib.ecc.rangeproofraisesModuleNotFoundError. v2023.7.12 has nobtclib.ecc.rangeproof. Act on it by importingbtclib_ecc.ecc.rangeproofin its place.btclib.ecc.rfc6979_nonceisbtclib_ecc.ecc.rfc6979_nonce(closes #2404), andimport btclib.ecc.rfc6979_nonceraisesModuleNotFoundError. v2023.7.12 hasbtclib.ecc.rfc6979_nonce. Act on it by importingbtclib_ecc.ecc.rfc6979_noncein its place.btclib.ecc.ssaisbtclib_ecc.ecc.ssa(closes #2404), andimport btclib.ecc.ssaraisesModuleNotFoundError. v2023.7.12 hasbtclib.ecc.ssa. Act on it by importingbtclib_ecc.ecc.ssain its place.btclib.ecc.diffie_hellmanisbtclib_ecc.ecc.diffie_hellman(closes #2404), andfrom btclib.ecc import diffie_hellmanraisesImportError. v2023.7.12’sbtclib.ecchasdiffie_hellman. Act on it by importing it frombtclib_ecc.eccinstead.btclib.ecc.second_generatorisbtclib_ecc.ecc.second_generator(closes #2404), andfrom btclib.ecc import second_generatorraisesImportError. v2023.7.12’sbtclib.ecchassecond_generator. Act on it by importing it frombtclib_ecc.eccinstead.btclib.ecc.ellswift.create_varisbtclib_ecc.ecc.ellswift.create_var(closes #2404), andfrom btclib.ecc.ellswift import create_varraisesImportError. v2023.7.12 has nocreate_var. Act on it by importing it frombtclib_ecc.ecc.ellswiftinstead.btclib.ecc.ellswift.decode_varisbtclib_ecc.ecc.ellswift.decode_var(closes #2404), andfrom btclib.ecc.ellswift import decode_varraisesImportError. v2023.7.12 has nodecode_var. Act on it by importing it frombtclib_ecc.ecc.ellswiftinstead.btclib.ecc.ellswift.encode_varisbtclib_ecc.ecc.ellswift.encode_var(closes #2404), andfrom btclib.ecc.ellswift import encode_varraisesImportError. v2023.7.12 has noencode_var. Act on it by importing it frombtclib_ecc.ecc.ellswiftinstead.btclib.hashes.tagged_hashisbtclib_ecc.hashes.tagged_hash(closes #2404), andfrom btclib.hashes import tagged_hashraisesImportError. v2023.7.12’sbtclib.hasheshastagged_hash. Act on it by importing it frombtclib_ecc.hashesinstead.btclib.hashes.reduce_to_hlenisbtclib_ecc.hashes.reduce_to_hlen(closes #2404), andfrom btclib.hashes import reduce_to_hlenraisesImportError. v2023.7.12’sbtclib.hasheshasreduce_to_hlen. Act on it by importing it frombtclib_ecc.hashesinstead.btclib.exceptions.BTClibEccExceptionisbtclib_ecc.exceptions.BTClibEccException(closes #2404), andfrom btclib.exceptions import BTClibEccExceptionraisesImportError. v2023.7.12 has noBTClibEccException. Act on it by importing it frombtclib_ecc.exceptionsinstead.btclib.exceptions.BTClibEccValueErrorisbtclib_ecc.exceptions.BTClibEccValueError(closes #2404), andfrom btclib.exceptions import BTClibEccValueErrorraisesImportError. v2023.7.12 has noBTClibEccValueError. Act on it by importing it frombtclib_ecc.exceptionsinstead.btclib.exceptions.BTClibEccTypeErrorisbtclib_ecc.exceptions.BTClibEccTypeError(closes #2404), andfrom btclib.exceptions import BTClibEccTypeErrorraisesImportError. v2023.7.12 has noBTClibEccTypeError. Act on it by importing it frombtclib_ecc.exceptionsinstead.btclib.exceptions.BTClibEccRuntimeErrorisbtclib_ecc.exceptions.BTClibEccRuntimeError(closes #2404), andfrom btclib.exceptions import BTClibEccRuntimeErrorraisesImportError. v2023.7.12 has noBTClibEccRuntimeError. Act on it by importing it frombtclib_ecc.exceptionsinstead.btclib.exceptions.BorromeanRingErrorisbtclib_ecc.exceptions.BorromeanRingError(closes #2404), andfrom btclib.exceptions import BorromeanRingErrorraisesImportError. v2023.7.12 has noBorromeanRingError. Act on it by importing it frombtclib_ecc.exceptionsinstead.btclib.exceptions.InvalidContributionErrorisbtclib_ecc.exceptions.InvalidContributionError(closes #2404), andfrom btclib.exceptions import InvalidContributionErrorraisesImportError. v2023.7.12 has noInvalidContributionError. Act on it by importing it frombtclib_ecc.exceptionsinstead.btclib.p2p.magic_from_chainisbitcoin_core_rpc.magic_from_chain(closes #2404), andfrom btclib.p2p import magic_from_chainraisesImportError. v2023.7.12 has nomagic_from_chain. Act on it by importing it frombitcoin_core_rpcinstead.btclib.p2p.magic_from_signet_challengeisbitcoin_core_rpc.magic_from_signet_challenge(closes #2404), andfrom btclib.p2p import magic_from_signet_challengeraisesImportError. v2023.7.12 has nomagic_from_signet_challenge. Act on it by importing it frombitcoin_core_rpcinstead.btclib.p2p.magic.magic_from_chainisbitcoin_core_rpc.magic_from_chain(closes #2404), andfrom btclib.p2p.magic import magic_from_chainraisesImportError. v2023.7.12 has nomagic_from_chain. Act on it by importing it frombitcoin_core_rpcinstead.btclib.p2p.magic.magic_from_signet_challengeisbitcoin_core_rpc.magic_from_signet_challenge(closes #2404), andfrom btclib.p2p.magic import magic_from_signet_challengeraisesImportError. v2023.7.12 has nomagic_from_signet_challenge. Act on it by importing it frombitcoin_core_rpcinstead.
v2026.9.29¶
Breaking changes¶
requires-pythonis>=3.11. A 3.10 install no longer resolves this release; 3.10 reaches end of life on 2026-10-31.btclib.bip21isbtclib_wallet.bip21(issue #2129), in thebtclib-walletdistribution, andimport btclib.bip21raisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.bip21in its place.btclib.bip32isbtclib_wallet.bip32(issue #2129), in thebtclib-walletdistribution, andimport btclib.bip32raisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.bip32in its place.btclib.bip322isbtclib_wallet.bip322(issue #2129), in thebtclib-walletdistribution, andimport btclib.bip322raisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.bip322in its place.btclib.bip38isbtclib_wallet.bip38(issue #2129), in thebtclib-walletdistribution, andimport btclib.bip38raisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.bip38in its place.btclib.bip44isbtclib_wallet.bip44(issue #2129), in thebtclib-walletdistribution, andimport btclib.bip44raisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.bip44in its place.btclib.bip85isbtclib_wallet.bip85(issue #2129), in thebtclib-walletdistribution, andimport btclib.bip85raisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.bip85in its place.btclib.bolt11isbtclib_wallet.bolt11(issue #2129), in thebtclib-walletdistribution, andimport btclib.bolt11raisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.bolt11in its place.btclib.bolt9isbtclib_wallet.bolt9(issue #2129), in thebtclib-walletdistribution, andimport btclib.bolt9raisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.bolt9in its place.btclib.coin_selectionisbtclib_wallet.coin_selection(issue #2129), in thebtclib-walletdistribution, andimport btclib.coin_selectionraisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.coin_selectionin its place.btclib.core_importisbtclib_wallet.core_import(issue #2129), in thebtclib-walletdistribution, andimport btclib.core_importraisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.core_importin its place.btclib.descriptorsisbtclib_wallet.descriptors(issue #2129), in thebtclib-walletdistribution, andimport btclib.descriptorsraisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.descriptorsin its place.btclib.fetchisbtclib_wallet.fetch(issue #2129), in thebtclib-walletdistribution, andimport btclib.fetchraisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.fetchin its place.btclib.hwiisbtclib_wallet.hwi(issue #2129), in thebtclib-walletdistribution, andimport btclib.hwiraisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.hwiin its place.btclib.minikeyisbtclib_wallet.minikey(issue #2129), in thebtclib-walletdistribution, andimport btclib.minikeyraisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.minikeyin its place.btclib.mnemonicisbtclib_wallet.mnemonic(issue #2129), in thebtclib-walletdistribution, andimport btclib.mnemonicraisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.mnemonicin its place.btclib.psbtisbtclib_wallet.psbt(issue #2129), in thebtclib-walletdistribution, andimport btclib.psbtraisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.psbtin its place.btclib.psbt_signerisbtclib_wallet.psbt_signer(issue #2129), in thebtclib-walletdistribution, andimport btclib.psbt_signerraisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.psbt_signerin its place.btclib.psbt_signer_contractisbtclib_wallet.psbt_signer_contract(issue #2129), in thebtclib-walletdistribution, andimport btclib.psbt_signer_contractraisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.psbt_signer_contractin its place.btclib.silent_paymentsisbtclib_wallet.silent_payments(issue #2129), in thebtclib-walletdistribution, andimport btclib.silent_paymentsraisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.silent_paymentsin its place.btclib.slip132isbtclib_wallet.slip132(issue #2129), in thebtclib-walletdistribution, andimport btclib.slip132raisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.slip132in its place.btclib.tx_builderisbtclib_wallet.tx_builder(issue #2129), in thebtclib-walletdistribution, andimport btclib.tx_builderraisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.tx_builderin its place.btclib.tx_or_psbtisbtclib_wallet.tx_or_psbt(issue #2129), in thebtclib-walletdistribution, andimport btclib.tx_or_psbtraisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.tx_or_psbtin its place.btclib.walletisbtclib_wallet.wallet(issue #2129), in thebtclib-walletdistribution, andimport btclib.walletraisesModuleNotFoundError. Act on it by installingbtclib-walletand importingbtclib_wallet.walletin its place.BIP44ScriptType,BlockCipherF,EmbeddedScriptType,KeyOrder,MnemonicLang,ValidSigHashTypeandH160_Netleavebtclib.alias(closes #2244), andfrom btclib.alias import BlockCipherFraisesImportError. Of these, v2023.7.12’sbtclib.aliashasH160_Netalone. btclib-wallet defines its own copies of the others:BIP44ScriptTypeinbtclib_wallet.bip44,BlockCipherFinbtclib_wallet.bip38,EmbeddedScriptTypeandKeyOrderinbtclib_wallet.wallet.script_wallet,MnemonicLanginbtclib_wallet.mnemonic.mnemonicandValidSigHashTypeinbtclib_wallet.psbt.psbt_in.H160_Nethas no replacement: spell ittuple[bytes, str]. btclib-wallet 2026.9.24 predates those copies, and its modules import all of them butMnemonicLangfrombtclib.alias, so upgrade btclib-wallet together with btclib, to a release later than 2026.9.24.except BTClibExceptiondoes not catch what the curve arithmetic and the schemes built on it raise (issue #2282).btclib.curves,btclib.number_theory,btclib.kdfand everybtclib.eccmodule butbmsare btclib_ecc’s objects bound again, and they raise that package’sBTClibEccValueError,BTClibEccTypeErrorandBTClibEccRuntimeError, as does a btclib function handing its argument on to them:b58.wif_from_prv_keyrefuses a key out of range withBTClibEccValueError. v2023.7.12’sdsa.Sig.parseraisedBTClibValueError. Each class derives from the built-in its name ends in, so act on it by catchingValueError,TypeErrororRuntimeError, or by namingBTClibEccException, whichbtclib.exceptionsexports, besideBTClibException.InvalidContributionErrorandBorromeanRingErrorderive fromBTClibEccRuntimeError.BTCLIB_NO_LIBSECP256K1isBTCLIB_ECC_NO_LIBSECP256K1(issue #2282): btclib_ecc reads the variable that starts a process with the delegation to libsecp256k1 off, under its own name, and nothing reads the old one. Act on it by renaming the variable wherever it is set.var_bytes.parseraisesBTClibValueErrorfor a truncated or a zero-size field, where it raisedBTClibRuntimeError(closes #2289), matchingvar_int.parseandutils.read_exactly. Every caller ofvar_bytes.parseis affected, transaction, script and block parsers as well as the p2p ones:git grep -n 'var_bytes\.parse(' -- srcnames each call site. Act on it by catchingBTClibValueErrorwherever anexcept BTClibRuntimeErrorwas written around one of them.ScriptErrortakes itscodesecond, asScriptError(message, code, index=None, stack_depth=None)(closes #2314), where it took(message, index, stack_depth), and itsargsare those four. v2023.7.12 has noScriptError. Act on it by passing aScriptErrorCodeafter the message wherever one is raised.btclib.script.engine.script.prepare_scriptis gone (issue #2341), where v2023.7.12 had it asprepare_script(script, flags, segwit). Its OP_CODESEPARATOR check isassert_const_scriptcode(op_code, flags, segwit), asked of one op code. Act on it by calling that for each op code of the script.read_push_datatakes noelement_size_limit(issue #2341): the limit isMAX_SCRIPT_ELEMENT_SIZEin both engines. v2023.7.12 has noread_push_data. Act on it by dropping the argument.A taproot script tree is None where there is none, its nodes are lists and its leaves are tuples (closes #2339).
taproot.output_pubkey,output_prvkeyandScriptPubKey.p2trrefuse[], which v2023.7.12 took for no tree; those three,input_script_sigandtree_helperrefuse a leaf written[0xC0, script]and a node written as a tuple, both of which v2023.7.12 took. Act on it by passing None for no tree,(0xC0, script)for a leaf and a list for every node.bech32.decode’s refusals do not quote the string they refuse (closes #2344), nor dob32.witness_from_addressandScriptPubKey.from_address, which pass them on. Each raises its bare category where it raised<category>: <input>:no separator character,empty HRP,too short checksum,HRP character out of range,mixed case,invalid character in checksumandinvalid data character. The checksum refusal raisesinvalid checksumwhere it raisedinvalid checksum: '<input>'.Act on it if you match on the text of a refusal: match the category alone. Every one is still a
BTClibValueError, so anexcepton that class is unaffected.bech32.decoderefuses a data part character outside 33..126 asdata part character out of range(closes #2347), andb32.witness_from_addressandScriptPubKey.from_addresswith it: any non-ASCII character instrinput, a space, DEL and the control characters. The refusal comes ahead of the case check and the alphabet lookup, where these inputs raisedmixed case,invalid data characterorinvalid character in checksum. An uppercase address with U+212A KELVIN SIGN in place ofKdecoded as that address, and is refused.Act on it if you match on the text of these refusals: match
data part character out of rangeas well. It is still aBTClibValueError, so anexcepton that class is unaffected.script_from_script_pub_keydoes not quote the string it refuses (closes #2350). It raisesneither a script nor an addresswhere it raisedneither a script nor an address: '<input>'.Act on it if you match on the text of that refusal: match it without the colon. It is still a
BTClibValueError, so anexcepton that class is unaffected.The address, WIF, base64 signature and ip decoders strip ASCII whitespace alone (closes #2349):
b32.witness_from_address,b32.is_segwit_prefixed,b58.h160_from_address,b58.prv_key_data_from_wif,bms.Sig.b64decode,bms.sign’saddrandNetworkAddress’sip, and what reads its input through them,ScriptPubKey.from_addressandbms.verifyamong them. A string padded with U+00A0, U+3000, U+2028, U+001C or another characterstr.isspacecounts beyond space, tab, newline, carriage return, vertical tab and form feed is refused withBTClibValueError, where it was taken for the value it wraps, andis_segwit_prefixedanswers False where that padding leads.Act on it if you hand these functions text padded that way: strip it first.
script.serializeandtaproot.serializematch an op code name only upper-case, asparsewrites it, and refuse a non-ASCII string command (closes #2352)."op_dup"raisesinvalid string command: op_dupwhere it serialized as OP_DUP. A string command holding a non-ASCII character raisesnon-ASCII string command, U+3000 or U+00A0 around an op code name or anUNKNOWN_OP_CODE_nincluded.taproot.serializeraisesinvalid string command: <command>for an OP_SUCCESS number written with a sign, an underscore, whitespace or a leading zero, where it read the number. Aninvalid string commandrefusal quotes the command in the case it was written in, where it quoted it upper-cased. Hex data is read in either case.Act on it by writing op code names upper-case. Each of these refusals is a
BTClibValueError.script.serializereads anUNKNOWN_OP_CODE_ncommand only asparsewrites it (closes #2361). A number written with an underscore, a+or a leading zero, or naming a byte that has an op code, raisesinvalid string command: <command>, where it was read as a byte. So does a negative number, one above 255, a name followed by no digits and a name with more than whitespace ahead of it, where each raised a bareValueErrororOverflowError.script.serializeandtaproot.serializestrip ASCII whitespace alone around a string command (closes #2363). A command padded with U+001C to U+001F raisesinvalid string command: <command>, where it was taken for the command it wraps.Act on either if you catch
OverflowErrorfromscript.serialize, or write a string command other than asparsedoes: each refusal is aBTClibValueError.The amount and fee-rate readers read ASCII digits and strip ASCII whitespace alone (closes #2360):
valid_btc_amount,valid_sats_amount,FeeRate.from_sats_per_vbyteandFeeRate.from_btc_per_kvbyte, and what reads an amount through them,sats_from_btc,btc_from_satsandTxOut.from_dictamong them. A string written in digits outside ASCII, U+0661 U+0660 or U+FF11 U+FF10 for ten among them, or padded with a characterstr.isspacecounts beyond space, tab, newline, carriage return, vertical tab and form feed, is refused withBTClibValueError. So is an underscore in afrom_sats_per_vbytequote, or in afrom_btc_per_kvbyteone withround_up, where it read as the digits around it.Act on it if you hand these functions such text: convert the digits to ASCII and strip the padding first.
utils.int_from_integerandutils.hex_stringrefuse a0xstring whose digits are not ASCII hex asinvalid hex integer: what follows 0x is not ASCII hex digits(closes #2353), whereint()read0x1_0, and0xfollowed by fullwidth or Arabic-Indic digits, as 16, and refused the rest asinvalid hex integer: '<input>'. Only ASCII whitespace is stripped. A0xstring padded after its digits with U+00A0, U+3000 or any other characterstr.isspacecounts is refused asinvalid hex integerabove; the same padding ahead of the0x, or around a string without one, is refused bybytes.fromhex, asinvalid hex string: <its message>.Act on it if you pass such a string, or match on the text of this refusal: pass ASCII hex digits, and match
invalid hex integeralone. It is still aBTClibValueError, so anexcepton that class is unaffected.A network name is stripped of ASCII whitespace alone (closes #2373).
network.validated_network_name,network.network_from_nameand everynetwork: strparameter that reads its name through them refuse a name padded with U+00A0, U+3000, U+2028, U+001C or another characterstr.isspacecounts beyond space, tab, newline, carriage return, vertical tab and form feed, withunknown network, where it was taken for the name it wraps.network.normalized_network_namerefuses nothing and leaves that padding in place.Act on it if you pass network names padded that way: strip them first.
The amount and fee-rate readers refuse a leading
+(closes #2372):valid_btc_amount,valid_sats_amount,FeeRate.from_sats_per_vbyteandFeeRate.from_btc_per_kvbyte, and what reads an amount through them."+1"raisesBTClibValueError, where it read as 1. The+of an exponent,"1e+1", is still read.Act on it if you hand these functions a signed positive string: drop the
+first.int_from_json_number, andBlockHeader’sversionandnoncethrough it, refuse a str and bytes (closes #2371):"1"andb"1"raiseBTClibTypeError, where they read as 1. A Decimal or a Fraction that is not whole raisesBTClibValueError, where it was truncated. ABTClibValueErrorout of it readsinvalid <field>: not a whole number, with no value quoted.Act on it if you pass a number as text: pass the int.
ScriptPubKey.p2shrefuses a redeem script longer thanMAX_SCRIPT_ELEMENT_SIZE(closes #2381), withBTClibValueErrorreadingredeem script exceeds size limitand the length, where it returned the script_pub_key of an output nothing can spend.Act on it if you build p2sh outputs from scripts that long:
p2wshtakes them, a witness script not being held to the element size.The amount and fee-rate readers spell a number as Bitcoin Core’s
ParseFixedPointdoes (closes #2378):valid_btc_amount,valid_sats_amount,FeeRate.from_sats_per_vbyteandFeeRate.from_btc_per_kvbyte, and what reads an amount through them. A leading zero before another digit ("01","00","01e1") and a point without a digit on both sides of it (".5","1.",".5e1") raiseBTClibValueError, where they were read as the number they spell;valid_sats_amountread"01"and"00".Act on it if you hand these functions such text: write
"1","0.5"and"1.0".b58.p2shrefuses a redeem script longer thanMAX_SCRIPT_ELEMENT_SIZE(closes #2383), with theBTClibValueErrorofScriptPubKey.p2sh, where it returned the address of an output nothing can spend.Act on it as on the
ScriptPubKey.p2shbullet.ScriptPubKey.p2wsh,b32.p2wshandb58.p2wsh_p2shrefuse a witness script longer thanMAX_SCRIPT_SIZE(closes #2384), withBTClibValueErrorreadingwitness script exceeds size limitand the length, where each returned the script_pub_key or the address of an output nothing can spend.Act on it if you build p2wsh outputs from scripts that long: no spend of one is valid, and a tapscript is not held to
MAX_SCRIPT_SIZE. This bounds thep2wshtheScriptPubKey.p2shbullet points to, and Bitcoin Core relays a p2wsh spend only while its witness script is at most 3600 bytes, itsMAX_STANDARD_P2WSH_SCRIPT_SIZE, a policy limit btclib does not apply.FeeRate.from_sats_per_vbyterefuses a rate above MAX_MONEY satoshi per virtual byte (closes #2385), withBTClibValueError, where it built theFeeRate: no fee exceeds MAX_MONEY and no transaction is under a virtual byte, so nothing can pay such a rate.Act on it if your code can pass a rate that large: catch
BTClibValueErrorthere.FeeRate(sats_per_kvbyte=...)refuses a rate above MAX_MONEY satoshi per virtual byte (closes #2389),2_100_000_000_000_000_000sat/kvB, withBTClibValueError, where it built theFeeRate: the boundfrom_sats_per_vbyteholds a quote to, held by the constructor too.Act on it as on the
from_sats_per_vbytebullet above.
v2026.9.24¶
Breaking changes¶
An address is built from a
btclib.key.PubKeyData, not from any spelling of a key (issue #1188). Atv2023.7.12,btclib.b58.p2pkh(key: Key, network: str | None = None, compressed: bool | None = None),btclib.b58.p2wpkh_p2sh(key: Key, network: str | None = None)andbtclib.b32.p2wpkh(key: Key, network: str | None = None)took theKeyunion –int, bytes, str, BIP32KeyData, Point, withstrreading as hex octets, as a WIF or as an extended key – and they arep2pkh(key: PubKeyData),p2wpkh_p2sh(key: PubKeyData)andp2wpkh(key: PubKeyData)now, the key carrying the network the arguments used to supply.ScriptPubKey.p2pk,.p2pkh,.p2ms,.p2wpkhand.p2trnarrow the same way, and thenetworkandcompressedargumentsp2pk,p2pkhandp2mscarried go with it;script.taproot.output_pubkeyandinput_script_sigtake aPubKeyDatainternal key;btclib.wallet.KeyWalletand itsaddtake abtclib.key.PrvKeyDataor aPubKeyData, which is what says whether the wallet can sign for the address it hands back.Act on it wherever you passed a key to one of them.
btclib.key.PubKeyData(sec, network)wraps SEC octets or their hex;btclib.key.PrvKeyData(q, network, compressed).pubderives the public key of a scalar andbtclib.b58.prv_key_data_from_wif(wif).pubthat of a WIF; andbtclib.key.PubKeyData(*btclib.bip32.pub_keyinfo_from_xkey(xkey))is the extended-key spelling. Where the key was a public onecompressedfiltered the octets handed over rather than converting them, so the form aPubKeyDatacarries is what it used to select andPubKeyData.is_compressedanswers it; where the key was a private one it chose which SEC form to derive, andPrvKeyData.compressedis that choice. A private key no longer reaches an address builder unannounced, which is the point:SECURITY.mdpublishes that the Python scalar multiplication is not constant-time.ScriptPubKey.p2mstakeslexicographic_sortingthird now, wherenetworkstood, so a network passed there by position reaches the sorting flag instead: pass the flag by keyword.btclib.to_prv_keyandbtclib.to_pub_keyare gone (closes #1188). Atv2023.7.12the first declaredPrvKey = Union[int, bytes, str, BIP32KeyData],PrvkeyInfo = Tuple[int, str, bool]andprv_keyinfo_from_prv_key(prv_key: PrvKey, network: str | None = None, compressed: bool | None = None), and the secondKey = Union[int, bytes, str, BIP32KeyData, Point],PubkeyInfo = Tuple[bytes, str],point_from_key(key: Key, ec: Curve = secp256k1),pub_keyinfo_from_key,pub_keyinfo_from_pub_keyandpub_keyinfo_from_prv_key, each of the last three with that same(network, compressed)pair. Importing either module raisesImportError.Act on it wherever you imported one of those names.
btclib.key.PrvKeyData(q, network, compressed)is the recordprv_keyinfo_from_prv_keyanswered andbtclib.key.PubKeyData(sec, network)the onepub_keyinfo_from_pub_keydid, each carrying the fields the tuples held;btclib.key.PrvKeyData(q).pubispub_keyinfo_from_prv_key.btclib.curves.scalar_from_prv_keyreads a scalar andbtclib.curves.point_from_pub_keya public key, which ispoint_from_keyfor the half the caller holds. TheKeyunion has no replacement by design: a caller states which half of a key pair it has, rather than leaving a size or a format to decide it.ecc.ssa.verify,verify_,batch_verify,batch_verify_andecc.dsa.verify,verify_raise on a structurally invalid signature or public key instead of answeringFalse(issue #2170): a wrong-length BIP340 signature or public key, or one spelled in a way no conversion accepts, now raisesBTClibValueErrororBTClibTypeError, matching BIP340’s own reference and the bindings these modules delegate to. A well-formed signature or key that is merely not authentic – a scalar out of range, a key that does not lift, a failed equation – still answersFalse, and so doesdsa.verify’s own malformed DER encoding, which stays outside this change.Act on it wherever a caller treats
Falsefrom one of these functions as proof of nothing but a forged signature: a caller that used to readFalsefor a truncated or malformed key or signature now sees an exception. Parse the signature first –ssa.Sig.parse/dsa.Sig.parse, which already raise – to tell a malformed argument from a forged signature ahead of callingverify.ecc.bms.verify,ecc.borromean.verify,ecc.pedersen.verify,ecc.dleq.verify_proofandecc.rangeproof.verifyraise on a structurally invalid argument instead of answeringFalse(closes #2170), which is the same split over the rest ofecc. An address that decodes to no address, a base64 spelling that is no 65-octet compact signature, octets that are no borromean signature over the rings given or no rangeproof at all, a point spelled in a way no conversion reads, a proof that is not 64 octets, and anIntegerthat is no number, each raiseBTClibValueError. What staysFalseis everything well formed that merely does not verify: another key’s address, a recovery flag or a scalar out of range, a ring shape that is not the signature’s, and an opening that does not recompute the commitment.Act on it wherever a caller treats
Falsefrom one of these as proof of nothing but a bad signature.bms.Sig.b64decode,borromean.BorromeanSig.parse,rangeproof.RangeProof.parseandcurves.point_from_pub_keyare the parses that answer the structural question on their own, ahead of the call, for a caller that wants to keep filtering on a bool.A message whose size the function declares raises where it is not that size (issue #2170):
ecc.dsa.verify_takes a digest ofhf’s size andecc.dleq.verify_proofa 32-octet message, and any other length now raisesBTClibValueErroron either. Both arms ofdsa.verify_are covered, the one the libsecp256k1 bindings answer and the pure-Python one. A message of no declared size is untouched and still answersFalse:ecc.dsa.verify,ecc.ssa.verify,verify_and the batch spellings,ecc.bms.verify,ecc.borromean.verify, andecc.rangeproof.verify’sextra_commit.Act on it wherever a caller passes a truncated or foreign hash to a prepared spelling — reading
Falsefor it today and an exception after.hashes.reduce_to_hlen(msg, hf)is what produces the digest those functions declare; a caller holding one from elsewhere checks its length, or calls the unpreparedverify, which reduces the message itself and has no length to miss.ecc.rangeproof.assert_as_validandecc.rangeproof.rewindraiseBTClibValueErrorfor aRangeProofwhose stateRangeProof.assert_validrefuses, andecc.rangeproof.verifyanswersFalsefor one (closes #2182), which is whatecc.bmsanswers for aSiga caller built the same way.check_validity=Falseis what makes such a proof reachable: a header this format has no octets for, a body the mantissa does not describe, amin_valuepast the eight octets of that field or a ring commitment wider than the curve’s own are each that state, and the last two raised anOverflowErrorfromint.to_bytes– whichverifydid not catch either.Act on it wherever a caller builds a proof rather than parsing one.
RangeProof.assert_validis the same refusal ahead of the call, and the constructor runs it unlesscheck_validity=Falsesays not to.bip322.verifyraises on a structurally invalid address or signature instead of answeringFalse(closes #2181), which carries the same split outsideecc. A string that decodes to no address, and text written in neither BIP322’s own base64 encodings nor the 65-octet compact one the legacy variant carries, each raise rather than answer. What is raised is aBTClibValueErroror aBTClibRuntimeError, the parse layer answering either for text it cannot read. What staysFalseis everything well formed that is merely not authentic: another key’s address, a signature for another message, a script the engine does not satisfy, an inconclusive one, a compact signature offered for an address that is not p2pkh, and one offered wherelegacy=Falseasked for BIP322 proper.Act on it wherever a caller treats
Falsefrombip322.verifyas proof of nothing but a bad signature. Ahead of the call,script.ScriptPubKey.from_addressanswers the structural question about the address on its own, andbip322.Sig.b64decode– orecc.bms.Sig.b64decodefor the legacy variant – about the signature, for a caller that wants to keep filtering on a bool: that caller catches both classes, either being what an unreadable signature answers.
CHANGELOG.md has why each of these changed, and the rest of what this cycle changed.
v2026.9.13¶
Breaking changes¶
btclib.ecc.pedersenandbtclib.ecc.rangeprooftake the generator they work at (closes #1986).pedersen.commit(r, v, ec: Curve = secp256k1, hf: HashF = sha256)– the spelling atv2023.7.12but forrandv, which widened toInteger– derivedHfromecandhfand iscommit(r, v, gen: Point, ec: Curve = secp256k1)now;pedersen.verify(r, v, commitment, ec, hf)and thepedersen.assert_as_validbeside it takegenafter the commitment and nohf. Inecc.rangeproof,sign_public_value(blind, value, nonce)andRangeProof.nonce_chain(commitment, value, nonce, message)take it fourth, ahead ofmessagein the second, andRangeProof.pubk_rings(commitment)takes it second.Act on it if you called any of them.
btclib.ecc.pedersen.second_generator()is the generator those calls used to derive, so passing it keeps every answer the same;btclib.ecc.pedersen.second_generator(ec, hf)is the argument for a curve or a hash function other than the defaults, andbtclib.ecc.pedersen.generator_from_seed(seed, blind)is the other way to make one. CHANGELOG.md has why the generator became an argument, and the rest of what this cycle changed.
v2026.9.10¶
Breaking changes¶
ssa’s sign-to-contract tags change (closes #1680). They weres2c/bip340/pointands2c/bip340/data; they are nows2c/schnorr/pointands2c/schnorr/data, matching bitcoin-core/secp256k1#1140’s spelling.Act on it if you hold a BIP340 sign-to-contract commitment made before this release: it no longer opens, and there is no version byte to switch on. Re-derive it with the new tags.
A WIF is
btclib.b58’s object now, notbtclib.to_prv_key’s (issue #1188).btclib.b58.wif_from_prv_key(prv_key: PrvKey, network: str | None = None, compressed: bool | None = None)took the widePrvKeyunion – an int, an octets scalar, a WIF, a BIP32 xprv, or aBIP32KeyData– and narrows towif_from_prv_key(prv_key: Integer, network: str = "mainnet", compressed: bool = True), an int, its octets or their hex only. Reading a WIF back is a new function,btclib.b58.prv_key_data_from_wif, answering abtclib.key.PrvKeyDatarather than the(int, str, bool)tupleto_prv_key.prv_keyinfo_from_prv_keyused to for one.to_prv_key.PrvKey,int_from_prv_keyandprv_keyinfo_from_prv_keyno longer accept a WIF at all: a WIF handed to any of them is refused as the octets it is not.Act on it if you called
wif_from_prv_keywith a WIF, an xprv or aBIP32KeyDatato re-encode it under a different network or compression, or if you passed a WIF toto_prv_key.int_from_prv_keyorprv_keyinfo_from_prv_key.btclib.b58.prv_key_data_from_wif(wif, network, compressed).qreads the scalar out of a WIF; an xprv or aBIP32KeyDatastill goes throughto_prv_key, unaffected.btclib.ecc.bms.signandbtclib.bip322.signtake abtclib.key.PrvKeyData, not aPrvKey(issue #1188). Both tookprv_key: PrvKey–bms.sign(msg: Octets, prv_key: PrvKey, addr: String | None = None)at v2023.7.12, unchanged since – and answered the network and the compression flag by parsing whatever spelling was handed in; both now take the already-parsedPrvKeyDataand raiseBTClibTypeErrorfor anything else, a WIF and a bare scalar included.Act on it if you called either with a WIF, an xprv, a
BIP32KeyDataor a bare scalar.btclib.b58.prv_key_data_from_wif(wif)reads a WIF into the object both now want; a bare scalar isbtclib.key.PrvKeyData(q, network, compressed).btclib.ecc.bms.gen_keysno longer takes aprv_keyargument (issue #1188). It wasgen_keys(prv_key: PrvKey | None = None, network: str | None = None, compressed: bool | None = None)at v2023.7.12, drawing a random key whenprv_keywasNoneand re-deriving the pair from it otherwise; it isgen_keys(network: str = "mainnet", compressed: bool = True)now, drawing only.Act on it if you called
gen_keyswith an explicitprv_key.btclib.b58.wif_from_prv_key(prv_key, network, compressed)andbtclib.b58.p2pkhon the WIF it returns are the pairgen_keysused to hand back for one.btclib.b32.p2wpkhno longer resolves a WIF (issue #1188). It tookkey: Keyat v2023.7.12 and resolved a WIF among the spellingsKeycovers;b32sits belowb58, which is where a WIF is read now, and has no way to reach it.Act on it if you called
b32.p2wpkhwith a WIF.btclib.b58.prv_key_data_from_wif(wif).pub.secreads the SEC octetsp2wpkhstill takes.EsploraFetcherasks which chain the explorer serves, before the first fetch (closes #1674). An explorer on another chain than the label is now aBTClibValueErrorwhere it used to be addresses for coins that are not there.Act on it if a caller has checked the explorer’s chain by other means, or already knows which chain it is asking:
EsploraFetcher(base_url, verify_network=False)is the previous behaviour.An extended key is no longer a key spelling (issue #1188).
to_prv_key.PrvKeywasint | bytes | str | BIP32KeyDataat v2023.7.12 and isint | Octets;to_pub_key.PubKeywasbytes | str | BIP32KeyData | Pointand isOctets | Point | PreparedPoint;Keywasint | bytes | str | BIP32KeyData | Pointand isint | Octets | Point | PreparedPoint. So an xprv or an xpub – as Base58Check text or as aBIP32KeyData– is refused wherever one of the three is taken:b58.p2pkh(key: Key, ...),b58.p2wpkh_p2sh(key: Key, ...)andb32.p2wpkh(key: Key, ...), all three unchanged in signature since v2023.7.12,dsa.verify(msg, key, sig, ...)and itsassert_as_validtwin, thescript.script_pub_keyconstructors,wallet.KeyWallet.add, andto_prv_key/to_pub_key’s own converters.Act on it if you pass an extended key to any of them.
bip32reads one:bip32.prv_keyinfo_from_xprv(xprv)answers the(scalar, network, compressed)triple,bip32.point_from_xpub(xpub)the point, andbip32.pub_keyinfo_from_xkey(xkey)– new in this release – the SEC octets and the network from either half of a pair, which is what the address builders and the script constructors take.b58.p2pkh(xprv)becomesb58.p2pkh(*bip32.pub_keyinfo_from_xkey(xprv)), the network travelling with the octets because a SEC key names none.bip44.address_from_der_path,slip132.address_from_xkeyand thewalletclasses still take an extended key and are unaffected: each performs that call for you.Act on it too if you match on the text of the refusal. An extended key on the wrong network now leaves
bip32asnot a mainnet key: version 0x..., where thecontextlib.suppressaround the BIP32 parse used to letto_pub_key’s “not a private or public key for mainnet” out instead.ConsensusParamstakes abip30_unspendableargument (closes #1695), the blocks Bitcoin Core’sIsBIP30Unspendablenames. It has no default, as no field of the row has.Act on it if you build a row of your own for a custom chain: pass
bip30_unspendable=(), which is what every chain but mainnet carries.bip32’s refusals of an extended key’s public half are lower case (closes #1719).pub_keyinfo_from_xpubraisesuncompressed SEC / compressed BIP32 mismatchwhere it raisedUncompressed SEC / compressed BIP32 mismatch, and both it andpub_keyinfo_from_xkeyraisenot a <network> key: version 0x...where they raisedNot a <network> key: version 0x.... Each is the wordingprv_keyinfo_from_xprvuses for the same fault on the private half.Act on it if you match on the text of either refusal. One pattern serves both halves of a pair, so a match written for the private half needs no second spelling for the public one.
to_prv_key.int_from_prv_keyandto_pub_key.point_from_pub_keymove tobtclib.curves(issue #1188).int_from_prv_key(prv_key: PrvKey, ec: Curve = secp256k1)– that spelling at v2023.7.12 – is removed, andbtclib.curves.scalar_from_prv_key(prv_key: Integer, ec: Curve = secp256k1)is the call: same answer, same spellings, andIntegeris the unionPrvKeyhad already narrowed to.point_from_pub_key(pub_key: PubKey, ec: Curve = secp256k1)keeps its name and its signature and is imported frombtclib.curvesnow, as isPubKeyitself;btclib.to_pub_keyexports neither.Act on it if you import either name from a converter:
from btclib.curves import point_from_pub_key, scalar_from_prv_key, andfrom btclib.curves import PubKeyfor the annotation.point_from_key,pub_keyinfo_from_key,pub_keyinfo_from_pub_key,pub_keyinfo_from_prv_key,prv_keyinfo_from_prv_key,PrvKeyandKeystay where they are.Act on it too if you match on the text of a private key’s refusal.
int_from_prv_keyanswered a type no spelling has withBTClibTypeError("not a private key")and octets that are no scalar withNotAPrvKeyError("not a private key: not octets (...)");scalar_from_prv_keyrefuses both throughbytes_from_octets, asinvalid octets type: floatandinvalid hex string: ...or a size, and a bool asint_from_integer’snon-integer: True. Every one is still aBTClibTypeErroror aBTClibValueError, so anexcepton either class is unaffected.bip32.pub_keyinfo_from_xpubanswers aboutcompressedonce the key has decoded (closes #1721).pub_keyinfo_from_xpub("not an xkey", compressed=False)raisesBase58 string contains invalid characters, the decode’s own refusal, where the compression mismatch answered first;prv_keyinfo_from_xprvbeside it reads in that order.Act on it if you match on the text of that mismatch to catch a bad key: it answers for a key that decoded, so text that is no extended key wants the decode’s own refusal matched instead. The mismatch reads
uncompressed SEC / compressed BIP32 mismatchin this release, andUncompressed SEC / compressed BIP32 mismatchat v2026.9.3 and at v2023.7.12, where reading an extended key wasto_pub_key’s.btclib.script.ScriptPubKeyrefuses anetworkthat is not a string withBTClibTypeError(closes #1662).assert_valid— which__init__runs unlesscheck_validity=False, and whichTxOut,sig_hashand the descriptor and wallet lookups run again on a script handed to them — puts the name throughbtclib.network._validated_network_name, which raisesBTClibTypeError, aTypeError, where it raisedBTClibValueError: unknown network: None.Act on it if you catch
BTClibValueErroraround building or validating aScriptPubKeyto handle a name you have not checked is astr: catchBTClibException, which is the base of both, or check the type yourself. Astrno network answers to is still aBTClibValueError, and the names accepted are wider than before —" MainNet "resolves here as it does everywhere else in the library.btclib.bolt11.Bolt11Invoiceaccepts the network-name spellings the rest of the library does (closes #1671)." MainNet "and"MAINNET"now resolve to"mainnet"in thenetworkfield, where the defaultcheck_validity=Truerefused them outright; built withcheck_validity=False, two spellings of one network now compare equal and hash alike, where they used to compare unequal and hash apart.Act on it if you relied on
Bolt11Invoice(" MainNet ", ...)raising, or on two differently-spelled invoices built withcheck_validity=Falsebeing distinct in a set or as dict keys: they now collapse to one.btclib.bolt11.Bolt11Invoice.signaccepts the same network-name spellings, and refuses the rest withBTClibValueError(closes #1775)." MainNet "now resolves to"mainnet"where it raised a bareKeyErrorbeforesignever reachedBolt11Invoice.__init__’s own coercion; a name no lightning network answers to,"testnet4"included, now raisesBTClibValueErrorwhere it raised that same bareKeyError.Act on it if you relied on
Bolt11Invoice.sign(..., " MainNet ", ...)raising, or if you catchKeyErroraroundsignto detect a network it does not recognize: catchBTClibValueError, or theBTClibExceptionit is a subclass of, instead.btclib.descriptors.Descriptorand every fragment class built on it accept the network-name spellings the rest of the library does (closes #1776)." MainNet "now resolves to"mainnet"in thenetworkfield of a directly constructed descriptor —RawDescriptor(script=..., network=" MainNet ")and the like — where the field kept it exactly as given; two spellings of one network now compare equal and hash alike, where they used to compare unequal and hash apart.Act on it if you rely on two differently-spelled descriptors built this way being distinct in a set or as dict keys: they now collapse to one. The parse path,
descriptors.parse, already normalized the name and is unaffected.A Lightning invoice stating a feature without the features BOLT9 says it depends on is refused (closes #1655).
bolt11.Bolt11Invoice.from_invoiceandassert_validaccepted one, where BOLT9’s Dependencies column hasbasic_mppdepend onpayment_secret,zero_fee_commitmentsonoption_channel_type,option_zeroconfonoption_scid_alias,option_simple_closeonoption_shutdown_anysegwit, andoption_onion_messages_only_channelsonoption_onion_messages.Act on it if you decode invoices whose
9field is short of one: the refusal isBTClibValueError: unmet feature dependencies: basic_mpp requires payment_secret, naming every pair it found.btclib.bolt9.FEATURE_DEPENDENCIESis that column andbtclib.bolt9.unmet_dependenciesthe same lookup over any feature vector. Either bit of a pair states its feature, so an invoice offeringpayment_secretat bit 15 meetsbasic_mpp’s dependency as one requiring it at bit 14 does.borromean.signandborromean.assert_as_validcompute a differente0(closes #1940). The preimage has beenm || r_0 || ... || r_lastsincev2023.7.12, the message hash before the ring points; it isr_0 || ... || r_last || mnow, matching secp256k1-zkp’srangeproofmodule.Act on it if you hold a borromean signature this module wrote: re-signing is the whole of the migration, and nothing else is on offer. There is no version byte in the wire format to switch on, and
signandassert_as_validcompute the preimage the same way every time, so no argument makes either of them read an older signature. CHANGELOG.md has why the break was worth paying.
Worth knowing, though nothing raises¶
psbt_signer_contract.optional_protocolsreturnsOptionalProtocols, aNamedTuple, in place of a plain tuple (closes #1624). Act on it if you read the result by index rather than by name: a field read by name keeps answering the same question after the next optional protocol is inserted, where an index answers whatever question now sits at that position.Unpacking, indexing,
isinstanceagainsttupleand comparing against a plain tuple ofboolall answer as before, so this is no breaking change;type(...) is tupleandrepr(...)do not, which is what to check if either is what you read.
v2026.9.3¶
Breaking changes¶
btclib.__author__,btclib.__author_email__andbtclib.__license__no longer exist (closes #1507). Each duplicated a factpyproject.tomlalready states.Act on it if you read any of the three:
btclib.__author__andbtclib.__author_email__’s replacement isimportlib.metadata.metadata("btclib")["Author-email"], which carries both as one"name <email>"string;btclib.__license__’s isimportlib.metadata.metadata("btclib")["License-Expression"], which answers"MIT"rather thanbtclib.__license__’s former"MIT License".btclib.__version__andbtclib.__copyright__are unaffected.Networktakes aconsensusrow, and its dict carries aconsensuskey (closes #1578).btclib.network.Networkgained a field naming the consensus parameters of the chain it spells keys for,to_dictwrites the row’s name, andfrom_dictreads it back.Act on it if you build a
Networkyourself or load one from a dict you stored. The constructor takes it as a required keyword argument —Network(..., consensus=CONSENSUS_PARAMS["mainnet"]), frombtclib.consensus— and a dict without the key raisesBTClibValueError: missing network field: consensus, a dict naming a row that does not existBTClibValueError: unknown consensus parameters. Add"consensus": "mainnet"to a stored dict, spelled with the name of the network it is. ReadingNETWORKS, and everything that resolves a network by name or by prefix, is unaffected.btclib.p2p.handshake.Version’sversionfield defaults to Core’s own protocol version, not zero (closes #1582). Built with no explicitversion, it used to serialize0.Act on it if you build a
Versionwith no explicitversionand read back0, or compare its serialization against a fixed buffer that assumed one:Version().versionis nowbtclib.p2p.limits.PROTOCOL_VERSION,70016.Version.parseis unaffected, reading whatever a peer sent rather than this default.psbt_signer_contract.optional_protocolsanswers for a third protocol, and answers it in the middle (closes #1588). It reportedAddressDisplayandMessageSigner; it now reportsAddressDisplay,WalletPolicyAddressDisplayandMessageSigner, in that order.Act on it if you call it. Before:
displays_address, signs_message = optional_protocols(signer)
Now:
displays_address, displays_policy_address, signs_message = ( optional_protocols(signer) )
Unpacking the old shape raises
ValueError: too many values to unpack (expected 2, got 3), which is the loud case. The quiet one is an index: the new element is inserted rather than appended, sooptional_protocols(signer)[1]used to answer whether the signer signs messages and now answers whether it displays a wallet-policy address. Read the last element for the message signer, or unpack.btclib.fetch.fetcher.Fetchergained a fourth abstract method,get_block_header(closes #1132). It answers a header by height, checked withBlockHeader.assert_validandassert_valid_powon arrival.Act on it if you subclass
Fetcheryourself, rather than usingBitcoinCoreFetcherorEsploraFetcher: an existing subclass that answered the previous three questions can no longer be instantiated. Construction raisesTypeError, namingget_block_headeras the method it has no implementation for. Match on that name and not on the sentence around it – CPython reworded the message in 3.12, and this package supports 3.10. Add the method, answering abtclib.block.BlockHeaderfor a non-negativeheight: int.Bip21.parse’slightning=parameter is typed, and no longer one of the parametersBip21.otherskeeps untyped (closes #1585). It used to be swept in like any other unrecognised parameter; it is now parsed into abolt11.Bolt11Invoiceand cross-checked against the address it rides beside.Act on it if you read
uri.others["lightning"]or iterate.othersexpecting that key: it is gone, anduri.lightningis where the value is now, typed rather than a raw string. Act on it too if you parse a URI whoselightning=value is not a well-formed, internally consistent invoice:Bip21.parsenow raises where it used to store the string unexamined,othershaving no validation to fail.btclib.hwirefuses anetworkthat is not a string withBTClibTypeError(closes #1631).HwiSigner(network=...)andenumerate_devices(network=...)put the name throughbtclib.network._validated_network_name, which raisesBTClibTypeError— aTypeError— whereHwiSignerraisedBTClibValueError: unknown network: None.Act on it if you catch
BTClibValueErroraround either call to handle a name you have not checked is astr: catchBTClibException, which is the base of both, or check the type yourself. Astrno network answers to is still aBTClibValueError, and the names accepted are wider than before —" TestNet4 "resolves here as it does everywhere else in the library.A Lightning invoice setting an even feature bit BOLT9 does not assign is refused (closes #1637).
bolt11.Bolt11Invoice.from_invoiceandassert_validaccepted one, where BOLT9’s rule is that a reader meeting a feature bit it does not know fails on the even half of a pair and ignores the odd half.Act on it if you decode invoices carrying such a bit: the refusal is
BTClibValueError: unknown even feature bits: ..., naming them.btclib.bolt9.FEATURE_NAMESis the table that answers it, the even bit of each pair BOLT9 assigns and the name the BOLT gives it, andbtclib.bolt9.unknown_even_bitsis the same lookup over any feature vector. An unknown odd bit is carried as it was.btclib.fetchandbtclib.walletrefuse anetworkthat is not a string withBTClibTypeError(closes #1641).Fetcher.__init__andWallet.__init__— the bases every backend and every wallet calls up into — put the name throughbtclib.network._validated_network_name, which raisesBTClibTypeError, aTypeError, where each raisedBTClibValueError: unknown network: None.Act on it if you catch
BTClibValueErroraround building a fetcher or a wallet to handle a name you have not checked is astr: catchBTClibException, which is the base of both, or check the type yourself. Astrno network answers to is still aBTClibValueError, and the names accepted are wider than before —" Testnet "resolves here as it does everywhere else in the library.
Worth knowing, though nothing raises¶
btclib.orgis no longer this project’s site, and this repository serves none (issue btclib-org/.github#530). The domain is the btclib-org organization’s page now, and it says what the organization is rather than documenting the library.Act on it if you have
btclib.orgbookmarked or linked: the documentation is https://btclib.readthedocs.io/, which[project.urls] homepagenames and which the package index shows as this project’s home. Nothing in the library changes, and no import, symbol or behaviour moves with it.
v2026.8.29¶
Worth knowing, though nothing raises¶
bytes_from_octetsreturnsbytes, and not the buffer it was handed (closes #1255). Abytearrayor amemoryviewcame back as itself, so what a caller got was the object it had passed in and the-> byteson the signature was not what the function did.Act on it if you pass a
bytearrayor amemoryviewtobtclib.utils.bytes_from_octetsand then use what comes back as a mutable buffer: writing through it raisesTypeError: 'bytes' object does not support item assignment, andisinstance(result, bytearray)is now False. Abytesargument and a hexstrare unaffected, and anything that reads the result as octets reads it unchanged.The other direction is what the change is for and asks nothing of you. A
BIP32KeyDatabuilt from a bytearray chain code kept that bytearray as its field, so the xprv the key serialized to moved when the caller wrote a byte into a buffer that was its own to write to; what a field built through this coercion holds is now a copy.
v2026.8.27¶
Breaking changes¶
A bool is no longer accepted as an integer (issue #1206), which matters most where it was accepted as a key:
b58.wif_from_prv_key(True) # was a WIF of the key 1
Act on it if you pass
TrueorFalsewhere an integer is expected — a key, a multiplier, a curve parameter, anything typedInteger. The class is alwaysBTClibTypeError; the message depends on which check the value reaches first, so match on the class and not on the text. A key is the case to watch:wif_from_prv_key(True)says “not a private key” andp2pkh(True)“not a private or public key”, wheremult(True)anddsa.sign(msg, True)say “non-integer: True”.A BIP340 x-only key is where that lands hardest,
ssahaving answered about a bool rather than refusing one —Trueas the key at x = 1,Falseas a complaint about the coordinate that theverifyspellings swallow. All nine entry points raise aBTClibTypeErrornow:point_from_bip340pub_keywhere it returned that point, the fourverifyspellings where they returned False, and the fourassert_spellings where they raised aBTClibRuntimeErrorforTrueand aBTClibValueErrorforFalse. Anexceptwritten for either stops catching this.An
IntEnumis unaffected and stays an integer. CHANGELOG.md has why a bool was reaching a key at all, and what the two arms did with it.A
Point’s coordinates are no longer accepted as bools (issue #1249).is_on_curve((x, False))used to answer about the point at infinity for any x,False == 0in Python;is_on_curve((True, y))about the point at x = 1. Act on it if you build aPointtuple from a value that could be a bool — a JSON decoder’strue/falseincluded:point_from_pub_key,point_from_bip340pub_key,PreparedPointandbytes_from_pointall raiseBTClibTypeErrornow, on every curve. CHANGELOG.md has which coordinate the message names.borromean.signrefuses a private key or a nonce outside 1..n-1 (issue #1243). Neither sequence was read as a scalar, so a key of 0, ofnor ofq + nsigned, where every other signer ineccrefuses all three.q + nis the one to look for in your own code: step 2’s own% ec.nreduced it toq, so it produced a signature that verifies, and it now raisesBTClibValueError: private key not in 1..n-1. A nonce ofk + nwas reduced by the same line and is refused by the same check.borromean.sign(msg, ks, idx, [q + secp256k1.n], rings) # signed borromean.sign(msg, ks, idx, [q % secp256k1.n], rings) # reduce first
Act on it if you build a key or a nonce by addition and rely on the reduction. An
intkey already in 1..n-1 signs exactly as it did.Widened in the same call:
ksandsign_keysareSequence[Integer]where they wereSequence[int], so a scalar held as itsn_sizeoctets or as hex is taken here asmultanddsa.signtake it. Those spellings used to leave Python’s ownOverflowErrorandTypeError.sign_key_idxis stillSequence[int]: it indexes a ring.pedersen.commitrefuses a blinding factor of 0 mod n (issue #1250).commit(0, v)andcommit(ec.n, v)returnedv*H, a commitment with no blinding in it that anyone can recompute by guessingv, and now raiseBTClibValueError: invalid (unblinded) commitment: r is 0 mod n.assert_as_validraises the same error, recomputing throughcommit;verifyanswersFalseinstead of raising, as it already does for every other invalid(r, v).Act on it if you construct a blinding factor that can land on 0 mod n — the sum of two blinding factors chosen to cancel each other is the case to watch; a blinding factor drawn at random and never summed to that value is unaffected.
vis not checked:commit(r, 0)is untouched.eccno longer takes a WIF or an extended key as a private key (issue #1188). The entry points that took a private key however it was spelled — every one indsa,ssa,musig2,dleq,ecies,ellswiftand the three nonce modules,gen_keys,Signer,anti_exfil_signer_commitandanti_exfil_signamong them — took a WIF, an xprv, anintor octets. They now take anint, itsn_sizeoctets, or their hex.borromeanis not among them and never was: it asked for a sequence ofintoutright, and issue #1243’s bullet above is what gave it the same three spellings — never the WIF.dsa.sign(msg, wif) # was dsa.sign(msg, prv_keyinfo_from_prv_key(wif)[0]) # is
prv_keyinfo_from_prv_keyis the converter that decodes every spelling, and it answers the network and the compression flag beside the scalar; take the first of the three. The point is that the conversion is now a call you write, where it used to be a try-and-see inside the signer.Act on it if you hand one of those nine anything but a scalar.
ecc.bmsis not among them: message signing is bitcoin, so it still takes a WIF, an xprv and everything else it took, and everything below is about the nine and not about it.Refusals change with the input.
NotAPrvKeyErroris no longer raised by the nine — wrong-size octets, a non-hex string and a bad-checksum WIF arebytes_from_octets’ own complaints now — andbmsraises it exactly as before, so anexcept NotAPrvKeyErroraroundbms.signstays load-bearing while one arounddsa.signstops catching.One shape changes exception family: an extended public key spelled as a
BIP32KeyDatawas anInvalidPrvKeyError, which is aBTClibValueError, and is now aBTClibTypeError. The private one does not appear here because it was accepted before and is withdrawn, not re-messaged.except BTClibValueErrordoes not cover everything these nine raise — but it never did, a wrong type having always been aBTClibTypeError. If that is your catch, widen it toBTClibException; the advice is the same as it always was, and this change makes more inputs reach it.ecc.ssano longer accepts a BIP32 extended key as a BIP340 public key (issue #1188).BIP340PubKeywasBIP340PubKey = Integer | Octets | BIP32Key | Point | PreparedPoint
— with
BIP32Keyin it as far back asv2023.7.12— and is nowBIP340PubKey = int | Octets | Point | PreparedPoint
Act on it if you pass a public extended key — an xpub as text, the same text as ASCII bytes, or a public
BIP32KeyData— tossa.verify,ssa.verify_,ssa.assert_as_valid,ssa.assert_as_valid_,ssa.point_from_bip340pub_keyor the batch-verification entry points. That is the whole of the withdrawal: an xprv and a privateBIP32KeyDatawere refused before this change too, the first as octets it could not parse and the second by name.Convert it first. From a
BIP32KeyDatathe public key is.key, and from either text spelling it isBIP32KeyData.b58decode(xpub).key: 33 compressed SEC octets, which these still take. One check does not survive the conversion: an xpub handed to a non-secp256k1ecwas refused, its version bytes matched against the curve — as text the complaint that surfaced was about octets, as aBIP32KeyDatait was about the type. The 33 octets carry no version, so nothing compares them to the curve; what is left is the lift, which on a curve of the same size answers for about half of them and refuses the rest. Onsecp256k1, which is BIP340’s curve, the answer is the same as before.Everything else is unchanged, and one thing is wider: an
int, the p-size octets BIP340 defines, 33 or 65 SEC octets, their hex, aPointand aPreparedPointall still work, and abytearrayormemoryviewnow works at the p-size too, where before it worked only at the SEC sizes.Refusals move as well, and the one to act on is a class change. What the old dispatch could not tell apart it reported as a type error, and each of those is a value error now: a
Pointoff the curve, the point at infinity, a tuple that is malformed or out of range, a buffer of no key size, and a buffer of a key size that is no point. Code catchingBTClibTypeErroralone around any of them has to widen toBTClibValueErroror toBTClibException— which is the rule rather than the list, the list being what was measured. CHANGELOG.md has the wording changes, which need no action.fingerprintisbtclib.bip32’s, and takes a BIP32 key (issue #1188). It wasfrom btclib.to_pub_key import fingerprint fingerprint(key, network)
— the spelling as far back as
v2023.7.12— and is nowfrom btclib.bip32 import fingerprint fingerprint(xkey)
Act on it if you import it from
to_pub_key, if you pass anything that is not an extended key, or if you pass a network. Any extended key still works, SLIP132’szprvandupubamong them, and so does every spelling of one — the text, that text as bytes, or aBIP32KeyData. The first is an import change and nothing more. For the second, the fingerprint of a plain public key was only everhash160of its compressed SEC octets cut to four; take it directly, deriving the public key first if what you hold is a scalar or a WIF, which the old function accepted too.For the third, the argument refused a key whose version bytes named another network, and nothing inherits that. Reconstructing the check is a membership test rather than a name comparison: take the version — a
BIP32KeyDatahas.version, andBIP32KeyData.b58decodegets one from the text — and ask whether it is inxprvversions_from_network(net)for a private key orxpubversions_from_network(net)for a public one, which is the pair the argument chose between by the kind of key it had. Notnetwork_from_xkeyversion(...) == net: that reverse lookup answers “testnet” for the versions testnet, regtest, signet and testnet4 share, so a name comparison rejects a signet key for being signet, which is the trapto_prv_keyrecords as issue #207.psbt.psbt_utils.deserialize_txno longer acceptsNoneforinclude_witness(issue #1190). The annotation declaredbool | Noneand a comment calledNone“either encoding”; the code took the same strict arm forNoneas forFalse,not Nonebeingnot False. A third spelling of the second behaviour, and the only one whose documented meaning was never implemented. PassingNonenow raisesBTClibTypeErroras any other non-bool does.Act on it only if you call this function with
None, which no caller in this package did: passFalse, which is whatNonewas doing.Trueis unchanged and is still the default, and is the value that accepts either encoding.NETWORKS["regtest"].genesis_blockwas byte-reversed and is now Bitcoin Core’s value (issue #1203):0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206
where it read the same octets in the opposite order,
06226e46…f188910f. Nothing inside btclib reads the field, so addresses, WIF and the bip32 versions are unaffected, and no other network’s value moves. A caller that read it — seeding a regtest chain, or comparing againstgetblockhash 0— got a silent wrong answer rather than an error, and one that had compensated by reversing the octets itself has to stop doing so. CHANGELOG.md has why.The importable package moved from the repository root to
src/btclib/(issue #1322).import btclibresolves exactly as it did for anything installed from PyPI or from a built wheel; what moved is the checkout. A checkout is no longer importable straight from its own root, and a path inside this repository that named the package directly —btclib/…— now readssrc/btclib/….Act on it if your tooling imports from a checkout of this repository rather than from an installed distribution, or reads the package’s path directly rather than through
import btclib. CHANGELOG.md has every file the move touched.ssa.challenge_anddsa.recover_pub_key_no longer accept a bool (issue #1248), the same rule issue #1206 gave the rest of the library reaching two entry points it did not: both take a bareintrather than anInteger, sossa.challenge_(msg, True, x_K, ec, hf)read the bool as the x-coordinatex_Qanddsa.recover_pub_key_(True, msg_hash, sig)as the recovery id, each as if it had been passed1.Act on it if you pass
TrueorFalseaschallenge_’sx_Qorx_K, or asrecover_pub_key_’skey_id; both now raiseBTClibTypeError. CHANGELOG.md has the three wordings.branchandaddress_indexnow raiseBTClibTypeErrorfor a bool or any other non-integer, where they raisedBTClibValueError(issue #1403) –derive_from_account_andderive_from_account_range_, andderive_from_account/derive_from_account_rangethrough them. Both parameters were already refused, incidentally, by the string round trip_derive_from_accountandderive_from_account_range_build a der path with;is_integernow refuses them directly, before that round trip runs.Act on it if your code catches
BTClibValueError, rather than the common baseBTClibException, around a call passing one of these four functions abranchoraddress_indexthat is not a plainint.The same four functions’
max_indexnow raisesBTClibTypeErrorfor a bool, where it silently narrowed the accepted range instead of raising anything at all (closes #1413).max_index=Truemadederive_from_account_(xpub, 0, 0, max_index=True)answer the depth-5 key rather than fail,0 <= Trueholding arithmetically; a caller relying on0xFFFF’s default and passing a bool by mistake got a narrowed range rather than a caught one.Act on it if you pass a bool as
max_indextoderive_from_account_,derive_from_account_range_,derive_from_accountorderive_from_account_range; all four now raiseBTClibTypeErrorrather than silently narrowing what they accept.script.taproot’s internal key refuses a hybrid SEC prefix, on both arms (closes #1227).output_pubkeyandinput_script_sigtook a0x06/0x07-prefixed internal key withbtclib_secp256k1installed and refused the same octets without it, so which keys they accepted was decided bypip installrather than by btclib. Both now raiseBTClibValueError: invalid internal public key: hybrid SEC prefix 0x06(or0x07) regardless of which arm answers.Act on it if an internal key you pass to either is ever hybrid-prefixed — nothing in bitcoin produces one, so a signer’s own key material is unaffected; a hand-built or fuzzed test vector is where this shows. CHANGELOG.md has where the check runs and why.
Worth knowing, though nothing raises¶
A
bytearrayand amemoryvieware octets, and now the signatures say so (issue #1238).OctetsandStringname all four spellings, andInteger,PrvKey,PubKey,KeyandCommandare built from them. Every one of those buffers was already accepted at run time — the type checks inside the library listed them — so no call that worked stops working, and nothing new is refused.Act on it only if you type-check your own code against btclib: a
# type: ignore[arg-type]you wrote to pass a buffer is now unused, and mypy reports an unused ignore as an error underwarn_unused_ignores. Delete those and the annotation says what the library does.Several places did not in fact take a buffer, and now do. The two worth reading are the ones that answered rather than raising: a legacy BMS signature held as a bytearray was checked as a BIP322 signature, which it is not, and came back False; and an address handed to
bms.signasbyteswas not stripped of surrounding blanks where the same address as text was, so it signed under a different address than the caller named and saidmismatch between private key and address.One exception class moves with that second fix: a non-ascii address as
bytesraised Python’sUnicodeDecodeErrorand now raisesBTClibValueError: non-ascii character in address, so anexcept UnicodeDecodeErroraroundbms.signstops catching it. CHANGELOG.md lists them.A BIP32 derivation path held as a
bytearrayor amemoryviewis read as packed 4-byte indexes, the same asbytes(closes #1258).indexes_from_der_pathnarrowed the packed-octets arm tobytesalone, so either buffer fell through to the iterable branch and was read one index per byte instead, deriving a different key from the same octets with nothing raised or warned.Act on it if you pass a derivation path as a
bytearrayor amemoryviewanywhereDerPathis accepted —bip32.derive,bip44,bip85’s derivation functions,psbt_signerandhwiamong them: a path that previously derived through the byte-per-index reading now derives through the packed one, a different key for the same octets. A path held asbytes, or as a string or a plain sequence ofint, is unaffected.
v2026.8.21¶
Breaking changes¶
ansi_x9_63_kdfisbtclib.kdf.ansi_x9_63_kdf. SEC 1’s key derivation function moved out ofbtclib.ecc.dhinto a module of its own, beside RFC 5869’shkdfwhich arrives with it, so neitherfrom btclib.ecc import ansi_x9_63_kdfnorfrom btclib.ecc.dh import ansi_x9_63_kdfresolves any more: writefrom btclib.kdf import ansi_x9_63_kdf. The signature, the answer and the exceptions are unchanged, andbtclib.ecc.dh.diffie_hellmanis unaffected – it calls the KDF where it now lives. CHANGELOG.md has why a KDF is not underecc.psbt.musig2.session_contextreturnsSession, not a bareSessionContext.session_context(psbt, vin_i, aggregate_pub_key) -> musig2.SessionContextis now-> Session, aNamedTupleof.context(theSessionContextit used to return alone) and.key_agg_ctx(theKeyAggContextit built the session on). A caller reading the result as aSessionContext– passing it tobtclib.ecc.musig2.signorpartial_sig_verify_, or reading.pub_keys,.tweaks,.is_xonly,.msgor.agg_nonceoff it – takes.contextfirst. CHANGELOG.md has why.musig2.SessionValuescarries three more fields. The frozen dataclass gainedL,secondandpub_keys_setaftere, soSessionValues(Q, gacc, tacc, b, R, e)is aTypeErrornow. Reading one is unaffected, and reading is what it is for: it is whatsession_values(session_ctx)hands back, and every field it already had answers the same thing. A caller that builds one itself passes the three, which are what a per-signer key-aggregation coefficient is computed from – fixed for a session, so computed once here rather than by each of_session_key_agg_coeff’s callers. CHANGELOG.md has the measurement.pip install btclibno longer installsbtclib_secp256k1. The bindings are thesecp256k1extra now —pip install "btclib[secp256k1]"— and an install that does not ask for them gets a btclib that answers on its own Python arithmetic: tens of times slower, and not constant-time, both of whichSECURITY.mdpublishes. Nothing raises and no import fails, so an upgrade that forgets the extra is a quiet change of implementation rather than an error; askbtclib.curves.is_libsecp256k1_serving()if the answer matters. Environments that resolve from a lock file are unaffected until the lock is regenerated.dsa.recover_pub_key_reports a key_id outside 0..3 as aBTClibValueError. It raisedBTClibRuntimeError— “signature verification failed” — for a key_id whosex_K = r + j*nis no field element, that being the verification refusing it a double multiplication later; the screen that now refuses it says so as a value error, so anexcept BTClibRuntimeErrorwritten against key_id 4 catches nothing.recover_pub_keys_is unaffected, suppressing both classes as it always did, and so is every key_id a signature can name.recover_pub_keys_also stops reporting the point at infinity as a recovered key, which CHANGELOG.md has.a transaction naming one outpoint twice is refused.
Tx.assert_validimplements Core’sbad-txns-inputs-duplicatenow, so building, parsing or serializing such a transaction raisesBTClibValueErrorwhere it used to go through, and so does validating a psbt whose unsigned transaction is one. A caller that was holding a duplicate on purpose – to measure it, or to feed it to the script engine – passescheck_validity=False, which is what that flag is for. CHANGELOG.md has why the rule is not gated onunsigned_template.Tx.parserefuses a BIP144 marker over witnesses that are all empty. It used to take such octets and answer the transaction without them, which re-serialized to the stripped encoding – a differenthash, so a caller relaying what it had parsed sent something other than what it received. It raisesBTClibValueError("superfluous witness record")now, which is Bitcoin Core’s own refusal of the same bytes, andBlock.parseinherits it, a block’s marker being per transaction.check_validity=Falsedoes not get past it: that flag gatesassert_valid, and what is malformed here is the encoding rather than the transaction, which no field records. No transaction on any chain is affected – Core has never accepted one – so what changes is what a caller may be handed by a peer or read out of a file. CHANGELOG.md has the reasoning, and what it cost two of BIP174’s vectors.TxOut.from_dictrefuses anullvalue. It used to build an output of zero satoshi,valid_sats_amountreadingNoneas zero for the caller it was written for; a stored dict carrying{"value": null}now raisesBTClibValueErrorinstead of loading as an output that pays nothing.PsbtOut.amountis unaffected: thereNoneis the field being absent, which a psbt output may legitimately say.the two descriptor parsers refuse three arguments they used to take.
descriptors.parse(descriptor, <not a network name>)andminiscript.parse(expression, <not P2WSH or tapscript>)are refused where they used to be carried into the object and refused later, or not at all; andprv_keysmust be a mapping orNonein both. A caller passing values of the declared types is unaffected, and the network name is now normalized as everywhere else in the library —" MainNet "and"mainnet"were already one network to the encoders, and the parsed object says so too.taproot.parse’sexit_on_op_successis the bool bullet below’s, that being where every flag of the library was classified.thirty-odd
boolarguments that used to be accepted are refused. A flag that decides what is computed is a kind and not a truth, sodsa.sign(msg, q, lower_s="no")— which returned a low-s signature,"no"being true — andpub_keyinfo_from_prv_key(q, compressed="no")— which returned the compressed key, and with it a different address — raiseBTClibTypeErrornow. So docompressedin the nine other signatures that carry it,grind, the script engine’ssegwit,const_scriptcode,skip_executionandexit_on_op_success,signed,include_witnessandunsigned_templateat the psbt boundary,shuffle_inpandshuffle_out, BIP322’slegacy,sort,pad,shuffle,to_be_hashed,extendable,lexicographic_sorting,emulators,musig2,activeandinternal. A caller passing aboolis unaffected, and mypy already refused every one of these calls;0and1are refused too,boolbeing a subclass ofintand that being what made the type check no check at all. The flags that decide only whether a check runs —check_validity,check_root_xkey,verify_checksum,strict,bip380_enforcedand the rest, listed intests/bool_parameter_test.py— are still read for their truth, on the one condition issue #884 added: a truth’sTruehas to be its conservative value. Every wrong value is true, so the misreading is always the flag’sTrue, and three whoseTruewas the permissive one are refused with the kinds above — the script engine’sverified, which suppressed the NULLFAIL rule for a signature that failed to verify;assert_signed’sallow_partial, which accepted an input nobody signed; andpoint_from_octets’shybrid, which parsed the 0x06 and 0x07 prefixes it was written to keep out.the serialization boundary refuses what it used to take, and reports through the exception contract. A
from_dicthanded a mapping without a field raisesBTClibValueErrorwhere it raised a bareKeyError, so anexcept KeyErroraround one catches nothing now;Witness.from_dict({"stack": None})was an empty witness and is refused;tx.serialize(1)andblock.serialize(0)want theboolthey declare;PsbtIn.serialize(psbt_version=3)andPsbtOut’s want one of the two versions there are; andBip21.parse(b"bitcoin:...")raisesBTClibTypeErrorrather thanBTClibValueError, which anexcept BTClibValueErrorwritten against it no longer catches. A caller passing values of the declared types is unaffected.four arguments that used to be accepted are refused.
KeyGroup(1.5, keys)built a group with a float quorum andKeyGroup(keys, verify="no")one withverify=True,"no"being truthy;estimated_input_sizes(psbt_in, tx_in, sizer=<not callable>)went through for every input the function answers for on its own, the sizer being consulted in one branch; andsatisfaction_sizer(one_key)took the key for a list of them,Iterable[Octets]accepting astrand abytes. All four raise aBTClibTypeErrornow. A caller handing any of them a value of the declared type is unaffected, and mypy already refused the first three.the
_varsuffix finishes its sweep:ellswift.encode_var,decode_var,create_var, anddsa.crack_prv_key_var. The map of BIP324’s ElligatorSwift branches on its data — its inverse measures 29.62x, 28 calls of 50 returning early — so the four public names built on it take the suffix,crack_prv_key_becomingcrack_prv_key_var_where both conventions apply and the prepared-input underscore stays last.ellswift.xdhis unchanged at 1.01x, being dominated by amultthat is regular and blinded: the key agreement is not the map. CONTRIBUTING.md lists what measured at the floor and kept its plain name, with the figure for each.nine more reads are properties,
master_fingerprintandcapabilitiesamong them.PsbtSigner.master_fingerprintandPsbtSigner.capabilities– the two argument-less members of the signer contract – are properties, and so areHwiSigner’s,SoftwareSigner’s andSignerDecorator’s implementations of them, plusPsbtView.prevouts. Drop the parentheses.For an adapter written against the contract this is a change to implement and not merely to call: a signer of your own declares
master_fingerprintandcapabilitieswith@propertynow, or as a plain attribute, which a Protocol property accepts as well.psbt_signer_contract.assert_psbt_signerreports the mismatch if you forget. Nothing costs a device round trip in any implementation that exists – HWI’s ownget_master_fingerprintdoes, and if that is the signer being wrapped, the contract can be relaxed deliberately.six
boolmethods are properties:tx.is_segwit, nottx.is_segwit().Tx.is_segwit,Tx.is_coinbase,TxIn.is_segwit,TxIn.is_coinbase,OutPoint.is_coinbaseandBlock.is_segwittook nothing butselfand were the only argument-less bools in the library that were not properties – thirty others were. Drop the parentheses; keeping them isTypeError: 'bool' object is not callable, which is a loud failure and not a silent one.It also makes a bug unsayable rather than merely caught:
if tx.is_segwit:with the parentheses forgotten was a bound method, and every bound method is true. mypy’struthy-functionreports it, so anyone type-checking was already safe; anyone not type-checking was not.seven public
boolnames carry a prefix now.b32.has_segwit_prefixisb32.is_segwit_prefixed,BlockContext.bip34_activeisis_bip34_active,Block.has_segwit_txisBlock.is_segwit,Miniscript.within_resource_limitsisis_within_resource_limits,Miniscript.needs_signatureisis_signature_required,CurveGroup.jac_equalityisis_jac_equal, andhwi.availableishwi.is_available. Old name,AttributeErrororImportError; new name, same answer, no change of signature or behaviour.Six other bools keep an English name —
Psbt.inputs_modifiable,Psbt.outputs_modifiable,Psbt.has_sig_hash_single,Miniscript.mixes_timelocks,Miniscript.has_duplicate_keysandminiscript.reads_back— where the name is the standard’s and a prefix would cost the reading. Those are unchanged.dsa.verifyanswers False for a message that is not octets, where it raised. It reduced the message withhfbefore thetry, so a hex string that is not hex was aBTClibValueErrorwhereverify_, handed the hash, answered False about the same input.ssa.verifyandssa.batch_verifydid the same and move with it. Code that relied on the refusal — atryaroundverifyto catch a malformed message — has to read the bool instead;assert_as_validis the spelling that still says why.The other way round, a
Noneor a float in a verification is aBTClibTypeErrornow where it was a nativeTypeErrororAttributeError:ssa.batch_verify’s three sequences,merkle_proof.verify’s branch,bms.verify’s andbip322.verify’s signature, and both engine signature adapters. Code catchingTypeErrorkeeps working,BTClibTypeErrorbeing one; code catchingAttributeErroraround one of those twoverifycalls has to catchTypeErrororBTClibException.pedersen.verifyrefuses a commitment of a type no point has, where it answered False.the functions whose duration follows their operand gain a
_varsuffix, andmod_invchanges meaning. The plain name beside the suffix is the one a secret may be handed. Innumber_theory,mod_invismod_inv_var,xgcdisxgcd_var,legendre_symbolislegendre_symbol_var,mod_sqrtismod_sqrt_varandtonelliistonelli_var; incurves,double_multandmulti_multaredouble_mult_varandmulti_mult_var, andCurveGrouprenamesaff_from_jac,aff_from_jac_batch,x_aff_from_jac,y_aff_from_jac,add,add_aff,double_aff,y,y_even,y_lowandy_quadratic_residuethe same way.curves.multis unchanged, its two arms making the same additions for every scalar, and so is everything above the arithmetic: the suffix is measured on the value a function receives, not inherited from what it calls.An import or a call of one of the old spellings is an
AttributeErroror anImportError, and each new name is a rename with no change of signature or behaviour.mod_invis the exception and does not raise: the name survives and now returns the same inverse computed with a random blinding factor, so a caller inverting a secret is protected without changing a line, and one inverting public data should saymod_inv_varto keep the 1.11x. CHANGELOG.md has the measurement behind each suffix and CONTRIBUTING.md the rule.eleven
check_*functions are renamed, and the prefix means one thing. It meant four at once: nine refusals returningNone, two bool verdicts, a converter returning bytes and a query returning a pair of bools. The nine areassert_*now –assert_nullfail,assert_nulldummy,assert_pub_key_num,assert_signature_num,assert_not_disabled,assert_stack_size,assert_minimal_push,assert_balanced_ifandassert_psbt_signer–b32.check_witnessisb32.bytes_from_witness_program, andpsbt_signer_contract.check_optional_protocolsisoptional_protocols. What keeps the prefix is the two that answer a bool and refuse what cannot be an answer:script.engine.script.check_pub_keyandscript.taproot.check_output_pubkey.An import of any of the eleven old names is an
ImportError, and the new name is a rename with no change of signature or behaviour.tests/name_contract_test.pyis the gate that keeps the four prefixes meaning what CONTRIBUTING.md says they mean.a verification refuses a type it does not declare, where it used to answer
False.dsa.verifytakes aPubKey– bytes, a hex string, aBIP32KeyDataor aPoint– and an int is none of those: in this library an int is a private key.dsa.verify(msg, 12, sig)is aBTClibTypeErrornow where it wasFalse, and so isecc.dleq.verify_proofwith one. A key of a declared type that is not valid is stillFalse–dsa.verify(msg, "not a key", sig)is unchanged – so a caller filtering signatures that arrived as bytes is unaffected; what changes is a call mypy already refused.The converters underneath moved with it, and that is the part to act on:
to_pub_key’spoint_from_pub_key,pub_keyinfo_from_pub_key,point_from_keyandpub_keyinfo_from_keyanswer aBTClibTypeErrorfor a type no spelling of a key has, where every refusal used to be aBTClibValueError.to_prv_key’sint_from_prv_keyandprv_keyinfo_from_prv_keydo the same, so aPointpassed as a private key is aBTClibTypeErrorwhere it was aNotAPrvKeyErrorreporting three formats tried against a value none of them could hold. Code catchingTypeErrororBTClibExceptionkeeps working; code catchingBTClibValueError— orNotAPrvKeyError— alone around one of those six has to widen.a bad network name raises
BTClibValueError, notKeyError. Every function taking anetwork: str–b58.p2pkh,b32.p2wpkh,to_pub_key.fingerprint,bip39.mxprv_from_mnemonicand the rest – refused an unknown name with a bareKeyError, which is aLookupErrorand so not caught by anexcept BTClibValueError. Code catchingKeyErroraround one of these has to catchBTClibValueErrorinstead; code already catchingBTClibValueErrorstarts working. A non-string name is aBTClibTypeErrorwhere it was anAttributeError. Nothing that worked stops working: the same call with a good name is unchanged, and a name in the wrong case or with spaces around it –"MAINNET"tob32.address_from_witness– is accepted now where it used to raise.a malformed argument raises a btclib error, not a native one. The rest of issue #744’s census, and the same move the network name above made: an out-of-range derivation index was an
OverflowError, an out-of-rangevin_ianIndexError, a header timestamp that is no datetime anAttributeError, a hex string that is not one a bareValueError. Each is aBTClibValueErroror aBTClibTypeErrornow. Code catchingValueErrororTypeErrorkeeps working, the two deriving from those; code catchingOverflowError,IndexErrororAttributeErroraround one of these has to catchBTClibException, or one of the two builtins, instead.Two of them are not a narrowing, and are what to act on. What is neither
bytesnor a hexstris aBTClibTypeErrorwherebytes_from_octetsused to return it untouched – a tuple of 33 ints passedtaproot.assert_valid_control_blockas a control block size, andbin_str_entropy_from_entropy(())was reported as zero bits. And a dozen calls that answered a malformed argument with a number refuse it:sig_hash.taprootwith aninput_indexpast the end of the vin,taproot.input_script_sigwith a negative leaf index,bech32.encodewith a negative digit,mod_invwith a float,int_from_json_numberwith 1.5,Psbt.weight_estimateon an incoherent psbt. CHANGELOG.md lists all twelve.the individual point multiplications are private.
from btclib.curves.curve_group import mult_jacis anImportErrornow, and so is every other variant ofcurve_groupandcurve_group_2: themult_*, the twodouble_mult_*,multiples,cached_multiples,cached_multiples_fixwind,odd_multiples,signed_odd_multiples,jac_from_aff,mods,wNAF_of_m,convert_number_to_baseandmultiplier_decomposereach carry a leading underscore. Usemult,double_multandmulti_mult, which are where they were and are the three that check a point is on the curve before multiplying it – which is what the variants never did and what made them worth hiding. A variant that used to default tow=4takes the width from its caller.verifying and recovering no longer take
lower_s.dsa.assert_as_valid,dsa.verify,dsa.recover_pub_keys,dsa.recover_pub_keyand their four trailing-underscore twins used to takelower_s: bool = Truein the slot beforehf, andbms.assert_as_validandbms.verifyin the slot after the signature:dsa.verify(msg, key, sig, True, sha256)andbms.verify(msg, addr, sig, False)are aTypeErrornow, as is either spelled as a keyword. Drop the argument. Both forms ofsare then accepted, which is what theTruedefault refused and what Bitcoin Core’sverifymessagealways accepted – whethersis the low one of the two was decided by whoever signed. A caller that does want the strict answer asks a private function for it:dsa._assert_as_valid_(c, QJ, r, s, ec, lower_s=True).dsa.signis unchanged,lower_s=Trueand all, the rule being the signer’s: a high-s signature in a transaction is non-standard and does not relay.an ECDSA signature is low-R now, and signing with your own nonce asks for
grind=False.dsa.signanddsa.sign_grind by default, as Core has done since its 0.17, so the signature of a given key and message is a different one for about half of all messages – and one DER byte shorter.grind=Falseis the plain RFC6979 signature, which is what a caller pinning btclib’s bytes has to pass now.Two things to act on rather than one, because grinding is a search over nonces and its default pairs with
nonce=None:dsa.sign(msg, key, nonce)anddsa.sign_(msg_hash, key, nonce)raiseBTClibValueError("grinding derives its own nonce"), as does either with a sign-to-contractcommit. Passgrind=Falsebeside the nonce. The pair is refused rather than resolved in the caller’s favour or the library’s: which of the two won would not be readable back out of the signature.dsa.sign_recoverableand with itbms.signare unaffected, a compact signature having no DER pad to save, and so isbip322.sign, which asks for the plain signature to keep reproducing the BIP’s own vectors.an ECDSA signature is low-R now.
dsa.signanddsa.sign_grind for it wherever the nonce is theirs to derive, as Core has done since its 0.17, so the signature of a given key and message is a different one for about half of all messages – and one DER byte shorter.grind=Falseis the plain RFC6979 signature, which is what a caller pinning btclib’s bytes has to pass now.dsa.sign_recoverableand with itbms.signare unaffected, a compact signature having no DER pad to save, and so isbip322.sign, which asks for the plain signature to keep reproducing the BIP’s own vectors.NETWORKSis read-only, andNetwork.magic_bytesis gone.NETWORKS["mynet"] = Network(...)now raisesTypeError. It was never honoured throughout: the extended-key version lists are built at import, so keys of a network registered afterwards were refused bybip32whilenetwork_from_xkeyversionnamed it. ANetworkis an encoding table and every field of one is the same for every deployment of that network, so the only thing a caller had to register a network for was a custom signet’s p2p magic – and that identifies a node, not an encoding.bitcoin_core_rpc.magic_from_chain(chain)andmagic_from_signet_challenge(challenge)are where it is now;NETWORKS[net].magic_byteshas no replacement here, and note the byte order is Core’spchMessageStartwhere this field was its reverse. A custom signet isBitcoinCoreFetcher(client, "signet", signet_challenge=...), which is the check that magic was read for.XPRV_VERSIONS_ALLandXPUB_VERSIONS_ALLare frozensets.version in XPRV_VERSIONS_ALLis unchanged and is what nearly every use was; indexing, slicing and.index()are not. The one use of the parallel positions – the xpub version paired with an xprv version – isnetwork.xpubversion_from_xprvversion(version).a MOV-weak curve is refused with
BTClibValueError, notUserWarning.Curve(p, a, b, G, n, cofactor)with the defaultweakness_check=Trueused to raiseUserWarning("weak curve")for a curve whose embedding degree is under 100, which noexcept BTClibValueErrorcatches; every other refusal in that constructor already raised one. A caller that builds its own curves and catchesUserWarninghas to catchBTClibValueErrorinstead. The catalogued curves are unaffected: they are built withweakness_check=False, the check having been paid once intest_catalogued_curves.taproot takes no curve.
output_pubkey,output_pubkey_from_merkle_root,output_prvkey,output_prvkey_from_merkle_rootandcheck_output_pubkeyused to end inec: Curve = secp256k1, and a caller passing one positionally –output_pubkey(internal_key, script_tree, ec),check_output_pubkey(q, script, control, ec)– now gets aTypeError. Dropping the argument is the whole of the change: BIP341 is defined for secp256k1 alone, and the parameter was never honoured, the arithmetic behind it having always used secp256k1’s generator whatever was passed.BIP32KeyDatais frozen.xkey.index = 0on an already-built extended key, or on oneb58decode/parsereturned, now raisesdataclasses.FrozenInstanceErrorinstead of silently taking effect. A caller that needs a modified copy usesdataclasses.replace(xkey, index=0), which re-validates by default – the same functionBIP32KeyData(...)still takes, and still defaulting toTrue.the script number zero is the empty vector.
encode_num(0)wasb"\x00"and isb"";decode_num(b"")was aBTClibValueErrorand is0; andscript.serialize([0]), which pushes whatencode_numwrites, was0100and is00– OP_0, with no “consider using OP_0” warning left to raise. A caller pinning any of those bytes has one substitution to make, and a caller reading a script number back has one refusal fewer to catch.push_int(0),op_int(0)and the engine are unchanged, all three having answered OP_0 and the empty vector all along. The reason to act rather than to keep the old spelling:0100is not a minimally encoded script number, so the interpreter refuses it as one wherever MINIMALDATA is in force – btclib’s own engine included. One message moves with the pair: a negative zero read as a number under that flag is refused asnon-minimal encoding of 0: 80, where it readnon-minimal encoding of zero, the general check now answering for it too.borromean.signandborromean.assert_as_validcompute a different challenge hash. The four-part preimage has beenm || R || ring || positionsincev2023.7.12, the message hash before the point or the closinge0; it isR || m || ring || positionnow, matching secp256k1-zkp’srangeproofmodule. Every borromean signature this module ever produced was made with the old order and does not verify under the new one, and there is no version byte in the wire format to switch on – CHANGELOG.md has why the break was worth paying.musig2.partial_sig_aggrefuses a session that carries an adaptor. It briefly answeredssa.Sig | PreSignature, the type depending onsession_ctx.adaptor; that shipped onmainfor under an hour before this release, so “before” is that commit rather than a numbered release. It is-> ssa.Sigagain, exactly as every caller before adaptor signatures existed already relied on, and raisesBTClibValueErrorfor a session that carries an adaptor. The newpartial_sig_agg_adaptoris the spelling for that session, answering thePreSignaturethe union used to. CHANGELOG.md has why: a return type keyed on a field of an argument taxes every caller that will never touch an adaptor, and it moved against where secp256k1-zkp#330 is taking the C API.borromean.signreturns aBorromeanSig, andverifyandassert_as_validtake one instead of the baree0/spair they have taken sincev2023.7.12. Before:e0, s = borromean.sign(msg, ks, sign_key_idx, sign_keys, pubk_rings)andborromean.verify(msg, e0, s, pubk_rings). Now:sig = borromean.sign(...)andborromean.verify(msg, sig, pubk_rings)–sigis aBorromeanSigwith.e0,.sand.ec,serialize()/BorromeanSig.parse()for its wire format, andverify/assert_as_validalso accept theserialize()d octets directly insig’s place. A caller unpacking the old tuple readssig.e0/sig.sinstead; a caller passinge0andsas two arguments passessigas one.sign/assert_as_validanswering the point at infinity with a bareBTClibValueErroralso changes, to aBorromeanRingError(aBTClibRuntimeError): a caller catchingValueErroraround that one corner case catches nothing now. CHANGELOG.md has why, for both.borromean.verifyanswersFalse, not a bareIndexError, for asigwhose ring shape disagrees withpubk_rings;assert_as_validandsignrefuse one withBTClibValueError, not the sameIndexError. Before: asigwith fewer rings thanpubk_rings, or a ring with fewer s-values than it has keys, indexed past the end of a ring’s tuple inassert_as_valid; asign_keysshorter thanpubk_ringsindexed past its own end insign’s step 2 the same way. Both reached a plainIndexError, neither caught byverify’sexcept (ValueError, BTClibRuntimeError)nor documented by any of the three functions. Now:assert_as_validandsignboth raiseBTClibValueErrornaming the ring and the counts, andverifyanswersFalsefor it, the same as any other invalid signature. A caller catchingIndexErroraround any of the three calls to detect either case has to catchBTClibValueError, or nothing at all againstverify, which no longer raises here. CHANGELOG.md has why the check is aBTClibValueErrorand notBorromeanRingError.BorromeanSig(e0, [[]], ...)– a ring with no keys – is refused, where it used to build silently. Before:BorromeanSig.__init__andBorromeanSig.parse, both withcheck_validity’s default ofTrue, accepted it;assert_as_validthen reached a bareIndexErrorindexinge[i][0]on the empty list built for that ring, escapingverify’sexcept (ValueError, BTClibRuntimeError)the same way issue #1088’s did. Now:BorromeanSig.assert_validrefuses it asBTClibValueError, so construction andBorromeanSig.parseraise it directly,assert_as_validraises it in place of theIndexError, andverifyanswersFalsefor it like any other invalid signature. A caller building aBorromeanSigwithcheck_validity=Falseto hold one anyway still has it refused the momentassert_as_valid,serializeorassert_validitself runs. CHANGELOG.md has why the check lives onBorromeanSigand not beside_assert_matches_pubk_rings.borromean.signrefuses asign_key_idx[i]that is not a position in its own ring. Before: a value at or past the ring’s size walkeds[i][j - 1]andpubk_rings[i][j - 1]past the end of the ring’s tuple in step 2, a bareIndexError; a negative value did not raise at all, Python’s own negative indexing quietly signing a different position than the one named and returning aBorromeanSigthat does not verify. Both areBTClibValueErrornow, naming the ring, its size and the index, raised once before step 1 – which is also what refuses a ring with no keys on the signing side, no index being valid into an empty one. CHANGELOG.md has why this is a bound onsign_key_idxand not a copy of the empty-ring check above.
Worth knowing, though nothing raises¶
Signing on the Python arm now checks the signature before answering with it, where it did not check at all. Bitcoin Core’s
CKey::Signdoes the same and the delegated arm always did, so this is the fallback ceasing to answer differently from the arm it stands in for — a signature that does not verify is a computation that went wrong, and the protection is not publishing one.Nothing raises that did not raise before and no signature changes: the same key and message give the same octets. What moves is the time, and it moves a long way. On an installation without the bindings a call that took 165.09 microseconds takes 907.87 — five and a half times what it was — the check adding 742.78, which is about four and a half signatures. One session, 5 rounds of 300 calls, minimum kept, noise 0.24, an Apple M5, macOS 26.6, arm64, CPython 3.14.6.
What to act on, and only if that shows:
dsa.sign(..., verify=False)declines the check and gives the old time back, anddsa.sign(..., pub_key=...)hands in the key the check would otherwise derive, which brings the call to 754.17 — the check down to 589.08.Neither is needed on an installation with the bindings, where the call is 33.06 against 13.52 unchecked: the check adds 19.54 there, and handing the key in takes that to 13.75. Same process as the figures above and not the same run — a signature there being a twelfth of one here, those rows are 9 rounds of 3000 calls, noise 0.04.
btclib.curves.is_libsecp256k1_serving()is what says which arm is answering.The same is true of BIP340 signing, and there the check is the specification’s own step rather than a policy of this library:
ssa.sign,ssa.sign_andssa.Signernow check before answering, where the Python arm checked not at all. On an installation without the bindings a call that took 305.50 microseconds takes 962.81 — 3.15 times what it was — the check adding 657.31, which is about two signatures. One session, 9 rounds of 300 calls, minimum kept, noise 3.01, the same machine as above.verify=Falsedeclines it, on the free functions and on aSigneralike. There is no key to hand in as there is for ECDSA: BIP340 checks under a point the signer already holds, which is why that scheme pays two signatures where ECDSA pays four and a half, and why nopub_keyargument exists here to bring it down.
The bindings are now btclib_secp256k1¶
The secp256k1 bindings were renamed, and btclib requires the new name:
btclib_secp256k1>=0.8.0.1, where it requiredbtclib_libsecp256k1>=0.7.1.3.libnamed the C library, and a python distribution is not that library. Nothing in btclib’s own API moves, and an install of btclib picks the new dependency up on its own. What to act on, and only if you name the bindings yourself: the old distribution stops at 0.7.1.3 and nothing on PyPI bridges the two, so a project that pinsbtclib_libsecp256k1beside btclib pins a package btclib no longer uses. The two can be installed at once — the import package was renamed with the distribution, so neither shadows the other — which is what makes moving one requirement at a time possible.
v2026.8.9¶
Breaking changes¶
the kind of a musig2 tweak is a
booland nothing else.apply_tweak,key_agg_and_tweakandSessionContextused to readis_xonlyfor its truth, so1was an x-only tweak and"false"was one too; both raiseBTClibTypeErrornow. A caller passingTrueorFalse, which the annotation always asked for, is unaffected.a
BitcoinCoreFetcherasks the node which chain it serves, before the first fetch. Onegetblockchaininfoper fetcher, and a node on another chain than the label is aBTClibValueErrorinstead of addresses for coins that are not there.BitcoinCoreFetcher(client, network, verify_network=False)is the previous behaviour, for a caller that has checked by other means or is talking to something that does not answer that call.btclib.keystoreisbtclib.wallet, and its two classes are named after the family they now belong to. The module is a package holding three kinds of wallet behind one vocabulary, sofrom btclib.keystore import BIP32KeyStore, KeyStore, AddressInfobecomesfrom btclib.wallet import BIP32KeyWallet, KeyWallet, AddressInfo. The methods a caller already used are unchanged in name and in answer –address,next_address,addresses,address_info,prv_key,sign,add,is_watch_only,in,len()– and what is added is the surface the other two wallets share:script_pub_key,redeem_script,witness_script,position_ofandbranches.AddressInfocarries two fields more,branchandindex, so a caller comparing a whole record has to pass them; the three it had are in the same order. Two error messages read “wallet” where they read “keystore”: an address the wallet never handed out, and the refusal to sign without a private key.a
KeyManagerhas one method more.psbt.signnow offers a taproot input its script path as well as its key path, and asks for a leaf signature throughsign_schnorr_script_path(pub_key, origin, msg_hash, leaf_hash). A manager written against v2026.8.7 implementssign_ecdsaandsign_schnorronly: mypy stops accepting it where the protocol is asked for, and a taproot input carrying leaf scripts reaches it with anAttributeError. The method signs with the leaf key untweaked – the tweak is what the control block proves – andNonefrom it is a manager saying it holds no key for that leaf, asNonefrom the other two already is.btclib.descriptorsis a package, and its three checksum tables moved with the module into it.INPUT_CHARSET,CHECKSUM_CHARSETandGENERATORarebtclib.descriptors.descriptors.INPUT_CHARSETand its two neighbours; they were never exported and are the tables BIP380’s checksum is computed from, whichchecksum,add_checksumandstrip_checksumanswer with. Every exported name is unchanged:from btclib.descriptors import parseand its neighbours reach the same objects, andbtclib.descriptors.miniscriptis the new subgroup beside them.
What it buys¶
A message can be signed for an address no key can be recovered from.
ecc.bmssigns with a key and lets the verifier recover it, so it speaks only about the addresses that are a public key hash: a taproot address is a tweaked BIP340 key and a p2wsh address is the hash of a script, and no recovery flag names either. The newbtclib.bip322makes the address the script_pub_key of a virtual output and the signature whatever spends it, so verification isscript.enginerather than a key comparison, and every script the engine runs is a script that can sign – multisig, taproot, time locks. Both directions and all four variants:signwrites the simple and full forms for the script types a single key satisfies, andverifyreads those, the proof of funds psbt, and the legacy compact signatureecc.bmsalready made. It answers BIP322’s three states rather than two,InconclusiveErrorbeing what today’s rules cannot judge. The BIP’s own vector files are vendored whole and every case runs, the error cases included and nothing markedxfail. SIGHASH_ALL is enforced through the interpreter, which reports what it consumed as a signature, rather than guessed at from the shape of a stack element – and that is what makes a proof of funds a proof: ANYONECANPAY commits to no other input, so a signature lifted out of the transaction that really spent a utxo would otherwise satisfy that utxo’s input inside a proof of control over it.A witness script says what spends it.
wsh()no longer refuses a miniscript, andbtclib.descriptors.miniscriptis BIP379’s language on its own:parsereads an expression,Miniscript.scriptcompiles it,from_scriptreads a script back into the expression it is, andstrwrites that expression out again. The round trip is the property both directions are for – a signer handed a witness script can say what spends it without being told, which is what miniscript exists for. The type system comes with it,parsenaming the innermost fragment of an ill-typed expression rather than the whole, and so does the sanity a descriptor is held to:wsh(<miniscript>)is refused where the expression is malleable, needs no signature, mixes timelocks in blocks with timelocks in seconds, repeats a key, or has a spend that would pass a resource limit – the same five Bitcoin Core refuses, in the same words. Both of BIP379’s contexts are implemented,P2WSHandTAPSCRIPT; a miniscript is readable and spendable as atr()leaf;Miniscript.satisfypicks a branch and satisfies it non-malleably; andpsbt.finalizespends such an input. The oracle is Core’s ownfixed_tests, vendored whole: every expression it holds is checked in both contexts for validity, for the script it compiles to, for the type answers Core asserts, for every resource bound its calls pass, and for both round trips.Three sources of addresses answer one set of questions.
btclib.keystoreisbtclib.wallet, a package holding three kinds of wallet whose words mean the same thing whichever one a caller holds:script_pub_key(branch, index),address,next_address,redeem_script,witness_script,position_of,address_info,addresses,len(),inandis_watch_only.BIP32KeyWalletis the one that was there;DescriptorWalletis a descriptor per chain, built from BIP389’s<0;1>multipath spelling or from an account xpub; andScriptWalletis for the scripts no descriptor states – the multisig wallets predating output descriptors that miss BIP380-390 by a detail, a<n> OP_CSV OP_DROPwhere miniscript writesOP_CSV OP_VERIFY, or a BIP67 sort applied to the derived keys of a quorum, which is an order no ranged descriptor can state.position_ofis the one that is not a convenience: it is “is this output mine”, the whole script computed at every position of every branch and compared – never a key origin whose four-byte fingerprint matches, which is what would send change to somebody else – and it takes the output as aScriptPubKey, as bytes or hex, or as the address. The non-goals are unchanged and now stated once for all three: no utxos, no balances, no transaction building, no persistence, no encryption at rest.A psbt taproot input is offered its script path as well as its key path.
PSBT_IN_TAP_SCRIPT_SIGwas a field this library read, verified and finalized and never wrote, so the only script path signature a tree could produce was a BIP373 MuSig2 aggregation, one leaf shape of the several BIP371 describes.signnow offers each candidate the psbt names – a key filed under a tapleaf hash byPSBT_IN_TAP_BIP32_DERIVATION, the leaf itself inPSBT_IN_TAP_LEAF_SCRIPT, both required as Bitcoin Core’s signer requires them – and asks aKeyManagerfor a leaf signature throughsign_schnorr_script_path. That key signs as it is: a script path spend proves the leaf, the output key’s tweak being what the control block carries, so there is no merkle root to tweak by. One input may come back signed for both paths, which of the two is spent being the Finalizer’s choice.What this library refuses to guess at, a caller can now supply.
finalizetakes anInputSolverandestimated_input_sizesaSolutionSizer, for the inputs each was refusing not for want of data but for want of knowledge nobody but the caller has: a witness script of no standard kind, whose spend built from the signatures and the script is a guess that fails when the network runs it rather than when it is built, and a taproot script path, where which leaf will be spent is not in the psbt. Neither is asked in place of an answer btclib can work out, and neither takes over the bookkeeping BIP174 asks of a Finalizer.Psbtgrowsweight_estimateandvsize_estimateto pass a sizer, a property being unable to take one, andsatisfaction_sizeris a sizer for a miniscript: the branch a spend will build, whereminiscript_sizeranswers the largest it could – a timelocked recovery quorum behind the same address used to pay for whichever branch was larger even when it never opened it.A signer written outside btclib can be held to the contract. A protocol is a promise the type checker reads and nothing runs, so an adapter answering a five-byte fingerprint, an xpub derived from the wrong path, or a signature on an input whose key origin names another master type-checks and is wrong at the first spend.
check_psbt_signerasks that question from outside and takes anyPsbtSigner– a command line adapter, an in-process driver, a signing service – and it is a function belonging to no test framework. Beside it,select_deviceandmerge_devicesare the choice a caller makes before it holds a signer at all, by fingerprint and in an order that is the caller’s;SignerNotFoundErrortells a backend that is not installed from a device that refused; andSoftwareSigner.from_accountsbuilds a signer on the accounts a device exported, for the master fingerprint they came from, where the constructor takes one key and answers that key’s own.Three parsers answer for their own input.
OutPointaccepts half a coinbase marker, as Bitcoin Core does – its rule is the conjunction where this library’s was the exclusive or – so a transaction naming a utxo through a synthetic funding transaction of that shape can be read at all, which is what BIP322’s proof-of-funds vectors do and whatPsbt.parseused to refuse before any signature could be looked at.Psbt.b64decoderaisesBTClibValueErrorfor base64 it cannot read, wherebinascii.Errorand a bareValueErrorescaped from the codec. And a malformedhwi enumerateentry is aSignerError, carrying what the backend said, rather than an exception from inside the parsing of it.tests/fuzz_test.pyreaches the entry points it was missing – the base64 wrappers,ecies.Envelope.parse, and the two text languagesdescriptors.parseandminiscript.parse– and adding the first of them is what found thePsbt.b64decodedefect.The flow the ordinary suite skips is run against a real node, on a schedule. An
integrationworkflow downloads a pinned Bitcoin Core release, checks it against the sha256 four guix builders attested, and runs the round trip end to end: btclib exports an account, Core imports it and pays it, btclib signs the spend and the node relays it. Two things it does not do: gate a merge – a Core release or an unreachable download is not a branch’s fault – and trust a green exit, a step after the run failing the job if a regtest test skipped rather than ran, which is how a fixture that stopped finding the node would otherwise report success.
v2026.8.7¶
The first release since 2023, and the largest; every entry of it is in CHANGELOG.md. What follows is what a user has to act on and what a user gains.
Every change is a behaviour change somewhere, so the honest summary is this: btclib now refuses input it used to accept, reports errors it used to swallow, and no longer lets one object’s mutation reach another. If something that worked stops working, the entry explaining why is in CHANGELOG.md.
Breaking changes¶
The changes below break code that worked on v2023.7.12. Each is described in
full in CHANGELOG.md. Every “before” spelling was checked
against the v2023.7.12 tag.
A descriptor parsed from an xprv no longer derives a hardened step on its own.
descriptors.parsekeeps no private key: it neuters the xprv and fills theprv_keysmapping handed to it, andscript_pub_keys,satisfy,update_psbt_inputand their neighbours take that mapping back as a last argument.parse(d).script_pub_keys(0)becomeskeys = {}; parse(d, prv_keys=keys).script_pub_keys(0, keys)where the path has a hardened step; everything else is unchanged.str_from_index_int(i, "H")raises. A derivation path is written withhor', the two hardened indicators BIP380 allows; the uppercaseHthat BIP32 writes its own vectors with is still read and is no longer written. Pass"h"or"'", or take the default.btclib.bitcoin_core_rpcis thebitcoin-core-rpcpackage. The Bitcoin Core rpc client is no longer a module of btclib: it is a distribution of its own, which btclib now depends on, sopip install btclibstill brings it andimport btclib.bitcoin_core_rpcno longer resolves.from bitcoin_core_rpc import ...is the spelling, andbtclib.fetch.BitcoinCoreRpcClientandbtclib.fetch.bitcoin_core.BitcoinCoreRpcClientkeep working unchanged. The one behaviour that moves with it: reaching the client through either of those names and catchingbtclib.exceptions.RpcErrorno longer catches, the package raising its own —bitcoin_core_rpc.RpcErroris what a directclient.callraises now. AFetcheris unaffected and still raises btclib’s,statusandcodeincluded.btclib.fetch.bitcoin_core.core_chain_from_networkischain_from_network, and its pairbitcoin_core_rpc.network_from_core_chainisnetwork_from_chain. The rename is thebitcoin-core-rpcpackage’s, in the v2026.8.7 release btclib now requires, and it leaves no alias behind: thecore_prefix said inside a package named for Core what the package name already said. Both take and return what they always did.from btclib.ec import ...isfrom btclib.curves import .... Every name the package exports is the name it exported before.Block.weightis the weight of the block, where it was the sum of its transactions’ weights: Core’sGetBlockWeight, so the 80-byte header and the var_int holding the transaction count are counted too — 332 more for a block with hundreds of transactions, 324 for one holding a single transaction — andBlock.vsizemoves with it.Tx.weightis unchanged. This is the number consensus reads,MAX_BLOCK_WEIGHTbounding it; the sum is still available assum(t.weight for t in block.transactions), andBlock.stripped_sizeis the other quantity a block is bounded by.a block is proved against a network’s pow limit, mainnet’s unless you say which.
BlockHeader.assert_valid_pow()andBlock.assert_valid()compared the hash with the target and made none ofCheckProofOfWork’s four range checks on that target, so a regtest or signet block passed as a mainnet one. Both now take apow_limit_bits, and a block of another network is answeredproof-of-work target above the limituntil it is named:assert_valid(REGTEST_POW_LIMIT_BITS).Block.__init__,parseandserializehave no such parameter, so build withcheck_validity=Falseand validate in a second step.a psbt carrying a PSBT v2 field is refused, where every one of the twelve was filed under
unknownand round-tripped. BIP370 forbids them in version 0, which is the only version btclib reads, soPsbt.b64decodenow answersPSBT_IN_PREVIOUS_TXID is not allowed in a v0 psbtand names whichever of the twelve it found. What this breaks is a psbt of your own using one of those type bytes — global0x02to0x06, input0x0eto0x12, output0x03and0x04— as a spare slot for data of your own: pick a byte no BIP has taken, or0xfc, which is reserved for exactly that.finalize_psbtrefuses a taproot input that carries no taproot signature, where it used to build a script_sig out of the input’sPSBT_IN_PARTIAL_SIGentries — a spend BIP341 gives no meaning to and btclib’s own script engine rejects. A p2tr input is now finalized fromPSBT_IN_TAP_KEY_SIGorPSBT_IN_TAP_SCRIPT_SIG, which is whatbtclib.psbt.musig2writes for a MuSig2 session and what any taproot signer writes; an input carrying neither answers “missing taproot signature”.a psbt whose global version or input sighash type is not four octets wide is refused. BIP174 defines both as a little-endian uint32, and both were read at whatever length they arrived at and written back at four:
PSBT_GLOBAL_VERSIONof02in one octet was version 2, andPSBT_IN_SIGHASH_TYPEof01in one octet was SIGHASH_ALL. Both now answerinvalid global version length: 1 bytes instead of 4andinvalid sig_hash type length: 1 bytes instead of 4. What this breaks is a psbt written by something that padded neither field to its width; write the four octets.psbt_utils.deserialize_intis gone with the last of its call sites —deserialize_sized_intis the one to use, with the width of the field.a psbt whose MuSig2 fields are malformed is refused, where all four type bytes BIP373 defines were filed under
unknownand round-tripped: input0x1a,0x1band0x1c, output0x08. They are fields now, so a key or value of the wrong size is an error rather than opaque data —invalid musig2 aggregate pub key length: 32 bytes instead of 33and the like — and what this breaks is the same thing the entry above breaks, one of those bytes used as a spare slot for data of your own:0xfcis reserved for exactly that.PsbtIn.to_dictandPsbtOut.to_dictcarry the new fields, andfrom_dictneeds them, so a dict written by an older btclib does not load.Psbt.txis computed, not stored, andPsbt(...)takes the transaction’s version where it took the transaction.Psbt(tx, inputs, outputs, version, hd_key_paths, unknown)isPsbt(tx.version, inputs, outputs, version, hd_key_paths, unknown, fallback_lock_time, tx_modifiable), andPsbt.from_tx(tx)— which now takes the input and output maps too — is the way to build one from a transaction. Readingpsbt.txstill works and gives the same transaction; writing into it no longer reaches the psbt, because what comes back is built from the fields at every access:psbt.tx.vin[0].prev_out = outpointis nowpsbt.inputs[0].previous_tx_id, psbt.inputs[0].output_index, andpsbt.tx.lock_time = nispsbt.fallback_lock_time = n.Psbt.to_dict()carries the fields it holds —tx_version,fallback_lock_time,tx_modifiable, and the new per-input and per-output ones — with the transaction beside them for reading;from_dictneeds the fields, so a dict written by an older btclib does not load. Why the format is held this way, and not as BIP174’s transaction with the BIP370 fields shadowing it, is in the module docstring ofbtclib.psbt.psbt.sort_inputs,sort_outputsandjoin_psbtscan refuse a version 2 psbt, andcombine_psbtsrefuses psbts of different versions. The first three are a Constructor’s work, which BIP370 gates onPSBT_GLOBAL_TX_MODIFIABLE; nothing changes for a version 0 psbt, which has no such field. For the fourth, convert first withto_v0()orto_v2().btclib.curvesno longer exports the individual multiplications: the elevenmult_*variants,multiples,cached_multiplesandjac_from_affcome frombtclib.curves.curve_group, or fromcurve_group_2formult_sliding_window,mult_w_NAFandmult_endomorphism_secp256k1.mult,double_multandmulti_multare where they were.btclib.ec.libsecp256k1andbtclib.ecc.libsecp256k1are gone.mult,dsa.signandssa.signcall the bindings themselves.btclib.bip32.bip32.ecis gone. BIP32 is defined for secp256k1 and for nothing else, so it was never configuration.borromean.ecandborromean.hfare gone, and areecandhfparameters ofsign,verifyandassert_as_valid, with the same defaults.btclib.ecc.sign_to_contractis gone, and the commitment is a keyword-only parameter ofdsa.signandssa.sign:dsa_commit_sign(commit, msg, prv_key)isdsa.sign(msg, prv_key, commit=commit), returning the same(sig, receipt), anddsa_verify_commit(commit, receipt, msg, key, sig)isdsa.verify(msg, key, sig, commit=commit, receipt=receipt). ssa takes a commitment now too, which the module never offered. The signature is not the one v2023.7.12 produced, and an opening kept from it no longer opens: the scheme is libsecp256k1-zkp’secdsa_s2cnow, tagged hashes and all, because the old one let two commitments over one message leak the private key. Re-sign, and do not pass a nonce of your own beside a commitment — that is refused, the commitment having to reach the nonce derivation.check_validityis keyword-only, in all 91 signatures that take it:f(..., check_validity=False), never positionally.strictofdsa.Sig.parsefollows it behind the same star.ssa’smsg_hashandm_hashesparameters aremsgandmsgs, and take a BIP340 message of any size rather than a 32-byte array.BlockHeader’s third parameter ismerkle_root, notmerkle_root_.multiplier_decomposertakes the scalar alone:multiplier_decomposer(m), where it was(m, ec). The curve is what the bug was — it decomposed moduloec.pwhere the congruence holds modulo the group order, somult_endomorphism_secp256k1answered the wrong point for every scalar above ~2^127. The constants are secp256k1’s andCurveGrouphas nonto offer, so the parameter is gone rather than corrected.OutPoint,TxOut,Witness,ScriptandScriptPubKeyare frozen dataclasses. Assigning to a field raisesFrozenInstanceError; build a new instance, or usedataclasses.replace.Witness.stackis atuple[bytes, ...].Witness([*w.stack, element])replacesappend, and code comparing a stack against a list has to compare against a tuple. The constructor still takes any sequence, andto_dictstill yields a list.borromean.assert_as_validreturnsNoneand raises on failure, as itsdsa,ssaandbmscounterparts do. It used to return abool, soif borromean.assert_as_valid(...)accepted forged ring signatures in silence;borromean.verifyis the one that answers a bool.dsa.Sig.parserejects trailing bytes. A script signature and a PSBT partial signature are a DER encoding plus a sighash type byte, and the parse used to ignore that byte instead of refusing it:Sig.parse(sig[:-1])is the spelling now, andstrict=Falsekeeps the old leniency for a caller that wants it.ScriptPubKeyequality compares the network type,"main"or"test", not the network name: a testnetScriptPubKeyis now equal to a signet, regtest or testnet4 one with the same script, those four networks sharing every address prefix, and mainnet is still equal to none of them. Code asserting that two test networks differ has to compare.networkitself.sig_hash.legacy_scriptandsig_hash.witness_v0_scriptare gone. Both returned the list of script codes for zero, one, two … OP_CODESEPARATORs executed, and both built each rung by re-serializing a parse, which is not the bytes a signature commits to.sig_hash.legacynow elides the separators itself, where Bitcoin Core elides them, so a legacy script code is the script as it stands; a segwit v0 one keeps them, as BIP143 says; andfrom_tx(..., codesep_index=k)is how a signer asks for the script code after the k-th of them.sig_hash.taproot_annex_and_extloses itsprevoutsparameter.taproot_annex_and_ext(tx, prevouts, vin_i)istaproot_annex_and_ext(tx, vin_i), the parameter having gone unused; dropping it movesvin_ito second position, so a positional caller breaks even where it passedprevoutsasNoneor[].sig_hash.SIG_HASH_TYPESis afrozenset, not alist. Every use of it is a membership test —assert_valid_hash_typeand the script engine’s own check — and alistwas one shared mutable value nobody was meant to hold onto. Indexing it, appending to it, or comparing it against an equal-content list breaks;sig_hash_type in SIG_HASH_TYPESis unaffected.btclib.network.n_versionsis gone, with the_REPEATED_NETWORKSlist it counted for: the version-prefix lookups no longer index a parallel list of names, so the number of prefixes per network stopped being a fact about anything.len(xprvversions_from_network(net))is the spelling if it is wanted.script.engine.script.check_balanced_if(script)isscript.engine.script_op_codes.check_balanced_if(condition_stack), and it answers a different question: it was a pass over a parsed script counting OP_IF, OP_NOTIF and OP_ENDIF, and it is now the check Bitcoin Core makes once the interpreter loop is over, on the condition stack the loop leaves behind. The count could not see a conditional closed before it was opened, which is the script it let through.Psbt.parse’s parameter isdata: BinaryData, notpsbt_bin: Octets, so only a caller naming it by keyword has to change. Bytes and hex strings parse as before; aBytesIOnow does too, and is left positioned right after the psbt.psbt_utils.deserialize_mapreturns the map, not the(map, stream)pair:deserialize_map(data)[0]isdeserialize_map(data), and a caller threading the stream through passes its own.PsbtIn.parseandPsbtOut.parsetakeBinaryData, not a decodedMapping[bytes, bytes]: each reads one map from the stream, its terminator included, and leaves the stream on the next one.PsbtIn.serializeandPsbtOut.serializeend with the0x00delimiter thatPsbt.serializeused to append for them, as Bitcoin Core’sPSBTInput::Serializedoes. A serialized psbt is unchanged; code appending that byte itself has to stop.The three psbt constants are Bitcoin Core’s.
btclib.psbt.psbt.PSBT_MAGIC_BYTESis the whole five-byte header,b"psbt\xff";PSBT_SEPARATORis the0x00that ends a map and is imported frombtclib.psbt.psbt_utils, where it was the0xffand came frombtclib.psbt.psbt;PSBT_DELIMITER, which was that0x00, is gone.malformed psbt: missing separatorgoes with it: one header is one check, and a fifth byte that is not0xffismalformed psbt: missing magic bytes.Psbt.parseandPsbt.b64decodereject trailing bytes, asdsa.Sig.parsedoes: octets are a whole psbt, andmalformed psbt: N bytes after the psbtis the answer to anything after one. Handing aBytesIOover is how a caller says the rest of the buffer is theirs.to_dictrenders a script as{"asm": ..., "hex": ...}, where it rendered the bare hex string:TxIn’sscriptSig,TxOut’sscriptPubKey,PsbtIn’sredeem_script,witness_scriptandfinal_script_sig, andPsbtOut’sredeem_scriptandwitness_script.d["scriptSig"]isd["scriptSig"]["hex"], and so on for the seven.from_dictstill reads the old spelling, a stored dict staying readable, and reads thehexin both — but anasmthat thehexdoes not produce is refused rather than ignored.TxOut.to_dictno longer emitsreqSigs, which was alwaysNone; Bitcoin Core dropped it in v22 for being an answer only a bare multisig had.electrum.mnemonic_from_entropyreturns the mnemonic Electrum returns, which is not the one btclib returned: the words run least-significant first and the search starts atentropy + 1, so the same entropy now gives a different sentence, andelectrum.entropy_from_mnemonicreads the same sentence as a different integer. Anyone who stored an entropy value expecting btclib to reproduce a mnemonic from it has to store the mnemonic instead — which is the safe direction anyway, the seed deriving from the words alone.version_from_mnemonicalso answers"old"now for a pre-2.0 Electrum seed, where it raised — or, for an old seed whose hash happened to start with one of the four prefixes, named a new version and handed back the wrong derivation; and it accepts what Electrum accepts, so an upper-cased or accented mnemonic is read rather than refused.bip39.seed_from_mnemonicnormalizes NFKD, so a non-ASCII mnemonic or passphrase derives another wallet than it used to. BIP39 stretches the sentence and the passphrase in UTF-8 NFKD and btclib normalized neither, which made all twenty-four of BIP39’s Japanese vectors wrong seeds. ASCII is NFKD already, so an English mnemonic with an ASCII passphrase is untouched; anyone whose passphrase or mnemonic holds a character outside ASCII was deriving a wallet no other implementation agrees with, and has to re-derive from the same words to reach the right one.Script(script_bytes)no longer raises for a script that cannot be executed. A push over 520 bytes and a push declaring more bytes than follow it used to beInvalid pushdata lengthandNot enough data for pushdataout ofScript,ScriptPubKey,.asmandscript.parse; they are now decoded, the second as everything up to the place the bytes stop being a script plus the marker"[error]"Bitcoin Core writes there. Code that caughtBTClibValueErroraround aScriptto sort scripts it could handle from scripts it could not has to ask the question it meant:"[error]" in Script(s).asmfor one that cannot be read to the end,script.engine.verify_inputfor one that cannot be spent. There are twelve such scripts in blocks 251718 to 299571.script.parse(stream, accept_unknown)isscript.parse(stream). The parameter’s answer is fixed at what every caller passed, so a byte no op-code table names is alwaysUNKNOWN_OP_CODE_nand neverUnknown op code: Core reads it too, and it is the interpreter that refuses it. A caller passing it positionally or by keyword gets a TypeError.script.engine.validate_redeem_scriptisscript.engine.validate_push_only, and takes the script_sig bytes:validate_push_only(tx.vin[i].script_sig), where it wasvalidate_redeem_script(parse(tx.vin[i].script_sig)). It is Core’sCScript::IsPushOnly, which compares each op code against OP_16 — and the name says which script it is asked about, the script_sig, at both call sites as in Core.script.engine.script.calculate_script_codeand.op_checksigname their code-separator parametercodesep_offset, where it wasseparator_indexandcodesep_index.script.engine.tapscript. op_checksiggains a requiredflags: ScriptFlagparameter besides, which is what lets it refuse a tapscript public key that is neither empty nor 32 bytes under DISCOURAGE_UPGRADABLE_PUBKEYTYPE. All three are the script engine’s own internals —verify_inputandverify_transactiontake no new parameter — and break only a caller driving the interpreter’s op codes directly.join_psbtsandjoin_txsno longer takemerge_out. It was the fourth positional parameter of both, andmerge_out=Trueraisedoutput merge not implemented yet: delete the argument at each call site,merge_out=Falsehaving been the only value that did anything. Merging two outputs that pay one script changes the output set, so every signature already made over it stops verifying, and both functions shuffle or sort the outputs first — summing two payments into one output is the caller’s, before signing.psbt_utils.assert_valid_taproot_treeis gone, with the leaf-script validation it performed: a PSBT tap tree is stored as it arrives, as Core’s PSBT stores it. Nothing replaces the call —PsbtOut.assert_validsimply no longer parses the leaves — and a caller that wants to know whether a leaf can be executed runs it.psbt_utils.assert_valid_taproot_signatures’s second parameter iswhat, noterr_msg. It used to be raised as the whole message; now it names what is being validated, and the function builds one of three messages around it depending on the failure — a wrong length, an explicit SIGHASH_DEFAULT byte, an unsupported hash type — so a caller passing a full sentence gets it wrapped inside a new one rather than raised verbatim.BIP32DerPathisDerPath, and the three*_from_bip32_pathconverters are*_from_der_path.indexes_from_bip32_path,str_from_bip32_pathandbytes_from_bip32_pathanswer as they did underindexes_from_der_path,str_from_der_pathandbytes_from_der_path, so a search and replace forbip32_pathandBIP32DerPathis the whole cost. No alias is kept, as thebtclib.ecrename kept none.CurveSubGroupis gone, and nothing replacesfrom btclib.ec.curve import CurveSubGroup: the class held a generator and no order, which is a cyclic group that cannot say how many elements it has.CurveGroupandCurveare the hierarchy — every point of the curve, and the cyclic subgroup of prime order generated by G — andCurve(p, a, b, G, n, cofactor)is what a caller of the removed class wanted.from btclib.ecc import bip340_nonce_isfrom btclib.ecc.bip340_nonce import bip340_nonce_. The package now names the three nonce modules —bip340_nonce,rfc6979_nonce,commit_nonce— where it used to export one function out of one of them, and no name ending in an underscore is in its__all__any more.a truncated or over-long serialization is refused where it used to parse. A fixed-width field has to hold its bytes now, and an octet string handed to
parsehas to hold exactly one object:Tx.parse(raw[:-1])andTx.parse(raw + b"junk")both raiseBTClibValueError, where the first answered a transaction with a shorter lock time and the second answered the transaction ofraw. The same holds forTxIn,TxOut,OutPoint,Block,BlockHeader,BIP32KeyData,Witness,PsbtInandPsbtOut, and whatevercheck_validitysays — the length is what makes the fields mean anything, not an opinion about what they hold. A stream is unaffected, what follows the object in it being the caller’s: reading a transaction out of a block reads on as before. Parsing one object out of a longer buffer isparse(BytesIO(buffer))rather thanparse(buffer).BIP32KeyOrigin.parsegoes with them for the width of its master fingerprint, whichcheck_validity=Falseused to defer: four octets, or it is not a key origin.a boolean is refused wherever a field is an integer quantity.
boolbeing a subclass ofint,valid_sats_amount(True)was 1,FeeRate(sats_per_kvbyte=True)was a one-sat/kvB rate, andOutPoint(tx_id, True)was output number one; all of them raiseBTClibTypeErrornow. This matters at a json boundary, wheretruedecodes toTrue: what used to be one satoshi is an error next to the field that carried it. Only an actual boolean is affected — anIntEnumor any other deliberate integer subclass is still an integer.ssa.verifyanswers False for a 65-byte taproot witness signature, where it answered True: the 65th octet is BIP341’s sighash type, not part of the BIP340 signature, andSig.parseread the first sixty-four octets and dropped the rest.ssa.Sig.parseandssa.assert_as_validraiseBTClibValueErroron it, as they do on a truncation. Strip the byte at the call site —ssa.verify(msg, pub_key, witness_sig[:64]), which is what btclib’s own script engine does after reading the sighash type off it.btclib.psbtno longer exports the ninepsbt_utilsnames:serialize_bytes,deserialize_int,deserialize_map,deserialize_tx,encode_dict_bytes_bytes,decode_dict_bytes_bytes,serialize_dict_bytes_bytes,serialize_hd_key_pathsandassert_valid_unknowncome frombtclib.psbt.psbt_utils, which is where they are defined. They are how one field of one psbt map is written and read;Psbt,PsbtInandPsbtOutare where a caller reads and writes a psbt.from btclib.base58 import b58encode, b58decodeisencode, decode. The two call sites that need both codecs in scope —btclib/b58.pyandbtclib/to_prv_key.py— alias them back at the import,from btclib.base58 import decode as b58decode, encode as b58encode, so a caller doing the same keeps its own names.BIP32KeyData.b58encode/.b58decode,bms.Sig.b64encode/.b64decodeandPsbt.b64encode/.b64decodeare methods and are unaffected.descriptors.descriptor_checksumand.descriptor_from_addressarechecksumandfrom_address. Both spellings were already there atv2023.7.12— checked against the tag.add_checksumandstrip_checksumkeep their names.tx.join_txsistx.join;psbt.combine_psbts,psbt.join_psbtsandpsbt.finalize_psbtarecombine,joinandfinalize. All four spellings were already there atv2023.7.12— checked against the tag.psbt.extract_txis unchanged.btclib.bip32.slip132isbtclib.slip132.from btclib.bip32 import slip132was the spelling atv2023.7.12— checked against the tag — and isfrom btclib import slip132now.bip44, which needs the same top-level placement for the same reason, was already there.from btclib.<module> import *hands out that module’s own names. Every module of the library declares__all__now, where none did atv2023.7.12— checked against the tag — so a star import stops binding what the module imported:Octets,Stringandsha256came out ofbtclib.b58and come out ofbtclib.aliasandbtclib.hashes, which define them. Every named import of a name a module defines is unchanged,from btclib.b58 import p2pkhincluded. What does go is the residue of three load loops and one type variable:net,filenameandfinbtclib.network,filename,file_andec_nameinbtclib.curves.curve, andTypeAinbtclib.psbt.psbt, all underscored now, sofrom btclib.network import net— which the underscore rule already said was nobody’s to write — raisesImportError.from btclib import *binds the library’s modules, where it boundnameand the two names the version lookup imports.btclib.__all__is the packages and top-level modules now, imported on demand by a module__getattr__, soimport btclibstill costs the metadata lookup alone andbtclib.b58answers without an import of its own.btclib.nameis where it was, and is no longer star-imported.network.datadirandcurves.curve.datadirarePath, notstr.str(btclib.network.datadir)recovers thev2023.7.12value; code that concatenated it, sliced it, or called a string method on it does not.
Two changes are deliberately not on that list, because what they change
stays compatible. The new BTClibTypeError, NotAPrvKeyError and
InvalidPrvKeyError all derive from what was raised before, so except BTClibValueError and except TypeError keep catching them. And the is_p2*
and verify families now let a TypeError out where they used to answer
False: that is a caller error surfacing, not an interface moving.
What it buys¶
Forged signatures and mutated blocks are refused.
borromean.assert_ as_validused to return a bool, so calling it as a statement — which is what itsdsaandssacounterparts ask for — accepted forgeries in silence.Block.assert_validnow rejects the CVE-2012-2459 merkle mutation and checks the BIP141 witness commitment, without which every signature in a block could be replaced wholesale with the header untouched; it also bounds the block’s size, weight and signature operations, and a caller holding a height and a clock can ask the two rules that need them — the coinbase’s BIP34 commitment and the timestamp — throughBlock.assert_valid_contextual. The low-s rule is decided by exact integer division, whereec.n / 2had put the threshold 2^127 above the true midpoint, anddsa.verifyno longer accepts a private key where a public one goes.Secrets stay out of logs. A routine network mismatch used to put a full xprv into the exception text; the messages now carry the version bytes or the size, and a private
BIP32KeyDatarepr masks its key and chain code.Hostile input costs what it should. Five bytes of a PSBT used to cost gigabytes, and 160k characters in an address field 3.3 seconds. Parsers bound their allocation by the data they were handed,
var_intenforces Core’s shortest encoding and 32 MiB cap, andtests/fuzz_test.pyholds every parse entry point to the exception contract ofbtclib/exceptions.py.Every script that is on chain can be read. Twelve
scriptPubKeys in blocks 251718 to 299571 raised out ofScript,ScriptPubKeyand.asm, two of them for pushing more than the stack can hold and ten for declaring a push longer than the bytes that follow it. Whether a script can be executed is now the interpreter’s answer, given by executing it, which is where Bitcoin Core keeps it — and the five transactions reported are vendored as vectors.Signing a transaction is linear in its inputs, where it was Θ(N²): the new
sig_hash.PrecomputedTxDatatakes 400 taproot inputs from 164 ms to 0.4 ms.bms.signis twice as fast, recovering one candidate public key at a time where it recovered all four and then searched them. A public key from a private key is 13% faster, its compressed serialization now sliced out of the bindings’ own answer instead of routed through a Python point. Importing btclib is 140 ms faster, andScript.asmis cached.Importing btclib changes nothing outside btclib. It no longer dies where hashlib has no RIPEMD-160, no longer re-enables OpenSSL’s deprecated algorithms process-wide, and no longer traps decimal
FloatOperationin the process context.One object’s mutation no longer reaches another.
OutPoint,TxOut,Witness,ScriptandScriptPubKeyare frozen,Witness.stackis a tuple, default arguments are built per call, andassert_validno longer rewrites what it validates —verify_transactionused to rewrite the very transaction it was validating.A failure says what failed. 76 empty
BTClibValueError()raises in the script engine carry a message and the command index; a private key in a recognised-but-wrong format reports its own fault instead of being retried as another format; the script verification flags are anenum.Flag, where a misspelled name used to be a silently disabled consensus rule.A descriptor is now an address, not just a checksum.
descriptors.parsereads BIP380 to BIP386 and BIP389 — everything but miniscript — and hands back the scripts and addresses a descriptor pays to at any index, so one line of text is enough to watch a wallet. Checked against Bitcoin Core’s own vectors; miniscript and the four functions left out say so by name rather than being read wrong.A mnemonic in any of the twelve languages, where two word-lists shipped and English was the only one a seed could be derived in:
seed_from_mnemonicverified every checksum against English, and normalized neither the sentence nor the passphrase, which BIP39 requires and which is the difference between two seeds rather than between an accepted input and a rejected one. All 288 vectors of the reference implementation pass, and so do the japanese ones the BIP cites beside them. The language need not be given — the words say which it is — and electrum’s five word-lists are here too, its 1626-word Portuguese included.BIP340 messages of any size, as the BIP has allowed since 2023-04: the four vectors btclib used to
xfailall verify.MuSig2 is implemented,
btclib.ecc.musig2against all 56 cases of BIP327’s eight vector files: many signers, one BIP340 signature thatssa.verify_accepts. One primitive per round rather than a function that signs, the protocol being interactive.A psbt carries a taproot signature with its sig_hash type, the 65-byte form of BIP341 that BIP371 spells out and btclib refused, while its own script engine read it.
btclib can go and ask the chain, which it never could:
btclib.fetchis a transaction by id, the output an outpoint names and the chain tip, behind one interface with two backends — a full node’s JSON-RPC and a block explorer’s HTTP api — answering inTxandTxOut. Nothing to install for it: the client isurllib.request. It isbtclib.bitcoin_core_rpc, one standard-library-only file a project can copy whole instead of depending on btclib, andbtclib.exceptionsre-exports the three exceptions it defines so that oneexceptcatches them by either name — which is why an import that reachesbtclib.exceptionsloadsurllib.requesttoo,import btclibitself still costing the metadata lookup alone. Nothing connects until a call is made.btclib can hand a psbt to an external signer.
btclib.psbt_signerdefines thePsbtSignerprotocol —master_fingerprint,xpub,sign_psbt,capabilities,close— and the checks a caller runs over an untrusted answer:request_signaturesholds the returned psbt to the one that was sent,export_accountrefuses an xpub that is not the account the path names,display_addresscompares a device’s own address against btclib’s.btclib.hwi.HwiSigneris the one shipped implementation, over Bitcoin Core HWI’s five JSON commands — HWI reaching Trezor, Ledger, KeepKey, Digital Bitbox, Coldcard, BitBox02 and Jade — selecting a device by fingerprint rather than by enumeration order, with nothing imported fromhwiliband nothing to install: an executable named at the call site is the whole runtime requirement.exceptions.SignerErrorcarries HWI’s own error code, so a declined signature and a disconnected cable answer as different numbers rather than as one unread message (issue #381).Borromean ring signatures work on a curve other than secp256k1, which is what the
ecparameter has been offering since it stopped being a module global: the arithmetic ignored it and computed on secp256k1, so the first point encoded againstecraised and no other curve could sign at all.SLIP-0039 shares can be read and written.
btclib.mnemonic.slip39is the third scheme beside BIP39 and Electrum, and until now btclib could not read a single share of the Shamir backup every Trezor since 2019 offers.The documentation has a guide and not only a reference. A new page arranged by task — a mnemonic and its seed, an account xpub and the BIP44/49/84/86 addresses under it, reading a raw transaction, building one and computing the hash it commits to, ECDSA and BIP340, a signed message, a PSBT — where there had been fifteen pages of
automoduleand nothing to start from (issue #120). Every example on it is a doctest the test suite runs, so what follows a>>>is what the library answered rather than what somebody expected it to.Python 3.10 through 3.14, free-threaded 3.14t included; 3.7, 3.8 and 3.9 are gone. 3.9 went end-of-life in 2025-10, and it had become the only interpreter pulling a second toolchain into the lock: 35 of 132 packages resolved twice, mypy 1.19 beside 2.3 and pytest 8.4 beside 9.1, so the 3.9 jobs were testing against releases nobody else ran. The project is managed with uv, the lint gate is
.pre-commit-config.yamland CI runs exactly it, and btclib.readthedocs.io has an API in it again — it had been fifteen module titles with nothing under them.
v2023.7.12¶
This is the last release supporting py37.
Major changes include:
added first draft implementation of descriptors
added first draft implementation of script engine
added taproot psbt fields
improved bip32 derivation (speeded-up, added one more test)
supported py3.12 with btclib_libsecp256k1
updated toolchain
v2023.5.30¶
Major changes include:
Fix circular import between
scriptandb32
v2023.2.3¶
Major changes include:
enabled libsecp256k1 by default
improved documentation
used generic containers (Sequence instead of list, Mapping instead of dict) where possible
v2023.1.17¶
Major changes include:
exported names per module (bip32, block, ec, ecc, mnemonic, psbt, script, tx)
added join_psbts and join_txs
refactored bip340_nonce
improved integration of libsecp256k1
added secp256k1-py test vectors
improved typing
added SECURITY, CONTRIBUTING, bug report and feature request templates
added pre-commit hooks
adopted mypy –strict and from __future__ import annotations
v2022.12.31¶
Major changes include:
add support for PSBT’s taproot fields (BIP370)
added support for Python 3.11
fixed the OpenSSL 3.x RIPEMD160 issue in btclib/hashes.py
added CONTRIBUTING and SECURITY
solved issue #73 Re-import Tx subclasses into btclib.tx
v2022.7.20¶
Major changes include:
by default ssa, dsa and point multiplication are now sped up using btclib_libsecp256k1; this provides an 8 times speed up in benchmarks and 3 times in real world applications.
v2022.5.3¶
Major changes includes:
dropped Python 3.6 support
added support for btclib_libsecp256k1
the hashes.fingerprint function, removed in the previous version, has been reinstated in the to_pub_key module
encode_num and decode_num have been moved from script.op_codes to utils
op_pushdata and op_str have been renamed to serialize_bytes_command and serialize_str_command
script.op_codes has been removed and its functions merged in script
script serialization is now more consistent: all integers, even small ones, are now considered like bytes. To put small integers on the stack OP_X must be used explicitly. Using integers directly will lead to larger scripts that will be likely to be rejected by the network as not standard
check_validity is now correctly propagated inside each function
v2022.2.9¶
This is the latest release to support Python 3.6
Major changes includes:
added bech32m
added Taproot support
introduced ScriptPubKey class
used script_type instead of prefix/wit_ver for b58/b32 address functions
split up op_int in op_num and op_int
prevented bip32 account derivation with arbitrarily high index
ensured der.Sig.r is congruent to a valid x-coordinate
renamed ScriptToken as Command
moved witness and script_pub_key into script folder
removed dataclasses_json dependency
introduced submodules
renamed Tx.tx_id as Tx.id
renamed deserialize as parse
renamed signature functions: trailing underscore marks hash-reduced versions
updated BIP32 test vectors
moved continuous testing from TravisCI to Github Actions
simplified configuration files
fixed pylint and flake8 warnings
v2020.12.19¶
Major changes includes:
added secp256k1 point multiplication based on efficient endomorphism
fixed ssa batch verification functions’ logic
enforced snake_case variable naming convention, e.g. ‘script_pub_key’, etc.
added BIP32KeyOrigin, BIP32KeyPath, and BIP32KeyPaths
adopted str instead of bytes as default type for BIP32 keys, bms sigs, PSBTs, addresses, and WIFs; base58 and bech32 encodings keep returning bytes, like base64
cleaned up and refactored all dataclasses, now using serialize/deserialized and possibly b58encode/b58decode, b64encode/b64decode, etc.
renamed TxIn.witness as TxIn.script_witness
fixed Witness management in TxIn and Tx, including equality operator
consolidated sig_hash code into sig_hash module
added more script_pub_key functions: assert_p2pkh, is_p2pkh, etc.
v2020.11.23¶
Major changes includes:
updated BIP340 (Schnorr signature) implementation as per the latest changes in bitcoin core
refactored PsbtIn, PsbtOut, and Psbt
added legacy sighash
made btclib compatible with Python 3.6
ssa.det_nonce now returns an int
moved tagged_hash from ssa into hashes module
added CurveGroup._y_aff_from_jac and removed unused methods
discontinued y_odd in favor of y_even as y-symmetry tiebreaker criterium
removed nonce input from dsa.sign and ssa.sign (only available from _sign functions)
cleaned up Exception handling, avoided bare/broad except
introduced btclib Exceptions that can be discriminated from regular Exceptions
v2020.11.10¶
Major changes includes:
removed TypedDict in favor of dataclass; this also restored the ability of using btclib with Python 3.7
introduced dataclasses_json as requirement, used to serialize to file the json representation of dataclasses
Network is now a dataclass
bip32: BIP32KeyData is now a dataclass instead of dict, its data member have to be accessed accordingly. Consequently, where previously it was bip32.deserialize(xkey), now it is bip32.BIP32KeyData.deserialize(xkey)
bip32: added str_from_bip32_path and bytes_from_bip32_path
bip32: made the index an int (not bytes) to avoid byteorder ambiguity. Consequently, where previously it was xkey_dict[“index”][0] < 0x80, now it is xkey_dict.index < 0x80000000
bip32: local “./” derivation, opposed to absolute “m/” derivation, is not available anymore
bip32: indexes_from_bip32_path now returns list[int] instead of Tuple[list[bytes], bool] losing the “absolute derivation” bool
bms: serialize/deserialize have been renamed encode/decode as they include the base64 (de)encoding, not jut the plain (de)serialization
Block: fixed bug in difficulty calculation
introduced first beta version of HdKeyPaths, PartialSigs, PsbtIn, PsbtOut, and Psbt data classes and their associated helper functions
refactored Diffie-Hellman and ANSI-X9.63-KDF
introduced assorted elliptic curve point multiplication algorithms
script: renamed Token as ScriptToken
script: encode/decode have been renamed as serialize/deserialize as they were not encoding at all; the previous serialize/deserialize which had varint(len()) before serialized data are not available anymore
alias: few definitions have moved in their relevant modules from which they can be imported
pytest: enforced pytest > 6
pytest: using as many processes as the available CPU cores
v2020.8.21¶
Major changes includes:
added BlockHeader and Block data classes
added OutPoint, TxIn, TxOut, and TX data classes
added segwit_v0 sighash
added PsbtIn, PsbtOut, and Psbt data classes for partially signed bitcoin transactions (BIP174)
moved from unitest to pytest, including revision of error messages and tests’ logic
v2020.5.11¶
Major changes includes:
switched to tox testing, gradually moving to pytest testing (while discontinuing unittest)
adopted black formatter and added compatible flake8 and isort configurations
added Integer as hex-string or bytes representation of an int
adopted the function signature of dsa.sign for rfc6979.rfc6979 too
added CURVES dictionary of all elliptic curves, e.g.: from btclib.curve import CURVES; ec = CURVES[‘secp256k1’]
renamed prvkey_info_xyz as prvkey_info_xyz
renamed pubkey_info_xyz as pubkey_info_xyz
renamed bytes_from_key as pubkeyinfo_from_key
renamed network_from_xpub as network_from_xkeyversion extending its functionality to xprv too
redundant spaces (and also tabs, newlines, returns, formfeeds, etc.) are removed from mnemonic phrases using “ “.join(mnemonic.split()) before any encoding of the mnemonic
moved the WordLists class into the mnemonic module and removed the wordlist module
moved all entropy functions into the entropy module
entropy.generate has been renamed as entropy.randbinstr
v2020.5.3¶
Major changes includes:
Fixed Schnorr MuSig and Threshold Signature
Generic public/private key accepted wherever PubKey is expected (except for Schnorr where a public key cannot be discriminated as different from a private key)
P2PK and P2MS now handle also compressed public keys
added gen_keys to dsa, ssa, bms, so that now all the standard gen_keys, sign, and verify functions are available
Wherever an input/output parameter sequence had ‘compressed: bool, network: str’, the order has been inverted resulting in ‘network: str, compressed: bool’. Affected functions: base58address.p2pkh, base58wif.wif_from_prvkey, to_prvkey.prvkey_info_from_prvkey, to_pubkey._bytes_from_xpub, to_pubkey.bytes_from_key, to_pubkey.pubkey_info_from_prvkey, hashes.hash160_from_pubkey, secpoint.bytes_from_point,
renamed mxprv_from_bip39_mnemonic and mxprv_from_electrum_mnemonic
made entropy the first input parameter of mnemonic_from_entropy
improved size checks for bytes_from_octets
entropy.generate_entropy has been renamed as entropy.generate
v2020.4.21¶
Major changes includes:
The Bitcoin Message Signing module btcmsg.py has been rename bms.py
refactored address/scriptPubKey
consolidated wif_from_* in wif_from_prvkey
removed ambiguous functions going from prv_key to address
refactored to_pub and to_prv functions
added network <-> prefix <-> curve functions in network module
removed trailing _scriptPubKey suffix from the function names in the scriptPubKey module
tests are now distributed as btclib.tests subpackage
removed p2pkh_from_xpub, p2wpkh_p2sh_from_xpub, and p2wpkh_from_xpub (use p2pkh, p2wpkh, and p2wpkh instead)
introduced CurveGroup and CurveSubGroup as grand-parent and parent of Curve. Also, renamed ec._p as ec.p and removed default parameters from double_mult
renamed ec.opposite(P) as ec.negate(P)
the usage of DER (de)serialization is advocated through dsa.(de)serialize, similarly to ssa.(de)serialize and bms.(de)serialize; therefore, the corresponding der.py functions have been renamed with leading underscore
introduced XXXSig and XXXSigTuple for XXX = DSA, BTCMSG, and SSA
v2020.4.7¶
This is a major release that complete the far-reaching refactoring initiated with v2020.3.20; it requires Python>=3.8 as we use TypedDict.
Chances are this release might break most projects using btclib, but the changes were long overdue and should be stable in time. Functions and modules have been renamed to better reflect the library design; anyway, because of the clearer logic, it should not be hard to find the new versions. The module alias.py might be a good entry point to familiarize with the new design.
Most notably the library is now able to accept any representation of private keys as input, with all the WIF/BIP32/bytes/integer conversion auto-magically being taken care of. The same apply to public key BIP32/SEC-bytes/tuple conversion. As usual, whenever bytes are accepted, hex-string or text string are accepted too, as appropriate.
Moreover, major changes include:
updated the Schnorr implementation to BIP340 proposed standard
refactored BIP32 for increased derivation efficiency
improved documentation
extended functional test case coverage (as usual tests cover 100% of the code base)
removed all mypy warnings (but one)