Ethereum EVM illustrated

exploring some mental models and implementations

Takenobu T.
Rev. 0.01.1

NOTE- Please refer to the official documents in detail.
- This information is current as of Mar, 2018.
- Still work in progress.

Contents
1. Introduction- Blockchain- World state- Account- Transaction- Message- Decentralised database- Atomicity and order

Appendix A : Implementation- Source code in Geth
- EVM developer utility- Solidity ABI

2. Virtual machine- Ethereum virtual machine (EVM)- Message call
- Exception- Gas and fee- Input and output- Byte order- Instruction set- Miscellaneous

Appendix C :- Markle tree and RLP- Consensus

Appendix B : User interface- Web3 API- Geth, Mist, Solc, Remix, Truffle, ...

References

1. Introduction

1. Introduction

Blockchain

A transaction-based state machineTransaction

World state

World state

st

s t+1

Ethereum can be viewed as a transaction-based state machine.

References : [E1] Ch.2, [E3]A transaction-based state machineTransaction

World state

World state

st

s t+1

A transaction represents a valid arc between two states.

References : [E1] Ch.2, [E3]

Block and transactions

Block
Transaction T1
Transaction T2
Transaction T3

World state

World state

st

s t+1

Transactions are collated into blocks.
A block is a package of data.

References : [E1] Ch.2, Ch.4, [E2], [E3]

Chain of states

Block bBlock b+1

Transaction T1

Transaction T4

Transaction T2

Transaction T5

Transaction T3

Transaction T6

World state

World state

World state

st

s t+1

s t+2

From the viewpoint of the states,
Ethereum can be seen as a state chain.

References : [E1] Ch.2, Ch.4, [E2], [E3]

Chain of blocks: Blockchain

Block bBlock b+1

Transaction T1

Transaction T4

Transaction T2

Transaction T5

Transaction T3

Transaction T6

World state

World state

World state

st

s t+1

s t+2

From the viewpoint of the implementation,
Ethereum can also be seen as a chain of blocks, so it is `BLOCKCHAIN`.

References : [E1] Ch.2, Ch.4, [E2], [E3], [W3]

Stack of transactions : Ledger

Transaction
Transaction
Transaction

Block b+1

Transaction
Transaction

Block bTransaction::

Transaction
Transaction
Transaction

Block 6

Transaction
Transaction
Transaction

Block 5

Transaction
Transaction
Transaction

Block 4

Transaction
Transaction
Transaction

Block 3

Transaction
Transaction
Transaction

Block 2Block 1

Transaction
Transaction
Transaction
Transaction
Transaction

Genesis block

From the viewpoint of the ledger,
Ethereum can also be seen as a stack of transactions.
References : [E1] Ch.2, Ch.4, [E2], [E3], [W3]

1. Introduction

World stateWorld state
World state s t

Address 1

Account state 1

Address 2

Account state 2

Address 3

Account state 3::

The world state is a mapping between address and account state.
References : [E1] Ch.4, [E2]

Several views of world state
World state
Address 1

Account state 1

Address 2

Account state 2

Address 3

Account state 3::

Mapping view

World state

Table view

Address 1

Account state 1

Address 2

Account state 2::

Address n

Account state nWorld state
Account 1
Account 2

Object view:
Account n

References : [E1] Ch.4

1. Introduction

Account

Account

World state

Account 1

Account 2

Account 3:

An account is an object in the world state.
References : [E1] Ch.4, [E2]

Account

World state

Account

Address 1

Account state 1

Address 2

Account state 2

Address 3

Account state 3::

An account is a mapping between address and account state.

References : [E1] Ch.4, [E2]

Account state
World state
Account
Account state

Addressnoncebalancestorage hashcode hashAccount storage

EVM code

An account state could contain EVM code and storage.
References : [E1] Ch.4

Two practical types of accountExternal actor

World state

Externally owned account (EOA)

Contract account

EVM codestorageAutonomous object

EOA is controlled by a private key.

Contract account contains EVM code.

References : [E1] Ch.4

Two practical types of accountExternal actor

