SlideShare une entreprise Scribd logo
1  sur  53
Robust Programming of Smart
Contracts in Solidity+
RK Shyamasundar
Department of Computer Science & Engg
Indian Institute of Technology Bombay
rkss@cse.iitb.ac.in
(Joint work with Snehal Borse and Prateek Patidar)
11/03/2020 ICBC2020 1
Smart Contracts
• Smart contracts provide the feeling of sequential
execution, but they are have stark similarity with
shared variable programs.
• One Comes across several vulnerabilities in
Solidity – a widely used language on Ethereum
• Realize robustness through methodologies of
distributed programs over shared variables.
– Explicit Declarations for concurrency and
– Process Interaction
– Specification of Concurrent Modules
11/03/2020 ICBC2020 2
Approach
• Capture the patterns of Vulnerabilities
• Generalize the patterns as Declarations for the
Programs
• Declarations + Program
Solidity program with Error handling
Features like require, assert, revert
11/03/2020 ICBC2020 3
Automatic Transform
Outline of Proof Carrying Code
Advantages
• Effective for Programmer - ease of programming
• Debugging at the level of Solidity and not
Ethereum
• A sort of Informal framework of proof carrying
code on the blockchain for smart contracts
• Parallels ensuring data integrity without
unnecessary mutual exclusion, permitting
dynamic resource management.
• Amenable structurally for formal correctness
(Model Checkers or Verifiers) similar to
concurrent programs
11/03/2020 ICBC2020 4
Classic Shared Variable PL
•
11/03/2020 ICBC2020 5
11/03/2020 ICBC2020 6
• SOLIDITY +
• DECLARATIONS
• NONREENTRANT
• IMPORT
• EXPORT
• ACCESS
• PARALLEL
• INVAR …
• contract Coin {
• // The keyword "public" makes variables
• // accessible from other contracts
• address public minter;
• mapping (address => uint) public balances;
• // Events allow clients to react to specific
• // contract changes you declare
• event Sent(address from, address to, uint amount);
• // Constructor code is only run when the contract
• // is created
• constructor() public {
• minter = msg.sender;
• }
• // Sends an amount of newly created coins to an address
• // Can only be called by the contract creator
• function mint(address receiver, uint amount) public {
• require(msg.sender == minter);
• require(amount < 1e60);
• balances[receiver] += amount;
• }
• // Sends an amount of existing coins
• // from any caller to an address
• function send(address receiver, uint amount) public {
• require(amount <= balances[msg.sender], "Insufficient balance.");
• balances[msg.sender] -= amount;
• balances[receiver] += amount;
• emit Sent(msg.sender, receiver, amount);
• }
• }
11/03/2020 ICBC2020 7
Pre -Processor
11/03/2020 ICBC2020 8
SimpleDAO Attack
9
SimleDAO
mapping (addr => uint) credit;
function donate(uint amount) {
credit[caller] += amount;
}
function withdraw(uint amt) {
if(credit[withdrawer] >= amt) {
send amt to withdrawer;
reduce credit[withdrawer];
}
}
Attacker
function atttack() {
SimpleDAO.donate(1);
SimpleDAO.withdraw(1);
}
function() { //Fallback Function
SimpleDAO.withdraw(1);
}
Crowdfunding: Decentralized business model for organizing both
commercial and non-profit enterprises
Reentrancy in SimpleDAO
10
A.balance = 1;
DAO.balance = 2;
credit[A] = 0;
A.running = false;
A.balance = 0;
DAO.balance = 3;
credit[A] = 1;
A.running = true;
credit[A] = 1;
amount = 1;
A.balance = 1;
DAO.balance = 2;
credit[A] = 1;
A.running = true;
credit[A] = 1;
amount = 1;
A.balance = 2;
DAO.balance = 1;
credit[A] = 1;
A.running = true;
credit[A] = 1;
amount = 1;
A.balance = 3;
DAO.balance = 0;
credit[A] = 1;
A.running = true;
credit[A] = 1;
amount = 1;
A.balance = 3;
DAO.balance = 0;
credit[A] = 0;
A.running = false;
Attacker’s balance is
more than what
he/she donated.
donate
Initial state
Final state
withdraw
withdraw
withdraw
withdraw
A: Address of Attacker contract
DAO: Address of DAO contract
amount: Amount to be withdrawn
running: flag to show if attacker is still
running or not
credit: mapping (addr => uint)
donate: donate(1)
withdraw: withdraw(1)
A.balance = 3;
DAO.balance = 0;
credit[A] = 0;
A.running = false;
11/03/2020 ICBC2020
SimpleDAO Example
11
SimleDAO
PARALLEL ( NIL)
NONREENTRANT (withdraw)
mapping (addr => uint) credit;
function donate(uint amount) {
credit[caller] += amount;
}
function withdraw(uint amt) {
if(credit[withdrawer] >= amt) {
send amt to withdrawer;
reduce credit[withdrawer];
}
}
Attacker
function atttack() {
SimpleDAO.donate(1);
SimpleDAO.withdraw(1);
}
function() { //Fallback Function
SimpleDAO.withdraw(1);
}
Modified Contract
11/03/2020 ICBC2020 12
After removal of Reentrancy
13
A.balance = 1;
DAO.balance = 2;
credit[A] = 0;
A.running = false;
callStack = {}
A.balance = 0;
DAO.balance = 3;
credit[M] = 1;
A.running = true;
callStack = {“donate”}
credit[A] = 1;
amount = 1;
isReentrant = false;
callStack = {“withdraw”}
A.balance = 1;
DAO.balance = 2;
credit[A] = 1;
A.running = true;
callStack = {“withdraw”}
A.balance = 1;
DAO.balance = 2;
credit[A] = 0;
A.running = false;
callStack = {}
credit[A] = 1;
amount = 1;
isReentrant = true;
callStack = {“withdraw”}
Final state
Initial state
Since withdraw was
already present in
callStack, stop
executing
donate withdraw
withdraw
A: Address of Attacker contract
DAO: Address of DAO contract
amount: Amount to be withdrawn
running: flag to show if attacker is still
running or not
credit: mapping (addr => uint)
callStack: to store which functions of a
contract are called
11/03/2020 ICBC2020
11/03/2020 ICBC2020 14
Require(1)
• The require function should be used to ensure
valid conditions that cannot be detected until
execution time.
• These conditions include inputs, or contract
state variables are met, or to validate return
values from calls to external contracts.
• You can optionally provide a message string
for require, but not for assert.
11/03/2020 ICBC2020 15
Require (2)
• Internally, Solidity performs a revert operation (instruction
0xfd) for a require-style exception and executes an invalid
operation (instruction 0xfe) to throw an assert-style
exception.
• In both cases, this causes the EVM to revert all changes
made to the state.
• The reason for reverting is that there is no safe way to
continue execution, because an expected effect did not
occur.
• Because we want to keep the atomicity of transactions, the
safest action is to revert all changes and make the whole
transaction (or at least call) without effect.
11/03/2020 ICBC2020 16
Assert
• The assert function should only be used to
test for internal errors, and to check
invariants.
• Properly functioning code should never reach
a failing assert statement;
– if this happens there is a bug in your contract
which you should fix.
– Language analysis tools can evaluate your contract
to identify the conditions and function calls which
will reach a failing assert.
11/03/2020 ICBC2020 17
Assert and Require
• assert-style exceptions consume all gas
available to the call,
• while require-style exceptions do not consume
any gas starting from the Metropolis release.
11/03/2020 ICBC2020 18
Revert
11/03/2020 ICBC2020 19
• The revert function is another way to trigger exceptions from
within other code blocks to flag an error and revert the
current call.
• The function takes an optional string message containing
details about the error that is passed back to the caller.
11/03/2020 ICBC2020 20
Concurrency
21
contract GetterSetter {
uint balance;
function get() returns (uint) {
return balance;
}
function set(uint x) {
balance = x;
}
}
C1 calls set(100);
C2 calls set(50);
C1 calls get(); - returns 50
C2 calls get(); - returns 50
C1 calls set(100);
C1 calls get(); - returns 100
C2 calls set(50);
C2 calls get(); - returns 50
C1 calls set(100);
C1 calls get(); - returns 100
C2 calls set(50);
C2 calls get(); - returns 50
C1 calls set(100);
C2 calls set(50);
C1 calls get(); - returns 50
C2 calls get(); - returns 50
Getter Setter Contract
11/03/2020 ICBC2020 22
11/03/2020 ICBC2020 23
ACCESS (get set)
PARALLEL (Get, Get)
11/03/2020 ICBC2020 24
Order of execution :
11/03/2020 ICBC2020 25
Also No Parallel Invokations
ERC20
• ERC20 is a technical standard used for smart
contracts on the Ethereum blockchain for
implementing tokens.
• ERC-20 token standard became popular with
crowdfunding companies working on initial
coin offering (ICO) cases due to simplicity of
deployment, together with its potential for
interoperability with other Ethereum token
standards.
11/03/2020 ICBC2020 26
11/03/2020 ICBC2020 27
ERC20(2)
• Alice allows Bob to transfer 100 of Alice’s
token by calling approve(Bob’s address, 100).
• After some time Alice decides to change the
approved token from 100 to 50, so she calls
approve(Bob’s address, 50).
• Before Alice’s second transaction was mined,
Bob calls transferFrom to transfer 100 Alice’s
tokens somewhere.
• If Bob’s transaction will be executed before
Alice’s then Bob has already transferred 100
tokens and now additionally has permission
to transfer 50 tokens.
• Before Alice notices that something went
wrong,
• Bob calls Transfer from to transfer 50 Alice’s
token to somewhere.
• Nondeterminism:
• Alice initially wanted to change the allowed
tokens from 100 to 50 but this change made
it possible for Bob to transfer 150 tokens.
Alice never wanted to allow Bob to spend
this much of her tokens.
11/03/2020 ICBC2020 28
11/03/2020 ICBC2020 29
ACCESS (approve)* or
(approve)+((allowance) (transferFrom))* or
((allowance) (transferFrom))*
11/03/2020 ICBC2020 30
Gasless send
contract Sender {
function transferAmt() {
receiver.send(n);
print(“Successfully sent n ether
to receiver”);
}
}
contract Receiver {
uint x = 0;
function() { //Fallback function
}
}
33
◎ send: predefined amount of gas
i.e. 2300 which can’t be
changed
◎ Sufficient for Fallback function
without state change
◎ Insufficient for Fallback function
with state change
contract Sender {
function transferAmt() {
receiver.send(n);
print(“Successfully sent n ether
to receiver”);
}
}
contract Receiver {
uint x = 0;
function() {
x++;
}
}
Successful
◎ send: predefined amount of gas
i.e. 2300 which can’t be
changed
◎ Sufficient for Fallback function
without state change
Failed
contract Sender {
function transferAmt() {
receiver.send(n);
print(“Successfully sent n ether
to receiver”);
}
}
contract Receiver {
uint x = 0;
function() {
x++;
}
}
Gasless Send Solution
34
◎ Whenever there is a transfer of ether using send function, use guard
function for that send call
contract Sender {
function transferAmt() {
require(receiver.send(n), “Insufficient gas”);
print(“Successfully sent n ether
to receiver”);
}
}
contract Receiver {
uint x = 0;
function() {
x++;
}
}
FAIL
11/03/2020 ICBC2020 35
Classic Shared Variable PL
•
11/03/2020 ICBC2020 36
11/03/2020 ICBC2020 37
Transaction Order
• ACCESS (get set)
• PARALLEL (Get Get) // functions not
mentioned cannot execute in parallel
11/03/2020 ICBC2020 38
SimpleDAO Attack
39
SimleDAO
mapping (addr => uint) credit;
function donate(uint amount) {
credit[caller] += amount;
}
function withdraw(uint amt) {
if(credit[withdrawer] >= amt) {
send amt to withdrawer;
reduce credit[withdrawer];
}
}
Attacker
function atttack() {
SimpleDAO.donate(1);
SimpleDAO.withdraw(1);
}
function() { //Fallback Function
SimpleDAO.withdraw(1);
}
DAO Program with Checks in
Solidity+
• PARALLEL (NIL)
• NONREENTRANT ( withdraw)
11/03/2020 ICBC2020 40
11/03/2020 ICBC2020 41
ERC20
• ACCESS (approve)* or
• (approve)+((allowance) (transferFrom))* or
• ((allowance) (transferFrom))*
11/03/2020 ICBC2020 42
11/03/2020 ICBC2020 43
Typecast
• IMPORT Alice
11/03/2020 ICBC2020 44
Type Cast Transformed
45
contract A {
function foo() {
print(“Calling foo of contract A”);
}
}
contract B {
function foo() {
print(“Calling foo of contract B”);
}
}
contract C{
function callFoo(A a) { //call foo() of A
require(a==Addr of A, “Calling apprpriate foo()”);
a.foo();
}
}
callFoo(addr of A): succeed
callFoo(addr of B): failed
11/03/2020 ICBC2020 46
• SOLIDITY +
• DECLARATIONS
• IMPORT
• EXPORT
• ACCESS
• PARALLEL
• NONREENTRANT
• INVAR …
• contract Coin {
• // The keyword "public" makes variables
• // accessible from other contracts
• address public minter;
• mapping (address => uint) public balances;
• // Events allow clients to react to specific
• // contract changes you declare
• event Sent(address from, address to, uint amount);
• // Constructor code is only run when the contract
• // is created
• constructor() public {
• minter = msg.sender;
• }
• // Sends an amount of newly created coins to an address
• // Can only be called by the contract creator
• function mint(address receiver, uint amount) public {
• require(msg.sender == minter);
• require(amount < 1e60);
• balances[receiver] += amount;
• }
• // Sends an amount of existing coins
• // from any caller to an address
• function send(address receiver, uint amount) public {
• require(amount <= balances[msg.sender], "Insufficient balance.");
• balances[msg.sender] -= amount;
• balances[receiver] += amount;
• emit Sent(msg.sender, receiver, amount);
• }
• }
Merits of Solidity+
1. Solidity and Solidity+ executionally remain
unchanged without adding burden on the
programmer.
2. It only adds runtime checks to the program as
per declarations.
3. Allows programmer to debug at the source level
itself rather than EVM.
4. An informal framework for proof carrying smart
contracts, Adaptable for formal correctness as
well (model checking, theorem prover …)
11/03/2020 ICBC2020 47
4811/03/2020 ICBC2020
Graph Generation
49
◎ In addition to the transformation into Solidity+, we generate a graph of a
Solidity program
◎ As pictures speak more than words, it makes easier for naive user to
understand the flow of a program
◎ After graph generation, we try to find out a pattern for a vulnerability and
make conclusive statement about the contract
Graph for reentrant SimpleDAO
50
Reentranc
y
11/03/2020 ICBC2020
Graph for non-reentrant
SimpleDAO
5111/03/2020 ICBC2020
Related Work
◎ Oyente [2]
○ Based on symbolic execution
○ Creates CFG for bytecode
◎ Mythril OSS [7]
○ Based on concolic execution, taint analysis and control flow checking
◎ Problems with the above approaches:
○ Neither sound nor complete
○ Several false alarms even in trivial contracts
○ Hard to recreate the intent from bytecode alone
52
Related Work
◎ F* [4]
○ Presents two tools which are based on shallow embedding in F*
○ Does not handle loops
○ Only a subset of Solidity is translated to F*
○ Reasoning may require manual proofs
◎ Why3 [8]
○ Supports only a small subset of entire syntax
○ Solidity to Why3 translation is not yet tested and can not be trusted
◎ ZEUS [3]
○ Based on abstract interpretation and symbolic model checking
○ Conducts policy checking based on user provided policies
53
Related Work
◎ Securify [5]
○ Derives semantic facts inferred by analyzing the contract’s dependency graph
○ Uses these facts to check a set of compliance and violation patterns
◎ Hirai et al. [9]
○ Used the Isabelle proof assistant and Lem language
○ Defined a formal model for the Ethereum Virtual Machine
○ Proved safety properties of smart contracts using existing interactive theorem provers
◎ Amani et al. [10]
○ Extended the existing EVM formalisation by Hirai et al.
○ Structured the bytecode sequences into basic blocks and created a program logic to
reason about these
54
Related Work
◎ KEVM [11]
○ A formal semantics of the EVM written using the K-framework
○ Properties are specified in Reachability Logic and verified with a separate analysis tool
◎ Grishchenko et al. [12]
○ Complete small-step semantics of EVM bytecode
○ Formalized in the F* proof assistant
○ Also formalized a number of security properties
◎ Jiao et al. [13]
○ Defined a small-step operational semantics for a subset of the Solidity language
○ Their work is executable in the K-framework
◎ All the above semantics are executable and were validated against the
official Ethereum test suite.
55

