For the many individuals who are involved with exchanges in cryptocurrency, chances are good that you know of – or have passing knowledge of – ‘smart contracts.’ These functions have proven themselves to be an asset when it comes to connecting sellers and buyers. They also help reinforce the idea that middlemen are not always necessary for a contract to be properly executed. With that said, smart contracts are not without their flaws. This is why it’s so important to learn how to learn how to audit a smart contract.

So how does one go about auditing a smart contract? Why is this such a crucial procedure for an otherwise reliable system?

What are Smart Contracts?

Smart contracts are self-executing contracts with the terms of the agreement and any other data that is involved between the buyer and the seller being written directly into lines of code. The code and the agreements involved both exist within a distributed, decentralized blockchain network. Smart contracts are designed to allow trusted transactions and agreements to be carried out among varying anonymous parties. There’s no need of a middleman, such as a legal system, central authority, or regulator.

Additionally, smart contracts make transactions transparent and traceable, as well as irreversible.

The benefits that can come from using a smart contract in your endeavors include:

  • Turning legal obligations into more of an automated process
  • Guaranteeing a higher level degree of security
  • Reducing the standard reliance on trusted intermediates and any other form of middlemen
  • Lowering transaction costs

Uses of Smart Contracts

Smart contracts tend to mostly get tied to and associated with crypto-centric practices. But they actually have the potential to provide their services to other fields. Examples would include insurance, the music and film industry, education, art, energy, and the list goes on. Smart contracts use their system for assorted projects ranging from straightforward to intricate.

BlockchainHub has created a chart that ranks the type of smart contracts. They rate certain case examples of each from simple to complex:

  1. Digital value exchange – The act of sending a form of cryptocurrency (ex. Bitcoin) from one family member to another.
  2. Smart right and obligation – A consumer purchasing a digital content stream.
  3. Basic smart contract – A landlord locking out a tenant from their apartment because they are not paying.
  4. Multiparty smart contract – A merchant looking to sell their house will lend the buyer the funds.
  5. Distributed autonomous business unit – A corporation unit issues its own bonds and buyers can monitor the payments via a communal ledger.
  6. Distributed autonomous organization – Self-driving trucks that conduct peer-to-peer deliveries, pay the local toll road fees, and buy local electricity.
  7. Distributed autonomous government – The settlers belonging to a previously uninhabited area can code their own self-enforcing government services.
  8. Distributed autonomous society – Groups of settlers hailing from different areas establishing self-enforcing trade agreements.

Services that offer time-stamping are a great example of how smart contracts are useful. This would be applicable with art registries, governmental registries that distribute documents such as birth certificates, land titles, and school and university degrees.

Auditing a Smart Contract

Auditing a smart contract means checking the code to find any trace of system bugs, vulnerabilities, and risks. This is a procedure that must be done before the analyzed code is deployed. Because once it’s used in the primary Ethereum network, it cannot be modified. It does not necessarily verify a code as being secure or written as airtight as possible. Rather it provides a guarantee that the code has been through a revision process by experts to make it secure.

Security is a key factor in a smart contract. That’s why auditing them (i.e. checking the code) is such a crucial component in their construction.

Medium writer, Merunas Grincalaitis, composed an explanation of the structure of a standard smart contract audit, which goes as follows:

The Structure of a Standard Smart Contract

  1. The disclaimer. In this section, you will state that the audit is not a legally binding document and that it does not vouch for anything. It is nothing more than a document used for discussion.
  2. The overview of the audit and the nice features. A brief view of the smart contract that is set to undergo an audit and the good practices that are found.
  3. The attacks made to the contract. In this section, you will be discussing the attacks done to the contract and the results that followed. This is to verify that the smart contract is secure.
  4. The critical vulnerabilities that can be found in the contract. Any critical issue can potentially lead to heavy damage to the integrity of the contract. It can be anything, like a bug that would allow attackers to steal the currency (in this case, Ether).
  5. The ‘medium’ vulnerabilities found in the contract. These particular liabilities could damage the contract, however, they would have some form of limitation. An example of this would be a bug that could permit other people to modify a random variable.
  6. The low severity vulnerabilities found in the contract. These are issues that do not pose a threat to the stability of the contract and could potentially exist in the finalized, deployed version of the contract.
  7. The line by line comments. This is the section where you will analyze the most important lines in the contract. It will also be where you see areas that have potential improvements.
  8. The summary of the audit. This is where you can voice your opinion about the state of the contract and any other final conclusions about the audit.