World state
Externally owned account (EOA)

Contract account

Account state
Addressnonce

Account state
Addressnoncebalancebalancestorage hashstorage hashcode hashcode hashstoragecode

EOA is controlled by a private key.
EOA cannot contain EVM code.

Contract contains EVM code.
Contract is controlled by EVM code.
References : [E1] Ch.4

Address of accountExternally owned account (EOA)

Contract accountPrivate key
Sender address

Nonce

Public key

RLP, KEC, right 160 bits

hash

Address

Address

160 bits

160 bits

A 160-bit code used for identifying accounts.

References : [E1] Ch.4, Ch.7, [E2]

1. Introduction

Transaction

A transaction

BlockTransaction

Transaction
Transaction
World state

World state

st

s t+1

A transaction is a single cryptographically-signed instruction.

References : [E1] Ch.2, Ch.4, [E2]A transaction to world state
External actor(a person or other entity)

Transaction

Ethereum world

World state

A transaction is submitted by external actor.
References : [E1] Appendix A

Two practical types of transaction
External actor

External actor

Contract creation

Message callTransaction

Transaction

CreateContract
account

World state

Message
EOA

EOA or CA

World state

There are two practical types of transaction, contract creation and message call.
References : [E1] Ch.4

Contract creation
Transaction

init code

Address 1

Account state 1

Address 1

Account state 1

Address 2

Account state 2

Address 2

Account state 2

:

:

:

:

Address N

Account state N

codeWorld state s t

storage

World state s t+1

References : [E1] Ch.7

Message callTransaction

input data

Address 1

Account state 1

Address 1

Account state 1

Address 2

Account state 2

Address 2

Account state 2

:

:

:

:

Address N

Account state N

Address N

Account state N

codeWorld state s t

storagecodestorage

World state s t+1

References : [E1] Ch.7

Field of a transaction
Transaction
nonce

gasPrice
gasLimit
160 bits address or 0 if contract creation

to
value

transferred wei (ether)v, r, sinit or data

contract creation or message call

References : [E1] Ch.4

1. Introduction

MessageMessage

World state

Account A

Account B
Message

Message is passed between two Accounts.
Message is Data (as a set of bytes) and Value (specified as Ether) .

References : [E1] Ch.8, Appendix A

Message
Triggered by transaction

Triggered by EVM code

Transaction

EOA

MessageAccount

Contract
account

MessageAccount

EVM codeWorld stateTransaction triggers an associated message.

World state

EVM can also send a message.

References : [E1] Ch.8

Four cases of message
By Transaction From EOA

By EVM code From CA

Transaction

Message
EOA

EOA

EOA

To EOACA

Messagecode

Transaction

EOA

Message

To CA
Message
CA

CA

code

CA

References : [E1] Ch.8

1. Introduction

Decentralised databaseGlobally shared, transactional database

World state

A blockchain is a globally shared, transactional database.
References : [E3], [E7] Ch.7

Decentralised database

World state

World state
World state

P2P
network

World state

World state

World state
World state
World state

A blockchain is a globally shared, decentralised, transactional database.
References : [E3], [E7] Ch.7

P2P network inter nodes

Ethereumnode

Ethereum
nodeWorld state

World state

Ethereum
node...

World state

P2P

Decentralised nodes constitute Ethereum P2P network.
References : [E3],Interface to a node
External
actor

Contract creation

Message callTransaction

Transaction

Inspection

Interface (Web3 API)

Ethereum
world

World state

Ethereum node (Geth, Parity, ...)

External actors access the Ethereum world through Ethereum nodes.
References : [E1] Appendix A, Ch.4, Ch.7, Ch.8

1. Introduction

Atomicity and orderAtomicity of transaction

Transaction

A transaction is an atomic operation. Can't divide or interrupt.

Transaction

orTransaction

That is, All (complete done) or Nothing (zero effect).

Order of transactions

order (timing)

Transaction
Blockchain

Transaction

Transaction
Transaction

Transactions cannot be overlapped.
Transactions must be executed sequentially.

Order of transactions
External actor A

