Firebreak

Reference implementation

Bond tree

The Taproot bond output, its script leaves and the pre-signed notice, release and slash transactions.

Source
8 files, 797 lines
Tests
3 files, 33 cases
Paper
sec:settlement

Treaty bonds on Bitcoin

Purpose

The paper's settlement layer holds each operator or sovereign bond in a Taproot output whose spending conditions are fixed at creation, and gets the destination restrictions Bitcoin script lacks by pre-signing a small transaction tree (Protocol Specifications, "Bond output and transaction tree"). This module builds those outputs and transactions with bitcoinjs-lib 7 and @bitcoinerlab/secp256k1, computes the MuSig2 internal key with @scure/btc-signer, checks control blocks with an independent BIP341 implementation on @noble/curves, applies the bond policy as a pure function, and offers a local checker for its own leaf templates. The regtest suite proves every path against a real bitcoind.

Keys

  • P: the operator's key (or the state's, for a sovereign bond), 33-byte compressed; its x-only form goes in the leaves.
  • K_C: the Inspection Council's FROST group key (src/frost), so the Council's signature on a slash or notice is a t-of-n FROST signature, produced through ROAST (src/roast).
  • Internal key of both outputs: KeyAgg(KeySort([P, K_C])) per BIP327 MuSig2 (bondInternalKey). The tests reproduce BIP327's key-aggregation vectors.

The key path is cooperative but unused. Spending by key path would need the FROST council to act as a single MuSig2 signer (nested threshold MuSig2). There is no standardized, audited construction for that, so this reference spends only by script path. Flag for the authors: either specify a nested scheme or say that cooperative spends use the 2-of-2 leaf.

Outputs (scripts are exact; decompiled and compared in the tests)

B (bond output), P2TR(KeyAgg(P, K_C), [
    leaf A, 2-of-2:        <P> OP_CHECKSIGVERIFY <K_C> OP_CHECKSIG                    (Notice; Adjudicated slash)
    [ leaf C, crypto slash: OP_SHA256 <C> OP_EQUALVERIFY <P> OP_CHECKSIG               (STAND-IN, see below)
      leaf R, recovery:     <tau_rec> OP_CHECKLOCKTIMEVERIFY OP_DROP <P> OP_CHECKSIG ] ])

N (notice output), P2TR(KeyAgg(P, K_C), [
    [ leaf W, release:      <tau_w> OP_CHECKSEQUENCEVERIFY OP_DROP <P> OP_CHECKSIG
      leaf A, 2-of-2:       (Adjudicated slash) ]
    [ leaf C, crypto slash, leaf R, recovery ] ])

P2A anchor: OP_1 <0x4e73>, 240 sat

The paper's Notice and Adjudicated-slash leaves have the same condition (P and K_C), so they are one leaf; the signed transaction (notice or slash) tells them apart. Numbers are minimally encoded (tau_w = 16 becomes OP_16, 144 becomes 0x9000). Witnesses: 2-of-2 [sig_KC, sig_P, leaf, control]; crypto slash [sig_P, preimage, leaf, control]; release or recovery [sig_P, leaf, control]. Signatures are 64-byte BIP340 with SIGHASH_DEFAULT, so each commits to every input and output of its transaction.

