<?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 ChainSecurity on Medium]]></title>
        <description><![CDATA[Stories by ChainSecurity on Medium]]></description>
        <link>https://medium.com/@chain_security?source=rss-8b14ef67c636------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*IYEDevVjlqHJSXRJhxagdA.png</url>
            <title>Stories by ChainSecurity on Medium</title>
            <link>https://medium.com/@chain_security?source=rss-8b14ef67c636------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 21:24:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chain_security/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[Glamsterdam’s Hoodi Delay: What It Means for Smart Contracts]]></title>
            <link>https://medium.com/@chain_security/glamsterdams-hoodi-delay-what-it-means-for-smart-contracts-eb5ee8bfe183?source=rss-8b14ef67c636------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb5ee8bfe183</guid>
            <dc:creator><![CDATA[ChainSecurity]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 09:32:08 GMT</pubDate>
            <atom:updated>2026-10-24T09:32:08.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lIyhIB7-sEVfSlr-S41DpQ.jpeg" /></figure><p>The Glamsterdam upgrade on the Hoodi testnet has been <a href="https://blog.ethereum.org/en/2026/10/22/glamsterdam-hoodi-delay">postponed</a> to allow further investigation into how EIP-8037 interacts with existing smart contracts. ChainSecurity’s findings contributed to this discussion. As noted in our <a href="https://x.com/chain_security/status/2113303061078671814">announcement</a>, we have identified 13 real-world examples and are coordinating responsible disclosure with the affected projects.</p><p>Glamsterdam would introduce new execution rules affecting already deployed contracts. Under the proposed changes, some contracts could respond differently to a failed operation, even though their code remains unchanged.</p><p>Two proposals are involved. EIP-8037 changes how state creation is charged and introduces separate state-gas accounting. EIP-8038 changes the execution costs of accessing and modifying state.Together, they can affect both how much gas a call needs and how much work the caller can complete after it fails. We examine both in more detail <a href="https://www.chainsecurity.com/blog/glamsterdam-gas/">here</a>.</p><p>Some contracts use the gas remaining after a call to detect whether it received too little gas. Others rely on a failure handler running out of gas and reverting the surrounding operation. Gas refills and repricing can undermine these protections by allowing a failure handler to complete where it previously reverted. Depending on the contract, this could turn an operation that should remain retryable into a permanent failure.</p><p>Contracts warrant particular review are those that continue after a failed subcall, for example to record a permanent failure, process batches or switch to a fallback, as well as proxies and intermediaries. Protocol teams should:</p><ul><li>recalculate the gas their failure paths need under both Osaka and Glamsterdam rules</li><li>check for storage slots that are set and cleared within the same transaction</li><li>revalidate fixed gas budgets and thresholds against the proposed costs and gas-accounting rules</li><li>test direct and nested subcall failures, including out-of-gas failures across different gas budgets and reservoir balances, and verify that insufficient gas cannot permanently disable retries or invalidate otherwise valid claims</li></ul><p>The impact depends on each contract’s execution path and failure handling. The 13 examples identified so far do not establish the full scope: as we explained in the <a href="https://eipsinsight.com/calls/acde/248">core developers’ discussion</a>, our search was not exhaustive.</p><p>The postponement gives protocol teams time to review their failure-handling safeguards under the proposed rules. For technical details, read <a href="https://www.chainsecurity.com/blog/glamsterdam-gas/">Glamsterdam Hard Fork: When Spent Gas Comes Back</a>.</p><p>If you are unsure whether your protocol is affected, the ChainSecurity team can help: <a href="/service/mailto:glamsterdam@chainsecurity.com">glamsterdam@chainsecurity.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb5ee8bfe183" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beware of Undefined Behavior! — Underhanded Solidity Contest Winner 22]]></title>
            <link>https://medium.com/chainsecurity/beware-of-undefined-behavior-underhanded-solidity-contest-winner-22-42c6a52e2a8?source=rss-8b14ef67c636------2</link>
            <guid isPermaLink="false">https://medium.com/p/42c6a52e2a8</guid>
            <dc:creator><![CDATA[ChainSecurity]]></dc:creator>
            <pubDate>Wed, 13 Apr 2022 14:44:45 GMT</pubDate>
            <atom:updated>2022-04-13T14:44:45.088Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beware of Undefined Behavior! — Underhanded Solidity Contest Winner 22</h3><p>This year’s Underhanded Solidity Contest featured <a href="https://github.com/ethereum/solidity-underhanded-contest/tree/master/2022/submissions_2022">many great submissions</a> highlighting quirks in Solidity which can bite developers and auditors. We are proud to be <a href="https://twitter.com/solidity_lang/status/1491470227187634178">among excellent company</a> as judges for this contest, and even more so that this year the submission of Tynan, one of our Blockchain Security Engineers, <a href="https://twitter.com/solidity_lang/status/1512828084784971780">won the contest</a> for abusing a little known quirk in Solidity. This behavior, among others, was analyzed by Tynan as part of his ETH Zurich thesis in collaboration with ChainSecurity. In the following we are describing issues with undefined behavior in Solidity and how it was used to craft a benign-looking but malicious AMM smart contract for the 2022 Underhanded Solidity contest.</p><h4>Undefined Behavior</h4><p>Undefined behavior is a term many developers have likely encountered before. But what exactly does it mean? When using a programming language that has multiple competing compilers, it is vital to have a language specification in order for the same program to yield the same output regardless of which compiler is used. However, if the language specification is not precise enough, or intentionally leaves some edge cases out, this means that each compiler can decide for itself how to deal with certain situations. For example, in C the result of integer division by 0 is undefined.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aca5967aeda3a7ef233c1cc481c90472/href">https://medium.com/media/aca5967aeda3a7ef233c1cc481c90472/href</a></iframe><p>This means that each C compiler can decide to compile this code however it likes. Usually, this means either choosing the most convenient way, or throwing an error. However, the compiler could also do something completely different and still be a ‘correct’ implementation of the C language.</p><p>As a developer, it is important to avoid such undefined behavior. It means you no longer have complete control over the compiled code. While most of the time, one would expect that only obscure edge cases are left unspecified, in some cases it’s easier to trigger undefined behavior than you might expect.</p><h4>Undefined Behavior in Solidity</h4><p>The situation regarding Solidity is slightly different than C. There is only one Solidity compiler, and the language specification is evolving alongside it. This is not necessarily unusual, but it has lead to some quirky behaviors.<br>For example, when using contract inheritance, it is not specified whether first all state variables are initialized, or whether the state variables are simply initialized just before running the constructor of the contract they belong to. This is well demonstrated by this example from the Solidity docs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1de669646b6fd9ef2296304f18cad864/href">https://medium.com/media/1de669646b6fd9ef2296304f18cad864/href</a></iframe><p>Of course, this example is quite contrived; it’s unlikely someone would actually create a contract with this structure. Additionally, as long as the compiler doesn’t change how it handles this behavior, it doesn’t actually matter if you rely on its handling of this case.<br>Unfortunately, depending on whether you use the default compiler settings, or the new experimental compilation which goes through the Yul intermediate representation, you can get either behavior. Given the Yul pipeline is eventually supposed to replace the current one, it is important that developers do not rely on these behaviors.</p><h4>Evaluation Order</h4><p>Why does undefined behavior matter if we only run into it in specifically constructed examples? Alas, <a href="https://docs.soliditylang.org/en/v0.8.13/control-structures.html#order-of-evaluation-of-expressions">as we can see in the Solidity docs</a>, the evaluation order of expressions is unspecified. What this means is that sub-expressions within another expression can be evaluated in any order. For example, let’s take a look at the expression f(g(...), h(...)). Of course, g and h need to be evaluated before f , since it depends on their outputs. However, the evaluation order could be g -&gt; h -&gt; f or h -&gt; g -&gt; f.<br>If g and h do not have side effects, everything is fine. If they read/write memory, storage, or make an external call, we can quickly run into issues.</p><p>uint256 i = 0;<br>f(i, i++);</p><p>In this example, intuitively we might expect the result to be f(0, 0). However, the compiler could also choose to evaluate i++ before i, so the result could be f(1, 0) while still be following the language specification. Naturally, this doesn’t matter too much unless the Solidity compiler actually does sometimes evaluate expressions in an unexpected order.</p><h4>addmod and mulmod</h4><p>The first case we will look at are addmod and mulmod. These are not functions you see very often in Solidity code, but they are globally available in any Solidity contract. addmod(a, b, N) simply calculates (a + b) mod N , whereas mulmod(a, b, N) calculates (a * b) mod N. But what happens when N = 0? At the EVM level, the respective opcodes simply return 0. The Solidity team didn’t want this potentially unexpected result to be exposed to the developer, so they assert that N != 0 and revert otherwise. If this check fails, there is no need to evaluate a and b, so the compiler evaluates the arguments in right-to-left order. Hence, the following example results in 1, as a++ is evaluated first.</p><p>uint256 a = 1; <br>addmod(a, a++, 2);</p><h4>Events</h4><p>The situation with events is more complicated. An event can have indexed and non-indexed parameters. Again, when emitting an event, the evaluation order of nested expressions is unspecified. In this case, the compiler chooses to first evaluate the indexed parameters in right-to-left order, followed by the non-indexed parameters in left-to-right order. Thus, the following example evaluates in the order h -&gt; f -&gt; g -&gt; i.</p><p>event Hello(uint indexed a, uint b, uint indexed c, uint d); <br>emit Hello(f(...), g(...), h(...), i(...))</p><p>To complicate things further, compilation via the Yul IR tries to evaluate everything in left-to-right order, but does not guarantee it. Therefore, the examples mentioned above do yield the expected behavior if you specify the --experimental-via-ir compiler option. In fact, there are many small differences between the default compilation and the experimental Yul compiler. The Solidity team has compiled a list of such differences <a href="https://docs.soliditylang.org/en/v0.8.13/ir-breaking-changes.html">here</a>.</p><h4>Underhanded Solidity</h4><p>While it’s unlikely that undefined behavior leads to an accidental exploit in a smart contract, this doesn’t stop bad-faith developers from intentionally introducing them. This was demonstrated by the winning submission to the Underhanded Solidity Contest 2022.<br>The submission is a relatively simple decentralized exchange. It implements a constant product trading system. Each trade accrues some fees, which are put into the liquidity pool. The owner of the exchange can claim an admin fee, which is calculated based on the increase in liquidity since the last time the fee was claimed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b142ced92ca87947391f704bb90b427/href">https://medium.com/media/9b142ced92ca87947391f704bb90b427/href</a></iframe><p>Importantly, this calculation means that admin fees can be claimed retroactively — if the owner changes the fees and then claims them, the liquidity accrued before the claim will still be included in the calculation.<br>In order to mitigate this, the admin fee changing process forces the owner to claim fees when changing them. Additionally, there is a 7 day waiting period where the admin can’t claim fees, in order to allow liquidity providers to withdraw their funds before the higher funds are claimed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f05269d1363ee68101064824d7665b27/href">https://medium.com/media/f05269d1363ee68101064824d7665b27/href</a></iframe><p>However, as we have seen, indexed event parameters are evaluated right-to-left. This means that setNewAdminFee is executed before retireOldAdminFee. As a consequence, the fees for the previous period are actually claimed with the newly set one! In fact, in this particular contract there is no maximum admin fee, so the owner can set an arbitrarily high fee in order to drain the entire underlying balances.</p><h3>Closing remarks</h3><p>For a dive into what the other winners were able to use, take a look at the <a href="https://blog.soliditylang.org/2022/04/09/announcing-the-underhanded-contest-winners-2022/">excellent summary</a> from the Solidity team. If you are interested to work with us on uncovering quirks in blockchain-based systems, reach out to <a href="/service/mailto:jobs@chainsecurity.com">jobs@chainsecurity.com</a> and if you require a smart contract audit or other assurance that your blockchain project is secure, get in touch with us at <a href="/service/mailto:info@chainsecurity.com">info@chainsecurity.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42c6a52e2a8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chainsecurity/beware-of-undefined-behavior-underhanded-solidity-contest-winner-22-42c6a52e2a8">Beware of Undefined Behavior! — Underhanded Solidity Contest Winner 22</a> was originally published in <a href="https://medium.com/chainsecurity">ChainSecurity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TrueUSD ↔ Compound Vulnerability]]></title>
            <link>https://medium.com/chainsecurity/trueusd-compound-vulnerability-bc5b696d29e2?source=rss-8b14ef67c636------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc5b696d29e2</guid>
            <category><![CDATA[trueusd]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[compound-finance]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[bugs]]></category>
            <dc:creator><![CDATA[ChainSecurity]]></dc:creator>
            <pubDate>Mon, 21 Mar 2022 16:16:26 GMT</pubDate>
            <atom:updated>2022-03-21T16:16:26.801Z</atom:updated>
            <content:encoded><![CDATA[<p>TrueUSD (TUSD) is a stablecoin on the Ethereum blockchain. Until recently, it had multiple entry points, which could cause issues for various protocols. We discovered such an issue in our <a href="https://chainsecurity.com/security-audit/compound-ctoken/">audit</a> of the Compound cToken contract. The issue, with several millions at risk, has been mitigated by Compound and <a href="https://openzeppelin.com/">OpenZeppelin</a> and a detailed write-up can be found <a href="https://blog.openzeppelin.com/compound-tusd-integration-issue-retrospective/">here</a>.</p><h4>The Source of the Problem</h4><p>How can a contract have multiple entry points? Well, a single contract can’t. In the case of TUSD, there were in fact two <em>different</em> contracts that both interact with the same balances. Essentially, the real implementation of TUSD is at the address 0x0000000000085d4780b73119b644ae5ecd22b376, and the secondary entry point 0x8dd5fbce2f6a956c3022ba3663759011dd51e73e simply forwards any calls to the primary contract. From an external point of view, this means that interacting with one of the contracts affects the balances of both. In most cases, this is not a problem, because you just supply one of the addresses to your contract and ignore the other. However, if you interact with both, you can run into issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*iIJHCQ-XiXl1b8hpBDvCrQ.png" /><figcaption>Interacting with either contract will modify the same token balances</figcaption></figure><h4>The Dangers of Interacting with Arbitrary Contracts</h4><p>Why would a developer ever want to interact with two different addresses of the same token? Well, of course they wouldn’t. In fact, it never even makes sense to interact with the secondary address, since the cost will be higher and the outcome is the same. Hence, there is no well-meaning reason to call the secondary contract. But, if your contract can make calls into arbitrary addresses, this can be abused. In the specific case of Compound, the following function was susceptible to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b396a21d6a078ea394d3c07ec4a43d5/href">https://medium.com/media/2b396a21d6a078ea394d3c07ec4a43d5/href</a></iframe><p>As you can see, an arbitrary address of a contract that implements the transfer and balanceOf functions can be supplied. Interestingly, this function was only added so that users who accidentally transferred their tokens to the contract could rescue them.</p><p>So, how can we exploit this function? Let’s take a closer look at it. First, we make sure that the token we are sweeping is not the underlying token of the CToken contract. Next, we check the balance of our contract and transfer any funds it might have to the admin. Recall that TUSD has two entry points — if the underlying token is the primary TUSD address, but we call this function with the secondary address, the require condition will pass. Hence, the contract will transfer its entire underlying balance to the admin address. Luckily, the developers had the foresight to at least transfer the tokens to the administrator, otherwise this exploit would have been far worse.</p><h4>How This Exploit Can Be Abused</h4><p>Initially, it seems we can only transfer the underlying funds to the admin. This would effectively disable the contract, as no more funds could be borrowed or withdrawn, at least until the funds can be returned. While harmful, this is more of a griefing exploit and not profitable for the attacker. What else is affected by the missing funds? The exchange rate of the cTUSD token is calculated as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc4f84dcc2143d027487a6a91c65850f/href">https://medium.com/media/bc4f84dcc2143d027487a6a91c65850f/href</a></iframe><p>The exchange rate of TUSD / cTUSD is defined as:<br>(totalCash + totalBorrows - totalReserves) / totalSupply <br>Here, totalCash is the total amount of TUSD in the contract, totalBorrows is the amount of TUSD borrowed from the contract, and totalReserves is the amount that belongs to the protocol. Lastly, totalSupply is the total amount of cTUSD that have been minted.<br>What happens to the exchange rate if all the underlying tokens are transferred away? It means that totalCash will be 0, the ratio of TUSD to cTUSD will drop and hence the value of cTUSD will suddenly precipitously drop. Later, when the funds are returned, the exchange rate will suddenly jump back to its initial value. How can an attacker profit? There are several options:</p><ol><li>Liquidate users who provided TUSD as collateral for their loans.</li><li>Borrow TUSD, execute the attack, then pay back less TUSD.</li><li>Execute the attack, then mint cTUSD. When the funds are returned to the contract, redeem the cTUSD for a profit.</li></ol><p>Currently, TUSD can not be used as collateral, so the first attack does not work.<br>At the time we discovered this exploit, the second attack would have yielded a profit of around 12% of the TUSD contained in the contract, which would have been around $3.1 million. Since then, the amount of funds in the contract has only increased.</p><h4>How To Avoid This Issue</h4><p>During our audit sweepToken function behind admin privileges. Since the funds are transferred to the admin anyway, their involvement is necessary regardless, so they might as well execute the call themselves. Of course, this may not be the right fix in all cases. A more generally applicable fix could be the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d05513800254a9fd82772e78f047df8a/href">https://medium.com/media/d05513800254a9fd82772e78f047df8a/href</a></iframe><p>Essentially, what we’re doing is checking that the contract’s underlying balance stays the same before and after the sweep. This does incur additional costs due to the cross-contract calls, but means we never have to worry about any other token with multiple entry points.</p><h4>Conclusion</h4><p>In the meantime, the secondary TUSD contract has been disabled, so the token now only has a single entry point. Naturally, this does not mean that this vulnerability can never arise again, as there might be more tokens out there with multiple entry points. For example, Tether USD (USDT) could enable a secondary entry point in the future when upgrading their contract. As a consequence, great care should be taken when calling into arbitrary contracts. If the caller can specify any contract that happens to conform to your required interface, you should expect that anything can happen.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc5b696d29e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chainsecurity/trueusd-compound-vulnerability-bc5b696d29e2">TrueUSD ↔ Compound Vulnerability</a> was originally published in <a href="https://medium.com/chainsecurity">ChainSecurity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TotalSupply Inconsistency in ERC1155 NFT Tokens]]></title>
            <link>https://medium.com/chainsecurity/totalsupply-inconsistency-in-erc1155-nft-tokens-8f8e3b29f5aa?source=rss-8b14ef67c636------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f8e3b29f5aa</guid>
            <dc:creator><![CDATA[ChainSecurity]]></dc:creator>
            <pubDate>Fri, 12 Nov 2021 15:51:57 GMT</pubDate>
            <atom:updated>2021-11-12T20:34:34.479Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Article written by </strong><a href="/service/mailto:matthias.egli@chainsecurity.com"><strong>Matthias Egli</strong></a><strong>, CTO of ChainSecurity</strong></p><p>On November 1st, 2021, we reported a vulnerability to OpenZeppelin in which the totalSupply can appear lower than it actually is for ERC1155 NFT tokens. This affects projects relying on totalSupply for calculations, e.g. when voting or determining market caps. All tokens utilizing the <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/extensions/ERC1155Supply.sol">ERC1155Supply.sol</a> extension prior to v4.3.2 are affected. The vulnerability was promptly <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2956">fixed</a> and publicly disclosed on November 12th. We want to thank the OpenZeppelin team around <a href="/service/mailto:frangio@openzeppelin.com">Francisco Giordano</a> for their excellent collaboration and responsiveness on this issue.</p><h3>Background — ERC1155 inner workings</h3><p>ERC1155 tokens implement the “Multi Token Standard” in which both fungible (ERC20-like) and non-fungible (ERC721-like) tokens can be handled by a single contract. The standard allows to create non-fungible tokens with unique IDs, but allowing each one to have multiple instances, making them fungible among themselves.</p><p>The <a href="https://eips.ethereum.org/EIPS/eip-1155">EIP-1155</a> standard does not contain a need to track totalSupply for the fungible tokens on the smart contract level and opts to suggest projects to track events to keep a count of the total number of tokens existing. While this works well for some use-cases, others require to know on-chain the total amount of tokens issued. To facilitate this, OpenZeppelin provides an extension to ERC1155 called <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/extensions/ERC1155Supply.sol">ERC1155Supply.sol</a> which adds the totalSupply field known from ERC20 tokens to ERC1155 tokens. This field is updated whenever tokens are <a href="https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/v4.3.2/contracts/token/ERC1155/extensions/ERC1155SupplyUpgradeable.sol#L51">minted</a> or <a href="https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/v4.3.2/contracts/token/ERC1155/extensions/ERC1155SupplyUpgradeable.sol#L78">burned</a>.</p><p>Another feature of ERC1155 is to allow receivers of tokens to be notified, which can enable interesting use-cases in the composable Ethereum universe. The downside is that control flow is handed over to untrusted parties, allowing the infamous reentrancy attacks. Due to this, every project handling ERC1155 tokens (and ERC712 tokens) must be careful to protect against these attacks.</p><h3>The ERC1155Supply vulnerability explained</h3><p>The following code snippet presents a simplified view of the functions involved in minting new tokens:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35a29492e37dca9a524a9ba7313122c3/href">https://medium.com/media/35a29492e37dca9a524a9ba7313122c3/href</a></iframe><p>ERC1155 first does some checks in beforeTokenTransfer (L12), then mints the new tokens to the receiver (L14) who is allowed to do an acceptance check (L17). The acceptance check is implemented in L29 by calling onERC1155Received on the receiver smart contract, handing over control flow to the receiver.</p><p>ERC1155Supply adds tracking of totalSupply by first calling ERC1155 mint method and then increasing the totalSupply. The crucial part here is that before the totalSupply is increased, control flow is given to the receiver as part of the normal ERC1155 minting. At this stage, an attack already has tokens which they can e.g. use to vote, but the totalSupply has not yet been increased, potentially allowing the attack to pretend to have a higher share of tokens than they really should have (including having a share bigger than the totalSupply which could lead to other attacks if applications assume that totalSupply &lt;= balance[any_user] ). Technically, this is a light form of a re-entrancy attack as the attack would just re-enter the totalSupply view function and not modify any state. This is frequently seen as a “benign reentrancy”, but in this case can lead to real attacks.</p><p>What to do</p><p>For the attack to be exploitable, the mint function must be called with untrusted receivers. While this is usually the case for dynamically mintable tokens, be aware that this can also happen in case the token isn’t generally minted to untrusted receivers, but bridged to side-chains like Polygon. In this case a transfer of tokens from Ethereum to the side-chain usually triggers mint on the EIP1155 contracts on the side-chain.</p><p>If you are <strong>in charge of an ERC1155 token</strong> implementing ERC1155Supply, consider upgrading to the newly released version of <a href="https://www.npmjs.com/package/@openzeppelin/contracts-upgradeable/v/4.3.3">OpenZeppelin v4.3.3</a> or newer. If upgrading is not possible, add a warning to your documentation for integrators to make them aware of the Security Advisory.</p><p>If you are <strong>in charge of a platform handling ERC1155 tokens</strong> which implements the ERC1155Supply extension and which allows minting from anyone, you cannot rely on totalSupply from these tokens anymore and need to prepare an alternative implementation.</p><p><strong>Any project</strong> utilizing OpenZeppelin or other commonly used libraries should make sure that they report on which libraries are used in the <a href="https://blog.openzeppelin.com/smart-contract-security-registry/">Smart Contract Security Registry </a>and also make sure that their security contact details are up to date.</p><p>If you are a holder of an ERC1155 token affected by this vulnerability, no immediate action is needed as your tokens remain safe as long as they aren’t used in a platform vulnerable to this attack. If you aren’t sure about the safety of the platform, withdraw your tokens and reach out to the platform to ask them to confirm if they are safe against this vulnerability.</p><h3>About us</h3><p>ChainSecurity’s mission is to build trust within the blockchain ecosystem, to allow this emerging technology to reach its potential among established organizations, governments and blockchain companies alike.</p><p>If you have questions, don’t hesitate to reach out to <a href="/service/mailto:contact@chainsecurity.com">contact@chainsecurity.com</a> for general requests including requests for audits, and to <a href="/service/mailto:help@chainsecurity.com">help@chainsecurity.com</a> for questions about this or other vulnerabilities. Also, visit us on <a href="https://chainsecurity.com/">chainsecurity.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f8e3b29f5aa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chainsecurity/totalsupply-inconsistency-in-erc1155-nft-tokens-8f8e3b29f5aa">TotalSupply Inconsistency in ERC1155 NFT Tokens</a> was originally published in <a href="https://medium.com/chainsecurity">ChainSecurity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is DeFi worth the risk?]]></title>
            <link>https://medium.com/chainsecurity/is-defi-worth-the-risk-3f9769fbd909?source=rss-8b14ef67c636------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f9769fbd909</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[investment]]></category>
            <category><![CDATA[cryptocurency]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[ChainSecurity]]></dc:creator>
            <pubDate>Wed, 21 Apr 2021 16:34:11 GMT</pubDate>
            <atom:updated>2021-05-18T05:59:52.656Z</atom:updated>
            <content:encoded><![CDATA[<p>Originally published on February 15th, 2021 by Nico Schäfer, Senior Engineer for ChainSecurity</p><p><strong>The skyrocketing prices of cryptocurrencies — including Bitcoin and Ethereum — are drawing increased attention to the cryptocurrency market. And, this in turn, becomes a catalyst for growth of projects on these underlying distributed ledger networks. With a vast array of finance-based projects emerging (e.g. lending protocols, stablecoins, derivatives, exchanges), investors want to be better informed in terms of risk. When researching Decentralised Finance (DeFi) projects, investors easily find claims about the potential for huge returns, and, on the flip side, news about hacked smart contracts, scams and other fraudulent behaviour. However, quantifying the opportunities and risk associated with an investment is far more complicated than these headlines make it out to be.</strong></p><p>2020 was a landmark year for DeFi. We saw promises of unbelievable returns and headlines about ‘hacks’ with amounts in the tens of millions. Known incidents [1] in 2020 are estimated at over $200 million, with about 50% of the value recovered after the fact. The majority of these incidents happened in the last months of the year. This fourth quarter surge is an indication of the increased scrutiny of, and vulnerability of the DeFi industry as it gains momentum and grows at an unprecedented pace.</p><figure><img alt="DeFi hacks in 2020, DeFi exploits, Decentralized Finance security, smart contract security, smart contract exploits, smart contract hacks, how much money was stolen in DeFi in 2020 ?, How much did DeFi hackers stole ?, is DeFi safe ?," src="https://cdn-images-1.medium.com/max/685/1*j2uKNAUquTK0z-76hJccnw.png" /><figcaption>Thanks to Kimberly Liu for this amazing graphic.</figcaption></figure><p>So, what does this all mean? If you’re an investor interested in exploring the DeFi space, it’s about whether opportunities in the DeFi space outweigh the risk.</p><p><strong>What are the risks of investing in DeFi?</strong></p><p>Given the accelerated rise of DeFi, it’s not nearly as mature as institutional investing — yet having an understanding of the types of risk can give an investor a better picture of what’s at stake. Though not a comprehensive list, here is some food for thought.</p><p><strong>Who’s accountable?</strong></p><p>In traditional finance, you know your counterparty. And, if a company acts fraudulently, you can legally prosecute them. The regulators further minimise risk by enforcing proper risk management, appropriate insurances and requirements regarding physical and software security. However, DeFi projects aren’t regulated like traditional finance projects and are, by nature, decentralised. As an example, the term ‛rug pulling’ has emerged to describe the sudden disappearance of project members with user funds. Recent examples are Compounder.Finance, Yfdex.Finance and SharkTron, to name a few. In these cases, the projects were neither managed nor owned by an identifiable party that could be prosecuted. At the end of the day, do you know who’ll be held accountable when things go south?</p><p><strong>Who’s keeping an eye on DeFi?</strong></p><p>Many DeFi projects are still in a ‛trial and error’ phase, experimenting in an ecosystem where generally accepted industry standards are still lacking. To add to this, regulations are lagging behind the technology in most, if not all, countries. This means DeFi projects do not need to undergo the same level of risk requirements as traditional financial projects. Without regulatory oversight, who’s keeping an eye on DeFi?</p><p><strong>‛Code is law’, or is it?</strong></p><p>In traditional finance, trust is built by the institution and the regulators overseeing it. In blockchain, however, trust is built within publicly available immutable code. Some users even go as far as to say ‛code is law’, implying that whatever blockchain technology allows is also legal. This is not the case, but it highlights the importance of legally defining what role a smart contract can play in the blockchain.</p><p><strong>More layers, more vulnerabilities</strong></p><p>DeFi projects are built on huge stacks of technologies, with each layer adding more potential attack surfaces. Layers like the cryptographic principles, including their implementation, and the network layer have often been reviewed intensively. However, securing one layer doesn’t protect against vulnerabilities in other layers of the system. Taking a holistic, top-down view is critical to securing your project.</p><p><strong>Do you know where your keys are?</strong></p><p>If someone has your private key, they can steal all your wealth. Yet, at the same time, private keys are impossible to remember. An example in 2020 was when Nexus Mutual’s CEO Hugh Karp’s machine was compromised and crypto of approximately eight million USD was stolen. Can you store your keys in a way that you won’t lose access to it or forget it, and where no-one can access it?</p><p><strong>Is the solution to go back to centralisation?</strong></p><p>One might conclude that going back to centralised crypto management is the solution. Unfortunately, it’s not that simple. Users’ funds in centralised exchange have also fallen prey to hacks and mismanagement. To give you an idea of the amounts at stake, in 2020, centralised exchange KuCoin got hacked and $280 million were lost.</p><p><strong>Is DeFi worth the risk?</strong></p><p>As with all new ventures, it’s hard to understand the full breadth of risks. However, where there is risk, there is also opportunity. By knowing and managing the associated risks when entering the DeFi market, these new projects might be an interesting playground as well as a promising future technology. And, at the end of the day, the most tried and true risk management strategy still holds: diversification.</p><p>[1] In our inventory of ‛known incidents’ we capture events that were made public knowledge via media coverage, including the value of funds that were stolen (and, if applicable, the amount that was recovered). The value of funds stolen/recovered is based on what was publicly reported at the time of the incident. We have not included events where there was no financial impact.</p><p>— — — -</p><h4>More about us</h4><p>ChainSecurity’s mission is to build trust within the blockchain ecosystem, to allow this emerging technology to reach its potential among established organizations, governments and blockchain companies alike.</p><p>We have the capabilities to guide and support you wherever you are on the path — from exploring how you can use DLT and smart contracts and formal assessments of your smart contracts before they launch, to monitoring your smart contracts once they’re in place. If you want to know more about smart contract security or are interested in working with us, visit <a href="http://www.chainsecurity.com/">www.ChainSecurity.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f9769fbd909" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chainsecurity/is-defi-worth-the-risk-3f9769fbd909">Is DeFi worth the risk?</a> was originally published in <a href="https://medium.com/chainsecurity">ChainSecurity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PolPatrol — Validator for Polkadot Runtimes]]></title>
            <link>https://medium.com/chainsecurity/polpatrol-validator-for-polkadot-runtimes-c89a874c5d09?source=rss-8b14ef67c636------2</link>
            <guid isPermaLink="false">https://medium.com/p/c89a874c5d09</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[runtimes-validator]]></category>
            <category><![CDATA[automated]]></category>
            <category><![CDATA[polkadot]]></category>
            <category><![CDATA[web3-foundation]]></category>
            <dc:creator><![CDATA[ChainSecurity]]></dc:creator>
            <pubDate>Mon, 23 Dec 2019 15:25:52 GMT</pubDate>
            <atom:updated>2019-12-23T15:41:55.166Z</atom:updated>
            <content:encoded><![CDATA[<h3>PolPatrol — Validator for Polkadot Runtimes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EFjBWuYVLJaqqYpDz6TrLw.png" /></figure><p>ChainSecurity is happy to release PolPatrol, an <strong>automated validator for testing the stability and security of Polkadot relay chain runtimes with respect to generic security and performance properties</strong>. Since Polkadot’s relay chain runtime lies at the core of the Polkadot network, the current version of PolPatrol focuses on ensuring that relay chain runtimes are secure and functionally correct.</p><p>Peter Czaban, Executive Director of Web3 Foundation, said:</p><blockquote>“Polkadot Runtimes make it easier than ever before to flexibly describe and deploy blockchain logic. To ensure that this richness of capabilities leads to secure developments, we are committed to funding tools which can support developers during their creation. We are excited to work with a leading blockchain security firm ChainSecurity to research and develop new approaches to automated blockchain logic analysis”.</blockquote><p>Petar Tsankov, Chief Scientist of ChainSecurity, said:</p><blockquote>“We are dedicated to bringing to Polkadot’s developers and users practical and useful security tools that enable them to easily assess the safety and security of Polkadot. Starting with manual testing and random fuzzing of Polkadot Runtimes, we are looking forward to building further tools capable of deep security fuzzing and verification. We are grateful to Web3 Foundation for their support in this project”.</blockquote><h3>Who is PolPatrol for?</h3><p>Two user groups will primarily use PolPatrol:</p><ul><li>Developers of new relay chain runtimes who would like to test the correctness of their code.</li><li>DOT token holders who can vote on newly proposed relay chain runtimes and would like to check whether a proposed runtime is safe and secure.</li></ul><p>For both user groups, PolPatrol automatically analyzes any given relay chain Web assembly binary (or, a Wasm blob) and warns users upon violation of important security and performance properties.</p><h3>How can I use PolPatrol?</h3><p>The source code of PolPatrol is available at <a href="https://github.com/chainsecurity/polpatrol">https://github.com/chainsecurity/polpatrol</a>.</p><p>To learn how to install PolPatrol and how to run it on a custom relay chain runtime, please refer to the official documentation at <a href="https://polpatrol.ch/">https://polpatrol.ch/</a>.</p><h3>How does it work?</h3><p>PolPatrol uses an instrumented Polkadot runtime environment to run the provided relay chain runtime and log all calls that it makes to the environment. In addition to the calls, it also monitors essential performance metrics, such as execution time and memory usage. This enables PolPatrol to check relevant trace and performance properties. PolPatrol aggregates the collected runtime information to let developers draw conclusions on the overall behavior of the runtime and compare different implementations.</p><h3>What properties does PolPatrol check?</h3><p>The focus of PolPatrol is on performance and safety properties.</p><h4>Performance of runtime entries</h4><p>PolPatrol collects statistics about all calls to runtime entries and reports the total number of calls made while testing the run-time, the maximum execution time (in seconds), the maximum memory usage (in MB), and the maximum number of storage-related calls to the environment:</p><pre>====================================================================<br>Entry Name            | # Calls | Max Time | Max Mem | Max #Storage<br>--------------------------------------------------------------------<br>initialize_block      |      31 |   0.0324 |  68.294 |         59<br>execute_block         |      31 |   0.9438 |  72.484 |        341<br>inherent_extrinsics   |      31 |   0.0404 |  68.290 |          1<br>apply_extrinsic       |     109 |   0.6399 |  71.959 |         79<br>finalize_block        |      31 |   0.3210 |  69.862 |        110<br>====================================================================</pre><p>For example, the above sample output identifies that the initialize_block entry was called 31 times, each call took at most 0.0324 seconds and consumed at most 68.294 MB of memory, making at most 59 storage-related calls. We note that PolPatrol outputs additional metrics (not shown above), such as the mean execution time and mean memory usage.</p><h3>Performance of extrinsics</h3><p>PolPatrol also reports statistics about applied extrinsics, reporting the same metrics as the ones reported for environment entries:</p><pre>====================================================================<br>Entry Name               Max Time | Max Mem | Max Storage| Weight<br>--------------------------------------------------------------------<br>Balances::force_transf   0.031489 |  68.296 |         57 |  1000000<br>Balances::transfer       0.031372 |  68.296 |         66 |  1000000<br>Democracy::propose       0.028740 |  68.290 |         39 |  5000000<br>Council::execute         0.029009 |  68.290 |         47 |   100000<br>Slots::fix_deploy_data   0.028606 |  68.290 |         38 |   500000<br>Democracy::fast_track    0.028877 |  68.290 |         39 |   200000<br>ImOnline::heartbeat      0.026807 |  68.289 |         13 |    10000<br>Democracy::undelegate    0.029554 |  68.289 |         54 |   500000<br>Balances::set_balance    0.029181 |  68.290 |        102 |        0<br>Democracy::resign_proxy  0.028444 |  68.289 |         40 |   100000<br>Council::vote            0.030299 |  68.290 |        107 |   200000<br>Parachains::set_heads    0.028418 |  68.289 |         13 |  1000000<br>Democracy::set_proxy     0.028941 |  68.290 |         41 |   100000<br>Democracy::cancel_queu   0.028394 |  68.289 |         39 |    10000<br>Council::propose         0.029840 |  68.290 |         95 |  5000000<br>Democracy::external_pro  0.028710 |  68.290 |         39 |  5000000<br>Claims::claim            0.027391 |  68.289 |         11 |  1000000<br>Slots::new_auction       0.028643 |  68.290 |         56 |        0<br>Democracy::second        0.028793 |  68.289 |         40 |  5000000<br>Democracy::delegate      0.029207 |  68.290 |         52 |   500000<br>Democracy::vote          0.028790 |  68.289 |         40 |   200000<br>FinalityTracker::final   0.026426 |  68.289 |         13 |    10000<br>Democracy::cancel_refe   0.028563 |  68.289 |         39 |    10000<br>Democracy::remove_proxy  0.028664 |  68.290 |         41 |   100000<br>Council::set_members     0.029432 |  68.290 |         51 |        0<br>Democracy::emergency     0.028735 |  68.289 |         39 |   500000<br>Slots::elaborate_deploy  0.659817 |  71.959 |         51 |  5000000<br>Timestamp::set           0.028862 |  68.289 |         29 |    10000<br>Democracy::proxy_vote    0.028574 |  68.289 |         41 |   200000<br>Democracy::veto_external 0.028529 |  68.290 |         39 |   200000<br>Slots::bid               0.029268 |  68.289 |         57 |   500000<br>Democracy::external_prop 0.028528 |  68.290 |         39 |  5000000<br>====================================================================</pre><p>In addition to reporting the execution time, memory usage, and storage calls, PolPatrol also reports the assigned weight of each extrinsic. This allows developers and users to judge whether the weights are adequately defined based on the actual performance of the extrinsic.</p><h4>Safety properties</h4><p>Based on the performance information, PolPatrol checks several safety properties, such as:</p><pre>====================================================================<br>Maximum block execution time:   0.944 s   - OK<br>Maximum block memory:          72.484 MB  - OK<br>Maximum block length:           0.375 MB  - OK<br>====================================================================</pre><p>In particular, PolPatrol ensures that the maximum block execution time is below 2 seconds, the maximum block memory is below 10,000 MB and the block length does not exceed 10,000 MB (measured as bytes of a block, scale-encoded). Further safety properties can be easily added.</p><h3>Acknowledgments</h3><p>ChainSecurity would like to thank the Web3 Foundation for supporting the research and development of PolPatrol with a research grant.</p><h4>About Polkadot</h4><p>Polkadot is the first interoperability protocol that enables blockchain networks to work together under the protection of shared security.</p><p>For more information on Polkadot, visit <a href="https://polkadot.network/">polkadot.network</a>.</p><h4>About Web3 Foundation</h4><p>Established in Zug, Switzerland by Ethereum co-founder and Chief Technology Officer Dr. Gavin Wood, Web3 Foundation funds research and development teams building the stack of technologies behind the decentralized web.</p><p>For more information on Web3 Foundation, visit <a href="https://web3.foundation/">web3.foundation</a>.</p><h4>About ChainSecurity</h4><p>ChainSecurity provides security services and develops custom security solutions for blockchain projects.</p><p>Learn more about ChainSecurity at <a href="https://chainsecurity.com/">chainsecurity.com</a>.</p><p><em>Originally published at </em><a href="https://chainsecurity.com/polpatrol-validator-for-polkadot-runtimes/"><em>https://chainsecurity.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c89a874c5d09" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chainsecurity/polpatrol-validator-for-polkadot-runtimes-c89a874c5d09">PolPatrol — Validator for Polkadot Runtimes</a> was originally published in <a href="https://medium.com/chainsecurity">ChainSecurity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Istanbul Hardfork EIPs — Changing Gas Costs and More]]></title>
            <link>https://medium.com/@chain_security/https-medium-com-chain-security-istanbul-hardfork-eips-changing-gas-costs-903c74efc431?source=rss-8b14ef67c636------2</link>
            <guid isPermaLink="false">https://medium.com/p/903c74efc431</guid>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[ChainSecurity]]></dc:creator>
            <pubDate>Fri, 04 Oct 2019 19:51:01 GMT</pubDate>
            <atom:updated>2019-10-15T08:19:06.065Z</atom:updated>
            <content:encoded><![CDATA[<h3>Istanbul Hardfork EIPs — Changing Gas Costs and More</h3><p>The Ethereum network will soon have its next hardfork called Istanbul. Many Ethereum Improvment Proposals (EIPs) were submitted to be included in that hardfork. Six EIPs have been accepted for Istanbul, but due to the large number of proposals eight have been tentatively accepted and will likely be part of another hardfork, called Berlin. The list of proposed EIPs can be found <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1679.md">here</a>.</p><p>In this article we will briefly touch on some of the EIPs of the Istanbul hardfork while going into more detail about EIP-1884, which ChainSecurity has been researching.</p><p>Let us start with an overview of the accepted EIPs and then dive deeper into EIP-1884.</p><p><strong>EIP-152</strong> will add a new Blake2b precompile to the EVM. This is a hashing function similar to keccak256 but <a href="https://crypto.stackexchange.com/questions/31674/what-advantages-does-keccak-sha-3-have-over-blake2">said to be faster in general purpose solutions</a>. It is also what is used by Zcash and therefore allows interoperability with Zcash on the Ethereum main network.</p><p><strong>EIP-1344</strong> will add a new CHAINID opcode which returns the id of the current chain. Recall that there are multiple Ethereum chains exist which differ in their id, e.g. mainnet has id 1 and ropsten has id 3. This will help prevent pre-signed data from being replayed on different chains. If a contract accepts pre-signed data which it validates by using ecrecover, it can now also include the chain id in the pre-signed data. By checking that this chain&#39;s id matches the current chain&#39;s id of the Ethereum node replay attacks on different chains are prevented.</p><p><strong>EIP-1884</strong> Due to the growth of the Ethereum state certain opcodes now are more resource-intensive than they used to be. Therefore, EIP-1884 raises the gas costs for the trie-size-dependent opcodes:</p><ul><li>SLOAD: gas cost changes from 200 to 800 gas;</li><li>BALANCE: gas cost changes from 400 to 700 gas;</li><li>EXTCODEHASH: gas cost changes from 400 to 700 gas.</li></ul><p>Furthermore, the EIP will introduce a new opcode:</p><ul><li>SELFBALANCE: BALANCE of current contract, 5 gas.</li></ul><p><strong>EIP-1108</strong> reduces the gas cost of the alt_bn128 precompile contract. Client implementation have gotten more efficient implementations for this precompiled contract which allows the gas reduction and makes it cheaper to perform cryptographic operations on-chain.</p><p><strong>EIP-2028</strong> reduces the gas cost per non-zero byte of calldata from 68 to 16. Calldata is the input data that is passed to a transaction. Hence, transactions with a lot of input data, e.g. contract deployments and proof verifications, will become considerably cheaper.</p><p>Shortly before the previous Constantinople hardfork a bug was found in EIP-1283. EIP-1283 decreased the gas cost of writing to <em>dirty</em> storage slots within a single transaction. This made a reentrancy <a href="https://medium.com/chainsecurity/constantinople-enables-new-reentrancy-attack-ace4088297d9">possible</a> in certain cases. Due to this, EIP-1283 was retracted from the Constantinople hardfork. With the upcoming Istanbul hardfork an updated version of this EIP will be added, namely EIP-2200.</p><p><strong>EIP-2200</strong> is identical to EIP-1283, except for two changes. First, due to the previously described gas cost increase of SLOAD, the gas cost of updating a <em>dirty</em> storage slot has also been increased from 200 to 800. Secondly, to prevent the reentrancy bug a check is added that disallows an SSTORE to be executed if the gasleft is 2300 or less.</p><p><strong>EIP-152</strong><br>This EIP simply adds more functionality and flexibility. There are no known security problems with BLAKE2.</p><p><strong>EIP-1344</strong><br>With the new opcode CHAINID it now becomes possible to prevent replaying pre-signed data on multiple chains. It won&#39;t take long before Solidity adds a global variable to execute this opcode, e.g. chainid(). If a contract verifies pre-signed data using ecrecover we would expect the chain id to be included in the pre-signed data, as well as a check that it matches the current chain id. This EIP seems to add value and is great for signature schemes as it provides additional context which is generally good for signatures.</p><p><strong>EIP-2200</strong><br>With SSTORE being cheaper for dirty slots, certain transactions will become cheaper. For new contracts the effect might be limited, as the solidity compiler has become better at optimizing multiple storage writes into a single storage write. As there is now a cheaper way to perform state changes developers need to stop using .gas(5000) to protect against state changes. Instead they should try to use STATICCALL, which provides EVM-level protection against state changes in the called contract.</p><p><strong>EIP-1884</strong></p><p>The Ethereum blockchain grows with time as it is recording all important information. As you can see below the chain data size of the parity client increased by roughly 50% since the beginning of the year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*KE_SuGKSi4kIJmP04Nnjng.png" /></figure><p>More information in the database results in increasing lookup times and hence, increasing verification times. Below you see an <a href="https://github.com/holiman/vmstats">analysis</a> from Martin Holst Swende. The black line shows the average relation between gas costs and execution costs. As it is going up over time the SLOAD operation becomes &quot;too cheap&quot; relative to its execution cost, hence the EIP proposes to raise the cost for SLOAD and other opcodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CVZcNk_k0h_E8k00IfjlBw.png" /></figure><p>Such mismatches between gas and execution costs open the door for denial-of-service attacks. Hence, EIP-1884 proposes to increase the gas cost. This sounds reasonable given the increased computational work needed to look entries up in the growing database. Nevertheless, increasing the gas cost for certain operations has certain side effects. Hubert Ritzdorf and other security engineers found multiple smart contracts which indirectly assume a fixed gas price. If for example a function can be executed with the current stipend of 2300 gas, it may not execute anymore because it exceeds the gas stipend. Therefore, <strong>EIP-1884 is not backward compatible</strong>. It needs to be mentioned, that this is not the first time that the gas price has been adjusted for SLOAD. The gas cost of SLOAD was raised from 50 to 200 in October 2016.</p><p>The following examples illustrate cases where contracts would break for two main causes: 1) Fallback function which consumes close to the current gas stipend and 2) Providing a fixed amount of gas to a function call. We do not intend to blame the developers as they, in most cases, followed best practices. For more examples, see <a href="https://gist.github.com/ritzdorf/1c6bd72955391e831f8a397d3152b4e0">here</a>.</p><p><strong>Fallback function which consumes close to the current gas stipend</strong><br> Most commonly the contracts use a fallback function which consumes a little less than the current gas stipend. Some famous code examples are:</p><p><a href="https://etherscan.io/address/9ae49c0d7f8f9ef4b864e004fe86ac8294e20950#code">KyberNetwork</a></p><pre>function() public payable {<br>        require(reserveType[msg.sender] != ReserveType.NONE);<br>        EtherReceival(msg.sender, msg.value);<br>}</pre><p><a href="https://etherscan.io/address/0x0a74d136fafed0f8d58ce4b7307283695ec7a0b6#code">Aragon’s DepositableDelegateProxy</a></p><pre>    function isDepositable() public view returns (bool) {<br>        return DEPOSITABLE_POSITION.getStorageBool();<br>    }<br>    event ProxyDeposit(address sender, uint256 value);<br>    function () external payable {<br>        // send / transfer<br>        if (gasleft() &lt; FWD_GAS_LIMIT) {<br>            require(msg.value &gt; 0 &amp;&amp; msg.data.length == 0);<br>            require(isDepositable());<br>            emit ProxyDeposit(msg.sender, msg.value);<br>        } else { // all calls except for send or transfer<br>            address target = implementation();<br>            delegatedFwd(target, msg.data);<br>        }<br>    }</pre><ul><li>This function checks how much gas was provided and if it was called with 2300 gas, it only consumes 1759 gas. its execution contains one SLOAD due to isDepositable(). Therefore, it <strong>will break</strong> with EIP-1884 as the new gas cost would be 2359 gas;</li><li>Aragon is aware of the issue and has fixed it, more information is available <a href="https://github.com/aragon/aragonOS/issues/549">here</a></li></ul><p><strong>Providing a fixed amount of gas to a function call</strong></p><ul><li><a href="https://www.totle.com/">Totle</a> combines multiple Decentralized Exchange Platforms (e.g. KyberSwap);</li><li>When the TotlePrimary contract executes, it internally calls getDecimals on the target token contract. As part of this call, getDecimals only passes 5000 gas as seen above. If the traded token is Augur&#39;s REP token, the <a href="https://etherscan.io/address/0x1985365e9f78359a9b6ad760e32412f4a445e862#code">Delegator</a> will be called. This call currently consumes 4511 gas and successfully returns 18. However, this call also contains three invocations of SLOAD so it will cost 6311 after the activation of the Istanbul hardfork. Hence, it <strong>will break</strong> after the hardfork;</li><li>As certain tokens do not implement the decimals function the failing call (due to out-of-gas) will be interpreted as 0 decimals. As the decimals are used to calculate token quantities, <strong>incorrect token quantities will be computed</strong>. <strong>Threfore, the security check for the minimum rate could be circumvented</strong>;</li><li>Totle is aware of the <a href="https://github.com/TotlePlatform/contracts/issues/1">issue</a> and has provided a fix.</li></ul><p>Contract Library has also identified affected contracts through static analysis:<br><a href="https://contract-library.com/?w=FALLBACK_WILL_FAIL">https://contract-library.com/?w=FALLBACK_WILL_FAIL</a></p><p>Further security considerations on EIP-1884 can be found at:<br><a href="https://github.com/holiman/eip-1884-security">https://github.com/holiman/eip-1884-security</a></p><p><strong>Resulting imbalances in gas costs</strong></p><p><a href="https://medium.com/@agusx1211/evm-istambul-storage-pricing-5befaac32403">This analysis</a> highlights the resulting inconsistencies of the EIP-1884 gas cost changes. As SLOAD becomes more expensive, it is cheaper to read from another contract through EXTCODECOPY rather than reading from the currently executed contract through SLOAD. This might have to addressed in future hardforks.</p><p><strong>Conclusion &amp; Take-Aways</strong></p><p>In this hardfork gas prices will be adjusted to account for new realities. Certain transactions, e.g. on-chain STARK/SNARK verification, could become significantly cheaper. The increased gas costs for the increasing computational power needed to look up entries in the database breaks even popular contracts written according to best practices. This highlights the tension between protocol security and usability. From a usability perspective all changes should be backwards compatible but from a protocol security perspective certain changes will be necessary.</p><p>It has become clear that gas costs should not be assumed to be constant. This also has to be reflected in smart contract development. Hence, <a href="https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/">Consensys</a> and others have changed their recommendations and now recommend to use .call.value() instead of .transfer() in Solidity as it passes all of the available gas. This is the opposite recommendation that was given just a short time ago. However, when using .call.value() separate protection against reentrancies, e.g. a <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol">ReentrancyGuard</a>, is needed.</p><p><em>Originally published at </em><a href="https://chainsecurity.com/istanbul-hardfork-eips-increasing-gas-costs-and-more/"><em>https://chainsecurity.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=903c74efc431" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ChainSecurity joins the Capital Markets and Technology Association]]></title>
            <link>https://medium.com/chainsecurity/chainsecurity-joins-the-capital-markets-and-technology-association-b29a2d7a564e?source=rss-8b14ef67c636------2</link>
            <guid isPermaLink="false">https://medium.com/p/b29a2d7a564e</guid>
            <category><![CDATA[press-release]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[capital-markets]]></category>
            <category><![CDATA[membership]]></category>
            <category><![CDATA[dlt]]></category>
            <dc:creator><![CDATA[ChainSecurity]]></dc:creator>
            <pubDate>Tue, 27 Aug 2019 15:16:02 GMT</pubDate>
            <atom:updated>2019-08-27T15:24:34.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6SlCiUyLjuDxlRu6c1a8wQ.png" /></figure><p>ZURICH — 19 August, 2019 — We are pleased to announce that ChainSecurity has joined the Capital Markets and Technology Association (CMTA) whose members include well-known FinTech leaders such as Bank Vontobel, Mt Pelerin Group, and Taurus Group.</p><blockquote><em>“ChainSecurity brings critical smart contract security and audit expertise to the CMTA and we are happy to have them on board” comments Fedor Poskriakov, General Secretary of the CMTA.</em></blockquote><p>Established by Lenz &amp; Staehelin, Swissquote Bank Ltd, and Temenos AG, with the support of EPFL, the CMTA is a not-for-profit, non-governmental association, which aims to facilitate the use of distributed ledger technology (DLT) in the field of capital markets. The mission of the CMTA is to develop standards for the application of DLT in the field of finance, which aligns with ChainSecurity’s goal to promote the adoption of security standards and implementation of best practices for DLT.</p><blockquote><em>“At ChainSecurity we are excited to contribute our expertise in blockchain security, while gaining a deeper understanding of the marketplace and learn how to be more effective through collaboration” says Matthias Egli, COO of ChainSecurity. “We believe that we can accomplish this by fostering education and collaboration among the members and other industry stakeholders”.</em></blockquote><p><strong>About CMTA</strong></p><p>CMTA is an independent association formed by leading actors from Switzerland’s financial, technological and legal sectors to create common standards around issuing, distributing and trading securities in the form of tokens using the distributed ledger technology. To learn more about the Capital Markets and Technology Association, visit the website at <a href="http://www.cmta.ch/">www.cmta.ch</a>.</p><p><strong>About ChainSecurity</strong></p><p>ChainSecurity provides security services and develops custom security solutions for blockchain projects. Learn more about ChainSecurity at <a href="https://chainsecurity.com/">chainsecurity.com</a>.</p><p><em>Originally published at </em><a href="https://chainsecurity.com/chainsecurity-joins-the-capital-markets-and-technology-association/"><em>https://chainsecurity.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b29a2d7a564e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chainsecurity/chainsecurity-joins-the-capital-markets-and-technology-association-b29a2d7a564e">ChainSecurity joins the Capital Markets and Technology Association</a> was originally published in <a href="https://medium.com/chainsecurity">ChainSecurity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Dispatcher — First Line Of Defense In Any EOS Smart Contract]]></title>
            <link>https://medium.com/chainsecurity/https-medium-com-chain-security-the-dispatcher-first-line-of-defense-8aec1a6f7e7b?source=rss-8b14ef67c636------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aec1a6f7e7b</guid>
            <category><![CDATA[eos]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[dispatcher]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[ChainSecurity]]></dc:creator>
            <pubDate>Fri, 19 Jul 2019 11:07:22 GMT</pubDate>
            <atom:updated>2019-07-19T11:07:22.457Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Dispatcher — First Line Of Defense In Any EOS Smart Contract</h3><h4>Back in September 2018, an attacker managed to steal US$200 000 worth of EOS from the EOSBet contract. The attacker exploited a serious bug in a designated entry function of the contract, called the dispatcher. Moreover, the introduced fix only partially closed the security issue, leaving the contract vulnerable. This incident highlights the need for education about security critical details of the dispatcher function.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AkQGRYc-5ECDi33qLYwJcg.png" /></figure><p>This blog post aims to help developers write secure dispatchers in their EOS contracts and avoid such bugs, which put the funds of the smart contract at risk.</p><h3>The Dispatcher Function</h3><p>A dispatcher is the function that is executed first whenever the code of the account is invoked. This function receives an action identifying the function to be invoked, and it is the dispatcher’s responsibility to invoke the intended function. Every EOS smart contract must provide an apply handler that defines the behavior of the dispatcher function.</p><p>To implement the dispatcher, the contract development toolkit (eosio.cdt) allows developers to generate the dispatcher automatically by executing the macros inside a contract. All functions which are marked by [[eosio::action]] will be callable by actions. However, for some projects this is insufficient and the developer may need to customize the dispatcher, e.g., to accept certain actions only upon a token transfer. While basic helper functions are available, these only cover the invocation of the functions, not the control logic enforcing the condition of when they may be invoked.</p><h3>Recap — EOS’ communication model</h3><p>Before we dive in, we need to get up to speed with EOS’ communication model.</p><p>To execute a smart contract, actions need to be pushed to its account. During the execution of a smart contract it may notify other accounts about this action. Notifying another account is done by calling require_recipient(). What happens is that after the execution of this smart contract&#39;s code, the dispatcher of the notified account is invoked with a copy of this action.</p><p>Let us look at a simple dispatcher:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/429c0841e9a412a76e6b0e14997eeefd/href">https://medium.com/media/429c0841e9a412a76e6b0e14997eeefd/href</a></iframe><p>We see the implementation of apply(): If code is equal to receiver, the passed action is called, the helper function EOSIO_DISPATCH_HELPER does this for us. But what are these function parameters passed to apply() exactly? To write secure dispatchers, it is vital to fully understand these parameters.</p><p>The following parameters are passed to the apply function: uint64_t receiver, uint64_t code and uint64_t action. Let us have a look at the EOS source code!</p><p>This is the function that invokes the dispatcher of the smart contract by calling the apply() function and passing the following parameters:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e17541778e46ca0a475b86d7ca3ae1b7/href">https://medium.com/media/e17541778e46ca0a475b86d7ca3ae1b7/href</a></iframe><ul><li>receiver is context.get_receiver(), the account currently executing code</li><li>code is context.get_action().account, the account the action was sent to</li><li>action is context.get_action().name, the name of the action</li></ul><p>But what exactly does that mean? It is important to understand the difference between code and receiver. In short, code is always the first receiver of the action, while receiver is the account currently executing the action.</p><h3>code and receiver - aren&#39;t they the same?</h3><p>Not necessarily! They may be equal, e.g. when an action is sent to an account (= code) and this account’s code is currently executing (= receiver). In EOS’ communication model, contracts executing code can notify other accounts about this action by calling require_recipient(). This invokes the code of the recipient&#39;s account (= receiver changes) but the code stays constant, thus code and receiver differ.</p><p>By using code == receiver the dispatcher knows that this contract has been called by the action directly, while in the case of code != receiver the action was originally destined for another account, but this account has been notified about it.</p><h3>Most prominent use case — reacting to a token transfer</h3><p>If your contract receives a transfer of EOS tokens for example, you may want to execute a certain action. This functionality allows you to do so because the eosio.token contract notifies the sender and the receiver about a successful token transfer and gives them the opportunity to execute code. Note that the transfer action, to transfer x funds from account a to b, was sent to the eosio.token account, so code is equal to eosio.token. After a successful transfer, the receiver is informed about it and its dispatcher is invoked. Here code is eosio.token and receiver is b, because b is currently executing.</p><p>Let us stop here for a moment. Assume we are within our dispatcher and code is equal to eosio.token ( receiver is equal to our account), what exactly do we know at this point? Did we just receive a token transfer?</p><p>Not necessarily! At this point we just know that the original action was sent to the eosio.token contract (hence code is eosio.token), but we have absolutely no other information about the actual details of the token transfer! Most importantly we need to make sure that the transfer was to our account (ensuring parameter to of the action is our account) and that the amount is what we expect. If we don&#39;t do this (most importantly checking the to field), attacks of the following kind are possible:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*hhoLughhX0SOFGBV.png" /></figure><p>A simple example: we have a trading contract and transfer some GoldTokens if we received some EOS tokens. Our contract, however, only checks if code == eosio.token and the amount of tokens, it does not check if it was actually the receiver of these tokens. Alice notices this and decides to get some GoldTokens without actually transfering EOS to our contract.</p><p>All Alice needs is an account where she can deploy a simple contract. The only thing this contract has to do is to implement a transfer action and inform our trading contract about the transfer action. The attack works as follows:</p><ol><li>Alice sends a transaction to the eosio.token contract to transfer EOS from her account to the attacking contract she controls (where later she can reclaim these tokens).</li><li>Upon executing the action, the eosio.token contract notifies the sender and the receiver about the action.</li><li>The receiver, Alice&#39;s attacking contract, in turn just notifies our trading contract.</li><li>Our trading contract gets a copy of the action, where code is equal to eosio.token.</li></ol><p>Without doing any further checks our contract mistakenly thinks it just received some EOS tokens and transfers GoldTokens to Alice.</p><p>This example highlights the importance of checking everything properly.</p><h3>How to ensure your contract actually received an (EOS-) token transfer</h3><p>The following considerations are valid for the eosio.token contract, but likely also applicable to other token contracts. The first important thing to note is that you have to fully trust the token contract, especially that it only notifies you about the transfer if the transfer actually happened and succeeded. One of the token contracts you can trust to only notify you in case of a successful transfer is the system&#39;s eosid.token contract.</p><p>First, a mandatory requirement is that code is equal to eosio.token. Why? The eosio.token contract allows token transfers only when the action to transfer is directly sent to its account. When the eosio.token contract notifies you about a token transfer, your dispatcher gets a copy of the action.</p><p>The name of the passed action must be equal to transfer. Furthermore, all parameters, especially the field to and the quantity, need to be checked. A check if(to != self) return; is often added at a later stage in the contract to enforce this. Why is this done outside of the dispatcher? Inside the dispatcher it is hard to access the fields of the function&#39;s argument, once inside the function these parameters are easily accessible.</p><p>If you follow these guidelines you can be sure that your contract actually received an EOS token transfer.</p><p>Ensure that you only invoke functions of your smart contract which depend on a token transfer after these checks successfully passed. Please ensure that your custom dispatcher does not allow to bypass these checks on invoking these functions! Such mishaps happened in the past, let us walk through one well-known example.</p><h3>What went wrong for EOSBet?</h3><p>EOSBet allows you to bet EOS tokens. You transfer EOS tokens to their contract which places your bet. Later, if you win, you can claim and withdraw your prize. To state the obvious: one should only be able to place a bet after having transferred EOS. What went wrong in the first version of their dispatcher?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fe8ef8013a6591061108a0f87a6d538/href">https://medium.com/media/5fe8ef8013a6591061108a0f87a6d538/href</a></iframe><p>This dispatcher allows any action (if it exists) sent to the contract directly to execute, including the transfer function which should only be invoked after an actual transfer of EOS tokens to this contract. Thus an attacker was able to place bets for free and cash out the winnings. All US$200 000 worth of funds were drained from the contract.</p><p>EOSBet went ahead and fixed their code after the attack. The fixed code can be found in their <a href="https://gitlab.com/EOSBetCasino/eosbetdice_public/blob/master/EOSBetDice.cpp">Gitlab repository</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7769e7bcb53cc26d2b3e7d3eb87620c0/href">https://medium.com/media/7769e7bcb53cc26d2b3e7d3eb87620c0/href</a></iframe><p>The fix introduced checks verifying that the original recipient of the action is eosio.token in case of a call to the transfer action. As described above, this is insufficient to ensure that the EOSBet contract really received EOS tokens. While this fix now ensures that the action transfer was directed to the eosio.token contract, no checks have been added to the transfer() function, which handles this action, to ensure that the transfer.to receiver of the EOS tokens was the EOSBet smart contract. Please note that EOSBet is aware of this and all their deployed contracts are not subject to this issue anymore.</p><p>This blog post focuses on the most common use case, which is reacting to a token transfer. Please note that the same or similar problems exist during other interactions of smart contracts in EOS.</p><p>We hope this article raised your awareness, improved your understanding of the dispatcher of EOS contracts and will help you write secure smart contracts!</p><h3>Need a security audit of your EOS contracts?</h3><p>For an expert security review of your EOS contracts, reach out to us at <strong>contact@chainsecurity.com</strong>.</p><p><em>Originally published at </em><a href="https://chainsecurity.com/the-dispatcher-first-line-of-defense-in-any-eos-smart-contract/"><em>https://chainsecurity.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aec1a6f7e7b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chainsecurity/https-medium-com-chain-security-the-dispatcher-first-line-of-defense-8aec1a6f7e7b">The Dispatcher — First Line Of Defense In Any EOS Smart Contract</a> was originally published in <a href="https://medium.com/chainsecurity">ChainSecurity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero Gas Price Transactions — what they do, who creates them, and why they might impact Scalability]]></title>
            <link>https://medium.com/chainsecurity/zero-gas-price-transactions-what-they-do-who-creates-them-and-why-they-might-impact-scalability-aeb6487b8bb0?source=rss-8b14ef67c636------2</link>
            <guid isPermaLink="false">https://medium.com/p/aeb6487b8bb0</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[ChainSecurity]]></dc:creator>
            <pubDate>Wed, 05 Jun 2019 21:53:33 GMT</pubDate>
            <atom:updated>2019-06-06T17:54:14.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>Zero Gas Price Transactions — what they do, who creates them, and why they might impact Scalability</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j15_cENAw205KstAsT-P6w.jpeg" /></figure><p>From time to time it is important to question some fundamental assumptions about a system, especially as auditors. Today we look at the following assumption:</p><blockquote>Every transaction on Ethereum costs some Ether</blockquote><p>It turns out that this assumption is <em>not completely true</em>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o6MbdNxKf9iO7bYSA%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o6MbdNxKf9iO7bYSA%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3o6MbdNxKf9iO7bYSA%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="328" frameborder="0" scrolling="no"><a href="https://medium.com/media/014f56ff623c183a373e559f853a2d12/href">https://medium.com/media/014f56ff623c183a373e559f853a2d12/href</a></iframe><p>A quick recap: On Ethereum, transactions cost Gas depending on their complexity. Transaction creators can set a Gas Price which, multiplied with the Gas needed, determines the Gas Cost which has to be paid in Ether. Why is paying for transactions important in Ethereum? It <strong>limits spam attacks</strong> as the originator of a transaction actually needs to pay for the transaction. It<strong> incentivizes miners</strong> to include transactions. A third benefit is a little more indirect: it <strong>prevents certain attacks against smart contracts</strong> as the attack cost is higher than the economic gain. As an example, integer rounding errors in dividend-emitting contracts can give attackers very small advantages, which in practice are made infeasible due to the much higher gas cost of those transactions.</p><p>So why is it not completely true? In 0.5% of all blocks of the Ethereum main chain in Q1 2019 there are transactions with an actual Gas Price of 0. We call these going forward “Zero Gas Price Transactions”.</p><h3>What they do</h3><p>In the following we will analyze three different Zero Gas Price Transactions and the purpose of these transactions.</p><h4>First transaction — Minereum token mining</h4><p>Let us start by looking at <a href="https://etherscan.io/tx/0x4f719da4e138bd8ab929f4110e84d773b57376b37d1c635d26cd263d65da99cb">this</a> transaction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9_Vtl-0T5mP5BOAD0YWIsA.png" /><figcaption><a href="https://etherscan.io/tx/0x4f719da4e138bd8ab929f4110e84d773b57376b37d1c635d26cd263d65da99cb">https://etherscan.io/tx/0x4f719da4e138bd8ab929f4110e84d773b57376b37d1c635d26cd263d65da99cb</a></figcaption></figure><p>This transaction was signed by account 0x4554984fa368c745616bba60a28eb65b0976d38b which is one of the <a href="https://www.minereum.com/">Minereum</a> genesis addresses. The important thing to understand is that the <em>private key</em> of this address is <a href="https://www.reddit.com/r/Minereum/comments/6mgh6y/developer_updates/">publicly known</a>. Minereum was <a href="https://www.minereum.com/mining">designed</a> to have people compete with high Gas Price transactions to be the first to withdraw newly minted tokens from this address. To transfer tokens from an address, that address needs to hold some <em>Ether</em> to pay for the gas. In the case of this address it is not possible as any <em>Ether</em> sent to it will immediately be transferred away by sweeper bots with very high Gas Price transactions, effectively making any other transaction, which all have higher Gas requirements, impossible. In this case the attackers succeeded because they managed to get a transaction included where they actually did not have to pay any Ether! There is a nice write-up of this activity here: <a href="https://www.reddit.com/r/ethereum/comments/7lx1do/a_christmas_mystery_sweepers_and_zero_gas_price/">A Christmas Mystery: sweepers and zero gas price transactions</a>. The address used here to receive the tokens is 0xe386e3372e3d316ae063af50c38704ec6fba5149which is an address used in <a href="https://forum.ethereumclassic.org/t/security-issue-in-geth-console-transfer-etc/2979">hacks of users</a>.</p><h4>Second Transaction — GasToken mining</h4><p>Let us look at <a href="https://etherscan.io/tx/0x7f68d647a206943eb8aa782728be58cee728c7682c9b8b1cdca7fa3a8d8ace17">another</a> similar transaction, but this time against the <a href="https://etherscan.io/token/0x0000000000b3f879cb30fe243b4dfee438691c04">GasToken2</a> contract:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qNuB-nUdxTYsS45liTeAug.png" /><figcaption><a href="https://etherscan.io/tx/0x7f68d647a206943eb8aa782728be58cee728c7682c9b8b1cdca7fa3a8d8ace17">https://etherscan.io/tx/0x7f68d647a206943eb8aa782728be58cee728c7682c9b8b1cdca7fa3a8d8ace17</a></figcaption></figure><p>At first sight, this looks like someone creating <a href="https://gastoken.io/">GasTokens</a> without paying anything, which can later be used to save gas cost, e.g. when gas prices are high. Why would a miner include this transaction? The first reason we though of is that there were not any pending transactions in the network at that time and the miner was simply optimizing their profits by mining <a href="https://gastoken.io/">GasTokens</a>. But there are several question marks behind this assumption. A miner doesn’t have to use Zero Gas Price Transactions in the first place as they are receiving the mining fee anyways. Also, the following block was full and paid out roughly 5x in transaction fees, which might have been lucky, but is more likely to indicate that the miner didn’t include all transactions on purpose. Nevertheless, the biggest question mark by far is something else, the use of <em>0x00a329c0648769a73afac7f9381e08fb43dbea72</em> as the from-address which received the mined tokens. This address is another well-known address where the private key is publicly known: the “empty passphrase” parity address.<br>Why would a miner mine tokens to this address instead of a private one?</p><h4>Third Transaction — Failing Token Transfer</h4><p>Now let us look at a <a href="https://etherscan.io/tx/0x0a09242cf39152002e294b3129770ae629a239728ba4626d2b57506ec0d0975e">third</a> type of transaction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmrXBQzYTHjQ6J8aGLvIzA.png" /><figcaption><a href="https://etherscan.io/tx/0x0a09242cf39152002e294b3129770ae629a239728ba4626d2b57506ec0d0975e">https://etherscan.io/tx/0x0a09242cf39152002e294b3129770ae629a239728ba4626d2b57506ec0d0975e</a></figcaption></figure><p>This transaction is <em>failing. </em>It turns out that <em>a lot</em> of transactions with a zero gas price are failing. In this case, a transfer of the well known Beauty Chain Token is attempted. This project was <a href="https://blog.peckshield.com/2018/04/22/batchOverflow/">hacked in 2018</a> and has paused all trading activity since that day, causing all transfer calls to fail. It is also notable that the from-address used here is very likely another address with a known private key given that the account shows the usual sweeper bot activity whenever Ether is transferred into it.</p><h3>Who creates them</h3><p>Analyzing all of these different types of transactions leads us to the following assumption: this activity originates very likely from a single actor who is trying to transfer tokens away from compromised accounts. The script used is not very sophisticated as it tries again and again to transfer tokens which are permanently locked up. Mining tokens into these addresses might serve as a honeypot to incentivize others to try and steal those tokens, but given that there are easier ways it is not yet clear why the actor follows this strategy.</p><p>There is another important component. Zero Gas Price Transactions are usually not propagated in the network, and clients like geth and parity do not accept them by default. Even after we configured our nodes to accept all transactions including those with zero gas prices, we couldn’t find any such transactions being propagated on the Ethereum P2P network. The only way someone can include these transaction is by mining directly or by sending them to supportive mining pools without using the Ethereum P2P layer. If you know of a way to make a mining pool include <strong>only </strong>your transaction, please let us know in the comments.</p><h3>Why it will impact scalability</h3><p>So the big question is: what is the impact on the Ethereum network?</p><p>Currently, the absolute numbers of blocks containing these Zero Gas Price Transactions are relatively minor. Only 0.5% of all blocks mined in Q1 2019 on Ethereum Mainnet contain these types of transactions. More worrying is that the total mining power which colludes with this actor is, while still small at 4.3%,not negligible. Among the mining pools who include these transactions are well-known names like <a href="https://etherscan.io/txs?block=7408013">DwarfPool</a> and <a href="https://etherscan.io/txs?block=7406264">uupool</a>.</p><p>So why is this something to keep a close eye on? It is clear that miners can increase their profits by creating transactions and include them in their blocks, be it by design like in the case of GasTokens or Minereum or by activity like transferring tokens from addresses which are otherwise unusable. Currently most blocks in Ethereum are full and paid for by users with Gas, which in most cases gives the mining pools more profit than to include these transactions.</p><p>With higher maximal network throughput, which is the primary goal of Ethereum scalability, it is to be expected that in off-peak times half-full or even mostly empty blocks will become the norm. What would happen to the network if miners start to fill up these blocks with transactions e.g. mining for GasTokens to optimize their profits?</p><blockquote>Compared to mostly empty blocks, full blocks greatly increase the load on all participants and have the potential to cause long-term harm.</blockquote><p>The effects of this long-term harm can already be observed <a href="https://github.com/holiman/vmstats">in the growing effective costs for </a><a href="https://github.com/holiman/vmstats">SLOAD operations</a>.</p><p>Is it enough to trust miners to not harm the network out of self-interest? How will that change if the mining rewards for new blocks go down even more and the transaction fees become a sizeable part of their income? Let us know what you think in the comments!</p><h3>A short comment on EIP 1559</h3><p>How will a new fee model like the one proposed by <a href="https://eips.ethereum.org/EIPS/eip-1559">Vitalik Buterin and Eric Conner in EIP 1559</a> change this? It introduces a BASEFEEwhich gets burned, which can prevent Zero Gas Price Transactions on the network layer (as long as the BASEFEE is above zero) and by that prevent the attacks described here. While Zero Gas Price Transactions aren’t mentioned in the motivation for the EIP, a <a href="https://eips.ethereum.org/EIPS/eip-1559#motivation">broad band of other attacks</a> are:</p><blockquote>[…] incentivizing mining “sister blocks” that steal transaction fees, opening up much stronger selfish mining attack vectors, and more.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aeb6487b8bb0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chainsecurity/zero-gas-price-transactions-what-they-do-who-creates-them-and-why-they-might-impact-scalability-aeb6487b8bb0">Zero Gas Price Transactions — what they do, who creates them, and why they might impact Scalability</a> was originally published in <a href="https://medium.com/chainsecurity">ChainSecurity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>