{"id":"XE-12914","kind":"bounty","visibility":"public","source":"web","source_repo":"","source_ref":"","source_url":"","reporter_id":2401,"title":"core/finality: emitFinalLocked persists the FINAL vote before the Sync() durability gate that claims to defer it","area":"consensus","claimed_tier":"minor","assessed_tier":null,"verdict":null,"duplicate_of":null,"tracked":false,"internal_ref":"","internal_url":null,"status":"triaging","closed_reason":null,"github_state":"","disclosed_at":null,"award_xe":null,"award_approved":false,"paid_ref":"","created_at":"2026-11-14T14:17:10.278047+00:00","updated_at":"2026-11-20T19:46:45.620143+00:00","source_created_at":null,"told_at":"2026-11-20T19:45:52.924323+00:00","status_changed_at":"2026-11-20T19:45:47.663216+00:00","url":"https://bounty.xe.network/XE-12914","body":"### Summary\n`emitFinalLocked` (core/finalization.go) persists the FINAL vote with `PutVote`\n(:291) and only then checks the store's `Sync()` durability gate (:295-300). On\nsync failure it logs that the final vote is being \"deferred\" and returns without\nnotifying the quorum manager or gossiping — but nothing was deferred: the vote is\nalready in the vote store, where any later `Retally` counts it at full weight in\n`finalTally`, and `VotesForPosition` serves it to peers answering vote requests.\nThe same file's `castVoteLocked` FINAL re-emit branch checks `Sync()` *before*\nemitting — the ordering `emitFinalLocked` gets backwards.\n\n### Impact\nOn a node whose Badger `Sync()` errors (failing disk / fsync error), the\noperator-visible state (\"vote deferred, not cast\") diverges from the consensus\nstate (\"vote stored, tally-live, pull-servable\"). If the node crashes before a\nlater successful sync, whether the \"deferred\" vote survives restart is\nnondeterministic across nodes.\n\n### Suggested fix\nRun the Sync gate before `PutVote`, or roll back / suppress the stored vote when\nSync fails, so a vote reported as deferred is not tally-live.","patch_refs":[],"thread":[{"id":3090,"source":"web","source_ref":"reporter:2401:ad0b0c1b58beedcf","author":"xe:352fe8fc","team":false,"body":"PoC re-supplied as a message: the attachment on the original filing did not register on this ticket (it was sent under a wrong multipart field name), so the full PoC source is pasted here verbatim.\n\nFile: poc_consensus_test.go — tests: TestPoCFinalVotePersistedDespiteSyncFailure. Verified PASS against xeprotocol/xe @ 89a542ea51d38375299aee54c6c99102e9bfa666 before filing (see report body).\n\n```\n// PoC tests for XE consensus/finality audit @ 89a542ea51d38375299aee54c6c99102e9bfa666.\n//\n// Run (from the clone root):\n//\n//\tcp ~/workspace/bugbounty/xe/leads/poc-consensus/poc_consensus_test.go core/poc_consensus_test.go\n//\tGOTOOLCHAIN=local GOPATH=~/workspace/tools/gopath GOMODCACHE=~/workspace/tools/gopath/pkg/mod \\\n//\t  ~/workspace/tools/go/bin/go test ./core/ -run 'TestPoC' -v -count=1\n//\trm core/poc_consensus_test.go\n//\n// The tests are in package core_test so they can use store.MemStore\n// (package store imports package core, so an in-package core test cannot).\n// Everything runs in-process against the local build only: no network,\n// no testnet writes.\npackage core_test\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/xeprotocol/xe/core\"\n\t\"github.com/xeprotocol/xe/store\"\n)\n\n// ---------- shared harness ----------\n\ntype harness struct {\n\tt       *testing.T\n\tmem     *store.MemStore\n\tledger  *core.Ledger\n\tgenKP   *core.KeyPair // genesis account + sole representative (100% weight)\n\taKP     *core.KeyPair // funded account whose chain forks\n\tbAddr   string\n\tnowNano int64\n\temitted []*core.Vote\n\tvm      *core.VoteManager\n\tqm      *core.QuorumManager\n\n\trecvHash string // A's opening receive = the fork position's Previous (P)\n\ts1, s2   *core.Block\n}\n\nfunc (h *harness) tick(sec int64) {\n\th.nowNano += sec * int64(time.Second)\n}\n\nfunc (h *harness) sign(b *core.Block, kp *core.KeyPair) *core.Block {\n\tb.Timestamp = h.nowNano\n\tif err := core.SignBlock(b, kp); err != nil {\n\t\th.t.Fatalf(\"SignBlock: %v\", err)\n\t}\n\treturn b\n}\n\nfunc (h *harness) add(b *core.Block) {\n\tif err := h.ledger.AddBlock(b); err != nil {\n\t\th.t.Fatalf(\"AddBlock(%s %s): %v\", b.Type, b.Hash[:12], err)\n\t}\n}\n\n// newHarness builds a ledger on a custom genesis whose account is also the\n// sole representative (full GenesisSupply delegated to itself), funds\n// account A, and creates a two-way fork on A at position P (s1 on chain,\n// s2 staged + conflict record with weight snapshot, exactly as\n// Ledger.addBlock does in production).\nfunc newHarness(t *testing.T, voteStore core.VoteStore) *harness {\n\tt.Helper()\n\th := &harness{t: t, nowNano: int64(1700000000) * int64(time.Second)}\n\n\tgenKP, err := core.GenerateKeyPair()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\th.genKP = genKP\n\th.aKP, err = core.GenerateKeyPair()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tbKP, err := core.GenerateKeyPair()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\th.bAddr = bKP.Address()\n\n\t// Fake clock: core.Now drives vote timestamps, conflict DetectedAt and\n\t// the stability-window arithmetic.\n\torigNow := core.Now\n\tcore.Now = func() time.Time { return time.Unix(0, h.nowNano) }\n\tt.Cleanup(func() { core.Now = origNow })\n\n\t// Custom genesis: account == representative == genKP, full supply.\n\tgen := &core.Block{\n\t\tType:          core.BlockGenesis,\n\t\tAccount:       genKP.Address(),\n\t\tPrevious:      \"0\",\n\t\tBalance:       core.GenesisSupply,\n\t\tTimestamp:     0,\n\t\tAsset:         \"XE\",\n\t\tRepresentative: genKP.Address(),\n\t\tPubKey:        genKP.PubKeyHex(),\n\t}\n\tif err := core.SignBlock(gen, genKP); err != nil {\n\t\tt.Fatalf(\"sign genesis: %v\", err)\n\t}\n\tgenJSON, err := json.Marshal(gen)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := core.SetGenesisJSON(genJSON); err != nil {\n\t\tt.Fatalf(\"SetGenesisJSON: %v\", err)\n\t}\n\tt.Cleanup(core.ClearGenesisOverride)\n\n\th.mem = store.NewMemStore()\n\th.ledger = core.NewLedger(h.mem, core.LedgerConfig{Difficulty: 0, TimestampWindow: 0})\n\n\tif voteStore == nil {\n\t\tvoteStore = h.mem\n\t}\n\th.vm = core.NewVoteManager(voteStore, genKP, h.ledger)\n\th.qm = core.NewQuorumManager(h.mem, h.mem, voteStore, h.ledger)\n\th.vm.SetQuorumManager(h.qm)\n\th.vm.VoteEmitter = func(v *core.Vote) {\n\t\tcp := *v\n\t\th.emitted = append(h.emitted, &cp)\n\t}\n\n\t// Fund A: genesis --send 1_000_000--> A --receive(open)--> frontier P.\n\tconst fund = uint64(1_000_000)\n\th.tick(10)\n\tsend := h.sign(&core.Block{\n\t\tType: core.BlockSend, Account: genKP.Address(), Previous: gen.Hash,\n\t\tBalance: core.GenesisSupply - fund, Asset: \"XE\", Amount: fund,\n\t\tDestination: h.aKP.Address(),\n\t}, genKP)\n\th.add(send)\n\n\th.tick(10)\n\trecv := h.sign(&core.Block{\n\t\tType: core.BlockReceive, Account: h.aKP.Address(), Previous: \"0\",\n\t\tBalance: fund, Asset: \"XE\", Source: send.Hash,\n\t\tRepresentative: genKP.Address(),\n\t}, h.aKP)\n\th.add(recv)\n\th.recvHash = recv.Hash\n\n\t// Model the receive's own (orthogonal) finalization so that\n\t// depsFinalized(sibling) can pass: in production confirmConflict sets\n\t// exactly this height once the receive's source finalizes.\n\tif err := h.mem.SetFinalHeight(h.aKP.Address(), 1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Fork A at P: s1 goes on chain; s2 (different amount => different\n\t// hash) is staged and a conflict with a weight snapshot is recorded.\n\th.tick(10)\n\th.s1 = h.sign(&core.Block{\n\t\tType: core.BlockSend, Account: h.aKP.Address(), Previous: recv.Hash,\n\t\tBalance: fund - 100, Asset: \"XE\", Amount: 100, Destination: h.bAddr,\n\t}, h.aKP)\n\th.add(h.s1)\n\n\th.tick(10)\n\th.s2 = h.sign(&core.Block{\n\t\tType: core.BlockSend, Account: h.aKP.Address(), Previous: recv.Hash,\n\t\tBalance: fund - 200, Asset: \"XE\", Amount: 200, Destination: h.bAddr,\n\t}, h.aKP)\n\th.add(h.s2)\n\n\tconf := h.ledger.GetConflict(h.aKP.Address(), h.recvHash)\n\tif conf == nil {\n\t\tt.Fatalf(\"expected conflict record at (A, recv)\")\n\t}\n\tif conf.WeightSnapshot == nil || conf.TotalWeight == 0 {\n\t\tt.Fatalf(\"expected weight snapshot on conflict, got %+v\", conf)\n\t}\n\tif staged := h.ledger.GetBlockOrStaged(h.s2.Hash); staged == nil {\n\t\tt.Fatalf(\"expected s2 to be staged\")\n\t}\n\treturn h\n}\n\nfunc (h *harness) finalEmitted() int {\n\tn := 0\n\tfor _, v := range h.emitted {\n\t\tif v.Final {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n\n// ---------- Lead 1: stability-window state survives across elections ----------\n\n// The 3s lock-stability window (core/quorum.go lockStabilityWindow) is the\n// guard that stops a representative FINAL-locking a candidate before the\n// candidate set has settled. Its bookkeeping (seenCandidates /\n// lastNewCandidateNanos in core/vote.go) is keyed by (account, prev) and\n// is NEVER deleted — not on conflict resolution, not on the orphan or\n// phantom conflict drops, not on rollback. When an election at the same\n// (account, prev) re-opens (conflict dropped while unfinalized, the same\n// staged sibling body — which the drop paths leak, cf. XE-8341/XE-9790 —\n// is re-delivered and a fresh conflict record is created), every candidate\n// is already \"seen\" and the stamp is ancient, so maybeLockLocked emits the\n// FINAL vote on the very first cast of the new election: no window at all.\nfunc TestPoCStabilityWindowSkippedOnReopenedElection(t *testing.T) {\n\th := newHarness(t, nil)\n\tacct, prev := h.aKP.Address(), h.recvHash\n\n\t// --- Election 1, first cast: window must apply (control). ---\n\th.vm.CastVote(acct, prev, h.s1.Hash)\n\tif n := h.finalEmitted(); n != 0 {\n\t\tt.Fatalf(\"election 1 first cast emitted %d FINAL votes; stability window should defer the lock\", n)\n\t}\n\town, err := h.mem.GetVote(acct, prev, h.genKP.PubKeyHex())\n\tif err != nil || own == nil {\n\t\tt.Fatalf(\"expected stored converge vote, err=%v own=%v\", err, own)\n\t}\n\tif own.Final {\n\t\tt.Fatalf(\"election 1 first cast stored a FINAL vote; stability window did not defer\")\n\t}\n\n\t// --- The election is dropped while unfinalized (no FINAL lock was\n\t// ever written). This mirrors the production drop paths\n\t// (dropConflictIfOrphaned / all-phantom drop): votes + conflict\n\t// record are deleted; the staged sibling body is left in the store;\n\t// nothing touches the VoteManager's seen/stamp maps. ---\n\tif err := h.mem.DeleteVotesForConflict(acct, prev); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcore.RemoveConflict(h.mem, acct, prev)\n\t// Cancel the pending stability redrive timer so it cannot fire into\n\t// election 2. (In production the timer would fire, find no\n\t// candidates, and return — it does not refresh the stamp either.)\n\th.vm.Close()\n\n\t// Time passes; the position re-opens much later.\n\th.tick(3600)\n\n\t// The same staged sibling is re-delivered: a FRESH conflict record\n\t// (with a fresh snapshot) is created for the same (account, prev).\n\th.add(h.s2)\n\tif conf := h.ledger.GetConflict(acct, prev); conf == nil {\n\t\tt.Fatalf(\"expected a fresh conflict record after re-delivery\")\n\t}\n\th.emitted = nil\n\n\t// --- Election 2, first cast: candidates were \"seen\" an hour ago,\n\t// so the stability stamp reads as long-expired and the FINAL lock\n\t// is emitted immediately, inside the first cast. ---\n\th.vm.CastVote(acct, prev, h.s1.Hash)\n\tif n := h.finalEmitted(); n == 0 {\n\t\tt.Fatalf(\"expected FINAL vote on first cast of reopened election (stale stability stamp), got none\")\n\t}\n\t// The emitted FINAL is tally-live: the position finalizes inside the\n\t// same cast (cleanup then deletes the stored votes, so a stored-vote\n\t// check is not the right oracle — final height is).\n\tif fh := h.ledger.FinalHeight(acct); fh != 2 {\n\t\tt.Fatalf(\"expected position to finalize within the reopened election's first cast (height 2), got %d\", fh)\n\t}\n\tt.Logf(\"BUG CONFIRMED: reopened election FINAL-locked on its first cast \"+\n\t\t\"(election 1 correctly deferred); final height now %d\", h.ledger.FinalHeight(acct))\n}\n\n// ---------- Lead 2: emitFinalLocked stores the FINAL vote before the durability gate ----------\n\ntype failSyncVoteStore struct {\n\tcore.VoteStore\n}\n\nfunc (failSyncVoteStore) Sync() error { return errors.New(\"simulated durability sync failure\") }\n\n// emitFinalLocked (core/finalization.go) logs \"durability sync failed,\n// deferring final vote\" and returns without notifying the quorum manager\n// or gossiping when store.Sync() fails — but it has ALREADY persisted the\n// FINAL vote via store.PutVote. The vote is therefore live in every later\n// tally and is served to peers via VotesForPosition; only the emission\n// was deferred, not the vote. (Contrast castVoteLocked's FINAL re-emit\n// branch, which checks Sync() BEFORE emitting.)\nfunc TestPoCFinalVotePersistedDespiteSyncFailure(t *testing.T) {\n\t// Build the harness on the plain store first, then rebuild the vote\n\t// manager / quorum manager over that same store wrapped with a\n\t// Syncer whose Sync() always fails (a disk/durability error).\n\th := newHarness(t, nil)\n\tacct, prev := h.aKP.Address(), h.recvHash\n\n\twrapped := failSyncVoteStore{VoteStore: h.mem}\n\tvm := core.NewVoteManager(wrapped, h.genKP, h.ledger)\n\tqm := core.NewQuorumManager(h.mem, h.mem, wrapped, h.ledger)\n\tvm.SetQuorumManager(qm)\n\tvar emitted []*core.Vote\n\tvm.VoteEmitter = func(v *core.Vote) { cp := *v; emitted = append(emitted, &cp) }\n\n\t// First cast: converge vote only; stability window defers the lock.\n\tvm.CastVote(acct, prev, h.s1.Hash)\n\t// Let the stability window expire (fake clock) and cast again: the\n\t// lock attempt now runs emitFinalLocked, which stores the FINAL\n\t// vote and then hits the failing Sync().\n\th.tick(10)\n\tvm.CastVote(acct, prev, h.s1.Hash)\n\n\tfinalSeen := 0\n\tfor _, v := range emitted {\n\t\tif v.Final {\n\t\t\tfinalSeen++\n\t\t}\n\t}\n\tif finalSeen != 0 {\n\t\tt.Fatalf(\"expected no FINAL vote emitted (sync failure should defer), saw %d\", finalSeen)\n\t}\n\tstored, err := h.mem.GetVote(acct, prev, h.genKP.PubKeyHex())\n\tif err != nil || stored == nil {\n\t\tt.Fatalf(\"expected a stored vote, err=%v stored=%v\", err, stored)\n\t}\n\tif !stored.Final {\n\t\tt.Fatalf(\"expected the FINAL vote to be already persisted despite the sync failure\")\n\t}\n\tif fh := h.ledger.FinalHeight(acct); fh != 1 {\n\t\tt.Fatalf(\"expected quorum not yet notified (final height 1), got %d\", fh)\n\t}\n\t// The supposedly-deferred vote is tally-live: a Retally triggered by\n\t// anything else finalizes the position from the stored FINAL vote.\n\tqm.Retally(acct, prev)\n\tif fh := h.ledger.FinalHeight(acct); fh != 2 {\n\t\tt.Fatalf(\"expected stored FINAL vote to finalize on next tally (height 2), got %d\", fh)\n\t}\n\tt.Logf(\"BUG CONFIRMED: FINAL vote persisted and tally-live although emitFinalLocked \" +\n\t\t\"reported it deferred on sync failure\")\n}\n\n```","created_at":"2026-11-14T15:21:02.682766+00:00"},{"id":15291,"source":"desk","source_ref":"reply:13182","author":"Joseph Denne","team":true,"body":"Thanks for the report. We have read it against the code and confirmed the behaviour you describe. It is being handled, and this ticket will be updated when there is a change to check.","created_at":"2026-11-20T19:45:52.915403+00:00"}]}