Skip to content

Fix BTC segwit regex to accept testnet (tb) addresses - #477

Open
uttam12331 wants to merge 1 commit into
python-validators:masterfrom
uttam12331:fix-btc-testnet-segwit-prefix
Open

Fix BTC segwit regex to accept testnet (tb) addresses#477
uttam12331 wants to merge 1 commit into
python-validators:masterfrom
uttam12331:fix-btc-testnet-segwit-prefix

Conversation

@uttam12331

Copy link
Copy Markdown

Summary

btc_address() rejects every valid testnet bech32/segwit address.

The segwit branch is guarded by:

if value[:2] in ("bc", "tb")

so both mainnet (bc) and testnet (tb) HRPs are routed into the regex — but the regex only accepts bc or tc:

re.compile(r"^(bc|tc)[0-3][02-9ac-hj-np-z]{14,74}$").match(value)

tc is not a valid Bitcoin human-readable part (mainnet is bc, testnet is tb — see BIP173). Because the guard never lets a tc-prefixed value reach the regex, the tc alternative is dead code; the intended prefix is clearly tb. As written, any tb... address matches the guard, then fails the regex, and btc_address returns a ValidationError.

Reproduction

>>> from validators import btc_address
>>> btc_address("tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx")  # canonical BIP173 testnet
ValidationError(func=btc_address, ...)   # should be True
>>> btc_address("bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4")  # mainnet
True

Fix

-        re.compile(r"^(bc|tc)[0-3][02-9ac-hj-np-z]{14,74}$").match(value)
+        re.compile(r"^(bc|tb)[0-3][02-9ac-hj-np-z]{14,74}$").match(value)

Tests

Added the canonical BIP173 testnet address to the valid-address cases in tests/crypto_addresses/test_btc_address.py. It fails on the current code and passes with the fix; the full file passes (9 tests).

The bech32/segwit branch guard routes both `bc` (mainnet) and `tb` (testnet)
HRPs into the regex, but the regex accepted `(bc|tc)`. `tc` is not a valid
Bitcoin HRP (mainnet is `bc`, testnet is `tb`), and since the guard never
lets a `tc`-prefixed value reach the regex, that alternative was dead code.
As a result every valid testnet segwit address was rejected.

Change the regex alternative to `(bc|tb)` and add a testnet address test.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant