Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Analysis of Smart Contracts

Analysis of Smart Contracts

I gave this talk at TU München for the seminar "Technical analysis of existing blockchains". It covers "smart contracts" in depth including but not limited to following points:
- Introduction to Smart Contract
- Use-cases and benefits
- Smart contracts on Ethereum
- Writing Smart Contracts
- Solidity
- Example of a Token Contract
-Security & The DAO Hack Solidity pitfalls
- Tools in Ethereum ecosystem

Avatar for Shumail Mohyuddin

Shumail Mohyuddin

November 21, 2017

More Decks by Shumail Mohyuddin

Other Decks in Technology

Transcript

  1. Lehrstuhl für Software Engineering betrieblicher Informationssysteme (sebis) Fakultät für Informatik

    Technische Universität München wwwmatthes.in.tum.de Analysis of Smart Contracts Shumail Mohyuddin
  2. Introduction to Smart Contract  Use-cases and benefits Ethereum 

    Accounts  Messages and Transactions  STARTGAS and GASPRICE  Ethereum Virtual Machine Writing Smart Contracts  Solidity  Example of a Token Contract Security & The DAO Hack Solidity pitfalls Tools in Ethereum ecosystem Outline © sebis 2 21.11.2017 - Analysis of Smart Contracts
  3. • First proposed by Nick Szabo in 1996 as “a

    smart contract is a set of promises, specified in digital form, including protocols within which the parties perform on these promises.” [1] • A smart contract is a computer protocol intended to facilitate, verify, or enforce the negotiation or performance of a contract.  In a smart contract approach, an asset or currency is transferred into a program “and the program runs this code and at some point it automatically validates a condition and it automatically determines whether the asset should go to one person or back to the other person, or whether it should be immediately refunded to the person who sent it or some combination thereof.” In the meantime, the decentralized ledger also stores and replicates the document which gives it a certain security and immutability. - Vitalik Buterin, Ethereum Founder Smart Contract © sebis 3 [1] Smart Contracts: Building Blocks for Digital Markets http://www.fon.hum.uva.nl/rob/Courses/InformationInSpeech/CDROM/Literature/LOTwinterschool2006/szabo.best.vwh.net/smart_contracts_2.html [Accessed 10.11.2017] 21.11.2017 - Analysis of Smart Contracts
  4. To create a smart contract you need: 1) Subject of

    the contract The program must have access to goods or services under contract to lock and unlock them automatically. 2) Digital signatures All the participants initiate an agreement by signing the contract with their private keys. 3) Contract terms Terms of a smart contract take the form of an exact sequence of operations. 4) Decentralized platform The smart contract is deployed to the Blockchain of this platform and distributed among the nodes. Smart Contracts © sebis 5 Smart Contracts, Explained https://cointelegraph.com/explained/smart-contracts-explained [Accessed 10.11.2017] 21.11.2017 - Analysis of Smart Contracts
  5. • Token Systems - On-blockchain token systems have many applications

    ranging from sub-currencies representing assets such as USD or gold to company stocks, individual tokens (launched usually with Initial Coin Offering - ICO) representing smart property, secure unforgeable coupons. • Identity and Reputation Systems – Residing on blockchain, a decentralized database for identities management. Example. uPort • Decentralized Autonomous Organization (DAO) – Democracy on blockchain DAO is virtual entity that exists on a blockchain, has a certain set of members or shareholders which have the right to vote in support or against the proposal. Once a predetermined amount of time and a certain number of members has voted, the proposal can be executed: the contract counts the votes and if there are enough votes it will execute the given transaction. Smart Contracts: Use-Cases © sebis 6 21.11.2017 - Analysis of Smart Contracts
  6. What can Smart Contracts provide? © sebis 7 • Autonomy

    – You’re the one making the agreement without involvement of a intermediary (a broker, lawyer or other intermediaries). • Transparency – Every state change becomes openly available. • Fairness – The source is openly available therefore the contract design can tell us if it is based on fairness or not. • Trust – Your documents are encrypted on a shared ledger. There’s no way that someone can say they lost it. • Backup – Imagine if your bank lost your savings account. On the blockchain, each and every one of your friends has your back. Your documents are duplicated many times over. • Savings – Smart contracts can save you money by removing the presence of an intermediary. • Accuracy – Automated contracts are not only faster and cheaper but also avoid the errors that come from manually filling out heaps of forms. 21.11.2017 - Analysis of Smart Contracts
  7. Introduction to Smart Contract  Use-cases and benefits Ethereum 

    Accounts  Messages and Transactions  STARTGAS and GASPRICE  Ethereum Virtual Machine Writing Smart Contracts  Solidity  Example of a Token Contract Security & The DAO Hack Solidity pitfalls Tools in Ethereum ecosystem Outline © sebis 8 21.11.2017 - Analysis of Smart Contracts
  8. Bitcoin facilitate a weak version of ‘Smart Contracts’ using its

    built-in scripting language however it has several important limitations: • Lack of Turing-completeness  Though supports a large subset of computations, it doesn’t support everything.  E.g. Loops. To avoid infinite loops. • Lack of state  Either spent or unspent. No opportunity for multi-stage contracts that allow any other internal state.  Can be used to build only simple, one-off, non-complex stateful contracts such as decentralized organizations. Scripting in Bitcoin © sebis 9 21.11.2017 - Analysis of Smart Contracts
  9. • 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. • Inspired from Bitcoin; idea was to merge together and improve upon the existing concepts and allow developers to create arbitrary consensus-based applications with support for:  Scalability  Standardization  Feature-completeness  Ease of development Ethereum © sebis 10 21.11.2017 - Analysis of Smart Contracts
  10. • Ethereum allowed that by introducing an ‘ultimate abstract foundational

    layer’:  a blockchain  with a built-in Turing-complete programming language  Anyone can write smart contracts and decentralized applications where they can create their own arbitrary rules for ownership, transaction formats and state transition functions. Ethereum © sebis 11 21.11.2017 - Analysis of Smart Contracts
  11. • The Ethereum project was bootstrapped via an ether pre-sale

    during August 2014 by fans all around the world. • "Ether" is the main internal crypto-fuel of Ethereum, and is used to pay transaction fees • Current price: $367/ETH • Current market cap: $35 Billion ( $35,249,919,945 – Nov 20, 2017) Ethereum © sebis 12 21.11.2017 - Analysis of Smart Contracts
  12. Contract Creation © sebis 13 Write Contract Code import 'A.sol';

    contract B is A{ uint public a; function B() { a = 0; } } 21.11.2017 - Analysis of Smart Contracts
  13. Contract Creation © sebis 14 import 'A.sol'; contract B is

    A{ uint public a; function B() { a = 0; } } VM Byte Code Compiler 0x6060604052 604051610450 380380610450 833981016040 528080518201 919060200150 505b5b3360... 21.11.2017 - Analysis of Smart Contracts
  14. Contract Creation © sebis 15 import 'A.sol'; contract B is

    A{ uint public a; function B() { a = 0; } } Deploy Transaction TX from data amount Compiler 0x6060604052 604051610450 380380610450 833981016040 528080518201 919060200150 505b5b3360... 21.11.2017 - Analysis of Smart Contracts
  15. Contract Creation © sebis 16 import 'A.sol'; contract B is

    A{ uint public a; function B() { a = 0; } } Compiler 0x6060604052 604051610450 380380610450 833981016040 528080518201 919060200150 505b5b3360... TX from data amount Client VM Node TX Deploy contract through transaction Push into network Contract creation request 21.11.2017 - Analysis of Smart Contracts
  16. Contract Creation © sebis 17 import 'A.sol'; contract B is

    A{ uint public a; function B() { a = 0; } } Compiler 0x6060604052 604051610450 380380610450 833981016040 528080518201 919060200150 505b5b3360... TX from data amount Client VM Node TX Deploy contract through transaction Push into network Contract Address 21.11.2017 - Analysis of Smart Contracts
  17. Contract Creation © sebis 18 import 'A.sol'; contract B is

    A{ uint public a; function B() { a = 0; } } Compiler 0x6060604052 604051610450 380380610450 833981016040 528080518201 919060200150 505b5b3360... TX from data amount Client VM Node TX Deploy contract through transaction Push into network Contract Address Client VM Node (Miner) TX Pool TX 21.11.2017 - Analysis of Smart Contracts
  18. Contract Creation © sebis 19 import 'A.sol'; contract B is

    A{ uint public a; function B() { a = 0; } } Compiler 0x6060604052 604051610450 380380610450 833981016040 528080518201 919060200150 505b5b3360... TX from data amount Client VM Node TX Deploy contract through transaction Push into network Client VM Node (Miner) TX Pool TX Contract Mined! Contract Address 21.11.2017 - Analysis of Smart Contracts
  19. Contract Creation © sebis 20 import 'A.sol'; contract B is

    A{ uint public a; function B() { a = 0; } } Compiler 0x6060604052 604051610450 380380610450 833981016040 528080518201 919060200150 505b5b3360... TX from data amount Client VM Node TX Deploy contract through transaction Push into network Client VM Node (Miner) TX Pool TX Client VM Node Contract Address 21.11.2017 - Analysis of Smart Contracts
  20. • In Ethereum, the state is made up of objects

    called “accounts”. • Each account – 20-byte address • State transitions = direct transfer of value and information between accounts. • An Ethereum account contains four field:  Nonce, a counter used to make sure each transaction can only be processed once  The account's current ether balance  The account's contract code, if present  The account's storage (empty by default) 2 Types of accounts: • Externally owned accounts (controlled by private keys) An externally owned account has no code, and one can send messages from an externally owned account by creating and signing a transaction. • Contract accounts (controlled by their contract code) When Contract account receives a message its code activates, allowing it to read and write to internal storage and send other messages or create contracts in turn Ethereum: Accounts © sebis 21 21.11.2017 - Analysis of Smart Contracts
  21. Messages in Ethereum are somewhat similar to “transactions” in Bitcoin

    but with these 3 important differences: 1. An Ethereum message can be created either by an external entity or a contract, whereas a Bitcoin transaction can only be created externally. 2. There is an explicit option for Ethereum messages to contain data. 3. The recipient of an Ethereum message, if it is a contract account, has the option to return a response; this means that Ethereum messages also encompass the concept of functions. Transaction in Ethereum refers to signed data package that stores a message to be sent from an externally owned account. It is a type of message call that are published on blockchain. A transaction may perform other message calls, but these are not transactions (sometimes referred to as internal transactions). These message calls are not published on blockchain. Ethereum: Messages & Transactions © sebis 22 { from: ..., to: "C1”, value: ..., gas: ..., data: ..., gasPrice: ..., nonce: ... } 21.11.2017 - Analysis of Smart Contracts
  22. STARTGAS In order to prevent exponential blowup and infinite loops

    in code, each transaction is required to set a limit to how many computational steps of code execution it can spawn, including both the initial message and any additional messages that get spawned during execution. That limit is STARTGAS. GASPRICE The fee to pay to the miner per computational step. What happens if transaction execution runs out of gas? • All state changes revert except for the payment of the fees • If transaction execution halts with some gas remaining, remaining portion of fees is refunded to the sender Ethereum: STARTGAS and GASPRICE © sebis 23 21.11.2017 - Analysis of Smart Contracts
  23. • An important consequence of the message mechanism is the

    "first class citizen" property of Ethereum - the idea that contracts have equivalent powers to external accounts, including the ability to send message and create other contracts. • This allows contracts to simultaneously serve many different roles: for example, one might have a member of a decentralized organization (a contract) be an escrow account (another contract) between an paranoid individual employing custom quantum-proof Lamport signatures (a third contract) and a co-signing entity which itself uses an account with five keys for security (a fourth contract). The strength of the Ethereum platform is that the decentralized organization and the escrow contract do not need to care about what kind of account each party to the contract is. Ethereum: First class citizen property © sebis 24 Ethereum, A Next-Generation Smart Contract and Decentralized Application Platform - White Paper https://github.com/ethereum/wiki/wiki/White-Paper [Accessed 10.11.2017] 21.11.2017 - Analysis of Smart Contracts
  24. Execution model specifies how the system state is altered given

    a series of byte code instructions and small tuple of environmental data. That is specified through a formal model of virtual state machine called Ethereum Virtual Machine (EVM). • A surprisingly simple execution model. • Full computational state of EVM defined by the tuple: (block_state, transaction, message, code, memory, stack, pc, gas) • block_state is global state containing all accounts including their balances and storage. • Operations have access to three types of space for storing data:  Stack – 32-byte values can be pushed/popped  Memory – an infinitely expandable byte array  Contract’s long term storage, a persistent key/value store. Ethereum Virtual Machine © sebis 25 21.11.2017 - Analysis of Smart Contracts Ethereum, A Secure Decentralised Generalised Transaction Ledger- Yellow Paper https://yellowpaper.io [Accessed 10.11.2017]
  25. • Simple stack based architecture • Word size of machine

    (and stack item) is 256-bit or 32-byte • Memory model: simple word-addressed byte array. • Maximum size of stack is 1024 • Execution of operation specified by program counter (which begins at zero). Counter is incremented by one until end of code is reached or STOP/RETURN instruction is detected. • Each operation has its own specification in terms of how it affects the tuple.  ADD pops two items off the stack and pushes their sum, reduces gas by 1 and increments program counter by 1 • Same runtime environment across all the nodes. Ethereum Virtual Machine © sebis 26 21.11.2017 - Analysis of Smart Contracts
  26. For a smart contract, we can determine the efficiency using

    these 3 metrics: 1. Gas 2. Reserved storage size 3. Bytecode size Relative Importance: Gas > storage size > bytecode size !!! Prioritise the gas cost above all else. Quantifying ‘efficiency’ © sebis 27 21.11.2017 - Analysis of Smart Contracts
  27. Introduction to Smart Contract  Use-cases and benefits Ethereum 

    Accounts  Messages and Transactions  STARTGAS and GASPRICE  Ethereum Virtual Machine Writing Smart Contracts  Solidity  Example of a Token Contract Security & The DAO Hack Solidity pitfalls Tools in Ethereum ecosystem Outline © sebis 28 21.11.2017 - Analysis of Smart Contracts
  28. Smart contracts for Ethereum can be written in following high

    level languages: 1. Solidity (a JavaScript-like language) 2. Serpent (a Python-like language) 3. Mutan (C-like) 4. LLL (Lisp-like) Writing Smart Contracts for Ethereum © sebis 29 21.11.2017 - Analysis of Smart Contracts
  29. Solidity is a contract-oriented, high-level language whose syntax is similar

    to that of JavaScript and it is designed to target the Ethereum Virtual Machine (EVM). • Statistically typed language • Provides memory centric data types • Supports inheritance, libraries and complex user-defined types Solidity © sebis 30 21.11.2017 - Analysis of Smart Contracts
  30. • bool • Integers  int / uint : Signed

    and unsigned integers of various sizes  Int8 … int256, uint8 … uint256 • address  20 byte value representing an Ethereum address. • Fixed-size byte arrays  bytes1, bytes2, … bytes32 • Dynamically sized byte arrays  string  bytes • Enums  enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } • Constant • Structs • …. Types © sebis 31 21.11.2017 - Analysis of Smart Contracts Solidity Docs, - Types http://solidity.readthedocs.io/en/develop/types.html [Accessed 10.11.2017]
  31. • Mapping  A hash table which is virtually initialized

    with every possible key mapped to a default value – a value whose byte-representation is all zero.  mapping(_KeyType => _ValueType)  e.g. mapping(address => uint256); • Function types  Internal functions  External functions  function (<parameter types>) {internal|external} [pure|constant|view|payable] [returns (<return types>)] Types © sebis 32 21.11.2017 - Analysis of Smart Contracts Solidity Docs - Types http://solidity.readthedocs.io/en/develop/types.html [Accessed 10.11.2017]
  32. Internal Functions • Internal functions can only be called inside

    the current contract (more specifically, inside the current code) because they cannot be executed outside of the context of the current contract. Calling an internal function is realized by jumping to its entry label, just like when calling a function of the current contract internally. • Called directly by function name. f() External Functions • External functions consist of an address and a function signature and they can be passed via and returned from external function calls. • Called using this.f() The public functions of the current contract can be used both as an internal and as an external function. To use f as an internal function, just use f, if you want to use its external form, use this.f Functions © sebis 33 21.11.2017 - Analysis of Smart Contracts Solidity Docs - Functions http://solidity.readthedocs.io/en/develop/contracts.html#functions [Accessed 10.11.2017]
  33. Functions Internal Function Example: contract internalFuncDemoContract { function InternalFunc() internal

    { // do something } function foo() { InternalFunc(); } } External Function Example: contract Foo { function greet(bytes rcvBytes) { // do something with the received bytes } } contract Bar { // known contract Foo constant foo = Foo(0x1234567); function doSomething() { foo.greet("Hello Sebis!"); } } © sebis 34 21.11.2017 - Analysis of Smart Contracts Solidity Docs - Functions http://solidity.readthedocs.io/en/develop/contracts.html#functions [Accessed 10.11.2017]
  34. Solidity provides different access specifiers for functions: • external External

    functions are part of the contract interface, which means they can be called from other contracts and via transactions. An external function f cannot be called internally (i.e. f() does not work, but this.f() works). • public Public functions are part of the contract interface and can be either called internally or via messages • internal Can only be accessed internally (i.e. from within the current contract or contracts deriving from it), without using this • private Private functions and state variables are only visible for the contract they are defined in and not in derived contracts Functions: Visibility © sebis 35 21.11.2017 - Analysis of Smart Contracts Solidity Docs - Visibility http://solidity.readthedocs.io/en/develop/contracts.html#visibility-and-getters [Accessed 10.11.2017]
  35. • Fallback function is the specific function in a contract

    which is triggered when the function signature doesn’t match any of the available functions in the contract. • Unnamed function • Cannot have arguments and cannot return anything • Also executed whenever the contract receives plain Ether (without data) • in order to receive Ether, the fallback function must be marked payable • The default behavior (if no fallback function is explicitly given) in these situation is to thrown an exception Fallback function © sebis 36 Solidity Docs – Fallback Function http://solidity.readthedocs.io/en/develop/contracts.html#fallback-function [Accessed 10.11.2017] 21.11.2017 - Analysis of Smart Contracts
  36. Fallback function: Example © sebis 37 contract Test { uint

    x; // This function is called for all messages sent to this contract (there is no other function) // Sending Ether to this contract will cause an exception, // because the fallback function does not have the "payable” modifier function() { x = 1; } } // This contract keeps all Ether sent to it with no way to get it back. contract Sink { function() payable { } } contract Caller { function callTest(Test test) { test.call(); // results in test.x becoming == 1. } } 21.11.2017 - Analysis of Smart Contracts
  37. • Functions defined with keyword modifier within a contract. •

    The modifier defined can be applied to a function which then executes the modifier before function is executed. • From the modifier, 2 possibilities:  throw – prevents the function from being executed  return modifier isOwner { if (msg.sender != owner) throw; } function kill() external isOwner { // only owner can do this distribute(tokens); } Function Modifiers © sebis 38 21.11.2017 - Analysis of Smart Contracts Solidity Docs – Functions Modifiers http://solidity.readthedocs.io/en/develop/contracts.html#function-modifiers [Accessed 10.11.2017]
  38. • Complex types that don’t fit in 256 bits are

    needed to be handled carefully. • Copying them can be very expensive (remember: gas!), we have to carefully think if we want them to be stored in memory (non-persistent) or storage (persistent data stored on-chain). • Such complex types thus have an additional annotation: ‘data location’ about whether it is stored on memory or storage. • There’s always a default depending on the context. • Default for  functions parameters: memory  State variables: storage • But this can be overridden by appending either keyword storage or memory to the type. • If you create a local variable in a function that references a storage variable, modifying that will result in modifying the persistent storage data which the local variable references to. • Behavior like JavaScript or C pointers. Reference Types © sebis 39 21.11.2017 - Analysis of Smart Contracts
  39. • Events allow the convenient usage of the EVM logging

    facilities • When they are called, they cause the arguments to be stored in the transaction’s log - a special data structure in the blockchain. • These logs are associated with the address of the contract. • Up to three parameters can receive the attribute indexed which will cause the respective arguments to be searched for: It is possible to filter for specific values of indexed arguments in the user interface. • Consider an event in contract: MyContract. event StudentCreated(uint indexed id, uint indexed programCode); • And now consider a function function foo() { StudentCreated(10, 7); } • You can now watch for this event. For example, the use in JavaSCript API would be like: (see next page) Events © sebis 40 21.11.2017 - Analysis of Smart Contracts Solidity Docs - Events http://solidity.readthedocs.io/en/develop/contracts.html#events [Accessed 10.11.2017]
  40. Events © sebis 41 • Example usage in Javascript for

    listening to the event StudentCreated with programCode 7. var createdEvent = myContract.StudentCreated({programCode: 7}); createdEvent.watch(function(err, result) { if (err) { console.log(err) return; } console.log("Found ", result); }) 21.11.2017 - Analysis of Smart Contracts
  41. • Defines a common list of rules for all Ethereum

    tokens to follow • Standard helps developers by empowering them to accurately predict how new tokens will function within the larger Ethereum system • ERC-20 defines six different functions for the benefit of other tokens within the Ethereum system • Allow dapps and wallets to handle tokens across multiple interfaces/dapps • Most of the current tokens follow this standard ERC20 Token Standard © sebis 42 21.11.2017 - Analysis of Smart Contracts Ethereum Wiki - ERC20 Standard https://theethereum.wiki/w/index.php/ERC20_Token_Standard [Accessed 10.11.2017]
  42. ERC20 Standard Interface © sebis 43 contract ERC20 { /*

    Get the total token supply */ function totalSupply() constant returns (uint totalSupply); /* Get the account balance of another account with address _owner */ function balanceOf(address _owner) constant returns (uint balance); /* Transfer the balance from owner's account to another account */ function transfer(address _to, uint _value) returns (bool success); /* Send _value amount of tokens from address _from to address _to */ function transferFrom(address _from, address _to, uint _value) returns (bool success); /* Allow _spender to withdraw from your account, multiple times, up to the _value amount */ function approve(address _spender, uint _value) returns (bool success); /* Returns the amount which _spender is still allowed to withdraw from _owner */ function allowance(address _owner, address _spender) constant returns (uint remaining); /* Triggered when tokens are transferred */ event Transfer(address indexed _from, address indexed _to, uint _value); /* Triggered whenever approve(address _spender, uint256 _value) is called. */ event Approval(address indexed _owner, address indexed _spender, uint _value); } 21.11.2017 - Analysis of Smart Contracts
  43. • A code library in Ethereum is similar to contract,

    declared with the library keyword instead of contract. • Libraries can have no storage of their own. • Their purpose is that they are deployed only once at a specific address and their code is reused using the DELEGATECALL • If library functions are called, their code is executed in the context of the calling contract, i.e. this points to the calling contract, and especially the storage from the calling contract can be accessed. • Calls to library functions look just like calls to functions of explicit base contracts (L.f() if L is the name of the library). • When deploying, the library will actually be deployed to a separate contract on the blockchain. • It's important to note the importance of the storage keyword in function parameters for libraries. Without this keyword, functions will create a deep copy of any arguments passed in, which is not only expensive in memory consumption but also means that modifying storage directly via library methods would not be possible- and you'd have a read-only library which isn't very useful. • One useful application of libraries is extension to the core datatypes available in language. (See the example on next page for implementation of a set) Library Code © sebis 44 21.11.2017 - Analysis of Smart Contracts Solidity Docs - Library http://solidity.readthedocs.io/en/develop/contracts.html#libraries [Accessed 10.11.2017]
  44. Library Code: Example © sebis 45 pragma solidity ^0.4.11; library

    Set { // We define a new struct datatype that will be used to // hold its data in the calling contract. struct Data { mapping(uint => bool) flags; } // Note that the first parameter is of type "storage // reference" and thus only its storage address and not // its contents is passed as part of the call. This is a // special feature of library functions. It is idiomatic // to call the first parameter 'self', if the function can // be seen as a method of that object. function insert(Data storage self, uint value) returns (bool) { if (self.flags[value]) return false; // already there self.flags[value] = true; return true; } function remove(Data storage self, uint value) returns (bool) { if (!self.flags[value]) return false; // not there
  45. Example of a Token Smart Contract (1) © sebis 46

    contract TokenContractFragment { // Balances for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; // What is the balance of a particular account? function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // Transfer the balance from owner's account to another account function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; return true; } else { return false; } } source: Ethereum Wiki – TokenContract https://theethereum.wiki/w/index.php/ERC20_Token_Standard [Accessed 10.11.2017] 21.11.2017 - Analysis of Smart Contracts
  46. Example of a Token Smart Contract (2) © sebis 47

    // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; return true; } else { return false; } } 21.11.2017 - Analysis of Smart Contracts
  47. Example of a Token Smart Contract (3) © sebis 48

    // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; return true; } } 21.11.2017 - Analysis of Smart Contracts
  48. Token Balance Assume that with the smart contract in example,

    this token has 2 token holders: • 0x1111111111111111111111111111111111111111 with a balance of 100 units • 0x2222222222222222222222222222222222222222 with a balance of 200 units The token contract's balances data structure will contain the following information: balances[0x1111111111111111111111111111111111111111] = 100 balances[0x2222222222222222222222222222222222222222] = 200 The balanceOf(...) function will return the following values: tokenContract.balanceOf(0x1111111111111111111111111111111111111111) will return 100 tokenContract.balanceOf(0x2222222222222222222222222222222222222222) will return 200 Example of a Token Smart Contract (4) © sebis 49 21.11.2017 - Analysis of Smart Contracts
  49. Transfer Token Balance If 0x1111111111111111111111111111111111111111 wants to transfer 10 tokens

    to 0x2222222222222222222222222222222222222222, 0x1111111111111111111111111111111111111111 will execute the function: tokenContract.transfer(0x2222222222222222222222222222222222222222, 10) The token contract's transfer(...) function will alter the balances data structure to contain the following information: balances[0x1111111111111111111111111111111111111111] = 90 balances[0x2222222222222222222222222222222222222222] = 210 The balanceOf(...) function will now return the following values: tokenContract.balanceOf(0x1111111111111111111111111111111111111111) will return 90 tokenContract.balanceOf(0x2222222222222222222222222222222222222222) will return 210 Example of a Token Smart Contract (5) © sebis 50 21.11.2017 - Analysis of Smart Contracts
  50. Approve And TransferFrom Token Balance If 0x1111111111111111111111111111111111111111 wants to authorise

    0x2222222222222222222222222222222222222222 to transfer some tokens to 0x2222222222222222222222222222222222222222, 0x1111111111111111111111111111111111111111 wi ll execute the function: tokenContract.approve(0x2222222222222222222222222222222222222222, 30); The approve data structure will now contain the following information: tokenContract.allowed[0x1111111111111111111111111111111111111111][0x2222222222222222222222222222222222222222] = 30 If 0x2222222222222222222222222222222222222222 wants to later transfer some tokens from 0x1111111111111111111111111111111111111111 to itself, 0x2222222222222222222222222222222222222222 executes the transferFrom(...) function: tokenContract.transferFrom(0x1111111111111111111111111111111111111111, 0x2222222222222222222222222222222222222222, 20); Example of a Token Smart Contract (6) © sebis 51 21.11.2017 - Analysis of Smart Contracts
  51. The balances data structure will be altered to contain the

    following information: tokenContract.balances[0x1111111111111111111111111111111111111111] = 70 tokenContract.balances[0x2222222222222222222222222222222222222222] = 230 And the approve data structure will now contain the following information: tokenContract.allowed[0x1111111111111111111111111111111111111111][0x2222222222222222222222222222222222222222] = 10 So 0x2222222222222222222222222222222222222222 can still spend 10 tokens from 0x1111111111111111111111111111111111111111. The balanceOf(...) function will now return the following values: tokenContract.balanceOf(0x1111111111111111111111111111111111111111) will return 70 tokenContract.balanceOf(0x2222222222222222222222222222222222222222) will return 230 Example of a Token Smart Contract (7) © sebis 52 21.11.2017 - Analysis of Smart Contracts
  52. Introduction to Smart Contract  Use-cases and benefits Ethereum 

    Accounts  Messages and Transactions  STARTGAS and GASPRICE  Ethereum Virtual Machine Writing Smart Contracts  Solidity  Example of a Token Contract Security & The DAO Hack Solidity pitfalls Tools in Ethereum ecosystem Outline © sebis 53 21.11.2017 - Analysis of Smart Contracts
  53. • Solidity requires taking extreme care of minor details. Always

    know what you are doing. • Always test the gas cost of methods. Don’t presume you’ll always be allocated enough. • The DAO Hack:  Attacker managed to drain more than 3.6 million ether. ($55 million at that time)  Attacker found a loophole in regular splitDAO function so that they could use the same DAO tokens over and over again.  Combined 2 exploits Security & DAO Attack © sebis 54 21.11.2017 - Analysis of Smart Contracts
  54. The DAO Hack © sebis 55 function splitDAO( uint _proposalID,

    address _newCurator ) noEther onlyTokenholders returns(bool _success) { // ... // Burn DAO Tokens Transfer(msg.sender, 0, balances[msg.sender]); // be nice, and get his reward withdrawRewardFor(msg.sender); totalSupply -= balances[msg.sender]; balances[msg.sender] = 0; paidOut[msg.sender] = 0; return true; } // ... function transfer(address _to, uint256 _value) returns(bool success) { /* ... */ } Analysis of the DAO exploit http://hackingdistributed.com/2016/06/18/analysis-of-the-dao-exploit/ [Accessed 10.11.2017] 21.11.2017 - Analysis of Smart Contracts
  55. The DAO Hack © sebis 56 function splitDAO( uint _proposalID,

    address _newCurator ) noEther onlyTokenholders returns(bool _success) { // ... // Burn DAO Tokens Transfer(msg.sender, 0, balances[msg.sender]); // be nice, and get his reward withdrawRewardFor(msg.sender); totalSupply -= balances[msg.sender]; balances[msg.sender] = 0; paidOut[msg.sender] = 0; return true; } // ... function transfer(address _to, uint256 _value) returns(bool success) { /* ... */ } event Transfer(address indexed _from, address indexed _to, uint256 _amount); // ... function withdrawRewardFor(address _account) noEther internal returns(bool _success) { if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account]) throw; uint reward = (balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account]; if (!rewardAccount.payOut(_account, reward)) // !!!!! vulnerable throw; paidOut[_account] += reward; return true; } // ... function payOut(address _recipient, uint _amount) returns(bool) { if (msg.sender != owner || msg.value > 0 || (payOwnerOnly && _recipient != owner)) throw; if (_recipient.call.value(_amount)()) { // !!!!! Vulnerable – calls the fallback func PayOut(_recipient, _amount); return true; } else { return false; } } Analysis of the DAO exploit http://hackingdistributed.com/2016/06/18/analysis-of-the-dao-exploit/ [Accessed 10.11.2017] 21.11.2017 - Analysis of Smart Contracts
  56. You may notice that, even after overwhelming the stack and

    executing many more malicious splits than was required, the hacker would have their balance zeroed out by the code at the end of splitDAO: So how did attacker get around this? Thanks to the ability to transfer DAO tokens, he didn't really need to! All he had to do was call the DAO's helpful transfer function at the top of his stack, from his malicious function The DAO Hack © sebis 57 function splitDAO( .... withdrawRewardFor(msg.sender); // be nice, and get his rewards totalSupply -= balances[msg.sender]; balances[msg.sender] = 0; paidOut[msg.sender] = 0; return true; } function transfer(address _to, uint256 _amount) noEther returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0) { balances[msg.sender] -= _amount; balances[_to] += _amount; ... 21.11.2017 - Analysis of Smart Contracts
  57. • The attacker calls splitDAO, which calls withdrawRewardFor and then

    payOut. They provide extra gas in order to recursively run more function calls than TheDAO intended. payOut reads the splitter's balance and attempts to refund their ether to exit them from the DAO. The DAO Hack © sebis 58 Image rights: https://github.com/pospi/talk-solidity-blockchain-intro/tree/master/res - used with permission 21.11.2017 - Analysis of Smart Contracts
  58. The DAO Hack © sebis • splitDAO is public. •

    So the attacker can use a fallback function in their own contract (fired when payOut runs _recipient.call.value(_amount)()) to call splitDAO while the original splitDAO call is still running... 59 Image rights: https://github.com/pospi/talk-solidity-blockchain-intro/tree/master/res - used with permission 21.11.2017 - Analysis of Smart Contracts
  59. The DAO Hack © sebis • splitDAO (2) calls withdrawRewardFor

    calls payOut... • The original call (1) to splitDAO has still not run balances[msg.sender] = 0; so payOut transfers the same balance back to the attacking contract as before... 60 Image rights: https://github.com/pospi/talk-solidity-blockchain-intro/tree/master/res - used with permission 21.11.2017 - Analysis of Smart Contracts
  60. The DAO Hack © sebis • This keeps on going

    but attacker is careful enough to stop before the EVM stack depth limit is reached, as this would cause everything to roll back (EVM exceptions cause all state changes to be rolled back) 61 Image rights: https://github.com/pospi/talk-solidity-blockchain-intro/tree/master/res - used with permission 21.11.2017 - Analysis of Smart Contracts
  61. The DAO Hack © sebis • Each payOut function will

    eventually finalize and return, and splitDAO will call the Transfer event each time in order to transfer its internal tokens over to the new split DAO. • it should have called the transfer function instead. 62 Image rights: https://github.com/pospi/talk-solidity-blockchain-intro/tree/master/res - used with permission 21.11.2017 - Analysis of Smart Contracts
  62. The DAO Hack © sebis They can then move these

    tokens back into the original account and start the process all over again. 63 Image rights: https://github.com/pospi/talk-solidity-blockchain-intro/tree/master/res - used with permission 21.11.2017 - Analysis of Smart Contracts
  63. The DAO Hack © sebis Without transfer being called to

    correctly finalise the split, the attacker is free to move their DAO tokens into a secondary contract at the time their inner call to splitDAO returns, leaving the DAO thinking the recipient's tokens have been correctly moved across. 64 Image rights: https://github.com/pospi/talk-solidity-blockchain-intro/tree/master/res - used with permission 21.11.2017 - Analysis of Smart Contracts
  64. • Ensure you update your contract's own internal state before

    interacting with any external addresses. • If these interactions fail, handle the effect in a way which does not interfere with any other address being processed. • Presume any methods in your contract other than internal and private ones will be called by contracts other than those you expect. • Presume any call to an externally accessible contract method you define may run out of gas and fail. • Never presume that an address implies a user. An address does not guarantee a real person. • Use .transfer or .send instead of .call wherever possible. Even then, ensure you handle failures correctly, and again, update your contract's own state first.  https://ethereum.stackexchange.com/questions/6470/6474#6474 • Using .transfer is more safe than .send because send is low-level counter part of transfer. If the execution fails, the current contract will not stop with an exception, but send will return false. Whereas, transfer throws an exception in case of failure. The DAO Hack: Takeaway © sebis 65 21.11.2017 - Analysis of Smart Contracts
  65. Introduction to Smart Contract  Use-cases and benefits Ethereum 

    Accounts  Messages and Transactions  STARTGAS and GASPRICE  Ethereum Virtual Machine Writing Smart Contracts  Solidity  Example of a Token Contract Security & The DAO Hack Solidity Pitfalls Tools in Ethereum ecosystem Outline © sebis 66 21.11.2017 - Analysis of Smart Contracts
  66. Private Information and Randomness • Everything you use in a

    smart contract is publicly visible, even local variables and state variables marked private. • Using random numbers in smart contracts is quite tricky if you do not want miners to be able to cheat. Gas Limit and Loops • Loops that do not have a fixed number of iterations, for example, loops that depend on storage values, have to be used carefully: Due to the block gas limit, transactions can only consume a certain amount of gas. • Either explicitly or just due to normal operation, the number of iterations in a loop can grow beyond the block gas limit which can cause the complete contract to be stalled at a certain point. • This may not apply to constant functions that are only executed to read data from the blockchain Callstack Depth • External function calls can fail any time because they exceed the maximum call stack of 1024. • In such situations, Solidity throws an exception • Note that .send() does not throw an exception if the call stack is depleted but rather returns false in that case. The low-level functions .call(), .callcode() and .delegatecall() behave in the same way Solidity Pitfalls © sebis 67 21.11.2017 - Analysis of Smart Contracts Solidity Docs - Considerations http://solidity.readthedocs.io/en/develop/security-considerations.html [Accessed 10.11.2017]
  67. Re-Entrancy • Any interaction from a contract (A) with another

    contract (B) and any transfer of Ether hands over control to that contract (B). This makes it possible for B to call back into A before this interaction is completed. • Ether transfer always includes code execution, so the recipient could be a contract that calls back into withdraw. This would let it get multiple refunds and basically retrieve all the Ether in the contract Solidity Pitfalls © sebis 68 pragma solidity ^0.4.0; // THIS CONTRACT CONTAINS A BUG - DO NOT USE contract Fund { /// Mapping of ether shares of the contract. mapping(address => uint) shares; /// Withdraw your share. function withdraw() { if (msg.sender.send(shares[msg.sender])) shares[msg.sender] = 0; } } 21.11.2017 - Analysis of Smart Contracts
  68. To avoid re-entrancy, you can use the Checks-Effects-Interactions pattern as

    outlined further below: Solidity Pitfalls: Re-Entrancy © sebis 69 pragma solidity ^0.4.11; contract Fund { /// Mapping of ether shares of the contract. mapping(address => uint) shares; /// Withdraw your share. function withdraw() { var share = shares[msg.sender]; shares[msg.sender] = 0; msg.sender.transfer(share); } } 21.11.2017 - Analysis of Smart Contracts
  69. Introduction to Smart Contract  Use-cases and benefits Ethereum 

    Accounts  Messages and Transactions  STARTGAS and GASPRICE  Ethereum Virtual Machine Writing Smart Contracts  Solidity  Example of a Token Contract Security & The DAO Hack Solidity Pitfalls Tools in Ethereum ecosystem Outline © sebis 70 21.11.2017 - Analysis of Smart Contracts
  70. • Geth  Geth is the official client software provided

    by the Ethereum Foundation. It is written in the Go programming language  https://github.com/ethereum/go-ethereum • Web3.js  Web3.js is a javascript library which can be used to interact with a node. Since it is a javascript library, you can use it to build web based dApps.  https://github.com/ethereum/web3.js/ • Truffle/Embark  Just like you have frameworks for web application development such as Ruby on Rails, Python/Django etc, Truffle and Embark are the two most popular frameworks used to develop dapps. They abstract away lot of the complexities of compiling and deploying your contract on the blockchain.  http://truffleframework.com  https://github.com/iurimatias/embark-framework Some Tools and Technologies in Ethereum ecosystem © sebis 71 21.11.2017 - Analysis of Smart Contracts
  71. • Metamask  MetaMask is a bridge that allows you

    to visit the distributed web of tomorrow in your browser today. It allows you to run Ethereum dApps right in your browser without running a full Ethereum node.  https://metamask.io • ENS  Ethereum Naming System is the DNS for the Ethereum world. Just like you map an IP address to a human readable name, you can map any Ethereum contract or wallet address to a human readable name  http://ens.domains • Whisper  Whisper is a communication protocol for DApps to communicate with each other  https://github.com/ethereum/wiki/wiki/Whisper Some Tools and Technologies in Ethereum ecosystem © sebis 72 21.11.2017 - Analysis of Smart Contracts
  72. Lets write a simple smart contract that has the following

    behavior: • The smart contract is written for distributing 1000 tokens. • The smart contract is called SebisContract • The owner who originally deploys the smart contract on blockchain is called owner and 1000 tokens are stored in owner’s account. • Anyone who wants to get these tokens, can send a transaction with some Wei to this smart contract’s transfer function. • On successful transaction, he/she gets the tokens equal to the number of Wei originally sent, provided that there’s enough balance in owner’s account. • In case of a failure, the transaction is rolled back. • Use the online Solidity compiler located at http://remix.ethereum.org for compiling the code on next 2 page and exhibiting the behavior of Smart Contract Another Example of a simple Smart Contract © sebis 171103 Matthes Deutsche Folienvorlage (breit) 73
  73. Smart Contract Code in Solidity © sebis 74 21.11.2017 -

    Analysis of Smart Contracts pragma solidity ^0.4.11; contract SebisContract { address public owner; mapping (address => uint) balances; event SuccessfulTransaction ( address _from, address _to, uint256 _amount ); modifier ifFunds(address _to, uint _value) { if (balances[owner] <= _value) { throw; } _; } function SebisContract() { owner = msg.sender; balances[owner] = 1000; }
  74. Smart Contract Code in Solidity © sebis 75 21.11.2017 -

    Analysis of Smart Contracts function getBalance(address _user) constant returns (uint _balances) { return balances[_user]; } // we know who's sending transaction by msg.sender and value by msg.value function getTokens() ifFunds(msg.sender, msg.value) payable returns (bool success) { balances[owner] -= msg.value; balances[msg.sender] += msg.value; SuccessfulTransaction(owner, msg.sender, msg.value); return true; } }
  75. Special Thanks to Patrick Holl (Research Associate, SEBIS TU München)

    for continuous support and mentoring. Acknowledgement © sebis 76 21.11.2017 - Analysis of Smart Contracts
  76. • Ethereum, A Next-Generation Smart Contract and Decentralized Application Platform

    (White Paper) https://github.com/ethereum/wiki/wiki/White-Paper • Solidity, Developer docs http://solidity.readthedocs.io/en/develop/ • Ethereum Yellow Paper http://yellowpaper.io • Smart Contracts: The Blockchain Technology That Will Replace Lawyers https://blockgeeks.com/guides/smart-contracts/ • The Ethereum Wiki https://theethereum.wiki/w/index.php/Main_Page • ERC20 Token https://theethereum.wiki/w/index.php/ERC20_Token_Standard • Analysis of DAO Exploit http://hackingdistributed.com/2016/06/18/analysis-of-the-dao-exploit/ • Ethereum Stackexchange http://ethereum.stackexchange.com • Etherscan, Ethereum Block Explorer https://etherscan.io • Contracts in Bitcoin, https://en.bitcoin.it/wiki/Contract • Dissecting Ponzi schemes on Ethereum: identification, analysis, and impact by Massimo Bartoletti, Salvatore Carta, Tiziana Cimoli, Roberto Saia https://arxiv.org/pdf/1703.03779.pdf • Ethereum Improvement Proposal https://github.com/ethereum/EIPs References © sebis 77 21.11.2017 - Analysis of Smart Contracts
  77. Technische Universität München Fakultät für Informatik Lehrstuhl für Software Engineering

    betrieblicher Informationssysteme Boltzmannstraße 3 85748 Garching bei München Tel +49.89.289. Fax +49.89.289.17136 wwwmatthes.in.tum.de Florian Matthes Prof. Dr. 17132 [email protected] Inhaber des Lehrstuhls