SlideShare a Scribd company logo
1 of 31
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!
REENTRANCY ATTACK
UNCHECKED SEND
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;
}
INTEGER UNDERFLOW
function underflow() returns (uint256 _underflow) {
uint256 min = 0;
return min - 1;
}
0 - 1 = 2**256 - 1
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
FORCIBLY SENDING ETHER TO A
CONTRACT
contract Vulnerable {
function () payable {
revert();
}
function somethingBad() {
require(this.balance > 0);
// Do something risky here
}
}
BEST PRACTICES
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)
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);
}
AVOID REENTRANCY
UsesomeAddress.send() or
someAddress.transfer()
Bad
Good
someAddress.call.value()() //give all the gas!
someAddress.send()
//or
someAddress.transfer()
HANDLE ERRORS
Bad Good
someAddress.send(55);
someAddress.value(55)();
someAddress.value(100)(bytes4(sha3("deposit()")));
if(!someAddress.send(55)) {
// Some failure code
}
ExternalContract(someAddress).deposit.value(100);
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);
}
}
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);
}
}
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;
}
}
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;
}
}
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); }
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
}
LOCK COMPILER VERSION
Bad Good
pragma solidity ^0.4.4;
pragma solidity 0.4.4;
DIFFERENTIATE FUNCTIONS AND
EVENTS
Bad Good
event Transfer() {}
function transfer() {}
event LogTransfer() {}
function transfer() external {}
USER NEW CONSTRUCTS
Bad Good
suicide()
sha3()
selfdestruct()
keccak256()
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();
}
}
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
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
NEXT STEP
https://capturetheether.com/
STAY IN TOUCH
Gene Leybzon https://www.linkedin.com/in/leybzon/
https://www.meetup.com/members/90744
20/
https://www.leybzon.com

More Related Content

What's hot

Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...
Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...
Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...
Simplilearn
 
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
劉 維仁
 
Examples of Smart Contracts
Examples of Smart ContractsExamples of Smart Contracts
Examples of Smart Contracts
101 Blockchains
 
Seminar Report On Bitcoin
Seminar Report On BitcoinSeminar Report On Bitcoin
Seminar Report On Bitcoin
Touroxy
 
Web3 Security: The Blockchain is Your SIEM
Web3 Security: The Blockchain is Your SIEMWeb3 Security: The Blockchain is Your SIEM
Web3 Security: The Blockchain is Your SIEM
Tal Be'ery
 

What's hot (20)

Smart Contract & Ethereum
Smart Contract & EthereumSmart Contract & Ethereum
Smart Contract & Ethereum
 
Overview of blockchain technology and architecture
Overview of blockchain technology and   architectureOverview of blockchain technology and   architecture
Overview of blockchain technology and architecture
 
Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...
Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...
Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...
 
Blockchain consensus algorithms
Blockchain consensus algorithmsBlockchain consensus algorithms
Blockchain consensus algorithms
 
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
 
Introduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart ContractsIntroduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart Contracts
 
Ethermint 2.0: An Ethereum Scaling Solution by Cosmos
Ethermint 2.0: An Ethereum Scaling Solution by CosmosEthermint 2.0: An Ethereum Scaling Solution by Cosmos
Ethermint 2.0: An Ethereum Scaling Solution by Cosmos
 
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
 
Ethereum-Cryptocurrency (All about Ethereum)
Ethereum-Cryptocurrency (All about Ethereum) Ethereum-Cryptocurrency (All about Ethereum)
Ethereum-Cryptocurrency (All about Ethereum)
 
Examples of Smart Contracts
Examples of Smart ContractsExamples of Smart Contracts
Examples of Smart Contracts
 
Seminar Report On Bitcoin
Seminar Report On BitcoinSeminar Report On Bitcoin
Seminar Report On Bitcoin
 
Les principales failles de sécurité des applications web actuelles
Les principales failles de sécurité des applications web actuellesLes principales failles de sécurité des applications web actuelles
Les principales failles de sécurité des applications web actuelles
 
Blockchain Consensus Protocols
Blockchain Consensus ProtocolsBlockchain Consensus Protocols
Blockchain Consensus Protocols
 
Web3 Security: The Blockchain is Your SIEM
Web3 Security: The Blockchain is Your SIEMWeb3 Security: The Blockchain is Your SIEM
Web3 Security: The Blockchain is Your SIEM
 
Smart contracts using web3.js
Smart contracts using web3.jsSmart contracts using web3.js
Smart contracts using web3.js
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
 
Smart contract
Smart contractSmart contract
Smart contract
 
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...
 
Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 

Similar to Solidity Security and Best Coding Practices

Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
Abdul Samee
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
AOE
 

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 in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
 
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
 

More from Gene Leybzon

Non-fungible tokens (nfts)
Non-fungible tokens (nfts)Non-fungible tokens (nfts)
Non-fungible tokens (nfts)
Gene 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

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
+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
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
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
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
+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...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
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-...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 

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/