The crypto-slash leaf is a stand-in. The paper completes this path with an optimistic verification protocol (BitVM2-style connectors) for a violation predicate. Here a revealed SHA-256 preimage of a commitment C stands for "the verification game ended in the challenger's favor". It shows the transaction shape (the operator's pre-signed slash, completed without the Council) and nothing of BitVM2's security: whoever learns the preimage can complete the slash.

Transaction tree

 bond creation: operator signs Tx_notice, Tx_release, Tx_slash (adjudicated and crypto, from B and from N);
                slash pre-signatures are deposited with the Council (presignBond)

   funding --> B --Tx_notice (2-of-2: P pre-signed, K_C co-signs to begin withdrawal)--> N
               |                                                                         |
               |--Tx_slash_B (2-of-2: P pre-signed, K_C completes) --> slash outputs     |--Tx_release (P alone, nSequence = tau_w) --> operator
               |--Tx_slash_B (crypto stand-in: P pre-signed + preimage) --> same outputs |--Tx_slash_N (2-of-2 or crypto stand-in) --> slash outputs
               |--Tx_recover (P alone, nLockTime = tau_rec) --> operator                 |--Tx_recover (P alone, nLockTime = tau_rec) --> operator
               '--rollover (2-of-2, both sign by rule) --> fresh bond B'

Every transaction is version 3 (BIP431 TRUC, which also satisfies BIP68's version >= 2), pays a fee frozen at creation (params.fee), and ends in a 240-sat P2A anchor. Slash outputs pay the bounty pool and a challenger reward output in fixed basis points (the last destination takes the rounding remainder). Because the operator's signature commits to the outputs, the Council (or a challenger) can complete a slash but cannot change it.

Policy (checkBondPolicy(bond, nowHeight, maxDetectPlusAdjudicate))

A pure function of the bond's parameters, its state and the height. It reports violations and four decisions:

  • tau_w must be 1..65,535 blocks (BIP68) and at least the time to resolve a pending claim, or an operator under investigation can notice and release first.
  • tau_rec must be a block height after creation, more than the longest detection plus adjudication time after it.
  • The rollover window W (renewals stop at tau_rec - W) must exceed the license period plus detection and adjudication, so a violation under the last license can still be slashed before tau_rec.
  • mustRollOver from tau_rec - W until rolled over; renewalAllowed is false inside an unrolled rollover window, after tau_rec, or when any rule is broken.
  • Sovereign bonds on withdrawal (paper, exit protocol: "returned only after a final inspection confirms that no violation occurred during membership"): the bond stays slashable until its final inspection. releaseAllowed (the Council co-signing the notice) is false until a final-inspection record exists and is clean, and tau_rec must fall after the scheduled final inspection plus adjudication, or the party could recover the bond alone before it. Recovery opening before the record exists is reported as a violation.

Fees

Pre-signed transactions freeze their fee. Each carries a P2A anchor (standard since Bitcoin Core 28) so anyone can fee-bump it by CPFP with a v3 child, submitted as a package (submitpackage). CPFP never changes the parent's txid, which matters: Tx_release and Tx_slash_N spend Tx_notice's output, so their pre-signatures commit to Tx_notice's txid. RBF of a pre-signed transaction, or adding fee inputs with ANYONECANPAY, would change txids and void the pre-signatures below it. TRUC limits the child to 1,000 vB, which bounds pinning. Bitcoin Core 32.1 accepted a v3 slash plus a CPFP child as a package in the regtest suite.

Timelock limits

BIP68 relative locks live in 16 bits: at most 65,535 blocks, about 455 days. So tau_w must be in 1..65,535 and the recovery delay must be an absolute CLTV height, which gives each bond a fixed expiry tau_rec. A violation found after tau_rec cannot be slashed reliably (the operator can take the bond alone and races any slash), hence rollover. csvSequence, cltvHeight, bondTemplate and checkBondPolicy reject out-of-range values.

Security properties and the tests that check them

Unit tests in test/bond/bond.test.ts and test/bond/policy.test.ts; regtest in test/regtest/bond.test.ts (bitcoind 32.1.0). Every forbidden case in regtest is rejected by testmempoolaccept and also by generateblock, so it is invalid by consensus, not only by relay policy.

Property Unit test Regtest (bitcoind)
Internal key is BIP327 KeyAgg of P and K_C (BIP327 vectors reproduced), order-independent, in every control block "MuSig2 internal key" all spends use it
Leaves are exactly the paper's scripts; B and N have the paper's leaf sets "leaf scripts" all paths spend them
Control blocks verify under an independent BIP341 check; wrong leaf, output, parity or path fail "control blocks ..." accepted spends
Sighashes are stable; the operator's pre-signature commits to every output "sighashes are stable", "commits to every output" bitcoind accepts the signatures
Notice needs the Council's co-signature "notice completes with the council's co-signature ..." notice completed by ROAST, mined
Release only after tau_w blocks "release completes only with nSequence >= tau_w ..." rejected non-BIP68-final right after notice and at tau_w - 1; mined at tau_w
Adjudicated slash needs the Council: operator-only fails "rejects a slash signed only by the operator" rejected (stack size; operator twice: Invalid Schnorr signature), from B and from N
Council cannot redirect a slash "rejects a council-redirected slash ..." rejected Invalid Schnorr signature
Council slashes from B, and from N during the notice period, with a FROST signature "a 3-of-5 council signature completes ..." both mined; the B slash's signature came from ROAST with one malicious and one silent signer
Crypto-slash stand-in completes with the preimage only "crypto-slash stand-in completes with the preimage ..." wrong preimage rejected (OP_EQUALVERIFY); from B and from N mined
Recovery from B and from N only from tau_rec, operator alone "recovery from B and from N needs nLockTime >= tau_rec ..." rejected non-final one block early, Locktime requirement not satisfied with an earlier lock, Invalid Schnorr signature when the Council signs; both mined at tau_rec
Anchors are spendable for CPFP "every transaction is version 3 and ends in a 240-sat P2A anchor" slash + child accepted by submitpackage, both mined
Tx_notice's txid is independent of its witness, so release and slash-from-N are pre-signed first "the notice's txid does not depend on its witness ..." all N spends were pre-signed before the notice was completed
Rollover, renewal and parameter rules policy.test.ts "bond policy" (with a fast-check property) n/a
Sovereign bond stays slashable until a clean final inspection; tau_rec after the scheduled final inspection policy.test.ts "sovereign bond on withdrawal" n/a

The local checker (checkLeafSpend) recognizes only this module's four leaf shapes. It is a teaching and testing aid, not a script interpreter; bitcoind is the authority.

Interpretations

  • Interpretation: one 2-of-2 leaf serves Notice and Adjudicated slash (identical conditions; two identical leaves would only add a tree level).
  • Interpretation: KeyAgg order. KeySort first, so the internal key does not depend on who is listed first.
  • Interpretation: the crypto-slash commitment C is a bond parameter; see the stand-in note above.
  • Interpretation: N keeps a recovery leaf, as the paper lists it, so a notice that neither releases nor is slashed (the Council vanished mid-withdrawal) is not stuck.
  • Interpretation: slash destinations are a parameter. The tests use a bounty pool (key-path P2TR under K_C) at 80% and a challenger-reward escrow at 20%.
  • Interpretation: rollover window W > lambda + D and tau_w >= adjudication time are our reading of "rolled over by rule ... well before tau_rec" and "giving the Council time to act".
  • tau_rec is a block height, never a Unix time.

Open questions for the paper authors

  1. MuSig2 with a FROST key (above): specify a nested threshold MuSig2 scheme, or state that cooperative spends use the script-path 2-of-2.
  2. Notice and Adjudicated slash are the same condition. Nothing in script stops the Council and operator from using the "notice" leaf to sign a slash or vice versa; only the pre-signed transactions differ. The paper lists them as separate leaves.
  3. Who receives the challenger reward? The operator pre-signs the slash with SIGHASH_ALL before any challenger exists, so the reward output can only pay a fixed escrow, and paying the real challenger takes a second, Council-signed transaction. It is not automatic. SIGHASH_SINGLE|ANYONECANPAY would let the completer add an output but would also let the Council take the unassigned value.
  4. The cryptographic (BitVM2) slash is not built (stand-in only). BitVM2-style protocols fix the asserter and challengers in a graph pre-signed at setup; here the challenger is unknown at setup and the accused operator must pre-sign the graph. The paper should say who may assert, how the operator's pre-signatures cover unknown asserters, and what the operator's contest transaction spends.
  5. The appeal period cannot be enforced by script on B. A CSV on B counts from B's confirmation, long past. On-chain enforcement needs an intermediate "slash pending" output; as built, the appeal period is procedural (the Council withholds its signature).
  6. Recovery race. From tau_rec both a slash and the recovery are valid spends; the first to confirm wins. The rollover margin should be stated.
  7. Sovereign bond timing. A withdrawing party's final inspection must finish, and any finding be adjudicated, before tau_rec. If inspection is delayed (the party obstructs access), the bond reaches tau_rec and the party recovers it alone. The paper should say whether withdrawal forces a rollover to a later tau_rec, and who signs it if the party refuses.
  8. Changing the Council key (as opposed to resharing it) invalidates K_C in every live bond and forces a rollover of all of them.
  9. Spending the bounty pool by key path needs FROST signing with the BIP341 tweak; the wasm wrapper does not expose that yet.
  10. Partial slashes need one pre-signed slash per fraction; the paper slashes whole bonds.

Source

The code

src/bond/check.ts118 lines
/**
 * A local checker for spends of the bond's own leaf templates.
 *
 * This is not a script interpreter. It recognizes exactly the three leaf shapes
 * this module builds (2-of-2, hash lock + key, CLTV + key, CSV + key), checks the control block
 * with the independent BIP341 code in taproot.ts, checks BIP340 signatures over
 * the BIP341 sighash, and applies the BIP65/BIP112 rules to the transaction's
 * own fields. Bitcoin Core is the authority; the regtest suite asks it.
 */
import { opcodes, script, Transaction } from "bitcoinjs-lib";
import * as ecc from "@bitcoinerlab/secp256k1";
import { equalBytes } from "@noble/curves/utils.js";
import { sha256 } from "@noble/hashes/sha2.js";
import { tapLeafHash, verifyControlBlock } from "./taproot";
import { LOCKTIME_THRESHOLD, SEQUENCE_DISABLE_FLAG } from "./timelock";

/** Result of a local check. */
export type CheckResult = { readonly ok: true; readonly leaf: LeafKind } | { readonly ok: false; readonly reason: string };

/** Which template a leaf matched. */
export type LeafKind = "two-of-two" | "hashlock" | "cltv" | "csv";

/** Optional chain context for the timelock finality checks. */
export interface ChainContext {
  /** Height of the block the spend would be mined in. */
  readonly spendHeight?: number;
  /** Height the spent output was confirmed at. */
  readonly prevoutHeight?: number;
}

const SEQUENCE_TYPE_FLAG = 1 << 22;
const SEQUENCE_MASK = 0xffff;

/** Checks one BIP340 signature (64 bytes = SIGHASH_DEFAULT, 65 = explicit type) for input 0. */
function sigOk(tx: Transaction, prevScript: Uint8Array, value: bigint, leaf: Uint8Array, sig: Uint8Array, key: Uint8Array): boolean {
  if (sig.length !== 64 && sig.length !== 65) return false;
  const type = sig.length === 65 ? sig[64]! : Transaction.SIGHASH_DEFAULT;
  if (sig.length === 65 && type === Transaction.SIGHASH_DEFAULT) return false;
  const h = tx.hashForWitnessV1(0, [prevScript], [value], type, tapLeafHash(leaf));
  return ecc.verifySchnorr(h, key, sig.subarray(0, 64));
}

/** Reads a minimally encoded script number from a decompiled chunk. */
function num(chunk: number | Uint8Array | undefined): number | null {
  if (chunk === undefined) return null;
  if (typeof chunk === "number") {
    if (chunk >= opcodes.OP_1! && chunk <= opcodes.OP_16!) return chunk - opcodes.OP_1! + 1;
    return null;
  }
  return script.number.decode(chunk, 5);
}

/** Checks input 0 of `tx` spending a P2TR output (`prevScript`, `value`) through one of the bond's leaf templates. */
export function checkLeafSpend(tx: Transaction, prevScript: Uint8Array, value: bigint, ctx: ChainContext = {}): CheckResult {
  const input = tx.ins[0];
  if (!input) return { ok: false, reason: "no input" };
  const w = input.witness;
  if (w.length < 3) return { ok: false, reason: "witness too short for a script-path spend" };
  if (prevScript.length !== 34 || prevScript[0] !== 0x51 || prevScript[1] !== 0x20) return { ok: false, reason: "prevout is not P2TR" };
  const control = w[w.length - 1]!;
  const leaf = w[w.length - 2]!;
  const stack = w.slice(0, -2);
  if (!verifyControlBlock(prevScript.subarray(2), leaf, control)) return { ok: false, reason: "control block does not commit to this leaf" };

  const c = script.decompile(leaf);
  if (!c) return { ok: false, reason: "leaf does not parse" };

  if (c.length === 4 && c[1] === opcodes.OP_CHECKSIGVERIFY && c[3] === opcodes.OP_CHECKSIG) {
    const [k1, , k2] = c as [Uint8Array, number, Uint8Array, number];
    if (stack.length !== 2) return { ok: false, reason: "2-of-2 needs exactly two signatures" };
    const [s2, s1] = stack as [Uint8Array, Uint8Array];
    if (!sigOk(tx, prevScript, value, leaf, s1, k1)) return { ok: false, reason: "first key's signature (P_op) invalid" };
    if (!sigOk(tx, prevScript, value, leaf, s2, k2)) return { ok: false, reason: "second key's signature (P_c) invalid" };
    return { ok: true, leaf: "two-of-two" };
  }

  if (c.length === 5 && c[0] === opcodes.OP_SHA256 && c[2] === opcodes.OP_EQUALVERIFY && c[4] === opcodes.OP_CHECKSIG) {
    const [, commitment, , key] = c as [number, Uint8Array, number, Uint8Array, number];
    if (stack.length !== 2) return { ok: false, reason: "hash-lock leaf needs a signature and a preimage" };
    const [sig, preimage] = stack as [Uint8Array, Uint8Array];
    if (!equalBytes(sha256(preimage), commitment)) return { ok: false, reason: "preimage does not match the commitment" };
    if (!sigOk(tx, prevScript, value, leaf, sig, key)) return { ok: false, reason: "signature invalid" };
    return { ok: true, leaf: "hashlock" };
  }

  if (c.length === 5 && c[2] === opcodes.OP_DROP && c[4] === opcodes.OP_CHECKSIG) {
    const lock = num(c[0]);
    const key = c[3] as Uint8Array;
    if (lock === null || lock < 0) return { ok: false, reason: "bad lock operand" };
    if (stack.length !== 1) return { ok: false, reason: "single-key leaf needs one signature" };

    if (c[1] === opcodes.OP_CHECKLOCKTIMEVERIFY) {
      if (input.sequence === 0xffffffff) return { ok: false, reason: "CLTV: input sequence is final" };
      if ((lock < LOCKTIME_THRESHOLD) !== (tx.locktime < LOCKTIME_THRESHOLD)) return { ok: false, reason: "CLTV: lock type mismatch" };
      if (tx.locktime < lock) return { ok: false, reason: `CLTV: nLockTime ${tx.locktime} < ${lock}` };
      if (ctx.spendHeight !== undefined && tx.locktime >= ctx.spendHeight) {
        return { ok: false, reason: `non-final: nLockTime ${tx.locktime} not below spend height ${ctx.spendHeight}` };
      }
      if (!sigOk(tx, prevScript, value, leaf, stack[0]!, key)) return { ok: false, reason: "signature invalid" };
      return { ok: true, leaf: "cltv" };
    }

    if (c[1] === opcodes.OP_CHECKSEQUENCEVERIFY) {
      const seq = input.sequence;
      if (tx.version < 2) return { ok: false, reason: "CSV: version < 2" };
      if (seq & SEQUENCE_DISABLE_FLAG) return { ok: false, reason: "CSV: sequence disable flag set" };
      if ((seq & SEQUENCE_TYPE_FLAG) !== (lock & SEQUENCE_TYPE_FLAG)) return { ok: false, reason: "CSV: lock type mismatch" };
      if ((seq & SEQUENCE_MASK) < (lock & SEQUENCE_MASK)) return { ok: false, reason: `CSV: sequence ${seq & SEQUENCE_MASK} < ${lock}` };
      if (ctx.spendHeight !== undefined && ctx.prevoutHeight !== undefined && ctx.spendHeight - ctx.prevoutHeight < (seq & SEQUENCE_MASK)) {
        return { ok: false, reason: "non-BIP68-final: prevout too young" };
      }
      if (!sigOk(tx, prevScript, value, leaf, stack[0]!, key)) return { ok: false, reason: "signature invalid" };
      return { ok: true, leaf: "csv" };
    }
  }
  return { ok: false, reason: "leaf matches no bond template" };
}

View on GitHub

src/bond/policy.ts103 lines
/**
 * Bond policy as a pure function: the off-chain rules the Council's issuance
 * software applies to each bond (rollover, renewal, withdrawal), and the
 * parameter conditions that make the on-chain timelocks safe. All heights and
 * durations are in blocks.
 */
import { LOCKTIME_THRESHOLD, MAX_RELATIVE_BLOCKS } from "./timelock";

/** A sovereign bond's withdrawal record. */
export interface WithdrawalRecord {
  /** Height at which notice of withdrawal was given. */
  readonly noticeHeight: number;
  /** Height by which the final inspection is scheduled to finish. */
  readonly finalInspectionScheduled: number;
  /** Set once the final inspection is recorded; `clean` means no violation during membership. */
  readonly finalInspection?: { readonly height: number; readonly clean: boolean };
}

/** The facts about one bond that the policy needs. */
export interface BondPolicyInput {
  readonly kind: "operator" | "sovereign";
  readonly createdAt: number;
  /** tau_rec (absolute height). */
  readonly recoveryHeight: number;
  /** tau_w (relative blocks). */
  readonly noticeDelay: number;
  /** Rollover window W: the bond must be rolled over before tau_rec - W. */
  readonly rolloverWindow: number;
  /** Longest license the bond's holder can be issued, in blocks (lambda). */
  readonly licensePeriod: number;
  /** True once this bond has been moved into a fresh bond output. */
  readonly rolledOver: boolean;
  readonly withdrawal?: WithdrawalRecord;
}

/** Optional limits beyond the main one. */
export interface PolicyOptions {
  /** Longest time to resolve a pending claim once detected (defaults to maxDetectPlusAdjudicate). */
  readonly maxAdjudicate?: number;
}

/** What the policy says about a bond at a height. */
export interface BondPolicyReport {
  /** Parameter or state rules the bond breaks; empty when the bond is sound. */
  readonly violations: readonly string[];
  readonly ok: boolean;
  /** At or past tau_rec - W and not yet rolled over. */
  readonly inRolloverWindow: boolean;
  /** The holder must roll this bond over now. */
  readonly mustRollOver: boolean;
  /** Renewals may be issued to the holder. */
  readonly renewalAllowed: boolean;
  /** The Council may co-sign the notice (begin returning the bond). */
  readonly releaseAllowed: boolean;
  /** tau_rec has passed: the holder alone can recover the bond, and it can no longer be relied on. */
  readonly recoveryOpen: boolean;
}

/** Applies the bond rules at `nowHeight`, given the longest detection-plus-adjudication time. */
export function checkBondPolicy(
  bond: BondPolicyInput,
  nowHeight: number,
  maxDetectPlusAdjudicate: number,
  opts: PolicyOptions = {},
): BondPolicyReport {
  const v: string[] = [];
  const D = maxDetectPlusAdjudicate;
  const A = opts.maxAdjudicate ?? D;
  const { recoveryHeight: tRec, noticeDelay: tW, rolloverWindow: W } = bond;

  if (!Number.isInteger(tW) || tW < 1 || tW > MAX_RELATIVE_BLOCKS) v.push(`tau_w must be 1..${MAX_RELATIVE_BLOCKS} blocks (BIP68)`);
  if (tW < A) v.push("tau_w is shorter than the time to resolve a pending claim");
  if (!Number.isInteger(tRec) || tRec >= LOCKTIME_THRESHOLD || tRec <= bond.createdAt) v.push("tau_rec must be a block height after creation");
  if (tRec - bond.createdAt <= D) v.push("tau_rec must exceed the longest detection plus adjudication time");
  // Renewals stop at tau_rec - W; the last license runs lambda more; a violation in it must be adjudicated before tau_rec.
  if (W <= bond.licensePeriod + D) v.push("rollover window must exceed the license period plus detection and adjudication");

  const recoveryOpen = nowHeight >= tRec;
  const inRolloverWindow = !bond.rolledOver && nowHeight >= tRec - W;

  let releaseAllowed = !recoveryOpen;
  if (bond.kind === "sovereign") {
    const w = bond.withdrawal;
    // A sovereign bond is returned only after a final inspection confirms no violation during membership.
    releaseAllowed = releaseAllowed && w?.finalInspection?.clean === true;
    if (w) {
      if (tRec <= w.finalInspectionScheduled + A) v.push("tau_rec must fall after the scheduled final inspection plus adjudication");
      if (recoveryOpen && !w.finalInspection) v.push("recovery opened before the final inspection was recorded");
    }
  }

  const ok = v.length === 0;
  return {
    violations: v,
    ok,
    inRolloverWindow,
    mustRollOver: inRolloverWindow && !recoveryOpen,
    renewalAllowed: ok && !recoveryOpen && !inRolloverWindow && !(bond.kind === "sovereign" && bond.withdrawal),
    releaseAllowed: ok && releaseAllowed,
    recoveryOpen,
  };
}

View on GitHub

src/bond/presign.ts101 lines
/**
 * The operator's pre-signatures at bond creation, and how the Council or a
 * challenger completes them. Per the paper, the operator signs the notice,
 * release and slash transactions when the bond is created; the slash
 * pre-signatures are deposited with the Council. Each operator signature commits
 * to the whole transaction, so a completer can finish it but not change it.
 */
import type { Transaction } from "bitcoinjs-lib";
import {
  BOND_LEAF,
  buildNotice,
  buildRelease,
  buildSlash,
  leafSighash,
  NOTICE_LEAF,
  noticeOutput,
  setCryptoSlashWitness,
  setSingleSigWitness,
  setTwoOfTwoWitness,
  signSchnorr,
  type BondTemplate,
  type Prevout,
} from "./tree";

/** One pre-signed transaction: its body, the sighash a co-signer must sign, and the operator's signature. */
export interface PreSignedTx {
  readonly tx: Transaction;
  readonly prevout: Prevout;
  readonly sighash: Uint8Array;
  readonly operatorSig: Uint8Array;
}

/** Everything the operator signs at creation. */
export interface PreSignedBond {
  readonly notice: PreSignedTx;
  readonly release: PreSignedTx;
  readonly adjudicatedSlash: { readonly fromBond: PreSignedTx; readonly fromNotice: PreSignedTx };
  readonly cryptoSlash: { readonly fromBond: PreSignedTx; readonly fromNotice: PreSignedTx };
}

/** Which output a slash spends. */
export type SlashSource = "fromBond" | "fromNotice";

/** Signs one transaction body through one leaf. */
function presign(tx: Transaction, prevout: Prevout, leaf: Uint8Array, priv: Uint8Array, aux?: Uint8Array): PreSignedTx {
  const sighash = leafSighash(tx, prevout, leaf);
  return { tx, prevout, sighash, operatorSig: signSchnorr(sighash, priv, aux) };
}

/** The operator's pre-signatures over the notice, release and all four slash transactions for a funded bond. */
export function presignBond(t: BondTemplate, bond: Prevout, operatorPriv: Uint8Array, aux?: Uint8Array): PreSignedBond {
  const noticeTx = buildNotice(t, bond);
  const n = noticeOutput(t, noticeTx);
  const slashB = buildSlash(t, bond);
  const slashN = buildSlash(t, n);
  return {
    notice: presign(noticeTx, bond, t.bond.leaves[BOND_LEAF.notice]!, operatorPriv, aux),
    release: presign(buildRelease(t, n), n, t.notice.leaves[NOTICE_LEAF.release]!, operatorPriv, aux),
    adjudicatedSlash: {
      fromBond: presign(slashB, bond, t.bond.leaves[BOND_LEAF.adjudicatedSlash]!, operatorPriv, aux),
      fromNotice: presign(slashN, n, t.notice.leaves[NOTICE_LEAF.adjudicatedSlash]!, operatorPriv, aux),
    },
    cryptoSlash: {
      fromBond: presign(slashB.clone(), bond, t.bond.leaves[BOND_LEAF.cryptoSlash]!, operatorPriv, aux),
      fromNotice: presign(slashN.clone(), n, t.notice.leaves[NOTICE_LEAF.cryptoSlash]!, operatorPriv, aux),
    },
  };
}

/** Council co-signs the notice to begin a cooperative withdrawal. */
export function completeNotice(t: BondTemplate, p: PreSignedBond, councilSig: Uint8Array): Transaction {
  const tx = p.notice.tx.clone();
  setTwoOfTwoWitness(tx, t.bond, BOND_LEAF.notice, p.notice.operatorSig, councilSig);
  return tx;
}

/** The operator's release after tau_w. */
export function completeRelease(t: BondTemplate, p: PreSignedBond): Transaction {
  const tx = p.release.tx.clone();
  setSingleSigWitness(tx, t.notice, NOTICE_LEAF.release, p.release.operatorSig);
  return tx;
}

/** Council completes an adjudicated slash with its (FROST) signature over the pre-signed transaction. */
export function completeAdjudicatedSlash(t: BondTemplate, p: PreSignedBond, from: SlashSource, councilSig: Uint8Array): Transaction {
  const s = p.adjudicatedSlash[from];
  const tx = s.tx.clone();
  const [out, leaf] = from === "fromBond" ? [t.bond, BOND_LEAF.adjudicatedSlash] : [t.notice, NOTICE_LEAF.adjudicatedSlash];
  setTwoOfTwoWitness(tx, out, leaf, s.operatorSig, councilSig);
  return tx;
}

/** A challenger completes the crypto-slash stand-in by revealing the preimage. */
export function completeCryptoSlash(t: BondTemplate, p: PreSignedBond, from: SlashSource, preimage: Uint8Array): Transaction {
  const s = p.cryptoSlash[from];
  const tx = s.tx.clone();
  const [out, leaf] = from === "fromBond" ? [t.bond, BOND_LEAF.cryptoSlash] : [t.notice, NOTICE_LEAF.cryptoSlash];
  setCryptoSlashWitness(tx, out, leaf, s.operatorSig, preimage);
  return tx;
}

View on GitHub

src/bond/scripts.ts71 lines
/**
 * Tapscript leaves of the bond and notice outputs, and the outputs the
 * pre-signed transactions pay to.
 */
import { opcodes, script } from "bitcoinjs-lib";
import { hexToBytes } from "@noble/hashes/utils.js";
import { cltvHeight, csvSequence } from "./timelock";

/**
 * BIP341's suggested NUMS point H: its x coordinate is SHA-256 of the
 * uncompressed encoding of the generator G, so no one knows its discrete log.
 * It is the internal key of every bond output, which therefore has no key path.
 */
export const NUMS_H: Uint8Array = hexToBytes("50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0");

/** Checks a 32-byte x-only key (shape only; the leaf builders cannot know if it is on the curve). */
function xOnly(label: string, k: Uint8Array): Uint8Array {
  if (k.length !== 32) throw new Error(`${label} must be a 32-byte x-only key`);
  return k;
}

/** 2-of-2: `<P_op> OP_CHECKSIGVERIFY <P_c> OP_CHECKSIG`. Serves Notice, Rollover and Adjudicated slash (same condition). */
export function twoOfTwoLeaf(pOp: Uint8Array, pC: Uint8Array): Uint8Array {
  return script.compile([xOnly("P_op", pOp), opcodes.OP_CHECKSIGVERIFY, xOnly("P_c", pC), opcodes.OP_CHECKSIG]);
}

/** Recovery: `<T_rec> OP_CHECKLOCKTIMEVERIFY OP_DROP <P_op> OP_CHECKSIG`, the operator alone after height T_rec. */
export function recoverLeaf(tRec: number, pOp: Uint8Array): Uint8Array {
  return script.compile([
    script.number.encode(cltvHeight(tRec)),
    opcodes.OP_CHECKLOCKTIMEVERIFY,
    opcodes.OP_DROP,
    xOnly("P_op", pOp),
    opcodes.OP_CHECKSIG,
  ]);
}

/** Release: `<delta> OP_CHECKSEQUENCEVERIFY OP_DROP <P_op> OP_CHECKSIG`, the operator alone delta blocks after notice confirms. */
export function releaseLeaf(deltaBlocks: number, pOp: Uint8Array): Uint8Array {
  return script.compile([
    script.number.encode(csvSequence(deltaBlocks)),
    opcodes.OP_CHECKSEQUENCEVERIFY,
    opcodes.OP_DROP,
    xOnly("P_op", pOp),
    opcodes.OP_CHECKSIG,
  ]);
}

/**
 * STAND-IN for the cryptographic slash: `OP_SHA256 <C> OP_EQUALVERIFY <P_op> OP_CHECKSIG`.
 * The paper completes this path with a BitVM-style optimistic verification game. Here
 * the revealed preimage of C stands for "the game ended in the challenger's favor";
 * whoever knows the preimage can complete the operator's pre-signed slash. It shows the
 * transaction shape only and has none of BitVM2's security.
 */
export function cryptoSlashLeaf(commitment: Uint8Array, pOp: Uint8Array): Uint8Array {
  if (commitment.length !== 32) throw new Error("commitment must be a 32-byte SHA-256 hash");
  return script.compile([opcodes.OP_SHA256, commitment, opcodes.OP_EQUALVERIFY, xOnly("P_op", pOp), opcodes.OP_CHECKSIG]);
}

/** Pay-to-Anchor output script `OP_1 <0x4e73>` (standard to create and spend since Bitcoin Core 28). */
export const P2A_SCRIPT: Uint8Array = Uint8Array.of(0x51, 0x02, 0x4e, 0x73);

/** Value of each anchor output: 240 sat, the P2A dust threshold, so the parent needs no ephemeral-dust rules. */
export const ANCHOR_VALUE = 240n;

/** P2TR output script for a 32-byte output key: `OP_1 <32 bytes>`. */
export function p2trScript(outputKey: Uint8Array): Uint8Array {
  return script.compile([opcodes.OP_1, xOnly("output key", outputKey)]);
}

View on GitHub

src/bond/taproot.ts97 lines
/**
 * Taproot outputs with a script tree and no key path (internal key NUMS H):
 * construction with bitcoinjs-lib, and an independent BIP341 control-block check
 * written against @noble/curves.
 */
import { initEccLib, payments, type Network } from "bitcoinjs-lib";
import * as ecc from "@bitcoinerlab/secp256k1";
import { schnorr, secp256k1 } from "@noble/curves/secp256k1.js";
import { concatBytes } from "@noble/hashes/utils.js";
import { bytesToNumberBE, equalBytes, numberToBytesBE } from "@noble/curves/utils.js";
import { NUMS_H } from "./scripts";

initEccLib(ecc);

/** BIP342 tapscript leaf version. */
export const LEAF_VERSION = 0xc0;

/** A script tree: a leaf script, or a pair of subtrees. */
export type LeafTree = Uint8Array | readonly [LeafTree, LeafTree];

/** A P2TR output with a script tree and internal key NUMS H. */
export interface TaprootOutput {
  /** scriptPubKey: OP_1 <output key>. */
  readonly script: Uint8Array;
  /** 32-byte tweaked output key Q. */
  readonly outputKey: Uint8Array;
  /** Always NUMS_H: no one can sign for it, so the output has no key path. */
  readonly internalKey: Uint8Array;
  /** Leaves in depth-first, left-to-right order. */
  readonly leaves: readonly Uint8Array[];
  /** Control block for each leaf, same order as `leaves`. */
  readonly controlBlocks: readonly Uint8Array[];
  readonly address: string;
}

type Taptree = { output: Uint8Array } | [Taptree, Taptree];

/** Converts a LeafTree to bitcoinjs-lib's Taptree, collecting leaves in order. */
function toTaptree(t: LeafTree, leaves: Uint8Array[]): Taptree {
  if (t instanceof Uint8Array) {
    leaves.push(t);
    return { output: t };
  }
  return [toTaptree(t[0], leaves), toTaptree(t[1], leaves)];
}

/** Builds a P2TR output for `tree` whose internal key is NUMS H, so every spend must use a script leaf. */
export function taprootOutput(tree: LeafTree, network: Network): TaprootOutput {
  const internalKey = NUMS_H;
  const leaves: Uint8Array[] = [];
  const scriptTree = toTaptree(tree, leaves);
  const base = payments.p2tr({ internalPubkey: internalKey, scriptTree, network });
  if (!base.output || !base.pubkey || !base.address) throw new Error("p2tr construction failed");
  const controlBlocks = leaves.map((leaf) => {
    const p = payments.p2tr({ internalPubkey: internalKey, scriptTree, redeem: { output: leaf, redeemVersion: LEAF_VERSION }, network });
    const w = p.witness;
    if (!w || w.length < 2) throw new Error("p2tr did not produce a control block");
    return w[w.length - 1]!;
  });
  return { script: base.output, outputKey: base.pubkey, internalKey, leaves, controlBlocks, address: base.address };
}

/** Bitcoin's CompactSize length prefix (scripts here are far below 0xfd bytes). */
function compactSize(n: number): Uint8Array {
  if (n < 0xfd) return Uint8Array.of(n);
  return Uint8Array.of(0xfd, n & 0xff, n >> 8);
}

/** BIP341 TapLeaf hash of a tapscript leaf. */
export function tapLeafHash(leaf: Uint8Array, version = LEAF_VERSION): Uint8Array {
  return schnorr.utils.taggedHash("TapLeaf", Uint8Array.of(version), compactSize(leaf.length), leaf);
}

/** Verifies a control block for `leaf` against output key Q, independently of bitcoinjs-lib (BIP341 rules). */
export function verifyControlBlock(outputKey: Uint8Array, leaf: Uint8Array, controlBlock: Uint8Array): boolean {
  if (controlBlock.length < 33 || (controlBlock.length - 33) % 32 !== 0) return false;
  const version = controlBlock[0]! & 0xfe;
  const parity = controlBlock[0]! & 1;
  const p = controlBlock.slice(1, 33);
  let k = tapLeafHash(leaf, version);
  for (let off = 33; off < controlBlock.length; off += 32) {
    const e = controlBlock.slice(off, off + 32);
    const [a, b] = bytesToNumberBE(k) < bytesToNumberBE(e) ? [k, e] : [e, k];
    k = schnorr.utils.taggedHash("TapBranch", concatBytes(a, b));
  }
  const t = bytesToNumberBE(schnorr.utils.taggedHash("TapTweak", concatBytes(p, k)));
  if (t >= secp256k1.Point.CURVE().n) return false;
  let P;
  try {
    P = schnorr.utils.lift_x(bytesToNumberBE(p));
  } catch {
    return false;
  }
  const Q = P.add(secp256k1.Point.BASE.multiply(t)).toAffine();
  return equalBytes(numberToBytesBE(Q.x, 32), outputKey) && Number(Q.y & 1n) === parity;
}

View on GitHub

src/bond/timelock.ts46 lines
/**
 * Bitcoin timelock limits that shape the bond.
 *
 * Relative locks (BIP68/BIP112, OP_CHECKSEQUENCEVERIFY) live in the low 16 bits
 * of nSequence, so a block-based relative lock is at most 65,535 blocks, about
 * 455 days at ten minutes a block. Any longer delay must be an absolute lock
 * (BIP65, OP_CHECKLOCKTIMEVERIFY), which gives every bond a fixed expiry height.
 */

/** Largest block-based relative lock BIP68 can express. */
export const MAX_RELATIVE_BLOCKS = 0xffff;
/** nLockTime values below this are block heights; at or above, Unix times. */
export const LOCKTIME_THRESHOLD = 500_000_000;
/** BIP68 disable flag (bit 31 of nSequence). */
export const SEQUENCE_DISABLE_FLAG = 0x80000000;
/** nSequence that enables nLockTime without signalling anything else. */
export const SEQUENCE_ENABLE_LOCKTIME = 0xfffffffe;
/** Mean block interval used only for human-readable durations. */
export const SECONDS_PER_BLOCK = 600;

/** Validates a block-based relative delay for CSV and returns the nSequence that satisfies it. */
export function csvSequence(blocks: number): number {
  if (!Number.isInteger(blocks) || blocks < 1 || blocks > MAX_RELATIVE_BLOCKS) {
    throw new RangeError(`relative lock must be 1..${MAX_RELATIVE_BLOCKS} blocks (BIP68), got ${blocks}`);
  }
  return blocks; // type flag (bit 22) clear = blocks; disable flag clear
}

/** Validates an absolute block height for CLTV. */
export function cltvHeight(height: number): number {
  if (!Number.isInteger(height) || height < 1 || height >= LOCKTIME_THRESHOLD) {
    throw new RangeError(`absolute lock must be a block height 1..${LOCKTIME_THRESHOLD - 1}, got ${height}`);
  }
  return height;
}

/** Approximate days for a number of blocks (ten-minute blocks). */
export function blocksToDays(blocks: number): number {
  return (blocks * SECONDS_PER_BLOCK) / 86400;
}

/** Chooses the lock type a delay needs: relative if it fits in BIP68, else absolute. */
export function lockKindFor(delayBlocks: number): "relative" | "absolute" {
  return delayBlocks <= MAX_RELATIVE_BLOCKS ? "relative" : "absolute";
}

View on GitHub

src/bond/tree.ts193 lines
/**
 * The bond's outputs and transactions, following the paper's Protocol
 * Specifications ("Bond output and transaction tree").
 *
 *   internal key (both outputs): BIP341 NUMS H, so there is no key path; every spend uses a leaf
 *
 *   B (bond)   leaves: [ 2-of-2 , [ crypto slash (stand-in) , recovery after tau_rec ] ]
 *   N (notice) leaves: [ [ release after tau_w , 2-of-2 ] , [ crypto slash (stand-in) , recovery after tau_rec ] ]
 *
 *   2-of-2 = <P> CHECKSIGVERIFY <K_C> CHECKSIG: Notice and Rollover (signed by rule) and the
 *   Adjudicated slash (P pre-signed, K_C completes); the signed transaction tells them apart.
 *
 * Every transaction is version 3 (TRUC) and carries a P2A anchor so it can be
 * fee-bumped by CPFP without changing its txid, which later pre-signatures commit to.
 */
import { Transaction, type Network } from "bitcoinjs-lib";
import * as ecc from "@bitcoinerlab/secp256k1";
import { hexToBytes } from "@noble/hashes/utils.js";
import { ANCHOR_VALUE, cryptoSlashLeaf, P2A_SCRIPT, recoverLeaf, releaseLeaf, twoOfTwoLeaf } from "./scripts";
import { tapLeafHash, taprootOutput, type TaprootOutput } from "./taproot";
import { cltvHeight, csvSequence, SEQUENCE_ENABLE_LOCKTIME } from "./timelock";

/** Transaction version for every bond transaction (BIP431 TRUC; also satisfies BIP68's version >= 2). */
export const TX_VERSION = 3;

/** One fixed destination of a slash, with its share of the slashed value in basis points. */
export interface SlashDestination {
  readonly label: string;
  readonly script: Uint8Array;
  readonly shareBps: number;
}

/** Everything fixed when the bond is created. */
export interface BondParams {
  readonly network: Network;
  /** Operator key P, 33-byte compressed (its x-only form goes in the leaves). */
  readonly operatorKey: Uint8Array;
  /** Council FROST group key K_C, 33-byte compressed. */
  readonly councilKey: Uint8Array;
  /** tau_w: blocks the notice output must age before release (1..65535). */
  readonly noticeDelay: number;
  /** tau_rec: absolute height from which P alone can recover B or N. */
  readonly recoveryHeight: number;
  /** SHA-256 commitment for the crypto-slash stand-in (see cryptoSlashLeaf). */
  readonly cryptoCommitment: Uint8Array;
  /** Where a slash pays (bounty pool, challenger reward), in fixed proportions summing to 10000 bps. */
  readonly slashDestinations: readonly SlashDestination[];
  /** Where release and recovery pay the operator. */
  readonly operatorPayout: Uint8Array;
  /** Fee frozen into each pre-signed transaction, in sat. */
  readonly fee: bigint;
}

/** The two output templates derived from the parameters. */
export interface BondTemplate {
  readonly params: BondParams;
  readonly bond: TaprootOutput;
  readonly notice: TaprootOutput;
}

/** An outpoint with the value and script it holds. */
export interface Prevout {
  /** Txid in explorer (display) byte order. */
  readonly txid: string;
  readonly vout: number;
  readonly value: bigint;
  readonly script: Uint8Array;
}

/** Leaf indexes in the bond output B (Notice, Rollover and Adjudicated slash share the 2-of-2 leaf). */
export const BOND_LEAF = { notice: 0, rollover: 0, adjudicatedSlash: 0, cryptoSlash: 1, recover: 2 } as const;
/** Leaf indexes in the notice output N. */
export const NOTICE_LEAF = { release: 0, adjudicatedSlash: 1, cryptoSlash: 2, recover: 3 } as const;

/** x-only form of a 33-byte compressed key. */
function xOnly(k: Uint8Array): Uint8Array {
  if (k.length !== 33 || (k[0] !== 2 && k[0] !== 3)) throw new Error("expected a 33-byte compressed key");
  return k.slice(1);
}

/** Validates parameters and builds the B and N output templates. */
export function bondTemplate(params: BondParams): BondTemplate {
  csvSequence(params.noticeDelay);
  cltvHeight(params.recoveryHeight);
  const total = params.slashDestinations.reduce((a, d) => a + d.shareBps, 0);
  if (params.slashDestinations.length === 0 || total !== 10_000) throw new Error("slash shares must sum to 10000 bps");
  if (params.slashDestinations.some((d) => !Number.isInteger(d.shareBps) || d.shareBps <= 0)) {
    throw new Error("slash shares must be positive integers");
  }
  const p = xOnly(params.operatorKey);
  const kc = xOnly(params.councilKey);
  const pair = twoOfTwoLeaf(p, kc);
  const crypto = cryptoSlashLeaf(params.cryptoCommitment, p);
  const recover = recoverLeaf(params.recoveryHeight, p);
  const bond = taprootOutput([pair, [crypto, recover]], params.network);
  const notice = taprootOutput([[releaseLeaf(params.noticeDelay, p), pair], [crypto, recover]], params.network);
  return { params, bond, notice };
}

/** A transaction with one input spending `prev`, version 3. */
function spend(prev: Prevout, sequence: number, locktime = 0): Transaction {
  const tx = new Transaction();
  tx.version = TX_VERSION;
  tx.locktime = locktime;
  tx.addInput(hexToBytes(prev.txid).reverse(), prev.vout, sequence);
  return tx;
}

/** Value left for the payload outputs after the frozen fee and the anchor. */
function payload(t: BondTemplate, value: bigint): bigint {
  const v = value - t.params.fee - ANCHOR_VALUE;
  if (v <= 0n) throw new Error("bond value does not cover the fee and the anchor");
  return v;
}

/** Tx_notice: B -> N, plus an anchor (2-of-2 leaf: operator pre-signs, council co-signs to begin withdrawal). */
export function buildNotice(t: BondTemplate, bond: Prevout): Transaction {
  const tx = spend(bond, SEQUENCE_ENABLE_LOCKTIME);
  tx.addOutput(t.notice.script, payload(t, bond.value));
  tx.addOutput(P2A_SCRIPT, ANCHOR_VALUE);
  return tx;
}

/** The notice output of a Tx_notice as a Prevout. */
export function noticeOutput(t: BondTemplate, notice: Transaction): Prevout {
  const out = notice.outs[0]!;
  return { txid: notice.getId(), vout: 0, value: out.value, script: t.notice.script };
}

/** Tx_rollover: B -> the bond output of a fresh template (later tau_rec, new tree), plus an anchor; P and K_C sign by rule. */
export function buildRollover(t: BondTemplate, bond: Prevout, next: BondTemplate): Transaction {
  const tx = spend(bond, SEQUENCE_ENABLE_LOCKTIME);
  tx.addOutput(next.bond.script, payload(t, bond.value));
  tx.addOutput(P2A_SCRIPT, ANCHOR_VALUE);
  return tx;
}

/** Tx_release: N -> operator after tau_w blocks (nSequence = tau_w), plus an anchor. */
export function buildRelease(t: BondTemplate, notice: Prevout): Transaction {
  const tx = spend(notice, csvSequence(t.params.noticeDelay));
  tx.addOutput(t.params.operatorPayout, payload(t, notice.value));
  tx.addOutput(P2A_SCRIPT, ANCHOR_VALUE);
  return tx;
}

/** Tx_slash (from B or N, either slash leaf): the value split over the fixed destinations, plus an anchor. */
export function buildSlash(t: BondTemplate, from: Prevout): Transaction {
  const tx = spend(from, SEQUENCE_ENABLE_LOCKTIME);
  const value = payload(t, from.value);
  let left = value;
  t.params.slashDestinations.forEach((d, i) => {
    const last = i === t.params.slashDestinations.length - 1;
    const v = last ? left : (value * BigInt(d.shareBps)) / 10_000n;
    left -= v;
    tx.addOutput(d.script, v);
  });
  tx.addOutput(P2A_SCRIPT, ANCHOR_VALUE);
  return tx;
}

/** Tx_recover (from B or N): operator with nLockTime = tau_rec, plus an anchor. */
export function buildRecover(t: BondTemplate, from: Prevout): Transaction {
  const tx = spend(from, SEQUENCE_ENABLE_LOCKTIME, t.params.recoveryHeight);
  tx.addOutput(t.params.operatorPayout, payload(t, from.value));
  tx.addOutput(P2A_SCRIPT, ANCHOR_VALUE);
  return tx;
}

/** BIP341 script-path sighash (SIGHASH_DEFAULT) for input 0 spending `prev` through `leaf`. */
export function leafSighash(tx: Transaction, prev: Prevout, leaf: Uint8Array): Uint8Array {
  return tx.hashForWitnessV1(0, [prev.script], [prev.value], Transaction.SIGHASH_DEFAULT, tapLeafHash(leaf));
}

/** A single-key BIP340 signature (the operator's), with optional auxiliary randomness for reproducibility. */
export function signSchnorr(sighash: Uint8Array, privateKey: Uint8Array, aux?: Uint8Array): Uint8Array {
  return ecc.signSchnorr(sighash, privateKey, aux);
}

/** Sets the witness for a 2-of-2 leaf: [sig_c, sig_op, leaf, control]. P's signature is checked first. */
export function setTwoOfTwoWitness(tx: Transaction, output: TaprootOutput, leafIndex: number, sigOperator: Uint8Array, sigCouncil: Uint8Array): void {
  tx.setWitness(0, [sigCouncil, sigOperator, output.leaves[leafIndex]!, output.controlBlocks[leafIndex]!]);
}

/** Sets the witness for the crypto-slash stand-in: [sig_op, preimage, leaf, control]. */
export function setCryptoSlashWitness(tx: Transaction, output: TaprootOutput, leafIndex: number, sigOperator: Uint8Array, preimage: Uint8Array): void {
  tx.setWitness(0, [sigOperator, preimage, output.leaves[leafIndex]!, output.controlBlocks[leafIndex]!]);
}

/** Sets the witness for a single-signature leaf (release or recover): [sig, leaf, control]. */
export function setSingleSigWitness(tx: Transaction, output: TaprootOutput, leafIndex: number, sig: Uint8Array): void {
  tx.setWitness(0, [sig, output.leaves[leafIndex]!, output.controlBlocks[leafIndex]!]);
}

View on GitHub

src/bond/index.ts68 lines
/**
 * Treaty bonds on Bitcoin, per the paper's Protocol Specifications: Taproot outputs
 * with no key path (internal key NUMS H), script leaves for notice / rollover /
 * adjudicated slash (2-of-2), a crypto-slash stand-in, CSV release and CLTV recovery,
 * the operator's pre-signed transaction tree, and the bond policy. See SPEC.md.
 */
export {
  ANCHOR_VALUE,
  cryptoSlashLeaf,
  NUMS_H,
  P2A_SCRIPT,
  p2trScript,
  recoverLeaf,
  releaseLeaf,
  twoOfTwoLeaf,
} from "./scripts";
export { LEAF_VERSION, tapLeafHash, taprootOutput, verifyControlBlock, type LeafTree, type TaprootOutput } from "./taproot";
export {
  blocksToDays,
  cltvHeight,
  csvSequence,
  lockKindFor,
  LOCKTIME_THRESHOLD,
  MAX_RELATIVE_BLOCKS,
  SECONDS_PER_BLOCK,
  SEQUENCE_DISABLE_FLAG,
  SEQUENCE_ENABLE_LOCKTIME,
} from "./timelock";
export {
  BOND_LEAF,
  bondTemplate,
  buildNotice,
  buildRecover,
  buildRelease,
  buildRollover,
  buildSlash,
  leafSighash,
  NOTICE_LEAF,
  noticeOutput,
  setCryptoSlashWitness,
  setSingleSigWitness,
  setTwoOfTwoWitness,
  signSchnorr,
  TX_VERSION,
  type BondParams,
  type BondTemplate,
  type Prevout,
  type SlashDestination,
} from "./tree";
export {
  completeAdjudicatedSlash,
  completeCryptoSlash,
  completeNotice,
  completeRelease,
  presignBond,
  type PreSignedBond,
  type PreSignedTx,
  type SlashSource,
} from "./presign";
export {
  checkBondPolicy,
  type BondPolicyInput,
  type BondPolicyReport,
  type PolicyOptions,
  type WithdrawalRecord,
} from "./policy";
export { checkLeafSpend, type ChainContext, type CheckResult, type LeafKind } from "./check";

View on GitHub