<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by AfterDark Labs on Medium]]></title>
        <description><![CDATA[Stories by AfterDark Labs on Medium]]></description>
        <link>https://medium.com/@afterdark_labs?source=rss-dbb7326ef37------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tvITwed1klzE4bcVxHHO-g.png</url>
            <title>Stories by AfterDark Labs on Medium</title>
            <link>https://medium.com/@afterdark_labs?source=rss-dbb7326ef37------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 22:14:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@afterdark_labs/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How the OP Stack Works: What Happens When You Mint a Base Day One NFT?]]></title>
            <link>https://medium.com/@afterdark_labs/how-the-op-stack-works-what-happens-when-you-mint-a-base-day-one-nft-c5abbca37a25?source=rss-dbb7326ef37------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5abbca37a25</guid>
            <category><![CDATA[coinbase]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[optimism]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[AfterDark Labs]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 22:01:12 GMT</pubDate>
            <atom:updated>2023-08-28T19:11:47.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*56UbZTFmRQZQSD2h" /></figure><p>Base launched earlier this month, kicking off <a href="https://onchainsummer.xyz/">onchain summer</a>. Part of the festivities involve minting new NFTs everyday. For participants, all you have to do is connect your wallet, click mint, sign the transaction, and an NFT arrives in your wallet. At least that’s what happens at a high-level. If you’re interested in gaining a deeper understanding of what the process looks like from start to finish, this article is for you.</p><h3>Gathering Gas Fees</h3><p>Ok, so we connected our Coinbase Wallet and clicked the big mint button. Now what? The first request the web page makes is to a Base RPC URL to get the chain’s current gas prices. The response from the HTTP request can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/0*ik3Vnhu6WocfIlVS" /><figcaption>Gas Fees for Base Layer 2</figcaption></figure><p>This is unsurprising, as we will need to know these gas prices so that we can form a proper transaction. Since the OP stack is EVM equivalent, its transactions take the same form as Ethereum transactions. A simplified example of a transaction object can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_HLchixNVmIn_a4TEHkRqQ.png" /><figcaption>Sample transaction object</figcaption></figure><p>Great, so we have our <em>maxPriorityFeePerGas</em> and the <em>maxFeePerGas</em>. Reviewing the above transaction object, we can spot a number of items in there that we already should have information for as well. We’ve already specified within our wallet the <em>chainId</em>, <em>gasLimit</em>, and our <em>source</em> address. It’s also reasonable to believe the front-end is aware of the <em>destination</em> address and any required <em>amount</em>. However, since seeing is believing, here is a snippet of the script on the web page that runs during minting. <em>e</em> in this case is the ERC721 drop contract that the front-end is already aware of:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*J03LIp7H0--YhGiq" /><figcaption>Script containing contract address and function to be called</figcaption></figure><p>It would appear that all we need now is to gather the <em>nonce</em>, form our <em>data</em> and then craft a <em>signature</em>.</p><p>Yet, the next HTTP request made is not intended to gather any of these missing details. Instead, an <em>eth_call</em> request is made to a Base RPC node for a contract deployed at <em>0x420000000000000000000000000000000000000F</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hnS9bZu33Y1yoHGd" /></figure><p>This address is the OP (or in this case Base) Gas Price Oracle. To understand why our next call would be to a gas oracle, let’s take a step back and quickly review the design of rollups built using the OP stack.</p><h3>Building Transactions</h3><p>Rollups, such as Base, built on the OP stack have their own execution environment (<strong>op-geth</strong>) for modifying state on Layer 2. In addition to this, they also need to publish their transaction data to Ethereum Mainnet, after all this is what fundamentally makes them rollups. This means that transactions will have to pay gas for state changes on the Layer 2 level as well as gas for the publication of data to Layer 1. Let’s examine how the gas fee is calculated for data that will be published to Ethereum by answering a few probing questions:</p><ol><li>How does the OP stack transaction data actually get posted to Ethereum?</li></ol><p>When a transaction is created in the OP stack, it is sent in two places. To a batcher and off for execution. The <strong>op-batcher</strong> compresses a batch of transactions and submits them to Ethereum Mainnet as calldata. The execution environment (<strong>op-geth</strong>) provides us with a new state after execution on Layer 2. A diagram of this process taken from the official OP docs can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G_Y148JSK8w97rGG" /><figcaption>Transaction flow for OP stack rollups</figcaption></figure><ol><li>How does the <strong>op-batcher</strong> compress the transaction data?</li></ol><p>Ok, so we know that <a href="https://ethereum.org/en/developers/tutorials/short-abi/#cost-of-l2-transactions">Ethereum charges</a> 4 gas per zero byte of calldata and 16 gas per non-zero byte of calldata. However, we also know that since Bedrock, the OP stack leverages compression to reduce the amount of calldata that needs to be posted to Ethereum mainnet. At a high-level, transaction data is batched together and zlib compressed into ~9.5mb (at the time of writing) channels. Since compression occurs on a batch level, each transaction should pay for a portion of its batch’s gas overhead.</p><ol><li>How does the <strong>op-batcher</strong> submit the transaction data?</li></ol><p>After the <strong>op-batcher</strong> compresses the transaction data into a channel, it submits the channel in a single transaction as calldata to a contract on the Ethereum mainnet chain, called the <a href="https://etherscan.io/address/0xff00000000000000000000000000000000000010">Batch Inbox Address</a>.</p><p>Adding all of this together gives us the following formula for the total price of a transaction on an OP stack rollup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vu_uz3k3Vi8oQ7WWgacU4A.png" /><figcaption>Total gas fee calculation for a transaction on Base</figcaption></figure><p>Where the fee scalar currently is ~0.68, a net decrease to the transaction’s pricing in Layer 1 gas terms, attributed to efficiency gains from data compression.</p><p>Ok, so now it becomes much clearer why we needed to gather the Layer 1 price of the mint transaction.</p><p>If we continue looking at the traffic, we see that the next thing that occurs is the app makes an RPC call to get the transaction count for our address:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*0RPfStb2Rr3uljgZ" /></figure><p>This will be the <em>nonce</em> that needs to be included in our signed Base transaction for minting the NFT. In our case, this is a brand new wallet and the result is 0x0.</p><p>Now that our wallet has the gas required for the Layer 1 transaction and the <em>nonce</em> of our account, we just need the <em>data</em> for our transaction and then our literal signature of approval and we can submit our transaction for inclusion on the network!</p><p>But how do we get the data? Come to think of it, how did we already submit a transaction with <em>data</em> to the Layer 1 Gas Price Oracle earlier?</p><p>The <em>data</em> is supposed to contain information, among other things, regarding what contract we want to interact with and any function we want to call. In other words, the front-end needs the contract ABI to be able to properly form the <em>data</em>, request a signature of this <em>data</em> from the user’s wallet, and then send a request out to the designated RPC provider.</p><p>The reason the front-end already has the information required to form the data is because before we even clicked the mint button, several <em>.js</em> scripts were loaded on the website. One of these scripts contained the ABI for the ERC721 drop contract that will ultimately be used to mint us a Base day one NFT. Pictured below is a snippet of the ABI for the function that will be called when minting the Base day one NFT:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*PHDYqjf9ilK6qGBG" /></figure><p>With the correct ABI, the front-end can create the transaction with all of the information we have already uncovered and then ask the user to sign the transaction through their wallet provider.</p><h3>Sending Transactions</h3><p>Now, we should have everything we need to send our mint transaction, but before that gets sent, Coinbase Wallet actually simulates the transaction using its own api:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AbpwIza0J5lOHBML" /></figure><p>This provides the user with a popup box giving them an idea of what the upcoming transaction will effectively do. In this case it showed that an NFT named Based would be sent from the zero address to our wallet. A snippet of the JSON output of the simulated transaction can be seen here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qp0E88NqIxJ1UsI7" /></figure><p>Once we click confirm, our transaction is officially sent out to the RPC provider:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QS6RayzjoooLD9FI" /></figure><p>What does this do? Well, this sends a request to the RPC node to send out a pre-signed transaction on our behalf to the Base network. What happens from here? If you’d like a deeper dive for the actual broadcasting and execution of the transaction, there’s an excellent blog post that covers this in great detail <a href="https://www.notonlyowner.com/learn/what-happens-when-you-send-one-dai#reception">here</a>.</p><h3>Settling Transactions on Layer 1</h3><p>What is not covered in that blog is how the transactions are actually sent from Layer 2 to Layer 1. We’ll dig into this by referencing the <strong>op-batcher</strong> source code, after all the batcher is responsible for posting transactions to Layer 1.</p><p>To start, a new batch submitter service is <a href="https://github.com/ethereum-optimism/optimism/blob/dc146ac1d15053d5b6c7d9aba6848b7c4a4aafbb/op-batcher/batcher/batch_submitter.go#L39-L46">created and started</a> from within the <strong>op-batcher</strong>. Once this service has started, it executes the <a href="https://github.com/ethereum-optimism/optimism/blob/dc146ac1d15053d5b6c7d9aba6848b7c4a4aafbb/op-batcher/batcher/driver.go#L143">loop</a> function. Within this function, the batcher loads blocks into <a href="https://github.com/ethereum-optimism/optimism/blob/dc146ac1d15053d5b6c7d9aba6848b7c4a4aafbb/op-batcher/batcher/driver.go#L298C16-L298C35">memory</a> which it ultimately gathers from the <a href="https://github.com/ethereum-optimism/optimism/blob/dc146ac1d15053d5b6c7d9aba6848b7c4a4aafbb/op-batcher/batcher/driver.go#L230C18-L230C26">l2client</a>.</p><p>In other words, the batcher is pulling down and reading from the Layer 2’s (Base’s) published block data.</p><p>This pulled down data is then formed into a <a href="https://github.com/ethereum-optimism/optimism/blob/96562692558e5c3851899488bcebe51fbe3b7f09/op-batcher/batcher/driver.go#L366">TXData</a> object which <a href="https://github.com/ethereum-optimism/optimism/blob/96562692558e5c3851899488bcebe51fbe3b7f09/op-batcher/batcher/channel_manager.go#L225">processes</a> the blocks by <a href="https://github.com/ethereum-optimism/optimism/blob/96562692558e5c3851899488bcebe51fbe3b7f09/op-batcher/batcher/channel_builder.go#L202">adding</a> them into the channel compression pipeline in batches. These batches are then RLP encoded and <a href="https://github.com/ethereum-optimism/optimism/blob/96562692558e5c3851899488bcebe51fbe3b7f09/op-node/rollup/derive/channel_out.go#L135">compressed</a> on a per batch basis into an output channel. Finally, the entire channel is <a href="https://github.com/ethereum-optimism/optimism/blob/96562692558e5c3851899488bcebe51fbe3b7f09/op-batcher/batcher/driver.go#L375">published</a> to Layer 1 when the <strong>op-batcher</strong> sends it as calldata to the <a href="https://etherscan.io/address/0xff00000000000000000000000000000000008453">Batch Inbox Address</a>.</p><p>If we look at the Batch Inbox Address, we can see that the channels are posted every minute on Base:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JXt7LzxXCGz5huU1" /></figure><p>And that’s it! Very shortly after we’ve received confirmation of our transaction being included on Base, the transaction data will be posted to the Batch Inbox Address on Ethereum mainnet. Our NFT now lives on Ethereum as a compressed transaction and on Base as part of the client state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bv00k1XksL2ogFDB.png" /></figure><p>If you’re interested in a smart contract audit or other security services, get the process started by visiting <a href="https://afterdarklabs.xyz/">afterdarklabs.xyz</a> or reaching out to <em>info@afterdarklabs.xyz</em> directly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5abbca37a25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How a Vyper 0-day Led to Tens of Millions of Dollars in Hacked Funds]]></title>
            <link>https://medium.com/@afterdark_labs/how-a-vyper-0-day-led-to-tens-of-millions-of-dollars-in-hacked-funds-d220fa8f41fe?source=rss-dbb7326ef37------2</link>
            <guid isPermaLink="false">https://medium.com/p/d220fa8f41fe</guid>
            <category><![CDATA[vyper]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[curve-finance]]></category>
            <dc:creator><![CDATA[AfterDark Labs]]></dc:creator>
            <pubDate>Mon, 31 Jul 2023 17:25:58 GMT</pubDate>
            <atom:updated>2023-07-31T17:25:58.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-00eyPdZ7Dshuh5bF5x8fg.png" /><figcaption>Connect with us at <a href="https://afterdarklabs.xyz/">afterdarklabs.xyz </a>or <a href="https://twitter.com/afterdark_labs">@afterdark_labs</a></figcaption></figure><h3>What Happened?</h3><p>Over $50,000,000 has been hacked from protocols due to a novel vulnerability in the Vyper programming language. The root cause of the issue is the way the Vyper compiler assigns storage slots for contracts leveraging the built-in <em>@reentrancy</em> decorator. This only affects Vyper versions <em>&gt;= 0.2.15 &lt; 0.3.1</em>. If your protocol is currently deployed using any of these versions, we suggest reaching out to a security professional to determine if you are impacted and explore potential courses of action.</p><p>This article is going to go over the vulnerability from first principles. If you are familiar with the concepts of reentrancy and cross-function reentrancy, feel free to skip ahead to the section titled “Reentrancy in Vyper 0.2.15”.</p><h3><strong>Background</strong></h3><h4><strong>Reentrancy in Solidity</strong></h4><p>Doubtless most developers and auditors in the space are familiar with reentrancy at this point. Still, it’s worth going over a few examples that relate to the issue regarding how Vyper’s compiler handled reentrancy protection. Below we have the quintessential example of reentrancy in a Solidity smart contract:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aGpQikYO146VpbaU" /><figcaption>Example vault contract vulnerable to reentrancy</figcaption></figure><p>If we look at the <em>withdraw()</em> function here, we can see that it does not follow the <a href="https://fravoll.github.io/solidity-patterns/checks_effects_interactions.html">checks-effects-interaction</a> pattern and as a result is vulnerable to a classic reentrancy issue. Since the external call occurs before the balance of the <em>msg.sender</em> is updated, we can easily devise a contract that could call back into the withdraw function while the <em>msg.sender</em> still has a positive balance. The <em>msg.sender</em> could continue to get paid out its initial balance as long as the contract holds Ether, without donating any extra funds to the contract. In other words, anyone could drain this vault.</p><h4><strong>Mitigations</strong></h4><p>As a developer who wishes to prevent reentrancy issues, there are typically two approaches to take. The first is to follow the checks-effects-interaction pattern. In this case, that would mean moving the <em>balances[msg.sender] = 0;</em> line directly before the external call. This would make it so that even if the user did call back into the withdraw function, the balance would be correctly accounted for during the reentrancy.</p><p>A second way to prevent reentrancy issues is to make use of a reentrancy guard. In Solidity, reentrancy guards are not built into the language, so developers must leverage external libraries or otherwise implement their own. Let’s take a look at the popular OpenZeppelin’s reentrancy guard implementation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/0*UuEA_DJIzstIekFW" /><figcaption>A snippet from OpenZeppelin’s ReentrancyGuard contract</figcaption></figure><p>The way the reentrancy guard works is it sets the <em>_status</em> variable, which takes up a single slot in storage, to the value of either 1 or 2 depending on if a function has already been entered or not. Any function that has the <em>nonReentrant</em> modifier cannot be reentered, as once one function containing this modifier has been entered the <em>_status</em> variable is set to 1 (<em>_ENTERED</em>).</p><p>Consider our example now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*AECf40fwJJRp75Zo" /><figcaption>Example vault contract with some reentrancy protections</figcaption></figure><p>We can no longer enter the withdraw function more than one time. However, the observant reader may have noticed that there is another function containing withdrawal capabilities that does not have the <em>nonReentrant</em> modifier.</p><h4><strong>Cross-function Reentrancy</strong></h4><p>While it is true that the <em>nonReentrant</em> modifier prevents a user from reentering the <em>withdraw()</em> function during the external call, nothing prevents a user from calling the <em>withdrawTo()</em> function before the <em>withdraw()</em> function has updated the balances mapping. This issue is known as cross-function reentrancy and in this case it would allow the user to redeem their balance while simultaneously sending their balance out to another user before it is set to 0. In other words, users can spend double of what they actually have. This could be repeated an indefinite amount of times to eventually drain the vault.</p><p>This could be fixed by simply adding the <em>nonReentrant</em> modifier to <em>withdrawTo()</em> as well. This works, because the <em>_status </em>variable is occupying a single storage slot in the contract that determines whether a function has been entered or not. In other words, any function that leverages the <em>nonReentrant</em> modifier cannot be reentered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PIxVdFd7tCdQgg2T" /><figcaption>Example vault with reentrancy protections to prevent draining</figcaption></figure><h4><strong>Reentrancy in Vyper 0.2.15</strong></h4><p>Reentrancy guards in Vyper are implemented differently than they are in Solidity. In Vyper, the <em>@nonreentrant</em> decorator is a built-in type handled by the language itself. Developers do not need to import a library to protect functions from reentrancy. Instead, they just need to apply the decorator to any function they wish to have reentrancy protection for. Here is the same vault written in Vyper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*K19Mu0DU8ax_VBMB" /><figcaption>Example vault with reentrancy protections to prevent draining</figcaption></figure><p>Let’s take a quick look at how the <em>@nonreentrant</em> decorator works in Vyper 0.2.15. When generating the intermediate representation (IR) for a function, the Vyper compiler <a href="https://github.com/vyperlang/vyper/blob/e9b9aff85b315371a21b574406cf8a4601ecc779/vyper/old_codegen/function_definitions/external_function.py#L164">includes the reentrant pre and post condition</a>s as calculated from the <em>get_nonreentrant_lock()</em> function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rfhrWRxeVFiPa2T2" /><figcaption>@nonreentrant decorator pre and post conditions</figcaption></figure><p>We gain quite a few insights from the above function, at least based on how the IR will be built. The precondition for the function will check that the storage slot (<em>nkey</em>) holding the reentrancy flag is not already set to the designated <em>temp_value</em>. If that holds true, then it will store the <em>temp_value</em> into the <em>nkey</em> storage slot, setting the reentrancy flag. Finally the post condition will store the <em>final_value</em> in the <em>nkey</em> storage slot, unsetting the reentrancy flag.</p><p>This looks quite a bit like the Solidity library we dug into, except one thing remains unanswered: how is the storage slot for <em>nkey</em> calculated? To determine this, we turn to the parse module that calculates the layout of storage variables during contract compilation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_DoRck8xFzmUqfxh" /></figure><p>The first loop goes over each function definition and determines if they have the <em>@nonreentrant</em> decorator. If they do, it sets the reentrancy key position to <em>storage_slot</em>. So far so good. But then it increments the <em>storage_slot</em>. Uh oh. Are we seeing the problem? Every single <em>@nonreentrant</em> decorator receives its own storage slot. This implies cross-function reentrancy is not covered by the decorator. Let’s confirm this with our vault example from before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/0*h3fYULkqcJJu9VhU" /></figure><p>Unfortunately it is indeed true that the vault is still vulnerable to cross-function reentrancy despite having the <em>@nonreentrant</em> decorator placed on both withdraw functions. The vault example and its tests will be released in the near future for educational purposes. Now that we understand the problem let’s examine one of the protocols that was impacted by this vulnerability.</p><h3><strong>pETH-ETH Pool Attack</strong></h3><p>Taking a closer look at the pETH-ETH pool contract, it can be seen that functions for depositing and withdrawing from the protocol contain the <em>@nonreentrant</em> decorator. However, we know from our above example that this does not prevent cross-function reentrancy in Vyper 0.2.15. Examining the <em>remove_liquidity()</em> function, it becomes clear that this does not follow the checks-effects-interactions pattern as there are state variables updated after an external call is made to the <em>msg.sender</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J9_g61EovvmQfF_V" /></figure><p>The question now becomes, is there another function that relies on the values from <em>total_supply</em> or the <em>msg.sender</em>’s balance? It turns out, there is. The <em>add_liquidity()</em> function will increase the <em>total_supply</em> and the balance of the <em>msg.sender</em> based on a calculated value called the <em>mint_amount</em>. Looking closer, we can see that the <em>mint_amount itself</em> is calculated using the existing <em>total_supply</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vMu0vqHVCHT6M6EF" /></figure><p>This means that an artificially high <em>total_supply</em>, as is the case when liquidity has been removed but not yet accounted for, will produce an abnormally large <em>mint_amount</em>. Armed with this knowledge, let’s breakdown the <a href="https://explorer.phalcon.xyz/tx/eth/0xa84aa065ce61dbb1eb50ab6ae67fc31a9da50dd2c74eefd561661bfce2f1620c">attack transaction</a> that drained the pool.</p><h4>Attack Transaction</h4><p>1. The attacker takes out a flash loan for 80,000 WETH from the balancer vault. They then withdraw that to give themselves 80,000 ETH.</p><p><strong>Attacker balance: 80,000 ETH</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hxpX2lsUsqt83Qd1" /></figure><p>2. The attacker calls <em>add_liquidity()</em> on the pETH-ETH curve pool with 40,000 ETH. This gives them a balance of 32,431 pETH-ETH LP tokens.</p><p><strong>Attacker balance: 40,000 ETH | 32,431 pETH-ETH</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XxOED-AOTBorhxE0" /></figure><p>3. The attacker calls <em>remove_liquidity</em> with a 32,431 <em>_burn_amount</em>. The value is calculated as 34,316 ETH which is then sent using the <em>raw_call()</em> to the attacker’s fallback function.</p><p><strong>Attacker balance: 74,316 ETH | 32,431 pETH-ETH</strong></p><p>4. The attacker’s fallback function contains a call to <em>add_liqudity()</em> before <em>remove_liquidity()</em> has completed. This is successful due to the issue in Vyper’s compiler for <em>@nonreentrant</em> decorators. The attacker sends 40,000 ETH to the <em>add_liqudity()</em> function. The <em>mint_amount</em> is artificially inflated and as a result the attacker is credited with 82,182 pETH-ETH.</p><p><strong>Attacker balance: 34,316 ETH | 114,613 pETH-ETH</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ByZeJXkU8Db9aqJm" /></figure><p>5. The second coin in the initial <em>remove_liquidity()</em> loop is hit and the attacker receives 3,740 pETH. At the end of the <em>remove_liquidty()</em> function, the initial <em>_burn_amount</em> of 32,431 is subtracted from the attacker’s pETH-ETH balance.</p><p><strong>Attacker balance: 34,316 ETH | 82,182 pETH-ETH | 3,740 pETH</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g76RVL1bxA_YXSsZ" /></figure><p>6. The attacker now calls <em>remove_liquidity()</em> once more with a 10,272 Ether <em>_burn_amount</em> which now is worth 47,506 ETH and 1,187 pETH. The attacker is credited with both the ETH and the pETH.</p><p><strong>Attacker balance: 81,822 ETH | 71,910 pETH-ETH | 4927 pETH</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Frsl-0ps0L9yOrEm" /></figure><p>Finally, the attacker exchanges their pETH for 4,285 ETH. They now convert all of their ETH to WETH, pay off the flash loan and their final balance is their profit.</p><p><strong>Attacker balance: 6,106 WETH | 71,910 pETH-ETH</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MRGy79iNtNcoSmvv" /></figure><h4><strong>Ecosystem Impact</strong></h4><p>Multiple curve pools and other protocols have already been <a href="https://twitter.com/PeckShieldAlert/status/1685794015915229184">affected by this issue</a> for about $52,000,000 in losses as of July 30, 2023.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1wgr5W5O42ScBwAs.png" /></figure><p>If you’re interested in a smart contract audit or other security services, get the process started by visiting <a href="https://afterdarklabs.xyz/">afterdarklabs.xyz</a> or reaching out to <em>info@afterdarklabs.xyz</em> directly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d220fa8f41fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EIPs Explained: EIP-4337]]></title>
            <link>https://medium.com/@afterdark_labs/eips-explained-eip-4337-e10980b64be4?source=rss-dbb7326ef37------2</link>
            <guid isPermaLink="false">https://medium.com/p/e10980b64be4</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[account-abstraction]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[AfterDark Labs]]></dc:creator>
            <pubDate>Thu, 27 Jul 2023 18:23:33 GMT</pubDate>
            <atom:updated>2023-07-27T18:23:33.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NLKy94iz1CIQ4erWiBSnvA.png" /><figcaption>Connect with us at <a href="https://afterdarklabs.xyz/">afterdarklabs.xyz </a>or <a href="https://twitter.com/afterdark_labs">@afterdark_labs</a></figcaption></figure><h3><strong>Background</strong></h3><p>EIP-4337, also referred to as account abstraction, came from the idea of separating the verification mechanism from the transaction inclusion mechanism on Ethereum. Separating or abstracting these two mechanisms allows for several key improvements in user experience including: sponsoring of gas costs, gas payments in ERC20 tokens, and support for alternative verification mechanisms beyond ECDSA to name a few. Before we go over the use cases, let’s discuss how EIP-4337 came to be.</p><p>Ethereum at launch decided there would be two types of accounts:</p><ol><li>Externally Owned Accounts (EOAs)</li><li>Smart Contract Accounts (contract accounts)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gCGGbh4yvCLZNu7r" /><figcaption>Image from <a href="https://ethereum.org/en/developers/docs/accounts/">Ethereum developer docs</a></figcaption></figure><p>EOAs can be thought of as common user accounts. They are controlled by private keys and importantly can send messages by creating and signing transactions. These are the type of accounts most wallets use to initiate transactions. If you’ve ever used metamask or coinbase wallet to interact with a dApp, you’ve used an EOA.</p><p>In contrast to the EOA, a contract account is reactive in nature. Contract account code can read and write to internal storage and even send other messages but only upon receipt of an initial message. This is an important distinction and we will see why later. For now, remember that EOAs are essentially the only account type that can actually create and send a transaction without first receiving a message.</p><p>In addition to this two type account architecture, the creators of the Ethereum Virtual Machine decided not to include logic for transaction verification within the EVM itself. Why did they make this decision? Well, for one there was concern over how to manage gas and compute costs if a transaction proved to be invalid. For example, if a miner were to have to process a transaction before it could determine if it was valid, then this computational overhead could serve as a denial of service vector.</p><h4>Previous EIPs</h4><p>The potential benefits of account abstraction were seen very early on in Ethereum’s development. In fact, there are proposals from as early as 2016 suggesting a form of abstraction. The below timeline covers some of the key precursors to EIP-4337:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xKKrS0aAc4-CnuiT.jpg" /></figure><ul><li><a href="https://eips.ethereum.org/EIPS/eip-86">EIP-86</a> and <a href="https://github.com/ethereum/EIPs/pull/208">EIP-208</a> (2016–2017) — EIP-86 suggested the creation of a forwarding contract. Under EIP86, if the signature of a transaction was v=r=s=0, then the transaction was considered valid and the sending address was set to a specific entry point. Transactions could then start from this entry point and then make a call to a contract account which would hold the logic for sending other messages. Problematically, these EIPs did not preserve transaction hash uniqueness and they also created a denial of service vector where a single transaction could invalidate a whole stack of transactions in the mempool.</li><li><a href="https://ethresear.ch/t/tradeoffs-in-account-abstraction-proposals/263">Informal proposals from 2017</a> — There were several ideas floating around for implementing account abstraction in 2017, some of which began to resemble EIP-4337 (Panic + PAYGAS). Still, none of these addressed the denial of service vector that could be caused by a single invalid transaction.</li><li><a href="https://ethresear.ch/t/a-recap-of-where-we-are-at-on-account-abstraction/1721">Informal proposal from 2018</a> — An idea from 2018 surfaced that mostly solved for the denial service vector by modifying the EVM to check during the verification portion of transaction execution if an account reads or writes the state of things outside of its own account. If it did, then this transaction would be thrown out. This would make it so that the only way a valid transaction in the mempool could become invalid would be if the transaction itself caused that invalid state.</li><li><a href="https://eips.ethereum.org/EIPS/eip-2938">EIP-2938</a> (2020) — EIP-2938 took the previous ideas on account abstraction and bundled them up into a formal EIP. It proposed a new transaction type and entrypoint as described in EIP-86, leveraged the Panic + PAYGAS ideas from 2017, and suggested preventing accounts from reading from or writing to the state of other accounts during the verification portion of transaction execution (as proposed in 2018). While this was really beginning to look like EIP-4337, the key difference here is that EIP-2938 was a protocol layer change. In the end, the decision was made to favor a higher layer implementation of account abstraction.</li></ul><h3>EIP Summary</h3><p>The core idea of EIP-4337 was to actually achieve the same outcome as EIP-2938 but to do this without making any base protocol changes to consensus. It achieved this by allowing accounts to package up the actions they wanted to take into a <em>UserOperation</em> struct instead of creating a new type of transaction at the protocol layer. The <em>UserOperation</em> object can then be sent to a dedicated mempool where bundlers can grab them and put them all into a bundled transaction that makes a single call to a global entry point contract. The process is outlined below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FtACOsdJVacUFpWq" /><figcaption><em>Diagram from official proposal for EIP-4337</em></figcaption></figure><p>What you have here is a system based on a global entry point contract and an open, MEV-like market that arranges multiple operations into a single wrapper transaction, verifies all of those transactions, and then executes them.</p><p>Note that the entry point contract is placed on-chain. Wallets must individually choose to trust this entry point contract in order to interact with it on behalf of their users.</p><p>Let’s further explore the process step by step:</p><p><strong>1. <em>UserOperation</em> Object Creation</strong></p><p>Users who wish to leverage EIP-4337 first create a <em>UserOperation</em> object from a regular EOA that will interact with their account contract. This object’s goal is to take the place of a regular transaction and as a result the fields will pertain to the account contract as opposed to the EOA. The <em>UserOperation</em> object and its fields can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/0*IpoPNtnmOyD-Y1x_" /></figure><p>Note that the sender is set to the contract account which itself will verify the signature in addition to receiving and executing the calldata.</p><p><strong>2. Bundling and Execution of <em>UserOperations</em></strong></p><p><em>UserOperation</em> objects are sent to a dedicated mempool where a set of bundlers are responsible for handling these objects and including them in a single transaction to the entry point contract.</p><p>Before a <em>UserOperation</em> is eligible for transaction inclusion, a bundler must first run a set of <a href="https://eips.ethereum.org/EIPS/eip-4337#client-behavior-upon-receiving-a-useroperation">sanity checks</a> to verify the <em>UserOperation</em> was formed appropriately using valid inputs for its fields. If these checks are passed, then the bundler runs a simulation to determine if the <em>UserOperation</em> is indeed valid and capable of paying for its execution. This is done by making a call to <em>EntryPoint.simulateValidation()</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1MvJwGMmKEPQNnIt" /><figcaption>simulateValidation function from the global entry point contract</figcaption></figure><p>This in turn calls <em>sender.validateUserOp()</em> as part of the verification. The <em>validateUserOp()</em> function also checks if the signature itself is valid. A base implementation of this function can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YSI8uxFgKRwFjkxV" /><figcaption>validateUserOp function from a base account contract</figcaption></figure><p>If all of these checks pass, then the function will revert with the expected error, the <em>UserOperation</em> will be considered valid, and the bundler will add it to the dedicated mempool. This <em>UserOperation</em> would now be eligible for bundling and transaction inclusion. This is where the Bundlers work their magic by submitting (as calldata) a set of <em>UserOperations</em> to the <em>EntryPoint.handleOps()</em> function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xjG9ClD8ZipwochF" /><figcaption>handleOps function from the global entry point contract</figcaption></figure><p>This will in turn call into the <em>UserOperation.sender</em> with the <em>UserOperation.calldata</em>. It up to the contract account to implement a workflow for handling and reacting to this calldata. Typically, the account will implement an <em>execute()</em> function that parses the calldata as a series of one or more calls for the contract account to make.</p><p>Armed with an understanding of the process for creating and including a standard EIP-4337 transaction, let’s discuss some extra functionality that can be included in an EIP-4337 transaction.</p><h4><strong>Extensions</strong></h4><p>There are two extensions within EIP-4337 worth mentioning: Paymasters and Signature Aggregation. Paymasters are contract accounts that can pay on behalf of other users. This is used for sponsoring or otherwise offering users gasless transactions. The slightly modified workflow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fxt0PkIUKNr4vq1L" /><figcaption><em>Diagram from official proposal for EIP-4337</em></figcaption></figure><p>Signature aggregators are also helper contract accounts but instead of paying on behalf of other users, they validate an aggregated signature for multiple transactions improving efficiency of the verification process. For example, BLS signatures generated by multiple unique keys can be aggregated into a single signature which can then be verified in a single step. A base implementation of such an aggregator can be found <a href="https://github.com/eth-infinitism/account-abstraction/blob/develop/contracts/samples/bls/BLSSignatureAggregator.sol">here</a>.</p><h3><strong>Use Cases</strong></h3><p>EIP-4337 brings many advantages to users and protocols alike:</p><ul><li>Gas payments can be sponsored by protocols to give users a gasless experience</li><li>Gas payments can be made in ERC20 tokens so users no longer need to have or use native ETH directly</li><li>Alternative verification mechanisms can be supported beyond ECDSA. This is beneficial for future proofing Ethereum if quantum computing renders ECDSA broken</li><li>User experience is improved for implementing more granular account permissions such as role based account access</li><li>Multisignature accounts can be first class citizens and may see wider adoption as a result</li></ul><p>Broadly speaking, account abstraction is widely <a href="https://www.youtube.com/watch?v=WsZBymiyT-8">viewed</a> as an important stepping stone in Ethereum’s path to massive user adoption.</p><h3><strong>Security Considerations</strong></h3><h4>Entry Point Contract</h4><p>The way EIP-4337 is structured, the bulk of the security risk lies in the entry point contract. This serves as a central trust point for every single EIP-4337 compliant account.</p><h4><strong>Contract Accounts</strong></h4><p>For smart wallet developers, there are a few things to consider when implementing EIP-4337 accounts. These accounts will have to implement their own verification functions that should accurately check signatures (or equivalent authentication mechanism), increment nonces, and pay fees. Also special care should be taken to ensure that functions on the account follow the principles of least privilege. Adding a modifier that requires the <em>msg.sender</em> to be the entry point contract is a good idea to ensure that sensitive interactions can only be called by the entry point itself.</p><h3>Closing Thoughts</h3><p>EIP-4337’s high-level account abstraction implementation offers several advantages for users and protocols. Protocols can offer their users an improved experience by sponsoring transaction fees and users can even take advantage of EIP-4337 to pay directly in ERC-20 tokens. Importantly, EIP-4337 is one of the first steps towards creating quantum computer resistant transactions on Ethereum. While a bulk of the security responsibility lies on the entry point contract, account developers should also be aware that they must implement some of the functionality themselves. We recommend minimizing the threat surface by restricting as much of the sensitive operations as possible to the entry point contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RsOeRseq_gCSuRX-.png" /></figure><p>If you’re interested in a smart contract audit or other security services, get the process started by visiting <a href="https://afterdarklabs.xyz/">afterdarklabs.xyz</a> or reaching out to <em>info@afterdarklabs.xyz</em> directly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e10980b64be4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EIPs Explained: EIP-2612]]></title>
            <link>https://medium.com/@afterdark_labs/eips-explained-eip-2612-9c7d6690802d?source=rss-dbb7326ef37------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c7d6690802d</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[AfterDark Labs]]></dc:creator>
            <pubDate>Fri, 14 Jul 2023 15:43:02 GMT</pubDate>
            <atom:updated>2023-07-14T15:43:02.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m7sqgL5_4n3snKX9" /><figcaption>Connect with us at <a href="https://afterdarklabs.xyz/">afterdarklabs.xyz </a>or <a href="https://twitter.com/afterdark_labs">@afterdark_labs</a></figcaption></figure><h3><strong>Background</strong></h3><p>EIP-2612 is purpose built to allow an ERC20 token approval to occur within the same transaction it is consumed. This builds upon two previous standards: <a href="https://eips.ethereum.org/EIPS/eip-20">EIP-20</a> and <a href="https://eips.ethereum.org/EIPS/eip-712">EIP-712</a>. We will briefly cover some of the important aspects of these two standards but if you are unfamiliar with either, we recommend you review them first before continuing with this article.</p><h3><strong>EIP Summary</strong></h3><p>EIP-2612 can be thought of as an extension of EIP-20. For those unfamiliar with EIP-20, it is the standard that describes the API requirements for nonfungible ERC-20 tokens. EIP-2612 adds 3 new functions to the ERC-20 token standard: <em>permit()</em>, <em>nonces()</em>, and <em>DOMAIN_SEPARATOR()</em>.</p><p>The bulk of the added functionality can be found within the permit() function of this EIP. It takes the <em>owner</em> of the ERC-20 tokens, the account that will be given permission to spend on behalf of the <em>owner</em>, the <em>value</em> to set the approval to, a <em>deadline</em>, and a signature in order to update the approval mapping for the ERC-20 token.</p><p>Let’s take a practical look at how <em>permit()</em> works by reviewing an implementation of it by the popular OpenZeppelin library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wG1ZBLmePCMumJ3ppgTUPw.png" /><figcaption><em>permit()</em> function as seen in OpenZeppelin’s ERC20Permit.sol</figcaption></figure><p>We’ll further break this up into three sections:</p><h4><strong>Deadline Enforcement</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5r3Pk39Aq82RjBnQ9u_q2Q.png" /></figure><p>In this first line, we see that the deadline is being enforced by comparing it to the current timestamp. If the current block’s timestamp is greater than the deadline, we know that the time limit has passed and we revert the transaction. This check allows users to provide an expiration date for their signed approval.</p><h4><strong>Signature Hash Encoding</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmieFCOxKcjRXpRqtjjg3A.png" /></figure><p>In these two lines, the hash of the parameters is being set up so that a signature can be recovered from it. Note that it contains all of the relevant information mentioned in the EIP: the <em>owner</em>, <em>spender</em>, <em>value</em>, and <em>deadline</em>. The <em>_useNonce()</em> wrapper is a fancy way of incrementing the nonce immediately after it has been consumed. Constructing the hash in this way means the original signer needs to have signed off on all of this same information in order for the signature recovery to work properly. The correctly encoded EIP-712 hash for this domain is constructed using the hashed struct and domain separator.</p><p>This is a good time to step out of the <em>permit()</em> function and discuss the domain separator. The domain separator is used to limit a signature to a domain. This is useful to ensure users aren’t signing a blank check. By incorporating information such as the ERC-20 token name and <em>chainID</em> into the domain, the signature shouldn’t apply broadly across other apps and chains.</p><h4><strong>Signature Recovery</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5EIpuyFy5avJqDi_5qK0lA.png" /></figure><p>Last, we recover the address of the signer using both the signed hash and the values that represent the signature and recovery identifier themselves. The <em>ECDSA.recover</em> call is a wrapper around the <em>ecrecover</em> precompile. This precompile returns the public key from a signature, the recovery identifier, and a signed message. If the public key matches the owner then we know the owner originally signed this message and the approval will be made.</p><p>And that’s the bulk of the added functionality! We’ll now go over a few use cases and security considerations for those considering using EIP-2612 functionality in their protocol.</p><h3><strong>Use Cases</strong></h3><p><strong>1. Gasless Transactions</strong></p><p>One very popular use of EIP-2612 is for performing gasless transactions. Since the EIP-712 style signatures can be gathered offchain, the user is not expected to be the party that posts the transaction containing the call to permit(). Protocols can therefore offer gasless transactions for their users that may have otherwise required a user to interact directly with an app.</p><p><strong>2. Reduced Approval Footprint</strong></p><p>As we covered in “<a href="https://medium.com/@afterdark_labs/top-5-smart-contract-vulnerabilities-of-2023-9c871662f61e">Top 5 Smart Contract Vulnerabilities of 2023</a>”, unrevoked approvals are a major source of lost funds for users in DeFi. Leveraging EIP-2612 to collect signatures on the spot for approvals, it is feasible for protocols to offer their users a seamless experience without requiring a permanent max approval. This can help users reduce their approval footprint and potentially keep them safe during protocol hacks.</p><p><strong>3. Batched Transactions</strong></p><p>Interactions across apps that handle tokens making use of EIP-2612 can be batched together. Batching can improve intra transaction composability, allowing users to interact with multiple protocols and potentially be less susceptible to transaction ordering attacks. Batched transactions can also benefit from the ability to be made gasless for users.</p><h3><strong>Security Considerations</strong></h3><h4><strong>Replay Protection</strong></h4><p>It’s important that the signing domain be unique, otherwise signatures can be replayed across domains. In practice, popular EIP-712 libraries take care of a lot of this for you. We recommend using unique names and/or versions when constructing each of your tokens to improve the robustness of replay protection.</p><h4><strong>Signature Malleability</strong></h4><p>Signature malleability occurs when non-unique signatures can be considered valid for the same signed output. The EVM opcode <em>ecrecover</em> itself can return the same address for non-unique signatures. Similar to replay issues, much of this can be mitigated by using popular libraries which reject a second set of signatures that <em>ecrecover</em> would accept.</p><h4><strong><em>ecrecover</em> Silent Failure</strong></h4><p>As mentioned in EIP-2612 itself, the <em>ecrecover</em> precompile fails silently and returns the 0 address for the signer on failure. This means that it’s important to check that the signer is not the 0 address when performing a <em>permit()</em>. Most of the well-known libraries account for this by throwing an error when <em>ecrecover</em> returns 0.</p><h4><strong>Protocol Complexity</strong></h4><p>Adding EIP-2612 functionality to a protocol can increase the complexity. In addition to adding frontend capabilities for gathering signatures, the contracts themselves often require both permit functionality and traditional non-signature based functionality as well. Protocols should therefore keep in mind the potential increase in deployment costs as well as complexity when choosing to add EIP-2612 functionality.</p><h4><strong>Censorship Potential</strong></h4><p>It is typical for protocols that implement EIP-2612 functionality to also submit the transactions on the user’s behalf. This means that the user relies on the protocol to submit their transaction in order to interact with its apps.</p><h3><strong>Closing Thoughts</strong></h3><p>EIP-2612 offers additional functionality that is useful for protocols that wish to offer gasless or batched transactions. If implemented properly, it also can help users reduce their approval footprint and allow them to interact with dApps more safely. Using existing libraries can help development teams avoid common cryptographic pitfalls and implementing a traditional way to interact with their dApps in addition to the EIP-2612 methods can limit the risk of censorship issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dRA6Lfu96TBfYQjz.png" /></figure><p>If you’re interested in a smart contract audit or other security services, get the process started by visiting <a href="https://afterdarklabs.xyz/">afterdarklabs.xyz</a> or reaching out to <em>info@afterdarklabs.xyz</em> directly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c7d6690802d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart Contract Audits: Pentests of Web3?]]></title>
            <link>https://medium.com/@afterdark_labs/smart-contract-audits-pentests-of-web3-6b6ed8dfbebc?source=rss-dbb7326ef37------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b6ed8dfbebc</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[application]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[AfterDark Labs]]></dc:creator>
            <pubDate>Wed, 19 Apr 2023 18:07:27 GMT</pubDate>
            <atom:updated>2023-04-19T18:07:27.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yV_dtIyM3TG5VOs2gVbMhg.png" /></figure><p>Even in the midst of a bear market, the number of developers and security researchers joining Web3 still <a href="https://www.developerreport.com/developer-report">grew</a> in 2022. This article is targeted at these newcomers, or anyone else who may be interested in how software testing processes differ between Web2 and Web3.</p><p>For many of you, pentests are a familiar part of the software development life cycle. Web2 Developer teams build an application, perform internal security checks and then, before they release to production, they get an external pentest. In Web3, the process is similar but it often leads to a smart contract audit instead of a pentest.</p><p><strong>So, what are smart contract audits and how do they differ from pentests?</strong></p><p>A smart contract audit is a comprehensive review of an application (smart contract) that will run on top of a decentralized network. Similar to application pentests, smart contract audits are seeking to uncover vulnerabilities in an application before they can be exploited.</p><p>Unlike pentests, smart contract audits differ in a few meaningful ways: <em>smart contract audits are performed on open-source applications that are small enough to be manually reviewed in their entirety. </em>They culminate in a report intended to be for both the development team and the community at large.</p><h4>Whitebox vs Blackbox Testing</h4><p>For anyone who has worked as an external pentester in the Web2 security space, you know that blackbox testing is the norm for application reviews. Pentesters are given access to the application in roughly the same manner as an intended user would be. From there, they try to find ways to exploit the application without direct knowledge of the underlying technology. Since pentesters are “flying blind” in this type of test, a lot of time can be spent on reconnaissance gathering and brute-force guessing and fuzzing of application inputs. There are a few reasons blackbox pentests are more popular in Web2, one being that protecting proprietary information is a common concern in traditional software development.</p><p>Contrast this with Web3 applications which are far more likely to be open-source projects. With the source code being available, there is an expectation that the code itself is reviewed during a smart contract audit. On-top of a manual review of the entire codebase, a good quality smart contract audit should also include an automated component using techniques such as static analysis, dynamic analysis, and fuzzing. This makes the typical smart contract audit much closer to a whitebox pentest.</p><h4>Application Size</h4><p>Another significant difference between smart contract audits and pentests is that, at the time of writing, applications built on top of blockchains are often much smaller than traditional software applications. While decentralization is one of the primary benefits of building on top of a blockchain, the built-in consensus mechanisms and resource constraints used to help achieve this property also limit the amount of compute and storage available. As a result, on-chain components of applications often number in the thousands to tens of thousands of lines of code. This makes full manual reviews of smart contracts feasible.</p><p>In comparison, it is not uncommon for Web2 pentesters to be given a few weeks to test an application that has hundreds of thousands of lines of code. In this case, it is simply infeasible to perform a thorough code-review of the entire project in the allotted time. As a result, much of the codebase has to be tested through automated or semi-automated means.</p><h4>Audience of Deliverables</h4><p>The last difference we will be discussing is how the deliverables differ between pentests and smart contract audits. For both tests, a report that details all findings and their suggested remediations is the typical client deliverable.</p><p>For a pentest, this deliverable is usually for internal stakeholder eyes only. This means that the target audience for a report may be limited to the organization’s executives, compliance/audit teams, and the engineering/technology teams responsible for implementing fixes. Tailored for these audiences, pentest reports often contain segments for each stakeholder with the expectation that it only needs to be understood by that stakeholder.</p><p>Web3 projects quite often post their source code for all to see. Combine this with the fact that Web3 users have an increased expectation of transparency, and it becomes unsurprising to hear that projects often wish to make their audit reports public for all to see. The audience of a smart contract audit can therefore include the entire world. This drastically changes the nature of report writing. For reports that will be made publicly available, they should be written so that they can be easily understood even by individuals lacking domain expertise.</p><h4>Takeaway</h4><p>If we were to try to describe smart contract auditing using traditional security terminology, it fits closest to a whitebox pentest that includes a full code-review. Just like in the traditional software development life cycle, teams should have their code tested before a release. Every Web3 development team should get at least one smart contract audit and the accompanying report should be written with the audience in mind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mzxyb82bmMYi__ma.png" /></figure><p>If you’re interested in a smart contract audit or security advisory services, get the process started by visiting <a href="https://afterdarklabs.xyz/">afterdarklabs.xyz</a> or reaching out to <em>info@afterdarklabs.xyz</em> directly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b6ed8dfbebc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 5 Smart Contract Vulnerabilities of 2023]]></title>
            <link>https://medium.com/@afterdark_labs/top-5-smart-contract-vulnerabilities-of-2023-9c871662f61e?source=rss-dbb7326ef37------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c871662f61e</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[AfterDark Labs]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 20:24:37 GMT</pubDate>
            <atom:updated>2023-04-11T20:24:37.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KNI1Uqn2qQMXnTFs-U8bjA.png" /></figure><h4>Background</h4><p>Smart contract development is difficult. Part of what makes smart contract applications so appealing is their immutable (or quite often semi-immutable) nature. It helps keep the ecosystem trustless, as we can count on the code to perform exactly how it says it will. But this also means development teams have one shot to get it right before their project is a sitting duck for any dangers lurking in the dark. Sure, they can participate in monitoring and bug bounty programs but as we saw with this past weekend’s <a href="https://crypto.news/exclusive-hacker-behind-sushiswaps-preemptive-sifu-hack-explained-how-it-was-done/">Sushi Swap</a> hack, fixing bugs post-deployment comes with its own challenges. If we’re ever going to reach mass adoption of Web3, we need to make users feel comfortable when interacting with decentralized applications. We need to reduce the number of hacks that occur in this space. By reviewing what vulnerabilities are being missed before deployment, we can work to prevent future incidents.</p><p>This article is for developers, auditors, and anyone who wants to understand the most common security incidents to date in 2023. We took an in-depth look at nearly 40 smart contract hacks that occurred this year to bring you the list of the top 5 most common issues. This list excludes hacks that are not directly related to smart contract vulnerabilities such as: rugpulls, mishandled admin keys, phishing, or governance takeovers that did not rely on an issue present in smart contract code.</p><h3>Top 5 List</h3><h4><strong>1. Faulty Calculation</strong></h4><p>This category is broad and encompasses a wide range of vulnerabilities that were caused by either a mathematical or logical mistake in the deployed code, but did not fit well in any of the other categories. Incidents in this category contained errors related to incorrect collateralization requirements, the accrual of bad debt, incorrect decimal scaling of tokens, inappropriate rewards distributions, off-by-one mistakes, or other mathematical errors. There were 12 instances identified as faulty calculations.</p><p><strong>Notable hacks</strong>: Allbridge, Euler Finance, Platypus Finance, Omm Finance</p><h4><strong>2. Approval Issues</strong></h4><p>The approval mechanism for tokens on EVM chains is used to give permission in a permissionless world. Approvals work by allowing another party to spend tokens on your behalf. This is convenient when you are sending tokens through an intermediary or when interacting with a contract that will need to use your tokens to perform an action such as swapping on a DEX. One of the biggest dangers of approvals is that it can be cumbersome, expensive, and even downright tricky to frequently gather and spend them in full. As a result it is common practice for many applications to request “infinite approvals”. Many of these approvals persist unrevoked for EOAs and contracts alike, so when a bug appears in the contract, all of these approved funds can be at risk. There were 7 incidents that were identified as approval issues.</p><p><strong>Notable hacks</strong>: Cow Swap, Dexibel, FEGToken, Dungeon Swap + Launch Zone, Sushi Swap</p><h4><strong>3. Oracle issues</strong></h4><p>Oracles are how on-chain applications get information from the real world. In other words, they are used to provide off-chain data to on-chain applications. Integrating oracles can be a challenge because even a moment of inaccuracy in reported data can have catastrophic consequences. A small discrepancy in price reported by an oracle can open up a DeFi application to huge amounts of arbitrage. As a result, oracle results are often aggregated and weighted across a period of time to reduce the points of failure. Nevertheless, oracle issues are still one of the most common occurring incidents in smart contract security. This category includes issues where the oracle dependencies provided faulty data, the oracle reported on an easily manipulable pool, or the oracle relied on spot prices. There were 4 incidents that were identified as oracle issues.</p><p><strong>Notable hacks</strong>: Mycelium, BonqDao, ROE Finance, DKP token</p><h4><strong>4. Reentrancy</strong></h4><p>Reentrancy is perhaps the most infamous issue in the smart contract auditing and development world. It can occur when a contract contains an operation where its control flow can be interrupted and rerouted. This is often the case when a contract contains external calls made to other contracts. The state that a contract is in the moment it gives up control flow to another contract is the state it will be in if it is “reentered”. That is to say, if control flow is given up to another contract and that contract decides to interact with the original contract once more (within the same transaction), the original contract will maintain the state it had before it gave up control flow. This becomes an issue when the original contract relied on logic occurring after control flow was given up to put it in a valid or safe state. While classic reentrancy is the oldest trick in the book for smart contract hackers, read only reentrancy is more nuanced in that it takes advantage of applications that rely on unguarded view functions to perform important calculations. There were 4 incidents that were identified as reentrancy, 3 of which were read only reentrancy.</p><p><strong>Notable hacks</strong>: Midas Capital, Orion Protocol, DForce, Sentiment</p><h4><strong>5. Inappropriate Access Controls</strong></h4><p>Access controls are what define how users of an application can interact with it. They limit the roles of certain users so that they can’t unfairly impact other users or the system itself. Oftentimes these are enforced via function modifiers and function visibility. While access controls are not intrinsically more difficult to implement than a lot of other potential security concerns, a mistake in access controls can have large consequences. The issues here included a public burn function, an unprotected mint function, and a Cardano specific issue where the project assumed using solely stake addresses would be sufficient for user validation. There were 3 incidents that were identified as inappropriate access controls.</p><p><strong>Notable Hacks</strong>: SafeMoon, Degen Millionaires Club, Mutant NFTs</p><h4><strong>Honorable mention: Rebasing tokens</strong></h4><p>Technically rebasing tokens tied for 5th place, however the amount of funds lost was used as a tie breaker and more were caused due to inappropriate access controls. Rebasing tokens are tokens that can have their balances (or some other mechanism used to calculate their value) manipulated during certain events. This could be an increase to the total supply via minting of new tokens, or a decrease in the value that tracks the total available balance to represent burning of tokens. This allows a token to hold inflationary or deflationary properties. Rebasing tokens are difficult to manage in an application because the posts are always shifting. It is easy to overlook edge cases when integrating with tokens that can change their effective supply. These changes often lead to applications that operate on point in time values while anticipating future deviations. There were 3 instances identified as rebasing tokens.</p><p><strong>Notable Hacks</strong>: Sperax, BEVO NFT, Dragonball</p><h4><strong>Takeaway:</strong></h4><p>Faulty calculations unique to projects are by a large margin the most common issue leading to hacks on deployed smart contracts right now. After that, we see that contracts holding approvals on behalf of other parties led to a large portion of the incidents. The design choice of holding approvals for users places a great deal of responsibility on the project and as a result, the security of such projects should not be taken lightly. They should be particularly careful when accepting user input and making external calls. The presence of oracle and reentrancy issues high up in the list reminds us that variations of these problems are still proving difficult for development teams to avoid. Finally, the fact that rebasing tokens made the list shows us that integrating with tokens that have a changing supply can greatly increase the complexity of an application.</p><p>The best way to bring the number of hacks down today is for projects to get a high quality audit before deployment. A vast majority of hacks still occur on unaudited codebases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9vWYe-s0za5VTNOkhxFmw.png" /></figure><p>If you’re interested in a smart contract audit or security advisory services, get the process started by visiting <a href="https://afterdarklabs.xyz/">afterdarklabs.xyz</a> or reaching out to <em>info@afterdarklabs.xyz</em> directly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c871662f61e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing AfterDark Labs!]]></title>
            <link>https://medium.com/@afterdark_labs/introducing-afterdark-labs-8801debafa96?source=rss-dbb7326ef37------2</link>
            <guid isPermaLink="false">https://medium.com/p/8801debafa96</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[founding-team]]></category>
            <dc:creator><![CDATA[AfterDark Labs]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 19:41:11 GMT</pubDate>
            <atom:updated>2023-04-03T19:41:11.782Z</atom:updated>
            <content:encoded><![CDATA[<p>Smart contracts are programmable, self-executing digital agreements that are often utilized in blockchain-based systems to automate and enforce contractual obligations between parties. Although these contracts have immense potential for streamlining business processes and reducing transactional costs, they are also prone to vulnerabilities that can result in unintended consequences or even malicious attacks. In 2022, smart contract exploits resulted in the loss of a staggering <a href="https://cointelegraph.com/news/the-10-largest-crypto-hacks-and-exploits-in-2022-saw-2-1b-stolen">2.1 billion dollars</a>. This highlights the critical need for robust security measures and thorough auditing processes to safeguard against potential vulnerabilities.</p><p>As a smart contract auditing firm, we specialize in identifying potential security gaps and other areas of weakness in these contracts. Our objective is to equip clients with secure and reliable systems that can withstand potential attacks and other threats.</p><p>One of the most common challenges clients encounter during the auditing process is poor communication. We recognize the value of keeping our clients informed and engaged throughout the entire process, and we prioritize open and consistent communication with them. From the onset of the audit, we engage closely with clients to gain a thorough understanding of their unique needs and concerns, and we provide frequent updates on our findings and recommendations. By fostering a collaborative and transparent relationship with our clients, we can help them make well-informed decisions about their smart contracts and ensure the security and dependability of their systems.</p><h3>Who are we?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ReQ_CwGnbJT6CCGw53aeeg.jpeg" /></figure><p><strong>Roderic</strong> is a cybersecurity expert with several years of industry experience. As a red team consultant at Mandiant, he led penetration testing exercises for Fortune 500 companies spanning every industry vertical. These exercises often culminated in working directly with executives to assess organizational security risks. He quickly realized the best results come from collaborative engagements where consultants and clients communicate early and often to ensure mutually beneficial outcomes. He brought this with him to Coinbase and most recently OpenZeppelin where he worked as a smart contract auditor. Here, Roderic helped secure some of the biggest protocols in Web3. In his free time, he enjoys competing in CTFs and hackathons and has received numerous CVEs and bounties for responsibly disclosing bugs in Web2 and Web3 software.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*TeuhNjB2dak-W-jM8nBr4A.jpeg" /></figure><p>As someone who previously co-founded a company in the exploratory data product industry, <strong>Andrew</strong> understands the importance of ensuring the security and accuracy of data-driven systems. The team worked remotely with companies all over the world, built an ecosystem of student data scientists, published open source products for the community, and won the 2020 Columbia University Venture competition. Most recently, Andrew managed the back office of over $500M assets under management across 45 venture capital firms at AngelList. Managing the back office of 45 VCs simultaneously requires an immense amount of communication skills, including effective coordination with a diverse range of stakeholders, managing competing priorities, and maintaining clear and consistent lines of communication.</p><h3>Going Forward</h3><p>We believe that smart contract auditing is an essential service that will ensure the continued growth and success of the blockchain ecosystem. With our expertise and dedication, we’re confident that we can make a meaningful contribution to this space.</p><p>If you’re interested in learning more about our firm or how we can help you secure your smart contracts, please don’t hesitate to reach out at <a href="https://afterdarklabs.xyz/">https://afterdarklabs.xyz</a>. We’d love to chat with you and see how we can help! DMs are always open :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*HjQdO7BXMjVFPMleCS2CeA.jpeg" /><figcaption>Fun fact: This selfie cost $20. Andrew took this photo at ETH Denver and missed a free shuttle to an event by 4 seconds. He had to grab an Uber to make it on time.</figcaption></figure><p><em>Andrew and Rod</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9vWYe-s0za5VTNOkhxFmw.png" /><figcaption>Elite smart contract audits that shine a light on the darkest corners of Web3</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8801debafa96" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>