ADVANCED
Presenter: Loc Doan
SMART CONTRACT
SECURITY ISSUES
❖ Race Condition
❖ Timestamp Dependence
❖ Integer Overflow and Underflow
❖ DoS with (Unexpected) revert
❖ DoS with Block Gas Limit
❖ Transfer vs Send
FROM BUSINESS REQUIREMENTS TO TECHNICAL
IMPLEMENTATION (CROWDSALE, TRANCHE SALE, ETC)
❖ Basic Functionality
❖ Basic Functionality for Token
❖ Basic Functionality for Crowdsale
Timeline
RACE CONDITION
public class Counter {
protected long count = 0;
public void add(long value){
this.count = this.count + value;
}
}
this.count = 0;
A: Reads this.count into a register (0)
B: Reads this.count into a register (0)
B: Adds value 2 to register
B: Writes register value (2) back to memory.
this.count now equals 2
A: Adds value 3 to register
A: Writes register value (3) back to memory.
this.count now equals 3
❖ Thread A wants to add 2 to this.count.
❖ Thread B wants to add 3 to this.count.
❖ Expected result => 5.
❖ Real results => 3.
REENTRANCY
mapping (address => uint) private userBalances;
function withdrawBalance() public {
uint amountToWithdraw = userBalances[msg.sender];
require(msg.sender.call.value(amountToWithdraw)()); // At this point, the caller's code is executed, and can call
withdrawBalance again
userBalances[msg.sender] = 0;
}
CROSS-FUNCTION RACE CONDITIONS
t
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)()); // At this point, the caller's code is executed, and can call transfer()
userBalances[msg.sender] = 0;
}
CHECKS-
EFFECTS-INTERACTIONS
1. Conditions
2. Effects (potentially changing
conditions)
3. Interaction
You need to not only avoid calling external functions
too soon, but also avoid calling functions which call
external functions.
MUTEX
t
function deposit() payable public returns (bool) {
require(!lockBalances);
lockBalances = true;
balances[msg.sender] += msg.value;
lockBalances = false;
return true;
}
MUTEX
t
contract StateHolder {
uint private n;
address private lockHolder;
function getLock() {
require(lockHolder == 0);
lockHolder = msg.sender;
}
function releaseLock() {
require(msg.sender == lockHolder);
lockHolder = 0;
}
function set(uint newState) {
require(msg.sender == lockHolder);
n = newState;
}
}
If you use mutexes to protect against race conditions, you will need to
carefully ensure that there are no ways for a lock to be claimed and
never released.
TIMESTAMP DEPENDENCE
Can be manipulated by the
miner
Use block.number + average blocktime to estimate
INTEGER OVERFLOW
AND UNDERFLOW
Beware of small int
DOS WITH BLOCK GAS LIMIT
struct Payee {
address addr;
uint256 value;
}
Payee[] payees;
uint256 nextPayeeIndex;
function payOut() {
uint256 i = nextPayeeIndex;
while (i < payees.length && msg.gas > 200000) {
payees[i].addr.send(payees[i].value);
i++;
}
nextPayeeIndex = i;
}
Don't iterate. If you have, you
can divide it into multiple
transaction.
DOS WITH (UNEXPECTED) REVERT
contract Auction {
address currentLeader;
uint highestBid;
function bid() payable {
require(msg.value > highestBid);
require(currentLeader.send(
highestBid)); // Refund the old leader, if it fails then revert
currentLeader = msg.sender;
highestBid = msg.value;
}
}
address[] private refundAddresses;
mapping (address => uint) public refunds;
// bad
function refundAll() public {
for(uint x; x < refundAddresses.length; x++) { // arbitrary
length iteration based on how many addresses participated
require(refundAddresses[x].send(
refunds[refundAddresses[x]])) // doubly bad, now a single
failure on send will hold up all funds
}
}
Solution: pull over push payment: create a refund function.
Transfer vs Send
Transfer
address x = 0x123;
address myAddress = this;
if (x.balance < 10 && myAddress.balance >= 10) x.transfer(10);
If x is a contract address, its code (more specifically: its fallback function, if
present) will be executed together with the transfer call (this is a feature of
the EVM and cannot be prevented). If that execution runs out of gas or fails
in any way, the Ether transfer will be reverted and the current contract will
stop with an exception.
Send
If the execution fails, the current contract will not stop with an exception,
but send will return false.
There are some dangers in using send: The transfer fails if the call stack
depth is at 1024 (this can always be forced by the caller) and it also fails if
the recipient runs out of gas. So in order to make safe Ether transfers,
always check the return value of send, use transfer or even better: use a
pattern where the recipient withdraws the money.
❖ Token
❖ Pricing Strategy
❖ Finalize Agent
Crowdsale
Structure
SAFE MATH OWNABLE HALTABLE
Safe unsigned safe
math.
Provides basic
authorization control.
Implement an
emergency stop
mechanism.
BURNABLE
TOKEN
RELEASABLE
TOKEN
UPGRADEABLE
TOKEN
Implement burn
functionality for token.
It means destroy, or
make the token
invalid.
Allow token to be
transfered after the
crowdsale. Still give
some special case can
be transfered
Content: Allow to
transfer token from a
contract to another
contract. This "another
contract" can have
upgraded functionality
for the token.
MINTABLE
TOKEN
CROWDSALE
TOKEN
Implement mint
functionality for token.
It means to create new
token in the system.
A crowdsaled token.
PRICING
STRATEGY
FLAT
PRICING
Interface for defining
crowdsale pricing.
Fixed crowdsale pricing
- everybody gets the
same price.
MILESTONE
PRICING
TOKEN TRANCHE
PRICING
Time milestone based
pricing with special
support for pre-ico
deals.
Tranche based pricing
with special support for
pre-ico deals.
FINALIZE AGENT NULL
FINALIZE AGENT
DEFAULT
FINALIZE AGENT
Finalize agent defines
what happens at the
end of succeseful
crowdsale.
A finalize agent that
does nothing. Token
transfer must be
manually released by
the owner.
Unlock tokens.
BONUS
FINALIZE AGENT
EXTRA
FINALIZE AGENT
At the end of the
successful crowdsale
allocate % bonus of
tokens to the team.
Unlock tokens.
At the end of the
successful crowdsale
allocate % bonus of
tokens to the team.
Do not unlock the
tokens.
CROWDSALEBASE CROWDSALE UNCAPPEDCROWDSALE
Implements basic state
machine logic, but leaves
out all buy functions so
that subclasses can
implement their own
buying logic.
Abstract base contract
for token sales with the
default buy entry
points.
Handle
Does not Handle
Intended usage
- A short time window
- Flat price
- No cap
MINTEDETHCAPPE-
CROWDSALE
MINTEDTOKENCAPPED-
CROWDSALE
RELAUNCHED-
CROWDSALE
ICO crowdsale contract
that is capped by
amount of ETH.
Tokens are dynamically
created during the
crowdsale.
ICO crowdsale contract
that is capped by amout
of tokens.
Tokens are dynamically
created during the
crowdsale.
A crowdsale that retains
the previous token, but
changes some parameters.
Investor data can be
manually fed in.
Mostly useful as a hot fix
Q&A
THANK YOU FOR LISTENING

