<?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 Angel Java Lopez on Medium]]></title>
        <description><![CDATA[Stories by Angel Java Lopez on Medium]]></description>
        <link>https://medium.com/@angeljavalopez?source=rss-357cf59669cc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*i6fBn3odzI6eU6nb</url>
            <title>Stories by Angel Java Lopez on Medium</title>
            <link>https://medium.com/@angeljavalopez?source=rss-357cf59669cc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:36:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@angeljavalopez/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[World State and Block Execution]]></title>
            <link>https://angeljavalopez.medium.com/world-state-and-block-execution-e9330aa50fbf?source=rss-357cf59669cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9330aa50fbf</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[rsk]]></category>
            <category><![CDATA[trie]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Angel Java Lopez]]></dc:creator>
            <pubDate>Tue, 25 May 2021 19:19:20 GMT</pubDate>
            <atom:updated>2021-05-25T19:58:44.881Z</atom:updated>
            <content:encoded><![CDATA[<p>Every day, I’m having fun implementing a blockchain in Java (<a href="https://github.com/ajlopez/blockchainj">see project</a>, <a href="https://github.com/ajlopez/blockchainj#posts">see posts</a>), based on Ethereum, like others, <a href="https://github.com/rsksmart/rskj">like RSK</a>, my daily job. One of the interesting part to code is the representation of the world state. In the last years I implemented the Trie, many times, in many languages (like Java and C#), and one thing it is for sure: it is important in the most popular use case a blockchain node has: the execution of block.</p><p>(If you don’t know what a Trie is and how it is used in Ethereum blockchains, read <a href="https://easythereentropy.wordpress.com/2014/06/04/understanding-the-ethereum-trie/">Understanding the Ethereum Trie</a>, mentioned in my blog post <a href="https://angeljavalopez.medium.com/programming-for-rsk-b28333b440c">Programming for RSK</a>; also read <a href="https://medium.com/@eiki1212/ethereum-state-trie-architecture-explained-a30237009d4e">Ethereum State Trie Architecture Explained</a>).</p><p>I say that execution of block is the most popular use case because if you monitor the execution of an Ethereum-like node, the execution of blocks occupy most of the time and resources (memory, storage access, etc) of the node. Specially if the blockchain has Proof of Work, and the miners produce many sibling blocks per candidate height: it’s not only the execution of the block with height, ie, 10000, but it also involves the execution of other competing blocks with the same height.</p><p>In this kind of blockchains (like my implementation) the trie is used to store the world state, for example, the Account states, and the Smart Contract Storage Cells (accessed by key value). The world state could be stored using simply a key-value store, BUT the trie allows to have something additional: the world state has a hash root, the root hash of the accounts world state, that includes, indirectly, also the storage world state. Practically, it’s the only reason to have a trie: to use its hash root as part of the distributed consensus algorithm. The nodes in the blockchain MUST obtain the same WORLD STATE HASH ROOT at the end of each BLOCK execution.</p><p>Since 2016, I experimented and implemented many tries, but with performance and efficiency as the guide to choose implementation. One thing I preferred in my implementations it’s to to have trie nodes, where the subnodes ARE REFERRED in-memory (it’s an usual way to implement a Trie, but also I implemented it without reading any other implementation code, as usual, following the TDD (Test-Driven Development) workflow, and pushing for simplicity along the way). This way of doing things, implementing code without reading other implementation, to explore alternative solutions, gave me many satisfactions these years.</p><h3>Executing a Block</h3><p>Using this approach, the tries to use DURING the execution of a block, lives in memory: only some nodes are retrieved from key-value storage: when the node is needed.</p><p>Also, when a value should be retrieve using a key, but the trie nodes that represent the key are partially in memory, no access to disk is needed. So, the tries in memory (accounts, storages) started to grow DINAMYCALLY, with adaptation to the CURRENT block execution: the nodes that are needed usually are retrieved only once, and visited many times in-memory during the execution of the block.</p><p>This way of doing things has a profound impact in performance. For example, RSK implementation is similar (but not so simple, you know, I prefer simplicity), and then the use of this approach (tries growing in-memory, with an additional cache, in RSK case), give us some interesting numbers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*ojTMEZBL1AkK3SpAmMURwA.png" /><figcaption>Some numbers from RSK Testnet</figcaption></figure><p>The first column is the number of block. Second and third column are the number of transactions and uncles in the block (these blocks spent more than 6 million gas units each, so, they are filled, with “DeFi-like” transactions). The fourth column is the block processing time in milli-seconds. NOTICE that some blocks (with similar transactions) ARE EXECUTED in 20x/40x times than others. If you have the detailed logs produced by this node, you will realize that the performance is due to the fact that the accounts and storage cells used during the execution of a block ARE ALREADY in memory, in an internal cache. The bottleneck is the storage access.</p><p>(The above data was obtained in some internal stress and performance test using production nodes running in testnet; they are many of this tests, run during the last year, that shows a similar pattern).</p><p>Data Cache</p><p>In RSK implementation, there is a cache in memory for key-values, so the values are not retrieved EVERY time from storage (in RSK, from leveldb). To show the impact of the retrieve of values from storage, look this log lines:</p><pre>2021-05-07-<strong>23:31:12.253</strong> TRACE [datasourcewithcache]  Activity: No. Gets: 968. No. Puts: 469. No. Gets from Store: 966<br>2021-05-07-<strong>23:31:32.838</strong> TRACE [datasourcewithcache]  Activity: No. Gets: 724. No. Puts: 384. <strong>No. Gets from Store: 426</strong><br>2021-05-07-23:32:19.899 TRACE [datasourcewithcache]  Activity: No. Gets: 1789. No. Puts: 858. No. Gets from Store: 1199<br>2021-05-07-23:32:45.941 TRACE [datasourcewithcache]  Activity: No. Gets: 1418. No. Puts: 649. No. Gets from Store: 757<br>2021-05-07-23:33:11.732 TRACE [datasourcewithcache]  Activity: No. Gets: 1629. No. Puts: 659. No<br>. Gets from Store: 740</pre><p>Each line shows some results of the execution of A BLOCK. Notice that the time internval between the first and second line IS 20 seconds aprox. And that the execution of the second blocks invoved the retrieve of 426 values FROM LEVELDB (missing from cache).</p><p>Look now at these log files, when the cache is more populated with the most used data, some time after the above blocks execution:</p><pre>2021-05-08-<strong>00:11:13.557</strong> TRACE [datasourcewithcache]  Activity: No. Gets: 1438. No. Puts: 602. No. Gets from Store: 10<br>2021-05-08-<strong>00:11:15.201</strong> TRACE [datasourcewithcache]  Activity: No. Gets: 1800. No. Puts: 789. <strong>No. Gets from Store: 46</strong><br>2021-05-08-<strong>00:11:15.881</strong> TRACE [datasourcewithcache]  Activity: No. Gets: 1393. No. Puts: 639. <strong>No. Gets from Store: 12</strong><br>2021-05-08-00:11:17.476 TRACE [datasourcewithcache]  Activity: No. Gets: 1385. No. Puts: 654. No. Gets from Store: 42<br>2021-05-08-00:11:18.626 TRACE [datasourcewithcache]  Activity: No. Gets: 962. No. Puts: 462. No. Gets from Store: 28</pre><p>Now, the second block (in this sequence) processing time was 2 seconds, and the number of missing values was only 46. And look at the third block: execution of less than 0.7 seconds, only 12 missed values.</p><p>The transactions are similar in the above blocks: simple invocations to DeFi-like smart contracts. But the influence of data cache is important to performance.</p><h3>Separation of Concern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*zhL3f37W-zeRrC4P.png" /><figcaption>(Image taken <a href="https://aspiringcraftsman.com/2008/01/03/art-of-separation-of-concerns/">https://aspiringcraftsman.com/2008/01/03/art-of-separation-of-concerns/</a>)</figcaption></figure><p>To me, RSK code trie and execution code is not “the best”. There are some current issues to improve and fix trie usage (see <a href="https://github.com/rsksmart/rskj/issues/1510">https://github.com/rsksmart/rskj/issues/1510</a> and <a href="https://github.com/rsksmart/rskj/issues/1511">https://github.com/rsksmart/rskj/issues/1511</a>). But also the use of the retrieved value is executed by not so simple code.</p><p>More than a year, I proposed a pull request to really start separate the use of the values in block execution (using internal key-value caches) from the trie storages: read <a href="https://angeljavalopez.medium.com/decoupling-storage-from-execution-in-rsk-blockchain-ea92aeb02259">Decoupling Storage from Execution in RSK Blockchain</a>. In this way, the internal representation follows the usages: key-values, instead of trie access. It could be a “baby step” to have in the future a journal of key values. According to <a href="https://github.com/rsksmart/rskj/pull/1123">my pull request comments</a> the performance should be also improved: less convoluted code to retrieve values from trie path, and a more direct key-value access to emergent caches adapted to the current execution pattern (the most used contracts already in-memory).</p><h3>Dynamic World State</h3><p>Some years ago, I wrote (in an Spanish post): “the disk is the modern tape”, pointing to have all in-memory to improve performance execution of modern systems. The use of all the above approach (in-memory trie, trie nodes in cache, separation of trie path-value from key-value), allows the emergence of a dynamic world state in memory ADAPTED to the current blocks under execution (the most used values are already in memory), an approach that have its impact, as the numbers from stress and performance test in testnet shown. I think it could even solve more of the problems described in <a href="https://blog.ethereum.org/2021/05/18/eth_state_problems/">Dodging a bullet: Ethereum State Problems</a>.</p><p>Angel “Java” Lopez<br>@ajlopez</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9330aa50fbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Code Many Storages]]></title>
            <link>https://angeljavalopez.medium.com/one-code-many-storages-afbbe1643c0a?source=rss-357cf59669cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/afbbe1643c0a</guid>
            <dc:creator><![CDATA[Angel Java Lopez]]></dc:creator>
            <pubDate>Fri, 09 Apr 2021 10:17:01 GMT</pubDate>
            <atom:updated>2021-04-09T10:17:01.513Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/943/0*wfDco4MJ_CNH2f1H.jpg" /></figure><p>When you deploy a compiled smart contract to an Ethereum-like blockchain like RSK, your transaction includes the compiled bytecode, including the constructor code.</p><p>An example, if you want to deploy Counter.sol:</p><pre>pragma solidity &gt;=0.5.0 &lt;0.6.0;</pre><pre>contract Counter {<br>    uint public counter;<br>    <br>    function increment() public {<br>        counter++;<br>    }<br>    <br>    function add(uint value) public {<br>        counter += value;<br>    }<br>    <br>    function incrementFail() public {<br>        counter++;<br>        require(false, &quot;fail error&quot;);<br>    }<br>    <br>    function fail() public pure {<br>        require(false, &quot;fail error&quot;);<br>    }<br>}<br></pre><p>your transaction will contain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5fg8eDHsf2gqcZykeTn89A.png" /><figcaption>Deploy Transaction for Counter.sol</figcaption></figure><p>The data field is huge, for such small smart contract. Imagine its size when you deploy a more complicated DeFi-related contract. The size of the payload and the size of the runtime bytecodes in the contract HAVE an associated cost in gas. This is because you must pay for the work every node in the network will execute to deploy this contract.</p><p>Some times, you need to deploy the same contract many times. IE, a liquidity pool in a DeFi project, or a surrogate contract for representing a user without balance using metatransactions (see my project <a href="https://github.com/ajlopez/EthMeta">https://github.com/ajlopez/EthMeta</a>)</p><p>For those cases, I have a proposal and associated code. Instead of sending the smart contract code EVERY TIME you need a new instance, you can say:</p><blockquote>“I need a new instance BUT WITH THE same code another instance has”.</blockquote><p>Then, this new instance will have its own storage, but the code is shared with another account.</p><p>The way to specify this intention is SENDING THE another instance ADDRESS as part of the data field. My proposal: send a data field with 32 bytes, including the address padded to the right:</p><pre>data: 0x000000000000000000000000157973f817512a87a4f5eb12b1a1ec448d1d7049</pre><p>In this way, the cost could be lower, and it could be significant impact, for example, in metatrasactions implementations that support thousands of surrogate contracts representing users without balance.</p><p>I coded a first implementation in my <a href="https://github.com/ajlopez/BlockchainJ">personal BlockchainJ project</a>, see commit <a href="https://github.com/ajlopez/BlockchainJ/commit/206c1d57a47608b5ead619ca493c3e444f02aee2">https://github.com/ajlopez/BlockchainJ/commit/206c1d57a47608b5ead619ca493c3e444f02aee2</a></p><p>The price to pay: you lost the constructor. But it is a common pattern now, with upgradable contracts, to have an initialized() function to be called immediately after the creation of the new instance.</p><p>Usually this kind of deploy are executed using scripts, so there is no change in the wallet implementations.</p><p>Angel “Java” Lopez<br><a href="https://twitter.com/ajlopez">@ajlopez</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afbbe1643c0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Files in the Blockchain]]></title>
            <link>https://angeljavalopez.medium.com/files-in-the-blockchain-dc929ecbdaaa?source=rss-357cf59669cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc929ecbdaaa</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[rsk]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[storage]]></category>
            <dc:creator><![CDATA[Angel Java Lopez]]></dc:creator>
            <pubDate>Tue, 16 Feb 2021 13:26:42 GMT</pubDate>
            <atom:updated>2021-02-16T13:26:42.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DKeWY62jgUi1XJ41" /><figcaption>Photo by <a href="https://unsplash.com/@jankolar?utm_source=medium&amp;utm_medium=referral">Jan Antonin Kolar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>These days I am practicing programming smart contracts in Solidity using TDD. There are several projects I am working on: some DeFi projects, a programmatic faucet, user login and onboarding, personal notes, some games. One of the projects already has something to show: I have been able to upload (image) files to RSK’s testnet.</p><p>One comment: a blockchain is not the more appropriate place to save files, at least an Ethereum-like. The upload of a file could cost many millions of gas units. And the retrieval is not the fastest. But I wanted to explore some Solidity code, and also, do an experiment with web application.</p><h3>Show Me The Code</h3><p>The project is at <a href="https://github.com/ajlopez/SimpleFS">https://github.com/ajlopez/SimpleFS</a></p><p>The main contract I’m using is <a href="https://github.com/ajlopez/SimpleFS/blob/master/contracts/ChunkedFile.sol">ChunkedFile.sol</a>. It can contains an array of chunks. Each chunk is a bytes array. The owner of the contract can upload a file, putting chunks into this smart contract. The chunks can be retrieved by anyone, one by one.</p><p>The internal state is very simple:</p><pre>contract ChunkedFile {<br>    address public owner;<br>    <br>    bytes[] public chunks;</pre><p>There are functions for put and get chunks:</p><pre>function get(uint nchunk) public view returns (bytes memory) {<br>    return chunks[nchunk];<br>}</pre><pre>function put(uint nchunk, bytes memory content) public onlyOwner {<br>    if (nchunk == chunks.length)<br>        chunks.push(content);<br>    else<br>        chunks[nchunk] = content;<br>}</pre><h3>Uploading and Downloading Files</h3><p>As in other of my projects, I added commands that use my RskApi library (read <a href="https://angeljavalopez.medium.com/command-line-tools-for-rsk-node-565d53c240c1">Command Line Tools for RSK</a>). Detailed instructions at <a href="https://github.com/ajlopez/SimpleFS/tree/master/commands">https://github.com/ajlopez/SimpleFS/tree/master/commands</a></p><p>Having defined the host and some user with balance, you can upload a file (I recommend to use a file with size less than 20K) using a chunk size of 4096 bytes:</p><pre>node deploy myuser file1 ChunkedFile<br>node upload myuser file1 &lt;localfilepath&gt; 4096</pre><p>To download the file, execute</p><pre>node download myuser file1 &lt;localfilepath&gt;</pre><h3>Viewing Files</h3><p>I wrote an express web application, that you can run locally (<a href="https://github.com/ajlopez/SimpleFS/tree/master/dapps/imagesexpress">read instructions</a>). It has an index with six images, and one page to show each one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*Ipw0WqXWdMtt_FoYi1UdlA.png" /><figcaption>One of my watercolor painting practice, now immortalized in the blockchain</figcaption></figure><h3>Next Steps</h3><ul><li>A next.js web application</li><li>Deploy the sample dapp to a hosting service (maybe vercel)</li><li>Use of directories</li><li>Add properties to files and directories</li></ul><p>I had a lot of fun with this project!</p><p>Angel “Java” Lopez<br>@ajlopez</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc929ecbdaaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database-like Tables in Blockchain]]></title>
            <link>https://angeljavalopez.medium.com/database-like-tables-in-blockchain-d75e4df4b7b6?source=rss-357cf59669cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d75e4df4b7b6</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[rsk]]></category>
            <dc:creator><![CDATA[Angel Java Lopez]]></dc:creator>
            <pubDate>Tue, 15 Dec 2020 21:39:53 GMT</pubDate>
            <atom:updated>2020-12-15T21:39:53.775Z</atom:updated>
            <content:encoded><![CDATA[<p>Based on an idea by <a href="https://twitter.com/bguiz">bguiz</a> published in RSK reseach forum: <a href="https://research.rsk.dev/t/crazy-idea-new-opcodes-for-relational-db-like-data-reads-and-writes/52">Crazy Idea: New opcodes for relational DB like data reads and writes</a>, I was writing Solidity code to explore an alternative implementation in an Ethereum-like blockchain. I don’t add opcodes because these are scarce, and adding them could broke compability with Ethereum. My project is <a href="https://github.com/ajlopez/BDTables">BDTables</a>.</p><p>The base idea is to have an smart contract representing a database-like table with rows and columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FpPevnvGinJSYv5h99SHVA.png" /><figcaption>Table smart contract storage</figcaption></figure><p>That is, a Table smart contract has: no of rows, no of columns, and a data offset where the data START to reside. The data is dynamically used, it’s not a fixed side array, and each field contains a bytes32.</p><p>A fragment of the current <a href="https://github.com/ajlopez/BDTables/blob/master/contracts/Table.sol">Table.sol</a> code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*3FgMYJ75vlfprC6ipjGamg.png" /><figcaption>Table smart contract constructor</figcaption></figure><p>To manage the data cells (in consecutive storage cells starting at data offset) I’m using assembly tricks, ie:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*QY2W8bSsy_el4yXv7yzz0w.png" /><figcaption>Adding a row of bytes32 using assembly</figcaption></figure><p>I have functions to add, get and delete rows. Also to get an specific field (by row and column). And a function to return the first row in a range that satisfies an equality match over a column.</p><p>But, what if you want to manage integers, strings? Well, I implemented an <a href="https://github.com/ajlopez/BDTables/blob/master/contracts/ExtendedTable.sol">ExtendedTable.sol</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C29qztyCKq3UCziBmoZ-cQ.png" /><figcaption>An extended table could manage strings and define comparisonoperators</figcaption></figure><p>Using an extended table, I can define a table with other fields and types, ie <a href="https://github.com/ajlopez/BDTables/blob/master/contracts/ExpensesTable.sol">ExpensesTable.sol</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*ws7aSNWp4TUb88wwhwaamw.png" /></figure><p>Notice that the string is saved as a bytes32 hash, and the mapping to the original string is kept by the extended table. In the current code, I have another extended sample <a href="https://github.com/ajlopez/BDTables/blob/master/contracts/TransfersTable.sol">TransfersTable.sol</a>.</p><p>As usual, I wrote all the code following the TDD (Test-Driven Development) workflow, so the tests are a guide to the use of these contracts.</p><p>In these tables, I have ad-hoc query functions, by string value or by unsigned integer comparison. Notice that in the query functions I’m providing a range of rows ids to process in the query, so the calling transaction or smart contract could limit the gas to use in the operation.</p><p>Next steps</p><p>There are many ideas to add:</p><ul><li>A database smart contract, that contains the names and address of tables</li><li>Code generation of extended tables, based on columns definitions (types), so the query functions are generated</li><li>Write a precompiled contract to manage any Table smart contract storage (the recommendation is that this contract has only the cells I described at the beginning of this post: no of rows, no of columns, data offset and field cells)</li><li>Add to that precompiled contract some capacity to parse and execute a simplified SQL statement</li><li>Write a “to do dapp” but I’m not yet confident writing such project</li></ul><p>I could write the precompiled contract into the RSK implementation, but I think <a href="https://angeljavalopez.medium.com/decoupling-storage-from-execution-in-rsk-blockchain-ea92aeb02259">the RSK storage management is not decoupled from inner storage in tries</a>, so, to avoid such complications, I could start using <a href="https://github.com/ajlopez/blockchainj">my personal blockchain project</a>.</p><p>I have a lot of fun with this project, thanks for the idea <a href="https://twitter.com/bguiz">bguiz</a>!</p><p>Angel “Java” Lopez</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d75e4df4b7b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoupling Storage from Execution in RSK Blockchain]]></title>
            <link>https://angeljavalopez.medium.com/decoupling-storage-from-execution-in-rsk-blockchain-ea92aeb02259?source=rss-357cf59669cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea92aeb02259</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[rsk]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Angel Java Lopez]]></dc:creator>
            <pubDate>Tue, 08 Dec 2020 11:22:23 GMT</pubDate>
            <atom:updated>2020-12-08T11:22:23.352Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/530/0*CkpDk-oTtFCt4BFk.png" /></figure><p>These years I was programming a log, using TDD (Test-Driven Programming), to keep me trained in design and developer skills. To me, TDD is a great workflow to discover emergence design solutions, to simple and complex domains. One of my preferred domains is blockchain, and I wrote tons of code in Java, C# and JavaScript, even Solidity smart contracts. The top example is <a href="https://github.com/ajlopez/blockchainj">my personal blockchain project in Java</a> (see also <a href="https://github.com/ajlopez/blockchainj#posts">my published posts</a>).</p><p>I learned about blockchain thanks to my work in <a href="https://www.rsk.co/">RSK</a>. The company flag product is an Ethereum-like blockchain, connected to the Bitcoin blockhain. <a href="https://github.com/rsksmart/rskj">The open source node</a> is a derived work from <a href="https://github.com/ethereum/ethereumj">EthereumJ implementation</a> (now deprecated).</p><p>One thing I learned from my personal experiments in blockchain implementation, is that the Ethereum-like smart contract storage COULD (and SHOULD) BE decoupled from block/transaction execution. I described some of my implementation in <a href="https://angeljavalopez.medium.com/building-a-blockchain-executing-smart-contracts-ad06c8ec037">Building a Blockchain: Executing Smart Contracts</a>.</p><p>The usual implemenation in Ethereum for smart contract storage involves the use of Trie (see <a href="https://medium.com/@eiki1212/ethereum-state-trie-architecture-explained-a30237009d4e">Ethereum State Trie Architecture Explained</a> for a general description). Implementing a Trie is a beautiful work, and using TDD, I implemented it many times (including most of the code of a new Trie implementation for RSK I wrote in 2016, completed and reviewed with team work, replacing the original EthereumJ implementation).</p><p>Since then, I think that the execution of smart contract could be executed WITHOUT knowing the existence of a trie. That is, the storage can be easily decoupled from execution.</p><p>I started a proposal for RSK in 2018 (<a href="https://github.com/ajlopez/rskj/tree/repositories">see branch</a>) to get rid of any coupling (EthereumJ implementation was very convoluted in that area). But the project took another path, that in my opinion, didn’t solved this issue: nothing in the transaction execution SHOULD know about a trie storage. Also, I though that a more clear implementation of the use and access of the storage cells would be better for the project.</p><p>I wrote another proposal for RSK in 2019 (<a href="https://github.com/ajlopez/rskj/tree/repositories2">see branch</a>) to have instances like <a href="https://github.com/ajlopez/BlockchainJ/blob/master/src/main/java/com/ajlopez/blockchain/execution/ExecutionContext.java">ExecutionContext.java</a> from my personal project. Only the <a href="https://github.com/ajlopez/BlockchainJ/blob/master/src/main/java/com/ajlopez/blockchain/execution/TopExecutionContext.java">TopExecutionContext.java</a> KNOWS the existence of a trie (and it could even improved), while <a href="https://github.com/ajlopez/BlockchainJ/blob/master/src/main/java/com/ajlopez/blockchain/execution/ChildExecutionContext.java">ChildExecutionContext.java</a> only manage internal cache for accounts and storage valeus.</p><p>My informal experiments showed an improvement in execution time also (see my comments <a href="https://github.com/rsksmart/rskj/pull/1123">in a pull request</a>). There are INFORMAL, but they look good to explore. My first thought: the improve in performance is due to this decoupling, and to have a clear key-value cache, separated by account and by storage, avoiding in most case the calculation of long trie keys. But I should try to improve these experiments, but, as you know: lack of time, so many ideas, only one life.</p><p>One more thing; this decoupling facilitates the migration to have a journal of key values instead of a nested stack of execution context, avoiding the abuse of retrieving values from deep-nested smart contract code. I will wrote a journal implementation in my personal project, to show that is totally transparent to the execution logic.</p><p>(the top image was taken from <a href="https://medium.com/@dahnielson/decoupling-2045aadf7729">Decoupling blog post</a>)</p><p>Angel “Java” Lopez</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea92aeb02259" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Paying Storage Access]]></title>
            <link>https://angeljavalopez.medium.com/paying-storage-access-d78157757dc3?source=rss-357cf59669cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d78157757dc3</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[rsk]]></category>
            <category><![CDATA[storage]]></category>
            <dc:creator><![CDATA[Angel Java Lopez]]></dc:creator>
            <pubDate>Fri, 27 Nov 2020 12:27:07 GMT</pubDate>
            <atom:updated>2020-11-27T12:27:07.885Z</atom:updated>
            <content:encoded><![CDATA[<p>In an Ethereum-like blockchain (like <a href="https://www.rsk.co/">RSK</a> or <a href="https://github.com/ajlopez/blockchainj">my personal project BlockchainJ</a>) the smart contracts have a linear storage, composed by cells thafied by a key.</p><p>In case of storage, the key is a data word of 32 bytes (a kind of unsigned big number) and the value is also a data word (well, in RSK and my implementation, the value could be any byte array, is up to the consumer code the interpretation of that value).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DU_0OeGxA1SHFQijuPC6SA.png" /><figcaption>Smart contract storage</figcaption></figure><p>The storage looks linear BUT only the values that are not zero are saved. In Solidity, the mappings, strings and dynamic arrays occupy more than one cell that are scattered along a 32-byte address space.</p><p>Generally the internal implementation uses byte arrays as keys and values. In order to calculate the world state root, the storage is saved using a trie structure.</p><p>There are many interesting things to discuss about tries: their number of children nodes per node (ie: I found the hexary tries better to binary ones in terms of storage usage), compression, retrieve and update (ie, only save the UPDATED values at THE END of a block execution), that can affect the performance and the resource consumption of a blockchain node.</p><p>Due to the resource involved (ie disk access and space) the load and store of storage cell values cost more gas than the cost of load and store of transient memory values. Along the time, the space occupied by all the world states in a full node could be huge. This post is an idea, a proposal, to be discussed and improved, about one simple way to collect execution fees to pay that storage.</p><h3>The Proposal</h3><p>First: it DOES NOT cover the same issues than storage rent (read <a href="https://medium.com/going-byzantine/ethereum-storage-rent-a2b89e96bd35">Ethereum Storage Rent: What should expect?</a> and <a href="https://eips.ethereum.org/EIPS/eip-1682">EIP-1682: Storage Rent</a>). It’s only a “baby step” approach that could not affect the block execution performance and with low disk space footprint.</p><p>The idea is simple: to attach to each value saved in a trie node, an <strong>associated</strong> <strong>BLOCK NUMBER</strong>. At first, this block number corresponds to the last block THAT UPDATED the value.</p><p>So, it implies to save a block number (in current implementations, around 4 bytes), when create the trie node that contains the value.</p><p>Then, when the value is retrieved again in a future block, if its block number is LESS than current block number minus N (maybe N could be 100_000 blocks), then the COST if LOAD STORE is GREATER. In this way, the fees collaborate to mantain old storage.</p><p>Second, there is a minor improvement: to consider another block number with the LAST BLOCK that READS the value. I PREFER to use THE SAME block number.</p><p>But there is a minor problem: each reads should update that number for each value retrieved, and that will increase the cost of load store into memory. If that cost is translated to more gas costs, it could be excesive.</p><p>So, my idea is TO UPDATE the block number B (in case of read the value) ONLY IF B is less that current block number minus N (again, N could be 100_000).</p><p>With these two cases, the old storage cost will be covered if:</p><ul><li>It is read (but only in fraction of the reads)</li><li>It is written (with more cost if the value is old)</li></ul><h3>Variants</h3><p>First, the number N should be determinad, and could be different for gas increment vs detecting old reads.</p><p>Second: the additional cost in gas to pay could be proportional to the AGE of the value.</p><p>It can be implemented as a network update (hard fork) and in an incremental way (adapting the values WITHOUT associated block number along the blockchain advance, I have an idea to do this without much resource consumptions).</p><p>It could be implemented not only for STORAGE but also other values that are part of the world state, like account states.</p><p>Also, the associated block number (to a value) could be extended to EACH trie node (not only the ones with values) and be used in other algorithms (like storage garbage collection).</p><h3>Pros and Cons</h3><p>There should be many, but now:</p><ul><li>Pros: simplicity, incremental adoption</li><li>Cons: it does not consider old storage that it is never read or written</li></ul><p>Maybe, I will add this number to my current implementation.</p><p>Angel “Java” Lopez</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d78157757dc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Blockchain: Executing Smart Contracts]]></title>
            <link>https://angeljavalopez.medium.com/building-a-blockchain-executing-smart-contracts-ad06c8ec037?source=rss-357cf59669cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad06c8ec037</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[virtual-machine]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Angel Java Lopez]]></dc:creator>
            <pubDate>Wed, 25 Nov 2020 12:54:34 GMT</pubDate>
            <atom:updated>2020-11-25T12:54:34.692Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m very proud of my favorite personal <a href="https://github.com/ajlopez/blockchainj">project BlockchainJ</a>: build a Blockchain in Java, from scratch, using TDD (Test-Driven Development). Previous posts:</p><p><a href="https://angeljavalopez.medium.com/building-a-blockchain-introduction-e4193fd7f174">Building a Blockchain: Introduction</a><br><a href="https://angeljavalopez.medium.com/building-a-blockchain-main-entities-8dd4c94c48e0">Building a Blockchain: Main Entities</a><br><a href="https://angeljavalopez.medium.com/building-a-blockchain-serialization-4561c686767a">Building a Blockchain: Serialization</a><br><a href="https://angeljavalopez.medium.com/building-a-blockchain-key-value-stores-5103f1052dc4">Building a Blockchain: Key Value Stores</a><br><a href="https://angeljavalopez.medium.com/bui%C3%B1ding-a-blockchain-subroutines-in-the-virtual-machine-a79cc2dbf0e5">Building a Blockchain: Subroutines in the Virtual Machine</a><br><a href="https://angeljavalopez.medium.com/building-a-blockchain-towards-beam-synchronization-de4eb30466e8">Building a Blockchain: Towards Beam Synchronization</a></p><p>It’s based in Ethereum, so it supports smart contracts. I’m using the same bytecodes, to keep compability with the ecosystem (like Solidity compilers and wallets).</p><p>Today, I want to describe my current implementation of how to execute an smart contract in the <a href="https://github.com/ajlopez/BlockchainJ/blob/master/src/main/java/com/ajlopez/blockchain/vms/eth/VirtualMachine.java"><strong>VirtualMachine.java</strong></a> class. A diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fayQyKkizRSbGrFRNzjwfQ.png" /><figcaption>Instances provided to Virtual Machine to execute smart contract code</figcaption></figure><p>The left classes are injected at constructor time. The right classes are injected when I want to execute the code. Using TDD, I could change the design at any moment, without pain. Really, I changed this design in the last week, without much effort. The instances injected at constructor time are:</p><p><a href="https://github.com/ajlopez/BlockchainJ/blob/master/src/main/java/com/ajlopez/blockchain/bc/BlockChain.java"><strong>BlockData.java</strong></a>: having the information of the current block under execution, like number, difficulty, chain id (yes, I added chain id to the block header)</p><p><a href="https://github.com/ajlopez/BlockchainJ/blob/master/src/main/java/com/ajlopez/blockchain/vms/eth/MessageData.java"><strong>MessageData.java</strong></a>: it has the information about the current call: sender address, origin (original transaction sender) address, receiver address (usually the current smart contract under execution), gas limit, gas price, etc. Maybe I could split this data in two: TransactionData, and MessageData. The first one would be inmutable ALONG the execution of the smart contract and its internal call. Remember: an smart contract could INVOKE ANOTHER smart contract, and again, having many levels of invocations. This instance is inmutable during the invocation of the current code under process.</p><p><a href="https://github.com/ajlopez/BlockchainJ/blob/master/src/main/java/com/ajlopez/blockchain/execution/ExecutionContext.java"><strong>ExecutionContext.java</strong></a>: an interface that allows the access and update of the world state: accounts and contract storages. The important thing to take into account: after execution of the code, its changes could be commited or rollbacked, depending on the success or failure of the execution (ie a revert should raise a rollback, so the world state is not changed; but only a rollback of this level: an smart contract A could call smart contract B, then B reverts, then the changes OF B (ONLY B) are rollbacked; then the smart contract A could decide to bubble up the revert or not).</p><p>At execution time I provide to the virtual machine two instances:</p><p><a href="https://github.com/ajlopez/BlockchainJ/blob/master/src/main/java/com/ajlopez/blockchain/vms/eth/Storage.java"><strong>Storage.java</strong></a>: the current smart contract storage (a minor but critical detail: it should be provided by the current execution context, to live under the umbrella of rollback or commit; this coupling says to me something: I could review this design later, TDD rules!)</p><p><strong>Code</strong>: a byte array with the bytecodes</p><p>At the end, the execution returns an <a href="https://github.com/ajlopez/BlockchainJ/blob/master/src/main/java/com/ajlopez/blockchain/vms/eth/ExecutionResult.java"><strong>ExecutionResult.java</strong></a> with information about the success or failure of the execution, error message, etc.</p><p>Keep tuned!</p><p>Angel “Java” Lopez</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad06c8ec037" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyzing RSK Blocks: Miners]]></title>
            <link>https://angeljavalopez.medium.com/analyzing-rsk-blocks-miners-427e70c59193?source=rss-357cf59669cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/427e70c59193</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[rsk]]></category>
            <category><![CDATA[mining]]></category>
            <dc:creator><![CDATA[Angel Java Lopez]]></dc:creator>
            <pubDate>Mon, 02 Nov 2020 20:59:47 GMT</pubDate>
            <atom:updated>2020-11-02T20:59:47.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eiWog4JQXFCkYTD4" /><figcaption>Photo by <a href="https://unsplash.com/@estherrj?utm_source=medium&amp;utm_medium=referral">Esther Jiao</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Some months ago, I wrote about <a href="https://angeljavalopez.medium.com/command-line-tools-for-rsk-node-565d53c240c1">Command Line Tools for RSK Node</a>; now those tools are included in <a href="https://github.com/rsksmart/rskj/releases/tag/PAPYRUS-2.1.0">the latest RSKJ release</a> (under the package with name co.rsk.tools.cli).</p><p>Using a local testnet database, I exported 5000 blocks with the command:</p><pre>java -cp &lt;rsk.jar&gt; co.rsk.cli.tools.ExportBlocks 718000 722999 --testnet &gt; testnetblocks.txt</pre><p>These days, I wrote <a href="https://github.com/ajlopez/RskUtils/tree/master/procblocks">new commands in JavaScript</a> to analyze that info, specially to obtain the blocks mined by each miner account.</p><h3>Counting the Blocks</h3><p>Using <a href="https://github.com/ajlopez/RskUtils/blob/master/procblocks/count.js">count.js</a>, I executed:</p><pre>node count testnetblocks.txt</pre><p>The output was:</p><pre>no blocks 5000<br>no transactions 250849<br>average no transactions per block 50.1698<br>no uncles 6461<br>average no uncles per block 1.2922<br>no uncles same miner 4126<br>total size (bytes) 57563723<br>block average size (bytes) 11512.7446</pre><p>It’s interesting to see that the number of uncles included into a BLOCK that belongs to the same miner that the one that builds the block, it’s only around 2/3, so each miner uses the blocks received from other miners.</p><h3>Blocks by Miner</h3><p>Using <a href="https://github.com/ajlopez/RskUtils/blob/master/procblocks/miners.js">miners.js</a>, I executed:</p><pre>node miners.js testnetblocks.txt</pre><p>the output was:</p><pre>{<br>    &quot;1fab9a0e24ffc209b01faa5a61ad4366982d0b7f&quot;: 3933,<br>    &quot;b774aa2876145b2f6f3de27e5e6ac970aa12d771&quot;: 1067<br>}</pre><p>There are only two miners in RSK testnet. More interesting result could be obtained from mainnet block ranges.</p><h3>Blocks and Uncles by Miner</h3><p>I also wrote <a href="https://github.com/ajlopez/RskUtils/blob/master/procblocks/minersu.js">minersu</a>.js and executed:</p><pre>node minersu.js testnetblocks.txt</pre><p>This time not only the blocks were processed but also their uncles. The result was:</p><pre>{<br>    &quot;1fab9a0e24ffc209b01faa5a61ad4366982d0b7f&quot;: 8702,<br>    &quot;b774aa2876145b2f6f3de27e5e6ac970aa12d771&quot;: 2759<br>}</pre><h3>Pending Work</h3><p>The minersu.js command was written thinking on processing NOT only the blocks that were included into the main chain, but also siblings (avoiding to count repeated uncles more than once). I should modify the export blocks commands to export the known siblings in the working database (it could vary from node to node). Now, that command line tools only exports the blocks included in the mainchain.</p><p>I want to add also more analysis, ie, the works executed by federated accounts (ie which one sends more transaction and info, etc)</p><p>Angel “Java” Lopez</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=427e70c59193" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tokens for Your Users]]></title>
            <link>https://angeljavalopez.medium.com/tokens-for-your-users-2804c186292e?source=rss-357cf59669cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2804c186292e</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Angel Java Lopez]]></dc:creator>
            <pubDate>Sat, 31 Oct 2020 21:15:42 GMT</pubDate>
            <atom:updated>2020-10-31T21:15:42.756Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose that you have an online web site, social network, or game. Your users connect with your server(s) using a mobile, web or desktop client application. Each user has a nickname, and should provide credentials to initiate a session with your server.</p><p>Now, you want to give them tokens, as they complete tasks, activities, games, receive likes, or provide content to your system. That tokens resides in an Ethereum-like blockchain. I want to describe a workflow that allow your users to participate in the blockchain.</p><h3>Blockchain Sign Up</h3><p>A user must sign up to participate in the blockchain activities. He/she has a nickname, and presents credentials to sign into the server application. But I’m talking about OTHER process: to assign a blockchain account to the user, he/she must register with a new and private credential, unknown to the server application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fG0Ay7ypqww_s-i_N89V2g.png" /><figcaption>User Sign Up to Blockchain</figcaption></figure><ol><li>The user fill the blockchain sign up form, given new and private credentials (ie a new password)</li><li>Given the user nickname and the new credentials, the client applications calculates a blockchain address. It could use the nickname and new credentials to generate the “twelve words” needed to generate an account.</li><li>The client application sends the account information (its address) to the server application.</li><li>The server application associates the user nickname with the new blockchain address, using a public registry smart contract. Maybe it sends the first tokens to the user blockchain account.</li><li>The client application could check the availability of tokens associated to user blockchain account address</li></ol><h3>Blockchain Sign In</h3><p>No private key or “twelve words” are saved in the client side. If the user needs to initiate a blockchain session again, then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IHZbGk57HP-JvOf1be-1GQ.png" /><figcaption>Initiates the Session</figcaption></figure><ol><li>The user provides the blockchain credentials (ie private password)</li><li>The client application, given the user nickname and provided private credential, generates the account information (private key, address).</li><li>The client application verifies that the address generated is associated with user nickname querying the public registry smart contract</li></ol><h3>Crypto Gas for the User</h3><p>Usually, the user don’t send transactions to the blockchain. He/she considers the tokens as a points program. But if he/she is interested in operate in the blockchain, crypto ether is needed to pay gas cost, then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6V0byTNPoHlDMLqPTvIPrg.png" /><figcaption>Exchange Tokens with Crypto</figcaption></figure><ol><li>The user informs to the client application his/her intention to exchange N tokens by gas</li><li>The client application, using the in-memory private key, builds and signs a user transaction, that transfer some tokens to the server account</li><li>The server application do: <br>a) Checks if the user has at least N tokens<br>b) Funds the user account with enough gas to execute the tokens transfer transaction<br>c) If the transaction is executed succesfully, then the server application transfer gas/crypto to the user account</li></ol><p>If the total fund were transferred in point b, then the user could use those funds to execute an ALTERNATIVE transaction, that competes with the token transfer transaction provided.</p><p>There are many points to discuss, and some improvements. Instead of associate a user nickname with an address, the client application could provide a JSON string with a keystore information (see <a href="https://medium.com/@julien.maffre/what-is-an-ethereum-keystore-file-86c8c5917b97">What is an Ethereum keystore file?</a>).</p><p>Angel “Java” Lopez</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2804c186292e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Blockchain: Towards Beam Synchronization]]></title>
            <link>https://angeljavalopez.medium.com/building-a-blockchain-towards-beam-synchronization-de4eb30466e8?source=rss-357cf59669cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/de4eb30466e8</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Angel Java Lopez]]></dc:creator>
            <pubDate>Fri, 30 Oct 2020 20:00:19 GMT</pubDate>
            <atom:updated>2020-10-30T20:00:19.440Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m very enthusiastic about my personal <a href="https://github.com/ajlopez/blockchainj">open source project BlockchainJ</a>, a blockchain written in Java using TDD. To me, it’s very interesting (and a lot of fun) to design, write and explore ideas and code using the Test-Driven Development workflow. I think that you can understand any problem if you write a solution to it. And to write a blockchain is a not trivial project, but also one that can be achieved. Every day, I wrote few lines of test and production code, to complete the task. Now, I can run many nodes, communicate them, mine blocks, execute transfer transactions, and some smart contract transactions. There are many things to complete, but in these years, I learned a lot from this assignment.</p><p>In <a href="https://medium.com/@angeljavalopez/building-a-blockchain-key-value-stores-5103f1052dc4">a previous post</a> I described the key value stores I’m using, and at the end of the post, I presented the remote storage: instead of having a local key value store, you can access the data from other nodes in the network. Using this feature, I could implement the execution of a block that comes from the network WITHOUT knowing the previous blocks in the blockchain. It could be described as a beam synchronization: the local node does not need to retrieve all the blocks in the blockchain to start operation. Also, I was thinking about these features to implement a light client.</p><p>In this post, I describe remote store in a bit more detail, and present a short code tests executing a block without having local accounts, contract codes and contract storage cells: they are provided by ANOTHER node transparently.</p><h3>Remote Stores</h3><p>The retrieve of a remote value associated with a key could be described in this diagram and steps description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vfr6e7gSR3Z9SZTTTEsA5A.png" /><figcaption>Remote Store Retrieving Value</figcaption></figure><ol><li><strong>Remote Store</strong> receives a request: given a key (byte array) retrieve the associated value (byte array)</li><li><strong>Remote Store</strong> sends a request to <strong>Send Processor</strong>, and waits for a future instance completion.</li><li><strong>Send Processor</strong> sends a request message to some of the peer nodes.</li><li>One peer node sends the value in a message. <strong>KeyValueProcessor</strong> check the consistency (ie key as a hash correspond to the supplied value, in case the key value store is the Account Trie).</li><li><strong>Key Value Processor</strong> completes the pending future for <strong>Remote Store</strong>.</li><li><strong>Remote Store</strong> response with the required value.</li></ol><p>In order to use remote stores in a transparent way, there are <strong>Dual Stores</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5vibZJGwaY5DGzEV912X0Q.png" /><figcaption>Dual Store to Build a Local Store using Remote Data incrementally</figcaption></figure><ol><li><strong>Dual Store</strong> receives a request: given a key (byte array) retrieve the associated value (byte array)</li><li>It checks the existence of the corresponding value consulting <strong>Local Store</strong>. If it exists, jump to step 4.</li><li>It retrieves the value using the <strong>Remote Store</strong>. If the value is retrieved, it is ALSO SAVED into <strong>Local Store</strong>. In this way, the local store is populated incrementally, using the most required data first.</li><li><strong>Remote Store</strong> response with the required value.</li></ol><h3>A Beam Execution</h3><p>This is a fragment of a test code that executes a block using dual stores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mqhO1xKW8eQrYBdDGai0Q.png" /><figcaption>Executing a Block using Dual and Remote Stores</figcaption></figure><p>The key piece is the construction of the <strong>BlockExecutor</strong>: it is injected with dual stores and store providers (the creation of these store is not included in the above fragment). There are two <strong>NodeProcessors </strong>that are communicated using peer to peer messages. The dual stores provided to the <strong>BlockExecutor </strong>have: local stores for node processor 2, and remote stores that access the rest of the network: in this case, the node processor 1.</p><p>When the <strong>BlockExecutor </strong>executes a block that is totally new in the context of node processor 2, it retrieves all the information needed from node processor 1, transparently. After the execution, the account trie nodes and any storate trie nodes retrieved are now available in the local stores of node processor 2. Then, along new blocks are received, they are executed faster, as the local stores (account trie, storage trie and key value code store) have more values, usually the most used in this range of the blockchain.</p><p>In this way, the node can start to validate blocks without dying in a long synchronization process. I could use partial merkle proof to assert the value that correspond to a given key, but it is interesting to collect more data about this alternative approach: one thing is that each value retrieved adds information to the local for FUTURE executions. Even shortened the size of the partial proof (maybe the first part is already know by the local node), this algorithm allows to detect quickly if some part of the required path IS ALREADY known by the node. It employs more bandwidth in messages, to be analyzed.</p><p>As I confessed, I had lot of fun implementing this feature.</p><p>Angel “Java” Lopez</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de4eb30466e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>