Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sepolia deposit adapter implementation #821

Merged
merged 41 commits into from
Feb 21, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
e21b86a
Sepolia deposit contract (interface for tests)
vp4242 Feb 7, 2024
876a3b0
Add basic test for Sepolia deposit
vp4242 Feb 7, 2024
7e1d8e2
Put simple deployment test
vp4242 Feb 7, 2024
bf3540a
Basic deposit adapter implementation
vp4242 Feb 7, 2024
3e89caf
Some experiments over adapter tests
vp4242 Feb 8, 2024
d5474b3
Simplify adapter
vp4242 Feb 8, 2024
6bb847f
Split tests, fix style
vp4242 Feb 8, 2024
3eeafd1
Improve contract readability
vp4242 Feb 8, 2024
52df1f9
Remove Sepolia deposit contract code, change all interaction to inter…
vp4242 Feb 12, 2024
287e868
Fix warnings
vp4242 Feb 12, 2024
04d6b7f
Add immutable
vp4242 Feb 13, 2024
cabc5cd
Add Ownable mix to Deposit
vp4242 Feb 13, 2024
2b905b2
Implement drain Bepolia logic and send back ether to contract owner
vp4242 Feb 13, 2024
53861a2
Remove general drain func as it now send eth to owner automatically
vp4242 Feb 13, 2024
da8ea29
Improve adapter logic
vp4242 Feb 14, 2024
c60e04a
Improve tests
vp4242 Feb 14, 2024
90f4b03
Add owner logging
vp4242 Feb 14, 2024
f13cb41
Add auto drain to deposit() and tests around
vp4242 Feb 14, 2024
3ff2df1
Fix contract warning
vp4242 Feb 14, 2024
f122422
Fix deployment test
vp4242 Feb 14, 2024
3180ee5
Remove cruft
vp4242 Feb 14, 2024
b5193c1
More readable name
vp4242 Feb 15, 2024
d14eb54
Fix naming
vp4242 Feb 15, 2024
97db353
Fix test
vp4242 Feb 15, 2024
b752379
Skip test for local node testing
vp4242 Feb 15, 2024
80d018d
Provide address for drain
vp4242 Feb 15, 2024
04d4267
Comment on how run Sepolia-specific tests
vp4242 Feb 15, 2024
fb73385
Add chain id
vp4242 Feb 15, 2024
a5793ec
Fix contract
vp4242 Feb 15, 2024
15320be
Combine tests and fix them after renamings
vp4242 Feb 15, 2024
b334ea4
Update contracts/0.8.9/SepoliaDepositAdapter.sol
vp4242 Feb 20, 2024
401b886
Update contracts/0.8.9/SepoliaDepositAdapter.sol
vp4242 Feb 20, 2024
312d708
Update test/0.8.9/sepolia-deposit-adapter.test.js
vp4242 Feb 20, 2024
e82e9b3
Extract interfaces and improve adapter contract
vp4242 Feb 20, 2024
c916979
Fix tests for contract changes
vp4242 Feb 20, 2024
e3a089e
Suppress warnings
vp4242 Feb 20, 2024
c9d0887
Details on while Adapter is required
vp4242 Feb 20, 2024
a3e2982
Add DepositEvent and checks for it
vp4242 Feb 20, 2024
a802e43
Fix comment
vp4242 Feb 20, 2024
7536ba8
fix: update storage layout action
TheDZhon Feb 20, 2024
2480651
Emit event on Bepolia recover
vp4242 Feb 21, 2024
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
221 changes: 221 additions & 0 deletions contracts/0.6.11/sepolia_deposit_contract.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
// SPDX-License-Identifier: Apache-2.0
folkyatina marked this conversation as resolved.
Show resolved Hide resolved
// solhint-disable-next-line lido/fixed-compiler-version
pragma solidity ^0.6.8;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";


// ======================================= WARNING ========================================
//
// WARNING: This is an UNOFFICAL TESTNET-ONLY deposit contract HACK.
// *No security garantuees, at all*. Merely used for random permissioned (not verified) testnets.
//
// ================================================================================================




