<?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 Maurelian on Medium]]></title>
        <description><![CDATA[Stories by Maurelian on Medium]]></description>
        <link>https://medium.com/@maurelian?source=rss-703568bf3986------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AW1mbHWcIh7sSOj4XJboOw.jpeg</url>
            <title>Stories by Maurelian on Medium</title>
            <link>https://medium.com/@maurelian?source=rss-703568bf3986------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 01:13:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maurelian/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[Questions DeFi users should be asking DeFi Developers]]></title>
            <link>https://medium.com/consensys-diligence/questions-defi-users-should-be-asking-defi-developers-1effe51509ce?source=rss-703568bf3986------2</link>
            <guid isPermaLink="false">https://medium.com/p/1effe51509ce</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Maurelian]]></dc:creator>
            <pubDate>Mon, 02 Mar 2020 17:37:52 GMT</pubDate>
            <atom:updated>2020-04-22T23:28:44.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TFjLcEPkz6i-2WuG.jpg" /><figcaption><a href="https://unsplash.com/photos/i--IN3cvEjg">Photo by Evan Dennis on Unsplash</a></figcaption></figure><p><em>Originally published at </em><a href="https://diligence.consensys.net/blog/2020/03/questions-defi-users-should-be-asking-defi-developers/"><em>https://diligence.consensys.net</em></a><em> on March 2, 2020, republished here because holy crap this stuff just keeps happening.</em></p><p>The DeFi space has had a tumultuous couple months, with a number of attacks as well as unexploited vulnerabilities being reported.</p><p>Bugs are unavoidable, but there are many things that can be done to reduce their frequency, and mitigate their negative effects.</p><p>As auditors, we want to help, but in order to really get developers to truly prioritize security, users need to start asking tough questions, and putting their money into the protocols that can answer them thoughtfully.</p><p>The following list of questions is useful for understanding a development team’s security stance. There isn’t always a right or wrong answer, and some teams (or solo developers) don’t have the resources to cover all the bases, regardless users deserve to have the information to decide what level of risk they are comfortable with.</p><p>We hope that asking these question will push the conversation in the right direction.</p><h3>1. Admin permissions</h3><p>The majority of popular defi protocols have some form of centralized control that enables specific ‘administrator’ addresses to intervene in powerful ways.</p><p>This has some security benefits, but it means that you have to trust the administrator(s) not to abuse their privileges. It also adds the risk of an attacker gaining access to an administrator’s private keys, and all the privileges that come with them.</p><p>An administrator account can take several possible forms, including a single address, a multisig wallet, or even be a DAO controlled by a voting process.</p><ul><li>What special actions can administrators take?</li><li>Pausing the system?</li><li>Modifying balances?</li><li>Whitelisting/blacklisting of tokens and/or users?</li><li>Upgrading a subset of the system.</li><li>Upgrading all of the system (which is equivalent to omnipotence).</li><li>Anything else?</li><li>Which of these actions ones do and do not have a time delay on them?</li><li>If there is a time delay, how long is that time delay?</li><li>How many people have administrator privileges?</li><li>How many of those admins must approve before some action is taken?</li><li>Are any administrative actions controlled by on-chain governance (ie. a DAO)?</li><li>Where can I stay up to date about proposed changes to the protocol?</li></ul><p>Some of this information is already being tracked at <a href="https://defiwatch.net/admin-key-config-and-opsec/project-reviews">DefiWatch</a>.</p><h3>2. External Dependencies</h3><p>The Ethereum chain is full of adversarial actors, so in general developers should avoid making any assumptions about how contracts from other systems will behave. In many DeFi applications this is not possible, as services are built on top of existing contracts.</p><p>These questions should help expose risks related to external dependencies.</p><ul><li>What oracles does your system depend on?</li><li>What exchanges does your system depend on?</li><li>What 3rd party smart contracts did you use to build your system (ie. OpenZeppelin)?</li><li>What tokens does your system support, and what assumptions do you make about their functionality?</li></ul><h3>3. Responsible disclosure and bounty programs</h3><p>For talented hackers, there are strong financial incentives to attack DeFi protocols. Having a bounty program in place creates a financial incentive to report vulnerabilities rather than exploit them. Reporting a vulnerability through a bounty program is also good for a hacker’s reputation, and the added benefit of not being illegal.</p><p>Any company running a DeFi protocol, with people’s money on the line, should have a bounty program. Here are some good questions you can ask about their program and disclosure process:</p><ul><li>Is the source code of your contracts publicly available?</li><li>Is it easy to find the security contact information on your website and git repos?</li><li>Do you have a bounty program on your contracts?</li><li>Which contracts are in scope?</li><li>What is the range of bounty payments?</li><li>Have you ever made a bounty payment?</li><li>Have you ever denied payment on a bug report?</li><li>Is it easy to find details of the bounty program on your website and git repos?</li></ul><p>Ideally this information would all be found at “website.com/security” and make use of GitHub’s SECURITY.md feature.</p><h3>4. Incident response planning</h3><p>It’s difficult for developers to think clearly during a security incident, while new information keeps coming in, and users are asking tough questions on Twitter, Telegram, Discord etc…</p><p>Having a plan is evidence of a healthy orientation towards security. It may not make sense for a team to make their full plan public, but they should be able to answer some basic questions about it:</p><ul><li>Do you have a written plan outlining how to handle a security incident?</li><li>Which scenarios does your plan take into consideration?</li><li>If your system is upgradeable, are the steps to do so well documented?</li><li>If you discover a vulnerability which places funds at risk, would you preemptively exploit it to protect the funds?</li></ul><h3>5. Audits and secure development</h3><p>Auditing is not a silver bullet, and not all audits are equal, but it is a crucial step for any DeFi contracts before deployment.</p><p>There isn’t necessarily a ‘right answer’ for each of these questions, but the answers should enable knowledgeable community members to get a feel for the developer teams’ security stance.</p><ul><li>When was your last audit?</li><li>How much effort (in person-hours) went into the audit?</li><li>Which firm(s) performed it?</li><li>Is the report public?</li><li>Was any portion of your system excluded from the scope?</li><li>Have your contracts been upgraded since your last audit? If so, what changed?</li><li>Do you have an ongoing relationship with any security firms?</li><li>Do developers review each other’s PRs (at least in Solidity files) before merging?</li><li>What portion of your contract code is covered by unit tests?</li><li>Do you use any other security analysis tools in your process?</li></ul><p>For DeFi users interested in keeping up with these matters, another project to watch is ConsenSys’ <a href="https://defiscore.io/">DeFi Score</a>, which is taking on the difficult task of evaluating the <a href="https://codefi.consensys.net/blog/the-defi-score-in-action-bzx-report">quality of audits</a> and other security processes on various major DeFi projects.</p><p><em>Thank you to </em><a href="https://twitter.com/The3D_"><em>Emilio</em></a><em> and Ernesto (@eboado on Telegram) (both Aave developers), and </em><a href="https://twitter.com/jack_clancy93"><em>Jack</em></a><em> from DeFi Score for providing feedback on earlier drafts of this post.</em> Thinking about smart contract security? We can provide training, ongoing advice, and smart contract auditing.<a href="https://diligence.consensys.net/contact">Contact us</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1effe51509ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/consensys-diligence/questions-defi-users-should-be-asking-defi-developers-1effe51509ce">Questions DeFi users should be asking DeFi Developers</a> was originally published in <a href="https://medium.com/consensys-diligence">Consensys Diligence</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Prepare for a Smart Contract Audit]]></title>
            <link>https://medium.com/consensys-diligence/how-to-prepare-for-a-smart-contract-audit-9d2934e74b88?source=rss-703568bf3986------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d2934e74b88</guid>
            <category><![CDATA[audit]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Maurelian]]></dc:creator>
            <pubDate>Tue, 17 Sep 2019 16:00:00 GMT</pubDate>
            <atom:updated>2019-09-20T14:36:52.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="checklist" src="https://cdn-images-1.medium.com/max/1024/0*wbGE17M9VI3TOO9o.jpg" /><figcaption><a href="https://unsplash.com/photos/RLw-UC03Gwc">Photo by Glenn Carstens-Peters</a></figcaption></figure><p><em>Originally published at </em><a href="https://diligence.consensys.net/posts/2019/09/how-to-prepare-for-a-smart-contract-audit/"><em>https://diligence.consensys.net</em></a><em> on September 17, 2019.</em></p><p>An audit is an investment in the security of your smart contract system. Besides selecting a high quality auditor for the work ( <a href="https://diligence.consensys.net/contact/">contact us here</a>), there are several things you can do to make sure you get the most out of your investment.</p><p>Following these steps to prepare for an audit will go a long way to helping you get the best results.</p><ol><li>Documentation</li><li>Clean code</li><li>Testing</li><li>Automated Analysis</li><li>Frozen code</li><li>Use a checklist</li></ol><h3>1. Documentation</h3><p>The less time we spend trying to understand your system, the faster we can get deep into your code, and the more time we can spend finding bugs. This is why the number one thing you can do to improve the quality of your audit is provide good documentation.</p><p>Good documentation starts with a <em>plain English</em> description of what you are building, and why you are building it. It should do this both for the overall system <em>and</em> for each unique contract within the system.</p><p>Another marker of good documentation is that it includes a specification of your system’s intended functionality. For each contract, it should describe the most important properties or behaviors that should be maintained. It should also describe the actions and states that should not be possible.</p><p>One of the best examples we’ve seen is the <a href="https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#trade-settlement">protocol spec for the 0xProject</a>. In particular, their use of flow charts nicely illustrates how the system fits together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-GfwEbTZD9Jy5B0q.png" /></figure><p>Don’t let me scare you off. Good documentation requires a lot of effort. If you don’t have the capacity to put it together, we can help. Writing our own documentation of the code’s behavior is an excellent way to understand it. It can even lead us to discover vulnerabilities and unexpected edge cases.</p><p><strong>What about a pseudocode spec?</strong> I placed an emphasis on “plain English” above (as opposed to rigid/formal English) because plain English more clearly expresses what you <em>want</em> the code to do. By contrast, the actual code is often so similar to the pseudocode specification that it can be hard to see when they both describe something you do not actually want.</p><p>Pseudocode does have its place and can be especially helpful for precisely describing complex mathematics, but it should always be accompanied by some English about what the math is meant to achieve.</p><h3>2. Clean code</h3><p>Polished, well-formatted code is easier to read, which reduces the cognitive overhead needed to review it. A little bit of cleanup will go a long way towards allowing us to focus our energy on finding bugs.</p><ol><li>Run a linter on your code. Fix any errors or warnings unless you have a good reason not to. For Solidity, we like <a href="https://www.ethlint.com/">EthLint</a>.</li><li>If the compiler outputs any warnings, address them.</li><li>Remove any comments that indicate unfinished work (ie. TODO or FIXME).<br><em>(This is assuming it&#39;s your final audit before deploying to mainnet. If not, exercise your judgement about what makes sense to leave in.)</em></li><li>Remove any code that has been commented out.</li><li>Remove any code you don’t need.</li></ol><h3>3. Testing</h3><p>Write tests! A good goal is a test suite with <a href="https://en.wikipedia.org/wiki/Code_coverage">100% code coverage</a>.</p><p>Review the list of test cases for gaps. Are your tests mostly focused on making sure the the ‘happy path’ works? Write some tests to verify undesirable actions are properly protected against, and that the contract fails properly instead of landing in an undesired state.</p><p><strong>Important:</strong> Your README should give clear instructions for running the test suite. If any dependencies are not packaged with your code (e.g. Truffle), list them and their exact versions.</p><h3>4. Automated Analysis</h3><p>Ethereum has many good security analysis tools to help find some of the most common issues. We use some of these during our audits, though you can also run them in advance, which will allow us to spend our time looking for trickier bugs.</p><p>Our <a href="https://mythx.io/">MythX</a> suite, which runs several kinds of analysis at once, is a great place to start. There are many ways to submit your contracts for analysis, including CLI tools for JavaScript and Python as well as plugins for Remix and Truffle. You can find more security tools listed in our <a href="https://consensys.github.io/smart-contract-best-practices/security_tools/">Smart Contract Best Practices</a>.</p><p>It’s not essential to do this, but it helps. A caveat is that you will often get warnings about issues that don’t actually exist. If you’re unsure if something is an issue, just let us know and we’ll assess it during the audit.</p><h3>5. Frozen code</h3><p>At the risk of stating the obvious, you should be done with development of your smart contracts before we audit them.</p><p>At the start of our audit, we’ll confirm that you’ve “frozen the code” (i.e. halted development), and we’ll ask for a specific git commit hash to be the target of our audit.</p><p>If a change comes in halfway through an audit, it means the auditors wasted time on old code. In addition, the auditors would have to stop and incorporate the change, which can have wide-ranging impacts on things like the threat model and other code that interacts with the changed code.</p><p>If your code won’t be ready by the scheduled start date, let us know. It’s better to delay altogether than try to complete an audit while you continue development.</p><h3>6. Use a checklist</h3><p>I’ve summarized these steps in a <a href="https://gist.github.com/maurelian/13831f1940340e0dcd0482555eb5c4fe">markdown checklist</a> that you can copy and paste for use in your own project.</p><h3>Conclusion</h3><p>A little bit of work to prepare for an audit will go a long way to getting you the most value out of the process.</p><p>If you’re thinking about an audit for your smart contracts, or have other questions about smart contract security <a href="https://diligence.consensys.net/contact/">get in touch</a>! Sooner is better as we’re typically booking projects 6 to 8 weeks out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d2934e74b88" width="1" height="1" alt=""><hr><p><a href="https://medium.com/consensys-diligence/how-to-prepare-for-a-smart-contract-audit-9d2934e74b88">How to Prepare for a Smart Contract Audit</a> was originally published in <a href="https://medium.com/consensys-diligence">Consensys Diligence</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart Contract Securiety Newsletter 19 — MythX, IBM X-Force Red, Security Considerations for EIPs]]></title>
            <link>https://medium.com/consensys-diligence/smart-contract-securiety-newsletter-19-mythx-ibm-x-force-red-security-considerations-for-eips-8c7c16160af9?source=rss-703568bf3986------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c7c16160af9</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Maurelian]]></dc:creator>
            <pubDate>Mon, 11 Mar 2019 03:11:30 GMT</pubDate>
            <atom:updated>2019-03-13T16:15:17.682Z</atom:updated>
            <content:encoded><![CDATA[<h3>Smart Contract Security Newsletter 19 — MythX, IBM X-Force Red, Security Considerations for EIPs</h3><p><em>Sign up to get this newsletter every week: </em><a href="https://tinyletter.com/smart-contract-security/">https://tinyletter.com/smart-contract-security/</a></p><h3>MythX is Real!</h3><p>(<a href="https://medium.com/consensys-diligence/mythx-is-real-f3fafd86685e">medium.com/consensys-diligence</a>)</p><p>Our MythX security analysis API (<a href="https://docs.mythx.io/">docs.mythx.io</a>) launched in public beta this past week! It’s free for anyone to use, for a limited time.</p><blockquote>MythX is a security analysis platform for Ethereum smart contracts. It allows any developer or development team to perform a comprehensive range of industry-leading analyses on smart contracts, including an input fuzzer, a static code analyzer, linter, and a symbolic analyzer. All accessible through an easy-to-use API.</blockquote><h3>IBM “X-Force Red” Launches Blockchain Cybersecurity Service</h3><p>(<a href="https://newsroom.ibm.com/2019-03-050-IBM-X-Force-Red-Launches-New-Service-for-Blockchain-Security-Testing">newsroom.ibm.com</a>)</p><p>From the press release:</p><blockquote>With worldwide spending on blockchain solutions forecasted to reach $9.7 billion by 2021, the number of blockchain implementations will likely grow exponentially across all industries.1 Meanwhile, the benefit of the network effect inherent to blockchain networks means they include broad, decentralized ecosystems of organizations, which in turn offers different attack vectors than traditional applications and creates opportunities for cybercriminals seeking to manipulate or monetize the data being shared on the blockchain.</blockquote><p>The offering (<a href="https://www.ibm.com/security/services/blockchain-testing">https://www.ibm.com/security/services/blockchain-testing</a>) appears to be quite broad, not specifying any particular blockchain technology, and includes the full stack:</p><blockquote>IBM X-Force Red is seeing that 70 percent of solutions that incorporate blockchain rely on traditional technologies for backend processes like authentication, data processing and Application Programming Interfaces (API). The X-Force Red Blockchain Testing service will evaluate the whole implementation including chain code, public key infrastructure and hyperledgers. X-Force Red will also test backend processes, applications and physical hardware used to control access and manage blockchain networks.</blockquote><h3>EIP: mandatory “Security Considerations” for EIPs</h3><p>(<a href="https://ethereum-magicians.org/t/eip-mandatory-security-considerations-for-eips/2839">ethereum-magicians.org</a>)</p><p>This week in the “wow, that makes a lot of sense” category, my colleague tintinweb drafted a meta-EIP that would require all EIPs to include a ‘Security Considerations’ section.</p><p>As an interesting historical note, the EIP (Ethereum Improvement Proposal) process was inspired by BIPs (Bitcoin Improvement Proposal)… which was inspired by Python’s PEP (Python Enhancement Proposals)… which was inspired by the IETF’s RFC process (Internet Engineering Task Force / Request For Comments). RFCs do have a Security Considerations section, unfortunately somewhere on the path from RFC to EIP, it seems to have been forgotten.</p><p>Another recent proposal (<a href="https://ethereum-magicians.org/t/security-review-period-for-hardfork-roadmap/2721">eth-magicians.org</a>) which is nicely complimentary suggests instituting a “defined review period time where the specific purpose is security”.</p><h3>Also this week</h3><h4>On efficient Ethereum Storage (using a CREATE2 hack) — (<a href="https://medium.com/coinmonks/on-efficient-ethereum-storage-c76869591add">medium.com/coinmonks</a>)</h4><h4>What is Ghidra? The Reverse Engineering tool the NSA just open sourced — (<a href="https://twitter.com/ErrataRob/status/1103098102716813313">Robert Graham on Twitter</a>)</h4><h4>SOLTIX: Scalable automated framework for testing Solidity compilers — (<a href="https://github.com/eth-sri/soltix">github.com/eth-sri</a>)</h4><h4>A python based solidity parser — (<a href="https://github.com/ConsenSys/python-solidity-parser">github.com/consensys</a>)</h4><p>That’s all for this week, thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c7c16160af9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/consensys-diligence/smart-contract-securiety-newsletter-19-mythx-ibm-x-force-red-security-considerations-for-eips-8c7c16160af9">Smart Contract Securiety Newsletter 19 — MythX, IBM X-Force Red, Security Considerations for EIPs</a> was originally published in <a href="https://medium.com/consensys-diligence">Consensys Diligence</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart Contract Security Newsletter #17 — MythX, False Positives on chain, & Front Running]]></title>
            <link>https://medium.com/consensys-diligence/smart-contract-security-newsletter-17-mythx-false-positives-on-chain-front-running-d22f6aefc361?source=rss-703568bf3986------2</link>
            <guid isPermaLink="false">https://medium.com/p/d22f6aefc361</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[newsletter]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Maurelian]]></dc:creator>
            <pubDate>Sun, 24 Feb 2019 22:22:31 GMT</pubDate>
            <atom:updated>2019-02-26T18:06:20.726Z</atom:updated>
            <content:encoded><![CDATA[<h3>Smart Contract Security Newsletter #17 — MythX, False Positives on chain, &amp; Front Running</h3><p><em>Sign up to get this newsletter in your inbox every week: </em><a href="https://tinyletter.com/smart-contract-security/">https://tinyletter.com/smart-contract-security/</a></p><p>Happy Sunday everyone! I normally try to have this out by Saturday night, so I’m a bit tardy this week.</p><p>Brief housekeeping note: in the last couple weeks my emails have started getting caught by a lot of spam filters. If you find this in your spam, and your email client gives you an explanation for why, <strong>please let me know!</strong> I’ve gone back to the previous subject format (ie. ===), so… maybe that will help?</p><p>Lastly, I’m experimenting a bit with how I include links. TinyLetter masks them with lame tracking URLs, and it’s annoying to have no idea where a link will take you. If you think this approach is better, or if it impacts the readability, I’d appreciate a quick note from you.</p><h3>Distilled News</h3><h4>Why you should Buidl on the MythX API</h4><p>(<a href="https://medium.com/consensys-diligence/why-you-should-buidl-on-mythx-api-and-earn-revenue-share-in-dai-13d8bc7ca803">medium.com/consensys-diligence</a>)</p><p>I’m so excited that our MythX platform will go into public beta in early March! By combining static code analysis, guided grey-box fuzzing and symbolic execution it covers twice as many security weaknesses as Mythril Classic, and is 10 times faster.</p><p>Tool devs who integrate can earn 25% on subscription revenues generated by their users.</p><h4>Academic paper: Smart contract vulns does anyone care?</h4><p>(<a href="https://arxiv.org/pdf/1902.06710.pdf">PDF on arxiv</a>)</p><p>You may recall several papers in the last year or so, each introducing a new analysis technique or tool, and listing some very large number of vulnerable on-chain contracts they had identified.</p><p>This paper surveys those findings, and suggests that there were quite a few false positives in the findings.</p><blockquote><em>We find that at most 504 out of 21,270 contracts have been subjected to exploits. This corresponds to at most 9,094 ETH (1 million USD1), or only 0.30% of the 3 million ETH (350 million USD) claimed in some of the papers. While we are certainly not implying that smart contract vulnerability research is without merit, our results suggest that the potential impact of vulnerable code had been greatly exaggerated.</em></blockquote><p>Interestingly, they also found surprisingly little overlap in the set of broken contracts each paper listed, which further suggests a large number of false positives.</p><h4>Taxonomy of Front Running Attacks</h4><p>(post <a href="https://medium.com/consensys-diligence/transparent-dishonesty-taxonomy-of-front-running-attacks-on-blockchain-317d8ff78068">medium.com/consensys-diligence</a>, pdf at <a href="https://arxiv.org/abs/1902.05164">https://arxiv.org/abs/1902.05164</a>)</p><p>“Front Running” attacks on smart contracts occur anytime an attacker can gain an advantage by inserting a transaction before yours. As Phil Daian has described in detail (ie. <a href="https://slideslive.com/38911605/smart-contract-security-incentives-beyond-the-launch">his Devcon4 talk</a>), this is <em>very</em> common with decentralized exchanges (ie. seeing a large price-moving buy-order, and racing to get a buy-order in first). However, there are several variations on this pattern, which are different enough to makes the whole concept of “front running” feel vague.</p><p>At last week’s Financial Cryptography conference, my teammate Shayan Eskandari presented a paper which adds a lot of clarity, by describing 3 distinct categories of front running (‘Displacement’, ‘Insertion’ and ‘Suppression’). This slide sums it up nicely:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SoWtr8Y4s_rxxUgV.jpg" /></figure><h3>Links</h3><ul><li><strong>Last call on EIP 615</strong>: Subroutines and static jumps for the EVM (<a href="https://ethereum-magicians.org/t/eip-615-subroutines-and-static-jumps-for-the-evm/2728/21">ethereum-magicians forum</a>).</li><li>Can the capabilities of CREATE be stretched enough to fulfill the intent of CREATE2? Not quite, but if you ignore the snarky tone, it’s a good thought experiment. (<a href="https://medium.com/coinmonks/why-create2-e99b6afcc28c">“Why CREATE2” on Medium</a>).</li><li>Eveem creator Tomasz Kolinko, has some nice slides about: “Finding all the underflows in mainnet contracts” (<a href="http://eveem.org/static/underflows.pdf">PDF at eveem.org</a>).</li><li>Coinbase CEO Brian Armstrong’s <a href="https://twitter.com/brian_armstrong/status/1098656491609849856">twitter thread</a> suggesting that QuadrigaCX has been running “fractionally” (a la MtGOX), ever since June 2017 (<a href="https://www.reddit.com/r/ethereum/comments/6ettq5/statement_on_quadrigacx_ether_contract_error/">reddit post</a>) when they locked 67000 ETH in an ETH/ETC splitter contract (<a href="https://etherscan.io/address/0x1e143b2588705dfea63a17f2032ca123df995ce0#code">Etherscan</a>).</li><li>From Zac Mitton, a “generalized merkle-patricia-proof module” in js that now supports Ethereum state proofs (<a href="https://github.com/zmitton/eth-proof">github.com/zmitton</a>).</li></ul><p>Want to help make this newsletter better? Join the #maurelians-newsletter channel in <a href="https://discord.gg/ffRsZCm">MythX’s discord chat</a>.</p><p>Want more weekly goodness? Read my friends’ stuff!</p><p>Ben’s <a href="https://notes.ethereum.org/c/Sk8Zs--CQ">“What’s new in ETH 2.0”</a>Evan’s <a href="https://weekinethereum.substack.com/">“Week in Ethereum”</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ls67NPcQ4-eITuYM.png" /></figure><p>This newsletter is supported by <a href="https://consensys.net/diligence">ConsenSys Diligence</a>, where I work. We can help with all things smart contract security; auditing, secure development guidance, and training.</p><p>We’re also building the <a href="https://mythx.io/">MythX</a> platform for smart contract security analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*diW8dkMPyO9GS79VJQX84A.png" /></figure><h3>We’re hiring!</h3><p><a href="https://consensys.net/open-roles/1129067/">Developer — Security Analysis Tools</a><br><a href="https://consensys.net/open-roles/1401943/">Frontend and Dapp Engineer, MythX</a><br><a href="https://consensys.net/open-roles/1420298/">Marketing and Brand Manager, MythX</a><br><a href="https://consensys.net/open-roles/609611/">Security Engineer and Auditor — Smart Contracts</a><br><a href="https://consensys.net/open-roles/1401927/">Senior Technical Recruiter</a><br><a href="https://consensys.net/open-roles/902518/">Smart Contract Security Business Development Lead</a><br><a href="https://consensys.net/open-roles/1401931/">Technical Product Manager, MythX</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d22f6aefc361" width="1" height="1" alt=""><hr><p><a href="https://medium.com/consensys-diligence/smart-contract-security-newsletter-17-mythx-false-positives-on-chain-front-running-d22f6aefc361">Smart Contract Security Newsletter #17 — MythX, False Positives on chain, &amp; Front Running</a> was originally published in <a href="https://medium.com/consensys-diligence">Consensys Diligence</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart Contract Security Newsletter #16 — CREATE2 FAQ]]></title>
            <link>https://medium.com/consensys-diligence/smart-contract-security-newsletter-16-create2-faq-b641405044bf?source=rss-703568bf3986------2</link>
            <guid isPermaLink="false">https://medium.com/p/b641405044bf</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[newsletter]]></category>
            <dc:creator><![CDATA[Maurelian]]></dc:creator>
            <pubDate>Mon, 18 Feb 2019 15:50:55 GMT</pubDate>
            <atom:updated>2019-02-19T00:39:00.629Z</atom:updated>
            <content:encoded><![CDATA[<h3>Smart Contract Security Newsletter #16 — CREATE2 FAQ</h3><p><em>Sign up to get this newsletter every week: </em><a href="https://tinyletter.com/smart-contract-security/">https://tinyletter.com/smart-contract-security/</a></p><h3>Distilled News</h3><p>This week was a little bit slow in the sense that there were no “major incidents”. Though there has been a lot of chatter about CREATE2 (EIP-1014) this week.</p><h4>So, what is all this stuff about CREATE2?</h4><p>I thought I’d try to distill that down a bit, and an FAQ format felt like the right way to do it.</p><h4>What is CREATE2?</h4><p>It’s a new opcode for deploying smart contracts. Similar to CREATE, when CREATE2 is called in a contract (which I’ll refer to as the ‘factory’) it will run some init_code. Whatever that init_codereturns will be the code in the new contract. In Solidity, this init_code is defined by a constructor() function.</p><h4>How is it different from CREATE?</h4><p>The important difference is in how the address of the new contract is determined.</p><p>With CREATE the address is determined by the factory contract’s nonce. Everytime CREATE is called in the factory, it’s nonce increases by 1.</p><p>With CREATE2, the address is determined by an arbitrary salt value, and the init_code.</p><h4>Why do we need it?</h4><p>The big advantage of CREATE2 is that the destination address is not dependent on the exact state (ie. the nonce) of the factory when it’s called. This allows for the result of a transaction to be simulated off-chain, which is an important part of many <strong>state channel</strong> based approaches to <em>scaling</em>.</p><h4>So what is everybody so worked up about?</h4><p>Recalling two things I wrote above:</p><ol><li>Whatever that init_code returns will be the code in the new contract.</li><li>With CREATE2, the address is a function of an arbitrary salt value, and the init_code.</li></ol><p>So here’s the key detail: if CREATE2 is run twice in the <strong>same factory contract</strong>, with the <strong>same </strong><strong>salt</strong>, and the <strong>same</strong><strong>init_code</strong>, it will result in a <strong>second contract</strong> being deployed to the <strong>same address as the first contract</strong>!</p><h4>OK, so… then what happens?</h4><p><em>If</em> the first contract is still at the address when CREATE2 tries to put a new contract there, the operation will simply REVERT; which is fine.</p><p>But a few other facts complicate the story:</p><ol><li>Another infamous opcode, SELFDESTRUCT, is also lurking within the EVM.</li><li>The same init_code can return different values at different times.</li></ol><h4>How could an attacker make use of this?</h4><p>An example attack that this would enable goes like this:</p><ol><li>Using CREATE2, deploy a safe looking contract.</li><li>Convince some people to deposit their ETH, Tokens, Kittens, etc.</li><li>Call SELFDESTRUCT on that safe looking contract, and it will be removed from state.</li><li>Using CREATE2 again, replace it with a malicious contract that sends all the funds to you.</li></ol><h4>My god that’s horrible</h4><p>Right!?</p><h4>What can we do about it?</h4><p>Even if a contract was deployed by CREATE2, the attack would not be possible if it doesn’t contain a SELFDESTRUCT, DELEGATECALL, or CALLCODE opcode.</p><p>That kind of analysis could technically be run by wallets and block explorers to warn users, but this is quite a burden to place on them.</p><p>(Interestingly, Etherscan shows a <a href="https://ropsten.etherscan.io/address/0x7973d5166b9526b9e4e63595293d6b895d2d4fe3#code">“reinit” warning</a> on the Ropsten testnet (where CREATE2 is live), although if you’re seeing that warning it’s already too late. )</p><h4>Why weren’t people talking about this earlier?</h4><p>This to me is one of the more interesting things, ie. the pattern of bugs not being found, or possible issues not being discussed until the last minute.</p><p>The Constantinople fork was postponed with 48 hours notice before due to a potential vulnerability completely unrelated to CREATE2. So, this public conversation very easily may not have happened before the change was made permanent.</p><p>The <a href="https://medium.com/the-ethereum-name-service/security-lessons-from-the-ens-launch-c5bc96bf439e">ENS launch</a> was the same; two serious bugs were discovered the day of it’s launch.</p><h4>What should we do to get more attention on these things?</h4><p>Some <a href="https://twitter.com/MattCorva/status/1095836317202698240">advocate bug bounties</a>, which worked recently for Gnosis’ dxDAO. But bounties often see very little activity, and because of the economics, bounty hunters tend to look broadly for easy to find bugs.</p><p>In order to ensure the security of protocol changes, both a deep and holistic review is required. The <a href="https://www.coindesk.com/ethereum-developers-delay-mining-algorithm-change-for-code-audit">audit being done on ProgPOW</a> is a good start in that direction.</p><h4>What do I think about CREATE2?</h4><p>Well… scaling is essential, and state channels are extremely promising, so I want the improvements it brings. But I’m starting to think the side effects are excessively dangerous. A suggestion I find compelling was put forward by Nick Johnson:</p><blockquote><em>I honestly think the simplest solution to all of this would have been to modify self destruct to leave an account’s nonce intact. Selfdestruct is already an ineffective way to encourage freeing state, and this would solve the issues.</em></blockquote><h4>More CREATE2 links:</h4><ul><li><a href="https://twitter.com/mhswende/status/1093995835518537728?s=09">Tweet by Martin Swende iniating the conversation</a></li><li><a href="https://twitter.com/technocrypto/status/1096111100859420673">An informative tweetstorm by Jeff Coleman</a></li><li><a href="https://ethereum-magicians.org/t/potential-security-implications-of-create2-eip-1014/2614/1">An extremely thorough forum discussion</a></li></ul><h3>Other Good Links</h3><ul><li><a href="https://medium.com/consensys-diligence/poison-block-explorer-byte-code-bcf034a5d132"><strong>Poison block explorer byte code</strong></a><strong>:</strong> A rather clever attack devised by my teammate Daniel Luca</li><li><a href="https://medium.com/agoric/preventing-reentrancy-attacks-in-smart-contracts-3899bf837f23"><strong>Preventing Reentrancy attacks in smart contracts</strong></a><strong>:</strong> Ideas for an async smart contract programming model (in javascript believe it or not)</li><li><a href="https://www.parity.io/new-parity-ethereum-update-fixes-several-rpc-vulnerabilities/"><strong>New Parity Ethereum update fixes several vulnerabilities</strong></a><strong>:</strong> There were some more bugs. Update yer Paritys.</li><li><a href="https://www.smartcontractaudits.com/"><strong>smartcontractaudits.com</strong></a><strong>:</strong> A listing of audit providers</li><li><a href="https://medium.com/limechain/etherlime-debugger-is-here-to-unravel-transactions-d628a4e6686"><strong>“Etherelime”</strong></a><strong>:</strong> A new debugger</li><li><a href="https://blog.gtank.cc/modern-alternatives-to-pgp/"><strong>Modern alternatives to PGP</strong></a><strong>:</strong> warning, nothing whatsover to do with blockchains</li></ul><p>Want to help make this newsletter better? Join the <a href="https://discord.gg/ffRsZCm">#maurelians-newsletter channel in the MythX</a>discord chat.</p><p>Want more weekly goodness? Read my friends’ stuff!</p><p>Ben’s <a href="https://notes.ethereum.org/c/Sk8Zs--CQ">“What’s new in ETH 2.0”</a>Evan’s <a href="https://weekinethereum.substack.com/">“Week in Ethereum”</a></p><p>This newsletter is supported by <a href="https://consensys.net/diligence">ConsenSys Diligence</a>, where I work. We can help with all things smart contract security; auditing, secure development guidance, and training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dvhd2U5KEUBxdmDq.png" /></figure><h3>We’re hiring!</h3><p><a href="https://consensys.net/open-roles/1129067/">Developer — Security Analysis Tools</a><br><a href="https://consensys.net/open-roles/1401943/">Frontend and Dapp Engineer, MythX</a><br><a href="https://consensys.net/open-roles/1420298/">Marketing and Brand Manager, MythX</a><br><a href="https://consensys.net/open-roles/609611/">Security Engineer and Auditor — Smart Contracts</a><br><a href="https://consensys.net/open-roles/1401927/">Senior Technical Recruiter</a><br><a href="https://consensys.net/open-roles/902518/">Smart Contract Security Business Development Lead</a><br><a href="https://consensys.net/open-roles/1401931/">Technical Product Manager, MythX</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b641405044bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/consensys-diligence/smart-contract-security-newsletter-16-create2-faq-b641405044bf">Smart Contract Security Newsletter #16 — CREATE2 FAQ</a> was originally published in <a href="https://medium.com/consensys-diligence">Consensys Diligence</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An early look at Vyper]]></title>
            <link>https://medium.com/@maurelian/an-early-look-at-vyper-d101e0c349c1?source=rss-703568bf3986------2</link>
            <guid isPermaLink="false">https://medium.com/p/d101e0c349c1</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Maurelian]]></dc:creator>
            <pubDate>Mon, 12 Feb 2018 22:44:17 GMT</pubDate>
            <atom:updated>2018-02-12T23:35:21.999Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently dug into <a href="http://vyper.readthedocs.io/">Vyper</a>, a new language for the Ethereum Virtual Machine, with a python like syntax.</p><p>I presented a brief tutorial of my investigation to about 20 of my colleagues at ConsenSys. I was excited to take a look at the Vyper team’s perspective on contract design, but ultimately struggled to understand many of the design decisions.</p><p>This post is meant as a friendly critique of what I found. Realizing that the language is still experimental, I hope it’s helpful that I share my impressions sooner than later.</p><p>First, I should say that although Python was my first language, I am much<br>stronger in JS and Solidity. So there may be ‘pythonic’ design elements <br>which I misunderstand.</p><p>Secondly, I will try to frame my comments with respect to the <a href="https://vyper.readthedocs.io/en/latest/index.html#principles-and-goals">stated design <br>goals for the language</a>. They are very laudable goals, which are what <br>initially attracted me to the language:</p><blockquote><strong><em>Principles and goals</em></strong></blockquote><blockquote><strong>1. Security:</strong> It should be possible and natural to build secure smart-contracts in Vyper.<br>2. <strong>Language and compiler simplicity: </strong>The language and the compiler implementation should strive to be simple.<br>3. <strong>Auditability: </strong>Vyper code should be maximally human-readable. Furthermore, it should be maximally difficult to write misleading code.</blockquote><p>I’m particularly interested in the “Auditability” portion. Although the term is not explicitly defined, I believe an auditable language would include:</p><ul><li>explicit over implicit syntax (ie. function visibility must be declared, there is no default)</li><li>low cognitive overhead to differentiate between types, and track state variables</li></ul><h4>The code and my impressions</h4><p>The following is a toy contract I wrote, which is mostly a grab bag of functionality to see what I could get to compile. In order to communicate my likes and dislikes, it seemed easiest to just include it as comments in the code itself.</p><p>I wrote whatever I was trying to do in square brackets, ie.[Declare a storage variable] followed by my comments on attempting to do that thing. You can also <a href="https://gist.github.com/maurelian/0ab71465b467e991680698de75c3fe9e">read it on Github</a> if you prefer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbb9c7dd5c801d894efd41e67aafdfee/href">https://medium.com/media/cbb9c7dd5c801d894efd41e67aafdfee/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d101e0c349c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Smart Contract Best Practices for UX and Interoperability]]></title>
            <link>https://medium.com/consensys-media/beyond-smart-contract-best-practices-for-ux-and-interoperability-6d94d27c1e0f?source=rss-703568bf3986------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d94d27c1e0f</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Maurelian]]></dc:creator>
            <pubDate>Thu, 07 Dec 2017 19:49:52 GMT</pubDate>
            <atom:updated>2017-12-07T21:04:40.140Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post is intended to spark discussion, not immediately undo a well established approach to secure smart contract development. Read and follow this advice with caution.</em></p><p>I spend a fair bit of time helping to maintain ConsenSys’ <a href="https://consensys.github.io/smart-contract-best-practices/">Smart Contract Best Practices</a> guide. Given the impact the <em>Best Practices</em> have had on the craft of writing smart contracts in the Ethereum ecosystem, it’s a responsibility I take seriously. I believe everyone writing smart contracts on Ethereum, (in any language not just Solidity), should learn and refer back to our best practices frequently.</p><p>I also believe that in order to create the blockchain applications that will truly change how humanity collaborates, we must:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*BjBJIRD7xwWv1tj0n7DwWw.png" /><figcaption>(Picasso <a href="https://news.ycombinator.com/item?id=7754905">may not </a>have actually said that, but you can imagine he did)</figcaption></figure><p>This is the first of a short series of articles, in which I’ll discuss when, and how to consider breaking some of the prevailing best practices. We’ll see where it goes, but I expect to give this treatment to the following:</p><ol><li><a href="https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls">Favor pull over push for external calls</a></li><li><a href="https://consensys.github.io/smart-contract-best-practices/recommendations/#be-aware-of-the-tradeoffs-between-send-transfer-and-callvalue">Prefer </a><a href="https://consensys.github.io/smart-contract-best-practices/recommendations/#be-aware-of-the-tradeoffs-between-send-transfer-and-callvalue">address.send(), and </a><a href="https://consensys.github.io/smart-contract-best-practices/recommendations/#be-aware-of-the-tradeoffs-between-send-transfer-and-callvalue">address.</a><a href="https://consensys.github.io/smart-contract-best-practices/recommendations/#be-aware-of-the-tradeoffs-between-send-transfer-and-callvalue">t</a>ransfer() <a href="https://consensys.github.io/smart-contract-best-practices/recommendations/#be-aware-of-the-tradeoffs-between-send-transfer-and-callvalue">over </a><a href="https://consensys.github.io/smart-contract-best-practices/recommendations/#be-aware-of-the-tradeoffs-between-send-transfer-and-callvalue">address.</a><a href="https://consensys.github.io/smart-contract-best-practices/recommendations/#be-aware-of-the-tradeoffs-between-send-transfer-and-callvalue">call()</a></li><li><a href="https://consensys.github.io/smart-contract-best-practices/known_attacks/#timestamp-dependence">Use block numbers instead of timestamps</a></li></ol><p>Here we go:</p><h3>Part 1. Revisiting “pull over push for external calls”</h3><p>A common recommendation (not only in our documentation), is to make ETH transfers with a “Pull”, rather than a “Push”.</p><p>What this means, is that when a transaction results in a contract owing a a balance of ETH to a user, rather than sending the ETH right away, the user should collect their balance with a separate withdrawal transaction. This prevents a failed transfer from blocking the normal operation, and makes the rest of the contract unusable for anyone else.</p><p>The image below shows the <a href="https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls">“Pull over Push” examples in the Best Practices</a>, with the bad example on the left, good example on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5zXAhMje8PSf2nB0Xu8q8g.png" /></figure><p>This is a very safe recommendation, but it also punishes the 99.9% of people who don’t look like this:</p><pre>pragma solidity ^0.4.0;<br>contract RuinsThePartyForEveryone{}</pre><p>A simple change to the Best Practices pattern, to improve the user experience would be:</p><ol><li>try to send</li><li>if it fails, simply queue up a refund</li></ol><p>Here’s how the example shown above would look if we do that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/156ecce121d1488223acdfefc6c661ea/href">https://medium.com/media/156ecce121d1488223acdfefc6c661ea/href</a></iframe><p>All we had to do was add an extra if condition, to handle a failed .send() .</p><h3>Examples in the wild</h3><h4>BlockParty’s journey from push to pull</h4><p>My friend Makoto got me thinking about this with his post outlining the evolution (or UX devolution?) of the refund mechanism in BlockParty:</p><p><a href="https://medium.com/@makoto_inoue/a-smartcontract-best-practice-push-pull-or-give-b2e8428e032a">A SmartContract best practice: Push, Pull, or Give?</a></p><p>BlockParty is an event application that collects a fee from attendees to save them a spot. If you attend you get your money back, if you don’t attend your money is divided evenly among the attendees.</p><p>After the event, the owner calls the payout() function. His post describes the decision to make the <a href="https://github.com/makoto/blockparty/commit/74857ed687b145ec5053de611e827fb8d4468c00#diff-55340df5ccefa1a922c729284ddee347">following change</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGdIoz3px-14FD4A51Op-g.png" /><figcaption><strong>WARNING: in the code on the left, if you invite too many friends you’ll run into a </strong><a href="https://consensys.github.io/smart-contract-best-practices/known_attacks/#dos-with-block-gas-limit"><strong>different problem</strong></a><strong> with gas limits.</strong></figcaption></figure><p>Before the change, the worst that can happen is the highlighted line returns false, but the transaction marches on. After the change, the worse that can happen is some people forget, or never bother to come claim their payouts. Which pattern is<em> less bad</em> is a judgement call you get to make.</p><h4>How the ENS Registrar decides if a failed send should throw</h4><p>Another approach can be seen in the ENS Registrar contract, which implements a fairly complex Vickery auction for name space.</p><p>For a little bit of a background, any ETH sent to the Registrar to bid on an auction are held in a unique Deed contract. Each Deed has an owner, and a balance. The Registrar contract can decrease the balance by calling this <a href="https://github.com/ethereum/ens/blob/master/contracts/HashRegistrarSimplified.sol#L64-L70">setBalance()</a> function:</p><pre>function setBalance(uint newValue, bool throwOnFailure)      <br>  onlyRegistrar <br>  onlyActive <br>{        // Check if it has enough balance to set the value             <br>  if (value &lt; newValue) throw;        <br>  value = newValue;        // Send the difference to the owner           <br>  if (!owner.send(this.balance - newValue) &amp;&amp; throwOnFailure) throw;    <br>}</pre><p>Notice the bool throwOnFailure argument? As the name suggests, it’s used to determine how to handle a failed send. If you look at how it’s used in the code, you’ll notice a pattern:</p><p>If the send fails, the call will onlythrow if it interferes with an action by the owner of the deed. Take for example the following scenario:</p><ol><li>you reveal a new bid,</li><li>becoming the new highest bidder,</li><li>causing ETH to be sent to the old highest bidder</li><li>but the old highest bidder is a contract which fails to receive the payout,</li><li>well too bad.</li></ol><p>The Registrar never allows an throwing receiver contract to prevent others from taking action. A call to the Registrar only throws on a failed send, when it prevents the receiver themselves from completing an action.</p><h3>Conclusion</h3><p>Once you understand the reasoning behind best practices, you can begin to identify situations where those reasons might be outweighed by other considerations, in this case UX. Choose wisely.</p><p><em>Thank you to Goncalo Sa, </em><a href="https://medium.com/u/4380e912132e"><em>Mike Goldin</em></a><em>, </em><a href="https://medium.com/u/9afbf877fa2f"><em>Simon de la Rouviere</em></a><em> for providing feedback on this post. Thank you also to </em><a href="https://medium.com/u/d069a785929c"><em>Raine Rupert Revere</em></a><em> for her talk at Devcon3, which touches on this idea, and to </em><a href="https://medium.com/u/3714a5b1af38"><em>makoto_inoue</em></a><em> for his post which made me write this post.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d94d27c1e0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/consensys-media/beyond-smart-contract-best-practices-for-ux-and-interoperability-6d94d27c1e0f">Beyond Smart Contract Best Practices for UX and Interoperability</a> was originally published in <a href="https://medium.com/consensys-media">ConsenSys Media</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Devcon3 Security Round Up]]></title>
            <link>https://medium.com/@maurelian/devcon3-security-round-up-e7754cd30c23?source=rss-703568bf3986------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7754cd30c23</guid>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Maurelian]]></dc:creator>
            <pubDate>Fri, 03 Nov 2017 19:50:01 GMT</pubDate>
            <atom:updated>2017-11-19T22:44:41.299Z</atom:updated>
            <content:encoded><![CDATA[<p>The second day of Devcon3 was packed with security topics. It’s going to take me some time to synthesize all that information, this post is a first attempt at trying to do that.</p><p><em>Many links to resources are missing, and I’m sure there are ideas that I’m not conveying clearly. Please comment if you have a useful link, or a correction I should make.</em></p><p>I’ve grouped the ideas into 3 themes, along with a few miscellaneous observations</p><ol><li>Tools</li><li>Formal verification</li><li>New languages</li></ol><h3>Tools</h3><p>Although our tools have improved tremendously in the past year (ie. Truffle’s debugger, and huge usability improvements to Remix), we still have a long, long way to go.</p><p>There were a couple very cool new tools relevant to security introduced this week:</p><h4>EVM-LAB</h4><p>In his talk, Martin Swende made the interesting observation that even when different EVM implementations agree on the state root hash, it’s possible for there to be ‘ephemeral disagreements’ in the stack and memory, which could be manipulated to cause a consensus failure.</p><p>In order to address this, Geth and Parity have introduced a standard trace object, which can be outputted after after <em>every EMV operation</em> during the execution of a transaction. This enabled him to create opviewer (aka Retromix), which is an in terminal version of the Remix debugger, and is part of his <a href="https://github.com/holiman/evmlab">EVM-Lab</a> tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nyw9bGU1s0eiwJTnS9IQ8Q.png" /><figcaption>Martin Swende’s ‘Retromix’</figcaption></figure><p>He also discussed the Ethereum Foundations work using <strong>fuzz testing</strong> to scale consensus testing between different EVM implementations.</p><p><strong>More information:</strong></p><p><a href="https://github.com/holiman/evmlab">evmlab repository</a><br><a href="https://github.com/holiman/evmlab/blob/e2d281636436b5aceba97ff68450879daf53e086/containers/testeth/README.md">TestEth</a> (fuzzing in evmlab)<br><a href="https://github.com/holiman/evmfuzz">evmFuzz repository</a><br><a href="https://youtu.be/8sXzxkODH-c?t=2h11m59s">Talk recording</a></p><h4>Zeppelin OS</h4><p>Manuel Araoz discussed Zeppelin OS, which promises a robust approach to upgrading contract logic on chain. It also comes with a new zeppelin_os command line tool, which I&#39;m sure will be full of goodies.</p><p><strong>More information:<br></strong><a href="https://zeppelinos.org/">Site</a><br><a href="https://zeppelinos.org/data/zeppelinOS_Whitepaper_Draft.pdf">Whitepaper</a><br>Talk Recording: <em>Not yet available</em></p><h4>Static Analysis</h4><p>We heard an update from Loi Luu about Oyente, as well as a newer entry from Securify. Both tools perform their analysis at the bytecode level, and are able to identify common classes of vulnerabilites such as re-entry.</p><p><strong>More information:<br></strong><a href="https://oyente.melon.fund/">Oyente IDE</a> <br><a href="https://eprint.iacr.org/2016/633.pdf">Oyente paper</a> <br>Talk Recording: <em>Not yet available</em></p><p><a href="https://securify.ch/">Securify site</a><br>Talk Recording: <em>Not yet available</em></p><h4>Hydra Framework</h4><p>Hydra is an interesting project from the prolific Phil Daian (and his talented colleagues), taking a 3-pronged approach to security:</p><ol><li>Formal verification and specification</li><li>escape hatches</li><li>bug bounties</li></ol><p>Hydra introduces a concept called an <em>exploit gap;</em> a way for developers to turn crippling exploits into safe, decentralized bounty payments using a new form of fault tolerance called N-of-N Version Programming (NNVP).</p><p><a href="https://github.com/IC3Hydra/Hydra">Hydra Repo</a> Paper: <a href="https://thehydra.io/paper.pdf">https://thehydra.io/paper.pdf</a> <br><a href="https://docs.google.com/presentation/d/1jqqBeQx2B7hoqM5_al4UvYerIYx5Se1AFGTuahQMu6M">Slides</a> <br>Talk Recording: Not yet available</p><h3>New languages</h3><p>A lot of work and research effort is going into building new EVM languages which incorporate lessons learned from solidity. I especially love learning about these projects, because they give a new lens through which to view the EVM, and contract architecture in general. Even if you never deploy a contract written in anything but solidity, learning a new EVM language will make you a better smart contract developer.</p><h4>Viper</h4><p>I was fortunate to get a tutorial from <a href="https://github.com/DavidKnott">David Knott</a>, a primary contributor to the Viper compiler. Viper’s design is more constrained than Solidity. For instance, Viper doesn’t support contract inheritance, and doesn’t have modifiers, both of which are essential features in Solidity. There are also plans for a rich typing mechanism which could ensure for example that a value is always derived from the same units (ie. price = wei/currency).</p><p><a href="https://github.com/ethereum/viper">Viper repository</a> <br><a href="http://viper.readthedocs.io/en/latest/">Viper Docs</a></p><h4>Bamboo</h4><p>Bamboo is a functional programming language being designed by Dr. Yoichi, (formal verification engineer at the Ethereum foundation). Bamboo uses makes state transitions explicit, while having the “sugarly syntax to trap solidity developers”. Incidentally, Yoichi’s dry humor is hilarious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sa4EZC4l0sBR6-vl-8eRXQ.png" /></figure><p>Although very early, I think Bamboo is promising, and I’m excited to watch this project evolve.</p><p><a href="https://yoichihirai.com/yoichi-bamboo.pdf">Talk slides</a> <br><a href="https://github.com/pirapira/bamboo">Bamboo repository</a> <br>Talk Recording: <em>Not yet available</em></p><h4>Babbage</h4><p>Christian Reitwiessner’s Babbage is a <em>visual</em> programming language which models smart contracts as machinery. Keeping with the trend of other languages, it’s less expressive, and more constrained than solidity.</p><p>Medium post: <a href="https://medium.com/@chriseth/babbage-a-mechanical-smart-contract-language-5c8329ec5a0e">https://medium.com/@chriseth/babbage-a-mechanical-smart-contract-language-5c8329ec5a0e</a> Paper: <a href="https://chriseth.github.io/notes/articles/babbage/babbage.pdf">https://chriseth.github.io/notes/articles/babbage/babbage.pdf</a> Slides: <a href="https://chriseth.github.io/notes/talks/babbage_devcon3/#/7">https://chriseth.github.io/notes/talks/babbage_devcon3/#/7</a> Talk Recording: TBD</p><h4>Solidity improvements</h4><p>Though solidity lacks the shiny newness of the more experimental languages, Solidity continues to mature, becoming more battle hardened with each release (and each vuln).</p><p><strong>Julia IR<br></strong>Alex Beregszaszi introduced Julia, a new intermediate language to be used in the Solidity compiler. Julia promises to make the compiler more less complex and more maintainable. It could also help with auditing contract systems, and even adapting solidity to new VMs.</p><p><strong>SMTChecker<br></strong>Christian Reitwiessner demonstrated the new SMTChecker, which can formally verify that certain error conditions (such as under/overflow, or invalid states) are unreachable.</p><p>He demonstrated with this code, though I haven’t yet figured out how to access the SMTChecker feature.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/984a7fb72a2b50afbb0a6abe0ff04e43/href">https://medium.com/media/984a7fb72a2b50afbb0a6abe0ff04e43/href</a></iframe><p>Slides: <a href="https://chriseth.github.io/notes/talks/solidity_update_devcon3/">https://chriseth.github.io/notes/talks/solidity_update_devcon3/</a></p><h3>Formal verification</h3><h4>K-EVM</h4><p>Everett Hildenbrandt presented K-EVM, an implementation of the EVM, in the “K” language. K provides a formally defined set of semantics, enabling formal reasoning, and theorem proofs about programs. It also comes with a rich toolset for analysis, and has been used for formal verification in other languages including C.</p><p>This project will eventually give us new tools to ease the process of writing and proving specifications about programs written in high-level languages. Another team is extending K-EVM provide a formal verification of the Viper compiler!</p><p>Paper: <a href="https://github.com/kframework/evm-semantics">https://github.com/kframework/evm-semantics</a></p><h4>Formally verifying Casper</h4><p>Yoichi has been hard at work on verifying Casper (the friendly finally gadget), his talk provided a great update on the evolution of the protocol, as well as outlining the assumptions which he is working on proving.</p><p>Slides: <a href="https://yoichihirai.com/yoichi-verifying-casper.pdf">https://yoichihirai.com/yoichi-verifying-casper.pdf</a></p><h3>Good old secure programming</h3><p>Perhaps my favorite session of all was a panel reflecting on the Underhanded Solidity contest. Rather than big promises from early stage projects, the panelists focused on the basics:</p><ul><li>Just knowing how to write solidity isn’t enough. Developers, and especially auditors, need to know the EVM, and the ethereum protocol.</li><li>Write more tests! A great comment was on the need to do more testing of large scale interactions. Typically systems are tested interacting with 10 or so accounts, when it would be more realistic to test with 1000s of users.</li><li>Reading carefully: an interesting bit of wisdom I gleaned from Martin Swende. When auditing he reads contracts from bottom to top, which helps him to avoid internalizing the developer’s assumptions about the contract system.</li></ul><p>I appreciated Raine Revere’s comment that there are times when ignoring <em>certain</em> <a href="https://consensys.github.io/smart-contract-best-practices/">security best practices</a> is justified in order to provide a better user experience, and enable interoperability with other systems.</p><p>Underhanded solidity contest repo: <a href="https://github.com/Arachnid/uscc">https://github.com/Arachnid/uscc</a></p><h3>Bringing it all together</h3><p>There’s much to learn on day 3 and 4 of Devcon, and I’ll likely still be trying to assemble a coherent view of the current trends and gaps in smart contract security in the weeks following the conference.</p><h4>Do you love this stuff?</h4><p>I’m part of the team at <a href="https://media.consensys.net/introducing-consensys-diligence-cf38f83948c">ConsenSys Diligence</a>. If you have a knack for diving deeply into Solidity and the EVM, and an interest in smart contract security, we’re looking for people to join our smart contract audit practice (<a href="https://consensys.net/open-positions/?gh_jid=609611">apply here</a>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7754cd30c23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The use of revert(), assert(), and require() in Solidity, and the new REVERT opcode in the EVM]]></title>
            <link>https://medium.com/consensys-media/when-to-use-revert-assert-and-require-in-solidity-61fb2c0e5a57?source=rss-703568bf3986------2</link>
            <guid isPermaLink="false">https://medium.com/p/61fb2c0e5a57</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Maurelian]]></dc:creator>
            <pubDate>Tue, 19 Sep 2017 18:42:20 GMT</pubDate>
            <atom:updated>2017-09-22T12:07:59.120Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40cBeLqjc7RPFajJtYyoCg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/search/photos/fence-gate?photo=05Ola97OFoQ">Osman Rana</a></figcaption></figure><p>The release of Solidity version <a href="https://github.com/ethereum/solidity/releases/tag/v0.4.10">0.4.10</a> introduced the assert(), require() and revert() functions, and confusion has reigned ever since.</p><p>In particular, the assert() and require() “guard” functions improve the readability of contract code, but differentiating between them can be quite confounding.</p><p>In this article, I’ll:</p><ol><li>explain the problem these functions solve.</li><li>discuss how the Solidity compiler handles the new assert(), require() and revert().</li><li>Give some rules of thumb for deciding how and when to use each one.</li></ol><p>For convenience, I’ve created a simple contract using each of these features which you can <a href="https://remix.ethereum.org/#gist=c7b647b64d9d2422b81108f8b6af0c7c&amp;version=soljson-v0.4.16+commit.d7661dd9.js">test out in remix</a>.</p><p>If you really just want a TLDR, this answer on the <a href="https://ethereum.stackexchange.com/questions/15166/difference-between-require-and-assert-and-the-difference-between-revert-and-thro">ethereum stackexchange</a> should do it.</p><h3>Patterns for error handling in Solidity</h3><h4>The old way: throw and the if … throw pattern</h4><p>Say your contract has a few special functions, that should only be callable by a particular address which is designated as the owner.</p><p>Prior to Solidity 0.4.10 (and for a while afterwards), this was a common pattern for enforcing permissions:</p><pre>contract HasAnOwner {<br>    address owner;<br>    <br>    function useSuperPowers(){ <br>        if (msg.sender != owner) { throw; }<br>        // do something only the owner should be allowed to do<br>    }<br>}</pre><p>If the useSuperPowers() function is called by anyone other than owner, the function will throw returning an invalid opcode error, undoing all state changes, and using up all remaining gas (see <a href="https://www.google.com/url?q=https://media.consensys.net/ethereum-gas-fuel-and-fees-3333e17fe1dc&amp;sa=D&amp;ust=1505493857490000&amp;usg=AFQjCNE7J1D8vcvRB1IcveGYgCJf3JpXkw">this article</a> for more on gas and fees in ethereum).</p><p>The throw keyword is now being deprecated, and eventually will be removed altogether. Fortunately, the new functions assert(), require(), and revert() provide the same functionality, with a much cleaner syntax.</p><h4>Life after throw</h4><p>Let’s look at how to update that if .. throw pattern with our new guard functions.</p><p>This line:</p><p>if(msg.sender != owner) { throw; }</p><p>currently behaves exactly the same as all of the following:</p><ul><li>if(msg.sender != owner) { revert(); }</li><li>assert(msg.sender == owner);</li><li>require(msg.sender == owner);</li></ul><p><em>Note that in the </em><em>assert() and </em><em>require() examples, the conditional statement is an inversion of the </em><em>if block’s condition, switching the comparison operator </em><em>!= to </em><em>==.</em></p><h3>Differentiating between assert() and require()</h3><p>First, to help separate these ‘guard’ functions in your mind, imagine <strong>assert() </strong>as an overly <strong>assertive</strong> bully, who steals all your gas.<strong> </strong>Then imagine <strong>require() </strong>as a polite managerial type, who calls out your errors, but is more <strong>forgiving</strong>.</p><p>With that mnemonic handy, what’s the real difference between these two functions?</p><p>Prior to the Byzantium network upgrade, require() and assert() actually behave identically, but their bytecode output is slightly different.</p><ol><li>assert() uses the <strong>0xfe</strong> opcode to cause an error condition</li><li>require() uses the <strong>0xfd</strong> opcode to cause an error condition</li></ol><p>If you look up either of those opcodes in the yellow paper, you won’t find them. This is why you see the invalid opcode error, because there’s no specification for how a client should handle them.</p><p>That will change however after Byzantium, and the implemention of <a href="https://www.google.com/url?q=https://github.com/axic/EIPs/blob/revert/EIPS/eip-140.md&amp;sa=D&amp;ust=1505493857492000&amp;usg=AFQjCNGXZHdWiEuBOiiP1YhvQr4Ilij8hA">EIP-140: REVERT instruction in the Ethereum Virtual Machine </a>. Then the0xfd opcode will be mapped to theREVERT instruction.</p><p>This is what I find really fascinating:</p><p><strong>Many contracts have been deployed since version 0.4.10, which include a new opcode lying dormant, until it’s no longer invalid. At the appointed time, it will wake up, and become </strong><strong>REVERT!</strong></p><p><em>Note: </em><em>throw and</em><em>revert() also use </em><strong><em>0xfd</em></strong><em>. Prior to 0.4.10. </em><em>throw used </em><strong><em>0xfe</em></strong>.</p><h3>What the REVERT opcode will do</h3><p><strong>REVERT</strong> will still undo all state changes, but it will be handled differently than an “invalid opcode” in two ways:</p><ol><li>It will allow you to return a value.</li><li>It will refund any remaining gas to the caller.</li></ol><h4>1. It will allow you to return a value</h4><p>Most smart contract developers are quite familiar with the notoriously unhelpful invalid opcode error. Fortunately, we’ll soon be able to return an error message, or a number corresponding to an error type.</p><p>That will look something like this:</p><p>revert(‘Something bad happened’);</p><p>or</p><p>require(condition, ‘Something bad happened’);</p><p><em>Note: solidity doesn’t support this return value argument yet, but you can watch </em><a href="https://www.google.com/url?q=https://www.google.com/url?q%3Dhttps://github.com/ethereum/solidity/issues/1686%2523issuecomment-328181514%26sa%3DD%26ust%3D1505492320159000%26usg%3DAFQjCNHaxNwU92XDdLnWcaMYGX9luuhaQg&amp;sa=D&amp;ust=1505493857494000&amp;usg=AFQjCNEqYU3HJRPkQLJRNvYobZIVPufwbA"><em>this issue</em></a><em> for that update.</em></p><h4>2. Refund the remaining gas to the caller</h4><p>Currently, when your contract throws it uses up any remaining gas. This can result in a very generous donation to miners, and often ends up costing users a lot of money.</p><p>Once REVERT is implemented in the EVM, it will be plain old bad manners not to use it to refund the excess gas.</p><h3>Choosing between revert(), assert() and require()</h3><p>So, ifrevert() and require() both refund any left over gas, AND allow you to return a value, why would want to burn up gas using assert()?</p><p>The difference lies in the bytecode output, and for this I’ll quote from the <a href="https://www.google.com/url?q=https://solidity.readthedocs.io/en/develop/control-structures.html%23error-handling-assert-require-revert-and-exceptions&amp;sa=D&amp;ust=1505493857495000&amp;usg=AFQjCNGsr19Xr-gK6reStgpM9BcgXnCb3Q">docs</a> (emphasis mine):</p><blockquote>The require function should be used to ensure valid conditions, such as inputs, or contract state variables are met, or to validate return values from calls to external contracts. If used properly, analysis tools can evaluate your contract to identify the conditions and function calls which will reach a failing assert. <strong>Properly functioning code should never reach a failing assert statement; if this happens there is a bug in your contract which you should fix.</strong></blockquote><p>To clarify that somewhat: it should be considered a normal and healthy occurrence for a require() statement to fail (same with revert()). When an assert() statement fails, something very wrong and unexpected has happened, and you need to fix your code.</p><p>By following this guidance, <a href="https://en.wikipedia.org/wiki/Static_program_analysis">static analysis</a> and <a href="https://en.wikipedia.org/wiki/Static_program_analysis#Formal_methods">formal verification</a> tools will be able to examine your contracts to find and prove the conditions which could break your contract, or to prove that your contract operates as designed without flaws.</p><p>In practice, I use a few heuristics to help me decide which is appropriate.</p><p><strong>Use </strong><strong>require()to:</strong></p><ul><li>Validate user inputs ie. require(input&lt;20);</li><li>Validate the response from an external contract ie. require(external.send(amount));</li><li>Validate state conditions prior to execution, ie. require(block.number &gt; SOME_BLOCK_NUMBER) or require(balance[msg.sender]&gt;=amount)</li><li>Generally, you should use require most often</li><li>Generally, it will be used towards <strong>the beginning</strong> of a function</li></ul><p>There are many examples of require() in use for such things in our <a href="https://github.com/ConsenSys/smart-contract-best-practices">Smart Contract Best Practices</a>.</p><p><strong>Use </strong><strong>revert()to:</strong></p><ul><li>Handle the same type of situations as require(), but with more complex logic.</li></ul><p>If you have some complex nested if/else logic flow, you may find that it makes sense to use revert() instead of require(). Keep in mind though, <a href="https://github.com/ConsenSys/smart-contract-best-practices#fundamental-tradeoffs-simplicity-versus-complexity-cases">complex logic is a code smell</a>.</p><p><strong>Use </strong><strong>assert() to:</strong></p><ul><li>Check for <a href="https://github.com/ConsenSys/smart-contract-best-practices#integer-overflow-and-underflow">overflow/underflow</a>, ie. c = a+b; assert(c &gt; b)</li><li>Check <a href="https://en.wikipedia.org/wiki/Invariant_(computer_science)">invariants</a>, ie. assert(this.balance &gt;= totalSupply);</li><li>Validate state after making changes</li><li>Prevent conditions which should never, ever be possible</li><li>Generally, you will probably use assert less often</li><li>Generally, it will be used towards <strong>the end</strong> of a function.</li></ul><p>Basically, require() should be your go to function for checking conditions, assert() is just there to prevent anything really bad from happening, but it shouldn’t be possible for the condition to evaluate to false.</p><p>Also: “you should not use assert blindly for overflow checking but only if you think that previous checks (either using ifor require) would make an overflow impossible”. — <a href="https://medium.com/@chriseth/thanks-for-this-detailed-writeup-83addc4b7f87">comment</a> from @chriseth</p><h3>Conclusion</h3><p>These functions are very powerful tools for your security toolbox. Knowing how and when to use them will not only help prevent vulnerabilities, but also make your code more user friendly, and future proof against upcoming changes.</p><h4>Do you love this stuff?</h4><p>I’m part of the team at <a href="https://media.consensys.net/introducing-consensys-diligence-cf38f83948c">ConsenSys Diligence</a>. If you have a knack for diving deeply into Solidity and the EVM, and an interest in smart contract security, we’re looking for people to join our smart contract audit practice (<a href="https://consensys.net/open-positions/?gh_jid=609611">apply here</a>).</p><p>If you made it this far in the post, but don’t meet the exact criteria in the job description, that’s OK. Just include a message mentioning this post, and calling out your experience with, and interest in Ethereum.</p><p><strong><em>Like this piece? Sign up </em></strong><a href="http://consensys.us11.list-manage.com/subscribe?u=947c9b18fc27e0b00fc2ad055&amp;id=257df01285"><strong><em>here</em></strong></a><strong><em> for our weekly newsletter.</em></strong></p><blockquote>Disclaimer: The views expressed by the author above do not necessarily represent the views of Consensys AG. ConsenSys is a decentralized community with <a href="https://medium.com/consensys-media">ConsenSys Media</a> being a platform for members to freely express their diverse ideas and perspectives. To learn more about ConsenSys and Ethereum, <a href="https://consensys.net/">please visit our website.</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61fb2c0e5a57" width="1" height="1" alt=""><hr><p><a href="https://medium.com/consensys-media/when-to-use-revert-assert-and-require-in-solidity-61fb2c0e5a57">The use of revert(), assert(), and require() in Solidity, and the new REVERT opcode in the EVM</a> was originally published in <a href="https://medium.com/consensys-media">ConsenSys Media</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preparing for a Smart Contract Code Audit]]></title>
            <link>https://medium.com/consensys-media/preparing-for-a-smart-contract-code-audit-83691200cb9c?source=rss-703568bf3986------2</link>
            <guid isPermaLink="false">https://medium.com/p/83691200cb9c</guid>
            <category><![CDATA[token-sale]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[dapps]]></category>
            <dc:creator><![CDATA[Maurelian]]></dc:creator>
            <pubDate>Wed, 06 Sep 2017 18:35:05 GMT</pubDate>
            <atom:updated>2019-11-01T13:29:33.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAZAFQj6zcjP4TMCblkFOQ.jpeg" /></figure><p><em>A more up to date version version of this article (from September 2019) can be found </em><a href="https://diligence.consensys.net/blog/2019/10/vyper-preliminary-security-review/"><em>here</em></a><em>.</em></p><p>If you are planning to launch a project on the Ethereum blockchain, you probably know the importance of a third-party code audit. An external audit can ensure that your contracts function as intended and remove vulnerabilities in the code.</p><p>Choosing a team of experienced, rigorous auditors is of course essential, but your preparation will also impact the quality of the audit. Some effort on your part will go a long way toward getting you a better, faster audit.</p><h3>The Preparedness Mindset</h3><p>Imagine you’re about to onboard a senior developer to your team. You have very little time to get them FULLY up to speed on your codebase, also they’re remote, and you’re not going to talk to them much because you’re busy. This is essentially the relationship you have with an auditor.</p><p>Through our experience working with teams at ConsenSys and prominent project in the Ethereum ecosystem, we’ve identified a few things you can do to help us (or whoever your auditor is) help you:</p><h4>1. Adhere to best practices</h4><p>ConsenSys Diligence, with the help of the community, actively maintains a guide to what we consider <a href="https://consensys.github.io/smart-contract-best-practices/">Smart Contract Best Practices</a>. We recommend reading this document early on, and again prior to seeking an audit.</p><h4>2. Provide a plain english specification</h4><p>Smart contract development has often been likened to writing mission critical code for NASA, and yet projects rarely have a specification describing what their contract code is meant to do.</p><p>Writing a specification is always a good idea, and doesn’t have to be a scary proposition. Many developers tell us this process helped them clarify their thinking and even identify issues in their own code.</p><p>Your specification should describe, in plain English, how each function of a contract should work and how those functions should work together. Functions may be treated as “black boxes”; the specification should describe what goes in, what comes out, what should happen, and what should not. After this, outline the design decisions behind the intended behavior of your code, rather than alternative approaches you might have chosen. This will help clarify for yourself the alternatives, as well as how people may misinterpret or misuse your code.</p><p>Diagrams are tremendously helpful, and highly indicative of a well thought-out design process. Both <a href="https://github.com/weifund/weifund-contracts/blob/master/docs/developer-guide.md#standardcampaign-state-machine">WeiFund</a> and <a href="https://blog.golemproject.net/gnt-crowdfunding-contract-in-pictures-d6b5a2e69150">Golem</a> have excellent specification diagrams that can be used as examples.</p><h4>3. Think start to finish</h4><p>Your smart contract code could be well-audited and safe. But there are still several critical steps before that code is deployed on the blockchain. Any mishaps in those steps could wipe out all your team’s efforts at providing a safe system.</p><p>Thus, a documented deployment process is essential in order to avoid introducing insecurities. Such a guide would include: which compiler version to use for which contracts, the order in which contracts will be deployed, and constructor parameters for initialization of each contract.</p><h4>4. Write a good README</h4><p>Your project should have a good README.md file which clearly describes how to install the system locally and run the test suite. It should also clearly link to other references which are useful to understanding the project.</p><p>If your contracts have a complex inheritance graph, this should be documented. If you will run a bug bounty after the audit (which we recommend), provide instructions for participation.</p><h4>5. Clean up the project repository</h4><p>Reducing clutter in your code makes an auditor’s job much easier. You should remove any unused or unnecessary contracts, files, or code.</p><p>You should also indicate:</p><ul><li>which contracts are only used for testing purposes, and are not part of the final system,</li><li>which contracts are reused from audited code, or inherit heavily from audited code.</li></ul><p>A good directory layout for your contracts might look something like this:</p><pre>.<br>├── contracts<br>    ├── Migrations.sol<br>    ├── NewContract0.sol<br>    ├── NewContract1.sol<br>    ├── NewContract2.sol<br>    ├── NewContract3.sol<br>    ├── base<br>    │   ├── MultiSigWallet.sol<br>    │   ├── StandardToken.sol<br>    │   └── Owned.sol<br>    └── test<br>        ├── ReentryTestContract.sol<br>        └── TestContract.sol</pre><p>In the above directory tree,</p><ul><li>./contracts/*.sol: would be the primary focus of the audit.</li><li>./contracts/base/*.sol would be well audited contracts which are inherited by the top level contracts. They might still require scrutiny, but to a lesser degree.</li><li>./contracts/test/*.sol would be contracts which exist only for testing purposes, and are not meant to be deployed with the contract system.</li></ul><h4>6. Lint your code</h4><p>Use <a href="https://github.com/duaraghav8/Solium">solium</a>, or <a href="https://github.com/federicobond/solcheck">solcheck</a>, and follow the <a href="https://solidity.readthedocs.io/en/develop/style-guide.html">official Solidity style guide</a>. Also use a linter on your test suite.</p><h4>7. Comment complex sections of code</h4><p>Gratuitous comments are not necessary, but comments clarifying your intention can be helpful, especially in highly complex sections of code.</p><h4>8. Measure your test coverage</h4><p>You’re using a test driven development approach to writing your contracts, right? ;)</p><p>Measuring test coverage is helpful for identifying sections of code that are not tested, or need more testing. <a href="https://www.npmjs.com/package/solidity-coverage"><strong>Solidity-coverage</strong></a> is a great tool for this.</p><p>Of course 100% test coverage is not a panacea, so we also evaluate the quality and thoroughness of the test code. Writing tests in Python, or using the async/await syntax of NodeJS makes them much more readable and easier to follow.</p><h4>9. Freeze the codebase</h4><p>The purpose of a code audit is not to clean up your code or check for simple mistakes. Your contract system must be considered <strong>ready</strong> prior to the commencement of an audit. A commit hash from your git repo is required to specify the state of the code to be audited.</p><h3><strong>Conclusion</strong></h3><p>A good code audit can bring tremendous peace of mind, but it doesn’t relieve you or your developers of responsibility. Taking the time to prepare your code for a proper handoff will allow your auditors to do their best work, and allow you to feel more confident in your contract system.</p><p><strong><em>Like this piece? Sign up </em></strong><a href="http://consensys.us11.list-manage.com/subscribe?u=947c9b18fc27e0b00fc2ad055&amp;id=257df01285"><strong><em>here</em></strong></a><strong><em> for our weekly newsletter.</em></strong></p><blockquote>Disclaimer: The views expressed by the author above do not necessarily represent the views of Consensys AG. ConsenSys is a decentralized community with <a href="https://medium.com/consensys-media">ConsenSys Media</a> being a platform for members to freely express their diverse ideas and perspectives. To learn more about ConsenSys and Ethereum, <a href="https://consensys.net/">please visit our website.</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83691200cb9c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/consensys-media/preparing-for-a-smart-contract-code-audit-83691200cb9c">Preparing for a Smart Contract Code Audit</a> was originally published in <a href="https://medium.com/consensys-media">ConsenSys Media</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>