Test P2A signing and future SegWit address rendering
What changed, and why it matters
This commit is almost entirely new test code for the COLDCARD hardware wallet. It adds checks that the wallet correctly shows and signs transactions involving newer Bitcoin address types (SegWit v1 through v16, including P2A 'anchor' outputs). The only production code change is a comment update in shared/chains.py that clarifies how future SegWit addresses are rendered. There is no patch to a vulnerability and no change to wallet behavior; it improves test coverage and documentation.
No security action required. Treat as normal test/comment improvement. If auditing, verify that the existing render_address implementation already enforces the BIP-350 length and version constraints tested here.
Security signals we found
Adds test coverage for BIP-350 Bech32m address encoding/decoding
Adds malformed witness script rejection tests for render_address
Adds HSM whitelist tests for future SegWit (v1/v2) outputs
Adds P2A (SegWit v1, 2-byte program) transaction signing test
Production code change is comment-only in address rendering routine
Evidence from the diff
The commit adds BIP-350 Bech32m address test vectors, malformed witness-script rejection tests, HSM whitelist tests for future SegWit versions, and a P2A output signing test. The sole non-test change is in shared/chains.py, where comments are updated to reference BIP-350 and P2A and to note that witness versions 1-16 require Bech32m. No logic in render_address() is altered. The change increases confidence that future SegWit and P2A outputs are rendered and signed correctly, but it does not fix a known bug.
Changed components
shared/chains.py (comments only)testing/devtest/bip350.py (new test file)testing/test_hsm.pytesting/test_sign.pytesting/test_unit.pyInspect captured patch +206 / −2
### shared/chains.py
@@ -257,8 +257,9 @@ def render_address(cls, script):
if ll in (22, 34) and script[0] == 0 and script[1] in (0x14, 0x20) and (ll-2) == script[1]:
return ngu.codecs.segwit_encode(cls.bech32_hrp, script[0], script[2:])
- # segwit v1 (P2TR) and later segwit version
- # - BIP-141 allows a 2 to 40 byte program for any of them
+ # segwit v1 (P2TR, P2A) and future witness versions through v16
+ # - BIP-141 allows witness programs of 2 to 40 bytes
+ # - BIP-350 requires Bech32m encoding for witness versions 1 through 16
if 4 <= ll <= 42 and (OP_1 <= script[0] <= OP_16) and script[1] == ll - 2:
return ngu.codecs.segwit_encode(cls.bech32_hrp, script[0] - 80, script[2:])
### testing/devtest/bip350.py
@@ -0,0 +1,86 @@
+# (c) Copyright 2026 by Coinkite Inc. This file is covered by license found in COPYING-CC.
+#
+# Native SegWit address vectors from BIP-350 (Pieter Wuille, BSD-2-Clause):
+# https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki#test-vectors-for-v0-v16-native-segregated-witness-addresses
+# These test address codecs and output rendering, not input signing support.
+
+import ngu
+from ubinascii import unhexlify
+from chains import BitcoinMain, BitcoinTestnet
+
+
+valid = [
+ ('BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4',
+ '0014751e76e8199196d454941c45d1b3a323f1433bd6'),
+ ('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7',
+ '00201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262'),
+ ('bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kt5nd6y',
+ '5128751e76e8199196d454941c45d1b3a323f1433bd6751e76e8199196d454941c45d1b3a323f1433bd6'),
+ ('BC1SW50QGDZ25J',
+ '6002751e'),
+ ('bc1zw508d6qejxtdg4y5r3zarvaryvaxxpcs',
+ '5210751e76e8199196d454941c45d1b3a323'),
+ ('tb1qqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesrxh6hy',
+ '0020000000c4a5cad46221b2a187905e5266362b99d5e91c6ce24d165dab93e86433'),
+ ('tb1pqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesf3hn0c',
+ '5120000000c4a5cad46221b2a187905e5266362b99d5e91c6ce24d165dab93e86433'),
+ ('bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0',
+ '512079be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
+]
+
+for address, script_hex in valid:
+ script = unhexlify(script_hex)
+ hrp, version, program = ngu.codecs.segwit_decode(address)
+ assert hrp == address.lower().split('1')[0], address
+ assert version == (script[0] - 0x50 if script[0] else 0), address
+ assert program == script[2:], address
+ assert ngu.codecs.segwit_encode(hrp, version, program) == address.lower(), address
+ chain = BitcoinMain if hrp == 'bc' else BitcoinTestnet
+ assert chain.render_address(script) == address.lower(), address
+
+
+invalid = [
+ ('tc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vq5zuyut',
+ True, 'Invalid human-readable part'),
+ ('bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqh2y7hd',
+ False, 'Invalid checksum (Bech32 instead of Bech32m)'),
+ ('tb1z0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqglt7rf',
+ False, 'Invalid checksum (Bech32 instead of Bech32m)'),
+ ('BC1S0XLXVLHEMJA6C4DQV22UAPCTQUPFHLXM9H8Z3K2E72Q4K9HCZ7VQ54WELL',
+ False, 'Invalid checksum (Bech32 instead of Bech32m)'),
+ ('bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kemeawh',
+ False, 'Invalid checksum (Bech32m instead of Bech32)'),
+ ('tb1q0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vq24jc47',
+ False, 'Invalid checksum (Bech32m instead of Bech32)'),
+ ('bc1p38j9r5y49hruaue7wxjce0updqjuyyx0kh56v8s25huc6995vvpql3jow4',
+ False, 'Invalid character in checksum'),
+ ('BC130XLXVLHEMJA6C4DQV22UAPCTQUPFHLXM9H8Z3K2E72Q4K9HCZ7VQ7ZWS8R',
+ False, 'Invalid witness version'),
+ ('bc1pw5dgrnzv',
+ False, 'Invalid program length (1 byte)'),
+ ('bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7v8n0nx0muaewav253zgeav',
+ False, 'Invalid program length (41 bytes)'),
+ ('BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P',
+ False, 'Invalid program length for witness version 0 (per BIP141)'),
+ ('tb1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vq47Zagq',
+ False, 'Mixed case'),
+ ('bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7v07qwwzcrf',
+ False, 'zero padding of more than 4 bits'),
+ ('tb1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vpggkg4j',
+ False, 'Non-zero padding in 8-to-5 conversion'),
+ ('bc1gmk9yu',
+ False, 'Empty data section'),
+]
+
+for address, wrong_hrp, reason in invalid:
+ try:
+ hrp, version, program = ngu.codecs.segwit_decode(address)
+ except ValueError:
+ assert not wrong_hrp, (address, reason)
+ else:
+ # Unlike the BIP's decode(expected_hrp, address), the ngu API returns
+ # the actual HRP. The tc vector has a valid checksum but belongs to
+ # neither Bitcoin network in these vectors.
+ assert wrong_hrp, (address, reason)
+ assert hrp == 'tc', address
+ assert hrp not in (BitcoinMain.bech32_hrp, BitcoinTestnet.bech32_hrp), address
### testing/test_hsm.py
@@ -613,6 +613,35 @@ def test_whitelist_single(dev, start_hsm, tweak_rule, attempt_psbt, fake_txn, wi
tweak_rule(0, dict(whitelist=[dest, junk]))
attempt_psbt(psbt)
+@pytest.mark.parametrize('script', [bytes.fromhex('51024e73'), b'\x52\x10' + b'\x22'*16])
+def test_whitelist_future_segwit(script, quick_start_hsm, tweak_rule, tweak_hsm_attr,
+ attempt_psbt, fake_txn, use_testnet):
+ import bech32
+ use_testnet()
+ address = bech32.encode('tb', script[0] - 0x50, script[2:])
+ # No zero-value bypass: the output must match the whitelist itself.
+ quick_start_hsm(DICT(warnings_ok=True, rules=[dict(whitelist=[address])]))
+ def hack(psbt):
+ from ctransaction import CTransaction
+ from io import BytesIO
+ tx = CTransaction()
+ tx.deserialize(BytesIO(psbt.txn))
+ tx.vout[0].scriptPubKey = script
+ psbt.txn = tx.serialize()
+
+ raw = fake_txn(1, 2, segwit_in=True, psbt_v2=False,
+ outstyles=['p2pkh', 'p2wpkh'], change_outputs=[1],
+ outvals=[240, 100000000 - 10000 - 240], psbt_hacker=hack)
+ attempt_psbt(raw)
+ tweak_hsm_attr('warnings_ok', False)
+ attempt_psbt(raw, 'has 1 warning(s)')
+ tweak_hsm_attr('warnings_ok', True)
+
+ other = script[:-1] + bytes([script[-1] ^ 1])
+ tweak_rule(0, dict(whitelist=[bech32.encode('tb', other[0] - 0x50, other[2:])]))
+ attempt_psbt(raw, 'non-whitelisted')
+
+
def test_whitelist_multi(dev, start_hsm, tweak_rule, attempt_psbt, fake_txn, amount=5E6):
# sending to one whitelisted, and one non, etc.
junk = EXAMPLE_ADDRS[0]
### testing/test_sign.py
@@ -2727,6 +2727,76 @@ def test_send2taproot_addresss(fake_txn , start_sign, end_sign, cap_story, use_t
signed = end_sign(accept=True, finalize=False)
assert signed
+@pytest.mark.parametrize('testnet', [False, True])
+@pytest.mark.parametrize('psbt_v2', [False, True])
+@pytest.mark.parametrize('with_bip32_path', [False, True])
+@pytest.mark.parametrize('anchor_value', [0, 240])
+def test_sign_p2a_output(testnet, psbt_v2, with_bip32_path, anchor_value, fake_txn,
+ start_sign, end_sign, cap_story, use_testnet):
+ # An actual P2A output, not the zero-value P2WPKH in test_txn_v3_eph_anchor.
+ use_testnet(testnet)
+ anchor = bytes.fromhex('51024e73')
+ address = 'tb1pfees9rn5nz' if testnet else 'bc1pfeessrawgf'
+ # Ephemeral dust uses a zero-fee parent; a later child funds the package.
+ fee = 0 if anchor_value == 0 else 10000
+
+ def add_anchor(psbt):
+ # Host-supplied key paths must not make the anchor look like change.
+ psbt.outputs[1].bip32_paths = psbt.outputs[0].bip32_paths.copy() if with_bip32_path else {}
+ if psbt.version == 2:
+ psbt.txn_version = 3
+ psbt.outputs[1].script = anchor
+ else:
+ tx = CTransaction()
+ tx.deserialize(BytesIO(psbt.txn))
+ tx.nVersion = 3
+ tx.vout[1].scriptPubKey = anchor
+ psbt.txn = tx.serialize()
+
+ raw = fake_txn(1, 2, segwit_in=True, psbt_v2=psbt_v2,
+ outstyles=['p2wpkh', 'p2pkh'], change_outputs=[0],
+ fee=fee, outvals=[100000000 - fee - anchor_value, anchor_value],
+ psbt_hacker=add_anchor)
+ original = BasicPSBT().parse(raw)
+ if psbt_v2:
+ original.to_v0()
+ start_sign(raw, finalize=True)
+ title, story = cap_story()
+ assert title == 'OK TO SEND?'
+ assert address in story
+ assert 'to script' not in story
+ assert 'Sending to 1 not well understood script(s).' in story
+ assert 'Change back' in story
+ assert 'Consolidating' not in story
+ assert ('Non-standard zero value output(s).' in story) == (anchor_value == 0)
+
+ result = end_sign(accept=True, finalize=True)
+ tx = CTransaction()
+ tx.deserialize(BytesIO(result))
+ signature, pubkey = tx.wit.vtxinwit[0].scriptWitness.stack
+
+ assert tx.nVersion == 3
+ assert tx.serialize_without_witness() == original.txn
+ assert (tx.vout[1].nValue, tx.vout[1].scriptPubKey) == (anchor_value, anchor)
+ # Independently verify the funding input's BIP-143 signature, which commits
+ # to the P2A script and value as well as the change output.
+ from ctransaction import hash256
+ from pysecp256k1 import ec_pubkey_parse, ecdsa_signature_parse_der, ecdsa_verify
+ utxo = CTxOut()
+ utxo.deserialize(BytesIO(original.inputs[0].witness_utxo))
+ assert hash160(pubkey) == utxo.scriptPubKey[2:]
+ script_code = b'\x19\x76\xa9\x14' + utxo.scriptPubKey[2:] + b'\x88\xac'
+ assert signature[-1] == 1 # SIGHASH_ALL
+ digest = hash256(struct.pack('<i', tx.nVersion)
+ + hash256(b''.join(i.prevout.serialize() for i in tx.vin))
+ + hash256(b''.join(struct.pack('<I', i.nSequence) for i in tx.vin))
+ + tx.vin[0].prevout.serialize() + script_code
+ + struct.pack('<qI', utxo.nValue, tx.vin[0].nSequence)
+ + hash256(b''.join(o.serialize() for o in tx.vout))
+ + struct.pack('<II', tx.nLockTime, 1))
+ assert ecdsa_verify(ecdsa_signature_parse_der(signature[:-1]), ec_pubkey_parse(pubkey), digest)
+
+
def test_sign_taproot_input(fake_txn, start_sign, end_sign, cap_story):
psbt = fake_txn(1, 2, taproot_in=True)
start_sign(psbt)
### testing/test_unit.py
@@ -15,6 +15,9 @@ def test_remote_exec(sim_exec):
def test_codecs(sim_execfile):
assert sim_execfile('devtest/segwit_addr.py') == ''
+def test_bip350(sim_execfile):
+ assert sim_execfile('devtest/bip350.py') == ''
+
def test_b58decode_rejects_overlong_decoded_size(sim_exec):
result = sim_exec("""\
import ngu
@@ -311,6 +314,21 @@ def test_render_future_segwit(script_hex, ok, sim_exec):
assert rv == (bech32.encode('bc', spk[0] - 0x50, spk[2:]) if ok else 'ValueError')
+@pytest.mark.parametrize('script', [
+ b'', # empty script
+ b'\x51', # missing push length
+ b'\x52\x02' + b'\x11'*3, # trailing byte after program
+ b'\x51\x4c\x02\x4e\x73', # PUSHDATA1 instead of direct push
+ b'\x61\x02\x4e\x73', # opcode beyond OP_16
+ b'\x00\x02\x4e\x73', # invalid v0 program length
+])
+def test_render_invalid_witness_script(script, sim_exec):
+ rv = sim_exec('from chains import BitcoinMain\n'
+ 'try: BitcoinMain.render_address(%r)\n'
+ 'except ValueError: RV.write("rejected")' % script)
+ assert rv == 'rejected'
+
+
@pytest.mark.parametrize('patterns, paths, answers', [
(["m"], ("m", "m/2", "*", "any"), [True, False, False, False]),
(["any"], ("m", "m/2", "*", "1/2/3/4/5/6h/55h"), [True]*4),Why this scored 19/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.