<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Michael Connor on Medium]]></title>
        <description><![CDATA[Stories by Michael Connor on Medium]]></description>
        <link>https://medium.com/@iammichaelconnor?source=rss-a7394af65626------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gaUiRDXUeUIGMrBeCCBZzg@2x.jpeg</url>
            <title>Stories by Michael Connor on Medium</title>
            <link>https://medium.com/@iammichaelconnor?source=rss-a7394af65626------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:42:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iammichaelconnor/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Running Mocha tests programmatically in ECMAScript modules]]></title>
            <link>https://iammichaelconnor.medium.com/running-mocha-tests-programmatically-in-ecmascript-modules-9af55dd7bf44?source=rss-a7394af65626------2</link>
            <guid isPermaLink="false">https://medium.com/p/9af55dd7bf44</guid>
            <category><![CDATA[test]]></category>
            <category><![CDATA[ecmascript]]></category>
            <category><![CDATA[esm]]></category>
            <category><![CDATA[mocha]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Michael Connor]]></dc:creator>
            <pubDate>Fri, 22 Jan 2021 15:54:48 GMT</pubDate>
            <atom:updated>2021-01-22T15:54:48.348Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dg-CEFVxCtizENgbVoLbBA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@punttim?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tim Gouw</a> on <a href="https://unsplash.com/s/photos/stressed?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I just spent too long figuring out how to run Mocha tests on my .mjs app to run from within a JS ES module. It was painful. I hated it. Here’s what I did…</p><h4>Setting the scene:</h4><ul><li>Node v13 or higher.</li><li>Your JS application is in .mjs files.</li><li>You want to trigger Mocha tests from within a .mjs file (rather than from the command line), a.k.a. ‘programmatically’.</li><li>You might have tried, but are getting errors like: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module:</li></ul><p>call-test.mjs :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa84d92149fd9fde495876ecc9603058/href">https://medium.com/media/fa84d92149fd9fde495876ecc9603058/href</a></iframe><p>This looks really similar to the existing guide on <a href="https://github.com/mochajs/mocha/wiki/Using-Mocha-programmatically">‘Using Mocha programatically’</a>, except the code is written in a .mjs file and calls a Mocha test written in a .cjs file.</p><p>Next comes the fiddly bit…</p><p>If you’re calling a Mocha test <em>programmatically</em>, you’ll need to write that test in <em>common js</em> (with a .cjs file extension). That means require statements instead of imports , etc.</p><p><strong>The problem</strong> (and the purpose of this article) is that a .cjs file cannot easily import code written in a .mjs file, because the ES syntax would be ‘alien’ to the .cjs file.</p><p>I.e. your Mocha test won’t be able to test your app’s .mjs files without the hack below…</p><p>Let’s take a look at the Mocha test file:</p><p>test.cjs :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d77c550db3c8716777df402506d9131/href">https://medium.com/media/2d77c550db3c8716777df402506d9131/href</a></iframe><p>Notice the weird require statement half way down? We use the esm package to ‘translate’ our app’s .mjs syntax into a format that the Mocha test file can ‘read’.</p><p>Make sure to add the <a href="https://www.npmjs.com/package/esm">esm package</a> to the dependencies of your package.json.</p><p>With this approach, you can test an ES module, like this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e11f2a5294bc9107dfc101c794fbe94e/href">https://medium.com/media/e11f2a5294bc9107dfc101c794fbe94e/href</a></iframe><p>Hopefully that works for you.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9af55dd7bf44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Merkle Membership Proofs]]></title>
            <link>https://iammichaelconnor.medium.com/merkle-membership-proofs-fceb9fee3230?source=rss-a7394af65626------2</link>
            <guid isPermaLink="false">https://medium.com/p/fceb9fee3230</guid>
            <category><![CDATA[merkle-tree]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[set-membership]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Michael Connor]]></dc:creator>
            <pubDate>Wed, 23 Sep 2020 12:47:41 GMT</pubDate>
            <atom:updated>2020-09-23T18:54:14.307Z</atom:updated>
            <content:encoded><![CDATA[<h3>Zero-knowledge Merkle Membership Proofs</h3><p>Say we want to <em>prove</em> that a particular value <em>exists</em> as a leaf in a Merkle tree, without revealing <em>which</em> value we’re talking about.</p><p>This is a common ingredient in zero-knowledge blockchain applications (‘zApps’), where we want to <em>refer </em>to private states; without <em>revealing</em> the value or storage location of such states.</p><p>Here’s a pretty GIF to illustrate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CvGEivMLCLnEGRv1XvMnNQ.gif" /></figure><h4>Notes</h4><ul><li>The values <em>0…30</em> in the tree are node <em>indices</em>, <strong>not</strong> node <em>values</em>. The actual <em>values</em> at each node are not shown, because they’d just be random-looking hashes which would make the illustration cluttered and confusing.</li><li>A leaf’s <em>path</em> comprises its <em>parent</em> nodes up the tree.</li><li>A leaf’s <em>sibling path</em> comprises the <em>siblings</em> of its path (where ‘<em>siblings</em>’ are two nodes which share a parent node).</li><li>The binary decomposition of a leaf’s index (indexed from <em>0</em>) gives us the “leftness” or “rightness” of its sibling path (relative to its path) up the tree.</li></ul><h4>Example</h4><p>Say, for example, we want to <em>prove</em> that we know the value at node index <em>19</em> (equiv. leaf index <em>4</em>), without revealing the value nor its location.</p><ul><li>Get the <em>membership witness</em> for the leaf: i.e. the <em>value</em> itself; its <em>leaf index</em>; and its <em>sibling path</em>.</li><li>Re-calculate the <em>root</em> of the Merkle tree (from the <em>membership witness</em>)<em>, </em>as part of a <em>zk-SNARK </em>proof generation process.</li><li>Submit the zk-SNARK’s <em>proof </em>and<em> public input (</em>the<em> root)</em>, to the <em>verifier</em> (smart contract).</li></ul><p>The verifier will:</p><ul><li><em>verify</em> the zk-SNARK,</li><li><em>check</em> that the submitted root equals the stored root.</li></ul><p>If both checks pass, the verifier will be <em>convinced</em> that we’ve correctly referred to a private state. Crucially, notice that we’ve not <em>revealed</em> to the verifier <em>which</em> state we were referring to, as the only intelligible information we submitted was the <em>root.</em></p><p>That’s it for this article. Enjoy watching my GIF.</p><p>:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fceb9fee3230" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Timber]]></title>
            <link>https://iammichaelconnor.medium.com/timber-7db8a5130849?source=rss-a7394af65626------2</link>
            <guid isPermaLink="false">https://medium.com/p/7db8a5130849</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[nightfall]]></category>
            <category><![CDATA[timber]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[merkle-tree]]></category>
            <dc:creator><![CDATA[Michael Connor]]></dc:creator>
            <pubDate>Thu, 12 Dec 2019 20:52:31 GMT</pubDate>
            <atom:updated>2020-09-28T16:43:12.148Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWjMHQrK0MQ0bjW_2wq3qw.png" /></figure><h4>Cutting Merkle Tree gas costs</h4><h3>Quick Learn</h3><p>If you’re in a rush…<br>Here’s the repo:</p><p><a href="https://github.com/EYBlockchain/timber">EYBlockchain/timber</a></p><p>Here’s a GIF of the ‘old’ on-chain Merkle Tree design (notice how much was being stored on-chain):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SswMK1wQAIzalBt236QsDA.gif" /></figure><p>Here’s a GIF of the ‘new’ on-chain Merkle Tree design (a.k.a. Timber):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*idwNzkCglu9nGE5JdmksEw.gif" /></figure><p>See how little on-chain storage there is now? Only the frontier and the root get stored.</p><p>If you’re in less of a rush, here’s a slowed down GIF of Timber:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ikrh7jnXLD4Kh6d2qSeYsw.gif" /></figure><p>I love GIFs.</p><p>If you’re not in a rush at all, I explain Timber below…</p><h3>Motivation</h3><p>I’ve been part of the team working on <a href="https://github.com/EYBlockchain/nightfall">Nightfall</a> for over a year now. It’s a set of tools for private transactions over Ethereum. We keep trying to reduce the cost of a private transfer (whilst preserving security and privacy), and this article explains one little development.</p><p>Keeping gas costs down is important when building anything on Ethereum. With private transaction protocols, the costliest of cost burdens are:</p><ul><li>Elliptic curve operations</li><li>Storage</li><li>Hashing</li></ul><p>We’re not going to talk about reducing the use of elliptic curve operations here. Nor will we talk about hashing costs². <strong>Timber tackles the less painful storage problem.</strong></p><p><em>² Timber is agnostic to the hashing function which gets used within the Merkle Tree, although the analysis later in this article uses sha256 (because it’s cheap).</em></p><blockquote>Why are Merkle Trees used?</blockquote><p>Many private transaction protocols use Merkle Trees. Tokenised assets can be ‘wrapped’ in cryptographic commitments, and each of these commitments can be stored as a new leaf in the tree. We use a Merkle Tree structure so that we can ‘refer’ to a commitment at some point in the future; but <em>without</em> revealing to the world which commitment we’re actually referring to. I.e. we can spend a token privately, without revealing the token we’re spending. <em>(Have a read around ‘zero knowledge set membership proofs’ if you’re unfamiliar with this)</em>.</p><p>Every time a new leaf (commitment) gets added to the tree, we ask the smart contract to recalculate the root of the tree, by hashing all the way up the ‘path’ from the leaf to the root.</p><blockquote>What was the storage problem?</blockquote><p><strong>Before Timber</strong>, we previously stored <em>all</em> the nodes of the Merkle Tree within a smart contract.</p><p>The problem was (and is), that the Merkle Trees we use are MASSIVE. They contain 2³² leaves. That’s 4,294,967,296 leaves. That’s 8,589,934,591 tree nodes altogether!</p><p><em>Why so many leaves? Because more leaves means greater anonymity. It’s harder for outside observers to deduce which leaf is being referred to by a transactor, if there is a pool containing millions of leaves. I.e. it makes it harder to figure out what ‘private token’ commitment is being spent. If we were to reduce the number of leaves (a.k.a. the ‘Anonymity Set’), it might make it easier for analytics software to make inferences about what’s being transacted over the private transaction protocol. Users should be wary of small anonymity sets.</em></p><p>When we were previously storing every node of the Merkle Tree in the smart contract, we were storing between 1 and 33 <em>new</em> values on-chain <em>every transaction </em>(because the tree has height 32)<em>. </em>Even in the cheapest case, we were <em>overwriting</em> 32 storage values. That meant users would have been paying between 180,000 gas ( = 32 nodes * 5,000 gas + 20,000 gas) and 660,000 gas ( = 33 nodes * 20,000 gas) <em>every transaction, </em>just<em> </em>in Merkle Tree storage <em>(that’s between $0.72 and $2.64 assuming 200USD/ETH and 20Gwei/gas)</em>.</p><p>Not only was this storage an expensive component of a single transaction, its large variance wasn’t very nice. A transaction could have cost an extra couple of dollars just because of the ‘bad timing’ of a leaf’s position in the tree.</p><p><strong>Timber </strong>provides a method for reducing unnecessary Merkle Tree storage costs each transaction. It also results in much less price volatility per transaction. Read below if you’re interested in the details.</p><h3>Contents</h3><ul><li>Objectives</li><li>Summary</li><li>Technical Details</li><li>In the repo…</li><li>API</li><li>Gas Costs</li><li>What next?</li></ul><h3>Objectives</h3><ol><li>Keep track of a Merkle Tree’s root on-chain;</li><li>Minimise the gas cost of adding leaves to the Tree;</li><li>Minimise the gas cost of updating the root;</li><li>Ensure data availability;</li></ol><h3>Summary</h3><p>Leaves are submitted to a MerkleTree smart-contract by users. Submitting multiple leaves in-bulk results in considerable gas cost savings per leaf.</p><p>Only the root and a small frontier of nodes is stored on-chain. New leaves are not stored on-chain; they’re emitted as events.</p><p>A local merkle-tree database (off-chain) is populated with the leaves and nodes of the Tree, based on NewLeaf events emitted by the smart-contract.</p><p>The database can then be queried, e.g. for sibling-paths in order to provide set-membership proofs to the smart-contract.</p><p><strong>Disclaimer: Note that the code has not yet completed a security review and therefore we strongly recommend that you do not use it in production. We take no responsibility for any loss you may incur through the use of the code.</strong></p><h3>Technical Details</h3><h4>On-chain</h4><p>The leaves of the tree are not stored on-chain; they’re emitted as events.</p><p>The intermediate-nodes of the tree (between the leaves and the root) are not stored on-chain.</p><p>Only a frontier array is stored on-chain (see the detailed explanation below).</p><h4>Off-chain</h4><p>We filter the blockchain for NewLeaf event emissions, which contain:</p><pre>NewLeafEvent: {<br> leafIndex: 1234,<br> leafValue: ‘0xacb5678’,<br> root: ‘0xdef9012’<br>}</pre><p>We then insert each leaf into a local mongodb database.</p><p>With this database, we can reconstruct the entire merkle tree.</p><h4>Technical details</h4><p>We consistently use the following indexing throughout the codebase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbvxxJopRbstgFgAxwYO-Q.png" /></figure><p>We start with an empty frontier = [ , , , , ].</p><p>The frontier will represent the right-most fixed nodeValues at each level of the tree. So frontier[0] will be the right-most fixed nodeValue at level 0, and so on up the tree. By ‘fixed nodeValue’, we mean that the nodeValue will never again change; it is permanently fixed regardless of future leaf appends.</p><h4>Inserting leaf 0</h4><p>A user submits the 0th leaf (leafIndex = 0) to the MerkleTree smart contract.</p><p>We add it to leafIndex = 0 (nodeIndex = 15) in the contract’s local stack (but not to persistent storage, because we can more cheaply emit this leaf’s data as an event).</p><p>Let’s provide a visualisation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLkgISM3cxuVxJgbRL8ThQ.png" /></figure><p>We use the unusual notation 15.0 to mean “the nodeValue from the 0th update of nodeIndex 15”.</p><p>We now need to hash up the merkle tree to update the root. In order to do this, we need the nodeValues of the sibling-path of leafIndex = 0.</p><p>The 0th leaf is an easy case where the sibling-path nodes are always to the right of the leaf’s path:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyH3QAgNkzWlV2TDbBikRQ.png" /></figure><p>Hashing up the tree is easy in this case; if a sibling-node is to the right, then it must never have been updated before, and hence must have nodeValue 0.</p><p>So it’s easy to update the tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rELg_itjcYQDxOqchJCtxQ.png" /></figure><p>We will only use the frontier to inject sibling-nodes which are to the left of a leaf’s path. More on that later.</p><p>Our updated tree can be visualised like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUhhFP8xikQsjX87GVO6Mw.png" /></figure><p>By 7.0, we mean “the nodeValue from the 0th update of nodeIndex 7”, etc.</p><p>Note that nothing has yet been stored in persistent storage on-chain.</p><p>Notice now, that the nodeValue 15.0 will never change in future. Notice also that when we come to insert a new leaf to leafIndex = 1, its sister-path will include nodeValue 15.0 on its left. Therefore, when we come to update the root to include the new leaf, we will need to left-inject nodeValue 15.0 into our hashing computation.</p><p>Now hopefully the purpose of the frontier starts to become clear. We will add nodeValue 15.0 to frontier[0] (persistent storage), so that we can later left-inject it into our hashing computation when we come to insert leafIndex = 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ygJcm6FURYY1hIfXYAgr2A.png" /></figure><p>The smart contract emits the leaf value as an event NewLeaf, which is then picked-up by Timber&#39;s event listener and added to the mongodb.</p><p>That completes the insertion of leaf 0.</p><h4>Inserting leaf 1</h4><p>Let&#39;s add some more leaves (always appending them from left to right):</p><p>A user submits the 1th leaf (leafIndex = 1) to the MerkleTree smart contract.</p><p>We add it to leafIndex = 1 (nodeIndex = 16) in the contract&#39;s local stack (but not to persistent storage, because we can more cheaply emit this leaf&#39;s data as an event).</p><p>Let&#39;s provide a visualisation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_SeyIetEk6gWn8WTGinEw.png" /></figure><p><em>Note, we haven&#39;t yet recalculated the path from </em><em>leafIndex = 1 (</em><em>nodeValue = 16.0) to the root.</em></p><p>The above visualisation is a bit misleading, because most of this data wasn&#39;t stored in persistent storage. In actual fact all the smart contract can draw upon at this time is:</p><pre>// Data known by the smart contract:</pre><pre>frontier = [ 15.0,   ,   ,   ,   ];</pre><p>In order to insert nodeValue 16.0 into the tree and update its path, we will need the nodeValues of the sibling-path of leafIndex = 1, and we will also need to know whether those sibling-nodes are on the left or the right of the path up the tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKXSx4uFxKAI9-f6REHcPQ.png" /></figure><p>We can actually deduce the &#39;left-ness&#39; or &#39;right-ness&#39; of a leaf&#39;s path up the tree from the binary representation the leaf&#39;s leafIndex:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CLSk8R4bIuu-_0tLUJR6xQ.png" /></figure><p>Notice how for `leafIndex = 1 = 0b0001` the path is on the right, left, left, left as we work up the tree? <em>(Associate a binary `1` with `right` and a binary `0` with `left`, and you&#39;ll see a pattern for the &#39;left-ness&#39; or &#39;right-ness&#39; of the path up the tree from a particular leafIndex)</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yk_ml43p_AMWvYtLLEjw7g.png" /></figure><p>Now we can hash up the tree, by injecting the sister-path to the opposing &#39;left, right, right, right&#39; positions (as indicated by the arrows below):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rp6TixvjECT3sI6-7OfNIQ.png" /></figure><p>We can visualise the tree after updating the path (but remember the smart contract isn&#39;t actually storing anything except the frontier!):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x1_ehK8uFfvd7J_8lfXwhg.png" /></figure><p>Now we&#39;ve udpated the tree, how do we decide which nodeValue to add to the frontier?</p><p>We use the following algorithm to decide which index (or storage &#39;slot&#39;) of the frontier to update:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OeuejFD8qdmj90HJwC-8oA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9KYZH1UagOjVjini90uxQ.png" /></figure><p>After adding the 1st leaf and updating the root, the smart contract now has stored:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3s0g7KF_xN5tTI7QbM81lA.png" /></figure><p>That&#39;s very lightweight in terms of storage costs!</p><h4>Future inserts</h4><p>We can project forward and show how the frontier will progress as new leaves are added:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uruNEP4xA6ZYeYI8NEDbUw.png" /></figure><h3>In the repo…</h3><pre>./docker-compose.yml ← ‘startup’ configuration<br>|<br>./merkle-tree/ ← the ‘main’ microservice of this repo<br>    |<br>    src/<br>        |<br>        db/ ← services for managing the merkle-tree mongodb<br>        |<br>        routes/ ← API routes for externally accessing this<br>                  microservice &amp; db<br>        |<br>        filter-controller.js ← Ethereum event filter<br>        |<br>        merkle-tree-controller.js ← merkle-tree update &amp;<br>                                    calculation controller<br>|<br>./deployer/ ← example ‘stub’ microservice, demonstrating how one<br>              would use ‘timber’ as part of a Dapp<br>    |<br>    contracts/ ← example MerkleTree.sol contract for efficient<br>                 merkle-tree updates</pre><h4>Example Usage:</h4><h4>Add leaves to the tree:</h4><p>Submit a leaf / leaves to the MerkleTree.sol smart contract. <em>(We provide test scripts to simulate this).</em></p><p>Interact with the merkle-tree microservice through its API. A postman collection (for local testing) is provided in the repo.</p><h4>Start the event filter:</h4><p>Send a start request to start the merkle-tree’s event filters for NewLeaf and NewLeaves events. Any ‘new leaf’ events will be picked up by the filters, and cause the new leaf data to be inserted into the mongodb.</p><h4>Update the merkle-tree database:</h4><p>Send an update request to the merkle-tree microservice. Given the leaves now stored in the mongodb, this update command will recalculate all of the intermediate nodes from the leaves to the root, and store all of these new or updated nodes in the mongodb.</p><p><strong>Get information from the merkle-tree database:</strong></p><p>Send a GET request for (e.g.) the siblingPath for a particular leaf.</p><h3>API</h3><p>At the time of writing, Timber has the following route functionalities:</p><p>insertLeaf<br>getLeafByLeafIndex<br>getLeafByValue<br>insertLeaves<br>getLeaves (by indices, a range of indices, or all)<br>checkLeaves (to check the integrity of the db)<br>countLeaves</p><p>insertNode<br>getNodeByNodeIndex<br>getNodeByValue<br>updateNodeByNodeIndex<br>getNodes<br>updateNodes<br>countNodes<br>getRoot</p><p>getMetadata<br>getContractAddress<br>insertContractAddress<br>getContractInterface<br>insertContractInterface<br>getLatestLeaf<br>updateLatestLeaf<br>getLatestRecalculation<br>updateLatestRecalculation</p><p>startEventFilter<br>update<br>getSiblingPathByLeafIndex<br>getPathByLeafIndex</p><h3>Gas Costs</h3><p>The following gives gas cost measurements for inserting leaves into the MerkleTree.sol contract. 2^n</p><h4>insertLeaf</h4><ul><li>treeHeight = 32</li><li>32 sha256() hashes. We use assembly to minimise the cost of calling the sha256 precompiled contract.</li><li>1,024 leaves inserted, one-at-a-time, from left to right.</li><li>Notice how there is a jump in cost every 2**n leaves, when a new level of the frontier is written to for the first time. We could avoid these jumps by initialising the frontier at deployment, through the contract’s constructor() .</li><li>The very first transaction costs the most, due to initialising of the leafCount and latestRoot parameters.</li><li>Gas values shown include the 21,000 gas transaction cost.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8lMJ78Fht5aaL46GhM2ZwQ.png" /></figure><h3>insertLeaves</h3><ul><li>treeHeight = 32</li><li>We explore the cost of inserting leaves in batches of varying sizes (doubling the batch size each time).</li><li>We insert each batch into an empty tree each time.</li><li>Gas values shown include the 21,000 gas transaction cost each time.</li><li>The gas cost per leaf reduces asymptotically with batch size.</li><li>Batches of 128 leaves and over appear to start levelling out around 10,000 gas per leaf.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tnPDqqUTq3GHeiQmaGknUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mjc7yq4kOanmhVuc2eZw-w.png" /></figure><p>We also explore the cost of inserting a fixed total of 512 leaves, but in batches of varying sizes (doubling the batch size each time).<br>I.e.:</p><ul><li>512 transactions of batches of 1 leaf</li><li>256 transactions of batches of 2 leaves</li><li>64 transactions of batches of 4 leaves</li><li>…</li><li>1 transaction of a batch of 512 leaves</li><li>We begin each set of transactions with an empty tree each time.</li><li>Gas values shown have been adjusted to exclude the 21,000 gas transaction cost each time. This helps hone in on the ‘internal contract’ gas costs, but massively understates the costs of multiple transactions of small batches (e.g. we’re understating the cost of “512 transactions of batches of 1” by over 10MGas in the below graph).</li><li>The gas cost for inserting a given number of leaves reduces asymptotically as batch size increases.</li><li>Beyond batches of 128 leaves, the gas savings begin to level out.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*foPyoeWmjYQqJQ9Q1rD1KQ.png" /></figure><h3>What next?</h3><p>You might ask “Why don’t we take the Merkle Tree off-chain entirely, and just provide a zero knowledge proof that the root has been updated correctly?”.</p><p>We could. But there are some compromises. I might discuss these compromises in a future article…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7db8a5130849" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>