<?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 enigbe ochekliye on Medium]]></title>
        <description><![CDATA[Stories by enigbe ochekliye on Medium]]></description>
        <link>https://medium.com/@enigbe?source=rss-7ab9ec0a61e9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rx7rUnMNwbov0KJq7mMYVw.jpeg</url>
            <title>Stories by enigbe ochekliye on Medium</title>
            <link>https://medium.com/@enigbe?source=rss-7ab9ec0a61e9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 11 Apr 2026 03:08:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@enigbe/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[Part I: Bloom Filters]]></title>
            <link>https://enigbe.medium.com/part-i-bloom-filters-164d046f34b6?source=rss-7ab9ec0a61e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/164d046f34b6</guid>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[bloom-filter]]></category>
            <category><![CDATA[light-client]]></category>
            <dc:creator><![CDATA[enigbe ochekliye]]></dc:creator>
            <pubDate>Fri, 13 May 2022 05:30:25 GMT</pubDate>
            <atom:updated>2022-05-13T05:30:25.402Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>As bitcoin adoption grows, so has the growth of light clients, i.e. nodes on the network incapable of independent transaction verification. To ensure that these clients can verify transactions related to them, the concept of bloom filters was proposed for usage in what is known as simple payment verification.</p><p>The introduction and usage of bloom filters made it possible for light clients to verify transactions in interested blocks in ways that, to a certain degree, preserved their privacy. However, this “privacy-preserving” method of payment verification is not without leaks, requiring trust in honest peers (full nodes) to forward Merkle blocks containing the desired transactions, for work they (full nodes) have no incentive to do.</p><p>For all the benefits they provide, the problems with bloom filters initiated the drive towards client-side transaction filtering based on trustless peer connections, and with no privacy leaks. In this article, I provide a basic overview of how light clients utilize bloom filters for payment verification, some of the challenges associated with their use, and why there was a need for a different way to conduct transaction verification.</p><h3>Light Client Transaction Verification</h3><p>Not all devices have the “luxury” of performing independent verification of transactions, which can only be done with access to the entire bitcoin ledger. This is primarily because of device-specific constraints on space, bandwidth, and processing power. These constrained devices are, in truth, only interested in the transactions related to the addresses in their wallets and should not be downloading multiple GBs of unrelated data. Also, with the growth of bitcoin, it has become increasingly more expensive to run a full node. Beyond just downloading the blockchain, nodes must remain connected to different peers on the network all the time. The memory, processing, and bandwidth requirements are quite “steep” and unreasonable for all nodes on the network to have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*Pv2C_RVntk5m7eNMUqEv3Q.png" /><figcaption>Figure 1: A block of transactions with a transaction of interest for a light client</figcaption></figure><p>For devices like mobile phones and tablets, it is possible to partake in the network by running lightweight clients — nodes that do not have access to the full blockchain but can conduct verification of payments by depending on full nodes, and their access to the complete ledger. To verify that a transaction of interest, i.e. paying bitcoins to address(es) on their wallet, is valid, the light clients create and send bloom filters to full nodes, who, in turn, forward just about enough block information (in a Merkle block) for the light clients to recalculate the Merkle root in the block header. The light clients check a transaction’s proof of inclusion if the Merkle roots match. This is the only way a light client can be sure that the transaction was included in this block.</p><p>The lack of access to the full blockchain translates to light clients delegating double-spend detection to full nodes and miners. Light clients are not exactly susceptible to double-spend attacks because they outsource the responsibility of detecting transactions spending the same UTXOs to miners. As long as honest miners have &gt;51% of the hashing power, there will be no double-spends, as enforced by the miners.</p><p>Full nodes can hide transactions from them, thereby denying them service. With the hope of peering with an honest full node, light clients randomly connect to several nodes on the network to combat the aforementioned attack. This makes them vulnerable to Sybil attacks that encircle them with fake nodes that disconnect them from the real network, stalling the light clients. This attack cannot steal funds but will impact usability.</p><p>Light clients conduct transaction verification by using tune-able bloom filters so that they do not leak information about the addresses in their wallets.</p><h3>Bloom Filters:</h3><p>Light clients cannot share their addresses/script_pubkeys to full nodes. Well, they can, but should not because of the loss of privacy in doing so. What they can do is create a superset of transactions they might be interested in. This is done using bloom filters — a probabilistic search filter. These filters are <strong><em>n</em></strong>-sized bit field created by passing transactions through a set number of hash functions, noting the output number <strong><em>q</em></strong> (between 1 and <strong><em>n</em></strong>) of each hash function, and flicking the bit at position <strong><em>q</em></strong> on (0 to 1).</p><p>This is how light clients use bloom filters. They:</p><ul><li>create a list of script hashes, and transaction IDs from any UTXO its wallet can spend: For any transaction paying bitcoins to addresses in the light client’s wallet, the light client creates a list containing the transaction’s ID, the pub keys, and hashes in the transaction output’s script_pubkey, each input in the transaction input, and signatures in the witness scripts (or script_sig). See the figure below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*p_QiLlgx5QWbIQvNWw_IDg.png" /><figcaption>Figure 2: Creating list of transaction objects</figcaption></figure><ul><li>add each list item to the bloom filter: Each item in the list is passed through the set number of hash functions to the bloom filter, as shown below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FpCjYySN3bMhxhTuY8pig.png" /><figcaption>Figure 3: Adding transaction objects to bloom filter</figcaption></figure><ul><li>send bloom filter to peers: The bloom filter is then sent to peers on the network. Full nodes match each incoming transaction to the bloom filter, sending a Merkle block to the light client only when there is a match.</li><li>verify transaction: With the Merkle block, the light client checks for matched transactions, and updates its view of the UTXO set, wallet balance, and the bloom filter to match future transactions that will reference the found UTXO.</li></ul><p>The way bloom filters work seems pretty straightforward. Light clients get to, to some degree, protect their privacy, and keep bandwidth and space requirements at a minimum. These benefits are not without their costs though. The risk of Sybil attacks remain for the light client. Full nodes also bear the brunt of the work when they match each incoming transaction to the bloom filters they received. It is work done without reward that also exposes them to denial of service attacks if they get spammed with fake bloom filters. Having one bloom filter per connected client does not scale.</p><p>For all the benefits of bloom filters, it appears most light clients rely on data from wallet vendors for transaction verification (Song, 2019). The drawback to using bloom filters heralded a new way for light clients to perform client-side transaction filtering and verification. This way has to provide the following benefits:</p><ol><li><strong>Privacy</strong>: Bloom filters are tune-able and you can achieve varying degrees of privacy by how they are constructed. The larger the size of the bitfield, and the number of hash functions, the greater the accuracy and specificity of the filter, and the worse the privacy score. With a lower specificity, the better the privacy score. Light clients should be able to request for block headers without worrying about how much privacy is lost with the specificity of their bloom filters. The new way must ensure that light clients can request for block data without compromising on their privacy.</li><li><strong>Trust</strong>: Light clients need to connect with at least one honest peer that would neither deny them service by hiding transactions nor send them double-spent transactions. The new way should encourage bitcoin’s philosophy of trustlessness. Light clients should request and get filter information for transactions they want to verify without having to trust any one honest peer.</li><li><strong>Work</strong>: Full nodes are in a state of perpetual work, scanning and re-scanning bloom filters for every incoming transaction they receive. Apart from providing a service that keeps the bitcoin network active for growing light clients, there is no reward for server-side transaction filtering. The risks of DOS attacks also need consideration. If a new solution to the transaction verification problem for light clients reduces the work of scanning to one-time computation and eliminates the attack vector, then that should be explored.</li><li><strong>Size</strong>: The size of the new filter should be lightweight. Small enough to compute and save to disk, and to relay along the network.</li></ol><p>The proposal and implementation of compact block filters provided these benefits. In the follow-up article to this, I will explore compact block filters and how it is a better alternative to bloom filters.</p><h3>Conclusion</h3><p>As bitcoin adoption grows, so has the growth of light clients. These clients, without access to the full ledger, have particular requirements concerning transaction verification for addresses in their wallets. They rely on a payment verification method that creates and sends bloom filters to full node peers. These filters are tune-able, giving light clients privacy control, but makes them vulnerable to Sybil attacks. These filters also place a disproportionate amount of work on full nodes. To counter the disadvantages, a new kind of filtering system called compact block filters was proposed and will be the topic of discussion in my article.</p><h3>Contact me</h3><p>I would deeply appreciate any feedback you can provide. If you found this article helpful/useful or found factual misrepresentation, please do not hesitate to comment or contact me here or on Twitter <a href="https://twitter.com/engb_os">@engb_os</a>.</p><h3>References</h3><ol><li>Antonopoulos, A. (2017). <em>Mastering Bitcoin: Programming the open blockchain</em></li><li>Song, J. (2019). <em>Programming bitcoin: Learn how to program bitcoin from scratch</em></li><li>Rosenbaum, K. (2019). <em>Grokking Bitcoin</em></li><li>Mouton, E (2021): <em>Compact Block Filters Deep Dive (BIP 158)</em>. <a href="https://bitcoin-dev.blog/blog/bip158-deep-dive/">https://bitcoin-dev.blog/blog/bip158-deep-dive/</a>. <em>Accessed 2 May 2022.</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=164d046f34b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a lightning node server and command-line interface (CLI)]]></title>
            <link>https://enigbe.medium.com/building-a-lightning-node-server-and-command-line-interface-cli-2b76fcd06028?source=rss-7ab9ec0a61e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b76fcd06028</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[actix-web]]></category>
            <category><![CDATA[lightning-network]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[cli]]></category>
            <dc:creator><![CDATA[enigbe ochekliye]]></dc:creator>
            <pubDate>Thu, 05 May 2022 02:00:12 GMT</pubDate>
            <atom:updated>2022-05-05T08:05:18.144Z</atom:updated>
            <content:encoded><![CDATA[<p>I spent the two weeks working on <a href="https://github.com/enigbe/LN-Node">LN-Node</a> — a CLI and server built on top of the Lightning Developer Kit (LDK) sample lightning node. I wanted to understand some of the inner workings of a lightning node and thought the best way to learn was to dive head-first into the LDK sample node. In this time frame, I forked and re-architected the LDK node application into one that has a separate CLI binary and server, embedded within the node, listening for requests from different client types. In this article, I try to explain my thought process while learning and building. It also contains information on how to test the application and upgrades I would love to implement sometime in the near future.</p><h3>Architecture</h3><p>This section covers some of the architectural modifications I made. It describes the state of the ldk-sample, the server, and the CLI binary.</p><h4>Lightning Node: ldk-sample</h4><p>This binary has remained largely unchanged from what I forked. A lightning node is a complex application with several parts coupled across the lightning protocol suite. The thought and decision-making that went into the network, messaging, p2p, routing, and payment layers were things that I didn’t want to change, given my scant but growing knowledge about the lightning network architecture. The fact that certain features are built across multiple layers meant that any changes I made, with the expectation that they would be constrained to one, would trickle across other layers.</p><p>The ldk-sample node has a coupled CLI as the only way to interact with the node. This CLI process commands that allow peer connection, channel opening, invoice generation, sending payment, signing messages, and a handful of other commands to glean information about the state of the node and to act in a channel with channel partner/peer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*xk6sCvmKSdeXIivc_oHtbw.png" /><figcaption>Figure 1: ldk-sample node</figcaption></figure><p>My goal for this project was to decouple the CLI and run the node in ways akin to how LND runs, i.e. lnd node running separately with lncli sending commands and retrieving node state responses. Within the LDK node, I decided to build a server that would listen to requests from the CLI, as well as other clients capable of sending requests to the server. The diagram below shows a depiction of the architectural changes I decided to make.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*nLfFIk2JtnQj7qBaSFQ1MQ.png" /><figcaption>Figure 2: LN-Node</figcaption></figure><h4>Server</h4><p>In the entry point to the <a href="https://github.com/lightningdevkit/ldk-sample">ldk-sample</a> project is a call that polls start_ldk() to start the node. Within this start function, the CLI for the node is started too. This interface polls for users’ input, matching them against defined lightning commands to, for example, get a node&#39;s information, or list connected peers, among others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*4QCEeGWBf4xRCMSeQxLjlA.jpeg" /><figcaption>Listing 1: ldk-sample entry point</figcaption></figure><p>I decided to replace the CLI’s loop within the node’s start-up function with a running instance of an actix-web server as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*RlKGhvRhsdPGJF8JuRa4cA.jpeg" /><figcaption>Listing 2: Replacing the CLI loop with a server</figcaption></figure><p>To pass the node’s variables to the server’s application state, I defined a struct NodeVar&lt;EventHandler&gt;, generic for any field that implements EventHandle. This event handler takes in the node&#39;s handle_ldk_events function and polls in another tokio runtime, awaiting the various event outcomes (e.g. funding generated, payment received, etc) possible within a payment channel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*MEkk_0SrzdLD4KqotmO_2A.jpeg" /><figcaption>Listing 3: Implementing an event handler</figcaption></figure><p>With this implementation, I could then create handlers for each command/path as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*UCKyCaBoouzXx42DLY0tow.png" /><figcaption>Listing 4: server handlers</figcaption></figure><p>For demonstration purposes, the node variable struct node_var is passed to the list_peers request handler within which the peers connected to the LN-Node can be retrieved and sent back to the calling client (CLI or HTTP).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*2l8O5VTQqi36DGY4UbFmuA.jpeg" /><figcaption>Listing 5: Retrieving connected peers</figcaption></figure><p>Beyond just the CLI making requests to this server, I wanted external HTTP clients to have the same capabilities, i.e. getting information about the node’s state, and acting to transact with other nodes in the network. I thought this would be a nice-to-have because of its “perceived” ease of use when compared with CLIs. Imagine having a dashboard with a great user interface to interact with your lightning node.</p><h4>CLI binary</h4><p>For the CLI to run separately, I created a different binary lnnode-cli within the project to take in command inputs, extract matching request body, send a request to the node&#39;s server with the reqwest crate, process server responses, and print to the caller&#39;s terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*_aOdOwEAXeIi0vRYBBEHzA.jpeg" /><figcaption>Listing 6: Collecting user command line input</figcaption></figure><p>To demonstrate the construction of a request body for the connectpeer command, the corresponding match arm parses the command’s arguments, i.e. public key, host, and port, to generate a hash map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*Yb8AwWaEouPN7FYC-GlkLw.jpeg" /><figcaption>Listing 7: Constructing hash map for request body</figcaption></figure><p>With the map constructed, the reqwest client can send the request to the server with the right body, i.e. json(&amp;command). To further explain what right means here, a user would type out a command on the terminal to connect with a new peer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*0CjngxOxxkOBWmvyNtRlrA.png" /></figure><p>The request body constructed from this terminal input is a hash map that is saved to the variable command .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*26KoBPKljTmpfLDaL-AH5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*XmMtwVhnALUgpuIr9lWp0g.jpeg" /><figcaption>Listing 8: Sending request to server with request body</figcaption></figure><p>With the returned response, the processing can be done and printed to the terminal within a match arm for the path visited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*8N9kSoeDSYfjKGapgwx6mg.jpeg" /><figcaption>Listing 8: processing server response to view a listing of connected peers</figcaption></figure><h3>Testing</h3><p>If you do not have bitcoin core and either LND, eclair, or c-lightning installed, testing the application will be difficult because of all the setup required. However, with the installation of <a href="https://lightningpolar.com/">Lightning Polar</a> , you can create a node network with as many as 3 lightning nodes and 1 block source (i.e. bitcoin core running in regtest). LN-Node can be connected to polar’s bitcoind and establish direct channels with any of the other nodes in the network. With the pre-requisites covered, clone the <a href="https://github.com/enigbe/LN-Node">LN-Node</a> repository and change to its root directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*-px6C_wZixzkAThnP_fE0A.png" /></figure><p>Within the root directory is a startup script lnnode.sh I wrote to make the process easier. With polar running and bitcoin node selected, copy the connection details from the Connect tab and populate the matching fields in the start-up script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NmZCwDIHQ-vzs6U_ON6Dag.png" /><figcaption>Figure 3: Polar’s bitcoind connection information highlighted in red</figcaption></figure><p>Having done that, open a terminal and run the script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*f06zFPSIcIOCYv6ygxpN4w.png" /></figure><p>This starts up the node and the embedded server. Switch to another terminal to test the CLI and get a list of the command and arguments that can be passed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*XNoDSTs--1z2iHMjx-dO3w.png" /></figure><p>With a HTTP client like Postman or Insomnia, the same requests to the node server can be made just like the CLI. Below is a screenshot of the request to open a channel with a peer with public key as shown, listening on host 127.0.0.1 and port 9736, with a channel funding amount of 100,000 sats.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*LdwMkChYeYfvwdY6VTsfuQ.png" /></figure><p>This node information was gleaned from another node (carol) on polar. The repo also has a JSON file (insomnia_rest_api.json) importable into a client like <a href="https://insomnia.rest/">Insomnia</a> to test the endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*8zSw95A-iFD0Nafz6kdEWg.png" /></figure><h3>Upgrades</h3><p>As my knowledge of the lightning network and Rust grows, I expect to periodically revisit and upgrade this project primarily to achieve the following:</p><ol><li>Remove reliance on the ldk-sample node by building a lightning node from scratch</li><li>Capture the channel events in server responses</li><li>Use a CLI-dedicated crate like clap to build a better client</li></ol><h3>Conclusion</h3><p>The building experience was more challenging than I anticipated. I struggled with Rust more than I expected to, given that I had spent over a month learning the language. However, some positives to take from this experience is my increasing comfort reading and writing the language, as well as my growing knowledge of the lightning network.</p><p>I am always open to helpful feedback. Reach out here or on Twitter (<a href="https://twitter.com/engb_os">@engb_os</a>) if you have some or just want to chat.</p><h3>References</h3><ol><li>LDK-sample: <a href="https://github.com/lightningdevkit/ldk-sample">https://github.com/lightningdevkit/ldk-sample</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b76fcd06028" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lightning Network: Establishing direct payment channels]]></title>
            <link>https://enigbe.medium.com/lightning-establishing-direct-payment-channels-2c5a7a5dd0de?source=rss-7ab9ec0a61e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c5a7a5dd0de</guid>
            <category><![CDATA[payment-channels]]></category>
            <category><![CDATA[lightning-network]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[enigbe ochekliye]]></dc:creator>
            <pubDate>Mon, 25 Apr 2022 08:35:48 GMT</pubDate>
            <atom:updated>2022-04-25T08:43:50.472Z</atom:updated>
            <content:encoded><![CDATA[<p>In the lightning network, payment channels define a financial relationship between network-connected peers, within which peers can make multiple fast, cheap, and private off-chain payments, by distributing the funds from a 2-of-2 multisignature address constructed with the public keys of the channel peers. Visually, a payment channel can be thought of as a link/edge between two nodes/vertices. I learned to visualize payment channels as the strings on an abacus where micro-payments between peers Bob and Alice could be made by sliding millisats along.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*kSvOcl2w5XKtn443N_L41w.png" /><figcaption>Figure 1: Lightning: Micropayments on a string</figcaption></figure><p>The creation of payment channels is foundational to the lightning network, underpinning the ability of connected nodes to make off-chain payments. Establishing these channels involves six (6) message exchanges between prospective peers to set channel capabilities, create funding and refund transactions, and enter channel operations of forwarding payments. In this article, I will briefly explain each one of these messages with a particular focus on funding &amp; refund transactions.</p><h3>Part I: Setting channel capabilities</h3><p>Prospective channel peers who would like to make millisat payments with each other start the process of creating a payment channel by sending two messages: <strong>open_channel</strong> where the initiator communicates their channel expectations, and <strong>accept_channel</strong> where the recipient accepts the proposed channel.</p><h4>1. Requesting to open a channel</h4><p>In the former, information regarding how much the channel will be funded with, the minimum channel balance, the time a peer needs to wait before claiming their funds in unilateral channel closing, the public key of the initiator, among others.</p><h4>2. Accepting proposed channel</h4><p>If the proposed channel expectations are found acceptable, the recipient responds with the latter message, providing their public keys also, alongside other information. The public keys of both the initiator and the recipient are needed to construct a 2-of-2 multisignature address for the funding transaction.</p><h3>Part II: Creating funding and refund transactions</h3><p>Having established a willingness to operate a channel between themselves, the initiating channel peer will do the following, in order:</p><ul><li>create a transaction payable to multisignature address constructed from both their public keys,</li><li>create a funding transaction without broadcasting the said transaction,</li><li>create a refund transaction chained with the funding transaction’s outpoint,</li><li>send a <strong>funding_created</strong> message to the recipient channel peer with the funding transaction’s ID and output index.</li></ul><p>The recipient channel partner will, upon receiving the message from the initiator:</p><ul><li>create and sign their version of the refund transaction</li><li>send a <strong>funding_signed</strong> message to the initiator</li></ul><p>With both signatures, the funding transaction can be broadcast and confirmed for channel operations to commence. This section will look a the creation of multisignature addresses, and the creation of funding and refund transactions.</p><h4>1. Multisignature Address Generation</h4><p>Consider the scenario where some entity created a *<strong>p2wpkh*</strong> transaction paying Alice <strong>200,000</strong> sats as depicted below. If Alice can provide a witness script structured in the same format as the witness script of <strong>Tx0P</strong> that redeems the UTXOs in <strong>Tx0Q:3</strong>, then Alice can spend the amount contained in <strong>Tx0P:0</strong> by providing a valid signature and a public key whose hash produces the same 20-byte hash contained in the transaction output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*c_ioXUrIzsXF4XH6gYiIVA.png" /><figcaption>Figure 2: A p2wpkh transaction payable to Alice</figcaption></figure><p><strong>Note</strong>:</p><ul><li>The hash contained in the locking script is <strong>hash160</strong>, i.e. SHA256 + RIPEMD.</li></ul><p>With the function below, the serialized locking script *<strong>s*</strong> is doubly hashed to produce a 32-byte hash.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee72a45c73a77a987e6f1b6c04cf43be/href">https://medium.com/media/ee72a45c73a77a987e6f1b6c04cf43be/href</a></iframe><p>Alice (iniitaiting channel partner) can create a <strong>p2wsh</strong> multisignature address by doing the following:</p><ul><li>Create a multisignature witness/redeem script with both hers and Bob’s public keys. Take note that the ordering of public keys presented here is just for depiction and not as is done in practice. Ideally, the ordering is done lexicographically.</li><li>Hash the script to get a 32-byte hash</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*A1cD_9Ctq6b65WtG0LMiUw.png" /><figcaption>Figure 3: Hashing witness script to generate a p2wsh public key script</figcaption></figure><h4>2. Funding transaction</h4><p>With the multisignature hash address, Alice can construct a funding transaction that pays say 140,000 sats to Bob (recipient channel partner). A visualization of the transaction is shown. Here Alice spends from a single input and pays to two addresses. The first is the payment to the multisignature address, and the second is change back to her.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*K3lUsf84duXQjDZvDHbbEw.png" /><figcaption>Figure 4: Creating a p2wsh funding transaction object (<strong>Tx01</strong>)</figcaption></figure><p>This transaction (<strong>Tx01</strong>) is not broadcast to the network by Alice but withheld. This withholding is done because Alice does not have the second quorum (Bob’s signature) to unlock the transaction if it is mined, without which she essentially has thrown money away if Bob withholds his signature. To get this signature, Alice has to send Bob a funding_created message, but not before creating a refund transaction that spends the UTXOs locked to the multisignature address, payable to herself.</p><h4>3. Refund transaction</h4><p>With the funding transaction created, Alice gets to create a <strong>p2wpkh</strong> refund transaction that pays the UTXOs locked in the 2-of-2 multisignature address to herself. As much as the funding transaction has not been broadcast, Alice can trust that the transaction’s ID will remain unchanged so that when it is eventually relayed to the network and mined, there is no malleability vector to worry about (<a href="https://medium.com/p/51f4ee1c2cbd">thanks to segwit</a>). When it is relayed and mined, Alice also needs Bob’s signature to spend the UTXO.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IyfC1ZOBviphebO6GwoiDA.png" /><figcaption>Figure 5: Creating a p2wpkh refund transaction (<strong>Tx02</strong>)</figcaption></figure><p>To get the needed signature, Alice sends a <strong>funding_created</strong> message to Bob letting him know about the funding outpoint. Bob creates and signs his version of the refund transaction and lets Alice know by sending a <strong>funding_signed</strong> message containing the signature corresponding to his public key used in creating the 2-of-2 multisignature address.</p><p>With both signatures, Alice has enough information to broadcast the funding transaction to the bitcoin network without fear of losing her money. She has the signatures needed in the witness script as shown in the rightmost transaction (see Figure 5) to recover all her money.</p><p>Having broadcast and confirmed the transaction, both channel partners share a <strong>funding_locked</strong> message that signals the readiness of the channel for operations (sending payments) between the peers.</p><h3>Conclusion</h3><p>In this article I looked at the messages prospective channel partners must share before a payment channel between them can be established using some diagrams that helped me visualize the processes better. Prospective peers must agree on the channel capabilities, the initiator must create funding and refund transaction and inform the other partner about this, sending enough information for the partner to create and sign their copy of the refund transaction, sharing the signature needed to refund the initiator if something goes wrong.</p><h3>Contact me</h3><p>I would deeply appreciate any feedback you can provide. If you found this article helpful/useful or found factual misrepresentation, please do not hesitate to comment or contact me here or on Twitter <a href="https://twitter.com/engb_os">@engb_os</a>.</p><h3>References</h3><ol><li>Song, J. (2019). <em>Programming bitcoin: Learn how to program bitcoin from scratch</em></li><li>Rosenbaum, K. (2019). <em>Grokking Bitcoin</em></li><li>Antonopoulos Andreas, Osuntokun Olaoluwa, &amp; Pickhardt René. (2021). <em>Mastering the lightning network: A second layer blockchain protocol for instant bitcoin payments</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c5a7a5dd0de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Randomness, signature scripts, and transaction malleability]]></title>
            <link>https://enigbe.medium.com/randomness-signature-scripts-and-transaction-malleability-51f4ee1c2cbd?source=rss-7ab9ec0a61e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/51f4ee1c2cbd</guid>
            <category><![CDATA[malleability]]></category>
            <category><![CDATA[signature]]></category>
            <category><![CDATA[randomness]]></category>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[enigbe ochekliye]]></dc:creator>
            <pubDate>Tue, 19 Apr 2022 07:41:23 GMT</pubDate>
            <atom:updated>2022-04-19T07:47:47.268Z</atom:updated>
            <content:encoded><![CDATA[<p>Segregated witness brought along with its activation a host of changes including fixing transaction malleability — the ability of a transaction’s identifier, a <strong>SHA256</strong> hash of the transaction, to change without the underlying transaction changing. A transaction object typically contains the following fields: version, transaction inputs (containing previous hash, previous index, signature script, and sequence), transaction outputs (containing amount and public key scripts), and the locktime.</p><p>These fields, except for the <strong>signature script</strong>, cannot be changed without invalidating the transaction. The field containing the unlocking script is emptied (a signature should not sign itself) before the transaction is hashed thus making it possible to change the unlocking script without rendering the transaction useless. Because of this reason, different unlocking scripts can represent the same transaction. How is this so? Initially, I thought that it had to do with how signatures are calculated, given that randomness is embedded in the signing algorithm used to sign transactions.</p><p>From my perspective, understanding the basic underlying mathematics of the signing process could provide some insights. Hence, in this article, I will explain my understanding of the basic math of signing, how different signatures, and in extension, unlocking scripts, can apply to the same transaction, and how segwit fixed transaction malleability.</p><h3>Basic mathematics of signing</h3><p>Signing is a way to prove the knowledge and possession of a secret number, i.e. private/signing key (<strong><em>e</em></strong>) without revealing this number. We know that in asymmetric cryptographic systems</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*-iQeEevmKkgJdU-2Z5xuyA.png" /><figcaption>Equation 1: Calculating public key from private key and generator point</figcaption></figure><p>where <strong><em>G</em></strong> is the generator point and <strong><em>P</em></strong> is the public key.</p><p>To sign a transaction hash, a random number <strong><em>k</em></strong> is selected such that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*cDhgyiUzCqsS5iFflFNGkg.png" /><figcaption>Equation 2: Calculating signature’s r value</figcaption></figure><p>I assumed that because <strong><em>G</em></strong> lies on the elliptic curve, <strong><em>R</em></strong> lies on it too so that the summation of two points on the curve will give the position of <strong><em>R</em></strong> (<a href="https://enigbe.medium.com/about-elliptic-curves-and-dlp-ed76c5e27497">addition is closed in a finite field</a>). These points (<strong><em>u, v</em></strong>) can be selected by the signer as depicted in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*aFAbFMhPAUAZisaIgG-kGQ.png" /><figcaption>Figure 1: Elliptic curve with uG, vP and kG points on the curve</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*-xttBm6K1xkEEhQqhM2zrQ.png" /><figcaption>Equation 3: Discrete Logarithm Problem (DLP)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*RCD7zxDOmsNN_sWyP3Lfug.png" /></figure><p>Knowing that <strong><em>eG = P</em></strong>, and rearranging</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*6s4jbF43zsc1yGqWEatTCw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/98/1*Kqce843_s1TmE1VA8xlSeQ.png" /><figcaption>Equation 4: Target of the signing</figcaption></figure><p>Equation <strong>4</strong> can be considered as another way to represent the discrete log problem (DLP) because you either have knowledge of <strong><em>e</em></strong>, to select <strong><em>k</em></strong> such that <strong><em>(k — u)/v</em></strong> is equal to <strong><em>e</em></strong> (thus solving <strong><em>eG = P</em></strong>), or you try a brute force approach by selecting several combinations of <strong><em>(k, u, v)</em></strong>.</p><p>In generating a valid signature <strong><em>S(r,s)</em></strong> for a transaction, we:</p><ul><li>hash the transaction to get <strong><em>z</em></strong> (the transaction hash) — taking note to empty the unlocking script and append appropriate <a href="https://enigbe.medium.com/signature-hash-flags-f059d035ddd0">signature hash flags</a>,</li><li>choose a random unique <strong><em>k</em></strong>,</li><li>calculate <strong><em>kG = R(r,y)</em></strong> and select its <strong><em>x</em></strong>-coordinate (<strong><em>r</em></strong>),</li><li>and calculate <strong><em>s</em></strong> such that the transaction hash (<strong><em>z</em></strong>), and signing key (<strong><em>e</em></strong>) are incorporated into the signature by selecting u and v as shown below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*XZBt3pyqUEsBjT6o8DOzoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*BFSOuRupQxZc0IgkbhW-OA.png" /></figure><p>Composing r and s gives a valid signature for the transaction.</p><h3>Why different signature scripts can apply to the same transaction</h3><p>As can be seen, any combination of <strong><em>k</em></strong> (must be unique for a signature), <strong><em>u</em></strong>, and <strong><em>v</em></strong> that satisfies the equation is valid for the given transaction hash <strong><em>z</em></strong>. From the signer’s perspective, this is fine. The signer of a transaction can sign the transaction many times, generating different signatures valid for the said transaction. This signature is then embedded in the signature script of the transaction, and then broadcast to the network.</p><p>However, some malicious users on the network can receive the broadcast transaction and modify it in different ways to generate a new valid but malleated transaction, which is essentially the same as the initially broadcasted transaction, albeit with a different transaction ID. These transactions spend the same inputs, transferring the same value to the same outputs, thus creating a conflict where only one of these transactions will be mined and added to the ledger. If the malleated transaction is mined, other transactions referencing outputs from the original transaction cannot spend from it.</p><p>How is this transaction malleability possible? The malicious user can modify the signature format of, add extra instructions to, or use cryptographic tricks on the signature script (Rosenbaum, 2019). Basically, by changing the signature script of the transaction, which changes the serialized transaction, and the transaction identifier.</p><h3>Segwit and fixing transaction malleability</h3><p>Segwit proposed to move the signature script data into another field — the <strong>witness</strong> field — that is not used for calculating the transaction ID, so that changes to the signature script field cannot impact the transaction identifier.</p><h3>Conclusion</h3><p>Randomness and the selection of a unique <strong><em>k</em></strong> value per signature allow signers to mutate transaction objects. They can generate different signatures for a transaction although one is selected and embedded into the unlocking script. In broadcasting their signed transaction, pre-segwit, users could experience a malleability attack that allowed malicious users to modify the signature script field of the broadcast transaction and change the transaction’s identifier. With segwit, moving the data from the signature script into a field that does not impact the calculation of the transaction ID, eliminated the malleability attack vector.</p><p><strong>Note</strong>:</p><p>I would deeply appreciate any feedback you can provide. If you found this article helpful/useful or found factual misrepresentation, please do not hesitate to comment or contact me here or on Twitter <a href="https://twitter.com/engb_os">@engb_os</a>.</p><h3>References</h3><ol><li>Antonopoulos, A. (2017). Mastering bitcoin: Programming the open blockchain</li><li>Song, J. (2019). <em>Programming bitcoin: Learn how to program bitcoin from scratch</em></li><li>Rosenbaum, K. (2019). <em>Grokking Bitcoin</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51f4ee1c2cbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signature Hash Flags]]></title>
            <link>https://enigbe.medium.com/signature-hash-flags-f059d035ddd0?source=rss-7ab9ec0a61e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f059d035ddd0</guid>
            <category><![CDATA[signature]]></category>
            <category><![CDATA[flags]]></category>
            <category><![CDATA[sighash]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[enigbe ochekliye]]></dc:creator>
            <pubDate>Mon, 11 Apr 2022 08:10:04 GMT</pubDate>
            <atom:updated>2022-04-11T10:16:49.314Z</atom:updated>
            <content:encoded><![CDATA[<p>A digital signature is a “mathematical scheme for demonstrating the authenticity of a message” (Antonopoulos, 2017). It finds use in bitcoin transactions where it proves that transactions have been created by “known” senders, that “known” senders cannot repudiate broadcast transactions, and that the transactions have not been changed from source to destination(s). Signatures are created by passing the transaction (or parts of it) through a hashing function and subsequently through a signing function that uses the owner’s private key.</p><p>Signatures can apply to all or parts of a transaction and the way we can tell is by inspecting the signature hash flags. These flags are 8-bit long characters appended to the end of a signature and are important because they make it possible for transactions to be constructed in different ways. The simplest type of transaction one can construct is a transaction that has just one input, referencing a UTXO, that pays to a single output address. However, transactions can have multiple inputs and outputs, with inputs referencing UTXOs from different owners who may sign their inputs. In this way, a partially constructed transaction can be created, where owners collaborate to collect all the needed signatures to make the otherwise invalid transaction valid. With signature hash (SIGHASH) flags, signatures can indicate what part of the transaction is included in the hash.</p><p>This article briefly explains the anatomy of signatures and how to identify SIGHASH flags, the types of SIGHASH flags, how SIGHASH types are applied, as well as scenarios where they can be used.</p><h3>Anatomy of a DER signature</h3><p>Digital signatures are serialized using the Distinguished Encoding Rules (DER) which encodes the standards for serializing digital signatures <strong><em>S(r,s)</em></strong>. These signatures consist of the following parts, in order:</p><ol><li>A starting byte of hex value <strong>[0x30]</strong></li><li>Length of the signature sequence <strong>[0x44]</strong> or <strong>[0x45]</strong></li><li><strong><em>r</em></strong>-marker byte of hex value <strong>0x02</strong></li><li>Length of <strong><em>r</em></strong> <strong>[0x21]</strong>|| Big-endian representation of <strong><em>r</em></strong></li><li><strong><em>s</em></strong>-marker byte of hex value <strong>0x02</strong></li><li>Length of <strong><em>s</em></strong> <strong>[0x20]</strong>|| Big-endian representation of <strong><em>s</em></strong></li><li>1-byte SIGHASH suffix*</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWW1EBMl0i6sB-883cY1ow.png" /><figcaption>Figure 1: Anatomy of a DER signature</figcaption></figure><h3>Types and application of signature hash flags</h3><p>There are three types of signature hash flags: ALL, NONE, and SINGLE. Figure 3 shows the byte representation of each type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*5MlTKiehVw-VzTjo23y1CA.png" /><figcaption>Figure 2: SIGHASH types</figcaption></figure><p>For <strong>SIGHASH</strong> <strong>ALL</strong>, given a transaction Tx, the signature applies to all of Tx’s inputs and all its outputs (see green bounding boxes). SIGHASH ALL is applied by</p><ol><li>Creating a copy of the transaction,</li><li>Empty <strong><em>script_sigs</em></strong> for each input and replace with the <strong><em>script_pubkey</em></strong> they reference. This is done because the “signature is part of the script_sig and … can’t sign itself” (Song, 2019, p. 132)</li><li>Make sure that <strong>no</strong> other fields are set to empty before the transaction is serialized (<strong>Tx_ser</strong>).</li><li>The flag 0x01 is added to the end of the serialized transaction and passed through a hashing function.</li><li>This message is then signed by the signing algorithm to generate the signature.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*jcCqHCemV59BQvIirVXMSw.png" /><figcaption>Equation 1: Hashing function for SIGHASH ALL transaction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*8xHupP6dr2sCffIvEyeFiw.png" /><figcaption>Equation 2: Signing algorithm</figcaption></figure><p>where <strong><em>e</em></strong> is the signer’s private key and <strong><em>S(r,s)</em></strong> the signature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*E7CTcr4PAxioHYd04wXzDQ.png" /><figcaption>Figure 3: SIGHASH ALL</figcaption></figure><p>The transaction is rendered invalid if any of its details are changed because the signature will change too and be invalid.</p><p>For <strong>SIGHASH</strong> <strong>NONE</strong>, the signature applies to all of Tx’s inputs (see green bounding box) but to none of the outputs. The application process is as stated below:</p><ol><li>Create a copy of the transaction</li><li>Empty each script_sig for all inputs and replace with the script_pubkey they reference</li><li>Empty out all output fields</li><li>Serialize the transaction</li><li>Append 0x02 to <strong>Tx_ser</strong>, hash, and then sign</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*wl4mqPw5ZQwB6fxhwo3DCA.png" /><figcaption>Equation 3: Hashing function for SIGHASH NONE transaction</figcaption></figure><p>For <strong>SIGHASH NONE</strong>, any output can be modified without invalidating the signature, but if any one of the inputs is modified, the signature is rendered invalid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*oO94JmqsqQW4sdTY4dxu9Q.png" /><figcaption>Figure 4: SIGHASH NONE</figcaption></figure><p>For <strong>SIGHASH</strong> <strong>SINGLE</strong>, all the inputs of the given transaction Tx are signed and one output that has the same index of one of the inputs being signed. This is essentially “authorizing all other inputs to go with a specific output” (Song, 2019, p. 133).</p><ol><li>Create a copy of the transaction</li><li>Empty script_sigs for each input and replace with the script_pubkey they reference</li><li>Empty out all output fields bar the specific output</li><li>Serialize the transaction</li><li>Append 0x03 to <strong>Tx_ser</strong>, hash, and then sign</li></ol><p>A change to the specified output or to any of the inputs invalidates the signature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*ljI1g7cnIBEmj_vss6LXWQ.png" /><figcaption>Figure 5: SIGHASH SINGLE</figcaption></figure><h4>Modifier Flag</h4><p>An <strong>ANYONECANPAY</strong> modifier flag exists that can be added to the aforementioned flags that apply to a <strong>single</strong> input in a transaction. Rosenbaum (2019) considers the ANYONECANPAY modifier flag as a way to commit to inputs only, by setting or not setting it, and the existing SIGHASH types (ALL, NONE, SINGLE) as a way to commit to outputs only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*AMh9zBo5qGEKomZ7UG5fWQ.png" /><figcaption>Figure 6: ANYONECANPAY modifier</figcaption></figure><p>With ANYONECANPAY set for ALL, changes can be made to all inputs except the select input (index 0) and the outputs (see image below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*CqhYEWyDjUBKb5_6eVUz1g.png" /><figcaption>Figure 7: ALL|ANYONECANPAY</figcaption></figure><p>ANYONECANPAY set for NONE means that changes can be made to all outputs, and inputs except the current input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*bOaMqr1z87dpiUVktqg2cA.png" /><figcaption>Figure 8: NONE|ANYONECANPAY</figcaption></figure><p>ANYONECANPAY set for SINGLE means that changes can be made to all outputs except the output with a matching index with the current input. All other inputs can be modified, added, and/or removed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*2_10xy7lebzKFeMnRxDUcg.png" /><figcaption>Figure 9: SINGLE|ANYONECANPAY</figcaption></figure><h3>Scenarios</h3><p>The table below shows a summary of use cases where these flags can be applied</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*cpjp8e4h0JSDP-7d1dwYKQ.png" /><figcaption>Table 1: Use cases for SIGHASH flags</figcaption></figure><h3>Conclusion</h3><p>In reviewing the bitcoin fundamentals necessary to explore the lightning network, I went down the rabbit hole of signature hash flags. These flags mark the parts of a transaction that are signed by a signature and provide flexible ways to construct transactions. I explained how to identify these flags from the anatomy of a DER signature, the 6 types of flags (including modifiers) that exist, and how some of these flags are applied to a transaction.</p><p>I would deeply appreciate any feedback you can provide. If you found this article helpful/useful or found factual misrepresentation, please do not hesitate to comment or contact me here or on Twitter <a href="https://twitter.com/engb_os">@engb_os</a>.</p><p><strong>Note</strong>:</p><ol><li>The <strong>||</strong> symbol is used to indicate concatenation</li><li><strong>*</strong> SIGHASH flags should be a byte long although implementation serializes them to 4-bytes. Pieter Wuille provides a possible reason why this is the case <a href="https://bitcoin.stackexchange.com/questions/48108/why-are-sighash-flags-signed-as-4-bytes-when-only-1-byte-is-included-in-the-tran">here</a>.</li></ol><h3>References</h3><ol><li>Antonopoulos, A. (2017). Mastering bitcoin: Programming the open blockchain</li><li>Song, J. (2019). <em>Programming bitcoin: Learn how to program bitcoin from scratch</em></li><li>Rosenbaum, K. (2019). <em>Grokking Bitcoin</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f059d035ddd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lifetime Specifiers in Rust]]></title>
            <link>https://enigbe.medium.com/lifetime-specifiers-in-rust-8cdc1f070940?source=rss-7ab9ec0a61e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cdc1f070940</guid>
            <category><![CDATA[lifetime]]></category>
            <category><![CDATA[struct]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[function]]></category>
            <dc:creator><![CDATA[enigbe ochekliye]]></dc:creator>
            <pubDate>Mon, 14 Mar 2022 11:37:12 GMT</pubDate>
            <atom:updated>2022-03-21T14:10:08.153Z</atom:updated>
            <content:encoded><![CDATA[<p>Lifetimes, ownership, and borrowing are some of the fundamental concepts to grasp if I must write fluent rust. Lifetimes, in particular, ensure that functions, closures, structs, enums, and structs that own certain objects remain their owners after other variables have borrowed and/or returned them. It is <em>“some stretch of your program for which a reference could be safe to use”</em>.</p><p>They are “structures” we put in place to inform the compiler that objects borrowed remain, even after the borrowing object has been destroyed. We never really have to worry about lifetimes except when we create structs whose fields have borrowed data, or when we want to return borrowed data from a function.</p><p>I learned how to build a <a href="https://github.com/enigbe/pbjs">utility bitcoin library</a>, in Python, in February, and set a goal to port the said library to Rust. In the course of doing so, I ran into a missing lifetime specifier error that questioned my knowledge of lifetimes.</p><p>This article is captures what I learned about lifetimes that helped me resolve my error. It presents a simple explanation of struct and function lifetimes.</p><h3>Struct Lifetimes</h3><p>Say, for example, that you have a structure that models a base dimension with two fields: length and breadth, as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*lfGDo7mks16OMaCdeXLU-A.png" /><figcaption>Referenced BaseDimension structure</figcaption></figure><p>If another structure, a Tank, references an instance of BaseDimension, then we know that the instance of the BaseDimension struct must exist before the Tank struct is created and must remain after the tank is destroyed. We would need to reference the BaseDimension instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*PttoMgzpzK2aFAHr88BVpQ.png" /><figcaption>Struct with reference field (no lifetime specification)</figcaption></figure><p>To define a lifetime for a structure, we use the following syntax:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*2dE9_mjhF3DyDsmGTin3Rw.png" /><figcaption>Struct lifetime specifier</figcaption></figure><p>For our tank example, we define a lifetime &#39;base for the BaseDimension as shown below, without which you would encounter a missing lifetime specifier error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*vv-l215QQqpibGvLQvdxlQ.png" /><figcaption>Struct with reference field and lifetime specifier</figcaption></figure><p>You can run a test of the code below on the <a href="https://play.rust-lang.org/">rust playground</a>. Here is a walk-through:</p><ol><li>[<strong>Lines</strong> 2–5]: A BaseDimension struct is defined and has two fields: length and breadth</li><li>[Line 8]: A Colour enum with three (3) variances R, G, and B is defined.</li><li>[Lines 11–14]: A generic Tank structure with a lifetime of &#39;base is defined, having two fields: colour which is an enumeration of R, G, or B, and &#39;base which is a reference to a BaseDimension structure with a defined lifetime of &#39;base .</li><li>[Lines 16–21]: Within main, a base instance and a tank instance, with reference to the base, are created. The println! macro references the tank instance after it is called. The base and tank instances remain alive. Note that base20x40 will be alive for however long tank20x40 is, and can only be safe for destruction after the tank instance has been dropped.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65ad1d7b153a84efa260e42f3a756422/href">https://medium.com/media/65ad1d7b153a84efa260e42f3a756422/href</a></iframe><h3>Function Lifetimes</h3><p>The second case to consider where lifetimes matter is with functions and returning borrowed values from them. The syntax is as shown below. Here we see the creation of two lifetimes <strong>&#39;lt_a </strong>and <strong>&#39;lt_b</strong> belonging to instances of <strong>TypeA</strong> and <strong>TypeB</strong> respectively. This function <strong>func </strong>returns a tuple of references to types <strong>TypeA</strong> and <strong>TypeB</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9kD4payvgzRUHaB0Pjt94Q.png" /><figcaption>Definition of function lifetime specifier</figcaption></figure><p>An illustrative example to show the use of lifetimes in a function is shown in Listing 2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac99505f4f60c5ee686bf833c52694f6/href">https://medium.com/media/ac99505f4f60c5ee686bf833c52694f6/href</a></iframe><p>A walk-through of the example is listed below:</p><ol><li>[Lines 2–6]: A City struct with three String fields: name , country , continent is defined.</li><li>[Lines 9–12]: A Hospital struct with a lifetime of &#39;city which will reference a borrowed instance of City</li><li>[Lines 14–16]: A function healthcare_centres with lifetime specifiers &#39;h and &#39;cityfor the parameters that are references to instances of &amp;Hospital and City . Note how the struct lifetime is passed and the type of the return value: a tuple of borrowed objects.</li><li>[Lines 18–34]: Within main, instances of City and Hospital are created, with their references passed as arguments to healthcare_centre . The println! macros show how objects referenced by the function and tracked by their lifetimes outlive the function that called them.</li></ol><p>The Rust compiler knows to save referenced instances in such a manner that it will outlive the function call. With the defined lifetimes, Rust can assess the relationship between the arguments passed to the function and the values returned in a safe way.<em> </em>We can tell that the reference(s) of the returned value from the function points to the arguments passed, and no where else<em>.</em></p><p><strong>Note</strong>:</p><ul><li>A special lifetime &#39;static is reserved by Rust for objects that must remain in memory until the program ends.</li><li>Rust infers lifetimes. They (lifetimes) are only needed in defining functions or types.</li></ul><h3>Conclusion</h3><p>Lifetimes are ways the compiler keeps track of what objects can/must remain alive as they are borrowed by other objects. This is how I like to think about them. If you liked this article and would like to see where I am applying some of the new Rust knowledge I have gained over the past two weeks, please check out <a href="https://github.com/enigbe/bitlib">bitlib</a> — my attempt to port a bitcoin utility library to Rust.</p><p>Looking forward to any feedback I can get.</p><h3>References</h3><ol><li>Blandy Jim, Orendorff, J., &amp; Tindall, F, S, Leonora. (2021). <em>Programming rust: Fast, safe systems development<br></em> (2nd ed.) O’Reilly Media Inc.</li><li><a href="https://academy.zerotomastery.io/p/learn-rust">Rust Programming</a>: The Complete Developer’s Guide by Jason Lennon</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cdc1f070940" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serializing Public Keys]]></title>
            <link>https://enigbe.medium.com/serializing-public-keys-188ae1f02ae0?source=rss-7ab9ec0a61e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/188ae1f02ae0</guid>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[public-key]]></category>
            <dc:creator><![CDATA[enigbe ochekliye]]></dc:creator>
            <pubDate>Thu, 03 Mar 2022 10:06:39 GMT</pubDate>
            <atom:updated>2022-03-03T10:06:39.869Z</atom:updated>
            <content:encoded><![CDATA[<p>Serialization refers to the transformation of an object or a data structure into a format that can be transmitted across a network, saved to disk, or to memory, to be reconstructed/parsed for later use. It is the conversion of an object’s instance into binary or text form for the use cases thus mentioned.</p><p>Serialization is important because of the need to communicate different object data structures in efficient ways. In this article I will share some information about how public keys are serialized for transmission and use on the bitcoin network.</p><p>However, before serializing data into a binary representation, it is important to know what endianness is and how it affects the process.</p><h4>Endianness</h4><p>Endianness is byte-order and refers to the way computers order/organize bytes that make up the digital data in a computer’s memory (MDN, 2021) or the order in which bits are relayed over a channel. consider the hexadecimal representation of a 32-byte number 0x0A0B0C0D as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*bHzM1a388q6C3yVJ9y7PcQ.png" /><figcaption>Figure 1: 32-byte word</figcaption></figure><p>To access whatever data is encoded into this 32-byte word, the address of where this data is stored needs to be known. There are two ways a computer can access each byte in this word; the computer could access from the right end or the left end. These are known as big and little endianness. In the former, as shown in the figure below, the byte with the most significant byte (MSB) is saved to the highest address location while its least significant byte (LSB) can be accessed at the smallest address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*GO7jLpS6Jd3MZaQGLB1a0g.png" /><figcaption>Figure 2: Big-endian byte order for a 32-byte word. (Image replicated as shown in Ref: 3)</figcaption></figure><p>For little-endian representations, the reverse is the case. Here the LSB is accessed at the highest address while the MSB is accessed at the lowest address containing the 32-byte word. But why does this matter? Some bitcoin objects (the <em>x-</em> and <em>y-</em>coordinates of public keys) are serialized as big-endian and others (transaction version number, Merkle root, block timestamp) as little-endian. Because computers can be more efficient using the little-endian order as opposed to the big-endian, the byte-ordering for different objects must be taken into consideration when serializing and/or de-serializing them.</p><h4>Public Keys</h4><p>Public keys are points <strong><em>P(x,y)</em></strong> on the <strong><em>secp246k1</em></strong> elliptic curve that bitcoin uses. They have x and y coordinates and are serialized using the Standards for Efficient Cryptography (SEC) — a known standard for Elliptic Curve Digital Signature Algorithm (ECDSA) public keys. For public keys, there are two SEC formats: uncompressed and compressed.</p><p>For the uncompressed format, a serialization of the point <strong><em>P(x,y) </em></strong>is created by doing the following:</p><ol><li>Define a 1-byte prefix: 0x04</li><li>Add to the prefix the x-coordinate of <strong><em>P(x,y)</em></strong> encoded as 32-byte big-endian integer</li><li>Add to the prefix and x-coordinate the y-coordinate encoded as 32-byte big-endian integer</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*Oua0DEzHxIDJrM1d3b5Nyg.png" /><figcaption>Figure 3: 65-byte uncompressed SEC format for public key</figcaption></figure><p>Given a simple integer representation of the coordinates of the public key, a function to serialize</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2220856ba23259e2d63bcc9ebb65ea81/href">https://medium.com/media/2220856ba23259e2d63bcc9ebb65ea81/href</a></iframe><p>Looking at Figure 3, we see that the uncompressed SEC format is 65 bytes long. The need arose to reduce the size of transactions and to conserve disk space on full nodes. Compressed public keys achieve this reduction by almost half the size of the uncompressed one (compressed public keys are 33 bytes long). This is done by some clever mathematics where just the prefix (encoding information about the evenness of the y-coordinate in 1 byte) and the x-coordinate (32 bytes) is stored.</p><p>The necessary background to understand the underlying mathematics about how compressed public keys are serialized can be found in [2]. The serialization process is:</p><ol><li>Defining a prefix byte with a value of either 0x02, depicting an even y coordinate, or 0x03, depicting an odd y</li><li>Add to the prefix the x-coordinate of <strong><em>P(x,y)</em></strong> encoded as 32-byte big-endian integer</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*pv_l7pEvAUTYQKXjV5PjJA.png" /><figcaption>Figure 4: 33-byte compressed SEC format for public key</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83f2e9eb71298ba700a08c1ac1e6e80d/href">https://medium.com/media/83f2e9eb71298ba700a08c1ac1e6e80d/href</a></iframe><h4>Base58 Format Addresses</h4><p>Addresses are alphanumeric strings that users can share to receive bitcoin. An address, in the simplest case, is a string derived from a public key using two hashing algorithms: SHA256 and RACE Integrity Primitives Evaluation Message Digest (RIPEMD).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee72a45c73a77a987e6f1b6c04cf43be/href">https://medium.com/media/ee72a45c73a77a987e6f1b6c04cf43be/href</a></iframe><p>Given the byte and space savings of the compressed format of a public key, it is still considered too long and difficult to read. To address the length, readability, and security of public keys, the need arose to use an encoding format that could express more bits per character. Mixed alpha-numeric representations with a base greater than 10 can be used to make long characters more compact.</p><p>The hexadecimal (hex) encoding is one of such representations. For a 65-byte public key, the hex encoding has twice as many characters (see Figure 5) where 2 hex characters are needed to encode 1 byte. This makes for a 130-character long public key — bad for readability. As much as the hex representation is much shorter than a decimal representation, a Base 64 offers even more compactness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*S7kNPytZreyPaML9YVNe-g.png" /><figcaption>Figure 5: Hexadecimal representation of 1 byte. Here we see 4 bits/character</figcaption></figure><p>A subset of Base 64, i.e. Base 58 encodes 6 bits/character and makes for a smaller (~87) characters set. Base 58 consists of all numbers (0…9), lowercase alphabets (a…z), and uppercase alphabets (A…Z). However, six (6) lookalike numbers/alphabets (0, O, l, I, -, _) and symbols were removed to form Base 58 and are used to encode addresses where bitcoins could be sent to.</p><p>Base 58 encoding is great because it offers the following benefits:</p><ol><li>Compactness</li><li>Easy to read</li><li>Error detection</li></ol><p>Listing 3 shows how to achieve compactness and better human readability for any bytes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e980c22a2dedb38f32a8d28e42435ce7/href">https://medium.com/media/e980c22a2dedb38f32a8d28e42435ce7/href</a></iframe><p>For error detection, Base58Check encoding format is used in bitcoin. This has built-in error-checking with a 4-byte checksum derived from the hashed SEC public key and added to the end of the SEC public key. The encoding process is as stated below:</p><ol><li>A ‘version byte’ known prefix is prefixed to the SEC public key. This version prefix could be any one of the following —<strong> 0x00</strong> (1) for bitcoin address, <strong>0x6f</strong> (m or n) for bitcoin testnet address, <strong>0x0488b21e</strong> (xpub) for extended public keys (not discussed in this article). The version byte helps with readability.</li><li>The checksum is computed by applying SHA256 hashing algorithm, twice, to the result above, extracting the first 4 bytes, and appending the result to the end (prefix + SEC public key + checksum). These bytes will help with error detection.</li><li>The result from 2 above is encoded with Base 58 function to address compactness.</li></ol><p>A complete implementation with a simplified public key class is as shown below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab3e22430d39501d1604c8a95db8a562/href">https://medium.com/media/ab3e22430d39501d1604c8a95db8a562/href</a></iframe><h4>Conclusion</h4><p>This article explains endianness and how they affect serializing bitcoin objects, the SEC format for uncompressed and compressed public keys, and the base58check encoding of SEC addresses that improve readability, compactness, and security. I have been learning about bitcoin and found it helpful to conceive of serialization like I have outlined — with schematic representations of binary objects, and code. If you would like a more accurate implementation of a public key, you should get a copy of Programming Bitcoin by Jimmy Song or read it <a href="https://github.com/jimmysong/programmingbitcoin">online</a>.</p><p>If you found this article helpful or have recommendations to make it better, please do not hesitate to contact me. Happy reading.</p><h4>References</h4><ol><li>MDN Contributors (2021, October 8): <em>Endianness. </em><a href="https://developer.mozilla.org/en-US/docs/Glossary/Endianness"><em>https://developer.mozilla.org/en-US/docs/Glossary/Endianness</em></a><em>. Accessed 28 February 2022</em></li><li>Song, J. (2019). <em>Programming bitcoin: Learn how to program bitcoin from scratch</em> O’Reilly Media.</li><li>Wikipedia (N.D.): <em>Endianness. </em><a href="https://en.wikipedia.org/wiki/Endianness#Overview"><em>https://en.wikipedia.org/wiki/Endianness#Overview</em></a><em>. Accessed 28 February 2022</em></li><li>Antonopoulos, A. (2017). <em>Mastering bitcoin: Programming the open blockchain</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=188ae1f02ae0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elliptic Curves and the Discrete Log Problem]]></title>
            <link>https://enigbe.medium.com/about-elliptic-curves-and-dlp-ed76c5e27497?source=rss-7ab9ec0a61e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed76c5e27497</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[enigbe ochekliye]]></dc:creator>
            <pubDate>Mon, 14 Feb 2022 08:36:18 GMT</pubDate>
            <atom:updated>2022-05-23T09:45:08.760Z</atom:updated>
            <content:encoded><![CDATA[<p>Two weeks ago I started reading Programming Bitcoin by Jimmy Song with a goal to build a utility library alongside learning. The first few chapters cover the basic mathematics that underpins the asymmetric cryptographic scheme — elliptic curve cryptography (ECC) — that bitcoin uses. This is a cryptographic system that is based on elliptic curves over finite fields where a randomly selected private key is used to easily generate a public key but where the converse is computationally difficult/impossible.</p><p>But what are elliptic curves? What are finite fields? Why is ECC used in bitcoin?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*aFAbFMhPAUAZisaIgG-kGQ.png" /><figcaption>Eliiptic Curve</figcaption></figure><p>To answer these questions, I need a better understanding of the foundational mathematics used in ECC. In this article I summarized what I learned about the following: elliptic curves, finite fields, groups, group law, and finite cyclic groups, the discrete logarithm problem (DLP) and elliptic curve discrete logarithm problem (ECDLP).</p><h3>Elliptic Curves</h3><p>One way to think about the equation that describes an elliptic curve is to consider a stack of oranges arranged in such a way that each level contains a square matrix of oranges forming a pyramid. For example, level 4 at the base of the stack will contain (4 x 4) = 16 oranges, level 3 will contain (3 x 3) = 9 oranges, level 2 will have (2 x 2) = 4 oranges, and level 1 (1 x 1) = 1 orange. Consider an interesting problem of rearranging an n-level stack of oranges into a single square matrix. Would it be possible to have a square matrix if there were 3 levels in the stack? To find out if this is possible we have to take the sum of the square of each level and then compute the square root. If the square root is an integer then we have a solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*gId6UCVHL6BOHzDStEznzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*XjmSJNiuC6bN41EGC3bJuQ.png" /></figure><p>The equations above represents an elliptic curve. Given the knowledge of two points on the curve, the third can be found by the intersection of the elliptic curve and the straight line passing through the two known points.</p><p>Why is this equation and finding its solution important? To answer this we must understand what finite fields and groups are.</p><h3>Finite Fields</h3><p>A thing is said to be finite if it has definable/definite limits. Thus, finite fields are any fields (abstraction of numbers) with a finite set of elements. This means that there is a countable number of elements in the set representing the size/order of the set. Finite fields also have mathematically operations (addition and multiplication) that can be performed on the elements in the set such that the results of these operations are closed, i.e. are in the set. The following must hold true for finite fields:</p><ol><li>These operators, addition (<strong>+</strong>) and multiplication (<strong>.</strong>), perform binary operations</li><li>The result of adding element <strong><em>c</em></strong> and <strong><em>d</em></strong> must be in the set, making addition closed.</li><li>There exists a neutral element <strong><em>0</em></strong> such that <strong><em>0 + c = c</em></strong></li><li>There exists the identity element <strong><em>1</em></strong> such that <strong><em>1.c = c</em></strong></li><li>There exist <strong><em>-c</em></strong> such that <strong><em>-c + c = 0</em></strong></li><li>There exists the inverse of c such that</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/80/1*z5pHVE5d03Bxe2ll-UUPew.png" /></figure><p>7. There exist <strong>prime fields</strong> where the order of the finite field is a prime number <strong><em>p</em></strong> where the elements in the set (mod <strong><em>p</em></strong>) of this field are <strong><em>{0, 1, 2, …, p — 1}</em></strong></p><p>These conditions hold true because of modulo arithmetic that allow oversized results to wrapped around the divisor with the remainder falling within the boundary defined by the divisor. The snippet below shows how to implement a finite field element in Python.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adb111e97eccfdf6073081b9fc35068e/href">https://medium.com/media/adb111e97eccfdf6073081b9fc35068e/href</a></iframe><h3>Groups, Group Law, and Cyclic Groups</h3><p>The combination of a finite field and an elliptic curve over this field gives rise to an interesting entity — a group. If you have a finite field and an elliptic curve defined over the field such that the rules for the addition of two points on the curve results in a third, on the same curve, then we have a group.</p><p>Groups typically have one law, which is point addition (<strong>+</strong>) that extends the necessary conditions of a finite field operation. These conditions are:</p><p><strong>Additive Identity</strong>: Given a point <strong><em>P(x,y)</em></strong> on the elliptic curve, there exists an identity element <strong><em>0(x,y)</em></strong> such that <strong><em>0 + P = P. </em></strong>This identity element is known as the point at infinity.</p><p><strong>Additive Inverse</strong>: Given a point <strong><em>P(x,y)</em></strong> on the curve, there exists another point <strong><em>P(x,-y)</em></strong> such that <em>-</em><strong><em>P + P = 0 .</em></strong></p><p><strong>Point Addition</strong>: Given two points <strong><em>P₁(x₁, y₁)</em></strong> and <strong><em>P₂(x₂, y₂)</em></strong> on the elliptic curve, the third point <strong><em>P</em></strong>₃<strong><em>(x</em></strong>₃<strong><em>, y</em></strong>₃<strong><em>) </em></strong>is computed by calculating the slope (<strong><em>m</em></strong>) through <strong><em>P₁</em></strong> and <strong><em>P₂</em></strong>, and substituting into the equation of the line that passes through either <strong><em>P₁ </em></strong>or <strong><em>P₂ </em></strong>and <strong><em>P</em></strong>₃. The equations are as shown below and hold true for cases where <strong><em>P₁</em></strong> is not <strong><em>P₂</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/103/1*qinBT4pgCMiU5WOaG99GSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*5FGOQLspsFT5XkA9Owd66Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*-kYPCK3E-rsFNJVZaR6Hhw.png" /></figure><p><strong>Point Doubling</strong>: When <strong><em>P₁ = P₂</em></strong>, doubling is said to occur. Here <strong><em>P₁ + P₂ = P₁ + P₁ = 2P₁. </em></strong>The line formed is tangent to the point <strong><em>P₂ </em></strong>and passes through the third (technically second) point. The slope for this line is found by taken the derivative of the elliptic curve equation. The equation to compute <strong><em>y</em></strong>₃ remains unchanged however, the slope and <strong><em>x</em></strong>₃ equations change as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/124/1*DfzDbZlcKPoqeMKDD-Td-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*onYocxd9ZOMXC2wF7Qm6Lw.png" /></figure><p><strong>Scalar multiplication</strong>: What point doubling shows us is that we can perform a new kind of operation called scalar multiplication where <strong><em>P + P = 2P</em></strong> and <strong>2</strong> is a scalar multiple. This property is nonlinear and gives rise to two important considerations: finite cyclic groups and the discrete log problem.</p><p><strong>Finite Cyclic Groups</strong>:</p><p>At some scalar multiple (<strong><em>n</em></strong>) of a select <strong><em>P</em></strong>, we compute the point at infinity <strong><em>nP = 0</em></strong>. For the select <strong><em>P</em></strong>, this means that there exists a finite set of multiples of <strong><em>P </em></strong>called a finite cyclic group. And plot of <strong><em>{P, 2P, 3P, 4P, …, nP}</em></strong> over a finite field is a scattershot of points showing the non-linearity of point addition in finite cyclic groups. This non-linearity is a great property in cryptographic systems because computing the scalar multiple of a select point is easy but predicting the value of the scalar given a point is quite difficult. This is the discrete logarithm problem (DLP).</p><p>A point on a simplified elliptic curve <strong><em>y² = x³ + ax + b</em></strong> can be implemented in Python as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/605dbfffeac73ee055ff268d156dbc15/href">https://medium.com/media/605dbfffeac73ee055ff268d156dbc15/href</a></iframe><h3>Discrete Logarithm Problem</h3><p>The generalized discrete logarithm problem in a finite field is one that defines the difficulty of finding an integer <strong><em>x</em></strong> within the range of <strong><em>1</em></strong> and <strong><em>p — 1</em></strong> if there exists:</p><ol><li>A finite cyclic group with an order of <strong><em>p — 1</em></strong></li><li>A primitive element (<strong><em>α</em></strong>) which belongs to the finite cyclic group</li><li>A derivative element (<strong><em>β</em></strong>) such that <strong><em>αˣ = β</em></strong></li></ol><p>Computing the value of <strong><em>x</em></strong> is very hard if the parameters (<strong><em>p, α, β</em></strong>) are sufficiently large, even though computing the value of <strong><em>β </em></strong>is much easier.</p><p>Extending this, a DLP can be constructed with elliptic curves. Formally, the elliptic curve discrete logarithm problem (ECDLP) is the problem of finding an integer value <strong><em>e</em></strong> within the bounds of <strong><em>1</em></strong> and the number of points on the elliptic curve (which ~= the order of the finite cyclic group), such that the scalar multiplication of a primitive element <strong><em>G</em></strong> with <strong><em>e</em></strong>, i.e. <strong><em>eG, </em></strong>produces another point<strong><em> P </em></strong>on the elliptic curve.</p><p>In cryptographic systems <strong>e</strong> represents the uniformly selected random number that is the private key, <strong><em>G</em></strong> represents the generator point, <strong><em>P</em></strong> the derived public key.</p><h3>Bringing it all together</h3><p>Elliptic curves and the DLP are important because they form the primitives of ECC. With sufficiently large values for the order of the finite cyclic group (<strong><em>n</em></strong>), the generator point (<strong><em>G</em></strong>), and the order of a finite field (<strong><em>p</em></strong>), an elliptic curve discrete logarithm problem can be implemented for security- and privacy-conscious systems. The values bitcoin uses (see Programming Bitcoin, Chapter 3, Page 59) large enough to not have a successful attack against and known to provide long-term security with a time span of decades.</p><p>ECC, when compared with schemes in the same asymmetric algorithm family, provides the same security level with significantly smaller key lengths. For example, to achieve a security level of 128 bits, ECC requires 256-bit long keys, while 3072 bits is the minimum requirement for the same security level in others. Handling key lengths of 256 bits is much practical with better speeds than 3072 length keys.</p><p><strong>Note:</strong></p><ol><li>If you are interested in the implementation of field and group operations in Python, <a href="https://github.com/jimmysong/programmingbitcoin">here</a> is a link to the code base for Programming Bitcoin. An implementation in C++ is contained in Chapter 9 of Pro Cryptography and Cryptanalysis.</li><li>If the resources above are too exhaustive, you can check out my <a href="https://github.com/enigbe/pbjs">repository</a>. It has a much smaller footprint and contains code written alongside learning from Programming Bitcoin.</li></ol><h3>References</h3><ol><li>Song, J. (2019). <em>Programming bitcoin: Learn how to program bitcoin from scratch</em> O’Reilly Media.</li><li>Hankerson, D., Menezes, A., &amp; Vanstone, S. (2004). <em>Guide to elliptic curve cryptography</em> Springer.</li><li>Paar, C., &amp; Pelzl, J. (2010). <em>Understanding cryptography</em> (2. corr. printing ed.). Springer.</li><li>Mihailescu, M., Iulian, &amp; Nita, S., Loredana. (2021). <em>Pro cryptography and cryptanalysis with C++20: Creating and programming advanced algorithms</em> Apress.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed76c5e27497" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interning with Zuri/HNGi8]]></title>
            <link>https://enigbe.medium.com/interning-with-zuri-hngi8-df797cb383ee?source=rss-7ab9ec0a61e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/df797cb383ee</guid>
            <dc:creator><![CDATA[enigbe ochekliye]]></dc:creator>
            <pubDate>Mon, 16 Aug 2021 07:11:33 GMT</pubDate>
            <atom:updated>2021-08-16T07:11:33.262Z</atom:updated>
            <content:encoded><![CDATA[<p>I have spent some months learning how to build and deploy software, yet, confident as I am in my ability to write and research, I have never done this as part of a team. Writing software, for majority of the use cases, is inherently collaborative.</p><p>Good software, used by millions of people around the world, is almost always built by a team. Collaborating with other developers and designers to achieve the goals of the given tasks/projects is why I have decided to intern with <a href="https://internship.zuri.team/">Zuri</a>. An organization whose long running partnership with HNG offers professionals with prior programming experience the opportunity to build software and connections.</p><p>My goal is simple. Finish the HNGi8 internship with another portfolio-worthy project whose backend is built mainly with Javascript. I believe that by completing each challenge for every stage of this program, I would apply the base knowledge I have gained learning programming, version control, deployment, and containerization. In achieving this, I expect to build good connections with fellow interns as we journey together.</p><p>In the event that you are looking to transition to software development like I have, these are recommendations of the best resources to level up:</p><ol><li>Programming: Python is a popular language, with a clean, uncluttered style that makes it easy to read and learn. To gain intermediate proficiency, I highly recommend Jose Salvatierra’s “<a href="https://www.udemy.com/course/the-complete-python-course/">The Complete Python Course | Learn by Doing</a>”. It is beginner-friendly and project-focused. You get the feeling of having a deep understanding of the language upon completion. For Javascript, Colt Steele and Stephen Grider’s “The Modern Javascript Bootcamp Course” comes highly rated on Udemy. It is split in two broad sections, where the first is focused on understanding the syntax of the language, and the second on building projects with it.</li><li>Versioning: Version control with git is a mandatory skill all software developers must have. The knowledge of which underpins collaboration in team projects. LinkedIn Learning’s “<a href="https://www.linkedin.com/learning/git-essential-training-the-basics">Git Essential Training: The Basics</a>” is a good place to start. The course is taught by Kevin Skoglund, covers the basics, and introduces new learners to the Git Workflow — a recommended approach to using git effectively.</li><li>UI/UX Design: Design analyses user interface and experience for products. Figma is tool that has gained mainstream popularity in recent years, appearing to be the defacto standard for mobile and web products. A good place to start learning is Andrei and Daniel’s Udemy course titled “<a href="https://www.udemy.com/course/complete-web-designer-mobile-designer-zero-to-mastery/">Complete Web &amp; Mobile Designer in 2021: UI/UX, Figma, +more</a>”</li><li>Scripting: Looking to add structure to your mobile and web products? HTML does just that. It is an easy to learn scripting language that is the foundation of all web applications. A good place to start is LinkedIn Learning’s “<a href="https://www.linkedin.com/learning/html-essential-training-4/what-is-html">HTML Essential Training</a>” by Jen Simmons.</li></ol><p>Please do not hesitate to message me if you want more information about the recommendations I have made, other courses you can take, and or general updates about my progress with Zuri and HNG.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df797cb383ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>