Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bindings/bin/l1crossdomainmessenger_deployed.hex

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion bindings/bin/l2crossdomainmessenger_deployed.hex

Large diffs are not rendered by default.

559 changes: 557 additions & 2 deletions bindings/bindings/l1crossdomainmessenger.go

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions bindings/bindings/l1crossdomainmessenger_more.go

Large diffs are not rendered by default.

191 changes: 189 additions & 2 deletions bindings/bindings/l2crossdomainmessenger.go

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions bindings/bindings/l2crossdomainmessenger_more.go

Large diffs are not rendered by default.

27 changes: 27 additions & 0 deletions contracts/contracts/l1/IL1CrossDomainMessenger.sol
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ pragma solidity =0.8.24;
import {ICrossDomainMessenger} from "../libraries/ICrossDomainMessenger.sol";

interface IL1CrossDomainMessenger is ICrossDomainMessenger {
/**********
* Errors *
**********/

/// @dev Thrown when the caller is neither the owner nor the rate limit admin.
error ErrNotOwnerOrRateLimitAdmin();

/// @dev Thrown when the rate limit admin tries to loosen or disable the ETH rate limit.
error ErrRateLimitAdminCanOnlyTighten();

/**********
* Events *
**********/
Expand Down Expand Up @@ -37,6 +47,23 @@ interface IL1CrossDomainMessenger is ICrossDomainMessenger {
bytes message
);

/// @notice Emitted when ETH is released under the ETH rate limit.
/// @param messageHash The hash of the relayed message.
/// @param amount The amount of ETH released.
/// @param remaining The amount of ETH left in the rate limiter.
event ETHRateLimitConsumed(bytes32 indexed messageHash, uint256 amount, uint256 remaining);

/// @notice Emitted when the config of the ETH rate limiter is updated.
/// @param isEnabled Whether the rate limit is enabled.
/// @param capacity The maximum amount of ETH the rate limiter can hold.
/// @param rate The amount of ETH refilled per second.
event UpdateETHRateLimiterConfig(bool isEnabled, uint256 capacity, uint256 rate);

/// @notice Emitted when the rate limit admin is updated.
/// @param oldRateLimitAdmin The address of the old rate limit admin.
/// @param newRateLimitAdmin The address of the new rate limit admin.
event UpdateRateLimitAdmin(address indexed oldRateLimitAdmin, address indexed newRateLimitAdmin);

/*****************************
* Public Mutating Functions *
*****************************/
Expand Down
58 changes: 58 additions & 0 deletions contracts/contracts/l1/L1CrossDomainMessenger.sol
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {ICrossDomainMessenger} from "../libraries/ICrossDomainMessenger.sol";
import {IL1MessageQueue} from "./rollup/IL1MessageQueue.sol";
import {IRollup} from "./rollup/IRollup.sol";
import {Verify} from "../libraries/common/Verify.sol";
import {RateLimiter} from "../libraries/common/RateLimiter.sol";
import {IL1CrossDomainMessenger} from "./IL1CrossDomainMessenger.sol";

/**
Expand All @@ -19,6 +20,8 @@ import {IL1CrossDomainMessenger} from "./IL1CrossDomainMessenger.sol";
* interface instead of interacting with lower-level contracts directly.
*/
contract L1CrossDomainMessenger is IL1CrossDomainMessenger, CrossDomainMessenger, Verify {
using RateLimiter for RateLimiter.TokenBucket;

/***********
* Structs *
***********/
Expand Down Expand Up @@ -69,6 +72,12 @@ contract L1CrossDomainMessenger is IL1CrossDomainMessenger, CrossDomainMessenger
/// avoid such situation.
mapping(uint256 => uint256) public prevReplayIndex;

/// @notice The token bucket limiting the ETH released by `proveAndRelayMessage`.
RateLimiter.TokenBucket internal ethRateLimiter;

/// @notice The address allowed to tighten the ETH rate limit.
address public rateLimitAdmin;

/***************
* Constructor *
***************/
Expand All @@ -94,6 +103,15 @@ contract L1CrossDomainMessenger is IL1CrossDomainMessenger, CrossDomainMessenger
emit UpdateMaxReplayTimes(0, 3);
}

/*************************
* Public View Functions *
*************************/

/// @notice Return the state of the ETH rate limiter, refilled to the current block.
function currentETHRateLimiterState() external view returns (RateLimiter.TokenBucket memory) {
return RateLimiter.currentState(ethRateLimiter);
}

/*****************************
* Public Mutating Functions *
*****************************/
Expand Down Expand Up @@ -156,6 +174,9 @@ contract L1CrossDomainMessenger is IL1CrossDomainMessenger, CrossDomainMessenger
"Messenger: invalid withdrawal inclusion proof"
);
}
// rate limit the ETH released from the messenger
ethRateLimiter.consume(_value);

