{"id":"XE-8798","kind":"bounty","visibility":"public","source":"web","source_repo":"","source_ref":"","source_url":"","reporter_id":1930,"title":"core/supply: LeaseExpired escrow-burn branch lacks the settle/force-settle guard — archived settled leases get escrow double-counted (+Cost per lease)","area":"leasing-ledger","claimed_tier":"medium","assessed_tier":null,"verdict":"duplicate","duplicate_of":null,"tracked":false,"internal_ref":"","internal_url":"","status":"closed","closed_reason":"duplicate","github_state":"","disclosed_at":null,"award_xe":null,"award_approved":false,"paid_ref":"","created_at":"2026-11-12T00:58:16.825981+00:00","updated_at":"2026-11-20T00:04:29.355710+00:00","source_created_at":null,"told_at":"2026-11-20T00:04:29.398195+00:00","status_changed_at":"2026-11-20T00:04:29.363781+00:00","url":"https://bounty.xe.network/XE-8798","body":"# core/supply: LeaseExpired escrow-burn branch has no settle/force-settle guard — an archived lease whose settle (or force-settle) block is in the census gets its escrow counted twice (or counted as burned after refund), XUSD discrepancy = +Cost per lease\n\n**Track:** XE Bounty round 2, Track B3 (supply accounting coverage walk)\n**Repo / HEAD:** `xeprotocol/xe` @ `89a542ea51d38375299aee54c6c99102e9bfa666` (testnet-0005), static analysis only — nothing filed, nothing run.\n**Suggested tier:** Medium (ceiling 2,500 XE) — reasoning at the end; a Minor assessment (650 ceiling) is plausible because the trigger needs a narrow race, and this note says so openly.\n\n---\n\n## Summary\n\n`SupplyAuditor.walk()` (`core/supply.go`) derives the XUSD `EscrowBurned` term from **two independent branches** that are never reconciled with each other:\n\n1. the **settle branch** (L242–251): for every `lease_settle` block in the census it adds the lease's base cost to `EscrowBurned`;\n2. the **expired branch** (L280–284): for every lease *record* whose `State == LeaseExpired` it adds `l.Cost` to `EscrowBurned` again — with **no check** whether that lease also has a settle emission (or a force-settle refund) in the census.\n\nThe neighbouring stake branch *does* carry exactly this guard (`if _, settled := emissions[h]; settled { continue }`, L261–263). The expired branch does not. The two branches key off different sources — chain blocks vs. the mutable lease-record store — and a lease record can be flipped to `LeaseExpired` *after* its settle/force-settle block has already committed, because the node's archival path (`node/node.go` `archiveExpiredLease`) overwrites the lease record from a stale snapshot without re-reading state, without taking the per-lease lock that block ingestion takes, and because `DeletePendingSend` silently no-ops when the escrow was already deleted by the settle/force-settle commit.\n\nResult per affected lease (no renewals — the renewal interaction is the already-taken XE-4023 and is excluded here):\n\n- **Settle sub-variant:** the escrow `Cost` is counted in `EscrowBurned` **twice**. XE emission is counted once and correctly. XUSD `Destroyed` is overstated by exactly `Cost`, so `Accounted > Created` and `Discrepancy = +Cost` (µXUSD), `Conserved = false` — permanently, on every subsequent report, because the record stays `LeaseExpired`.\n- **Force-settle sub-variant:** the escrow was **refunded** to the consumer (ledger truth: burned = 0), but the expired branch still adds `Cost` to `EscrowBurned` → same `Discrepancy = +Cost`, `Conserved = false`.\n\nThe sign is a discriminator: the known renewal bug (XE-4023) produces a **negative** discrepancy (−Σ renewal costs); this one produces a **positive** discrepancy of exactly the base cost of each archived-after-resolution lease, with XE unaffected.\n\nThe auditor is the side that double-counts given its inputs; the enabling defect is the node's stale-state archival overwrite. Both fixes are given below. No funds are created, lost, or double-spent in the ledger itself — this is an integrity-canary defect in the audit layer, the same impact family as XE-4023 / XE-0049.\n\n---\n\n## Locations at HEAD\n\n| What | Where |\n|---|---|\n| Auditor settle branch (escrow burn #1) | `core/supply.go:242–251` |\n| Auditor stake branch **with** the emissions guard (the pattern the expired branch lacks) | `core/supply.go:256–276`, guard at `:261–263` |\n| Auditor expired branch (escrow burn #2, unguarded) | `core/supply.go:280–284` |\n| Conservation identity evaluated per asset | `core/supply.go:299–304` |\n| Chain census (`termsFromChain`): `leaseCost` keyed by lease-block hash, `settleEmission` keyed by settle `Source` | `core/supply.go:95–100` |\n| Node settle loop (10 s ticker; settle → force-settle → archive, sequentially, one goroutine; block ingestion runs on other goroutines) | `node/node.go:1757–1769` |\n| Archive eligibility read from the fetched snapshot only | `node/node.go:1855–1861` (`shouldArchiveExpiredLease`) |\n| Archive pass fetches `LeaseAccepted` leases once, then archives from the stale copies | `node/node.go:1863–1879` (`tryArchiveExpiredLeases`) |\n| Archival overwrite: no state re-read, no lease lock, `PutLease` unconditional | `node/node.go:1881–1900` (`archiveExpiredLease`) |\n| `DeletePendingSend` is a silent no-op when the pending send is already gone | `store/badger_store.go:236–243` (`ErrKeyNotFound → return nil`); `store/mem_store.go:126–131` (missing key → `return nil`) |\n| Block ingestion *does* serialize lease transitions (contrast with archival, which takes no lock) | `core/ledger.go:788–790` (`acquireLeaseLock` for `BlockLeaseAccept/Settle/Cancel/ForceSettle`) |\n| Settle commit: deletes the escrow pending, returns stake, marks record `Settled/LeaseSettled` | `core/ledger.go:2224–2233`; `store/badger_store.go:798–812` / `store/mem_store.go:354–358` |\n| Force-settle commit: consumer balance credited `oldBal + pending.Amount` (full escrow refund), pending deleted, record `Settled=true, State=LeaseUnfulfilled` | `core/ledger.go:1970, 1982–1983`; `store/badger_store.go:843–857` / `store/mem_store.go:367–371` |\n| testnet-0005 lease timing (genesis override actually deployed) | `genesis/testnet-0005/ledger-genesis.json`: settle grace 120 s, force-settle gap 300 s, escrow expiry 3,600 s, archive gap 600 s |\n\n---\n\n## Evidence\n\n### 1. The auditor's two escrow-burn branches (core/supply.go)\n\nSettle branch — burn #1, keyed off the census:\n\n```go\n// core/supply.go:242-251\nfor h, em := range emissions {\n    add(&get(AssetXE.Symbol).Emitted, em)\n\n    if cost, ok := costs[h]; ok {\n        add(&get(AssetXUSD.Symbol).EscrowBurned, cost)\n    } else {\n        rep.Notes = append(rep.Notes, fmt.Sprintf(\"settle for lease %s has no lease block in the census; escrow unaccounted\", shortHash(h)))\n        rep.Conserved = false\n    }\n}\n```\n\nExpired branch — burn #2, keyed off the lease record, **no census cross-check**:\n\n```go\n// core/supply.go:280-284\nfor _, l := range leases {\n    if l.State == LeaseExpired {\n        add(&get(AssetXUSD.Symbol).EscrowBurned, l.Cost)\n    }\n}\n```\n\nThe stake branch, by contrast, explicitly refuses to double-classify a lease that has a settle emission:\n\n```go\n// core/supply.go:261-263\nif _, settled := emissions[h]; settled {\n    continue\n}\n```\n\nIdentity that the double count breaks (`core/supply.go:299–304`):\n\n```go\na.Created   = sumU64(&overflow, a.Genesis, a.Minted, a.Emitted)\na.Destroyed = sumU64(&overflow, a.Burned, a.EscrowBurned, a.StakeForfeited)\na.Accounted = sumU64(&overflow, a.Observed, a.LockedStake, a.Destroyed)\na.Conserved = a.Accounted == a.Created\n```\n\n`EscrowBurned` feeds `Destroyed` once per branch, so a lease present in both branches contributes `2 × Cost` to `Destroyed` for `Cost` actually burned once (settle) or `Cost` for `0` actually burned (force-settle refund).\n\n### 2. The ledger's actual balance effects (what the auditor must mirror)\n\nSettle (`validateAndAddLeaseSettle`, `core/ledger.go:2224–2233`): the escrow pending is deleted exactly once and the provider's stake is returned as an off-chain credit:\n\n```go\ncommit.SettleLeaseHash = b.Source\ncommit.DeletePendingID = b.Source\n...\ncommit.AssetCredit = &AssetDelta{Account: b.Account, Asset: \"XUSD\", Amount: lease.Stake}\n```\n\nForce-settle (`validateAndAddLeaseForceSettle`, `core/ledger.go:1970, 1982–1983`): the consumer is credited the **entire** pending escrow — nothing is burned:\n\n```go\nexpectedBal := oldBal + pending.Amount\n...\ncommit.DeletePendingID = b.Source\ncommit.UnfulfillLeaseHash = b.Source\n```\n\n### 3. How a resolved lease's record becomes `LeaseExpired` anyway (node/node.go)\n\nArchival eligibility is evaluated once, on copies fetched at the top of the pass, and the overwrite never re-reads the record:\n\n```go\n// node/node.go:1863-1879 (tryArchiveExpiredLeases)\nleases, err := ls.GetLeasesByState(core.LeaseAccepted)\n...\nfor _, lease := range leases {\n    if !shouldArchiveExpiredLease(lease, now) {\n        continue\n    }\n    n.archiveExpiredLease(lease)\n}\n\n// node/node.go:1881-1892 (archiveExpiredLease) — no GetLease re-read, no lease lock\nif err := n.store.DeletePendingSend(lease.LeaseHash); err != nil {\n    log.Printf(\"archive: DeletePendingSend %s: %v\", shortHash(lease.LeaseHash), err)\n    return\n}\nupdated := *lease\nupdated.State = core.LeaseExpired\nupdated.Settled = true\nif err := ls.PutLease(&updated); err != nil { ... }\n```\n\nAnd the first step cannot detect that resolution already happened, because both stores treat deleting an absent pending send as success:\n\n```go\n// store/badger_store.go:239-243\nitem, err := txn.Get(pendingKey)\nif err == badger.ErrKeyNotFound {\n    return nil\n}\n// store/mem_store.go:126-131 — same: missing key returns nil\n```\n\nBlock ingestion, which commits the settle/force-settle, runs concurrently on gossip/sync/API goroutines and takes the per-lease lock (`core/ledger.go:788–790`); `archiveExpiredLease` takes no lock at all and is driven from the 10-second `settleLoop` ticker (`node/node.go:1757–1769`). So the window is: settle (or force-settle) for lease *L* commits **after** `GetLeasesByState(Accepted)` snapshots *L* (or while earlier leases in the same pass are being archived — each archival is two store transactions) and **before** `archiveExpiredLease(L)` issues its unconditional `PutLease`. The terminal record (`LeaseSettled`/`LeaseUnfulfilled`, `Settled=true`) is then overwritten with `LeaseExpired, Settled=true`, while the settle/force-settle **block remains in the provider's/consumer's chain** and therefore in the auditor's census. From then on, every `Report()` (2-second cache TTL) reproduces the double count deterministically — the race only has to be lost once, the false report is permanent.\n\nWhy the honest paths don't save it:\n\n- If the settle commits *before* the fetch, the lease is `LeaseSettled` and is not fetched — safe.\n- If archival completes first, the record's `Settled=true` makes any later settle fail validation (`lease already settled`) — safe, single count.\n- Only the interleaving above is unsafe, and nothing in the code closes it: no re-read inside `archiveExpiredLease`, no `ExpectLeaseState`-style compare-and-swap on the archival `PutLease` (block commits have exactly such a guard — `ExpectLeaseHash`/`ExpectLeaseState` in `core/store.go` / `store/mem_store.go:300–306` — the archival path does not use it).\n\n### 4. testnet-0005 reachability (normal operation, no attacker)\n\nDeployed timing (`genesis/testnet-0005/ledger-genesis.json`, loaded via `node/genesis.go:75` `core.SetGenesisJSON`): settle grace 120 s, force-settle gap 300 s, escrow expiry 3,600 s, archive gap 600 s; minimum lease duration 5 s. So a lease whose provider goes quiet is force-settleable at expiry+420 s, refundable until expiry+3,600 s, and is archived by **every** node holding the record at expiry+4,200 s. Archival is not an edge case on testnet-0005 — it is the routine terminal path for abandoned leases, and it runs on all nodes, including pure observer/sync nodes whose only lease activity is ingesting other nodes' settle/force-settle blocks concurrently with their own archive pass. The trigger needs one such block to land inside one archive pass on one node; the miscount then persists in that node's `/supply` output indefinitely.\n\n---\n\n## Impact arithmetic (per affected lease, renewals excluded)\n\nLet base escrow `C = lease.Cost` (µXUSD, `C ≥ 1` by `LeaseCost`), stake `S` (0 on testnet-0005 — `LeaseStakeDivisor = 0`, `core/ledger.go:116` — so stake terms are identically zero and play no part).\n\n**Settle sub-variant** — ledger truth: XUSD escrow `C` burned once, XE emission `E` created once, stake returned.\nAuditor: `EscrowBurned = C (settle branch) + C (expired branch) = 2C`; `Emitted = E` ✓.\n→ XUSD `Destroyed` overstated by `C`; `Discrepancy = Accounted − Created = +C`; `Conserved = false`. XE report stays `conserved: true` — a signature that distinguishes this from XE-4023 (negative discrepancy, −Σ renewals).\n\n**Force-settle sub-variant** — ledger truth: escrow `C` refunded to the consumer's balance, burned = 0, stake forfeited.\nAuditor: balances already include the refund and the pending is gone, yet the expired branch adds `EscrowBurned += C`.\n→ XUSD `Destroyed` overstated by `C`; `Discrepancy = +C`; `Conserved = false`.\n\nAggregate: `Discrepancy_XUSD = +Σ Cost` over all leases archived after resolution on that node. Magnitude per lease is one lease's full base cost (the same order as the per-lease amounts in XE-0049's live data: 98 settled leases ⇒ base costs totalling 67,738 µXUSD, i.e. ~691 µXUSD average per lease). The report is the network's documented conservation authority (`GET /supply`); a permanent false `conserved:false` with a *positive* discrepancy on a ledger that actually conserves both masks real leaks (alert fatigue / learned-ignore) and cannot be explained by any existing note — the walk emits no note for this branch, so operators see `conserved:false, notes` without this cause.\n\n**Which side is wrong:** the ledger's balance effects are correct in both sub-variants (escrow burned exactly once at settle; fully refunded at force-settle). The auditor double-counts *given* a lease record that says `Expired` for a resolved lease; the record reaches that state through the node's unguarded archival overwrite. Both layers are identified with locations; the auditor-side guard alone (below) makes the report correct for *any* record state, which is the same defensive pattern the stake branch already uses.\n\n**Suggested fixes**\n\n1. Auditor (sufficient on its own): in the expired branch, skip leases whose hash has a settle emission in the census, and skip leases for which a `lease_force_settle` block exists in the census — i.e. build a resolved-hash set from `termsFromChain` (`settleEmission` keys, plus a new `forceSettled` set from `BlockLeaseForceSettle` blocks keyed by `Source`) and mirror the stake branch's guard. A lease with neither block and `State == LeaseExpired` keeps the current `EscrowBurned += l.Cost` behaviour (the genuine both-parties-offline burn).\n2. Node (root cause): `archiveExpiredLease` should re-read the lease inside the archival step and abort unless it is still `LeaseAccepted && !Settled` — ideally via the same compare-and-swap discipline block commits use (`ExpectLeaseState`), or under the ledger's per-lease lock.\n\n---\n\n## Dedupe evidence\n\nBoard swept 2026-11-12 via the public API (`/v1/tickets`, all 925 public tickets in 4 pages of 250) for `termsFromChain`, `SupplyAuditor`, `supply auditor`, `conservation`, `EscrowBurned`, plus full reads of every supply-class ticket found:\n\n| Ticket | What it covers | Why this is different |\n|---|---|---|\n| XE-4023 (also XE-3447, XE-2754, XE-0049→dup of XE-0015/GH#4 finding 3) | Renewal top-ups omitted from `EscrowBurned` on the **settle** and **expired** paths → **negative** discrepancy −Σ renewals | This finding is renewal-free by construction: the expired branch *itself* double-fires against the settle branch (or fires after a refund). Discrepancy is **+Cost**, opposite sign, different root cause (missing cross-branch guard + stale archival overwrite, not a missing `BlockLeaseRenew` census term). XE-4023's own suggested fix (accumulate renewals into `leaseCost`; sum renewals in the expired loop) does **not** fix this — after that fix the double count becomes `+(Cost)` unchanged in the settle sub-variant. |\n| XE-4779 | Genesis-era XUSD mint blocks skipped → created under-counted, +212,890,638 discrepancy from missing *issuance* | Different term (Minted vs EscrowBurned), different mechanism (historical asset registration), no lease-record involvement. |\n| XE-5217 | Invalid-asset balances vs issuance gating; claims cross-asset emission keying | At HEAD leases are asset-locked by validation (`lease`/`lease_accept`/`lease_renew`/`lease_force_settle` must be XUSD, `lease_settle` must be XE), so emissions cannot be cross-asset; and that ticket never mentions the expired branch, archival, or double counting. |\n| XE-8689 (filed 2026-11-12) | `termsFromChain` plain `+=` wraps mint/burn/genesis sums past 2⁶⁴, masking the XE-0661 cancel-overflow wipe → false `conserved:true` | Different defect (uint64 wrap in census sums, false-green direction). Here all sums are small and exact; the report is false-**red**, driven by a duplicated term, not a wrapped one. |\n| XE-3430 | `SpendableBalances` (different function) omits returned settle stake | Auditor's `Balances` come from `GetAssetBalances`, which *does* credit the settle stake (`AssetCredit` + `rebuildAssetBalances`); not the function or term here. Stake is 0 on testnet-0005 in any case. |\n| XE-4066 | Cascade overlay (`cascadeBuild.addUndo`) omits `ReducePendingID` → stale escrow during reorg validation | Overlay/validation-time mechanism; no cascade is involved here — the double count occurs on a flat, stable census (`stable:true`) from committed blocks plus the lease record. |\n| XE-6482 | `archiveExpiredLease` uses local **wall clock** instead of attested time → premature archival on a skewed node | Timing-source defect. This finding needs no clock skew: archival fires at the correct time, but overwrites a record that was resolved *during the pass*. XE-6482's scenario (archive first, settle rejected later) yields a *correct* single count in the auditor; this one is the opposite interleaving. |\n| XE-0102 / XE-0015 finding 3 (part 1) | Node builds force-settle blocks with base `Cost` only, so renewed leases can't force-settle via the shipped client | Ledger/client-side, renewal-dependent. The force-settle sub-variant here uses **un-renewed** leases whose force-settle blocks are valid and committed. |\n| XE-0067 / XE-5241 family | Ledger `lease_cancel` refunds base cost only (renewal top-ups vanish) | Ledger refund bug, cancel path, renewals required. No cancel block is involved here. |\n\nNo public ticket title or body found in the sweep mentions the expired branch double-firing against a settle/force-settle block, an `Expired`-record overwrite of a terminal lease, or a positive-discrepancy auditor double count.\n\n---\n\n## Tier reasoning\n\n- Impact class is identical to XE-4023 / XE-0049 (the protocol's conservation canary permanently wrong on an actually-conserving ledger; no fund loss, no mint, no double-spend): those were claimed High/Medium and, per the round-2 brief, this class has historically assessed **around Medium**.\n- Discounts vs XE-4023: the miscount is per-node (only the node that loses the archival race reports it), and the trigger is a race window (settle/force-settle commit inside one archive pass) rather than a deterministic every-renewal path. That argues the claim should be **Medium**, with Minor a realistic assessment outcome.\n- Not Minor-only by construction: archival is a routine, always-on path on testnet-0005 (70-minute cycle), the window repeats every 10 s tick on every node for every archivable lease, the loss of the race is permanent once it happens, and the auditor-side defect (an unguarded second burn branch) is a code fact independent of how often the race is lost.\n- **Suggested: Medium (ceiling 2,500 XE); expected assessment Minor–Medium.**","patch_refs":[],"thread":[{"id":12663,"source":"desk","source_ref":"reply:10685","author":"Joseph Denne","team":true,"body":"Thanks. This is the same finding as an earlier report that is not public, which was filed first; the programme pays the\nfirst verifiable submission, so this one closes as a duplicate. If you believe it is a different\nbug, file a new report that links https://bounty.xe.network/XE-8798 and says what differs; it is read like any other.","created_at":"2026-11-20T00:04:29.355710+00:00"}]}