remove sign; L1Helper with registration; minimal withdraw; maximum deposit; refactoring

This commit is contained in:
Alexey 2021-10-06 17:51:46 +03:00
parent 13bd330e67
commit f78bb5d597
18 changed files with 1024 additions and 4993 deletions

View File

@ -1,2 +1,4 @@
PRIVATE_KEY=
ETH_RPC=https://
MINIMUM_WITHDRAWAL_AMOUNT=0.05
MAXIMUM_DEPOSIT_AMOUNT=1

View File

@ -1,8 +1,8 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import { IAMB } from "./interfaces/Bridge.sol";
import "@openzeppelin/contracts/contracts/proxy/TransparentUpgradeableProxy.sol";
import { IAMB } from "./interfaces/IBridge.sol";
import "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol";
/**
* @dev TransparentUpgradeableProxy where admin acts from a different chain.

View File

@ -43,7 +43,7 @@ contract MerkleTreeWithHistory is Initializable {
hasher = IHasher(_hasher);
}
function initialize() external initializer {
function _initialize() internal {
for (uint32 i = 0; i < levels; i++) {
filledSubtrees[i] = zeros(i);
}

View File

@ -9,4 +9,8 @@ contract MerkleTreeWithHistoryMock is MerkleTreeWithHistory {
function insert(bytes32 _leaf1, bytes32 _leaf2) public returns (uint32 index) {
return _insert(_leaf1, _leaf2);
}
function initialize() external {
super._initialize();
}
}

View File

@ -1,7 +1,7 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import { IAMB, IOmniBridge } from "../interfaces/Bridge.sol";
import { IAMB, IOmniBridge } from "../interfaces/IBridge.sol";
contract MockOmniBridge is IOmniBridge {
IAMB public AMB;

View File

@ -13,37 +13,16 @@
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/contracts/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { IERC20Receiver, IERC6777 } from "./interfaces/IBridge.sol";
import { IVerifier } from "./interfaces/IVerifier.sol";
import "./MerkleTreeWithHistory.sol";
interface IERC6777 is IERC20 {
function transferAndCall(
address,
uint256,
bytes calldata
) external returns (bool);
}
interface IVerifier {
function verifyProof(bytes memory _proof, uint256[7] memory _input) external view returns (bool);
function verifyProof(bytes memory _proof, uint256[21] memory _input) external view returns (bool);
}
interface IERC20Receiver {
function onTokenBridged(
IERC6777 token,
uint256 value,
bytes calldata data
) external;
}
contract TornadoPool is MerkleTreeWithHistory, IERC20Receiver {
contract TornadoPool is MerkleTreeWithHistory, IERC20Receiver, ReentrancyGuard {
int256 public constant MAX_EXT_AMOUNT = 2**248;
uint256 public constant MAX_FEE = 2**248;
bytes32 public constant ACCOUNT_TYPEHASH = keccak256("TornadoAccount(address owner,bytes publicKey)");
uint256 public immutable L1_CHAIN_ID;
address public immutable governance;
IVerifier public immutable verifier2;
IVerifier public immutable verifier16;
@ -51,7 +30,9 @@ contract TornadoPool is MerkleTreeWithHistory, IERC20Receiver {
address public immutable omniBridge;
address public immutable l1Unwrapper;
uint256 public totalDeposited;
uint256 public lastBalance;
uint256 public minimalWithdrawalAmount;
uint256 public maximumDepositAmount;
mapping(bytes32 => bool) public nullifierHashes;
struct ExtData {
@ -82,6 +63,11 @@ contract TornadoPool is MerkleTreeWithHistory, IERC20Receiver {
event NewNullifier(bytes32 nullifier);
event PublicKey(address indexed owner, bytes key);
modifier onlyGovernance() {
require(msg.sender == governance, "only governance");
_;
}
/**
@dev The constructor
@param _verifier2 the address of SNARK verifier for 2 inputs
@ -95,27 +81,36 @@ contract TornadoPool is MerkleTreeWithHistory, IERC20Receiver {
IERC6777 _token,
address _omniBridge,
address _l1Unwrapper,
uint256 _l1ChainId
address _governance
) MerkleTreeWithHistory(_levels, _hasher) {
verifier2 = _verifier2;
verifier16 = _verifier16;
token = _token;
omniBridge = _omniBridge;
l1Unwrapper = _l1Unwrapper;
L1_CHAIN_ID = _l1ChainId;
governance = _governance;
}
function initialize(uint256 _minimalWithdrawalAmount, uint256 _maximumDepositAmount) external initializer {
_configureLimits(_minimalWithdrawalAmount, _maximumDepositAmount);
super._initialize();
}
function configureLimits(uint256 _minimalWithdrawalAmount, uint256 _maximumDepositAmount) public onlyGovernance {
_configureLimits(_minimalWithdrawalAmount, _maximumDepositAmount);
}
function transact(Proof memory _args, ExtData memory _extData) public {
if (_extData.extAmount > 0) {
// for deposits from L2
token.transferFrom(msg.sender, address(this), uint256(_extData.extAmount));
totalDeposited += uint256(_extData.extAmount);
require(uint256(_extData.extAmount) <= maximumDepositAmount, "amount is larger than maximumDepositAmount");
}
_transact(_args, _extData);
}
function _transact(Proof memory _args, ExtData memory _extData) internal {
function _transact(Proof memory _args, ExtData memory _extData) internal nonReentrant {
require(isKnownRoot(_args.root), "Invalid merkle root");
for (uint256 i = 0; i < _args.inputNullifiers.length; i++) {
require(!isSpent(_args.inputNullifiers[i]), "Input is already spent");
@ -135,12 +130,13 @@ contract TornadoPool is MerkleTreeWithHistory, IERC20Receiver {
} else {
token.transfer(_extData.recipient, uint256(-_extData.extAmount));
}
totalDeposited -= uint256(-_extData.extAmount);
require(uint256(-_extData.extAmount) >= minimalWithdrawalAmount, "amount is less than minimalWithdrawalAmount"); // prevents ddos attack to Bridge
}
if (_extData.fee > 0) {
token.transfer(_extData.relayer, _extData.fee);
}
lastBalance = token.balanceOf(address(this));
_insert(_args.outputCommitments[0], _args.outputCommitments[1]);
emit NewCommitment(_args.outputCommitments[0], nextIndex - 2, _extData.encryptedOutput1);
emit NewCommitment(_args.outputCommitments[1], nextIndex - 1, _extData.encryptedOutput2);
@ -232,42 +228,17 @@ contract TornadoPool is MerkleTreeWithHistory, IERC20Receiver {
uint256 _amount,
bytes calldata _data
) external override {
(Account memory _account, Proof memory _args, ExtData memory _extData, bytes memory _signature) = abi.decode(
_data,
(Account, Proof, ExtData, bytes)
);
require(isValidSignature(_account, _signature), "Invalid account signature");
(Proof memory _args, ExtData memory _extData) = abi.decode(_data, (Proof, ExtData));
require(_token == token, "provided token is not supported");
require(msg.sender == omniBridge, "only omni bridge");
require(_amount == uint256(_extData.extAmount), "amount from bridge is incorrect");
require(uint256(_extData.extAmount) + totalDeposited >= token.balanceOf(address(this)), "bridge did not send enough tokens");
totalDeposited += uint256(_extData.extAmount);
if (_account.owner != address(0) && _account.publicKey.length > 0) {
_register(_account);
}
require(_amount >= uint256(_extData.extAmount), "amount from bridge is incorrect");
require(token.balanceOf(address(this)) >= uint256(_extData.extAmount) + lastBalance, "bridge did not send enough tokens");
require(uint256(_extData.extAmount) <= maximumDepositAmount, "amount is larger than maximumDepositAmount");
_transact(_args, _extData);
}
function isValidSignature(Account memory _account, bytes memory _signature) public view returns (bool) {
bytes32 hashStruct = keccak256(abi.encode(ACCOUNT_TYPEHASH, _account.owner, keccak256(_account.publicKey)));
bytes32 hash = keccak256(abi.encodePacked(uint16(0x1901), domainSeparator(), hashStruct));
address signer = ECDSA.recover(hash, _signature);
return signer == _account.owner;
}
function domainSeparator() public view returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes("TornadoPool")),
keccak256(bytes("1")), // Version
L1_CHAIN_ID,
address(this)
)
);
function _configureLimits(uint256 _minimalWithdrawalAmount, uint256 _maximumDepositAmount) internal {
minimalWithdrawalAmount = _minimalWithdrawalAmount;
maximumDepositAmount = _maximumDepositAmount;
}
}

View File

@ -1,737 +0,0 @@
/**
*Submitted for verification at BscScan.com on 2021-03-09
*/
pragma solidity 0.7.6;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface IOmnibridge {
function relayTokens(
address _token,
address _receiver,
uint256 _value
) external;
/**
* @dev Initiate the bridge operation for some amount of tokens from msg.sender.
* The user should first call Approve method of the ERC677 token.
* @param token bridged token contract address.
* @param _receiver address that will receive the native tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
* @param _data additional transfer data to be used on the other side.
*/
function relayTokensAndCall(
address token,
address _receiver,
uint256 _value,
bytes memory _data
) external;
}
interface IWETH {
function deposit() external payable;
function withdraw(uint256 _value) external;
function approve(address _to, uint256 _value) external;
}
contract Sacrifice {
constructor(address payable _recipient) payable {
selfdestruct(_recipient);
}
}
/**
* @title AddressHelper
* @dev Helper methods for Address type.
*/
library AddressHelper {
/**
* @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract
* @param _receiver address that will receive the native tokens
* @param _value the amount of native tokens to send
*/
function safeSendValue(address payable _receiver, uint256 _value) internal {
if (!(_receiver).send(_value)) {
new Sacrifice{ value: _value }(_receiver);
}
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @title OwnableModule
* @dev Common functionality for multi-token extension non-upgradeable module.
*/
contract OwnableModule {
address public owner;
/**
* @dev Initializes this contract.
* @param _owner address of the owner that is allowed to perform additional actions on the particular module.
*/
constructor(address _owner) {
owner = _owner;
}
/**
* @dev Throws if sender is not the owner of this contract.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Changes the owner of this contract.
* @param _newOwner address of the new owner.
*/
function transferOwnership(address _newOwner) external onlyOwner {
owner = _newOwner;
}
}
/**
* @title Claimable
* @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations.
*/
contract Claimable {
using SafeERC20 for IERC20;
/**
* Throws if a given address is equal to address(0)
*/
modifier validAddress(address _to) {
require(_to != address(0));
_;
}
/**
* @dev Withdraws the erc20 tokens or native coins from this contract.
* Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()).
* @param _token address of the claimed token or address(0) for native coins.
* @param _to address of the tokens/coins receiver.
*/
function claimValues(address _token, address _to) internal validAddress(_to) {
if (_token == address(0)) {
claimNativeCoins(_to);
} else {
claimErc20Tokens(_token, _to);
}
}
/**
* @dev Internal function for withdrawing all native coins from the contract.
* @param _to address of the coins receiver.
*/
function claimNativeCoins(address _to) internal {
uint256 value = address(this).balance;
AddressHelper.safeSendValue(payable(_to), value);
}
/**
* @dev Internal function for withdrawing all tokens of ssome particular ERC20 contract from this contract.
* @param _token address of the claimed ERC20 token.
* @param _to address of the tokens receiver.
*/
function claimErc20Tokens(address _token, address _to) internal {
IERC20 token = IERC20(_token);
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(_to, balance);
}
}
/**
* @title WETHOmnibridgeRouter
* @dev Omnibridge extension for processing native and wrapped native assets.
* Intended to work with WETH/WBNB/WXDAI tokens, see:
* https://etherscan.io/address/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
* https://bscscan.com/address/0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c
* https://blockscout.com/poa/xdai/address/0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d
*/
contract WETHOmnibridgeRouter is OwnableModule, Claimable {
IOmnibridge public immutable bridge;
IWETH public immutable WETH;
/**
* @dev Initializes this contract.
* @param _bridge address of the HomeOmnibridge/ForeignOmnibridge contract.
* @param _weth address of the WETH token used for wrapping/unwrapping native coins (e.g. WETH/WBNB/WXDAI).
* @param _owner address of the contract owner.
*/
constructor(
IOmnibridge _bridge,
IWETH _weth,
address _owner
) OwnableModule(_owner) {
bridge = _bridge;
WETH = _weth;
_weth.approve(address(_bridge), uint256(-1));
}
/**
* @dev Wraps native assets and relays wrapped ERC20 tokens to the other chain.
* Call msg.sender will receive assets on the other side of the bridge.
*/
function wrapAndRelayTokens() external payable {
wrapAndRelayTokens(msg.sender);
}
/**
* @dev Wraps native assets and relays wrapped ERC20 tokens to the other chain.
* @param _receiver bridged assets receiver on the other side of the bridge.
*/
function wrapAndRelayTokens(address _receiver) public payable {
WETH.deposit{ value: msg.value }();
bridge.relayTokens(address(WETH), _receiver, msg.value);
}
/**
* @dev Wraps native assets and relays wrapped ERC20 tokens to the other chain.
* It also calls receiver on other side with the _data provided.
* @param _receiver bridged assets receiver on the other side of the bridge.
* @param _data data for the call of receiver on other side.
*/
function wrapAndRelayTokens(address _receiver, bytes memory _data) public payable {
WETH.deposit{ value: msg.value }();
bridge.relayTokensAndCall(address(WETH), _receiver, msg.value, _data);
}
/**
* @dev Bridged callback function used for unwrapping received tokens.
* Can only be called by the associated Omnibridge contract.
* @param _token bridged token contract address, should be WETH.
* @param _value amount of bridged/received tokens.
* @param _data extra data passed alongside with relayTokensAndCall on the other side of the bridge.
* Should contain coins receiver address.
*/
function onTokenBridged(
address _token,
uint256 _value,
bytes calldata _data
) external {
require(_token == address(WETH));
require(msg.sender == address(bridge));
require(_data.length == 20);
WETH.withdraw(_value);
address payable receiver;
assembly {
receiver := calldataload(120)
}
AddressHelper.safeSendValue(receiver, _value);
}
/**
* @dev Claims stuck coins/tokens.
* Only contract owner can call this method.
* @param _token address of claimed token contract, address(0) for native coins.
* @param _to address of tokens receiver
*/
function claimTokens(address _token, address _to) external onlyOwner {
claimValues(_token, _to);
}
/**
* @dev Ether receive function.
* Should be only called from the WETH contract when withdrawing native coins. Will revert otherwise.
*/
receive() external payable {
require(msg.sender == address(WETH));
}
}

View File

@ -0,0 +1,49 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
import "omnibridge/contracts/helpers/WETHOmnibridgeRouter.sol";
contract L1Helper is WETHOmnibridgeRouter {
event PublicKey(address indexed owner, bytes key);
struct Account {
address owner;
bytes publicKey;
}
constructor(
IOmnibridge _bridge,
IWETH _weth,
address _owner
) WETHOmnibridgeRouter(_bridge, _weth, _owner) {}
function register(Account memory _account) public {
require(_account.owner == msg.sender, "only owner can be registered");
_register(_account);
}
function _register(Account memory _account) internal {
emit PublicKey(_account.owner, _account.publicKey);
}
/**
* @dev Wraps native assets and relays wrapped ERC20 tokens to the other chain.
* It also calls receiver on other side with the _data provided.
* @param _receiver bridged assets receiver on the other side of the bridge.
* @param _data data for the call of receiver on other side.
* @param _account tornadoPool account data
*/
function wrapAndRelayTokens(
address _receiver,
bytes memory _data,
Account memory _account
) public payable {
WETH.deposit{ value: msg.value }();
bridge.relayTokensAndCall(address(WETH), _receiver, msg.value, _data);
if (_account.owner == msg.sender) {
_register(_account);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// https://docs.tokenbridge.net/amb-bridge/development-of-a-cross-chain-application/how-to-develop-xchain-apps-by-amb#call-a-method-in-another-chain-using-the-amb-bridge
interface IAMB {
@ -11,3 +12,19 @@ interface IAMB {
interface IOmniBridge {
function bridgeContract() external view returns (IAMB);
}
interface IERC6777 is IERC20 {
function transferAndCall(
address,
uint256,
bytes calldata
) external returns (bool);
}
interface IERC20Receiver {
function onTokenBridged(
IERC6777 token,
uint256 value,
bytes calldata data
) external;
}

View File

@ -0,0 +1,8 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
interface IVerifier {
function verifyProof(bytes memory _proof, uint256[7] memory _input) external view returns (bool);
function verifyProof(bytes memory _proof, uint256[21] memory _input) external view returns (bool);
}

View File

@ -16,6 +16,15 @@ const config = {
},
},
},
{
version: '0.7.5',
settings: {
optimizer: {
enabled: true,
runs: 200,
},
},
},
{
version: '0.7.6',
settings: {

View File

@ -22,10 +22,9 @@
"author": "",
"license": "ISC",
"dependencies": {
"@metamask/eth-sig-util": "^4.0.0",
"@nomiclabs/hardhat-ethers": "^2.0.2",
"@nomiclabs/hardhat-waffle": "^2.0.1",
"@openzeppelin/contracts": "git+https://github.com/tornadocash/openzeppelin-contracts.git#6e46aa6946a7f215e7604169ddf46e1aebea850f",
"@openzeppelin": "git+https://github.com/tornadocash/openzeppelin-contracts.git#6e46aa6946a7f215e7604169ddf46e1aebea850f",
"@openzeppelin/contracts-upgradeable": "3.4.2",
"@typechain/ethers-v5": "^7.0.1",
"@typechain/hardhat": "^2.3.0",
@ -37,13 +36,13 @@
"dotenv": "^10.0.0",
"eth-sig-util": "^3.0.1",
"ethereum-waffle": "^3.2.0",
"ethereumjs-util": "^7.1.2",
"ethers": "^5.0.0",
"ffiasm": "^0.1.3",
"ffjavascript": "^0.2.36",
"fixed-merkle-tree": "^0.5.1",
"hardhat": "^2.3.0",
"mocha": "^9.1.0",
"omnibridge": "git+https://github.com/peppersec/omnibridge.git#aa3a970c29752a4da5f3fc7ccf0733783c1acf0b",
"snarkjs": "git+https://github.com/tornadocash/snarkjs.git#616c2d30699f28c8f3ab737b877402ccbb604cfe",
"tmp-promise": "^3.0.2",
"typechain": "^5.1.2"

View File

@ -1,11 +1,13 @@
const { ethers } = require('hardhat')
const MERKLE_TREE_HEIGHT = 23
const { MINIMUM_WITHDRAWAL_AMOUNT, MAXIMUM_DEPOSIT_AMOUNT } = process.env
async function main() {
require('./compileHasher')
const govAddress = '0x03ebd0748aa4d1457cf479cce56309641e0a98f5'
const omniBridge = '0x59447362798334d3485c64D1e4870Fde2DDC0d75'
const amb = '0x162e898bd0aacb578c8d5f8d6ca588c13d2a383f'
const token = '0xCa8d20f3e0144a72C6B5d576e9Bd3Fd8557E2B04' // WBNB
const l1Unwrapper = '0xcf35E84bbA3506BB97cf6fAEFe6cc1A9bd843Fc2' // WBNB -> BNB
const l1ChainId = 56
@ -26,7 +28,7 @@ async function main() {
console.log(`hasher: ${hasher.address}`)
const Pool = await ethers.getContractFactory('TornadoPool')
const tornado = await Pool.deploy(
const tornadoImpl = await Pool.deploy(
verifier2.address,
verifier16.address,
MERKLE_TREE_HEIGHT,
@ -34,20 +36,18 @@ async function main() {
token,
omniBridge,
l1Unwrapper,
)
await tornado.deployed()
console.log(`TornadoPool address: ${tornado.address}`)
const CrossChainUpgradeableProxy = await ethers.getContractFactory('CrossChainUpgradeableProxy')
const proxy = await CrossChainUpgradeableProxy.deploy(
tornado.address,
govAddress,
[],
omniBridge,
l1ChainId,
)
await tornadoImpl.deployed()
console.log(`TornadoPool implementation address: ${tornadoImpl.address}`)
const CrossChainUpgradeableProxy = await ethers.getContractFactory('CrossChainUpgradeableProxy')
const proxy = await CrossChainUpgradeableProxy.deploy(tornadoImpl.address, govAddress, [], amb, l1ChainId)
await proxy.deployed()
console.log(`proxy address: ${proxy.address}`)
const tornadoPool = await Pool.attach(proxy.address)
await tornadoPool.initialize(MINIMUM_WITHDRAWAL_AMOUNT, MAXIMUM_DEPOSIT_AMOUNT)
}
main()

View File

@ -144,7 +144,7 @@ async function transaction({ tornadoPool, ...rest }) {
})
const receipt = await tornadoPool.transact(args, extData, {
gasLimit: 1e6,
gasLimit: 2e6,
})
return await receipt.wait()
}

View File

@ -4,17 +4,15 @@ const { loadFixture } = waffle
const { expect } = require('chai')
const { utils } = ethers
const { toBuffer } = require('ethereumjs-util')
const { signTypedData, SignTypedDataVersion } = require('@metamask/eth-sig-util')
const Utxo = require('../src/utxo')
const { transaction, registerAndTransact, prepareTransaction } = require('../src/index')
const { Keypair } = require('../src/keypair')
const { EIP721Params, encodeDataForBridge } = require('./utils')
const { encodeDataForBridge } = require('./utils')
const MERKLE_TREE_HEIGHT = 5
const L1ChainId = 1
const SENDER_PRIVATE_KEY = '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80'
const l1ChainId = 1
const MINIMUM_WITHDRAWAL_AMOUNT = utils.parseEther(process.env.MINIMUM_WITHDRAWAL_AMOUNT || '0.05')
const MAXIMUM_DEPOSIT_AMOUNT = utils.parseEther(process.env.MAXIMUM_DEPOSIT_AMOUNT || '1')
describe('TornadoPool', function () {
this.timeout(20000)
@ -32,10 +30,10 @@ describe('TornadoPool', function () {
const verifier16 = await deploy('Verifier16')
const hasher = await deploy('Hasher')
const token = await deploy('PermittableToken', 'Wrapped ETH', 'WETH', 18, L1ChainId)
const token = await deploy('PermittableToken', 'Wrapped ETH', 'WETH', 18, l1ChainId)
await token.mint(sender.address, utils.parseEther('10000'))
const amb = await deploy('MockAMB', gov.address, L1ChainId)
const amb = await deploy('MockAMB', gov.address, l1ChainId)
const omniBridge = await deploy('MockOmniBridge', amb.address)
/** @type {TornadoPool} */
@ -48,9 +46,8 @@ describe('TornadoPool', function () {
token.address,
omniBridge.address,
l1Unwrapper.address,
L1ChainId,
gov.address,
)
await tornadoPoolImpl.initialize() // not necessary
const proxy = await deploy(
'CrossChainUpgradeableProxy',
@ -58,12 +55,12 @@ describe('TornadoPool', function () {
gov.address,
[],
amb.address,
L1ChainId,
l1ChainId,
)
const TornadoPool = await ethers.getContractFactory('TornadoPool')
const tornadoPool = TornadoPool.attach(proxy.address)
await tornadoPool.initialize()
await tornadoPool.initialize(MINIMUM_WITHDRAWAL_AMOUNT, MAXIMUM_DEPOSIT_AMOUNT)
await token.approve(tornadoPool.address, utils.parseEther('10000'))
@ -156,7 +153,7 @@ describe('TornadoPool', function () {
const { tornadoPool, token } = await loadFixture(fixture)
// Alice deposits into tornado pool
const aliceDepositAmount = 1e7
const aliceDepositAmount = utils.parseEther('0.1')
const aliceDepositUtxo = new Utxo({ amount: aliceDepositAmount })
await transaction({ tornadoPool, outputs: [aliceDepositUtxo] })
@ -165,10 +162,10 @@ describe('TornadoPool', function () {
const bobAddress = bobKeypair.address() // contains only public key
// Alice sends some funds to Bob
const bobSendAmount = 3e6
const bobSendAmount = utils.parseEther('0.06')
const bobSendUtxo = new Utxo({ amount: bobSendAmount, keypair: Keypair.fromString(bobAddress) })
const aliceChangeUtxo = new Utxo({
amount: aliceDepositAmount - bobSendAmount,
amount: aliceDepositAmount.sub(bobSendAmount),
keypair: aliceDepositUtxo.keypair,
})
await transaction({ tornadoPool, inputs: [aliceDepositUtxo], outputs: [bobSendUtxo, aliceChangeUtxo] })
@ -187,9 +184,9 @@ describe('TornadoPool', function () {
expect(bobReceiveUtxo.amount).to.be.equal(bobSendAmount)
// Bob withdraws a part of his funds from the shielded pool
const bobWithdrawAmount = 2e6
const bobWithdrawAmount = utils.parseEther('0.05')
const bobEthAddress = '0xDeaD00000000000000000000000000000000BEEf'
const bobChangeUtxo = new Utxo({ amount: bobSendAmount - bobWithdrawAmount, keypair: bobKeypair })
const bobChangeUtxo = new Utxo({ amount: bobSendAmount.sub(bobWithdrawAmount), keypair: bobKeypair })
await transaction({
tornadoPool,
inputs: [bobReceiveUtxo],
@ -203,36 +200,19 @@ describe('TornadoPool', function () {
it('should deposit from L1 and withdraw to L1', async function () {
const { tornadoPool, token, omniBridge } = await loadFixture(fixture)
const owner = (await ethers.getSigners())[0].address
const aliceKeypair = new Keypair() // contains private and public keys
// Alice deposits into tornado pool
const aliceDepositAmount = 1e7
const aliceDepositAmount = utils.parseEther('0.07')
const aliceDepositUtxo = new Utxo({ amount: aliceDepositAmount, keypair: aliceKeypair })
const { args, extData } = await prepareTransaction({
tornadoPool,
outputs: [aliceDepositUtxo],
})
const signature = signTypedData({
privateKey: toBuffer(SENDER_PRIVATE_KEY),
data: EIP721Params({
chainId: L1ChainId,
verifyingContract: tornadoPool.address,
owner,
publicKey: aliceKeypair.address(),
}),
version: SignTypedDataVersion.V4,
})
const onTokenBridgedData = encodeDataForBridge({
account: {
owner,
publicKey: aliceKeypair.address(),
},
proof: args,
extData,
signature,
})
const onTokenBridgedTx = await tornadoPool.populateTransaction.onTokenBridged(
@ -245,10 +225,10 @@ describe('TornadoPool', function () {
await omniBridge.execute(tornadoPool.address, onTokenBridgedTx.data)
// withdraws a part of his funds from the shielded pool
const aliceWithdrawAmount = 2e6
const aliceWithdrawAmount = utils.parseEther('0.06')
const recipient = '0xDeaD00000000000000000000000000000000BEEf'
const aliceChangeUtxo = new Utxo({
amount: aliceDepositAmount - aliceWithdrawAmount,
amount: aliceDepositAmount.sub(aliceWithdrawAmount),
keypair: aliceKeypair,
})
await transaction({
@ -267,6 +247,12 @@ describe('TornadoPool', function () {
it('should work with 16 inputs', async function () {
const { tornadoPool } = await loadFixture(fixture)
await transaction({ tornadoPool, inputs: [new Utxo(), new Utxo(), new Utxo()] })
const aliceDepositAmount = utils.parseEther('0.07')
const aliceDepositUtxo = new Utxo({ amount: aliceDepositAmount })
await transaction({
tornadoPool,
inputs: [new Utxo(), new Utxo(), new Utxo()],
outputs: [aliceDepositUtxo],
})
})
})

View File

@ -2,44 +2,14 @@ const { ethers } = require('hardhat')
const abi = new ethers.utils.AbiCoder()
function encodeDataForBridge({ account, proof, extData, signature }) {
function encodeDataForBridge({ proof, extData }) {
return abi.encode(
[
'tuple(address owner,bytes publicKey)',
'tuple(bytes proof,bytes32 root,bytes32[] inputNullifiers,bytes32[2] outputCommitments,uint256 publicAmount,bytes32 extDataHash)',
'tuple(address recipient,int256 extAmount,address relayer,uint256 fee,bytes encryptedOutput1,bytes encryptedOutput2,bool isL1Withdrawal)',
'bytes',
],
[account, proof, extData, signature],
[proof, extData],
)
}
function EIP721Params({ chainId, verifyingContract, owner, publicKey }) {
return {
types: {
EIP712Domain: [
{ name: 'name', type: 'string' },
{ name: 'version', type: 'string' },
{ name: 'chainId', type: 'uint256' },
{ name: 'verifyingContract', type: 'address' },
],
TornadoAccount: [
{ name: 'owner', type: 'address' },
{ name: 'publicKey', type: 'bytes' },
],
},
primaryType: 'TornadoAccount',
domain: {
name: 'TornadoPool',
version: '1',
chainId,
verifyingContract,
},
message: {
owner,
publicKey,
},
}
}
module.exports = { encodeDataForBridge, EIP721Params }
module.exports = { encodeDataForBridge }

1340
yarn.lock

File diff suppressed because it is too large Load Diff