More Related Content

PPT
Qtum How To Make EVM Run On UTXO Model - Patrick Dai
PPTX
Solidity Security and Best Coding Practices
PPTX
Hands on with smart contracts 2. Presentation for the Blockchain Applications...
PDF
Smart contract and Solidity
PPTX
Smart Contracts with Solidity hands-on training session
PPTX
Principais vulnerabilidades em Smart Contracts e como evitá-las
PPTX
Dex and Uniswap
PDF
0853352_Report_Valuing Warrants With VBA
Qtum How To Make EVM Run On UTXO Model - Patrick Dai
Solidity Security and Best Coding Practices
Hands on with smart contracts 2. Presentation for the Blockchain Applications...
Smart contract and Solidity
Smart Contracts with Solidity hands-on training session
Principais vulnerabilidades em Smart Contracts e como evitá-las
Dex and Uniswap
0853352_Report_Valuing Warrants With VBA

What's hot (16)

PDF
Lattice Cryptography
PPTX
Solidity
PDF
ERC20 Token Contract
PDF
Lattice Based Cryptography - GGH Cryptosystem
PDF
Introduction - Lattice-based Cryptography
PPTX
Hands on with smart contracts
PDF
Fast Multiparty Threshold ECDSA with Fast TrustlessSetup
PDF
A survey on Fully Homomorphic Encryption
PPT
The rsa algorithm
PPT
The rsa algorithm
PPTX
CRC Error coding technique
PDF
Homomorphic encryption in_cloud
PDF
Multi qubit entanglement
PDF
CRC JAVA CODE
PPTX
Bch codes
PPTX
Substitution techniques
Lattice Cryptography
Solidity
ERC20 Token Contract
Lattice Based Cryptography - GGH Cryptosystem
Introduction - Lattice-based Cryptography
Hands on with smart contracts
Fast Multiparty Threshold ECDSA with Fast TrustlessSetup
A survey on Fully Homomorphic Encryption
The rsa algorithm
The rsa algorithm
CRC Error coding technique
Homomorphic encryption in_cloud
Multi qubit entanglement
CRC JAVA CODE
Bch codes
Substitution techniques
Ad

