You are on page 1of 42

FITE3011

Distributed ledger and blockchain


Lecture 4 Ethereum
Ethereum
› A 19 year-old developer named, Vitalik Buterin, wanted to
apply the idea of decentralization (no central authority)
to more than just money transfer
› In Jan 2014, he officially published the white paper
proposing the development of a new platform with a more
general scripting language
› A team formed shortly and one of the developers, Dr.
Gavin Wood soon released the yellow paper which
covered the Ethereum Virtual Machine (EVM), the runtime
environment that executes all of the smart contracts on
the network

1
Ethereum
From a computer science
perspective, Ethereum is a
deterministic but practically
unbounded state machine,
consisting of a globally accessible
singleton state and a virtual
machine that applies changes to
that state.

2
Ethereum
› From a more practical perspective, Ethereum is an open
source (https://github.com/ethereum), globally
decentralized computing infrastructure that executes
programs called smart contracts
› It uses a blockchain to synchronize and store the
system’s state changes, along with a cryptocurrency
called ether to meter and constrain execution resource
costs

3
Ethereum
› A “World Computer”
› Ethereum allows developers to write and deploy
immutable programs to the blockchain
– When deployed, these programs can be trusted to execute
without interference from external non-blockchain events
› These programs are colloquially known as “smart
contracts”

4
Source: https://blockspoint.com/guides/ethereum/what-is-ethereum

5
Decentralized Apps (DApps)
› In the narrowest definition, a decentralized application
(DApps) is a smart contract with a frontend

Source:
https://www.zastrin.com/courses/eth
ereum-primer/lessons/1-5

6
Ethereum Architecture
› There is no central server to which all clients connect to
– This means, in an ideal decentralized world, every person who
wants to interact with a DApp (Decentralized Application) will
need a full copy of the blockchain running on their
computer/phone, etc.
› A full blockchain in your mobile phone?!
– Current blockchain size: https://bitinfocharts.com/

7
Ethereum Blockchain Components
› Ledger (or the Database)
– Every transaction in the network is stored in the blockchain
– When you deploy your application, it is considered as a
transaction. All these transactions are public, and any one can
see this and verify. This data can never be tampered with
– To make sure all the nodes in the network have same copy of
the data and to ensure no invalid data gets written to this
database

8
Ethereum Blockchain Components
› Code
– The ledger aspect of blockchain just stores the transactions
– What about the logic of doing the transactions?
– The logic/application code (called contract) is written in a
language called Solidity.
› The code is compiled to Ethereum Byte Code and then deployed to the
blockchain

› So, not only does Ethereum blockchain store the


transactions, but it also stores and executes the contract
code

9
Ethereum Blockchain
› To build Web-based DApps, Ethereum comes with a
handy JavaScript library called web3.js
(https://github.com/ethereum/web3.js/) which connects
to your blockchain node
› You can just include this library in your famous js
framework like Node.js, reactjs and angularjs and start
building

10
Smart Contracts
› Informally speaking, a contract is a written agreement
between two or many parties
› If we take this written contract and translate it into code
and deploy on the blockchain, we get digital contracts
› The contract itself can enforce the agreement and so it is
“smart”
› Once a contract is deployed to the blockchain, it can not
be modified
› Question: Is “smart contract” really that “smart”?

11
Traditional Contracts vs. Smart Contracts

Traditional Smart
Specification Natural Language Code
Identity & Consent Signatures Digital Signatures
Dispute Resolution Judges, Arbitrators Decentralized Platform
Cancel Judges N/A
Payment Conducted Separately Built-in
Escrow Trusted Third Party Built-in

12
Example
› To build a Crowdfunding application
› There is a creator who wants to raise $10,000 to create a
product and there are potential customers who are interested
in this product and are willing to pre-pay for it
› The agreement is, each customer will contribute anywhere
between $10 - $10,000 and
– If the goal is met, the money is sent to the creator
– If not, money is sent back to the contributors
› Also, anyone can trigger a refund to all the customers if the
goal is not reached within a certain time frame
› Sample code:
– https://www.toshblocks.com/solidity/complete-example-crowd-
funding-smart-contract/

13
Example – Domain Name System

14
15
Ethereum Address
› To login to any Website like Facebook, you usually use an
email/username and password
– Your username is your identity in Facebook and you use your
username/password to authenticate with Facebook
› In Ethereum blockchain, address is your identity
– An Ethereum 160-bit address looks like this:
001d3f1ef827552ae1114027bd3ecf1f086ba0f9
– An address has a corresponding private key
› You need this pair of “address + private key” to interact
with the blockchain

16
Ethereum Address Generation
› Generate a private key, sk, using the Elliptic Curve Digital Signature
Algorithm (ECDSA)
– E.g., sk =
f8f8a2f43c8376ccb0871305060d7b27b0554d2cc72bccf41b2705608452f315

› Derive the public key, pk, from sk


– E.g., pk =
6e145ccef1033dea239875dd00dfb4fee6e3348b84985c92f103444683bae07b83
b5c38e5e2b0c8529d7fa3f64d46daa1ece2d9ac14cab9477d042c84c32ccd0

› Calculate the hash of the public key by using keccak256 algorithm


– Keccak256(pk) =
2a5bc342ed616b5ba5732269001d3f1ef827552ae1114027bd3ecf1f086ba0f9001
d3f1ef827552ae1114027bd3ecf1f086ba0f9
› Take the last 160 bits of the generated hash to get the Ethereum address
– 0x001d3f1ef827552ae1114027bd3ecf1f086ba0f9

17
Ethereum Account
› The combination of Ethereum address and its private key
is referred to as an account
› An account in Ethereum can hold balance (ether) and can
send transactions
› Two types
– Externally owned accounts (EOA)
› This is the account we mentioned above which is a combination of public
address and private key. You can use these accounts to
– Send and receive ether to/from another account
– Send transactions to smart contracts

18
Ethereum Account (cont.)
– Contract accounts
› These accounts do not have a corresponding private key
› These accounts are generated when you deploy your contract to the
blockchain. Some key features of contract (accounts) are
– They can send and receive ether just like EOA
– They have code associated with them unlike EOA
– Transactions have to be triggered by an EOA or another contract

19
Ethereum Wallet
› Software plugins/libraries that are used to store and
manage your Ethereum accounts
› To manage multiple accounts, provides functionality to
sign transactions, track balances
› Deterministic and Non-Deterministic Wallet

Source: https://blog.ethereum.org/2015/09/16/ethereum-wallet-developer-preview/

20
Gas, Gas Price and Gas Limit
› To use the Ethereum
network, to send value from
account to account, or to
deploy a smart contract to
the blockchain, we pay a
gas fee to the miners that
secure the network
› To pay this gas fee, we use
ether, the native currency
of the Ethereum blockchain Source: https://www.zastrin.com/courses/ethereum-primer/lessons/2-2

21
Gas, Gas Price and Gas Limit
› The yellow paper has specification on how many units of
work a transaction has
– For example, if your transaction is to simply add two numbers,
that is 3 units of work. If it is multiplication, that would be 5 units
of work and so on. This unit of work is called gas.

22
Source: https://www.ethos.io/what-is-ethereum-gas/
Gas, Gas Price and Gas Limit
› We now know how much gas each transaction will need. But
we still do not know how much ether we have to pay the
miners
› That is determined by Gas Price
– You can set whatever gas price you want.
– For example, you can say “I am willing to pay 3 Gwei per gas” for my
transaction. If your transaction takes 100000 gas and you set the gas
price to 3 Gwei, you end up paying 300000 Gwei for your transaction
› The higher the gas price you set, the sooner your transaction
gets mined
› Ethereum Gas Tracker: https://etherscan.io/gastracker
23
Gas, Gas Price and Gas Limit
› It is very difficult to know exactly how much gas your
transaction will take
› As a developer, you do not want to blindly execute a
transaction and realize your transaction took hundreds of
dollars worth of Ether
› To avoid this situation, you can specify a Gas Limit which
indicates the maximum amount of gas you are willing to
buy to execute your transaction

24
All transactions specify START_GAS,
GAS_PRICE
› If START_GAS ⨉ GAS_PRICE > caller.balance, halt
› Deduct START_GAS ⨉ GAS_PRICE from caller.balance
› Set GAS = START_GAS
› Run code, deducting from GAS
› For negative values, add to GAS_REFUND
– GAS only decreases
› After termination, add GAS_REFUND to caller.balance

25
Byte Code
› Smart contract code is usually written in a high level
programming language such as Solidity
› This code gets compiled to something called the EVM
bytecode which gets deployed to the Ethereum
blockchain
– This is very similar to a programming language like Java where
the code get converted to JVM Byte code
› Other languages: Vyper (similar to Python) and Bamboo

26
Ethereum Virtual Machine (EVM)
› The Ethereum Virtual Machine (EVM) is a Virtual Machine that
allows anyone to execute arbitrary EVM Byte Code
› The EVM is part of the Ethereum Protocol and plays a crucial
role in the consensus engine of the Ethereum system. It
allows anyone to execute arbitrary code in a trust-less
environment in which the outcome of an execution can be
guaranteed and is fully deterministic
› When you install and start the geth, parity or any other client,
the EVM is started and it starts syncing, validating and
executing transactions
› It also comes with a JavaScript client (geth console) that can
be used to connect to the blockchain

27
Flow of Ethereum Transaction
› The developer deploys a smart contract to the blockchain
› The DApp instantiates the contract and executes a contract
method by passing a number of values
› The DApp signs the transaction
› Transaction is validated locally
› Transaction is broadcast to the network
› Miner Node accepts the transaction
› Miner Node finds a valid block and broadcasts to the network
› Local Node receives/syncs the new block
28
Related Tools and Technologies
› geth -
https://github.com/et
hereum/go-
ethereum/wiki/geth
› web3.js –
https://web3js.readth
edocs.io/en/1.0/inde
x.html

29
Related Tools and Technologies
› Metamask - https://metamask.io/
› Etherscan - https://etherscan.io/

30
More on Ethereum Architecture
› Order-Execute-Validate
› Ethereum combines consensus and execution of transactions
as follows
– Every node assembles a block containing valid transactions (to
establish validity, this peer already pre-executes those transactions);
– The peer tries to solve a PoW puzzle;
– If the peer is lucky and solves the puzzle, it disseminates the block to
the network via a gossip protocol;
– Every peer receiving the block validates the solution to the puzzle and
all transactions in the block. Effectively, every peer thereby repeats
the execution of the lucky peer from its first step. Moreover, all peers
execute the transactions sequentially (within one block and across
blocks).

31
More on Ethereum Architecture

Order-execute architecture in replicated services

Source: Hyperledger Fabric: A Distributed Operating System for Permissioned Blockchains 32


Consensus Layer

Block Header Block Header

Transaction State root Transaction State root


root hash hash root hash hash

Blockchain

Smart Contract Smart Contract

Input, output Input, output


code code
Store root hash
State Data
State of all accounts,
storage storage Layer
Including EOA
invokes/ and contract
queries accounts

Application
Layer
Applications
Transaction Root and State Root
› State Root = Tree formed › Transaction Root = Tree
by all accounts formed by all transactions
– Address of the block
– Code – From
– Storage – To
– Balance – Data
– Nonce – Value (#of Wei to be sent)
– StartGas (aka gas limit)
– GasPrice

34
Key Challenges
› - Smart contracts on public blockchains can be trusted
for correctness and availability,
› but not privacy
› - Blockchain resources are expensive
› - Uncertain delays, and front running
› - On the blockchain, “Code is law”

35
Rock Paper Scissors in Ethereum (Naïve
Implementation)
› function add_player() payable;
– Takes player’s deposit of 1 ETH.
› function input(uint choice);
– Records player’s choice (0 or 1 or 2)
› function check_winner();
– Decides who wins, pays the winner

36
struct Player { uint num_players = 0;
uint choice; uint reward = 0;
uint addr; mapping (uint => Player) player;
}
function check_winner() returns(int) {
function add_player() payable { require(block.timestamp >= start + 30
require(num_players < 2); minutes);
require(msg.value >= 2000 szabo); var p0_choice = player[0].choice;
reward += msg.value; var p1_choice = player[1].choice;
player[num_players].addr = if (p0_choice - p1_choice % 3 == 1)
msg.sender; // Player 0 wins
player[num_players].choice = 0; player[0].addr.send(reward);
num_players++; else
} if (p0_choice - p1_choice % 3 == 2)
// Player 1 wins
function input(uint choice, uint idx) player[1].addr.send(reward);
{ else {
require(msg.sender == player[0].addr.send(reward/2);
layer[idx].addr); player[1].addr.send(reward/2);
player[idx].choice = choice; }
} }
37
Coin Flip Game from Hash Functions
› Alice and Bob each generate a secret string
– a and b
› They each publish the hash of their values before time T
– A = H(a)
– B = H(b)
› After time T, they each reveal their secret values a and b
– The winner is computed as (a xor b) % 2

38
Any Problem?

39
Rock Paper Scissors in Ethereum

40
References
› Slides from Dr. Dennis Liu of PolyU
› Slides from Dr. Andrew Millier of UIUC
› Ethereum Yellow Paper, available at:
https://ethereum.github.io/yellowpaper/paper.pdf

41

You might also like