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

DepositableDelegateProxy: optimize for EIP-1884 #551

Merged
merged 9 commits into from
Sep 3, 2019
Merged
Show file tree
Hide file tree
Changes from 5 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
36 changes: 28 additions & 8 deletions contracts/common/DepositableDelegateProxy.sol
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,34 @@ contract DepositableDelegateProxy is DepositableStorage, DelegateProxy {
event ProxyDeposit(address sender, uint256 value);

function () external payable {
// send / transfer
if (gasleft() < FWD_GAS_LIMIT) {
require(msg.value > 0 && msg.data.length == 0);
require(isDepositable());
emit ProxyDeposit(msg.sender, msg.value);
} else { // all calls except for send or transfer
address target = implementation();
delegatedFwd(target, msg.data);
uint256 forwardGasThreshold = FWD_GAS_LIMIT;
bytes32 isDepositablePosition = DEPOSITABLE_POSITION;

// Optimized assembly implementation to prevent EIP-1884 from breaking deposits, reference code in Solidity:
// https://github.com/aragon/aragonOS/blob/v4.2.1/contracts/common/DepositableDelegateProxy.sol#L10-L20
assembly {
// Continue only if the gas left is lower than the threshold for forwarding to the implementation code,
// otherwise continue outside of the assembly block.
if lt(gas, forwardGasThreshold) {
// Only accept the deposit and emit an event if all of the following are true:
// the proxy accepts deposits (isDepositable), msg.data.length == 0, and msg.value > 0
if and(and(sload(isDepositablePosition), iszero(calldatasize)), gt(callvalue, 0)) {
let logData := mload(0x40) // free memory pointer
mstore(logData, caller) // add 'msg.sender' to the log data (first event param)
mstore(add(logData, 0x20), callvalue) // add 'msg.value' to the log data (second event param)

// Emit an event with one topic to identify the event: keccak256('ProxyDeposit(address,uint256)') = 0x15ee...dee1
log1(logData, 0x40, 0x15eeaa57c7bd188c1388020bcadc2c436ec60d647d36ef5b9eb3c742217ddee1)
izqui marked this conversation as resolved.
Show resolved Hide resolved

stop() // Stop. Exits execution context
}

// If any of above checks failed, revert the execution (if ETH was sent, it is returned to the sender)
revert(0, 0)
}
}

address target = implementation();
delegatedFwd(target, msg.data);
}
}
8 changes: 8 additions & 0 deletions contracts/test/helpers/EthSender.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
pragma solidity 0.4.24;


contract EthSender {
function sendEth(address to) external payable {
to.transfer(msg.value);
}
}
17 changes: 17 additions & 0 deletions contracts/test/helpers/ProxyTarget.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
pragma solidity 0.4.24;

contract ProxyTarget {
event Pong();

function ping() external {
emit Pong();
}
}

contract ProxyTargetWithFallback is ProxyTarget {
event ReceivedEth();

function () external payable {
emit ReceivedEth();
}
}
24 changes: 24 additions & 0 deletions contracts/test/mocks/apps/DepositableDelegateProxyMock.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
pragma solidity 0.4.24;

import "../../../common/DepositableDelegateProxy.sol";


contract DepositableDelegateProxyMock is DepositableDelegateProxy {
address private implementationMock;

function enableDepositsOnMock() external {
setDepositable(true);
}

function setImplementationOnMock(address _implementationMock) external {
implementationMock = _implementationMock;
}

function implementation() public view returns (address) {
return implementationMock;
}

function proxyType() public pure returns (uint256 proxyTypeId) {
return UPGRADEABLE;
}
}
2 changes: 1 addition & 1 deletion test/contracts/apps/recovery_to_vault.js
Original file line number Diff line number Diff line change
Expand Up @@ -338,4 +338,4 @@ contract('Recovery to vault', ([permissionsRoot]) => {
await recoverEth({ target: kernel, vault })
})
})
})
})
173 changes: 173 additions & 0 deletions test/contracts/common/depositable_delegate_proxy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
const { toChecksumAddress } = require('web3-utils')
const { assertAmountOfEvents, assertEvent } = require('../../helpers/assertEvent')(web3)
const { decodeEventsOfType } = require('../../helpers/decodeEvent')
const { assertRevert, assertOutOfGas } = require('../../helpers/assertThrow')
const { getBalance } = require('../../helpers/web3')

