Ethereum
Ethereum
Block n
Block n+m
Output:
Input:
OP_DUP
… OP_HASH160 <sig1>
<pubKeyHash1> <pubKey1>
OP_EQUALVERIFY
OP_CHECKSIG
ScriptPubKey ScriptSig
Stack Script Description
<sig1> <pubKey1> OP_DUP OP_HASH160 <pubKeyHash1>
Empty
OP_EQUALVERIFY OP_CHECKSIG
Add constant values from left
OP_DUP OP_HASH160 <pubKeyHash1> OP_EQUALVERIFY
<sig1> <pubKey1> to right to the stack until we
OP_CHECKSIG
reach an opcode.
<sig1> <pubKey1>
OP_HASH160 <pubKeyHash1> OP_EQUALVERIFY OP_CHECKSIG Duplicate top stack item
<pubKey1>
<sig1> <pubKey1>
<pubKeyHash1> OP_EQUALVERIFY OP_CHECKSIG Hash at the top of the stack
<pub1Hash>
<sig1><pubKey1>
Push the hashvalue to the
OP_EQUALVERIFY OP_CHECKSIG
<pub1Hash><pubKeyHash1> stack
● Namecoin:
○ Bitcoin fork: Currency NMC
○ Decentralized name registration database: DNS, identities etc
● Colored coins:
○ On top of Bitcoin
○ Allows people to create their own digital currencies
● OmniLayer (formerly Mastercoin)
○ On top of Bitcoin
○ Distributed exchange, smart property, distributed e-commerce, etc
● OpenBazaar
○ On top of Bitcoin
○ Decentralized marketplace
Ethereum
Same principles as Bitcoin
● A peer-to-peer network: connects the participants
● A consensus algorithm: Proof of Work (will move to PoS)
● A digital currency: ether
● A global ledger: the blockchain
○ Addresses: key pair
○ Wallets
○ Transactions: digital signatures
○ Blocks
Ethereum: A universal Replicated State Machine
● Transaction-based deterministic state machine
○ Global singleton state
○ A virtual machine that applies changes to global state
● A global decentralized computing infrastructure
● Anyone can create their own state transition functions
● Stack-based bytecode language
● Turing-completeness
● Smart contracts
● Decentralized applications
Ethereum accounts
● Global state of Ethereum: accounts
● They interact to each other through transactions (messages)
● A state associated with it and a 20-byte address (160-bit identifier)
Ethereum account
No UTXOs
The balance of the account
in Ethereum
address balance nonce
Total transactions
UTXO vs Accounts
● UTXOs pros:
○ Higher degree of privacy
○ Scalability (parallelism, sharding)
● Accounts pros:
○ Space saving
○ Better fungibility
○ Simplicity
○ Efficiency
Two types of accounts
● Personal accounts (what we’ve seen)
● Contract accounts
Ethereum contract account
to ∅ receiver contract
Start gas
End
Transaction Receiver
170
Remaining
gas
Out of gas exceptions
● State reverts to previous state
● gas_limit * gas_price is still deducted from balance
Introduction to Solidity
Solidity
● A high level programming language for writing smart contracts on
Ethereum
● Compile code for the Ethereum Virtual Machine
● Syntax looks like JavaScript
Solidity
● Contracts look like classes / objects
● Static Type (Most types can be cast, e.g bool(x))
● Most of the control structures from JavaScript are available in Solidity
except for switch
pragma solidity ^0.5.1;
contract HelloWorld {
}
Pragmas
contract <contract-name> { … }
Constructors
contract HelloWorld {
constructor () public { … }
contract HelloWorld {
}
Solidity: Variables
● State variables:
○ Contract variables
○ Permanently stored in contract storage
○ Must declare at compilation time
● Local variables
○ Within a function: cannot be accessed outside
○ Complex types: at storage by default
○ Value types: in the stack
○ Function arguments: in memory by default
Types
● The type of each variable needs to be specified (Solidity is a statically
typed language)
● Two types:
○ Value types
○ Reference types
● “undefined” or “null” values does not exist in Solidity
● Variables without a value always have a default value (zero-state)
dependent on its type.
● Solidity follows the scoping rules of C99 (variables are visible until the end
of the smallest {}-block)
Value types
Types: booleans
contract Booleans {
bool p = true;
bool q = false;
contract Address {
address owner;
// y.length == 32
}
Types: Enum
contract Purchase {
}
Reference types
Types: arrays
contract Arrays { ● The notation of declaring 2D arrays is reversed
uint256[2] x; when compared to other languages!
uint8[] y;
○ Declaration: uint[columns][rows] z;
bytes z;
string name; ○ Access: z[row][column]
// 2D: dynamic rows, 2 columns! ● bytes and string are special arrays.
uint [2][] flags; ● bytes is similar to byte[] but is cheaper (gas).
● string is a UTF-8-encoded.
function create () public {
● Members:
uint[] memory a = new uint[](7);
○ push: push an element at the end of array.
flags.push([0, 1]);
} ○ length: return or set the size of array.
} ● string does not have length member.
● Allocate memory arrays by using the keyword
new. The size of memory arrays has to be known
at compilation. You cannot resize a memory array.
Types: Struct
● A struct cannot contain a struct of its own type
contract Vote { (the size of the struct has to be finite).
● A struct can contain mappings.
struct Voter {
bool voted;
address voter;
uint vote;
}
Types: Mappings
contract Mappings {
key value
Visibility
Visibility
● public: Public functions can be called from other contracts, internally and
personal accounts. For public state variables an automatic getter function is
being created.
● external: External functions cannot be called internally. Variables cannot be
declared as external.
● Internal: Internal function and variables can be called only internally.
Contracts that inherit another contract can access the parent’s internal
variables and functions.
● private: Private functions and variables can be called only by the contract in
which they are defined and not in derived contract. Warning: private
variables are visible to all observers external to the blockchain.
Data location
Data location: areas
● Every complex type (arrays, structs, mappings) have a data location.
● As of Solidity version 5.0.0 you must always declare the data location of
○ Function’s complex local values are saved to storage by default. (Solidity versions >= 5.0.0
force you to declare the data location).
● Memory:
○ Non-persistent.
○ Function’s arguments and returned values are stored to memory by default. (Solidity
versions >= 5.0.0 force you to declare the data location for complex types).
Data location: assignment
● storage <-> memory: copy
Unnamed function
Solidity: Functions
● Can return multiple values
● Access
○ Public: Accessed by anyone
○ Private: Accessed only from the contract
Remember that on-chain
○ Internal: Accessed only internally data is public despite
○ External: Accessed only externally access declaration!!
● Declarations
○ View: They promise not to modify the state
○ Pure: They promise not to read from or modify the state.
○ Payable: Must be used to accept Ether
pragma solidity ^0.4.24; pragma solidity ^0.4.24;
}
Solidity: events
● EVM logging mechanism
● Register listeners to events
● Arguments are stored in the transaction log
● An alternative to store data cheaply
Solidity: events
pragma solidity ^0.4.24; var abi = /* abi as generated by the compiler */;
var ClientReceipt = web3.eth.contract(abi);
contract ClientReceipt { var clientInstance = ClientReceipt.at("0x1234...ab67" /*
event Deposit( address */);
address indexed _from,
bytes32 indexed _id, var event = clientInstance.Deposit();
uint _value
); // watch for changes
event.watch(function(error, result){
function deposit(bytes32 _id) public payable { if (!error)
emit Deposit(msg.sender, _id, msg.value); console.log(result);
} });
}
Solidity: structs
pragma solidity ^0.4.24;
contract CrowdFunding {
contract Ballot { struct Funder {
struct Voter { address addr;
uint amount;
uint weight;
}
bool voted;
address delegate; struct Campaign {
uint vote; address beneficiary;
} uint fundingGoal;
} uint numFunders;
uint amount;
mapping (uint => Funder) funders;
}
}
Solidity: enum
pragma solidity ^0.4.24;
contract Enum {
enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill }
ActionChoices choice;
ActionChoices constant defaultChoice = ActionChoices.GoStraight;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
Solidity: units and globally available variables
● Ether Units
○ A literal number can take a suffix of wei, finney, szabo or ether (2 ether == 2000 finney
evaluates to true)
● Time Units
○ Suffixes like seconds, minutes, hours, days, weeks and years (1 hours == 60 minutes)
Solidity: units and globally available variables
● Block and Transaction Properties
○ block.blockhash
○ block.coinbase
○ msg.data
○ msg.gas
○ Msg.value
○ msg.sender
○ now
○ tx.origin
Solidity: units and globally available variables
● Error Handling
○ assert
○ require
○ revert
● Mathematical and Cryptographic Functions
○ addmod, mulmod
○ Keccak256 (SHA-3), sha256, ripemd160
Solidity: units and globally available variables
● Address Related
○ <address>.balance
○ <address>.transfer
○ <address>.send
○ <address>.call, <address>.callcode, <address>.delegatecall
● Contract Related
○ this, selfdestruct
Send ether
Send ether
Safe against
transfer 2300 throws on failure
re-entrancy
Safe against
send 2300 false on failure
re-entrancy
contract Universe {
address[] planets;
event NewPlanet(address planet, string name);