Hacking Smart Contracts: Beginners Guide

0xPredator
8 min readApr 8, 2022

Overview of the basics of smart contracts.

In the simplest terms, a smart contract is nothing but a computer program that runs on a blockchain. Although the main goal of having real-world contracts executed via code was to reduce the cost and time involved in transforming natural language contracts into executable code, there has been a tremendous increase in the number of use cases surrounding smart contracts.

If you are new to this whole idea of smart contracts and have no idea where to begin, here’s something that might help you!

What is a Smart Contract?

A smart contract can be defined as an agreement within the blockchain between two people. The most important part about this agreement is that it is self-executing, secure and does not require any third party involvement like lawyers or banks. It also eliminates counterparty risk by allowing users to check their balances at any point in time and make sure no one has changed their balances without mutual consent. The best way to understand what do we mean when we say “smart contracts” is by breaking down it’s name piece by piece:

  1. Contracts: After various laws were added on top of each other over time for different reasons, a contract became more than just an exchange of promises between two people. A well-drafted agreement would contain all kinds of representations, warranties and clauses which were designed to protect both parties from unexpected events happening during the course of the transaction.
  2. Smart: This refers to how well self executing these agreements are in real life situations vs when they are actually needed.Now we know what constitutes Smart Contracts, let us look at some real world examples!A simple example would be transferring money from your bank account directly into your friend’s account every month without requiring you (or your friend) to manually

Why are they used?

Because of the way smart contracts are designed, they allow for the trustless execution of code. This means we can create autonomous organizations that don’t need to be controlled by a central authority. They reduce transaction costs and eliminate the need for trusted third parties. Why does this matter? Because it allows us to automate transactions with each other and ensure that they happen in a manner that has been agreed upon by all parties (the right amount of money, is sent at the right time, etc.). It also reduces the need for third parties who handle this process manually (like banks or lawyers).

What are they made of?

A smart contract is a computer protocol intended to digitally facilitate, verify, or enforce the negotiation or performance of a contract. Smart contracts allow the performance of credible transactions without third parties. These transactions are trackable and irreversible.

Smart contracts are made of software code that runs on blockchain technology. This code interacts with blockchain’s native ledger to execute specific functions when certain conditions are met. The code can be written in various programming languages such as Solidity (used by Ethereum), Simplicity (used by Blockstream), and others depending on the type of blockchain used to deploy the smart contract.

Generally speaking, a smart contract is created for two main reasons:

  • To store data about an agreement between two people in a transparent, conflict-free way while avoiding the services of a middleman
  • To run an application automatically based on this agreement

Solidity

Solidity is the most popular language for writing Ethereum smart contracts. It is a contract-oriented language, which means that it was built for writing smart contracts and mimics the real-world contract concepts such as class, state variables, functions, inheritance and libraries. Solidity inherits some syntax from JavaScript and Python languages as well.

The Solidity code is written in ECMAScript (or JavaScript) and compiled to bytecode for the EVM. It is statically typed, supports inheritance and libraries.

How do you get started?