Contenu connexe

Similaire à Robust Programming of Smart Contracts in Solidity+, RK Shyamasundar

A Decompiler for Blackhain-Based Smart Contracts Bytecode
A Decompiler for Blackhain-Based Smart Contracts BytecodeA Decompiler for Blackhain-Based Smart Contracts Bytecode
A Decompiler for Blackhain-Based Smart Contracts BytecodeShakacon
 
Ethereum
EthereumEthereum
EthereumV C
 
An Introduction to Upgradable Smart Contracts
An Introduction to Upgradable Smart ContractsAn Introduction to Upgradable Smart Contracts
An Introduction to Upgradable Smart ContractsMark Smalley
 
Solidity Security and Best Coding Practices
Solidity Security and Best Coding PracticesSolidity Security and Best Coding Practices
Solidity Security and Best Coding PracticesGene Leybzon
 
J.burke HackMiami6
J.burke HackMiami6J.burke HackMiami6
J.burke HackMiami6Jesse Burke
 
Solidity Simple Tutorial EN
Solidity Simple Tutorial ENSolidity Simple Tutorial EN
Solidity Simple Tutorial ENNicholas Lin
 
Best practices to build secure smart contracts
Best practices to build secure smart contractsBest practices to build secure smart contracts
Best practices to build secure smart contractsGautam Anand
 
