SlideShare a Scribd company logo
1 of 19
Australiaโ€™s National Science Agency
Smart
Contract
Testing
Dilum Bandara
| Architecture & Analytics Platforms (AAP) team
| Data61, CSIRO
| Dilum.Bandara@data61.csiro.au
Failures in Blockchains are Catastrophic
2 | Source: https://magoo.github.io/Blockchain-Graveyard/
Test Scope of Blockchain-Based Applications
3 |
Access control
& KYC
Smart contract
Integration
Data
management
Cryptography &
Key management
Infrastructure
Consensus
Privacy
DApp
architecture
Scalability &
Performance
Governance &
Compliance
Known Issues/Vulnerabilities
4 |
Known Issues/Vulnerabilities in SCs
โ€ข Race conditions
โ€“ Reentrancy
โ€“ Cross-function race conditions
โ€“ Deadlocks
โ€ข Denial of Service (DoS)
โ€“ Unexpected throw
โ€“ Size/gas limit
โ€“ SC calls & block
โ€ข Arithmetic
overflow/underflow
โ€ข TX order dependence
โ€ข Front running
โ€ข Timestamp & block no
dependence
โ€“ Random no
โ€ข Access control
โ€“ Ability to call selfdestruct()
โ€ข Bad error handling
โ€ข Language-specific behaviour
โ€“ In solidity SC owner is set at time
of initialization
โ€“ Depreciated functions
โ€“ Short address attack in EVM
โ€“ Call stack depth
5 |
Arithmetic Overflow/Underflow
6 |
mapping (address => uint256) public balanceOf;
function transfer(address _to, uint256 _value) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
}
function transfer(address _to, uint256 _value) {
require(balanceOf[msg.sender] >= _value &&
balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
}
Source: https://github.com/ConsenSys/smart-contract-best-
practices/blob/master/docs/known_attacks.md
Another solution is to use
SafeMath.sol library
Single Function Reentrancy
7 |
Source: https://github.com/ConsenSys/smart-contract-best-
practices/blob/master/docs/known_attacks.md
mapping (address => uint) private userBalances;
function withdrawBalance() public {
uint amountToWithdraw = userBalances[msg.sender];
(bool success, ) = msg.sender.call.value(amountToWithdraw)("");
require(success);
userBalances[msg.sender] = 0;
}
withdrawBalance() Value()
Cross Function Reentrancy
8 |
Source: https://github.com/ConsenSys/smart-contract-best-
practices/blob/master/docs/known_attacks.md
mapping (address => uint) private userBalances;
function transfer(address to, uint amount) {
if (userBalances[msg.sender] >= amount) {
userBalances[to] += amount;
userBalances[msg.sender] -= amount;
}
}
function withdrawBalance() public {
uint amountToWithdraw = userBalances[msg.sender];
(bool success, ) = msg.sender.call.value(amountToWithdraw)("");
require(success);
userBalances[msg.sender] = 0;
}
withdrawBalance()
Value()
transfer()
Cross Function Reentrancy โ€“ Failure Case
9 |
Source: https://github.com/ConsenSys/smart-contract-best-
practices/blob/master/docs/known_attacks.md
mapping (address => uint) private userBalances;
mapping (address => bool) private claimedBonus;
mapping (address => uint) private rewardsForA;
function withdrawReward(address recipient) public {
uint amountToWithdraw = rewardsForA[recipient];
rewardsForA[recipient] = 0;
(bool success, ) = recipient.call.value(amountToWithdraw)("");
require(success);
}
function getFirstWithdrawalBonus(address recipient) public {
require(!claimedBonus[recipient]);
rewardsForA[recipient] += 100;
withdrawReward(recipient);
claimedBonus[recipient] = true;
}
Tools & Techniques
10 |
โ€ข Avoid external calls
โ€“ Finish all internal work before making external calls
โ€“ Favour pull over push โ€“ Let users withdraw funds
โ€“ Use send() over call.value() โ€“ send() has a fixed gas limit of 2,300
โ€“ Keep fallback function simple
โ€ข Good programming practices
โ€“ Explicitly set visibility of functions & variables
โ€“ Exception handling โ€“ Be aware of different function behaviour
โ€“ Reuse well-tested code
โ€“ Use libraries/languages that prevent overflow & underflow
โ€“ Upgradable contracts โ€“ No hardcoded addresses, Proxy & SC Registry patterns
โ€ข Avoid multi-party contracts โ€“ One party may disappear
โ€ข Rate limiting โ€“ No of calls & crypto
Best Practices
11 |
Types of Software Testing
12 |
Software
Testing
Static
Source
code
Byte
code
Dynamic
White
box
Black
box
Code Smells[1]
13 |
[1] Chen, Jiachi, Xin Xia, David Lo, John Grundy, Daniel Xiapu Luo, and Ting Chen. "Domain Specific Code Smells in
Smart Contracts." arXiv preprint arXiv:1905.01467 (2019).
Ethereum SC
Testing
Solution
Space
14 |
Source: Di Angelo, M., & Salzer,
G. (2019, April). A survey of tools
for analyzing Ethereum smart
contracts. In 2019 IEEE Int. Conf.
on Decentralized Applications
and Infrastructures (DAPPCON).
Ethereum SC Security Testing Solutions
15 |
Source: Di Angelo,
M., & Salzer, G.
(2019, April).
โ€ข Fuzz testing โ€“ Automated testing
by providing invalid, unexpected,
or random data as inputs
โ€ข Set of test oracles
โ€ข Gasless send
โ€ข Exception disorder
โ€ข Reentrancy
โ€ข Timestamp dependency
โ€ข Block no dependency
โ€ข Dangerous delegate calls
โ€ข Freezing Ether
ContractFuzzer โ€“ Fuzzing SCs for Vulnerability
Detection[2]
16 |
[2] Jiang, Bo, Ye Liu, and W. K. Chan. "Contractfuzzer: Fuzzing smart
contracts for vulnerability detection." In Proc. 33rd ACM/IEEE Intl. Conf.
on Automated Software Engineering, pp. 259-269. ACM, 2018.
โ€ข Use an intermediate representation called Slither
โ€ข Supports security testing, code optimization, review, & user
understanding
Slither โ€“ A Static Analysis Framework for SCs[3]
17 |
[3] Feist, Josselin, Gustavo Grieco, and Alex Groce. "Slither: a static analysis framework for smart contracts." In 2019
IEEE/ACM 2nd Intl. Workshop on Emerging Trends in Software Engineering for Blockchain (WETSEB), pp. 8-15. IEEE, 2019.
Other Tools[4]
18 |
[4] Parizi, Reza M. et al., "Empirical vulnerability analysis of automated smart contracts security testing on blockchains." In
Proc. 28th Annual Intl. Conf. on Computer Science and Software Engineering, pp. 103-113, 2018.
Australiaโ€™s National Science Agency
Dilum.Bandara@
data61.csiro.au
linkedin.com/in/dilumb/
19 |

More Related Content

What's hot

Blockchain
BlockchainBlockchain
Blockchain
Liam Moore
ย 

What's hot (20)

Blockchain
BlockchainBlockchain
Blockchain
ย 
Exploring Blockchain Technology, Risks, and Emerging Trends
Exploring Blockchain Technology, Risks, and Emerging TrendsExploring Blockchain Technology, Risks, and Emerging Trends
Exploring Blockchain Technology, Risks, and Emerging Trends
ย 
Blockchain Technology | Blockchain Explained | Blockchain Tutorial | Blockcha...
Blockchain Technology | Blockchain Explained | Blockchain Tutorial | Blockcha...Blockchain Technology | Blockchain Explained | Blockchain Tutorial | Blockcha...
Blockchain Technology | Blockchain Explained | Blockchain Tutorial | Blockcha...
ย 
Block chain 101 what it is, why it matters
Block chain 101  what it is, why it mattersBlock chain 101  what it is, why it matters
Block chain 101 what it is, why it matters
ย 
Blockchain basics
Blockchain basicsBlockchain basics
Blockchain basics
ย 
Smart contracts using web3.js
Smart contracts using web3.jsSmart contracts using web3.js
Smart contracts using web3.js
ย 
Blockchain Essentials and Blockchain on Azure
Blockchain Essentials and Blockchain on AzureBlockchain Essentials and Blockchain on Azure
Blockchain Essentials and Blockchain on Azure
ย 
Blockchain Explained | Blockchain Simplified | Blockchain Technology | Blockc...
Blockchain Explained | Blockchain Simplified | Blockchain Technology | Blockc...Blockchain Explained | Blockchain Simplified | Blockchain Technology | Blockc...
Blockchain Explained | Blockchain Simplified | Blockchain Technology | Blockc...
ย 
Blockchain
BlockchainBlockchain
Blockchain
ย 
An Introduction to Blockchain Technology
An Introduction to Blockchain Technology An Introduction to Blockchain Technology
An Introduction to Blockchain Technology
ย 
The Blockchain - The Technology behind Bitcoin
The Blockchain - The Technology behind Bitcoin The Blockchain - The Technology behind Bitcoin
The Blockchain - The Technology behind Bitcoin
ย 
Blockchain Presentation
Blockchain PresentationBlockchain Presentation
Blockchain Presentation
ย 
Blockchain
BlockchainBlockchain
Blockchain
ย 
Introduction to Blockchain
Introduction to BlockchainIntroduction to Blockchain
Introduction to Blockchain
ย 
Blockchain ppt
Blockchain pptBlockchain ppt
Blockchain ppt
ย 
Blockchain in Real Estate
Blockchain in Real EstateBlockchain in Real Estate
Blockchain in Real Estate
ย 
Blockchain 101 presentation by fstream.io
Blockchain 101 presentation by fstream.ioBlockchain 101 presentation by fstream.io
Blockchain 101 presentation by fstream.io
ย 
An introduction to block chain technology
An introduction to block chain technologyAn introduction to block chain technology
An introduction to block chain technology
ย 
Introduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart ContractsIntroduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart Contracts
ย 
Blockchain: The Information Technology of the Future
Blockchain: The Information Technology of the FutureBlockchain: The Information Technology of the Future
Blockchain: The Information Technology of the Future
ย 

Similar to Smart Contract Testing

Application Security
Application SecurityApplication Security
Application Security
florinc
ย 
Applying Provenance in APT Monitoring and Analysis Practical Challenges for S...
Applying Provenance in APT Monitoring and Analysis Practical Challenges for S...Applying Provenance in APT Monitoring and Analysis Practical Challenges for S...
Applying Provenance in APT Monitoring and Analysis Practical Challenges for S...
Graeme Jenkinson
ย 
Secure and Privacy-Preserving Big-Data Processing
Secure and Privacy-Preserving Big-Data ProcessingSecure and Privacy-Preserving Big-Data Processing
Secure and Privacy-Preserving Big-Data Processing
Shantanu Sharma
ย 

Similar to Smart Contract Testing (20)

Design Patterns para Microsserviรงos com MicroProfile
 Design Patterns para Microsserviรงos com MicroProfile Design Patterns para Microsserviรงos com MicroProfile
Design Patterns para Microsserviรงos com MicroProfile
ย 
Student Spring 2021
Student Spring 2021Student Spring 2021
Student Spring 2021
ย 
Smart Contract Security Testing
Smart Contract Security TestingSmart Contract Security Testing
Smart Contract Security Testing
ย 
DEF CON 24 - Sean Metcalf - beyond the mcse red teaming active directory
DEF CON 24 - Sean Metcalf - beyond the mcse red teaming active directoryDEF CON 24 - Sean Metcalf - beyond the mcse red teaming active directory
DEF CON 24 - Sean Metcalf - beyond the mcse red teaming active directory
ย 
Sumo Logic Cert Jam - Security Analytics
Sumo Logic Cert Jam - Security AnalyticsSumo Logic Cert Jam - Security Analytics
Sumo Logic Cert Jam - Security Analytics
ย 
Kamailio - SIP Firewall for Carrier Grade Traffic
Kamailio - SIP Firewall for Carrier Grade TrafficKamailio - SIP Firewall for Carrier Grade Traffic
Kamailio - SIP Firewall for Carrier Grade Traffic
ย 
Implementation domain driven design - ch04 architecture
Implementation domain driven design - ch04 architectureImplementation domain driven design - ch04 architecture
Implementation domain driven design - ch04 architecture
ย 
Application Security
Application SecurityApplication Security
Application Security
ย 
SANS_PentestHackfest_2022-PurpleTeam_Cloud_Identity.pptx
SANS_PentestHackfest_2022-PurpleTeam_Cloud_Identity.pptxSANS_PentestHackfest_2022-PurpleTeam_Cloud_Identity.pptx
SANS_PentestHackfest_2022-PurpleTeam_Cloud_Identity.pptx
ย 
Application Security from the Inside - OWASP
Application Security from the Inside - OWASPApplication Security from the Inside - OWASP
Application Security from the Inside - OWASP
ย 
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
ย 
Security in Node.JS and Express:
Security in Node.JS and Express:Security in Node.JS and Express:
Security in Node.JS and Express:
ย 
Applying Provenance in APT Monitoring and Analysis Practical Challenges for S...
Applying Provenance in APT Monitoring and Analysis Practical Challenges for S...Applying Provenance in APT Monitoring and Analysis Practical Challenges for S...
Applying Provenance in APT Monitoring and Analysis Practical Challenges for S...
ย 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)
ย 
Verifiable Round-Robin Scheme for Smart Homes (CODASPY 2019)
Verifiable Round-Robin Scheme for Smart Homes (CODASPY 2019)Verifiable Round-Robin Scheme for Smart Homes (CODASPY 2019)
Verifiable Round-Robin Scheme for Smart Homes (CODASPY 2019)
ย 
MongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDBMongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDB
ย 
IRJET- An Approach for Implemented Secure Proxy Server for Multi-User Searcha...
IRJET- An Approach for Implemented Secure Proxy Server for Multi-User Searcha...IRJET- An Approach for Implemented Secure Proxy Server for Multi-User Searcha...
IRJET- An Approach for Implemented Secure Proxy Server for Multi-User Searcha...
ย 
Beyond the mcse red teaming active directory
Beyond the mcse  red teaming active directoryBeyond the mcse  red teaming active directory
Beyond the mcse red teaming active directory
ย 
Secure and Privacy-Preserving Big-Data Processing
Secure and Privacy-Preserving Big-Data ProcessingSecure and Privacy-Preserving Big-Data Processing
Secure and Privacy-Preserving Big-Data Processing
ย 
NET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxNET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptx
ย 

