{"id":"XE-0124","kind":"bounty","visibility":"public","source":"github","source_repo":"xeprotocol/xe","source_ref":"200","source_url":"https://github.com/xeprotocol/xe/issues/200","reporter_id":39,"title":"store: account chain stored as one JSON array (Θ(N²) writes, measured 2k=1.1 s → 4k=4.4 s) and the lease table scanned in full 3× per 10 s","area":"node-api","claimed_tier":"medium","assessed_tier":null,"verdict":null,"duplicate_of":null,"tracked":false,"internal_ref":"","internal_url":null,"status":"triaging","closed_reason":null,"github_state":"open","disclosed_at":null,"award_xe":null,"award_approved":false,"paid_ref":"","created_at":"2026-10-29T16:51:36.838060+00:00","updated_at":"2026-11-08T20:17:41.885067+00:00","source_created_at":"2026-10-29T16:51:20+00:00","told_at":"2026-11-08T20:18:40.179288+00:00","status_changed_at":"2026-11-08T20:17:51.899521+00:00","url":"https://bounty.xe.network/XE-0124","body":"**Suggested severity: Medium (2,500 XE)**\n**Area:** `store/badger_store.go` (account chain value, lease prefix scans), `node/node.go` (`settleLoop`)\n**Repo pin:** 9787859 (testnet-0005)\n\nTwo hot paths in the store do whole-table / whole-value work. Both grow monotonically because nothing in the normal path deletes records, and neither needs a privileged actor to grow.\n\n## A — a per-account chain is one JSON array, rewritten on every block\n\n```go\n// store/badger_store.go:701-713\nhashes := make([]string, len(c.Chain.Blocks))\nfor i, b := range c.Chain.Blocks { hashes[i] = b.Hash }\nchainData, err := json.Marshal(hashes)      // whole history in one value\n...\nif err := txn.Set(chainKey, chainData); err != nil { ... }\n```\n\nReading is symmetric: one value, then N random `Get`s + N `Unmarshal`s (`store/badger_store.go:144-156`). `prepareBlockWrite` (`core/ledger.go:2250-2261`) calls `GetAccountChain` for **every** new block, so each block costs Θ(N) reads and rewrites 67·N bytes. Over a chain of N blocks the node writes Σ67·i = Θ(N²) bytes. Nothing chunks, prunes or caps the chain length.\n\nMeasured (sequential commits on one account, shipped store):\n\n```\nN=2 000: 1.112 s total\nN=4 000: 4.378 s total      (3.9x for 2x N -> quadratic)\n```\n\nExtrapolated to N=100 000: ≈335 GB written per node for ≈30 MB of actual block data (≈11 000× write amplification — SSD wear, IOPS, value-log GC), and every `GetBalance` / `GetBlockHeight` / `IsFinalized` / `GetAssetBalanceAtBlock` for that account becomes O(N) (they are on the quorum path: `promotable`, `confirmConflict`).\n\n## B — the lease table is scanned in full three times every 10 s\n\n```go\n// store/badger_store.go:1619 — GetLeasesByState (and GetLeasesByProvider at :1592)\nopts := badger.DefaultIteratorOptions\nit := txn.NewIterator(opts)\nfor it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() {\n\tvar l core.Lease\n\titem.Value(func(val []byte) error { return json.Unmarshal(val, &l) })   // every lease\n\tif l.State == state { out = append(out, &l) }\n}\n```\n\n```go\n// node/node.go:1754-1770 — ticker 10 s\ncase <-ticker.C:\n\tn.trySettleExpiredLeases()      // GetLeasesByProvider\n\tn.tryForceSettleStaleLeases()   // GetLeasesByState(Accepted)\n\tn.tryArchiveExpiredLeases()     // GetLeasesByState(Accepted)\n```\n\nLeases are never deleted: `archiveExpiredLease` only writes state `Expired` (`node/node.go:1886-1896`), and rollback is the only removal path. A lease costs micro-XUSD to create, so the table is attacker-growable.\n\nMeasured (`-mode=leases`):\n\n```\n5 000 leases:  47 ms, 3.46 MB allocated per scan\n20 000 leases: 279 ms, 13.45 MB per scan     (linear, ~14 µs and ~673 B per lease)\n```\n\nAt 1 000 000 leases: ≈14 s and ≈670 MB allocation per scan, ×3 every 10 s — the node spends all its time scanning and GCing and stops processing gossip/finality, permanently, with no recovery short of deleting the DB. The same call backs `/leases?state=` (found in `api/handler.go:735`), so one unauthenticated request also blocks for that duration.\n\n## Suggested fix\n\n- Store the per-account chain as an index: one key per block position (`account | index -> hash`) plus a frontier key, so a commit writes O(1) and reads page-sized ranges.\n- Keep `state -> hashes` and `provider -> hashes` as incremental indexes updated inside the same `db.Update`, so the 10 s loop reads only the relevant bucket.\n- Add pagination at the store layer (`start/limit`) and use it in the loop and in `/leases`.\n- Prune or archive settled/expired leases to a separate prefix with a bounded retention.\n","patch_refs":[{"id":213,"repo":"xeprotocol/xe","kind":"pr","ref":"213","title":"fix(store): index account chains and secondary lease state/provider tables (fixes #200)","url":"https://github.com/xeprotocol/xe/pull/213","note":"","state":"open","author":"arturbarszcz78","added_by":"desk","created_at":"2026-10-29T19:53:06.730077+00:00"}],"thread":[{"id":1595,"source":"desk","source_ref":"reply:511","author":"Joseph Denne","team":true,"body":"Thanks for the report and the measurements. We have confirmed both storage behaviours you describe and they are being handled; we will update this ticket when there is a fix to point at.","created_at":"2026-11-08T20:17:41.885067+00:00"}]}