Bounty
XE-12914 · Bounty

core/finality: emitFinalLocked persists the FINAL vote before the Sync() durability gate that claims to defer it

Triaging claimed Minor web filed 2026-11-14 14:17 UTC by xe:352fe8fc

Report

Summary

emitFinalLocked (core/finalization.go) persists the FINAL vote with PutVote (:291) and only then checks the store's Sync() durability gate (:295-300). On sync failure it logs that the final vote is being "deferred" and returns without notifying the quorum manager or gossiping — but nothing was deferred: the vote is already in the vote store, where any later Retally counts it at full weight in finalTally, and VotesForPosition serves it to peers answering vote requests. The same file's castVoteLocked FINAL re-emit branch checks Sync() before emitting — the ordering emitFinalLocked gets backwards.

Impact

On a node whose Badger Sync() errors (failing disk / fsync error), the operator-visible state ("vote deferred, not cast") diverges from the consensus state ("vote stored, tally-live, pull-servable"). If the node crashes before a later successful sync, whether the "deferred" vote survives restart is nondeterministic across nodes.

Suggested fix

Run the Sync gate before PutVote, or roll back / suppress the stored vote when Sync fails, so a vote reported as deferred is not tally-live.

Thread

xe:352fe8fc2026-11-14 15:21 UTCweb

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.

File: poc_consensus_test.go — tests: TestPoCFinalVotePersistedDespiteSyncFailure. Verified PASS against xeprotocol/xe @ 89a542ea51d38375299aee54c6c99102e9bfa666 before filing (see report body).

// PoC tests for XE consensus/finality audit @ 89a542ea51d38375299aee54c6c99102e9bfa666.
//
// Run (from the clone root):
//
//	cp ~/workspace/bugbounty/xe/leads/poc-consensus/poc_consensus_test.go core/poc_consensus_test.go
//	GOTOOLCHAIN=local GOPATH=~/workspace/tools/gopath GOMODCACHE=~/workspace/tools/gopath/pkg/mod \
//	  ~/workspace/tools/go/bin/go test ./core/ -run 'TestPoC' -v -count=1
//	rm core/poc_consensus_test.go
//
// The tests are in package core_test so they can use store.MemStore
// (package store imports package core, so an in-package core test cannot).
// Everything runs in-process against the local build only: no network,
// no testnet writes.
package core_test