Starkware: Account Abstraction
Starkware: Account AbstractionStarkware: Account Abstraction
Starkware: Account AbstractionTinaBregovi
 
Build on Streakk Chain - Blockchain
Build on Streakk Chain - BlockchainBuild on Streakk Chain - Blockchain
Build on Streakk Chain - BlockchainEarn.World
 
ERC20 Token Contract
ERC20 Token ContractERC20 Token Contract
ERC20 Token ContractKC Tam
 
Serverless Design Patterns (London Dev Community)
Serverless Design Patterns (London Dev Community)Serverless Design Patterns (London Dev Community)
Serverless Design Patterns (London Dev Community)Yan Cui
 
Blockchain Tokenization
Blockchain TokenizationBlockchain Tokenization
Blockchain TokenizationBellaj Badr
 
Blockchain technology-in-fin tech - Anton Sitnikov
Blockchain technology-in-fin tech - Anton SitnikovBlockchain technology-in-fin tech - Anton Sitnikov
Blockchain technology-in-fin tech - Anton SitnikovDataFest Tbilisi
 
Socket programming in C
Socket programming in CSocket programming in C
Socket programming in CDeepak Swain
 
以太坊代幣付款委託 @ Open Source Developer Meetup #12
以太坊代幣付款委託 @ Open Source Developer Meetup #12以太坊代幣付款委託 @ Open Source Developer Meetup #12
以太坊代幣付款委託 @ Open Source Developer Meetup #12Aludirk Wong
 
