Skip to content

fix(TBC777M): enforce the escrow audit invariant - #522

Closed
codenlighten wants to merge 2 commits into
bitcoin-computer:stagingfrom
codenlighten:fix/tbc777m-escrow-audit
Closed

codenlighten wants to merge 2 commits into
bitcoin-computer:stagingfrom
codenlighten:fix/tbc777m-escrow-audit

Conversation

@codenlighten

Copy link
Copy Markdown

Summary

TBC777M's header promises that a withdraw succeeds only if totalDeposits >= totalWithdraws + totalFinalWithdraws,
"even if the escrow is malicious or buggy". The audit didn't enforce it:

  • withdraw() had its check inverted. if (0 < balance) throw rejected every escrow that still held funds
    and accepted every escrow that had authorized more than it received. On LTC regtest, a token that minted 3n
    deposited 2n into an escrow that authorized 1000n. The claim succeeded, and the token held 1001n.
  • withdrawFinal() always threw TypeError: Cannot read properties of undefined (reading 'includes'),
    because the constructor never set finalWithdrawn.
  • Final withdraws were left out of the balance. computeFinalWithdraws existed but was never called, and
    withdrawFinal compared the balance with the caller's own final amount only. Two final claims of 2n each against
    a 2n deposit both paid (3n minted, 5n afterwards).

This PR makes TBC777M check the same thing TBC777's EscrowAuditor already checks.

Changes (packages/TBC777/src/tbc777m.ts)

  • The constructor defaults finalWithdrawn: [].
  • getBalance() subtracts computeFinalWithdraws(states, root). Finals are counted from the claimed revision
    only, since they can only be paid from the last revision.
  • withdraw() and withdrawFinal() both reject when balance < 0n.
  • A new claimAmounts() helper, used by computeWithdraws and computeFinalWithdraws, requires claim amounts to
    be non-negative bigints, so a negative claim for a token that never withdraws can't offset a larger claim. Today
    such a claim happens to fail anyway: in-contract computer.sync returns a negative bigint as a string (-998n
    becomes "-998n"), and the sum throws Cannot mix BigInt and other types. This makes the rejection explicit and
    keeps it working if that changes.
  • finalWithdraws ?? [] in computeFinalWithdraws, so an escrow without the field still works for regular
    withdraws. getBalance() didn't read the field before.

Tests (packages/TBC777/test/tbc777m.test.ts, "escrow audit")

test on staging with this PR
rejects a withdraw of more than was deposited fails: the claim is accepted ✔
rejects a negative claim that would offset an over-claim fails: rejected only by the Cannot mix BigInt TypeError ✔
allows a partial withdraw while the escrow still holds the rest fails: Escrow balance (1) too low ✔
pays a final withdraw from the last revision fails: TypeError ✔
rejects final withdraws that together exceed the deposits fails: TypeError ✔
  • Full TBC777 package suite on LTC regtest: 52 passing, 1 pending (pre-existing), 0 failing.
  • The new tests passed in 8 of 9 repeated runs. The one miss was a 30 s waitForIndexed timeout in the node's
    indexer, not an assertion.
  • npx turbo run types lint passes: 33/33 tasks.

The new tests wait for the node where the audit needs it. They call waitForIndexed after each write, as in
#487, and before a withdraw they poll getTXOs({ rev, isConfirmed: true }) for the escrow revision, because the
in-contract prev needs a confirmed revision and mine() returns before the node has indexed the block. Without
those waits the tests failed intermittently with txn-mempool-conflict and Revision … not found by prev.

Notes

  • build/ is not rebuilt here, following how src/ changes usually land. Packages import build/src/index.js,
    so the fix reaches chess-app, chess-contracts and commodity only after a rebuild. I'm happy to add it to this PR
    if you prefer.
  • Contract code is fixed when a token is minted, so tokens minted from an earlier TBC777M module keep the old
    behaviour.
  • TBC777 is not changed by this PR.
  • fix(lib): replay reconciliation, author cache, and _root from the running method #521 (fix/security-review) only changes the TBC20 import in tbc777m.ts, and this patch applies cleanly on top of it.

withdraw() rejected when the audited balance was positive and accepted
when it was negative, so an escrow that authorized more than it received
could pay out, and an escrow that kept a remainder could not pay out at
all. Reject a negative balance instead, as TBC777 does.

getBalance() now also subtracts final withdraws, using the existing
computeFinalWithdraws helper, so several final claims can no longer
together exceed the deposits. Claim amounts must be non-negative bigints,
so a negative claim cannot offset a larger one in the totals. The
constructor now defaults finalWithdrawn, without which withdrawFinal()
always threw.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟢 Approval recommended

The security invariant enforcement and accompanying regression tests look correct, with only a minor doc-comment wording fix suggested.

Review effort: Lite
Findings: 1 Low severity

Open (1)
What changed in this PR

This PR hardens TBC777M’s on-chain escrow audit so withdrawals (regular and final) cannot inflate supply even if an escrow contract over-authorizes or behaves incorrectly, bringing TBC777M in line with TBC777’s existing audit invariant.

Changes:

  • Fixes the escrow balance check in withdraw() / withdrawFinal() to reject only when the audited balance is negative, and ensures finalWithdrawn is initialized.
  • Updates getBalance() to subtract authorized finalWithdraws (counted conservatively from the supplied revision) and adds claimAmounts() validation to reject negative / non-bigint claim amounts.
  • Adds an “escrow audit” test suite that exercises over-claims, negative-claim offsets, partial withdrawals, and final-withdraw behavior.
File Description
packages/​TBC777/​src/​tbc777m.ts Enforces non-negative audited escrow balance including final-withdraw authorizations; initializes finalWithdrawn; validates claim amount types/signs.
packages/​TBC777/​test/​tbc777m.test.ts Adds regression tests for malicious/buggy escrow authorization scenarios and indexing/confirmation timing.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines 182 to +185
if (this.finalWithdrawn.includes(rev)) throw new Error('Cannot withdraw multiple times')

const balance = await TBC777M.getBalance(rev, _root)
if (balance < 0n) throw new Error(`Escrow balance (${balance}) too low`)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 41e0266, which also regenerates build/src/tbc777m.*.

@ClemensLey

Copy link
Copy Markdown
Contributor

Thank you for the report. The inverted withdraw check, the missing finalWithdrawn initialization, and final claims being left out of the balance are all real.

We removed TBC777M in #530. It was the earlier token. Chess already uses TBC777, and nothing else in the repository imported TBC777M. TBC777 already enforces the same audit: it rejects a negative available balance, counts final claims, and refuses a non-positive claim.

Closing this pull request because the contract is gone.

@ClemensLey ClemensLey closed this Sep 29, 2026
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.

3 participants