Blog

  • Ethainter: A Smart Contract Security Analyzer for Composite Vulnerabilities

    Ethainter: A Smart Contract Security Analyzer for Composite Vulnerabilities

    Lexi Brent∗
    Int’l Computer Science Institute Berkeley, CA, USA
    lexi@icsi.berkeley.edu

    Neville Grech
    University of Athens Athens, Greece
    me@nevillegrech.com

    Sifis Lagouvardos
    University of Athens Athens, Greece
    sifis.lag@di.uoa.gr

    Bernhard Scholz
    University of Sydney Sydney, NSW, Australia
    bernhard.scholz@sydney.edu.au

    Yannis Smaragdakis
    University of Athens Athens, Greece
    yannis@smaragd.org

    Abstract
    Smart contracts on permission less blockchains are exposed to inherent security risks due to interactions with untrusted entities. Static analyzers are essential for identifying security risks and avoiding millions of dollars worth of damage. We introduce Ethainter, a security analyzer checking information flow with data sanitization in smart contracts. Ethainter identifies composite attacks that involve an escalation of tainted information, through multiple transactions, leading to severe violations. The analysis scales to the entire blockchain, consisting of hundreds of thousands of unique smart contracts, deployed over millions of accounts. Ethainter is more precise than previous approaches, as we confirm by automatic exploit generation (e.g., destroying over 800 contracts on the Ropsten network) and by manual inspection, showing a very high precision of 82.5% valid warnings for end-to- nd vulnerabilities. Ethainter’s balance of precision and completeness offers significant advantages over other tools such as Securify, Securify2, and teEther.

    CCS Concepts: · Software and its engineering → Formal software verification; · Theory of computation →Program analysis.
    Keywords: static analysis, information flow, smart contracts

    Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than the author(s) must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Request permissions from permissions@acm.org. PLDI ’20, June 15ś20, 2020, London, UK © 2020 Copyright held by the owner/author(s). Publication rights licensed to ACM. ACM ISBN 978-1-4503-7613-6/20/06. . . $15.

    ACM Reference Format:
    Lexi Brent, Neville Grech, Sifis Lagouvardos, Bernhard Scholz, and Yannis Smaragdakis. 2020. Ethainter: A Smart Contract Security Analyzer for Composite Vulnerabilities. In Proceedings of the 41st ACM SIGPLAN International Conference on Programming Language Design and Implementation (PLDI ’20), June 15ś20, 2020, London, UK. ACM, New York

    Introduction
    Permissionless blockchain platforms such as Bitcoin [30] and Ethereum [6, 42] promise to revolutionize all sectors of multiparty interaction, by enabling decentralized, resilient consensus. The Ethereum platform, in particular, allows the execution of arbitrary programs, which are called smart contracts. Smart contracts are registered immutably on the blockchain and operate autonomously. Software correctness in smart contracts is critical, as (1) the contracts are high-value targets (since they manage monetary assets), (2) are immutable and cannot be patched, and (3) are fully available for inspection (and invocation) by potential attackers. The need for contract correctness has gained prominence via several recent high profile incidents resulting in losses of cryptocurrency amounts valued in the hundreds of millions [9, 41]. Smart contracts are Turing-complete programs, typically expressed in a domain-specific language called Solidity [40]. Solidity contracts are compiled to low-level bytecode and executed by the Ethereum Virtual Machine (EVM) on the blockchain. Smart contracts store data either on the blockchain or in execution-ephemeral memory. Solidity programs implement unconventional data structures using cryptographic hashing, posing a challenge for static bytecode analyzers. Furthermore, EVM bytecode does not explicitly expose control flow, necessitating sophisticated decomplication methodologies [5, 13, 24, 44]. Hence, checking for even basic security vulnerabilities is non-trivial, as security analyzers for smart contracts require complex techniques to overcome these challenges [14, 37].

    With the rising awareness of Ethereum security risks and the development of recommended practices, realistic attacks have become increasingly complex. They often chain successive exploits that each expose more vulnerabilities. A new class of security analyzers is required to identify such composite attacks. The most notorious (albeit relatively simple) example of a composite attack is the Parity wallet hack, where the equivalent of $280M [9] was stolen or frozen via two separate vulnerabilities. The attack involved reinitializing part of the contract that sets owner variables, via a vulnerable library function, prior to attacking the contract.

    To safeguard against sophisticated attacks, it is essential to model the information flow [34] inside smart contracts accurately. Information flow classifies information into trusted and untrusted and considers how it propagates in the code. For example, if untrusted (łtaintedž) information from external sources is allowed to spread to critical program points, it can alter key aspects of program behavior.

    Smart contract programmers employ guarding patterns to prevent an untrusted entity from executing sensitive operations, such as destroying the contract. For example, the contract code could check whether the user of the contract (a.k.a., its caller or sender) has specific privileges. The simplest check is to permit only a particular contract owner account to perform critical actions. For security analyzers, it is essential to model this guarding mechanism, for any highfidelity information flow analysis: if guards are not taken into consideration, many contracts will be incorrectly inferred to be vulnerable, when the only user that can łexploitž these vulnerabilities would be the owner of the contract themselves. Conversely, the guarding code can itself be attacked, by invoking code that manipulates the state of the contract in unexpected ways.

    In this work, we present Ethainter: the first security analyzer for detecting composite information flow violations in Ethereum smart contracts. Ethainter enhances the understanding of tainted information flow with the tainting of guard conditions, other potential ineffectiveness of guards, as well as different kinds of taint that are not prevented by guarding. Ethainter models not just the existence of guards but also whether they are effective in sanitizing information. The specification of the analysis is in a formalism of independent value. It ignores orthogonal, well-understood technical complexities, capturing, instead, the essence of new information flow concepts (e.g., tainted guards, taint through storage) in minimal form. For example, we consider a tainted memory store to induce further information flow more eagerly than an untainted (yet still statically undetermined) memory store. The precision, recall, and scalability of Ethainter are highly fine-tuned using mutually-recursive Datalog rules for tainting and overall information flow. The contribution of our work is as follows:



    Access the full document

  • Gigahorse: Thorough, Declarative Decompilation of Smart Contracts

    Gigahorse: Thorough, Declarative Decompilation of Smart Contracts

    Neville Grech
    University of Athens and University of Malta Greece and Malta
    me@nevillegrech.com

    Lexi Brent
    The University of Sydney Australia
    lexi.brent@sydney.edu.au

    Bernhard Scholz
    The University of Sydney Australia
    bernhard.scholz@sydney.edu.au

    Yannis Smaragdakis
    University of Athens Greece
    yannis@smaragd.org

    Abstract—The rise of smart contracts—autonomous applications running on blockchains— as led to a growing number of threats, necessitating sophisticated program analysis. However, smart contracts, which transact valuable tokens and cryptocurrencies, are compiled to very low-level bytecode. This bytecode is the ultimate semantics and means of enforcement of the contract. We present the Gigahorse toolchain. At its core is a reverse compiler (i.e., a decompiler) that decompiles smart contracts from Ethereum Virtual Machine (EVM) bytecode into a highlevel 3-address code representation. The new intermediate representation of smart contracts makes implicit data- and control flow dependencies of the EVM bytecode explicit. Decompilation obviates the need for a contract’s source and allows the analysis of both new and deployed contracts.


    Gigahorse advances the state of the art on several fronts. It gives the highest analysis precision and completeness among decompilers for Ethereum smart contracts—e.g., Gigahorse can decompile over 99.98% of deployed contracts, compared to 88% for the recently-published Vandal decompiler and under 50% for the state-of-the-practice Porosity decompiler. Importantly, Gigahorse offers a full-featured toolchain for further analyses (and a “batteries included” approach, with multiple clients already implemented), together with the highest performance and scalability. Key to these improvements is Gigahorse’s use of a declarative, logic-based specification, which allows high-level insights to inform low-level decompilation. Index Terms—Ethereum, Blockchain, Decompilation, Program
    Analysis, Security


    INTRODUCTION
    Distributed blockchain platforms have captured the imagination of scientists and the public alike. Blockchain technology offers decentralized consensus mechanisms for any transactions that, in the past, would have required a trusted centralized authority. One of the most evident embodiments of this vision is the development of smart contracts: Turing-complete autonomous agents that run on distributed blockchains, such as Ethereum or Cardano. A smart contract may, for instance, implement a lending policy, a charging scheme for digital goods, an auction, the full set of operations of a bank, and virtually any other logic governing multi-party transactions. Ethereum is the best-known, most popular blockchain platform that supports full-featured smart contracts. (As of this writing, the Ethereum cryptocurrency market capitalization is $13B.) Ethereum offers an excellent demonstration of the potential for smart contracts, as well as their technical challenges. Developers typically write smart contracts in a high-level language called Solidity, which is compiled into immutable low-level Ethereum VM (EVM) bytecode for the blockchain’s distributed virtual machine.


    The open nature of smart contracts, as well as their role in handling high-value currency, raise the need for thorough contract analysis and validation. This task is hindered, however, by the low-level stack-based design of the EVM bytecode that has hardly any abstractions as found as in other languages, such as Java’s virtual machine. For example, there is no notion of functions or calls—a compiler that translates to EVM bytecode needs to invent its own conventions for implementing local calls over the stack. It is telling that recent research [1], [9], [22], [34] has focused on decompiling smart contracts into a higher-level representation, before applying any further (usually securityoriented) analysis. Past decompilation efforts have been, at best, incomplete. The best-known decompiler (largely defining the state-of-the-practice) is Porosity [33], which in our study fails to yield results for 50% of deployed contracts of all smart contracts on the block chain. Upcoming research tools including the Vandal decompiler [35] still fail to decompile a significant portion of real contracts (around 12%) due to the complex task of converting EVM’s stack-based operations to a register-based intermediate representation.


    Such difficulties are much more than technicalities of the platform or idiosyncrasies of existing tools. Any current or future smart contract platform is likely to employ virtual machines that are low-level. The designs of these virtual machines are optimized for massively replicated execution of smart contracts. The bytecode effectively represents an assembly language designed for efficient execution and compact program representation, since the bytecode must be stored on the blockchain. Hence, the bytecode for smart contracts will never be optimal for human readability or reverse compilation. For effective decompilation, significant program comprehension of the bytecode is necessary. A decompiler requires deep program understanding before it can reconstruct the bytecode to a high-level representation. For instance, to recognize which low-level jumps correspond to high-level function calls, a decompiler must deduce possible addresses for jump instructions to be able to reconstruct the control-flow of a smart contract. Such understanding is compounding: once calls are recognized as calls (and not just as a mere intra-procedural
    jump), its decompilation precision can further improve, by pruning impossible targets.

    In this paper, we introduce the Gigahorse toolchain for analysis of Ethereum smart contracts. Gigahorse addresses the above challenges, making the following contributions:

    • It offers a highly-effective decompiler, yielding higher precision and completeness than the state-of-the-art (e.g., decompiling virtually all existing contracts on the Ethereum blockchain).
    • Gigahorse anchors around it a full-featured tool suite, offering libraries for building analyses, as well as readymade clients for existing analyses.
    • The Gigahorse approach provides new decompilation insights (possibly of value for many more platforms): As higher level program features are discovered, they feed back to lower level analyses. E.g., by discovering functions, stack analyses are performed locally (more precisely), and the effects of function calls on the stack are also summarized, enabling both more precise and more scalable analysis.
    • Gigahorse showcases an unconventional decompilation approach, which enables the above benefits: the decompiler is specified declaratively, using logic-based (Datalog) rules.
    • Gigahorse is evaluated and its features illustrated on the full set of smart contracts of the Ethereum blockchain. Gigahorse is powering the ongoing free Contract Library service (https://contract-library.com), which offers decompiled versions of all contracts on the Ethereum blockchain. Contract Library is a valuable service for Ethereum security analysts, and is currently receiving several tens of unique visitors and over a thousand page views per day.

    BACKGROUND
    We next present some background on the EVM bytecode language and declarative static analysis. A. Low-Level Bytecode in the Ethereum Block



    Access the full document

  • Rising Gas Prices Are Threatening Our Security (No, It’s Not the Saudi Attack)

    Rising Gas Prices Are Threatening Our Security (No, It’s Not the Saudi Attack)

    Mr. Out of gas exception

    EIP 1884 is set to be implemented into the upcoming Ethereum ‘Istanbul’ hard fork. It:

    • increases the cost of opcode SLOAD from 200 to 800 gas
    • increases the cost of BALANCE and EXTCODEHASH from 400 to 700 gas
    • adds a new opcode SELFBALANCE with cost 5.

    Due to a fixed gas limit (2300) imposed by the .send(..) and .transfer(..) Solidity functions, fallback functions that use these opcodes may now start to fail due to an out-of-gas exception. This has significant implications for contracts relying heavily on default functions, which might not execute as expected under the new gas constraints.

    Analysis by Contract-library.com team

    Contract-library.com, an automated security resource-intensive service, performs sophisticated static analysis on all deployed smart contracts (over 20 million of them). As static analysis is a technique that takes into account all (or almost all) possible program executions, it is expected to return the most comprehensive list of smart contracts affected by security vulnerabilities.

    On Friday August 16th Martin Holst Swende of the Ethereum foundation asked a question on the ETHSecurity channel on telegram about how to go about finding smart contracts whose fallback function may fail due to EIP-1884. Since contract-library.com already had gas consumption analysis built into its core static analyses, we reached out on the same day with a list of contracts (continuously updated) that may be affected.

    Over the subsequent days, also with the input of Martin Holst Swende, the gas cost analysis computation was updated and improved, over several iterations. The analysis currently reveals over 800 contracts that are highly likely to fail if called with 2300 gas (whereas they would succeed prior to EIP-1884). A subsequent, more general, analysis was also developed. This would be the most comprehensive list of possibly affected smart contracts for this particular issue, but also contains many false positives. This more general “may” analysis reveals that 7000 currently deployed smart contracts may fail under some execution paths with 2300 gas.

    In addition, since our analysis is fully automated, we have also performed experiments to see whether these issues can be simply avoided by repricing the LOG0, LOG1 ... opcodes. Note that these opcodes tend to occur quite often in fallback functions. By halving the Glog and Glogtopic gas costs (refer to the yellow paper), the number of flagged contracts is reduced by approximately half!

    Although repricing opcodes can always break contracts, the EVM should be able to evolve too. These changes are crucial to support the ongoing growth of the Ethereum network, ensuring scalability and future compatibility with diverse applications.

    Clearly, a decent number of contracts will be broken due to this change, so care must be taken to lessen the impact on the overall ecosystem. In this case, we recommend repricing the LOGx opcodes, which seem to be mispriced anyway. This way, there will be fewer contracts affected.

    A more interesting, but perhaps equally serious side-effect of EIP-1884 and EIP-2200 combined is that it lowers the cost of performing an unbounded mass iteration attack, which is currently quite high. This attack is described in MadMax. In summary, this is an attack carried out by an unauthorized user, to increase the size of an array or data structure, which is iterated upon by any other user, rendering the functionality inaccessible by increasing gas cost beyond the block gas limit. The combined effect of EIP-1884 and EIP-2200 make this kind of attack around 7 times cheaper on average, rendering it much more feasible. This attack requires 2 SSTOREs per array element that is added by the attacker. This array is then iterated upon by the victim, requiring an additional SLOAD. For a list of contracts that may be susceptible to unbounded iteration, we have you covered. The list contains approximately 15k contracts.

    Which contracts will be affected? What about the one I’m currently developing?

    If your contract does not have fallbacks which may fail with 2300 gas) or is not susceptible to unbounded iteration, then you’re most probably fine. If it is, you may still be ok, but further investigation is necessary. If you would like to see whether the contract you are developing may be affected, deploy it to one of the Ethereum testnets and check your results at contract-library.com.

    Below are sample contracts with a non-zero Ether balance that are affected by the repricing of SLOAD operations, so that their fallback is no longer runnable under the send/transfer gas allowance of 2300.

    KyberNetwork

    function() public payable {
            require(reserveType[msg.sender] != ReserveType.NONE);
            EtherReceival(msg.sender, msg.value);
        }

    NEXXO crowdsale :

    modifier onlyICO() {
            require(now >= icoStartDate && now < icoEndDate, "CrowdSale is not running");
            _;
        }
        function () public payable onlyICO{
            require(!stopped, "CrowdSale is stopping");
        }

    For NEXXO, it checks three slots, icoStartDateicoEndDate and stopped, totalling 2400 with new gas rules.

    Crowd Machine Compute Token crowdsale:

    modifier onlyIfRunning
      {
        require(running);
        _;
      }
      function () public onlyIfRunning payable {
        require(isApproved(msg.sender));
        LogEthReceived(msg.sender, msg.value);
      }

    Important reminder: The crowdsales above do not inherently break, it just means that callers need to add some more gas than 2300 to partake in the ICO contracts.

    CappedVault

    • Fallback function:
    function () public payable {
            require(total() + msg.value <= limit);
        }

    Unknown Harvester with 5 ETH

    require((msg.value >= stor___function_selector__));
      emit 0xafd096c64445a293507447c2ecb78f03b4f5459ec28b8e9bfe113c35b75d624a(address(msg.sender), msg.value, 0x447);
      exit();

    No source code available. Note that this contract would work if LOGx gas cost is reduced.

    Aragon’s DepositableDelegateProxy

    function isDepositable() public view returns (bool) {
            return DEPOSITABLE_POSITION.getStorageBool();
        }
        event ProxyDeposit(address sender, uint256 value);
        function () external payable {
            // send / transfer
            if (gasleft() < FWD_GAS_LIMIT) {
                require(msg.value > 0 && msg.data.length == 0);
                require(isDepositable());
                emit ProxyDeposit(msg.sender, msg.value);
            } else { // all calls except for send or transfer
                address target = implementation();
                delegatedFwd(target, msg.data);
            }
        }
    }

    Note that this contract would work if LOGx gas cost is reduced. According to the contract-library analysis, the fallback function may fail due to anything between 2308 and 2438 gas. Issue at Aragon

    How does the static analysis on contract-library.com work?

    Static program analysis is a technique that considers all of a program’s behaviors without having to execute the program. Static analysis is generally thought to be expensive, but over the years we have developed techniques to counter this. Firstly, we developed new techniques in the area of “declarative program analysis”, which simplifies analysis implementations. Secondly, we have applied our analyses at scale, which makes them worth the effort. Contract-library’s internal analysis framework decompiles all smart contracts on the main Ethereum network and most popular testnets to an IR representation, amenable to analysis. The decompilation framework is described in a 2019 research paper. Following this analysis, many “client analyses”, are applied. These analyses all benefit from a rich suite of analysis primitives, such as gas cost analysis (similar to worst-case execution analysis), memory contents analysis, etc. These are instantiated and customized in each client analysis. Finally, we encode all our analyses, decompilers, etc. in a declarative language, and automatically synthesize a fast C++ implementation using Soufflé.

    For illustration, the FALLBACK_WILL_FAIL static analysis is encoded in the following simplified datalog spec, deployed on contract-library.com:

    % Restrict the edges that form the possible paths to those in fallback functions
    FallbackFunctionBlockEdge(from, to) :-
       GlobalBlockEdge(from, to), 
       InFunction(from, f), FallbackFunction(f),
       InFunction(to, g), FallbackFunction(g).
    % Analyze the fallback function paths with the
    % conventional gas semantics, taking shortest paths
    GasCostAnalysis = new CostAnalysis(
      Block_Gas, FallbackFunctionBlockEdge, 2300, min
    ).
    % Analyze the fallback function paths with the
    % updated gas semantics, taking shortest paths
    EIP1884GasCostAnalysis = new CostAnalysis(
      EIP1884Block_Gas, FallbackFunctionBlockEdge, 2300, min
    ).
    FallbackWillFailAnyway(n - 2300) :-
       GasCostAnalysis(*, n), n > 2300.
    % fallback will fail with n - m additional gas
    EIP1884FallbackWillFail(n - m) :-
       EIP1884GasCostAnalysis(block, n), n > 2300,
       GasCostAnalysis(block, m),
       !FallbackWillFailAnyway(*).

    The analysis performs a gas cost computation over all possible paths in the fallback functions, using the gas cost semantics of both PRE and POST EIP-1884. In cases where there is a path that can complete in the former semantics but not the latter, we flag the smart contract.

  • Gigahorse: Thorough, Declarative Decompilation of Smart Contracts

    Gigahorse: Thorough, Declarative Decompilation of Smart Contracts

    The rise of smart contract—autonomous applications running on blockchains—has led to a growing number of threats, necessitating sophisticated program analysis. However, smart contracts, which transact valuable tokens and cryptocurrencies, are compiled to very low-level bytecode. This bytecode is the ultimate semantics and means of enforcement of the contract.

    We present the Gigahorse toolchain. At its core is a reverse compiler (i.e., a decompiler) that decompiles smart contracts from Ethereum Virtual Machine (EVM) bytecode into a high- level 3-address code representation.

    Read more

  • Chronicle of an Attack Foretold

    Chronicle of an Attack Foretold

    Co-written with 

    Neville Grech

    In a few hours, an attacker will claim the prize for the first Consensys Diligence Ethereum hacking challenge. Here’s how they’ll do it, why nobody else can perform the same attack (any longer), and why the attacker has to wait…

    The challenge consisted of a smart contract submitted to the mainnet, without sources. The contract is meant to be decoded, attacked, and drained of its minimal funds. The draining account will then get an off-contract bounty.

    At this point in time, an attacker has not just entered the house but also locked the door behind them, so nobody else can enter. (Which is also why we stopped looking into the challenge and are are instead writing this text.) But, interestingly, the attacker has to wait until the Constantinople rollout enables the CREATE2 opcode, for the second step of the attack to take place!

    To understand the challenge, let’s look at a decompiled version of the contract. We are using our favorite decompiler — our own service, contract-library.com, applied on the challenge contract.

    As it turns out, the challenge requires solving two sub-problems: first, gaining ownership of the contract, in order to enable a delegatecallto a contract that the attacker controls, and, second, circumventing checks over the bytecode of the contract getting delegatecall-ed: the contract cannot contain instructions createcallcallcodedelegatecallstaticcallselfdestruct. Let’s look at both sub-problems in detail, and see how they are solved.

    Challenge Problem 1

    In the decompiled code, one can notice that there are two arrays, with guessed names array_0 and owners. The latter is used to check whether the caller has the required privileges to perform the final part of the attack. Although there are no setters for owners, one can still pollute the data stored in it, as all arrays are stored in the same address space. The length of the first array in the deployed contract was set to maxint: a size that allows overflow, so that an attacker can write anywhere in storage.

    Per standard convention for (dynamic) storage arrays, their lengths are stored in storage locations 0 and 1, while their contents are stored at storage locations keccak256(0) and keccak256(1), respectively. One can therefore compute the offset of the contents of owners and of the length of owners (as well as that of array_0) relative to the start of the contents of array_0, as can be seen in the following “attacker’s” code:

    function offsets() private returns (uint, uint, uint) {
      uint array0start = uint(keccak256(abi.encodePacked(uint(0))));
      uint array1start = uint(keccak256(abi.encodePacked(uint(1))));
      uint contentOffset  = array1start - array0start;
      uint lengthOffset = uint(-array0start);
      return (contentOffset, lengthOffset, lengthOffset + 1);
    }

    Since the challenge contract allows overflow of the array_0 contents area, these offsets let us write into owners, and also change the length of owners. In fact, the attacker did not stop there! They also set the length of array_0 to 0, so that no future attacker can employ the same overflow.

    function attack() public {
      address attackerAddress = address(...);
      address victim = address(0x68Cb...);
      (uint contentOffset, uint lengthOffset0, uint lengthOffset1) 
          = offsets();
      bool success;
      bytes memory result;
      // set address I control as one of the owners
      victim.call(abi.encodeWithSelector(
          bytes4(0x4214352d), uint(attackerAddress), contentOffset)
      );
      
      // set length of array 0 to 0 (no more out of bounds)
      victim.call(abi.encodeWithSelector(
          bytes4(0x4214352d), uint(0), lengthOffset0)
      );
      
      // set length of array 1 to 1 (make attacker the only owner)
      victim.call(abi.encodeWithSelector(
          bytes4(0x4214352d), uint(1), lengthOffset1)
      );  
    }

    The contract registered as owner (attackerAddress) can be any that the attacker controls. Now the attacker has both entered and secured the door! But the more serious challenge is still up ahead.

    Challenge Problem 2

    The second part of the challenge is the actual draining of the contract’s funds. This involves creating yet another attacker contract that will simply drain the contract’s balance. If one checks function 0x2918435f of the challenge contract, the code calls delegatecall on an attacker-supplied address parameter, effectively handing it full control of the account. There is a small twist to this plot however. The delegatecall is preceded by checks of all the bytecodes of the called contract, to ensure that they never match values 0xf0, 0xf1, 0xf2, 0xf4, 0xfa, or 0xff. This precludes use of instructions createcallcallcodedelegatecallstaticcall, and selfdestruct.

    Currently (Feb. 27), these are the only instructions that can be used to drain a contract from its funds. In a few hours, however, a new bytecode instruction (create2) will be available and it can also move funds! Hence the attacker now only needs to pass the address to a smart contract implementing something similar to this:

    contract BountyClaimer {    
        function() external {
            uint res;
            assembly {
                let res := create2(balance(address), 0, 1, 0)
            }
        }
    }

    A minor challenge is that byte value 0xff arises commonly in Solidity compilation, so the attacker has to use roundabout ways to compute some values, but this is little more than a nuisance.

    We would like to salute the clever attacker that will be executing this attack within the next few hours.

    Happy hunting!

  • Bad Randomness is Even Dicier Than You Think

    Bad Randomness is Even Dicier Than You Think

    Co-written with Neville Grech

    Bad Randomness

    Trivial Exploits of Bad Randomness In Ethereum, and How To Do On-Chain Randomness (Reasonably) Well

    Ethereum has been used as a platform for a variety of applications of financial interest. Several of these have a need for randomness — e.g., to implement a lottery, a competitive game, or crypto-collectibles. Unfortunately, writing a random number generator on a public blockchain is hard: computation needs to be deterministic, so that it can be replayed in a decentralized way, and all data that can serve as sources of randomness are also available to an attacker. Several exploits of bad randomness have been discussed exhaustively in the past. Next, we discuss near-trivial exploits of bad randomness, as well as ways to obtain true randomness in Ethereum.

    We begin by showing how easy it often is to exploit bad randomness without complex machinery, such as being a miner or reproducing the attacked contract’s internal state. The key idea is to use information leaks inside a transaction to determine whether the outcome of a random trial favors the attacker: an intra-transaction information leak. This is, to our knowledge, a new flavor of attack. Even though it shares most elements of past attacks on randomness, it generalizes to more contracts and is more easily exploitable.

    Before we discuss the interesting aspects of intra-transaction information leaks, a bit of background is useful.

    Ethereum Randomness Practices and Threat Model

    Much has been written on the topic of random number generation in Ethereum smart contracts. The Ethereum Yellow Paper itself suggests “[approximating randomness with] pseudo-random numbers by utilising data which is generally unknowable at the time of transacting. Such data might include the block’s hash, the blocks’s timestamp, and the block’s beneficiary address. In order to make it hard for malicious miners to control those values, one should use the BLOCKHASH operation in order to use hashes of the previous 256 blocks as pseudo-random numbers.

    More recent excellent advice on anti-practices and hands-on demonstrations of good practices have helped raise the bar of random number generation in smart contracts, as have several high-profile contracts (e.g., CryptoKitties — more on that later), serving as prototypes. For instance, it is now well understood that the current block number (or contents, or gas price, or gas limit, or difficulty, or timestamp, or miner address) is not a source of randomness. These quantities can be read by any other transaction within the same mined block. Even worse, they can be manipulated if the attacker is also a miner.

    Ethereum miners predict the future by inventing it. Furthermore, Ethereum, the distributed “world computer”, is much slower than a physical computer. Therefore, a miner can actively choose to invent a future (i.e., mine a block) whose “random” properties will yield a favorable outcome. In one extreme case, a miner can precompute several alternative “next blocks”, pick the one that favors him/her, and then invest in making this block the next one (e.g., by dedicating more compute power to mine more subsequent blocks).

    Therefore, the current understanding of the threat model to pseudo-randomness focuses on the scenario where the attacker is a miner. Thorough, well-considered discussions often recommend avoiding randomness “[that uses] a blockhash, timestamp, or other miner-defined value.” A common guideline is that “BLOCKHASH can only be safely used for a random number if the total amount of value resting on the quality of that randomness is lower than what a miner earns by mining a single block.” (As we discuss at the end, this guideline can be both too conservative and too lax. The expected value of all bets in a single block should be used instead of the “total amount of value”.)

    Even though the usual threat model considers the case of a miner, most of the block-related pseudo-random properties can be exploited a lot more easily. The interesting block-related properties of the EVM are (in Solidity syntax) block.coinbaseblock.difficultyblock.gaslimitblock.numberblock.timestamp, and blockhash. For all these, an attacker can get the same information as the victim contract by just having a transaction in the same block. (The blockhash value is only defined for the previous 256 blocks, the rest of the quantities are only defined for the current block. In both cases, all current-block transactions receive the same values for these quantities.) In this way, an attacker can replay the randomness computation of the attacked contract before deciding whether to take a random bet. Effectively the pattern becomes:

    if (replicatedVictimConditionOutcome() == favorable)
       victim.tryMyLuck();

    Possible? Yes. Easy? Not quite.

    Although the attack just described seems trivial, in practice it requires sophistication. A typical generator of randomness in a contract is often not merely blockhash(block.number-1) or some other such block-relative quantity. Instead, a common pattern mixes a seed value with block-relative quantities — for instance:

    function _getRandomNumber(uint _upper) private returns (uint) {
       _seed = uint(keccak256(_seed, 
                              block.blockhash(block.number — 1),
                              block.coinbase, 
                              block.difficulty));
       return _seed % _upper;
    }

    This does not make the contract less vulnerable, in principle. There is no secret in the blockchain, so even a private _seed variable can be read. But in practice this can make the attack significantly harder. A contract with several users and intense activity will see its private seed modified often enough to be much less predictable. The attacker either needs (again) to be a miner, or needs to somehow coordinate receiving non-stale external information before the attack transaction. A very interesting illustration of both kinds of attacks (both as a miner and as a transaction with external information) shows how they are possible but not before admitting: “So much for a simple solution.

    It’s Easier to Ask For Forgiveness Than to Get Permission

    Yet, there is a very simple, non-miner attack that has guaranteed success, even with fast-changing private seeds. The transactional model of Ethereum computation together with the public nature of all stored information make exploitation of bad random number generators near-trivial.

    The general pattern is simple. All a contract needs to do to be vulnerable is to finalize in a single transaction (typically before the end of a public call) an outcome that possibly favors the attacker. (This outcome may be determined through any technique producing entropy, including hashing of past blocks, reading the current block number, etc.) The attacker simply executes code such as:

    victim.tryMyLuck();
    require(victim.conditionOutcome() == favorable);

    In other words, the attacker can choose to commit a transaction only when the outcome of a “random” trial is favorable, and abort otherwise. The only cost in the latter case is minor: the gas spent to execute the transaction. The attack works even if there is value transfer in the tryMyLuck() trial: if the transaction aborts, its effects are reverted.

    In this transaction-revert-and-retry approach, the attacker turns the code of the victim contract against itself! There is no need to emulate the victim’s randomness calculation, only to check if the result is favorable. This is information that’s typically publicly accessible, or easy for the attacker to leak out of the victim (e.g., via gas computations, as we will discuss later).

    Practical Examples

    There are several examples of (already with past techniques) vulnerable contracts that can be attacked more easily in the way we describe. For a vivid illustration, consider the (defunct?) CryptoPuppies Dapp. CryptoPuppies attempted to build on the CryptoKitties code base and add “rarity assessments for puppies determined by the average between initial CryptoPuppy attributes (Strength + Agility + Intelligence + Speed) / 4”. The code for the contract, however, adds (to the otherwise solid CryptoKitties contract code) a bad random number generator, combining a seed and block properties (including block.blockhash(block.number-1)block.coinbaseblock.difficulty). Furthermore, the result is readily queryable: anyone can read the attributes of a generated puppy. It is trivial for an attacker to try to breed a puppy with the desired attributes and to abort the transaction if the result is not favorable.

    In other cases of vulnerable contracts, an attacker can determine a favorable outcome of a battle between dragons and knights, create pets only when they have desired features, set the damage inflicted by heros or monsters, win a coin toss, and more.

    (All contract examples are collected via analysis queries on the bytecode of the entire contents of the blockchain and inspected in source or via our alpha-version decompiler at contract-library.com.)

    Hiding State Does Little To Help

    The benefit of the attack pattern that cancels the transaction based on outcome is that the outcome of an Ethereum computation is easy to ascertain. In most cases, the vulnerable contract exposes publicly the outcome of a “random” trial. Even when not (i.e., when the outcome of the trial is kept in private storage only) it is easy to have an intra-transaction information leak. Perhaps the most powerful technique for leaking information (regarding what a computation did) is by measuring the gas consumption of different execution paths. Given the widely different gas costs of distinct instructions, this technique is often a reliable way of determining randomness outcomes.

    For illustration, consider a rudimentary vulnerable contract:

    contract Victim {
       mapping (address => uint32) winners;
        … 
       function draw(uint256 betGuess) public payable {
         require (msg.value >= 1 ether);
         uint16 outcome = badRandom(betGuess);
         if (winning(outcome))
           winners[msg.sender] = outcome;
       }
     }

    The contract performs an extra store in the case of a winning outcome. The attacker can trivially exploit this to leak information about the outcome, before the transaction even completes:

    contract Attacker {
       function test() public payable {
         Victim v = Victim(address(<address of victim>));
         v.draw.value(msg.value)(block.number); // or any guess
         require (gasleft() < 253000); // or any number that will
                                       // distinguish an extra store
                                       // relative to the original gas
       }
     }

    So, What Can One Do? The Blockhash Minus-256 Problem

    We saw some of the pitfalls of bad randomness on Ethereum, but what can one do to produce truly random numbers? A standard recommendation is to go off-chain and employ external sources. These are typically either an outside “oracle” service (e.g., Oraclize), or hashed inputs by multiple users with competitive interests. Both solutions have their drawbacks: the former relies on external trust, while the latter is only applicable in specific usage scenarios and may require as much care as designing nearly any cryptographic protocol. Furthermore, the issue with randomness on Ethereum is not the entropy of the bits — after all, there are excellent sources of entropy on the blockchain, yet they are predictable. Therefore, in principle, even external solutions may be vulnerable to transaction-revert-and-retry attacks, if they have not been carefully coded.

    Although off-chain solutions have great merit, an interesting question is what one can do to produce random numbers entirely on-chain. There are certainly limitations to such randomness, but it is also quite possible, under strict qualifications. The best recommendation is to use the blockhash of a “future” block, i.e., a block not-yet-known at the time a bet is placed. For instance, a good protocol (formulating a random trial as a “bet”) is the following:

    • accept a bet, with payment, register the block number of the bet transaction
    • in a later transaction, compute the blockhash of the earlier-registered block number, and use it to determine the success of the bet.

    The key to the approach is that the hash used for randomness is not known at bet placement time, yet cannot change on future trials. The approach still has limitations in the randomness it can yield, because of miners, who can predict the future (at a cost). We analyze these limitations in the next section, where we collect all randomness qualifications in a single place. Before that, however, we need to consider another caveat of the approach. As mentioned earlier, the blockhash function is only defined for the previous 256 blocks. (In the non-immediate future, EIP-210 aims to change this.) Therefore, if the second step of the above protocol is performed too late (>256 blocks later) or too early (in the same transaction as the first step), the result (zero) of blockhash will be known to an attacker.

    Therefore, any protocol using blockhash of “future” blocks needs to integrate extra assumptions. The most practical ones seem to be:

    • the bettor has to not only place the bet but also invoke the contract in a future transaction (within the next 256 blocks) to determine the outcome
    • if the bettor is too late (or too early) the outcome should favor the contract, not a potential attacker.

    Some smart contracts have attempted to circumvent the need for the second step with solutions that may be acceptable in context. A good example is the randomizer in the CryptoKitties GeneScience contract. (This contract seems to have no publicly available source code, unlike the CryptoKitties front-end contract, so we examine its decompiled intermediate-language version.) In function mixGenes, one can see code of the form:

    v22b_a = block.blockhash(varg2);
    if (!v22b_a) {
      v22b_c = ((block.number & -0x100) + (varg2 & 0xff));
      if ((v22b_c >= block.number)) {
        v22b_c = v22b_c — 256;
      }
      v22b_a = block.blockhash(v22b_c);
    }

    That is, if the block number of the bet is older than 256 blocks back (i.e., blockhash returns zero) the current block number’s high bits are merged with the older block’s lower bits, possibly with 256 subtracted, so as to produce a block number within the 256 most recent, whose blockhash is taken.

    Such code can be well exploited with the transaction-revert-and-retry approach. The benefit of hashing an unknown-at-betting-time block is lost, instead sampling a predictable quantity, whose outcome may vary upon a retry. However, retries will yield different values only every 256 blocks — once the high bits of the block number change. In the specific context of the application (where other players can breed the same crypto-kitty) this risk is probably acceptable.

    Putting it All Together

    Based on the above, let us consider an end-to-end recommendation for purely-on-chain randomness. Computing the blockhash of a “future” block is a pattern that can yield truly unknown bits to the current transaction, but is still vulnerable to miners: a miner can place a bet, then mine more than one version of the “future” block. Therefore, for safe use of blockhash, the expected value of the random trial for an attacker should be lower than the reward of mining a block: an attacker should never benefit from throwing away non-winning blocks. Note that this expected value may be much lower than the total stakes riding on the randomness. For instance, a bet awarding 1000 ETH with probability 1/1000 is still only worth 1ETH to an attacker. Such randomness could, therefore, be quite practical for many applications.

    However, in computing the expected value of a random trial it is important to remember that bets are compounding. If a single block contains N bets (e.g., in N independent transactions, which could be by the same attacker), each for 1000ETH, and each with 1/1000 probability, the expected value of the block for the attacker is N ETH. This reasoning can be used to bound the maximum number of bets accepted in the same transaction. Unfortunately, a single contract cannot know what other bets are taken by other contracts’ transactions in a single block, and an attacker could well be targeting multiple contracts to compound bets. Therefore, the estimate will be either approximate, or too conservative, yielding very low expected values per bet. Even worse, a badly-coded contract can incentivize attackers to violate the randomness of an unrelated contract, at least temporarily. The attacker/miner has an incentive in exploiting the badly-coded, vulnerable contract, and an extra opportunity to also take bets against a contract that wouldn’t be profitable on its own. (The attacker may not be able to exploit the weaker contract more, e.g., because it has limits in the bets per block, but can fit in more transactions in the same block.) Still, such an attack is only valid until the badly-coded contract is depleted.

    A back-of-the-envelope calculation of pessimistic values with the current block mining reward (3ETH) and block gas limit (8 million) suggests that an expected value of an individual bet at under 3.75E-7 ETH-per-unit-of-gas is safe for steady-state use, even if temporarily vulnerable (until depletion of other contracts). For instance, a transaction consuming 100,000 gas should result in bets with expected return at most 0.0375 ETH. (If the block was filled with such transactions, it would still be unprofitable for an attacker-miner to throw it away.) This is currently around 50x the gas cost of such a transaction, so the bet value is not unrealistically low for real applications. Again, this does not limit the payoff of the bet but the expected return. The successful bet could result in 1M ETH, but if this only happens with probability 1/27,000,000, the expected bet value is under 0.0375 ETH.

    More generally, such reasoning motivates an interesting practice that we have not seen adopted so far: to make bets consume gas proportionately to their expected value. For instance, a bet with a high expected value, e.g., of 2 ETH, should be perfectly possible but should require gas nearly equal to the block gas limit (i.e., the caller should know to supply the gas and the bet contract should consume it via extra computation), so that virtually no other transactions can be part of the same block.

    [Standard caveat: all analysis assumes an attacker is incentivized only to maximize his/her profit in ETH (or tokens) based on smart contract execution. There may be attack models not considered, although most conventional attacks (e.g., double spending through chain reorg) don’t seem to benefit from throwing away a block. However, notably, the assumption does not apply to an attacker willing to lose ETH to perpetrate an attack (e.g., in order to cause damages to the victim, or to disrupt the ecosystem in order to manipulate ETH exchange rates, or …). Such attack conditions are a topic for a different post, but much of Ethereum is vulnerable to such attacks.]

    To summarize, our recommendation for on-chain random number generation is to follow a pattern such as:

    • Accept a bet, with payment, register the block number of the bet transaction.
    • The bettor has to not only place the bet but also invoke the contract in a future transaction (within the next 256 blocks). The contract will compute the blockhash of the earlier-registered block number, and use it to determine the success of the bet.
    • If the bettor is too late (or too early) the outcome should favor the contract, not a potential attacker.
    • The expected value of the random trial for all bets in a single block should be lower than the reward for mining a block. (You should convince yourself that this calculation works in your favor.)

    This approach has the disadvantages of a delay until a bet outcome is revealed, of requiring a second transaction, and of placing severe limits on the expected value of the bet. It is, however, otherwise the only known quasi-acceptable technique for purely-on-chain randomness.

  • A Guide to Smart Contracts Security and Audits 

    A Guide to Smart Contracts Security and Audits 

    Auditing Smart Contracts Code | Mitigating Security Issues in Blockchain

    Auditing Smart Contracts

    Introduction

    Have you ever wondered how secure your smart contracts are? In the Wild West of blockchain technology, ensuring their safety and reliability is paramount. Let’s take a dive into the world of smart contract code audits and discover why it’s a game-changer for blockchain applications.

    What Are Smart Contract Security Audit?

    Definition and Basic Concepts

    So, what’s a smart contract, anyway? Think of it as a self-executing contract in which the terms between buyer and seller are directly written into lines of code. They reside on a blockchain, ensuring transparency and immutability.

    Importance in Blockchain Technology

    Smart contracts are the lifeblood of decentralized applications (dApps). They automate agreements, reduce the need for intermediaries, and make transactions more efficient. But great power comes great responsibility and security is a must. If they’re not adequately secured, they can be a hacker’s playground.

    The Need for Smart Contracts Audit Services

    Common Vulnerabilities in Smart Contracts

    You might be surprised how many smart contracts have vulnerabilities lurking beneath the surface. From reentrancy attacks to integer overflows, the list of potential pitfalls is long and winding. Learn More.

    Consequences of Unsecured Smart Contracts

    An unsecured smart contract is like leaving your wallet open on a public bus. Hackers can exploit vulnerabilities to steal funds, manipulate data, or even shut down entire platforms. Remember the Curve Finance of 2023? It resulted in a loss of $70 million! Learn more.

    Smart Contract Audit | Process

    Cost and Schedule Proposal

    The audit process starts with estimating the cost and timeline based on the smart contract’s complexity and scope. The assessment is aligned with the project’s deadlines and budget for a smooth process from start to finish.

    Audit Commencement

    After the terms are agreed upon, auditors analyze the contract thoroughly and communicate regularly with the development team for continuous feedback and adjustments to ensure optimal outcomes.

    Preliminary Findings Delivery

    During the audit, a preliminary report categorizes identified vulnerabilities by risk level: Critical, High, Medium, Low, or Advisory. The development team is engaged in a discussion to clarify the issues and understand the required steps for resolution.

    Issue Resolution Process

    After the preliminary findings are delivered, the development team fixes the identified vulnerabilities. Auditors provide guidance to ensure that the issues are correctly addressed according to the security recommendations offered.

    Final Review and Report

    Once the issues are resolved, auditors conduct a final review to verify that all vulnerabilities have been adequately mitigated. They then issue a comprehensive final audit report documenting the process, the findings, and the remediation efforts.

    Smart Contract Audit | Methodology

    A thorough, smart contract audit involves a blend of technical expertise and collaborative review. The process typically involves multiple senior security researchers, alongside cryptography or financial modeling specialists, to address each project’s unique complexity. Their hands-on, multi-phase approach—paired with advanced automated tools—ensures code security and optimization while considering integrations with external protocols like oracles and AMMs. Learn more.

    Team Composition

    A successful smart contract audit is conducted by at least two senior security researchers alongside cryptography or financial modeling specialists, carefully selected to match the complexity and nature of the smart contracts being analyzed.

    Meticulous Code Review

    The audit process involves a thorough, line-by-line review of the entire codebase. Both auditors thoroughly examine every contract within the audit scope, ensuring a deep understanding of the code and forming a mental model of its interactions and assumptions. This hands-on approach is critical to identifying potential vulnerabilities.

    Critical Strategies in Smart Contract Auditing

    Two-Phase Review Auditing:

    1. Phase A: The auditors focus on the contract’s intended functionality and legitimate use cases, gaining a complete understanding of the contract’s expected behavior.
    2. Phase B: The auditors adopt an adversarial mindset, actively attempting to exploit weaknesses by abusing the system’s flexibility to subvert its security assumptions.

    Collaborative Challenges

    The two senior auditors continuously challenge each other’s findings throughout the audit. This back-and-forth ensures no stone is left unturned. By explaining complex code elements, they push each other to uncover potential blind spots or overlooked vulnerabilities.

    Multi-Level Thinking

    Auditors analyze the code at the level of individual functions and consider how different parts of the system interact. This approach helps identify complex attack vectors that could arise from unexpected combinations of contract components.

    Use of Advanced Tools

    Automated tools also play a critical role. Projects are uploaded to automated analysis systems, including static analysis, AI-driven testing, property based testing, and fuzzing tools. Auditors manually review the output from over 70 algorithms, supplemented by custom tests they create to explore possible issues further.

    Gas Efficiency and Integrations

    Beyond security, auditors also identify inefficiencies in gas usage and provide optimization recommendations. Additionally, we thoroughly examine external integrations with protocols like AMMs, lending platforms, and oracles to ensure they function as expected and align with their specifications.

    Choosing a Smart Contract Auditor

    Qualifications to Look For

    Auditors possess varying levels of expertise. Look for professionals with a strong blockchain security and cryptography background and a track record of successful audits.

    Questions to Ask Potential Auditors

    Don’t hesitate to ask direct questions when choosing an auditor. Understanding their process and tools is essential, as is ensuring they stay updated on the latest security trends. Key questions include:

    • What specific projects have they audited before?
    • Are those projects similar in complexity or structure to yours?

    For example, if your project involves a liquidity pool, selecting an auditor with extensive experience in similar environments can provide deeper insights into potential vulnerabilities. Familiarity with the same functions or libraries your contract uses allows the auditor to identify issues faster and offer more targeted recommendations for improvement.

    Check References and Post-Audit Security

    When selecting an auditor, it’s crucial to assess their experience and check for references and testimonials from past clients. Positive feedback from reputable projects can be a strong indicator of their reliability.

    Additionally, it’s wise to research whether their audited projects have maintained security post-audit. Websites like Rekt News Leaderboard provide valuable insights into projects that have been hacked after their audits.

    If a project repeatedly appears on these lists after an audit, it could signal issues with the thoroughness of the auditor’s work or missed vulnerabilities. Always cross-check testimonials with such resources to ensure the auditors can deliver long-term security, not just pass initial checks.

    Best Practices

    Provide Clear Documentation

    Ensure you supply the auditors with concise but comprehensive documentation. This should include both high-level project overviews and detailed code explanations. The goal is to align the auditors’ understanding of the project’s intent with its technical implementation.

    Consistent Naming and Comments

    Use consistent naming conventions and comments throughout your code. Well-documented code can significantly reduce auditors’ time interpreting complex logic and help them focus on identifying vulnerabilities.

    Establish a Communication Channel

    Maintain an open line of communication between your team and the auditors. Whether it’s a walkthrough of your code or real-time questions during the audit, responsiveness is key to keeping the process efficient and focused.

    Ensure Your Project Is Ready

    Before the audit begins, compile your project without errors and thoroughly test it. This allows auditors to concentrate on complex security issues and concerns rather than debugging fundamental functionality issues. Deploying your code on a testnet and testing it against edge cases can save valuable time.

    Recognize the Scope of an Audit

    Do not substitute audits for thorough testing or assume you will find all bugs. Use audits to identify security vulnerabilities, especially in adversarial environments. Functional correctness issues may not be within the auditor’s purview unless clearly communicated.

    The Future of Smart Contract Auditing

    Emerging Technologies

    Artificial intelligence (AI) and machine learning (ML) will transform smart contract auditing by automating vulnerability detection and improving accuracy. These technologies enable advanced static analysis, pattern recognition, and anomaly detection, and allow auditors to identify potential risks more efficiently and precisely.

    Regulatory Considerations

    Regulatory compliance is becoming increasingly crucial in smart contract auditing as governments establish more explicit frameworks for blockchain technology.

    In the European Union, the Markets in Crypto-Assets Regulation (MiCA), introduced by the European Securities and Markets Authority (ESMA), is a significant step toward regulating digital assets. MiCA aims to ensure transparency, consumer protection, and market integrity across the EU.

    As this regulation takes effect, auditors will need to ensure that smart contracts comply with security standards and regulatory requirements like those outlined in MiCA. This includes ensuring that smart contracts meet criteria for transparency, risk management, and governance, making compliance a critical part of the auditing process.

    Conclusion

    A Web3 project Audit is absolutely essential. As blockchain technology continues to reshape industries, ensuring the security and reliability of smart contracts will be more critical than ever. So, are your smart contracts up to the task?

    FAQs

    Q1: How often should you audit smart contracts?

    A: Ideally, before any major release or after significant code changes. Regular audits help maintain security over time.

    Q2: Can automated tools replace human auditors?

    A: Not entirely. While they can catch many issues, a human auditor’s nuanced understanding is irreplaceable.

    Q3: How much does a smart contract audit cost?

    A: Costs vary based on the complexity of the contract and the auditor’s expertise. It’s an investment in security.

    Q4: What is a reentrancy attack?

    A: A reentrancy attack is a common vulnerability where an attacker repeatedly calls a function before the previous execution is completed, potentially draining funds. Learn More.

    Q5: Should you audit all smart contracts?

    A: Even though auditing is not mandatory, you should strongly consider it to prevent security breaches and build user trust.

  • Dedaub FAQ (Frequently Asked Question)

    Dedaub FAQ (Frequently Asked Questions) –  Looking for clear answers about Dedaub’s security services?

    Dedaub is a Web3 security company specializing in smart contract auditing, monitoring, and analysis tools—trusted by the Ethereum Foundation, Chainlink, and EigenLayer.

    This FAQ provides comprehensive information on a wide range of topics, including audit timelines and real-time monitoring. Whether you’re new to smart contract security or comparing top-tier auditors, start here.

    Dedaub FAQ

    How long does a smart contract audit take?

    A smart contract audit can take anywhere from 3 days to over 4 weeks, depending on the scope and complexity of the code. Simpler contracts, such as ERC-20 tokens, are often reviewed within a week. More complex dApps or DeFi protocols can take multiple weeks to assess thoroughly.

    Key variables include:

    • Size and complexity of the codebase
    • Type of protocol (token vs entire ecosystem)
    • Audit scope
    • Auditor team size and availability
    • Developer responsiveness during the process

    What are typical audit durations based on project type?

    Different project types require different levels of scrutiny. Here’s a rough breakdown of audit timelines based on common Web3 use cases:

    • Basic ERC-20 token: 3–5 days
    • Mid-sized dApp with integrations: 1–2 weeks
    • Advanced DeFi protocol or upgradable system: 3–4+ weeks

    These ranges assume a dedicated team of experienced auditors following best-practice methodologies.

    What factors influence how long an audit takes?

    The duration depends on more than just the volume of code. What matters most is how the protocol behaves, how its components interact, and what security guarantees it needs to offer.

    Main factors include:

    • Complexity of control flow and logic
    • Number of contracts and upgradeability
    • Use of external integrations (e.g., oracles, AMMs)
    • Availability of documentation and test coverage
    • How responsive the developers are to questions and patch reviews

    What is Dedaub’s audit methodology?

    Dedaub uses a rigorous process designed to uncover vulnerabilities that both automated tools and casual reviews often miss. Audits are conducted by two senior researchers working in parallel.

    The process includes:

    • Phase A: Understand how the protocol is supposed to work
    • Phase B: Break assumptions by thinking like an attacker
    • Auditor dueling: Reviewers challenge each other’s findings
    • Multilevel threat modeling: Look for bugs that emerge from system interactions
    • Advanced tooling: 70+ static analyzers and custom fuzzing pipelines

    📖 Read more: https://dedaub.com/blog/web3-audit-methodology/

    What should I watch out for when choosing an auditor?

    Fast turnaround and low prices can be tempting, but rushed audits often miss deep, protocol-level vulnerabilities. Choosing the wrong partner can lead to costly security failures.

    Red flags to avoid:

    • Audits promising “delivery in 24 hours”
    • Solo auditors for complex or high-value protocols
    • No retesting or fix-verification process
    • Vague, copy-pasted, or templated reports

    Choose an audit team that explains its reasoning clearly, documents findings in detail, and provides retesting after fixes.

    What is smart contract auditing?

    Smart contract auditing refers to a more advanced, context-aware approach to security audits, especially in blockchain and smart contract environments. Unlike basic scans or static checks, smart auditing combines deep manual analysis with automated tools and attacker-level thinking. Here’s how Dedaub defines and applies it:

    Not just a checklist. Not just a scan.
    Smart auditing goes beyond surface-level pattern matching. At Dedaub, this includes:

    • Two-phase review: First, understanding the system like a developer. Then, attacking it like a hacker.
    • Code dueling: Auditors challenge each other to catch what the other might miss.
    • Tool-enhanced precision: Dozens of static analyses, fuzzing, and AI tools assist—but don’t replace—human insight.
    • System-level reasoning: Thinking about how components interact, not just how they function in isolation.
    • Gas cost and protocol integration checks: Because inefficiency can be as damaging as insecurity.

    In short, it’s a methodical breakdown of logic, assumptions, and attack surfaces, guided by both human expertise and machine-scale audit methodology. 📖 Read more: https://dedaub.com/blog/web3-audit-methodology/

    How to audit a Solidity contract?

    Auditing a Solidity contract involves reviewing its code to identify vulnerabilities, verify correct logic, and prevent potential exploits. The process blends manual inspection with tool-assisted analysis to cover both design flaws and technical bugs. A proper audit focuses not only on individual functions but also on how the entire system behaves, especially under adverse conditions.

    The audit typically unfolds in structured phases:

    • Understand the system. Before touching the code, auditors study the protocol’s design, its documentation, and intended use cases. The goal is to grasp the flow of value, user interactions, and security assumptions that underpin the smart contracts.
    • Map the attack surface. This involves identifying all external entry points—public or external functions, upgradable proxies, privileged roles—and checking how they interact with external systems (like oracles, AMMs, or tokens). Any component that can be manipulated from the outside becomes part of the threat model.
    • Perform a manual code review. Every line of code is carefully inspected. Auditors trace state changes, permissions, and dependencies while looking for common issues, such as reentrancy, unchecked external calls, incorrect math, and faulty access control. Each function is evaluated for its assumptions and edge cases.
    • Switch to an attacker mindset. Once the system is understood, auditors deliberately seek ways to exploit it. This means thinking like a malicious actor: chaining calls, manipulating control flow, using flash loans, or probing for inconsistencies between internal assumptions and external interactions.
    • Use automated tools to scale the analysis. Tools such as Slither, Echidna, and Dedaub’s Security Suite are used to perform static analysis, symbolic execution, and fuzzing. These tools help uncover subtle bugs and complement the manual effort, but they don’t replace it.
    • Test and verify findings. Suspected vulnerabilities are validated through test cases and simulations. This confirms exploitability and helps determine the severity and real-world impact of the issue.
    • Deliver a structured report. Every issue is thoroughly documented with a clear description, detailed reproduction steps, an impact analysis, and remediation guidance. Good reports also highlight positive findings, code quality observations, and gas optimizations.

    Smart auditing is not about running a scanner and hoping for the best. It’s a layered process that depends on human expertise, adversarial reasoning, and advanced tooling—all aimed at catching what automated tools alone can’t. Read more: https://dedaub.com/blog/web3-audit-methodology/

    What is smart contract security?

    Smart contract security ensures that blockchain-based code works safely and as intended—even in adversarial conditions. Contracts, typically written in languages like Solidity, Rust, Move, Go (Golang), and Cairo, must function correctly and securely under all scenarios. Since smart contracts are immutable once deployed and often manage assets, any flaw in logic, access control, or integration can be catastrophic. Security in this context is about anticipating how a contract might be attacked, misused, or fail in edge cases, and taking proactive steps to mitigate those risks before deployment, as well as maintaining vigilance after deployment.

    A comprehensive security posture combines pre-deployment auditing, post-deployment monitoring, and operational hygiene. While code vulnerabilities can drain funds instantly, many of the most considerable Web3 losses stem from compromised private keys or misused admin powers—failures that go beyond the smart contract itself. Social engineering, phishing, and poor key management are often the actual entry points for attackers.

    The discipline covers a broad range of activities and principles:

    • Code correctness. Ensuring the contract behaves as specified across all inputs and states.
    • Access control. Verifying that only authorized entities can perform sensitive operations, both at the contract and protocol governance level.
    • Resistance to known exploits. Defending against vulnerabilities like reentrancy, integer overflows, logic bugs, or oracle manipulation.
    • Integration safety. Auditing interactions with other contracts, protocols, or tokens to ensure assumptions hold under adversarial conditions.
    • Gas efficiency and DoS prevention. Minimizing resource costs while avoiding gas griefing or contract lockouts.
    • Upgrade and governance safety. Ensuring that contract upgrades, admin actions, and timelocks are adequately controlled and transparent.
    • Smart contract monitoring. Continuously tracking on-chain behavior to detect exploit attempts, deviations from expected logic, or protocol abuse. Monitoring is essential for rapid incident response once contracts are live.
    • Anti-social engineering hygiene. Enforcing multisig on privileged accounts, avoiding hardcoded private keys, training teams on phishing awareness, and using hardware wallets or secure enclaves to manage operational security.

    Smart contract security is adversarial by design. It’s not just about correctness—it’s about outpacing the attacker. That means securing the code, the infrastructure, and the humans behind it.

    How risky are smart contracts? 

    Smart contract risk depends on code quality, audit coverage, and operational practices. Most failures come from missing reviews, not the technology itself.

    The most common risks stem from:

    • Poorly written logic that introduces edge-case vulnerabilities.
    • Missing or broken access controls that expose administrative functions.
    • Unsafe integrations with oracles, tokens, or third-party protocols.
    • Human error, including compromised private keys or faulty upgrades.

    These risks compound quickly in DeFi, where contracts often hold millions in user funds. However, they’re not unavoidable.

    To mitigate them:

    • Audit every line of code before deployment. Involve senior reviewers, simulate adversarial scenarios, and validate assumptions to ensure accuracy and reliability.
    • Deploy monitoring that continuously watches smart contracts for signs of attack or protocol deviations.
    • Harden operations with multisig wallets, secure key custody, and anti-phishing training.

    Smart contracts are only as risky as the processes behind them. With the right audits and continuous monitoring, they become resilient, predictable infrastructure—even in adversarial environments.

    What are the vulnerabilities of smart contracts?

    Smart contracts are vulnerable to a wide range of risks, most of which arise from flawed assumptions, incorrect logic, or misuse of low-level EVM behavior. These vulnerabilities aren’t theoretical; they’ve been exploited in real-world hacks, resulting in hundreds of millions of dollars in value being drained. Developers need to recognize the patterns and build with defensive assumptions.

    According to Dedaub’s guide on Solidity Security Vulnerabilities, some of the most common classes include:

    • Access Control Failures
      Missing onlyOwner or similar checks lets attackers call privileged functions. This can allow them to change core parameters or hijack contract logic.
    • Unchecked External Calls
      Calling unknown or untrusted contracts without restrictions opens the door to malicious behavior. Developers should whitelist known, trusted contracts.
    • Reentrancy Attacks
      Malicious contracts can re-enter a vulnerable function before the state is updated. Use the checks-effects-interactions pattern to prevent recursive exploitation.
    • Integer Overflow/Underflow
      Arithmetic operations can wrap around if unchecked, leading to logic errors. Solidity 0.8+ helps, but unchecked blocks must be used carefully.
    • Out-of-Gas Situations
      Expensive loops or bad design can cause transactions to fail or be griefed. Use pull-based patterns and avoid unbounded iterations.
    • Oracle Staleness and Manipulation
      Relying on outdated or unreliable data from oracles can lead to contract breaches. Always validate feed freshness and avoid Automated Market Makers (AMMs) as primary sources of price information.

    Most of these vulnerabilities are preventable. Awareness is the first step, followed by static analysis, fuzz testing, manual review, and real-time monitoring post-deployment. As Dedaub’s article emphasizes, even minor mistakes, such as using tx.origin for authentication, can escalate into massive exploits.

    What is Dedaub?

    Dedaub is a Web3 security firm specializing in smart contract audits and comprehensive blockchain security solutions. They provide advanced auditing services for Ethereum, the EVM-compatible ecosystem, as well as Sui, Aptos, and Zksync, utilizing specialized tools for static analysis, fuzzing, and real-time monitoring. The firm’s experienced team comprises white-hat hackers, PhDs, and industry veterans dedicated to securing blockchain projects from vulnerabilities and potential hacks. Dedaub’s Security Suite provides a comprehensive set of tools designed for decompilation, static code analysis, and continuous monitoring, ensuring secure and reliable smart contract operations.

    Academic publications

    Dedaub’s co-founders and collaborators have made significant contributions to smart contract security research. Notable publications include:

    Dedaub has worked with over 70 Web3 projects, including:

    Supported chains

    Pre-deployment and post-deployment security measures encompass a wide range of L1 and L2 Networks, including 27 networks. From Ethereum and Base to newer ecosystems like Berachain and Zircuit, Dedaub works across the most critical infrastructure in Web3, including:

    Critical vulnerabilities and security coverage

    Dedaub, a prominent blockchain security firm, has played a significant role in identifying and disclosing critical vulnerabilities across various Web3 projects. Their expertise has been instrumental in preventing substantial potential losses and has earned them recognition and bug bounties.

    Trusted by web3 leaders for security and insight

    Dedaub is trusted by security leaders across Web3—from core infrastructure teams to fast-moving DeFi protocols. Here’s what founders, engineers, and researchers say about working with us:

    “I love Dedaub decompiler.” – Fuyao Zhao, CEO, Sentio (https://sentio.xyz)

    “At MetaMask, user security is our #1 priority. I’m thrilled to see the Dedaub Snap successfully rolled out on the MetaMask Snaps platform and available to all of our users to help keep them safe.” – Christian Montoya, Developer Innovation Lead, MetaMask (https://metamask.io)

    “I love the Dedaub decompiler—No other tool even comes close to what Dedaub has created.” – David Benchimol, Blockchain Security Engineer, Ironblocks (https://www.ironblocks.xyz)

    “Dedaub thoroughly reviewed our TypeScript crypto library and was able to share valuable improvement recommendations.” – Moritz Boullenger, Co-Founder, Fluidkey (https://fluidkey.com)

    “The Dedaub Security Suite provides an efficient Decompiler API with an intuitive user interface for quick navigation. Its performance and speed set a high standard in the industry, making it a competitive choice for gaining data-driven security insights. The team behind Dedaub is responsive to user feedback, enhancing the overall experience.” – David Daniel, Director of Threat Intelligence, OZ Networks (https://oznet.xyz)

    “As a returning customer, we knew Dedaub would deliver. Their expertise in DeFi security and smart contract analysis is unmatched. For Liquity V2, they identified vulnerabilities and provided key insights to optimize our protocol. Once again, Dedaub delivered flawlessly.” – Bingen Eguzkitza, Head of Development, Liquity (https://www.liquity.org)

    “Dedaub provided a very generous and thorough pro-bono audit of the on-chain funding mechanism for Protocol Guild, uncovering critical vulnerabilities and offering valuable insights that improved our overall security. Dedaub achieved a deep understanding of the codebase, and we had clear communication throughout the process. We highly recommend their services to others.” – Fredrik Svantes, Security Researcher, Ethereum Foundation (https://ethereum.foundation)

    “Dedaub’s meticulous audit process gave us invaluable insights and strengthened our protocol’s security. Thanks to Yannis and the team for their expertise and collaboration!” – Ulvi Kağan Dağdeviren, Co-Founder, Stablejack (https://stablejack.xyz)

    “The audit conducted by Dedaub on our Eoracle middleware contracts was comprehensive and successful. The team at Dedaub delivered a precise and detailed analysis, further strengthening the security of our smart contracts.” – Yoni Keselbrenner, Smart Contracts Team Lead, Eoracle (https://eoracle.io)

    “Dedaub brought exceptional clarity and depth to our smart contract security audit. Their rigorous review and actionable insights strengthened our core protocol.” – Arun Devabhaktuni, CSO, SatLayer (https://satlayer.io)

    What specific services does Dedaub offer?

    Dedaub primarily provides smart contract auditing and comprehensive blockchain security services. 

    Dedaub Security Stack:

    • EVM Decompiler: Extract and analyze Solidity-like Intermediate Representation (IR) and ABI on demand.
    • Static Analysis: Over 70 algorithms for rigorous, deep checks of smart contract code.
    • Transaction Simulation: Testing transactions against mainnet data prior to sending.
    • Token Safety: Identifying risks such as honeypots, rug pulls, and impersonations.
    • Monitoring & Alerting: Real-time alerting through agents powered by DedaubQL.
    • On-Chain Firewall: Automatically pausing risky actions and enforcing custom security policies.

    Smart Contract Services:

    • Comprehensive Audit: Thorough security assessments combining automated and manual code reviews.
    • Gas Inefficiency Analysis: Optimizing code to improve gas usage efficiency.
    • External Protocol Integrations Audit: Detailed examination of integrations with external protocols.
    • White Glove Monitoring: Customized, continuous monitoring solutions engineered explicitly for protocol-specific vulnerabilities and threats, including:
      • Real-time, human-validated alerts
      • Expert-driven static analysis and incident response
      • Custom-built monitoring queries tailored to unique operational requirements
      • Proactive threat intelligence to anticipate and mitigate risks
    • Focused Expertise: Specialized audit and security solutions for complex blockchain protocols and financial instruments, including perpetual contracts, zero-knowledge proofs (ZK Proof), and distributed middleware consensus.

    How much does a smart contract audit cost?

    Smart contract audit costs vary widely depending on the complexity of the codebase, the protocol’s novelty, and the depth of the review required. There is no fixed price—costs range from a few thousand dollars for basic contracts to hundreds of thousands for large-scale DeFi systems.

    The main cost drivers are:

    • Codebase size and scope. More lines of code, contracts, or integrations require more auditor hours.
    • Complexity and novelty. New primitives, custom mechanisms, or unconventional architectures demand deeper review.
    • Timeline and urgency. Tight deadlines or last-minute requests can raise the cost due to resource prioritization.
    • Reputation and thoroughness. Established auditing firms with senior researchers charge more, but often deliver significantly higher value.

    Ultimately, a good audit is an investment, not just in security, but in launch credibility and long-term resilience. Cutting corners here often comes at a higher cost later.

    What’s the difference between an audit firm and automated code scanners?

    Automated scanners help identify surface-level issues, such as common reentrancy patterns, unchecked return values, or unsafe math. They’re fast, cheap, and good for initial triage. But they’re limited. Scanners don’t understand intent. They can’t reason about protocol logic, economic incentives, or novel attack paths.

    Audit firms, on the other hand, combine human expertise with tooling. Teams like Dedaub, Trail of Bits, and OpenZeppelin review every line of code with context: What’s the protocol supposed to do? Where could assumptions break down? How might an attacker chain interactions across contracts?

    Unlike scanners, firms also simulate attacks, analyze integration risks, and provide detailed, actionable reports. Many use proprietary tools—Dedaub, for example, pairs expert manual auditing with a high-performance decompiler and a battery of static analyses designed for DeFi-scale complexity.

    Which notable clients has Dedaub worked with?

    Dedaub’s clients include L1s, L2s, DeFi protocols, and infrastructure teams. It collaborates with some of the most respected names in Web3, spanning security-critical systems and high-value protocols.

    Whether it is pre-deployment audits, ongoing monitoring, or tool integration, Dedaub is trusted by the teams building and securing Web3.

    What vulnerabilities does Dedaub typically detect?

    Dedaub focuses on deep, logic-level vulnerabilities that automated scanners often miss. The team combines manual expert auditing with advanced static analysis and proprietary value-flow techniques to uncover both well-known and protocol-specific issues. This approach isn’t theoretical—it’s based on uncovering real, high-impact bugs in production codebases. Examples from past audits include:

    • Access control flaws – missing or misused permissions, such as onlyOwner, or entirely unchecked privileged functions.
      Reentrancy vulnerabilities – classic patterns as well as nuanced multi-function reentry risks.
    • Unchecked external calls – use of call, delegatecall, or transfer without verifying success or target validity.
    • Integer overflows/underflows – especially in unchecked math blocks or poorly handled token decimals.
    • Denial of service (DoS) – logic bugs that allow griefing or stall the protocol under specific conditions.
    • Flash loan exploits – systems that assume token balances or prices are stable within a block.
    • Oracle manipulation – protocols that accept stale, zero, or manipulable data without validation.
    • Upgradeability risks – flawed proxy patterns, uninitialized storage slots, or dangerous delegatecall.
    • Economic attack surfaces – flaws in auction pricing, fee calculation, or liquidity incentives.
    • Protocol-specific edge cases – issues that emerge only under real-world, adversarial behavior.

    This approach enables Dedaub to detect complex security issues that require understanding protocol logic, not just code patterns. Real systems, real stakes, real bugs. That is what makes expert-level auditing essential. Source: https://dedaub.com/audits/

    What is Dedaub’s approach to smart contract security?

    Dedaub approaches smart contract security with a rigorous, hands-on methodology that prioritizes deep understanding over checklists. Every audit is performed by at least two senior researchers, each of whom reviews 100% of the code. There’s no shortcut—auditors form a complete mental model of the system before trying to break it.

    The process is structured around four core strategies:

    • Two-phase review. In Phase A, auditors analyze the code as intended, understanding its legitimate use cases and applications. In Phase B, they shift to an adversarial mindset, actively probing for vulnerabilities by subverting assumptions and testing edge behavior.
    • Internal challenge. Auditors do not just work in parallel—they cross-examine each other’s understanding. If one claims to “cover” a section, the other pushes them to explain its corner cases. This back-and-forth reveals blind spots and deepens insight.
    • Thinking in systems. Rather than isolating functions, auditors analyze how different parts of a protocol interact. Many real exploits emerge from subtle cross-module behaviors, not isolated bugs.
    • Powered by advanced tools. The code is run through the Dedaub Security Suite, featuring more than 70 static analyses, as well as AI and fuzzing. 

    Beyond vulnerabilities, Dedaub also highlights gas inefficiencies, integration misalignments, and external dependencies—like AMMs, oracles, or governance modules—that may behave unexpectedly.

    It’s not just about finding bugs. It’s about breaking assumptions, pressure-testing design, and delivering high-signal, human-validated insights. That’s the Dedaub approach.

    Does Dedaub offer continuous security monitoring?

    Yes. Dedaub provides real-time, protocol-specific monitoring to detect vulnerabilities, governance risks, and exploits before they escalate.

    Here’s what sets it apart:

    • Tailored protections. Monitoring rules are custom-written for your protocol’s logic, APIs, and assumptions—not generic templates.
    • Expert-driven static analysis. Dedaub engineers continuously apply advanced static tools to evolve detection rules as your system and the threat landscape change.
    • Real-time incident response. Alerts are human-validated and routed through your preferred channels. The Dedaub team can assist with containment actions immediately.
    • Full-spectrum coverage. Goes beyond financial exploits—covering governance, transaction integrity, and protocol-specific attack vectors.
    • Multi-chain monitoring. Custom agents track high-value asset movements and contract activity across multiple blockchains.
    • Proactive threat intelligence. Dedaub works directly with your team to anticipate potential threats before they occur, providing you with critical lead time to respond.

    Dedaub offers more than monitoring. It’s security engineering applied continuously, tailored to your protocol.

    What makes Dedaub a trusted authority in blockchain security?


    High-impact clients trust Dedaub for consistent methodology, rigorous audits, and practical tooling, grounded in research and real-world impact. It protects billions in assets through audits, monitoring, and real-time threat detection.

    • Industry recognition and top-tier clients
      Dedaub collaborates with prominent organizations, including the Ethereum Foundation, Uniswap Foundation, EigenLayer, Chainlink, Coinbase, Lido, and others.
    • Successful audits and real-world impact
      Identified critical vulnerabilities in production systems across DeFi, staking, oracles, and governance logic.
      260+ total audits, 145 public reports, 74 clients, 27 chains
    • Contributions to blockchain security research
      Developed tools like Gigahorse and MadMax. Published Ethereum Improvement Proposal (EIP) impact studies (e.g., 3074, 7251, 6466) and protocol post-mortems.
      → The Dedaub Decompiler is offered for free to support the ecosystem. It has over 7,000 users, has decompiled more than 9 million contracts, and has identified over 11 million vulnerabilities via static analysis.
    • Live threat detection and monitoring
      Offers protocol-specific monitoring with custom alerting, rule-based protections, and incident response support.
    • Transparent reporting and open communication
      Publishes selected audit reports and technical blogs. Shares findings and lessons across the community.
    • Ecosystem engagement
      • Founding collaborator of SEAL 911 – https://dedaub.com/blog/seal-911/
      • Security partner for Oasis Sapphire -https://x.com/OasisProtocol/status/1787506821583774172
      • Uniswap Foundation security provider – https://uniswapfoundation.mirror.xyz/v6aMiVHOHERaXy6BJqY0YWLM-tW-bf22AM66vYN3QEo
      • Chainlink BUILD partner – https://www.binance.com/en/square/post/2024-07-10-chainlink-announces-partnership-with-dedaub-to-enhance-web3-security-and-smart-contract-auditing-10591805245849
      • zkSync Security Council member – https://dedaub.com/blog/zksync-security-council/
      • Arbitrum DAO Security Advisor – https://dedaub.com/blog/arbitrum-dao-security-advisor/

    Dedaub’s reputation isn’t built on claims—it’s built on what’s shipped, caught, published, and protected.

    Are Dedaub’s findings public?

    Dedaub maintains transparency by publishing selected audit reports, case studies, and detailed post-mortems of major security incidents. However, clients have the right to request that audit findings remain confidential and unpublished.

    Where can I find Dedaub’s educational content and technical insights?

    Dedaub regularly publishes in-depth technical blogs, whitepapers, research papers, and case studies accessible via their website under the ‘Tech Deep Dive’, ‘Research’, and ‘Case Study’ sections.

    What open-source or community initiatives does Dedaub support?

    Dedaub contributes to open-source projects, academic research (e.g., Gigahorse, MadMax), and collaborates with industry initiatives, including:

    • Founding collaborator of the SEAL 911
    • Oasis Protocol Sapphire’s Security Partner
    • Uniswap Foundation Security Provider
    • Chainlink BUILD Program Partnership
    • Member of the zkSync Security Council
    • Arbitrum DAO Security Advisor

    How can I request a smart contract audit from Dedaub?

    Audit requests can be submitted directly through the contact forms available on dedaub.com. After submission, a detailed proposal will be provided, including costs, timelines, and deliverables. https://dedaub.com/form/request-an-audit/ 

    What is a smart contract audit?

    A smart contract audit reviews blockchain code to detect bugs, vulnerabilities, and logic flaws before deployment. It also ensures functional correctness and optimizes performance. At Dedaub, this process is meticulous and follows structured strategies.

    • Two-Phase Review: Initially, auditors understand the code’s intended functionality. Subsequently, they adopt an adversarial perspective to identify potential exploits. 
    • Collaborative Analysis: At least two senior auditors work together, continuously challenging each other’s findings to ensure thorough coverage. 
    • Multi-Level Thinking: Auditors analyze both individual components and their interactions to uncover complex vulnerabilities. 
    • Advanced Tooling: Utilization of the Dedaub Security Suite, which includes over 70 static analysis algorithms, AI-driven testing, and automated fuzzing, facilitates the identification of potential issues. 
    • Comprehensive Reporting: Findings are categorized by severity—Critical, High, Medium, Low, or Advisory—and detailed in reports to guide remediation efforts. 

    This rigorous approach ensures that smart contracts are secure, efficient, and reliable before they are deployed.

    What is the purpose of a smart contract audit?

    The primary purpose of a smart contract audit is to thoroughly evaluate the security and reliability of a smart contract before it is deployed. This rigorous examination aims to identify vulnerabilities, logical errors, and inefficiencies that could compromise its functionality or security. Specifically, audits involve:

    • Identifying Vulnerabilities: Using manual code review and automated tools, auditors detect weaknesses such as front-running, reentrancy attacks, and other known issues.
    • Ensuring Correctness: Audits verify that contracts behave as intended, validating the logic and ensuring adherence to defined rules and conditions, thus preventing unintended outcomes.
    • Improving Code Quality: Auditors suggest improvements to optimize performance, reduce gas costs, and enhance readability and maintainability.
    • Reducing Risk: Early identification and mitigation of vulnerabilities significantly reduce the risk of security breaches and financial losses.
    • Building Trust: Successful audits demonstrate commitment to security, bolstering user and investor confidence in the project’s integrity and reliability

    Who audits smart contracts?

    Smart contracts are audited by specialized security firms, dedicated teams of experts, and occasionally skilled individual auditors. These auditors comprehensively review smart contract code, its logic, and associated security measures to identify potential vulnerabilities. Prominent specialized security firms include Dedaub, ChainSecurity, CertiK, OpenZeppelin, Quantstamp, and Hacken, among others. In-house security teams within blockchain application development companies also regularly conduct smart contract audits. Occasionally, experienced individuals with significant expertise in blockchain and security conduct independent audits. Auditors typically utilize a combination of automated tools and manual analysis to uncover issues that could lead to financial losses, security breaches, or other vulnerabilities. The resulting audit report provides detailed findings and actionable recommendations to enhance the contract’s security and functionality before deployment.

    How does smart contract auditing work?

    Smart contract auditing entails a comprehensive examination of smart contract code to identify potential vulnerabilities and flaws, thereby ensuring the security and reliability of blockchain applications. The process includes:

    • Documentation Review: Auditors review project documentation, codebase, whitepapers, and architecture to grasp the project’s objectives and design.
    • Automated Testing: Utilization of specialized tools to detect common issues like reentrancy and denial-of-service vulnerabilities.
    • Manual Code Review: Security experts meticulously examine code line by line to identify subtle bugs, vulnerabilities, and inefficient coding practices.
    • Dynamic Analysis: Testing the smart contract in a simulated environment to assess behavior under various conditions and potential malicious scenarios.
    • Security Modeling: Evaluation of the contract’s logic and interactions to uncover design flaws and potential vulnerabilities.
    • Reporting: Providing a detailed report outlining findings, vulnerabilities, their severity, and actionable recommendations.
    • Follow-up: Working with clients to implement necessary fixes based on audit findings.

    Key aspects include vulnerability identification, code quality assessments, business logic validation, and adherence to security best practices. This comprehensive approach significantly reduces the risk of security breaches and ensures the integrity of decentralized applications.

    Can ChatGPT audit smart contracts?

    ChatGPT can offer general advice and basic insights, but professional smart contract auditing requires specialized tools and human expertise.

    How many types of smart contract audits exist?

    There are several types of smart contract audits, primarily categorized as automated, manual, and hybrid audits. Audits can also be comprehensive, limited, or continuous, depending on the project needs:

    • Automated Audits: Use software tools to detect known vulnerabilities.
    • Manual Audits: Involve a detailed, line-by-line review by human experts.
    • Hybrid Audits: Combine automated tools and manual reviews for thorough analysis.
    • Comprehensive Audits: Evaluate all aspects and integration of smart contracts.
    • Limited Audits: Focus on specific issues or components.
    • Continuous Audits: Ongoing monitoring to address emerging vulnerabilities.

    Are smart contracts anonymous?


    Smart contracts are generally transparent and public, although user identities behind contract interactions can remain pseudonymous.

    How do I become a contract auditor?

    Becoming a smart contract auditor involves gaining proficiency in blockchain technologies, mastering languages like Solidity, understanding cybersecurity principles, and acquiring experience through practice, certification, and professional engagements.

    How do you do a smart contract audit?

    A smart contract audit is a structured process used to assess the correctness, security, and reliability of blockchain-based code. The goal is to identify vulnerabilities, logic errors, and integration risks before deployment. Below is a breakdown of how professional auditors approach this task using established methodologies.

    1. Two-Phase Code Review

    The audit begins with a comprehensive reading of the smart contract source code. In Phase One, the auditors aim to understand the code’s intended functionality, use cases, and invariants (conditions that must always hold true). In Phase Two, they adopt an adversarial mindset, attempting to break the contract’s assumptions by simulating potential attacks or misuse cases, including exploring edge cases, permission boundaries, and upgrade paths. (https://dedaub.com/blog/web3-audit-methodology/)

    1. Peer Review and Auditor Cross-Examination

    Many audit teams, such as Dedaub,  incorporate an internal challenge mechanism where at least two senior researchers independently review the same codebase and then critique each other’s findings. This process surfaces blind spots and reinforces a deeper understanding. It also reduces the chance of one auditor overlooking critical logic flaws.

    1. Composability and Multilayered Thinking

    Auditors must consider how different components of the protocol interact, not only within the contract but also across contract boundaries. For example, interactions with oracles, Automated Market Makers (AMMs), or third-party dependencies are reviewed to detect compositional risks. Vulnerabilities often emerge not from isolated code but from unintended interactions between modules.

    1. Static Analysis and Fuzz Testing

    While human review remains central, auditors typically augment their process with automated tools. For example, the Dedaub Security Suite runs over 70 specialized analysis algorithms. These cover a range of detections including reentrancy risks, arithmetic overflows, unchecked calls, and unusual storage patterns (https://www.alchemy.com/dapps/dedaub-contract-library/).

    The tools used often include:

    • Static analysis to detect code smells or known anti-patterns (https://www.youtube.com/watch?v=sDgeB–Lh6w
    • Symbolic execution to model potential program states
    • Fuzzing to uncover crashes or unexpected behavior under randomized inputs 

    Importantly, all automated results are manually reviewed by expert auditors. These tools serve to expand the inspection surface, but do not replace human reasoning or adversarial thinking. 

    1. Optimization and Ecosystem Compatibility

    Beyond security, audits also assess performance-related issues such as gas inefficiencies. Contracts are reviewed for adherence to best practices in Solidity (or other applicable languages) and compatibility with widely-used infrastructure (e.g., ERC standards, layer-2 networks, upgradeable proxies).

    1. Reporting and Severity Classification

    Findings are organized by severity (e.g., critical, high, medium, low, informational) with detailed explanations, reproduction steps, and remediation guidance. A good audit report communicates not only what’s wrong but why it matters, and what the potential impact could be if left unresolved.

    Smart contract audits follow a rigorous, layered methodology:

    • Understand code behavior in depth
    • Model attacker scenarios
    • Use peer review to validate assumptions
    • Supplement with static tools and fuzzers
    • Review integrations and ecosystem alignment
    • Produce clear, prioritized findings

    This process is designed to reduce the risk of on-chain exploits and ensure that contracts behave reliably under adversarial conditions.

    What is Dedaub’s Decompiler?

    The Dedaub Decompiler is a free tool designed to reconstruct human-readable Solidity-like code from Ethereum Virtual Machine (EVM) bytecode. It’s particularly useful for analyzing smart contracts that lack publicly available source code or ABI, such as MEV bots and proxy contracts.

    Key Features

    • High Decompilation Success Rate: Successfully decompiles over 99.98% of deployed contracts on the Ethereum blockchain. Dedaub
    • Advanced Static Analysis: Identifies vulnerabilities like reentrancy, unguarded delegate calls, and unsafe self-destructs through comprehensive static analysis. 
    • 3-Address Code Representation: Utilizes a unique approach that makes data and control-flow dependencies explicit, aiding further security analysis. Dedaub
    • Broad EVM Chain Support: Supports multiple EVM-compatible chains, including Ethereum, Binance Smart Chain, and Polygon. 
    • Free Access: Offered at no cost to support the Web3 community, with over 7,000 registered users and more than 9 million contracts decompiled, identifying over 11 million vulnerabilities.

    How It Works

    Users can input a contract address or raw bytecode into the decompiler interface. The tool then reconstructs a Solidity-like representation of the contract, highlighting potential vulnerabilities and providing insights into the contract’s logic and structure.  For more information or to try the decompiler, visit the Dedaub Decompiler page at app.dedaub.com 

    What is DeFi protocol-level security?

    DeFi protocol-level security involves safeguarding the core logic and mechanisms of decentralized finance systems. It ensures that smart contracts and their interactions function as intended, protecting against vulnerabilities that could lead to financial losses or systemic failures.

    Key Components

    • Smart Contract Integrity: Ensuring that contracts are free from vulnerabilities like reentrancy, integer overflows, and logic errors.
    • Economic Exploit Prevention: Protecting against manipulations such as flash loan attacks, price oracle exploits, and governance attacks.
    • Inter-Contract Interaction Security: Securing the interactions between multiple contracts to prevent cascading failures or unintended behaviors.
    • Continuous Monitoring: Implementing real-time surveillance to detect and respond to anomalies or suspicious activities promptly.

    Dedaub specializes in this domain, offering comprehensive audits and monitoring solutions tailored to DeFi protocols. Our expertise ensures that the foundational elements of your DeFi system are robust and secure.