Smart contracts, Ethereum, and solidity

Goal: Be excited about smart contracts and wanting to write one

Smart contracts

Break 

Smart contracts and Ethereum

Break

Hacks and examples

Agenda

45min

45min

30min

15min

15min

Smart contracts

Agenda

Nick Szabo

What is a smart contracts ?

What is a contract ?

What are smart contracts ?

Relation with traditional law

Why ?

Exampels

Failures

Comparison

Complexity

Summary

Conclusion

Nick Szabo

Nick Szabo

What is a contract ?

What are smart contracts ?

Relation with traditional law

Why ?

Examples

Failures

Comparison

Complexity

Summary

Conclusion

What is a smart contract?

What is a contract?

Nick Szabo

What is a contract ?

What is a smart contract ?

Relation with traditional law

Why ?

Examples

Failures

Comparison

Complexity

Summary

Conclusion

Contracts

What are they ?

Contracts

What are they ?

What are smart contracts ?

Nick Szabo

What is a contract ?

What are smart contracts ?

Relation with traditional law

Why ?

Examples

Failures

Comparison

Complexity

Summary

Conclusion

The idea with a smart contract is that we’re totally defining the rules of our agreement in code

Smart Contracts

What is it ?

"New institutions, and new ways to formalize the relationships that make up these institutions, are now made possible by the digital revolution. I call these new contracts "smart", because they are far more functional than their inanimate paper-based ancestors. No use of artificial intelligence is implied. A smart contract is a set of promises, specified in digital form, including protocols within which the parties perform on these promises." -Nick Szabo, The idea of Smart Contracts

Smart Contracts

What is it ?

Smart Contracts

What is it ?

Smart Contracts

What is it ?

Smart Contracts

What is it ?

Smart Contracts

What is it ?

Any property that can be represented digitally can be managed with smart contracts

Difficult

Smart Contracts

What is it ?

Smart Contracts

What is it ?

"a contract is a program that runs on the brains of lawyers" - Nick Szabo

Relation to traditioal law

Nick Szabo

What is a contract ?

What are smart contracts ?

Relation with traditional law

Why ?

Examples

Failures

Comparison

Complexity

Summary

Conclusion

Smart Contracts

Relation with traditional law

source: Szabos

  • Smart contract similar to the repo man, its a security protocol that controls the burden of lawsuit
  • If "possession is 9/10 of the law" then crossborder blockchain-based financial smart contract may be 99% of the law
     
  • Do smart contracts need to be legally enforceable ?

 

  • Traditional contracts, interpreted by brain -> Wet code
     

  • Smart contracts are interpreted by a machine -> Dry code
     

  • Fiduciary(trust) vs Fiduciary Process (smart contract)

Why ?

Nick Szabo

What is a contract ?

What are smart contracts ?

Relation with traditional law

Why ?

Examples

Failures

Comparison

Complexity

Summary

Conclusion

Smart contracts

Why ?

  • Secure a wide variety of things
  • Cost of trust and security
  • Trust minimization (e.g send bitcoin does not need a fiduciary)
  • Minimize trust assumptions
  • Centralization is insecure

 

Smart Contracts

Centralization is insecure

Smart Contracts

Public and global

source: bitcoinmap 

Bitcoin

Etherium

Examples

Nick Szabo

What is a contract ?

What are smart contracts ?

Relation with traditional law

Why ?

Examples

Failures

Comparison

Complexity

Summary

Conclusion

Smart contracts

Exampels

  • Dispute mediation
  • Oracles 
  • Smart property
  • Tokens
  • Financial derivatives
  • Social sites
  • DNS
  • Atomic swaps
  • etc ...

Dispute mediation

Oracles

Smart property

Locks

Financial derivatives

contract

1000usd/eth

1000usd/eth

USD/ETH

1000usd/eth

REST

Social sites

Oracle

Etherium

Reddit

Pay bob 10 eth

Address: 123....

balance: 5eth

   accounts:

      reddit: note89

      twitter: note89

DNS

(name, ip)[]

Failures

Nick Szabo

What is a contract ?

What are smart contracts ?

Relation with traditional law

Why ?

Examples

Failures

Comparison

Complexity

Summary

Conclusion

Smart contracts

Failures

Insurrance claims and other very wet code heavy tasks

Comparison

Nick Szabo

What is a contract ?

What are smart contracts ?

Relation with traditional law

Why ?

Examples

Failures

Comparison

Complexity

Summary

Conclusion

Smart contracts

Comparison

Law Software
Reasoning method subjective minds, analogy boolean logic, bits
Security imprisonment / Contempt replication + cryptography
Predictability flexible rigid
Matuiry highly evolved / many cases infantile / few examples

