<?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 Shreemoy Mishra on Medium]]></title>
        <description><![CDATA[Stories by Shreemoy Mishra on Medium]]></description>
        <link>https://medium.com/@shreemoy?source=rss-780d0c2fb896------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fVWueiipuYMdF2Af6JIIMQ.png</url>
            <title>Stories by Shreemoy Mishra on Medium</title>
            <link>https://medium.com/@shreemoy?source=rss-780d0c2fb896------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:46:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shreemoy/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[Client Performance with Experimental Storage Rent Implementation]]></title>
            <link>https://medium.com/rootstock-tech-blog/client-performance-with-experimental-storage-rent-implementation-3ad19ce41610?source=rss-780d0c2fb896------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ad19ce41610</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[rentstorage]]></category>
            <category><![CDATA[rootstock]]></category>
            <dc:creator><![CDATA[Shreemoy Mishra]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 18:33:30 GMT</pubDate>
            <atom:updated>2023-01-09T16:42:49.109Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*hh0EW5AKQoWT51iniTE5Rg.png" /></figure><p>Our proposal for Storage Rent in Rootstock (<a href="https://github.com/rsksmart/RSKIPs/blob/master/IPs/RSKIP240.md">RSKIP240</a>) adds a new field to <em>each node</em> in the RSK Unitrie. The new field, called <em>lastRentPaidTime</em>, is a unix timestamp indicating the last time storage rent was collected for that trie node.</p><p>Our current <a href="https://github.com/rsksmart/rskj/tree/storage-rent-2022-audit">implementation</a> introduces <a href="https://github.com/rsksmart/rskj/tree/storage-rent-2022-audit/rskj-core/src/main/java/co/rsk/storagerent">new classes</a> of Java objects — e.g. <em>StorageRentManager</em>, <em>Rented Node</em>. These are used for rent tracking, rent computation, and rent timestamp updates — i.e. actions are triggered by trie access (reads, writes, deletes) methods in the Repository.</p><p>Naturally, these changes will have some impact on the performance of RSKj nodes, e.g. block execution time, disk IO access, disk usage etc. So, we conducted some experiments to measure such impact.</p><h3>What we expected</h3><p>We expect storage rent to utilize more RAM and consume more disk space — this is because the new timestamp adds 8 bytes to each unitrie node. We also expect the rent implementation to run a bit slower. This is because the node tracking, rent computations, and rent updates should lead to longer block execution time and more disk IO.</p><h3>What we found</h3><p>We used simple, two-sided, <strong>t-tests</strong> (at 5% level) to measure if an observed change in a metric was statistically significant. We found that</p><p><strong>Block Execution</strong> time increases by around 10%.</p><ul><li>An increase of 6% can be attributed to node tracking and rent computations.</li><li>An increase of 4% can be attributed to rent collection and timestamp updates.</li></ul><p><strong>Disk space usage</strong> (as measured by increase in unitrie LevelDB files) increases by almost 20%. Such a large increase can be understood as follows.</p><ul><li>A typical node consumes less than 100 bytes. Adding 8 bytes to each node (the rent timestamp) will naturally increase the size of each entry in the key value database.</li><li>Edited after initial post: IOV Labs Chief Scientist, <a href="https://medium.com/@SDLerner">Sergio Lerner</a>, notes that there may be another reason for this increase. It is possible that some <em>previously embedded nodes </em>may no longer remain embedded after the change. One way to verify this (in a future experiment) is to increase the threshold for embedding nodes by 8 bytes (in the Trie class within RSKj).</li><li>Rent timestamps are added to every node, <em>including internal nodes</em>. About half the nodes in the unitrie are internal nodes. These nodes typically do not contain any value (some of them do have a value). The impact of adding a timestamp is more pronounced for these small nodes. On the other hand, nodes that contain contract bytecode are large and the impact of adding a timestamp is small. However, relative to accounts and storage cells, there are very few nodes that contain contract code.</li><li>RSKj does not have garbage collection enabled (not by default). Thus, every time a rent timestamp is updated, the old value is not removed. Thus, in addition to having larger values, the key-value database also ends up with more keys (some with stale information).</li></ul><p><strong>RAM usage and Disk IO</strong> were <strong>unaffected</strong>. We expected both of these to increase, but the experimental blockchain was not large enough to have any statistical impact on RAM usage or on disk IO. We suspect that this may remain the case even once storage rent is activated on mainnet. This is because the RSK state is still under 1GB which is not large enough to impact most clients (RAM is typically 8GB or higher). However, as the state of RSK blockchain grows in the future, we should definitely expect to see some performance impact from additional disk IO.</p><h3><strong>Takeaway</strong></h3><p>An increase in disk usage is expected. This should not have any major performance impact on the node. What matters for performance is disk IO, which is impacted by the number of trie keys in the latest state snapshot, not historical state. But as mentioned above, disk IO and RAM consumption are not really affected by rent. This may change in the future when RSK state grows by a lot. The main concern from these experiments is the 10% increase in block execution time. At present, RSK blocks are usually not full. But as adoption increases, the performance impacts will be felt more strongly. Therefore, this can be an area of improvement and optimization in the future.</p><p><strong>How we evaluated the performance impact</strong></p><p>We compared 4 different versions of RSKJ. Two of them, HOP-4.0.0 and HOP-4.1.0, obviously do not include storage rent. The current implementation of storage rent is in between these releases.</p><p>We also ran <strong><em>two versions</em></strong> of the storage rent implementation. The first is the actual reference rent implementation for RSKIP240 linked at the start of the document. The RSKJ benchmarking tool can <em>create</em> and <em>replay</em> a blockchain with 100 blocks in just a few minutes. In these benchmarking runs, the time between blocks is too small for any meaningful amount of storage rent to build up. Nevertheless, these runs can help us measure the impact on execution time due to rent tracking and computation.</p><p>In the other version, we replaced the rent timestamp (same as block timestamp) with a block <em>number</em> instead. We also increased the parameter used for the price of storage rent (the rental rate) by a large factor. The rental rate was increased by a factor so that each set of 100 blocks — in the experiment — correspond to <strong>an entire year</strong>’s worth of blocks. This change helped “accumulate” <em>economically meaningful amounts</em> of storage rent, which leads to rent collections and timestamp updates. This helps us measure the impact of storage rent on disk IO, and disk usage, and the additional impact on block execution time.</p><p>So we ran 10 iterations for each variation, with about 300 blocks in each run. The storage rent accumulations can therefore be interpreted as those from a simulation of a 3 year run of the blockchain.</p><p>To keep the comparisons meaningful, we need to create “similar” blockchains.</p><ul><li>We set the block fill level “HALF” instead of the default FULL. Setting blocks to full (approximate, but still) can lead to unexpected errors should there be significant rent collections in some test scenario — which could then push transactions to the next block (making comparisons slightly less meaningful).</li><li>And we increased the <em>gaslimit</em> to account for the possibility of rent collections being triggered.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ad19ce41610" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rootstock-tech-blog/client-performance-with-experimental-storage-rent-implementation-3ad19ce41610">Client Performance with Experimental Storage Rent Implementation</a> was originally published in <a href="https://medium.com/rootstock-tech-blog">RootstockLabs: Research &amp; Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Porting a ZK Rollup Payments Solution from Ethereum to RSK]]></title>
            <link>https://medium.com/rootstock-tech-blog/porting-a-zk-rollup-payments-solution-from-ethereum-to-rsk-1c9fe0b22e41?source=rss-780d0c2fb896------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c9fe0b22e41</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[zkrollup]]></category>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[rsk]]></category>
            <category><![CDATA[evm]]></category>
            <dc:creator><![CDATA[Shreemoy Mishra]]></dc:creator>
            <pubDate>Wed, 08 Jun 2022 15:06:02 GMT</pubDate>
            <atom:updated>2022-06-15T15:33:11.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*JQInHs1lLa-QwIRNssFwHA.png" /></figure><p>By Raúl Laprida, Julian Len, Shreemoy Mishra, and Diego Masini</p><p><strong>The need for cheap and fast payments</strong></p><p>Over the past couple of years DeFi protocols have dominated the scene compared to other use cases of public blockchains. In the case of Ethereum, the growth of DeFi has even <em>priced out</em> some other applications. The RSK ecosystem has also experienced its share of growth of DeFi projects. Despite the striking growth, current DeFi protocols — with leveraged trading, automated market maker pools, yield farming and so on — remain quite complex for regular people to use in their daily lives. IOV Labs is targeting the development of simpler financial products including those for cheap and fast P2P payments.</p><p>For a long time, <em>payment channels</em> were thought to offer the best approach for P2P payments. However, despite their technical maturity, projects such as the Lightning Network on Bitcoin or the Raiden network on Ethereum have <a href="https://medium.com/raiden-network/the-state-of-the-raiden-network-9aa4b9a9e2fc">not gained mass</a> adoption. Similarly, on RSK, the Lumino project also struggled with adoption. The challenges are not purely technological. For instance, in <a href="https://medium.com/breez-technology/lightning-is-a-liquidity-network-550896ca27ea">a recent blog post</a>, developers of the Breeze wallet suggest that payment failures in the lightning network frequently arise due to <em>liquidity issues</em>.</p><p>This is not to say that payment channels are a dead end. On the contrary, there is a lot of renewed interest in using them to support <em>stablecoin payments</em>. One prominent example is a new proposal called <a href="https://docs.lightning.engineering/the-lightning-network/taro"><em>Taro</em></a> from Lightning Labs. There is another approach based on the Omni protocol called <a href="https://github.com/omnilaboratory/OmniBOLT-spec">Omni-Bolt</a>. The IOV Labs R&amp;I team is closely following these developments and working to build partnerships. However, these solutions are far from being fully developed.</p><p>So what can be done now for scalable payments on RSK? At present, the only demonstrably cheap, fast, and secure alternative for EVM blockchains is to use <em>rollup technology</em>. ZK rollups, in particular, have gathered a lot of attention. We reached out to Matter Labs to integrate their L2 rollup service, ZKSync (version 1), with RSK.</p><p>However, the timing wasn’t quite right as Matter Labs were preoccupied with the development of version 2 of their system. We look forward to working with Matter Labs and other innovators in this space in the future. Nevertheless, since ZKSync V1 is an open source project with a permissive license — we were able to fork it, understand how it operates, and port the solution as well as some related DApps to work on RSK. To be clear, this was a proof of concept working in <em>local development (regtest)</em> mode. While we did deploy the contracts on RSK testnet, the plans for a full-featured deployment are still work in progress.</p><p><strong>The porting exercise</strong></p><p>ZKSync uses a <em>rollup contract</em> on Ethereum to bridge ERC20 tokens with their L2 blockchain. Once on L2, the tokens can be transferred much faster and cheaper than on L1. Users can even pay for gas using tokens. Security is provided through Proofs of Computational Integrity, often achieved using zero-knowledge cryptography.</p><p>Like most rollup services, ZKSync V1 uses a <em>centralized sequencer</em> to process L2 transactions. This means users have to submit their L2 transactions to a single server through an API. In addition, ZKSync uses <em>on-chain Data Availability </em>— meaning that state changes associated with <em>each</em> L2 transaction are communicated to L1. In case of irrecoverable failure of the rollup system, data availability permits users to reconstruct the L2 state and recover locked assets from the rollup contract on L1.</p><p><em>Zero Knowledge</em> cryptography (based on PLONK proof system) is used for <em>validation proofs</em>. The proofs guarantee the validity of all L2 transactions. Proofs are created off chain (code is open source), but are submitted to the rollup contract on L1. Thus, there is no need to trust any third parties. This is a significant advantage compared to other systems such as <em>opportunistic</em> rollups which rely on economic agents for <em>fraud proofs</em> and game-theoretic incentives. The combination of validation proofs, on-chain data availability, an <em>open source (auditable) codebase</em> and a <em>trustless asset recovery</em> system provides a very high degree of transparency and security.</p><p>The RSK blockchain aspires to offer Dapp developers and projects <em>functional compatibility</em> with EVM — so their applications can be deployed in either Network with minimal effort. Therefore, this exercise in porting ZKSync was also a learning experience to discover pain points. Porting a Dapp from one EVM chain project is not simply about swapping out one blockchain client (Geth) for another (RSKJ) — but it should not be too complicated a process.</p><p>For example, we discovered an inconsistency in the way the RSKJ client handled two JSON RPCs: <em>web3_sha3</em> and <em>eth_sendRawTransaction, which</em> lead to mismatches in transaction IDs (hashes). This in turn resulted in integration test failures — as the backend server (in ZKSync) was unable to validate L2 transactions on L1. We worked with RSK <a href="https://github.com/rsksmart/rskj/pull/1637">core developers</a> to fix the issue, which improved compatibility with Web3. We also modified the corresponding code in the ZKsync server itself to make it more robust on how to compute transaction hashes.</p><p>To understand how ZKSync works, we gathered information from multiple sources including blog posts, developer documentation, user documentation, in-source documentation in the code base, and their Discord server. Sometimes there were inconsistencies across these sources. Such inconsistencies are not surprising given the complexity of the system and the fact that the project has evolved over time. Indeed, many open source software projects (including RSK) suffer from some divergence and inconsistency of information across multiple channels. We reported some of the glaring inconsistencies to ZKSync representatives on Discord.</p><p>Working with the backend server code was an opportunity for us to learn to work with a codebase in Rust — a language we did not have prior experience with. It turned out to be one of many high points of working on this project. For example, we made some other changes to the server, such as adding the ability to use secure API access using HTTPS. By itself, such a change would not be remarkable. However, it turned out that introducing this simple feature revealed some of the challenges (regarding dependencies) when working with a relatively new, but still hugely popular language like Rust. We initially added HTTPS support using a library called <em>rustls.</em> However, after some weeks, the feature broke when we merged our code with newer commits from Matter Lab’s upstream branch.This happened because, in the meantime, the upstream branch had incorporated a different version of the same library — with a different API, and it broke our feature. To avoid working with different versions of the same library, we thought it safer to switch to a different library, one that used <em>openssl</em> and had a more consistent API across versions.</p><p>We ran into some other dependency issues. Sometimes, Matter Labs representatives were able to assist on Discord. In other cases, we found some solutions that we subsequently shared in their community channels. In one case, we reported a breaking change in a library (<em>wasm-pack</em>) to Matter labs and created a tiny PR with a temporary fix, which was subsequently merged. We think these are isolated events, but as always, one needs to be mindful when working with dependencies that are not part of a language’s standard library or those developed by individuals or very small teams.</p><p>Back on the RSKJ side, some of the tests required manual control of block timestamps and for the <em>automine</em> feature to be turned on (in regtest mode). In this setting, the RSKJ node mines blocks only when transactions are sent to it manually (e.g. over RPC). We also initially had to increase the number of transaction account slots in the RSKJ node (using <em>node.conf</em>) from the default 5 to something around 20. This was done to avoid “<em>nonce too high” errors</em> as some test scripts sent too many transactions, in a very short timeframe, from a single account. Later, we modified the tests to wait for some transactions to be mined before sending the rest.</p><p>One of the most vexing issues happened when we were trying to set up CI using github actions. ZKSync uses a dockerized deployment of various components — the backend server, the RSKJ node, postgres server etc. A simple docker networking issue prevented the RSKJ client from being visible to the backend server. It turned out that the <em>name</em> of the RSKJ docker service (from the main <em>docker-compose</em> file) needs to be included in the list of RPC providers <em>hosts</em> in the RSK <a href="https://github.com/rsksmart/ri-aggregation/blob/383de6c1fe331ad5827a53666fd02595871a5f76/docker/rskj/node.conf#L56"><em>node.conf</em></a> file as well.</p><p>While simple, such details of configuration settings or differences with the Geth ecosystem can affect the portability of other projects. For instance, in the course of the project, some team members migrated to M1 Macs (arm64). But there were no RSKJ docker images or ppa for M1 Macs. So we created a<a href="https://github.com/rsksmart/ri-aggregation/tree/rsk_merge_master_Dec2021/docker/rskj#readme"> dockerfile</a> for our use and to share with the RSK community.</p><p>Depending on the application being ported, other changes may also be needed in RSKJ or the RSK ecosystem. For instance, ZK rollups rely on using calldata for on-chain data availability. In Ethereum, the cost of calldata was reduced explicitly with rollups in mind. The RSK community may also need to consider such a change in the future. A final example of ecosystem changes is the availability of multiple price oracles to feed token price data into the service — especially since fees are payable in tokens.</p><p><strong>Porting related DApps<br></strong>Once the porting of the backend rollup service (to RSK) was complete, it was a natural next step to port some existing applications to demonstrate utility and functionality.</p><p><strong>Wallet dApp</strong></p><p>The wallet dApp can be used to transfer assets on layer 2. In zkSync version 1 this L2 wallet needs to be connected to an Ethereum-compatible wallet such as Metamask. In zkSync v2 users can use an Ethereum-compatible wallet directly.</p><p><strong>Checkout dApp</strong></p><p>The checkout app allows a user to <em>batch</em> several payment transactions (up to 20, with different recipients) into a single batch transaction. A common scenario is a checkout page, where <em>each transaction</em> represents an item being purchased, potentially from a different vendor.</p><p><strong>Explorer App</strong></p><p>The explorer app is based on an old L2 explorer created by Matter Labs. The current version of zkSync’s explorer app is not public yet but Matter Labs assured us the source code will be published soon. As a workaround we ported an old, but fully-functional, version of the L2 explorer app.</p><p><strong>Hardware Experiments</strong></p><p>ZKSync is a very complex project, one that has been under development for a long time. It is not surprising, that in many situations, we found inconsistent and conflicting documentation across various channels: Matter Labs’ discord channels, blog posts, web site, official documentation, github repo. Naturally, there are such inconsistencies in most blockchain projects including RSK! A great thing about Matter Labs is they kept the core code open source — which made this whole porting exercise even possible. We are grateful for that.</p><p>However, there was one area in which we struggled to get even some high level input from them. Generating Zero Knowledge proofs requires high-end hardware. Despite numerous requests, the Matter Labs team were not comfortable divulging details of the hardware infrastructure they use to run the prover(s). So we had to experiment and iterate, until we were able to pass all the resource-heavy tests. After all, without that knowledge, it is impossible to estimate potential costs of running a rollup service — which will ultimately be paid by users.</p><p>In this regard, we are grateful to our Devops Team for helping us by patiently deploying and upgrading cloud infrastructure resources per our evolving needs. We used increasingly larger AWS EC2 servers to generate proofs to successfully pass the integration tests and ZK circuit tests. We determined that the minimum hardware requirements involve 128GB of RAM and about 32 CPUs (e.g. AWS EC2 <em>m5a.8Xlarge</em> instance or similar). It is possible to run multiple prover threads, to generate proofs in parallel. In a production scenario, depending on the load, multiple servers can be deployed as needed — but each should meet the minimum specification.</p><p><strong>Operational Costs</strong></p><p>Matter Labs does not pass the cost of ZK proof generation to end users. However, users <em>collectively</em> must pay fees to cover all other operational costs. These costs include transaction fees (gas) for relaying information to L1 about state changes, token withdrawals, block commitments, block validation (SNARK proof verification) etc. We collected transaction data from ZKSync’s explorer to perform simple statistical analysis of the costs of the rollup service. We were then able to correlate these costs with the relevant part of the backend server code which handles fee estimation — this will be useful when deploying the system (e.g. for recalibrating fee components).</p><p><strong>Anticipated benefits of adopting this solution</strong></p><p>For simplicity, assume 1BTC is about 30K US Dollars. We estimate that deploying ZKSync V1.x on RSK can <em>increase transaction processing capacity</em> by 80X (from 6 to 470 token transfers per second) and <em>lower the cost</em> of token transfers by 25X (from USD 0.085 to USD 0.0033 per transfer). The cost estimate is a combination of on-chain cost of 1500 <em>gas</em> per transfer (USD 0.003 at current gas price) and off-chain <em>infrastructure</em> cost of around USD 0.0003 per transfer. The average infrastructure cost is calculated (conservatively) assuming that the number of rollup transactions is at least as high as the current capacity for <em>regular</em> token transfers on layer 1. Future RSKIPs to lower the cost of calldata or ZK verification can improve upon both capacity and cost estimates.</p><p><strong>Wrapup</strong></p><p>The <a href="https://ethereum-magicians.org/t/a-rollup-centric-ethereum-roadmap/4698">rollup-centric</a> future envisioned by Vitalik Buterin for Ethereum may apply to all L1s more broadly. There are a lot of EVM compatible chains in the ecosystem now. Some non-EVM chains such as Near Protocol are integrating L2 systems that are EVM compatible. There are even suggestions for building <a href="https://tr3y.io/articles/crypto/bitcoin-zk-rollups.html">ZK rollups on top of Bitcoin</a>. RSK is EVM compatible by design, so it comes as no surprise that this porting exercise ultimately did not require any critical code changes. Most of our time was spent developing context and trying to understand how ZKSync works. Apart from a few speed bumps mentioned earlier, the process was largely uncomplicated, even without direct support from Matter Labs. However, more complex tasks lie ahead as we assist other teams to deploy the system into production starting with testnet.</p><p><strong>Acknowledgments: </strong>Many thanks to <a href="https://medium.com/@SDLerner">Sergio Lerner</a>, Patricio Gallardo, Gaby Genovese and other colleagues for suggestions and assistance in preparing this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c9fe0b22e41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rootstock-tech-blog/porting-a-zk-rollup-payments-solution-from-ethereum-to-rsk-1c9fe0b22e41">Porting a ZK Rollup Payments Solution from Ethereum to RSK</a> was originally published in <a href="https://medium.com/rootstock-tech-blog">RootstockLabs: Research &amp; Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Impermanent loss” is inevitable in AMM DeFi protocols — and that’s totally fine]]></title>
            <link>https://medium.com/rootstock-tech-blog/impermanent-loss-is-inevitable-in-amm-defi-protocols-and-thats-totally-fine-c7f07ea001d6?source=rss-780d0c2fb896------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7f07ea001d6</guid>
            <category><![CDATA[automated-market-maker]]></category>
            <category><![CDATA[decentralized-exchange]]></category>
            <category><![CDATA[rsksmart]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Shreemoy Mishra]]></dc:creator>
            <pubDate>Thu, 17 Feb 2022 17:44:07 GMT</pubDate>
            <atom:updated>2022-02-17T17:44:07.466Z</atom:updated>
            <content:encoded><![CDATA[<h3>“Impermanent loss” is inevitable in AMM DeFi protocols — and that’s totally fine</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NWdiDYwA4DGoeL3wW5IzRw.jpeg" /></figure><p>Impermanent loss is the <em>opportunity cost of providing liquidity</em> to constant product Automated Market Making (AMM) DeFi protocols. It is measured as the difference between the value of a Liquidity Provider’s (LP) tokens at the <em>time of withdrawal</em> from the pool, versus the hypothetical situation where the LP had not made the investment at all.</p><p>As long as an LP remains invested in a constant product decentralized exchange (DEX) pool like Uniswap, the loss is merely an accounting issue. The loss becomes larger as the<em> </em><strong><em>ratio of token prices</em></strong><em> </em><strong><em>outside</em></strong> the pool drifts further away from the point when the LP entered the pool. It is ultimately realized — and becomes a real or “permanent” loss— when an LP withdraws their tokens from the pool.</p><p>This post explains why providing liquidity to constant product AMM DeFi protocols <em>necessarily involves</em> some impermanent loss. Before proceeding, bear in mind that the loss is merely the cost of doing business — as DEX protocols compensate LPs with income from <em>trading</em> <em>fees</em> and <em>protocol rewards</em>.</p><p>The idea behind impermanent loss is simple. Suppose the ratio of token prices <em>outside the pool</em> changes (in any direction). The divergence in relative prices within and outside the AMM pool presents <em>traders</em> with the opportunity to exchange tokens (with the DEX) on terms that are <em>more favorable</em> than the wider market. Naturally, the direction of the arbitrage trade depends on the direction in which relative prices have changed. As traders take advantage of the price difference, the ratio of token prices within the pool approaches that as the market’s. However, in the course of these exchanges, the pool is left with a modified balance of tokens. If an LP were to withdraw their share of tokens from the pool, their share will be worth less than the LP’s original investment (when computed using <em>current</em> prices). This is illustrated in an intuitive fashion by online calculators such as <a href="https://dailydefi.org/tools/impermanent-loss-calculator/">this one</a>.</p><p>While it is easy to grasp the intuition behind the drop in value, I was not able to view it as a general result in my mind. Thinking about a simple proof helped me realize my mistake. The error was that I only thought about the curve in an AMM pool as being determined by the product of the number of tokens initially deposited in the pool — something like <em>xy=k</em></p><p>While the above is true, it glosses over the fact that the constant depends on <em>asset prices</em> too, not just quantities. Indeed, it is this dependence on prices which provides a “liquidity interpretation” to the constant in constant product protocols.</p><p>An AMM relationship is not an arbitrary product of some initial amount “<em>x0</em>” of <em>token X</em> and some initial “<em>y0</em>” of <em>token Y</em>. At the time of creating or entering a pool, these amounts must be worth the <em>same value</em> (measured in dollars or any coin/token). Using <em>px0</em> and <em>py0</em> to denote the <em>initial token prices</em>, the quantities must satisfy the relation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*oAJPVpIj9dIQeJVAdtp2Ug.png" /></figure><p>where L denotes the liquidity provided (e.g. in USD) in each token for a total investment of 2L in the pool.</p><p>For simplicity, assume there are no other liquidity providers. Then, a constant product market AMM curve is something like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*pLUeu9IHoNsA9_gU44IobQ.png" /></figure><p>The <em>relative price</em> or the <em>exchange rate</em> of token <em>Y</em> (for 1 unit of token <em>X</em>) at any point along the curve is given by the slope of a <em>tangent</em> at that point. This is just the absolute value of the derivative of the curve</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*RghlOoPfg5l5igA2T57Rzw.png" /></figure><p>The initial ratio of prices must satisfy the above for the initial quantities <em>x=x0</em> and <em>y=y0</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*vyQUYK96E4Op5QbWabHNuQ.png" /></figure><h3>Change in asset prices</h3><p>Now suppose the prices change to <em>px1 </em>and <em>py1</em>. Unless the two tokens are highly correlated, the new ratio will generally be different from before. This will move us to a new point on the curve that has the slope corresponding to the new ratio of prices. The actual shift will be driven by traders who view any difference in the ratio of prices within a pool and outside as an <em>arbitrage opportunity</em>.</p><p>Being on the <strong>same invariant</strong> (curve) as before implies the new point (x1,y1) satisfies</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*W0PyXQhoyt9GhmNENP7Izg.png" /></figure><p>The slope of the tangent then provides the new <strong>price condition</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*5qtMKMA8l4RavFetbSNwXw.png" /></figure><p>Solving for x1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*vhy-I66EoBIrv1nL-dycgA.png" /></figure><p>and for y1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*-EHvV-wnRv8u9y8fVN-waA.png" /></figure><p>The total value of assets in the pool is then given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*NJ0tm8qM04wa-97r-MNNcg.png" /></figure><h3>Opportunity cost of providing liquidity</h3><p>The hypothetical value of assets <strong>outside the pool</strong> under the new prices — i.e. imagine the LP <em>never invested</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*0R2qgRFGaAYTaTHdsNGtLw.png" /></figure><p>Now we can see why the <em>opportunity cost is always positive</em>. We’ll assume (incorrectly) that providing liquidity is always profitable and then arrive at a contradiction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*EdzDjWR8LvW37noQTRWDbQ.png" /></figure><p>Naturally, the loss only arises if there is a change in the <strong>ratio of prices</strong> at the time of withdrawal. If the price of both tokens increases or decreases by the same factor, then there is no loss.</p><p>Thanks to Julian Kusnetzoff, Julian Len, Nicolás Vescovo, Diego Masini and members of the IOV Labs R&amp;I DeFi group for discussions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7f07ea001d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rootstock-tech-blog/impermanent-loss-is-inevitable-in-amm-defi-protocols-and-thats-totally-fine-c7f07ea001d6">“Impermanent loss” is inevitable in AMM DeFi protocols — and that’s totally fine</a> was originally published in <a href="https://medium.com/rootstock-tech-blog">RootstockLabs: Research &amp; Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Escrows for Decentralized Marketplaces]]></title>
            <link>https://medium.com/rootstock-tech-blog/escrows-for-decentralized-marketplaces-2229731669ab?source=rss-780d0c2fb896------2</link>
            <guid isPermaLink="false">https://medium.com/p/2229731669ab</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[descentralized]]></category>
            <category><![CDATA[marketplaces]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Shreemoy Mishra]]></dc:creator>
            <pubDate>Thu, 05 Aug 2021 17:15:00 GMT</pubDate>
            <atom:updated>2021-08-06T17:49:32.164Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69tos7p505tyqMHbuFHmZA.jpeg" /><figcaption>ar</figcaption></figure><p>When paying for an online purchase with a credit card, I feel reassured that, if necessary, the charges can be disputed. Payments made using cryptocurrencies, once buried a few blocks deep, cannot be reversed. This “irreversibility” is intentional and crucial in keeping cryptocurrencies secure and trustless.</p><p><em>“Transactions that are computationally impractical to reverse would protect sellers from fraud, and routine escrow mechanisms could easily be implemented to protect buyers.”<br>- </em>Satoshi Nakamoto, 2nd paragraph of the Bitcoin paper [1]</p><p>The above excerpt from the Bitcoin paper states the role that <em>escrows</em> can play in <em>decentralized marketplaces</em>. The role is stated very plainly, but it covers nearly all use cases.</p><p>Escrow services can help resolve disputes involving some <em>off-chain</em>, “<em>real world”</em> fact — something decentralized protocols, by themselves, can neither verify nor refute. However, escrow providers <em>do not</em> have to serve as arbitrators. Their<em> primary service is to effectively reverse transactions.</em> The arbitration can be performed by yet another party — but it should be handled as part of the system.</p><p>Using a buyer/seller narrative, the typical flow is something like this. A buyer “locks in” enough crypto-assets (coins, tokens) in an<em> escrow contract </em>to cover the value of a purchase. When the terms of exchange are met by both sides, then the asset is transferred to the seller <em>without any assistance</em> from the escrow provider. This is different from conventional escrows where the service provider must actively transfer the asset. Furthermore, decentralized escrows can be <em>non-custodial</em>, so the service provider cannot steal any assets. If there is a dispute which cannot be resolved (mutually or with the assistance of an arbitrator), then the escrow provider releases the lock, so the buyer can reclaim their asset — which reverses their initial transfer.</p><p>What is <em>unchanged</em> from conventional escrows is that the service provider still serves as a <strong><em>trusted third party</em></strong>. The term “escrow” is used quite liberally — even <em>while stating that the “escrow” does not actually solve the trust problem</em> [2]. Some crypto auction platforms say their contracts hold bids (in ETH) in escrow. But this is how auction smart contracts work in general. Time-lock escrows are another example, they do not really need trusted third parties.</p><p>In my mind, there is no such thing as a fully trustless escrow. And for this reason, escrows cannot be fully automated — irrespective of the complexity of the smart contracts involved. If a service can be made fully trustless, then it is no longer an escrow, it is just a <em>bilateral exchange</em> <em>protocol</em>. DApp developers should state their trust requirements clearly and be mindful to distinguish arbitration (verify facts) from escrow (release disputed assets to one party).</p><h3>A standards-based architecture</h3><p>Relative to traditional escrows, locking and releasing crypto-assets (e.g. coins, tokens) using a non-custodial P2WSH [3] or a smart contract is simple, cheap (depending on the blockchain) and fast. For crypto escrows, the <strong>design choices</strong> are really about handling disputes, integration with other components and overall user experience for developers and end users.</p><p>For those looking to build an escrow system as part of their DApp, I recommend adopting ideas from a standards framework proposed by <a href="https://kleros.io/"><em>Kleros.io</em></a>. Kleros provides decentralized arbitration services through a system of courts. Courts are organized depending on the domain expertise needed to rule on disputes. Users seeking arbitration must submit their disputes to appropriate courts. Cases are decided based on a plurality voting system where jurors are picked randomly from a set of volunteers. Jurors indicate their willingness to serve by staking Kleros’ token (PNK). Jurors earn rewards in Ether for coherent decisions and lose part of their stake for incoherent rulings. Their escrow is just one part of a wider, decentralized arbitration system.</p><p>At a high level, Kleros’ approach is built on two proposed standards. Details of these proposals and discussion can be found at their respective Ethereum EIP Github issues [4a, 4b]</p><ol><li><strong>ERC 792:</strong> This standard proposes two smart contract interfaces</li></ol><p>* <strong>Arbitrator contracts interface:</strong> contracts through which registered EOA arbitrator(s) can serve rulings on disputes.</p><p>* <strong>Arbitrable contracts interface:</strong> contracts can use this interface to designate a specific arbitrator contract (above) to provide arbitration rulings.</p><p><strong>2. ERC 1497:</strong> <strong>Evidence interface</strong> to <em>structure</em> and <em>submit</em> evidence when raising disputes</p><p>These standards are intended for general dispute resolution contracts, <em>not </em>escrows specifically.</p><h3>Developer Resources</h3><p>Kleros’ developer documentation [5] provides an overview of the system and a live demonstration DApp. The demo happens to be a very rudimentary escrow for coins. More advanced and practical implementations can be found in other repositories [6, 7], which, at present, are not included in their developer documentation.</p><p>The dev docs are intended to help users write “arbitrable” contracts which can then be used to resolve disputes using Kleros’ courts. Naturally, the emphasis is on illustrating how their system works and encourage people to use the service. I suspect that many developers may wish to keep their DApps simple by managing the dispute resolution process themselves or with known arbitrators.</p><p>Being Ethereum based, it is straightforward for DApp developers to deploy elements of the approach on Ethereum-compatible networks like RSK. The stack is fairly standard <em>npm, web3</em>, <em>Truffle</em>. I forked one of their repos with <strong>token escrows</strong> and made some small changes so it works with <em>HardHat</em> (instead of <em>Buidler</em>) for development and testing [8].</p><h3>Escrows for Non Fungible Tokens (NFTs)</h3><p>Recently, there has been extraordinary interest in NFTs. This has been driven by sales of NFTs worth thousands or millions of dollars granting “ownership” of otherwise freely available digital goods such as art, YouTube videos, even tweets [9]. Thus, it is natural to wonder about the relevance of escrows for NFTs.</p><p>The exchange of <em>on-chain assets</em> can be handled entirely in a trustless manner through smart contracts. Thus, if NFTs are bought and sold using cryptocurrencies or tokens, then there is <em>no absolute need for escrows</em> at all. For instance, consider <a href="http://www.opensea.io/">www.opensea.io</a>, one of the largest marketplaces for NFTs. Searching for the word “<em>escrow</em>” in their user support documentation leads to the following</p><ul><li><em>“OpenSea is decentralized, so we never escrow or hold your items.”</em></li><li><em>“OpenSea does not offer payment escrow through the main website or otherwise.”</em></li></ul><p>Of course, there may be some situations where escrows make sense for NFTs:</p><ul><li>An NFT marketplace with payments made using fiat</li><li>Fiat loans secured by “demonstrably valuable” NFTs</li><li>C<em>ustomization services</em> that involve adding features to in-game NFTs where some data is not stored on chain and needs manual verification</li></ul><p>However, even in such cases, NFT-escrows will <strong>not require</strong> any special handling. The basic approach described previously should suffice.</p><h3>Other Services and Design Options</h3><p>I am a fan of following standards-based approaches for the long term. But building consensus around standards can be very challenging. Despite their efforts, Kleros’ proposed standards (ERC 792, ERC 1497) have not been merged into the main ERC repository.</p><p>On the other hand, the widespread use of <em>ad-hoc designs</em> by various teams reminds us that escrow solutions are often <em>just one component</em> of a more complex service. In this context, Australia based <a href="https://localcryptos.com/">Localcryptos.com</a> offers a fantastic example for DApp developers. The service makes money from a P2P cryptocurrency marketplace. However, in order to do so, they offer crypto-escrows, a dispute resolution service, encrypted messaging, meta-transactions to cover gas costs, even a dynamic reputation system.</p><p>A new system is being developed by <a href="https://www.smartlink.so/">Smartlink.so</a>. This looked very promising initially (whitepaper etc). But on closer inspection, the development effort is not very mature yet. Their stated focus is to develop escrow services for marketplaces. Therefore, it would be prudent for developers and product designers to keep an eye on their progress. Smartlink will be deployed on Tezos network and their first solution is stated for Q4 of 2021.</p><p><strong>Acknowledgements:</strong> I thank Artem Brazhnikov, Raúl Laprida, and Diego Masini for helpful suggestions and discussions.</p><h3>References</h3><ol><li><a href="https://bitcoin.org/en/bitcoin-paper">https://bitcoin.org/en/bitcoin-paper</a></li><li><a href="https://docs.soliditylang.org/en/v0.8.6/solidity-by-example.html#safe-remote-purchase">https://docs.soliditylang.org/en/v0.8.6/solidity-by-example.html#safe-remote-purchase</a></li><li><a href="https://blog.localcryptos.com/how-bitcoin-escrow-works/">https://blog.localcryptos.com/how-bitcoin-escrow-works/</a></li><li>[a] <a href="https://github.com/ethereum/EIPs/issues/792">https://github.com/ethereum/EIPs/issues/792</a><br>[b] <a href="https://github.com/ethereum/EIPs/issues/1497">https://github.com/ethereum/EIPs/issues/1497</a></li><li><a href="https://developer.kleros.io/en/latest/index.html">https://developer.kleros.io/en/latest/index.html</a></li><li><a href="https://github.com/kleros/escrow-contracts/blob/master/contracts/0.7.x/MultipleArbitrableTokenTransactionWithAppeals.sol">https://github.com/kleros/escrow-contracts</a></li><li><a href="https://github.com/kleros/erc-792">https://github.com/kleros/erc-792</a></li><li><a href="https://github.com/optimalbrew/escrow-contracts">https://github.com/optimalbrew/escrow-contracts/</a></li><li><a href="https://www.npr.org/2021/03/05/974089381/whats-an-nft-and-why-are-people-paying-millions-to-buy-them">https://www.npr.org/2021/03/05/974089381/whats-an-nft-and-why-are-people-paying-millions-to-buy-them</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2229731669ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rootstock-tech-blog/escrows-for-decentralized-marketplaces-2229731669ab">Escrows for Decentralized Marketplaces</a> was originally published in <a href="https://medium.com/rootstock-tech-blog">RootstockLabs: Research &amp; Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Primer on Blockchain Storage Economics]]></title>
            <link>https://medium.com/rootstock-tech-blog/a-primer-on-blockchain-storage-economics-b65b242c6ec0?source=rss-780d0c2fb896------2</link>
            <guid isPermaLink="false">https://medium.com/p/b65b242c6ec0</guid>
            <category><![CDATA[rsk]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[storage]]></category>
            <dc:creator><![CDATA[Shreemoy Mishra]]></dc:creator>
            <pubDate>Tue, 09 Feb 2021 23:32:43 GMT</pubDate>
            <atom:updated>2021-02-14T19:32:13.676Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*cwk6mCAt-K_3lQyaAi8UUg.jpeg" /></figure><p>Most web and mobile applications rely on cloud-storage solutions. Storage costs charged to developers and enterprises are determined using <a href="https://aws.amazon.com/s3/pricing/">tiered-pricing</a> schemes that depend on several factors <em>e.g.</em> amount of data stored, duration, bandwidth, latency, security, replication and distributed-designs etc. There are also contractual obligations and service level guarantees.</p><p>Things are quite different in <em>trustless,</em> <em>peer to peer</em>, <em>blockchain networks</em> like <a href="https://bitcoin.org/">Bitcoin</a>, <a href="https://ethereum.org/en/">Ethereum</a> and <a href="https://www.rsk.co/">RSK</a>. In this post we explore some basic engineering-economics of storing data in blockchains.</p><h3>Storing Blocks vs Storing State</h3><p>When thinking about the costs of data storage in Ethereum-like blockchains, we distinguish between historical <em>transaction data</em> (stored in <em>blocks</em>) from <em>State data</em>. The “state” — at any point in time — refers to a “snapshot” of account <em>balances</em>, <em>smart contract</em> <em>code</em> that power <em>decentralized applications</em>, and data stored on-chain for use by these applications. Usually, state just refers to the <em>current</em> one. There is <em>no common reference clock</em> in blockchains. So, when referring to some <em>previous</em> state, it is typical to specify a <em>block height</em> or <em>number</em> as reference.</p><p>Using decentralized applications involves <strong>interacting with</strong> smart contracts. By interaction, we mean</p><ul><li>a Transaction sent from a user’s account …</li><li>usually through their cryptographic <em>wallet software in a browser or mobile app…</em></li><li>to a smart contract — identified by the <em>contract’s address</em> on the blockchain…</li><li>with some <em>data </em>for the contract to process.</li></ul><p>Most transactions involve reading and modifying some state data, and these changes must be <em>persistent</em> across interactions. Contracts and any contract-specific data that are no longer needed can be removed from state. There are even financial incentives to do so and reduce state size.</p><p>At any point in time, the blockchain’s state is the net <em>outcome</em> of all historical transactions until that point. When a new blockchain node starts for the first time, it re-creates the <em>current state</em> of the chain by downloading blocks from (older) peers and executing (i.e. <em>replaying</em> and <em>verifying</em>) all the transactions in every block starting from block 0 (called the “Genesis” block). This initial sync can takes hours — or even days — depending on bandwidth and processing power. A node that has been offline for some time has to do something similar, but it can start from wherever it left off — i.e. from the snapshot of the state when it was last online.</p><p>Whether starting from scratch or simply catching up, the process of re-executing all prior blocks <em>is sequential</em> — the very nature of blockchains like Bitcoin and RSK prevents parallel execution of transactions. Trying to process transactions in a parallel fashion can fail, or much worse — lead to inconsistent state changes. After all, the whole point of blockchains is for non-trusting peers to <em>reach consensus on a single historical order of transactions</em>.</p><p>Block and transaction data are typically encoded in a manner specified by the chain’s protocol. These are then stored on disk using key-value databases. The state, however, is stored using tree-like abstract data structures called <a href="https://en.wikipedia.org/wiki/Trie"><strong>tries</strong></a>. Ethereum uses variants with 16 branches (<em>hexary</em> tries) while RSK uses a <em>binary</em> trie. See <a href="https://medium.com/iovlabs-innovation-stories/similarities-and-differences-between-rsk-and-ethereum-e480655eff37">this post</a> for a rich comparison of these approaches. State data is stored in <em>trie leaf nodes</em>. Leaf nodes used to store data that are specific to smart contracts are called <em>Storage Cells</em>. Depending on the implementation (e.g <a href="https://github.com/ethereum/go-ethereum">Geth</a>, <a href="https://github.com/ledgerwatch/turbo-geth">Turbo-Geth</a>, <a href="https://github.com/rsksmart/rskj">RSKJ</a>), the tries may be stored in encoded form or expanded form. But ultimately, as with transaction data, they are backed up by key-value databases.</p><p>The cumulative size of blockchain <em>history</em> (blocks, transactions, transaction receipts) in Ethereum is over a Terabyte. It simply won’t fit on my laptop’s 512GB SSD disk — I need an external drive. Ethereum’s <em>current</em> <em>state</em> is smaller, less than 100 gigabytes (GB). While the state can fit on my computer’s internal disk, it is far too big to fit on RAM (which is about 8GB). These storage limitations have a large impact on node and network performance. The RSK blockchain is younger and smaller than Ethereum. But even then, the storage requirements are not trivial.</p><h3>Implicit and Explicit Costs of Storage</h3><p>In Ethereum and RSK, blockchain storage costs — as charged to <em>users</em> via <em>transaction fees</em> — are almost entirely related to storing or modifying state, not for storing historical transaction data. Of course, those <em>operating</em> blockchain nodes have to cover the costs of storing both state and storing the (much larger) history.</p><p>We cannot process transactions without state data. To execute even a simple transfer of coins from Marina’s account to Celia’s we need to know Marina’s <em>current balance</em>. The record of her past transactions does not play any direct role. In Ethereum like settings, someone operating a blockchain client (or node) will try to keep as much of the blockchain’s state as practical in RAM. This is <em>unlike Bitcoin</em>, where new transactions are constructed <em>using previous transactions as input</em>! There are no “accounts” or “balances” in Bitcoin. In fact, some people say <em>there is no state</em> in Bitcoin — only transactions with “leftover money” i.e. <em>Unspent Transaction Outputs (UTXOs</em>). Those familiar with <a href="https://bitcoin.org/en/bitcoin-paper">Satoshi’s paper</a> will recall that the only way to avoid Bitcoin’s <em>fundamental security problem — </em>the <em>double spending attack —</em> is to <em>be aware of all prior transactions</em>. This holds for all blockchains. For maximum security, anyone running a full node must maintain the entire set of historical transactions.</p><p>As the number of users, accounts, and contracts grows, it becomes impossible to store all of the state data on RAM. Imagine that the size of the state is currently at 50GB. And suppose I dedicate 5GB of my computer’s RAM to storing state — enough to store only 10% of it. Then, 90% of the time, the state data needed to execute some transaction <em>will not be</em> in RAM. We need to go look for it and retrieve it from disk. This associated <strong>IO latency</strong> slows things down, and it gets worse as state size <em>continues to increase</em>. IO latency can also be a target for <em>denial of service (DoS) </em><a href="https://www.coindesk.com/so-ethereums-blockchain-is-still-under-attack"><em>attacks</em></a><em> </em>by malicious actors. The fact that <em>reads</em> are blocking and transactions processing <em>cannot be parallelized</em> (not at present anyway) also make things worse.</p><p>IO latency is an <em>implicit</em> <em>cost of storing blockchain data</em> — developers can use tools to keep track of such performance costs. Some Ethereum developers try and restrict their smart contracts from accessing too much state data. They are willing to trade off higher fees (for additional computations) for lower IO latency. Most developers, however, are much more familiar with the <strong><em>explicit</em> <em>costs</em></strong> of storing data. As mentioned earlier, these costs are primarily driven by state data — not the storage used to store previous transactions.</p><p>Smart contracts are executed in the environment of the Ethereum Virtual Machine (EVM). Individual instructions — that form the basis of the code — are called EVM opcodes. Each EVM opcode has an associated computational cost- measured in a unit called gas . The total cost of all the operations required by a transaction determines that <strong>transaction’s fees</strong>. Miners (or block producers) collect fees as compensation. When broadcasting their (cryptographically-signed) transactions to the network, users (i.e. <em>transaction senders)</em> must specify how much they are willing to pay in fees. This is called a transaction’s <em>gaslimit</em>. After a transaction is executed, any <em>leftover</em> gas is refunded to the sender.</p><p>Saving or modifying data in a smart contract’s storage nodes (called <em>Storage Cells</em>) utilizes an EVM opcode called SSTORE. Each storage cell can hold 32 bytes of data. The cost of an SSTORE operation depends on <em>how it is used: </em>to create a new cell, to reset a value, or to clear data.</p><p>When used to create a new storage cell the SSTORE opcode costs 20,000 gas. Using the same SSTORE opcode to delete a cell (changing the value from non-zero to zero) results in a <em>refund</em> of 15,000 gas. <em>Updating</em> some previously stored (non-zero) value to a non-zero value in a storage cell costs 5000 gas.</p><p>These are some costs of <em>writing</em> data to blockchain state — what about <em>reading?</em> The<em> </em>SLOAD opcode is used to read data from a contract’s storage cell, and it costs 200 gas per read. Reading an <em>account’s balance</em> (using BALANCE) costs 400 gas. These values are for the RSK blockchain.</p><p>Of course, these details of various opcodes and gas costs remain hidden from regular users — they only need to be aware that transaction fees increase with complexity — richer interactions cost more.</p><p>The gas costs were originally calibrated by Ethereum developers to the execution time (e.g. in nanoseconds) of different operations. These are <strong><em>engineering costs</em></strong> or computational resource costs. As blockchain software and hardware evolve over time, these engineering costs <em>drift away</em> from the initial benchmarks. Therefore, these references ought to be <em>re-calibrated</em> from time to time. One example is a recently adopted proposal in Ethereum, <a href="https://eips.ethereum.org/EIPS/eip-1884">EIP-1884</a>, which altered some of these engineering costs. For instance, in Ethereum, an SLOAD now costs 800 gas (up from 200), while checking the balance now costs 700 gas (up from 400).</p><p>The path from engineering costs to actual economic and business costs goes through <strong>“fee-market” economics</strong>. The first component is gasprice, which links each unit of gas to the native cryptocurrency like Ether or BTC (in RSK). The second factor is more obvious — the <strong><em>exchange rate</em></strong> between the native coin and a fiat currency like the dollar.</p><p>The fact that the exchange rate, such as the US dollar to Ethereum or Bitcoin, <em>changes over time</em> comes as no surprise. However, people are sometimes surprised by the <em>volatility in gas price</em>.</p><p>The reason gas prices change with time is because there is <em>limited space in blocks</em> for transactions. Limits are needed to ensure blocks are created at regular intervals without imposing too much computational burden on nodes. Instead of directly limiting the number of transactions, the block limit is expressed in terms of the total <em>transaction fees</em> (in gas) that can be collected in a block. Currently, this is around 12.5 <em>million gas</em> in Ethereum.</p><p>The <em>key</em> thing though is that <strong>users</strong> (i.e. transaction senders) <em>set their own offer </em>for gas price — and block producers (miners) prioritize transactions that offer them <em>more money for the same computational cost</em>.</p><p>This “market competition” between users to have their transactions included in a block (before others’) makes <strong><em>gas price determination</em></strong> somewhat like an <strong>auction for limited blockspace</strong>. There is a (highly debated) <a href="https://eips.ethereum.org/EIPS/eip-1559">proposal </a>to alter the way gas prices evolve in Ethereum. But that is another topic.</p><h3>Gaming the Market: Gas Arbitrage</h3><p><em>Introducing economic incentives</em> into any system with limited resources can lead to <em>undesirable side effects</em> and <em>externalities</em>. One example is the interaction between “fixed” engineering costs (in gas) and the “variable” economic ones: gas price and exchange rates.</p><p>Two EVM opcodes — SSTORE and SELF_DESTRUCT (delete a previously deployed contract) — offer <strong>gas</strong> <strong>refunds for removing</strong> unwanted information from blockchain state.<strong> </strong>These refunds serve as <em>gas subsidies </em>and are intended to encourage developers to reduce state size. The refunds are <strong>not</strong> actually paid out in coin! Rather, they are more like <em>coupons</em> and can only be used to<em> partially offset</em> transaction fees, and are applied at the very end of a transaction’s execution.</p><p>However, some users take advantage of this incentive scheme to implement a sort of “<em>gas bank</em>” (e.g. see <a href="https://gastoken.io/">gastoken</a>). They <em>strategically</em> store data on chain when gasprice is <em>cheap</em>, and then claim refunds for deleting that data (stored earlier) when gasprice is <em>very high</em>. This behavior is called <strong>gas arbitrage</strong> and it is frowned upon because it contributes to storage bloat. In Ethereum, rampant use of such patterns have lead to <a href="https://twitter.com/peter_szilagyi/status/1359481892412792836">proposals</a> to remove refunds entirely.</p><h3>Accounting for Storage Costs</h3><p>Anyone running a full blockchain node has to cover storage costs — including bandwidth, storage drives, and IO access. Transaction <em>senders</em> pay for storage costs as part of transaction fees. At the other end, blockchain <em>miners</em> collect the transaction fees associated with a block. In RSK transaction fees are their <em>only</em> source of income. In Ethereum, miners also earn a block <em>subsidy</em>. Lately, even in Ethereum, transaction fees have become a significant part of revenue.</p><p>What about <em>non-mining</em> full nodes? They do not receive any transaction fees.</p><p>Professional node operators — such as <em>crypto</em> <em>exchanges</em>, <em>merchants</em>, <em>oracles</em> and other service providers — operate nodes with massive amounts of RAM and disk storage. Some of them even provide <em>archiving</em> services by storing multiple snapshots of blockchain state at various points in time. This allows them to <em>serve complex queries</em> about an account or contract’s historical balance or transactions. Being service providers, they have revenue streams to cover their large operating costs.</p><p><em>Individuals </em>running full nodes do not receive <em>any</em> compensation — they do so perhaps driven by altruism or security — a wallet connected to a full node offers maximum security. Reducing storage costs offers the highest benefit to individual peers and can encourage more users to run full nodes.</p><h3>Current State of Affairs in Ethereum</h3><p>Early proponents of the <a href="https://www.coindesk.com/what-is-defi">DeFi</a> movement had imagined that these innovations would enable ridiculously cheap value transfers and financial services for “the masses”. However, at present, even simple transfers of the native coin (not tokens) cost about $8 in Ethereum. This is because, while the engineering costs of executing transactions have not changed much, the economics has changed dramatically.</p><p>With ETH at close to $1800 and gasPrice around <a href="https://ethgasstation.info/">200 gwei</a> (a billionth of an ETH) — eachSSTORE operation to store additional data costs about $8. That’s $8 <em>to store 32 bytes</em>! Modifying an existing value (using the same opcode) is 4 times cheaper. $2 to modify 32 bytes of data is hardly something to cheer about. An ERC20 token transfer involves a balance check (400 gas), two balance updates (5000 gas each), the basic transaction fee (21000 gas), and additional fees for interacting with the token’s smart contract. In terms of gas, these costs add up to about 37,000 gas —around $13 at present— for a simple token transfer!</p><h3>Current State in RSK</h3><p>At current gasPrices, simple send transactions on RSK cost about $0.05. Not exactly cheap - Bitcoin at over $40,000 will do that - after all, RSK’s native currency is <a href="https://www.rsk.co/powpeg/">pegged 1:1</a> with Bitcoin. Nevertheless, with a ratio of 8 to 0.05, payments are 160 times cheaper on RSK than Ethereum.</p><p>Staying with the storage costs theme, an SSTORE opcode on RSK also costs about $0.05. And this 1:160 cost advantage over Ethereum carries over generally to all costs of interacting with decentralized applications.</p><p>The RSK community has several proposals and research projects to improve the economics of blockchain storage. For example, <a href="https://github.com/rsksmart/RSKIPs/blob/ephemeralbc/IPs/RSKIP215.md">RSKIP-215</a>, is a proposal to adopt <strong>consensus-determined state checkpointing</strong>. Such synchronized, state checkpoints can allow nodes to <em>prune</em> old blocks and transactions from storage. Another proposal — state <a href="https://github.com/rsksmart/RSKIPs/blob/storageRent2020/IPs/RSKIP_rent2020.md"><strong>access rent</strong></a> — explores implementing state <em>access fees</em> along a <em>time-dimension</em> to provide incentives for better use of storage resources.</p><p>In the Ethereum community there are proposals called <em>scaling solutions</em> — which can offload hundreds or thousands of transactions to a <em>secondary layer</em>. They can provide significant reductions in storage used and also reduce transaction fees. These approaches are also being actively researched in the <a href="https://medium.com/iovlabs-innovation-stories/an-introduction-to-second-layer-protocols-49e2d0da101a">RSK community</a>. In addition to these initiatives, the community is also working on integrating novel solutions for <strong>incentivized</strong>,<strong> torrent-like</strong>, <strong>decentralized storage</strong> of <em>arbitrary content</em> using technologies like <a href="https://ipfs.io/">IPFS</a> and <a href="https://swarm.ethereum.org/">Swarm</a> — e.g. see <a href="https://www.rifos.org/storage">RIF Storage</a> solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b65b242c6ec0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rootstock-tech-blog/a-primer-on-blockchain-storage-economics-b65b242c6ec0">A Primer on Blockchain Storage Economics</a> was originally published in <a href="https://medium.com/rootstock-tech-blog">RootstockLabs: Research &amp; Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Storage Rent in RSK — Part 2]]></title>
            <link>https://shreemoy.medium.com/implementing-storage-rent-in-rsk-part-2-8f1f30a43d2c?source=rss-780d0c2fb896------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f1f30a43d2c</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum-virtual-machine]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[rsk]]></category>
            <dc:creator><![CDATA[Shreemoy Mishra]]></dc:creator>
            <pubDate>Wed, 09 Dec 2020 06:22:08 GMT</pubDate>
            <atom:updated>2020-12-11T20:12:09.612Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZrA7tu_uBcvo4L4kJmHKA.png" /><figcaption>Node Performance with Increasing Fraction (25, 50, 75%) of Token Transfers</figcaption></figure><h3>Implementing Storage Rent in RSK — Part 2</h3><p>In a previous post, we discussed a proposal to implement storage rent which is a <strong>data access fee</strong> charged to transaction senders. In this post we present some (engineering) performance implications of storage rent. This post assumes that readers are familiar with blockchain metrics such as <em>VM</em> and <em>Block Execution</em> times, or <em>Trie get value</em> operations times.</p><p><strong>Objective:</strong> The research implementation of <em>Storage Rent in RSKJ</em> has not been optimized. While we expect it to run somewhat slower than an unmodified RSKJ node, it is important to quantify the performance impact. This can help improve the implementation and also guide future design decisions.</p><p><strong>Summary:</strong> We expect 2 main areas of impact:</p><ol><li>an increase in <strong>Trie Get Value</strong> operations to query rent timestamps and</li><li>an increase in <strong>VM execution</strong> time for rent tracking and payments</li></ol><p>We expect the impact to vary across transactions of different complexity.</p><p>The following chart shows the quantitative impact for 3 <em>different </em>c<em>lasses </em>of transactions:</p><ul><li>ERC20 contract <strong>deployment</strong> transactions (4 transactions in the 1st block after genesis).</li><li>transactions for initial <strong>token allocation</strong> to some randomly selected users (about 40 blocks containing 125 transactions each).</li><li>and finally, <strong>transfer</strong> transactions (180 transactions in the final 100 blocks. 1/2 in <em>native coin</em> and 1/2 <em>token transfers</em>).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wJKza8WiiiRrAgSi.png" /><figcaption>Execution time and memory usage for different classes of transactions</figcaption></figure><p>Naturally, the impact of the additional VM computations or Trie getValue operations depends on the type of transactions. Those that already involve more computations are less affected by the introduction of storage rent.</p><p>The increases in VM execution and Trie GetValue times lead to predictable increases in <strong>Block Execution</strong> and <strong>Connection</strong> times. The quantitative impact (<em>% increase</em> ) is summarized in the following table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*3DIN_CdscVcXmlUlDMOknA.png" /><figcaption><strong>Note:</strong> <em>values in table represent percentage increase in storage rent implementation compared to baseline RSKJ</em></figcaption></figure><p>Once we have accounted for VM execution and Trie gets, all <em>remaining variation</em> in <em>Block Execution</em> or <em>Block Connection</em> times have no further statistical links with storage rent. We confirmed this with Linear Regression Analysis.</p><h3>Details</h3><p>Comparison framework:</p><ul><li>As before we use an in-house benchmarking tool developed by Raul Laprida from the research team at IOV Labs.</li><li>We generate data from <strong>6 simulated blockchain runs</strong>: one set each for Baseline and Storage Rent.</li><li>Each simulation generates 100 blocks with 180 transactions in each block.</li><li><strong>Half</strong> of the transactions involve <em>pure coin</em> transfers while the remaining are transfers of <em>ERC20 tokens</em>.</li><li>ThegasLimits are <strong>set higher</strong> (exactly double) in the storage rent case. This “doubling” keeps the number and mix of transactions identical across the two settings. This is required because the experimental storage rent implementation splits a transaction’s <em>gaslimit </em>into two equal budgets, one for normal execution gas and another to pay for rent.</li><li>In order to generate transfer transactions, the simulation tool first <strong>deploys</strong> 5 ERC20 token contracts and then <strong>randomly pre-allocates</strong> initial token balances to some accounts (from a set of 1000 accounts).</li><li>We also track the performance impact of blocks containing these setup (deployment, token-allocation) transactions. Deployment only needs a couple of blocks. The initial allocations take about 120 blocks.</li></ul><h3>Execution Time</h3><p>We expect to see <em>higher VM execution time</em> due to additional computation for tracking and collecting rent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UrNPP50T-gFrEBz9.png" /><figcaption>Execution time comparison (Transfer transactions only)</figcaption></figure><p>As expected VM execution takes longer. As a consequence, we see this effect spill over to block execution and connection times. But as we saw earlier, the impact is markedly lower for other types of transactions (e.g. contract deployment) or pre allocations. Generally the impact of introducing rent may be smaller for transactions that require more computations anyway.</p><h3>Trie Task Times</h3><p>Storage rent does not require querying nodes that would not normally (without rent) be touched by a transaction. Thus, we do not expect any difference in the number of trie nodes generated using calls to fromMessage.</p><p>We <em>do expect</em> to see more trie getValue operations with storage rent. These additional operations are to obtain the <em>last rent paid timestamp</em>s for value containing nodes. Naturally, these additional operations will consume more time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0SHpg9hcPAtGvF0x.png" /><figcaption>Trir task time comparison (Transfer transactions only)</figcaption></figure><p><strong>Takeaway:</strong> While there are a lot more trie getValue operations with rent, the <em>time taken</em> by those operations does not increase linearly.</p><p><strong>Takeaway:</strong> Another key takeaway is that introducing storage rent does not increase the number of trie nodes loaded into memory, this can be observed from the plots of TriefromMsgevents.</p><h3>Database and Memory</h3><p>We do not expect significant difference in database IO, but we do expect somewhat higher RAM use with storage rent for the additional tracking of rent timestamps and outstanding amounts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SoVTsErKZa-tk0cb.png" /><figcaption>IO and memory comparison (Transfer transactions only)</figcaption></figure><h3>Performance comparison on a per transaction basis</h3><p>Increasing the complexity of transactions obviously leads to lower performance. We saw some of this impact above when comparing node performance for different categories of transactions. However, quantify-ing “additional complexity” is not straightforward.</p><p>A much simpler way to explore the impact of additional smart contract complexity is to somehow <em>control for the complexity </em>by keeping the level of complexity fixed. We can do this by looking at blocks that only contain coin or token transfers (as above). But now, we <strong>vary the <em>fraction</em></strong><em> of token transfers </em>and <em>pure coin</em> transfers. This is what the image at the top of the post does.</p><p>The figure is repeated below for convenience. It compares the rent and baseline node implementations while increasing the fraction of token transfers from 25, to 50 and then to 75% of all transactions in a block. Changing the mix of transaction means the number of transactions that can fit in a block is no longer the same. For example, coin transfers cost 21000 gas, while token transfers cost 53000. We can fit a lot more coin transfers in a block. Therefore, — in this case — the performance metrics are presented on a <em>per-transaction basis</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZrA7tu_uBcvo4L4kJmHKA.png" /></figure><p>As expected, the impact of introducing storage rent on node performance (on a per transaction basis) responds to the fraction of token transfers.</p><h3>Aggregated comparison across classes</h3><p><strong>Note: </strong>In some cases, the storage rent version <em>appears</em> to outperform the baseline implementation. <em>In none of these cases is this difference statistically significant</em>. This is merely incidental as each simulation run uses a different set of pseudo random numbers.</p><p>Most of the comparison charts above are for <em>coin or token transfer </em>transactions only. The charts below show aggregated results for different transaction classes.</p><h4>ERC20 contract deployment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oqX2d8ZV44n-OAup.png" /></figure><h3>ERC20 initial balance allocations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sn1G6Ke9zZHQAN_i.png" /></figure><h3>Transfer transactions</h3><p>Some of these plots have already appeared above in groups</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PrXQvVUDmV56_nKS.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f1f30a43d2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Storage Rent in RSK — Part 1]]></title>
            <link>https://shreemoy.medium.com/implementing-storage-rent-in-rsk-part-1-8a9c1db6ffd2?source=rss-780d0c2fb896------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a9c1db6ffd2</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Shreemoy Mishra]]></dc:creator>
            <pubDate>Wed, 09 Dec 2020 06:09:28 GMT</pubDate>
            <atom:updated>2021-02-09T23:35:56.389Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*52g5aO2Gfds0K0zL1rCHYg.jpeg" /></figure><h3>Implementing Storage Rent in RSK — Part 1</h3><p>Storage rent is a <a href="https://github.com/rsksmart/RSKIPs/blob/master/IPs/RSKIP113.md">proposal</a> to add a <strong>data access fee</strong> to transactions on the RSK blockchain network. A key difference from current storage-related gas costs (e.g. SSTOREor SLOAD) is that storage rent depends on both the amount of data accessed, as well as the <em>duration for which data are stored</em> in blockchain state. Storage rent offers an additional method to protect the network from IO based DoS attacks.</p><p>In this post, we go over the motivation and basic structure of the proposal. In part 2 of this series, we present benchmarking results to quantify the performance impact of implementing storage rent in the reference java based node (RSKJ).</p><h3>What is state data?</h3><p>For our purpose, state data refers to three types of information that are essential to execute transactions on ethereum like blockchains such as RSK</p><ul><li><em>Account information</em> (native coin balance, nonce)</li><li><em>Smart Contract Code</em> (stored as EVM bytecode)</li><li>Contract <em>Storage</em> (e.g. ERC20 token balances)</li></ul><p>The state of the blockchain evolves as transactions get mined and included in blocks. For processing transactions, only the <em>current</em> state matters and this is based on the <em>most recent block</em>.</p><p>Aside: <em>Historical state</em> (e.g. some account’s balance on March 14, 2020) has no relevance for processing transactions. However, should anyone need it, historical state at any point can be computed by replaying the blockchain from <em>genesis</em> till that point. This is similar to what new nodes do when <em>syncing</em> with the blockchain for the first time. Since this is a very cumbersome process, historical state is often retrieved from service providers running full <em>archive</em> nodes who maintain several snapshots of historical state. But we digress. Let us get back to storing current state.</p><h3>Where is current state data stored?</h3><p>To process transactions and blocks quickly, the most recent state data should be in a blockchain node’s memory (RAM). However, as the number of users, smart contracts, and application data grow, it is infeasible to store <em>all</em> state data in RAM and it is necessary to store some part (if not most) of state on disk.</p><p>When a transaction needs state data that is not in a <em>primary cache</em> (or RAM), that data has to be fetched from a secondary layer cache or, in the worst case, from disk. As state size grows such disk IO operations become more frequent. Increases in IO operations degrade node performance and by extension, network performance suffers as well.</p><h3>State IO (DoS) Attacks</h3><p><em>Attackers</em> can craft transactions to require more IO operations leading to denial of service (DoS).The Ethereum network experienced such an attack in 2016. These are sometimes called the Shanghai attacks, apparently because they happened while Ethereum co-founder Vitalik Buterin was on a flight to Shanghai for a conference. In response, Ethereum raised the costs of several IO op-codes (by orders of magnitude) via <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-150.md">EIP-150</a>.</p><p>For example, consider an SLOAD operation in the Ethereum Virtual Machine (EVM). This opcode instructs the EVM to read a single piece of data from a contract’s storage cell. EIP-150 raised the cost of this operation from 50 gas to 200 gas. The cost of EXTCODE* — a family of IO-heavy op-codes — was increased from 20 to 700. These changes raised the costs of carrying out an IO attack. Further increases were proposed in <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2929.md">EIP-2929</a>, which raise the cost of an SLOAD to 2100 gas and that of EXTCODE* to 2600 gas. Such <strong>gas-repricing</strong> decisions are one way to protect the network from IO attacks.</p><p><em>Implementing storage rent offers another way of defending the network from DoS attacks</em></p><p>To understand how storage rent works, let us recall how state is stored and re<strong>trie</strong>ved.</p><h3>How is state data stored?</h3><p>State data is stored in data structures called <a href="https://en.wikipedia.org/wiki/Tri">Tries</a>, which are <em>prefix</em> trees. The prefix helps quickly organize and retrieve information related to particular accounts. While Ethereum uses a combination of <em>hexary</em> (radix-16) trees, RSK uses a unified <em>binary tree</em> called the <a href="https://blog.rsk.co/noticia/towards-higher-onchain-scalability-with-the-unitrie/">Unitrie</a>. Individual pieces of state data — e.g. account state, contract code, and contact storage — are stored within nodes in the unitrie. These value-containing nodes typically have no <em>children</em> (i.e. they are usually <em>leaf</em> nodes).</p><p>The trie is an abstract object. Actual state data is backed up in a <em>key-value datastore</em> where each &lt;key-value&gt; pair refers to a particular node in the Unitrie. See the linked <a href="https://blog.rsk.co/noticia/towards-higher-onchain-scalability-with-the-unitrie/">Unitrie</a> post for details of how keys are created using hashes of account addresses and how values are encoded.</p><h4>How does state evolve?</h4><p>Whenever some state data changes, the relevant node is deleted from the trie. Updated values and freshly created accounts are stored by inserting new nodes into the trie.</p><h3>Cost of storing state</h3><p>There are direct and indirect costs of storing state. Existing storage related opcodes charge users for the computational burden of these trie and IO operations. However, they do not provide strong incentives for limiting the duration of storing information. Once data is stored in state, it can stay there forever at no further cost.</p><p>Storage device prices keep falling. Thus, the <em>direct</em> cost of storing state are small, especially if it is on disk. This cost gets magnified due to replication by each full node. But that is still small for RSK. However, — as mentioned earlier — increasing state size increases IO operations and the vulnerability to IO attacks. The goal of storage rent is to reduce these <strong>indirect costs</strong>.</p><h3>Storage rent provides time incentives</h3><p>Cloud data storage services like Amazon’s S3 charge for the <em>size</em>, <em>duration</em>, and even for <em>bandwidth</em> (data flows) from ‘storage buckets’. The idea of storage rent for blockchains is neither new nor surprising. There is a history of previous proposals in Ethereum or RSK. However, past proposals were quite complex, and lacked broad community support. <a href="https://github.com/rsksmart/RSKIPs/blob/master/IPs/RSKIP113.md">RSKIP113</a> distilled and simplified the previous approaches. The current proposal is even simpler.</p><h3>Main elements of the Proposal</h3><h4>Who pays rent?</h4><p>A transaction’s <strong>sender</strong> is charged storage rent for <strong>each data-containing</strong> Unitrie node <strong>touched by</strong> that transaction.</p><p>Example: An ERC20 token transfer transaction involves at least the following trie nodes</p><ul><li><em>account state</em> nodes for the sender and recipient (of the token transfer)</li><li>the node containing the token <em>contract’s account information</em></li><li>the node containing the <em>contract’s bytecode</em></li><li>the contracts’s <em>storage root</em> and the <em>storage cells</em> containing the sender and recipient’s token balances.</li></ul><h4>How is rent paid?</h4><p>Rent is collected in <strong>units of gas</strong> just like usual transaction fees. To handle rent payments, a transaction’s gasLimit is internally divided into <em>separate budgets</em> to cover <em>execution gas</em> (current fees) and <em>storage rent gas</em> (proposed). All unused (leftover) execution gas and rent gas are refunded at the end of the transaction.</p><h4>Will all transactions be charged rent?</h4><p>No. Several transactions may not have any rent collection. To avoid collecting small amounts there are <strong>rent collection triggers</strong>. If the data stored in a trie node is <em>modified</em> by the transaction, then we collect rent for that node only if the outstanding amount of rent exceeds 1000 gas. However, if data from a trie node is <em>accessed but not modified</em> then we require a higher bar of 10,000 gas.</p><p>Thus, if two accounts are routinely used for a particular token transfer, then it is very likely that most of these transactions will not involve any rent collection as the outstanding amounts will be too small.</p><h4>How is rent computed?</h4><p>Rent tracking is based on <strong>a timestamp</strong> (lastRentPaidTime in Unix seconds) associated with each value-containing trie node. The rent for a node is based on</p><ul><li>the <strong>node’s size</strong> (in <em>bytes</em>), which is the approximate size of encoded data plus a storage overhead of 128 bytes.</li><li>the <strong>time since last rent payment</strong> (in <em>seconds</em>)</li><li>and a <strong>rental rate</strong> of 1/(2^21) <em>gas per byte per second</em></li></ul><h4>Example rent computations</h4><p>The rental rate of 1/(2^21) is not easy to interpret. To place this in context, recall that a simple send transaction costs 21000 gas.</p><p>Here are some examples of what rent costs may look like.</p><ul><li>An <strong>externally owned account</strong>: <strong>Rent:</strong> about 2075 gas/year</li><li>A <strong>smart contract</strong> with 10K bytes in <strong>code</strong> and 100 <strong>storage </strong>cells<strong>. Rent:</strong> about 380K gas/year</li><li>A <strong>very popular contract</strong> with 100,000 <strong>storage </strong>cells<strong>: Rent </strong>about 44K gas/<strong>day</strong></li></ul><p>These costs are fairly low. Ordinary users may not even notice them.</p><p>The rental rate has evolved over time and will be finalized according to community feedback based on level of deterrence needed against DoS attacks.</p><h4>Rent for new trie nodes</h4><p>Newly created accounts and trie nodes are charged some rent in <em>advance</em>. This is done by setting their rent paid timestamp to 6 months in the future. Which can be useful as <strong>a penalty</strong> for IO attacks where the attacker forces the node to look up non-existent nodes.</p><h4>Who is rent paid to?</h4><p>As with existing transaction fees, all rent is passed along to miners. In RSK, this is managed by the REMASC fee distribution contract.</p><h4>How does this impact the size of blocks?</h4><p>Rent gas <em>does not count</em> towards block-level gaslimit. Therefore, there is no impact on the number of transactions that can be included in a block.</p><h4>What happens if rent remains unpaid?</h4><p>Nothing. The data remains in state, but the transaction will OOG (out of gas exception) and will not get executed. For transactions to get executed, they must include enough gas to cover all outstanding rent that is due — provided the outstanding amounts are high enough to be worth collecting (small amounts are not collected).</p><h4>Will rent work with existing wallets?</h4><p>We intend to implement rent in a way so that existing wallets can continue as before without breaking changes. This is easier in cases where wallets use RPC based calls to estimateGas prior to sending transactions.</p><p>However, the implementation has to be mindful of some predictable failures. For example, some wallets simply use 21000 gas as default for <em>pure send</em> transactions (and do not use estimateGas). One approach to handle such situations is to turn rent computations off for transactions that <em>do not include any</em> data (i.e. pure transfers).</p><p>We will seek community feedback for other breaking scenarios or edge cases.</p><h3>Other benefits of implementing storage rent</h3><ul><li>Encourage sensitivity to <strong>duration</strong> of storing data. This is primarily for developers, contract designers, and service providers.</li><li>Limiting <strong>gas arbitrage</strong> and discourage <strong>storage spam</strong>.</li><li>Rent <strong>timestamps</strong> can be used for state <strong>caching</strong> and <strong>node hibernation</strong>.</li><li>Since rent is an additional source of fees, it may permit us to <strong>reduce some existing fees</strong>.</li></ul><h4>Why has Ethereum not implemented storage rent?</h4><p>They have tried (for years)! For example see <a href="https://eips.ethereum.org/EIPS/eip-1682">EIP-1682</a> and <a href="https://github.com/ledgerwatch/eth_state/blob/master/State_Fees_3.pdf">this proposal</a> by Alexey Akhunov which has also received attention. However, despite support from Vitalik Buterin, there is no consensus and discussions appear to have stalled. Mostly, the proposals in ethereum have been a bit too complex to gain broad support. The emphasis has shifted to other things like Eth 2, and layer 2 scaling solutions.</p><h3>Next steps</h3><p>In part 2 of this series we discuss some (engineering) performance consequences of implementing storage rent in the reference Java implementation of an RSK node i.e. RSKJ.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a9c1db6ffd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Offline experiments with Remix and local RSKJ Node]]></title>
            <link>https://shreemoy.medium.com/offline-experiments-with-remix-and-local-rskj-node-713e2f724e59?source=rss-780d0c2fb896------2</link>
            <guid isPermaLink="false">https://medium.com/p/713e2f724e59</guid>
            <dc:creator><![CDATA[Shreemoy Mishra]]></dc:creator>
            <pubDate>Fri, 20 Nov 2020 22:51:40 GMT</pubDate>
            <atom:updated>2021-01-08T00:04:49.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*q01B2zPdJVmhfj3rHJq7Sg.png" /></figure><p>The <a href="https://remix-project.org/">Remix IDE</a> is a popular environment to experiment with and deploy smart contracts written in Solidity for Ethereum-like blockchains including <a href="https://www.rsk.co/">RSK</a>. In this post we go over a few simple steps to run Remix IDE <em>locally</em> along with a <em>local RSKJ node</em>. A local setup is useful for <em>offline</em> testing and can also serve as an alternative to the <a href="https://remix.ethereum.org/">Ethereum foundation’s service</a>.</p><h3>Components</h3><p>Remix users work with the following components</p><ol><li>A <strong>blockchain</strong>: This may be a <strong>local blockchain</strong> e.g. ganache,geth, rskj, or a <strong>public blockchain endpoint</strong> e.g. <a href="https://public-node.testnet.rsk.co/">https://public-node.testnet.rsk.co</a>.</li><li>A <strong>wallet</strong> to manage blockchain credentials (accounts, private keys, signatures). This is often a <em>browser extension</em> e.g. <a href="https://www.poa.network/for-users/nifty-wallet">Nifty</a> or <a href="https://metamask.io/">Metamask</a>. Users can also use a hardware wallet.</li><li><strong>Remix IDE in a Web Browser, </strong>typically <a href="https://remix.ethereum.org/">https://remix.ethereum.org</a> via Chrome or Firefox.</li></ol><p>To use Remix, users connect their browser wallet to a relevant blockchain. This is only needed if users wish to deploy or administer smart contracts. Those using Remix IDE just to compile contracts (no deployment) do not have to use a wallet or connect to any blockchain.</p><p>In the current exercise we run two of the above components within separate <em>docker containers</em>: one to run a blockchain (a local RSKJ node) and another to serve Remix. We then connect to these services as before — through a browser (with a wallet) on the host machine. I used Google Chrome with <em>Nifty wallet extension</em> enabled.</p><p>A Ubuntu 20.04 LTS machine served as the host system. I used a docker image with Ubuntu 18.04 LTS base for both containers. The process is quite straightforward and largely follows instructions from respective docs (RSKJ and Remix).</p><h3>Steps in brief</h3><ol><li>Follow <a href="https://developers.rsk.co/rsk/node/install/">these instructions</a> to install RSKJ. Start the node in <strong>regtest</strong> mode</li><li>Follow <a href="https://github.com/ethereum/remix-project#installation">these instructions</a> to install Remix IDE. Start the service.</li><li>Enable a wallet extension in your browser. Connect wallet to the local RSK blockchain (custom RPC endpoint, with CORS enabled)</li><li>Use [<a href="https://developers.rsk.co/rsk/node/architecture/json-rpc/">JSON RPC</a>] to fund the account in the wallet so we can pay for gas costs of deploying contracts from Remix</li></ol><pre>#use eth_accounts() to<br>#find out pre-funded accounts on the node (regtest)</pre><pre>curl localhost:4444     -X POST     -H &quot;Content-Type: application/json&quot;     --data &#39;{&quot;jsonrpc&quot;:&quot;2.0&quot;,&quot;method&quot;:&quot;eth_accounts&quot;,&quot;params&quot;: [],&quot;id&quot;:1}&#39; </pre><pre>#use eth_sendTransaction() to fund the wallet account</pre><pre>#change &quot;to&quot;, &quot;from&quot;, &quot;value&quot; as needed</pre><pre>curl localhost:4444 -X POST -H &quot;Content-Type: application/json&quot; --data &#39;{&quot;jsonrpc&quot;:&quot;2.0&quot;,&quot;method&quot;:&quot;eth_sendTransaction&quot;,&quot;params&quot;:[{&quot;from&quot;:&quot;0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826&quot;,&quot;to&quot;: &quot;0xf87594Cb9036302G1081753D2d6D4Fb7e9127Ac5&quot;,&quot;gas&quot;:&quot;0x76c0&quot;,&quot;gasPrice&quot;: &quot;0x9184e72a000&quot;,&quot;value&quot;: &quot;0xb6255df5f50080000&quot;,&quot;data&quot;: &quot;0x&quot;}],&quot;id&quot;:1}&#39;</pre><p>Now we can use our own Remix service to compile and deploy contracts on our own local (experimental) blockchain.</p><h3>Steps in more detail</h3><p><strong>Note:</strong> Depending on your user account (user id), you may need to use sudo when installing.</p><h3>Install RSKJ</h3><p>RSKJ is a Java implementation of an RSK node. Use the general steps described <a href="https://developers.rsk.co/rsk/node/install/">here</a> or this <a href="https://developers.rsk.co/rsk/node/reproducible/">reproducible build</a>. Some steps are reproduced here for convenience. I suggest you follow those from source links as they are more likely to be up to date. Binaries are also available for some systems. An x64 system, with at least 2 cores and 8GB RAM is recommended.</p><pre>apt-get update -y &amp;&amp; \<br>    apt-get install -y git curl gnupg openjdk-8-jdk &amp;&amp; \<br>    rm -rf /var/lib/apt/lists/* &amp;&amp; \<br>    apt-get autoremove -y &amp;&amp; \<br>    apt-get clean</pre><pre>gpg --keyserver https://secchannel.rsk.co/release.asc --recv-keys 1A92D8942171AFA951A857365DECF4415E3B8FA4<br>gpg --finger 1A92D8942171AFA951A857365DECF4415E3B8FA4</pre><pre># clone the project into a local directory<br>git clone --single-branch --depth 1 --branch PAPYRUS-2.1.0 https://github.com/rsksmart/rskj.git /code/rskj</pre><pre># switch to the directory<br>cd /code/rskj<br>gpg --verify SHA256SUMS.asc<br>sha256sum --check SHA256SUMS.asc</pre><pre>#run the config script, changing persmission with chmod +x as needed<br>./configure.sh</pre><pre># build the project, automated tests can be run later if desired<br>./gradlew clean build -x test<br></pre><pre>#The built JARS will be in the directory `rskj-core/build/libs/`<br># For a quick check of the installation, we can start the node in `regtest` mode.</pre><pre>java -cp rskj-core/build/libs/rskj-core-2.1.0-SNAPSHOT-all.jar co.rsk.Start --regtest</pre><p><strong>Cross Origin Resource Sharing:</strong> In order to connect to the node from a browser based wallet, we should run the node with CORS enabled. See <a href="https://developers.rsk.co/rsk/node/configure/">node configuration</a> for details. One way to do this is to start a node with this option (instead of the one above)</p><pre>java -cp rskj-core/build/libs/rskj-core-2.1.0-SNAPSHOT-all.jar  -Drpc.providers.web.cors=* co.rsk.Start --regtest</pre><p>If the node starts normally, then there will be <em>no messages</em>. This can seem odd the first time. But the node is working! It can be accessed via http://localhost:4444 from another terminal attached to the container. This is also the URL to use for custom RPC endpoint for browser wallets.</p><p>Test the node with a JSON remote procedure call (RPC) using curl such as</p><pre>curl localhost:4444/1.1.0/ -X POST -H &quot;Content-Type: application/json&quot; --data &#39;{&quot;jsonrpc&quot;:&quot;2.0&quot;,&quot;method&quot;:&quot;eth_blockNumber&quot;,&quot;params&quot;:[],&quot;id&quot;:1}&#39;</pre><p>the response should be something like</p><pre>{&quot;jsonrpc&quot;:&quot;2.0&quot;,&quot;id&quot;:1,&quot;result&quot;:&quot;0x10b&quot;}</pre><p>For later use, forward the port from docker container to host machine. Using an environment such as Visual Studio Code — with extensions for docker — makes this really simple.</p><h3>Install Remix IDE</h3><p>Remix IDE is open source with <a href="https://github.com/ethereum/remix-project#installation">installation instructions here</a>. There is a desktop version available as well (that I have not tested).</p><p>Assuming we already have curl, git, wget, yarn etc installed. <strong>Run commands with sudo</strong> as needed.</p><pre># Install a recent version of node from debsource .. <br>curl -sL https://deb.nodesource.com/setup_15.x -o nodesource_setup.sh</pre><pre># make it executable and execute<br>bash chmod +x node*.sh</pre><pre># Install the nx CLI<br>npm install -g @nrwl/cli # to enable nx executable commands</pre><pre># Install Yarn package manager<br>curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - echo &quot;deb https://dl.yarnpkg.com/debian/ stable main&quot; | sudo tee /etc/apt/sources.list.d/yarn.list</pre><pre>apt-get update &amp;&amp; sudo apt-get install yarn</pre><pre># Clone the Remix repo (needs wget)<br>apt-get install wget</pre><pre>git clone https://github.com/ethereum/remix-project.git</pre><pre>cd remix-project</pre><pre># install and serve<br>npm install<br>nx build remix-ide --with-deps<br>nx serve</pre><p>If using docker, forward the port so we can access the service from browser on host machine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=713e2f724e59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aspirations and Challenges in DeFi]]></title>
            <link>https://medium.com/rootstock-tech-blog/aspirations-and-challenges-in-decentralized-finance-b25392b21c4b?source=rss-780d0c2fb896------2</link>
            <guid isPermaLink="false">https://medium.com/p/b25392b21c4b</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[innovation]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Shreemoy Mishra]]></dc:creator>
            <pubDate>Fri, 11 Sep 2020 04:38:59 GMT</pubDate>
            <atom:updated>2021-01-07T13:48:01.707Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*liK5urP6WaTiYJP37HUGWQ.jpeg" /></figure><p>n the United States, my bank charges $3 for an electronic funds transfer to someone else’s account at a different bank, a process that takes 2–3 business days. Next-day transfers cost $10 while same-day transfers cost $25.</p><p>Meanwhile, in the surreal world of the Ethereum blockchain, this <a href="https://etherscan.io/tx/0xa4170b9a9fd6934a8e2dc22b35d88962125989aa993a083ee6a4981040c3bfc2">recent transaction</a> cost 87 cents to send the equivalent of $6500. Such transfers usually take around 2 minutes, but they do suffer from occasional spikes in cost and confirmation times.</p><p>Coming back to regular funds transfers, one can use apps like <em>Venmo </em>or <em>Zelle</em> to send instant transfers for free. Similar (or even better) apps are available in nearly all countries. However, they usually work when recipients use them as well — which can be a problem since adoption varies a lot by demographics. User adoption is one issue that technological innovations in mainstream finance share with emerging blockchain-based transactions. They have enormous potential but are severely dependent on network effects.</p><p>As a former academic economist and engineer, I am fascinated by cryptocurrency-based systems for relatively cheap, fast, trustless, global payments, and by the use of smart contracts for financial intermediation through decentralized exchanges. That sounds like quite a mouthful — and it is. That is because, in addition to payments, we are talking about novel market mechanisms to borrow and lend money, to invest or hedge risks, to create derivative securities and to engage in speculative trading. Trading, in particular, has experienced enormous growth in recent times. Meanwhile, the overall crypto-ecosystem appears to have matured beyond the scammy ICOs of past.</p><p>Several crypto enthusiasts are interested in another aspect of <em>decentralized finance</em> — which is to build infrastructure to serve those neglected by main street corporations or those living under economically restrictive regimes. Many people in this group think of <em>stablecoins</em> — cryptocurrencies whose values are tied to the Dollar or other <em>fiat</em> currency — as a product category of utmost importance. This is partly driven by beliefs that popular currencies such as Bitcoin and Ether <em>will</em> <em>remain far too volatile</em> to serve as stores of value for the masses.</p><p>In our own ways, all of us — researchers, developers, users, entrepreneurs — are trying to contribute to the development of new products and use cases. As the cliche goes… good product design requires clear understanding of what users need. However, developing this understanding can be very challenging. Not least because people — ourselves included — are not always clear about what we really need. Indeed, at times some of my research projects have taken a turn that seems like a weary response looking for a good question to settle down with.</p><p>In this context, Don Norman’s <em>The Psychology of Everyday Things</em>, offers a masterclass in human centered design. The book — also known as <em>The Design of Everyday Things</em> — includes illuminating anecdotes and examples.</p><p>One of Norman’s striking observations on user experience is that people often blame themselves for mistakes when using a product, even when the errors are <em>predictable consequences of bad design</em>.</p><p>I am reminded of this when I see my father struggling with a change in the user interface of some app on his Android phone. My dad always blames himself. Which is silly and frustrating. When I see him struggling, I think of it as a design failure.</p><p>In an interesting twist of duality, Norman reminds us that principles that drive good design can be applied (in reverse) to make some tasks <em>intentionally difficult</em> for users. This can be adopted for security e.g. accidentally deleting cryptographic keys or sending funds to unintended recipients.</p><p>Product design is always challenging. Development and testing are restricted by cost, schedule, uncertain demand, features, team rivalries or misaligned incentives. But for those who strive to design and build useful products, Norman’s book offers timeless advice and inspiration.</p><p>At this point in time, there is no urgent need for people to be intimately familiar with crypto-based payments or applications. This small user base creates challenges in designing and testing products.</p><p>However, transformative change and user adoption can arrive in spectacular fashion. In November 2016, in a surprise move, the Government of India invalidated all large denomination currency bills in circulation — overnight. The idea was to catch tax evaders off guard. Instead, it resulted in months of economic chaos, especially for millions of poor, unbanked Indians working in the informal sector. However, smart phone payment apps (particularly one backed by SoftBank) got a huge boost in user adoption.</p><p>In future posts in this series, we will explore challenges in the rapidly evolving De-Fi space and examine how the community is addressing them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b25392b21c4b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rootstock-tech-blog/aspirations-and-challenges-in-decentralized-finance-b25392b21c4b">Aspirations and Challenges in DeFi</a> was originally published in <a href="https://medium.com/rootstock-tech-blog">RootstockLabs: Research &amp; Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>