{"id":"XE-0014","kind":"bounty","visibility":"public","source":"github","source_repo":"xeprotocol/xe","source_ref":"30","source_url":"https://github.com/xeprotocol/xe/issues/30","reporter_id":10,"title":"Structurally impossible blocks are rejected with 503 {retryable:true} instead of 400 {retryable:false}","area":"node-api","claimed_tier":"medium","assessed_tier":null,"verdict":null,"duplicate_of":null,"tracked":true,"internal_ref":"","internal_url":null,"status":"accepted","closed_reason":null,"github_state":"open","disclosed_at":null,"award_xe":null,"award_approved":false,"paid_ref":"","created_at":"2026-10-29T13:57:14.630014+00:00","updated_at":"2026-11-10T11:38:18.966619+00:00","source_created_at":"2026-10-24T13:04:47+00:00","told_at":"2026-11-10T00:15:32+00:00","status_changed_at":"2026-10-29T14:04:12.572573+00:00","url":"https://bounty.xe.network/XE-0014","body":"**Severity (suggested):** Medium — inconsistent API responses / validation gap. No fund risk.\n\n**XE payout address:** will be provided in a follow-up comment (this was found from throwaway testnet\naccounts; happy to give a stable mainnet address when the pool is finalized).\n\n### Contract\n\nAPI Reference → \"Retryable errors\" states:\n\n> A rejected block returns `{\"error\":\"block rejected: …\",\"retryable\":<bool>}`:\n> **400 with `retryable: false` for a deterministically invalid block** (bad signature or PoW,\n> structural or value validation), **503 with `retryable: true` for a transient failure**\n> (a dependency this node has not synced yet, a frontier race). **Branch on the flag, not the prose.**\n\nBoth cases below can *never* become valid, yet the node returns `503` + `retryable:true`.\nThe official SDK branches on `isRetryable(err)`, so a conforming client retries these blocks forever.\n\n### Case A — non-open block for an account that has no declared public key\n\n```\nPOST /blocks/send\n{\"type\":\"send\",\"account\":\"<unopened-address>\",\"previous\":\"<valid 64-hex>\",\"balance\":…,\n \"timestamp\":…,\"asset\":\"XE\",\"destination\":\"<address>\",\"amount\":1,\"signature\":…,\"pow_nonce\":…}\n\nHTTP/1.1 503\n{\"error\":\"block rejected: signature: unopened account abababababab... has no declared public key\",\n \"retryable\":true}\n```\n\nA block with `previous != \"0\"` and no `pub_key`, for an account that was never opened, is structurally\nimpossible — waiting and retrying cannot help. **Reproduced 4/4.**\n\n### Case B — `previous = 0` on an account that already has a chain\n\n```\nHTTP/1.1 503\n{\"error\":\"block rejected: previous mismatch: got 000000000000..., want 898c054e658b...\",\n \"retryable\":true}\n```\n\nSame account and fields with the real frontier → `201`, so signing and the chain are fine.\n**Reproduced as `503 retryable:true` in 5 of 6 attempts; once returned\n`400 {\"…block conflicts with finalized block…\",\"retryable\":false}` for the same construction.**\nEither way a client cannot tell from the documented contract whether to retry.\n\n### Reproducer\n\nSingle file, stdlib + `cryptography` only (no XE binary needed; the encoder is a byte-for-byte port of\n`core/encoding.go` / `crypto.go` / `pow.go`, validated against `sdk/test/vectors.json` —\nsend/receive/burn: `canonical_hex`, `hash` and `signature` all byte-identical):\n\n```bash\nexport XE_SEED=<64-hex seed of a funded testnet account>\npython repro_retryable_503.py --node https://ldn.core.test.network\n```\n\n<details>\n<summary>repro_retryable_503.py</summary>\n\n```python\n#!/usr/bin/env python3\n\"\"\"Standalone reproducer: structurally impossible blocks are rejected with 503 retryable:true.\n\nDependencies: stdlib + `cryptography` (ed25519). No XE binary needed.\n  export XE_SEED=<64-hex seed of a funded testnet account>\n  python repro_retryable_503.py --node https://ldn.core.test.network\nExit codes: 1 = reproduced, 0 = correctly rejected, 2 = could not run.\n\"\"\"\nimport argparse, hashlib, json, os, struct, sys, time, urllib.error, urllib.request\n\nNODE_DEFAULT = \"https://ldn.core.test.network\"\nVERSION_BYTE, TYPE_SEND = 0x02, 0x01\nAUX_TAG_PUBKEY = b\"xe/block/pubkey/v1\"\nACCOUNT_DOMAIN = b\"xe/account/v1\"\nDEFAULT_DIFFICULTY = 0xFFFFF80000000000\n\n\ndef u64(v): return struct.pack(\">Q\", v & 0xFFFFFFFFFFFFFFFF)\n\ndef hex32(s):\n    b = bytes.fromhex(s)\n    if len(b) != 32: raise ValueError(f\"expected 32 bytes, got {len(b)}\")\n    return b\n\ndef derive_address(pub_hex):\n    return hashlib.sha256(ACCOUNT_DOMAIN + bytes.fromhex(pub_hex)).hexdigest()\n\ndef canonical(b):\n    out = bytearray([VERSION_BYTE, TYPE_SEND])\n    out += (b.get(\"asset\") or \"\").encode().ljust(8, b\"\\x00\")\n    out += hex32(b[\"account\"])\n    out += b\"\\x00\" * 32 if b.get(\"previous\", \"0\") == \"0\" else hex32(b[\"previous\"])\n    out += u64(int(b.get(\"balance\") or 0))\n    out += u64(int(b.get(\"timestamp\") or 0))\n    out += hex32(b[\"destination\"])\n    out += u64(int(b.get(\"amount\") or 0))\n    out += b\"\\x00\" * 32                     # representative\n    memo = (b.get(\"memo\") or \"\").encode()\n    out.append(len(memo)); out += memo\n    return bytes(out)\n\ndef aux(b):\n    pk = b.get(\"pub_key\") or \"\"\n    if not pk: return b\"\"\n    tag, val = AUX_TAG_PUBKEY, pk.encode()\n    return u64(len(tag)) + tag + u64(len(val)) + val\n\ndef block_hash(b, network_id):\n    h = hashlib.sha256(); h.update(network_id.encode()); h.update(canonical(b)); h.update(aux(b))\n    return h.hexdigest()\n\ndef pow_hash(nonce, hb):\n    h = hashlib.blake2b(digest_size=8)\n    h.update(struct.pack(\"<Q\", nonce & 0xFFFFFFFFFFFFFFFF)); h.update(hb)\n    return struct.unpack(\">Q\", h.digest())[0]\n\ndef compute_pow(bh, difficulty=DEFAULT_DIFFICULTY):\n    hb, n = bytes.fromhex(bh), 0\n    while pow_hash(n, hb) < difficulty: n += 1\n    return n\n\ndef sign(b, seed, network_id, declare_pub_key=False):\n    from cryptography.hazmat.primitives import serialization\n    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey\n    priv = Ed25519PrivateKey.from_private_bytes(seed)\n    pub = priv.public_key().public_bytes(serialization.Encoding.Raw,\n                                         serialization.PublicFormat.Raw)\n    out = dict(b)\n    if declare_pub_key and not out.get(\"pub_key\"): out[\"pub_key\"] = pub.hex()\n    out[\"hash\"] = block_hash(out, network_id)\n    out[\"signature\"] = priv.sign(bytes.fromhex(out[\"hash\"])).hex()\n    out[\"pow_nonce\"] = compute_pow(out[\"hash\"])\n    return out\n\ndef get(u):\n    with urllib.request.urlopen(u, timeout=25) as r: return json.loads(r.read())\n\ndef post(u, body):\n    req = urllib.request.Request(u, data=json.dumps(body).encode(), method=\"POST\",\n                                 headers={\"Content-Type\": \"application/json\"})\n    try:\n        with urllib.request.urlopen(req, timeout=25) as r: return r.status, r.read().decode()[:400]\n    except urllib.error.HTTPError as e: return e.code, e.read().decode()[:400]\n\ndef main():\n    ap = argparse.ArgumentParser(); ap.add_argument(\"--node\", default=NODE_DEFAULT)\n    args = ap.parse_args()\n    seed_hex = os.environ.get(\"XE_SEED\", \"\").strip()\n    if len(seed_hex) != 64:\n        print(\"ERROR: set XE_SEED to a funded testnet account's 64-hex seed\", file=sys.stderr); return 2\n    seed = bytes.fromhex(seed_hex)\n    from cryptography.hazmat.primitives import serialization\n    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey\n    priv = Ed25519PrivateKey.from_private_bytes(seed)\n    pub_hex = priv.public_key().public_bytes(serialization.Encoding.Raw,\n                                             serialization.PublicFormat.Raw).hex()\n    node = args.node.rstrip(\"/\"); me = derive_address(pub_hex)\n    network_id = get(f\"{node}/node\")[\"network_id\"]\n    total = int(get(f\"{node}/accounts/{me}/chain?limit=1\").get(\"total\") or 0)\n    if total == 0:\n        print(\"ERROR: account unopened; fund it from the faucet first\", file=sys.stderr); return 2\n    frontier = get(f\"{node}/accounts/{me}/chain?limit=1&offset={total-1}\")[\"blocks\"][-1][\"hash\"]\n    bal = int((get(f\"{node}/accounts/{me}/balance\").get(\"balances\") or {}).get(\"XE\") or 0)\n    other, now = hashlib.sha256(b\"repro-destination\").hexdigest(), time.time_ns()\n\n    c1 = {\"type\": \"send\", \"account\": me, \"previous\": \"0\", \"balance\": bal - 1,\n          \"timestamp\": now, \"asset\": \"XE\", \"destination\": other, \"amount\": 1}\n    st1, bd1 = post(f\"{node}/blocks/send\", sign(c1, seed, network_id, declare_pub_key=True))\n    c2 = {\"type\": \"send\", \"account\": hashlib.sha256(b\"repro-unopened\").hexdigest(),\n          \"previous\": frontier, \"balance\": bal - 1, \"timestamp\": now,\n          \"asset\": \"XE\", \"destination\": other, \"amount\": 1}\n    st2, bd2 = post(f\"{node}/blocks/send\", sign(c2, seed, network_id))\n\n    def rep(name, st, bd):\n        try: rt = json.loads(bd).get(\"retryable\")\n        except Exception: rt = None\n        bad = st >= 500 and rt is True\n        print(f\"[{name}] expected HTTP 400 retryable:false | observed HTTP {st} retryable={rt}\")\n        print(f\"         body: {bd.strip()[:200]}\")\n        print(f\"         -> {'REPRODUCED' if bad else 'correctly rejected'}\")\n        return bad\n    print(f\"node={node} network={network_id} account={me[:12]}… height={total}\")\n    ok = rep(\"case1 previous=0\", st1, bd1) | rep(\"case2 unopened account\", st2, bd2)\n    return 1 if ok else 0\n\nif __name__ == \"__main__\":\n    raise SystemExit(main())\n```\n</details>\n\n### Suggested fix\n\nDistinguish \"structurally impossible\" from \"not ready yet\":\n\n- `previous == 0` while the account already has a chain → `400 retryable:false`;\n- non-open block whose `account` is unknown / has no declared `pub_key`, so the block can never be\n  attributed → `400 retryable:false`;\n- keep `503 retryable:true` only for the documented transient cases (a `previous` the node knows about\n  but has not synced yet; frontier races).\n\n### Out of scope / already checked clean\n\nSame campaign, all correctly rejected with `400 retryable:false`: `account` set to an existing account but\nsigned by another key (account takeover attempt), `pub_key` declared on a non-open block, `asset:\"xe\"`,\n`timestamp:0`, `amount = 2^64-1`, `balance = 2^64-1`, `amount = 0`, over-balance amount, memo 65 bytes,\n`destination` = self.\n\nTwo things I initially suspected and then **disproved**, so they are *not* claimed here: hex case is not\nmalleability (upper/lower produce an identical block hash — the canonical encoding decodes hex to bytes),\nand replaying a signed block is idempotent (balance decreases once, height unchanged).\n","patch_refs":[{"id":121,"repo":"xeprotocol/xe","kind":"pr","ref":"36","title":"core,api: reject structurally impossible blocks with 400 retryable=false","url":"https://github.com/xeprotocol/xe/pull/36","note":"","state":"open","author":"ocakciomursel-pixel","added_by":"desk","created_at":"2026-10-29T13:57:30.091343+00:00"}],"thread":[{"id":6,"source":"github","source_ref":"6384645585","author":"kenmungeneskar","team":false,"body":"**XE payout address:** `b68f2b4d8a062d9219590f0c2d7753d783ec9f5d43d85a125230bb0f7a41a86e`\n\nThis is a locally held key. The address is `sha256(xe/account/v1 ‖ pubkey)` and does not depend on\nthe network id, so the same key yields the same address after a testnet wipe and at mainnet genesis.\nSay the word if you'd rather have a different form (e.g. a designated mainnet address) and I'll supply it.","created_at":"2026-10-24T13:13:30+00:00"},{"id":1562,"source":"github","source_ref":"6755089692","author":"XE desk","team":true,"body":"Read and accepted. It is tracked internally and the fix will land in a public PR; this issue is\nupdated when it does, and the tier and award follow the fix. The desk entry is https://bounty.xe.network/XE-0014.","created_at":"2026-11-10T00:15:32+00:00"}]}