3rd submitted
Transaction

External actor B
1st submitted

2nd submitted

Transaction

Transaction

order (timing)???
Transaction

Transaction

Transaction

Blockchain

Transaction order is not guaranteed.

???

Ordering inner blocksendersendersenderTransaction B
Transaction C

Transaction A

Transaction A

Transaction C

Transaction
poolTransaction B

determinedby miner
Transaction C
Transaction A

orderedTransaction B

Block

Miner can determine the order of transactions in a block.

Ordering inter blocks
Winner
miner

miner

miner

(Block b+2)

(Block b+2)

(Block b+2)

Transaction C

Transaction B

Transaction A

Transaction A

Transaction D

Transaction E

Transaction B

Transaction A

Transaction C

fast

selected by PoW

Transaction T1

Transaction T4

Transaction T2

Transaction T5

Transaction T3

Transaction T6

Block bBlock b+1

The order between blocks is determined by a consensus algorithm such as PoW.
References : [E1] Ch.2, Ch.4

2. Virtual machine2. Virtual machine

Ethereum virtual machine (EVM)

Ethereum virtual machineTransaction of message call
input data
World state s t

Address N

World state s t+1

Address N

Account state N

code

storageAccount state N

code

storage

EVM(Ethereum Virtual Machine)

EVM code is executed on Ethereum Virtual Machine (EVM).
References : [E1] Ch.9, Appendix H

Ethereum virtual machine

Code

Virtual machine

EVM code

EVM (Ethereum Virtual Machine)

The Ethereum Virtual Machine is the runtime environment for smart contracts in Ethreum.

References : [E1] Ch.9, Appendix H, [E4], [W1]

EVM architecture
Ethereum Virtual Machine (EVM)

Virtual ROM
EVM code(immutable)

Program counter

Stack

Memory(Account) storage

PC
Gas available
Gas

Machine state m

World state s(volatile)(persistent)

The EVM is a simple stack-based architecture.
References : [E1] Ch.9, Appendix H, [E4]

Machine space of EVM

Registers

Stack

Memory(Account) storage

stack memory

volatile memory

persistent memory

256 bits x 1024 elements

byte addressing
linear memory

256 bits to 256 bits
key-value store-

There are several resources as space.

References : [E1] Ch.9, Appendix H, [E3], [E7], [W2]

StackStack

256-bit read/write:

operation with 16 elements
in stack top:

1024 elements

256 bits

All operation are performed on the stack.
Access with many instructions such as PUSH/POP/COPY/SWAP, ...

References : [E1] Ch.9, Appendix H, [E7], [W2]

Memory

Memory256-bit load:

256-bit store
or
8-bit store
8 bitsMemory is linear and can be addressed at byte level.
Access with MSTORE/MSTORE8/MLOAD instructions.
All locations in memory are well-defined initially as zero.

References : [E1] Ch.9, Appendix H, [E7], [W2]

Account storage(Account) storage

256-bit load/store

Key 1

Value 1

Key2

Value 2

:

:

Key n

Value n256 bits

256 bits

Storage is a key-value store that maps 256-bit words to 256-bit words.
Access with SSTORE/SLOAD instructions.
All locations in storage are well-defined initially as zero.

References : [E1] Ch.9, Appendix H, [E7], [W2]

EVM code
Assembly view

PUSH1 e0
PUSH1 02
EXP
PUSH1 00
CALLDATALOAD:

Bytecode view

0x60e060020a600035...

EVM Code is the bytecode that the EVM can natively execute.

References : [E1] Ch.9, Appendix H

Execution model
EVM
EVM code

instructions

Stack
PC

operations

Memorystack top

(Account) storage

randomaccessGas availrandomaccesspush/pop/...

References : [E1] Ch.9, Appendix H

2. Virtual machine

Message call

Message callWorld state

EOA

Contract accountMessage

EVM code

Contract accountMessage
EVM code

EVM can send a message to other account.
The depth of message call is limited to less than 1024 levels.
References : [E1] Ch.8, Appendix A

Instructions for Message call
input data

Stack

