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

Blockchains and Smart Contracts: Architecture Design and Model-Driven Develop...
Blockchains and Smart Contracts: Architecture Design and Model-Driven Develop...Blockchains and Smart Contracts: Architecture Design and Model-Driven Develop...
Blockchains and Smart Contracts: Architecture Design and Model-Driven Develop...Ingo Weber
 
The Ethereum Blockchain - Introduction to Smart Contracts and Decentralized A...
The Ethereum Blockchain - Introduction to Smart Contracts and Decentralized A...The Ethereum Blockchain - Introduction to Smart Contracts and Decentralized A...
The Ethereum Blockchain - Introduction to Smart Contracts and Decentralized A...Alessandro Sanino
 
Intro to Web3
Intro to Web3Intro to Web3
Intro to Web3asasdasd5
 
Event-Driven Microservices With NATS Streaming
Event-Driven Microservices With NATS StreamingEvent-Driven Microservices With NATS Streaming
Event-Driven Microservices With NATS StreamingShiju Varghese
 
An Investor's Guide to Web3 / Crypto / Blockchain
An Investor's Guide to Web3 / Crypto / BlockchainAn Investor's Guide to Web3 / Crypto / Blockchain
An Investor's Guide to Web3 / Crypto / BlockchainBernard Leong
 
Blockchain Intro to Hyperledger Fabric
Blockchain Intro to Hyperledger Fabric Blockchain Intro to Hyperledger Fabric
Blockchain Intro to Hyperledger Fabric Araf Karsh Hamid
 
Introduction to Blockchain
Introduction to BlockchainIntroduction to Blockchain
Introduction to BlockchainMalak Abu Hammad
 
Distributed tracing 101
Distributed tracing 101Distributed tracing 101
Distributed tracing 101Itiel Shwartz
 
Non-fungible tokens (nfts)
Non-fungible tokens (nfts)Non-fungible tokens (nfts)
Non-fungible tokens (nfts)Gene Leybzon
 
Introduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart ContractsIntroduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart ContractsSaad Zaher
 
Blockchain
BlockchainBlockchain
BlockchainSai Nath
 
Blockchain Explained | How Does A Blockchain Work | Blockchain Explained Simp...
Blockchain Explained | How Does A Blockchain Work | Blockchain Explained Simp...Blockchain Explained | How Does A Blockchain Work | Blockchain Explained Simp...
Blockchain Explained | How Does A Blockchain Work | Blockchain Explained Simp...Simplilearn
 
Distributed tracing using open tracing & jaeger 2
Distributed tracing using open tracing & jaeger 2Distributed tracing using open tracing & jaeger 2
Distributed tracing using open tracing & jaeger 2Chandresh Pancholi
 
Blockchain Technology Explained | Blockchain Technology Tutorial | Blockchain...
Blockchain Technology Explained | Blockchain Technology Tutorial | Blockchain...Blockchain Technology Explained | Blockchain Technology Tutorial | Blockchain...
Blockchain Technology Explained | Blockchain Technology Tutorial | Blockchain...Simplilearn
 
Microservices Architecture Part 2 Event Sourcing and Saga
Microservices Architecture Part 2 Event Sourcing and SagaMicroservices Architecture Part 2 Event Sourcing and Saga
Microservices Architecture Part 2 Event Sourcing and SagaAraf Karsh Hamid
 

What's hot (20)

BLOCKCHAIN
BLOCKCHAINBLOCKCHAIN
BLOCKCHAIN
 
Blockchains and Smart Contracts: Architecture Design and Model-Driven Develop...
Blockchains and Smart Contracts: Architecture Design and Model-Driven Develop...Blockchains and Smart Contracts: Architecture Design and Model-Driven Develop...
Blockchains and Smart Contracts: Architecture Design and Model-Driven Develop...
 
The Ethereum Blockchain - Introduction to Smart Contracts and Decentralized A...
The Ethereum Blockchain - Introduction to Smart Contracts and Decentralized A...The Ethereum Blockchain - Introduction to Smart Contracts and Decentralized A...
The Ethereum Blockchain - Introduction to Smart Contracts and Decentralized A...
 
Blockchain 2.0
Blockchain 2.0Blockchain 2.0
Blockchain 2.0
 
Intro to Web3
Intro to Web3Intro to Web3
Intro to Web3
 
Hyperledger Fabric
Hyperledger FabricHyperledger Fabric
Hyperledger Fabric
 
Event-Driven Microservices With NATS Streaming
Event-Driven Microservices With NATS StreamingEvent-Driven Microservices With NATS Streaming
Event-Driven Microservices With NATS Streaming
 
An Investor's Guide to Web3 / Crypto / Blockchain
An Investor's Guide to Web3 / Crypto / BlockchainAn Investor's Guide to Web3 / Crypto / Blockchain
An Investor's Guide to Web3 / Crypto / Blockchain
 
