<!-- XE-13254 · lease_cancel after lease_renew destroys the renewal escrow top-up · testnet -->
*Markdown view of <https://bounty.xe.network/XE-13254>. The page is the record; this is the same page for reading.*

XE-13254 · Bounty

# lease\_cancel after lease\_renew destroys the renewal escrow top-up

Closed · duplicate
—claimed Minor
[xe#391](https://github.com/xeprotocol/xe/issues/391)
filed 2026-11-11 15:08 UTC
by AIRDROP TREASURESS

Verdict
:   Duplicate

Tier
:   —

Claimed
:   Minor

Area
:   Leasing / ledger

Duplicate of
:   [XE-0067](https://bounty.xe.network/XE-0067) accepted

Tracked
:   internally

Updated
:   2026-11-20 00:06 UTC

Told
:   2026-11-20 00:04 UTC

### Patches

- [xe#407](https://github.com/xeprotocol/xe/pull/407) open by arturbarszcz78
  fix(core/ledger): refund full escrow pending amount on lease\_cancel for renewed leases (#395, #391)
- [xe#886](https://github.com/xeprotocol/xe/pull/886) open by tipprb
  fix(xe): lease-cancel-after-lease-renew (fixes #391)

### History

- [543795](https://bounty.xe.network/log/543795) 2026-11-20 00:05 UTC github.state\_pushed
- [543794](https://bounty.xe.network/log/543794) 2026-11-20 00:05 UTC github.labels
- [543757](https://bounty.xe.network/log/543757) 2026-11-20 00:05 UTC reply.mirrored
- [543464](https://bounty.xe.network/log/543464) 2026-11-20 00:04 UTC proposal.adopted
- [543463](https://bounty.xe.network/log/543463) 2026-11-20 00:04 UTC reply.sent
- [543462](https://bounty.xe.network/log/543462) 2026-11-20 00:04 UTC ticket.status new → closed
- [541962](https://bounty.xe.network/log/541962) 2026-11-20 00:04 UTC proposal.adopted
- [541961](https://bounty.xe.network/log/541961) 2026-11-20 00:04 UTC ticket.facts area
- [541960](https://bounty.xe.network/log/541960) 2026-11-20 00:04 UTC proposal.adopted
- [541959](https://bounty.xe.network/log/541959) 2026-11-20 00:04 UTC ticket.facts
- [541958](https://bounty.xe.network/log/541958) 2026-11-20 00:04 UTC proposal.adopted
- [541957](https://bounty.xe.network/log/541957) 2026-11-20 00:04 UTC ticket.facts

[Full history](https://bounty.xe.network/log?ref=XE-13254) · [JSON](https://bounty.xe.network/v1/tickets/XE-13254) · [markdown](https://bounty.xe.network/XE-13254.md)

### Report

**Title:** lease\_cancel after lease\_renew destroys the renewal escrow top-up

**Suggested tier:** Low

**XE address (reward destination):** 9b663fdac108be34a3b715ef78a9f9bd878af6ef8142f388c6514918e6852dd7

## Summary

Cancelling a lease that was renewed refunds only the base lease cost. The renewal
top-up added to the pending send is deleted along with it, so the renewal funds
vanish — credited to nobody (neither consumer nor provider).

## Impact

Funds are destroyed, not stolen. The loss is bounded by the renewal amounts
(517 micro-XUSD per renewal in the reproduction below, ≈ $0.0005). Reachability
is narrow: cancelling an accepted lease only succeeds via
`resolveCancelWinsOverAccept`, which requires the provider's accept block to be
unfinalized and still the provider's frontier. Once the accept is finalized,
cancel is rejected. So the loss only occurs inside the pre-finality race window
(accept → renew → cancel).

## Steps to reproduce

Unit test against the real ledger code (`github.com/xeprotocol/xe`, testnet-0005):

```
git clone https://github.com/xeprotocol/xe
cd xe
cp cancel_renewal_poc_test.go core/
go test ./core -run TestCancelAfterRenewalDestroysTopUp -v -count=1
```

**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.

The test funds a consumer \+ provider with 1,000,000 micro-XUSD each, creates a
60 s lease (1 vCPU / 1 GB / 1 GB, multiplier 1000 → cost 517 micro-XUSD), the
provider accepts with a 1-of-1 timekeeper attestation, the consumer renews for
another 60 s (escrow tops up to 1034), then the consumer cancels.

**Expected:** cancel refunds the whole escrow → consumer balance back to 1,000,000.

**Actual (reproduced 2026-11-11):**

```
escrow before cancel: 1034 micro-XUSD (base 517 + renewal 517)
consumer XUSD: funded=1000000 after-lease+renew=998966 after-cancel=999483
lease state after cancel: cancelled; pending sends to provider: 0
BUG: cancel after renewal destroyed 517 micro-XUSD
--- FAIL: TestCancelAfterRenewalDestroysTopUp
```

The test asserts the correct behaviour and FAILS on current code — that failure
is the demonstration.

## Root cause

`core/ledger.go`, `validateAndAddLeaseCancel` refunds `oldBal + leaseBlock.Amount`
(base cost only) and deletes the whole pending send
(`commit.DeletePendingID = b.Source`), while renewals top the pending up via
`commit.TopUpPendingID / TopUpPendingAmount` (`core/lease_renew.go`). Compare
`validateAndAddLeaseForceSettle`, which refunds `pending.Amount` in full —
cancel is the outlier.

## Live grounding

The 3 cancelled leases observed on the public testnet had no renewals and
refunded in full — consistent with this finding (the bug only appears when a
renewal exists).

## Suggested fix

Refund `pending.Amount` on cancel, as force-settle does (or reject cancel when
an unspent renewal top-up exists, with an explicit reason).

\<details\>
\<summary\>PoC test file (cancel\_renewal\_poc\_test.go)\</summary\>

```
package core_test

// PoC for: lease_cancel after lease_renew destroys the renewal escrow top-up.
// The cancel validator refunds only leaseBlock.Amount (the base cost) while the
// pending escrow at that point is base cost + sum(renewal costs). The pending
// send is deleted in full, so the renewal funds vanish: they are credited to
// neither the consumer nor the provider.
//
// Compare with lease_force_settle, which refunds pending.Amount in full.
//
// Run: go test ./core -run TestCancelAfterRenewalDestroysTopUp -v
// The test asserts the CORRECT behaviour (full refund) and FAILS on the
// current code, demonstrating the bug.

import (
	"strings"
	"testing"
	"time"

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

func mustKP(t *testing.T) *core.KeyPair {
	t.Helper()
	kp, err := core.GenerateKeyPair()
	if err != nil {
		t.Fatalf("keygen: %v", err)
	}
	return kp
}

func mustSign(t *testing.T, b *core.Block, kp *core.KeyPair) *core.Block {
	t.Helper()
	if err := core.SignBlock(b, kp); err != nil {
		t.Fatalf("sign %s: %v", b.Type, err)
	}
	return b
}

func TestCancelAfterRenewalDestroysTopUp(t *testing.T) {
	consumer := mustKP(t)
	provider := mustKP(t)
	tk := mustKP(t)

	nowNs := time.Now().UnixNano()
	certHash := strings.Repeat("b", 64) // any hash: lookup fn returns the cert for it
	st := store.NewMemStore()

	led := core.NewLedger(st, core.LedgerConfig{
		Difficulty:      0,
		TimestampWindow: 0,
		TimekeeperConfigFn: func() *core.TimekeeperConfig {
			return &core.TimekeeperConfig{Keys: []string{tk.PubKeyHex()}, Threshold: 1}
		},
		CertificateLookupFn: func(hash string) *core.CertificateInfo {
			return &core.CertificateInfo{
				Provider:             provider.Address(),
				ExpiresAt:            nowNs + int64(7*24*time.Hour),
				PriceMultiplierMilli: 1000,
			}
		},
		EpochAtFn: func(ns int64) []core.EpochParams {
			return []core.EpochParams{{R: 1000, PayoutCap: 1500, TWAP: 1000}}
		},
	})

	const fund uint64 = 1_000_000 // micro-XUSD
	// fund consumer + provider with XUSD via the test seeding path
	for _, kp := range []*core.KeyPair{consumer, provider} {
		mint := mustSign(t, &core.Block{
			Type: core.BlockMint, Asset: "XUSD", Account: kp.Address(),
			Previous: "0", Balance: fund, Amount: fund,
			Timestamp: nowNs,
		}, kp)
		if err := led.SeedAssetForTesting(mint); err != nil {
			t.Fatalf("seed %s: %v", kp.Address()[:12], err)
		}
	}

	// cost check: 1 vCPU + 1GB + 1GB for 60s at multiplier 1000 = 517 micro-XUSD
	cost, err := core.LeaseCost(1, 1024, 1, 60, 1000)
	if err != nil || cost != 517 {
		t.Fatalf("LeaseCost = %d, err %v (expected 517)", cost, err)
	}

	// 1) consumer creates the lease (escrow 517)
	lease := mustSign(t, &core.Block{
		Type: core.BlockLease, Asset: "XUSD", Account: consumer.Address(),
		Previous: led.GetChain(consumer.Address())[0].Hash,
		Balance:  fund - cost, Amount: cost,
		Destination: provider.Address(), VCPUs: 1, MemoryMB: 1024, DiskGB: 1,
		Duration: 60, CertificateHash: certHash, Timestamp: nowNs + int64(time.Second),
	}, consumer)
	if err := led.AddBlock(lease); err != nil {
		t.Fatalf("lease: %v", err)
	}

	// 2) provider accepts (attestation from the single trusted timekeeper)
	att0, err := core.SignAttestation(lease.Hash, nowNs, tk)
	if err != nil {
		t.Fatalf("attestation: %v", err)
	}
	accept := mustSign(t, &core.Block{
		Type: core.BlockLeaseAccept, Asset: "XUSD", Account: provider.Address(),
		Previous: led.GetChain(provider.Address())[0].Hash,
		Balance:  fund, Amount: 0, // stake is 0 (LeaseStakeDivisor == 0)
		Source: lease.Hash, CertificateHash: certHash,
		LockedR: 1000, LockedPayoutCap: 1500, LockedTWAP: 1000,
		Attestations: []core.TimekeeperAttestation{*att0},
		Timestamp:    nowNs + 2*int64(time.Second),
	}, provider)
	if err := led.AddBlock(accept); err != nil {
		t.Fatalf("accept: %v", err)
	}

	// 3) consumer renews for another 60s (escrow tops up by another 517)
	att1, err := core.SignAttestation(lease.Hash, nowNs+2*int64(time.Second), tk)
	if err != nil {
		t.Fatalf("attestation: %v", err)
	}
	renew := mustSign(t, &core.Block{
		Type: core.BlockLeaseRenew, Asset: "XUSD", Account: consumer.Address(),
		Previous: lease.Hash,
		Balance:  fund - 2*cost, Amount: cost, Duration: 60,
		Source: lease.Hash, CertificateHash: certHash,
		LockedR: 1000, LockedPayoutCap: 1500, LockedTWAP: 1000,
		Attestations: []core.TimekeeperAttestation{*att1},
		Timestamp:    nowNs + 3*int64(time.Second),
	}, consumer)
	if err := led.AddBlock(renew); err != nil {
		t.Fatalf("renew: %v", err)
	}

	// escrow must now be base + renewal = 1034
	pending := led.GetPendingForAccount(provider.Address())
	if len(pending) != 1 || pending[0].Amount != 2*cost {
		t.Fatalf("escrow after renew: got %+v, want one pending of %d", pending, 2*cost)
	}
	t.Logf("escrow before cancel: %d micro-XUSD (base %d + renewal %d)", pending[0].Amount, cost, cost)

	// 4) consumer cancels. The validator forces Balance = oldBal + base cost only.
	balBefore := led.GetAssetBalances(consumer.Address())["XUSD"]
	cancel := mustSign(t, &core.Block{
		Type: core.BlockLeaseCancel, Asset: "XUSD", Account: consumer.Address(),
		Previous: renew.Hash,
		Balance:  balBefore + cost, // what validateAndAddLeaseCancel demands
		Source: lease.Hash,
		Timestamp: nowNs + 4*int64(time.Second),
	}, consumer)
	if err := led.AddBlock(cancel); err != nil {
		t.Fatalf("cancel: %v", err)
	}

	balAfter := led.GetAssetBalances(consumer.Address())["XUSD"]
	leaseAfter, _ := st.GetLease(lease.Hash)
	t.Logf("consumer XUSD: funded=%d after-lease+renew=%d after-cancel=%d", fund, balBefore, balAfter)
	t.Logf("lease state after cancel: %s; pending sends to provider: %d", leaseAfter.State, len(led.GetPendingForAccount(provider.Address())))

	// Correct behaviour: full escrow refund -> balance back to `fund`.
	// Actual behaviour on current code: balance is `fund - cost` (renewal lost).
	if balAfter != fund {
		t.Errorf("BUG: cancel after renewal destroyed %d micro-XUSD: balance after cancel = %d, want %d (full escrow refund)",
			fund-balAfter, balAfter, fund)
	}
}
```

\</details\>

### Thread

**Joseph Denne**team2026-11-20 00:04 UTCgithub

Thanks. This is the same finding as https://bounty.xe.network/XE-0067, 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-13254 and says what differs; it is read like any other.