Similar to Advanced smart contract (20)

PDF
“Create your own cryptocurrency in an hour” - Sandip Pandey
PDF
Blockchain School 2019 - Security of Smart Contracts.pdf
PDF
Security in the blockchain
PPTX
Best practices to build secure smart contracts
PPTX
Hello world contract
PDF
Smart Contract Security
PDF
Blockchain and smart contracts, what they are and why you should really care ...
PPTX
Abstract Factory pattern application on multi-contract on-chain deployments
PPTX
ICO protocols & implementations - Ivan Kamakin - Codemotion Amsterdam 2018
PPTX
lecture7 blockchain ethereum mechanics 101
PPTX
Smart Contract Testing
PPTX
Robust Programming of Smart Contracts in Solidity+, RK Shyamasundar
PPTX
Solidity Simple Tutorial EN
ODP
Stefano Maestri - Blockchain and smart contracts, what they are and why you s...
PPTX
Ethereum
PPTX
Introduction_to_Blockchain_&_Ethereum.pptx
PDF
PPT Class Blockchain - Validation and CASE.pdf
PPTX
The Ethereum Blockchain - Introduction to Smart Contracts and Decentralized A...
PDF
Smart Contarct Vulnerabilities and Attack Prevention
PPTX
Kriptovaluták, hashbányászat és okoscicák
“Create your own cryptocurrency in an hour” - Sandip Pandey
Blockchain School 2019 - Security of Smart Contracts.pdf
Security in the blockchain
Best practices to build secure smart contracts
Hello world contract
Smart Contract Security
Blockchain and smart contracts, what they are and why you should really care ...
Abstract Factory pattern application on multi-contract on-chain deployments
ICO protocols & implementations - Ivan Kamakin - Codemotion Amsterdam 2018
lecture7 blockchain ethereum mechanics 101
Smart Contract Testing
Robust Programming of Smart Contracts in Solidity+, RK Shyamasundar
Solidity Simple Tutorial EN
Stefano Maestri - Blockchain and smart contracts, what they are and why you s...
Ethereum
Introduction_to_Blockchain_&_Ethereum.pptx
PPT Class Blockchain - Validation and CASE.pdf
The Ethereum Blockchain - Introduction to Smart Contracts and Decentralized A...
Smart Contarct Vulnerabilities and Attack Prevention
Kriptovaluták, hashbányászat és okoscicák
Ad

Recently uploaded (20)