Smart contracts

Comparison

Law Software
Area jurisdictional silos (on the blockchain) independent from institutions and politics, seamless across boarders
Costs Lawsuits/expensive very low

Complexity

Nick Szabo

What is a contract ?

What are smart contracts ?

Relation with traditional law

Why ?

Examples

Failures

Comparison

Complexity

Summary

Conclusion

Summary & conclusion

Smart contracts on Ethereum

Agenda

The state of things

Intro

History

Ethereum

  Accounts

  Messages and transactions

  Ethereum state transition function

  Gas

  Storage, memory the stack

  Messages

  Delegate call

  Logs

  Create

  Destruct

  Misc

------ Part 3

Examples

Hacks

  The Dao

  Parity

EC20 Smart Contracts

The state of things now

Instituions

Operation

Instituions

Contention

Instituions

Authority

Blockchain has solved the issue of multiparty contention without having to involve a human.

Trust is no longer needed to interact with a third-party.

Ethereum

Build unstoppable applications

Ethereum is a decentralized platform that runs smart contracts: applications that run exactly as programmed without any possibility of downtime, censorship, fraud or third-party interference.

Etherium

Etherium is a very slow and expensive world computer

Commodities Trust

Turing-complete language

Ultimate abstract foundation layer

First class smart contract support

Value awareness

Blockchain-awareness

State

  • 2013 proposed by Vitalik Buterin
  • Crowdsale July to August 2014
  • ~18 million dollars for 11.9 million coins
  • June 2016 The Dao Hack
  • Juli hard fork
  • 13 000% increase 2017
  • General purpose

Intro

History

  • Decentralized digital currency around for a long time
    • digicash 80s
    • b-money 90s
      • First with the idea of computer puzzles
    • PayPal
    • reusable proof of work 2005
    • 2009 Bitcoin
      • proof of work
        • moderately effective consensus algo
        • free entry
    • proof of stake

History

Bitcoin

APPLY(S,TX) -> S' or ERROR

History

Mining

History

Alternative blockchains

  • Namecoin
  • Colored coins
  • Metacoins

History

Scripting

  • Bitcoinscript allows for weak version of smart contracts
     
  • Multisignature can be implemented
     
  • Atomic swaps
    "This Bitcoin UTXO is yours if you can provide an SPV proof that you sent a Dogecoin transaction of this denomination to me"

History

Scripting

  • Lack of Turing-completeness - loops missing
  • Value-blindness
  • Lack of state
  • Blockchain-blindness

History

Summary

Three approaches to building advanced applications on top of cryptocurrency

  • New blockchain
  • Using scripting on top of Bitcoin
  • Building a meta-protocol

Ethereum

EVM

Ethereum virtual machine

Runtime environment for smart contracts

Sandboxed and isolated

No access to network, filesystem or other processes, limited access to other smart contracts

Etherium

Accounts

External accounts

Contract accounts

public key

creator address + nonce

address

storage

key-value 256-bit words

key-value 256-bit words

balance

wei

wei

code

no

Yes

Etherium

Messages and Transactions

A Transaction is a message from one account to another 

Might be the same or special zero-account

address 0 creates a contract

Etherium

Messages and Transactions

  • The recipient of the message
  • A signature identifying the sender
  • The amount of ether to transfer from the sender to the recipient
  • An optional data field
  • A STARTGAS value, representing the maximum number of computational steps the transaction execution is allowed to take
  • A GASPRICE value, representing the fee the sender pays per computational step

Etherium

Ethereum state transition function

Etherium

GAS

Etherium

Storage, memory and the Stack

  • Storage
    • 256-bit words
    • persistent
    • not possible to enumerate
    • costly to read
    • even more costly to write
    • only read and write to own storage
  • Memory
    • cleared of every message call
    • Linear, addressed at byte level
    • reads limited to width of 256-bit
    • expanded in chunks of 256-bit
    • must be paid at time of expansion
    • Memory more costly the larger it is scales quadratically

Etherium

Storage, memory and the Stack

Not a registry but a stack machine

It has a maximum size of 1024 elements and contains words of 256 bits

  • Access to stack limited to top end
    • copy one of the topmost 16 elements to the top
    • swap the topmost element with one of the 16 below it
  • Other operations combine topmost two elements from the stack and push the result back 

Etherium

Storage, memory and the Stack

Possible to move stack element to storage or memory, but not possible to access aribtrary elements deeper in the stack without first removeing the top stack

Etherium

Instruction set

Instructions for EVM are keept at minimal to avoid incorrect implementations which could cause concensus problems.