Powering Consistent, High-throughput, Real-time Distributed Calculation Engin...
Powering Consistent, High-throughput, Real-time Distributed Calculation Engin...Powering Consistent, High-throughput, Real-time Distributed Calculation Engin...
Powering Consistent, High-throughput, Real-time Distributed Calculation Engin...HostedbyConfluent
 
BA and Beyond 20 - Geert Haerens - Evolvable Architecture — Are you hoping fo...
BA and Beyond 20 - Geert Haerens - Evolvable Architecture — Are you hoping fo...BA and Beyond 20 - Geert Haerens - Evolvable Architecture — Are you hoping fo...
BA and Beyond 20 - Geert Haerens - Evolvable Architecture — Are you hoping fo...BA and Beyond
 
DataArt Innovation Showcase Blockchain Billing
DataArt Innovation Showcase Blockchain BillingDataArt Innovation Showcase Blockchain Billing
DataArt Innovation Showcase Blockchain BillingAlan Quayle
 

Similaire à Robust Programming of Smart Contracts in Solidity+, RK Shyamasundar (20)

A Decompiler for Blackhain-Based Smart Contracts Bytecode
A Decompiler for Blackhain-Based Smart Contracts BytecodeA Decompiler for Blackhain-Based Smart Contracts Bytecode
A Decompiler for Blackhain-Based Smart Contracts Bytecode
 
Ethereum
EthereumEthereum
Ethereum
 
An Introduction to Upgradable Smart Contracts
An Introduction to Upgradable Smart ContractsAn Introduction to Upgradable Smart Contracts
An Introduction to Upgradable Smart Contracts
 
Solidity Security and Best Coding Practices
Solidity Security and Best Coding PracticesSolidity Security and Best Coding Practices
Solidity Security and Best Coding Practices
 
J.burke HackMiami6
J.burke HackMiami6J.burke HackMiami6
J.burke HackMiami6
 
Solidity Simple Tutorial EN
Solidity Simple Tutorial ENSolidity Simple Tutorial EN
Solidity Simple Tutorial EN
 
Best practices to build secure smart contracts
Best practices to build secure smart contractsBest practices to build secure smart contracts
Best practices to build secure smart contracts
 
Starkware: Account Abstraction
Starkware: Account AbstractionStarkware: Account Abstraction
Starkware: Account Abstraction
 
Build on Streakk Chain - Blockchain
Build on Streakk Chain - BlockchainBuild on Streakk Chain - Blockchain
Build on Streakk Chain - Blockchain
 
Advanced smart contract
Advanced smart contractAdvanced smart contract
Advanced smart contract
 
ERC20 Token Contract
ERC20 Token ContractERC20 Token Contract
ERC20 Token Contract
 
Serverless Design Patterns (London Dev Community)
Serverless Design Patterns (London Dev Community)Serverless Design Patterns (London Dev Community)
Serverless Design Patterns (London Dev Community)
 
Blockchain Tokenization
Blockchain TokenizationBlockchain Tokenization
Blockchain Tokenization
 
Blockchain technology-in-fin tech - Anton Sitnikov
Blockchain technology-in-fin tech - Anton SitnikovBlockchain technology-in-fin tech - Anton Sitnikov
Blockchain technology-in-fin tech - Anton Sitnikov
 
Socket programming in C
Socket programming in CSocket programming in C
Socket programming in C
 
web3j Overview
web3j Overviewweb3j Overview
web3j Overview
 
以太坊代幣付款委託 @ Open Source Developer Meetup #12
以太坊代幣付款委託 @ Open Source Developer Meetup #12以太坊代幣付款委託 @ Open Source Developer Meetup #12
以太坊代幣付款委託 @ Open Source Developer Meetup #12
 
