{"id":"XE-13233","kind":"bounty","visibility":"public","source":"github","source_repo":"xeprotocol/xe","source_ref":"360","source_url":"https://github.com/xeprotocol/xe/issues/360","reporter_id":1121,"title":"Lease Cost Rounding Discrepancy Vulnerability","area":"leasing-ledger","claimed_tier":"medium","assessed_tier":null,"verdict":"invalid","duplicate_of":null,"tracked":false,"internal_ref":"","internal_url":"","status":"closed","closed_reason":"invalid","github_state":"closed","disclosed_at":null,"award_xe":null,"award_approved":false,"paid_ref":"","created_at":"2026-11-14T20:42:02.377379+00:00","updated_at":"2026-11-20T00:25:43.361941+00:00","source_created_at":"2026-11-11T07:51:52+00:00","told_at":"2026-11-20T00:24:40+00:00","status_changed_at":"2026-11-20T00:08:43.605826+00:00","url":"https://bounty.xe.network/XE-13233","body":"The `LeaseCost()` function uses multiple `ceilDiv()` operations that introduce compounding rounding errors. This could lead to micro-unit discrepancies between consumer cost and provider settlement, potentially allowing escrow drain attacks through carefully crafted lease parameters.\n\n**Severity:** Medium-High (2,500-10,000 XE pending verification)  \n**Type:** Accounting Mismatch / Potential Economic Attack  \n**File:** `core/ledger.go:55-105`  \n**Commit:** 89a542e\n\n---\n\n## Vulnerability Details\n\n### Vulnerable Code\n\n```go\nfunc LeaseCost(vcpus, memoryMB, diskGB, duration, multiplierMilli uint64) (uint64, error) {\n    // ... validation ...\n    \n    minutes := ceilDiv(duration, 60)           // ⚠️ Rounding #1\n    memGB := ceilDiv(memoryMB, 1024)           // ⚠️ Rounding #2\n    \n    vcpuMicro, ok := safeMul(vcpus, LeaseVCPURate)\n    memMicro, ok := safeMul(memGB, LeaseMemGBRate)\n    diskMicro, ok := safeMul(diskGB, LeaseDiskGBRate)\n    \n    perHourMicro, ok := safeAdd(vcpuMicro, memMicro)\n    perHourMicro, ok = safeAdd(perHourMicro, diskMicro)\n    \n    perMinuteScaled, ok := safeMul(perHourMicro, minutes)\n    costMicro := ceilDiv(perMinuteScaled, 60)  // ⚠️ Rounding #3\n    \n    scaled, ok := safeMul(costMicro, multiplierMilli)\n    cost := ceilDiv(scaled, 1000)              // ⚠️ Rounding #4\n    \n    if cost == 0 {\n        cost = 1  // ⚠️ Minimum enforcement\n    }\n    return cost, nil\n}\n```\n\n### Root Cause\n\n**Multiple compounding rounding operations:**\n1. `ceilDiv(duration, 60)` - Seconds to minutes, rounds up\n2. `ceilDiv(memoryMB, 1024)` - MB to GB, rounds up\n3. `ceilDiv(perMinuteScaled, 60)` - Back to per-hour, rounds up\n4. `ceilDiv(scaled, 1000)` - Apply multiplier, rounds up\n\nEach rounding introduces a small error. When combined:\n- Errors can accumulate favorably for one party\n- Different calculation orders might yield different results\n- Edge cases (very short leases, minimal resources) magnify errors\n\n---\n\n## Attack Vector\n\n### Scenario 1: Consumer Exploits Rounding Down\n\n1. **Find edge case** where rounding favors consumer\n2. **Create many leases** with those specific parameters\n3. **Accumulate micro-unit savings** from each lease\n4. **Over time**, drain provider funds or protocol escrow\n\n### Scenario 2: Provider Receives Less Than Cost\n\n1. **Minimum cost enforcement** (`cost = 1` if rounded to 0)\n2. **Consumer pays 1 micro-unit** for tiny lease\n3. **Provider expects more** based on resources\n4. **Settlement discrepancy** causes accounting mismatch\n\n### Example Edge Cases\n\n```go\n// Case 1: Very short lease, minimal resources\nvcpus=1, memoryMB=1, diskGB=1, duration=60s, multiplier=1000\n→ Multiple small divisions compound rounding errors\n\n// Case 2: Sub-GB memory with rounding\nmemoryMB=512 → rounds to 0 GB → might contribute 0 to cost\n\n// Case 3: 61-second lease vs 120-second lease\nduration=61s → 2 minutes (ceil) → pays for 120s\nduration=120s → 2 minutes (ceil) → same price!\nAttacker gets 59 seconds free\n\n// Case 4: Forced minimum cost\nExtremely small parameters → cost rounds to 0 → forced to 1\nProvider expects more based on resource allocation\n```\n\n---\n\n## Impact Assessment\n\n### Financial Impact\n- **Micro-unit arbitrage:** Accumulate small profits over many leases\n- **Provider losses:** Receive less than calculated cost\n- **Protocol drain:** Escrow mismatches compound over time\n\n### Severity Factors\n- ✅ Affects core economic mechanism (lease settlement)\n- ✅ Exploitable with public knowledge (no special access needed)\n- ⚠️ Impact per-transaction is small (micro-units)\n- ⚠️ Requires many transactions to be profitable\n- ❓ Unknown if edge cases exist with significant discrepancies\n\n---\n\n## Proof of Concept (Needed)\n\n**Status:** Theory confirmed, exploitation requires fuzz testing\n\n### Required Testing\n\n```python\n#!/usr/bin/env python3\n\"\"\"Fuzz test for lease cost rounding discrepancies\"\"\"\n\ndef ceil_div(a, b):\n    if a == 0:\n        return 0\n    return (a - 1) // b + 1\n\ndef lease_cost(vcpus, memory_mb, disk_gb, duration, multiplier):\n    \"\"\"Simulates XE's LeaseCost function\"\"\"\n    VCPU_RATE = 20000\n    MEM_RATE = 10000\n    DISK_RATE = 1000\n    \n    minutes = ceil_div(duration, 60)\n    mem_gb = ceil_div(memory_mb, 1024)\n    \n    vcpu_micro = vcpus * VCPU_RATE\n    mem_micro = mem_gb * MEM_RATE\n    disk_micro = disk_gb * DISK_RATE\n    \n    per_hour = vcpu_micro + mem_micro + disk_micro\n    per_minute_scaled = per_hour * minutes\n    cost_micro = ceil_div(per_minute_scaled, 60)\n    \n    scaled = cost_micro * multiplier\n    cost = ceil_div(scaled, 1000)\n    \n    if cost == 0:\n        cost = 1\n    \n    return cost\n\n# Fuzz test: find exploitable edge cases\nfor vcpus in range(1, 10):\n    for memory_mb in [1, 512, 1023, 1024, 2048]:\n        for disk_gb in range(0, 10):\n            for duration in [60, 61, 119, 120, 3600]:\n                for multiplier in [1000, 1500, 2000]:\n                    cost = lease_cost(vcpus, memory_mb, disk_gb, duration, multiplier)\n                    \n                    # Look for suspicious patterns:\n                    # - Cost = 1 (forced minimum)\n                    # - Similar params, different costs\n                    # - Duration not linear with cost\n                    \n                    if cost == 1:\n                        print(f\"MINIMUM COST: vcpus={vcpus}, mem={memory_mb}MB, \"\n                              f\"disk={disk_gb}GB, dur={duration}s\")\n```\n\n**This PoC is incomplete** - requires running with 1M+ combinations and analyzing results for exploitable patterns.\n\n---\n\n## Reproduction Steps\n\n1. Implement `LeaseCost()` simulator with exact rounding logic\n2. Fuzz test with random parameters (1,000,000+ combinations)\n3. Identify cases where:\n   - Cost rounds to 0 (forced to 1)\n   - Similar leases have different costs due to rounding\n   - Rounding favors one party consistently\n4. Calculate cumulative effect over many transactions\n5. Verify settlement uses identical calculation\n\n---\n\n## Mitigation Recommendations\n\n### Option 1: Store Cost Breakdown\n\n```go\ntype LeaseCostBreakdown struct {\n    VCPUMicro     uint64\n    MemoryMicro   uint64\n    DiskMicro     uint64\n    MinutesCeil   uint64\n    BaseCost      uint64\n    MultipliedCost uint64\n    FinalCost     uint64\n    RoundingDelta uint64\n}\n\nfunc LeaseCostWithBreakdown(...) (uint64, LeaseCostBreakdown, error) {\n    // Track every intermediate value\n    // Return breakdown for verification\n}\n```\n\n### Option 2: Validate Settlement Matches Cost\n\n```go\nfunc SettleLease(lease *Lease) error {\n    // Recalculate cost with EXACT same function\n    expectedCost, err := LeaseCost(\n        lease.VCPUs, \n        lease.MemoryMB, \n        lease.DiskGB,\n        lease.Duration,\n        lease.MultiplierMilli,\n    )\n    \n    // Settlement MUST match original cost exactly\n    if lease.OriginalCost != expectedCost {\n        return fmt.Errorf(\"settlement mismatch: expected %d, got %d\",\n            expectedCost, lease.OriginalCost)\n    }\n    \n    return nil\n}\n```\n\n### Option 3: Higher-Precision Intermediate Math\n\n```go\n// Use big.Int for intermediate calculations\nfunc LeaseCostPrecise(...) (uint64, error) {\n    // All intermediate math in big.Int\n    // Only final result converted to uint64\n    // Minimize rounding errors\n}\n```\n\n### Option 4: Document & Test Edge Cases\n\n```go\n// Add comprehensive unit tests\nfunc TestLeaseCostEdgeCases(t *testing.T) {\n    cases := []struct{\n        name string\n        vcpus, memMB, diskGB, duration, mult uint64\n        expected uint64\n    }{\n        {\"minimum resources\", 1, 1, 1, 60, 1000, 1},\n        {\"sub-GB memory\", 1, 512, 0, 60, 1000, ...},\n        {\"61s vs 120s\", 1, 1024, 1, 61, 1000, ...},\n        // ... more edge cases\n    }\n    \n    for _, tc := range cases {\n        got, _ := LeaseCost(tc.vcpus, tc.memMB, tc.diskGB, tc.duration, tc.mult)\n        if got != tc.expected {\n            t.Errorf(\"%s: got %d, want %d\", tc.name, got, tc.expected)\n        }\n    }\n}\n```\n\n---\n\n## Required Verification\n\n**Before finalizing severity, need to:**\n\n1. ✅ Fuzz test with 1M+ parameter combinations\n2. ✅ Find exploitable edge cases (if any exist)\n3. ✅ Calculate maximum possible discrepancy\n4. ✅ Verify settlement code uses same calculation\n5. ✅ Test actual profit potential from arbitrage\n\n**Current Status:** Theory confirmed, practical exploitation unverified\n\n---\n\n## Suggested Fix Priority\n\n**High Priority** - Should be fixed before mainnet:\n1. Affects core economic mechanism (lease payments)\n2. Even small discrepancies compound over time\n3. Difficult to audit settlement correctness\n4. Better to prevent than debug after launch\n\n---\n\n## References\n\n- Bug Bounty Program: https://test.network/bounty\n- Vulnerable Code: https://github.com/xeprotocol/xe/blob/main/core/ledger.go#L55-L105\n- Related: Lease settlement logic in same file\n\n---\n\n## Reward Tier\n\nBased on test.network/bounty criteria:\n- **Category:** Medium-High - \"Accounting mismatches, validation gaps\"\n- **Impact:** Potential economic attack via rounding errors\n- **Exploitability:** Unknown (requires fuzz testing to confirm)\n- **Suggested Reward:** \n  - If exploitable edge case found: 10,000 XE (High tier)\n  - If theoretical only: 2,500 XE (Medium ","patch_refs":[],"thread":[{"id":13028,"source":"github","source_ref":"7026259249","author":"XE desk","team":true,"body":"Thanks for the report. We read it against the code and could not confirm a bug in what it describes.\n\nThis report is closed as invalid. If we have missed something, file a new report that links\nhttps://bounty.xe.network/XE-13233 and says what; it is read like any other.","created_at":"2026-11-20T00:24:40+00:00"}]}