All operations operate on basic datatype 256-bit words.

Artichmatic, bit, logical and comparison operators are present. conditional and unconditional jumps are possible.

Contracts can access relevant properties of current block like number and timestamp

Etherium

Messages

Similar to transactions

Contracts can call other contracts or send ETH to non contract accounts by means of message calls.

A contract can decide how much of its remaning gas should be sent with inner message call.

The Called contract(can be same) will have cleared memory and access to the call payload(calldata). After finished execution it can return data to caller.

Etherium

Messages

Calls are limited to a depth of 1024, so for more complex operations loops should be preferred over recursive calls.

Etherium

Delegatecall/Callcode and Libraries

There exists a special variant of a message call, named delegatecall. same as message call just that the the target address will be called in same context as the call calling contract and msg.sender and msg.value do not change their values. 

Means we can dynamically load code from diffrent addresses at runtime. only code is taken from the called address. 

 

Makes librarys possible 

Etherium

Logs

Possible to store data in specially indexed data structure that maps up to blocklevel. Called logs and is used by for example Solidity to implement events.

Contracts cannot access log data after it has been created. But can be efficiently accessed from outside the blockchain. some of the logs are stored in bloom filters, makes it possible to search it fast and cryptographically secure. You dont need to download the whole blockchain so light clients can still find this logs.

Etherium

Create

Even contracts can create contracts

opcode or 0 address

Etherium

Self-destruct

The only possibility that code is removed from the blockhchain is when a contract performs the selfdestruct operation.

EXAMPLES

pragma solidity ^0.4.0;

contract SimpleStorage {
    uint storedData;

    function set(uint x) public {
        storedData = x;
    }

    function get() public constant returns (uint) {
        return storedData;
    }
}

Storage

pragma solidity ^0.4.0;

contract Coin {
    // The keyword "public" makes those variables
    // readable from outside.
    address public minter;
    mapping (address => uint) public balances;

    // Events allow light clients to react on
    // changes efficiently.
    event Sent(address from, address to, uint amount);

    // This is the constructor whose code is
    // run only when the contract is created.
    function Coin() public {
        minter = msg.sender;
    }

    function mint(address receiver, uint amount) public {
        if (msg.sender != minter) return;
        balances[receiver] += amount;
    }

    function send(address receiver, uint amount) public {
        if (balances[msg.sender] < amount) return;
        balances[msg.sender] -= amount;
        balances[receiver] += amount;
        Sent(msg.sender, receiver, amount);
    }
}

Subcurrency 

Coin.Sent().watch({}, '', function(error, result) {
    if (!error) {
        console.log("Coin transfer: " + result.args.amount +
            " coins were sent from " + result.args.from +
            " to " + result.args.to + ".");
        console.log("Balances now:\n" +
            "Sender: " + Coin.balances.call(result.args.from) +
            "Receiver: " + Coin.balances.call(result.args.to));
    }
})

Subcurrency 

HACKS!

The DAO Hack

50 MILLION DOLLARS!

How the DAO spends money

  • Contractor submits a proposal
  • Token-holders vote on the proposal
  • Accepted proposals are sent ETH

Slock.IT

The Dao, May

JUNE! HACK!

The Dao Hack, June

FORK ? ACCEPT ?

FORK!

What was the bug ?

function splitDAO(
  uint _proposalID,
  address _newCurator
) noEther onlyTokenholders returns (bool _success) {

  ...
  // Move ether and assign new Tokens.  Notice how this is done first!
  uint fundsToBeMoved =
      (balances[msg.sender] * p.splitData[0].splitBalance) /
      p.splitData[0].totalSupply;

// This is the line the attacker wants to run more than once
  if (p.splitData[0].newDAO.createTokenProxy.value(fundsToBeMoved)(msg.sender) == false) 
      throw;

  ...
  // Burn DAO Tokens
  Transfer(msg.sender, 0, balances[msg.sender]);
  withdrawRewardFor(msg.sender); // be nice, and get his rewards

  //  Notice the preceding line is critically before the next few
  totalSupply -= balances[msg.sender]; 
  balances[msg.sender] = 0; 
  paidOut[msg.sender] = 0;
  return true;
}

Hacks

EC20 DEMO

Agenda

The state of things

Intro

History

Ethereum

  Accounts

  Messages and transactions

  Ethereum state transition function

  Gas

  Storage, memory the stack

  Messages

  Delegate call

  Logs

  Create

  Destruct

  Misc

------ Part 3

Examples

Hacks

  The Dao

  Parity

  Randomness

EC20 Smart Contracts

Smart contracts

By Nils Eriksson

Smart contracts

  • 1,031