Basic Concept of EVM
DeFiHackLabs Web3 Security Club Sharing · 35:02
Galois explains how the Ethereum Virtual Machine executes smart contracts, moving from accounts and world state to bytecode, the stack, memory, storage and gas. Code examples connect Solidity to deployment and execution, including storage layout and mappings. Basic Solidity and programming knowledge help. The account model shown predates EIP-7702, which now allows EOAs to delegate code execution.
Speakers
Topics
From DeFiHackLabs Web3 Security Club Sharing, published by DeFiHackLabs; community: DeFiHackLabs.
Transcript
[Music] [Applause] [Music] hi everyone I'm Gallos today I'm going to talk about the basic concept of evm and how Pico is formed and executed uh here's my Twitter handle if you have any question just DM me or if you I want to dis have a discussion with me or if I say anything wrong about the evm just come to correct me first I want to thank Sun for inviting me to make such a presentation um I think it's really important to me to make some
presentation and do some writings uh because it helped me reconstruct my knowledge I think it's really important for technical guys and researcher to do some technical writings and in some way it will help us to reconstruct our knowledge and help us reink and help us die deeper into our technical stack and I think practice make perfect theory is theory if you do not put practice into it uh if you want to dive deeper into the evbm I think
participating some CTF games is a good way to start uh in eano I met you know the CTF monster and he said he said one of his teammate was reviewing the puzzles even when he was eating um I think all the CTF player do share one thing in common that is that soling the puzzle might take some time or even take more time than you thought but in my opinion when I saw some puzzle all the all the puzzle I make would become well fire and if you want to go further I
think you should um learn some defy hacks we produced from sunx sunx defy hack Labs rap hold which is one of my favorite app hold on GitHub okay let's start here's a picture of the evm overview uh the evm is part of the ethereum that handles smart contract deployment and execution simple value transfer transaction from the from one EA to another vaa uh ea uh doesn't uh do not do not need to involve it
um but everything else would involve the stay update computed by the evm the job of the evm to update the ethereum state by Computing valid State transition as a result of smart contract code execution as defined by the etherum protocol this exp leads to the description of etherum as a transaction based State machine which reflect the fact that external actors initiate the state transis by transition by creating accepting and ordering
transaction we can see from the picture at the top level we we have the etherum world state uh the worst St is um mapping of etherum adresses uh which has 160 bits value to uh is account it's called account at the lower level uh we can see we can see um each we can see at the lower level each if ad just represent account compromising a
balance um a balance and the balance sted that as the number of weight owned by the account and the non and announce is representing the number of transactions successfully send from this account if is an EA or the number of contract created if it's a contract account the account storage which is a permanent the account storage which is a permanent permanent data stored only used by the smart contract and uh accounts program code
um uh if only a is if only the account is a smart contract account the account program code will be used um and EA and EA would will always have no code and empty storage will tou uh let's go deeper into it slide EA is controlled by a private key EA cannot contain evm code as we can see from the
picture um there are two kinds of accounts one is called uh EA and the other and the other one is called contract account um the two main differences between EA and contract account is about the EA the EA La start from Euro and the contract accounts start from one we can uh we can see from the picture that the EA public here drive
from uh drive from the private key um and after the Haring meod we get the 100 60 bits of address but um when it comes to the contract account here it comes to the contract account it depends on the create contract method it has two method to create a cont to create a contract uh but in this picture I just show you create method but uh the other the other uh the new one to create the contract is called create to uh when using Create method to create a contract the contract address is decided
by the Senter address and nons when using Create two method to create cont to create the contract is decided by the Senter address and in inal inal when a transaction result in smart contract execution and evm is instant shate instantiate with all the information require in relation to current BL being created and the specific transaction being processed in particular the event program code uh is
loaded with some code of uh with with a code of contract account being called the program the program content is set to zero and the storage is low from the contract contract account storage and the memory is set to all zeros and all the block and environment variable are set a key variable is the gas supplied for the execution which is set to the amount of gas paid for PID by the sender at the start of the transaction as Co execution progress the
gas supplies is reduced according to the gas cost of the operation execute if at any point the gas surprise is reduced to zero and an OG exception recall our of guas uh is immediately holds and the trans and the transaction is abandoned no change to the ethereum state apply is something like transaction in some relation relation database like myo and progress ql um except for the senders
nors being included and uh and um and the either State going down to pay the the uh to pay the Box resource use to execute code to the holding holding Point uh at this point you can think the evm running and a sand on a Sandbox copy of the eum will state with with this sandbox version being discard completely if execution cannot complete uh for whatever reason however if execution does completely successful then the real world state is update to match uh the
sandbox version including any change to the call contract storage data like uh the picture show or any new contract created or any either balance was initiated right transaction will change the wor St when you send a transaction uh it will change your world State like account state will update if you do some ERC 20 transfer it will update
balance okay let's go deeper to the evm storage laid out stage variables of contract are stored in the storage in a compact way um we can see this on the picture so uh multiple values sometimes use some we use the same storage LW slot uh except for the dynamic dynamically SI arrays and mappings data is
store continuously item after item starting from the first state variables which is store in slot zero we can see it from the picture and for each varibles a size of uh a size in Bas is determined according to its type multiple continuously continuous item needs less than uh 32 by a pack into a single storage clock if possible according to following rules the first item in a storage store is store is store low order Alli and value
type are used only as many buys uh are necessary to store them if a value type do not fit the remaining part of a storage code is store in the next storage slot uh struct and array data always start a new always start a new slot and the item app tightly according to this route item following struct or are data always start a new story slot for contract and inher inh inhance
the ordering of State variable is determined by the C free l linearized order of contract starting from the most Bas World contract if allow abide the B rules to stay AR from different contracts to share uh the same storage SL uh I'll check it let's check it the holwood contract we can see that the B xx1 xx2 xx3 xx4 are occupied occupi uh and xx5 they do share uh the same slot
because um all of them all of them are less uh the sum the sum value of them are less than 32 bu but but on uh in slot four we can see that the U in 128 is you is use because it's go beyond uh it's go beyond the Buy 32 to a 42 bu it go beyond 42 bu if we adding adding it into slot free so it occupi the new slot um let's let's go to check the Rob
ethereum contract storage layout on ethereum okay let's go let's open the link oh uh sorry I might take some time to okay okay we we can see we can um we can see we can see the storage laid out we can see from the picture that the decimal occupy the slot uh 0x2 and the decimal of of
etherum is 18 um I want to say that most of the time we don't use decim mod to use as a storage variable but uh W either is a special case so so I will I will I will show you how to check the St storage using the Alchemy or anchor RPC RPC to check the storage
okay I guess it might take some time because of my network is so good switch to Json RPC and use this ma e gas storage add and we can and we can copy the copy the W either contract and then paste it into the possible argument and quy the ZX2 always stru
and put and send the request we can see that the result of of the decimal of the 0x2 storage is 0x 12 uh which is 0 x 12 in X is is the number of 18 in decimal so we verify we verify the store um the the SL 0x2 is is correct um let's go to see the storage slot of some mapping structure mapping
structure uh we will go to quiry the euro X3 we can see from the result is a little bit different because um the result of the balance mapping is zero zero that's quite common because mapping mapping structure uh do occupy the slot but is has a zero zero value the real
calculation of the key value is using some some some other method to Cal to calculate the key card 2 256 of Haring Haring result from uh to get the to get the real storage start uh I will I will I will illustrate it I will illustrate it by writing some code uh let's uh please just wait
uh due to the unpredictable side mappings mappings and dynamic side type are not uh types cannot be stored in between the state variables proceeding and following them instead they are considered to occupi only 42 byes with regards to the rules about and the element they contain the stor start at the different stor that is computed using a key Cat 200 56 h I will show it later um assume that the storage of the mapping mapping or array ends up being
slot position P after applying the story layout for dynamic array the stock the slock store the number of the element in the area is the length of the arrays um for mapping the slot stay empty as is showed as it showed we can check it from the ra e contract at the result of the ZX free uh storage is zero um the slot stay is empty but you still need to ensure even there are two mappings next to each other and the content ends up with different storage Loc
let's check the slot detail by writing some code to verify our our algorithm uh please just wait me to open from the code okay okay let's get started to how to c I will show you how to calculate the storage slot when it comes to the mapping structure of a contract uh as we can see from the
previous anchor an anchor response is uh the St uh the storage slot of mapping structure will be zero and uh we we didn't want to know some key some keys like some uh some eoa account balance or some contract account balance uh in this w w ethereum contract balance method so we need to calculate the slot first the rule uh I'll just tell you the how to calculate the the storage lock directly um is uh it's about the address you want to
calculate that uh it would be encoded by encoded in you uh 42 by like you in 256 and what's next is the storage uh storage slot uh in this uh in this contract uh if you want to quy the balance off the slot will be 0x3 and then we can calculate the slot uh storage slot of the Z zero address uh let's let's check let's check the result of
attacking P like like here okay the result will be 0x 3 6 1 7 3 1 blah blah and let's go to verify it from the on the evm storage website uh let's click the balance button yes as as key as we can see so as we can see the slot would be exactly the same as uh exactly the same
as the result we calculated uh when we want to quiry the balance of Euro address we just go to put the slot into the anchor anchor and RC and use the E get storage ad meod and then we can get the zero address balance okay let's continue let's go further gas
um gas is a ethereum unit for measuring or for the computational uh and storage resource required to perform some action on the ethereum blockchain in contract to bitcoin uh the in Bitcoin the transaction fee only takes into the account the size of the transaction in kilobytes uh etherum must account for every every computation step performed by the transaction and smart contract code execution each operation performed by a transaction or contract cost uh a fix number of guest some example from
the zero paper um it's like adding two numbers free gas calculating the Key C 256 har cost 30 30 gas and six G for each 256 pie of data being har sending a transaction basically cost to uh 21,000 gas uh there's a famous famous attack called tangle investor uh we you can go deeper to check the details on EIP 608 uh this uh I can I can tell you something about the I can tell you some
overview about the attack the the attack is about the mismatch of res by the half C name called tangling RTO is it was relative to the gas cause uh when it comes to uh related to the gas CA I will know I will not go further but you can check it on the EIP uh 208 208 uh here is uh the basic the basic computer unit uh I think is about the basic computer unit of evm the evm is a simple stack based architecture uh as we can see from the
picture it consists of program Conta and some guess available uh variables stack and memory and storage to help them to calculate some unit uh the stack is uh 250 56 bits uh right read or right unit uh we can calculate or do some operation uh we do some operation on the stack and the max length of the stack the max depth of the stack is one uh 1,
1,2 24 elements here is how here is the evm execution models first we when we put some input buy code on the uh transactions call data uh and when it uh it would when the evm execute model gets the evm uh gets the instruction or the operation uh by passing the input data it will uh it will it will pass it into some operation and if we call some uh if you call some contract it will fetch the
evm codee uh from the storage contract storage and then it will uh maintain the program counter to calculate uh calculate some uh what step we are going what step we are going um which line of um which Step what step we are going and which exe uh which operation we are heading for and as the as the as the transaction post progress uh we will use some step uh we use some calculation uh by the help of a stack memory and storage to do some
computation computation uh that's a simple simp simple simple execution model but uh it deals with lots of State change uh okay let's go uh go to the next chapter um uh here's uh how I will show you how B Cod is formed uh most of the time uh B code is consist of three parts of this uh inque code run onetime code Constructor parameters uh but in my opinion this is a little bit single side
uh the Run Ty code is calculated by the evm and the returning value of evm when sending a transaction of contract creation is exactly the bik code of the runtime bike uh is exactly the Run type by code of the contract okay I will illustrate how the difference between constant and immutable in solidity um when it comes to uh when it comes to immutable I will I will only write some codes about immutable I think it's better uh if you uh it's better to leave to leave the constant one to you to
verify your ideas or your Discovery so let's get start uh I'm too lazy to create a new to create some new directory so so it's about some I write some code about it [Music] Constructor some variable like you in 256 public number and is mle yeah in Constructor we set the
number as zero then we comp it use and then we comply it use Forge build let's check the result let's check the result uh of this contract compile result of this contract yeah is your loock Json I will cop I'll copy the bite code and pass it to the evm code website which is one of my favorite website to and then click the
Run uh I'll go straight I'll go we can see we can see the return value return value we can see from the return value that the buy code is a little little bit different from the complying result we can see we can see the the prefix the prefix is exactly the same but when it comes to the number uh when it comes to this when it comes to uh the preix is the prefix of the bico is exactly the same except this this one
this this one uh in in compis result is zero but in return value is is two um this is because this is because we the comparing result is just compared result U it consists of two parts and in the in the code um we can see from the previous key not that uh the laid out of the bu code they need code is where we put some parameters or we put the parameters uh from behind uh behind the runtime code is that the precompile pre-compiled result we did
not we did not take the take the take the set the number into two uh this step into consideration so the result it it will be slightly different from the result as is complied so the constant one I will leave it to you guys to verify your proof uh here's my presentation reference I think is pretty helpful when debuging some uh pule or soling some puzzle and it's really helpful if you want to go deeper into the evbm
that's all my presentation thank you