More from Dilum Bandara

More from Dilum Bandara (20)

Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine Learning
ย 
Time Series Analysis and Forecasting in Practice
Time Series Analysis and Forecasting in PracticeTime Series Analysis and Forecasting in Practice
Time Series Analysis and Forecasting in Practice
ย 
Introduction to Dimension Reduction with PCA
Introduction to Dimension Reduction with PCAIntroduction to Dimension Reduction with PCA
Introduction to Dimension Reduction with PCA
ย 
Introduction to Descriptive & Predictive Analytics
Introduction to Descriptive & Predictive AnalyticsIntroduction to Descriptive & Predictive Analytics
Introduction to Descriptive & Predictive Analytics
ย 
Introduction to Concurrent Data Structures
Introduction to Concurrent Data StructuresIntroduction to Concurrent Data Structures
Introduction to Concurrent Data Structures
ย 
Hard to Paralelize Problems: Matrix-Vector and Matrix-Matrix
Hard to Paralelize Problems: Matrix-Vector and Matrix-MatrixHard to Paralelize Problems: Matrix-Vector and Matrix-Matrix
Hard to Paralelize Problems: Matrix-Vector and Matrix-Matrix
ย 
Introduction to Map-Reduce Programming with Hadoop
Introduction to Map-Reduce Programming with HadoopIntroduction to Map-Reduce Programming with Hadoop
Introduction to Map-Reduce Programming with Hadoop
ย 
Embarrassingly/Delightfully Parallel Problems
Embarrassingly/Delightfully Parallel ProblemsEmbarrassingly/Delightfully Parallel Problems
Embarrassingly/Delightfully Parallel Problems
ย 
Introduction to Warehouse-Scale Computers
Introduction to Warehouse-Scale ComputersIntroduction to Warehouse-Scale Computers
Introduction to Warehouse-Scale Computers
ย 
Introduction to Thread Level Parallelism
Introduction to Thread Level ParallelismIntroduction to Thread Level Parallelism
Introduction to Thread Level Parallelism
ย 
CPU Memory Hierarchy and Caching Techniques
CPU Memory Hierarchy and Caching TechniquesCPU Memory Hierarchy and Caching Techniques
CPU Memory Hierarchy and Caching Techniques
ย 
Data-Level Parallelism in Microprocessors
Data-Level Parallelism in MicroprocessorsData-Level Parallelism in Microprocessors
Data-Level Parallelism in Microprocessors
ย 
Instruction Level Parallelism โ€“ Hardware Techniques
Instruction Level Parallelism โ€“ Hardware TechniquesInstruction Level Parallelism โ€“ Hardware Techniques
Instruction Level Parallelism โ€“ Hardware Techniques
ย 
Instruction Level Parallelism โ€“ Compiler Techniques
Instruction Level Parallelism โ€“ Compiler TechniquesInstruction Level Parallelism โ€“ Compiler Techniques
Instruction Level Parallelism โ€“ Compiler Techniques
ย 
CPU Pipelining and Hazards - An Introduction
CPU Pipelining and Hazards - An IntroductionCPU Pipelining and Hazards - An Introduction
CPU Pipelining and Hazards - An Introduction
ย 
Advanced Computer Architecture โ€“ An Introduction
Advanced Computer Architecture โ€“ An IntroductionAdvanced Computer Architecture โ€“ An Introduction
Advanced Computer Architecture โ€“ An Introduction
ย 
High Performance Networking with Advanced TCP
High Performance Networking with Advanced TCPHigh Performance Networking with Advanced TCP
High Performance Networking with Advanced TCP
ย 
Introduction to Content Delivery Networks
Introduction to Content Delivery NetworksIntroduction to Content Delivery Networks
Introduction to Content Delivery Networks
ย 
Peer-to-Peer Networking Systems and Streaming
Peer-to-Peer Networking Systems and StreamingPeer-to-Peer Networking Systems and Streaming
Peer-to-Peer Networking Systems and Streaming
ย 
Mobile Services
Mobile ServicesMobile Services
Mobile Services
ย 

