SlideShare une entreprise Scribd logo
1  sur  204
Blockchain Academy
A community for technologists looking to learn more
about Crypto and Blockchain technology
Blockchain AcademyLeonid Beder April 24, 2018
About Me
April 24, 2018Blockchain Academy
leonid@orbs.com PGP Key:
leonid@kik.com D749 1F09 3721 0A31 72B5
@LeonidBeder DBF3 7F35 EBC3 E4B2 44B4
@lbeder
Leonid Beder
Agenda
1.Introduction to smart contracts
2.Introduction to Solidity
3.(In)famous bugs and issues
4.Additional tools and techniques
Introduction to
Smart Contracts
Leonid Beder Blockchain Academy
Nick Szabo, Smart Contracts: Building Blocks for Digital Markets, 1996
“A smart contract is a set of promises, specified in
digital form, including protocols within which the parties
perform on these promises.”
What is a Smart
Contract?
“A smart contract is a set of promises, specified in
digital form, including protocols within which the parties
perform on these promises.”
• Example: a sales contract.
• The seller promises to deliver the goods in exchange for the buyer.
• The buyer promises to pay the desired price.
What is a Smart
Contract?
“A smart contract is a set of promises, specified in
digital form, including protocols within which the
parties perform on these promises.”
• Digital form means that the contract has to be programmed in machine
readable code.
What is a Smart
Contract?
“A smart contract is a set of promises, specified in
digital form, including protocols within which the
parties perform on these promises.”
• For example, say the parties agree that the purchased good is to be paid in
Bitcoin. The obvious protocol of choice would then be the Bitcoin protocol
(Bitcoin scripting language).
What is a Smart
Contract?
“A smart contract is a set of promises, specified in
digital form, including protocols within which the parties
perform on these promises.”
Popular
Implementations
• Ethereum implements a (nearly) Turing-complete language on its
blockchain, a prominent smart contract framework.
• Bitcoin implements a Turing-incomplete Script language that
allows the creation of limited smart contracts, such as:
multisignature accounts, payment channels, escrows, time locks,
atomic cross-chain trading, oracles, etc.
Introduction to
Solidity
Leonid Beder Blockchain Academy
What is Solidity?
• Solidity is an OOP language for writing smart contracts (mostly?) on Ethereum
• It was originally developed by Dr. Gavin Wood, Dr. Christian Reitwiessner,
Alex Beregszaszi, Liana Husikyan, Yoichi Hirai and several former Ethereum
core contributors.
Dr. Gavin Wood Dr. Christian Reitwiessner Alex Beregszaszi Yoichi HiraiLiana Husikyan
An example
• Let’s start with a simple example of a smart contract named Greeter, which will:
• Initialized with a greeting message (e.g., “Hello World!”).
• Provide a method to read/query the greeting message.
• Provide a method to write/modify the greeting message.
• For this talk, we will use the official online Remix IDE:
https://remix.ethereum.org.
• You can find all the code here: https://github.com/blockchain-academy/how-
not-to-destroy-your-ether
Solidity version to use
Contract name
public state variable of type string
Constructor, receiving a single
argument of type string
public method, receiving a single
argument of type string
Fundamentals: Execution Model
• Every smart contract needs to be compiled and deployed to the network.
• Every transaction or message call in Ethereum is executed by the Ethereum Virtual
Machine (EVM) on every Ethereum node (miner or a just a full node).
• Since that every smart contract is running on the EVM, and every single operation is
actually executed simultaneously by every node in the network - there should be a
mechanism to limit the resources used by each contract.
• Such mechanism is implemented in Ethereum via gas:
• Every operation has a deterministic (yet, hard to sometimes predict) cost measured in
quantifying units of gas.
• Every gas unit consumed by a transaction must be paid for in Ether, based on a
gas/Ether price which is set by the sender of the original sender of transaction.
Fundamentals: Execution Model
• Transactions have also a gas limit parameter that is an upper
bound on how much gas the transaction can consume.
❏Why is the gas limit parameter needed?
❏There is also a block gas limit (i.e., an upper bound to the total
amount of gas consumed by all the transaction in a block. Why
is it needed?
❏The protocol allows the miner of a block to adjust the block
gas limit by a factor of 1/1024 (0.0976%) in either direction.
Fundamentals: Special Variables and
Functions
• There are special variables and functions which always exist in
the global namespace.
• For our talk, we (mostly) need to know:
• msg.sender (address): sender of the message (current call).
• msg.value (uint): number of wei sent with the message.
Fundamentals: Function and State
Variables Visibility
• In Solidity, there are four types of visibilities:
• For functions:
• external: can be called externally from other accounts/contracts.
• public (default): can be called by everyone.
• internal: can only be called internally.
• private: can only be called internally and only from the contract itself.
Fundamentals: Function and State
Variables Visibility
• For state variables:
• external: N/A
• public: can be accessed by everyone.
• internal (default): can only be accessed internally.
• private: can only be accessed internally and only from the
contract itself.
Fundamentals: Function
Modifiers• Modifiers can be used to modify the behaviour of functions.
• For example, a very common use case is by checking a pre- or post-conditions.
• They are very similar to before/after/around filters/hooks in other programming
languages.
• For example, let’s augment our Greeter smart contract to:
• Have an owner (in our case, the deployer of the smart contract).
• Make sure than only the owner can further modify the greeting.
Fundamentals: Fallback
Function
• A smart contract can have exactly one unnamed function.
• It’s executed on a call to the contract if none of the other
functions match the given function identifier.
• For example, when Ether is being transferred to the contract.
Fundamentals: Payable
ModifierIn order to receive Ether, every function must be marked as payable:
• When sending Ether as part of a function call, the function must be
marked as payable.
• When sending Ether directly to a contract, its fallback function must be
marked as payable.
If no such function exists, the contract cannot receive Ether through regular
transactions.
Leonid Beder
Blockchain Academy
Let’s
destroy
some Ether!
Leonid Beder
Blockchain Academy
Example #1
Bugs: Overflow/Underflow
• Solidity can handle (up to) 256 bit numbers (values up to 2²⁵⁶-1).
• Overflow is when a number gets incremented above its maximum value:
• Adding 1 to 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF results in 0.
• Underflow is the inverse case, when the number is unsigned,
decrementing will underflow the number:
• Subtracting 1 from 0x000000000000000000000000000000000000
results in 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF.
Mitigation #1: Test for
Correctness• Test for correctness before performing any operations:
Mitigation #2: SafeMath
• Always use the (de-facto) standard SafeMath library.
• You can it and many other nice, relatively stable, smart contracts
in OpenZeppelin’s Github repo:
https://github.com/OpenZeppelin/zeppelin-solidity
Leonid Beder
Example #2
Mitigation: Always Define
Visibility!
• Always define visibility explicitly.
• Limit function visibility when possible.
Use Case: Parity “hack” #1
• TL;DR: A vulnerability was found on the Parity Multisig
Wallet version 1.5+, that allowed an attacker to steal over
150,000 Ether ($30,000,000, at the time; $105,000,000 today
[ETH/USD 700]).
• A white hat hacker group subsequently drained other Parity
wallets to protect funds worth 377,105 ETH ($85,000,000, at
the time; ~$264,000,000 today [ETH/USD 700]).
Use Case: Parity “hack” #1
• So what’s happened there?
• You can find the original code here:
https://raw.githubusercontent.com/paritytech/parity/4d08e7b0ae
c46443bf26547b17d10cb302672835/js/src/contracts/snippets/
enhanced-wallet.sol
Use Case: Parity “hack” #1
But, wait… how does WalletLibrary work with the Wallet
contract?
_walletLibrary.delegatecall(msg.data)
⇕
_walletLibrary.func(args)
Use Case: Parity “hack” #1
• The attacker exploited this and simply changed the contract’s
m_owners state variable to a list containing only their address,
and requiring just one confirmation to execute any transaction:
https://etherscan.io/tx/0x9dbf0326a03a2a3719c27be4fa69aacc
9857fd231a8d9dcaede4bb083def75ec
`
Mitigation
• Complexity is a vulnerability. Keep It Simple Stupid.
• Always define visibility explicitly.
• Don’t extract the constructor logic into the library contract.
Avoid premature optimizations!
• Don’t use delegatecall as a catch-all forwarding mechanism.
Mitigation: Parity Developers’
Fix
• Parity has quickly fixed the issue here:
https://github.com/paritytech/parity/commit/e06a1e8dd9cfd8bf5
d87d24b11aee0e8f6ff9aeb
Leonid Beder
Example #3
Use Case: Rubixi
• Rubixi is a contract which implements a pyramid scheme (allegedly).
• Investors can deposit funds.
• The owner can collect all of the funds.
Mitigation
• Well, for starters, try not to misname functions…
• Stay vigilant! The scammers are getting better and better…
• Starting from 0.4.22, you can now use the safe constructor
method instead:
Leonid Beder
Example #4
“It will be like a taco inside a taco
within a Taco Bell that’s inside a KFC,
within a bowl, that’s inside your
brain...” / South Park S14E10
Mitigation #1: Checks-Effects-
InteractionsChecks-Effects-Interactions Pattern:
1.Perform checks (who called the function, are the arguments in range,
did they send enough Ether, does the person have tokens, etc.).
1.If all checks passed, effects to the state variables of the current
contract should be made.
1.Lastly, perform any interaction with other accounts/contracts.
Mitigation #2: Avoid call.value()()
When sending Ether, be aware of the relative tradeoffs between the use of:
1.address.call.value()(): will send the provided Ether and trigger code
execution given all available gas.
1.address.send(): will send the provided Ether and trigger code execution given
a limited stipend of 2,300 gas.
1.address.transfer(): is equivalent to require(address.send()). It will
automatically revert if the send fails.
Use Case: “The DAO”
• “The DAO” is the name of a particular DAO (Decentralized Autonomous
Organization), conceived of and programmed by the team behind German
startup Slock.it a company building "smart locks" that let people share
their things (cars, boats, apartments) in a decentralized version of Airbnb.
• It was launched on 30th April, 2016, with a 28-day funding window.
• It was the largest crowdfunding in history, having raised over
$150,000,000 from more than 11,000 enthusiastic members.
Use Case: “The DAO”
• On 18th June, the attacker started to drain “The DAO” using a
(relatively) sophisticated reentrancy attack.
• The attacker has managed to drain more than 3,600,000 Ether
($72,000,000, at that time; astounding $2,520,000,000 today
[ETH/USD 700]).
• How did the Ethereum community responded?
Leonid Beder
Example #5
Leonid Beder
Example #6
“Alternative” Ether Transfer
• In addition to the regular means to send Ether (e.g., call, send/transfer), there are two
more ways which will bypass the fallback function:
1.selfdestruct: The only possibility that code is removed from the blockchain is when a
contract at that address performs the selfdestruct operation.
• If the receiving address is a contract, its fallback function does not get executed.
1.As a miner, set the target address as the coinbase address in order for it to receive
block mining awards.
Mitigation: Beware of
Assumptions
• Never use a contract’s balance as a guard.
• In general, be mindful of language/framework specific features and updates.
1.Beware of compiler optimizations bugs and test accordingly
2.Beware of compiler specific bugs and always use strict compiler version.
3.Beware of potential miners’ intervention (e.g., front-running, chain re-org, etc.).
• 0.4.21 compiler version... Ethereum is still an alpha.
(Similar) Use Case: Parity
“hack” #2
TL;DR:
(Similar) Use Case: Parity
“hack” #2• Approximately 513,000 ETH ($154,000,000, at that time; $359,100,000
today [ETH/USD 700]) has been locked in the affected contracts.
• No funds were “stolen” per-say; only made unreachable, by an accident.
• There are few proposals for methods to restore the lost funds (e.g., the
very recent EIP999) and even for a new ERP (Ethereum Recovery
Proposal) governance model, but it’s unlikely to happen any time soon.
(Similar) Use Case: Parity
“hack” #2
So what’s happened there?
(Similar) Use Case: Parity
“hack” #2• The WalletLibrary contract contains a state variables that it expects to be
shadowed by the calling contract’s own state.
• Once deployed, the WalletLibrary contract is simply uninitialized, so
m_numOwners is 0.
• If the WalletLibrary isn’t executed in a Wallet contract’s context,
m_numOwners is 0, allowing anyone to call methods that this modifier guards,
one of which is initWallet.
(Similar) Use Case: Parity
“hack” #2• So what did devops199 has done exactly?
• Nov 06, 2017 14:33:47 (UTC):
https://etherscan.io/tx/0x05f71e1b2cb4f03e547739db15d080fd30c989eda
04d37ce6264c5686e0722c9
• Called the initWallet method against the deployed WalletLibrary.
• Set 0xae7168deb525862f4fee37d987a971b385b96952 as its only
owner.
(Similar) Use Case: Parity
“hack” #2• Nov 06, 2017 15:25:21 (UTC) (51 minutes from previous tx):
https://etherscan.io/tx/0x47f7cff7a5e671884629c93b368cb18f58a993f4
b19c2a53a8662e3f1482f690
• Called the kill method with
0xae7168deb525862f4fee37d987a971b385b96952 as the
beneficiary address.
(joke account)
Leonid Beder
Example #7
Mitigation #1: Favor Pull over
Push• Always remembers that you’re not only interacting with human
beings, but also with other contracts.
• Favor pull over push for external calls.
Mitigation #2: Ignore
Contracts• It’s usually not recommended or desired, but it’s also possible to opt-out
from interacting with contract using the following check:
Leonid Beder
Tools!
Testing and Development
• Truffle (http://truffleframework.com/) is the most popular development
framework for Ethereum.
• Reuse existing libraries, such as OpenZeppelin
(https://github.com/OpenZeppelin/zeppelin-solidity)
• Ganache (http://truffleframework.com/ganache/) is a tool which allows you
to quickly fire up a personal Ethereum blockchain which you can use to run
tests, execute commands, and inspect state while controlling how the chain
operates.
Testing and Development
• solidity-coverage (https://github.com/sc-forks/solidity-coverage)
code coverage for Solidity smart-contracts.
… and even that isn’t enough!
Remix
• Remix (https://remix.ethereum.org) performs static analysis to
your code and is able to spot many bugs:
Oyente
• Oyente (https://oyente.melon.fund) another analysis tool for
smart contracts with both CLI and a GUI similar interface to
Remix.
• At the moment, the latest supported compiler is 0.4.17.
Mythril
• Mythril (https://github.com/b-mueller/mythril) is a security
analysis tool for Ethereum smart contracts.
Securify
• Securify (https://securify.ch) is a static analysis tool for Smart
Contracts.
• At the moment, the latest supported compiler is 0.4.16.
Blockchain AcademyLeonid Beder
Questions?
April 24, 2018
Blockchain AcademyLeonid Beder April 24, 2018
Blockchain AcademyLeonid Beder April 24th, 2018
Thank You!

Contenu connexe

Tendances

Stefano Maestri - Blockchain and smart contracts, what they are and why you s...
Stefano Maestri - Blockchain and smart contracts, what they are and why you s...Stefano Maestri - Blockchain and smart contracts, what they are and why you s...
Stefano Maestri - Blockchain and smart contracts, what they are and why you s...Codemotion
 
Introduction to Ethereum
Introduction to EthereumIntroduction to Ethereum
Introduction to EthereumArnold Pham
 
Blockchain for Developers
Blockchain for DevelopersBlockchain for Developers
Blockchain for DevelopersShimi Bandiel
 
A research-oriented introduction to the cryptographic currencies (starting wi...
A research-oriented introduction to the cryptographic currencies (starting wi...A research-oriented introduction to the cryptographic currencies (starting wi...
A research-oriented introduction to the cryptographic currencies (starting wi...vpnmentor
 
Learning Solidity
Learning SolidityLearning Solidity
Learning SolidityArnold Pham
 
Eclipsecon Europe: Blockchain, Ethereum and Business Applications
Eclipsecon Europe: Blockchain, Ethereum and Business ApplicationsEclipsecon Europe: Blockchain, Ethereum and Business Applications
Eclipsecon Europe: Blockchain, Ethereum and Business ApplicationsMatthias Zimmermann
 
Kriptovaluták, hashbányászat és okoscicák
Kriptovaluták, hashbányászat és okoscicákKriptovaluták, hashbányászat és okoscicák
Kriptovaluták, hashbányászat és okoscicákhackersuli
 
Smart contracts and applications part II
Smart contracts and applications   part IISmart contracts and applications   part II
Smart contracts and applications part IIvpnmentor
 
Blockchain and smart contracts, what they are and why you should really care ...
Blockchain and smart contracts, what they are and why you should really care ...Blockchain and smart contracts, what they are and why you should really care ...
Blockchain and smart contracts, what they are and why you should really care ...maeste
 
The Ethereum Geth Client
The Ethereum Geth ClientThe Ethereum Geth Client
The Ethereum Geth ClientArnold Pham
 
Blockchain Programming
Blockchain ProgrammingBlockchain Programming
Blockchain ProgrammingRhea Myers
 
OWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contracts
OWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contractsOWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contracts
OWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contractsOWASP
 
EDCON 2017 sharing @Taipei Ethereum Meetup
EDCON 2017 sharing @Taipei Ethereum Meetup EDCON 2017 sharing @Taipei Ethereum Meetup
EDCON 2017 sharing @Taipei Ethereum Meetup Chang-Wu Chen
 
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)Nicholas Lin
 
Concept of BlockChain & Decentralized Application
Concept of BlockChain & Decentralized ApplicationConcept of BlockChain & Decentralized Application
Concept of BlockChain & Decentralized ApplicationSeiji Takahashi
 
Crypto Wallets: A Technical Perspective (Nakov at OpenFest 2018)
Crypto Wallets: A Technical Perspective (Nakov at OpenFest 2018)Crypto Wallets: A Technical Perspective (Nakov at OpenFest 2018)
Crypto Wallets: A Technical Perspective (Nakov at OpenFest 2018)Svetlin Nakov
 
Bitcoin, the Blockchain, and Open Source
Bitcoin, the Blockchain, and Open SourceBitcoin, the Blockchain, and Open Source
Bitcoin, the Blockchain, and Open SourceAll Things Open
 

Tendances (20)

Stefano Maestri - Blockchain and smart contracts, what they are and why you s...
Stefano Maestri - Blockchain and smart contracts, what they are and why you s...Stefano Maestri - Blockchain and smart contracts, what they are and why you s...
Stefano Maestri - Blockchain and smart contracts, what they are and why you s...
 
Explaining Ethereum
Explaining EthereumExplaining Ethereum
Explaining Ethereum
 
Introduction to Ethereum
Introduction to EthereumIntroduction to Ethereum
Introduction to Ethereum
 
Blockchain for Developers
Blockchain for DevelopersBlockchain for Developers
Blockchain for Developers
 
A research-oriented introduction to the cryptographic currencies (starting wi...
A research-oriented introduction to the cryptographic currencies (starting wi...A research-oriented introduction to the cryptographic currencies (starting wi...
A research-oriented introduction to the cryptographic currencies (starting wi...
 
Learning Solidity
Learning SolidityLearning Solidity
Learning Solidity
 
Eclipsecon Europe: Blockchain, Ethereum and Business Applications
Eclipsecon Europe: Blockchain, Ethereum and Business ApplicationsEclipsecon Europe: Blockchain, Ethereum and Business Applications
Eclipsecon Europe: Blockchain, Ethereum and Business Applications
 
Kriptovaluták, hashbányászat és okoscicák
Kriptovaluták, hashbányászat és okoscicákKriptovaluták, hashbányászat és okoscicák
Kriptovaluták, hashbányászat és okoscicák
 
Smart contracts and applications part II
Smart contracts and applications   part IISmart contracts and applications   part II
Smart contracts and applications part II
 
Blockchain and smart contracts, what they are and why you should really care ...
Blockchain and smart contracts, what they are and why you should really care ...Blockchain and smart contracts, what they are and why you should really care ...
Blockchain and smart contracts, what they are and why you should really care ...
 
Tmc mastering bitcoins ppt
Tmc mastering bitcoins pptTmc mastering bitcoins ppt
Tmc mastering bitcoins ppt
 
The Ethereum Geth Client
The Ethereum Geth ClientThe Ethereum Geth Client
The Ethereum Geth Client
 
Blockchain Programming
Blockchain ProgrammingBlockchain Programming
Blockchain Programming
 
Bitcoins Math
Bitcoins MathBitcoins Math
Bitcoins Math
 
OWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contracts
OWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contractsOWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contracts
OWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contracts
 
EDCON 2017 sharing @Taipei Ethereum Meetup
EDCON 2017 sharing @Taipei Ethereum Meetup EDCON 2017 sharing @Taipei Ethereum Meetup
EDCON 2017 sharing @Taipei Ethereum Meetup
 
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
 
Concept of BlockChain & Decentralized Application
Concept of BlockChain & Decentralized ApplicationConcept of BlockChain & Decentralized Application
Concept of BlockChain & Decentralized Application
 
Crypto Wallets: A Technical Perspective (Nakov at OpenFest 2018)
Crypto Wallets: A Technical Perspective (Nakov at OpenFest 2018)Crypto Wallets: A Technical Perspective (Nakov at OpenFest 2018)
Crypto Wallets: A Technical Perspective (Nakov at OpenFest 2018)
 
Bitcoin, the Blockchain, and Open Source
Bitcoin, the Blockchain, and Open SourceBitcoin, the Blockchain, and Open Source
Bitcoin, the Blockchain, and Open Source
 

Similaire à How to not Destroy Millions in Smart Contracts

Building Apps with Ethereum Smart Contract
Building Apps with Ethereum Smart ContractBuilding Apps with Ethereum Smart Contract
Building Apps with Ethereum Smart ContractVaideeswaran Sethuraman
 
Blockchain Experiments 1-11.pptx
Blockchain Experiments 1-11.pptxBlockchain Experiments 1-11.pptx
Blockchain Experiments 1-11.pptxsaiproject
 
Ethereum Solidity Fundamentals
Ethereum Solidity FundamentalsEthereum Solidity Fundamentals
Ethereum Solidity FundamentalsEno Bassey
 
Ethereum Devcon1 Report (summary writing)
Ethereum Devcon1 Report (summary writing)Ethereum Devcon1 Report (summary writing)
Ethereum Devcon1 Report (summary writing)Tomoaki Sato
 
Simone Bronzini - Weaknesses of blockchain applications - Codemotion Milan 2018
Simone Bronzini - Weaknesses of blockchain applications - Codemotion Milan 2018Simone Bronzini - Weaknesses of blockchain applications - Codemotion Milan 2018
Simone Bronzini - Weaknesses of blockchain applications - Codemotion Milan 2018Codemotion
 
Developing Blockchain Applications
Developing Blockchain Applications Developing Blockchain Applications
Developing Blockchain Applications malikmayank
 
Blockchain Development
Blockchain DevelopmentBlockchain Development
Blockchain Developmentpreetikumara
 
Attacking and Exploiting Ethereum Smart Contracts: Auditing 101
Attacking and Exploiting Ethereum Smart Contracts: Auditing 101Attacking and Exploiting Ethereum Smart Contracts: Auditing 101
Attacking and Exploiting Ethereum Smart Contracts: Auditing 101Simone Onofri
 
Ethereum
EthereumEthereum
EthereumV C
 
Contracts Across Coins - Smart Contracts for Bitcoin, Ripple and the altcoins
Contracts Across Coins - Smart Contracts for Bitcoin, Ripple and the altcoinsContracts Across Coins - Smart Contracts for Bitcoin, Ripple and the altcoins
Contracts Across Coins - Smart Contracts for Bitcoin, Ripple and the altcoinsRipple Labs
 
Ergo Presentation - Tokyo
Ergo Presentation - TokyoErgo Presentation - Tokyo
Ergo Presentation - TokyoAlex Chepurnoy
 
Smart contract honeypots for profit (and fun) - bha
Smart contract honeypots for profit (and fun)  - bhaSmart contract honeypots for profit (and fun)  - bha
Smart contract honeypots for profit (and fun) - bhaPolySwarm
 
Ethereum Block Chain
Ethereum Block ChainEthereum Block Chain
Ethereum Block ChainSanatPandoh
 
Understanding blockchain
Understanding blockchainUnderstanding blockchain
Understanding blockchainPriyab Satoshi
 
Ethereum in a nutshell
Ethereum in a nutshellEthereum in a nutshell
Ethereum in a nutshellDaniel Chan
 
Blockchain, Ethereum and Business Applications
Blockchain, Ethereum and Business ApplicationsBlockchain, Ethereum and Business Applications
Blockchain, Ethereum and Business ApplicationsMatthias Zimmermann
 

Similaire à How to not Destroy Millions in Smart Contracts (20)

Ethereum
EthereumEthereum
Ethereum
 
Ethereum-Cryptocurrency (All about Ethereum)
Ethereum-Cryptocurrency (All about Ethereum) Ethereum-Cryptocurrency (All about Ethereum)
Ethereum-Cryptocurrency (All about Ethereum)
 
Building Apps with Ethereum Smart Contract
Building Apps with Ethereum Smart ContractBuilding Apps with Ethereum Smart Contract
Building Apps with Ethereum Smart Contract
 
How to design, code, deploy and execute a smart contract
How to design, code, deploy and execute a smart contractHow to design, code, deploy and execute a smart contract
How to design, code, deploy and execute a smart contract
 
Blockchain Experiments 1-11.pptx
Blockchain Experiments 1-11.pptxBlockchain Experiments 1-11.pptx
Blockchain Experiments 1-11.pptx
 
Ethereum Solidity Fundamentals
Ethereum Solidity FundamentalsEthereum Solidity Fundamentals
Ethereum Solidity Fundamentals
 
Ethereum Devcon1 Report (summary writing)
Ethereum Devcon1 Report (summary writing)Ethereum Devcon1 Report (summary writing)
Ethereum Devcon1 Report (summary writing)
 
What is ethereum
What is ethereumWhat is ethereum
What is ethereum
 
Simone Bronzini - Weaknesses of blockchain applications - Codemotion Milan 2018
Simone Bronzini - Weaknesses of blockchain applications - Codemotion Milan 2018Simone Bronzini - Weaknesses of blockchain applications - Codemotion Milan 2018
Simone Bronzini - Weaknesses of blockchain applications - Codemotion Milan 2018
 
Developing Blockchain Applications
Developing Blockchain Applications Developing Blockchain Applications
Developing Blockchain Applications
 
Blockchain Development
Blockchain DevelopmentBlockchain Development
Blockchain Development
 
Attacking and Exploiting Ethereum Smart Contracts: Auditing 101
Attacking and Exploiting Ethereum Smart Contracts: Auditing 101Attacking and Exploiting Ethereum Smart Contracts: Auditing 101
Attacking and Exploiting Ethereum Smart Contracts: Auditing 101
 
Ethereum
EthereumEthereum
Ethereum
 
Contracts Across Coins - Smart Contracts for Bitcoin, Ripple and the altcoins
Contracts Across Coins - Smart Contracts for Bitcoin, Ripple and the altcoinsContracts Across Coins - Smart Contracts for Bitcoin, Ripple and the altcoins
Contracts Across Coins - Smart Contracts for Bitcoin, Ripple and the altcoins
 
Ergo Presentation - Tokyo
Ergo Presentation - TokyoErgo Presentation - Tokyo
Ergo Presentation - Tokyo
 
Smart contract honeypots for profit (and fun) - bha
Smart contract honeypots for profit (and fun)  - bhaSmart contract honeypots for profit (and fun)  - bha
Smart contract honeypots for profit (and fun) - bha
 
Ethereum Block Chain
Ethereum Block ChainEthereum Block Chain
Ethereum Block Chain
 
Understanding blockchain
Understanding blockchainUnderstanding blockchain
Understanding blockchain
 
Ethereum in a nutshell
Ethereum in a nutshellEthereum in a nutshell
Ethereum in a nutshell
 
Blockchain, Ethereum and Business Applications
Blockchain, Ethereum and Business ApplicationsBlockchain, Ethereum and Business Applications
Blockchain, Ethereum and Business Applications
 

Dernier

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 

Dernier (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 

How to not Destroy Millions in Smart Contracts

  • 1.
  • 2. Blockchain Academy A community for technologists looking to learn more about Crypto and Blockchain technology Blockchain AcademyLeonid Beder April 24, 2018
  • 3. About Me April 24, 2018Blockchain Academy leonid@orbs.com PGP Key: leonid@kik.com D749 1F09 3721 0A31 72B5 @LeonidBeder DBF3 7F35 EBC3 E4B2 44B4 @lbeder Leonid Beder
  • 4. Agenda 1.Introduction to smart contracts 2.Introduction to Solidity 3.(In)famous bugs and issues 4.Additional tools and techniques
  • 5.
  • 6. Introduction to Smart Contracts Leonid Beder Blockchain Academy
  • 7. Nick Szabo, Smart Contracts: Building Blocks for Digital Markets, 1996 “A smart contract is a set of promises, specified in digital form, including protocols within which the parties perform on these promises.”
  • 8.
  • 9. What is a Smart Contract? “A smart contract is a set of promises, specified in digital form, including protocols within which the parties perform on these promises.” • Example: a sales contract. • The seller promises to deliver the goods in exchange for the buyer. • The buyer promises to pay the desired price.
  • 10. What is a Smart Contract? “A smart contract is a set of promises, specified in digital form, including protocols within which the parties perform on these promises.” • Digital form means that the contract has to be programmed in machine readable code.
  • 11. What is a Smart Contract? “A smart contract is a set of promises, specified in digital form, including protocols within which the parties perform on these promises.” • For example, say the parties agree that the purchased good is to be paid in Bitcoin. The obvious protocol of choice would then be the Bitcoin protocol (Bitcoin scripting language).
  • 12. What is a Smart Contract? “A smart contract is a set of promises, specified in digital form, including protocols within which the parties perform on these promises.”
  • 13. Popular Implementations • Ethereum implements a (nearly) Turing-complete language on its blockchain, a prominent smart contract framework. • Bitcoin implements a Turing-incomplete Script language that allows the creation of limited smart contracts, such as: multisignature accounts, payment channels, escrows, time locks, atomic cross-chain trading, oracles, etc.
  • 15. What is Solidity? • Solidity is an OOP language for writing smart contracts (mostly?) on Ethereum • It was originally developed by Dr. Gavin Wood, Dr. Christian Reitwiessner, Alex Beregszaszi, Liana Husikyan, Yoichi Hirai and several former Ethereum core contributors. Dr. Gavin Wood Dr. Christian Reitwiessner Alex Beregszaszi Yoichi HiraiLiana Husikyan
  • 16. An example • Let’s start with a simple example of a smart contract named Greeter, which will: • Initialized with a greeting message (e.g., “Hello World!”). • Provide a method to read/query the greeting message. • Provide a method to write/modify the greeting message. • For this talk, we will use the official online Remix IDE: https://remix.ethereum.org. • You can find all the code here: https://github.com/blockchain-academy/how- not-to-destroy-your-ether
  • 17. Solidity version to use Contract name public state variable of type string Constructor, receiving a single argument of type string public method, receiving a single argument of type string
  • 18. Fundamentals: Execution Model • Every smart contract needs to be compiled and deployed to the network. • Every transaction or message call in Ethereum is executed by the Ethereum Virtual Machine (EVM) on every Ethereum node (miner or a just a full node). • Since that every smart contract is running on the EVM, and every single operation is actually executed simultaneously by every node in the network - there should be a mechanism to limit the resources used by each contract. • Such mechanism is implemented in Ethereum via gas: • Every operation has a deterministic (yet, hard to sometimes predict) cost measured in quantifying units of gas. • Every gas unit consumed by a transaction must be paid for in Ether, based on a gas/Ether price which is set by the sender of the original sender of transaction.
  • 19. Fundamentals: Execution Model • Transactions have also a gas limit parameter that is an upper bound on how much gas the transaction can consume. ❏Why is the gas limit parameter needed? ❏There is also a block gas limit (i.e., an upper bound to the total amount of gas consumed by all the transaction in a block. Why is it needed? ❏The protocol allows the miner of a block to adjust the block gas limit by a factor of 1/1024 (0.0976%) in either direction.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26. Fundamentals: Special Variables and Functions • There are special variables and functions which always exist in the global namespace. • For our talk, we (mostly) need to know: • msg.sender (address): sender of the message (current call). • msg.value (uint): number of wei sent with the message.
  • 27. Fundamentals: Function and State Variables Visibility • In Solidity, there are four types of visibilities: • For functions: • external: can be called externally from other accounts/contracts. • public (default): can be called by everyone. • internal: can only be called internally. • private: can only be called internally and only from the contract itself.
  • 28. Fundamentals: Function and State Variables Visibility • For state variables: • external: N/A • public: can be accessed by everyone. • internal (default): can only be accessed internally. • private: can only be accessed internally and only from the contract itself.
  • 29.
  • 30.
  • 31. Fundamentals: Function Modifiers• Modifiers can be used to modify the behaviour of functions. • For example, a very common use case is by checking a pre- or post-conditions. • They are very similar to before/after/around filters/hooks in other programming languages. • For example, let’s augment our Greeter smart contract to: • Have an owner (in our case, the deployer of the smart contract). • Make sure than only the owner can further modify the greeting.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39. Fundamentals: Fallback Function • A smart contract can have exactly one unnamed function. • It’s executed on a call to the contract if none of the other functions match the given function identifier. • For example, when Ether is being transferred to the contract.
  • 40. Fundamentals: Payable ModifierIn order to receive Ether, every function must be marked as payable: • When sending Ether as part of a function call, the function must be marked as payable. • When sending Ether directly to a contract, its fallback function must be marked as payable. If no such function exists, the contract cannot receive Ether through regular transactions.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58. Bugs: Overflow/Underflow • Solidity can handle (up to) 256 bit numbers (values up to 2²⁵⁶-1). • Overflow is when a number gets incremented above its maximum value: • Adding 1 to 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF results in 0. • Underflow is the inverse case, when the number is unsigned, decrementing will underflow the number: • Subtracting 1 from 0x000000000000000000000000000000000000 results in 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF.
  • 59. Mitigation #1: Test for Correctness• Test for correctness before performing any operations:
  • 60.
  • 61.
  • 62.
  • 63. Mitigation #2: SafeMath • Always use the (de-facto) standard SafeMath library. • You can it and many other nice, relatively stable, smart contracts in OpenZeppelin’s Github repo: https://github.com/OpenZeppelin/zeppelin-solidity
  • 64.
  • 65.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78. Mitigation: Always Define Visibility! • Always define visibility explicitly. • Limit function visibility when possible.
  • 79.
  • 80. Use Case: Parity “hack” #1 • TL;DR: A vulnerability was found on the Parity Multisig Wallet version 1.5+, that allowed an attacker to steal over 150,000 Ether ($30,000,000, at the time; $105,000,000 today [ETH/USD 700]). • A white hat hacker group subsequently drained other Parity wallets to protect funds worth 377,105 ETH ($85,000,000, at the time; ~$264,000,000 today [ETH/USD 700]).
  • 81. Use Case: Parity “hack” #1 • So what’s happened there? • You can find the original code here: https://raw.githubusercontent.com/paritytech/parity/4d08e7b0ae c46443bf26547b17d10cb302672835/js/src/contracts/snippets/ enhanced-wallet.sol
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87. Use Case: Parity “hack” #1 But, wait… how does WalletLibrary work with the Wallet contract?
  • 89.
  • 90. Use Case: Parity “hack” #1 • The attacker exploited this and simply changed the contract’s m_owners state variable to a list containing only their address, and requiring just one confirmation to execute any transaction: https://etherscan.io/tx/0x9dbf0326a03a2a3719c27be4fa69aacc 9857fd231a8d9dcaede4bb083def75ec
  • 91. `
  • 92. Mitigation • Complexity is a vulnerability. Keep It Simple Stupid. • Always define visibility explicitly. • Don’t extract the constructor logic into the library contract. Avoid premature optimizations! • Don’t use delegatecall as a catch-all forwarding mechanism.
  • 93. Mitigation: Parity Developers’ Fix • Parity has quickly fixed the issue here: https://github.com/paritytech/parity/commit/e06a1e8dd9cfd8bf5 d87d24b11aee0e8f6ff9aeb
  • 94.
  • 95.
  • 97. Use Case: Rubixi • Rubixi is a contract which implements a pyramid scheme (allegedly). • Investors can deposit funds. • The owner can collect all of the funds.
  • 98.
  • 99.
  • 100.
  • 101. Mitigation • Well, for starters, try not to misname functions… • Stay vigilant! The scammers are getting better and better… • Starting from 0.4.22, you can now use the safe constructor method instead:
  • 102.
  • 103. Leonid Beder Example #4 “It will be like a taco inside a taco within a Taco Bell that’s inside a KFC, within a bowl, that’s inside your brain...” / South Park S14E10
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114. Mitigation #1: Checks-Effects- InteractionsChecks-Effects-Interactions Pattern: 1.Perform checks (who called the function, are the arguments in range, did they send enough Ether, does the person have tokens, etc.). 1.If all checks passed, effects to the state variables of the current contract should be made. 1.Lastly, perform any interaction with other accounts/contracts.
  • 115.
  • 116. Mitigation #2: Avoid call.value()() When sending Ether, be aware of the relative tradeoffs between the use of: 1.address.call.value()(): will send the provided Ether and trigger code execution given all available gas. 1.address.send(): will send the provided Ether and trigger code execution given a limited stipend of 2,300 gas. 1.address.transfer(): is equivalent to require(address.send()). It will automatically revert if the send fails.
  • 117.
  • 118. Use Case: “The DAO” • “The DAO” is the name of a particular DAO (Decentralized Autonomous Organization), conceived of and programmed by the team behind German startup Slock.it a company building "smart locks" that let people share their things (cars, boats, apartments) in a decentralized version of Airbnb. • It was launched on 30th April, 2016, with a 28-day funding window. • It was the largest crowdfunding in history, having raised over $150,000,000 from more than 11,000 enthusiastic members.
  • 119. Use Case: “The DAO” • On 18th June, the attacker started to drain “The DAO” using a (relatively) sophisticated reentrancy attack. • The attacker has managed to drain more than 3,600,000 Ether ($72,000,000, at that time; astounding $2,520,000,000 today [ETH/USD 700]). • How did the Ethereum community responded?
  • 120.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138. “Alternative” Ether Transfer • In addition to the regular means to send Ether (e.g., call, send/transfer), there are two more ways which will bypass the fallback function: 1.selfdestruct: The only possibility that code is removed from the blockchain is when a contract at that address performs the selfdestruct operation. • If the receiving address is a contract, its fallback function does not get executed. 1.As a miner, set the target address as the coinbase address in order for it to receive block mining awards.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151. Mitigation: Beware of Assumptions • Never use a contract’s balance as a guard. • In general, be mindful of language/framework specific features and updates. 1.Beware of compiler optimizations bugs and test accordingly 2.Beware of compiler specific bugs and always use strict compiler version. 3.Beware of potential miners’ intervention (e.g., front-running, chain re-org, etc.). • 0.4.21 compiler version... Ethereum is still an alpha.
  • 152. (Similar) Use Case: Parity “hack” #2 TL;DR:
  • 153.
  • 154. (Similar) Use Case: Parity “hack” #2• Approximately 513,000 ETH ($154,000,000, at that time; $359,100,000 today [ETH/USD 700]) has been locked in the affected contracts. • No funds were “stolen” per-say; only made unreachable, by an accident. • There are few proposals for methods to restore the lost funds (e.g., the very recent EIP999) and even for a new ERP (Ethereum Recovery Proposal) governance model, but it’s unlikely to happen any time soon.
  • 155. (Similar) Use Case: Parity “hack” #2 So what’s happened there?
  • 156.
  • 157.
  • 158.
  • 159. (Similar) Use Case: Parity “hack” #2• The WalletLibrary contract contains a state variables that it expects to be shadowed by the calling contract’s own state. • Once deployed, the WalletLibrary contract is simply uninitialized, so m_numOwners is 0. • If the WalletLibrary isn’t executed in a Wallet contract’s context, m_numOwners is 0, allowing anyone to call methods that this modifier guards, one of which is initWallet.
  • 160. (Similar) Use Case: Parity “hack” #2• So what did devops199 has done exactly? • Nov 06, 2017 14:33:47 (UTC): https://etherscan.io/tx/0x05f71e1b2cb4f03e547739db15d080fd30c989eda 04d37ce6264c5686e0722c9 • Called the initWallet method against the deployed WalletLibrary. • Set 0xae7168deb525862f4fee37d987a971b385b96952 as its only owner.
  • 161.
  • 162. (Similar) Use Case: Parity “hack” #2• Nov 06, 2017 15:25:21 (UTC) (51 minutes from previous tx): https://etherscan.io/tx/0x47f7cff7a5e671884629c93b368cb18f58a993f4 b19c2a53a8662e3f1482f690 • Called the kill method with 0xae7168deb525862f4fee37d987a971b385b96952 as the beneficiary address.
  • 163.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177. Mitigation #1: Favor Pull over Push• Always remembers that you’re not only interacting with human beings, but also with other contracts. • Favor pull over push for external calls.
  • 178.
  • 179. Mitigation #2: Ignore Contracts• It’s usually not recommended or desired, but it’s also possible to opt-out from interacting with contract using the following check:
  • 181. Testing and Development • Truffle (http://truffleframework.com/) is the most popular development framework for Ethereum. • Reuse existing libraries, such as OpenZeppelin (https://github.com/OpenZeppelin/zeppelin-solidity) • Ganache (http://truffleframework.com/ganache/) is a tool which allows you to quickly fire up a personal Ethereum blockchain which you can use to run tests, execute commands, and inspect state while controlling how the chain operates.
  • 182.
  • 183.
  • 184. Testing and Development • solidity-coverage (https://github.com/sc-forks/solidity-coverage) code coverage for Solidity smart-contracts.
  • 185.
  • 186. … and even that isn’t enough!
  • 187. Remix • Remix (https://remix.ethereum.org) performs static analysis to your code and is able to spot many bugs:
  • 188.
  • 189.
  • 190. Oyente • Oyente (https://oyente.melon.fund) another analysis tool for smart contracts with both CLI and a GUI similar interface to Remix. • At the moment, the latest supported compiler is 0.4.17.
  • 191.
  • 192.
  • 193. Mythril • Mythril (https://github.com/b-mueller/mythril) is a security analysis tool for Ethereum smart contracts.
  • 194.
  • 195. Securify • Securify (https://securify.ch) is a static analysis tool for Smart Contracts. • At the moment, the latest supported compiler is 0.4.16.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 204. Blockchain AcademyLeonid Beder April 24th, 2018 Thank You!