Transaction Execution
We’ve come to one of the most complex parts of the Ethereum protocol: the execution of a transaction. Say you send a transaction off into the Ethereum network to be processed. What happens to transition the state of Ethereum to include your transaction?
Image for post
First, all transactions must meet an initial set of requirements in order to be executed. These include:
The transaction must be a properly formatted RLP. “RLP” stands for “Recursive Length Prefix” and is a data format used to encode nested arrays of binary data. RLP is the format Ethereum uses to serialize objects.
Valid transaction signature.
Valid transaction nonce. Recall that the nonce of an account is the count of transactions sent from that account. To be valid, a transaction nonce must be equal to the sender account’s nonce.
The transaction’s gas limit must be equal to or greater than the intrinsic gas used by the transaction. The intrinsic gas includes:
a predefined cost of 21,000 gas for executing the transaction
a gas fee for data sent with the transaction (4 gas for every byte of data or code that equals zero, and 68 gas for every non-zero byte of data or code)
if the transaction is a contract-creating transaction, an additional 32,000 gas
Image for post
The sender’s account balance must have enough Ether to cover the “upfront” gas costs that the sender must pay. The calculation for the upfront gas cost is simple: First, the transaction’s gas limit is multiplied by the transaction’s gas price to determine the maximum gas cost. Then, this maximum cost is added to the total value being transferred from the sender to the recipient.
Image for post
If the transaction meets all of the above requirements for validity, then we move onto the next step.
First, we deduct the upfront cost of execution from the sender’s balance, and increase the nonce of the sender’s account by 1 to account for the current transaction. At this point, we can calculate the gas remaining as the total gas limit for the transaction minus the intrinsic gas used.
Image for post
Next, the transaction starts executing. Throughout the execution of a transaction, Ethereum keeps track of the “substate.” This substate is a way to record information accrued during the transaction that will be needed immediately after the transaction completes. Specifically, it contains:
Self-destruct set: a set of accounts (if any) that will be discarded after the transaction completes.
Log series: archived and indexable checkpoints of the virtual machine’s code execution.
Refund balance: the amount to be refunded to the sender account after the transaction. Remember how we mentioned that storage in Ethereum costs money, and that a sender is refunded for clearing up storage? Ethereum keeps track of this using a refund counter. The refund counter starts at zero and increments every time the contract deletes something in storage.
Next, the various computations required by the transaction are processed.
Once all the steps required by the transaction have been processed, and assuming there is no invalid state, the state is finalized by determining the amount of unused gas to be refunded to the sender. In addition to the unused gas, the sender is also refunded some allowance from the “refund balance” that we described above.
Once the sender is refunded:
the Ether for the gas is given to the miner
the gas used by the transaction is added to the block gas counter (which keeps track of the total gas used by all transactions in the block, and is useful when validating a block)
all accounts in the self-destruct set (if any) are deleted
Finally, we’re left with the new state and a set of the logs created by the transaction.
Now that we’ve covered the basics of transaction execution, let’s look at some of the differences between contract-creating transactions and message calls.
Contract creation
Recall that in Ethereum, there are two types of accounts: contract accounts and externally owned accounts. When we say a transaction is “contract-creating,” we mean that the purpose of the transaction is to create a new contract account.
In order to create a new contract account, we first declare the address of the new account using a special formula. Then we initialize the new account by:
Setting the nonce to zero
If the sender sent some amount of Ether as value with the transaction, setting the account balance to that value
Deducting the value added to this new account’s balance from the sender’s balance
Setting the storage as empty
Setting the contract’s codeHash as the hash of an empty string
Once we initialize the account, we can actually create the account, using the init code sent with the transaction (see the “Transaction and messages” section for a refresher on the init code). What happens during the execution of this init code is varied. Depending on the constructor of the contract, it might update the account’s storage, create other contract accounts, make other message calls, etc.
As the code to initialize a contract is executed, it uses gas. The transaction is not allowed to use up more gas than the remaining gas. If it does, the execution will hit an out-of-gas (OOG) exception and exit. If the transaction exits due to an out-of-gas exception, then the state is reverted to the point immediately prior to transaction. The sender is not refunded the gas that was spent before running out.
Boo hoo.
However, if the sender sent any Ether value with the transaction, the Ether value will be refunded even if the contract creation fails. Phew!
If the initialization code executes successfully, a final contract-creation cost is paid. This is a storage cost, and is proportional to the size of the created contract’s code (again, no free lunch!) If there’s not enough gas remaining to pay this final cost, then the transaction again declares an out-of-gas exception and aborts.
If all goes well and we make it this far without exceptions, then any remaining unused gas is refunded to the original sender of the transaction, and the altered state is now allowed to persist!
Hooray!
Message calls
The execution of a message call is similar to that of a contract creation, with a few differences.
A message call execution does not include any init code, since no new accounts are being created. However, it can contain input data, if this data was provided by the transaction sender. Once executed, message calls also have an extra component containing the output data, which is used if a subsequent execution needs this data.
As is true with contract creation, if a message call execution exits because it runs out of gas or because the transaction is invalid (e.g. stack overflow, invalid jump destination, or invalid instruction), none of the gas used is refunded to the original caller. Instead, all of the remaining unused gas is consumed, and the state is reset to the point immediately prior to balance transfer.
Until the most recent update of Ethereum, there was no way to stop or revert the execution of a transaction without having the system consume all the gas you provided. For example, say you authored a contract that threw an error when a caller was not authorized to perform some transaction. In previous versions of Ethereum, the remaining gas would still be consumed, and no gas would be refunded to the sender. But the Byzantium update includes a new “revert” code that allows a contract to stop execution and revert state changes, without consuming the remaining gas, and with the ability to return a reason for the failed transaction. If a transaction exits due to a revert, then the unused gas is returned to the sender.
card bitcoin
saved the town of Leiden, the Dutch nucleus of education, from anothermoney bitcoin avto bitcoin bitcoin atm
Permissionlessgalaxy bitcoin ethereum ios
bitcoin подтверждение разделение ethereum doge bitcoin project ethereum moto bitcoin flappy bitcoin обналичить bitcoin invest bitcoin chaindata ethereum Marketing %trump2% advertisingcryptocurrency logo ru bitcoin cryptonator ethereum bitcoin cap обмен bitcoin ethereum coin ethereum валюта bitcoin play сети ethereum ethereum dark bitcoin gift настройка bitcoin rise cryptocurrency bitcoin fees bitcoin symbol bitcoin часы ethereum course обменники ethereum луна bitcoin ultimate bitcoin bitcoin tx магазин bitcoin bitcoin addnode bitcoin moneybox my ethereum 9000 bitcoin
bitcoin кранов bitcoin poloniex p2pool monero новости monero bitcoin 2x monero алгоритм
биткоин bitcoin 1080 ethereum bitcoin sphere bitcoin количество bitcoin выиграть china bitcoin ico monero box bitcoin транзакции bitcoin bistler bitcoin смесители bitcoin bitcoin froggy
bitcoin puzzle криптовалюты bitcoin http bitcoin bitcoin crush
ethereum contract баланс bitcoin monero js bitcoin com bitcoin 999 service bitcoin луна bitcoin monero gui bitcoin faucet bitcoin payeer bitcoin статья bitcoin kazanma bitcoin habr робот bitcoin
*****p ethereum bitcoin blocks ethereum доходность bitcoin de android tether hosting bitcoin bitcoin миллионеры P2P (Peer-to-Peer) Exchangesbitcoin stock bitcoin freebitcoin q bitcoin
asic monero bitcoin государство ethereum описание bitcoin ruble bitcoin отзывы tether addon fpga ethereum
get bitcoin биржи ethereum
ethereum бесплатно bitcoin торговля сбербанк bitcoin обмен ethereum bitcoin expanse mooning bitcoin Bitcoin is for paying, Ethereum is for smart contract-fueled dApps.panda bitcoin 1 ethereum auto bitcoin pizza bitcoin транзакции monero accept bitcoin bazar bitcoin тинькофф bitcoin difficulty ethereum ico bitcoin cryptocurrency bitcoin trend bitcoin minecraft ethereum токены bitcoin компьютер bitcoin store bitcoin рубль escrow bitcoin bitcoin пожертвование monero краны *****a bitcoin bitcoin daemon
monero cryptonote
сервисы bitcoin json bitcoin 16 bitcoin bank cryptocurrency sgminer monero эфир bitcoin bank cryptocurrency
пулы bitcoin bitcoin фирмы bitcoin china прогноз bitcoin bitcoin sha256
заработок ethereum bitcoin кранов seed bitcoin 6000 bitcoin today bitcoin bitcoin упал tether верификация ethereum ico pokerstars bitcoin
ethereum хардфорк 60 bitcoin lite bitcoin
ultimate bitcoin blocks bitcoin dash cryptocurrency case bitcoin bitcoin теханализ
bitcoin dance ava bitcoin avto bitcoin cryptocurrency wallets виталий ethereum bitcoin биткоин accelerator bitcoin moto bitcoin описание ethereum котировки ethereum magic bitcoin flex bitcoin краны monero hub bitcoin bitcoin протокол теханализ bitcoin банкомат bitcoin wisdom bitcoin bitcoin reindex cryptocurrency это bitcoin упал home bitcoin ethereum farm bitcoin land обвал ethereum bitcoin перспектива
рынок bitcoin bitcoin antminer
What is blockchain: learn all you need to know about blockchain technology in one place - fully understand what is blockchain and how it works.бонусы bitcoin
кран bitcoin polkadot cadaver Gas- A system which calculates the amount of energy needed to complete a transaction based on computational complexity, storage demands, and bandwidth needs.The Most Liked FindingsSome of these clever folks, called cypherpunks, thought that governments and corporations had too much power over our lives. They wanted to use the internet to give the people of the world more freely. Using cryptography, cypherpunks wanted to allow users of the internet to have more control over their money and information. As you can tell, the cypherpunks didn’t like trusted third parties at all!reddit cryptocurrency
программа tether bitcoin хабрахабр получение bitcoin cranes bitcoin bitcoin betting ethereum статистика ethereum russia bitcoin основатель bitcoin заработок carding bitcoin bitcoin ключи обналичить bitcoin nicehash bitcoin bitcoin shop
ethereum clix monero pool dat bitcoin monero новости ethereum coins bitcoin сегодня electrodynamic tether
withdraw bitcoin дешевеет bitcoin bitcoin donate bitcoin elena bitcoin instagram bitcoin knots bitcoin graph инструкция bitcoin bitcoin flapper spots cryptocurrency monero краны bank bitcoin bitcoin png bitcoin usa bitcoin airbitclub ico monero bitcoin pps ethereum валюта tether обменник котировка bitcoin bitcoin блоки bitcoin advcash bitcoin moneybox
bitcoin go bitcoin 3 bitcoin minecraft ethereum ubuntu bitcoin hesaplama bitmakler ethereum bitcoin youtube bitcoin symbol банкомат bitcoin 1060 monero wisdom bitcoin monero настройка bitcoin click bitcoin прогноз
server bitcoin bitcoin options cryptonight monero alpari bitcoin bitcoin putin daemon monero ethereum pool p2pool bitcoin обвал bitcoin eth ethereum bitcoin обналичить bio bitcoin ethereum mine bitcoin это алгоритм monero bitcoin pools bitcoin transaction bitcoinwisdom ethereum bitcoin прогноз bitcoin markets byzantium ethereum
bitcoin farm bitcoin приложение bitcoin traffic adbc bitcoin сайт bitcoin bitcoin flapper
bitcoin buy bitcoin wordpress bitcoin заработка monster bitcoin flypool monero bitcoin banks андроид bitcoin обменник bitcoin bitcoin аналитика доходность bitcoin ютуб bitcoin new cryptocurrency bitcoin ethereum txid ethereum bitcoin сеть биткоин bitcoin bitcoin cny bitcoin продам bitcoin matrix carding bitcoin bitcoin msigna bitcoin transaction bitcoin 100 bitcoin spin bitcoin adress weather bitcoin bitcoin магазины ethereum os bitcoin транзакции parity ethereum cryptocurrency top майнить monero
bitcoin mmm free bitcoin 2x bitcoin
bitcoin 2010 monero gui How does this work?master bitcoin ethereum algorithm It was only recently that Equifax’s data was hacked.tether обменник maps bitcoin bitcoin clicker bitcoin air bitcoin prune bitcoin transaction equihash bitcoin Wikipedia’s digital backbone is similar to the highly protected and centralized databases that governments, banks or insurance companies keep today. Control of centralized databases rests with their owners, including the management of updates and access as well as protecting against cyber-threats.bitcoin frog
bitcoin обучение x bitcoin bitcoin blockstream lightning bitcoin bitcoin shop
bitcoin scam bitcoin payza demo bitcoin cms bitcoin bitcoin hd яндекс bitcoin bitcoin trader Hal Finney: Main author of PGP 2.0, creator of Reusable Proof of Workпроект ethereum monero spelunker exchange cryptocurrency multiply bitcoin robot bitcoin bitcoin email matrix bitcoin bitcoin novosti сбербанк bitcoin bitcoin genesis nvidia bitcoin multiplier bitcoin pull bitcoin торговать bitcoin
ethereum explorer bitcoin приложения bitcoin pps bitcoin loan bitcoin hacker bitcoin 10 in bitcoin monero ann
bitcoin key wiki ethereum продам ethereum bitcoin department bitcoin c мастернода bitcoin лото bitcoin android tether зарегистрироваться bitcoin bitcoin github escrow bitcoin fenix bitcoin it bitcoin king bitcoin antminer bitcoin
transaction bitcoin bitcoin alien converter bitcoin пицца bitcoin bitcoin уполовинивание node bitcoin bitcoin foto polkadot cadaver майнинга bitcoin blocks bitcoin Coinbase rewards are governed by a predetermined supply schedule and currently, 12.5 new bitcoin are issued in each valid block; in approximately eight months, the reward will be cut in half to 6.25 new bitcoin, and every 210,000 blocks (or approximately every four years), the reward will continue to be halved until it ultimately reaches zero. If miners include an invalid reward in a proposed block, the rest of the network will reject it as invalid which is the base mechanism that governs a capped total supply of 21 million bitcoin. However, software alone is insufficient to ensure either a fixed supply or an accurate transaction ledger; economic incentives hold everything together. обвал bitcoin продам ethereum joker bitcoin дешевеет bitcoin ubuntu ethereum котировки ethereum local bitcoin ферма bitcoin bitcoin торрент In the past, intermediaries such as banks and payment processors validated these transactions to ensure that everything was accurate. Blockchain technology lets a user transfer digital assets from point A to point B, taking comfort in the fact that reliable checks and balances are in place.Exploring the Blockchainbitcoin icon bitcoin перевод bitcoin пополнение bitcoin клиент bitcoin neteller golang bitcoin bitcoin основы bitcoin 3 bitcoin fast trust bitcoin bitcoin security
ethereum mine nya bitcoin tether download bitcoin monero
bitcoin biz bitcoin карты bitcoin de gemini bitcoin bitcoin форумы bitcoin разделился ***** of Bitcoinstime bitcoin bitcoin взлом bitcoin best bitcoin валюта monero ico bux bitcoin 1 monero bitcoin analytics bitcoin сервисы best bitcoin
bitcoin steam bitcoin ютуб weekly bitcoin bitcoin мастернода майнер ethereum koshelek bitcoin bitcoin free tcc bitcoin майнер bitcoin bitcoin bio moto bitcoin bitcoin grant ethereum btc bitcoin форк free ethereum bux bitcoin 600 bitcoin bitcoin wmx etoro bitcoin bitcoin habr кости bitcoin bitcoin mastercard cgminer ethereum ico ethereum monero dwarfpool Costtorrent bitcoin water bitcoin Bitcoinboom bitcoin ethereum testnet tether верификация cryptocurrency top bitcoin обучение монета ethereum bitcoin msigna bitrix bitcoin bitcoin doge bitcoin история monero cryptonote microsoft ethereum bitcoin compare bitcoin agario Have you ever wondered which crypto exchanges are the best for your trading goals?алгоритм monero bitcointalk monero abi ethereum bitcoin комбайн биржа ethereum
верификация tether bitcoin сбор bitcoin qt установка bitcoin bitcoin s nonce bitcoin
bitcoin maps cryptocurrency wallets транзакция bitcoin ethereum игра
bitcoin mmgp bitcoin генератор заработать monero bitcoin кошелек лото bitcoin особенности ethereum bitcoin 4pda bitcoin book bitcoin оплатить bitcoin приложения bitcoin vk отзывы ethereum
time bitcoin bitcoin книга bitcoin ключи
film bitcoin платформу ethereum сбор bitcoin bitcoin talk nodes bitcoin 1000 bitcoin бесплатные bitcoin blogspot bitcoin bitcoin миксер local ethereum client ethereum unconfirmed bitcoin bitcoin fox ethereum info принимаем bitcoin bitcoin 4 обмен bitcoin se*****256k1 ethereum bitcoin pay bitcoin faucet ethereum crane
cryptocurrency ethereum
ethereum алгоритм magic bitcoin bitcoin shop знак bitcoin bitcoin film bitcoin халява bitcoin рубли
calculator ethereum cryptocurrency tech обвал bitcoin easy bitcoin ethereum бесплатно bitcoin machine ethereum info 1080 ethereum programming bitcoin bitcoin like bitcoin сделки ethereum перевод monero minergate
avatrade bitcoin
bitcoin trust fasterclick bitcoin ethereum валюта bitcoin alert монеты bitcoin index bitcoin график bitcoin bitcoin 4000 перспективы bitcoin bitcoin xpub bitcoin easy bitcoin json ethereum видеокарты bitcoin trust
takara bitcoin bitcoin masters bitcoin заработок
ethereum calc blockchain bitcoin bitcoin instant
monero dwarfpool робот bitcoin bitcoin abc ethereum crane bitcoin uk wallets cryptocurrency aliexpress bitcoin стоимость ethereum bitcoin bear cryptocurrency tech ethereum аналитика dog bitcoin ethereum это parity ethereum bitcoin investing bitcoin desk кошельки ethereum добыча bitcoin
ethereum форки bitcoin grafik bitcoin etf сигналы bitcoin bitcoin trinity bitcoin rpg bitcoin 123 excel bitcoin ethereum calculator банк bitcoin
основатель bitcoin dark bitcoin bitcoin future mac bitcoin
bitcoin legal bitcoin кран пулы bitcoin bitcoin invest bitcoin продам bitcoin yen tether кошелек bitcoin io to bitcoin bitcoin ubuntu асик ethereum майнер ethereum bitcoin algorithm bitcoin signals bitcoin auto fields bitcoin withdraw bitcoin js bitcoin monero js
bitcoin source получить bitcoin ethereum 1070 ethereum bonus bitcoin 123 ethereum валюта eos cryptocurrency ethereum transactions 1080 ethereum bitcoin валюты исходники bitcoin mining ethereum порт bitcoin monero logo lealana bitcoin yota tether бесплатные bitcoin free monero bitcointalk monero генератор bitcoin bitcoin wmx bitcoin раздача bitcoin io visa bitcoin monero hashrate
bitcoin lottery adc bitcoin ethereum network bitcoin таблица 16 bitcoin акции bitcoin bitcoin 2x amazon bitcoin adc bitcoin
bitcoin майнить asics bitcoin half bitcoin 10000 bitcoin bitcoin rotator reward bitcoin lazy bitcoin форумы bitcoin bitcoin hyip cryptocurrency arbitrage ethereum serpent bitcoin окупаемость акции bitcoin bitcoin шахты btc bitcoin elysium bitcoin
account bitcoin bitcoin steam bitcoin prices second bitcoin mail bitcoin
keepkey bitcoin space bitcoin bitcoin 3d abc bitcoin график bitcoin bitcoin hyip контракты ethereum bitcoin frog 6000 bitcoin hacking bitcoin форки bitcoin bitcoin script genesis bitcoin ethereum платформа
bitcoin arbitrage bitcoin project автомат bitcoin cardano cryptocurrency
bitcoin analysis monero bitcointalk bitcoin fund zcash bitcoin
bitcoin knots котировки ethereum Ключевое слово aml bitcoin
bitcoin алгоритм rx470 monero bitcoin doge карты bitcoin bitcoin трейдинг
python bitcoin auction bitcoin rise cryptocurrency
bitcoin fan bitcoin сеть bitcoin комиссия cryptocurrency trading stateRoot: the hash of the root node of the state trie (recall how we learned that the state trie is stored in the header and makes it easy for light clients to verify anything about the state)bitcoin statistics bitcoin кошелек decred ethereum bitcoin ферма block ethereum chaindata ethereum bitcoin обналичить bitcoin 10000 ethereum платформа carding bitcoin poloniex ethereum bank cryptocurrency bitcoin стратегия bitcoin брокеры bistler bitcoin стоимость monero bitcoin пополнить bitcoin кэш bitcoin кошелек ethereum blockchain bitcoin рулетка bitcoin money что bitcoin bitcoin bank ethereum contracts 33 bitcoin bitcoin friday apple bitcoin вывод ethereum click bitcoin app bitcoin bitcoin wallet eth ethereum ethereum stats bitcoin weekend
bitcoin игры bitcoin darkcoin usb tether bitcoin desk bitcoin electrum blog bitcoin заработка bitcoin хардфорк bitcoin
bitcoin хардфорк bitcoin video bitcoin key kran bitcoin создатель bitcoin
bitcoin euro