Blockchain Intro to Hyperledger Fabric
Blockchain Intro to Hyperledger Fabric Blockchain Intro to Hyperledger Fabric
Blockchain Intro to Hyperledger Fabric
 
Introduction to Blockchain
Introduction to BlockchainIntroduction to Blockchain
Introduction to Blockchain
 
Distributed tracing 101
Distributed tracing 101Distributed tracing 101
Distributed tracing 101
 
Non-fungible tokens (nfts)
Non-fungible tokens (nfts)Non-fungible tokens (nfts)
Non-fungible tokens (nfts)
 
Introduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart ContractsIntroduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart Contracts
 
Blockchain
BlockchainBlockchain
Blockchain
 
Blockchain Explained | How Does A Blockchain Work | Blockchain Explained Simp...
Blockchain Explained | How Does A Blockchain Work | Blockchain Explained Simp...Blockchain Explained | How Does A Blockchain Work | Blockchain Explained Simp...
Blockchain Explained | How Does A Blockchain Work | Blockchain Explained Simp...
 
Distributed tracing using open tracing & jaeger 2
Distributed tracing using open tracing & jaeger 2Distributed tracing using open tracing & jaeger 2
Distributed tracing using open tracing & jaeger 2
 
Blockchain Explained
Blockchain ExplainedBlockchain Explained
Blockchain Explained
 
Blockchain Technology Explained | Blockchain Technology Tutorial | Blockchain...
Blockchain Technology Explained | Blockchain Technology Tutorial | Blockchain...Blockchain Technology Explained | Blockchain Technology Tutorial | Blockchain...
Blockchain Technology Explained | Blockchain Technology Tutorial | Blockchain...
 
Blockchain
BlockchainBlockchain
Blockchain
 
Microservices Architecture Part 2 Event Sourcing and Saga
Microservices Architecture Part 2 Event Sourcing and SagaMicroservices Architecture Part 2 Event Sourcing and Saga
Microservices Architecture Part 2 Event Sourcing and Saga
 

Similar to Smart Contract Testing

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 MicroProfileVíctor Leonel Orozco López
 
Smart Contract Security Testing
Smart Contract Security TestingSmart Contract Security Testing
Smart Contract Security TestingDilum Bandara
 
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 directoryFelipe Prado
 
Sumo Logic Cert Jam - Security Analytics
Sumo Logic Cert Jam - Security AnalyticsSumo Logic Cert Jam - Security Analytics
Sumo Logic Cert Jam - Security AnalyticsSumo Logic
 
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 TrafficDaniel-Constantin Mierla
 
Implementation domain driven design - ch04 architecture
Implementation domain driven design - ch04 architectureImplementation domain driven design - ch04 architecture
Implementation domain driven design - ch04 architectureHarry Yao
 
Application Security
Application SecurityApplication Security
Application Securityflorinc
 
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.pptxJasonOstrom1
 
Application Security from the Inside - OWASP
Application Security from the Inside - OWASPApplication Security from the Inside - OWASP
Application Security from the Inside - OWASPSqreen
 
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 Massimiliano Dessì
 
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
 
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)Markus Eisele
 
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)Shantanu Sharma
 
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 MongoDBMongoDB
 
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...IRJET Journal
 
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 directoryPriyanka Aash
 
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 ProcessingShantanu Sharma
 
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.pptxpetabridge
 

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

Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine LearningDilum Bandara
 
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 PracticeDilum Bandara
 
Introduction to Dimension Reduction with PCA
Introduction to Dimension Reduction with PCAIntroduction to Dimension Reduction with PCA
Introduction to Dimension Reduction with PCADilum Bandara
 
Introduction to Descriptive & Predictive Analytics
Introduction to Descriptive & Predictive AnalyticsIntroduction to Descriptive & Predictive Analytics
Introduction to Descriptive & Predictive AnalyticsDilum Bandara
 
Introduction to Concurrent Data Structures
Introduction to Concurrent Data StructuresIntroduction to Concurrent Data Structures
Introduction to Concurrent Data StructuresDilum Bandara
 
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-MatrixDilum Bandara
 
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 HadoopDilum Bandara
 
Embarrassingly/Delightfully Parallel Problems
Embarrassingly/Delightfully Parallel ProblemsEmbarrassingly/Delightfully Parallel Problems
Embarrassingly/Delightfully Parallel ProblemsDilum Bandara
 
Introduction to Warehouse-Scale Computers
Introduction to Warehouse-Scale ComputersIntroduction to Warehouse-Scale Computers
Introduction to Warehouse-Scale ComputersDilum Bandara
 
Introduction to Thread Level Parallelism
Introduction to Thread Level ParallelismIntroduction to Thread Level Parallelism
Introduction to Thread Level ParallelismDilum Bandara
 