Powering Consistent, High-throughput, Real-time Distributed Calculation Engin...
Powering Consistent, High-throughput, Real-time Distributed Calculation Engin...Powering Consistent, High-throughput, Real-time Distributed Calculation Engin...
Powering Consistent, High-throughput, Real-time Distributed Calculation Engin...
 
BA and Beyond 20 - Geert Haerens - Evolvable Architecture — Are you hoping fo...
BA and Beyond 20 - Geert Haerens - Evolvable Architecture — Are you hoping fo...BA and Beyond 20 - Geert Haerens - Evolvable Architecture — Are you hoping fo...
BA and Beyond 20 - Geert Haerens - Evolvable Architecture — Are you hoping fo...
 
DataArt Innovation Showcase Blockchain Billing
DataArt Innovation Showcase Blockchain BillingDataArt Innovation Showcase Blockchain Billing
DataArt Innovation Showcase Blockchain Billing
 

Plus de Napier University

10. Data to Information: NumPy and Pandas
10. Data to Information: NumPy and Pandas10. Data to Information: NumPy and Pandas
10. Data to Information: NumPy and PandasNapier University
 
The Road Ahead for Ripple, Marjan Delatinne
The Road Ahead for Ripple, Marjan DelatinneThe Road Ahead for Ripple, Marjan Delatinne
The Road Ahead for Ripple, Marjan DelatinneNapier University
 
Delivering The Tel Aviv Stock Exchange Securities, Duncan Johnston-Watt
 Delivering The Tel Aviv Stock Exchange Securities, Duncan Johnston-Watt Delivering The Tel Aviv Stock Exchange Securities, Duncan Johnston-Watt
Delivering The Tel Aviv Stock Exchange Securities, Duncan Johnston-WattNapier University
 
RMIT Blockchain Innovation Hub, Chris Berg
RMIT Blockchain Innovation Hub, Chris BergRMIT Blockchain Innovation Hub, Chris Berg
RMIT Blockchain Innovation Hub, Chris BergNapier University
 
Browser-based Crypto M, C. F Mondschein
Browser-based Crypto M, C. F MondscheinBrowser-based Crypto M, C. F Mondschein
Browser-based Crypto M, C. F MondscheinNapier University
 
Should we transform or adapt to blockchain - a public sector perspective?, Al...
Should we transform or adapt to blockchain - a public sector perspective?, Al...Should we transform or adapt to blockchain - a public sector perspective?, Al...
Should we transform or adapt to blockchain - a public sector perspective?, Al...Napier University
 
IoT device attestation system using blockchain, Alistair Duke
IoT device attestation system using blockchain, Alistair DukeIoT device attestation system using blockchain, Alistair Duke
IoT device attestation system using blockchain, Alistair DukeNapier University
 
Using Blockchain for Evidence Purpose, Rafael Prabucki
Using Blockchain for Evidence Purpose, Rafael PrabuckiUsing Blockchain for Evidence Purpose, Rafael Prabucki
Using Blockchain for Evidence Purpose, Rafael PrabuckiNapier University
 
Cryptocurrencies and cyberlaundering- the need for regulation, Gian Marco Bov...
Cryptocurrencies and cyberlaundering- the need for regulation, Gian Marco Bov...Cryptocurrencies and cyberlaundering- the need for regulation, Gian Marco Bov...
Cryptocurrencies and cyberlaundering- the need for regulation, Gian Marco Bov...Napier University
 
Emerging Regulatory Approaches to Blockchain-based Token Economy, Agata Fereirra
Emerging Regulatory Approaches to Blockchain-based Token Economy, Agata FereirraEmerging Regulatory Approaches to Blockchain-based Token Economy, Agata Fereirra
Emerging Regulatory Approaches to Blockchain-based Token Economy, Agata FereirraNapier University
 
P2P Publication Model on Blockchain, Imtiaz Khan
P2P Publication Model on Blockchain, Imtiaz KhanP2P Publication Model on Blockchain, Imtiaz Khan
P2P Publication Model on Blockchain, Imtiaz KhanNapier University
 

Plus de Napier University (20)

Intrusion Detection Systems
Intrusion Detection SystemsIntrusion Detection Systems
Intrusion Detection Systems
 
Networks
NetworksNetworks
Networks
 
Memory, Big Data and SIEM
Memory, Big Data and SIEMMemory, Big Data and SIEM
Memory, Big Data and SIEM
 
What is Cyber Data?
What is Cyber Data?What is Cyber Data?
What is Cyber Data?
 
Open Source Intelligence
Open Source IntelligenceOpen Source Intelligence
Open Source Intelligence
 
10. Data to Information: NumPy and Pandas
10. Data to Information: NumPy and Pandas10. Data to Information: NumPy and Pandas
10. Data to Information: NumPy and Pandas
 
2. Defence Systems
2. Defence Systems2. Defence Systems
2. Defence Systems
 
1. Cyber and Intelligence
1. Cyber and Intelligence1. Cyber and Intelligence
1. Cyber and Intelligence
 
The Road Ahead for Ripple, Marjan Delatinne
The Road Ahead for Ripple, Marjan DelatinneThe Road Ahead for Ripple, Marjan Delatinne
The Road Ahead for Ripple, Marjan Delatinne
 
Delivering The Tel Aviv Stock Exchange Securities, Duncan Johnston-Watt
 Delivering The Tel Aviv Stock Exchange Securities, Duncan Johnston-Watt Delivering The Tel Aviv Stock Exchange Securities, Duncan Johnston-Watt
Delivering The Tel Aviv Stock Exchange Securities, Duncan Johnston-Watt
 
ARTiFACTS, Emma Boswood
ARTiFACTS, Emma BoswoodARTiFACTS, Emma Boswood
ARTiFACTS, Emma Boswood
 
RMIT Blockchain Innovation Hub, Chris Berg
RMIT Blockchain Innovation Hub, Chris BergRMIT Blockchain Innovation Hub, Chris Berg
RMIT Blockchain Innovation Hub, Chris Berg
 