// This interface is designed to be compatible with the Vyper version.
/// @notice This is the Ethereum 2.0 deposit contract interface.
/// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs
interface IDepositContract {
/// @notice A processed deposit event.
event DepositEvent(
bytes pubkey,
bytes withdrawal_credentials,
bytes amount,
bytes signature,
bytes index
);

/// @notice Submit a Phase 0 DepositData object.
/// @param pubkey A BLS12-381 public key.
/// @param withdrawal_credentials Commitment to a public key for withdrawals.
/// @param signature A BLS12-381 signature.
/// @param deposit_data_root The SHA-256 hash of the SSZ-encoded DepositData object.
/// Used as a protection against malformed input.
function deposit(
bytes calldata pubkey,
bytes calldata withdrawal_credentials,
bytes calldata signature,
bytes32 deposit_data_root
) external payable;

/// @notice Query the current deposit root hash.
/// @return The deposit root hash.
function get_deposit_root() external view returns (bytes32);

/// @notice Query the current deposit count.
/// @return The deposit count encoded as a little endian 64-bit number.
function get_deposit_count() external view returns (bytes memory);
}

// Based on official specification in https://eips.ethereum.org/EIPS/eip-165
interface ERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceId` and
/// `interfaceId` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceId) external pure returns (bool);
}

// This is a rewrite of the Vyper Eth2.0 deposit contract in Solidity.
// It tries to stay as close as possible to the original source code.
/// @notice This is the Ethereum 2.0 deposit contract interface.
/// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs
contract SepoliaDepositContract is IDepositContract, ERC165, IERC20, ERC20, ERC20Burnable {
uint constant GWEI = 1e9;

uint constant DEPOSIT_CONTRACT_TREE_DEPTH = 32;
// NOTE: this also ensures `deposit_count` will fit into 64-bits
uint constant MAX_DEPOSIT_COUNT = 2**DEPOSIT_CONTRACT_TREE_DEPTH - 1;

bytes32[DEPOSIT_CONTRACT_TREE_DEPTH] branch;
uint256 deposit_count;

bytes32[DEPOSIT_CONTRACT_TREE_DEPTH] zero_hashes;

address payable creator;
Fixed Show fixed Hide fixed

constructor () public ERC20("Testnet deposit token", "TDEP") {
// Compute hashes in empty sparse Merkle tree
for (uint height = 0; height < DEPOSIT_CONTRACT_TREE_DEPTH - 1; height++)
zero_hashes[height + 1] = sha256(abi.encodePacked(zero_hashes[height], zero_hashes[height]));
// No decimals: 1 token = 1 deposit.
_setupDecimals(0);
// Mint 1 million deposit tokens for the contract creator.
_mint(msg.sender, 1e9);
creator = msg.sender;
}

// Public function to send all available funds back to contract creator
function drain() public {
creator.transfer(address(this).balance);
}
Fixed Show fixed Hide fixed

function adminBurn(address account, uint256 amount) public {
require(msg.sender == creator);
_burn(account, amount);
}

/// @notice Query the current deposit root hash.
/// @return The deposit root hash.
function get_deposit_root() override external view returns (bytes32) {
bytes32 node;
Fixed Show fixed Hide fixed
uint size = deposit_count;
for (uint height = 0; height < DEPOSIT_CONTRACT_TREE_DEPTH; height++) {
if ((size & 1) == 1)
node = sha256(abi.encodePacked(branch[height], node));
else
node = sha256(abi.encodePacked(node, zero_hashes[height]));
size /= 2;
}
return sha256(abi.encodePacked(
node,
to_little_endian_64(uint64(deposit_count)),
bytes24(0)
));
}

/// @notice Query the current deposit count.
/// @return The deposit count encoded as a little endian 64-bit number.
function get_deposit_count() override external view returns (bytes memory) {
return to_little_endian_64(uint64(deposit_count));
}

/// @notice Submit a Phase 0 DepositData object.
/// @param pubkey A BLS12-381 public key.
/// @param withdrawal_credentials Commitment to a public key for withdrawals.
/// @param signature A BLS12-381 signature.
/// @param deposit_data_root The SHA-256 hash of the SSZ-encoded DepositData object.
/// Used as a protection against malformed input.
function deposit(
bytes calldata pubkey,
bytes calldata withdrawal_credentials,
bytes calldata signature,
bytes32 deposit_data_root
) override external payable {
// Extended ABI length checks since dynamic types are used.
require(pubkey.length == 48, "DepositContract: invalid pubkey length");
require(withdrawal_credentials.length == 32, "DepositContract: invalid withdrawal_credentials length");
require(signature.length == 96, "DepositContract: invalid signature length");

// Send back any goerli value they try to send us (some deposit tooling does not allow to change the amount)
msg.sender.transfer(msg.value);

// WARNING: disabled amount check.
// // Check deposit amount
// require(msg.value >= 1 ether, "DepositContract: deposit value too low");
// require(msg.value % GWEI == 0, "DepositContract: deposit value not multiple of gwei");
// uint deposit_amount = msg.value / GWEI;
// require(deposit_amount <= type(uint64).max, "DepositContract: deposit value too high");

// INSTEAD, burn 1 token (also checks the token balance)
_burn(msg.sender, 1);

// Emit `DepositEvent` log
// 32 ETH (in GWEI) hardcoded
bytes memory amount = to_little_endian_64(uint64(32e9));
emit DepositEvent(
pubkey,
withdrawal_credentials,
amount,
signature,
to_little_endian_64(uint64(deposit_count))
);

// Compute deposit data root (`DepositData` hash tree root)
bytes32 pubkey_root = sha256(abi.encodePacked(pubkey, bytes16(0)));
bytes32 signature_root = sha256(abi.encodePacked(
sha256(abi.encodePacked(signature[:64])),
sha256(abi.encodePacked(signature[64:], bytes32(0)))
));
bytes32 node = sha256(abi.encodePacked(
sha256(abi.encodePacked(pubkey_root, withdrawal_credentials)),
sha256(abi.encodePacked(amount, bytes24(0), signature_root))
));

// Verify computed and expected deposit data roots match
require(node == deposit_data_root, "DepositContract: reconstructed DepositData does not match supplied deposit_data_root");

// Avoid overflowing the Merkle tree (and prevent edge case in computing `branch`)
require(deposit_count < MAX_DEPOSIT_COUNT, "DepositContract: merkle tree full");

// Add deposit data root to Merkle tree (update a single `branch` node)
deposit_count += 1;
uint size = deposit_count;
for (uint height = 0; height < DEPOSIT_CONTRACT_TREE_DEPTH; height++) {
if ((size & 1) == 1) {
branch[height] = node;
return;
}
node = sha256(abi.encodePacked(branch[height], node));
size /= 2;
}
// As the loop should always end prematurely with the `return` statement,
// this code should be unreachable. We assert `false` just to be safe.
assert(false);
}

function supportsInterface(bytes4 interfaceId) override external pure returns (bool) {
return interfaceId == type(ERC165).interfaceId || interfaceId == type(IDepositContract).interfaceId || interfaceId == type(IERC20).interfaceId;
}

function to_little_endian_64(uint64 value) internal pure returns (bytes memory ret) {
ret = new bytes(8);
bytes8 bytesValue = bytes8(value);
// Byteswapping during copying to bytes.
ret[0] = bytesValue[7];
ret[1] = bytesValue[6];
ret[2] = bytesValue[5];
ret[3] = bytesValue[4];
ret[4] = bytesValue[3];
ret[5] = bytesValue[2];
ret[6] = bytesValue[1];
ret[7] = bytesValue[0];
}
}
41 changes: 36 additions & 5 deletions contracts/0.8.9/SepoliaDepositAdapter.sol
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,54 @@
pragma solidity 0.8.9;


contract SepoliaDepositAdapter {
abstract contract SepoliaDepositInterface {

uint public constant TEST_VALUE = 16;
address public immutable depositContract;
function get_deposit_root() external virtual view returns (bytes32);

function get_deposit_count() external virtual view returns (bytes memory);

function deposit(
bytes calldata pubkey,
bytes calldata withdrawal_credentials,
bytes calldata signature,
bytes32 deposit_data_root
) external payable {
}
) external virtual payable;

}

contract SepoliaDepositAdapter {

uint public constant VERSION = 2;
address public immutable depositContract;
address payable public creator;
Fixed Show fixed Hide fixed
github-advanced-security[bot] marked this conversation as resolved.
Fixed
Show resolved Hide resolved

constructor(address _deposit_contract) {
TheDZhon marked this conversation as resolved.
Show resolved Hide resolved
depositContract = _deposit_contract;
creator = payable(msg.sender);
}

function get_deposit_root() external view returns (bytes32) {
SepoliaDepositInterface origContract = SepoliaDepositInterface(depositContract);
return origContract.get_deposit_root();
}

function get_deposit_count() external view returns (bytes memory) {
SepoliaDepositInterface origContract = SepoliaDepositInterface(depositContract);
return origContract.get_deposit_count();
}

function deposit(
bytes calldata pubkey,
bytes calldata withdrawal_credentials,
bytes calldata signature,
bytes32 deposit_data_root
) external payable {
SepoliaDepositInterface origContract = SepoliaDepositInterface(depositContract);
origContract.deposit(pubkey, withdrawal_credentials, signature, deposit_data_root);
}

// Public function to send all available funds back to contract creator
function drain() public {
creator.transfer(address(this).balance);
}
Fixed Show fixed Hide fixed
}
27 changes: 27 additions & 0 deletions test/0.8.9/sepolia-deployment.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const { artifacts, contract, ethers } = require('hardhat')

const { EvmSnapshot } = require('../helpers/blockchain')

const SepoliaDepositAdapter = artifacts.require('SepoliaDepositAdapter')

contract('SepoliaDepositAdapter', ([deployer]) => {
let depositAdapter
let snapshot

before('deploy lido with dao', async () => {
depositAdapter = await SepoliaDepositAdapter.new(deployer, { from: deployer })
const dna = await depositAdapter.TEST_VALUE()
console.log(dna)

snapshot = new EvmSnapshot(ethers.provider)
await snapshot.make()
})

afterEach(async () => {
await snapshot.rollback()
})

describe('SepoliaDepositAdapter Logic', () => {
it(`state after deployment`, async () => {})
folkyatina marked this conversation as resolved.
Show resolved Hide resolved
})
})
52 changes: 52 additions & 0 deletions test/0.8.9/sepolia-deposit-adapter.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const { artifacts, contract, ethers } = require('hardhat')
const { assert } = require('../helpers/assert')

const { EvmSnapshot } = require('../helpers/blockchain')

const SepoliaDepositAdapter = artifacts.require('SepoliaDepositAdapter')

contract('SepoliaDepositAdapter impl', ([deployer]) => {
let depositAdapter
let snapshot
// const sepoliaDepositAdapterContract = '0x899e45316FaA439200b36c7d7733192530e3DfC0'
const sepoliaDepositContract = '0x7f02C3E3c98b133055B8B348B2Ac625669Ed295D'
const bepoliaTokenHolder = '0x388Ea662EF2c223eC0B047D41Bf3c0f362142ad5'
const EOAddress = '0x6885E36BFcb68CB383DfE90023a462C03BCB2AE5'

before('deploy lido with dao', async () => {
// depositAdapter = await SepoliaDepositAdapter.at(sepoliaDepositAdapterContract)

depositAdapter = await SepoliaDepositAdapter.new(deployer, { from: deployer })
const testVersion = await depositAdapter.VERSION()
assert.equals(testVersion, 2)

const bepoliaToken = await ethers.getContractAt('SepoliaDepositContract', sepoliaDepositContract)
const bepoliaStartBalance = await bepoliaToken.balanceOf(bepoliaTokenHolder)

const impersonatedSigner = await ethers.getImpersonatedSigner(bepoliaTokenHolder)
await impersonatedSigner.sendTransaction({ to: EOAddress, value: ethers.utils.parseEther('2.0') })

const bepoliaTokensToTransfer = 1
bepoliaToken.connect(impersonatedSigner).transfer(EOAddress, bepoliaTokensToTransfer)

const bepoliaOwnTokens = await bepoliaToken.balanceOf(EOAddress)
assert.equals(bepoliaOwnTokens, bepoliaTokensToTransfer)

const bepoliaEndBalance = await bepoliaToken.balanceOf(bepoliaTokenHolder)
assert.equals(bepoliaEndBalance, bepoliaStartBalance - bepoliaTokensToTransfer)
console.log(bepoliaEndBalance)

depositAdapter.connect(impersonatedSigner).deposit(bepoliaTokensToTransfer)

snapshot = new EvmSnapshot(ethers.provider)
await snapshot.make()
})

afterEach(async () => {
await snapshot.rollback()
})

describe('SepoliaDepositAdapter Logic', () => {
TheDZhon marked this conversation as resolved.
Show resolved Hide resolved
TheDZhon marked this conversation as resolved.
Show resolved Hide resolved
it(`state after deployment`, async () => {})
})
})
Loading