// relay message
xDomainMessageSender = _from;
(bool success, ) = _to.call{value: _value}(_message);
Expand All @@ -165,8 +186,13 @@ contract L1CrossDomainMessenger is IL1CrossDomainMessenger, CrossDomainMessenger
if (success) {
// Mark the withdrawal as finalized so it can't be replayed.
finalizedWithdrawals[_xDomainCalldataHash] = true;
if (_value != 0 && ethRateLimiter.isEnabled) {
emit ETHRateLimitConsumed(_xDomainCalldataHash, _value, ethRateLimiter.tokens);
}
emit RelayedMessage(_xDomainCalldataHash);
} else {
// The ETH stays in the messenger, so the consumed tokens are given back.
ethRateLimiter.refund(_value);
emit FailedRelayedMessage(_xDomainCalldataHash);
}
}
Expand Down Expand Up @@ -268,6 +294,38 @@ contract L1CrossDomainMessenger is IL1CrossDomainMessenger, CrossDomainMessenger
emit UpdateMaxReplayTimes(_oldMaxReplayTimes, _newMaxReplayTimes);
}

/// @notice Update the config of the ETH rate limiter.
/// @dev The owner can set any valid config. The rate limit admin can only tighten the rate limit:
/// enable it, or lower the capacity and the rate of an enabled one.
/// @param _config The new config.
function setETHRateLimiterConfig(RateLimiter.Config calldata _config) external {
address _sender = _msgSender();
if (_sender != owner()) {
if (_sender != rateLimitAdmin) revert ErrNotOwnerOrRateLimitAdmin();
RateLimiter.TokenBucket memory _current = ethRateLimiter;
if (
!_config.isEnabled ||
(_current.isEnabled && (_config.capacity > _current.capacity || _config.rate > _current.rate))
) {
revert ErrRateLimitAdminCanOnlyTighten();
}
}

ethRateLimiter.setConfig(_config);

emit UpdateETHRateLimiterConfig(_config.isEnabled, _config.capacity, _config.rate);
}

/// @notice Update the rate limit admin.
/// @dev This function can only called by contract owner.
/// @param _newRateLimitAdmin The address of the new rate limit admin, zero address revokes the role.
function updateRateLimitAdmin(address _newRateLimitAdmin) external onlyOwner {
address _oldRateLimitAdmin = rateLimitAdmin;
rateLimitAdmin = _newRateLimitAdmin;

emit UpdateRateLimitAdmin(_oldRateLimitAdmin, _newRateLimitAdmin);
}

/**********************
* Internal Functions *
**********************/
Expand Down
2 changes: 1 addition & 1 deletion contracts/contracts/l1/gateways/L1ETHGateway.sol
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ contract L1ETHGateway is GatewayBase, IL1ETHGateway, IMessageDropCallback {
(_from, _data) = abi.decode(_data, (address, bytes));
}

// @note no rate limit here, since ETH is limited in messenger
// @note no rate limit on deposits, ETH withdrawals are rate limited in L1CrossDomainMessenger

// 2. Generate message passed to L1CrossDomainMessenger.
bytes memory _message = abi.encodeCall(IL2ETHGateway.finalizeDepositETH, (_from, _to, _amount, _data));
Expand Down
14 changes: 14 additions & 0 deletions contracts/contracts/l2/IL2CrossDomainMessenger.sol
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ pragma solidity =0.8.24;
import {ICrossDomainMessenger} from "../libraries/ICrossDomainMessenger.sol";

