{"id":"XE-13254","kind":"bounty","visibility":"public","source":"github","source_repo":"xeprotocol/xe","source_ref":"391","source_url":"https://github.com/xeprotocol/xe/issues/391","reporter_id":2252,"title":"lease_cancel after lease_renew destroys the renewal escrow top-up","area":"leasing-ledger","claimed_tier":"minor","assessed_tier":null,"verdict":"duplicate","duplicate_of":"XE-0067","tracked":true,"internal_ref":"#1097","internal_url":"https://github.com/xeprotocol/core/issues/1097","status":"closed","closed_reason":"duplicate","github_state":"closed","disclosed_at":null,"award_xe":null,"award_approved":false,"paid_ref":"","created_at":"2026-11-14T20:42:04.159183+00:00","updated_at":"2026-11-20T00:06:58.619087+00:00","source_created_at":"2026-11-11T15:08:48+00:00","told_at":"2026-11-20T00:04:59+00:00","status_changed_at":"2026-11-20T00:04:38.197198+00:00","url":"https://bounty.xe.network/XE-13254","body":"**Title:** lease_cancel after lease_renew destroys the renewal escrow top-up\n\n**Suggested tier:** Low\n\n**XE address (reward destination):** 9b663fdac108be34a3b715ef78a9f9bd878af6ef8142f388c6514918e6852dd7\n\n## Summary\n\nCancelling a lease that was renewed refunds only the base lease cost. The renewal\ntop-up added to the pending send is deleted along with it, so the renewal funds\nvanish — credited to nobody (neither consumer nor provider).\n\n## Impact\n\nFunds are destroyed, not stolen. The loss is bounded by the renewal amounts\n(517 micro-XUSD per renewal in the reproduction below, ≈ $0.0005). Reachability\nis narrow: cancelling an accepted lease only succeeds via\n`resolveCancelWinsOverAccept`, which requires the provider's accept block to be\nunfinalized and still the provider's frontier. Once the accept is finalized,\ncancel is rejected. So the loss only occurs inside the pre-finality race window\n(accept → renew → cancel).\n\n## Steps to reproduce\n\nUnit test against the real ledger code (`github.com/xeprotocol/xe`, testnet-0005):\n\n```sh\ngit clone https://github.com/xeprotocol/xe\ncd xe\ncp cancel_renewal_poc_test.go core/\ngo test ./core -run TestCancelAfterRenewalDestroysTopUp -v -count=1\n```\n\n**Note:** `cancel_renewal_poc_test.go` is NOT in the public repository — attach this file to the issue (or paste its contents); without it, the XE team cannot run this reproduction.\n\nThe test funds a consumer + provider with 1,000,000 micro-XUSD each, creates a\n60 s lease (1 vCPU / 1 GB / 1 GB, multiplier 1000 → cost 517 micro-XUSD), the\nprovider accepts with a 1-of-1 timekeeper attestation, the consumer renews for\nanother 60 s (escrow tops up to 1034), then the consumer cancels.\n\n**Expected:** cancel refunds the whole escrow → consumer balance back to 1,000,000.\n\n**Actual (reproduced 2026-11-11):**\n\n```\nescrow before cancel: 1034 micro-XUSD (base 517 + renewal 517)\nconsumer XUSD: funded=1000000 after-lease+renew=998966 after-cancel=999483\nlease state after cancel: cancelled; pending sends to provider: 0\nBUG: cancel after renewal destroyed 517 micro-XUSD\n--- FAIL: TestCancelAfterRenewalDestroysTopUp\n```\n\nThe test asserts the correct behaviour and FAILS on current code — that failure\nis the demonstration.\n\n## Root cause\n\n`core/ledger.go`, `validateAndAddLeaseCancel` refunds `oldBal + leaseBlock.Amount`\n(base cost only) and deletes the whole pending send\n(`commit.DeletePendingID = b.Source`), while renewals top the pending up via\n`commit.TopUpPendingID / TopUpPendingAmount` (`core/lease_renew.go`). Compare\n`validateAndAddLeaseForceSettle`, which refunds `pending.Amount` in full —\ncancel is the outlier.\n\n## Live grounding\n\nThe 3 cancelled leases observed on the public testnet had no renewals and\nrefunded in full — consistent with this finding (the bug only appears when a\nrenewal exists).\n\n## Suggested fix\n\nRefund `pending.Amount` on cancel, as force-settle does (or reject cancel when\nan unspent renewal top-up exists, with an explicit reason).\n\n<details>\n<summary>PoC test file (cancel_renewal_poc_test.go)</summary>\n\n```go\npackage core_test\n\n// PoC for: lease_cancel after lease_renew destroys the renewal escrow top-up.\n// The cancel validator refunds only leaseBlock.Amount (the base cost) while the\n// pending escrow at that point is base cost + sum(renewal costs). The pending\n// send is deleted in full, so the renewal funds vanish: they are credited to\n// neither the consumer nor the provider.\n//\n// Compare with lease_force_settle, which refunds pending.Amount in full.\n//\n// Run: go test ./core -run TestCancelAfterRenewalDestroysTopUp -v\n// The test asserts the CORRECT behaviour (full refund) and FAILS on the\n// current code, demonstrating the bug.\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/xeprotocol/xe/core\"\n\t\"github.com/xeprotocol/xe/store\"\n)\n\nfunc mustKP(t *testing.T) *core.KeyPair {\n\tt.Helper()\n\tkp, err := core.GenerateKeyPair()\n\tif err != nil {\n\t\tt.Fatalf(\"keygen: %v\", err)\n\t}\n\treturn kp\n}\n\nfunc mustSign(t *testing.T, b *core.Block, kp *core.KeyPair) *core.Block {\n\tt.Helper()\n\tif err := core.SignBlock(b, kp); err != nil {\n\t\tt.Fatalf(\"sign %s: %v\", b.Type, err)\n\t}\n\treturn b\n}\n\nfunc TestCancelAfterRenewalDestroysTopUp(t *testing.T) {\n\tconsumer := mustKP(t)\n\tprovider := mustKP(t)\n\ttk := mustKP(t)\n\n\tnowNs := time.Now().UnixNano()\n\tcertHash := strings.Repeat(\"b\", 64) // any hash: lookup fn returns the cert for it\n\tst := store.NewMemStore()\n\n\tled := core.NewLedger(st, core.LedgerConfig{\n\t\tDifficulty:      0,\n\t\tTimestampWindow: 0,\n\t\tTimekeeperConfigFn: func() *core.TimekeeperConfig {\n\t\t\treturn &core.TimekeeperConfig{Keys: []string{tk.PubKeyHex()}, Threshold: 1}\n\t\t},\n\t\tCertificateLookupFn: func(hash string) *core.CertificateInfo {\n\t\t\treturn &core.CertificateInfo{\n\t\t\t\tProvider:             provider.Address(),\n\t\t\t\tExpiresAt:            nowNs + int64(7*24*time.Hour),\n\t\t\t\tPriceMultiplierMilli: 1000,\n\t\t\t}\n\t\t},\n\t\tEpochAtFn: func(ns int64) []core.EpochParams {\n\t\t\treturn []core.EpochParams{{R: 1000, PayoutCap: 1500, TWAP: 1000}}\n\t\t},\n\t})\n\n\tconst fund uint64 = 1_000_000 // micro-XUSD\n\t// fund consumer + provider with XUSD via the test seeding path\n\tfor _, kp := range []*core.KeyPair{consumer, provider} {\n\t\tmint := mustSign(t, &core.Block{\n\t\t\tType: core.BlockMint, Asset: \"XUSD\", Account: kp.Address(),\n\t\t\tPrevious: \"0\", Balance: fund, Amount: fund,\n\t\t\tTimestamp: nowNs,\n\t\t}, kp)\n\t\tif err := led.SeedAssetForTesting(mint); err != nil {\n\t\t\tt.Fatalf(\"seed %s: %v\", kp.Address()[:12], err)\n\t\t}\n\t}\n\n\t// cost check: 1 vCPU + 1GB + 1GB for 60s at multiplier 1000 = 517 micro-XUSD\n\tcost, err := core.LeaseCost(1, 1024, 1, 60, 1000)\n\tif err != nil || cost != 517 {\n\t\tt.Fatalf(\"LeaseCost = %d, err %v (expected 517)\", cost, err)\n\t}\n\n\t// 1) consumer creates the lease (escrow 517)\n\tlease := mustSign(t, &core.Block{\n\t\tType: core.BlockLease, Asset: \"XUSD\", Account: consumer.Address(),\n\t\tPrevious: led.GetChain(consumer.Address())[0].Hash,\n\t\tBalance:  fund - cost, Amount: cost,\n\t\tDestination: provider.Address(), VCPUs: 1, MemoryMB: 1024, DiskGB: 1,\n\t\tDuration: 60, CertificateHash: certHash, Timestamp: nowNs + int64(time.Second),\n\t}, consumer)\n\tif err := led.AddBlock(lease); err != nil {\n\t\tt.Fatalf(\"lease: %v\", err)\n\t}\n\n\t// 2) provider accepts (attestation from the single trusted timekeeper)\n\tatt0, err := core.SignAttestation(lease.Hash, nowNs, tk)\n\tif err != nil {\n\t\tt.Fatalf(\"attestation: %v\", err)\n\t}\n\taccept := mustSign(t, &core.Block{\n\t\tType: core.BlockLeaseAccept, Asset: \"XUSD\", Account: provider.Address(),\n\t\tPrevious: led.GetChain(provider.Address())[0].Hash,\n\t\tBalance:  fund, Amount: 0, // stake is 0 (LeaseStakeDivisor == 0)\n\t\tSource: lease.Hash, CertificateHash: certHash,\n\t\tLockedR: 1000, LockedPayoutCap: 1500, LockedTWAP: 1000,\n\t\tAttestations: []core.TimekeeperAttestation{*att0},\n\t\tTimestamp:    nowNs + 2*int64(time.Second),\n\t}, provider)\n\tif err := led.AddBlock(accept); err != nil {\n\t\tt.Fatalf(\"accept: %v\", err)\n\t}\n\n\t// 3) consumer renews for another 60s (escrow tops up by another 517)\n\tatt1, err := core.SignAttestation(lease.Hash, nowNs+2*int64(time.Second), tk)\n\tif err != nil {\n\t\tt.Fatalf(\"attestation: %v\", err)\n\t}\n\trenew := mustSign(t, &core.Block{\n\t\tType: core.BlockLeaseRenew, Asset: \"XUSD\", Account: consumer.Address(),\n\t\tPrevious: lease.Hash,\n\t\tBalance:  fund - 2*cost, Amount: cost, Duration: 60,\n\t\tSource: lease.Hash, CertificateHash: certHash,\n\t\tLockedR: 1000, LockedPayoutCap: 1500, LockedTWAP: 1000,\n\t\tAttestations: []core.TimekeeperAttestation{*att1},\n\t\tTimestamp:    nowNs + 3*int64(time.Second),\n\t}, consumer)\n\tif err := led.AddBlock(renew); err != nil {\n\t\tt.Fatalf(\"renew: %v\", err)\n\t}\n\n\t// escrow must now be base + renewal = 1034\n\tpending := led.GetPendingForAccount(provider.Address())\n\tif len(pending) != 1 || pending[0].Amount != 2*cost {\n\t\tt.Fatalf(\"escrow after renew: got %+v, want one pending of %d\", pending, 2*cost)\n\t}\n\tt.Logf(\"escrow before cancel: %d micro-XUSD (base %d + renewal %d)\", pending[0].Amount, cost, cost)\n\n\t// 4) consumer cancels. The validator forces Balance = oldBal + base cost only.\n\tbalBefore := led.GetAssetBalances(consumer.Address())[\"XUSD\"]\n\tcancel := mustSign(t, &core.Block{\n\t\tType: core.BlockLeaseCancel, Asset: \"XUSD\", Account: consumer.Address(),\n\t\tPrevious: renew.Hash,\n\t\tBalance:  balBefore + cost, // what validateAndAddLeaseCancel demands\n\t\tSource: lease.Hash,\n\t\tTimestamp: nowNs + 4*int64(time.Second),\n\t}, consumer)\n\tif err := led.AddBlock(cancel); err != nil {\n\t\tt.Fatalf(\"cancel: %v\", err)\n\t}\n\n\tbalAfter := led.GetAssetBalances(consumer.Address())[\"XUSD\"]\n\tleaseAfter, _ := st.GetLease(lease.Hash)\n\tt.Logf(\"consumer XUSD: funded=%d after-lease+renew=%d after-cancel=%d\", fund, balBefore, balAfter)\n\tt.Logf(\"lease state after cancel: %s; pending sends to provider: %d\", leaseAfter.State, len(led.GetPendingForAccount(provider.Address())))\n\n\t// Correct behaviour: full escrow refund -> balance back to `fund`.\n\t// Actual behaviour on current code: balance is `fund - cost` (renewal lost).\n\tif balAfter != fund {\n\t\tt.Errorf(\"BUG: cancel after renewal destroyed %d micro-XUSD: balance after cancel = %d, want %d (full escrow refund)\",\n\t\t\tfund-balAfter, balAfter, fund)\n\t}\n}\n```\n\n</details>","patch_refs":[{"id":546,"repo":"xeprotocol/xe","kind":"pr","ref":"407","title":"fix(core/ledger): refund full escrow pending amount on lease_cancel for renewed leases (#395, #391)","url":"https://github.com/xeprotocol/xe/pull/407","note":"","state":"open","author":"arturbarszcz78","added_by":"desk","created_at":"2026-11-14T20:42:19.939993+00:00"},{"id":737,"repo":"xeprotocol/xe","kind":"pr","ref":"886","title":"fix(xe): lease-cancel-after-lease-renew (fixes #391)","url":"https://github.com/xeprotocol/xe/pull/886","note":"","state":"open","author":"tipprb","added_by":"desk","created_at":"2026-11-19T19:53:20.487191+00:00"}],"thread":[{"id":12795,"source":"github","source_ref":"7025800765","author":"Joseph Denne","team":true,"body":"Thanks. This is the same finding as https://bounty.xe.network/XE-0067, which was filed first; the programme pays the\nfirst verifiable submission, so this one closes as a duplicate. If you believe it is a different\nbug, file a new report that links https://bounty.xe.network/XE-13254 and says what differs; it is read like any other.","created_at":"2026-11-20T00:04:59+00:00"}]}