Keynote, Naseem Naqvi
Keynote, Naseem Naqvi Keynote, Naseem Naqvi
Keynote, Naseem Naqvi
 
Browser-based Crypto M, C. F Mondschein
Browser-based Crypto M, C. F MondscheinBrowser-based Crypto M, C. F Mondschein
Browser-based Crypto M, C. F Mondschein
 
Should we transform or adapt to blockchain - a public sector perspective?, Al...
Should we transform or adapt to blockchain - a public sector perspective?, Al...Should we transform or adapt to blockchain - a public sector perspective?, Al...
Should we transform or adapt to blockchain - a public sector perspective?, Al...
 
IoT device attestation system using blockchain, Alistair Duke
IoT device attestation system using blockchain, Alistair DukeIoT device attestation system using blockchain, Alistair Duke
IoT device attestation system using blockchain, Alistair Duke
 
Using Blockchain for Evidence Purpose, Rafael Prabucki
Using Blockchain for Evidence Purpose, Rafael PrabuckiUsing Blockchain for Evidence Purpose, Rafael Prabucki
Using Blockchain for Evidence Purpose, Rafael Prabucki
 
Cryptocurrencies and cyberlaundering- the need for regulation, Gian Marco Bov...
Cryptocurrencies and cyberlaundering- the need for regulation, Gian Marco Bov...Cryptocurrencies and cyberlaundering- the need for regulation, Gian Marco Bov...
Cryptocurrencies and cyberlaundering- the need for regulation, Gian Marco Bov...
 
Emerging Regulatory Approaches to Blockchain-based Token Economy, Agata Fereirra
Emerging Regulatory Approaches to Blockchain-based Token Economy, Agata FereirraEmerging Regulatory Approaches to Blockchain-based Token Economy, Agata Fereirra
Emerging Regulatory Approaches to Blockchain-based Token Economy, Agata Fereirra
 
P2P Publication Model on Blockchain, Imtiaz Khan
P2P Publication Model on Blockchain, Imtiaz KhanP2P Publication Model on Blockchain, Imtiaz Khan
P2P Publication Model on Blockchain, Imtiaz Khan
 

Dernier

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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 

Dernier (20)

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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 