CPU Memory Hierarchy and Caching Techniques
CPU Memory Hierarchy and Caching TechniquesCPU Memory Hierarchy and Caching Techniques
CPU Memory Hierarchy and Caching TechniquesDilum Bandara
 
Data-Level Parallelism in Microprocessors
Data-Level Parallelism in MicroprocessorsData-Level Parallelism in Microprocessors
Data-Level Parallelism in MicroprocessorsDilum Bandara
 
Instruction Level Parallelism – Hardware Techniques
Instruction Level Parallelism – Hardware TechniquesInstruction Level Parallelism – Hardware Techniques
Instruction Level Parallelism – Hardware TechniquesDilum Bandara
 
Instruction Level Parallelism – Compiler Techniques
Instruction Level Parallelism – Compiler TechniquesInstruction Level Parallelism – Compiler Techniques
Instruction Level Parallelism – Compiler TechniquesDilum Bandara
 
CPU Pipelining and Hazards - An Introduction
CPU Pipelining and Hazards - An IntroductionCPU Pipelining and Hazards - An Introduction
CPU Pipelining and Hazards - An IntroductionDilum Bandara
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
High Performance Networking with Advanced TCP
High Performance Networking with Advanced TCPHigh Performance Networking with Advanced TCP
High Performance Networking with Advanced TCPDilum Bandara
 
Introduction to Content Delivery Networks
Introduction to Content Delivery NetworksIntroduction to Content Delivery Networks
Introduction to Content Delivery NetworksDilum Bandara
 
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 StreamingDilum 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

Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletAndrea Goulet
 
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-CloudAlluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-CloudAlluxio, Inc.
 
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...Abortion Clinic
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Henry Schreiner
 
What is a Recruitment Management Software?
What is a Recruitment Management Software?What is a Recruitment Management Software?
What is a Recruitment Management Software?NYGGS Automation Suite
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In hararekasambamuno
 
Weeding your micro service landscape.pdf
Weeding your micro service landscape.pdfWeeding your micro service landscape.pdf
Weeding your micro service landscape.pdftimtebeek1
 
Microsoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMicrosoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMarkus Moeller
 
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypseTomasz Kowalczewski
 
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Lisi Hocke
 
Transformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with LinksTransformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with LinksJinanKordab
 
Test Automation Design Patterns_ A Comprehensive Guide.pdf
Test Automation Design Patterns_ A Comprehensive Guide.pdfTest Automation Design Patterns_ A Comprehensive Guide.pdf
Test Automation Design Patterns_ A Comprehensive Guide.pdfkalichargn70th171
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In sowetokasambamuno
 
CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...
CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...
CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...Neo4j
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbankkasambamuno
 
Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfSrushith Repakula
 
Software Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements EngineeringSoftware Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements EngineeringPrakhyath Rai
 
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckMarc Lester
 
Auto Affiliate AI Earns First Commission in 3 Hours..pdf
Auto Affiliate  AI Earns First Commission in 3 Hours..pdfAuto Affiliate  AI Earns First Commission in 3 Hours..pdf
Auto Affiliate AI Earns First Commission in 3 Hours..pdfSelfMade bd
 

Recently uploaded (20)

Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea Goulet
 
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-CloudAlluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
 
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024
 
What is a Recruitment Management Software?
What is a Recruitment Management Software?What is a Recruitment Management Software?
What is a Recruitment Management Software?
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
 
Weeding your micro service landscape.pdf
Weeding your micro service landscape.pdfWeeding your micro service landscape.pdf
Weeding your micro service landscape.pdf
 
Microsoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMicrosoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdf
 
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
 
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
 
Abortion Clinic Pretoria ](+27832195400*)[ Abortion Clinic Near Me ● Abortion...
Abortion Clinic Pretoria ](+27832195400*)[ Abortion Clinic Near Me ● Abortion...Abortion Clinic Pretoria ](+27832195400*)[ Abortion Clinic Near Me ● Abortion...
Abortion Clinic Pretoria ](+27832195400*)[ Abortion Clinic Near Me ● Abortion...
 
Transformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with LinksTransformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with Links
 
Test Automation Design Patterns_ A Comprehensive Guide.pdf
Test Automation Design Patterns_ A Comprehensive Guide.pdfTest Automation Design Patterns_ A Comprehensive Guide.pdf
Test Automation Design Patterns_ A Comprehensive Guide.pdf
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
 
CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...
CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...
CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
 
Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdf
 
Software Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements EngineeringSoftware Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements Engineering
 
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined Deck
 
Auto Affiliate AI Earns First Commission in 3 Hours..pdf
Auto Affiliate  AI Earns First Commission in 3 Hours..pdfAuto Affiliate  AI Earns First Commission in 3 Hours..pdf
Auto Affiliate AI Earns First Commission in 3 Hours..pdf
 

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