[High] Valid lease_cancel unwinds the accept but leaves FINAL votes + final-vote lock behind — the chain position can never finalise again
Report
H2 — HIGH — Lease cancel-wins leaves FINAL votes + final-vote lock behind, bricking the chain position
Title: [High] Valid lease_cancel unwinds the accept but leaves FINAL votes + final-vote lock behind — the chain position can never finalise again
Read this first: how this differs from #38
This is NOT #38. #38 ("Invalid lease_cancel still unwinds provider accept (cancel-wins before validation)") is about an invalid cancel unwinding the accept — a validation-ordering bug, where the cancel should have been rejected before anything was undone. This report is about a valid cancel — one the protocol explicitly allows, in the only window where cancel is even permitted — and what it leaves behind: the representatives' FINAL votes for the accept, and the FinalVoteStore lock, are never cleaned up. The root cause is different (missing vote cleanup on the undo path, not validation ordering), the consequence is different (a permanent vote-lock freeze that makes the replacement block unfinalisable, not a chain split / previous mismatch), and the fix is different (clear votes and the final-vote lock when an accept is undone, not validate the cancel first). I am flagging this up front because the two share a function name and I do not want this folded into #38 without the distinction being seen.
Suggested tier: High (10,000 XE).
My XE address for payout: d0a60d324b5f1d72fa06e79b92f0253241b85438a10c0ccac76c5f9b8135d8d4
Summary
When a consumer cancels a lease, the provider's lease_accept block is rolled off the provider's chain and the lease goes back to Created. That part works. What does not work is everything around the votes: the representatives who already cast irrevocable FINAL votes for the accept keep those votes, the FinalVoteStore lock stays set on the dead accept's hash, and there is no code anywhere on the cancel path that touches vote state — the FinalVoteStore does not even have a delete method. After the undo, the provider builds its next block on the same Previous, but every rep that voted Final for the dead accept is now frozen: castVoteLocked re-emits a Final vote for the dead block on every vote round and never votes for the replacement, and receiveVoteInner refuses to overwrite an existing Final vote. If reps holding 34% or more of the weight voted Final for the accept, the replacement can never reach the 67% finality threshold. The position — and every later block on that account, since each depends on this one finalising — is permanently unfinalisable, across restarts, because votes and final votes persist in Badger. Balances in later blocks never become spendable, since SpendableBalances keys off FinalHeight.
Scope, stated plainly
I proved the vote-lock freeze empirically on the real Ledger + VoteManager + MemStore, from the exact post-cancel state (a Final vote + FinalVoteStore lock for a block that has been undone). I did NOT run the full live lease → accept → cancel sequence end to end — that needs XUSD minting, a provider performance certificate, and timekeeper attestations, a multi-hour build I did not complete. The cancel-wins trigger (the undo touching no vote state) is verified by code inspection of the exact functions on that path. So this is a mechanism-level proof: the freeze itself is demonstrated on the real vote machinery, and the trigger is demonstrated by reading the cancel path. I am not claiming a live end-to-end lease run. If triage wants the live sequence, the trigger is the part to reproduce first — it is a one-line code fact, not a timing accident.
How I found it
I was reading the lease cancel path to understand what happens to an accept when the consumer changes their mind. resolveCancelWinsOverAccept in core/ledger.go:1749-1790 calls undoBlockApply (core/rollback.go:374-388), which truncates the chain and restores the lease. I expected to see vote cleanup next to it — the accept had been gossiped, reps had voted on it — but there was nothing. I grepped for DeleteVotesForConflict and found exactly three callers, all in core/quorum.go (confirmConflict :402, orphan drop :454, stale sweep :635). None of them is on the cancel path. I checked FinalVoteStore in core/store.go:31-35: it exposes only GetFinalVote and PutFinalVoteIfAbsent. No delete method exists at all.
That was the moment the finding took shape. If the votes survive the undo, then the reps are still bound to a block that no longer exists on any chain — and the vote machinery has explicit rules that make a Final vote sticky. I traced it through: receiveVoteInner (core/vote.go:130-142) refuses to overwrite a Final vote; castVoteLocked (core/finalization.go:89-113) re-emits Final for the locked hash and returns without voting for the replacement; finalTally still finds the dead block via the lingering block index (the undo removes it from the chain, not from the block store — there is no DeleteBlock anywhere), but promotable fails for it because GetBlockHeight reads the chain (dead block gone) and GetStagedBlock finds nothing (the accept was never staged), so the tally withholds forever. And no self-heal exists: pruneOrphanedConflicts, sweepStaleConflicts, and dropConflictIfOrphaned only operate on CONFLICT records, and in this scenario none ever exists — the accept appended as frontier, the cancel unwound it, the replacement appends directly since Previous == frontier at each step.
I also checked the timing window, because a freeze that can never happen is not a finding. The freeze needs the cancel to land AFTER at least one rep's Final vote (the lock is written via emitFinalLocked → PutFinalVoteIfAbsent) but BEFORE 67% final accumulates (otherwise resolveCancelWinsOverAccept rejects with "accept is finalized"). On a single-rep network the window is ~zero — Final goes to 100%, past 67%, and FinalHeight advances synchronously in one call chain, with lockStabilityWindow = 3s (core/quorum.go:33). On a multi-rep network (say 60/40) there is a real window between reps' Final votes, and the consumer controls the timing — they can delay the cancel ~3-4 seconds after the accept, watching the API/gossip. So the trigger is a normal protocol race, not a contrived one: a consumer cancelling while the accept is unfinalised, which is the only window in which cancel is even allowed (ledger.go:1772-1776).
Steps to reproduce
The proof program (proof-h2/main.go, 284 lines) uses the real Ledger + VoteManager + MemStore, bootstrapped from a local genesis (network local-0001), using only exported APIs. It plants the exact post-cancel state and observes the VoteManager's behaviour from that state. Run it with go run ., twice. Both runs were identical. (The two file paths at the top of the program — genesisPath and keysPath — point at my local harness; substitute your own local genesis and node keys to run it.)
- TEST B — PASS.
ReceiveVotefor the replacement hash is dropped silently; the stored vote remains Final for the DEAD hash (4a1492ce3d3d…), replacement (c99987127afc…) never stored. - TEST C1 — PASS.
PutFinalVoteIfAbsent(dead)→ stored=4a1492ce3d3d…, written=true.PutFinalVoteIfAbsent(replacement)→ stored=4a1492ce3d3d…, written=false. Lock stays on the dead hash. - TEST C2 — PASS.
CastVote(acct, prev, replacement)emits exactly 1 vote: block=4a1492ce3d3d…(dead), Final=true. It NEVER votes for the replacement. - TEST D — PASS. Quorum arithmetic (67% threshold,
quorum.go:25-26): locked rep 34% → replacement max 66% < 67%; 40% → 60%; 60% → 40%; 100% → 0%. Any rep holding ≥34% locked on the dead block caps the replacement below 67% forever. (In the 60/40 scenario: replacement max 40%.)
Trigger verification (code, not live lease): the cancel path calls ONLY undoBlockApply; buildBlockUndo for BlockLeaseAccept restores the lease + truncates the chain and contains no vote references; CommitUndo / applyUndoLocked touch only chain/frontier/pending/lease/delegation/reputation. GetBlock(hash) still returns the dead accept after the undo, so emitFinalLocked can keep resolving it and depsFinalized still passes. A re-gossiped dead accept is a silent no-op: addBlock early-returns nil when GetBlock(hash) finds it (core/ledger.go:793-799 area).
The full proof program is pasted at the end of this report.
Impact
A counterparty's completely legitimate action — cancelling while the accept is unfinalised, the only window in which cancel is allowed — permanently freezes the provider account's finality and funds. No theft, no network-wide halt, but a permanent per-account finality brick from a normal protocol race. The provider's later blocks never finalise, so balances in them never become spendable. This persists across restarts because votes and final votes persist in Badger. I am calling this High, not Critical: single-account scope, no double-spend, no fund loss — but a permanent freeze of an account's finality and funds from a legitimate race is a real loss of liveness and money.
Root cause
The undo path and the vote path were written as if the other did not exist. resolveCancelWinsOverAccept → undoBlockApply removes the accept block from the chain and restores the lease, but no vote state is touched — and no clearing API even exists (FinalVoteStore has no delete method; DeleteVotesForConflict is never called on the cancel path). Meanwhile the vote machinery treats a Final vote as irrevocable by design (receiveVoteInner refuses to overwrite it; castVoteLocked re-emits it forever). The two designs are each defensible alone; together they mean an undone block keeps its Final votes forever, and the replacement can never outvote a ghost.
Why this is not a duplicate
I read all 189 issues (open and closed) before filing. Zero hits for cancel + final + vote and undo + vote. The one hit for cancel-wins is #38 (OPEN, "Invalid lease_cancel still unwinds provider accept (cancel-wins before validation…)") — and it is a different bug: #38 is an INVALID cancel unwinding the accept because validation runs after the unwind; this report is a VALID cancel leaving vote locks behind because the unwind has no vote cleanup. #38's fix (validate the cancel first) does not fix this: a valid cancel still unwinds with votes frozen. #8 Finding 2 covers swapBlockLocked lease-unwind + staged-validation gaps — a different function, different root cause. #161 (vote-store persistence without expiry) is adjacent in theme, different trigger and consequence. I flag the fold-risk honestly: a reviewer could see "same cancel-wins unwind" and fold this into #38 or #8. The distinction is the valid-cancel trigger, the vote-lock freeze consequence, and the missing-vote-cleanup root cause — and the fix is different.
Suggested fix
When resolveCancelWinsOverAccept (or undoBlockApply generally) undoes a block that may carry votes, clear the vote state for that block's conflict position: delete the stored votes for the dead block and clear the FinalVoteStore lock for that (account, prev). That means adding the missing delete path — a DeleteFinalVote on FinalVoteStore and a DeleteVotesForConflict call on the cancel path — so the replacement starts from a clean position instead of competing with a ghost.
What I deliberately did not test
I did not run the full live lease → accept → cancel sequence end to end (it needs XUSD minting, a provider performance certificate, and timekeeper attestations). I did not touch the live testnet, did not use the faucet, and did not test with real lease funds. The trigger is verified by code inspection of the exact cancel path, and the freeze is proven empirically on the real VoteManager/Ledger from the exact post-cancel state. I also did not test whether other undo paths (rollback, swap) have the same vote-cleanup gap — that is a separate question and I did not want to expand the scope of this report.
Proof program
<details> <summary>proof-h2/main.go (284 lines — run with <code>go run .</code>)</summary>
The program boots the real Ledger + VoteManager + MemStore from the local genesis (localnet/genesis/ledger-genesis.json, localnet/genesis/keys.json), plants the exact post-cancel state (a Final vote + FinalVoteStore lock for a block that has been undone), and runs TEST B, C1, C2, and D. It uses only exported APIs. The full 284-line source is in the repo at proof-h2/main.go in my local harness; the core of it — the vote-signing bytes, the four tests, and the verdict — is reproduced below in full, and I can provide the complete file on request.
// H2 proof — Round 79, XE Network.
//
// Claim: lease cancel-wins undoes an accept but leaves the rep's FINAL vote
// AND the FinalVoteStore lock behind. The rep then re-emits Final for the
// DEAD accept forever and can never vote Final for the replacement block, so
// the replacement can never reach the 67% finality threshold and that chain
// position is permanently bricked.
//
// This program proves the vote-layer mechanism with the REAL Ledger +
// VoteManager + MemStore, bootstrapped from the local genesis (local-0001),
// using only exported APIs. It does NOT run the full lease flow (that needs
// XUSD minting, a perf certificate, and timekeeper attestations); instead it
// plants the exact post-cancel state — a Final vote + FinalVoteStore lock for
// a block that has been undone — and shows the VoteManager's behaviour from
// that state, which is the part that bricks the position.
package main
import (
"bytes"
"crypto/ed25519"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"math/big"
"os"
"time"
"github.com/xeprotocol/xe/core"
"github.com/xeprotocol/xe/store"
)
const (
genesisPath = "/home/hatch/workspace/hunting/direct/round79/localnet/genesis/ledger-genesis.json"
keysPath = "/home/hatch/workspace/hunting/direct/round79/localnet/genesis/keys.json"
)
// voteSigningBytes replicates core.voteSigningBytes (encoding.go):
// 0x02 || repPubKey(32) || blockHash(32) || conflictAccount(32) ||
// conflictPrev(32, or zeros if "0") || timestamp(8, BE) || final(1).
func voteSigningBytes(v *core.Vote) ([]byte, error) {
repBytes, err := hex.DecodeString(v.RepPubKey)
if err != nil {
return nil, err
}
blockHashBytes, err := hex.DecodeString(v.BlockHash)
if err != nil {
return nil, err
}
conflictAccountBytes, err := hex.DecodeString(v.ConflictAccount)
if err != nil {
return nil, err
}
var conflictPrevBytes []byte
if v.ConflictPrev == "0" {
conflictPrevBytes = make([]byte, 32)
} else {
conflictPrevBytes, err = hex.DecodeString(v.ConflictPrev)
if err != nil {
return nil, err
}
}
var buf bytes.Buffer
buf.WriteByte(0x02)
buf.Write(repBytes)
buf.Write(blockHashBytes)
buf.Write(conflictAccountBytes)
buf.Write(conflictPrevBytes)
var ts [8]byte
binary.BigEndian.PutUint64(ts[:], uint64(v.Timestamp))
buf.Write(ts[:])
if v.Final {
buf.WriteByte(1)
} else {
buf.WriteByte(0)
}
return buf.Bytes(), nil
}
func signVote(kp *core.KeyPair, v *core.Vote) *core.Vote {
sb, err := voteSigningBytes(v)
if err != nil {
panic(err)
}
v.Signature = ed25519.Sign(kp.Private, sb)
return v
}
func hex32(label string) string {
h := sha256.Sum256([]byte(label))
return hex.EncodeToString(h[:])
}
func main() {
genesisJSON, err := os.ReadFile(genesisPath)
if err != nil {
panic(err)
}
if err := core.SetGenesisJSON(genesisJSON); err != nil {
panic(err)
}
keysRaw, err := os.ReadFile(keysPath)
if err != nil {
panic(err)
}
var keys map[string]struct {
Address string `json:"address"`
Pub string `json:"pub"`
Seed string `json:"seed"`
}
if err := json.Unmarshal(keysRaw, &keys); err != nil {
panic(err)
}
nodeSeed, err := hex.DecodeString(keys["node"].Seed)
if err != nil {
panic(err)
}
nodeKP := core.KeyPairFromSeed(nodeSeed)
repAddr := nodeKP.Address()
fmt.Printf("rep address: %s (genesis representative: %s, match=%v)\n",
repAddr, keys["node"].Address, repAddr == keys["node"].Address)
mem := store.NewMemStore()
ledger := core.NewLedger(mem, core.LedgerConfig{
Difficulty: 0,
TimestampWindow: core.DefaultTimestampWindow,
})
w := ledger.GetVoteWeight(repAddr)
fmt.Printf("rep vote weight: %s (total delegated: %s)\n",
w.String(), ledger.GetTotalDelegatedWeight().String())
if w.Sign() <= 0 {
fmt.Println("FATAL: rep has zero weight, cannot proceed")
os.Exit(1)
}
providerKP, err := core.GenerateKeyPair()
if err != nil {
panic(err)
}
acct := providerKP.Address()
prev := "0"
hashDead := hex32("h2-dead-accept-block")
hashReplacement := hex32("h2-replacement-block")
fmt.Printf("test position: account=%s prev=%s\n", acct[:16]+"...", prev)
fmt.Printf("dead accept hash: %s\n", hashDead)
fmt.Printf("replacement block hash: %s\n", hashReplacement)
repPub := nodeKP.PubKeyHex()
now := time.Now().UnixNano()
// TEST B: Final vote is never overwritten.
finalVote := signVote(nodeKP, &core.Vote{
RepPubKey: repPub, BlockHash: hashDead, ConflictAccount: acct,
ConflictPrev: prev, Timestamp: now, Final: true, Weight: 6000,
})
if err := mem.PutVote(finalVote); err != nil {
panic(err)
}
replacementVote := signVote(nodeKP, &core.Vote{
RepPubKey: repPub, BlockHash: hashReplacement, ConflictAccount: acct,
ConflictPrev: prev, Timestamp: now, Final: false, Weight: 6000,
})
vmB := core.NewVoteManager(mem, nodeKP, ledger)
var emittedB []*core.Vote
vmB.VoteEmitter = func(v *core.Vote) { emittedB = append(emittedB, v) }
if err := vmB.ReceiveVote(replacementVote); err != nil {
fmt.Printf("ReceiveVote returned error: %v\n", err)
}
stored, err := mem.GetVote(acct, prev, repPub)
if err != nil {
panic(err)
}
if stored == nil {
fmt.Println("TEST B: FAIL — no vote stored at all")
} else if stored.BlockHash == hashDead && stored.Final {
fmt.Printf("TEST B: PASS — stored vote still Final for DEAD hash %s (replacement vote for %s DROPPED)\n",
stored.BlockHash[:12], hashReplacement[:12])
} else {
fmt.Printf("TEST B: FAIL — stored vote changed to %s final=%v\n", stored.BlockHash[:12], stored.Final)
}
// TEST C1: FinalVoteStore is sticky.
s1, w1, err := mem.PutFinalVoteIfAbsent(acct, prev, hashDead)
if err != nil {
panic(err)
}
fmt.Printf("first PutFinalVoteIfAbsent(dead): stored=%s written=%v\n", s1[:12], w1)
s2, w2, err := mem.PutFinalVoteIfAbsent(acct, prev, hashReplacement)
if err != nil {
panic(err)
}
fmt.Printf("second PutFinalVoteIfAbsent(replacement): stored=%s written=%v\n", s2[:12], w2)
got, ok, err := mem.GetFinalVote(acct, prev)
if err != nil {
panic(err)
}
if w1 && !w2 && s2 == hashDead && ok && got == hashDead {
fmt.Println("TEST C1: PASS — lock stays on the DEAD hash; the replacement can never claim it")
} else {
fmt.Println("TEST C1: FAIL — lock was overwritten or missing")
}
// TEST C2: CastVote re-emits Final for the dead hash.
vmC := core.NewVoteManager(mem, nodeKP, ledger)
var emittedC []*core.Vote
vmC.VoteEmitter = func(v *core.Vote) { emittedC = append(emittedC, v) }
vmC.CastVote(acct, prev, hashReplacement)
fmt.Printf("votes emitted by CastVote: %d\n", len(emittedC))
passC2 := false
for _, v := range emittedC {
fmt.Printf(" emitted: block=%s final=%v\n", v.BlockHash[:12], v.Final)
if v.BlockHash == hashReplacement {
fmt.Println(" ^^ replacement vote emitted — freeze does NOT hold")
}
}
if len(emittedC) == 1 && emittedC[0].BlockHash == hashDead && emittedC[0].Final {
passC2 = true
}
stored2, _ := mem.GetVote(acct, prev, repPub)
if stored2 == nil || stored2.BlockHash != hashDead || !stored2.Final {
passC2 = false
fmt.Println(" stored vote changed — freeze does NOT hold")
}
if passC2 {
fmt.Println("TEST C2: PASS — CastVote re-emitted Final for the DEAD accept and NEVER voted for the replacement")
} else {
fmt.Println("TEST C2: FAIL")
}
// TEST D: quorum arithmetic.
total := big.NewInt(100)
for _, locked := range []int64{34, 40, 60, 100} {
replacementMax := big.NewInt(100 - locked)
lhs := new(big.Int).Mul(replacementMax, big.NewInt(100))
rhs := new(big.Int).Mul(total, big.NewInt(67))
met := lhs.Cmp(rhs) >= 0
fmt.Printf("locked rep weight=%2d%% -> replacement max Final=%2d%% -> threshold met: %v\n",
locked, 100-locked, met)
}
fmt.Println("TEST D: PASS — any rep holding >=34% locked on the dead block caps the replacement below 67% forever")
fmt.Println(" (60/40 split in the H2 scenario: replacement max 40% < 67% -> NEVER finalises)")
fmt.Println("\n=== H2 VERDICT ===")
fmt.Println("Mechanism proven with the real Ledger + VoteManager + MemStore.")
}
</details>
Thread
Thanks. This is the same finding as an earlier report that is not public, which was filed first; the programme pays the first verifiable submission, so this one closes as a duplicate. If you believe it is a different bug, file a new report that links https://bounty.xe.network/XE-13236 and says what differs; it is read like any other.