MemoryStackMemoryarguments

CALL instruction

return value

EVM

RETURN instruction

EVM

Message call is triggered by CALL instruction.
Arguments and return values are passed using memory.
References : [E1] Ch.8, Ch.9

2. Virtual machine

Exception

Exception
Transaction
input data
World state s t

Address N

World state s t+1

Address N

Account state N

Account state N

The behavior if an exception occurs is subtle. [E9]code storage

code

storage

Exception

EVM

ToDo: Refine this page

If an exception occurs in the EVM, the state is not updated.
References : [E9], [E1] Ch.9, Appendix H

Exception
EVM
invalidjump destination

EVM codeinvalid
instruction
Stack
PC

Memoryoperations

Gas avail

Storageout-of-gas

stack underflow

References : [E1] Ch.9, Appendix H

2. Virtual machine

Gas and fee

Gas and fee
Message callTransaction
World state

EOA
Gas supply

Message
Contract accountRefundGas
EVM code

All programmable computation in Ethereum is subject to fees (denominated in gas).

References : [E1] Ch.5, Ch.9, Appendix G

Gas
EVM

EVM code

Message call

Stack
PC

Gas avail

more
Gas

Memoryoperations

Gas

Storagemore
Gas

References : [E1] Ch.5, Ch.9, Appendix G

2. Virtual machine

Input and output

Input and Output of EVM
External
actor

Transaction

input datalog

Message call

EVM

EVM
return value

EVM can input external data from a message call.
EVM can output log. EVM can also return values to Caller EVM.

References : [E1] Ch.9, Appendix H

Instructions for input data
input data

CALLDATALOADCALLDATACOPY

Stack

MemoryEVM
References : [E1] Ch.7, Ch.9

2. Virtual machine

Byte orderEndian for Memory

address (byte addressing)

N N+1

Memory

...

N+31
...

256-bit load (MLOAD)
256-bit store (MSTORE)
MSB

LSB

Stack

EVM is big endian order (network byte order).

References : [E1] Ch.9, Appendix H, [E7], [W2]

Endian for Memory

address (byte addressing)N

Memory8-bit store (MSTORE8)

MSB

LSB

Stack

EVM is big endian order (network byte order).

References : [E1] Ch.9, Appendix H, [E7], [W2]

Endian for input data

address (byte addressing)

N N+1

input data

...

N+31
...

CALLDATALOAD or CALLDATACOPY

MSB

LSB

Stack
or
MemoryEVM is big endian order (network byte order).

References : [E1] Ch.9, Appendix H, [E7], [W2]

Byte order of BYTE and SIGNEXTEND instruction
Nth byte
0

...

1

31

...

Stack
MSB

LSB

BYTE instruction counts from MSB.

Nth byte
...

31

1

0

...

Stack
MSB

LSB

SIGNEXTEND instruction counts from LSB.
References : [E1] Ch.9, Appendix H, [E7], [W2]

Byte order of PUSH instructions
Nth byte...

31

PUSH1 0x01

1

...

Stack

0
01

MSB

right-aligned, big endianLSB

Nth byte...

31

PUSH4 0x01020304

...

Stack

1

0

01 02 03 04

MSB

right-aligned, big endianLSB

Nth byte
31

PUSH32 0x0102...1f20

Stack

...

1

0

01 02 ... 1b 1c 1d 1e 1f 20
MSB

LSB

right-aligned, big endian

References : [E1] Ch.9, Appendix H, [E7], [W2]

2. Virtual machine

Instruction set

Instruction set* Basically, 256-bit operation.
* Contract creation and destruct* CREATE, DELEGATECALL* Hash* SHA3* Shift operation* using MUL or DIV, SDIV
* Div operation* without zero divisional exception* ...

References : [E1] Ch.9, Appendix H

Copy of code and input data

input data

CALLDATALOADCALLDATACOPY

EVM code

EVM code
Stack

Memory

CODECOPY
EXTCODECOPY

EVM

EVM

There are several copy instructions for inter spaces.
References : [E1] Ch.8, Ch.9