PDF
22EC502-MICROCONTROLLER AND INTERFACING-8051 MICROCONTROLLER.pdf
PDF
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
PPT
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
PDF
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
PDF
737-MAX_SRG.pdf student reference guides
PDF
August -2025_Top10 Read_Articles_ijait.pdf
PPTX
"Array and Linked List in Data Structures with Types, Operations, Implementat...
PPTX
Management Information system : MIS-e-Business Systems.pptx
PPTX
Fundamentals of Mechanical Engineering.pptx
PPTX
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life App...
PDF
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
PPTX
Module 8- Technological and Communication Skills.pptx
PDF
Accra-Kumasi Expressway - Prefeasibility Report Volume 1 of 7.11.2018.pdf
PPTX
Sorting and Hashing in Data Structures with Algorithms, Techniques, Implement...
PDF
August 2025 - Top 10 Read Articles in Network Security & Its Applications
PDF
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
PPTX
communication and presentation skills 01
PDF
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
PDF
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
PPTX
ASME PCC-02 TRAINING -DESKTOP-NLE5HNP.pptx
22EC502-MICROCONTROLLER AND INTERFACING-8051 MICROCONTROLLER.pdf
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
737-MAX_SRG.pdf student reference guides
August -2025_Top10 Read_Articles_ijait.pdf
"Array and Linked List in Data Structures with Types, Operations, Implementat...
Management Information system : MIS-e-Business Systems.pptx
Fundamentals of Mechanical Engineering.pptx
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life App...
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
Module 8- Technological and Communication Skills.pptx
Accra-Kumasi Expressway - Prefeasibility Report Volume 1 of 7.11.2018.pdf
Sorting and Hashing in Data Structures with Algorithms, Techniques, Implement...
August 2025 - Top 10 Read Articles in Network Security & Its Applications
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
communication and presentation skills 01
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
ASME PCC-02 TRAINING -DESKTOP-NLE5HNP.pptx