Why Audit a Smart Contract?

Auditing the smart contract code is the chief process to ensure that it does what it was originally programmed to do. Due to the unmodifiable aspect of smart contracts, it is important to retool and verify the code. Because once the contract is released, then the still-remaining ‘bugs’ are next to impossible to fix.

A weak link in the blockchain system caused by a faulty smart contract can lead to devastating consequences. Not just for the reliable reputation that blockchain has tirelessly built up over time. But also because it would make the structure susceptible to other hazards.

DAO: The Ramifications

ETHNews writer, Jim Manning, speaks of the consequences that one weak and/or exploitable code can have on blockchain-based technology, including smart contracts:

While the blockchain is strong, a smart contract is only as secure (and strong) as its code.”

This specific type of vulnerability was what led to the DAO fiasco of 2016.

The DAO was a decentralized organization where a good portion of its governance method is autonomous. The organization was run through a series of rules that are encoded as computer programs that are blockchain-based, called ‘Executable Distributed Code Contracts’ (EDCC’s, or also known as smart contracts).

$50 million lost because of smart contract weak spot

A hacker had uncovered a weak spot in a smart contract and was able to exploit it to drain the DAO of over $50 million in pooled funds. Fortunately, a ‘hard fork’ (an extreme change to the blockchain where cryptocurrency is split into two in order to create a separate version) was able to restore a large portion of the lost investments.

There is much more to the story than that, but in order to go into more detail about how and why the DAO ended up being robbed of all those funds, the origin of the DAO should be explained as well.

How The DAO Hack Originated

This whole ordeal began in May of 2016 when a handful of members from the Ethereum community announced the initiation of the DAO, which was also known as Genesis DAO at the time. It was created as a smart contract on the Ethereum blockchain, with its coding framework having been developed open source by the Slock.it team. During the DAO’s creation period, anyone was granted the ability to send Ether to a unique wallet address in exchange for DAO tokens on a scale from 1 to 100. This period turned out to be a success, as it managed to garner up to 12.7 Ether, which equalled out to $150 million at the time. This would be regarded as their largest crowdfund ever.

At some point in time, Ether was trading at $20 and the total Ether amount from the DAO was worth over $250 million.

The main purpose and goal of this platform is to allow anyone with a project idea to pitch it to the community and could potentially receive funding from the DAO if the pitch is successfully compelling. Anyone possessing DAO tokens could vote on plans and would later earn rewards if the project ends up turning in a profit.

The DAO loophole

On June 17 of that same year, a hacker was able to find a loophole within the coding that allowed him to drain all the funds from the DAO. During the first few hours of the attack, he had managed to steal 3.6 million ETH (Ethereum currency), which was the equivalent of $70 million at the time. He then proceeded to withdraw the attack once the damage had been done. To get this exploit and eventual theft to work, the hacker was able to ‘ask’ the smart contract (the DAO) to give the Ether back numerous times before the contract could get the chance to update its balance.

The bug that allowed the attack to happen in the first place did not originate from Ethereum itself. But instead it was the code that had been written for the DAO. It had multiple flaws in its system and the recurrent call exploit was obviously one of them. Not only was the defective code intentionally allowing a large amount of money to be stolen, but it also managed to damage blockchain’s aforementioned reliable reputation.

How the Ethereum community responded to the DAO hack

Samuel Falkon, another writer for Medium, describes this disastrous situation by comparing Ethereum to the Internet and any other application based on Ethereum to a website:

If a site is not working, it doesn’t mean that the Internet is not working, it merely says that one website has a problem. The hacker stopped draining the DAO for unknown reasons, even though he could have continued to do so.”

Immediately after taking control of the situation, the Ethereum community and team began to throw out suggestions for various ideas and proposals as to how they should deal with this catastrophic exploit. The stolen funds had been placed into an account that was subject to a 28 day holding period, meaning that the hacker would not be able to complete his getaway with the money.

In order to refund all that had been stolen, Ethereum opted to implement a hard fork to send the hacked funds to an account available to all the original owners. The owners of the tokens were then given an exchange rate of 1 ETH to 100 DAO tokens, which was the same rate as the initial offering.

The Beginning of the End for DAO

In spite of the abrupt response on behalf of the Ethereum team to remedy the damage that the hack had caused, this attack marked the beginning of the end of the DAO’s run. It permanently ruined the DAO’s promising future and Ethereum users contested the hack, arguing that the hard fork function “violated the basic tenets of blockchain technology.” The final nail in the coffin occurred on September 5 when the cryptocurrency exchange, Poleniex, delisted DAO tokens. Kraken would later do the same thing in December.

Just when everyone assumed that this would be last that DAO would make headlines, something else related to the organization emerged the following year. In July of 2017, the United States Securities and Exchange Commission (SEC) released a report that gave their ruling regarding DAO tokens:

SEC Comments on the DAO Fiasco

Tokens offered and sold by a ‘virtual’ organization known as ‘The DAO’ were securities and therefore subject to the federal securities laws. The Report confirms that issuers of the distributed ledger or blockchain technology-based securities must register offers and sales of such securities unless a valid exemption applies. Those participating in unregistered offerings also may be liable for violations of the securities laws.”

Strictly speaking, the DAO had violated federal security laws, as did all of its investors.

This whole fiasco involving DAO can very well serve as a cautionary tale on the importance of auditing a smart contract. At its core, the blame of the hack can undoubtedly be placed on the fact that there was a conspicuous hole in the code that was obvious enough to lead to a cryptocurrency attack on funds.

Zeppelin’s role

By this point, it should be abundantly clear that a smart contract audit is not only a standard procedure, but it is also a vital one. One small bug in a code could have the probability of leading to a much larger problem that, given the nature of these contracts, cannot easily be fixed once released; if at all.

A good step in making sure that the code in a contract is truly secure is to copy the actions of enterprises, such as Ethercamp, and get the code audited by an outside source. Doing so will guarantee that custom smart contracts are indeed following the best standards in practice and simultaneously reduce any potential attacks.

Zeppelin is playing a pivotal role in making the act of writing secure smart contracts an easier task.

What is Zeppelin?

Zeppelin is a software that builds key infrastructure to both develop and operate smart contract systems. It makes it easier for developers to write complex applications and it additionally conducts in-depth audits of smart contract systems. Its website boasts that networks that are worth over $4.5 million have been built thanks to their protocol.

Through the OpenZeppelin project, they offer its users a foundation consisting of reusable and secure smart contracts that harness a standardized and tested code that is also community-reviewed. By using a code that has been proven to be substantial and stable in smart contracts, it increases security forthwith and makes writing them so much more simple and efficient.

Zeppelin writer, Manuel Araoz, has a recommended security pattern when approaching the codes of smart contracts and verifying them to make sure they are stable. He also provides mathematical equations of code to explain how to go about executing each step of the pattern. Here are the steps:

9 Step Security Check by Manuel Araoz

  1. Fail as early as possible. It is a simple, yet effective practice to make your code fail as promptly as possible. This can also be interpreted as failing as “loudly” as possible. The code should be actively looking for problems and immediately come to a halt when it detects any kind of defect. When a problem is found, it will ‘set off an alarm’, so to speak. If it were to fail in silence, then the flaw will go undetected. “If we hide errors, they can propagate to other parts of the code and cause inconsistencies which are difficult to trace,” Araoz writes.
  2. Favour pull over push payments. External calls can fail for any number of reasons, so in an effort to minimize these errors, isolate each external call into its own transaction that is able to be initiated by the call’s recipient. Using an example by Araoz, “Imagine someone bids from an address which simply throws an error every time someone sends money to it. What happens when someone else tries to outbid that? The send call will always fail, bubbling up and making bid throw an exception. A function call that ends in error leaves the state unchanged (any changes made are rolled back). That means nobody else can bid, and the contract is broken.” The solution to this issue is to separate the payments into different functions.
  3. Order your function code: conditions, actions, interactions. Essentially an extension of the ‘fail early’ principle, structure your functions like so: 1) check all of the pre-conditions; 2) make changes to the state of your contract; 3) interact with other contracts.
  4. Be aware of platform limits. The EVM (Ethereum Virtual Machine) contains a lot of hard limits on what it is the contracts are able to do. The EVM is said to be one of the most important elements in the construction of Ethereum, as it has the responsibility of handling internal state and mathematical calculations on the network. It also handles account information pertaining to balances, addresses, block data, and whatever the current gas prices may be.
  5. Write tests. It is a time-consuming and tedious practice, but it will prevent regression problems.
  6. Fault tolerance and automatic bug bounties. Automatic bug bounties are designed and implemented to find any vulnerabilities in the contract. As it has been previously discussed several times, finding a bug or a liability in the contract as soon as possible before the release will reduce any risk of the contract backfiring in some way.
  7. Limit the amount of funds that are deposited. Limit the scope of funds that the contract accepts to keep them safe from attacks. Most attackers will target the high-profile contracts that manage millions of dollars, so it is not at all a necessity for a contract to have such high stakes.
  8. Write simple and modular code. Functions should ideally be as short as possible, code dependencies should be reduced to the minimum, and the files should be as small as possible, detaching independent logic into modules with each having a single responsibility.
  9. Do not write all of your code from scratch. This is something that is related to an ‘age-old’ proverb that goes “Do not roll your own crypto.” This step is an important practice, as it adds to the goal of securing all smart contracts.

Conclusion

As reliable and innovative as smart contracts are, even they are susceptible to damage if not properly taken care of. To be more specific, it is their codes that need the most protection and verification if the parties involved with the contract want any hope of their exchange or agreement carrying out. If we have learned anything from the DAO 2016 incident, it is that precautions must be taken and there are no exceptions for whatever the system may be. There were other issues that led to it being an infamous operation – one of which being the SEC’s findings from their report on the matter – but it is exceptionally obvious that the core of the problem stemmed from its faulty coding.

The purpose of this article was not to create hesitancy in relation to smart contracts because of their potential vulnerability. The intention was to administer instructions on how to keep any of these potential vulnerabilities from getting out of hand and to explain the consequences of what a lack of attention to this procedure can have on the whole system. The DAO mishap was definitely a casualty on a budding system that had not quite taken off yet, but a lesson can be learned from the mistakes made.

By verifying the contract’s code and spotting bugs before they can create an infestation, you are not only ensuring the stability of your contract, but also maintaining the reliance of blockchain technology as a whole.

Sources:
https://www.investopedia.com/terms/s/smart-contracts.asp
https://blockchainhub.net/smart-contracts/
https://medium.com/ethereum-developers/how-to-audit-a-smart-contract-most-dangerous-attacks-in-solidity-ae402a7e7868
https://www.ethnews.com/the-importance-of-audits-and-secure-coding-for-smart-contracts
https://medium.com/swlh/the-story-of-the-dao-its-history-and-consequences-71e6a8a551ee
https://zeppelin.solutions/
https://blog.zeppelin.solutions/onward-with-ethereum-smart-contract-security-97a827e47702
https://github.com/ethereum/wiki/wiki/Safety#favor-pull-over-push-for-external-calls
https://www.mycryptopedia.com/ethereum-virtual-machine-explained/