Shift by MUL, DIV and SDIV
Left shift
MSB

LSB

Stack

MUL m (2^n) == m << nLeft shift is represented by MUL instruction.

Right shift
MSB

Stack

LSB

DIV m (2^n) == m >> n
DIV for logical right shift
SDIV for arithmetic right shift

Right shift is represented by DIV and SDIV instruction.
References : [E1] Ch.9, Appendix H, [E7], [W2]

2. Virtual machine

MiscellaneousEVM code generation

Solidity source

Viper source

LLL source

Solidity compiler

Viper compiler

LLL compiler

EVM code

Ethereum virtual machine code

References : [E7]

Ethereum virtual machine layer

codevirtual machine

runtime system(process)

EVM code

EVM
Ethereum Virtual Machine

Ethereum node
(Geth, Parity, ...)

softwarehardwarePhysical Processor(x86, ARM, ...)

References : [E1] Ch.9

eWASM

The eWASM is next generation VM.

Appendix A

Appendix A

Source code in Geth

Block header(go-ethereum version 1.8)

[core/types/block.go]
Block header
type Header struct {ParentHash common.Hash`json:"parentHash"
gencodec:"required"`UncleHashcommon.Hash`json:"sha3Uncles"
gencodec:"required"`
Root of State
Coinbasecommon.Address `json:"miner"
gencodec:"required"`Rootcommon.Hash`json:"stateRoot"
gencodec:"required"`TxHashcommon.Hash`json:"transactionsRoot" gencodec:"required"`
ReceiptHash common.Hash`json:"receiptsRoot"
gencodec:"required"`
Root of Transaction
Bloom
Bloom
`json:"logsBloom"
gencodec:"required"`
Difficulty *big.Int`json:"difficulty"
gencodec:"required"`
Number*big.Int`json:"number"gencodec:"required"`
GasLimit
uint64`json:"gasLimit"
gencodec:"required"`
GasUseduint64`json:"gasUsed"gencodec:"required"`Time*big.Int`json:"timestamp"
gencodec:"required"`Extra[]byte`json:"extraData"
gencodec:"required"`
MixDigest
common.Hash`json:"mixHash"
gencodec:"required"`
Nonce
BlockNonce`json:"nonce"
gencodec:"required"`}

References : [C1]

Transaction(go-ethereum version 1.8)

[core/types/transaction.go]
Transaction
type txdata struct {AccountNonce uint64`json:"nonce"
gencodec:"required"`Price*big.Int`json:"gasPrice" gencodec:"required"`to address
GasLimit
uint64`json:"gas"gencodec:"required"`
Recipient*common.Address `json:"to"rlp:"nil"`// nil means contract creation
Amount*big.Int`json:"value"
gencodec:"required"`value (Wei)Payload[]byte`json:"input"
gencodec:"required"`// Signature values
V *big.Int `json:"v" gencodec:"required"`
R *big.Int `json:"r" gencodec:"required"`
S *big.Int `json:"s" gencodec:"required"`

input data// This is only used when marshaling to JSON.
Hash *common.Hash `json:"hash" rlp:"-"`}

References : [C1]

World state(go-ethereum version 1.8)

