Module-V
Ethereum
Ethereum clients and releases
• Various Ethereum clients have been developed using different
languages and currently most popular are go-Ethereum and parity.
• go-Ethereum was developed using Golang, whereas parity was built
using Rust.
• There are other clients available too, but usually, the go-Ethereum
client known as geth is sufficient for all purposes.
• Mist is a user-friendly Graphical User Interface (GUI) wallet that runs
geth in the background to sync with the network.
Release
• The first release of Ethereum was known as Frontier.
• Current release of Ethereum is called homestead release.
• The next version is named metropolis and it focuses on protocol
simplification and performance improvement.
• The final release is named serenity, which is a Proof of Stake
algorithm (Casper) implemented with it.
Ethereum blockchain
In the preceding example, a transfer of 2 Ether from Address 4718bf7a to Address
741f7a2 is initiated. The initial state represents the state before the transaction
execution and the final state is what the morphed state looks like.
Currency (ETH and ETC)
• As an incentive to the miners, Ethereum also rewards its native
currency called Ether, abbreviated as ETH.
• Two Ethereum blockchains: one is called Ethereum classic and its
currency is represented by ETC, hard-forked version is ETH.
Forks
• The protocol was upgraded at block number 1,150,000, resulting in
the migration from the first version of Ethereum known as Frontier to
the second version of Ethereum called homestead.
• Network fork occurred at block number 2,686,351. This bug resulted
in geth failing to revert empty account deletions in the case of the
empty out-of-gas exception.
• This issue was resolved with the release of geth version 1.5.3.
Gas
• All transactions on the Ethereum blockchain are required to cover the cost
of computation they are performing. The cost is covered by something
called gas or crypto fuel, which is a new concep introduced by Ethereum.
• This gas as execution fee is paid upfront by the transaction originators. The
fuel is consumed with each operation. Each operation has a predefined
amount of gas associated with it. Each transaction specifies the amount of
gas it is willing to consume for its execution. If it runs out of gas before the
execution is completed, any operation performed by the transaction up to
that point is rolled back. If the transaction is successfully executed, then any
remaining gas is refunded to the transaction originator.
The consensus mechanism
• The consensus mechanism in Ethereum is based on the GHOST
protocol. (Greedy Heaviest-Observed Sub-Tree)
• Ethereum uses a simpler version of this protocol.
• Longest chain, as the longest chain must have been built by
consuming adequate mining effort.
• In GHOST, stale blocks are added in calculations to figure out the
longest and heaviest chain of blocks.
Longest versus heaviest chain
The world state
• The world state in Ethereum represents the global state of the
Ethereum blockchain.
• It is basically a mapping between Ethereum addresses and account
states.
• This mapping is a data structure that is serialized using Recursive
Length Prefix.
• RLP is a specially developed encoding scheme that is used in
Ethereum to serialize binary data for storage or transmission over the
network and also to save the state in a Patricia tree.
The account state
The account state consists of four fields:
• nonce
• balance
• Storage root
• codehash
• Nonce: This is a value that is incremented every time a transaction is
sent from the address.
• Balance: This value represents the number of Weis which is the
smallest unit of the currency (Ether) in Ethereum held by the address.
• Storageroot: This field represents the root node of a Merkle Patricia
tree that encodes the storage contents of the account.
• Codehash: This is an immutable field that contains the hash of the
smart contract code that is associated with the account.
Accounts trie (storage contents of account),
account tuple, world state trie, and state root
hash and their relationship
Transactions
• A transaction in Ethereum is a digitally signed data packet using a
private key that contains the instructions
• Message call transactions: This transaction simply produces a
message call that is used to pass messages from one account to
another.
• Contract creation transactions: As the name suggests, these
transactions result in the creation of a new contract.
common fields
• Nonce: Nonce is a number that is incremented by one every time a
transaction is sent by the sender.
• gasPrice:The gasPrice field represents the amount of Wei required in
order to execute the transaction.
• gasLimit: The gasLimit field contains the value that represents the
maximum amount of gas that can be consumed in order to execute
the transaction.
• To:As the name suggests, the to field is a value that represents the
address of the recipient of the transaction.
• Value:Value represents the total number of Wei to be transferred to
the recipient; in the case of a contract account, this represents the
balance that the contract will hold.
• Signature: Signature is composed of three fields, namely v, r, and s.
V is a single byte value that depicts the size and sign of the elliptic curve
point and can be either 27 or 28.
R is derived from a calculated point on the curve. First, a random
number is picked up.
S is calculated by multiplying R with the private key and adding it into
the hash of the message to be signed and by finally dividing it with the
random number chosen to calculate R. S is also a 32 byte sequence. R
and S together represent the signature.
• Init: The Init field is used only in transactions that are intended to
create contracts. This represents a byte array of unlimited length that
specifies the EVM code to be used in the account initialization
process.
• Data: If the transaction is a message call, then the data field is used
instead of init, which represents the input data of the message call. It
is also unlimited in size and is organized as a byte array.
Relationship between transaction,
transaction trie and block header
Contract creation transaction
There are a few essential parameters that are required when creating an account. These
parameters are listed as follows:
• Sender
• Original transactor
• Available gas
• Gas price
• Endowment, which is the amount of ether allocated initially
• A byte array of arbitrary length
• Initialization EVM code
• Current depth of the message call/contract-creation stack (current depth means
the number of items that are already there in the stack)
Message call transaction
A message call requires several parameters for execution, which are listed as follows:
• Sender
• The transaction originator
• Recipient
• The account whose code is to be executed
• Available gas
• Value
• Gas price
• Arbitrary length byte array
• Input data of the call
• Current depth of the message call/contract creation stack
Elements of the Ethereum
blockchain
Ethereum virtual machine (EVM)
• EVM is a simple stack-based execution machine that runs bytecode
instructions in order to transform the system state from one state to
another.
• The word size of the virtual machine is set to 256-bit.
• The stack size is limited to 1024 elements and is based on the LIFO
(Last in First Out) queue.
• EVM is a stack-based architecture.
• EVM is big-endian by design and it uses 256-bit wide words. This word
size allows for Keccak 256-bit hash and elliptic curve cryptography
computations.
• There are two types of storage available to contracts and EVM. The
first one is called memory, which is a byte array.
• When a contract finishes the code execution, the memory is cleared.
• The other type, called storage, is permanently stored on the
blockchain. It is a key value store.
Execution environment
• The key parameters
1. The address of the account that owns the executing code.
2. The address of the sender of the transaction and the originating address of this execution.
3. The gas price in the transaction that initiated the execution.
4. Input data or transaction data depending on the type of executing agent. This is a byte array; in
the case of a message call, if the execution agent is a transaction, then the transaction data is
included as input data.
5. The address of the account that initiated the code execution or transaction sender. This is the
address of the sender in case the code execution is initiated by a transaction; otherwise, it's the
address of the account.
6. The value or transaction value. This is the amount in Wei. If the execution agent is a transaction,
then it is the transaction value.
7. The code to be executed presented as a byte array that the iterator function picks up in each
execution cycle.
8. The block header of the current block
9. The number of message calls or contract creation transactions currently in execution. In other
words, this is the number of CALLs or CREATEs currently in execution.
Execution environment Tuple
Machine state
Machine state is also maintained internally by the EVM. Machine state
is updated after each execution cycle of EVM.
• Available gas
• The program counter, which is a positive integer up to 256
• Memory contents
• Active number of words in memory
• Contents of the stack
The EVM is designed to handle exceptions and will halt (stop execution)
in case any of the following exceptions occur:
• Not having enough gas required for execution
• Invalid instructions
• Insufficient stack items
• Invalid destination of jump op codes
• Invalid stack size (greater than 1024)
The iterator function
The iterator function mentioned earlier performs various important
functions that are used to set the next state of the machine and
eventually the world state. These functions include the following:
• It fetches the next instruction from a byte array where the machine
code is stored
• in the execution environment.
• It adds/removes (PUSH/POP) items from the stack accordingly.
• Gas is reduced according to the gas cost of the instructions/Opcodes.
• It increments the program counter (PC).
The iterator function
Accounts
Accounts are one of the main building blocks of the Ethereum blockchain.
The state is created or updated as a result of the interaction between
accounts. Operations performed between and on the accounts represent
state transitions.
1. Confirm the transaction validity by checking the syntax, signature validity,
and nonce.
2. Transaction fee is calculated and the sending address is resolved using the
signature. Furthermore, sender's account balance is checked and subtracted
accordingly and nonce is incremented. An error is returned if the account
balance is not enough.
3. Provide enough ether (gas price) to cover the cost of the transaction. This is charged
per byte incrementally according to the size of the transaction.
4. In this step, the actual transfer of value occurs. The flow is from the sender's account
to receiver's account. The account is created automatically if the destination account
specified in the transaction does not exist yet. Moreover, if the destination account is a
contract, then the contract code is executed. This also depends on the amount of gas
available. If enough gas is available, then the contract code will be executed fully;
otherwise, it will run up to the point where it runs out of gas.
5. In cases of transaction failure due to insufficient account balance or gas, all state
changes are rolled back with the exception of fee payment, which is paid to the miners.
6. Finally, the remainder (if any) of the fee is sent back to the sender as change and fee
is paid to the miners accordingly. At this point, the function returns the resulting state.
Types of accounts
There are two types of accounts in Ethereum:
• Externally owned accounts
• Contract accounts
The first is externally owned accounts (EOAs) and the other is contract
accounts. EOAs are similar to accounts that are controlled by a private key in
bitcoin.
Contract Account (CA) has ether balance, associated code, and the ability to
get triggered and execute code in response to a transaction or a message.
Block
Ethereum blocks consist of various components
• The block header
• The transactions list
• The list of headers of Ommers or Uncles
Block header
Block headers are the most critical and detailed components of an Ethereum block. The header contains valuable
information, which is described in detail here.
Parent hash
This is the Keccak 256-bit hash of the parent (previous) block's header.
Ommers hash
This is the Keccak 256-bit hash of the list of Ommers (Uncles) blocks included in the block.
Beneficiary
Beneficiary field contains the 160-bit address of the recipient that will receive the mining reward once the block is
successfully mined.
State root
The state root field contains the Keccak 256-bit hash of the root node of the state trie. It is calculated after all transactions
have been processed and finalized.
Transactions root
The transaction root is the Keccak 256-bit hash of the root node of the transaction trie. Transaction trie represents the list
of transactions included in the block.
Receipts root
The receipts root is the keccak 256 bit hash of the root node of the transaction receipt trie. This trie is
composed of receipts of all transactions included in the block.
Logs bloom
The logs bloom is a bloom filter that is composed of the logger address and log topics from the log entry of
each transaction receipt of the included transaction list in the block.
Difficulty
The difficulty level of the current block.
Number
The total number of all previous blocks; the genesis block is block zero.
Gas limit
The field contains the value that represents the limit set on the gas consumption per block.
Gas used
The field contains the total gas consumed by the transactions included in the block.
Timestamp
Timestamp is the epoch Unix time of the time of block initialization.
Extra data
Extra data field can be used to store arbitrary data related to the block.
Mixhash
Mixhash field contains a 256-bit hash that once combined with the nonce is used to prove
that adequate computational effort has been spent in order to create this block.
Nonce
Nonce is a 64-bit hash (a number) that is used to prove, in combination with the mixhash
field, that adequate computational effort has been spent in order to create this block.
Detailed diagram of block structure
with block header
Ether
• Ether is minted by miners as a currency reward for the computational effort they spend in order
to secure the network by verifying and with validation transactions and blocks.
• Ether is used within the Ethereum blockchain to pay for the execution of contracts on the EVM.
Messages
• Messages, as defined in the yellow paper, are the data and value that
are passed between two accounts.
• A message is a data packet passed between two accounts.
• A message consists of the components mentioned here:
1. Sender of the message
2. Recipient of the message
3. Amount of Wei to transfer and message to the contract address
4. Optional data field (Input data for the contract)
5. Maximum amount of gas that can be consumed
Mining
Mining is the process by which new currency is added to the blockchain. This is an
incentive for the miners to validate and verify blocks made up of transactions.
At a theoretical level, a miner performs the following functions:
1. Listens for the transactions broadcasted on the Ethereum network and
determines the transactions to be processed.
2. Determines stale blocks called Uncles or Ommers and includes them in the
block.
3. Updates the account balance with the reward earned from successfully
mining the block.
4. Finally, a valid state is computed and block is finalized, which defines the
result of all state transitions.