<?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 Idogwu Chinonso on Medium]]></title>
        <description><![CDATA[Stories by Idogwu Chinonso on Medium]]></description>
        <link>https://medium.com/@idogwuchi?source=rss-a9abcdd90f1f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2myhhVcuG7U39KCKo_C0uA.jpeg</url>
            <title>Stories by Idogwu Chinonso on Medium</title>
            <link>https://medium.com/@idogwuchi?source=rss-a9abcdd90f1f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 04:37:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@idogwuchi/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[Exploring Cartesi Honeypot & its PRT Inegration]]></title>
            <link>https://medium.com/@idogwuchi/exploring-cartesi-honeypot-its-prt-inegration-1ffd7b12db2e?source=rss-a9abcdd90f1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ffd7b12db2e</guid>
            <category><![CDATA[crack]]></category>
            <category><![CDATA[prt]]></category>
            <category><![CDATA[cartesi]]></category>
            <category><![CDATA[honeypot]]></category>
            <dc:creator><![CDATA[Idogwu Chinonso]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 11:42:35 GMT</pubDate>
            <atom:updated>2025-09-11T13:02:10.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JCtBd-4rdlLp1FdPFHRNhQ.png" /></figure><p><strong>Introduction</strong></p><p>The concept of honeypot has existed for over 3 decades, with the earliest records dating back to the early 1980s and 1990s. Honeypot challenges started as decoy systems designed to attract and analyse malicious activity. These early systems were primarily research-oriented, used by academics and security professionals to study attack patterns rather than as competitive challenges. Honeypot challenges as competitive exercises gained traction in the 2000s with the rise of CTF (capture the flag) competitions and bug bounty programs. Popularized by events like DefCon, incorporating honeypot-like scenarios where participants exploited decoy systems to capture flags or unique tokens proving successful penetration. By the mid-2000s, organizations recognized the value of honeypots in post-deployment audits. Companies deployed honeypots to test their security, Bug bounty programs, hosted by companies like Google, Microsoft and platforms like HackerOne and Bugcrowd, also began including honeypot like systems in their testing environments. These programs rewarded ethical hackers for finding vulnerabilities in live or staged systems.</p><p>This article will serve as a guide providing you with key focus areas, architechture and general knowledge on the <strong>Cartesi PRT Honeypot</strong>, a honeypot challenge launched by the Cartesi Foundation to demonstrate the robustness and safety of applications secured by the PRT fraud-proof algorithm. Following its uncracked predecessor, which held <strong>1,772,888 CTSI tokens</strong>, approximately <strong>$150,000</strong> at the time of its closure, the PRT Honeypot offers the general community once more a chance to test the security of Cartesi’s PRT fraud proof and possibly get their hands on CTSI rewards, it also offers a unique opportunity to explore the architecture of the Honeypot application, its integration with PRT and the Cartesi’s ecosystem.</p><p><strong>The Cartesi Honeypot Application</strong></p><p>At its core, the Cartesi honeypot application is an ERC20 vault application written in C++. This application is built on the Cartesi rollups framework and achieves consensus on the base layer using the PRT fraud proof system.</p><p>The application allows anyone to deposit assets into the vault, but only a preprogrammed address can withdraw those assets. Currently, the vault holds <strong>20,042 CTSI tokens</strong>, with this amount expected to grow in the future. This design creates a honeypot structure where funds can only be withdrawn by the preconfigured address or by someone who successfully hacks the vault. The application logic runs inside the Cartesi Machine, which is contained within the Cartesi Node and interacts with the Ethereum base layer through the Cartesi framework.</p><p>The Honeypot’s design incentivizes ethical hackers to test its security rigorously. By restricting withdrawals to a single address unless compromised, it presents a clear challenge: exploit the system to access the funds.</p><p><strong>Architecture of the Honeypot</strong></p><p>The Cartesi honeypot is not just a layer 2 application; it functions as an app chain, with distinct components deployed both on-chain and off-chain working simultaneously to ensure its optimal functionality. In this section, we’ll explore the critical components of the Honeypot architecture, categorized by their on-chain and off-chain roles, to provide a comprehensive understanding of its structure.</p><p><strong>On-Chain Components:</strong></p><p>Cartesi applications rely on a combination of shared and application-specific contracts deployed on the base layer. To illustrate the Honeypot’s on-chain architecture, we’ll trace the path of user interaction and asset deposits, highlighting the key contracts involved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ERd6YXtjI4tQkv7_" /><figcaption>Fig. 1: PRT Honeypot on-chain component architecture diagram</figcaption></figure><ul><li><strong>Input Box Contract:</strong></li></ul><p>This is also a universal contract (a single contract) deployed on every base layer where Cartesi operates. It serves as the entry point for all Cartesi applications on that chain, channelling user inputs to the appropriate off-chain components. Users interact with Cartesi applications by targeting the `<strong>addInput</strong>` function in this contract, specifying the target application’s address and the input data in the function argument. This unified entry point simplifies the process for Cartesi Nodes, which subscribe to events emitted by the Input Box contract, as they only need to subscribe to events emitted by one contract and then filter through the event variables, which contain the application address the user intends to interact with, to identify which information is meant for the application logic they’re running. This design optimizes communication between the base layer and off-chain components, ensuring seamless interaction between the node and the base layer.</p><ul><li><strong>Portal Contracts:</strong></li></ul><p>The Portal Contract is also a universal contract deployed on each base layer where Cartesi operates. While the input box serves as the entry point for data input to Cartesi applications, portals serve as the entry points for assets going to Cartesi applications. There are four types of portal contracts: Ether, ERC20, ERC721 and ERC1155 portals. Each handling assets as specified by their names. For example, to deposit ERC-20 tokens, a user calls the ERC-20 Portal, providing the target application’s address, the token address, and the quantity. The Portal Contract transfers the assets to the application’s contract address for ownership and control and then structures a payload containing the depositor’s address, token, and amount, which it sends to the Input Box contract. Cartesi Nodes, listening for Input Box events, pick up and process this payload as defined in the application’s logic.</p><ul><li><strong>Application (Honeypot) Contract:</strong></li></ul><p>The application contract is a contract representation of the application on the base layer. While it does not process the actual application logic, it holds assets (ERC20, ERC721 and ERC1155 tokens) deposited to the application, awaiting commands from the off-chain application logic in the form of vouchers, which instruct it to transfer these assets to specified addresses or interact with other base-layer contracts. The Honeypot Application Contract is linked to a PRT Consensus Contract, which manages the application’s state and ensures consensus.</p><ul><li><strong>PRT (Dave) Consensus Contract:</strong></li></ul><p>The Cartesi PRT Honeypot is the first real-world application to implement the PRT fraud-proof system. This system enables multiple independent users to act as validators and run application nodes to execute logic and submit the application’s final state to the base layer. In scenarios with multiple validators, disagreements over the application’s state may arise, thereby creating the need for a reliable consensus mechanism that could accurately identify the valid state in such situations. The PRT fraud-proof system resolves these disputes using a tournament-based approach, relying on a collection of contracts and interfaces that together are able to help the application contract identify the valid state submission amongst multiple conflicting submissions.</p><p>The PRT consensus contract is unique for each Cartesi application and is deployed alongside the application contract. It manages the application’s state and oversees the dispute resolution process by deploying a Tournament Contract for each epoch, opening, settling, and closing epochs as needed.</p><ul><li><strong>Tournament contract:</strong></li></ul><p>The tournament contract is a dispute resolution contract automatically deployed at the end of each epoch to handle state submissions for the subsequent epoch. For example, at the conclusion of epoch one, a Tournament Contract is deployed for epoch two. Validator nodes automatically submit the application’s state hash to this contract by calling the `<strong>joinTournament</strong>` function. If conflicting state hashes are submitted, the Tournament Contract initiates a multilevel dispute resolution process. Using the PRT fraud-proof algorithm, it conducts an interactive recursive binary search between conflicting state hashes to identify the correct one. If no conflicts arise, the tournament concludes after seven days plus a few hours, allowing any validator to call the `<strong>settle</strong>` function in the PRT Consensus Contract to finalize the epoch and deploy the Tournament Contract for the next epoch.</p><p><strong>Off-chain components</strong></p><p>The aim of rollups is to bundle, send and process transactions off-chain; therefore, off-chain components or layers are important components of the rollups infrastructure. For the Cartesi Honeypot, these off-chain components are primarily the Cartesi node and the application logic running inside the node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*fBi7_5SDUdhSTbtM" /><figcaption>Fig. 2: PRT Honeypot off-chain component architecture diagram</figcaption></figure><ul><li><strong>PRT Roll-up Node:</strong></li></ul><p>The PRT Roll-up Node is an off-chain setup comprising the Cartesi Machine, the user application, and services that enable the node to listen for and process inputs from the base layer. Anyone can run a node for any application, and each node is expected to maintain a consistent state by processing inputs and updating its state accordingly. Upon startup, a node processes every block from the application’s initial deployment, re-executing transactions to align its state with other nodes. If nodes arrive at different state hashes due to discrepancies, these hashes are submitted to the application contract on the base layer, triggering a dispute resolution process using the PRT algorithm to identify and store the valid state.</p><ul><li><strong>Application Logic:</strong></li></ul><p>The Honeypot application is a C++ program designed as a vault application. It includes the `<strong>inspect</strong>` and `<strong>advance</strong>` methods to interact with the Cartesi SDK along with two functions to handle ERC-20 token deposits and withdrawals. Inputs to the application must trigger either the deposit or withdrawal function; otherwise, the application raises an exception. The application features a hardcoded withdrawal address, restricting withdrawals to that address only. This ensures that anyone can deposit tokens, but only the specified withdrawal address or a successful hacker can withdraw them. This logic lays a solid foundation for the Honeypot challenge: cracking the application is the only way to access the funds without being the preconfigured owner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*MqfsqsQXnV5QHwj_" /><figcaption>Fig. 3: PRT Honeypot on-chain component architecture diagram</figcaption></figure><p><strong>Key Focus Areas</strong></p><p>Building on the architecture of the Cartesi Honeypot, this section outlines key processes critical to understanding or attempting to hack the honeypot application. Before diving in, it’s important to note that the architecture of the Cartesi Honeypot enables anyone to run a validator node for the honeypot application, meaning that the process flow we’ll be describing below occurs simultaneously across all validator nodes running the honeypot application. This design is one of the key pillars of the honeypot and PRT integration because decentralised validation improves security by enabling any single random honest user to single-handedly uphold the correct application state, thereby preventing hacks or malicious state updates from any other validator (node runner).</p><ul><li><strong>Deposit Flow:</strong></li></ul><p>Depositing assets to the Honeypot follows a straightforward process. A user interacts with the ERC-20 Portal by calling the `<strong>depositERC20Tokens</strong>` function, specifying the CTSI token address, the amount to deposit, and the Honeypot application’s address. The Portal transfers the assets to the honeypot application contract on the base layer and calls the `<strong>addInput</strong>` function in the Input Box contract, passing the Honeypot’s address, the token address, the amount, and the depositor’s address. The Input Box emits an `<strong>InputAdded</strong>` event containing the application’s address and the payload (token address, depositor address, and amount).</p><p>Cartesi Nodes, constantly listening for Input Box events, detect the `<strong>InputAdded</strong>` event and verify the application address. If it matches the Honeypot application, the payload is forwarded to the Cartesi Machine running the application logic. After input validation, the application updates its balance and withdrawable token records, ensuring the deposited assets are accurately tracked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*A0trWWHL6_fIrheF" /><figcaption>Fig. 4: PRT Honeypot Deposit flow</figcaption></figure><ul><li><strong>Withdrawal Request Flow:</strong></li></ul><p>Withdrawing assets is similar to depositing assets; it begins with the user interacting with the input box contract directly, calling the `<strong>addInput</strong>` function and specifying the honeypot application address as the destination, and then specifying an empty payload as input to the honeypot application. In a typical scenario, the user would have to pass a target function and arguments that the function requires, but the honeypot application logic is designed to check two conditions: the caller must be the preconfigured withdrawal address, and the payload must be empty. If both conditions are met, the withdrawal function is triggered, transferring the vault’s entire balance to the preconfigured address. This means that while anyone is able to interact with the honeypot and submit an empty payload, it’s expected that the withdrawal function should only be triggered if the calling address is the preconfigured withdrawal address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*xnivNgQEgFD5lq3M" /><figcaption>Fig. 5: PRT Honeypot Withdrawal flow</figcaption></figure><ul><li><strong>Claim Submission Flow:</strong></li></ul><p>Claims are automatically submitted by the node at the end of each epoch without the intervention of the users running the node. A claim consists of a cryptographic hash representing the application’s state at the epoch’s end, along with validated outputs (vouchers and notices) processed during the epoch. The epoch described in this case is different from the default epoch on Ethereum. For the Cartesi node, an epoch is a configurable period during which nodes process inputs before submitting the updated application state to the base layer. While this epoch is freely configurable, it’s best practice to have this set to seven days. For the Honeypot application, this is configured to seven days, meaning that every seven days, each active node submits a cryptographic hash of its state to the `<strong>joinTournament</strong>` function in the tournament contract for that epoch.</p><ul><li><strong>Dispute Resolution Flow:</strong></li></ul><p>In situations where conflicting state hashes are submitted for an epoch, possibly due to a validator executing a different or incorrect computation, the tournament contract pairs the conflicting state hashes and begins a three-level tournament bisection game between the two state hashes. Each level of the tournament bisection game is a binary search over the intermediate state hashes proposed by validators supporting each state hash. At each step in the binary search, the validator defending each state hash is expected to submit the intermediate state hash for that step, which the tournament contract compares. The process continues till the step where the first disagreement between these two validators is identified. The tournament contract then efficiently re-executes that specific step to identify the correct state hash for that step. Once the valid state hash is identified, the dishonest or invalid state hash is discarded, while the other state hash is accepted as the state hash for that epoch.</p><p>If multiple conflicting state hashes are submitted to an epoch, they are paired, and each pair undergoes the multilevel tournament process. At the end, about 50% of the total invalid state hashes are eliminated, and the surviving 50% are paired once more, and the tournament process is repeated. This process continues repeatedly, effectively slashing the invalid state hashes by half each time until a single valid state hash remains.</p><p>In situations where there is just a single state hash for that epoch, the tournament is concluded after seven days and a few hours and the single standing claim is declared the winner.</p><p>Once a tournament is concluded and the valid proof identified, any validator can then call the `<strong>settle</strong>` function in the PRT Consensus contract, passing the winning state hash to finalize the epoch and deploy the Tournament Contract for the next epoch.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FV_S5X_FlFkY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DV_S5X_FlFkY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FV_S5X_FlFkY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8613618274b573914d3a1b95165f577/href">https://medium.com/media/d8613618274b573914d3a1b95165f577/href</a></iframe><p><strong>Conclusion</strong></p><p>The Cartesi PRT honeypot is more than just a bounty challenge; it represents an innovative approach to achieving consensus in decentralised applications. By integrating the PRT fraud-proof system with the Cartesi rollups framework, this application stands out as the first application to implement the most efficient consensus mechanisms, ensuring that a single honest validator can uphold a valid app state against an overwhelming amount of dishonest validators.</p><p>That said, no system should ever be considered completely infallible. The Honeypot exists precisely because Cartesi embraces transparency: it invites developers, auditors, and hackers to rigorously test its infrastructure, identify flaws, and push the system to its limits. The rewards are both educational and financial. Successfully cracking the honeypot means <strong>you walk away with all the tokens contained in the vault,</strong> currently valued at over <strong>$1,000 in CTSI and growing</strong>.</p><p>But beyond the financial incentive, true value also lies in the technical insights you gain. For developers, security researchers, or auditors, understanding PRT and the honeypot’s architecture is one of the best ways to understand how next-generation consensus and fraud proofs can be applied not just for Cartesi applications but in other ecosystems as well.</p><p>In addition to this guide, also check out my article<a href="https://medium.com/@idogwuchi/prt-fraud-proof-for-non-mathematicians-f1d13fd37f2d"> <em>PRT for Non-Mathematicians</em></a> which breaks down the process flow of the Permissionless Refereed Tournament (PRT) in a simple, understandable way. Also check out the Cartesi documentation and the honeypot GitHub repository for more insights into PRT and the honeypot.</p><p>Happy Hacking!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ffd7b12db2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PRT FRAUD PROOF FOR NON-MATHEMATICIANS]]></title>
            <link>https://medium.com/@idogwuchi/prt-fraud-proof-for-non-mathematicians-f1d13fd37f2d?source=rss-a9abcdd90f1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1d13fd37f2d</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[fraud-proof]]></category>
            <category><![CDATA[consensus-algorithm]]></category>
            <category><![CDATA[cartesi]]></category>
            <dc:creator><![CDATA[Idogwu Chinonso]]></dc:creator>
            <pubDate>Tue, 29 Jul 2025 11:16:51 GMT</pubDate>
            <atom:updated>2025-07-29T22:40:30.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kCju-Um9EWldUzohtoLpEg.png" /></figure><h4><strong>Introduction</strong></h4><p>The need to scale programmable blockchains has created a strong demand for secure ways to offload computations outside the blockchain. One of the most popular options today is called rollups. Rollups involve off-chain nodes executing these offloaded computations, then proving the results back to the base layer. This is a good approach to solving the scalability issue, as these off-chain computers are not constrained by the limitations of the blockchain network. They, therefore, can be more specialised, faster and better equipped to handle complex transactions.</p><p>The decentralised and permissionless nature of the blockchain introduces new challenges. Anyone should be able to run one of these off-chain nodes, process computations and submit results to the base layer. The big question then is: How then do we handle conflicting results between these multiple off-chain validators? Or more importantly, how do these more computationally capable validators prove to a less computationally capable on-chain virtual machine that their execution is accurate even when others disagree?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*-BZS-YFsr8n53MrfLb-iwA.png" /><figcaption>Fig 1: Off-chain validator and on-chain virtual machine interaction</figcaption></figure><p>One of the simplest ways to determine correctness among multiple claims is a simple majority rule consensus, where all participants provide the result of a computation and the result that appears most frequently gets accepted. While this may look valid, it offers no protection against a dishonest majority and is susceptible to Sybil attacks, where an attacker sets up multiple fake validators to overwhelm the network and then posts a false result using them. To mitigate such risks, a number of more robust methods to identify a valid result among multiple others have been developed, and two of the most widely used are validity and fraud proofs. Validity proofs are very computationally intensive to generate, requiring that the proving machine meet high performance requirements to produce a proof. Fraud proofs, on the other hand, optimistically treat claims as valid but offer a time window for honest participants to challenge/dispute said claim. Thereby requiring less computationally intensive computers to run as compared to validity proofs.</p><p>While both validity and fraud proof offer strong points and trade-offs over the other, we’ll be focusing solely on just one of them, being fraud proof.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0q87LUs7OoGSHrVSfc5h5w.png" /><figcaption>Fig 2: Validity vs Fraud proofs</figcaption></figure><p>Fraud proofs generally fall into two categories: interactive and non-interactive. While both of them optimistically treat claims as valid, they differ in how disputes are handled. In interactive fraud proofs, the resolution process involves a back-and-forth exchange between the validator and his challenger. This interaction spans over multiple rounds or tournaments. Non-interactive fraud proofs, by contrast, rely on a single self-contained proof that is submitted without requiring multiple rounds of interaction.</p><p>Interactive fraud proofs generally allow an honest validator to challenge incorrect results submitted by other validators. This is done by initiating a dispute, where both parties present evidence, and an on-chain smart contract acts as a judge. It uses a predefined dispute resolution algorithm to guide the resolution process and determine which party is correct.</p><p>In this article, we’ll focus on one of the most effective dispute resolution algorithms available today: PRT (Permissionless Refereed Tournament). PRT is an interactive and scalable, fraud-proof system designed to efficiently identify the correct result, even in large networks with many conflicting claims. PRT’s scalable feature ensures that the system remains performant and accurate regardless of the number of Sybils or dishonest participants, as long as a single honest participant exists.</p><h4><strong>PRT FRAUD PROOF</strong></h4><p>PRT (Permissionless Refereed Tournaments) is a fraud-proof algorithm developed by <strong>Diego Nehab</strong> and <strong>Augusto Teixeira</strong>, two researchers at <strong>Cartesi</strong> and <strong>IMPA. </strong>At its core, PRT allows a <strong>single honest validator</strong> to enforce the correct result of a computation against a multitude of other false claims. Today, it’s regarded as one of the most decentralised and secure fraud-proof mechanisms, and in a couple of minutes we’ll understand why and how it works. <br>Before discussing more, it’s important to understand off-chain computations and certain fundamental assumptions for understanding PRT. We’ll review these through these three questions:</p><p><strong><em>1). How can off-chain validators be expected to arrive at the same result, especially when they are distributed and independently operated?</em></strong></p><p>To ensure verifiability, all validators run the same deterministic virtual machine, meaning that with the same input and state, they always produce the same output.</p><p>To make the outcome of each computation traceable and verifiable, these validators maintain a state commitment over their entire state. A state commitment is a hash that uniquely represents the entire memory state of a machine at a given time. This commitment allows anyone to verify that a machine transitioned from one valid state to another without inspecting the full memory.</p><p>Various data structures such as Merkle trees, Verkle trees, Patricia trees, and KZG commitments can be used to efficiently organise state data and compute these state commitments efficiently, but for the purpose of this article, we’ll be focusing on the widely used Merkle tree approach.</p><p>To visualise this, imagine the machine’s memory as a large shelf made up of individual compartments; each compartment (sometimes called a “slot” or “word”) holds a piece of information such as data, a value, a register, or an instruction. A Merkle tree organises these compartments in a way that allows you to generate one final “root hash” that summarises everything on the shelf. This is achieved by concurrently pairing and hashing these slots until a final root hash is obtained. Even a tiny change in one compartment causes the root hash to change, so if two machines produce the same root hash, we can be confident they ran the same computation and ended up in the same state.</p><p>This use of Merkle trees not only secures the memory but also enables rapid and efficient verification of memory contents without needing access to the entire memory.</p><p>The diagram below shows a basic example of this: it compares the memory state before and after adding the values from slots x0 and x2, then saving the result to slot x4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pj-yQiLXPfXYrrxZ9twSZQ.png" /><figcaption>Fig 3: Sample memory state comparison before and after running an execution</figcaption></figure><p><strong><em>2). How are transactions executed in this deterministic virtual machine?</em></strong></p><p>Deterministic environments are built so that no matter who runs a program, it will always produce the same result, so long as the input and initial state are the same. These environments process instructions one step at a time and track every memory change carefully.</p><p>Let’s take a simple maths expression as an example:</p><p><strong>(5 × 3) + (8 × 2)</strong>.</p><p>This is a high-level instruction a user wants to execute in a deterministic machine. A deterministic virtual machine wouldn’t just jump to the final answer. Instead, it would break this down into individual steps (low-level instructions), like loading values into memory, multiplying them, adding the results, and saving the final output. Each of these steps is recorded in what’s called an execution trace, a log of what the machine did at each step.</p><p>Here’s how that trace might look, using simplified labels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*MWAvLLrzzZPEQ3LDimyJ1Q.png" /><figcaption>Tab 1: Sample trace log of the execution of a simple maths expression</figcaption></figure><p>At each step, the machine updates its memory and generates a new Merkle root that summarises the memory’s state. This root acts like a fingerprint of the machine’s memory at that moment. So, instead of revealing the entire memory to prove what changed, a small Merkle proof can be used to show that a specific value changed correctly, based on its position in memory.</p><p>In the rest of this article, we will be making reference and basing our dispute on these execution steps above.</p><p><strong><em>3). How are computation results submitted to the base layer?</em></strong></p><p>At this point, we understand how computations are executed and how a log or Merkle proof of every state transition is generated. It’s now important we understand how computation results are submitted back to the base layer.</p><p>In addition to using a virtual machine, rollups use consensus contracts on the base layer to verify off-chain computations. These contracts do not rerun the full computation. But use a simplified logic to verify small steps. Verification is done on the submitted claims using trace data and Merkle proofs. This allows the consensus contract, <strong>which we’ll be referring to in this article as the verifier or referee,</strong> to confirm that a specific instruction was executed correctly, without needing to examine the full memory.</p><h4><strong>How PRT resolves disputes:</strong></h4><p>Now that we understand that every off-chain validator in a rollup protocol runs the same set of executions and should naturally return the same results and also how they each submit their result back to the base layer, it’s time to go a bit deeper and discuss how PRT handles conflicting results and disputes.</p><p>Remember from our earlier conversation, we mentioned that PRT enables a single honest prover to successfully defend a correct result against multiple false results. Let’s illustrate this using our already explained mathematical computation request:</p><p><strong>(5×3)+(8×2)</strong></p><p>This example will be based on 4 off-chain validators, Bob, Alice, Lex, and Matt, of whom Bob is honest, while Alice, Lex, and Matt are all dishonest. Bob runs the execution and has an accurate final result of 31, while Alice, Matt, and Lex all come up with incorrect results of 175, 50, and 70, respectively.</p><p>For final submission of results back to the base layer, PRT requests that each of the 4 participants submit three data sets to the verifier; these are the final state hash, the computation hash and a Merkle proof that the final state hash is part of the computation hash. We’ll be focusing on just 3 of these, as they fall within the scope of our discussion.</p><ol><li><strong>Final state hash: </strong>This is the root hash of a Merkle tree of all the storage slots of the off-chain VM after the complete execution; it represents the final state of the machine after the computation.</li><li><strong>Computation Hash: </strong>This is the root hash for a Merkle tree of the state hash after every step of the computation. Our model has 8 steps, so this would be a Merkle tree of 8 initial leaves, each representing the state of the machine after each step. What this means is that after every step, the off-chain VM generates a Merkle tree of its storage slots. At the end of the computation, we have 8 Merkle trees, one for each step, and then the root of each of the 8 Merkle trees is used to generate a new Merkle tree whose root becomes the computation hash.</li><li><strong>Merkle proof: </strong>This is a Merkle proof that is used by the verifier to confirm that the submitted final state hash is part of the leaves recursively hashed to obtain the computation hash.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrmEOA5DnMIV8EbTMNFn4g.png" /><figcaption>Fig 4: Sample merkle tree for computation and final state hash generation</figcaption></figure><p>The Verifier contract, on receiving these different result claims, pairs them up as they arrive. Let’s say Alice sends her result first, followed by Bob, Lex, and Matt; they are then grouped in pairs as they arrive into <strong>Alice X Bob</strong> and <strong>Lex X Matt</strong>. Each pair begins a dispute tournament, as explained below.</p><p>For each pair, the verifier performs a binary search over the STEPS to find a bisection where both opponents agree on a previous state hash but conflict in the next state hash. To understand this better, let’s narrow down to <strong>Bob X Alice’s battle</strong>. From the table below showing the STEP trace of Bob and Alice, it’s clear that they were both in sync until step 5, where Alice loads 20 instead of 2 to memory slot x5, thereby causing the state from that step forward to differ from what Bob proposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*40acbY2k4jOZe8_VM8uJdA.png" /><figcaption>Tab 2: Sample trace log detailing the execution trace for Bob and Alice</figcaption></figure><p>The verifier starts the binary search between for Bob X Alice at the mid-step, being step 4. It proceeds to ask both participants to present the state hash at step 4 and a Merkle proof that this state hash is contained in the initial <strong>computation hash </strong>submitted. Remember that the computation hash is a Merkle root of all the state hashes in the steps. This would ensure that no participant can present a random state hash during the dispute, as every hash presented is verified to be contained in the initial computation hash presented.</p><p>Both Bob and Alice present the state hash and Merkle proof for step 4 and since they both ran the same execution, they would have the same hash, so the verifier knows that the conflicting step happens somewhere after step 4. The verifier therefore adjusts the lower band of the binary search to 5 and the higher band remains at 8. This time the binary search lands at step 6, so the verifier proceeds to ask both parties once again for the state hash and the Merkle proof of state 6, which they both provide, and the verifier confirms that there’s a conflicting state hash at step 6.</p><p>It’s now obvious to the verifier that since there’s a conflicting hash at step 6 and a matching hash at step 4, the error likely happens between steps 6 and 4, so it adjusts and asks both parties to present the state hash and proof of step 5. After this presentation, the verifier confirms that there’s a conflicting hash in step 5. Since both Bob and Alice present the same hash in step 4 and a different hash in step 5, it means one or even both parties must have altered the normal execution flow in step 5.</p><p>On identifying the false proof, the verifier asks both parties to present the following:</p><ul><li><strong>The exact instruction ran:</strong> In our case, for step 5, Bob ran “Load 2 into slot x5,” while Alice ran “Load 20 into slot x5.”</li><li><strong>Merkle proof of every state accessed</strong>: This is a Merkle proof verifying that every storage slot read and used during that execution STEP was present in the previous state hash, and also every storage slot written to is present in the current state hash.</li></ul><p>We expect Bob to present a Merkle proof that “2 was loaded to slot x5,” which the verifier confirms using the root hash of STEP 5. Meanwhile, if Alice lies that she “loaded 2 into slot x5,” she’ll need to present a Merkle proof that will be run against the state root hash of STEP 5 and since she added 20, not 2, she’ll definitely be unable to present a proof that would verify that 2 was loaded.</p><p>Even if Alice can generate a proof for loading the correct value, she’ll end up getting in the same state hash as the honest machine (Bob), since that’s the only modified state in the STEP. However, if she admits that she “loaded 20 into slot x5” and presents honest proof of that, then this is confirmed to be true, but the verifier can tell that the expected execution for that step was to “load 2 to slot x5,” meaning she gets caught.</p><p>Alice is identified as dishonest and kicked out of the tournament. While at the same time, either Lex or Matt wins their match, and the other is kicked off, leaving just two validators in the tournament.</p><p>Let’s say Matt survived the tournament despite also being dishonest (this mostly happens if Lex lies in an earlier step compared to Matt and therefore is caught earlier than Matt). The surviving participants in this level are then grouped once more, and a new round of battle begins between<strong> Bob X Matt</strong>. The verifier goes through the entire process of carrying out a binary search to find the exact STEP in which they both present their first conflicting claim, then goes further to verify the process ran in that STEP, and as expected, Matt is caught and eliminated, leaving Bob as the final winner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MtM_WU9ZI67s1VMOI7wwoQ.png" /><figcaption>Fig 5: Tournament representation of PRT</figcaption></figure><p>As we can see from our sample model, a single honest machine, Bob, is able to defend a valid state hash against 3 other dishonest validators.</p><h4><strong>PRT 2 Levels:</strong></h4><p>While the explanation so far provides a solid foundation for understanding PRT’s structure and resolution process, it’s important to note that a single-level implementation (PRT 1L) would be too expensive and burdensome for the off-chain validators. This is because the kinds of complex computations that typically require off-chain validation are rarely simple; they often involve millions or billions of big steps, each composed of many micro-steps, like the example previously described.</p><p>Attempting to resolve real-world disputes using only PRT 1L would mean building a computation hash after every step of execution. For complex computations, often comprising billions or even trillions of steps, this would impose an immense computational load on validators. As a result, the process becomes too expensive and inefficient, especially for verifiers tasked with validating long-running or resource-intensive transactions.</p><p>To address this inefficiency, PRT 2L was introduced. The core idea behind PRT 2L remains similar to 1L: validators process off-chain requests and produce a computation hash. However, instead of doing so after every individual step, a sparse computation hash is generated after a large number of big steps; for example, a sparse computation hash can be generated after every 32,000 big steps (state transitions). This drastically reduces the overhead of generating Merkle proofs for every transition.</p><p>These 32k-interval state hashes are then compiled into a Merkle tree (i.e., a computation hash) to produce a final state commitment, which is submitted as a commitment to the verifier. The verifier, upon receiving multiple submissions, pairs them and feeds each pair into a two-level interactive dispute resolution tournament.</p><ul><li><strong>Level 1: Top Level</strong></li></ul><p>At the first level, a binary search is carried out over the sparse computation hashes that were submitted. The verifier performs a binary search across this range from 0 to the total number of sparse computation hashes to identify the exact hash where the bisection occurred. This process closely resembles the original PRT 1L approach, where at a point in the binary search, the verifier requests state hashes and corresponding proofs from the validators, verifies them, then updates the binary search range (either upper or lower bound) accordingly, until the exact interval where the disagreement occurs is pinpointed. This divergence represents a block of 32,000 state transitions, so narrowing down to one still leaves a full interval in which the disagreement lies.</p><p>Once this interval is identified, the verifier escalates the pair by recursively creating a new tournament; this new tournament is called the second-level tournament or Level 2 tournament.</p><ul><li><strong>Level 2: Bottom Level</strong></li></ul><p>This is the final stage of the tournament. By this point, we’ve narrowed down the dispute to a specific 32,000-step interval out of the original millions of state transitions. In this round, the verifier performs a binary search within that 32k range, requesting the computation hash and corresponding Merkle proof at each step it inspects. This process continues until the exact step at which the bisection occurs is found. Once this is identified, similar to PRT 1L, the verifier proceeds to check the execution logs and then identifies which of the pair is honest and which isn’t.</p><p>Transitioning from a single-level (PRT-1L) to a two-level (PRT-2L) dispute system significantly reduces the burden on both the validator and the verifier. Rather than performing a binary search over, say, ten million steps, the system narrows it down to just a few dozen hashes at the first level and then performs a more focused search in the second level. This drastically cuts down the number of interactions required for validators to submit computation hashes and Merkle proofs, leading to substantial savings in both computational effort and on-chain gas costs.</p><h4><strong>PRT 3 Levels and the Cartesi Honeypot:</strong></h4><p>The Cartesi Honeypot, currently deployed on both Mainnet and Sepolia, is the first real-world application utilising the PRT fraud-proof system. This application adopts a modified version of the standard PRT algorithm, which we’ll now refer to as <strong>PRT 3 Levels</strong>, in contrast to the earlier <strong>PRT 1 Level</strong> and <strong>PRT 2 Level</strong> approaches.</p><p>While the core components, such as off-chain computation, on-chain verification, and a consensus contract serving as the referee, remain unchanged, the major difference in PRT 3L is its tournament-level structure. In PRT 1L, disputes are resolved through a single-level binary search. PRT 2L improved on this by introducing a two-level structure; PRT 3L extends this idea by further adding a third level, making the process even more scalable.</p><p>With PRT 3L, computation hashes are generated even more sparsely when compared to PRT 2L; for example, a computation hash could be generated once every one million big steps. Thereby creating much larger intervals compared to the 32,000 big step intervals in PRT 2L. In PRT 3L, <strong>Level 1</strong> performs a binary search across these 1 million-step sparse computation hashes, significantly reducing the number of top-level checkpoints, while <strong>Level 2</strong> narrows the search to another smaller chunk of sparse computation hashes, for example, computation hashes generated after 128 big steps within the initially identified 1 million big step intervals. Finally, <strong>Level 3</strong> then carries out a fine-grained binary search over the final 128 big steps to pinpoint the exact step where divergence occurs.</p><p>This three-level structure, when compared to previous versions, drastically reduces the number of required interactions and on-chain operations, making it more efficient for handling very large computations.</p><h4><strong>Conclusion</strong></h4><p>Fraud-proof systems like PRT offer a powerful foundation for scaling decentralised systems by enabling secure, permissionless computation without requiring trust in any single participant. They ensure that correctness can be enforced not by majority rule but by verifiable truth, protecting networks from manipulation and maintaining integrity at scale.</p><p>While there are currently multiple fraud-proof algorithms available, PRT stands out for its ability to handle large numbers of participants, resolve disputes step-by-step, and also empower honest provers to win even in the face of many dishonest claims.</p><p>So far, we’ve explored how PRT works and visualised its step-by-step dispute resolution process. In upcoming articles, we’ll dive into <strong>DAVE</strong>, an advanced evolution of PRT. It introduces key optimisations and addresses certain limitations that could help PRT even scale better.</p><h4>REFERENCE</h4><p>Ne­hab, D., &amp; Teixeira, A. (2022, December 23). <em>Permissionless Refereed Tournaments</em> (arXiv:2212.12439). arXiv. <a href="https://doi.org/10.48550/arXiv.2212.12439">https://doi.org/10.48550/arXiv.2212.12439</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1d13fd37f2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Cartesi dApps with XMTP: Bridging decentralised computation and secured communication.]]></title>
            <link>https://medium.com/@idogwuchi/integrating-cartesi-dapps-with-xmtp-bridging-decentralised-computation-and-secured-communication-360fa7bdb1d1?source=rss-a9abcdd90f1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/360fa7bdb1d1</guid>
            <category><![CDATA[cartesi]]></category>
            <category><![CDATA[cartesi-rollups]]></category>
            <category><![CDATA[xmtp]]></category>
            <category><![CDATA[modular-architecture]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[Idogwu Chinonso]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 16:13:36 GMT</pubDate>
            <atom:updated>2024-08-29T16:46:58.185Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Co-Author: </strong><a href="https://medium.com/@riseandshaheen"><strong>Shaheen Ahmed</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LK3v7GV5c0BwSOe5BcpJFg.jpeg" /></figure><p>In this rapidly exploding era of interoperability and modular narrative, we’ve experienced increasing demands for integration between protocols supporting the modular narrative. We’ve also begun to see protocols built around the idea of modular architecture and interconnectivity. Execution layers, data availability layers, communication layers are becoming increasingly popular and we can see crazy projects and ideas around, leveraging the interconnection of these different modular components to build really exciting things.</p><p>In this article, we’ll be looking at one of such integrations between Cartesi an app-specific rollup and XMTP, a secure messaging layer for web3. By integrating dApps on Cartesi with XMTP, developers can create applications that not only leverage Cartesi’s off-chain computation capabilities but also incorporate secure, decentralised messaging. This combination opens up new possibilities for dApps on cartesi to implement more functionalities and also improve the user experience on these dApps. We will explore the process of integrating dApps on Cartesi with XMTP, highlighting the benefits and use cases of such integration. Whether you’re building a complex dApp that requires heavy computation or a messaging platform with robust privacy guarantees, this integration can provide a powerful foundation for your Cartesi project.</p><p>To keep this article as simple as possible we assume that you understand the basics of building on cartesi and also the importance, capabilities and limitations of <em>Notices</em> on Cartesi. We’ll be focusing on the components necessary for integrating Cartesi and XMTP and not on building a Cartesi dApp.</p><p><strong>Architecture:</strong></p><p>Integrating your Cartesi dApp with XMTP requires 3 different components, some of which you’ll need to write from scratch yourself while others you just integrate into your application through SDK. These components are;</p><ul><li><strong>The Cartesi dApp backend: </strong>This is any dApp written by the programmer in any language supported by Cartesi. The logic and execution in this dApp do not affect the integration in any way though for this particular example, the backend needs to be able to send properly structured notice to the GraphQL server which will further be relayed to the XMTP network.</li><li><strong>The Relayer Server:</strong> As you already know, dApps on Cartesi are sandboxed and therefore unable to interact with external servers or protocols. The XMTP protocol, on the other end, is a network of its own, dedicated to providing a secure protocol for messaging; therefore, there is a need for an external component which would be able to read data from dApps on Cartesi in real time and then relay these data to the expected destination on the XMTP network. This component plays a vital role of being the bridge between dApps on Cartesi and the XMTP network. It’s able to listen actively for requests from the Cartesi dApp and then forward these messages promptly to the destination address on XMTP.<br><strong><em>It’s important to note that while this component is crucial for this integration, it also introduces a degree of centralization to the project as this server is fully owned and controlled by the developer. We’re open to contributions and suggestions that help in decentralising this component.</em></strong></li><li><strong>The XMTP Network: </strong>This layer in the architecture is outside the control of the developer. This is the messaging protocol that handles and displays messages between different users. The relayer server interacts with this layer to relay messages from the Cartesi dApp, which the target user can pick up on the XMTP network.</li></ul><p>At the end of the day, we have an architecture similar to what’s shown below, where a user interacts with a Cartesi dApp and if necessary, a specially structured Notice is sent to the GraphQL server, which is further picked up by the relayer, destructured, and then relayed to the destination address on XMTP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*31ybciVJKbuVuAZkPOaiNQ.jpeg" /><figcaption>Cartesi — XMTP integration Architecture</figcaption></figure><p><strong>Deep Dive into the Relayer Server:</strong></p><p>At this point, it’s expected that you should have an understanding of the structure and functionalities of the relayer server. In this section, we’ll be taking things a little further by explaining in more detail the structure and components of the relayer server. For the sake of this integration, we developed a simple MVP for the relayer server. This should be seen as an MVP and not a fixed structure. We highly encourage developers to further modify this code to implement more complex functionalities and also better tailor the relayer to serve their dApp.</p><p>The relayer is divided into two (2<em>)</em> sections: the GraphQl client and the XMTP client. The GraphQl client utilises Apollo SDK to listen on the Cartesi dApp GraphQL server for notices meant to be relayed to a target user on XMTP. On finding such a notice, the GraphQL client destructures this notice, then sends it to the XMTP-Client section. This section utilises the Ethers Js library to control a private key belonging to a wallet address that’s registered on XMTP and will serve as the origin of all messages relayed from your Cartesi dApp to target users on XMTP. In summary, the relayer listens for a new notice from the Cartesi dApp, destructures this notice, and then uses its private key to relay the message via the XMTP network. The target user basically receives a message on XMTP from the relayer address containing the information in the notice (message) that was sent from the Cartesi dApp.</p><p><strong>Sample Relayer Code:</strong></p><p>Since we’ve laid out a good foundation on the importance, components and function of the relayer, we’ll be solidifying that knowledge with a sample relayer codebase detailing the different sections and their functions. We believe this would go a long way to serve as a template that you could directly use or better still build on to achieve the same functionality of integrating messaging via XMTP in your dApp.</p><p><strong>Project Structure:</strong></p><p>In this example, our relayer server is written in Node JS and leverages other libraries and SDKs like Ethers JS and Apollo SDK for additional functionalities, so it’s important that you have Node properly installed before attempting to code along. For this project, we’re using a simplified version of the MVC model to structure the repo like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*GsKAe8guFpSkvFOTza9_OQ.png" /><figcaption>repo structure for the relayer</figcaption></figure><p>We have a parent folder called RELAYER inside which we have the ‘graphqlClient’ and the ‘server.js’ files in a folder called ‘src’. Just beside the src folder, we also have a controllers folder, which would house the ‘graphql.controller’ and the ‘xmtp.controller’ files. In the same directory level as the src, we also have a .env file whose contents we would be explaining later in this article.</p><p><strong>Project Dependencies:</strong></p><p>For the scope of this project, we would be utilising a very streamlined set of dependencies selected to simply meet the requirements of integrating these two protocols. In your case, you might want to add more dependencies as you modify this code base further.</p><p>We’ll be using the below set of dependencies for now;</p><pre>   &quot;@apollo/client&quot;: &quot;^3.11.4&quot;,<br>   &quot;@xmtp/xmtp-js&quot;: &quot;^12.1.0&quot;,<br>   &quot;cors&quot;: &quot;^2.8.5&quot;,<br>   &quot;dotenv&quot;: &quot;^16.4.5&quot;,<br>   &quot;ethers&quot;: &quot;^6.13.2&quot;,<br>   &quot;express&quot;: &quot;^4.19.2&quot;,<br>   &quot;graphql&quot;: &quot;^16.9.0&quot;,<br>   &quot;graphql-tag&quot;: &quot;^2.12.6&quot;,<br>   &quot;viem&quot;: &quot;^2.19.6&quot;,</pre><ul><li><strong>.env file:</strong></li></ul><p>To make it easier to quickly modify some important variables that are used in the server and also to protect some private data, we’ve pushed a couple of variables to the .env file present in the repo:</p><pre>PRIVATE_KEY=&lt;private key for an evm wallet&gt;<br>PRIVATE_KEY2=&lt;private key for another evm wallet&gt;<br>URI=&#39;http://localhost:8080/graphql&#39;<br>POOL_INTERVAL=6000</pre><p>The above structure is what the out .env file should look like. `PRIVATE_KEY` represents the private key for an Ethereum wallet, which the server would use to relay messages to target addresses on XMTP. The `PRIVATE_KEY2` variable is a substitute target address; messages that are meant to be sent to users who unfortunately are not registered on XMTP are relayed to this address. This way, these messages are not lost but sent to a secured point from which they can be picked up and handled by the developer in any ways necessary so as to get these notifications to the target users. Next is the `URI` This is the URI of our cartesi dApp graphql server, If you’re running on localhost, you should have the same URI as in the section above but once you move to testnet or mainnet, you should change the URI to that of your testnet or mainnet application. Finally, we have the `POOL_INTERVAL`; this sets the interval in milliseconds between successive calls to the GraphQL URI, a lower amount represents faster pooling intervals, while a larger number represents a much slower polling interval.</p><ul><li><strong>Server.js file:</strong></li></ul><p>This is a simple express server running on PORT 3000. It also imports and calls the `fetchAndSendLatestNotice` function, which contains the main logic and functionalities of the server.</p><pre>const express = require(&#39;express&#39;);<br>const cors = require(&#39;cors&#39;);<br>const app = express();<br>const [fetchAndSendLatestNotice] = require(&#39;./graphqlClient.js&#39;);<br><br>const PORT = 3000;<br><br>app.use(cors());<br>app.use(express.json());<br><br><br><br>app.get(&#39;/test&#39;, function (req, res) {<br>    res.send(&#39;GraphQL listener is running. Check the console for notices.&#39;);<br>})<br><br>app.listen(PORT, function () {<br>    console.log(`server listening on port ${PORT}`);<br>});<br><br><br>fetchAndSendLatestNotice();</pre><ul><li><strong>graphqlClient.js file:</strong></li></ul><p>This contains the necessary Apollo sdk implementations and functionalities to poll notices from the graphQl url that was included in the .env file. Its sole purpose is to poll notices from the GraphQl server, then send these notices to be filtered and sorted out based on implementations in the ‘graphql.controller ’file.</p><pre>const { ApolloClient, InMemoryCache, ApolloProvider, gql } = require(&#39;@apollo/client&#39;);<br>const filterNotices = require(&#39;./controllers/graphql.controller&#39;);<br>require(&#39;dotenv&#39;).config();<br><br>/// @variable This is the url of a cartesi dApp subgraph as contained in the .env file.<br>const URI = process.env.URI;<br><br>/// @variable This is the interval in milliseconds at which the fetchAndSendLatestNotice function should be called.<br>const POOL_INTERVAL = process.env.POOL_INTERVAL;<br><br>/// @title fetchAndSendLatestNotice<br>/// @notice This function is a continues loop that periodically calls the graphql server based on the time interval specified in the .env file<br>async function fetchAndSendLatestNotice() {<br><br>    /// @notice Apollo SDK setup for an interaction client, it consimes the subgraph URI specified in the .env file<br>    const client = new ApolloClient({<br>        uri: URI,<br>        cache: new InMemoryCache(),<br>        fetch,<br>    });<br><br>    /// @notice Simplified query stucture to fetch all the notices from a Cartesi dApp graphql server<br>    const NOTICES_QUERY = gql`<br>            query notices {<br>            notices {<br>                edges {<br>                node {<br>                    index<br>                    input {<br>                    index<br>                    }<br>                    payload<br>                }<br>                }<br>            }<br>            }<br>    `;<br><br>    /// @notice Simple Interval loop that utilizes Apollo SDK to periodically fetch all the notices from a Cartesi dApp<br>    /// @notice Collected Notices are passed to the filterNotice function for further processing.<br>    setInterval(() =&gt; {<br>        client<br>            .query({<br>                query: NOTICES_QUERY,<br>                fetchPolicy: &#39;network-only&#39;,<br>            })<br>            .then(response =&gt; {<br>                const edges = response.data.notices.edges;<br>                filterNotices(edges);<br>            })<br>            .catch(error =&gt; {<br>                console.error(&#39;Polling error:&#39;, error);<br>            });<br>    }, POOL_INTERVAL);<br><br>}<br><br>module.exports = [fetchAndSendLatestNotice];</pre><ul><li><strong>graphql.controller.js file:</strong></li></ul><p>This section of the code plays a vital role in the functionality of this project. It tracks the index of the last notice that was parsed so as to prevent excessive and repeated relaying of old notices. It also filters the notices picked up from the GraphQL server in a way that previously analysed notices are skipped while more recent notices are destructured and then compared against an expected object structure.</p><pre>{<br>       TxType: &#39;InAppMessage&#39;,<br>       Origin: &#39;sender address&#39;,<br>       Destination: &#39;receiver address&#39;,<br>       Payload: &#39;message to be sent&#39;,<br>}</pre><p>Notices that meet this structure are then sent to the `xmtp.controller.js` contained functions.</p><pre>const ethers = require(&#39;ethers&#39;);<br>const viem = require(&#39;viem&#39;);<br>const sendNotice = require(&#39;./xmtp.controller.js&#39;);<br><br>/// @variable This keeps track of the index of the last notice that was sent out.<br>let lastAnalysedNotice = 0;<br><br>/// @title filterNotices<br>/// @notice This function extracts out notifications that have already been previously handled by the server based on the stored index (lastAnalysedNotice).<br>/// @notice Notices that have not been previously handled by the server are sent to the decodeNotice function<br>/// @param notices An array of all Notices from a subgraph server<br>function filterNotices(notices) {<br>    if (notices.length &gt; 0) {<br>        let slicedNotices = notices.slice(lastAnalysedNotice);<br>        lastAnalysedNotice = notices.length;<br>        for (let notice of slicedNotices) {<br>            decodeNotice(notice);<br>        }<br>    } else {<br>        console.log(&#39;No new notices found.&#39;);<br>    }<br>}<br><br>/// @title decodeNotice<br>/// @notice This function converts notices from hex to object notations, destructures them, then checks if they&#39;re ment to be relayed via XMTP network<br>/// @notice notices containing payload to be relayed via XMTP network are sent to the sendNotices function<br>/// @param notice A single Notices from a subgraph server<br>function decodeNotice(notice) {<br>    let payload = ethers.toUtf8String((notice.node.payload).toString());<br>    payload = JSON.parse(payload);<br>    console.log(payload);<br><br>    let TxType = payload.TxType;<br>    let Origin = payload.Origin;<br>    let Destination = payload.Destination;<br>    let Payload = payload.Payload;<br><br>    if (TxType === &#39;InAppMessage&#39;) {<br>        console.log(&#39;Received InAppMessage&#39;);<br>        sendNotice(Origin, Destination, Payload);<br>    }<br>}<br><br>module.exports = filterNotices;</pre><ul><li><strong>xmtp.controller.js file:</strong></li></ul><p>This is the final part of the codebase; it is the connection point between our server and the XMTP network. In this file we use the xmtp sdk to relay messages from the Cartesi dApp to target addresses on XMTP using the private key contained in our .env file.</p><pre>const { Client } = require(&#39;@xmtp/xmtp-js&#39;);<br>const { Wallet } = require(&#39;ethers&#39;);<br>require(&#39;dotenv&#39;).config();<br><br>/// @variable This is the private key belonging to the wallet that&#39;ll be used to relay messages from the dApp.<br>const PRIVATE_KEY = process.env.PRIVATE_KEY;<br><br>/// @variable This is the second private key belonging to a different wallet that&#39;ll be used to receive messages that were sent to addresses that are not active on XMTP this way they&#39;re not completely lost.<br>const PRIVATE_KEY2 = process.env.PRIVATE_KEY2;<br><br>let xmtp;<br><br>/// @title initializeXmtp<br>/// @notice This function uses a privatekey to get an account that will be used to create an active XMTP client for sending and receiving messages.<br>/// @param private_key Private key belonging to the wallet that&#39;s being used to setup an XMTP connection<br>async function initializeXmtp(private_key) {<br>    if (!xmtp) {<br>        try {<br>            const wallet = new Wallet(private_key);<br>            xmtp = await Client.create(wallet, { env: &#39;dev&#39; });<br>            return wallet.address;<br>        } catch (error) {<br>            console.error(&#39;Error initializing XMTP client:&#39;, error);<br>        }<br>    }<br>}<br><br>/// @title sendNotice<br>/// @notice This function checks if an address is active on XMTP then relays the message to destination adress else it relays the message to the fallback address.<br>/// @param Origin Address thats initiating the message<br>/// @param Destination Address the message is to be sent to<br>/// @param Payload message that&#39;s to be sent via XMTP<br>async function sendNotice(Origin, Destination, Payload) {<br>    try {<br>        await initializeXmtp(PRIVATE_KEY);<br><br>        const isOnNetwork = await Client.canMessage(<br>            Destination,<br>            { env: &quot;dev&quot; },<br>        );<br>        if (!isOnNetwork) {<br>            console.log(`Destination wallet is not on the network. Sending message to Fallback wallet......`);<br>            await initializeXmtp(PRIVATE_KEY2);<br>            const conversation = await xmtp.conversations.newConversation((new Wallet(PRIVATE_KEY2)).address);<br>            const messageContent = `Sender: ${Origin}, Message: ${Payload}`;<br>            const message = await conversation.send(messageContent);<br>            console.log(&#39;Message sent:&#39;, message);<br>        } else {<br>            const conversation = await xmtp.conversations.newConversation(Destination);<br>            const messageContent = `Sender: ${Origin}, Message: ${Payload}`;<br>            const message = await conversation.send(messageContent);<br>            console.log(&#39;Message sent:&#39;, message);<br>        }<br>    } catch (error) {<br>        console.error(&#39;Error sending message:&#39;, error);<br>    }<br>}<br><br>module.exports = sendNotice;</pre><p>At this point we have a fully functional server ready to pick up and relay notices from our Cartesi dApp to target addresses on XMTP. You can simply start your server by navigating into the src folder and running the command `node server.js`. The complete code base for this project, along with the template used in the demo video, can be found <a href="https://github.com/Mugen-Builders/xmtp-cartesi"><strong><em>HERE</em></strong></a>, while a demo video can be found <a href="https://x.com/riseandshaheen/status/1826965802664272008"><strong><em>HERE</em></strong></a>.</p><p>With this integration, you now have an endless list of possibilities that you can implement in your dApps, ranging from real-time notifications and callbacks in games to personalised alerts in Defi dApp. The use cases are just endless. Though it is important to note that target addresses for these messages need to be registered on XMTP, additional efforts might be needed in convincing and also helping your users register their addresses on XMTP.</p><p>Hopefully this article inspires and educates you enough to build a project leveraging the Cartesi and XMTP integration, If you’re ever in need of more ideas, education on other possible integrations or even facing challenges in your integrations, feel free to reach out or connect with the Developer Advocacy team on discord <strong><em>(</em></strong><a href="http://discord.gg/eZ6HehDzYK"><strong><em>Cartesi Community</em></strong></a><strong><em>)</em></strong>. We’ll be excited to hear from you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=360fa7bdb1d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Merkle Trees and Their Application in Bitcoin.]]></title>
            <link>https://medium.com/@idogwuchi/merkle-trees-and-their-application-in-bitcoin-88e82efca544?source=rss-a9abcdd90f1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/88e82efca544</guid>
            <category><![CDATA[merkle-tree]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Idogwu Chinonso]]></dc:creator>
            <pubDate>Wed, 06 Mar 2024 00:40:18 GMT</pubDate>
            <atom:updated>2024-03-06T00:40:18.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*_8Nn3g_TpMfQTTdeaT7srg.png" /><figcaption>Image credit: <a href="https://www.linkedin.com/in/syed-talal-musharraf/">Syed Talal Musharraf</a></figcaption></figure><p><strong>Introduction to Merkle Trees:</strong></p><p>Merkle trees, also known as binary hash trees, are a fundamental building block in blockchain architecture; they play a vital role in the efficiency, security, and integrity of the blockchain. Named after Ralph Merkle, who patented the concept in 1979, Merkle trees have extensive applications in various areas, with their significance particularly pronounced in blockchain networks.</p><p>At its core, a Merkle tree is a hierarchical data structure composed of hash values, designed to efficiently verify the integrity and consistency of large datasets. The structure resembles an inverted tree, where each leaf node is the hash of its child nodes, ultimately aggregating into a single root hash. This root hash serves as a compact and verifiable representation of the entire tree (dataset).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-1He61iK_3kr8EyTkEBgLA.png" /><figcaption>Image credit: Investopedia</figcaption></figure><p><strong>Anatomy of a Merkle Tree:</strong></p><p>To effectively breakdown and explain the anatomy of a Merkle tree, we will use the image above as an example and guide for better understanding. The Merkle tree image a few lines above is a Merkle tree generated from 8 transactions. We’ll be explaining the different components that make up this merkle tree, which are:</p><ol><li><strong>Leaf Nodes:</strong> These are individual data blocks, each representing a unique hash and in the case of bitcoin, they must be 32 bytes long. From the image, each of the blocks aside from the root hash can be seen as a leaf node.</li><li><strong>Child Nodes:</strong> These are all leaf nodes. Child nodes are used to refer to a pair of nodes that are concatenated and hashed to obtain a new node; these pairs of nodes are therefore said to be child nodes to the newly generated node. e.g., Ha and Hb from the example are child nodes of Hab. Children&#39;s nodes after concatenation are 64 bytes long; therefore, they must be hashed to reduce the size of the new leaf to 32 bytes.</li><li><strong>Parent Nodes: </strong>Moving up the tree, parent nodes are generated by concatenating and hashing pairs of child nodes. This process continues until a single root hash is computed, representing the entire dataset. e.g., Hab and Hcd are parent nodes to H(a-d).</li><li><strong>Root Node: </strong>The root node, located at the top of the tree, is the final block obtained after the continuous concatenation and hashing of pairs of data blocks until a single (final) block is obtained. Any alteration to any member of the dataset would bring about a change in the root hash. e.g., H (abcdefgh) is the root node of our example.</li></ol><p><strong>Generating a Merkle Root:</strong></p><p>In this section, we’ll focus on the step-by-step process of generating the merkle root of a group of 8 transactions (Ta — Th) similar to the merkle tree image displayed previously;</p><ul><li><strong>Step 1: Calculate the Hash of Individual Transactions: </strong>First, we need to calculate the hash for each transaction (Ta through Th). Each transaction is hashed individually using a cryptographic hash function, commonly SHA-256, to generate a new set of transactions (Ha—Hh).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O01xkKp8beoLcWV7EHZzrw.png" /></figure><ul><li><strong>Step 2: Construct Layer One of the Merkle Tree: </strong>Next, we combine the hashes of the transactions into pairs and hash them together to form the first layer of the Merkle tree (Hab, Hcd, Hef and Hgh).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j23B1LO8DzL7QvWK2XIfXQ.png" /></figure><ul><li><strong>Step 3: Construct Layer Two of the Merkle Tree: </strong>We continue this process, combining the hashes from the previous layer into pairs and hashing them together to form the second layer of the Merkle tree (Habcd and Hefgh).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DqFbPHGMVSYVczLrsj40_A.png" /></figure><p><strong>Step 4: Construct the Merkle Root:</strong></p><p>Finally, we combine the hashes from the second layer into pairs and hash them together to obtain the Merkle root.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pKjH2rHPRxG7Gi4q8BOeQg.png" /></figure><p>The Merkle root variable now holds the Merkle root of the group of 8 transactions. This single hash represents the entire set of transactions and can be used to verify that a specific transaction is included in the set by providing a Merkle path, which consists of the sibling hashes along the way from the transaction to the Merkle root.</p><p><strong>Generating a Merkle Path:</strong></p><p>To generate the Merkle path for a transaction (hash) in a Merkle tree, you need to trace back from the target leaf node to the root of the tree, collecting all the sibling nodes along the way. Each sibling node forms part of the Merkle path, which can be used to prove that a specific leaf node is included in the Merkle tree.</p><p>I understand that may be a lot to understand but let&#39;s break it down a bit. Let&#39;s generate the Merkel path of transaction Tb from the previous Merkel tree we generated in the previous section:</p><ul><li><strong>Step One:</strong> Identify the position of Te within the Merkle tree. Since Te is the 5th transaction out of 8 transactions, it’s at position 4 (since positions are zero-indexed).</li><li><strong>Step Two:</strong> First, we take into account the fact that Te is hashed into He, then we start at He and move up the tree to the root. At each level, find the sibling of the current node. For our example, He sibling would be the next transaction in the list, which is Hf.</li><li><strong>Step Three:</strong> Continue this process until reaching the root of the tree. At each level, record the sibling node’s hash.</li></ul><blockquote><em>level 1 → </em><strong><em>Sibling</em></strong><em> (</em><strong><em>Hf) → P</em></strong><em>arent</em><strong><em> (Hef);</em></strong></blockquote><blockquote><em>level 2 → </em><strong><em>Sibling</em></strong><em> (Hgh) → Parent (Hefgh);</em></blockquote><blockquote><em>level 3 → </em><strong><em>Sibling (Habcd)</em></strong><em> → Parent (Habcdefgh) (</em><strong><em>root</em></strong><em>)</em></blockquote><ul><li><strong>Step Four:</strong> The Merkle path for Tb consists of the hashes of all the siblings along the path to the root.</li></ul><blockquote><em>Merkle Path: (Hf → Hgh → Habcd);</em></blockquote><ul><li><strong>Step Five: </strong>To validate that Tb is indeed part of the Merkle tree, you would reconstruct the Merkle root by hashing (He) with its sibling (Hf) then hashing the result obtained with Hgh which will generate another hash value which we once again combine with Habcd then hash again. The final hash which is now obtained should match the known Merkle root of the tree.</li></ul><p>This method allows for efficient verification of the inclusion of individual transactions within a larger dataset without having to get the entire transactions in the merkle tree, as seen in the example above we can prove that transaction Te exists in the merkle tree above by just providing Te and 3 other hash value (<em>Merkle path</em>).</p><p><strong>Advantages of Utilizing Merkle Trees:</strong></p><ul><li><strong>Efficient Verification</strong>: Merkle trees make it possible to quickly and securely verify content across big datasets. A change in a single leaf (data) changes the root hash.</li><li><strong>Data Integrity</strong>: Merkle trees use hashes to keep the data constant and intact. Any attempt to change the data will result in a different hash, which is immediately visible.</li><li><strong>Scalability:</strong> Blockchains such as Bitcoin can accommodate a large number of transactions, and Merkle trees help to achieve this scalability by enabling for efficient verification of transaction history.</li><li><strong>Proof of Data Existence:</strong> Merkle trees allow for the construction of proof that a given piece of data is included in a certain block without revealing the complete information.</li></ul><p><strong>Applications of Merkle Trees in Blockchain:</strong></p><p>Merkle trees play a vital role in ensuring the security and immutability of blockchain networks. Here are some key applications:</p><p>1. <strong>Transaction Verification:</strong> The utilization of Merkle trees in blockchain transactions is an effective way to validate the inclusion of specific transactions within a block. By storing transaction hashes in leaf nodes and determining the root hash, participants may rapidly validate the legitimacy of transactions without having to traverse the entire block.</p><p>2. <strong>Block Validation:</strong> Merkle trees allow for quick validation of whole blocks in a blockchain network. By comparing the computed root hash in the block header hash, network participants can quickly determine the integrity of block contents, lowering the risk of manipulation or data damage.</p><p>3. <strong>Lightweight Client Verification:</strong> Merkle trees enable lightweight client verification, allowing nodes with limited processing resources to efficiently validate transactions and blocks. Merkle proofs allow lightweight clients to validate the inclusion of specific transactions in a block without downloading the full blockchain.</p><p><strong>Conclusion:</strong></p><p>From this article its visible that Merkle trees stands in as an efficient data structures in ensuring security, integrity, and scalability in the blockchain. The application of Merkle trees in Bitcoin improve and encourage confidence and trust in decentralised ecosystems, providing players with transparency in everything from transaction verification to lightweight client validation. As blockchain continues to improve sectors and also itself, Merkle trees remain critical, providing a solid basis for a more trust worthy and efficiently decentralised future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88e82efca544" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Your Own Encrypted Wallet: A Developer’s guide to playing in the mud.]]></title>
            <link>https://medium.com/@idogwuchi/building-your-own-encrypted-wallet-a-developers-guide-to-playing-in-the-mud-61cde41ceed9?source=rss-a9abcdd90f1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/61cde41ceed9</guid>
            <category><![CDATA[bitcoin-wallet]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[wallet]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <dc:creator><![CDATA[Idogwu Chinonso]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 18:49:47 GMT</pubDate>
            <atom:updated>2024-02-05T18:49:47.032Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Your Own Encrypted Wallet: A Developer’s Guide to Playing in the Mud.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PU9KGEcJUQ1x0hz01iNxkQ.jpeg" /></figure><p>Wallets are an important tool in blockchain architecture. This essential tool or application serves as the connection point between users and the blockchain itself. For non-developers, who account for a larger percentage of bitcoin users, most of their interaction with the blockchain occurs through a wallet, as their transactions must be signed using the private keys of an account, which is controlled by a wallet.Wallets are also important for holding and managing users’ assets (bitcoins) and as such, there’s a great need for proper security when it comes to building wallets. As of writing this article, there are lots of wallet architectures and mechanisms put in place to ensure the security of user’s assets held in wallets, but this article aims to guide new developers or Bitcoin enthusiasts through the general idea of wallet creation and also the importance of security, encryption, access, and re-accessibility in wallet design and architecture.</p><p>This article assumes that you already know the different Bitcoin networks (testnet, regtest, mainnet) and also the different wallet types (p2pk, p2pkh, etc.). For the scope of this article, we will be focusing on building a multipurpose Bitcoin wallet using a specific set of libraries.</p><ul><li><strong>BitcoinJs library:</strong> The BitcoinJS library is a JavaScript library that provides tools and utilities for working with Bitcoin and Bitcoin-like cryptocurrencies in Node.js and web applications. It allows developers to perform various tasks related to Bitcoin, such as generating Bitcoin addresses, creating and signing transactions, and working with Bitcoin scripts.</li><li><strong>ecpair library: </strong>The ecpair library is a part of the BitcoinJS ecosystem and is specifically designed for working with elliptic curve cryptography (ECC) in JavaScript applications. It provides functionality for creating and managing elliptic curve key pairs, which are essential for cryptographic operations such as digital signatures and public-key encryption.</li><li><strong>tiny-secp256k1 library:</strong> The tiny-secp256k1 library is a compact JavaScript library specifically designed for working with the secp256k1 elliptic curve, which is widely used in Bitcoin and other cryptocurrencies. This library provides efficient and optimized implementations of cryptographic operations related to the secp256k1 curve, including key pair generation, digital signature generation and verification, and public key recovery.</li><li><strong>CryptoJs library:</strong> The CryptoJS library is a popular JavaScript library that provides cryptographic functionalities for web applications. It offers a wide range of cryptographic algorithms and utilities, allowing developers to perform various cryptographic operations such as encryption, decryption, hashing, and HMAC (Keyed-Hash Message Authentication Code) generation.</li><li><strong>fs library:</strong> this is also called the file system library. It offers us the ability to create and read the contents of a file from our typescript code. we’ll be using this to store the details of each wallet we create.</li></ul><p>Our project will be written in TypeScript, so it is expected that you have Node and TypeScript installed before attempting to code along. Our project will be structured like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*hNuT8bNxsPgpN8hEGQ_zsQ.png" /></figure><p>We start by creating a new folder called “<strong>Bitcoin_Cli_Wallet</strong>” then we <strong><em>cd</em></strong> into that folder and run the command “<strong><em>npm init</em></strong>”. This will initialize a new node module with a package.json file in the directory, after which we create a new folder called “<strong>wallets</strong>” in our root directory. Then we run the command “<strong><em>npm i -D typescript ts-node</em></strong>” This will install typescript and a typescript execution environment to let us run typescript code in <strong>Node.js</strong>. Next, we install the libraries we would use by running the following codes: “<strong><em>npm install bitcoinjs-lib</em></strong>”, “<strong><em>npm install ecpair</em></strong>”, “<strong><em>npm install tiny-secp256k1”, “npm install crypto”, “npm install dotenv”. </em></strong>These, except dotenv library, have already been mentioned. The dotenv library helps us keep private data or information that is needed in our code in a separate file so that it is not exposed to the rest of our code.</p><h3><strong>Importing dependencies</strong></h3><p>Up Next, we create an index.ts file and then populate the index file with the logic for our wallet. We will start by importing all the dependencies we’ll need for the project.</p><pre>import * as bitcoin from &#39;bitcoinjs-lib&#39;<br>import {ECPairFactory, ECPairInterface} from &#39;ecpair&#39;;<br>import * as ecc from &#39;tiny-secp256k1&#39;;<br>import * as fs from &#39;fs&#39;<br>import * as crypto from &#39;crypto&#39;;<br>import * as walletTypes from &#39;bitcoinjs-lib/src/payments/index&#39;<br>import * as dotenv from &#39;dotenv&#39;;</pre><h3><strong>Setting global and .env variables</strong></h3><p>The above code basically brings the contents of the different libraries we would be using into the scope of our project.</p><pre>let totalWallets: number;<br>let allWalets: any;<br>let allAddresses: any;<br><br>interface History {<br>    totalWallets: number;<br>    allWalets: any;<br>    allAddresses: any;<br>}<br><br>interface walletData {<br>    keyPair: ECPairInterface;<br>    walletObject: walletTypes.Payment;<br>    walletType: string;<br>}<br><br>const ECPair = ECPairFactory(ecc);<br>const TESTNET = bitcoin.networks.testnet;<br>const REGTEST = bitcoin.networks.regtest;<br>const BITCOIN = bitcoin.networks.bitcoin;<br><br>dotenv.config();<br>const encryptionKey = process.env.ENCRYPTION_KEY;<br>const algorithm = process.env.ALGORITHM;</pre><p>Next, we define global variables to track the total number of wallets we’ve created, an array of all the wallet names, and an array of all the addresses we’ve created. we also define 2 interfaces. The first is to define an object structure for storing our wallet history. This is important because we would be storing the history of our wallet activities using that structure. Finally, we have an interface to define the structure of each wallet’s data, and we would be storing each wallet we create on our machine using that structure. Next, we define the different network types that users can create a wallet for; basically, users would be able to make use of this cli wallet to create a wallet for any of the above-listed networks and finally, we read the encryption key and algorithm variables from our dotenv file, so yeah, we need to create a “<strong>.env</strong>” file in our root directory and paste the following into the file:</p><pre>ENCRYPTION_KEY=MySuperSecretKey<br>ALGORITHM=&#39;aes-256-cbc&#39;</pre><p>This represents the key for encrypting and decrypting our wallet data, as well as the encryption algorithm we intend to use.</p><h3><strong>Create wallet function</strong></h3><pre>function createWallet(walletname:string, network:string, walletType:string) {<br>    let walletHistory = fetchWalletHistory();<br>    totalWallets = walletHistory.totalWallets;<br>    allWalets = walletHistory.allWalets;<br>    allAddresses = walletHistory.allAddresses;<br>    console.log(&quot;creating wallet.....................&quot;);<br><br>    let keyPair: ECPairInterface = decodeNetwork(network);<br>    let walletData: walletTypes.Payment = decodeWalletType(walletType, keyPair);<br>    let address: string | undefined = walletData.address;<br><br>    totalWallets += 1;<br>    allWalets.push(walletname);<br>    console.log(&quot;Initializing address:&quot;, address);<br>    allAddresses.push(address);<br>    console.log(&quot;all addresses&quot;, allAddresses);<br><br>    const newWallet: walletData = {<br>        keyPair: keyPair,<br>        walletObject: walletData,<br>        walletType: walletType<br>    }<br><br>    const newHistory: History = {<br>        totalWallets: totalWallets,<br>        allWalets: allWalets,<br>        allAddresses: allAddresses<br>    }<br><br>    writeWalletDataToFile(walletname, newWallet);<br>    writeWalletHistoryToFile(newHistory);<br>    console.log(&quot;wallet created. your wallet address is: &quot; + address);<br>}</pre><p>The above code is a function called `createWallet` that generates a new wallet. It begins by fetching the wallet history, encompassing the total wallet count, names, and addresses, using the `fetchWalletHistory` function. Subsequently, it initializes variables to store the retrieved wallet history data, then decodes the network and wallet type parameters that were passed in by the user to acquire the requisite key pair and wallet data for the new wallet. The function then increments the total wallet count and appends the new wallet name and corresponding address to the respective arrays. It proceeds to construct an object representing the new wallet, incorporating its key pair, wallet object, and type. Additionally, it generates a new history object containing the updated wallet count, names, and addresses. The function writes the new wallet’s data to a file using `writeWalletDataToFile` and updates the wallet history file with the new data via `writeWalletHistoryToFile` function. Finally, it logs a message confirming the wallet’s creation and displays its address. The above function called some helper functions “<strong>decodeNetwork(network)</strong>” and “<strong>decodeWalletType(walletType, keyPair)</strong>” so we’ll be discussing them next.</p><h3><strong>Helper functions</strong></h3><pre>function decodeNetwork(network: string): ECPairInterface {<br>    let keyPair: ECPairInterface;<br>    <br>    switch (network) {<br>        case &#39;testnet&#39;:<br>            keyPair = ECPair.makeRandom({ network: TESTNET });<br>            break;<br>        case &#39;bitcoin&#39;:<br>            keyPair = ECPair.makeRandom({ network: BITCOIN });<br>            break;<br>        case &#39;regtest&#39;:<br>            keyPair = ECPair.makeRandom({ network: REGTEST });<br>            break;<br>        default:<br>            throw new Error (&#39;Invalid wallet type&#39;);<br>    }<br>    <br>    return keyPair;<br>}<br><br><br>function decodeWalletType(userInput: string, keyPair: ECPairInterface):walletTypes.Payment {<br>    let walletData: walletTypes.Payment;<br>    switch (userInput) {<br>        case &#39;embed&#39;:  <br>            walletData = bitcoin.payments.embed({pubkey: keyPair.publicKey, network: TESTNET,});<br>            break;<br>        case &#39;p2ms&#39;:  <br>            walletData = bitcoin.payments.p2ms({pubkey: keyPair.publicKey, network: TESTNET,});<br>            break;<br>        case &#39;p2pk&#39;:  <br>            walletData = bitcoin.payments.p2pk({pubkey: keyPair.publicKey, network: TESTNET,});<br>            break;<br>        case &#39;p2pkh&#39;:  <br>            walletData = bitcoin.payments.p2pkh({pubkey: keyPair.publicKey, network: TESTNET,});<br>            break;<br>        case &#39;p2sh&#39;:  <br>            walletData = bitcoin.payments.p2sh({pubkey: keyPair.publicKey, network: TESTNET,});<br>            break;<br>        case &#39;p2wpkh&#39;:  <br>            walletData = bitcoin.payments.p2wpkh({pubkey: keyPair.publicKey, network: TESTNET,});<br>            break;<br>        case &#39;p2wsh&#39;:    <br>            walletData = bitcoin.payments.p2wsh({pubkey: keyPair.publicKey, network: TESTNET,});<br>            break;<br>        case &#39;p2tr&#39;:  <br>            walletData = bitcoin.payments.p2tr({pubkey: keyPair.publicKey, network: TESTNET,});<br>            break;<br>        default: throw new Error(&#39;Unknown wallet type: &#39; + userInput);<br>    }<br><br>    return walletData;<br>}</pre><p>The above code block consists of two functions aimed at decoding the network and wallet type parameters, respectively, within our Bitcoin wallet creation process.</p><ol><li><strong>decodeNetwork(network: string):</strong> ECPairInterface: This function takes a string parameter network representing the desired network type (‘testnet’, ‘bitcoin’, ‘regtest’). It then uses a switch statement to determine the appropriate network configuration based on the provided input. For each case, it generates a random key pair associated with the specified network using ECPair.makeRandom(). If an invalid network type is provided, it throws an error. Finally, it returns the generated key pair.</li><li><strong>decodeWalletType(userInput: string, keyPair: ECPairInterface): </strong>This function decodes the user input to determine the desired wallet type (‘p2ms’, ‘p2pk’, ‘p2pkh’, etc). It also accepts the key pair generated from the previous function as input. Similar to decodeNetwork, it utilizes a switch statement to construct the appropriate wallet data based on the provided input and network configuration. It utilizes the bitcoinJs library to generate and return the generated wallet data.</li></ol><h3><strong>Storing and retrieving encrypted data from wallets directory.</strong></h3><pre>function writeWalletDataToFile(walletname: string, walletData: walletData ): void {<br>    let filename: string = `${walletname}.json`;<br>    let filePath: string = `./wallets/${filename}`;<br>    const encryptedData = encryptData(JSON.stringify(walletData));<br>    fs.writeFileSync(filePath, encryptedData);<br>    console.log(&quot;Encrypted walletData stored sucessfully.......&quot;);<br>}<br><br><br>function readWalletDataFromFile(walletname: string): walletData {<br>    let filePath: string = `./wallets/${walletname}`;<br>    console.log(&quot;accessing wallet data.............&quot;)<br>    try {<br>        let data = fs.readFileSync(filePath, &#39;utf8&#39;);<br>        data = decryptData(data);<br>        console.log(&quot;wallet data accessed sucessfully......&quot;);<br>        return JSON.parse(data);<br>    } catch (e) {<br>        console.log(&quot;error accessing wallet data......&quot;);<br>        throw new Error (e);<br>    }<br>}<br><br>function writeWalletHistoryToFile(walletHistory: History): void {<br>    let filename: string = &#39;history.json&#39;;<br>    let filePath: string = `./wallets/${filename}`;<br>    const encryptedData = encryptData(JSON.stringify(walletHistory));<br>    fs.writeFileSync(filePath, encryptedData);<br>}</pre><p>The above code block contains function relating to encrypting wallet data and storing them to individual files in the wallets folder in our project root directory;</p><ul><li><strong>“<em>writeWalletDataToFile(walletname: string, walletData: walletData ): void:</em>”</strong> This function takes the name of the wallet and its corresponding data object as parameters. It constructs the filename and file path based on the wallet name, and then encrypts the wallet data using the encryptData helper function which will be explained later. The encrypted data is then written to the specified file path using fs.writeFileSync. This function ensures that wallet data is securely stored in a file after encryption to aid retrieval even after program shutdown.</li><li>“<strong><em>readWalletDataFromFile(walletname: string): walletData:</em></strong>” This function reads wallet data from a file based on the provided wallet name. It constructs the file path using the wallet name and attempts to read the data from the file. Upon successful reading, it decrypts the data using the decryptData function (which will be explained later), which corresponds to the encryption algorithm used during writing. The decrypted data is then parsed into a JSON object and returned. In case of an error during file reading or decryption, it throws an error.</li><li>“<strong><em>writeWalletHistoryToFile(walletHistory: History): void:</em></strong>” This function is responsible for writing wallet history data to a file. It takes the wallet history object as input, constructs the file path, encrypts the history data, and writes it to the file using fs.writeFileSync. Similar to writeWalletDataToFile, this function ensures that wallet history data is securely stored after encryption and can be re-accessed later at a user-defined time.</li></ul><pre>function fetchWalletHistory(): History {<br>    console.log(&quot;fetching wallet history..............&quot;);<br>    const historyFilePath = &#39;./wallets/history.json&#39;;<br><br>    try {<br>        if (!fs.existsSync(historyFilePath)) {<br>            // Create a new empty file if it doesn&#39;t exist<br>            console.log(&quot;New wallet history file created.&quot;);<br>            fs.writeFileSync(historyFilePath, &#39;{}&#39;);<br>            const newHistory: History = {<br>                totalWallets: 0,<br>                allWalets: [],<br>                allAddresses: []<br>            }<br>            writeWalletHistoryToFile(newHistory);<br>            return newHistory; // Return an empty object<br>        }<br><br>        let data = fs.readFileSync(historyFilePath, &#39;utf8&#39;);<br>        data = decryptData(data);<br>        console.log(&quot;wallet history accessed sucessfully......&quot;);<br>        return JSON.parse(data);<br>    } catch (e) {<br>        console.log(&quot;error accessing wallet history......&quot;);<br>        throw e;<br>    }<br>}</pre><p>The above function ensures the retrieval of wallet history data from a file, creates a new file if necessary, and handles errors that may occur during the process. It plays a crucial role in providing access to wallet history information for various operations within the application.</p><p>Firstly, it checks if the history file exists by using the <strong><em>fs.existsSync</em></strong> method to determine if the file exists at the specified path <strong><em>(./wallets/history.json)</em></strong>. If the history file does not exist, the function creates a new empty file at the specified path using <strong><em>fs.writeFileSync</em></strong>. It initializes an empty object representing the wallet history and writes it to the newly created file, ensuring that there is always a history file available for storing wallet history data.</p><p>If the history file exists, the function reads its contents using <strong><em>fs.readFileSync</em></strong> and specifies the encoding as UTF-8. It then decrypts the data using the <strong><em>decryptData</em></strong> function, which corresponds to the encryption algorithm used when writing the history file. After decrypting the data, the function parses the JSON-formatted data into a JavaScript object representing the wallet history. It returns this object to the caller, providing access to the wallet history data for further processing.</p><h3><strong>Encrypting and decrypting wallet data/ history</strong></h3><pre>// Function to encrypt data<br>function encryptData(data: string): string {<br>    console.log(&quot;encrypting data..........&quot;);<br>    const cipher = crypto.createCipher(algorithm, encryptionKey);<br>    let encryptedData = cipher.update(data, &#39;utf8&#39;, &#39;hex&#39;);<br>    encryptedData += cipher.final(&#39;hex&#39;);<br>    console.log(&quot;encryption succesful..........&quot;);<br>    return encryptedData;<br>}<br><br>// Function to decrypt data<br>function decryptData(encryptedData: string): string {<br>    console.log(&quot;decrypting data..........&quot;);<br>    const decipher = crypto.createDecipher(algorithm, encryptionKey);<br>    let decryptedData = decipher.update(encryptedData, &#39;hex&#39;, &#39;utf8&#39;);<br>    decryptedData += decipher.final(&#39;utf8&#39;);<br>    console.log(&quot;decrypting successful..........&quot;);<br>    return decryptedData;<br>}<br><br>function listAllAddresses(): [string | undefined] {<br>    console.log(&quot;Accessing all addresses...&quot;);<br>    let history = fetchWalletHistory();<br>    let allAddresses = history.allAddresses;<br>    console.log(&quot;All available addresses are: &quot; + JSON.stringify(allAddresses));<br>    return allAddresses;<br>}</pre><p>This last block of code contains the main logic to encrypt and decrypt data being stored or retrieved from our local machine. It also implements a function that reads the wallet history data from our local machine and then logs all the addresses that have been created using our program.</p><p>“<strong><em>encryptData(data: string): string: </em></strong>” This function takes a string of data as input and encrypts it using the specified encryption algorithm (algorithm) and encryption key (encryption key). It uses the crypto.createCipher method to create a Cipher object, updates the data with the ‘utf8’ encoding, and generates the encrypted data in hexadecimal format (‘hex’). Finally, it returns the encrypted data.</p><p>“<strong><em>decryptData(encryptedData: string): string:</em></strong>” This function takes the encrypted data as input and decrypts it using the same encryption algorithm and encryption key. It uses the ‘crypto.createDecipher’ method to create a decipher object, updates the encrypted data in hexadecimal format (‘hex’) and generates the decrypted data with the ‘utf8’ encoding. Finally, it returns the decrypted data.</p><p><strong><em>“listAllAddresses(): [string | undefined]:” </em></strong>This function retrieves all wallet addresses from the wallet history. It first fetches the wallet history using the fetchWalletHistory function and then extracts the array of all wallet addresses. It logs the retrieved addresses to the console and returns them as an array of strings or undefined values.</p><h3><strong>Creating wallets using the current code Base</strong></h3><p>With a combination of all the code blocks explained above, we can now successfully create a new wallet, encrypt the wallet details, and store the encrypted data on our local machine for retrieval and decryption when the need arises. We can test out the functionality of our current code base by adding the following lines of code just below the last line of code in the code base.</p><pre>// Below line of codes are simply for test purposes.<br>console.log(&quot;running tests...&quot;);<br>createWallet(&quot;myWallet&quot;, &quot;regtest&quot;, &quot;p2pkh&quot;);<br>console.log(&quot;================================================================&quot;);<br>createWallet(&quot;BobWallet&quot;, &quot;regtest&quot;, &quot;p2pkh&quot;);<br>console.log(&quot;================================================================&quot;);<br>createWallet(&quot;ALiceWallet&quot;, &quot;regtest&quot;, &quot;p2pkh&quot;);<br>console.log(&quot;================================================================&quot;);<br>listAllAddresses();</pre><p>To test our current code base, we simply save the current workflow we have and then run the command “<strong><em>tsc index.ts</em></strong>”. This command generates an index.js file corresponding to the transcribed JavaScript representation of our typescript codebase. Next, we execute the js file by running the command “<strong><em>node index.js</em></strong>” This command runs the function to create multiple wallets and then also returns the list of all addresses contained in our cli wallet.</p><h3><strong>Conclusion</strong></h3><p>The current code base implements a majority of the functions we’ll need in a minimalist wallet except for the initiate transaction function; we’ll be covering that in Part 2 of this article, where we create a function to spend a user’s UTXO. Pending that, a complete implementation of our current stage can be found here on Github:</p><p><a href="https://github.com/Nonnyjoe/Bitcoin_cli_wallet">https://github.com/Nonnyjoe/Bitcoin_cli_wallet</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61cde41ceed9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[U256 data types in Cairo: A New Developer’s Guide to StarkNet Smart Contracts]]></title>
            <link>https://medium.com/@idogwuchi/u256-data-types-in-cairo-a-new-developers-guide-to-starknet-smart-contracts-55f788ec2147?source=rss-a9abcdd90f1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/55f788ec2147</guid>
            <dc:creator><![CDATA[Idogwu Chinonso]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 15:17:32 GMT</pubDate>
            <atom:updated>2023-11-17T15:17:32.030Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*rY8cms0cxI-jiCJraoNadQ.png" /></figure><p>If you’re new to StarkNet and want to do cool things with it, understanding u256 is super important. This article will explain u256 in a way that makes sense, showing why it’s a big deal for StarkNet smart contracts. By the end, you’ll know what u256 is all about and how to use it for your own StarkNet projects</p><p>U256 is one of the seven types of unsigned integers popularly used in smart contracts. Unlike the other unsigned integers, under the hood, a U256 is actually a struct consisting of two U128 integers (low and high). This combination of two u128 to form a U256 requires a more complex implementation to manage mathematical operations involving a U256 data type, but don’t worry, you don’t need to handle all that.</p><p>Though certain development environments might abstract this complexity out and simplify the structure of the U256 data structure, the structure of the u256 data type is ideally different, and Its important to have a good understanding of the structure of this data type and what each of its components means.</p><pre>struct u256 {<br>   low: u128,<br>   high: u128,<br>}</pre><p>The first u128 (low) is where the actual value resides, while the second u128 (high) keeps track of how many times the low, being a u128, has overflowed. I know this might sound a bit confusing at first, but let’s simplify it.</p><p>For certain data types called fixed-size data types, there is a maximum value that can be stored in them, and once these values are exceeded, just like a clock that’s passed the number 12 mark starts counting again from 1, these fixed-size data types restart counting the value from zero and might end up finally storing a value smaller than the expected value. In programming, we call this phenomenon integer overflow. For example, if we have three values (a, b, and c) with a data type that can hold a maximum value of 8, then we assign a value of 7 to (a) and a value of 5 to (b);</p><pre>let a = 7;<br>let b = 5;</pre><p>Finally, we try assigning the sum of a and b to c.</p><pre>let c = a + b;</pre><p>Typically, we’ll expect c to be 12, but remember that c can only take a maximum value of 8, so we’ll end up with a final answer of 3. This is because on performing the addition, we get to the maximum value of 8, then on adding another value, it overflows to 0, then we continue the addition by adding the remaining 3 values contained in b, and we end up with a final answer of 3. Hope things make better sense now?</p><p>A u128 can only hold a maximum value of (2¹²⁸ — 1), while a u256 can hold a much larger value, up to (2²⁵⁶ — 1). So, in theory, a u256 data type should accommodate a value larger than the maximum of u128 (2¹²⁸ — 1). However, attempting to directly pass a number greater than (2¹²⁸ — 1) to a u256 data type would result in an error. This happens because, behind the scenes, the data we pass in is assigned to the low component of the u256 struct, which is actually of type u128. So, how do we handle this?</p><p>To pass values larger than the maximum of u128, we need to reformat our input. Instead of passing a single number, we pass in two numbers separated by a comma, like (200, 1). Here, the first value (200) represents the low component of the u256 struct and should be within the range of u128. The second value (1) represents the high component, keeping track of how many times the low value must have overflowed to reach the final value (200). In our example, (200, 1) suggests that the low value overflowed once, resulting in the final value of 200.</p><p><strong>Arithmetic operations on U256 (Addition)</strong></p><p>In this section, we will talk about how Cairo handles addition operations for u256 type variables under the hood. We’ll start by looking at the functions that handle the addition of u256 datatypes in the Cairo core library:</p><pre>   fn add(lhs: u256, rhs: u256) -&gt; u256 {<br>       u256_checked_add(lhs, rhs).expect(&#39;u256_add Overflow&#39;)<br>   }</pre><pre>fn u256_checked_add(lhs: u256, rhs: u256) -&gt; Option&lt;u256&gt; implicits(RangeCheck) nopanic {<br>   let (r, overflow) = u256_overflowing_add(lhs, rhs);<br>   if overflow {<br>       Option::None<br>   } else {<br>       Option::Some(r)<br>   }<br>}</pre><pre>fn u256_overflowing_add(lhs: u256, rhs: u256) -&gt; (u256, bool) implicits(RangeCheck) nopanic {<br>   let (high, overflow) = match u128_overflowing_add(lhs.high, rhs.high) {<br>       Result::Ok(high) =&gt; (high, false),<br>       Result::Err(high) =&gt; (high, true),<br>   };<br>   match u128_overflowing_add(lhs.low, rhs.low) {<br>       Result::Ok(low) =&gt; (u256 { low, high }, overflow),<br>       Result::Err(low) =&gt; {<br>           match u128_overflowing_add(high, 1_u128) {<br>               Result::Ok(high) =&gt; (u256 { low, high }, overflow),<br>               Result::Err(high) =&gt; (u256 { low, high }, true),<br>           }<br>       },<br>   }<br>}</pre><p>The three functions above were extracted from the Cairo core library. The combination of these three functions handles all addition operations for U256 data types in Cairo.</p><p>When we add two u256 values, we engage all three functions mentioned earlier. The ‘add’ function takes the two values to be summed and passes them to the ‘u256_checked_add’ function. This function, in turn, sends the arguments to the third function, ‘u256_overflowing_add.’ Here, it receives a tuple containing the final value and a boolean indicating whether an overflow occurred. The function then checks this overflow value. If false, it returns Option::Some(r), where r is the final value after the addition. If true, indicating an overflow, it returns Option::None. With this, the main addition logic of the logic is carried out in the ‘u256_overflowing_add’ function, which we will be reviewing next.</p><p>The ‘u256_overflowing_add’ starts by collecting two u256 types as arguments, after which it extracts the high value of the two arguments and passes them into the ‘u128_overflowing_add’ function (remember from our previous explanation that the high value represents the number of times the actual value&lt;low&gt; had overflown). The ‘u128_overflowing_add’ function returns a Result::ok(high) if the sum of the two highs does not overflow and a Result::Err(high) if the result does. Finally, it runs a match expression on the output from the Result output;</p><pre>let (high, overflow) = match u128_overflowing_add(lhs.high, rhs.high) {<br>       Result::Ok(high) =&gt; (high, false),<br>       Result::Err(high) =&gt; (high, true),<br>}</pre><p>If the Result being matched on holds an ok value, meaning that there was no overflow, the overflow flag is set to false; otherwise, if the Result value holds an Err, overflow flag is set to false, and regardless of the outcome, the high value is set to the final result of the addition carried out (high).</p><pre>   match u128_overflowing_add(lhs.low, rhs.low) {<br>       Result::Ok(low) =&gt; (u256 { low, high }, overflow),<br>       Result::Err(low) =&gt; {<br>           match u128_overflowing_add(high, 1_u128) {<br>               Result::Ok(high) =&gt; (u256 { low, high }, overflow),<br>               Result::Err(high) =&gt; (u256 { low, high }, true),<br>           }<br>       },<br>   }</pre><p>Moving to the next step, the function adds the low values of the two u256 structs by passing them into the ‘u128_overflowing_add’ function. Remember that the low value holds the actual number being stored in the u256 type. If this addition doesn’t result in an overflow, we get the high from the previous code block, then we build a new u256 struct by combining the low from the latest addition with the high from the previous code block, and this becomes the final output from the addition of the two u256. However, if the low value obtained from the ‘u128_overflowing_add’ overflows, we need to account for this by increasing the high value gotten from the previous code block. We achieve this by passing in the high value from the previous code block and the value 1 into the ‘u128_overflowing_add’ function. After that, we perform a match expression on the output (high) from the function. Whether or not there is an overflow in the result we get, we still construct a u256 from a combination of the new high and the low gotten from a few lines above, and then we return an overflow value alongside the created u256 to represent whether or not the addition of 1 to the high value overflowed. This output is picked up by the ‘u256_checked_add’ function, which runs a conditional expression on the overflow value and returns an Option:None if there was an overflow or it returns an Option::Some(r) If there was no overflow, r in this statement represents the final output of the sum of the two u256.</p><p>In conclusion, this journey has taken us through the structure of u256, it’s components and architecture, a brief brush through of integer overflow, and also a breakdown of addition operations in u256. It’s expected at this point that you should be able to explain why you need to pass in two numbers to a u256 data type and what the high and low values represent. A proper understanding of a combination of these concepts and operations is important to lay a solid foundation for developers, enabling them to unlock the full potential of starknet for their smart contract development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55f788ec2147" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blockchain use cases in green technology and sustainable projects.]]></title>
            <link>https://medium.com/@idogwuchi/blockchain-use-cases-in-green-technology-and-sustainable-projects-80dce1f35455?source=rss-a9abcdd90f1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/80dce1f35455</guid>
            <category><![CDATA[green-energy]]></category>
            <category><![CDATA[sustainable-development]]></category>
            <category><![CDATA[blockchain-application]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Idogwu Chinonso]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 11:42:32 GMT</pubDate>
            <atom:updated>2023-06-05T11:51:29.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*OwdSVz1bVKJSjyEbPXKKOg.png" /></figure><p>For years, there has been a growing clamor for green tech and sustainable projects as the entire planet is gradually awakening to the urgent need to address environmental challenges. This has led to greater momentum in the push for cleaner energy sources, responsible consumption, and a reduced carbon footprint. It’s not a hidden fact that the adoption of green technologies and sustainable practices not only offers a way to mitigate climate change but also holds a promise to transform our society for the better. This article explores the different use cases of blockchain technology in the aspect of green technology, sustainable projects and how innovative companies are currently leveraging blockchain technology to amplify the impact of green tech and sustainable projects in promoting a more sustainable future.</p><p>Green tech, also known as “green technology” or “clean technology, refers to the development and application of innovative solutions that aim to protect and preserve the environment while addressing sustainability challenges. It encompasses various technologies, practices, and initiatives that promote environmental sustainability, resource efficiency, and the reduction of carbon emissions. Blockchain, on the other hand, is a digital ledger built on a decentralized network of interconnected computers that work together to validate and secure the information on the blockchain in order to enable transparency, immutability, and trust among participants. These features make blockchain an ideal technology to help amplify the impact and adoption of green technology and sustainable projects on a wider scale. Some of the relevant use cases of blockchain in this rapidly evolving and increasingly important field are highlighted below:</p><p><strong>RENEWABLE ENERGY TRACKING:</strong></p><p>One prominent use case of blockchain is the tracking and verification of renewable energy generation and consumption. Blockchain can create an immutable, auditable, and publicly accessible record of energy production, thereby allowing for transparent tracking and trading of renewable energy certificates. This can incentivize the development and adoption of renewable energy sources while ensuring accurate and transparent accounting, thereby reducing fraud and improving trust in the system.</p><p>WePower a blockchain infused project is successfully democratizing access to renewable energy by allowing individuals to directly fund renewable energy projects through the purchase of tokens backed by future energy production, thereby enabling renewable energy projects to secure financing and providing investors with the opportunity to support and benefit from clean energy generation.</p><p><strong>SUPPLY CHAIN TRANSPARENCY:</strong></p><p>Blockchain technology can enhance supply chain transparency in green tech and sustainable projects. By leveraging blockchain’s decentralized ledger, stakeholders can trace the origin, movement, and impact of sustainable products and materials. This transparency enables consumers to make informed choices, incentivizes sustainable practices, and ensures accountability throughout the supply chain.</p><p>Companies like Circulor and Everledger are currently focused on leveraging blockchain to provide traceability and transparency for sustainable supply chains, specifically in industries like electric vehicles, renewable energy, and mining.</p><p><strong>CARBON CREDITS AND OFFSETTING:</strong></p><p>Blockchain has the potential to revolutionize carbon credit markets and offsetting programs. By utilizing smart contracts and tokenization, blockchain can automate the verification and transfer of carbon credits, streamlining the process and reducing administrative burdens. This innovation can unlock new opportunities for businesses and individuals to actively participate in carbon offsetting initiatives, thereby streamlining the process of global adoption. Additionally, blockchain-based platforms are being developed to incentivize and reward sustainable actions. For example, individuals can earn tokens or credits for reducing their carbon footprint or participating in environmental conservation activities. These tokens can be exchanged for rewards or used to support green initiatives, creating a positive feedback loop for sustainable behaviors.</p><p>CarbonX is a blockchain-based platform that allows individuals to offset their carbon footprint by purchasing and trading carbon credits. It provides a transparent and secure marketplace for carbon offsets, enabling individuals and organizations to support sustainable projects and reduce their environmental impact.</p><p><strong>DECENTRALIZED ENERGY GRIDS:</strong></p><p>The decentralized nature of blockchain is well suited for the development of peer-to-peer energy trading platforms and decentralized energy grids. Through the utilization and implementation of blockchain-based systems, individuals and businesses can trade excess renewable energy directly with others in their community without external mediation, thereby promoting localized and decentralized energy production, reducing reliance on traditional grids, fostering energy independence, and promoting eco-friendly energy generation.</p><p>Popular tech giant Power Ledger has successfully utilized blockchain technology to improve green tech in the areas of renewable energy tracking, exchange, and incentivization. With Power Ledger, users can comfortably trade renewable energy without intermediaries in a peer-to-peer network powered by the blockchain.</p><p><strong>DATA MANAGEMENT AND COLLABORATION:</strong></p><p>Blockchain technology revolutionizes data management and collaboration in green technology and sustainable projects. Blockchain ensures data integrity and trust through its transparent and tamper-resistant nature. It also facilitates secure data sharing and accessibility among stakeholders, promoting collaboration and understanding of sustainability efforts from all ends. Collaborative platforms powered by blockchain bring diverse stakeholders together for collective decision-making and knowledge exchange. By leveraging these blockchain capabilities, the field of green tech and sustainable projects gains transparency, efficiency, and effective stakeholder engagement, ultimately accelerating the transition towards a more sustainable future.</p><p>Ocean Protocol and EnergiMine are just a few of the top companies incorporating blockchain to improve aspects of data management and collaboration in the field of green technology and sustainable projects. Ocean Protocol offers a decentralized data exchange protocol that enables secure and privacy-preserving data sharing for sustainable projects. It allows individuals and organizations to share, monetize, and collaborate on data while maintaining control over their information.</p><p><strong>CONCLUSION:</strong></p><p>In conclusion, despite blockchain technology being relatively new and also struggling to achieve global adoption, it presents exciting opportunities for green tech and sustainable projects, which, despite their importance, have also yet to achieve global adoption. Blockchain can contribute to a more sustainable future by serving as a beacon structure for the radical innovation and global adoption of renewable energy tracking, supply chain transparency, carbon credit markets, decentralized energy grids, and data management. By putting more effort and support into research relating to blockchain and its application in enhancing green technology and sustainable projects, embracing these use cases, and finally leveraging blockchain’s unique features, we can accelerate the transition towards a greener and more sustainable world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80dce1f35455" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Create and Create2 for Contract Address Generation and Insights from the Tornado Cash…]]></title>
            <link>https://coinsbench.com/exploring-create-and-create2-for-contract-address-generation-and-insights-from-the-tornado-cash-b2cf24ad5d84?source=rss-a9abcdd90f1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2cf24ad5d84</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[hacks]]></category>
            <category><![CDATA[solidity-opcode]]></category>
            <category><![CDATA[dao]]></category>
            <dc:creator><![CDATA[Idogwu Chinonso]]></dc:creator>
            <pubDate>Sat, 27 May 2023 04:46:00 GMT</pubDate>
            <atom:updated>2023-05-30T11:49:42.648Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Create and Create2 for Contract Address Generation and Insights from the Tornado Cash Dao Hack</h3><p><strong>TABLE OF CONTENTS:</strong></p><p>i. Statement of purpose.</p><p>ii. Introduction.</p><p>iii. What are opcodes.</p><p>iv. Understanding Create and create2 opcodes.</p><p>v. Create: basic contract deployment.</p><p>vi. Create2: predictable and computed addresses.</p><p>vii. Exploring create and create2 application in the tornado cash hack.</p><p>viii. Security considerations and address generation best practices.</p><p>ix. Conclusion.</p><p><strong>STATEMENT OF PURPOSE</strong></p><p>After going through this article the reader is expected to achieve the following;</p><ol><li>Understanding of what Opcodes are.</li><li>Understand the functions of Create and Create2 opcodes.</li><li>Understand the differences between the create and create2 opcodes.</li><li>Understanding of the application of create and create2 opcodes in the Tornado cash Dao hack.</li><li>Get better knowledge of address generation best practices and recent security considerations in both Governance projects and address generation.</li></ol><p><strong>INTRODUCTION:</strong></p><p>Opcodes are a fundamental aspect of the Ethereum blockchain; they are a set of instructions or commands by which the EVM operates. In this article, we will be focusing on two of these opcodes (create and create2), their differences, and how they were smartly combined in the execution of the tornado cash Dao hack. We’ll finally be concluding with security considerations and best practices relating to address generation and smart contract security as regards to the use, advantages, and dangers of utilizing any of these two opcodes in smart contract deployment.</p><p>This article is fine-tuned to help both beginners and seasoned developers understand and appreciate the above topic, but I’ll be assuming that the reader has a basic understanding of the blockchain, EVM, smart contract deployment, interaction, and execution. Never the less, I’m sure the knowledge you seek will be transferred.</p><p><strong>WHAT ARE OPCODES?</strong></p><p>Opcodes, short for operation codes, are fundamental instructions for the Ethereum Virtual Machine (EVM) that define the operations to be executed by the EVM. Opcodes are low-level instructions represented by hexadecimal values, and they form the bytecode that is executed by the EVM during the execution of smart contracts. Each opcode represents a specific operation or action that the EVM can perform. Opcodes define a wide range of functionalities, including arithmetic operations, control flow instructions, memory manipulation, storage access, gas management, and interaction with the Ethereum network.</p><p>A list and adequate description of all EVM opcodes can be found in Section 9.4 “Execution” of the ethereum yellow paper (<a href="https://ethereum.github.io/yellowpaper/paper.pdf">https://ethereum.github.io/yellowpaper/paper.pdf</a>).</p><p><strong>UNDERSTANDING CREATE AND CREATE2 OPCODES:</strong></p><p>The create and create2 opcodes are two of the most popular low-level instructions smart contract developers utilize in deploying smart contracts; they both achieve the same goal of deploying and generating addresses for smart contracts but differ in certain ways, which we will be covering soon. I’ll be introducing the concepts of create and create2 with a very simple real-life illustration.</p><p>Imagine two blockchain developers, Alex and Bob, taking a vacation leave to go on holiday. Alex decides he will be traveling to the Maldives, so he prepares adequately, gets a visa, makes a hotel reservation ahead of time, and books a direct flight to the Maldives. While Bob registers with a tourism company for a holiday package, he is only limited to the available holiday destinations, but his flight, accommodation, and reservations will be arranged by the tourism agency.</p><p>This illustration might look oversimplified, but it can be directly related to the CREATE and CREATE2 opcodes on the EVM. In the analogy used, the two developers had something in common: they both wanted a vacation. Similarly, the create and create2 opcodes have something in common, which is that they both lead to deployment and address generation for smart contracts. The major difference lies in the fact that, similar to Bob’s situation, using the create opcode offers limited flexibility and predictability of smart contract addresses; we basically depend on a single and strict determiner for our contract address, unlike using the create2 opcode, where we are able to easily (in comparison to create) predict and set suitable conditions (salt) to generate a contract address of our choice.</p><p><strong>CREATE: BASIC CONTRACT DEPLOYMENT:-</strong></p><p>The ‘create’ opcode is the most commonly used contract creation opcode. When contracts are deployed from scripts or other development environments, the create opcode is the low-level instruction executed by the EVM to deploy and generate a contract address. The create opcode differs from other smart contract deployment methods in the sense that when contracts are deployed using this method, the address for the contract is generated by taking the last 20 bytes of the Keccak256 hash of the rpl encode of the deployer’s address and its transaction nonce.</p><figure><img alt="Flow chart for address generation using Create opcode" src="https://cdn-images-1.medium.com/max/793/1*K9ZB4sGzrSJ5xfmx2ZJwlA.png" /></figure><p>Therefore, for every deployer address, its nonce is the major determiner to determine the address of the contract being deployed. This could be seen as a two-way scale because we are basically sacrificing determinism for ease and simplicity.</p><p><strong>CREATE2: PREDICTABLE AND COMPUTED ADDRESSES:-</strong></p><p>The create2 opcode, which was not widely known before, has become increasingly popular. It has been utilized by DeFi companies like 1inch and played a significant role in the Tornado cash hack of 2023. The create2 opcode is a modification of the popular create opcode and was proposed in EIP1014, with its core strength being that it allows for the creation of contracts with a deterministic address based on additional input called a “salt” value. Using the create2 opcode, smart contract addresses are determined by the last 20 bytes of the keccak-256 hash of the following: contract offset, deployer address, salt, and contract initialization code. These four combined create an opportunity for determinism as developers are able to use brute force in determining the salt (a random 32-byte hex code), which when used would generate an address of choice.</p><figure><img alt="Formula for address generation using Create 2 opcode" src="https://cdn-images-1.medium.com/max/629/1*NCiQ6l29DR0ey0CSILSBqw.png" /></figure><p><strong>EXPLORING CREATE AND CREATE2 APPLICATION IN THE TORNADO CASH DAO HACK:</strong></p><p>Without objection, one of the most creative Defi hacks in the second quarter of 2023 is the Tornado Cash Governance hack, where the hacker utilized a combination of create, create2, and self-destruct to amass 1.2 million tornado vote tokens, which were being traded for $5–7 at the time of the attack. In this section, we will do a deep dive into the schematics of the attack.</p><p>The hack started when a legitimate proposal to penalize cheating network participants in the Tornado Cash crypto tumbler project was successfully passed by a DAO vote. Crazy enough, a few days after the proposal had passed the DAO vote, the function implementation contained in the contract changed, and on execution, it was able to grant the attacker 1.2 million vote tokens, which was more than the 700 thousand legitimate votes as of then, thereby granting the attacker control of the DAO. This led to more research into what really happened, and the following were discovered:</p><p>The hacker had deployed the proposal contract using the create opcode from a child factory contract that was also deployed from a parent factory contract using the create2 opcode. Yeah, I understand this may seem confusing, but the images below might be of help.</p><figure><img alt="Tornado cash Dao, hack contract deployment trace" src="https://cdn-images-1.medium.com/max/1024/1*7hz-a4iN8DSgQbNdY_7Lbg.png" /></figure><p>From the above illustration, the attacker wrote a parent factory contract that deploys the child factory, which serves as a factory to deploy two contracts: a legit proposal contract and a malicious proposal contract. Remember in the previous section we mentioned that the EVM uses the create opcode to deploy a contract with a combination of just the deployer address and its nonce, while a combination of an offset, deployer address, salt, and initialization bytecode is used for deploying with the create2 opcode.</p><p>By all indications, the attacker used a combination of his address and nonce to deploy and generate the address of the parent factory contract (0xaf5…..dbacb) (CREATE).</p><pre>Keccak256(rlp.encode([0x592...89de9, 6]))[12:]</pre><p>then he makes a call to a function in the parent factory contract which uses the create2 opcode to deploy the child factory contract,</p><pre>keccak256( 0xff ++ 0xaf5...dbacb ++ salt(Y) ++ keccak256(0x608....0000))[12:]</pre><p>Finally the child factory contract deploys the Legit proposal contract using the address of the child factory and its nonce which in this case is 1 to obtain the address of the legit proposal contract (0xc50….752d).</p><pre>Keccak256(rlp.encode([0x7dc...1353d, 1]))[12:]</pre><figure><img alt="Tornado cash Dao governance Hack contract deployment stack trace" src="https://cdn-images-1.medium.com/max/1024/1*9IVV0x7JIX31XeNC8C-mGg.png" /></figure><p>The attacker then proceeds to create a proposal on the tornado Dao targeting the address of the legit proposal contract, which, after verification from the Dao members, passes the Dao vote and is ready for execution after a delay period. The attacker, upon achieving his goal of passing the Dao voting, proceeds to call an “emergencyStop function” on the parent factory contract that triggers a self-destruct on both the child factory and the legit proposal contract, thereby resetting their nonce and moving their address back to a non-existent state.</p><figure><img alt="Parent factory EmergencyStop function trace" src="https://cdn-images-1.medium.com/max/1024/1*Om4x8k6f-sFmYiZUF8CQjA.png" /></figure><p>Finally the attacker calls a function in the parent factory contract which utilizes create2 to redeploy the child factory to its previous address using the same set of parameters as the initial deployment.</p><pre>keccak256( 0xff ++ 0xaf5...dbacb ++ salt(Y) ++ keccak256(0x608....0000))[12:]</pre><p>The child factory contract which has been redeployed to the same address as previous now has its nonce reset back to 0, using the create opcode which combines the child factory address and its new nonce(1) a new malicious contract is deployed to the same address as the previous Legit proposal contract.</p><pre>Keccak256(rlp.encode([0x7dc...1353d, 1]))[12:]</pre><p>At this point, when the Dao proposal is executed and the Dao contract makes a delegate call to the proposal contract address the hacker presented in the initial proposal, the malicious contract implementation is executed, not the legitimate implementation that was initially presented in the proposal.</p><p>With this, the attacker was able to gain control of the Dao through the malicious proposal by transferring 1.2 million vote tokens to his account, from which he has been able to withdraw 10,000 votes as Tron. This led to the price of the Tornado cash token, which was initially traded at $5–7, dropping by 30%.</p><p>Through governance control, the attacker now has the power to withdraw all of the locked votes and drain all of the tokens in the governance contract.</p><figure><img alt="Tornado cash Dao hack, governance vote withdrawal" src="https://cdn-images-1.medium.com/max/1024/1*PFGemdrjUDMT99qx9ERwhg.png" /></figure><p><strong>SECURITY CONSIDERATIONS AND ADDRESS GENERATION BEST PRACTICES:</strong></p><p>Smart contract address generation is an important aspect of blockchain technology, enabling the creation of unique identifiers for contracts located on the blockchain with unprecedented security, transparency, and determinism. While it is crucial to implement robust address generation practices to ensure integrity and trustworthiness, it’s also pertinent to ensure industry best practices are employed in order to mitigate potential risks and safeguard the assets and functionalities contained in the smart contract.</p><p>To ensure best practices for smart contract address generation, it is important to utilize deterministic mechanisms provided by Ethereum, such as the “create” and “create2” opcodes, as well as utilizing unique salts when using “create2” to enhance determinism and also prevent collision. Finally, stay updated with Ethereum standards. By following these guidelines, developers can generate reliable and secure smart contract addresses, thereby minimizing potential issues and vulnerabilities.</p><p>I believe the tornado cash hack serves as a wake-up call to our current Dao system that more effort is needed in the aspect of proposal auditing and that Dao members need to be careful about what they vote for. The same way a proposal description is to be trusted with a pinch of salt, the proposal logic ought to be treated the same way, and finally, proposals with the ability to self-destruct should not be allowed to pass a Dao vote.</p><p><strong>CONCLUSION:</strong></p><p>This article looks into the crucial idea of the create and create2 opcodes. It focuses on using the create and create2 methods to generate contract addresses and draws inspiration from the Tornado Cash DAO hack. It also successfully emphasizes the importance of strong address generation procedures in smart contract development in order to improve security and prevent potential vulnerabilities. This article provides helpful assistance for developers wishing to design secure and trustworthy smart contracts by understanding the specific functions of create and create2. The Tornado Cash DAO hack insights serve as a case study, providing useful lessons and considerations for preventing such vulnerabilities in the future. Overall, the purpose of this article is to demystify the create and create2 opcodes while simultaneously promoting secure smart contract practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2cf24ad5d84" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/exploring-create-and-create2-for-contract-address-generation-and-insights-from-the-tornado-cash-b2cf24ad5d84">Exploring Create and Create2 for Contract Address Generation and Insights from the Tornado Cash…</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>