interface IL2CrossDomainMessenger is ICrossDomainMessenger {
/**********
* Errors *
**********/

/// @dev Thrown when the ETH value of a L2 to L1 message exceeds `maxWithdrawalValue`.
/// @param value The ETH value of the message.
/// @param maxValue The maximum ETH value of a single message.
error ErrExceedMaxWithdrawalValue(uint256 value, uint256 maxValue);

/**********
* Events *
**********/
Expand All @@ -14,6 +23,11 @@ interface IL2CrossDomainMessenger is ICrossDomainMessenger {
/// @param newMaxFailedExecutionTimes The new maximum number of times each message can fail in L2.
event UpdateMaxFailedExecutionTimes(uint256 oldMaxFailedExecutionTimes, uint256 newMaxFailedExecutionTimes);

/// @notice Emitted when the maximum ETH value of a single L2 to L1 message is updated.
/// @param oldMaxWithdrawalValue The old maximum ETH value.
/// @param newMaxWithdrawalValue The new maximum ETH value.
event UpdateMaxWithdrawalValue(uint256 oldMaxWithdrawalValue, uint256 newMaxWithdrawalValue);

/*****************************
* Public Mutating Functions *
*****************************/
Expand Down
23 changes: 23 additions & 0 deletions contracts/contracts/l2/L2CrossDomainMessenger.sol
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ contract L2CrossDomainMessenger is CrossDomainMessenger, IL2CrossDomainMessenger
/// @notice Mapping from L1 message hash to a boolean value indicating if the message has been successfully executed.
mapping(bytes32 => bool) public isL1MessageExecuted;

/// @notice The maximum ETH value of a single L2 to L1 message, zero means no limit.
/// @dev Keep it no larger than the capacity of the ETH rate limiter in L1CrossDomainMessenger,
/// otherwise larger messages cannot be relayed on L1.
uint256 public maxWithdrawalValue;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/***************
* Constructor *
***************/
Expand Down Expand Up @@ -91,6 +96,20 @@ contract L2CrossDomainMessenger is CrossDomainMessenger, IL2CrossDomainMessenger
return L2ToL1MessagePasser(Predeploys.L2_TO_L1_MESSAGE_PASSER).leafNodesCount();
}

/************************
* Restricted Functions *
************************/

/// @notice Update the maximum ETH value of a single L2 to L1 message.
/// @dev This function can only called by contract owner.
/// @param _newMaxWithdrawalValue The new maximum ETH value, zero means no limit.
function updateMaxWithdrawalValue(uint256 _newMaxWithdrawalValue) external onlyOwner {
uint256 _oldMaxWithdrawalValue = maxWithdrawalValue;
maxWithdrawalValue = _newMaxWithdrawalValue;

emit UpdateMaxWithdrawalValue(_oldMaxWithdrawalValue, _newMaxWithdrawalValue);
}

/**********************
* Internal Functions *
**********************/
Expand All @@ -102,6 +121,10 @@ contract L2CrossDomainMessenger is CrossDomainMessenger, IL2CrossDomainMessenger
/// @param _gasLimit Optional gas limit to complete the message relay on corresponding chain.
function _sendMessage(address _to, uint256 _value, bytes memory _message, uint256 _gasLimit) internal nonReentrant {
require(msg.value == _value, "msg.value mismatch");
uint256 _maxWithdrawalValue = maxWithdrawalValue;
if (_maxWithdrawalValue != 0 && _value > _maxWithdrawalValue) {
revert ErrExceedMaxWithdrawalValue(_value, _maxWithdrawalValue);
}

address messagePasser = Predeploys.L2_TO_L1_MESSAGE_PASSER;
uint256 _nonce = L2ToL1MessagePasser(messagePasser).leafNodesCount();
Expand Down
2 changes: 1 addition & 1 deletion contracts/contracts/l2/gateways/L2ETHGateway.sol
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ contract L2ETHGateway is GatewayBase, IL2ETHGateway {
(_from, _data) = abi.decode(_data, (address, bytes));
}

// @note no rate limit here, since ETH is limited in messenger
// @note no rate limit here, ETH is capped in L2CrossDomainMessenger and rate limited in L1CrossDomainMessenger
bytes memory _message = abi.encodeCall(IL1ETHGateway.finalizeWithdrawETH, (_from, _to, _amount, _data));

uint256 nonce = IL2CrossDomainMessenger(messenger).messageNonce();
Expand Down
132 changes: 132 additions & 0 deletions contracts/contracts/libraries/common/RateLimiter.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// SPDX-License-Identifier: MIT
pragma solidity =0.8.24;

/// @title RateLimiter
/// @notice Token bucket rate limiter. The bucket holds at most `capacity` tokens and is refilled at `rate`
/// tokens per second, so the amount consumed during any period `T` never exceeds `capacity + rate * T`.
library RateLimiter {
/**********
* Errors *
**********/

/// @dev Thrown when the requested amount exceeds the bucket capacity, which can never succeed.
/// @param capacity The capacity of the bucket.
/// @param requested The requested amount.
error ErrRateLimitCapacityExceeded(uint256 capacity, uint256 requested);

/// @dev Thrown when the bucket does not hold enough tokens for now.
/// @param minWaitInSeconds The minimum time to wait before the bucket can cover the request.
/// @param available The amount of tokens currently available.
error ErrRateLimitReached(uint256 minWaitInSeconds, uint256 available);

/// @dev Thrown when the config is invalid.
/// @param isEnabled Whether the rate limit is enabled.
/// @param capacity The capacity of the bucket.
/// @param rate The refill rate of the bucket.
error ErrInvalidRateLimitConfig(bool isEnabled, uint128 capacity, uint128 rate);

/***********
* Structs *
***********/

struct Config {
// Whether the rate limit is enabled.
bool isEnabled;
// The maximum amount of tokens the bucket can hold.
uint128 capacity;
// The amount of tokens refilled per second.
uint128 rate;
}

struct TokenBucket {
// The amount of tokens in the bucket at `lastUpdated`.
uint128 tokens;
// The timestamp when the bucket was last updated.
uint32 lastUpdated;
// Whether the rate limit is enabled.
bool isEnabled;
// The maximum amount of tokens the bucket can hold.
uint128 capacity;
// The amount of tokens refilled per second.
uint128 rate;
}

/**********************
* Internal Functions *
**********************/

/// @dev Consume tokens from the bucket, revert if the bucket cannot cover the amount.
/// @param _bucket The token bucket.
/// @param _amount The amount of tokens to consume.
function consume(TokenBucket storage _bucket, uint256 _amount) internal {
if (!_bucket.isEnabled || _amount == 0) return;

uint256 _capacity = _bucket.capacity;
if (_amount > _capacity) revert ErrRateLimitCapacityExceeded(_capacity, _amount);

uint256 _rate = _bucket.rate;
uint256 _tokens = _refill(_bucket.tokens, _capacity, _rate, _bucket.lastUpdated);
if (_tokens < _amount) {
uint256 _wait = _rate == 0 ? type(uint256).max : (_amount - _tokens + _rate - 1) / _rate;
revert ErrRateLimitReached(_wait, _tokens);
}

_bucket.tokens = uint128(_tokens - _amount);
_bucket.lastUpdated = uint32(block.timestamp);
}

/// @dev Give back tokens to the bucket when the guarded transfer did not happen.
/// @param _bucket The token bucket.
/// @param _amount The amount of tokens to give back.
function refund(TokenBucket storage _bucket, uint256 _amount) internal {
if (!_bucket.isEnabled || _amount == 0) return;

uint256 _capacity = _bucket.capacity;
uint256 _tokens = _refill(_bucket.tokens, _capacity, _bucket.rate, _bucket.lastUpdated) + _amount;
_bucket.tokens = uint128(_tokens < _capacity ? _tokens : _capacity);
_bucket.lastUpdated = uint32(block.timestamp);
}

/// @dev Update the config of the bucket. An enabled bucket is refilled with the old config and then
/// capped at the new capacity, so updating the config never grants extra tokens. A disabled bucket
/// starts full once enabled, and a disabled config must be all zero.
/// @param _bucket The token bucket.
/// @param _config The new config.
function setConfig(TokenBucket storage _bucket, Config memory _config) internal {
if (_config.isEnabled ? _config.rate > _config.capacity : (_config.capacity != 0 || _config.rate != 0)) {
revert ErrInvalidRateLimitConfig(_config.isEnabled, _config.capacity, _config.rate);
}

uint256 _tokens = _bucket.isEnabled
? _refill(_bucket.tokens, _bucket.capacity, _bucket.rate, _bucket.lastUpdated)
: _config.capacity;
_bucket.tokens = uint128(_tokens < _config.capacity ? _tokens : _config.capacity);
_bucket.lastUpdated = uint32(block.timestamp);
_bucket.isEnabled = _config.isEnabled;
_bucket.capacity = _config.capacity;
_bucket.rate = _config.rate;
}

/// @dev Return the bucket refilled to the current block.
/// @param _bucket The token bucket.
function currentState(TokenBucket memory _bucket) internal view returns (TokenBucket memory) {
_bucket.tokens = uint128(_refill(_bucket.tokens, _bucket.capacity, _bucket.rate, _bucket.lastUpdated));
_bucket.lastUpdated = uint32(block.timestamp);
return _bucket;
}

/*********************
* Private Functions *
*********************/

/// @dev `_rate * elapsed` fits in uint256 since `_rate` is a uint128 and the timestamps are uint32.
function _refill(
uint256 _tokens,
uint256 _capacity,
uint256 _rate,
uint256 _lastUpdated
) private view returns (uint256) {
uint256 _refilled = _tokens + (block.timestamp - _lastUpdated) * _rate;
return _refilled < _capacity ? _refilled : _capacity;
}
}
Loading
Loading