// Mocks
const DepositableDelegateProxyMock = artifacts.require('DepositableDelegateProxyMock')
const EthSender = artifacts.require('EthSender')
const ProxyTarget = artifacts.require('ProxyTarget')
const ProxyTargetWithFallback = artifacts.require('ProxyTargetWithFallback')

const TX_BASE_GAS = 21000
const SEND_ETH_GAS = TX_BASE_GAS + 9999 // 10k gas is the threshold for depositing
izqui marked this conversation as resolved.
Show resolved Hide resolved
const FALLBACK_SETUP_GAS = 100 // rough estimation of how much gas it spends before executing the fallback code
const SOLIDITY_TRANSFER_GAS = 2300
const ISTANBUL_SLOAD_GAS_INCREASE = 600

contract('DepositableDelegateProxy', ([ sender ]) => {
let ethSender, proxy, proxyTargetBase, proxyTargetWithFallbackBase

// Initial setup
before(async () => {
ethSender = await EthSender.new()
proxyTargetBase = await ProxyTarget.new()
izqui marked this conversation as resolved.
Show resolved Hide resolved
proxyTargetWithFallbackBase = await ProxyTargetWithFallback.new()
})

beforeEach(async () => {
proxy = await DepositableDelegateProxyMock.new()
})

const itForwardsToImplementationIfGasIsOverThreshold = () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, this one is not guaranteeing anything related to the gas amount, I'd call it itForwardsToImplementation simply.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's implicitly guaranteeing it as by not setting the gas explicitly, it uses the gas limit value in truffle.js, but I think it is a good idea to make it explicit for these tests

let target

beforeEach(() => {
target = ProxyTargetWithFallback.at(proxy.address)
})

context('when implementation address is set', () => {
const itSuccessfullyForwardsCall = () => {
it('forwards call with data', async () => {
const receipt = await target.ping()
assertAmountOfEvents(receipt, 'Pong')
})
}

context('when implementation has a fallback', () => {
beforeEach(async () => {
await proxy.setImplementationOnMock(proxyTargetWithFallbackBase.address)
})

itSuccessfullyForwardsCall()

it('can receive ETH', async () => {
const receipt = await target.sendTransaction({ value: 1, gas: SEND_ETH_GAS + FALLBACK_SETUP_GAS })
assertAmountOfEvents(receipt, 'ReceivedEth')
})
})

context('when implementation doesn\'t have a fallback', () => {
beforeEach(async () => {
await proxy.setImplementationOnMock(proxyTargetBase.address)
})

itSuccessfullyForwardsCall()

it('reverts when sending ETH', async () => {
await assertRevert(target.sendTransaction({ value: 1 }))
})
})
})

context('when implementation address is not set', () => {
it('reverts when a function is called', async () => {
await assertRevert(target.ping())
})

it('reverts when sending ETH', async () => {
await assertRevert(target.sendTransaction({ value: 1 }))
})
})
}

const itRevertsOnInvalidDeposits = () => {
it('reverts when call has data', async () => {
await assertRevert(proxy.sendTransaction({ value: 1, data: '0x01', gas: SEND_ETH_GAS }))
})

it('reverts when call sends 0 value', async () => {
await assertRevert(proxy.sendTransaction({ value: 0, gas: SEND_ETH_GAS }))
})
}

context('when proxy is set as depositable', () => {
beforeEach(async () => {
await proxy.enableDepositsOnMock()
})

context('when call gas is below the forwarding threshold', () => {
const value = 100

const sendEthToProxy = async ({ value, gas, shouldOOG }) => {
izqui marked this conversation as resolved.
Show resolved Hide resolved
const initialBalance = await getBalance(proxy.address)

const sendEthAction = () => proxy.sendTransaction({ from: sender, gas, value })

if (shouldOOG) {
await assertOutOfGas(sendEthAction())
assert.equal((await getBalance(proxy.address)).valueOf(), initialBalance, 'Target balance should be the same as before')
} else {
const { receipt, logs } = await sendEthAction()

assert.equal((await getBalance(proxy.address)).valueOf(), initialBalance.plus(value), 'Target balance should be correct')
assertAmountOfEvents({ logs }, 'ProxyDeposit')
assertEvent({ logs }, 'ProxyDeposit', { sender, value })

return receipt
}
}

it('can receive ETH (Constantinople)', async () => {
const { gasUsed } = await sendEthToProxy({ value, gas: SEND_ETH_GAS })
console.log('Used gas:', gasUsed - TX_BASE_GAS)
})

// TODO: Remove when the targetted EVM has been upgraded to Istanbul (EIP-1884)
it('can receive ETH (Istanbul, EIP-1884)', async () => {
const gas = TX_BASE_GAS + SOLIDITY_TRANSFER_GAS - ISTANBUL_SLOAD_GAS_INCREASE
const { gasUsed } = await sendEthToProxy({ value, gas })
const gasUsedIstanbul = gasUsed - TX_BASE_GAS + ISTANBUL_SLOAD_GAS_INCREASE
console.log('Used gas (Istanbul):', gasUsedIstanbul)

assert.isBelow(gasUsedIstanbul, 2300, 'Gas cost under Istanbul cannot be above 2300 gas')
})

// TODO: Remove when the targetted EVM has been upgraded to Istanbul (EIP-1884)
it('cannot receive ETH if sent with a small amount of gas', async () => {
// deposit cannot be done with this amount of gas
const gas = TX_BASE_GAS + SOLIDITY_TRANSFER_GAS - ISTANBUL_SLOAD_GAS_INCREASE - 250
await sendEthToProxy({ shouldOOG: true, value, gas })
})

it('can receive ETH from contract', async () => {
const { tx } = await ethSender.sendEth(proxy.address, { value })
const receipt = await web3.eth.getTransactionReceipt(tx)
const logs = decodeEventsOfType(receipt, DepositableDelegateProxyMock.abi, 'ProxyDeposit')
assertAmountOfEvents({ logs }, 'ProxyDeposit')
assertEvent({ logs }, 'ProxyDeposit', { sender: toChecksumAddress(ethSender.address), value })
})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: perhaps it looks nice to wrap these into Constantinople and Istambul contexts

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is not possible to perform a call with value from a contract with less than 2300 gas, as calls that transfer value get a 2300 gas stipend (at the protocol level).

I was doing some debugging and saw that receiver.transfer() sets the gas for the call to 0 if the value sent is greater than 0, and if it is 0 the compiler sets the gas for the call to 2300 gas (which is hardcoded in the bytecode). This results in the contract that receives a .transfer always having at least 2300 gas regardless of whether it is coming from the protocol stipend or from the call being sent with 2300 gas.

Even if you do a 'low-level call' (receiver.call.value(v).gas(g)()) if v is greater than 0, the actual gas that the receiver will be called with is 2300 + g. This makes it impossible to test the Istanbul scenario in which we'd need receiver to be called with 1700 gas.


itRevertsOnInvalidDeposits()
})

context('when call gas is over forwarding threshold', () => {
itForwardsToImplementationIfGasIsOverThreshold()
})
})

context('when proxy is not set as depositable', () => {
context('when call gas is below the forwarding threshold', () => {
it('reverts when depositing ETH', async () => {
await assertRevert(proxy.sendTransaction({ value: 1, gas: SEND_ETH_GAS }))
})

itRevertsOnInvalidDeposits()
})

context('when call gas is over forwarding threshold', () => {
itForwardsToImplementationIfGasIsOverThreshold()
})
})
})
4 changes: 4 additions & 0 deletions test/helpers/assertThrow.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ module.exports = {
return assertThrows(blockOrPromise, 'invalid opcode')
},

async assertOutOfGas(blockOrPromise) {
return assertThrows(blockOrPromise, 'out of gas')
},

async assertRevert(blockOrPromise, reason) {
const error = await assertThrows(blockOrPromise, 'revert', reason)
const errorPrefix = `${THROW_ERROR_PREFIX} revert`
Expand Down