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.
bitcoin create ethereum miner ethereum programming особенности ethereum ethereum обозначение bitcoin example прогнозы bitcoin amazon bitcoin ethereum block фото ethereum ico ethereum
команды bitcoin
bitcoin спекуляция mooning bitcoin bitcoin система bitcoin сбербанк транзакции ethereum cryptocurrency news cms bitcoin korbit bitcoin konvert bitcoin 100 bitcoin bitcoin wmx bitcoin lurk заработать monero cryptocurrency exchanges bitcoin source bitcoin eobot pool bitcoin
pirates bitcoin bitcoin tor trezor bitcoin usdt tether
bitcoin journal 2016 bitcoin ethereum контракт ethereum casino bitcoin ваучер bitcoin location bitcoin knots bitcoin акции bitcoin компьютер куплю ethereum clame bitcoin цена ethereum
bitcoin png капитализация bitcoin bitcoin apple 2016 bitcoin
bitcoin code bitcoin 20
смесители bitcoin bitcoin котировка платформе ethereum pokerstars bitcoin ethereum news ethereum алгоритм monero node tether apk second bitcoin bonus bitcoin bitcoin hash обновление ethereum bitcoin сделки monero free bitcoin калькулятор bitcoin trinity
bitcoin россия land bitcoin bitcoin сколько ethereum io bitcoin приват24 bitcoin hype bitcoin testnet
bitcoin obmen bitcoin loan bitcoin программа ethereum forum ethereum asic
bitcoin future кости bitcoin bitcoin alert simple bitcoin hashrate bitcoin genesis bitcoin ethereum картинки zcash bitcoin raspberry bitcoin reddit ethereum
основатель ethereum importprivkey bitcoin токен ethereum bitcoin registration получить bitcoin fast bitcoin
bitcoin loto cryptocurrency tech аналоги bitcoin prune bitcoin blog bitcoin bitcoin knots кошельки bitcoin значок bitcoin bitcoin crane bitcoin flapper lightning bitcoin moneybox bitcoin Spend Litecoinpirates bitcoin Image for postgadget bitcoin bitcoin заработок capitalization cryptocurrency bitcoin code ethereum pool bitcoin брокеры server bitcoin planet bitcoin bitcoin explorer blocks bitcoin daemon monero ethereum russia bitcoin world bitcoin обозначение 99 bitcoin hashrate bitcoin
txid ethereum bitcoin loan
обменник bitcoin bitcoin обменять bitcoin торги
bounty bitcoin bitcoin apple bitcoin attack bitcoin weekly
обналичивание bitcoin bitcoin nonce bubble bitcoin maps bitcoin bitcoin будущее майнеры monero ethereum nicehash
bitcoin обои bitcoin регистрация neteller bitcoin проекты bitcoin tether coin часы bitcoin The 'Blocks' section briefly addressed the concept of block difficulty. The algorithm that gives meaning to block difficulty is called Proof of Work (PoW).testnet bitcoin
краны monero bitcoin instant monero client bitcoin synchronization bitcoin новости калькулятор bitcoin 22 bitcoin buy ethereum эмиссия ethereum bitcoin hype One week after bitcoin was launched, Hal Finney famously tweeted to the world that he was 'running bitcoin.' In 2011, Ross Ulbricht was alleged to have launched the Silk Road website which ultimately leveraged bitcoin to facilitate online payments for drugs, establishing one of the earliest widespread uses of bitcoin in commerce and undoubtedly playing a material role in the expansion of early adoption and awareness. In 2014, Mt. Gox was hacked and that event may have had the single greatest influence on the advancement and proliferation of bitcoin hardware wallets, as individuals and companies looked to avoid the risks of exchanges and developed ways to more securely hold bitcoin without the use of third-parties. In 2017, after a bitcoin service provider drew the ire of Nicolas Dorier, he set out to build a product that would obsolete that provider and service, spawning one of the most exciting open source projects within bitcoin, BTCPay Server. In 2018, Saifedean Ammous released The Bitcoin Standard, which has accelerated knowledge distribution and contributed to a wave of bitcoin adoption. There are obviously too many random acts to count or acknowledge but it is the randomness inherent to bitcoin and its permissionless nature, lacking in any conscious control, which has allowed it to evolve into the antifragile system it has become. If bitcoin were under the control of any single individual, company or even country, it would have never been viable as a currency because it would have always been dependent on trust and it would have lacked the randomness necessary to create a system capable of dispensing with the need of conscious control. Randomness is irreplicable and the foundation of bitcoin was built on it.bitcoin roll
ultimate bitcoin ethereum сложность nanopool ethereum ethereum frontier stock bitcoin 2x bitcoin баланс bitcoin ethereum serpent bitcoin проект bank bitcoin tp tether
cryptocurrency tech konverter bitcoin bitcoin xyz bitcoin strategy bitcoin strategy game bitcoin обменник bitcoin clame bitcoin что bitcoin bitcoin расшифровка purchase bitcoin ethereum siacoin casino bitcoin explorer ethereum пузырь bitcoin analysis bitcoin
курса ethereum 2016 bitcoin konvert bitcoin bitcoin weekly bitcoin tools payeer bitcoin rates bitcoin bitcoin unlimited usb tether bitcoin эфир bitcoin hourly платформы ethereum bitcoin home bitcoin чат bitcoin market coingecko ethereum monero майнер ethereum russia ethereum os sec bitcoin ios bitcoin
bitcoin рейтинг ethereum stratum сети bitcoin bitcoin автор wallet cryptocurrency 5 bitcoin bitcoin ubuntu ethereum видеокарты bitcoin растет pool bitcoin exchange bitcoin polkadot cadaver bitcoin location
ethereum курсы bitcoin machine ninjatrader bitcoin bitcoin проблемы обновление ethereum minergate ethereum bitcoin 0 скрипты bitcoin 2x bitcoin bitcoin plus500 bitcoin 50 minergate ethereum bye bitcoin bistler bitcoin казино ethereum bitcoin scam вложения bitcoin bitcoin genesis bitcoin forex lottery bitcoin bitcoin net bitcoin safe ethereum supernova bonus bitcoin
курс tether краны monero air bitcoin monero amd bitcoin jp wired tether maps bitcoin 123 bitcoin bitcoin котировки maps bitcoin сервисы bitcoin bitcoin bio bitcoin rig bitcoin machine bitcoin xt bitcoin халява bitcoin авито exchange bitcoin
фонд ethereum исходники bitcoin ethereum com ethereum кошелька epay bitcoin курсы bitcoin bitcoin лопнет 1080 ethereum ethereum stats multiplier bitcoin mikrotik bitcoin bitcoin conference автосборщик bitcoin korbit bitcoin Bitcoin Forksмайнеры monero tether yota бумажник bitcoin bitcoin biz ava bitcoin bitcoin auto bitcoin mmgp
bitcoin bitrix monero spelunker dance bitcoin
генераторы bitcoin android tether ethereum transactions ethereum habrahabr ethereum debian bitcoin кран bitcoin jp bitcoin grafik box bitcoin робот bitcoin bitcoin майнить bitcoin переводчик simple bitcoin
получить bitcoin работа bitcoin
Ключевое слово ethereum io ethereum usd bitcoin buy bitcoin вконтакте webmoney bitcoin cryptocurrency tech bitcoin collector reverse tether проверить bitcoin проверка bitcoin
bitcoin two карты bitcoin tether js hashrate bitcoin vizit bitcoin курс ethereum bitcoin матрица space bitcoin bitcoin pools курса ethereum криптовалюту monero bitcoin rub decred cryptocurrency ethereum studio ethereum ubuntu bitcoin pps checker bitcoin mixer bitcoin ethereum api сборщик bitcoin bitcoin бонусы ethereum core monero spelunker bitcoin bonus ethereum browser simplewallet monero bitcoin future и bitcoin bitcoin grafik теханализ bitcoin alien bitcoin bitcoin информация trezor ethereum config bitcoin bitcoin etherium tether chvrches bitcoin faucets эмиссия bitcoin code bitcoin
bitcoin goldman accepts bitcoin bitcoin puzzle bitcoin s bitcoin world cryptocurrency calculator
stock bitcoin bitcoin подтверждение прогноз ethereum bitcoin видеокарты bitcoin etherium bitcoin world ico monero bitcoin in bitcoin neteller bitcoin капча bitcoin yen bitcoin suisse фермы bitcoin
bitcoin value bitcoin ферма
accepts bitcoin bitcoin status Supply-chain managementbitcoin pos blocks bitcoin ethereum news cryptocurrency dash
cryptocurrency arbitrage bitcoin книга bitcoin plus
bitcoin компьютер
monero wallet bitcoin funding monero rur monero купить bitcoin balance bitcoin nvidia 0 bitcoin js bitcoin bitcoin сигналы основатель bitcoin зебра bitcoin bitcoin клиент tradingview bitcoin bitcoin chain
обменник bitcoin
carding bitcoin bitcoin bloomberg bitcoin перевод
bitcoin сокращение эфир ethereum отзывы ethereum bitcoin redex bitcoin balance статистика ethereum bitcoin c bitcoin скрипт trust bitcoin dwarfpool monero bitcoin jp my ethereum bitcoin clicker clame bitcoin bitcoin скрипт bitcoin purchase claim bitcoin coingecko ethereum торрент bitcoin best cryptocurrency bitcoin it bitcoin redex
ethereum developer 2x bitcoin wirex bitcoin bitcoin linux мерчант bitcoin ethereum stratum blocks bitcoin trezor ethereum bitcoin talk 600 bitcoin bitcoin wmz bitcoin 4000 биржи monero
bitcoin 2020 серфинг bitcoin заработать monero
exchanges bitcoin bitcoin anonymous bitcoin alert bitcoin logo кошелек bitcoin ethereum cryptocurrency
cold bitcoin polkadot store top bitcoin ethereum siacoin
зебра bitcoin 99 bitcoin
bitcoin hunter fast bitcoin bitcoin film sec bitcoin all bitcoin обвал ethereum raiden ethereum panda bitcoin bitcoin media bitcoin price bitcoin обналичить tp tether fox bitcoin bitcoin keywords click bitcoin пулы ethereum xapo bitcoin king bitcoin erc20 ethereum king bitcoin dog bitcoin сделки bitcoin 2016 bitcoin bitcoin gadget get bitcoin
фри bitcoin
bitcoin открыть bitcoin google пулы bitcoin app bitcoin bitcoin japan куплю bitcoin coin bitcoin уязвимости bitcoin bitcoin казино monero новости сеть ethereum cryptocurrency ico
bitcoin alert продам ethereum blogspot bitcoin регистрация bitcoin ico monero facebook bitcoin bitcoin markets bitcoin зарабатывать bitcoin bitrix
bitcoin click usdt tether bitcoin china ethereum rotator bitcoin генератор lootool bitcoin bitcoin super bitcoin is bitcoin luxury bitcoin compare
bitcoin перевести
free ethereum bitcoin банк китай bitcoin Blockchain is a combination of many technological breakthroughs that date back several decades. Bitcoin was the first real application of a blockchain technology in the form of a peer-to-peer electronic cash system.High hash rate - You can think of hash rate as the processing power of the hardware.bitcoin ne bitcoin луна
россия bitcoin форумы bitcoin отдам bitcoin bitcoin capitalization all bitcoin antminer bitcoin bitcoin unlimited cryptocurrency logo widget bitcoin token bitcoin bitcoin live bitcoin poloniex ethereum os ethereum miners bitcoin математика bitcoin заработок blogspot bitcoin bitcoin сервисы wiki bitcoin инструкция bitcoin monero продать
bitcoin анализ bitcoin биржа bitcoin wordpress matrix bitcoin bitcoin statistics