import (
	"encoding/json"
	"errors"
	"testing"
	"time"

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

// ---------- shared harness ----------

type harness struct {
	t       *testing.T
	mem     *store.MemStore
	ledger  *core.Ledger
	genKP   *core.KeyPair // genesis account + sole representative (100% weight)
	aKP     *core.KeyPair // funded account whose chain forks
	bAddr   string
	nowNano int64
	emitted []*core.Vote
	vm      *core.VoteManager
	qm      *core.QuorumManager

	recvHash string // A's opening receive = the fork position's Previous (P)
	s1, s2   *core.Block
}

func (h *harness) tick(sec int64) {
	h.nowNano += sec * int64(time.Second)
}

func (h *harness) sign(b *core.Block, kp *core.KeyPair) *core.Block {
	b.Timestamp = h.nowNano
	if err := core.SignBlock(b, kp); err != nil {
		h.t.Fatalf("SignBlock: %v", err)
	}
	return b
}

func (h *harness) add(b *core.Block) {
	if err := h.ledger.AddBlock(b); err != nil {
		h.t.Fatalf("AddBlock(%s %s): %v", b.Type, b.Hash[:12], err)
	}
}

// newHarness builds a ledger on a custom genesis whose account is also the
// sole representative (full GenesisSupply delegated to itself), funds
// account A, and creates a two-way fork on A at position P (s1 on chain,
// s2 staged + conflict record with weight snapshot, exactly as
// Ledger.addBlock does in production).
func newHarness(t *testing.T, voteStore core.VoteStore) *harness {
	t.Helper()
	h := &harness{t: t, nowNano: int64(1700000000) * int64(time.Second)}

	genKP, err := core.GenerateKeyPair()
	if err != nil {
		t.Fatal(err)
	}
	h.genKP = genKP
	h.aKP, err = core.GenerateKeyPair()
	if err != nil {
		t.Fatal(err)
	}
	bKP, err := core.GenerateKeyPair()
	if err != nil {
		t.Fatal(err)
	}
	h.bAddr = bKP.Address()

	// Fake clock: core.Now drives vote timestamps, conflict DetectedAt and
	// the stability-window arithmetic.
	origNow := core.Now
	core.Now = func() time.Time { return time.Unix(0, h.nowNano) }
	t.Cleanup(func() { core.Now = origNow })

	// Custom genesis: account == representative == genKP, full supply.
	gen := &core.Block{
		Type:          core.BlockGenesis,
		Account:       genKP.Address(),
		Previous:      "0",
		Balance:       core.GenesisSupply,
		Timestamp:     0,
		Asset:         "XE",
		Representative: genKP.Address(),
		PubKey:        genKP.PubKeyHex(),
	}
	if err := core.SignBlock(gen, genKP); err != nil {
		t.Fatalf("sign genesis: %v", err)
	}
	genJSON, err := json.Marshal(gen)
	if err != nil {
		t.Fatal(err)
	}
	if err := core.SetGenesisJSON(genJSON); err != nil {
		t.Fatalf("SetGenesisJSON: %v", err)
	}
	t.Cleanup(core.ClearGenesisOverride)

	h.mem = store.NewMemStore()
	h.ledger = core.NewLedger(h.mem, core.LedgerConfig{Difficulty: 0, TimestampWindow: 0})

	if voteStore == nil {
		voteStore = h.mem
	}
	h.vm = core.NewVoteManager(voteStore, genKP, h.ledger)
	h.qm = core.NewQuorumManager(h.mem, h.mem, voteStore, h.ledger)
	h.vm.SetQuorumManager(h.qm)
	h.vm.VoteEmitter = func(v *core.Vote) {
		cp := *v
		h.emitted = append(h.emitted, &cp)
	}

	// Fund A: genesis --send 1_000_000--> A --receive(open)--> frontier P.
	const fund = uint64(1_000_000)
	h.tick(10)
	send := h.sign(&core.Block{
		Type: core.BlockSend, Account: genKP.Address(), Previous: gen.Hash,
		Balance: core.GenesisSupply - fund, Asset: "XE", Amount: fund,
		Destination: h.aKP.Address(),
	}, genKP)
	h.add(send)

	h.tick(10)
	recv := h.sign(&core.Block{
		Type: core.BlockReceive, Account: h.aKP.Address(), Previous: "0",
		Balance: fund, Asset: "XE", Source: send.Hash,
		Representative: genKP.Address(),
	}, h.aKP)
	h.add(recv)
	h.recvHash = recv.Hash

	// Model the receive's own (orthogonal) finalization so that
	// depsFinalized(sibling) can pass: in production confirmConflict sets
	// exactly this height once the receive's source finalizes.
	if err := h.mem.SetFinalHeight(h.aKP.Address(), 1); err != nil {
		t.Fatal(err)
	}

	// Fork A at P: s1 goes on chain; s2 (different amount => different
	// hash) is staged and a conflict with a weight snapshot is recorded.
	h.tick(10)
	h.s1 = h.sign(&core.Block{
		Type: core.BlockSend, Account: h.aKP.Address(), Previous: recv.Hash,
		Balance: fund - 100, Asset: "XE", Amount: 100, Destination: h.bAddr,
	}, h.aKP)
	h.add(h.s1)

	h.tick(10)
	h.s2 = h.sign(&core.Block{
		Type: core.BlockSend, Account: h.aKP.Address(), Previous: recv.Hash,
		Balance: fund - 200, Asset: "XE", Amount: 200, Destination: h.bAddr,
	}, h.aKP)
	h.add(h.s2)

	conf := h.ledger.GetConflict(h.aKP.Address(), h.recvHash)
	if conf == nil {
		t.Fatalf("expected conflict record at (A, recv)")
	}
	if conf.WeightSnapshot == nil || conf.TotalWeight == 0 {
		t.Fatalf("expected weight snapshot on conflict, got %+v", conf)
	}
	if staged := h.ledger.GetBlockOrStaged(h.s2.Hash); staged == nil {
		t.Fatalf("expected s2 to be staged")
	}
	return h
}

func (h *harness) finalEmitted() int {
	n := 0
	for _, v := range h.emitted {
		if v.Final {
			n++
		}
	}
	return n
}

// ---------- Lead 1: stability-window state survives across elections ----------

// The 3s lock-stability window (core/quorum.go lockStabilityWindow) is the
// guard that stops a representative FINAL-locking a candidate before the
// candidate set has settled. Its bookkeeping (seenCandidates /
// lastNewCandidateNanos in core/vote.go) is keyed by (account, prev) and
// is NEVER deleted — not on conflict resolution, not on the orphan or
// phantom conflict drops, not on rollback. When an election at the same
// (account, prev) re-opens (conflict dropped while unfinalized, the same
// staged sibling body — which the drop paths leak, cf. XE-8341/XE-9790 —
// is re-delivered and a fresh conflict record is created), every candidate
// is already "seen" and the stamp is ancient, so maybeLockLocked emits the
// FINAL vote on the very first cast of the new election: no window at all.
func TestPoCStabilityWindowSkippedOnReopenedElection(t *testing.T) {
	h := newHarness(t, nil)
	acct, prev := h.aKP.Address(), h.recvHash

	// --- Election 1, first cast: window must apply (control). ---
	h.vm.CastVote(acct, prev, h.s1.Hash)
	if n := h.finalEmitted(); n != 0 {
		t.Fatalf("election 1 first cast emitted %d FINAL votes; stability window should defer the lock", n)
	}
	own, err := h.mem.GetVote(acct, prev, h.genKP.PubKeyHex())
	if err != nil || own == nil {
		t.Fatalf("expected stored converge vote, err=%v own=%v", err, own)
	}
	if own.Final {
		t.Fatalf("election 1 first cast stored a FINAL vote; stability window did not defer")
	}

	// --- The election is dropped while unfinalized (no FINAL lock was
	// ever written). This mirrors the production drop paths
	// (dropConflictIfOrphaned / all-phantom drop): votes + conflict
	// record are deleted; the staged sibling body is left in the store;
	// nothing touches the VoteManager's seen/stamp maps. ---
	if err := h.mem.DeleteVotesForConflict(acct, prev); err != nil {
		t.Fatal(err)
	}
	core.RemoveConflict(h.mem, acct, prev)
	// Cancel the pending stability redrive timer so it cannot fire into
	// election 2. (In production the timer would fire, find no
	// candidates, and return — it does not refresh the stamp either.)
	h.vm.Close()

	// Time passes; the position re-opens much later.
	h.tick(3600)

	// The same staged sibling is re-delivered: a FRESH conflict record
	// (with a fresh snapshot) is created for the same (account, prev).
	h.add(h.s2)
	if conf := h.ledger.GetConflict(acct, prev); conf == nil {
		t.Fatalf("expected a fresh conflict record after re-delivery")
	}
	h.emitted = nil

	// --- Election 2, first cast: candidates were "seen" an hour ago,
	// so the stability stamp reads as long-expired and the FINAL lock
	// is emitted immediately, inside the first cast. ---
	h.vm.CastVote(acct, prev, h.s1.Hash)
	if n := h.finalEmitted(); n == 0 {
		t.Fatalf("expected FINAL vote on first cast of reopened election (stale stability stamp), got none")
	}
	// The emitted FINAL is tally-live: the position finalizes inside the
	// same cast (cleanup then deletes the stored votes, so a stored-vote
	// check is not the right oracle — final height is).
	if fh := h.ledger.FinalHeight(acct); fh != 2 {
		t.Fatalf("expected position to finalize within the reopened election's first cast (height 2), got %d", fh)
	}
	t.Logf("BUG CONFIRMED: reopened election FINAL-locked on its first cast "+
		"(election 1 correctly deferred); final height now %d", h.ledger.FinalHeight(acct))
}

// ---------- Lead 2: emitFinalLocked stores the FINAL vote before the durability gate ----------

type failSyncVoteStore struct {
	core.VoteStore
}

func (failSyncVoteStore) Sync() error { return errors.New("simulated durability sync failure") }

// emitFinalLocked (core/finalization.go) logs "durability sync failed,
// deferring final vote" and returns without notifying the quorum manager
// or gossiping when store.Sync() fails — but it has ALREADY persisted the
// FINAL vote via store.PutVote. The vote is therefore live in every later
// tally and is served to peers via VotesForPosition; only the emission
// was deferred, not the vote. (Contrast castVoteLocked's FINAL re-emit
// branch, which checks Sync() BEFORE emitting.)
func TestPoCFinalVotePersistedDespiteSyncFailure(t *testing.T) {
	// Build the harness on the plain store first, then rebuild the vote
	// manager / quorum manager over that same store wrapped with a
	// Syncer whose Sync() always fails (a disk/durability error).
	h := newHarness(t, nil)
	acct, prev := h.aKP.Address(), h.recvHash

	wrapped := failSyncVoteStore{VoteStore: h.mem}
	vm := core.NewVoteManager(wrapped, h.genKP, h.ledger)
	qm := core.NewQuorumManager(h.mem, h.mem, wrapped, h.ledger)
	vm.SetQuorumManager(qm)
	var emitted []*core.Vote
	vm.VoteEmitter = func(v *core.Vote) { cp := *v; emitted = append(emitted, &cp) }

	// First cast: converge vote only; stability window defers the lock.
	vm.CastVote(acct, prev, h.s1.Hash)
	// Let the stability window expire (fake clock) and cast again: the
	// lock attempt now runs emitFinalLocked, which stores the FINAL
	// vote and then hits the failing Sync().
	h.tick(10)
	vm.CastVote(acct, prev, h.s1.Hash)

	finalSeen := 0
	for _, v := range emitted {
		if v.Final {
			finalSeen++
		}
	}
	if finalSeen != 0 {
		t.Fatalf("expected no FINAL vote emitted (sync failure should defer), saw %d", finalSeen)
	}
	stored, err := h.mem.GetVote(acct, prev, h.genKP.PubKeyHex())
	if err != nil || stored == nil {
		t.Fatalf("expected a stored vote, err=%v stored=%v", err, stored)
	}
	if !stored.Final {
		t.Fatalf("expected the FINAL vote to be already persisted despite the sync failure")
	}
	if fh := h.ledger.FinalHeight(acct); fh != 1 {
		t.Fatalf("expected quorum not yet notified (final height 1), got %d", fh)
	}
	// The supposedly-deferred vote is tally-live: a Retally triggered by
	// anything else finalizes the position from the stored FINAL vote.
	qm.Retally(acct, prev)
	if fh := h.ledger.FinalHeight(acct); fh != 2 {
		t.Fatalf("expected stored FINAL vote to finalize on next tally (height 2), got %d", fh)
	}
	t.Logf("BUG CONFIRMED: FINAL vote persisted and tally-live although emitFinalLocked " +
		"reported it deferred on sync failure")
}

Joseph Denneteam2026-11-20 19:45 UTCdesk

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.