SlideShare a Scribd company logo

Solidity Security and Best Coding Practices

Vulnerabilities of blockchain contracts and Solidity code How good coding practices can limit the scope of security exposure

1 of 31
Download to read offline
SOLIDITY BEST PRACTICES
BLOCKCHAIN AND SMART
CONTRACTS (SESSION 5)
Hands-on introduction for
Software Developers and
Architects
SECURITY RISKS • Security Risks
• Attacks
RACE CONDITIONS
Contract A Contract B Contract C Contract A Contract B Contract C
RACE CONDITIONS: REENTRANCY
mapping (address => uint) private userBalances;
function withdrawBalance() public {
uint amountToWithdraw =
userBalances[msg.sender];
require(msg.sender.call.value(amountToWithdraw)());
userBalances[msg.sender] = 0;
}
mapping (address => uint) private userBalances
function withdrawBalance() public {
uint amountToWithdraw =
userBalances[msg.sender];
userBalances[msg.sender] = 0;
require(msg.sender.call.value(amountToWithdra
}
RACE CONDITIONS: CROSS-FUNCTION
RACE CONDITIONS
mapping (address => uint) private userBalances;
function transfer(address to, uint amount) {
if (userBalances[msg.sender] >= amount) {
userBalances[msg.sender] -= amount;
userBalances[to] += amount;
}
}
function withdrawBalance() public {
uint amountToWithdraw =
userBalances[msg.sender];
require(msg.sender.call.value(amountToWithdraw)
userBalances[msg.sender] = 0;
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];
require(msg.sender.call.value(amountToWithdraw)());
userBalances[msg.sender] = 0;
FRONT RUNNING
(TRANSACTION-ORDERING
DEPENDENCE)
Set
Puzzle
Rewar
d
Submi
t
Soluti
on
Updat
e
Puzzle
Rewar
d
Set
Puzzle
Rewar
d
Submi
t
Soluti
on
Updat
e
Puzzle
Rewar
d
Miners can reorder transactions and hence
potentially influence their outcome!
Ad

Recommended

Write smart contract with solidity on Ethereum
Write smart contract with solidity on EthereumWrite smart contract with solidity on Ethereum
Write smart contract with solidity on EthereumMurughan Palaniachari
 
Introduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart ContractsIntroduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart ContractsTechracers
 
Developing applications with Hyperledger Fabric SDK
Developing applications with Hyperledger Fabric SDKDeveloping applications with Hyperledger Fabric SDK
Developing applications with Hyperledger Fabric SDKHorea Porutiu
 
Programming smart contracts in solidity
Programming smart contracts in solidityProgramming smart contracts in solidity
Programming smart contracts in solidityEmanuel Mota
 
Ethereum Solidity Fundamentals
Ethereum Solidity FundamentalsEthereum Solidity Fundamentals
Ethereum Solidity FundamentalsEno Bassey
 
Write Smart Contract with Solidity on Ethereum
Write Smart Contract with Solidity on EthereumWrite Smart Contract with Solidity on Ethereum
Write Smart Contract with Solidity on Ethereum劉 維仁
 

More Related Content

What's hot

Introduction To Solidity
Introduction To SolidityIntroduction To Solidity
Introduction To Solidity101 Blockchains
 
Blockchain Presentation
Blockchain PresentationBlockchain Presentation
Blockchain PresentationZied GUESMI
 
Learning Solidity
Learning SolidityLearning Solidity
Learning SolidityArnold Pham
 
Examples of Smart Contracts
Examples of Smart ContractsExamples of Smart Contracts
Examples of Smart Contracts101 Blockchains
 
Creating Smart Contract
Creating Smart ContractCreating Smart Contract
Creating Smart ContractDeepak Aryal
 
Blockchain consensus algorithms
Blockchain consensus algorithmsBlockchain consensus algorithms
Blockchain consensus algorithmsAnurag Dashputre
 
Hyperledger Fabric Architecture
Hyperledger Fabric ArchitectureHyperledger Fabric Architecture
Hyperledger Fabric Architecture상문 오
 
Blockchain Consensus Protocols
Blockchain Consensus ProtocolsBlockchain Consensus Protocols
Blockchain Consensus ProtocolsMelanie Swan
 
Smart Contract & Ethereum
Smart Contract & EthereumSmart Contract & Ethereum
Smart Contract & EthereumAkshay Singh
 
Introduction to Solidity and Smart Contract Development (9).pptx
Introduction to Solidity and Smart Contract Development (9).pptxIntroduction to Solidity and Smart Contract Development (9).pptx
Introduction to Solidity and Smart Contract Development (9).pptxGene Leybzon
 
Consensus Algorithms.pptx
Consensus Algorithms.pptxConsensus Algorithms.pptx
Consensus Algorithms.pptxRajapriya82
 
Overview of blockchain technology and architecture
Overview of blockchain technology and   architectureOverview of blockchain technology and   architecture
Overview of blockchain technology and architectureEY
 

What's hot (20)

Introduction To Solidity
Introduction To SolidityIntroduction To Solidity
Introduction To Solidity
 
Blockchain Presentation
Blockchain PresentationBlockchain Presentation
Blockchain Presentation
 
Learning Solidity
Learning SolidityLearning Solidity
Learning Solidity
 
Examples of Smart Contracts
Examples of Smart ContractsExamples of Smart Contracts
Examples of Smart Contracts
 
Smart contract
Smart contractSmart contract
Smart contract
 
Creating Smart Contract
Creating Smart ContractCreating Smart Contract
Creating Smart Contract
 
Blockchain consensus algorithms
Blockchain consensus algorithmsBlockchain consensus algorithms
Blockchain consensus algorithms
 
Hyperledger Fabric Architecture
Hyperledger Fabric ArchitectureHyperledger Fabric Architecture
Hyperledger Fabric Architecture
 
Hyperledger Fabric
Hyperledger FabricHyperledger Fabric
Hyperledger Fabric
 
Blockchain Consensus Protocols
Blockchain Consensus ProtocolsBlockchain Consensus Protocols
Blockchain Consensus Protocols
 
SSH - Secure Shell
SSH - Secure ShellSSH - Secure Shell
SSH - Secure Shell
 
Hyperledger
HyperledgerHyperledger
Hyperledger
 
Smart Contract & Ethereum
Smart Contract & EthereumSmart Contract & Ethereum
Smart Contract & Ethereum
 
Introduction to Solidity and Smart Contract Development (9).pptx
Introduction to Solidity and Smart Contract Development (9).pptxIntroduction to Solidity and Smart Contract Development (9).pptx
Introduction to Solidity and Smart Contract Development (9).pptx
 
Introduction to Cryptography
Introduction to CryptographyIntroduction to Cryptography
Introduction to Cryptography
 
Consensus Algorithms.pptx
Consensus Algorithms.pptxConsensus Algorithms.pptx
Consensus Algorithms.pptx
 
Blockchain 2.0
Blockchain 2.0Blockchain 2.0
Blockchain 2.0
 
Blockchain (1).pptx
Blockchain (1).pptxBlockchain (1).pptx
Blockchain (1).pptx
 
Ethereum
EthereumEthereum
Ethereum
 
Overview of blockchain technology and architecture
Overview of blockchain technology and   architectureOverview of blockchain technology and   architecture
Overview of blockchain technology and architecture
 

Similar to Solidity Security and Best Coding Practices

Principais vulnerabilidades em Smart Contracts e como evitá-las
Principais vulnerabilidades em Smart Contracts e como evitá-lasPrincipais vulnerabilidades em Smart Contracts e como evitá-las
Principais vulnerabilidades em Smart Contracts e como evitá-lasJúlio Campos
 
Smart Contract programming 101 with Solidity #PizzaHackathon
Smart Contract programming 101 with Solidity #PizzaHackathonSmart Contract programming 101 with Solidity #PizzaHackathon
Smart Contract programming 101 with Solidity #PizzaHackathonSittiphol Phanvilai
 
Robust Programming of Smart Contracts in Solidity+, RK Shyamasundar
Robust Programming of Smart Contracts in Solidity+, RK ShyamasundarRobust Programming of Smart Contracts in Solidity+, RK Shyamasundar
Robust Programming of Smart Contracts in Solidity+, RK ShyamasundarNapier University
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Abdul Samee
 
Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223Jarmo van de Seijp
 
The evolution of redux action creators
The evolution of redux action creatorsThe evolution of redux action creators
The evolution of redux action creatorsGeorge Bukhanov
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS a_sharif
 
From CRUD to messages: a true story
From CRUD to messages: a true storyFrom CRUD to messages: a true story
From CRUD to messages: a true storyAlessandro Melchiori
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuningAOE
 
Taming event-driven software via formal verification
Taming event-driven software via formal verificationTaming event-driven software via formal verification
Taming event-driven software via formal verificationAdaCore
 
“Create your own cryptocurrency in an hour” - Sandip Pandey
“Create your own cryptocurrency in an hour” - Sandip Pandey“Create your own cryptocurrency in an hour” - Sandip Pandey
“Create your own cryptocurrency in an hour” - Sandip PandeyEIT Digital Alumni
 
Solidity Simple Tutorial EN
Solidity Simple Tutorial ENSolidity Simple Tutorial EN
Solidity Simple Tutorial ENNicholas Lin
 
Compensating Transactions: When ACID is too much
Compensating Transactions: When ACID is too muchCompensating Transactions: When ACID is too much
Compensating Transactions: When ACID is too muchJBUG London
 

Similar to Solidity Security and Best Coding Practices (20)

Principais vulnerabilidades em Smart Contracts e como evitá-las
Principais vulnerabilidades em Smart Contracts e como evitá-lasPrincipais vulnerabilidades em Smart Contracts e como evitá-las
Principais vulnerabilidades em Smart Contracts e como evitá-las
 
Smart Contract programming 101 with Solidity #PizzaHackathon
Smart Contract programming 101 with Solidity #PizzaHackathonSmart Contract programming 101 with Solidity #PizzaHackathon
Smart Contract programming 101 with Solidity #PizzaHackathon
 
Robust Programming of Smart Contracts in Solidity+, RK Shyamasundar
Robust Programming of Smart Contracts in Solidity+, RK ShyamasundarRobust Programming of Smart Contracts in Solidity+, RK Shyamasundar
Robust Programming of Smart Contracts in Solidity+, RK Shyamasundar
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
 
Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223
 
The evolution of redux action creators
The evolution of redux action creatorsThe evolution of redux action creators
The evolution of redux action creators
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
Quiz 10 cp_sol
Quiz 10 cp_solQuiz 10 cp_sol
Quiz 10 cp_sol
 
C++
C++C++
C++
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS
 
From CRUD to messages: a true story
From CRUD to messages: a true storyFrom CRUD to messages: a true story
From CRUD to messages: a true story
 
Advanced smart contract
Advanced smart contractAdvanced smart contract
Advanced smart contract
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
 
Dex and Uniswap
Dex and UniswapDex and Uniswap
Dex and Uniswap
 
functions of C++
functions of C++functions of C++
functions of C++
 
Taming event-driven software via formal verification
Taming event-driven software via formal verificationTaming event-driven software via formal verification
Taming event-driven software via formal verification
 
“Create your own cryptocurrency in an hour” - Sandip Pandey
“Create your own cryptocurrency in an hour” - Sandip Pandey“Create your own cryptocurrency in an hour” - Sandip Pandey
“Create your own cryptocurrency in an hour” - Sandip Pandey
 
Solidity Simple Tutorial EN
Solidity Simple Tutorial ENSolidity Simple Tutorial EN
Solidity Simple Tutorial EN
 
Ngrx
NgrxNgrx
Ngrx
 
Compensating Transactions: When ACID is too much
Compensating Transactions: When ACID is too muchCompensating Transactions: When ACID is too much
Compensating Transactions: When ACID is too much
 

More from Gene Leybzon

Generative AI Application Development using LangChain and LangFlow
Generative AI Application Development using LangChain and LangFlowGenerative AI Application Development using LangChain and LangFlow
Generative AI Application Development using LangChain and LangFlowGene Leybzon
 
Generative AI Use cases for Enterprise - Second Session
Generative AI Use cases for Enterprise - Second SessionGenerative AI Use cases for Enterprise - Second Session
Generative AI Use cases for Enterprise - Second SessionGene Leybzon
 
Generative AI Use-cases for Enterprise - First Session
Generative AI Use-cases for Enterprise - First SessionGenerative AI Use-cases for Enterprise - First Session
Generative AI Use-cases for Enterprise - First SessionGene Leybzon
 
Non-fungible tokens (nfts)
Non-fungible tokens (nfts)Non-fungible tokens (nfts)
Non-fungible tokens (nfts)Gene Leybzon
 
Ethereum in Enterprise.pptx
Ethereum in Enterprise.pptxEthereum in Enterprise.pptx
Ethereum in Enterprise.pptxGene Leybzon
 
ERC-4907 Rentable NFT Standard.pptx
ERC-4907 Rentable NFT Standard.pptxERC-4907 Rentable NFT Standard.pptx
ERC-4907 Rentable NFT Standard.pptxGene Leybzon
 
Onchain Decentralized Governance 2.pptx
Onchain Decentralized Governance 2.pptxOnchain Decentralized Governance 2.pptx
Onchain Decentralized Governance 2.pptxGene Leybzon
 
Onchain Decentralized Governance.pptx
Onchain Decentralized Governance.pptxOnchain Decentralized Governance.pptx
Onchain Decentralized Governance.pptxGene Leybzon
 
Web3 File Storage Options
Web3 File Storage OptionsWeb3 File Storage Options
Web3 File Storage OptionsGene Leybzon
 
Web3 Full Stack Development
Web3 Full Stack DevelopmentWeb3 Full Stack Development
Web3 Full Stack DevelopmentGene Leybzon
 
Instantly tradeable NFT contracts based on ERC-1155 standard
Instantly tradeable NFT contracts based on ERC-1155 standardInstantly tradeable NFT contracts based on ERC-1155 standard
Instantly tradeable NFT contracts based on ERC-1155 standardGene Leybzon
 
Non-fungible tokens. From smart contract code to marketplace
Non-fungible tokens. From smart contract code to marketplaceNon-fungible tokens. From smart contract code to marketplace
Non-fungible tokens. From smart contract code to marketplaceGene Leybzon
 
The Art of non-fungible tokens
The Art of non-fungible tokensThe Art of non-fungible tokens
The Art of non-fungible tokensGene Leybzon
 
Graph protocol for accessing information about blockchains and d apps
Graph protocol for accessing information about blockchains and d appsGraph protocol for accessing information about blockchains and d apps
Graph protocol for accessing information about blockchains and d appsGene Leybzon
 
Substrate Framework
Substrate FrameworkSubstrate Framework
Substrate FrameworkGene Leybzon
 
OpenZeppelin + Remix + BNB smart chain
OpenZeppelin + Remix + BNB smart chainOpenZeppelin + Remix + BNB smart chain
OpenZeppelin + Remix + BNB smart chainGene Leybzon
 
Chainlink, Cosmos, Kusama, Polkadot: Approaches to the Internet of Blockchains
Chainlink, Cosmos, Kusama, Polkadot:   Approaches to the Internet of BlockchainsChainlink, Cosmos, Kusama, Polkadot:   Approaches to the Internet of Blockchains
Chainlink, Cosmos, Kusama, Polkadot: Approaches to the Internet of BlockchainsGene Leybzon
 
Accessing decentralized finance on Ethereum blockchain
Accessing decentralized finance on Ethereum blockchainAccessing decentralized finance on Ethereum blockchain
Accessing decentralized finance on Ethereum blockchainGene Leybzon
 

More from Gene Leybzon (20)

Generative AI Application Development using LangChain and LangFlow
Generative AI Application Development using LangChain and LangFlowGenerative AI Application Development using LangChain and LangFlow
Generative AI Application Development using LangChain and LangFlow
 
Chat GPTs
Chat GPTsChat GPTs
Chat GPTs
 
Generative AI Use cases for Enterprise - Second Session
Generative AI Use cases for Enterprise - Second SessionGenerative AI Use cases for Enterprise - Second Session
Generative AI Use cases for Enterprise - Second Session
 
Generative AI Use-cases for Enterprise - First Session
Generative AI Use-cases for Enterprise - First SessionGenerative AI Use-cases for Enterprise - First Session
Generative AI Use-cases for Enterprise - First Session
 
Non-fungible tokens (nfts)
Non-fungible tokens (nfts)Non-fungible tokens (nfts)
Non-fungible tokens (nfts)
 
Ethereum in Enterprise.pptx
Ethereum in Enterprise.pptxEthereum in Enterprise.pptx
Ethereum in Enterprise.pptx
 
ERC-4907 Rentable NFT Standard.pptx
ERC-4907 Rentable NFT Standard.pptxERC-4907 Rentable NFT Standard.pptx
ERC-4907 Rentable NFT Standard.pptx
 
Onchain Decentralized Governance 2.pptx
Onchain Decentralized Governance 2.pptxOnchain Decentralized Governance 2.pptx
Onchain Decentralized Governance 2.pptx
 
Onchain Decentralized Governance.pptx
Onchain Decentralized Governance.pptxOnchain Decentralized Governance.pptx
Onchain Decentralized Governance.pptx
 
Web3 File Storage Options
Web3 File Storage OptionsWeb3 File Storage Options
Web3 File Storage Options
 
Web3 Full Stack Development
Web3 Full Stack DevelopmentWeb3 Full Stack Development
Web3 Full Stack Development
 
Instantly tradeable NFT contracts based on ERC-1155 standard
Instantly tradeable NFT contracts based on ERC-1155 standardInstantly tradeable NFT contracts based on ERC-1155 standard
Instantly tradeable NFT contracts based on ERC-1155 standard
 
Non-fungible tokens. From smart contract code to marketplace
Non-fungible tokens. From smart contract code to marketplaceNon-fungible tokens. From smart contract code to marketplace
Non-fungible tokens. From smart contract code to marketplace
 
The Art of non-fungible tokens
The Art of non-fungible tokensThe Art of non-fungible tokens
The Art of non-fungible tokens
 
Graph protocol for accessing information about blockchains and d apps
Graph protocol for accessing information about blockchains and d appsGraph protocol for accessing information about blockchains and d apps
Graph protocol for accessing information about blockchains and d apps
 
Substrate Framework
Substrate FrameworkSubstrate Framework
Substrate Framework
 
Chainlink
ChainlinkChainlink
Chainlink
 
OpenZeppelin + Remix + BNB smart chain
OpenZeppelin + Remix + BNB smart chainOpenZeppelin + Remix + BNB smart chain
OpenZeppelin + Remix + BNB smart chain
 
Chainlink, Cosmos, Kusama, Polkadot: Approaches to the Internet of Blockchains
Chainlink, Cosmos, Kusama, Polkadot:   Approaches to the Internet of BlockchainsChainlink, Cosmos, Kusama, Polkadot:   Approaches to the Internet of Blockchains
Chainlink, Cosmos, Kusama, Polkadot: Approaches to the Internet of Blockchains
 
Accessing decentralized finance on Ethereum blockchain
Accessing decentralized finance on Ethereum blockchainAccessing decentralized finance on Ethereum blockchain
Accessing decentralized finance on Ethereum blockchain
 

Recently uploaded

No more Dockerfiles? Buildpacks to help you ship your image!
No more Dockerfiles? Buildpacks to help you ship your image!No more Dockerfiles? Buildpacks to help you ship your image!
No more Dockerfiles? Buildpacks to help you ship your image!Anthony Dahanne
 
Essence of Requirements Engineering: Pragmatic Insights for 2024
Essence of Requirements Engineering: Pragmatic Insights for 2024Essence of Requirements Engineering: Pragmatic Insights for 2024
Essence of Requirements Engineering: Pragmatic Insights for 2024Asher Sterkin
 
Self scaling Multi cloud nomad workloads
Self scaling Multi cloud nomad workloadsSelf scaling Multi cloud nomad workloads
Self scaling Multi cloud nomad workloadsBram Vogelaar
 
100 TOOLS TO MEASURE AND ANALYSE YOUR DIGITAL MARKETING EFFORTS
100 TOOLS TO MEASURE AND ANALYSE YOUR DIGITAL MARKETING EFFORTS100 TOOLS TO MEASURE AND ANALYSE YOUR DIGITAL MARKETING EFFORTS
100 TOOLS TO MEASURE AND ANALYSE YOUR DIGITAL MARKETING EFFORTSi-engage
 
sql ppt for students who preparing for sql
sql ppt for students who preparing for sqlsql ppt for students who preparing for sql
sql ppt for students who preparing for sqlbharatjanadharwarud
 
DBA Fundamentals Group: Continuous SQL with Kafka and Flink
DBA Fundamentals Group: Continuous SQL with Kafka and FlinkDBA Fundamentals Group: Continuous SQL with Kafka and Flink
DBA Fundamentals Group: Continuous SQL with Kafka and FlinkTimothy Spann
 
SPM 2024 – Overview of and benefits of AI in Product Management
SPM 2024 – Overview of and benefits of AI in Product ManagementSPM 2024 – Overview of and benefits of AI in Product Management
SPM 2024 – Overview of and benefits of AI in Product ManagementISPMAIndia
 
Les02 Restricting and Sorting Data using SQL.ppt
Les02 Restricting and Sorting Data using SQL.pptLes02 Restricting and Sorting Data using SQL.ppt
Les02 Restricting and Sorting Data using SQL.pptDrZeeshanBhatti
 
Software Testing life cycle (STLC) Importance, Phases, Benefits...
Software Testing life cycle (STLC) Importance, Phases, Benefits...Software Testing life cycle (STLC) Importance, Phases, Benefits...
Software Testing life cycle (STLC) Importance, Phases, Benefits...Flexsin
 
killingcamp 광고삽입문제 풀이, killingcamp 광고삽입문제 풀이
killingcamp 광고삽입문제 풀이, killingcamp 광고삽입문제 풀이killingcamp 광고삽입문제 풀이, killingcamp 광고삽입문제 풀이
killingcamp 광고삽입문제 풀이, killingcamp 광고삽입문제 풀이ssuser82c38d
 
Open Sprintera (Where Open Source Sparks a Sprint of Possibilities)
Open Sprintera (Where Open Source Sparks a Sprint of Possibilities)Open Sprintera (Where Open Source Sparks a Sprint of Possibilities)
Open Sprintera (Where Open Source Sparks a Sprint of Possibilities)GDSCNiT
 
App Builder - Hierarchical Data Apps.pptx
App Builder - Hierarchical Data Apps.pptxApp Builder - Hierarchical Data Apps.pptx
App Builder - Hierarchical Data Apps.pptxPoojitha B
 
Sql server types of joins with example.pptx
Sql server types of joins with example.pptxSql server types of joins with example.pptx
Sql server types of joins with example.pptxsameer gaikwad
 
"Discovery and Delivery through Product IntelliGenAI framework" by Ramkumar A...
"Discovery and Delivery through Product IntelliGenAI framework" by Ramkumar A..."Discovery and Delivery through Product IntelliGenAI framework" by Ramkumar A...
"Discovery and Delivery through Product IntelliGenAI framework" by Ramkumar A...ISPMAIndia
 
Industry 4.0: Building the Unified Namespace with Confluent, HiveMQ and Spark...
Industry 4.0: Building the Unified Namespace with Confluent, HiveMQ and Spark...Industry 4.0: Building the Unified Namespace with Confluent, HiveMQ and Spark...
Industry 4.0: Building the Unified Namespace with Confluent, HiveMQ and Spark...confluent
 
AUTOKEYUNLOCKER-BRANDS-SUPPORT-STANDARD-VERSION.pdf
AUTOKEYUNLOCKER-BRANDS-SUPPORT-STANDARD-VERSION.pdfAUTOKEYUNLOCKER-BRANDS-SUPPORT-STANDARD-VERSION.pdf
AUTOKEYUNLOCKER-BRANDS-SUPPORT-STANDARD-VERSION.pdfAutokey
 
P1 Inspection Types in Municity 5 Smartsheet
P1 Inspection Types in Municity 5 SmartsheetP1 Inspection Types in Municity 5 Smartsheet
P1 Inspection Types in Municity 5 SmartsheetMatthewTHawley
 
killing camp week 6 problem - maximal matrix.pdf
killing camp week 6 problem - maximal matrix.pdfkilling camp week 6 problem - maximal matrix.pdf
killing camp week 6 problem - maximal matrix.pdfssuser82c38d
 
AI Product Management by Abhijit Bendigiri
AI Product Management by Abhijit BendigiriAI Product Management by Abhijit Bendigiri
AI Product Management by Abhijit BendigiriISPMAIndia
 

Recently uploaded (20)

No more Dockerfiles? Buildpacks to help you ship your image!
No more Dockerfiles? Buildpacks to help you ship your image!No more Dockerfiles? Buildpacks to help you ship your image!
No more Dockerfiles? Buildpacks to help you ship your image!
 
Essence of Requirements Engineering: Pragmatic Insights for 2024
Essence of Requirements Engineering: Pragmatic Insights for 2024Essence of Requirements Engineering: Pragmatic Insights for 2024
Essence of Requirements Engineering: Pragmatic Insights for 2024
 
Self scaling Multi cloud nomad workloads
Self scaling Multi cloud nomad workloadsSelf scaling Multi cloud nomad workloads
Self scaling Multi cloud nomad workloads
 
100 TOOLS TO MEASURE AND ANALYSE YOUR DIGITAL MARKETING EFFORTS
100 TOOLS TO MEASURE AND ANALYSE YOUR DIGITAL MARKETING EFFORTS100 TOOLS TO MEASURE AND ANALYSE YOUR DIGITAL MARKETING EFFORTS
100 TOOLS TO MEASURE AND ANALYSE YOUR DIGITAL MARKETING EFFORTS
 
sql ppt for students who preparing for sql
sql ppt for students who preparing for sqlsql ppt for students who preparing for sql
sql ppt for students who preparing for sql
 
DBA Fundamentals Group: Continuous SQL with Kafka and Flink
DBA Fundamentals Group: Continuous SQL with Kafka and FlinkDBA Fundamentals Group: Continuous SQL with Kafka and Flink
DBA Fundamentals Group: Continuous SQL with Kafka and Flink
 
SPM 2024 – Overview of and benefits of AI in Product Management
SPM 2024 – Overview of and benefits of AI in Product ManagementSPM 2024 – Overview of and benefits of AI in Product Management
SPM 2024 – Overview of and benefits of AI in Product Management
 
Les02 Restricting and Sorting Data using SQL.ppt
Les02 Restricting and Sorting Data using SQL.pptLes02 Restricting and Sorting Data using SQL.ppt
Les02 Restricting and Sorting Data using SQL.ppt
 
Software Testing life cycle (STLC) Importance, Phases, Benefits...
Software Testing life cycle (STLC) Importance, Phases, Benefits...Software Testing life cycle (STLC) Importance, Phases, Benefits...
Software Testing life cycle (STLC) Importance, Phases, Benefits...
 
killingcamp 광고삽입문제 풀이, killingcamp 광고삽입문제 풀이
killingcamp 광고삽입문제 풀이, killingcamp 광고삽입문제 풀이killingcamp 광고삽입문제 풀이, killingcamp 광고삽입문제 풀이
killingcamp 광고삽입문제 풀이, killingcamp 광고삽입문제 풀이
 
Open Sprintera (Where Open Source Sparks a Sprint of Possibilities)
Open Sprintera (Where Open Source Sparks a Sprint of Possibilities)Open Sprintera (Where Open Source Sparks a Sprint of Possibilities)
Open Sprintera (Where Open Source Sparks a Sprint of Possibilities)
 
App Builder - Hierarchical Data Apps.pptx
App Builder - Hierarchical Data Apps.pptxApp Builder - Hierarchical Data Apps.pptx
App Builder - Hierarchical Data Apps.pptx
 
eLearning Content Development Company Code and Pixels.pdf
eLearning Content Development Company Code and Pixels.pdfeLearning Content Development Company Code and Pixels.pdf
eLearning Content Development Company Code and Pixels.pdf
 
Sql server types of joins with example.pptx
Sql server types of joins with example.pptxSql server types of joins with example.pptx
Sql server types of joins with example.pptx
 
"Discovery and Delivery through Product IntelliGenAI framework" by Ramkumar A...
"Discovery and Delivery through Product IntelliGenAI framework" by Ramkumar A..."Discovery and Delivery through Product IntelliGenAI framework" by Ramkumar A...
"Discovery and Delivery through Product IntelliGenAI framework" by Ramkumar A...
 
Industry 4.0: Building the Unified Namespace with Confluent, HiveMQ and Spark...
Industry 4.0: Building the Unified Namespace with Confluent, HiveMQ and Spark...Industry 4.0: Building the Unified Namespace with Confluent, HiveMQ and Spark...
Industry 4.0: Building the Unified Namespace with Confluent, HiveMQ and Spark...
 
AUTOKEYUNLOCKER-BRANDS-SUPPORT-STANDARD-VERSION.pdf
AUTOKEYUNLOCKER-BRANDS-SUPPORT-STANDARD-VERSION.pdfAUTOKEYUNLOCKER-BRANDS-SUPPORT-STANDARD-VERSION.pdf
AUTOKEYUNLOCKER-BRANDS-SUPPORT-STANDARD-VERSION.pdf
 
P1 Inspection Types in Municity 5 Smartsheet
P1 Inspection Types in Municity 5 SmartsheetP1 Inspection Types in Municity 5 Smartsheet
P1 Inspection Types in Municity 5 Smartsheet
 
killing camp week 6 problem - maximal matrix.pdf
killing camp week 6 problem - maximal matrix.pdfkilling camp week 6 problem - maximal matrix.pdf
killing camp week 6 problem - maximal matrix.pdf
 
AI Product Management by Abhijit Bendigiri
AI Product Management by Abhijit BendigiriAI Product Management by Abhijit Bendigiri
AI Product Management by Abhijit Bendigiri
 

Solidity Security and Best Coding Practices

  • 1. SOLIDITY BEST PRACTICES BLOCKCHAIN AND SMART CONTRACTS (SESSION 5) Hands-on introduction for Software Developers and Architects
  • 2. SECURITY RISKS • Security Risks • Attacks
  • 3. RACE CONDITIONS Contract A Contract B Contract C Contract A Contract B Contract C
  • 4. RACE CONDITIONS: REENTRANCY mapping (address => uint) private userBalances; function withdrawBalance() public { uint amountToWithdraw = userBalances[msg.sender]; require(msg.sender.call.value(amountToWithdraw)()); userBalances[msg.sender] = 0; } mapping (address => uint) private userBalances function withdrawBalance() public { uint amountToWithdraw = userBalances[msg.sender]; userBalances[msg.sender] = 0; require(msg.sender.call.value(amountToWithdra }
  • 5. RACE CONDITIONS: CROSS-FUNCTION RACE CONDITIONS mapping (address => uint) private userBalances; function transfer(address to, uint amount) { if (userBalances[msg.sender] >= amount) { userBalances[msg.sender] -= amount; userBalances[to] += amount; } } function withdrawBalance() public { uint amountToWithdraw = userBalances[msg.sender]; require(msg.sender.call.value(amountToWithdraw) userBalances[msg.sender] = 0; 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]; require(msg.sender.call.value(amountToWithdraw)()); userBalances[msg.sender] = 0;
  • 9. INTEGER OVERFLOW mapping (address => uint256) public balanceOf; function transfer(address _to, uint256 _value) { /* Check if sender has balance */ require(balanceOf[msg.sender] >= _value); /* Add and subtract new balances */ balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; } mapping (address => uint256) public balanceOf function transfer(address _to, uint256 _value) { /* Check if sender has balance and for overflo */ require(balanceOf[msg.sender] >= _value && balanceOf[_to] + _value >= balanceOf[_to]); /* Add and subtract new balances */ balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; }
  • 10. INTEGER UNDERFLOW function underflow() returns (uint256 _underflow) { uint256 min = 0; return min - 1; } 0 - 1 = 2**256 - 1
  • 11. DENIAL OF SERVICE address[] private refundAddresses; mapping (address => uint) public refunds; function refundAll() public { for(uint x; x < refundAddresses.length; x++) { // arbitrary length iteration based on how many addresses participated require(refundAddresses[x].send(refunds[refun dAddresses[x]])) // doubly bad, now a single failure on send will hold up all funds } } Contract A1 A2 A3 A4
  • 12. FORCIBLY SENDING ETHER TO A CONTRACT contract Vulnerable { function () payable { revert(); } function somethingBad() { require(this.balance > 0); // Do something risky here } }
  • 14. AVOID RACE CONDITIONS someAddress.call(); //Raw call ExternalContract.someMethod(); //Contract call Avoid state changes after external calls Checks  Who made the call?  Arguments correct?  Did they send enough money?  … Updates Change Internal State Updates Call Other Contract(s)
  • 15. EXTERNAL CALLS Bad Good Bank.withdraw(100); function makeWithdrawal(uint amount) { // Isn't clear that this function is potentially unsafe Bank.withdraw(amount); } UntrustedBank.withdraw(100); // untrusted external call TrustedBank.withdraw(100); // external but trusted bank contract maintained by XYZ function makeUntrustedWithdrawal(uint amount) { UntrustedBank.withdraw(amount); }
  • 16. AVOID REENTRANCY UsesomeAddress.send() or someAddress.transfer() Bad Good someAddress.call.value()() //give all the gas! someAddress.send() //or someAddress.transfer()
  • 18. FAVOR PULL OVER PUSH Bad Good contract auction { address highestBidder; uint highestBid; function bid() payable { require(value >= highestBid); if (highestBidder != 0) { highestBidder.transfer(highestBid); // if this call consistently fails, no one else can bid } highestBidder = sender; highestBid = value; } } contract auction { address highestBidder; uint highestBid; mapping(address => uint) refunds; function bid() payable external { require(value >= highestBid); if (highestBidder != 0) { refunds[highestBidder] += highestBid; // record the } highestBidder = sender; highestBid = value; } function withdrawRefund() external { uint refund = refunds[sender]; refunds[sender] = 0; .sender.transfer(refund); } }
  • 19. ASSERT Assert often. Create smart asserts contract Token { mapping(address => uint); public balanceOf; uint public totalSupply; function deposit() public payable { balanceOf[msg.sender] += msg.value; totalSupply += msg.value; assert(this.balance>= totalSupply); } }
  • 20. REQUIRE Require arguments pragma solidity ^0.4.0; contract Sharer { function sendHalf(address addr) public payable returns (uint balance) { require(msg.value % 2 == 0); // Only allow even numbers uint balanceBeforeTransfer = this.balance; addr.transfer(msg.value / 2); // Since transfer throws an exception on failure and // cannot call back here, there should be no way for us to // still have half of the money. assert(this.balance == balanceBeforeTransfer - msg.value / 2); return this.balance; } }
  • 21. AVOID ROUNDING ERRORS ERRORS Bad uint x = 5 / 2; contract Divide { function getDivided(uint numerator, uint denominator) public constant returns(uint quotient, uint remainder) { quotient = numerator / denominator; remainder = numerator - denominator * quotient; } }
  • 22. KEEP FALLBACK FUNCTIONS SIMPLE Bad Good function() payable { balances[msg.sender] += msg.value; } function deposit() payable external { balances[msg.sender] += msg.value; } function() payable { deposit(msg.sender); }
  • 23. MARK VISIBILITY IN FUNCTIONS AND VARIABLES Bad Good uint x; // the default is internal function buy() { // the default is public // public code } uint private y; function buy() external { // only callable externally } function utility() public { // callable externally, as well as internally: changing this code requires thinking about both cases. } function internalAction() internal { // internal code }
  • 24. LOCK COMPILER VERSION Bad Good pragma solidity ^0.4.4; pragma solidity 0.4.4;
  • 25. DIFFERENTIATE FUNCTIONS AND EVENTS Bad Good event Transfer() {} function transfer() {} event LogTransfer() {} function transfer() external {}
  • 26. USER NEW CONSTRUCTS Bad Good suicide() sha3() selfdestruct() keccak256()
  • 27. UNDERSTAND MULTIPLE INHERITANCEcontract Final { uint public a; function Final(uint f) public { a = f; } } contract B is Final { int public fee; function B(uint f) Final(f) public { } function setFee() public { fee = 3; } } contract C is Final { int public fee; function C(uint f) Final(f) public { } function setFee() public { fee = 5; } } contract A is B, C { function A() public B(3) C(5) { setFee(); } }
  • 28. UNDERSTAND 3 WAYS OF SENDING ETHER address.send() address.transfer( ) address.call.valu e()() contract Sender { function send(address _receiver) payable { _receiver.send(msg.value); } } contract Receiver { uint public balance = 0; event Receive(uint value); function () payable { Receive(msg.value); } } contract Sender { function send(address _receiver) payable { _receiver.transfer(msg.value); } } contract Receiver { uint public balance = 0; event Receive(uint value); function () payable { Receive(msg.value); } } contract Sender { function send(address _receiver) payable { _receiver.call.value(msg.value).gas(20317)(); } } contract Receiver { uint public balance = 0; function () payable { balance += msg.value; } } • Can not set gas limit • Returns false on error • Can not set gas limit • Exception on error • Can set gas limit • Exception on error
  • 29. MISCELLANEOUS SUGGESTIONS Don't assume contracts are created with zero balance Remember that on-chain data is public Be aware that players can “drop out” Remember that Block.timestamp can be manipulated Include a Fail-Safe Mode
  • 31. STAY IN TOUCH Gene Leybzon https://www.linkedin.com/in/leybzon/ https://www.meetup.com/members/90744 20/ https://www.leybzon.com

Editor's Notes

  1. https://consensys.github.io/smart-contract-best-practices/known_attacks/
  2. https://blog.acolyer.org/2018/03/08/zeus-analyzing-safety-of-smart-contracts/
  3. https://consensys.github.io/smart-contract-best-practices/known_attacks
  4. https://gist.github.com/aquabu/30378c5375f388a28572dd18d58f787f
  5. https://consensys.github.io/smart-contract-best-practices/recommendations/
  6. Clearly show in the code that this is the call to external (untrused) contract https://consensys.github.io/smart-contract-best-practices/recommendations/
  7. Only 2,300 gas given to called contract for “Good” x.transfer(y) === require(x.send(y))
  8. Clearly show in the code that this is the call to external (untrused) contract https://consensys.github.io/smart-contract-best-practices/recommendations/
  9. Clearly show in the code that this is the call to external (untrused) contract https://consensys.github.io/smart-contract-best-practices/recommendations/
  10. https://consensys.github.io/smart-contract-best-practices/recommendations/
  11. http://solidity.readthedocs.io/en/v0.4.21/control-structures.html#error-handling-assert-require-revert-and-exceptions
  12. // Result is 2
  13. Clearly show in the code that this is the call to external (untrused) contract https://consensys.github.io/smart-contract-best-practices/recommendations/
  14. Clearly show in the code that this is the call to external (untrused) contract https://consensys.github.io/smart-contract-best-practices/recommendations/
  15. Clearly show in the code that this is the call to external (untrused) contract https://consensys.github.io/smart-contract-best-practices/recommendations/
  16. Clearly show in the code that this is the call to external (untrused) contract https://consensys.github.io/smart-contract-best-practices/recommendations/
  17. Clearly show in the code that this is the call to external (untrused) contract https://consensys.github.io/smart-contract-best-practices/recommendations/
  18. When A is deployed, the compiler will linearize the inheritance from left to right, as: C -> B -> A
  19. 2300 is the gas limit
  20. http://solidity.readthedocs.io/en/develop/security-considerations.html?highlight=check%20effects#include-a-fail-safe-mode
  21. https://capturetheether.com/