To get started with smart contract hacking, you need to do the following:

  • Install Metamask
  • Create a new wallet in Metamask and save your seed phrase
  • Get free test Ether from a faucet (https://faucet.ropsten.be/ or https://faucet.metamask.io/)
  • Connect to the Ethereum Test Network (Ropsten) in Metamask through their dropdown menu at the top of the page
  • Install Remix (https://remix.ethereum.org/)
  • Install Solidity Compiler (https://solidity.readthedocs.io/en/develop/installing-solidity.html#binary-packages)
  • Install Truffle (http://truffleframework.com/) using npm install -g truffle
  • Install Solidity Linter (https://github.com/duaraghav8/SolidityLinter) using npm install -g solidity-linter

Common vulnerabilities and exploits

Several vulnerabilities exist in Smart Contracts that can be exploited by malicious actors. These attacks can allow an attacker to gain control of code execution and steal funds, delete data, or alter the state of a contract (aka change the rules it was coded to apply).

The most prominent vulnerability is called “replay attacks” because it allows an attacker to repeatedly perform actions on a Smart Contract (e.g. sending transactions) without spending any money from their own funds — which defeats the purpose of using the platform! If you send a transaction and your contract’s code accepts that transaction for some purpose (e.g. issuing tokens), then any later transaction with different inputs should be rejected by your contract’s logic as being invalid, since there has been no transfer of funds between those accounts! Unfortunately, this does not always happen, as attackers are often able to write custom contracts that don’t check for repeated transactions.

Another major issue is integer overflow and underflow. An integer overflow happens when a function overflows its limited range of numbers available (i.e. adding one million dollars to $0 evaluates to $1 million). An underflow happens when trying to convert one large number into another large number (e.g. converting 1 billion dollars into 4 billion dollars).

Reentrancy is another common attack mechanism: an attacker gaining control over your code may be able to use that access to run further actions themselves in order to exploit other parts of your code or even access other accounts controlled by you on this platform! This sort of problem occurs when employing functions that are designed so that they can take multiple arguments in order execute additional code — commonly referred as callback functions.

Replay attack

A replay attack is when a transaction is broadcast to the network by a malicious actor, then repeated by the same actor after it has been originally mined into a block.

Replay attacks happen when an attacker broadcasts a transaction to the network, and then tries to rebroadcast that same transaction before miners have had time to mine it into a block. This may cause the first broadcast of this transaction to be canceled since miners will ignore additional transactions with identical nonce and senders.

This can be prevented by making sure that the sender’s account and the nonce of each transaction are unique.

An example of such an attack would be if Alice sends Bob 10 ether, but Eve (who has access to Alice’s private key) rebroadcasts Alice sending Bob 10 ether again before it gets mined into a block. In this scenario, only one of Eve’s two attempted Ether transfers will successfully go through. If both were accepted, we could say that Eve ‘double-spent” her Ether transfer.

Integer Overflow and Underflow

It’s important to start off by going over what integer overflow and underflow are. These two functions allow for overflows and underflows — these are impossible outcomes that can cause bad things to happen. An integer is basically a whole number, like 1, 5, or 45; it’s the basic unit of computer data. Both overflow and underflow will result in an integer value being greater than or equal to the original number and less than the original number — in other words they both represent an impossibility! Check out my article about Integer Overflows and Underflows here.

Reentrancy Attack

What is a reentrancy attack? A reentrancy attack is a blockchain bug that allows hackers to steal the balance of a smart contract. It occurs when a smart contract calls an untrusted external address and that external address is able to call the original contract back again before the first transaction has completed. This can allow an attacker’s malicious code to drain the funds in the first account before it has finished executing.

How can you defend against this? Here are two ways you can protect your contracts from being vulnerable:

  • You should use require() or assert() statments each time your function transfers Ether, and make sure that there are no pending withdrawals from the same account. __However be aware__ that this does not cover all cases since withdrawing part of your balance could still allow for an attacker to withdraw more using reentrancy.
  • The best way to protect yourself from reentrancy attacks is through careful design. For example, in some instances it might be better to use mechanisms like withdrawal patterns instead of directly transferring Ether out of your contracts (more on this later.)

You can read more about this on my other article about re-entracy.

Why is this important for your project?

Smart contracts are code. And code, as we all know, can be hacked. Given the amount of attention being paid to smart contracts in the public sphere, no one should be surprised if hackers attempt to exploit security vulnerabilities in smart contracts.

Keeping this in mind, it is essential that you do not take smart contract security for granted. You need to test your smart contract by using test automation tools and audit its security with the help of experienced engineers and other experts who specialize in blockchain technology.

It is also important for you to understand the tools you are using and even how other people’s code works so that you can identify potential issues before they crop up during execution of transactions.

Smart contract technology is here to stay.

Hopefully you’ve enjoyed this short introduction to smart contracts and are now wondering how you can get involved in the field. If so, I have good news for you! You already possess some of the required skills.

If you have a solid understanding of Javascript, or know your way around C++/Python(Ruby)/GoLang and Linux, then this is definitely something worth exploring further. These are the primary languages used by most blockchain projects to write their smart contracts. Additionally, if you’re experienced working with Ethereum’s Solidity language, then even better! If not, then no worries! There are plenty of online resources that will help you learn the basics in no time at all. You can also join various community slack channels where people will be willing to answer any questions that might come up as you start learning more about this exciting new technology.

Contents distributed by Learn.Block6.tech

👉 Discord — Live Talks

👉 Twitter — Latest articles

👉 LinkTr.ee

--

--

0xPredator

I write about Crypto Currencies and Hacking Smart Contracts. Twitter: twitter.com/0xPredator Buy me a coffee: buymeacoffee.com/0xPredator