Robust Programming of Smart Contracts in Solidity+, RK Shyamasundar

  • 1. Robust Programming of Smart Contracts in Solidity+ RK Shyamasundar Department of Computer Science & Engg Indian Institute of Technology Bombay rkss@cse.iitb.ac.in (Joint work with Snehal Borse and Prateek Patidar) 11/03/2020 ICBC2020 1
  • 2. Smart Contracts • Smart contracts provide the feeling of sequential execution, but they are have stark similarity with shared variable programs. • One Comes across several vulnerabilities in Solidity – a widely used language on Ethereum • Realize robustness through methodologies of distributed programs over shared variables. – Explicit Declarations for concurrency and – Process Interaction – Specification of Concurrent Modules 11/03/2020 ICBC2020 2
  • 3. Approach • Capture the patterns of Vulnerabilities • Generalize the patterns as Declarations for the Programs • Declarations + Program Solidity program with Error handling Features like require, assert, revert 11/03/2020 ICBC2020 3 Automatic Transform Outline of Proof Carrying Code
  • 4. Advantages • Effective for Programmer - ease of programming • Debugging at the level of Solidity and not Ethereum • A sort of Informal framework of proof carrying code on the blockchain for smart contracts • Parallels ensuring data integrity without unnecessary mutual exclusion, permitting dynamic resource management. • Amenable structurally for formal correctness (Model Checkers or Verifiers) similar to concurrent programs 11/03/2020 ICBC2020 4
  • 5. Classic Shared Variable PL • 11/03/2020 ICBC2020 5
  • 6. 11/03/2020 ICBC2020 6 • SOLIDITY + • DECLARATIONS • NONREENTRANT • IMPORT • EXPORT • ACCESS • PARALLEL • INVAR … • contract Coin { • // The keyword "public" makes variables • // accessible from other contracts • address public minter; • mapping (address => uint) public balances; • // Events allow clients to react to specific • // contract changes you declare • event Sent(address from, address to, uint amount); • // Constructor code is only run when the contract • // is created • constructor() public { • minter = msg.sender; • } • // Sends an amount of newly created coins to an address • // Can only be called by the contract creator • function mint(address receiver, uint amount) public { • require(msg.sender == minter); • require(amount < 1e60); • balances[receiver] += amount; • } • // Sends an amount of existing coins • // from any caller to an address • function send(address receiver, uint amount) public { • require(amount <= balances[msg.sender], "Insufficient balance."); • balances[msg.sender] -= amount; • balances[receiver] += amount; • emit Sent(msg.sender, receiver, amount); • } • }
  • 9. SimpleDAO Attack 9 SimleDAO mapping (addr => uint) credit; function donate(uint amount) { credit[caller] += amount; } function withdraw(uint amt) { if(credit[withdrawer] >= amt) { send amt to withdrawer; reduce credit[withdrawer]; } } Attacker function atttack() { SimpleDAO.donate(1); SimpleDAO.withdraw(1); } function() { //Fallback Function SimpleDAO.withdraw(1); } Crowdfunding: Decentralized business model for organizing both commercial and non-profit enterprises
  • 10. Reentrancy in SimpleDAO 10 A.balance = 1; DAO.balance = 2; credit[A] = 0; A.running = false; A.balance = 0; DAO.balance = 3; credit[A] = 1; A.running = true; credit[A] = 1; amount = 1; A.balance = 1; DAO.balance = 2; credit[A] = 1; A.running = true; credit[A] = 1; amount = 1; A.balance = 2; DAO.balance = 1; credit[A] = 1; A.running = true; credit[A] = 1; amount = 1; A.balance = 3; DAO.balance = 0; credit[A] = 1; A.running = true; credit[A] = 1; amount = 1; A.balance = 3; DAO.balance = 0; credit[A] = 0; A.running = false; Attacker’s balance is more than what he/she donated. donate Initial state Final state withdraw withdraw withdraw withdraw A: Address of Attacker contract DAO: Address of DAO contract amount: Amount to be withdrawn running: flag to show if attacker is still running or not credit: mapping (addr => uint) donate: donate(1) withdraw: withdraw(1) A.balance = 3; DAO.balance = 0; credit[A] = 0; A.running = false; 11/03/2020 ICBC2020
  • 11. SimpleDAO Example 11 SimleDAO PARALLEL ( NIL) NONREENTRANT (withdraw) mapping (addr => uint) credit; function donate(uint amount) { credit[caller] += amount; } function withdraw(uint amt) { if(credit[withdrawer] >= amt) { send amt to withdrawer; reduce credit[withdrawer]; } } Attacker function atttack() { SimpleDAO.donate(1); SimpleDAO.withdraw(1); } function() { //Fallback Function SimpleDAO.withdraw(1); }
  • 13. After removal of Reentrancy 13 A.balance = 1; DAO.balance = 2; credit[A] = 0; A.running = false; callStack = {} A.balance = 0; DAO.balance = 3; credit[M] = 1; A.running = true; callStack = {“donate”} credit[A] = 1; amount = 1; isReentrant = false; callStack = {“withdraw”} A.balance = 1; DAO.balance = 2; credit[A] = 1; A.running = true; callStack = {“withdraw”} A.balance = 1; DAO.balance = 2; credit[A] = 0; A.running = false; callStack = {} credit[A] = 1; amount = 1; isReentrant = true; callStack = {“withdraw”} Final state Initial state Since withdraw was already present in callStack, stop executing donate withdraw withdraw A: Address of Attacker contract DAO: Address of DAO contract amount: Amount to be withdrawn running: flag to show if attacker is still running or not credit: mapping (addr => uint) callStack: to store which functions of a contract are called 11/03/2020 ICBC2020
  • 15. Require(1) • The require function should be used to ensure valid conditions that cannot be detected until execution time. • These conditions include inputs, or contract state variables are met, or to validate return values from calls to external contracts. • You can optionally provide a message string for require, but not for assert. 11/03/2020 ICBC2020 15
  • 16. Require (2) • Internally, Solidity performs a revert operation (instruction 0xfd) for a require-style exception and executes an invalid operation (instruction 0xfe) to throw an assert-style exception. • In both cases, this causes the EVM to revert all changes made to the state. • The reason for reverting is that there is no safe way to continue execution, because an expected effect did not occur. • Because we want to keep the atomicity of transactions, the safest action is to revert all changes and make the whole transaction (or at least call) without effect. 11/03/2020 ICBC2020 16
  • 17. Assert • The assert function should only be used to test for internal errors, and to check invariants. • Properly functioning code should never reach a failing assert statement; – if this happens there is a bug in your contract which you should fix. – Language analysis tools can evaluate your contract to identify the conditions and function calls which will reach a failing assert. 11/03/2020 ICBC2020 17
  • 18. Assert and Require • assert-style exceptions consume all gas available to the call, • while require-style exceptions do not consume any gas starting from the Metropolis release. 11/03/2020 ICBC2020 18
  • 19. Revert 11/03/2020 ICBC2020 19 • The revert function is another way to trigger exceptions from within other code blocks to flag an error and revert the current call. • The function takes an optional string message containing details about the error that is passed back to the caller.
  • 21. Concurrency 21 contract GetterSetter { uint balance; function get() returns (uint) { return balance; } function set(uint x) { balance = x; } } C1 calls set(100); C2 calls set(50); C1 calls get(); - returns 50 C2 calls get(); - returns 50 C1 calls set(100); C1 calls get(); - returns 100 C2 calls set(50); C2 calls get(); - returns 50 C1 calls set(100); C1 calls get(); - returns 100 C2 calls set(50); C2 calls get(); - returns 50 C1 calls set(100); C2 calls set(50); C1 calls get(); - returns 50 C2 calls get(); - returns 50
  • 23. 11/03/2020 ICBC2020 23 ACCESS (get set) PARALLEL (Get, Get)
  • 25. 11/03/2020 ICBC2020 25 Also No Parallel Invokations
  • 26. ERC20 • ERC20 is a technical standard used for smart contracts on the Ethereum blockchain for implementing tokens. • ERC-20 token standard became popular with crowdfunding companies working on initial coin offering (ICO) cases due to simplicity of deployment, together with its potential for interoperability with other Ethereum token standards. 11/03/2020 ICBC2020 26
  • 28. ERC20(2) • Alice allows Bob to transfer 100 of Alice’s token by calling approve(Bob’s address, 100). • After some time Alice decides to change the approved token from 100 to 50, so she calls approve(Bob’s address, 50). • Before Alice’s second transaction was mined, Bob calls transferFrom to transfer 100 Alice’s tokens somewhere. • If Bob’s transaction will be executed before Alice’s then Bob has already transferred 100 tokens and now additionally has permission to transfer 50 tokens. • Before Alice notices that something went wrong, • Bob calls Transfer from to transfer 50 Alice’s token to somewhere. • Nondeterminism: • Alice initially wanted to change the allowed tokens from 100 to 50 but this change made it possible for Bob to transfer 150 tokens. Alice never wanted to allow Bob to spend this much of her tokens. 11/03/2020 ICBC2020 28
  • 29. 11/03/2020 ICBC2020 29 ACCESS (approve)* or (approve)+((allowance) (transferFrom))* or ((allowance) (transferFrom))*
  • 31. Gasless send contract Sender { function transferAmt() { receiver.send(n); print(“Successfully sent n ether to receiver”); } } contract Receiver { uint x = 0; function() { //Fallback function } } 33 ◎ send: predefined amount of gas i.e. 2300 which can’t be changed ◎ Sufficient for Fallback function without state change ◎ Insufficient for Fallback function with state change contract Sender { function transferAmt() { receiver.send(n); print(“Successfully sent n ether to receiver”); } } contract Receiver { uint x = 0; function() { x++; } } Successful ◎ send: predefined amount of gas i.e. 2300 which can’t be changed ◎ Sufficient for Fallback function without state change Failed contract Sender { function transferAmt() { receiver.send(n); print(“Successfully sent n ether to receiver”); } } contract Receiver { uint x = 0; function() { x++; } }
  • 32. Gasless Send Solution 34 ◎ Whenever there is a transfer of ether using send function, use guard function for that send call contract Sender { function transferAmt() { require(receiver.send(n), “Insufficient gas”); print(“Successfully sent n ether to receiver”); } } contract Receiver { uint x = 0; function() { x++; } } FAIL
  • 34. Classic Shared Variable PL • 11/03/2020 ICBC2020 36
  • 36. Transaction Order • ACCESS (get set) • PARALLEL (Get Get) // functions not mentioned cannot execute in parallel 11/03/2020 ICBC2020 38
  • 37. SimpleDAO Attack 39 SimleDAO mapping (addr => uint) credit; function donate(uint amount) { credit[caller] += amount; } function withdraw(uint amt) { if(credit[withdrawer] >= amt) { send amt to withdrawer; reduce credit[withdrawer]; } } Attacker function atttack() { SimpleDAO.donate(1); SimpleDAO.withdraw(1); } function() { //Fallback Function SimpleDAO.withdraw(1); }
  • 38. DAO Program with Checks in Solidity+ • PARALLEL (NIL) • NONREENTRANT ( withdraw) 11/03/2020 ICBC2020 40
  • 40. ERC20 • ACCESS (approve)* or • (approve)+((allowance) (transferFrom))* or • ((allowance) (transferFrom))* 11/03/2020 ICBC2020 42
  • 43. Type Cast Transformed 45 contract A { function foo() { print(“Calling foo of contract A”); } } contract B { function foo() { print(“Calling foo of contract B”); } } contract C{ function callFoo(A a) { //call foo() of A require(a==Addr of A, “Calling apprpriate foo()”); a.foo(); } } callFoo(addr of A): succeed callFoo(addr of B): failed
  • 44. 11/03/2020 ICBC2020 46 • SOLIDITY + • DECLARATIONS • IMPORT • EXPORT • ACCESS • PARALLEL • NONREENTRANT • INVAR … • contract Coin { • // The keyword "public" makes variables • // accessible from other contracts • address public minter; • mapping (address => uint) public balances; • // Events allow clients to react to specific • // contract changes you declare • event Sent(address from, address to, uint amount); • // Constructor code is only run when the contract • // is created • constructor() public { • minter = msg.sender; • } • // Sends an amount of newly created coins to an address • // Can only be called by the contract creator • function mint(address receiver, uint amount) public { • require(msg.sender == minter); • require(amount < 1e60); • balances[receiver] += amount; • } • // Sends an amount of existing coins • // from any caller to an address • function send(address receiver, uint amount) public { • require(amount <= balances[msg.sender], "Insufficient balance."); • balances[msg.sender] -= amount; • balances[receiver] += amount; • emit Sent(msg.sender, receiver, amount); • } • }
  • 45. Merits of Solidity+ 1. Solidity and Solidity+ executionally remain unchanged without adding burden on the programmer. 2. It only adds runtime checks to the program as per declarations. 3. Allows programmer to debug at the source level itself rather than EVM. 4. An informal framework for proof carrying smart contracts, Adaptable for formal correctness as well (model checking, theorem prover …) 11/03/2020 ICBC2020 47
  • 47. Graph Generation 49 ◎ In addition to the transformation into Solidity+, we generate a graph of a Solidity program ◎ As pictures speak more than words, it makes easier for naive user to understand the flow of a program ◎ After graph generation, we try to find out a pattern for a vulnerability and make conclusive statement about the contract
  • 48. Graph for reentrant SimpleDAO 50 Reentranc y 11/03/2020 ICBC2020
  • 50. Related Work ◎ Oyente [2] ○ Based on symbolic execution ○ Creates CFG for bytecode ◎ Mythril OSS [7] ○ Based on concolic execution, taint analysis and control flow checking ◎ Problems with the above approaches: ○ Neither sound nor complete ○ Several false alarms even in trivial contracts ○ Hard to recreate the intent from bytecode alone 52
  • 51. Related Work ◎ F* [4] ○ Presents two tools which are based on shallow embedding in F* ○ Does not handle loops ○ Only a subset of Solidity is translated to F* ○ Reasoning may require manual proofs ◎ Why3 [8] ○ Supports only a small subset of entire syntax ○ Solidity to Why3 translation is not yet tested and can not be trusted ◎ ZEUS [3] ○ Based on abstract interpretation and symbolic model checking ○ Conducts policy checking based on user provided policies 53
  • 52. Related Work ◎ Securify [5] ○ Derives semantic facts inferred by analyzing the contract’s dependency graph ○ Uses these facts to check a set of compliance and violation patterns ◎ Hirai et al. [9] ○ Used the Isabelle proof assistant and Lem language ○ Defined a formal model for the Ethereum Virtual Machine ○ Proved safety properties of smart contracts using existing interactive theorem provers ◎ Amani et al. [10] ○ Extended the existing EVM formalisation by Hirai et al. ○ Structured the bytecode sequences into basic blocks and created a program logic to reason about these 54
  • 53. Related Work ◎ KEVM [11] ○ A formal semantics of the EVM written using the K-framework ○ Properties are specified in Reachability Logic and verified with a separate analysis tool ◎ Grishchenko et al. [12] ○ Complete small-step semantics of EVM bytecode ○ Formalized in the F* proof assistant ○ Also formalized a number of security properties ◎ Jiao et al. [13] ○ Defined a small-step operational semantics for a subset of the Solidity language ○ Their work is executable in the K-framework ◎ All the above semantics are executable and were validated against the official Ethereum test suite. 55