Taproot is not another hash wrapper: encoding P2TR behind one interface
A service that issues deposit addresses usually grows its encoders in order: P2PKH first, then P2WPKH nested in P2SH, then native segwit. By the third one the shape of the problem looks settled. Hash the compressed public key, wrap the digest in whatever envelope the format wants, return a string. Taproot breaks that shape. A P2TR address does not carry a hash of the key you derived; it carries a curve point computed from it, and an encoder that only knows how to hash cannot produce one.
I have been building custodial wallets and on-chain payment flows since 2018, and this is the kind of difference that is cheap to paper over and expensive to get wrong. An address produced with the hashing habit still looks like an address. It has a valid checksum, a wallet will accept it as a destination, coins will land on it, and nobody will ever be able to spend them. The failure is silent at exactly the moment you want it loud.
What follows is how I handled it in chain-addresses, a small Python package that derives deposit addresses from an account extended public key, with no private key anywhere in the process.
The constraint: one interface over four different computations#
The whole point of the package is that code holding an encoder does not know which chain it is serving. Everything satisfies one protocol:
@runtime_checkable
class AddressEncoder(Protocol):
"""Turns a compressed public key into an address for one chain and format."""
name: str
def encode(self, public_key: bytes) -> str:
"""Return the address for the 33-byte compressed *public_key*."""
...So the issuing path is the same sentence regardless of format:
from chain_addresses import ExtendedPublicKey, get_encoder
account = ExtendedPublicKey.parse(account_xpub)
deposit = account.derive("0/17")
get_encoder("bitcoin-p2tr").encode(deposit.public_key)That uniformity is the design goal, and it is also the trap. When three implementations of a protocol are the same computation under different wrappers, the fourth one gets written by analogy instead of by specification.
Three formats, one digest#
Here is what the pre-Taproot encoders actually do:
def _key_hash(public_key: bytes) -> bytes:
_point(public_key)
return hash160(public_key)
@dataclass(frozen=True)
class P2PKH:
name: str
version: int
def encode(self, public_key: bytes) -> str:
return b58check_encode(bytes([self.version]) + _key_hash(public_key))
@dataclass(frozen=True)
class P2SHP2WPKH:
name: str
version: int
def encode(self, public_key: bytes) -> str:
redeem_script = b"\x00\x14" + _key_hash(public_key)
return b58check_encode(bytes([self.version]) + hash160(redeem_script))
@dataclass(frozen=True)
class P2WPKH:
name: str
hrp: str
def encode(self, public_key: bytes) -> str:
return bech32.encode(self.hrp, 0, _key_hash(public_key))Three formats, one digest. hash160 over the 33 compressed bytes, then Base58Check with a version byte, or Base58Check over a second hash of a redeem script, or bech32 with witness version 0. The key stays an opaque string of bytes the whole way through.
The one detail worth noticing is the first line of _key_hash. It calls _point and throws the result away. _point wraps decompress and converts its ValueError into an AddressError, so a 33-byte blob that is not a point on secp256k1 gets rejected before anything is hashed. hash160 has no opinion about curves: it will digest garbage and hand back a perfectly well-formed address for a key that does not exist. That validation is the only reason the hashed encoders touch the curve at all.
The Taproot address is a point#
Taproot output keys are x-only: 32 bytes, the x coordinate, with the even-y point implied. And the key in the address is not the key you derived. It is that key, normalized to even y, shifted by a scalar that commits to its own x coordinate:
def _tagged_hash(tag: str, message: bytes) -> bytes:
prefix = sha256(tag.encode("ascii")).digest()
return sha256(prefix + prefix + message).digest()
def _taproot_output_key(public_key: bytes) -> bytes:
x, y = _point(public_key)
if y % 2:
# Taproot keys are x-only, so the internal key is always the even-y point.
y = FIELD_PRIME - y
tweak = int.from_bytes(_tagged_hash("TapTweak", x.to_bytes(32, "big")), "big")
if not 0 < tweak < CURVE_ORDER:
raise AddressError("taproot tweak is outside the curve order")
output = point_add((x, y), point_from_scalar(tweak))
if output is None:
raise AddressError("taproot tweak cancelled the internal key")
return output[0].to_bytes(32, "big")
@dataclass(frozen=True)
class P2TR:
name: str
hrp: str
def encode(self, public_key: bytes) -> str:
return bech32.encode(self.hrp, 1, _taproot_output_key(public_key))Four things here that no hashed encoder does.
It needs y. _point is no longer a validation whose result is discarded; the y coordinate is load-bearing. Recovering it means a modular square root over the field, which is the expensive part of the whole encoder.
It normalizes parity. A child public key derived through CKDpub has odd y about half the time. The internal key is defined as the even-y point with that x, so an odd y gets replaced by FIELD_PRIME - y before anything else happens. Skip that flip and the tweak lands on the wrong point, which produces a different x, which produces a different address: valid-looking, correctly checksummed, and unspendable by the signer that holds the seed. This is the specific silent failure I mentioned at the top, and it only shows up for roughly half your customers.
It hashes with a tag, twice. _tagged_hash prefixes the message with the SHA-256 of the tag repeated, which is what keeps a TapTweak digest from colliding with any other use of SHA-256 in the protocol. Writing this as a plain sha256(x) compiles, runs, and is wrong.
It commits to nothing but the key. No script root is appended to the message. That is the BIP86 key-path form, the only sensible shape for a deposit address, because there is no script tree to spend through.
The two degenerate outcomes, and why they are refusals#
Two results of that arithmetic cannot be encoded, and both get rejected rather than smoothed over.
A tweak outside (0, CURVE_ORDER) is not a scalar. point_from_scalar would raise a ValueError for it, which is the wrong exception to let cross an interface whose contract is AddressError. The explicit check turns a curve-module error into a format error at the boundary where the caller can actually interpret it.
A point_add returning None is the point at infinity, which has no x coordinate at all. Without the check, output[0] raises a TypeError, an error that tells the operator nothing about what happened.
Both are unreachable with any key you will ever derive. The tweak is a SHA-256 digest, so landing it above the curve order means finding a specific hash preimage, and cancelling the internal key means the tweak happening to be its negated discrete log. I did not write those two branches because they will fire. I wrote them because the alternative is an untyped exception escaping an encoder, and because an encoder that cannot return a wrong answer is easier to reason about than one that merely does not.
There is a useful contrast with the derivation side. ExtendedPublicKey.child has structurally the same two degenerate cases, an offset outside the curve order and a point_add that returns None, and there the BIP has a recovery: raise and tell the caller to retry at the next index. An encoder has no next index. The key it was handed is the key the ledger already committed to. Refusal is the only honest answer.
Where the difference leaks outside the encoder#
Two places, and both are easy to miss because they live in other modules.
The first is the checksum. Witness version 1 uses bech32m, not bech32, and getting it wrong produces a string that every conforming wallet rejects. In bech32.py the rule is written as a negation: _checksum_constant picks the bech32m constant for every witness version other than 0. Phrasing it as "not version 0" rather than "version 1" is deliberate, since it matches how the specification actually assigns the constants, so a future witness version does not require a patch to be encoded correctly.
The second is the derivation path. An encoder name says how an address is written; it does not say where the key came from, and the two are not independent. The purpose level is what tells a signer which output format an account holds, so chains.py keeps that metadata beside the names:
ChainInfo("bitcoin-p2wpkh", "bitcoin", Network.MAINNET, 84, 0),
ChainInfo("bitcoin-p2tr", "bitcoin", Network.MAINNET, 86, 0),
ChainInfo("bitcoin-testnet-p2tr", "bitcoin", Network.TESTNET, 86, 1),account_path("bitcoin-p2tr") # m/86'/0'/0'
account_path("bitcoin-testnet-p2tr") # m/86'/1'/0'Encoding children of an m/84'/0'/0' account as bc1p is the same class of mistake as skipping the parity flip: syntactically fine, scanned by nobody. Registering purpose 86 beside the encoder name means the question "which account do I ask the signer for" has one answer in one place.
What I would do differently#
I was tempted to let P2TR.encode accept a 32-byte x-only key, because that is what callers coming from Taproot-specific tooling tend to be holding. I kept the 33-byte compressed input so the protocol stays literally uniform and the parity normalization lives in exactly one function. The cost is real: a caller with an x-only key has to reattach a parity byte, and the encoder then spends a square root recovering the y it is about to normalize anyway. If I were serving signers directly rather than deposit ledgers, I would probably weigh that differently.
The other thing I would reconsider is _key_hash validating the point on every hashed address. It is a field exponentiation per address to catch an input that should never have reached the encoder. I keep it because the alternative is minting addresses for keys that do not exist, which is unrecoverable, and because the Taproot path pays that cost unavoidably. But it is a check at the wrong boundary: the parse step is where a bad key should die...
The interface is the payoff#
Four encoders, three of which hash some bytes and one of which multiplies a point by a scalar derived from its own coordinate. The caller derives a child key from an account xpub, looks up an encoder by name, and gets a string. That the fourth one is a different kind of computation is a fact about Bitcoin, not a fact the deposit ledger needs to carry around, provided somebody wrote the arithmetic out properly instead of reaching for hash160 a fourth time.