Advanced smart contract

  • 2. SECURITY ISSUES ❖ Race Condition ❖ Timestamp Dependence ❖ Integer Overflow and Underflow ❖ DoS with (Unexpected) revert ❖ DoS with Block Gas Limit ❖ Transfer vs Send FROM BUSINESS REQUIREMENTS TO TECHNICAL IMPLEMENTATION (CROWDSALE, TRANCHE SALE, ETC) ❖ Basic Functionality ❖ Basic Functionality for Token ❖ Basic Functionality for Crowdsale Timeline
  • 3. RACE CONDITION public class Counter { protected long count = 0; public void add(long value){ this.count = this.count + value; } } this.count = 0; A: Reads this.count into a register (0) B: Reads this.count into a register (0) B: Adds value 2 to register B: Writes register value (2) back to memory. this.count now equals 2 A: Adds value 3 to register A: Writes register value (3) back to memory. this.count now equals 3 ❖ Thread A wants to add 2 to this.count. ❖ Thread B wants to add 3 to this.count. ❖ Expected result => 5. ❖ Real results => 3.
  • 4. REENTRANCY mapping (address => uint) private userBalances; function withdrawBalance() public { uint amountToWithdraw = userBalances[msg.sender]; require(msg.sender.call.value(amountToWithdraw)()); // At this point, the caller's code is executed, and can call withdrawBalance again userBalances[msg.sender] = 0; }
  • 5. CROSS-FUNCTION RACE CONDITIONS t 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)()); // At this point, the caller's code is executed, and can call transfer() userBalances[msg.sender] = 0; }
  • 6. CHECKS- EFFECTS-INTERACTIONS 1. Conditions 2. Effects (potentially changing conditions) 3. Interaction You need to not only avoid calling external functions too soon, but also avoid calling functions which call external functions.
  • 7. MUTEX t function deposit() payable public returns (bool) { require(!lockBalances); lockBalances = true; balances[msg.sender] += msg.value; lockBalances = false; return true; }
  • 8. MUTEX t contract StateHolder { uint private n; address private lockHolder; function getLock() { require(lockHolder == 0); lockHolder = msg.sender; } function releaseLock() { require(msg.sender == lockHolder); lockHolder = 0; } function set(uint newState) { require(msg.sender == lockHolder); n = newState; } } If you use mutexes to protect against race conditions, you will need to carefully ensure that there are no ways for a lock to be claimed and never released.
  • 9. TIMESTAMP DEPENDENCE Can be manipulated by the miner Use block.number + average blocktime to estimate
  • 11. DOS WITH BLOCK GAS LIMIT struct Payee { address addr; uint256 value; } Payee[] payees; uint256 nextPayeeIndex; function payOut() { uint256 i = nextPayeeIndex; while (i < payees.length && msg.gas > 200000) { payees[i].addr.send(payees[i].value); i++; } nextPayeeIndex = i; } Don't iterate. If you have, you can divide it into multiple transaction.
  • 12. DOS WITH (UNEXPECTED) REVERT contract Auction { address currentLeader; uint highestBid; function bid() payable { require(msg.value > highestBid); require(currentLeader.send( highestBid)); // Refund the old leader, if it fails then revert currentLeader = msg.sender; highestBid = msg.value; } } address[] private refundAddresses; mapping (address => uint) public refunds; // bad function refundAll() public { for(uint x; x < refundAddresses.length; x++) { // arbitrary length iteration based on how many addresses participated require(refundAddresses[x].send( refunds[refundAddresses[x]])) // doubly bad, now a single failure on send will hold up all funds } } Solution: pull over push payment: create a refund function.
  • 13. Transfer vs Send Transfer address x = 0x123; address myAddress = this; if (x.balance < 10 && myAddress.balance >= 10) x.transfer(10); If x is a contract address, its code (more specifically: its fallback function, if present) will be executed together with the transfer call (this is a feature of the EVM and cannot be prevented). If that execution runs out of gas or fails in any way, the Ether transfer will be reverted and the current contract will stop with an exception. Send If the execution fails, the current contract will not stop with an exception, but send will return false. There are some dangers in using send: The transfer fails if the call stack depth is at 1024 (this can always be forced by the caller) and it also fails if the recipient runs out of gas. So in order to make safe Ether transfers, always check the return value of send, use transfer or even better: use a pattern where the recipient withdraws the money.
  • 14. ❖ Token ❖ Pricing Strategy ❖ Finalize Agent Crowdsale Structure
  • 15. SAFE MATH OWNABLE HALTABLE Safe unsigned safe math. Provides basic authorization control. Implement an emergency stop mechanism.
  • 16. BURNABLE TOKEN RELEASABLE TOKEN UPGRADEABLE TOKEN Implement burn functionality for token. It means destroy, or make the token invalid. Allow token to be transfered after the crowdsale. Still give some special case can be transfered Content: Allow to transfer token from a contract to another contract. This "another contract" can have upgraded functionality for the token.
  • 17. MINTABLE TOKEN CROWDSALE TOKEN Implement mint functionality for token. It means to create new token in the system. A crowdsaled token.
  • 18. PRICING STRATEGY FLAT PRICING Interface for defining crowdsale pricing. Fixed crowdsale pricing - everybody gets the same price.
  • 19. MILESTONE PRICING TOKEN TRANCHE PRICING Time milestone based pricing with special support for pre-ico deals. Tranche based pricing with special support for pre-ico deals.
  • 20. FINALIZE AGENT NULL FINALIZE AGENT DEFAULT FINALIZE AGENT Finalize agent defines what happens at the end of succeseful crowdsale. A finalize agent that does nothing. Token transfer must be manually released by the owner. Unlock tokens.
  • 21. BONUS FINALIZE AGENT EXTRA FINALIZE AGENT At the end of the successful crowdsale allocate % bonus of tokens to the team. Unlock tokens. At the end of the successful crowdsale allocate % bonus of tokens to the team. Do not unlock the tokens.
  • 22. CROWDSALEBASE CROWDSALE UNCAPPEDCROWDSALE Implements basic state machine logic, but leaves out all buy functions so that subclasses can implement their own buying logic. Abstract base contract for token sales with the default buy entry points. Handle Does not Handle Intended usage - A short time window - Flat price - No cap
  • 23. MINTEDETHCAPPE- CROWDSALE MINTEDTOKENCAPPED- CROWDSALE RELAUNCHED- CROWDSALE ICO crowdsale contract that is capped by amount of ETH. Tokens are dynamically created during the crowdsale. ICO crowdsale contract that is capped by amout of tokens. Tokens are dynamically created during the crowdsale. A crowdsale that retains the previous token, but changes some parameters. Investor data can be manually fed in. Mostly useful as a hot fix
  • 24. Q&A
  • 25. THANK YOU FOR LISTENING