<!-- XE-0861 · statechain/api: public read path holds Chain.mu across the Badger range scan, starving AddBlock ingestion (Medium) · testnet -->
*Markdown view of <https://bounty.xe.network/XE-0861>. The page is the record; this is the same page for reading.*

XE-0861 · Bounty

# statechain/api: public read path holds Chain.mu across the Badger range scan, starving AddBlock ingestion (Medium)

Triaging
claimed Medium
[xe#284](https://github.com/xeprotocol/xe/issues/284)
filed 2026-11-06 10:24 UTC
by Mabera

Verdict
:   published when the fix ships

Tier
:   published when the fix ships

Claimed
:   Medium

Area
:   DAO harness

Duplicate of
:   —

Tracked
:   —

Updated
:   2026-11-18 13:41 UTC

Told
:   2026-11-06 21:35 UTC

### Patches

- [xe#285](https://github.com/xeprotocol/xe/pull/285) open by tipprb
  statechain: eliminate mutex contention on public read endpoints

### History

- [15781](https://bounty.xe.network/log/15781) 2026-11-06 21:35 UTC github.labels
- [15745](https://bounty.xe.network/log/15745) 2026-11-06 21:35 UTC reply.mirrored
- [15744](https://bounty.xe.network/log/15744) 2026-11-06 21:35 UTC reply.sent
- [15743](https://bounty.xe.network/log/15743) 2026-11-06 21:35 UTC proposal.adopted
- [15742](https://bounty.xe.network/log/15742) 2026-11-06 21:35 UTC proposal.adopted
- [15741](https://bounty.xe.network/log/15741) 2026-11-06 21:35 UTC ticket.status new → triaging
- [15740](https://bounty.xe.network/log/15740) 2026-11-06 21:35 UTC proposal.adopted
- [15739](https://bounty.xe.network/log/15739) 2026-11-06 21:35 UTC ticket.award
- [15738](https://bounty.xe.network/log/15738) 2026-11-06 21:35 UTC proposal.adopted
- [15737](https://bounty.xe.network/log/15737) 2026-11-06 21:35 UTC ticket.facts
- [15736](https://bounty.xe.network/log/15736) 2026-11-06 21:35 UTC proposal.adopted
- [15735](https://bounty.xe.network/log/15735) 2026-11-06 21:35 UTC ticket.facts

[Full history](https://bounty.xe.network/log?ref=XE-0861) · [JSON](https://bounty.xe.network/v1/tickets/XE-0861) · [markdown](https://bounty.xe.network/XE-0861.md)

### Report

## Summary

The 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.

## Affected component

- `statechain/chain.go:15` — `mu sync.Mutex` (the chain's only lock; not an `RWMutex`).
- `statechain/chain.go:278-293` — `GetBlocks`: `c.mu.Lock(); defer c.mu.Unlock()` then `c.store.GetStateBlockRange(start, limit)` inside the locked region.
- `statechain/chain.go:269-276` (`GetBlock`) and `:295-303` (`BlockCount`) — same pattern; `handleStateChainBlocks` calls both per request (the response also includes `block_count`).
- `statechain/chain.go:106-111` — `AddBlock` takes the same `c.mu` before any validation, so even rejected submits queue behind in-flight reads.
- `store/badger_store.go:1800-1822` — `GetStateBlockRange` does the real disk \+ `json.Unmarshal` work per item.
- `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).
- `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.
- `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).
- Verified at repo commit `02e9641`.

## Impact

One 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.

Suggested severity: Medium.

## PoC

In-process, no repo modification, no signatures. A separate module with `replace github.com/xeprotocol/xe => ../repo` (clone the repo as a sibling `repo` directory):

`go.mod`:

```
module xpoc
go 1.25.0
require github.com/xeprotocol/xe v0.0.0
replace github.com/xeprotocol/xe => ../repo
```

`main.go`:

```
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"sync"
	"sync/atomic"
	"time"

	"github.com/xeprotocol/xe/statechain"
	"github.com/xeprotocol/xe/store"
)

const numBlocks = 1000
const blockPayload = 160 * 1024

// A block that fails VerifyBlockHash fast — but it still needs Chain.mu to
// start, so its duration measures lock-wait + cheap validation.
func rejectBlock() *statechain.Block {
	return &statechain.Block{
		Index: 0, PrevHash: "",
		Ops:        []statechain.Op{{Action: "set", Key: "k", Value: []byte(`"v"`)}},
		Signatures: []statechain.BlockSignature{},
		Hash:       "bogus", Timestamp: time.Now().UnixNano(),
	}
}

func timeAddBlock(c *statechain.Chain, n int) (avg, max time.Duration) {
	var tot time.Duration
	for i := 0; i < n; i++ {
		start := time.Now()
		_ = c.AddBlock(rejectBlock())
		d := time.Since(start)
		tot += d
		if d > max { max = d }
	}
	return tot / time.Duration(n), max
}

func main() {
	dir, _ := os.MkdirTemp("", "xpoc-")
	defer os.RemoveAll(dir)
	st, err := store.NewBadgerStore(filepath.Join(dir, "db"))
	if err != nil { panic(err) }
	g, err := statechain.ParseGenesis(statechain.GenesisJSON())
	if err != nil { panic(err) }
	c, err := statechain.NewChain(st, g)
	if err != nil { fmt.Println("NewChain failed:", err); os.Exit(1) }

	// Seed 1,000 realistic-size blocks directly at the store layer
	// (data volume only; AddBlock validation is not part of the probe).
	big := make([]byte, blockPayload)
	for i := range big { big[i] = byte('a' + i%26) }
	jsonBig := append(append([]byte{'"'}, big...), '"')
	for i := uint64(1); i <= numBlocks; i++ {
		b := &statechain.Block{
			Index: i, PrevHash: fmt.Sprintf("%064x", i-1),
			Ops:        []statechain.Op{{Action: "set", Key: fmt.Sprintf("kv-%d", i), Value: jsonBig}},
			Signatures: []statechain.BlockSignature{},
			Hash: fmt.Sprintf("%064x", i), Timestamp: int64(i),
		}
		if err := st.PutStateBlock(b); err != nil { panic(err) }
	}
	fmt.Printf("seeded %d blocks x %d KiB into badger\n", numBlocks, blockPayload/1024)

	start := time.Now()
	_, _ = c.GetBlocks(1, numBlocks)
	scanDur := time.Since(start)
	fmt.Printf("single GetBlocks(1,%d) under lock: %v\n", numBlocks, scanDur)

	fmt.Println("phase A: baseline AddBlock (no readers) ...")
	avgA, _ := timeAddBlock(c, 200)
	fmt.Printf("  avg=%v\n", avgA)

	const readers = 8
	var stop atomic.Bool
	var wg sync.WaitGroup
	for i := 0; i < readers; i++ {
		wg.Add(1)
		go func() { defer wg.Done(); for !stop.Load() { _, _ = c.GetBlocks(1, numBlocks) } }()
	}
	time.Sleep(scanDur * 2)
	fmt.Println("phase B: AddBlock under 8 concurrent GetBlocks(1,1000) readers ...")
	avgB, maxB := timeAddBlock(c, 15)
	stop.Store(true)
	wg.Wait()
	fmt.Printf("  avg=%v max=%v\n", avgB, maxB)
	fmt.Printf("RESULT: avg AddBlock baseline=%v vs loaded=%v (x%.0f slower)\n",
		avgA, avgB, float64(avgB)/float64(avgA))
}
```

Run: `go mod tidy && go build -o poc . && ./poc`

Real output (x86, badger v4, 1,000 x 160 KiB blocks):

```
seeded 1000 blocks x 160 KiB into badger
single GetBlocks(1,1000) under lock: 539.304134ms (err=<nil>)
phase A: baseline AddBlock (no readers) ...
  avg=1.2µs max=18.699µs
phase B: AddBlock under 8 concurrent GetBlocks(1,1000) readers ...
  avg=3.246345428s max=3.590561203s
RESULT: avg AddBlock baseline=1.2µs vs loaded=3.246345428s (x2705288 slower)
```

The 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`.

## Dedup notes

- 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.
- 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.
- 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.

### Thread

**Joseph Denne**team2026-11-06 21:35 UTCgithub

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

**Mabera**2026-11-18 13:41 UTCweb

Hi team. No update on this report to date?