Recently uploaded

CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female serviceCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
ย 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
ย 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
ย 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
bodapatigopi8531
ย 
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธ
anilsa9823
ย 

Recently uploaded (20)

How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
ย 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
ย 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
ย 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
ย 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
ย 
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female serviceCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
ย 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
ย 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
ย 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
ย 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
ย 
Vip Call Girls Noida โžก๏ธ Delhi โžก๏ธ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida โžก๏ธ Delhi โžก๏ธ 9999965857 No Advance 24HRS LiveVip Call Girls Noida โžก๏ธ Delhi โžก๏ธ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida โžก๏ธ Delhi โžก๏ธ 9999965857 No Advance 24HRS Live
ย 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...
ย 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
ย 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
ย 
Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...
ย 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
ย 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
ย 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
ย 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
ย 
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธ
ย 

Smart Contract Testing

  • 1. Australiaโ€™s National Science Agency Smart Contract Testing Dilum Bandara | Architecture & Analytics Platforms (AAP) team | Data61, CSIRO | Dilum.Bandara@data61.csiro.au
  • 2. Failures in Blockchains are Catastrophic 2 | Source: https://magoo.github.io/Blockchain-Graveyard/
  • 3. Test Scope of Blockchain-Based Applications 3 | Access control & KYC Smart contract Integration Data management Cryptography & Key management Infrastructure Consensus Privacy DApp architecture Scalability & Performance Governance & Compliance
  • 5. Known Issues/Vulnerabilities in SCs โ€ข Race conditions โ€“ Reentrancy โ€“ Cross-function race conditions โ€“ Deadlocks โ€ข Denial of Service (DoS) โ€“ Unexpected throw โ€“ Size/gas limit โ€“ SC calls & block โ€ข Arithmetic overflow/underflow โ€ข TX order dependence โ€ข Front running โ€ข Timestamp & block no dependence โ€“ Random no โ€ข Access control โ€“ Ability to call selfdestruct() โ€ข Bad error handling โ€ข Language-specific behaviour โ€“ In solidity SC owner is set at time of initialization โ€“ Depreciated functions โ€“ Short address attack in EVM โ€“ Call stack depth 5 |
  • 6. Arithmetic Overflow/Underflow 6 | mapping (address => uint256) public balanceOf; function transfer(address _to, uint256 _value) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; } function transfer(address _to, uint256 _value) { require(balanceOf[msg.sender] >= _value && balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; } Source: https://github.com/ConsenSys/smart-contract-best- practices/blob/master/docs/known_attacks.md Another solution is to use SafeMath.sol library
  • 7. Single Function Reentrancy 7 | Source: https://github.com/ConsenSys/smart-contract-best- practices/blob/master/docs/known_attacks.md mapping (address => uint) private userBalances; function withdrawBalance() public { uint amountToWithdraw = userBalances[msg.sender]; (bool success, ) = msg.sender.call.value(amountToWithdraw)(""); require(success); userBalances[msg.sender] = 0; } withdrawBalance() Value()
  • 8. Cross Function Reentrancy 8 | Source: https://github.com/ConsenSys/smart-contract-best- practices/blob/master/docs/known_attacks.md mapping (address => uint) private userBalances; function transfer(address to, uint amount) { if (userBalances[msg.sender] >= amount) { userBalances[to] += amount; userBalances[msg.sender] -= amount; } } function withdrawBalance() public { uint amountToWithdraw = userBalances[msg.sender]; (bool success, ) = msg.sender.call.value(amountToWithdraw)(""); require(success); userBalances[msg.sender] = 0; } withdrawBalance() Value() transfer()
  • 9. Cross Function Reentrancy โ€“ Failure Case 9 | Source: https://github.com/ConsenSys/smart-contract-best- practices/blob/master/docs/known_attacks.md mapping (address => uint) private userBalances; mapping (address => bool) private claimedBonus; mapping (address => uint) private rewardsForA; function withdrawReward(address recipient) public { uint amountToWithdraw = rewardsForA[recipient]; rewardsForA[recipient] = 0; (bool success, ) = recipient.call.value(amountToWithdraw)(""); require(success); } function getFirstWithdrawalBonus(address recipient) public { require(!claimedBonus[recipient]); rewardsForA[recipient] += 100; withdrawReward(recipient); claimedBonus[recipient] = true; }
  • 11. โ€ข Avoid external calls โ€“ Finish all internal work before making external calls โ€“ Favour pull over push โ€“ Let users withdraw funds โ€“ Use send() over call.value() โ€“ send() has a fixed gas limit of 2,300 โ€“ Keep fallback function simple โ€ข Good programming practices โ€“ Explicitly set visibility of functions & variables โ€“ Exception handling โ€“ Be aware of different function behaviour โ€“ Reuse well-tested code โ€“ Use libraries/languages that prevent overflow & underflow โ€“ Upgradable contracts โ€“ No hardcoded addresses, Proxy & SC Registry patterns โ€ข Avoid multi-party contracts โ€“ One party may disappear โ€ข Rate limiting โ€“ No of calls & crypto Best Practices 11 |
  • 12. Types of Software Testing 12 | Software Testing Static Source code Byte code Dynamic White box Black box
  • 13. Code Smells[1] 13 | [1] Chen, Jiachi, Xin Xia, David Lo, John Grundy, Daniel Xiapu Luo, and Ting Chen. "Domain Specific Code Smells in Smart Contracts." arXiv preprint arXiv:1905.01467 (2019).
  • 14. Ethereum SC Testing Solution Space 14 | Source: Di Angelo, M., & Salzer, G. (2019, April). A survey of tools for analyzing Ethereum smart contracts. In 2019 IEEE Int. Conf. on Decentralized Applications and Infrastructures (DAPPCON).
  • 15. Ethereum SC Security Testing Solutions 15 | Source: Di Angelo, M., & Salzer, G. (2019, April).
  • 16. โ€ข Fuzz testing โ€“ Automated testing by providing invalid, unexpected, or random data as inputs โ€ข Set of test oracles โ€ข Gasless send โ€ข Exception disorder โ€ข Reentrancy โ€ข Timestamp dependency โ€ข Block no dependency โ€ข Dangerous delegate calls โ€ข Freezing Ether ContractFuzzer โ€“ Fuzzing SCs for Vulnerability Detection[2] 16 | [2] Jiang, Bo, Ye Liu, and W. K. Chan. "Contractfuzzer: Fuzzing smart contracts for vulnerability detection." In Proc. 33rd ACM/IEEE Intl. Conf. on Automated Software Engineering, pp. 259-269. ACM, 2018.
  • 17. โ€ข Use an intermediate representation called Slither โ€ข Supports security testing, code optimization, review, & user understanding Slither โ€“ A Static Analysis Framework for SCs[3] 17 | [3] Feist, Josselin, Gustavo Grieco, and Alex Groce. "Slither: a static analysis framework for smart contracts." In 2019 IEEE/ACM 2nd Intl. Workshop on Emerging Trends in Software Engineering for Blockchain (WETSEB), pp. 8-15. IEEE, 2019.
  • 18. Other Tools[4] 18 | [4] Parizi, Reza M. et al., "Empirical vulnerability analysis of automated smart contracts security testing on blockchains." In Proc. 28th Annual Intl. Conf. on Computer Science and Software Engineering, pp. 103-113, 2018.
  • 19. Australiaโ€™s National Science Agency Dilum.Bandara@ data61.csiro.au linkedin.com/in/dilumb/ 19 |

Editor's Notes

  1. For about 3-years, I have been researching on BC-based applications, data migration, workloads, & performance I have also involved in BC architecture & security assessment of a couple of supply chain & capital market applications In this talk, my goal is to motivate why smart contracts testing is extremely important I will also cover a couple of example on how things can go wrong & tools we can rely on
  2. Failures in Blockchains are Permanent & Catastrophic Hereโ€™s some statistics from a web site called Blockchain graveyard We can see that application vulnerabilities & how you manage keys are key sources of attacks More frighteningly, quite a lot of attacks are classified as โ€œunknownsโ€ There are also issues around system-level vulnerabilities To guard against these issues First we need to be build secure software & infrastructure Then we should thoroughly test them
  3. BCs are not standalone systems. They need to interact with various external systems ranging from DApps to cloud & legacy systems, & even IoT devices We need to manage keys, data, privacy, & govern both the BC & things that interact with it Thus, when we saying we are testing a BC-based application we need to conduct a whole lot of assessments on: Architecture & Integration Smart contracts Key management & access control Data management & privacy When it comes to consortium or private BCs we also need to focus on Scalability & performance Consensus algorithm Infrastructure Data management, privacy, & governance While this broad evaluation is essential, it is costly & time consuming. Usually 3rd parties are used to perform last phase of testing In this talk, Iโ€™ll limit my discussion to smart contract testing
  4. These are some of the well-know issues in SCs A race condition occurs when more than one piece of code try to concurrently update a state. For e.g., we have seen the infamous DAO re-entrancy attack Today, we also advanced re-entrancy attacks spanning multiple functions. If you mess-up you may ended up with a deadlock too Denial of Service is possible when you donโ€™t properly handle errors or due to the block size/gas limit Arithmetic overflow & underflow of variables are common too There can be unintended behaviour when your SC is sensitive to TX order. One such example is front running Time & block no dependent decisions can invite attacks There can also be SC language specific issues, e.g., if you forget to set the owner of a SC. Also, use of depreciated functions is another problem, which can go unnoticed depending on the solidity compiler version you use Also, there were specific issues related to how EVM handle certain addresses and limits on function depth Now that you know these, you should definitely try to check for these. There can also be many others that are specific to a given SC. Hence, you need to check for those are well
  5. Heโ€™s a function to transfer crypto from a SC to a given address This is usual cases of over or under flowing a variable. Also, be aware this can happen with ++, --, *, /, and bit shift operations Be careful with the smaller data-types like uint8, uint16, uint24...etc: they can even more easily hit their maximum value. Solution is to check if sender has balance and for overflows Another solution is to rely on a library like SafeMath that perform these checks for you
  6. This is an example of re-entrancy within a single function. Call the fallback function. You donโ€™t have any idea what that fallback function does. For e.g., while you wait for success it may call the withdrawBalance func again & initiate multiple withdrawals. As thereโ€™s money youโ€™ll call this again & again This is what happened in DAO attack We need to move userBalance set to zero before call.value Also, we can use a withdraw function to get the receiver to pull the crypto
  7. Hereโ€™s an example with 2 functions In this example, re-entrancy can be used either to call transfer or withdraw functions Same bug can occur across multiple contracts, if those contracts share state
  8. Hereโ€™s another example where just setting balance wonโ€™t work The withdrawReward function is fixed to overcome re-entrancy issue However, it can be called within getFirstWithdrawalBonus function, where for the 1st withdrawal you get a bonus While call.value is pending you can call getFirstWithdrawalBonus function In this case, by calling withdraw function claimedBonus need to be set to True Potential solutions Use a mutex Use withdraw function
  9. Here are some of the best practices, some of which we have already seen as patterns For e.g., upgradable contracts can be developed through proxy or SC registry We also talked about speed bumps, rate limits, and balance limit as various from of limiting TXs
  10. There are several classifications of software testing. Hereโ€™s one way, that I would consider more relevant to SCs Most developers are familiar with dynamic testing, where we observe a SC while executing it in a local or test network Unit testing & integration testing are forms of dynamic testing as we execute the code White box testing โ€“ You know code or international functionality Black box testing โ€“ Only ABI is available so you know the functions & parameters Static testing โ€“ is a class of methods that examine the source code or bytecode of a contract without executing it Source code โ€“ use code as it is. Typically IDEs (e.g., Remix) give various hints as you write code. Or evaluated at the time of compilation Byte code โ€“ Use the compiled code, e.g., when multiple high-level languages can generate the same byte code
  11. Code smells are symptoms in source code that possibly indicate deeper problems By detecting code smells we can try to avoid potential bugs & improve the design of our code For e.g., 1st one check whether we are validating return value for an external call. Other e.g., include use of hard corded addresses, call in loops, high gas consuming functions, and reentrancy Hereโ€™s a checklist of 20 code smells that you should make sure your SC doesnโ€™t have these issues
  12. Hereโ€™s a table from a survey of testing tools for Ethereum SCs Each row is a tool Columns are group based on their purpose of testing (or objective) whether the test is performed based on bytecode or source code. We can see that most tools are for static testing & support for dynamic testing is low These 2 sets of columns capture the technique used by the tool Some tools will translate or convert either byte or source code to another intermediate language that is easier to analyse using formal techniques I would encourage your to have a look at this paper as itโ€™s not very difficult to read
  13. Hereโ€™s another table from the same paper on SC security testing tools It also split the testing based on the target, for e.g., whether itโ€™s testing the BC platform, EVM, or the source code. Source code testing may actually happen at bytecode You can see that Remix-IDE has a good coverage of tests. However, remember that good coverage doesnโ€™t necessarily mean good accuracy For e.g., a tool may not detect a more complex cases of these vulnerabilities. Hence, detailed & wide-spread testing is needed Good thing is, most of these tools are either open source or free
  14. Fuzzing or fuzz testing is an automated testing technique that gives invalid or random inputs to a program, & then monitor for exceptions such as crashes, failed assertions, or other potential issues. Groups of such inputs are called test oracles. ContractFuzzer generates fuzzing inputs based on the ABI specifications of a SC to detect security vulnerabilities For e.g., in gasless send address.send() is called with value = 0 In exception disorder we check whether an exception is propagated through a chain of calls Freezing Ether check for cases like calling selfdestruct without returning Ether It also use EVM to log SC runtime behavior, and analyzes these logs to identify security vulnerabilities
  15. Slither is another static analysis tool Given a complied SC, it transform the code and then perform various analysis on the transformed code Based on this analysis, Slither can support security testing, code optimization, review, & user understanding For e.g., it can check for re-entrancy, code optimizations, and provide various visualizations to understand code
  16. There are several other tools and Oyente and Myrhril are popular All these are static analysis tools Support for other smart contract languages such as JavaScript, Java, Go, & DAML is limited. Alternatively, some consortium blockchains also support Solidity so itโ€™s something to keep in mind when choosing your SC language There seems to be an interest to use WebAssembly as the SC binarly language. Then weโ€™ll have access to quite a lot static & dynamic testing tools design for WebAssembly