[core/state/statedb.go]
type StateDB struct {db
Databasetrie Trie

World state

stateObjects
map[common.Address]*stateObject
stateObjectsDirty map[common.Address]struct{}

Mapping for
Address to Account state

dbErr error
refund uint64
thash, bhash common.Hash
txIndexint
logs
map[common.Hash][]*types.Log
logSizeuint
preimages map[common.Hash][]byte:

References : [C1]

Account object (state object)(go-ethereum version 1.8)

[core/state/state_object.go]
type stateObject struct {address common.Address
addrHash common.Hashdata
Accountdb*StateDB

Address
Account state

dbErr error

trie Trie // storage trie, which becomes non-nil on first accesscode Code // contract bytecode, which gets set when code is loaded
cachedStorage Storage // Storage entry cache to avoid duplicate reads
dirtyStorage Storage // Storage entries that need to be flushed to disk
dirtyCode bool // true if the code was updated
suicided bool
touchedbool
deletedbool
onDirtyfunc(addr common.Address)}

References : [C1]

Account state, Code and Storage(go-ethereum version 1.8)

[core/state/state_object.go]
type Account struct {Account stateNonce
uint64
Balance *big.Int
Root
common.Hash // merkle root of the storage trie
CodeHash []byte}

type Code []byte

type Storage map[common.Hash]common.Hash

EVM code

Account storage

References : [C1]

Stack and Memory(go-ethereum version 1.8)

[core/vm/stack.go]
type Stack struct {data []*big.Int
}

Stack

func newstack() *Stack {return &Stack{data: make([]*big.Int, 0, 1024)}}[core/vm/memory.go]
type Memory struct {store[]bytelastGasCost uint64}

Memoryfunc NewMemory() *Memory {return &Memory{}}

References : [C1]

Instruction operation (arithmetic and stack)(go-ethereum version 1.8)

[core/vm/instruction.go]
Arithmetic operation
func opAdd(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack)([]byte, error) {x, y := stack.pop(), stack.pop()
stack.push(math.U256(x.Add(x, y)))evm.interpreter.intPool.put(y)return nil, nil}

Stack operation
func opPop(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack)([]byte, error) {evm.interpreter.intPool.put(stack.pop())
return nil, nil}

References : [C1]

Instruction operation (memory and storage)(go-ethereum version 1.8)

[core/vm/instruction.go]
Memory operation
func opMload(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack*Stack) ([]byte, error) {offset := stack.pop()
val := new(big.Int).SetBytes(memory.Get(offset.Int64(), 32))
stack.push(val)evm.interpreter.intPool.put(offset)
return nil, nil}
Storage operation
func opSload(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack*Stack) ([]byte, error) {loc := common.BigToHash(stack.pop())
val := evm.StateDB.GetState(contract.Address(), loc).Big()
stack.push(val)return nil, nil}

References : [C1]

Instruction operation (call)(go-ethereum version 1.8)

[core/vm/instruction.go]
Flow operation
func opCall(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack)([]byte, error) {// Pop gas. The actual gas in in evm.callGasTemp.
evm.interpreter.intPool.put(stack.pop())
gas := evm.callGasTemp// Pop other call parameters.
addr, value, inOffset, inSize, retOffset, retSize := stack.pop(),
stack.pop(), stack.pop(), stack.pop(), stack.pop(), stack.pop()
toAddr := common.BigToAddress(addr)
value = math.U256(value)// Get the arguments from the memory.
args := memory.Get(inOffset.Int64(), inSize.Int64())
if value.Sign() != 0 {gas += params.CallStipend}
ret, returnGas, err := evm.Call(contract, toAddr, args, gas, value)
if err != nil {:References : [C1]Gas(go-ethereum version 1.8)

[core/vm/gas.go]
const (
GasQuickStep
uint64 = 2
GasFastestStep uint64 = 3
GasFastStep
uint64 = 5
GasMidStep
uint64 = 8
GasSlowStep
uint64 = 10
GasExtStep
uint64 = 20

Gbase
Gverylow

GasReturnuint64 = 0
GasStopuint64 = 0
GasContractByte uint64 = 200)[core/vm/gas_table.go]func gasSStore(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem*Memory, memorySize uint64) (uint64, error) {var (y, x = stack.Back(1), stack.Back(0)val = evm.StateDB.GetState(contract.Address(),:
References : [C1]

Interpreter(go-ethereum version 1.8)

[core/vm/interpreter.go]
func (in *Interpreter) Run(contract *Contract, input []byte) (ret []byte, err
error) {// Increment the call depth which is restricted to 1024

in.evm.depth++defer func() { in.evm.depth-- }()increment call depth

in.returnData = nil

if len(contract.Code) == 0 {return nil, nil}
codehash := contract.CodeHash // codehash is used when doing jump dest cachingif codehash == (common.Hash{}) {codehash = crypto.Keccak256Hash(contract.Code)
}
var (
op
OpCode// current opcodemem= NewMemory() // bound memory
stack = newstack() // local stackcreate Memory
create Stack:
References : [C1]ApplyTransaction(go-ethereum version 1.8)

[core/state_processor.go]
func ApplyTransaction(config *params.ChainConfig, bc *BlockChain, author*common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx*types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, uint64, error){msg, err := tx.AsMessage(types.MakeSigner(config, header.Number))
if err != nil {return nil, 0, err}// Create a new context to be used in the EVM environment
context := NewEVMContext(msg, header, bc, author)// Create a new environment which holds all relevant information// about the transaction and calling mechanisms.
create EVM
vmenv := vm.NewEVM(context, statedb, config, cfg)// Apply the transaction to the current state (included in the env)_, gas, failed, err := ApplyMessage(vmenv, msg, gp)
if err != nil {return nil, 0, err}// Update the state with pending changes
var root []byte
if config.IsByzantium(header.Number) {:References : [C1]

Version of EVM instruction set(go-ethereum version 1.8)

[core/vm/interpreter.go]
func NewInterpreter(evm *EVM, cfg Config) *Interpreter {if !cfg.JumpTable[STOP].valid {switch {case evm.ChainConfig().IsByzantium(evm.BlockNumber):cfg.JumpTable = byzantiumInstructionSetcase evm.ChainConfig().IsHomestead(evm.BlockNumber):cfg.JumpTable = homesteadInstructionSet
default:
cfg.JumpTable = frontierInstructionSet:

added instructions:
STATICCALL, RETURNDATASIZE,
RETURNDATACOPY and REVERT
added instruction:
DELEGATECALL[core/config.go]var (MainnetChainConfig = &ChainConfig{
ChainId:
big.NewInt(1),HomesteadBlock: big.NewInt(1150000),
DAOForkBlock:big.NewInt(1920000),
DAOForkSupport: true,
EIP150Block:big.NewInt(2463000),
EIP150Hash: common.HexToHash("0x2086799aeebeae135c246c65021c82b4e15a2c451340993a
EIP155Block:big.NewInt(2675000),
EIP158Block:big.NewInt(2675000),
ByzantiumBlock: big.NewInt(4370000),:
References : [C1]

Bootstrap of EVM in Geth(go-ethereum version 1.8):
ApplyTransaction [core/state_processor.go]

create EVM

ApplyMessage [core/state_transaction.go]
TransactionDb [core/state_transaction.go]

Call [core/vm/evm.go]run [core/vm/evm.go]
Run [core/vm/interpreter.go]

create Memory
create Stack

References : [C1]Appendix A

EVM developer utility

Example of evm command(go-ethereum version 1.8)

The go-ethereum project provides evm utility command.
Compile EVM assembly code
$ cat sample.asm
push 0x1
push 0x2
add$ evm compile sample.asm
6001600201

Disassemble EVM bytecode$ cat sample.bin
6001600201$ evm disasm sample.bin
000000: PUSH1 0x01
000002: PUSH1 0x02
000004: ADD

References : [C1]

Example of evm command(go-ethereum version 1.8)

Run EVM assembly code
$ evm --debug run sample.asm#### TRACE ####
PUSH1
pc=00000000 gas=10000000000 cost=3

PUSH1
Stack:
00000000
ADD
Stack:
00000000
00000001
STOP
Stack:
00000000

pc=00000002 gas=9999999997 cost=30000000000000000000000000000000000000000000000000000000000000001
pc=00000004 gas=9999999994 cost=30000000000000000000000000000000000000000000000000000000000000002
0000000000000000000000000000000000000000000000000000000000000001
pc=00000005 gas=9999999991 cost=00000000000000000000000000000000000000000000000000000000000000003#### LOGS ####

References : [C1]Appendix A

Solidity ABI

Solidity Application Binary Interface

Function selector(SHA-3 hash)input data

Arguments, ...

4byte

CALLDATALOADCALLDATALOADCALLDATACOPY

function
dispatching
JUMPI

function A

function B

EVM code

Stack or Memory

EVM
References : [E7]. Ch.7, [E1] Ch.9, Appendix H, [W4], [W2]Appendix B

Appendix B

Web3 APIWeb3 API and client
CLI

WalletWalletIDE

IDE / CI

Geth
consoleMist

MetaMask

Remix

Truffle...

EthereumclientWeb3 API

Ethereum
network

World state

Ethereum clients access to Ethereum network via Web3 API.

References : [E8], [C1], [C3], [C4], [C5], [C6]Web3 API and client

EthereumclientGeth console,
Mist, MetaMask,
Remix, Truffle, ...

Web3 API

Ethereum
network

Ethereumnode

Ethereumnode(Geth, Parity, ...)

(Geth, Parity, ...)...

Ethereumnode(Geth, Parity, ...)

P2P

Ethereum clients access to Ethereum network via Web3 API.
References : [E8], [C1], [C3], [C4], [C5], [C6]Appendix B

Geth, Mist, Solc, Remix, Truffle, ...

Geth
Geth

consoleEthereumclientWeb3 APInode
Web3 I/F
Ethereum
network

EVM...

Ethereum
node

P2P(Geth, Parity, ...)

P2P

References : [C1]

Mist

Mist
Ethereumclientprivate key

Web3 API

Ethereum
network

Ethereumnode(Geth, Parity, ...)

References : [C3]

Solc
Solidity source
Solc(Solidity compiler)
EVM code(Geth, Mist, Truffle, ...)

Web3 API

Ethereum
network

Ethereumnode(Geth, Parity, ...)

References : [C2]

Remix
Remix
EVM
EthereumclientJavaScript
VM

Injected
Web3

Web3providerMetaMask
Web3 API

Ethereum
network

References : [C5]

Truffle
TruffleEthereumclientconsoleWeb3 API

Ethereum
network

Private chain

Ethereumnode(Geth, Parity, ...)

P2P

References : [C6]

ReferencesReferences[E1]

Ethereum Yellow PaperETHEREUM: A SECURE DECENTRALISED GENERALISED TRANSACTION LEDGER
https://ethereum.github.io/yellowpaper/paper.pdf[E2]

Glossaryhttps://github.com/ethereum/wiki/wiki/Glossary[E3]

White Paper
A Next-Generation Smart Contract and Decentralized Application Platform
https://github.com/ethereum/wiki/wiki/White-Paper[E4]

Design Rationale
https://github.com/ethereum/wiki/wiki/Design-Rationale[E5]

Ethereum Development Tutorial
https://github.com/ethereum/wiki/wiki/Ethereum-Development-Tutorial[E6]

Ethereum Introduction
https://github.com/ethereum/wiki/wiki/Ethereum-introduction[E7]

Solidity Documentation
https://media.readthedocs.org/pdf/solidity/develop/solidity.pdf
https://solidity.readthedocs.io/en/develop/[E8]

Web3 JavaScript app API for 0.2x.x
https://github.com/ethereum/wiki/wiki/JavaScript-API[E9]ethereum/wiki Subtleties
https://github.com/ethereum/wiki/wiki/Subtleties#exceptional-conditions

References[W1] Awesome Ethereum Virtual Machinehttps://github.com/pirapira/awesome-ethereum-virtual-machine[W2] Diving Into The Ethereum VM
https://blog.qtum.org/diving-into-the-ethereum-vm-6e8d5d2f3c30[W3] Stack Exchange: Ethereum block architecture
https://ethereum.stackexchange.com/questions/268/ethereum-block-architecture/6413[W4] Porosity
https://www.comae.io/reports/dc25-msuiche-Porosity-Decompiling-Ethereum-Smart-Contracts.pdf

References[C1]

Go Ethereum
https://github.com/ethereum/go-ethereum[C2]

Solc (Solidity compiler)
https://github.com/ethereum/solidity[C3]

Mist (Ethereum Wallet)
https://github.com/ethereum/mist[C4]

MetaMask
https://github.com/MetaMask/metamask-extension

[C5]

Remix
https://github.com/ethereum/browser-solidity[C6]

Trufflehttps://github.com/trufflesuite/truffle