Blockchain technology has revolutionized various industries by offering a secure and decentralized platform. However, as the popularity of blockchain-based applications and DeFi protocols grows, so does the attention of hackers seeking to exploit vulnerabilities. This article provides an overview of blockchain technology, discusses common attack vectors on smart contracts and DeFi protocols, and offers tips for Ethereum Solidity developers to guard against such hacks with code examples.
Blockchain is a distributed ledger technology that stores transactional data in a secure and immutable manner across a network of decentralized nodes.
Consensus mechanisms like Proof of Work (PoW) and Proof of Stake (PoS) ensure the integrity and validity of transactions.
Smart contracts are self-executing contracts with predefined rules written in code, enabling automation and transparency in blockchain applications.
Occurs when a contract's function is re-invoked before the initial function call completes. Hackers exploit this vulnerability to withdraw funds repeatedly until the contract's balance is depleted.
Arises when mathematical operations result in values that exceed the data type's maximum or minimum limit.
Hackers exploit this to manipulate values, leading to unintended consequences.
Hackers overload a smart contract or DeFi protocol with excessive requests, causing it to become unresponsive.
This prevents legitimate users from accessing the contract's functionalities.
Hackers monitor the blockchain for pending transactions and attempt to execute similar transactions with higher fees, gaining priority.
Front-runners can manipulate token prices, exploit arbitrage opportunities, or gain unfair advantages.
Exploits the ability to borrow funds without collateral and repay within a single transaction.
Hackers leverage these temporary funds to manipulate token prices or exploit protocol vulnerabilities.
I have dropped some great resources below that will put you on the path to blockchain domination!
https://github.com/ethereumbook/ethereumbook
https://app.buildspace.so/home
Learn more theory around programming, how to think as a programmer and also touches on HTML, CSS and JavaScript.
Harvard’s free Computer Science course (CS50x)
https://cs50.harvard.edu/x/2021/
This document provides a baseline knowledge of security considerations for intermediate Solidity programmers. It is maintained by ConsenSys Diligence, with contributions from friends in the Ethereum community.
https://consensys.github.io/smart-contract-best-practices/
The following code examples showcase various techniques and best practices that Solidity developers can employ to enhance the security of their smart contracts and DeFi protocols, safeguarding them against potential attacks and vulnerabilities.
Purpose: This pattern prevents reentrancy attacks by carefully managing the order of operations in a smart contract function.
How it works: It separates checks (such as ensuring the sender has sufficient balance) from effects (modifying the contract's state) and interactions (calling external contracts). This ensures that any external interactions are done after all the necessary checks and updates to the contract state, reducing the risk of reentrancy vulnerabilities.
function transferTokens(address _to, uint256 _amount) public {
require(balances[msg.sender] >= _amount, "Insufficient balance");
balances[msg.sender] -= _amount; // Checks & Effects
// Interactions
(bool success, ) = _to.call{value: 0}(
abi.encodeWithSignature("receiveTokens(address,uint256)",
msg.sender, _amount) );
require(success, "Transfer failed");
}
Purpose: This library helps prevent integer overflow and underflow vulnerabilities that can lead to unintended consequences in mathematical operations.
How it works: It performs arithmetic operations with additional checks to ensure that the result does not exceed the data type's maximum or minimum limits. If an overflow or underflow is detected, the function will throw an exception, preventing erroneous calculations and safeguarding the contract's integrity.
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256)
{
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
}
Purpose: This code example mitigates Denial of Service (DoS) attacks by limiting the frequency of executing certain functions.
How it works: By using a timestamp-based mechanism, the function can only be executed if a specific amount of time has passed since the last execution. This prevents malicious actors from overwhelming the contract with excessive function calls and keeps the contract responsive to legitimate users.
uint256 private lastExecutionTime;
uint256 private constant executionDelay = 1 hours;
function executeFunction() public {
require(block.timestamp >= lastExecutionTime +
executionDelay,"Function not ready yet");
// Function logic
lastExecutionTime = block.timestamp;
}
Purpose: This example demonstrates how to control access to specific functions or features within the contract, reducing the risk of unauthorized usage.
How it works: By maintaining a mapping of authorized addresses (e.g., administrators), the contract can use modifiers to restrict certain functions only to those with the proper authorization. This ensures that only trusted individuals can perform critical actions, minimizing the potential for unauthorized changes or misuse.
mapping(address => bool) public isAdmin; modifier onlyAdmin() {
require(isAdmin[msg.sender], "Not authorized");
_;
}
function addAdmin(address _newAdmin) public onlyAdmin {
isAdmin[_newAdmin] = true;
}
Blockchain technology has enormous potential to transform industries, but it is crucial to recognize and address its security challenges. Solidity developers working on smart contracts and DeFi protocols in Ethereum must be vigilant in understanding and mitigating the risks posed by potential vulnerabilities.
By adopting best coding practices and following the examples provided in this article, developers can bolster the security of their projects and contribute to a safer blockchain ecosystem.
Study and Take Quizzes on Ethereum smart contracts
https://github.com/x676f64/secureum-mind_map
Recommend doing these challenges in order. You will learn security concepts and practice/hone your skills.
Capture the Ether Challenger
Damn Vulnerable Defi
https://www.damnvulnerabledefi.xyz/
Paradigm CTF (one of the hardest around)
https://github.com/paradigm-operations/paradigm-ctf-2021
https://www.youtube.com/playlist?list=PLBy3Qkuapv_7R1ZI_Cs2NOFn7ZTaNWY6G
Subscribe to receive notifications when my next article is posted. Happy hunting!


