Original title: "Exploring the Vulnerabilities of Decentralized Finance (DeFi) Blockchain Smart Contracts"
Original Source: Abba Garba, WeBlock CTO
< /p>
Blockchain is a new type of distributed system system, which uses P2P peer-to-peer network communication, block storage, distributed algorithm consensus and encryption algorithm to prevent tamper. Essentially, blockchain can be seen as a distributed database jointly maintained by all network nodes. Compared with traditional distributed databases, blockchain is more suitable for applications that have clear requirements for decentralized trust due to its complete data backup, open and transparent network that cannot be tampered with, complete information traceability and weak trust model Scenes. In particular, typical blockchain application scenarios include digital payment, product traceability, copyright protection, supply chain finance, etc. In blockchain systems, smart contracts play an extremely important role in implementing decentralized application deployment and extending the functionality of applications. Compared with traditional applications, the blockchain system has the characteristics of openness, transparency, execution, non-tampering and no dependence on third parties, and can meet various decentralized applications. Scenario requirements, including decentralized finance (Defi) projects that have developed rapidly in recent years.
As of January 15, 2021, Decentralized Finance (DeFi) has become a successful A financial paradigm that utilizes blockchain-based smart contracts to ensure its integrity and security. Decentralized finance is a new field of development for exchanging, lending or borrowing tokens. Typically, these directives are 'yields' or revenue streams regulated by smart contracts (rather than a single centralized legal entity or individual) and/or controlled by a multi-party, decentralized governance mechanism (such as a DAO). Decentralized Finance (DeFi) — emerging on top of existing blockchain platforms. Components of this new field include those related to lending, asset trading, and derivatives markets. As a decentralized application, smart contracts manage a large number of digital assets, which also makes them vulnerable to various attacks.
This article will elaborate on the security of smart contracts from three dimensions: First, due to the Smart contract security due to vulnerabilities. Secondly, various recent attacks on DeFi and smart contracts will also be discussed. Finally, we will discuss how existing available tools and other effective practices can minimize such attacks.
1.0 Overview of Ethereum Architecture
Before discussing the vulnerabilities of smart contracts, let’s give a brief overview of the Ethereum smart contract architecture.
Blockchain networks can deploy and automate programmed script tasks. These programs, called smart contracts, define custom functions and rules that are invoked during transactions. Blockchain technology based on smart contracts has been applied in various industries such as finance, supply chain management, healthcare energy and government services. Only specific blockchain platforms support smart contracts: Ethereum was the first to support smart contracts. Other blockchain platforms such as EOS, Lisk, Bitcoin, and Hyperledger Fabric are compatible for deploying and executing smart contracts. A scripting type language called Solidity is used to develop smart contracts in the Ethereum platform. In this part, we introduce the security vulnerabilities related to the implementation of smart contracts on the Ethereum platform. Smart contracts can hold and manage the corresponding function Credit (address) {a large amount of virtual currency that may be worth thousands of dollars. As a result, adversaries are constantly trying to manipulate the execution of smart contracts to support their activities. Essentially, smart contracts run on a distributed and permissionless network that inherits many vulnerabilities. In traditional systems, this small set of centralized applications could be redeveloped or patched.
On the contrary, in a decentralized blockchain network, unless extreme measures are taken, it is impossible to modify or Upgrade deployed smart contracts. An immutable feature of smart contracts is their security strengths and weaknesses. Because of this immutability, hackers cannot make changes or modify the contract for their own benefit. However, developers also cannot modify the smart contract application after deployment. They can cancel or terminate the contract and create a new smart contract, then deploy it again. Therefore, for security reasons, smart contracts should be extensively tested before deploying them. We highlight the basic building blocks of Ethereum's smart contract architecture, as shown in Figure 1, which includes Ethereum's architecture.

Figure 1: The environment used to run the Ethereum blockchain is through a web user interface that interacts with the four layers of the Ethereum architecture service, the application layer, and the database for storing blockchain data , for cryptographic mechanisms supporting consensus protocols and for Internet services at the network layer [20].
a. Application layer: The Ethereum client executes the smart contract in the EVM, where the smart contract is associated with the Ethereum account. Ethereum supports two types of accounts: externally owned accounts (EOA) and contract accounts. EOA is used to deposit user funds in Wei, the smallest sub-denomination of Ether, worth 10-18 Ether. EOAs are associated with and resolved by public keys; access to EOAs is verified by revealing ownership of the corresponding private key. Instead, a contract account is associated with a piece of executable bytecode (i.e. a smart contract) that defines some interesting business logic. Smart contracts are the cornerstone of DApps. DApp usually has a user interface as its front end and some smart contracts as its back end. Some DApps issue their own cryptocurrencies called tokens for use in Initial Coin Offerings (ICOs) and exchanges. An Ethereum-based token is a special kind of smart contract (e.g. ERC-20) [20]. Smart contracts are executed in EVMs, which are quasi-Turing-complete machines using a stack-based architecture. The term "quasi" means execution is limited by the gas provided by the transaction. In the Ethereum application layer, various vulnerabilities occur, leading to many attacks, as shown in the diagram in the application layer.
b. Data layer: contains blockchain data structure. A transaction is an interaction between an EOA (called the sender) and another EOA or contract account (called the recipient). Transactions are specified by:
(i) nonce, which is a counter used to track the total number of transactions the sender has initiated;
(ii) Recipient, which specifies the target EOA or contract account for the transaction;
(iii) Value, which is the amount transferred from the sender to the payee (unit: Wei) (if applicable);
(iv) input, which is the bytecode or data corresponding to the purpose of the transaction;
(v) gasPrice and gasLimit, respectively specifying the sender is willing to pay The unit price and maximum amount of gas paid by the winning miner of the block containing the transaction;
(vi)(v,r,s), which is The sender's Elliptic Curve Digital Signature Algorithm (ECDSA) signature. Executing a transaction updates the state of the accounts involved, thus updating the blockchain.
c. Consensus layer: to ensure that the state of the blockchain is consistent. At the time of writing, Ethereum takes about 12-14 seconds to create a block, which means that multiple miners can create valid blocks at the same time, and there may be many blocks. Ethereum uses a variant of the GHOST consensus protocol to select the "heaviest" branch as the main chain, where the "heaviest" branch is the subtree rooted at the fork in question and has the highest cumulative block difficulty while noting staleness Blocks are not on the main chain. Note, however, that Ethereum is replacing its current use of Proof of Work (PoW) with Proof of Stake (PoS).
d. Network layer: Manage the Ethereum peer-to-peer (P2P) network of nodes or clients, so that nodes can always access from certain Active nodes get the updated state of the blockchain. The Ethereum network is a structured P2P network where each node (i.e. client) stores a copy of the entire blockchain. For node discovery and routing, each node maintains a dynamic routing table with 160 buckets, each bucket contains ID, IP address, UDP/TCP port entries of up to 16 other nodes. Ethereum uses the RLPx protocol to discover target clients and the Ethereum Wire protocol to facilitate the exchange of Ethereum blockchain information (e.g. transactions, blocks) between clients.
e. Ethereum blockchain environment: running in the environment of the following four layers: users and Ethereum blockchain An interactive web interface; a database of Ethereum clients to store blockchain data; encryption mechanisms for security purposes; and an internet infrastructure to support blockchain communication between Ethereum nodes. We distinguish the Ethereum blockchain architecture from the environment because attacks against the Ethereum blockchain may originate from the environment, and these attacks may be better addressed in the environment rather than by Ethereum.
1.1 Ethereum Smart Contract Vulnerabilities
It focuses on the smart contract vulnerabilities of each layer of the Ethereum system, as shown in Figure 2.

Figure 2: Classification of Vulnerabilities in Each Layer of Ethereum
1.1.1 Ethereum application layer:
Reentrancy: This vulnerability was originally discovered from the DAO attack[1 ], this vulnerability occurs when the external callee contract calls back a function in the caller contract before the consumer contract completes (i.e., a circular call in a sense). This allows an attacker to bypass proper validity checks until the caller contract is drained of ether or the transaction is spent.
Delegation Call Injection: This vulnerability was first discovered from an attack on the Parity wallet [2]. To facilitate code reuse, the EVM provides an opcode delegate call to insert the bytecode of the callee contract into the bytecode of the caller contract. As a result, a malicious callee contract can directly modify (or manipulate) the state variables of the caller contract. This vulnerability is caused by the fact that the callee contract can update the state variables of the caller contract. Declaring a stateless contract that is intended to be invoked as a library via a delegate is completely immune to this vulnerability.
Freezing Ether: This vulnerability was first discovered from an attack on the Parity wallet [3]. The bug resulted in users being unable to deposit money into their contract accounts, and unable to spend funds from those accounts, effectively freezing their funds.
Upgrade contract: The idea of contract upgrade is introduced to alleviate the problem that smart contracts cannot be modified once deployed, even if they are discovered later There are loopholes. To allow contract upgrades, there are two approaches: (i) split the contract into a proxy contract and a logic contract so that developers can upgrade the latter but not the former; (ii) use a registry contract to hold the updated contract. These approaches, while effective, introduce a new vulnerability: when the contract developer becomes malicious, the updated contract may be malicious. This vulnerability (i.e., insecure contact updates) remains an open issue.
DoS with Unexpected Revert: This occurs because the caller contract encountered an external call failure which resulted in The transaction is reverted, or the callee contract deliberately performs a revert operation to interrupt the execution of the caller contract. This vulnerability is caused by a caller contract performing callee contract restore. This vulnerability is prevented by having the receiver call a transaction to "withdraw" funds that the sender has reserved for the receiver, effectively preventing the sender's transaction from being reverted.
Integer overflow and underflow: This vulnerability was first discovered from an attack on BEC tokens [4]. This occurs when the result of an operation falls outside the range of a Solidity data type, such as resulting in unauthorized manipulation of an attacker's balance or other state variables. The vulnerability is caused by the Solidity source code not performing proper validation on numeric inputs, and neither the Solidity compiler nor the EVM provide integer overflow/underflow detection. This vulnerability can be prevented by using the SafeMath library to handle these issues.
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
Manipulating balances: when a contract's control flow decisions depend on it value, this vulnerability occurs. Balance, or balance, which an attacker can exploit to make themselves the only ones who can get their money. This vulnerability can be prevented by not using the contract balance in any condition statement [5]. Authentication via tx.origin: tx.origin is a global variable in Solidity that refers to the origin EOA that originated the transaction in question. This vulnerability occurs when the contract uses tx.origin for authorization, which can be compromised by phishing attacks. This vulnerability can be prevented by authenticating with msg.sender instead of tx.origin because msg.sender returns the account that caused the message.
Incorrect Visibility: Incorrectly specifying the visibility of a feature, allowing unauthorized access.
Unprotected Suicide: The owner of the contract (or a delegated third party) can use the suicide or self-destruct method to destroy the contract . When a contract is canceled, its associated bytecode and storage are deleted. The vulnerability is caused by insufficient authentication enforced by the contract. This vulnerability can be mitigated by enforcing, for example, multi-factor authentication, meaning suicide operations must be approved by multiple parties.
Leak Ether to Arbitrary Address: This vulnerability cannot occur when any caller can withdraw the funds of the contract , the caller is neither the owner of the contract nor an investor who deposited funds into the contract. This vulnerability is caused by an inability to check the identity of the caller when calling a function that sends ether to an arbitrary address. This vulnerability can be prevented by properly authenticating functions that send funds.
Confidentiality Loss: In blockchain, due to the public nature of blockchain (i.e. transaction details are well known), Restricting the visibility of a variable or function does not ensure that the variable or function is confidential. One possible solution to prevent this vulnerability is to use cryptographic techniques such as timed promises [6].
Insufficient Signature Information: This vulnerability occurs when a digital signature is valid for more than one transaction, when a sender ( This vulnerability can occur when, for example, Alice) sends money to multiple recipients (instead of initiating multiple transactions) through a proxy contract. This vulnerability was originally exploited in a replay attack against smart contracts. This vulnerability can be prevented by incorporating appropriate information (such as nonce and timestamp) in each message.
DoS with unrestricted operations: This vulnerability was first observed from the Govern Mental contract [7].
Unchecked call return value: This vulnerability is also known as mishandled exception. It has two variants called gas-less sending and unchecked sending. This occurs when the return value of a low-level call is not checked, and execution may continue even if the function call throws an error [8].
Uninitialized storage pointer: Recall that in Solidity, contract state variables are always placed consecutively in storage starting at slot 0 middle. For compound local variables (for example, struct, array, or mapping), assign a reference to an unoccupied slot in object storage to point to the state variable.
Incorrect constructor name: This vulnerability was originally observed from the Rubixi contract [9], the constructor name Incorrect, it enables anyone to be the owner of the contract. Prior to Solidity version 0.4.22, a function declared with the same name as a contract was considered a contract constructor, which was only executed when the contract was created.
Type conversion: This vulnerability was first discovered in [10]. , a contract written in the Solidity language can call another contract by directly referencing an instance of the callee contract.
Obsolete Compiler Version: Occurs when a contract uses an outdated compiler, which contains bugs and thus renders the compiled Contracts are vulnerable. This vulnerability can be prevented by using an up-to-date compiler.
Short Address: This vulnerability was first implemented in [11] and is widely discussed.
Ether Lost to Orphaned Address: Ether Lost to Orphaned occurs when sending money, Ethereum only checks the length of the recipient address No more than 160 bits without checking the validity of the recipient address. If money is sent to an orphaned address that does not exist, Ethereum will automatically register the address instead of terminating the transaction. Since the address is not associated with any EOA or contract account, no one can withdraw the transferred funds, which are effectively lost. This vulnerability is caused by the EVM not being able to protect in isolation. As of this writing, this vulnerability can only be prevented by manually ensuring the correctness of the recipient address.
Call stack depth limit: This vulnerability is caused by the insufficient execution model of the EVM and has been hard-scored by EIP-150 Fork that redefines the gas consumption rules for external calls to make it impossible to reach a 1,024 in call stack depth.
Opcode underestimation: This vulnerability was first discovered from two DoS attacks [12] [13].
Transaction order dependencies (aka front-running): This refers to concurrency issues, i.e. upcoming states of the blockchain Depends on the order in which transactions are executed, but is determined by the miners.
Time dependencies: when a contract uses block.timestamp as part of a trigger condition or This vulnerability occurs when used as a source of randomness that can be manipulated by malicious miners. The vulnerability is caused by Ethereum, which only requires timestamps to be greater than those of its parent block and within 900 seconds of the current clock.
Generating randomness: For example, many gambling and lottery contracts select winners at random, usually based on some initial private A seed (such as block.number, block.timestamp, block.difficulty, or blockhash) generates pseudo-random numbers. However, these seeds are fully controlled by the miner, which means that malicious miners can manipulate these variables to make themselves winners. This vulnerability is caused by a manipulated source of entropy.
1.1.2 Data Layer Vulnerabilities
Indistinguishable Chains: This vulnerability was first observed from cross-chain replay attacks when Ethereum split into two chains, ETH and ETC [13]. Recall that Ethereum uses ECDSA to sign transactions. Before the EIP-155 [7] hard fork, each transaction contained six fields (i.e., nonce, recipient, value, input, gasPrice, and gasLimit). However, digital signatures are not chain-specific because the chain-specific information is not even known at that point. As a result, transactions created for one chain can be reused by another chain. This vulnerability has been eliminated by incorporating chainID into the field.
"Empty Account" in the State Trie: This vulnerability was first reported from the DoS attack in references [12] [13] found in .
1.1.3 Vulnerabilities in the consensus layer p>
Publicities that can be outsourced: Recall that Ethereum adopted a PoW puzzle called Ethash, which was designed to be ASIC-resistant and able to limit the use of parallel computing (due to the fact that , most of the miner's work will be reading the dataset. via limited memory bandwidth). However, crafty miners can still divide the task of searching for solutions to puzzles into multiple smaller tasks and outsource them. The vulnerability is caused by Ethash, which only makes the puzzle solution partially sequential in the original image search, instead of relying on sequential PoW.
Probabilistic Finality: This vulnerability is caused by the Ethereum blockchain's design that favors availability over consistency, which is chosen according to the CAP theorem [14].
DoS with block padding: This vulnerability was first observed from Fomo3D contracts [15]. The vulnerability only caused the attacker's transactions to be included in newly mined blocks, while other transactions were abandoned by miners for a period of time. This can happen when an attacker offers a higher gasPrice to incentivize miners to choose the attacker's transaction. This vulnerability is caused by a greedy mining incentive mechanism. At the time of writing, there is no solution to prevent this vulnerability.
Honest mining assumption: This vulnerability is caused by the consensus protocol because it is not compatible with incentives, see [16] . As of this writing, this vulnerability is still an open issue.
Uncle block reward: it refers to the uncle block reward mechanism, which is used to deal with the increase of obsolete blocks due to the rapid generation of blocks . However, this mechanism has the side effect of allowing selfish miners to unclean stale blocks and earn rewards, effectively incentivizing selfish mining and double spending.
Validator's Dilemma: This vulnerability was first reported in reference [17] and refers No matter whether the miner chooses to verify the transaction or not, it will be attacked when the effort is calculated. If miners validate computationally intensive transactions, they spend a lot of time and give attackers an advantage in the race for the next block; if miners accept transactions without validation, the blockchain may contain incorrect transactions. This vulnerability is caused by the high cost of validating resource demand transactions in Ethereum. This vulnerability can be mitigated by limiting the amount of computation required to verify all transactions in a block [17]. However, it is unclear how to eliminate this vulnerability.
4.1 Unlimited nodes Creation of : This exploit is for versions of the Geth client prior to 1.8. In the Ethereum network, each node is identified by a unique ID, which is a 64-byte ECDSA public key. An attacker can create an unlimited number of nodes (i.e., with the same IP address) on a single computer, and then use these nodes to monopolize incoming and outgoing connections to certain victim nodes, effectively tying the victim to others in the network. Other peer nodes are isolated. This vulnerability is caused by a weak restriction on the node generation process. This vulnerability can be eliminated by using a combination of IP address and public key as the node ID. This countermeasure has not been implemented by the Geth developers, which they believe has a negative impact on the usability of the client.
4.2 Unrestricted Incoming Connections: This vulnerability is in the Geth client prior to version 1.8 [18]. Each node can have a total of maxpeers connections at any point in time (the default is 25), and can initiate up to 1(1+maxpeers)/2⌋ outbound TCP connections with other nodes. However, there is no upper limit to the number of incoming TCP connections initiated by other nodes. By establishing many incoming connections for maxpeers to a victim node with no outbound connections, the attacker has the opportunity to eclipse the victim. In Geth v1.8, this vulnerability was eliminated by enforcing a cap on the number of incoming TCP connections to a node, with a default value of ⌊maxpeers/3⌋ = 8.
4.3 Public peer selection: This vulnerability was detected in versions of the Geth client prior to 1.8 [18] .
4.4 Peer Selection: This vulnerability refers to the Geth client When selecting a node to establish an outbound connection in, always get a randomly selected bucket head. Since the nodes in each bucket are sorted by activity, an attacker could keep their nodes always ahead of others by periodically sending messages to the Geth client. This vulnerability has been eliminated in Geth v1.9 by randomly selecting a uniform node across the set of all nodes in the routing table, rather than just randomly selecting nodes from the header of each bucket.
4.5 Independent Block Synchronization: It allows attackers to partition the Ethereum P2P network without monopolizing connections from victim clients . Recall that each block header contains a difficulty field, which records the mining difficulty of that block. The total difficulty of the blockchain is represented by totalDifficulty, which is the sum of the difficulties up to the current block.
4.6 RPC API Exposure: This vulnerability was originally discovered through an attack on the Geth and Parity clients [19].
Quote:
[1] https://www.coindesk.com/ understanding-dao-hack-journalists
[2]https://www.freecodecamp.org/news/a-hacker-stole-31m-of-ether-how-it- happened-and-what-it-means-for-ethereum-9e5dc29e33ce/
[3] https://medium.com/blockcat/on-the-parity-multi-sig-wallet-attack-83fb5e7f4b8c
[4 ] https://nvd.nist.gov/vuln/detail/CVE-2018-10299
[5]https://medium.com/loom-network/how-to-secure-your-smart-contracts-6-solidity-vulnerabilities-and-how-to-avoid- them-part-2-730db0aa4834
[6] https://eprint.iacr .org/2016/1007.pdf
[7]https ://www.reddit.com/r/ethereum/comments/4ghzhv/governmentals_1100_eth_jackpot_payout_is_stuck/
[8]https://github.com/KadenZipfel/smart-contract-attack-vectors/blob/master/vulnerabilities/unchecked-call -return-value.md
[9]https://medium.com/hackernoon/hackpedia-16-solidity-hacks-vulnerabilities-their-fixes-and-real-world-examples-f3210eba5148
[10]https://medium.com /golem-project/how-to-find-10m-by-just-reading-blockchain-6ae9d39fcd95
[11]https://medium.com/loom-network/ how-to-secure-your-smart-contracts-6-solidity-vulnerabilities-and-how-to-avoid-them-part-2-730db0aa4834
[12] https://blog.ethereum.org/2016/09/22/transaction-spam- attack-next-steps/
[13] https://blog.comae.io/the-280m-ethereums-bug-f28e5de43513?gi=3b0603be9186
[14] https://dl.acm.org/doi/10.1145/3149.214121
[15]https://medium.com/coinmonks/how-the-winner-got-fomo3d-prize-a-detailed- explanation-b30a69b7813f
[16] https://dl.acm.org/doi /10.1145/3212998
[17] https://dl.acm.org/ doi/10.1145/2810103.2813659
[18]https://ljk.imag.fr/membres/Jean-Guillaume.Dumas/Enseignements/ProjetsCrypto/Ethereum/236.pdf
[19] https://mp.weixin.qq.com/s/ia9nBhmqVEXiiQdFrjzmyg
[20] https://dl.acm.org/doi/fullHtml/10.1145/3391195
Welcome to join the official BlockBeats community:
Telegram Subscription Group: https://t.me/theblockbeats
Telegram Discussion Group: https://t.me/BlockBeats_App
Official Twitter Account: https://twitter.com/BlockBeatsAsia