<?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 Ronan Sandford on Medium]]></title>
        <description><![CDATA[Stories by Ronan Sandford on Medium]]></description>
        <link>https://medium.com/@wighawag?source=rss-1dd100dcdf63------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*to5aoT-HH9xACyYg.png</url>
            <title>Stories by Ronan Sandford on Medium</title>
            <link>https://medium.com/@wighawag?source=rss-1dd100dcdf63------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 01:28:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wighawag/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[Infinite Games]]></title>
            <link>https://medium.com/@wighawag/infinite-games-1aa679e07834?source=rss-1dd100dcdf63------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aa679e07834</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[game-design]]></category>
            <dc:creator><![CDATA[Ronan Sandford]]></dc:creator>
            <pubDate>Fri, 19 Aug 2022 09:06:20 GMT</pubDate>
            <atom:updated>2022-08-19T15:11:09.019Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article was original posted on my </em><a href="https://ronan.eth.limo/blog/inifinite-games/"><em>blog</em></a><em> where you can find more articles.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*pY9uRmqZaMC0dv6xeH2zEw.png" /><figcaption>conquest.eth</figcaption></figure><p><a href="https://ethereum.org/en/what-is-ethereum/">Blockchain technology</a> is a breakthrough in that it enables the construction of permission-less and persistent systems that run independently of their creators. These are open systems on which anybody can build on top. We see that very clearly with <a href="https://ethereum.org/en/defi/">DeFi</a> protocols on <a href="https://ethereum.org/">Ethereum</a> but as a game designer, games have always been the most obvious use case for it and from the day I stumble upon Ethereum, I was hooked on the idea of creating games that run and evolve independently of their creator. “Infinite Games”</p><h3>Infinite Games are permission-less and persistent</h3><p>I used to call these, “unstoppable games”, a term borrowed from Ethereum website back in <a href="http://web.archive.org/web/20151102205354/https://www.ethereum.org/">2015</a> which lured me into its ecosystem with sentences like “build unstoppable applications”. You can read about one of my earliest experiments with on-chain games here: <a href="https://etherplay.medium.com/our-first-unstoppable-game-tug-of-war-bb69c63a8734">Tug Of War</a>.</p><p>This idea of permission-less and persistent games has been so appealing to me as a game designer: <strong>The ability to create virtual worlds that lives on their own is fascinating, to say the least.</strong></p><p>A recent article by <a href="https://twitter.com/l_udens">@l_udens</a> from <a href="https://0xparc.org/">0xParc</a> on <a href="https://0xparc.org/blog/autonomous-worlds">Autonomous world</a> expand on the idea, check it out. It should come with no surprise that the <a href="https://twitter.com/snailbrainx">creator</a> of the first ever blockchain game (<a href="https://xaya.io/huntercoin">Hunter Coin</a>) has his company named exactly that: <a href="https://autonomousworlds.com/">Autonomous World</a>. But while “autonomous world” is a great term, it somehow lacks a broader gaming component unless we restrict ourselves to simulation games. In some ways “Infinite Games” are autonomous worlds with meaning. In a game, players have most of the time something to do in that world, against or with other players.</p><p>While sadly, most current success stories in the blockchain gaming ecosystem have nothing to do with the possibility of unstoppable, autonomous worlds and infinite games, I am still very hopeful that if we retain something out of all the work put into the blockchain ecosystem (collaboration around EIPs via <a href="https://ethereum-magicians.org/">Ethereum Magicians forums</a>, protocol design and more, see <a href="https://vitalik.ca/">Vitalik’s blog</a> and <a href="https://ethresear.ch/">Ethereum Research forum</a> to get a view of some the hard work and thoughts that have been put into blockchain ecosystem in general), is exactly that: the creation of systems, that lives with and for their communities, independent of any central authorities. And of course, such systems can be games / autonomous worlds / virtual realities. Note that interestingly we are not here talking about the usual 3d/VR component normally associated with virtual realities, but about the more fundamental level where rules have a meaning because they are immutable and interoperable. The “metaverse” if you see what I mean. See my recent presentation at <a href="https://ethcc.io/">EthCC</a> on the <a href="https://www.youtube.com/watch?v=B2KWE1vd_CA">subject</a> and how the term “Metaverse”, coined first in <a href="https://en.wikipedia.org/wiki/Snow_Crash">“Snow Crash”</a> resonate well with that idea.</p><h3>Infinite Games are more than On-chain Games</h3><p>On-chain Games are games where all the meaningful action of the game happens on-chain. <a href="https://twitter.com/gubsheep">Brian (@gubsheep)</a> from 0xParc published a thoughtful article on that subject and it resonated with many. In particular, he makes us aware that if you want to look for true innovation in the blockchain space, the best is to look at the games that make use of the blockchain’s unique properties. Its <a href="https://gubsheep.substack.com/p/the-strongest-crypto-gaming-thesis">“The Strongest Crypto Gaming Thesis”</a> article focus on several properties:</p><ol><li>“The source of truth for game data is the blockchain.”</li><li>“The game logic and rules are implemented via smart contract.”</li><li>“The game is developed in accordance with open ecosystem principles.”</li><li>“The game is client-agnostic.”</li><li>“The game embraces real-world value digital assets.”</li></ol><p>These define on-chain games in a quite broad sense and we can recognize several games in the history of blockchain games that fit that schema, starting with Huntercoin where the whole blockchain is the game. and continuing with other title like “Tug Of War” mentioned above, but also <a href="https://galleass.io/">Galeass</a> and <a href="https://daog.io/">DAOG</a> by <a href="https://twitter.com/austingriffith">Austin Griffith</a>, <a href="https://ethernal.world/">Ethernal.world</a> by <a href="https://twitter.com/OhJia">Jia</a> and myself, <a href="https://dungeonprotocol.com/">Dungeon Protocol</a> by <a href="https://twitter.com/Qhuesten">Killari</a>, <a href="https://zga.me/">Dark Forest</a> by Brian, <a href="https://conquest.game/">conquest.eth</a> by me, <a href="https://mithraeum.io/">Mithrareum</a> by <a href="https://twitter.com/TheLastTriarius">Bohdan</a> and many more in construction these days: Check out <a href="https://twitter.com/0xCurio">0xCurio,</a> <a href="https://eykar.org/">Age of Eykar</a>, <a href="https://isaac-book.netlify.app/#/">Isaac</a> and <a href="https://twitter.com/LootRealms">Realms</a> (see their extensive <a href="https://scroll.bibliothecadao.xyz/docs/game/realms">doc</a>).It is worth pointing out that such games have their challenges and I invite you to read <a href="https://twitter.com/sylvechv">Sylve</a>’s article on the subject here: <a href="https://mirror.xyz/sylve.eth/6QJ6taBcobFAWMbijs4WrQrFZ_FGq5wXmJ_NIXW-GmQ">“Four challenges in blockchain gaming”</a></p><p><a href="https://twitter.com/EAThomson">Edward</a> from the <a href="https://decentralizedgaming.io/">Decentralised Gaming Association</a> would also add that decentralised games do not need to be on-chain in a traditional sense. See his articles on the subject here: <a href="https://edthomson.com/decentralized-gaming/">https://edthomson.com/decentralized-gaming/</a></p><p>Infinite Games are on-chain games but they are more than that. On-chain games can come in many forms and they are fascinating in their own right, but Infinite Games have a few more properties that make them truly unique. These same properties make “Infinite Games” practically impossible to build without blockchain.</p><ol><li>“The game is interoperable” (This is touched upon in Brian’s article but it is important that some effort is put into the game design to ensure that the game can truly be built upon. This includes offering an interesting enough programmable interface, so it merits emphasis.)</li><li>“The game is permission-less” (The game can be played by anyone at any time: no whitelist and no limits)</li><li>“The game is persistent” (The game has no end, allowing anyone to join at any time and for extensions built upon the game to live along the game forever)</li><li>“The game is immutable” (The ruleset cannot change once the game is launched)</li></ol><p>These properties are the same as that of the underlying programmable blockchain itself like Ethereum: it is programmable, permission-less, persistent and immutable. In other words <strong>“Infinite Games” are crypto-native on-chain games that preserve the properties of the underlying blockchain.</strong> They do not make any concessions. Players can come and go, build on top and be confident that their extensions live along. This allows any contribution to be more than mere source code.</p><p>By allowing this, Infinite Games become protocols themselves and worlds of their own. They also become an invitation to build. Indeed, such games allow extensions to be <a href="https://jacob.energy/hyperstructures.html">hyperstructures</a> themselves.</p><p>Note that while I believe point 9. is crucial to allow the game to be truly infinite, there is probably scope to allow the game itself to introduce mechanisms to make the game evolve. These could be done through the game itself or via governance mechanisms. Having said that, ideally, any governance should be handled by a forking mechanism so anybody can decide. This is because governance through DAO opens up the possibility of undesired capture. Furthermore, game evolution can also happen by simply launching a new version of the game that could even borrow state from the previous.</p><h3>Virtual Realities</h3><p>Such infinite games are so fascinating because they replicate reality by implementing rules of physics (= rules that do not change). They are their own reality with a life of their own. <a href="https://twitter.com/guiltygyoza">@guiltygyoza</a> has written an interesting article on the subject of on-chain physics that you should check out too : <a href="https://www.guiltygyoza.xyz/2022/04/onchain-realities">“Onchain Realities”</a>.</p><p>This breakthrough was enabled by Bitcoin in the first place, which we can see as the first artificial life form. Its existence while still dependent on human activity, remains independent in its direction. This is because humans have incentives to continue maintaining the chain, at least for some time. In some ways, humans are like the cells of Bitcoin’s “body”.</p><p>Ethereum takes it further and allows whole applications to run on it. Ethereum makes blockchain an ecosystem for new life forms to evolve. Defi explores the idea with basic exchanges of value.</p><p>Infinite games bring it to another level by allowing the whole gaming universe to be designed and be let alive. This allows the creation of universes inside our universe that lives independently of us.</p><p>It is worth noting that achieving such independence while still being a meaningful experience for players is not that easy. Something of value must be at stake for players to participate. Otherwise, any player could create thousands of accounts and this would break any sense of fairness. In some ways, by giving games the ability to track this resource at risk through on-chain rules, they provide a new mechanism for game designers: <strong>The ability to ensure fair game at scale</strong>. We see that in action in <a href="https://conquest.game/">conquest.eth</a> where any player can join at any time. They can create thousands of accounts for themselves if they wish and the game mechanism handles it.</p><h3>Conquest.eth, an Infinite Game, alive today</h3><p>Conquest.eth is an Infinite Game that is running and alive today. Launched in April (at <a href="https://defcon.0xparc.org/">Defcon</a>) it can be played by anyone <a href="https://defcon.conquest.etherplay.io/">here</a> and we have seen the rise and fall of space empires during that time. We even saw the selling of whole empires. All of it is done in a permissionless world with no white-lists nor any time limit. The game will continue to live as long as the underlying chain remains (<a href="https://www.gnosischain.com/">Gnosis Chain</a> in that case).</p><p>It is fascinating to watch. While before the community could build source code and tools, that get re-used across different instances of a game (See Dark Forest community in particular), <strong>with conquest.eth and other infinite games, we can build </strong><a href="https://jacob.energy/hyperstructures.html"><strong>hyperstructures</strong></a><strong> (“Crypto protocols that can run for free and forever, without maintenance, interruption or intermediaries.”) on top of the game itself</strong>. The stuff being built inherit the lifeline of the game and so by extension the blockchain it lives on.</p><p>We are at the beginning of all of it though. Conquest has explored a minimal game design to explore better how the core idea works but we will be exploring more complex mechanisms in the coming year and can’t wait to see what players will be building on top. You can follow progress on <a href="https://conquest.game/devlog/">conquest’s devlog</a></p><p>Note that the stuff to build does not even need to interoperate back into conquest’s smart contract. Systems that can only read conquest’s state can still provide a fascinating ecosystem to conquest’s player base and beyond. What if you build a game that reuses the state of conquest but adds its components on top?</p><h3>What will you build?</h3><p>If you have yourself the motivation to build new on-chain games, of the infinite variety even, I suggest as <a href="https://twitter.com/DangerWillRobin">Will Robinson</a> suggested several times, to have a look at <a href="https://boardgamegeek.com/">board games</a> in general as they share some of the same constraints. Check out his <a href="https://medium.com/alliancedao/unblocking-on-chain-games-part-one-throughput-d0dc7a4defab">article</a>. Interestingly, as Bohdan from Mithareum noticed in his <a href="https://twitter.com/TheLastTriarius/status/1554148975787352064">tweet</a>:</p><pre>Сurious fact that decentralized games were invented before centralized ones in the form of board games.</pre><pre>Even then, the moves were finalized by the consensus of the players, and endless patches and the direct influence of the developers were not needed to keep the game afloat</pre><p>Another source of inspiration that I did not see mentioned before is a particular trend of games that bear strong similarities with on-chain games and to some extent, “infinite games” is the <a href="https://en.wikipedia.org/wiki/Play-by-mail_game">“Play By Mail”</a> category, especially the one moderated by computer systems. See a list of games here: <a href="https://en.wikipedia.org/wiki/List_of_play-by-mail_games">https://en.wikipedia.org/wiki/List_of_play-by-mail_games</a>. Designers of such games have indeed similar constraints to on-chain games. The cost of a turn for players in such games can even be a few dollars!</p><p>By the way, if you are a dev, designer, or community enthusiast interested in the possibility behind infinite games, let me know. I would love to chat. I have lots to build for conquest and would love some help 😃</p><p><em>Special thanks to </em><a href="https://twitter.com/Qhuesten"><em>Killari</em></a><em>, </em><a href="https://twitter.com/EAThomson"><em>Edward</em></a><em>, </em><a href="https://twitter.com/sylvechv"><em>Sylve</em></a><em>, </em><a href="https://twitter.com/TheLastTriarius"><em>Bohdan</em></a><em> and </em><a href="https://twitter.com/zomglings"><em>Neeraj (@zomglings)</em></a><em> for feedback.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aa679e07834" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum: The Concept of Gas and its Dangers]]></title>
            <link>https://medium.com/@wighawag/ethereum-the-concept-of-gas-and-its-dangers-28d0eb809bb2?source=rss-1dd100dcdf63------2</link>
            <guid isPermaLink="false">https://medium.com/p/28d0eb809bb2</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[vulnerability]]></category>
            <dc:creator><![CDATA[Ronan Sandford]]></dc:creator>
            <pubDate>Thu, 27 Feb 2020 15:59:06 GMT</pubDate>
            <atom:updated>2023-02-11T15:55:07.163Z</atom:updated>
            <content:encoded><![CDATA[<p>The article is originally from <a href="https://ronan.eth.limo/blog/ethereum-gas-dangers/">https://ronan.eth.limo/blog/ethereum-gas-dangers/</a></p><figure><img alt="Photo by Jules D. on Unsplash" src="https://cdn-images-1.medium.com/max/1024/1*rk1PDPs4NuXf8p_2iMrPgQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@varietou?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jules D.</a> on <a href="https://unsplash.com/collections/9613830/gas/f37a4adc2ec3a831c909ba4f27a2e850?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Hi, I am back with an article on Ethereum. We’ll explore the concept of gas and explain how it behaves and show what its sometimes, subtle behaviour actually implies.</p><p>It turns out that almost every Smart Contract Accounts and Meta Transaction implementations so far fail to consider the specific rules of gas when calling other contracts and are thus <strong>vulnerable to malicious relayers</strong>.</p><p>To make matter worse, with the addition of “try/catch” in solidity 0.6, it is now even easier to expose contracts to a type of attack that share similarity to the infamous <strong>Call Depth Attack</strong> and seems to have never been discussed before nor been listed in attack vector listing like <a href="https://swcregistry.io/">the Smart Contract Weakness Registry</a>.</p><p>Indeed, the Ethereum community is yet to be fully aware of some of the pitfalls associated with Ethereum’s gas behaviour.</p><p>I hope this article will help shade some light on a core aspect of Ethereum smart contract development and hopefully help improve the situation.</p><p>If you are short on time, the crux of the article is that the current ethereum gas behaviour, including how gas is given to other contract via the various CALL* opcodes is not intuitive and can cause security issues in some situation, like meta-transactions. Plus contracts calling other contracts cannot be sure that the contracts they call reverted because of a lack of gas or simply because they intentionally reverted, not unlike the infamous “call depth attack”.</p><p>Let’s start with the basics. If you are already familiar with gas on ethereum you can skip to 2. Gas And Contracts Calls.</p><h3>1. What Is Gas?</h3><p>In a nutshell, gas is the measure of the computational resources used by the operations performed on the Ethereum network (including storage of data, temporary memory manipulation and operation like multiplication, hashing, etc…).</p><p>When a user submit a transaction on the Ethereum network, it needs to pay for the sum of all the operations its transaction performs so that it rewards the miner/validator that performs the operation and makes it prohibitively expensive to make a denial of service attack on the network. For a basic Ethereum transfer it costs for example 21,000 gas, but more complex operations can cost millions of gas.</p><p>Since Ethereum is <a href="https://en.wikipedia.org/wiki/Turing_completeness">Turing complete</a> (it can perform any kind of computation given infinite resources but exhibit the <a href="https://en.wikipedia.org/wiki/Halting_problem">halting problem</a>), the miners/validators (those that decide what transactions are included on the Ethereum network) can’t know the total cost of operations of the transaction without executing it first (in which case they would need to be rewarded for it, else the abuse would be trivial). The user (transaction’s signer) need to set a gas value representing the maximum gas they expect their transaction to use, this is usually called the transaction’s gasLimit (though it is sometime called startGas or simply gas).</p><p>If it turns out that the transaction being executed actually consumes more gas than specified by the gasLimit, the transaction&#39;s operations are nullified (we usually refers to it as a revert or throw (when all gas of gasLimit is consumed, like here) and the node has to revert the state&#39;s changes to ensure the transaction has no effects. If that happen, the transaction is still recorded and rewards the miner that included it, reducing the balance of the transaction&#39;s sender accordingly.</p><h3>Gas Has A Price</h3><p>Now, the miners/validators do not get rewarded in gas unit, but in Ether (ETH), Ethereum native currency. Indeed, the gas value is only an abstract measure of the cost. It can only be paid directly in ETH. As such when users submit transactions, they also set a gasPrice they are willing to pay (per gas unit used) to get their transactions included. And so users, cannot emit transactions on the Ethereum network without owning some ETH, unless the gasPrice they set is zero (in which case miners would not be incentivised to include the transaction).</p><p>It is worth noting that there are various efforts going on to solve this and allow users without ETH to interact with Ethereum through what is called “Meta Transactions”. It turns out, as we shall see later, that such solutions have potential issues with the behaviour of gas.</p><p>When transactions are included on the network, they are included in batches, called blocks. And to ensure that most modern computer can handle the network (so that the network remain decentralised and not just in the trust of powerful computers), there is a limit of the amount of gas that can be used in a block. This, in turn, limits the number of transactions in a block.</p><p>As such, users compete for the inclusion of their transaction and so the average price of the gas on Ethereum is set by the market: users compete for transaction inclusion and miners/validators pick the one that give more reward first (higher gasPrice).</p><h3>Gas Refund</h3><p>While the cost in ETH of a transaction is computed as follow</p><pre>transaction cost = gasUsed * gasPrice</pre><p>It is slightly more complicated than you might think.</p><p>Indeed, certain operations actually give a refund and that refund is only deduced <strong>after</strong> the transaction is done. This means that the gasUsed can actually be smaller than the gasLimit required to be given for the transaction to succeed. A more accurate equation is thus as follow:</p><pre>transaction cost = (gasRequired - gasRefund) * gasPrice</pre><p>where gasRequired is the minimum gas value that was required to be provided via gasLimit in order for the transaction to succeed (and not run out of gas) and gasRefund is the total amount of refund given as part of the execution of that transaction. An example of operation that gives a refund is operation that reset storage to zero values. This is to encourage contract developer to reduce storage space as this can reduce the overall cost of their operations.</p><h3>Gas Cost VS Real Cost</h3><p>We have thus seen that every operation performed on the Ethereum network costs an amount of computational resources and this is accounted for with a gas cost (which itself have an average price in ETH (currently around 0.000000001 ETH (or ~ $0.0000001) per gas unit)). The goal of such system it to try to be as accurate as possible with the actual resource cost of performing that operation on a computer so that no abuse of the network is possible without paying the true cost of it.</p><p>The gas cost is obviously not completely accurate for few reasons: implementation differences between nodes, differences in hardware and the intrinsic differences in operation cost based on their inputs. Furthermore, as the gas measure is a one dimensional value, differences between storage of value for long term, reading from memory and an operation like addition use the same metric which is not how a computer would normally perform.</p><p>Plus, as highlighted by the change in opcode pricing over time, the cost of each operation can change. It is also dependent on the state of Ethereum. Most notably, the latest opcode pricing changes like <a href="https://eips.ethereum.org/EIPS/eip-1884">EIP-1884</a> that make reading from storage 4 x more expensive was due to the realisation that as the Ethereum state size grew, it became more expensive to retrieve data from storage. The opcode gas pricing had to reflect that in order for the Ethereum network to remain protected from denial of service (DOS) attacks.</p><p>It is also worth noting that the gas pricing model currently used by Ethereum might be vulnerable to specially crafted smart contract that exploit the limited accuracy of the pricing. See for example the research done on <a href="https://arxiv.org/pdf/1909.07220.pdf">“Resource Exhaustion Attack”</a> by Daniel Perez and Benjamin Livshits with genetic algorithms to craft smart contracts whose execution is relatively cheap on gas compared to how expensive they are for the network to compute.</p><p>Nevertheless, the current gas opcode pricing provide a good ballpark representation of the cost of the operation your smart contract will perform and even if the gas cost can and will change the order of magnitude should remain the same.</p><p>As a smart contract developer you should never assume specific opcode pricing in your smart contract and your code should thus remain independent of it. Unfortunately it is still not too uncommon to see smart contract developers hard-coding gas value in their contract, please do not emulate them.</p><h3>Gas Estimation</h3><p>While smart contract developers can sometime have a good idea of how much gas is required to perform their contract operations, it is in many cases dependent on the inputs and the current state. As such Ethereum nodes provide a mechanism for users to estimate the gas required for a particular transaction. The applications’ front-end can thus perform these estimate to ensure enough (and not too much) gas is provided as gasLimit for the actual transaction. (Note that it is important to ensure gasLimit is not too high as this can delay the inclusion of the transaction, since it is easier to pack smaller transactions in and miner wants to maximise the use of a block. It is also nice for the user to let them know as accurately as possible the cost of the transaction).</p><p>The front-end would thus basically make a call to the users’s node or wallet with the exact parameters it will use for the real transaction. The node will execute the code without broadcasting anything to other node and return the gasRequired for the transaction to succeed.</p><p>Unfortunately as of today, the nodes have no better way than using a binary search to find the proper estimation. This means the node will sometime need to execute the code 20 times or more to find the minimum required gas. And even then, it could miss if the contract had for some reason, branching logic dependent on the gas available (unlikely but technically possible).</p><p>We should actually be able to improve the situation by giving node the ability to record max gas needed as they perform the operation. We could for example replace the gas opcode (which is normally used to be compared to some value) with a requireGas opcode that would register such gas need. Backward compatibility will limit the effectiveness of this strategy though. I have started to write a <a href="https://github.com/ethereum/EIPs/pull/2075">proposal</a> on this solution but need to continue working on it.</p><p>Note though that whatever estimate is given, it might not be enough as for some contract operations, the gas cost can depend on other users changing the state. If these changes happen between the time of the estimation and the time at which the transaction is included in a block, the estimation will be incorrect. Similarly, an operation could be time/block dependent and the estimation could be off. As such front-end will usually add some extra gas to cover these cases. There are alternative mechanisms being researched too like <a href="https://arxiv.org/pdf/1910.02945.pdf">GasFuzz</a>.</p><p>Smart contract developers can also help by designing contracts so that state changes can only decrease the gas cost for future user. This is not always possible or even desired though.</p><h3>The 2300 Gas Stipend</h3><p>Another particular behaviour that relates to gas is the gas stipend, that is extra gas given to recipient of ETH. So when a user’s transaction or a contract make a call to another address with an amount of ETH greater than zero, 2300 gas is added by the EVM to the gas passed to the destination. As such contracts receiving ETH, have the guarantee to have at least 2300 gas and can for example emit an event, but would have no guarantee to be able to write to storage and thus change state.</p><p>In solidity, the &lt;address&gt;.send and &lt;address&gt;.transfer functions will not pass any more gas and as such these call only receive 2300 gas. This for example ensure they cannot call back in the caller contract and change state. They are thus safe from <a href="https://consensys.github.io/smart-contract-best-practices/known_attacks/#reentrancy">re-entrency attacks</a>. Plus as you shall see, they are safe from issues mentioned further down.</p><h3>2. Gas And Contracts Calls</h3><p>We have so far, described what gas is on Ethereum and seen that every operation has a gas cost. One type of operation, the ones that call other contracts, is more complex in that it has special rules on how gas is given to called contracts and how “out of gas” or other failures are handled. As you should see, this has some important consequences.</p><p>In Ethereum, a contract (referred here as the <em>caller</em>) can call other contracts (referred here as <em>callees</em>) via special opcodes (CALL, STATIC_CALL, DELEGATE_CALL,…). When that happen, <em>callees</em> also receive an amount of gas as if they were called directly via a transaction. The gas provided is partially specified by the <em>caller</em> as part of the opcode parameters. See DELEGATE_CALL spec <a href="https://eips.ethereum.org/EIPS/eip-7">here</a> for example.</p><p>If the amount received is not enough (the total gas cost of all operations executed by the <em>callee</em> exceeds the gas received), the <em>callee</em>’s operations get reverted and execution goes back to the <em>caller</em> as the result of an “out of gas” exception. While in most cases, (when developers use normal function calls in solidity), the <em>caller</em> automatically reverts when receiving such failure, the EVM and solidity actually allow the <em>caller</em> to continue (this is now becoming easier with <a href="https://blog.ethereum.org/2020/01/29/solidity-0.6-try-catch/">try/catch</a> functionality in solidity 0.6). The <em>caller</em> has then at its disposition, whatever gas is left (including what was not spent by the <em>callee</em>).</p><p>The <em>callee</em> can also decide on its own to revert (revert its operations but return the unused gas) or throw (revert its operations and consume all gas given). This can be as a result of a specific error in which case the <em>callee</em> can specify an error message, or because it performed an invalid operation (like division by zero).</p><p><strong>Note that Ethereum has no established convention on error message yet and as such <em>caller</em> have usually no clue of the reason why <em>callee</em> fails</strong>, unless both contracts were build for each other. In particular it cannot know whether the error was actually caused by not being given enough gas or for another reason.</p><h3>The 1/64 Rule</h3><p>While I mentioned that it is the <em>caller</em> who specify how much gas is given to <em>callee</em>, this is a bit more complex.</p><p>In the current Ethereum version (post “Tangerine Whistle” hard fork that introduced <a href="https://eips.ethereum.org/EIPS/eip-150">EIP-150</a>), a <em>caller</em> can actually only give to a <em>callee</em>, an amount of gas no greater than:</p><pre>gas available - (1/64* gas available)</pre><p>This is because EIP-150 ensure the caller is left with at least 1/64 of the gas available, regardless of what happens to the call.</p><p>The reasoning behind the introduction of this 1/64 rule was to avoid the issue that previous implementation had: It used to be that <em>caller</em> could send all the gas currently available to them to the <em>callee</em>. But this implied that there could be contracts calling contracts, almost ad-infinitum (since the gas cost of a call is low). To ensure this did not cause “stack too deep” issue in Ethereum node’s implementation, the maximum depth was caped to 1024 (and still is). Upon reaching that depth, the last call would throw.</p><p>The consequence was that transaction signers could ensure that a specific call would throw by first making the transaction go through a series of calls and make it reach the depth of 1023 before calling a particular smart contract. This is known as the <strong>Call Depth Attack</strong>, see <a href="https://blog.ethereum.org/2016/06/10/smart-contract-security/">here</a> for an introduction.</p><p>In practice it meant that in most cases you could not trust your <em>caller</em> contract to continue processing its logic after receiving a revert from a <em>callee</em>. And note that such issue also affected simple &lt;address&gt;.send call (that would normally get the guaranteed gas stipend).</p><p>The solution to prevent this from happening, proposed first in <a href="https://github.com/ethereum/EIPs/issues/114">EIP-114</a> and finally accepted in <a href="https://eips.ethereum.org/EIPS/eip-150">EIP-150</a> is to always keep an amount of gas in the <em>caller</em>, specifically 1/64 of the available gas. Since at each extra depth level, the gas would diminish rapidly, the recursive depth would get limited naturally and while the 1024 limit still exist today in node implementation, it is for practical purpose unreachable.</p><p>This was not the only change in EIP-150 though. The gas provided as part of the CALL* opcodes has changed from a strict value to <strong>a maximum value</strong>, that is, if ~ 63/64 of the available gas is less than the value given to the opcode, the call will still proceed but with less gas than specified, as opposed to reverting, like in previous implementations. One of the reasoning behind such change (proposed first in <a href="https://github.com/ethereum/EIPs/issues/90">EIP-90</a> ) was that it was not a good idea to calculate the gas required by a call and that it was important to protect the <em>caller</em> by preventing the <em>callees</em> from using all the gas (actually ~63/64 of it). There were propositions to have &quot;give all available gas&quot; as an option but in the end, the idea of having the gas value simply being a maximum was decided. See <a href="https://github.com/ethereum/EIPs/issues/90">this issue</a> for some of the discussion.</p><p>The possibility of <em>proceed without enough gas</em> is something we do not naturally expect as developers and as you will see in the next section, it can lead to safety issues.</p><p>Many projects out there are actually affected, including <a href="https://safe.gnosis.io/">Gnosis Safe</a> and other smart contract wallet that support meta-transaction. This is also true of the <a href="https://gasstation.network/">Gas Station Network (GSN)</a> by <a href="https://openzeppelin.com/">OpenZeppelin</a>.</p><h3>3. Insufficient Gas Griefing Attack</h3><p>As we should see, this was a mistake. Indeed, in some cases, <em>caller</em> contracts need to ensure that the <em>callee</em> receive a specific amount of gas. A feat, not perfectly achievable with current opcodes unless you let your contract be <strong>dependent on specific opcode pricing</strong>.</p><p>Let’s look at an example of solidity code :</p><pre>contract Executor {<br>    function execute(address to, bytes calldata data, uint256 gas) external {<br>        (bool success, bytes memory returnData) = to.call.gas(gas)(data);<br>        // do something<br>    }<br>}</pre><p>If you were new to solidity, I am pretty sure you would expect that the <em>callee</em> (here to) should be certain to receive an amount of gas equal to gas. However, in the current EVM implementation, this only means that the <em>caller</em> is ensured to spend a maximum amount of gas equal to gas. In other words, the gas specified as parameter of the CALL* opcodes acts as a protection for the <em>caller</em> to not spend more than gas in the call. <strong>The <em>callee</em>, on the other hand, is not guaranteed to get any.</strong></p><p>Note that such behaviour is obviously different from the transaction’s gasLimit as in that latter case, the transaction is at least sure it will get that amount of gas.</p><p>You might be thinking that if the <em>callee</em> run out of gas, then surely the <em>caller</em> will throw because no more gas would be left for it neither.</p><p>That’s where the 1/64 rule, described above, kicks in. Since gas/ 64 is left anyway in the <em>caller</em>, this could well be enough for it to carry its execution to the end. As such, even if the <em>callee</em> fails because it did not receive the expected gas, the <em>caller</em> would carry on potentially assuming that the <em>callee</em> failed for another reason than a lack of gas.</p><p>By the way, 1/64 is not that small. If an inner call require 6,400,000 gas, the <em>caller</em> would still have 100,000 gas to carry on after the <em>callee</em>’s call fails.</p><p>As far as I know this vulnerability is not explained properly anywhere. Interestingly enough as I mentioned, it affects several projects already, including almost every smart contract wallet and meta-transaction implementation out there. It also affects EIP-165 (but to a less extent, because for practical purpose it might never matter) whose example implementation exemplify the issue, see <a href="https://github.com/ethereum/EIPs/pull/881#issuecomment-491677748">here</a>.</p><p>It was first reported as part of a Gnosis Safe bug bounty on <a href="https://solidified.io/">Solidified.io</a> back in March 2019, see <a href="https://web.solidified.io/contract/5b4769b1e6c0d80014f3ea4e/bug/5c83d86ac2dd6600116381f9">bug report</a>. Solidified agreed on the importance of the bug. Unfortunately Gnosis Safe team did not officially announce the issue that affects their users. The issue, later posted on github <a href="https://github.com/gnosis/safe-contracts/issues/100">here</a> remains unanswered. It is also worth noting that the <a href="https://github.com/gnosis/safe-contracts/blob/78494bcdbc61b3db52308a25f0556c42cf656ab1/docs/Gnosis_Safe_Formal_Verification_Report_1_0_0.pdf">formal verification</a> performed by <a href="https://runtimeverification.com/">Runtime Verification</a> for Gnosis, did not found the issue even though the contract code explicitly attempts to perform the check that enough gas is given to the transaction, see line 101 <a href="https://github.com/gnosis/safe-contracts/blob/5a8b07326faf30c644361c9d690d57dbeb838698/contracts/GnosisSafe.sol#L101">here</a>.</p><p>The community would have benefited from a disclosure from Gnosis when it published <a href="https://blog.gnosis.pm/formal-verification-a-journey-deep-into-the-gnosis-safe-smart-contracts-b00daf354a9c">the result of the formal verification</a> as this highlights the limitation of such verification, when the expected behaviour is not fully transcribed.</p><p>While it is true that the issue facing such smart contract wallet, can be circumvented by making sure users sign a metatx gasLimit (called safeTxGas in Gnosis case) higher than normally necessary, this is not ideal and we should aim to move the security of the wallet in the smart contract code as much as possible.</p><p>Indeed, with current Gnosis Safe implementation, the User Interface need to do extra work (increase the amount of gas to be signed by the user) to ensure users are safe against malicious relayers.</p><p>You can imagine building such interface on IPFS (so that users can trust it does not change) that ensure extra gas is given but then if opcode pricing change, the interface might become vulnerable.</p><p>Note that Consensys Dilligence actually mentions the issue <a href="https://consensys.github.io/smart-contract-best-practices/known_attacks/#insufficient-gas-griefing">here</a> and <a href="https://swcregistry.io/docs/SWC-126">here as SWC-126</a> but they actually fail to propose a correct solution, showing what seems a misunderstanding of the issue.</p><p>Indeed the following code (similar to the one shown on Consensys documentation linked above and to Gnosis Safe code) is not sufficient to prevent the problem from happening</p><pre>contract Executor {<br>    function execute(address to, bytes calldata data, uint256 gas) external {<br>        require(gasleft() &gt;= gas);<br>        (bool success, bytes memory returnData) = to.call.gas(gas)(data);<br>        // extra operation including the logic to reward relayer for submitting the tx<br>    }<br>}</pre><p>The require call will not ensure that to.call actually receives the gas specified via parameter gas This is for 2 reasons actually:</p><ul><li>The gas required for the call itself (opcode and memory) would further reduce the gas available to be lower than what reported by gasleft() when the call is actually made.</li><li>Most importantly though, it is that even if at the point of the call, the gas available was still sufficient, the 1/64 rule would reduce it even more. <strong>And because 1/64 of the gas required can be high enough for the rest of the tx to succeed, the call can continue.</strong></li></ul><p>For Meta transaction (like in Gnosis Safe case) this means that a relayer could sign the transaction (maliciously or by ignorance) with low enough gas so that the inner call fails but high enough so that transaction itself succeed. This would <strong>result in the relayer getting rewarded for the execution, while the user would see its meta transaction failing even if signed with a high enough </strong><strong>safeTxGas</strong></p><p>Furthermore as it is possible that a user could generate a series of meta-transaction messages. If a relayer was able to make the first one fail, it could impact the whole series.</p><p>This is why we need a way for smart contract to ensure that <em>callees</em> receive the exact amount of gas specified.</p><h3>Workaround Against “Insuficient Gas Griefing attack”</h3><p>As mentioned above, the solution proposed by Consensys Dilligence is insufficient. In order to properly guard against the issue, we need to ensure there is enough gas at the point of the call being made.</p><p>It turns out that with current EVM there are 2 ways to do it</p><p>1) Check before the call</p><pre>uint256 gasAvailable = gasleft() - E;<br>require(gasAvailable - gasAvailable / 64  &gt;= `txGas`, &quot;not enough gas provided&quot;)<br>to.call.gas(txGas)(data); // CALL</pre><p>where E is the gas required for the operation between the call to gasleft() and the actual call PLUS the gas cost of the call itself. This is unfortunately opcode pricing dependent. As gas pricing continue to evolve, it is important to have a mechanism to ensure a specific amount of gas is passed to the call so such mechanism can be used without having to rely on a specific gas pricing.</p><p>While it is possible to simply over estimate E by a large amount, it could still theoretically be insufficient as there are no guarantee opcode pricing will not change dramatically. Plus it would simply be better to have the EVM do the precise work itself.</p><p>2) Check after the call:</p><pre>to.call.gas(txGas)(data); // CALL<br>assert(gasleft() &gt; txGas / 63); // &quot;not enough gas left&quot;</pre><p>This workaround does not require to compute a E value as mentioned in the previous one and thus does not rely on a specific gas pricing (except for the behaviour of EIP-150). If the call is not given enough gas and fails for that reason, the condition above will always fail, ensuring the current call will revert.</p><p>Note that this check still pass if the gas given was less AND the external call reverted or succeeded EARLY (so that the gas left after the call &gt; txGas / 63). This can be an issue if the code executed as part of the CALL is reverting as a result of a check against the gas provided. Like a meta transaction in a meta transaction. That is why we use an assert here, so that all gas is used, emulating an out of gas exception.</p><p>This workaround is actually used in several places today.</p><ul><li>It was first implemented as part of my work on <a href="https://www.sandbox.game/">Sandbox</a> for a Meta Transaction standard (see <a href="https://github.com/ethereum/EIPs/issues/1776">EIP-1776</a>).</li><li>It is used by the winning entry I <a href="https://metatx.eth.link/">submited</a> for <a href="https://gitcoin.co/issue/MetaMask/Hackathons/2/3865">gitcoin Metamask hackathon</a>. See the code <a href="https://github.com/wighawag/singleton-1776-meta-transaction/blob/master/contracts/src/GenericMetaTxProcessor.sol#L180-L187">here</a> that checks for gas left after the call.</li><li>PISA research also include it on their solution, see <a href="https://github.com/PISAresearch/contracts.any.sender/blob/da3d14b321974f2079ec598108fdd9426117418a/versions/0.1.8/contracts/Relay.sol#L54">here</a></li></ul><p>While these workarounds can indeed be used now, they are limited and a proper solution will involve a change in the EVM.</p><h3>Proper Solution Against “Insuficient Gas Griefing attack”</h3><p>In order to properly guard against the issue, we need to ensure there is enough gas at the point of the call being made. While the workarounds in the previous section will help developer build safe smart contracts with the EVM today, they are limited and I have thus proposed an EVM improvement, namely <a href="https://eips.ethereum.org/EIPS/eip-1930">EIP-1930</a>.</p><p>In a nutshell, EIP-1930 would allow contracts to call other contracts with a strict gas semantic, that is, if the gas available (including the reduction done by the 1/64 rule) is not enough for the call to forward the amount of gas specified as part of the opcode, the caller get an out of gas exception.</p><p>It can be implemented either as 3 new CALL* opcodes or by reserving specific gas value range (if we can ensure they have never been used before). See the proposal for details.</p><p>This would allow smart contract wallet and meta-transaction in general to ensure that the user’s meta- transaction is given the exact amount of gas specified by the users’ signed message without any extra work or opcode pricing dependent logic. As such relayers would only get a reward if they give the right amount of gas for the transaction to succeed.</p><h3>3. Inner Call Out Of Gas Attack</h3><p>It turns out that the behavior of gas is responsible for yet another issue. Indeed, a gas based attack is also possible on contracts that call other contracts with all gas available (that is 63/64 of all gas available). In other words, while the issue facing meta-transaction mentionned above, is that they cannot ensure easily that the inner call get a specific amount of gas, the attack described below affects any inner call whose failure do not cause the <em>caller</em> to revert.</p><p>The result is somehow similar to a <strong>Call Depth Attack</strong> but different as for example calls like &lt;address&gt;.send won&#39;t fail as these are still given the gas stipend. Indeed, as mentioned above the gas stipend is extra gas and is not affected by the 1/64 rules. As a result such calls are always guaranteed to have 2300 and cannot revert for a lack of gas (assuming of course that the recipient do not use more than 2300, or revert intentionally).</p><p>But the issue has some similar semantic to the <strong>call depth attack</strong> when it is invoked on low level call that catch inner call failure. And these will probably become even more popular with the introduction of “try/catch” in solidity 0.6.</p><p>To illustrate the issue, here is a solidity snippet, with the new try/catch feature of solidity 0.6 but the same applies to lower level calls that check for success.</p><pre>contract Test {<br>    function test() external {<br>        try callNeeding6400000Gas() returns (string message) {<br>            // do something in case of success<br>        } catch {<br>            // do something else in case of failure<br>        }<br>    }<br>}</pre><p>A user calling test can basically make a transaction with a specific amount of gas that result in callNeeding6400000Gas not getting enough gas (&lt; 6,400,000), while the rest of test can continue.</p><p>Let say “do something else in case of failure” consume 50,000 gas. If the user make a transaction with a gasLimit of 6,400,000 gas, when it reaches the inner call, it would not have enough anymore to give that same amount “callNeeding6400000Gas() “. Assuming such inner call was needing that amount, it would fails with an “out of gas exception”. This would result in the catch block being executed, which as we said need 50,000 gas. Since we know that we had around 100,000 gas available (6,400,000 / 64), the transaction will complete sucessfully. The caller, here the Test contract would be unable to know wether the failure was due to a lack of gas or if the inner call simply reverted intentionally.</p><p>As such the widlcard catch should be used with caution. A recent article on Ethereum foundation <a href="https://blog.ethereum.org/2020/01/29/solidity-0.6-try-catch/">blog post</a>, while illustrating nicely the feature, fails to warn user about the potential danger. I hope this blog post will help spread the words and ensure developer carry on with caution.</p><p>A note in that regard has actually already been added to <a href="https://github.com/ethereum/solidity/commit/a3b7c73e3f864da288f3da8bacb778c69a03bce0">solidity documentation</a> after I mentioned the issue to Chris.</p><p>To be clear the issue only arise if there is logic in the try/catch that should not be executed if the <em>callee</em> was expected to revert intentionally. For example if the <em>caller</em> expects a revert in the <em>callee</em> for a specific reason, like rejecting token transfer and perform some different logic when the call revert than when it does not.</p><p>Let illustrates the issue with an example :</p><pre>contract Auction {<br>    ...<br>    ERC20Token token;<br>    address highestBidder;<br>    uint256 highestBid;<br>    function bid(uint256 amount) external {<br>        require(amount &lt; highestBid, &quot;higher bid required&quot;);<br>        address oldBidder = highestBidder;<br>        uint256 oldBid = highestBid;<br>        highestBidder = msg.sender;<br>        highestBid = amount;<br>        require(token.transferFrom(msg.sender, address(this), amount), &quot;transfer failed&quot;);<br>        if (oldBidder != address(0)) {<br>            try token.transferFrom(address(this), oldBidder, oldBid) {<br>            } catch {}<br>        }<br>    }<br>}</pre><p>We assume here that the ERC20 token used is safe in that its functions cannot call back in the contract nor allow the recipient to reject the transfer. Under this conditions, the code above look at first sight completely safe. The try catch would technically be unecessary, but let’s go with it for the sake of the example.</p><p>The reason why it is actually not safe, is, as described above, because the new bidder can provide a specific amount of gas so that there is not enough gas to give to the 2nd transfer call to succeed but enough for the rest. Since there is nothing happening after the try catch the rest will demand not much gas. maybe a few hundreds.</p><p>So if the transferFrom demand something like 20,000 gas (possible with an ERC20 token) it will throw while 20,000 / 64 &gt; 300 gas will be left in the bid call, which might be just enough to complete.</p><p>The astute reader might have noticed that this code is the analogue of the one described <a href="https://blog.ethereum.org/2016/06/10/smart-contract-security/">here</a> except it applies to ERC20 tokens and not ethers.</p><p>This is to illustrate how similar the <strong>Inner Call Out Of Gas Attack</strong> is to the <strong>Call Depth Attack</strong> that we aimed to destroy with EIP-150.</p><p>Obviously the example is made in purpose and might not have any real life equivalent. As for one, as described in the article describing the <strong>**Call Depth Attack**</strong> it is recommended to favour pull over push transfers.</p><p>But the recommendation normally stems from the fact that there are possibilities in the token for the recipient to reject a transfer. Here in the example above, that was not the issue.</p><p>While there might currently be no practical scenario where the attack mention here have any importance, we should remain aware of it. And this is another reason to favor pull over push transfer as mentioned by consensys <a href="https://consensys.github.io/smart-contract-best-practices/known_attacks/#dos-with-unexpected-revert">here</a> and <a href="https://consensys.github.io/smart-contract-best-practices/known_attacks/#dos-with-unexpected-revert">there</a>.</p><p>By the way you can easily try it out in <a href="http://remix.ethereum.org/">remix IDE</a></p><ol><li>Add the following file:</li></ol><pre>pragma solidity 0.6.0;</pre><pre>contract ERC20Token {<br>    event Transfer(address indexed from, address indexed to, uint256 amount);<br>    mapping (address =&gt; uint256) balances;<br>    function transferFrom(address from, address to, uint256 amount) external returns(bool) {<br>        uint256 fromBalance = balances[from];<br>        require(fromBalance &gt;= amount, &quot;not enough balance&quot;);<br>        balances[from] -= amount;<br>        balances[to] += amount;<br>        emit Transfer(from, to, amount);    <br>        return true;<br>    }<br>    function mint(address to, uint256 amount) external {<br>        balances[to] += amount;<br>        emit Transfer(address(0), to, amount);    <br>    }</pre><pre>    function balanceOf(address who) external view returns(uint256) {<br>        return balances[who];<br>    }<br>}</pre><pre>contract Auction {</pre><pre>    constructor(ERC20Token _token) public {<br>        token = _token;<br>    }</pre><pre>    ERC20Token token;<br>    address public highestBidder;<br>    uint256 public highestBid;<br>    function bid(uint256 amount) external {<br>        require(amount &gt; highestBid, &quot;higher bid required&quot;);<br>        address oldBidder = highestBidder;<br>        uint256 oldBid = highestBid;<br>        highestBidder = msg.sender;<br>        highestBid = amount;<br>        require(token.transferFrom(msg.sender, address(this), amount), &quot;transfer failed&quot;);<br>        if (oldBidder != address(0)) {<br>            try token.transferFrom(address(this), oldBidder, oldBid) {<br>            } catch {}<br>        }<br>    }<br>}</pre><ol><li>compile both</li><li>deploy ERC20Token</li><li>deploy Auction (passing the address of the ERC20Token contract as parameter)</li><li>select one account and execute mint with that address and amount = 1000</li><li>execute bid with that exact same amount (1000) (so zero is left in the balance afterward)</li><li>select another account and execute mint for that address with amount = 2000</li><li>execute bid with an amount = 1001 and SPECIFY gasLimit = 60000</li><li>check the balance of the first account and you will see it is still zero. That account did not receive its refund from its previous bid.</li></ol><p>You can then repeat the operartions without limiting the gas to 60000 for step 9. and you will see that the first account will get back the amount as intended.</p><p>This clearly shows that the transaction signer is able to influence the result of a contract call, simply by changing the gasLimit.</p><h3>Conclusion</h3><p>I hope the post was informative and helped elucidate the issue Ethereum developers are facing with the current gas behaviour. In particular how CALL* opcodes behave.</p><p>Help me put forward <a href="https://eips.ethereum.org/EIPS/eip-1930">EIP-1930</a> in the next hardfork as this would solve at least the gas issues faced by all smart contract wallet and meta transaction processor out there.</p><p>Special thanks to <a href="https://twitter.com/whalelephantK">Belsy</a>, <a href="https://medium.com/@fabiohildebrand">Fabio Hildebrand</a> and <a href="https://twitter.com/rolandk">Roland Kofler</a> for reviewing the article.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28d0eb809bb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatic Authentication Signatures For Web3]]></title>
            <link>https://medium.com/@wighawag/automatic-authentication-signatures-for-web3-dcbcbc64d6b5?source=rss-1dd100dcdf63------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcbcbc64d6b5</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[decentralized-web]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[wallet]]></category>
            <dc:creator><![CDATA[Ronan Sandford]]></dc:creator>
            <pubDate>Tue, 15 Jan 2019 11:56:26 GMT</pubDate>
            <atom:updated>2019-01-15T11:56:26.495Z</atom:updated>
            <content:encoded><![CDATA[<p>As part of my <a href="https://medium.com/@wighawag/3-proposals-for-making-web3-a-better-experience-974f97765700">previous article</a>, I described 3 proposals that greatly improve the state of web3 UX. This time I’ll continue with yet another proposal that would allow web3 users to be authenticated on demand without requiring their input providing yet again <strong>an improved user experience without sacrificing security</strong>. It is in some way a variation of the non-interactive signatures described in the <a href="https://medium.com/@wighawag/3-proposals-for-making-web3-a-better-experience-974f97765700">previous article</a>, but <strong>this time without the need for origin checks</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*gUp35FP0HVUlEZswJHKK-w.gif" /><figcaption>Not this kind of automatism :)</figcaption></figure><h3>Introduction</h3><p><strong>It is a common pattern for web3 applications to require their users to authenticate themselves to their back-end</strong> (if they have any) <strong>via their web3 wallet’s signature capability. </strong>This removes the need for a traditional sign-up process that would involve either passwords or some third-party sign-in mechanism and the risks they impose.</p><p>For example <a href="https://cryptokitties.co/">cryptokitties </a>uses such authentication signature mechanism to allows users to be the only one able to modify their kitty name (saved on their back-end, not in the blockchain) and prevent them from modifying the name of others’ kitties and that without ever requiring the users to sign up.</p><h3>How it works</h3><p>When a users visit the cryptokitties website for the first time (or from a new device) <strong>they are asked to sign a message</strong> with their web3 wallet. Since only the private key is able to sign messages, this allow the back-end to ensure that the address exposed by the web3 wallet API, is indeed controlled by the user. This establish authentication. From that point, the user’s authenticated status can then be saved in a cookie to not require further authentication signatures requests.</p><p>While that sounds already better than traditional password authentication, we can do better.</p><p><em>(It is worth noting that cryptokitties </em><strong><em>always use the same friendly message</em></strong><em> and as such is vulnerable to replay attacks (by someone who could get access to the signed message or by malicious application successfully requesting users to sign the exact same message). A proper implementation should inject unforgeable data in the message so no other parties could replay or create a valid message without having access to the private key.)</em></p><h3>Removing user’s confirmation step</h3><p>We could indeed go a bit further and provide an effortless authentication user experience without even needing user confirmation. Indeed, requiring the user to confirm an authentication pop-up like the one used by cryptokitties is actually unnecessary <strong>if wallets can be aware of the nature of the signature request (which should not be used in other contexts) and the verifier (the back-end) injects some unforgeable data in the message to be signed </strong>(not unlike a <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery">CSRF </a>token).</p><p>After all, it is generally assumed that a web3 wallet exposing a specific address has the corresponding private key. The signature required for authentication is only necessary because a dishonest user could simply expose an address as part of the web3 API for which it does not possess the private key.</p><p><strong>Requiring the users to confirm such signature would not increase the security of the mechanism though, as the users have no data to verify by themselves</strong> <strong>since such data is generated by the verifier itself</strong>. This is what allow such signature to be done automatically by the web3 wallet.</p><p>This is unlike the scheme used by cryptokitties which use a static message. Indeed, if such message is reused and no confirmation popup is presented to the user. Any application could generate the valid signature and then use that to maliciously authenticate as the user. This means though that the security of that scheme relies on user’s effort. This is in my opinion a bad user experience but also a security risk that could lead them to authorization fatigue. I’ ll invite you again to read my <a href="https://medium.com/@wighawag/3-proposals-for-making-web3-a-better-experience-974f97765700">previous article</a> which go in more details about this threat.</p><p>Currently though, every web3 wallets out there consider all signature requests equivalent and require users confirmation for all of them as a measure of security. This would need to change.</p><h3>Solution</h3><p>We simply need to come up with an <strong>authentication signature standard (</strong><a href="https://eips.ethereum.org/"><strong>EIP</strong></a><strong>) that would allow web3 wallets to recognize such specific signature requests and perform them without requiring user confirmation.</strong></p><p>This could take the form of a special signature format that wallet would recognise and would not be used in other contexts. I ll not describe a specific scheme here but this could take the form of a specific envelope type for <a href="https://github.com/ethereum/EIPs/pull/712">EIP712</a>.</p><p>To avoid signature replay, the application requesting authentication would have to provide different inputs to it every time like it should do with existing authentication signatures. And as mentioned above, to prevent a, malicious application to generate such authenticated signatures, the message needs to include data that only the correct application knows (like a CSRF token).</p><p>With standard such as <a href="https://github.com/ethereum/EIPs/issues/1271">ERC-1271</a> and <a href="https://github.com/ethereum/EIPs/issues/1654">ERC-1654</a> this could apply to smart contract wallet too.</p><p>For those who read my previous article on the <a href="https://medium.com/@wighawag/3-proposals-for-making-web3-a-better-experience-974f97765700">non-interactive signatures</a>, it is worth mentioning that we could use these for such scheme too. In which case the need for unforgeable data would vanish or inversely if unforgeable data is included, the origin would not need to be inspected by the verifier. They form thus a superset of the proposal outlined in the current article.</p><h3>Conclusion</h3><p>Authenticating web3 users via their wallet is a great UX improvement over traditional web as this does not require the annoying sign-up step nor does it require to use third-party signing to avoid it. <strong>On its own, such capability is a sure sign of the success of web3 over web2</strong>.</p><p>Unfortunately, as it stands it requires the constant use of unnecessary (and misleading) confirmation popup or/and the use of cookies to keep a user authenticated.</p><p>This is not an inherent issue with web3 though. It is simply due to the lack of an <strong>authentication signature standard that would allow wallets to perform such signatures without user confirmation and without reducing security</strong>.</p><p>By implementing an automatic authentication signature standard that allow applications to request signature without confirmations, applications could be sure at any time whether the user behind the exposed address is in control of it. Such mechanism would actually allow application to request such signatures on demand and bypass the need for cookies.</p><p>We could even imagine such standard to accept arbitrary payload and be used beyond simple login authentication. It could for example be used to sign every request made to the back-end.</p><p>Thanks for reading.</p><p>Don’t hesitate to follow me on medium or on <a href="https://twitter.com/wighawag">twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcbcbc64d6b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Proposals For Making Web3 A Better Experience]]></title>
            <link>https://medium.com/@wighawag/3-proposals-for-making-web3-a-better-experience-974f97765700?source=rss-1dd100dcdf63------2</link>
            <guid isPermaLink="false">https://medium.com/p/974f97765700</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[decentralized-web]]></category>
            <category><![CDATA[browsers]]></category>
            <dc:creator><![CDATA[Ronan Sandford]]></dc:creator>
            <pubDate>Fri, 12 Oct 2018 13:07:55 GMT</pubDate>
            <atom:updated>2019-05-24T18:18:37.030Z</atom:updated>
            <content:encoded><![CDATA[<h3>A.K.A. The Case For Automated Origin Checks And Non Interactive Signatures And Decryption</h3><p>Security and usability are often described as being at the expense of one another. But the truth is, without security, you can’t claim to have usability: security issues will bite your users at some point.</p><p>Similarly without usability you run the risk of pushing users to make mistakes compromising their own security. A typical example is <strong>authorization fatigue </strong>where users get asked too many times to confirm actions that in some contexts have very little importance, pushing them to blindly accept any such authorizations, <strong>including the important ones</strong>.</p><p>In the end both of these concepts goes hand in hand. I would like here to explain 3 related proposals, 2 of which I wrote as part of several <a href="https://ethereum.org/"><strong>ethereum</strong> </a><a href="https://eips.ethereum.org/"><strong>EIP</strong></a><strong> </strong>discussions that might not have been explained well enough. I would like here to try to explain the reasoning behind them and why they increase both security and usability and why <strong>we should implement them in web3 browsers today</strong>. Lastly, I bring forward a new proposal to <a href="https://github.com/ethereum/EIPs/pull/712"><strong>EIP712 </strong></a>to reduce authorization fatigue for <strong>when the signed messages in question carry little risks for the user in the context of a trusted application allowing a much nicer user experience</strong>. If I explained the proposals properly you should fall in love with them. For those not familiar with web3, have a look <a href="https://blog.stephantual.com/web-3-0-revisited-part-one-across-chains-and-across-protocols-4282b01054c5"><strong>here </strong></a>and <a href="https://blog.bigchaindb.com/blockchain-will-usher-in-the-era-of-decentralised-computing-7f35e94af0b6"><strong>there</strong></a>.</p><h3>document’s origin</h3><p>The key to understand these proposals is to understand how web3 applications’ front-ends interact with the user through an origin. This concept is borrowed from the web and relates to the same-origin policy implemented in all web browsers. See <a href="https://tools.ietf.org/html/rfc6454"><strong>https://tools.ietf.org/html/rfc6454</strong></a></p><p>To summarize, the origin of a document designates from where it was fetched (in the traditional web this is the domain name, protocol, port number…). And such origin is used to allow or refuse access to data meant to be used solely by one or a set of specified origins. In practise, a document from a particular origin is only allowed access to data put by a document of the same origin. This way one website cannot read or write data created by another website. It is used to allow documents from the same origin access to cookies and local storage for example and, that <strong>without requesting authorization from the user </strong>(you would not like it otherwise, trust me). <strong>This automatism is possible because the browsers can check the origin of a document by itself without user input.</strong></p><p>The origin guarantee is based on DNS security since the origin is usually set to be a domain. This require both trust in the overall DNS system and in the domain owner to not change the application’s content and logic at whim. On web3 though, we can now consider <a href="https://ipfs.io/"><strong>IPFS </strong></a>or <a href="http://swarm-gateways.net/bzz:/theswarm.eth/"><strong>SWARM </strong></a>hashes for example as origins, <strong>providing a much stronger origin guarantee </strong>that forbids the application’s owner to even change the application’s content and logic without also changing the origin. This is because with IPFS and SWARM (or other content-addressable networks) the origin itself encodes the hash of the content.<strong> As such web3 browsers can ensure that the content they fetched belong to the specified origin since changing the content would result in a different hash and thus origin. </strong>Care need to be taken by web3 browser though when such contents fetch non verifiable contents themselves (a.k.a. mixed content, a term also used for when https website fetch http content).</p><h3>Proposal 1: Non-Interactive Decryption</h3><p>While the web’s same-origin policy and its use in cookies and local storage is a very useful mechanism to protect data pertaining to an application, it does not facilitate what is now common : multi-devices use of applications. With web3 and the upcoming encryption methods (see<a href="https://github.com/ethereum/EIPs/issues/130"> <strong>#130</strong></a> and<a href="https://github.com/ethereum/EIPs/pull/1098"> <strong>#1098</strong></a><strong> </strong>as well as <a href="https://ethereum-magicians.org/t/the-ux-of-eip-1024-encrypt-decrypt/1243"><strong>here</strong></a><strong> </strong>and <a href="https://ethereum-magicians.org/t/eip-1024-cross-client-encrypt-decrypt/505"><strong>there</strong></a><strong> </strong>for the latest discussions (thanks <a href="https://medium.com/u/9cdd320de5c9">Dan Finlay</a>)) we will now have the possibility to support freely movable secure storage. The actual storage location won’t matter since it can now be encrypted and thus data will be able to be safely synced across devices.</p><p>Now, it is true that an application could encrypt data with the user public key so only the user could decrypt it. Unfortunately without automated origin checks like the web provides, a malicious app could also request such decryption and <strong>in order for the web3 browser UI to provide information to the user about where the encrypted data came from in the first place, the data in question would need to encode in some way its own origin</strong>. Web3 browsers could then provide a pop-up with clear indication. Unfortunately this would provide a less than ideal user experience.</p><p>Indeed, this means every time applications want to read back encrypted data, they would require the user to confirm a pop-up. This could lead the users to compromise their own security as a result of authorization fatigue <strong>and the users shouldn&#39;t actually need to authorize access when the data in question was created by and for one particular origin</strong>.</p><p>Imagine having to confirm for every cookies before websites can get access? You will soon accept every such request blindly. <strong>You might have already experienced a variation of this with websites that want to track you but want to remain GDPR compliant.</strong></p><p>The non-interactive decryption proposal (described first<a href="https://github.com/ethereum/EIPs/issues/130#issuecomment-329770999"> <strong>here</strong></a>) basically allows applications to encrypt and <strong>decrypt data</strong> on user’s behalf in a similar way that the web provide access to local storage and cookies. Now though since the data is encrypted, it can be synced safely across devices and that <strong>without user confirmation required.</strong> Indeed, it means the users will <strong>not</strong> be asked to confirm decryption when the origin matches the one used for encryption. <strong>After all if the application was responsible for the encryption, if it was indeed malicious, it would already have access to the decrypted data anyway.</strong></p><h3>How does it work?</h3><p>As mentioned in the <a href="https://github.com/ethereum/EIPs/issues/130#issuecomment-329770999"><strong>EIP comment</strong></a>, the idea is to add the origin (actually the origin(s) allowed to decrypt) as part of the data to be encrypted. This way when requesting decryption, the web3 browser can first inspect internally (by decrypting it) such origin(s) and if it matches the origin of the document requesting decryption, it can reveal the data to the application. On the other hand <strong>if the origin does not match, the web3 browser will refuse to pass the decrypted data to the malicious application</strong>. See below for a flow diagram explaining the web3 browser’s role:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*viioAefmbO9gpdUqE8-WlQ.png" /><figcaption>Decrypting data (note that the approval flow (highlighted in red) is very risky for the user and extra care should be taken to ensure the user is aware of what they are doing)</figcaption></figure><p>Note that if a user would like to transfer access to private data from one origin to another, we could accept cross-origin requests but these will be guarded by clear user authorization. The new data will then be encrypted with the new origin and the user can continue using that new application.</p><p>Alternatively, especially for when one application (served via IPFS hash for example) want to upgrade to a new hash/origin, the previous version could have a mechanism to encrypt data for a future origin, allowing such transition without user authorization, <strong>apart obviously from the application’s own confirmation UI.</strong> As a result a trusted application can provide a far better user experience, asking for confirmation only when updating the application’s content and logic.</p><h3>Proposal 2: Automated Origin Checks For Signatures</h3><p>There has been tremendous progress on “security via clarity” for web3 based signature with the introduction of <a href="http://github.com/ethereum/EIPs/pull/712"><strong>EIP712 </strong></a>and when looking at that proposal a while back, I realised the “origin” concept (used in the automated decrypting scheme mentioned above) could also be used there to add extra security. See original comment<a href="https://github.com/ethereum/EIPs/pull/712#issuecomment-330501545"> <strong>here</strong></a>.</p><p>In particular it would protect users from signing data belonging to another application without them realising it:</p><p>Imagine one application, let’s call it “Alice’s app” that allow users to transfer high-value tokens. Imagine then another application (a fun but malicious one), let’s call it “Bob’s app” whose smart contract use EIP712 with a very similar structure than “Alice’s app” but different enough to reassure the user that it does not match such app and cannot affect the tokens the user owns on “Alice’s app”. Now Charles, a user accustomed to “Alice’s app” discover “Bob’s app” and starts using it for a while. He start to get accustomed to the EIP712 signing po-pups and start to care less as the app does not have much value to him, except for the fun experience it provides.</p><p>But then, one day, the malicious app, change the signing request to match “Alice’s app” scheme exactly in order to steal some of Charles token pertaining to that app. While Charles should be able to notice the difference (since he would have never interacted with “Bob’s app” if the signing pop-up show information exactly like “Alice’s app” to begin with), <strong>its acclimatization to “Bob’s app” could result in him accepting the signature by mistake.</strong></p><p>(Note that this same vulnerability applies to “chainId” too which should also be checked by web3 browser. “ChainId” cannot be accessed on the EVM though, see this <a href="https://github.com/ethereum/EIPs/pull/1344"><strong>proposal </strong></a>as an attempt to fix the situation)</p><p>While, as you can see in the <a href="https://github.com/ethereum/EIPs/pull/712">EIP discussion</a>, the proposal as described actually led to some extra security added in the form of a <strong>fixed domain separator.</strong> Such scheme though, relies on the user being aware and accustomed to read carefully what it is signing<strong> all the time</strong>. A malicious application as described above could deliberately make the process so frequent that the user get used to accept confirmations blindly in the the context of that application. This is what <strong>‘authorization fatigue’ </strong>is about.</p><p>An automated origin field on the other hand would make such malicious use <strong>impossible </strong>regardless of users’ attention <strong>since the origin check would be automated</strong>. <strong>Applications would only be able to sign on users’ behalf when the origin added to the data to be signed matches their own origin.</strong></p><p>At that time, I was missing the time to look at the proposal in details but thought with some relative confidence that the “origin” concept will be considered and be part of the standard, especially as one commenter added a well received clarification (see<a href="https://github.com/ethereum/EIPs/pull/712#issuecomment-364495160"> <strong>here</strong></a>). As it turns out though, the proposal as it stand did not add such extra security scheme. I strongly believe we should not approve such proposal without it. This section hopefully clarify why. While there are web3 signer already implementing the current version of EIP712, this should not block us from rejecting its current version as a standard. Let’s aim for the long term.</p><h3>How does it work?</h3><p>Upon signing, the origin (could be the hash of the origin) is inserted as part of the message to be signed. The web3 browser then verify that the specified origin match the current document’s origin. The web3 browser can accept a wild-card origin though (by the application simply omitting it) for the verifiers (smart contracts) that don’t want their users to pay for extra transaction data and or have no use at all for the extra security or simply because the context of the application has no place for a document’s origin.</p><p>See the following flow diagram that show what web3 browsers are supposed to do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZrkoXRlvnafsxggJfbKLQ.png" /><figcaption>Signed origin flow for the web3 browser (note the path highlighted in red is when no origin is provided, acting like a wildcard. This is potentially risky for the user and extra care should be taken to ensure the user is aware of what they are doing)</figcaption></figure><p>The verifier (for example a smart contract) would then be given the signed message and verify the signature the same way as EIP712 currently does. Except this time the data could include the origin in which case the verifier will verify if that particular origin has been approved (by the user) before hand.</p><p>A contract would then have a dynamic set of authorized origins per user. This would allow users to accept or reject origins as they interact with different application front-ends. <strong>This provide a built-in mechanism for per application approval. </strong>The following flow diagram show how a verifier / smart contract could accept extra origins via application/user’s request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*f7sQsmRZ3AjnC_E90nlxRQ.png" /><figcaption>When an application want to request the user to approve its document’s origin</figcaption></figure><p>Let’s imagine one smart contract built by team A. That same team decide to specify the origin of their application front-end at IPFS hash “QmTkzDw…” to be one of the pre-approved origin from the get go (irrespective of user approval). Note that this is probably best practise for smart contracts to have <strong>no</strong> pre-approved origins. For that example though, this would allow the users to be able to start signing messages for that smart contract without any extra step before hand <strong>when and only when navigating through that application’s pre approved origin</strong>. Now if the origin check is part of the smart contract, no other applications could request valid signatures from the users. <strong>As such the smart contract for interoperability purpose would need to allow the users to approve more origins.</strong></p><p>This way, team B could create a competitor front-end for the smart contract by first requesting the users to approve the team B’s front-end’s origin on the smart contract (as shown in the flow diagram above). When executing such method the smart contract would add such origin to the approved list. After that, a signed message with such origin field requested from the user will be accepted.</p><p>An implementation of EIP712 adding an optional origin check can be found here :<a href="https://github.com/wighawag/eip712-origin"> <strong>https://github.com/wighawag/eip712-origin</strong></a><strong> </strong>and see the following flow diagram that show the verifier expected behaviour:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYU3mfmd9olP-ChrphfSdA.png" /><figcaption>The flow for the verifier. The path in red indicates a verifier that do not check origin and accept wildcard origin signatures. This is vulnerable to the authorization fatigue attack mentioned in the article</figcaption></figure><h3>Important note on the different type of origins</h3><p>While it might not be of the scope of the EIP712 proposal to define what are valid origins. <strong>I would suggest web3 browser to warn users when domain names are pointing to IP or other origins that do not provide a mechanism by which the browser could check their validity, and favour content-addressable origin like IPFS and SWARM as the way forward</strong>. <strong>It is also worth pointing that if such verifiable content is mixed with non-verifiable content, a warning should also be present.</strong></p><p>Furthermore, while it could be tempting to support <a href="https://ens.domains/"><strong>ENS </strong></a>names as trusted origin, I would argue that since the entity in control could change its underlying registered URI at whim, the web3 browser should enforce the origin field to match the registered URI (hash) under that name and not the ENS name itself. This way when the owner of the ENS name change the registered URI, t<strong>he users would be protected by first needing to approve the new hash</strong>. The applications’ front-end could obviously facilitate the transition by letting the user know of the underlying change before hand.</p><h3>Proposal 3: Non-Interactive Signatures</h3><p>Proposal 2 actually allow an even more interesting usability feature. Indeed,<strong> the automation of origin verification can actually allow seamless signature generation</strong>. I can predict that this proposal will be more difficult to digest since it breaks a common conception that user private key <strong>is</strong> the user and that no automatism should allow the use of private keys without user’s consent. As I ll show, the extra convenience could mean a lot for some applications and since it can be ignored by others, I<strong> highly recommend implementing such scheme as part of EIP712 on top of Proposal 2 </strong>to push adoption of such standard in web3 browsers and let the application developers decide of its usefulness. This scheme can also alleviates some of the potential authorization fatigue resulting from signing messages with little consequences.</p><p>Indeed, if the origin is checked automatically via web3 browser as mentioned above, it means applications can now request signatures on user’s behalf <strong>without permission</strong> depending on the context.<strong> </strong>Yes, you heard me right. Similarly to the encrypted data as secure synced storage, we can imagine lots of use case / context where it would <strong>not </strong>make sense to ask authorization from the user for every actions that require users’ signatures on top of the existing front-end’s UI.</p><p>Imagine a decentralised social platform where the application’s front-end provides a form with text input and a submit button. It would be for many use cases too much for the users to confirm via an extra scary pop-up after they already pressed the “submit” button. Especially if it is to change some basic information that the users care at minimum. Furthermore, in these cases, the application developer would have actually no incentives to maliciously update such information unless they want to loose their users. Remember that because the origin is checked, such application’s origin would have to be approved by the users first anyway. And if the content of such origin is verifiable (IPFS, SWARM), the source code could be audited to ensure that no malicious behaviour is even possible.</p><p>This is of course application/context specific but this is a decision made on the smart contract (or whatever is in charge of taking action based on the signed messages) and as such <strong>does not pose risks on the applications / smart contract which want to require user confirmation</strong>. They just need to refuse signatures that have been signed without confirmation.</p><p>In my opinion, such scheme will increase security by removing most of the non-important authorization requests that otherwise would have increase users’ authorization fatigue.</p><h3>How does it work?</h3><p>The key idea is to add an extra bit (byte) to indicate that the message was signed non-interactively (without user’s authorization). Of course as you can imagine, such signed messages won’t be accepted for every use cases but <strong>this scheme let the verifier decide.</strong></p><p><strong>Note though that such non-interactive signature requests make sense only if we have automated origin checks.</strong> Without such automated checks, any application would be able to sign any other application’s non-interactive messages on user’s behalf.</p><p>See the following flow diagram showing the expected behaviour of a web3 browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cEst86y8Mt3tJvWlD-Wuyg.png" /><figcaption>flow for web3 browsers that allow non-interactive signatures (without user confirmation) only when origin is provided and checked. (note the path highlighted in red is when no origin is provided, acting like a wildcard origin. This is potentially risky for the user and extra care should be taken to ensure the user is aware of what they are doing)</figcaption></figure><p>The verifier (a smart contract for example) will then as usual hash the message using the domain separator and the origin, including the extra byte (indicating if user confirmation took place or not) and check if the signature matches the expected signer’s address.</p><p>If the smart contract considers that the “action” in question requires user confirmation, it can simply add the bit/byte that indicates the signature was generated via prior user confirmation. Then if the malicious application did actually submit a signature created without user confirmation, the resulting signature will not match (since the interactive bit was different) and the signature will be refused.</p><p>On the other hand for cases where the smart contract considers the action to be of less importance, it can accept an “interactive” boolean as part of the function call that indicate whether the signature was made without user confirmation or not and accept both cases. Note that because of the automated origin checks, the application would only be able to act maliciously if the user pre-approved its origin as mentioned above.</p><p>See the flow diagram below showing the expected verifier’s behaviour:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3azcVHXUnX3d_Jz3I2SPeA.png" /><figcaption>The flow for the verifier. The path in red indicates a verifier that do not check origin and accept wildcard origin signatures. This is vulnerable to the authorization fatigue attack mentioned in the article</figcaption></figure><p>An implementation of EIP712 adding the interactive byte / bit can be found here :<a href="https://github.com/wighawag/eip712-origin"> <strong>https://github.com/wighawag/eip712-origin</strong></a><strong>.</strong></p><h3>Conclusion</h3><p>As mentioned in the introduction, security and usability goes hand in hand. The post then showed that by enforcing origin checks by web3 browsers, we can not only provide stronger security but also a secure distributed storage without the need to request approval from the user.<strong> Unfortunately we still need to wait for the web3 standard to evolve and add decryption and encryption methods</strong>. I invite you to participate in the discussion to push for such methods as they are surely needed (see <a href="https://github.com/ethereum/EIPs/issues/130"><strong>#130</strong></a>, <a href="https://github.com/ethereum/EIPs/pull/1098"><strong>#1098</strong></a>, <a href="https://ethereum-magicians.org/t/the-ux-of-eip-1024-encrypt-decrypt/1243"><strong>here</strong></a><strong> </strong>and <a href="https://ethereum-magicians.org/t/eip-1024-cross-client-encrypt-decrypt/505"><strong>there</strong></a>).</p><p>It also showed that by enforcing origins checks when signing messages (like in EIP712), we can protect users from malicious applications impersonating other applications by pushing the users to authorize blindly. It demonstrated the risk of authorization fatigue that origin checks prevent by letting the web3 browser checks on user’s behalf.</p><p>Lastly we showed an interesting use case of automated origin checks, that of <strong>non-interactive signature</strong>. These would allow applications that already have some confirmation UI (like a submit button) to <strong>bypass the need for an extra scary looking web3 browser signing pop-up that should be reserved for important actions where the applications could have malicious incentive in screwing its user (funds for example).</strong></p><p>Of course as mentioned such scheme is not for everything since it relies on the user trusting the application’s front-end in question. But for those case where a signature is used for minor changes, the gain in usability would bring extra security by reducing authorization fatigue.</p><p>It also worth noting that the combination of encryption with non-interactive signature + non-interactive decryption allows applications to read and write on authenticated storage without user input. Such <strong>storage provider would then be able to safely compartmentalize storage between each user/origin pair since it can authenticate requests of storage based on the signed encrypted data.</strong> What we need now is a decentralised storage that would support such authenticated storage request.</p><p>The work done on <a href="https://github.com/uport-project/3box-js"><strong>3box</strong></a><strong> </strong>by <a href="https://www.uport.me/"><strong>UPort</strong></a><strong> </strong>with <a href="https://github.com/orbitdb/orbit-db"><strong>orbit-db</strong></a><strong> </strong>could be a possible solution that would greatly benefit from the automated decryption and signature scheme mentioned above, removing the need for users to keep authorizing access and thus improving greatly the overall experience.</p><p>This has been a long post and I hope this had made my proposals a lot clearer than the ones spread over the EIP discussions. Let me know what you think.</p><p>I ll be coming to the <a href="https://web3summit.com/"><strong>web3 summit</strong></a> and <a href="https://devcon4.ethereum.org/"><strong>devcon 4</strong></a><strong> </strong>and would love to chat about such proposals. I ll be at the ethereum magicians’<a href="https://ethereumevents.global/events/2018-council-of-prague/"><strong> council of Prague</strong></a> so find me there and let’s improve the state of usability and security for the web3 ecosystem together.</p><p>Thanks for reading.</p><p>Don’t hesitate to follow me on <a href="https://twitter.com/wighawag">twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=974f97765700" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State Channels and Interactivity limitations]]></title>
            <link>https://medium.com/@wighawag/state-channels-and-interactivity-limitations-2872912f9d73?source=rss-1dd100dcdf63------2</link>
            <guid isPermaLink="false">https://medium.com/p/2872912f9d73</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[state-channels]]></category>
            <category><![CDATA[games]]></category>
            <dc:creator><![CDATA[Ronan Sandford]]></dc:creator>
            <pubDate>Thu, 09 Aug 2018 10:05:26 GMT</pubDate>
            <atom:updated>2018-08-09T10:05:26.874Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>State channel is often described as a way to scale and speed up operations on a blockchain network without sacrificing much security. They are described as fee-less and nearly instant.</p><p>These 2 claims hold only in particular cases though. In a state channel network (as opposed to ad-hoc channel between only 2 participants), fees become required for example to ensure propagation across the network.</p><p>As for the “instant” property, it only holds true in the best case when channel participants are honest. What this means is often overlooked it seems and in this article I would like to describe what it means in the context of a 2 players card game using an ad-hoc state channel for simplicity.</p><h3>State channels</h3><p>I won’t describe in details what state channel are here but for those not familiar, there are few resources :</p><p><a href="https://www.jeffcoleman.ca/state-channels/">State Channels - an explanation</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMEL50CVOcH4%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMEL50CVOcH4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMEL50CVOcH4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f85caa75b91db724ad42bf4558a2ca94/href">https://medium.com/media/f85caa75b91db724ad42bf4558a2ca94/href</a></iframe><p><a href="https://medium.com/l4-media/making-sense-of-ethereums-layer-2-scaling-solutions-state-channels-plasma-and-truebit-22cb40dcc2f4">Making Sense of Ethereum’s Layer 2 Scaling Solutions: State Channels, Plasma, and Truebit</a></p><p>In a nutshell, state channel allow transactions to happen offchain by letting the participants agree on state changes until the last. This means that once a channel is open, state changes can happen at the speed of light.</p><h3>Worst case scenarios</h3><p>While this sounds perfect, the catch is that the logic that need to verify the validity of off-chain messages need to be computed on a blockchain in case of conflict.</p><p>Furthermore, in order to allow both participants to claim their rights, conflict resolution need to give time to both participants to respond. Since such resolution happens on-chain the time is unfortunately of blockchain scale.</p><h3>A card game example</h3><p>What this means in the context of a card game for example is that each turn need to consider the worst case scenario and allows players to resolve conflict on the blockchain if needs arise, <strong>making real time game impossible with state channels alone.</strong></p><p>Let say Alice and Bob want to play a game off-chain. Assuming they already established a channel between them, they send each other messages to play the game at the speed of internet.</p><p>Then let say that after some time Alice is not receiving any messages from Bob. If we are dealing with a game of cards with 30 seconds turn, she should be able to claim victory or a “default move” from Bob after that time elapsed. But this would not be fair:</p><p>If this could work like that she would then submit Bob’s last message plus her own last move on-chain to grab the money. Unfortunately, she could well be lying. Bob might have sent the message already​ and is waiting for Alice’s next message.</p><p>To cater for these case, the smart contract should allow Bob to reply to Alice’s on-chain claim. And Bob should be watching the blockchain.</p><p>And here again, if indeed Alice cheated, it would be correct to give the money to Bob and end the game there.</p><p>Unfortunately, it could also be that it was Bob, not sending the message and waiting in purpose for Alice to bring the game on-chain. Bob could have done that in purpose to render the game unplayable by bringing the full game resolution on-chain. This makes it impossible to have a 30s game, even less a real time game.</p><p>Note again, that it does not matter if this on-chain resolution takes place or not. The game would need to be able to continue working on blockchain time scale. Imagine you play a real time first person shooter game and suddenly the opponents is not responding. As described above, to ensure fairness the game need to allow both player to come back to the game after on-chain resolution happened. Unfortunately for this kind of game, this would be unacceptable since the gameplay relies on eye-hand coordination.</p><h3>Need for an another solution</h3><p>This is a unacceptable situation. While there is no advantages for players to be playing on the blockchain, a malicious player like Bob with maybe more money, could suffer the cost and win by waiting the other player to give up. Bob could well be prepared to go on chain to maybe win few cents while Alice might just be playing for the fun and give up as soon as the cost of the onchain transaction compete with the prize in place.</p><p>In other words, since games would need to cater for blockchain times, in the order of minutes as opposed to near instant interaction as promised for offchain messages, <strong>the application of state channels for interactive application (like games) stay limited to specific types of application that can accept blockchain times as worst case scenario</strong>. Remember that this is the case because we need to cater for worst case scenario. If two honest players plays, the game could indeed be played with fast interactions but since the game would need to consider the worst case, a real time game could not be run using such technology alone.</p><h3>So where does this lead us to?</h3><p>There is of course ways to solve this using a central operator but how could we solve this issue in a decentralized way?</p><p>We basically need a reliable decentralized time-stamping service that will sign each player’s message with its time of reception.</p><p>And what technology could provide time-stamping reliably in a decentralized manner? A blockchain of course. But we are then back to square one with “slow” consensus.</p><p>Are they any alternative?</p><p>At Etherplay (<a href="http://etherplay.io/">http://etherplay.io</a>) we started thinking about a middle ground solution involving a set of witnesses.</p><p>The idea is to have several witnesses to chose from. Once two players agree on one, the chosen time-stamping service is used to prove to the others the existence of its previous message at specific times.</p><p>Of course, the chosen witness could collude with one of the player to claim existence of previous messages while not providing it at the time of the game.</p><p>In order to de-incentivize this behavior, witnesses could get paid a fee and get reputation score. This would allow player to select fair witnesses and punish unfair one.</p><p>This is not a perfect solution and open a whole can of worms. Nevertheless this could work for games as the rewards of one game would not be significant enough compared to the value of the witness reputation. Further works need to be done to design such system though.</p><p>One nice property of this potential time-stamping witness system is that it is game/app agnostic since their role is not to verify the game logic, but to prove reception of messages at specific times.</p><p>In other words, we need just one of this system running for all state channel games/apps that would require it, potentially increasing its decentralization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2872912f9d73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum Session Accounts]]></title>
            <link>https://medium.com/@wighawag/ethereum-session-accounts-fc61fb930dac?source=rss-1dd100dcdf63------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc61fb930dac</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Ronan Sandford]]></dc:creator>
            <pubDate>Tue, 03 Oct 2017 10:10:10 GMT</pubDate>
            <atom:updated>2022-01-10T12:07:46.234Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>For the last 3 month I have been working on Tug Of War (website is now down) a fully decentralised game, a game that run entirely on the <a href="https://ethereum.org/">ethereum </a>blockchain. It is now running on the testnets and we describe it in more details <a href="https://medium.com/@etherplay/our-first-unstoppable-game-tug-of-war-bb69c63a8734">here</a> .</p><p>We basically wanted to build a pure blockchain game with a fun interface and we had to make sure the game experience was as smooth as possible. Since the game required several interactions (for each move) we wanted to get rid of most transaction confirmation popup as we could so players could stay engaged in the game. The obvious solution was to build our game using state channels.</p><p>As it turned out, state channels added some undesirable timing complexity. In the situation where one of the player did not turn up, an extra timeout was required and the other player had to make sure to send a transaction in time to make its case recorded on the blockchain even though none of the player could be sure if the other player sent the message or if it was lost on the way. The simple timeout period became more complex and this had to be reflected on the interface causing potential confusion for the players.</p><p>On top of that due to the nature of the game, state channels didn’t bring much advantages apart from a potentially lower gas cost. It is also worth noting that by having the game running entirely on the blockchain, it did not require any server and become an unstoppable game by itself. We might reconsider state channel though for later games.</p><p>Tug of War is a turn based game where turn can be as long as 24h to ensure players can still play asynchronously on their own schedule. On the other hand if both players are online, they could well finish the game in 30 minutes. If you did not play it yet, I encourage you to do so <a href="http://tugofwar.io/">here</a> . If you did play you might have wondered how come the game run on the blockchain with only one transaction per player. It turns out that there is one transaction per move but they are hidden from view.</p><p><strong>Session accounts</strong></p><p>Our solution to get rid of most confirmation popup is actually quite simple and I was surprised to not see it used elsewhere since there are several dapps out there that require you to confirm many transactions for one particular task.</p><p>The solution is as follow : upon starting a game, a player gives rights to a temporary account that will make the next moves instead on its behalf. We used to call these account “shadow account” but a better name could well be “session account” since they operate like a short lived session.</p><p>These accounts’ private key are generated and stored client side. This was not an issue for our game since a secret was also required to be stored to account for the “hash and reveal” scheme used.</p><p>Upon setting the session account the first transaction also send some fund to it to cover the future moves’ gas cost. It means you need to be able to predict the gas required for the future interactions. This was trivial to compute the maximum gas required for our game but this is a lot higher than an average game’s requirement. Hence a refund mechanism was needed : On the final move, the funds not used by the session account are given back to the player account.</p><p><strong>Smart contract</strong></p><p>On the smart contract side, the method called as part of the first transaction (to create/start the game) is given the address of the session account by the player (that generated it client side) and store it. This method also transfers fund to that session account as gas allowance to be able to make further call by itself.</p><p>The other methods that are to be called during the session (in our case a game is a session) check whether the sender is the assigned session acount or the original player (we still allow player to execute the transaction in case gas run out, for example due to gas price increase). That’s basically it: the session account can now act on behalf of the player. It means the player can perform actions without requiring approval via interrupting popups.</p><p>The last bit is that the session account send the fund not used back to the player when the session ends. While this could be done independently of the smart contract we allow the final transaction to pass a value so that the session account can give back the fund to the player at the same time as calling that last method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*3QgwZpvM9Yn5FT82oPWHVw.png" /></figure><p><strong>interface side requirements</strong></p><p>This solution requires the safe storage of private key and currently the web3 api do not offer an api to encrypt such data.</p><p>The web3 api would benefit in having such method. There is a EIP for it here : <a href="https://github.com/ethereum/EIPs/issues/130">https://github.com/ethereum/EIPs/issues/130</a> and I hope it get adopted sooner rather than latter. In the mean time we plan do it ourselves but would require the player to remember another passphrase.</p><p>On the fully decentralised side of thing we will also require a way to store data in a secure deterministic location. Swarm has plan to tackle this too and I look forward to where it leads.</p><p><strong>Conclusion</strong></p><p>The use of session account allows players to focus on the game and not get bothered with scary ethereum transaction popup for every move. As player you might almost wonder if you really are playing on a blockchain.</p><p>You can have a look at the smart contract here : <a href="https://rinkeby.etherscan.io/address/0x8242e199f7d0559403f668e8d75db7c90c49a2af#code">https://rinkeby.etherscan.io/address/0x8242e199f7d0559403f668e8d75db7c90c49a2af#code</a></p><p>The create method and start method accept a “shadow” argument. This get stored and they get sent a gas allowance. Then for every functions that need authentication, the sender is checked against that account.</p><p>This could be applied to other dapp too that require several transactions for one bigger task. We actually plan to use it for our own skill game platform (<a href="http://etherplay.io/">http://etherplay.io</a>) so a player’s score is automatically submitted. You might have a use case for it too.</p><p>Thanks for reading</p><p>Do not hesitate to leave a comment if you have any questions</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc61fb930dac" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>