<?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 Mabel Oza on Medium]]></title>
        <description><![CDATA[Stories by Mabel Oza on Medium]]></description>
        <link>https://medium.com/@mabeloza?source=rss-bdd0b2ab4dde------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QlRQBeq3dwdjp4zjXWC0yA.jpeg</url>
            <title>Stories by Mabel Oza on Medium</title>
            <link>https://medium.com/@mabeloza?source=rss-bdd0b2ab4dde------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 08 Apr 2026 01:03:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mabeloza/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[Bitcoin Halving Events]]></title>
            <link>https://medium.com/coinmonks/bitcoin-halving-events-9d7c9c4a5830?source=rss-bdd0b2ab4dde------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d7c9c4a5830</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[crypto-mining]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[crypto]]></category>
            <dc:creator><![CDATA[Mabel Oza]]></dc:creator>
            <pubDate>Wed, 03 Apr 2024 12:02:07 GMT</pubDate>
            <atom:updated>2024-04-04T07:28:23.008Z</atom:updated>
            <content:encoded><![CDATA[<p>Unlike the past halving events, the upcoming halving (around April 16th) finds Bitcoin in a completely new landscape. Since the last halving, we’ve had ETFs, new regulatory standards, and a rally before the halving, creating a recipe for unpredictable aftershocks. Regardless of whether you’re a Bitcoin fan or hater, the effects of this halving are going to ripple throughout the economy and our politics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GTdYGKpka5hN3_c1" /></figure><p>This event will hit our finances, regulations, and global economy.</p><p><strong>Finances</strong></p><ul><li>How will established institutions that recently embraced Bitcoin through ETFs react to the sudden supply shock?</li><li>How will the sudden change in Bitcoin’s supply affect peripheral financial assets?</li></ul><p><strong>Regulations</strong></p><ul><li>As miners are forced out will regulators impose stricter controls on mining oligopolies?</li><li>Will regulators require more audibility from organizational and individual miners?</li></ul><p><strong>Global Economy</strong></p><ul><li>How will this affect the overseas and U.S. mining industry?</li></ul><p>We’ll examine the halving events and analyze all the chaos it will cause us:</p><ul><li><a href="#835f"><strong>What is a Bitcoin Halving?</strong></a></li><li><a href="#84b6"><strong>How often does it occur?</strong></a></li><li><a href="#1688"><strong>Price of Bitcoin and the Halving Events</strong></a></li><li><a href="#4b45"><strong>Economic Impact of Halving Events</strong></a></li><li><a href="#070f"><strong>Halving and Gresham’s Law</strong></a></li><li><a href="#6269"><strong>This Story in the Bitcoin Core Code</strong></a></li></ul><h3>What is a Bitcoin Halving?</h3><p>Every 210,000 blocks the block mining reward fee is reduced by half. This was determined years ago when the code was first implemented. The intention behind halving the fees over time is to slow down the network growth and give it time to mature.</p><p>The halving events should continue till the year 2140 when the maximum supply of 21 million Bitcoins are met.</p><h3><strong>How often does it occur?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*GXkbLfFYzqexkhQr.gif" /></figure><p>A <strong>new block is mined every 10 minutes</strong>, the 10 minute time is maintained by adjusting the difficulty (if blocks are mined too quickly the difficulty increases and if they’re mined to slowly the difficulty decreases).</p><p>So if we are halving every 210,000 blocks then we should have a halving event every 4 years.</p><p>Minutes Per Year = 60 minutes per hour * 24 hours per day * 365 days per year = <strong>525600 minutes a year</strong></p><p>Minutes to Mine 210,000 blocks = 10 minutes to mine block * 210,000 blocks = <strong>2,100,000 minutes to mine 210,000 blocks</strong></p><p><strong>2,100,000 minutes to mine 210,000 blocks</strong> / <strong>525600 minutes a year ~= 4 years</strong></p><p>Below are the date of the halving events and their estimated halving events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AfFXFcrr5HgtyWGk9foDHg.png" /></figure><h3>Price of Bitcoin and the Halving Events</h3><p>There isn’t a direct correlation between the price of Bitcoin and the halving events. Usually the trend is that Bitcoin is fairly stable then there is an uptick after a halving event, but this time (3rd halving event) we’ve seen the uptick before the halving event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxd96ngNDsqe8uFz7E4ZcA.png" /></figure><h3>Economic Impact of Halving Events</h3><p>The intention for the halving is to slow down the rate of Bitcoins coming into the market, and in turn keep the currency</p><h4>Impact on Crypto Related Stocks</h4><p>The companies that would be directly impacted by the halving are mining pool companies and companies that supply mining infrastructure. Marathon, Riot, and Clean Spark are some of the biggest miners today, halving the Bitcoin reward might remove many miners from the market and allow some of these larger mining companies to expand. Companies like NVIDIA and AMD will see negative affects from their mining equipment sales because there will be less miners.</p><blockquote><strong>Note</strong>: NVIDIA and AMD are growing their AI business and might not be deeply impacted from a stock perspective.</blockquote><p>The companies that are crypto adjacent have been Coinbase, Block (Square), Microstrategy, Galaxy Digital Holding, Paypal, and Reddit because they have a large holding of Bitcoin and some provide crypto utilities. Their growth is indirectly impacted by how the halving impacts the fiat value of Bitcoin and the movement of Bitcoin.</p><h4>Impact on other PoW Coins</h4><p>Since the halving event reduces the reward for mining Bitcoin PoW (proof of work) miners would have more of an incentive to mine on other PoW networks. As of today some of those networks are Dodgecoin, Bitcoin Cash, Litecoin, Ethereum Classic, Kaspa, and Monero. It doesn’t mean that the coins associated to these networks will increase in value, but there might be more activity around mining, which will eventually lead to trading in these networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htkwtcTHm8G-6SFYaVKefg.png" /><figcaption>Image from: <a href="https://crypto.com/price/categories/pow">https://crypto.com/price/categories/pow</a></figcaption></figure><h3>Halving and Gresham’s Law</h3><blockquote><em>bad money drives out good</em></blockquote><h4>A little bit about the Gresham Law…</h4><p>The idea behind the Gresham Law is if two forms of money are in circulation at the same time then people will use the bad money and save or hoard the good money, eventually driving the good money to appear less in circulation. An example is gold and fiat currency, gold it’s considered (even today) good money, but how many times did you buy something with gold or receive it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IeFIyBj_rBTHJKBn0C7g4w.png" /></figure><h4>Gresham Law and Bitcoin</h4><p>The supply of Bitcoin won’t decrease with the halving but it will slow down the supply, making it somewhat scarcer. This scarcity might drive people to hold on to their Bitcoin rather than spend it.</p><p>The combination of hoarding and new Bitcoins entering into circulation might decrease the velocity of Bitcoin (how quickly units are exchanged), causing an increased value. This would make Bitcoin, “the good money,” to disappear from circulation and for Fiat currency, “bad money,” to appear more in circulation.</p><p>The same theory can be applied to other cryptocurrencies and Bitcoin. As Bitcoin, the “good money,” is hoarded more blockchain projects will use cryptocurrencies that are considered the “bad money”. It wouldn’t make sense to create DApps that use a crypto that’s high in value, so instead, companies would create their DApps using crypto that has low transaction fees in fiat. This could give way to modern cryptocurrencies like Solana, Algorand, and Avalanche.</p><h3>Halving Story in the Bitcoin Core Code</h3><p>Here we have the logic that tells us that the mining reward (subsidy) is halved every 210,000 blocks.</p><pre> CAmount GetBlockSubsidy(int nHeight, const Consensus::Params&amp; consensusParams)<br>{<br>    int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;<br>    // Force block reward to zero when right shift is undefined.<br>    if (halvings &gt;= 64)<br>        return 0;<br><br>    CAmount nSubsidy = 50 * COIN;<br>    // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.<br>    nSubsidy &gt;&gt;= halvings;<br>    return nSubsidy;<br>}</pre><p>The 210,000 is defined as a parameter value (nSubsidyHalvingInterval) in the chain params.</p><pre>class CMainParams : public CChainParams {<br>public:<br>    CMainParams() {<br>        m_chain_type = ChainType::MAIN;<br>        consensus.signet_blocks = false;<br>        consensus.signet_challenge.clear();<br>        consensus.nSubsidyHalvingInterval = 210000;<br>...</pre><p>This is where the maximum supply of Bitcoin can exist, if a bug ever causes the supply to exceed 21 million Bitcoin will go into a fork. The “MoneyRange” line of code is crucial and is referenced throughout the codebase.</p><pre>// Copyright (c) 2009-2010 Satoshi Nakamoto<br>// Copyright (c) 2009-2021 The Bitcoin Core developers<br>// Distributed under the MIT software license, see the accompanying<br>// file COPYING or http://www.opensource.org/licenses/mit-license.php.<br><br>#ifndef BITCOIN_CONSENSUS_AMOUNT_H<br>#define BITCOIN_CONSENSUS_AMOUNT_H<br><br>#include &lt;cstdint&gt;<br><br>/** Amount in satoshis (Can be negative) */<br>typedef int64_t CAmount;<br><br>/** The amount of satoshis in one BTC. */<br>static constexpr CAmount COIN = 100000000;<br><br>/** No amount larger than this (in satoshi) is valid.<br> *<br> * Note that this constant is *not* the total money supply, which in Bitcoin<br> * currently happens to be less than 21,000,000 BTC for various reasons, but<br> * rather a sanity check. As this sanity check is used by consensus-critical<br> * validation code, the exact value of the MAX_MONEY constant is consensus<br> * critical; in unusual circumstances like a(nother) overflow bug that allowed<br> * for the creation of coins out of thin air modification could lead to a fork.<br> * */<br>static constexpr CAmount MAX_MONEY = 21000000 * COIN;<br>inline bool MoneyRange(const CAmount&amp; nValue) { return (nValue &gt;= 0 &amp;&amp; nValue &lt;= MAX_MONEY); }<br><br>#endif // BITCOIN_CONSENSUS_AMOUNT_H</pre><p>This is where we add the block subsidy (mining reward) with the transaction fee.</p><pre>CAmount GetBlockSubsidy(int nHeight, const Consensus::Params&amp; consensusParams)<br>{<br>    int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;<br>    // Force block reward to zero when right shift is undefined.<br>    if (halvings &gt;= 64)<br>        return 0;<br><br>    CAmount nSubsidy = 50 * COIN;<br>    // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.<br>    nSubsidy &gt;&gt;= halvings;<br>    return nSubsidy;<br>}</pre><p>Here we stop issuing fees if the accumulated fees exceed 21 million, as defined.</p><pre>            nFees += txfee;<br>            if (!MoneyRange(nFees)) {<br>                LogPrintf(&quot;ERROR: %s: accumulated fee in the block out of range.\n&quot;, __func__);<br>                return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, &quot;bad-txns-accumulated-fee-outofrange&quot;);<br>            }</pre><h3>Resources</h3><p><strong>Swan Bitcoin — Next Bitcoin Halving: April 19th History and What to Know!</strong></p><p><a href="https://www.swanbitcoin.com/bitcoin-halving-dates/">Next Bitcoin Halving: April 19th, 2024 History and What to Know!</a></p><p><strong>Swan Bitcoin — Gresham’s Law</strong></p><p><a href="https://www.swanbitcoin.com/greshams-law/">https://www.swanbitcoin.com/greshams-law/</a></p><p><strong>Bitcoin Core Github</strong></p><p><a href="https://github.com/bitcoin/bitcoin/tree/28f2ca675f89a764e1ec8eb5671b35357b8677f3">GitHub - bitcoin/bitcoin at 28f2ca675f89a764e1ec8eb5671b35357b8677f3</a></p><p><strong>Blockworks — Bitcoin Halving BTC Price Implications</strong></p><p><a href="https://blockworks.co/news/bitcoin-halving-btc-price-implications">https://blockworks.co/news/bitcoin-halving-btc-price-implications</a></p><p><strong>Bitcoin Talk</strong></p><p><a href="https://bitcointalk.org/index.php">Bitcoin Forum - Index</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d7c9c4a5830" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/bitcoin-halving-events-9d7c9c4a5830">Bitcoin Halving Events</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Publishing Your Image to Google Cloud Artifact]]></title>
            <link>https://faun.pub/publishing-your-image-to-google-cloud-artifact-8ba7675ca594?source=rss-bdd0b2ab4dde------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ba7675ca594</guid>
            <category><![CDATA[google-container-registry]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[jfrog-artifactory]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[containerization]]></category>
            <dc:creator><![CDATA[Mabel Oza]]></dc:creator>
            <pubDate>Sat, 11 Nov 2023 13:34:11 GMT</pubDate>
            <atom:updated>2025-12-16T04:18:17.725Z</atom:updated>
            <content:encoded><![CDATA[<h4>Publishing your image to Google Cloud Artifactory allows you to run cloud deployments on your application</h4><p>Publishing your image is crucial if you want share your masterpiece apps with the world. Let’s look at Google Cloud Artifact and how we can use that to share our application images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QgT4ORtxVnOXabHb.jpg" /></figure><h3>Images, Containers, and Container Registries</h3><p>How do images, containers, and container registries all fit together? Images can be thought of as an image file, the containers are those images in different frames, and container registries are like the gallery that houses all these containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0wbdBE3QH2nfnAh_DDfK9g.png" /></figure><p><strong>Image</strong>: Standalone, executable package that encapsulates all the necessary components to run an application, including the application code, runtime, libraries, and environment variables. It adheres to the Open Container Initiative (OCI) specifications for image formats and runtime, ensuring compatibility and interoperability across different containerization platforms.</p><p><strong>Container</strong>: Runtime instance of an image, functioning as an isolated environment in which the application executes. Think of it as a lightweight, portable, and self-sufficient environment for the image.</p><p><strong>Container Registry</strong>: Centralized service for storing and managing container images. It provides teams with the ability to securely store private images, conduct vulnerability analysis, and manage image lifecycles. The registry typically includes features for fine-grained access control, allowing administrators to define who can push or pull images, thereby ensuring that only authorized users can access and manipulate the images.</p><p><strong>Tagging</strong>: Used to mark a specific commit of an image and are often used in a CI/CD pipeline.</p><p><strong>Push: </strong>Act of uploading an image to the container registry from your local machine.</p><p><strong>Push</strong>: Act of downloading an image from the container registry to your local machine.</p><h3>Setting up Google Artifact Registry</h3><blockquote><strong>Note</strong>: These steps are the same regardless of what language you wrote you app in, because containers are language agnostic.</blockquote><p>Do the whole song and dance of setting up a Google Cloud account, it involves enabling APIs, accepting terms, etc. After your done go to your Google console <a href="https://console.cloud.google.com/">(https://console.cloud.google.com/</a>) and search “Artifact Registry”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*KenP-Wb55lER5WHReyNq5w.png" /></figure><p>Now you’re in the Artifact Registry tool, create a repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8VJzFrvJAo1i5CilWNPE5g.png" /></figure><p>When creating a repository name it whatever your heart desires, select the format “Docker”, mode “Standard”, your desired location, and the encryption “Google managed encryption key”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FK855L7RyXGRkxZOCNAFpw.png" /></figure><p>After creating a repository you should see your artifact folder you just created, click into the folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixW1AzSaAS6f3aaIOM_FrQ.png" /></figure><h3>Auth Docker into Google Cloud</h3><p>Next we’re going to use our docker to push into this repository to make that happen we’ll need our docker to be able to authenticate with our cloud instance.</p><p>Select “Setup Instructions” in your Google Cloud Console and you will find a command line that looks like the following, it might differ depending on your location. Run this command in your terminal in the same folder of your Dockerfile.</p><pre>gcloud auth configure-docker us-central1-docker.pkg.dev</pre><h3>Build and Pushing Images to Google Artifact Registry</h3><p>Click into the folder and select the breadcrumb copy button, this will give you the full path of the repository you just created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERQQcA12LJ1SbVKf_ABEyA.png" /></figure><p>Using the location of the repository run the command below to build you app to your repository.</p><pre>docker build -t [LOCATION OF REPOSITORY - REPLACE THIS]/[APP_NAME]:v1 .</pre><p>After a successful build push your image to the repository, using the command below:</p><pre>docker push [LOCATION OF REPOSITORY - REPLACE THIS]/[APP_NAME]:v1</pre><blockquote><strong>Note: </strong>The<strong> </strong>v1 at the end of the build and push commands should match up and should represent the version or tag you want to associate with the image.</blockquote><blockquote><strong>Potential Issue:</strong></blockquote><blockquote>If you aren’t properly authenticated or authenticated in one tab and trying to push your image in an older tab you will come across the error below. Make sure to authenticate in the same tab your pushing the image to the repository.</blockquote><pre>denied: Unauthenticated request. Unauthenticated requests do not have permission &quot;artifactregistry.repositories.uploadArtifacts&quot; on resource &quot;projects/something-12345/locations/us-central1/repositories/backendapis&quot; (or it may not exist)</pre><h3>BAM! Verify Your Image is Available in the Registry</h3><p>Go back to the cloud console &gt; Artifact Registry, and you should find your container within the the folder you created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*E39mr5jA_qFJ4dcipRWqaQ.png" /></figure><p>And if you click on the container you will find all the images and their associated tags, since you just did one push you will just have one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-iew0GVE1Fpp7wRNJsIuA.png" /></figure><h3>Resources</h3><p><strong>Google Official Artifact Registry Docs</strong></p><p><a href="https://cloud.google.com/artifact-registry/">Artifact Registry | Google Cloud</a></p><p><strong>Google Codelabs Artifact Registry</strong></p><p><a href="https://codelabs.developers.google.com/artifact-registry-deepdive">Artifact Registry Deep Dive | Google Codelabs</a></p><p><strong>Getting Started with Artifact Registry and GKE</strong></p><p><a href="https://medium.com/google-cloud/getting-started-with-artifact-registry-deploying-to-google-kubernetes-engine-ee490da2f6de">Getting Started with Artifact Registry: Deploying to Google Kubernetes Engine</a></p><p><strong>Introducing Artifact Registry</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F712Y0KpeHok%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D712Y0KpeHok&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F712Y0KpeHok%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a905e422860dfc12fc503a237b1f6ae5/href">https://medium.com/media/a905e422860dfc12fc503a237b1f6ae5/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ba7675ca594" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/publishing-your-image-to-google-cloud-artifact-8ba7675ca594">Publishing Your Image to Google Cloud Artifact</a> was originally published in <a href="https://faun.pub">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing the Right Lightning Network Implementation]]></title>
            <link>https://medium.com/coinmonks/choosing-the-right-lightening-network-implementation-c161d76a2a41?source=rss-bdd0b2ab4dde------2</link>
            <guid isPermaLink="false">https://medium.com/p/c161d76a2a41</guid>
            <category><![CDATA[bitcoin-lightning]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[lnd]]></category>
            <category><![CDATA[lightning-network]]></category>
            <category><![CDATA[eclair]]></category>
            <dc:creator><![CDATA[Mabel Oza]]></dc:creator>
            <pubDate>Tue, 24 Oct 2023 12:01:36 GMT</pubDate>
            <atom:updated>2023-10-24T17:00:40.911Z</atom:updated>
            <content:encoded><![CDATA[<p>The Lightning network is an open protocol that follows the <a href="https://github.com/lightningnetwork/lightning-rfc/blob/master/00-introduction.md">B.O.L.T</a> open standard. There are multiple implementations of the lightning network and they should all go by the B.O.L.T. standards. When in doubt, always refer to the B.O.L.T. standards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*L5T5JHDbr_iZrGsn" /></figure><h3>Popular Implementations</h3><p>Below are a few popular lightning network implementations that follow the BOLT standards, <a href="https://github.com/lightningnetwork/lnd">LND</a>, <a href="https://github.com/ElementsProject/lightning">C-Lightning</a>, <a href="https://github.com/ACINQ/eclair">Eclair</a>, <a href="https://github.com/lightningdevkit">Rust LDK</a>, and <a href="https://github.com/spesmilo/electrum">Electrum</a>. They mostly vary by language, C-Lightning is written in C, Eclair is written in Scala, LND is written in Go, Rust LDK is written in Rust, and Electrum is written in Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xc5z_Rugp6nA8YN1rEXCDA.png" /></figure><h3>Criteria</h3><p>Besides language preferences, here are a few additional considerations to take into account when choosing the right Bitcoin Lightning implementation.</p><p><strong>💻 </strong><a href="#0668"><strong>Platform Support</strong></a></p><p><a href="#71db"><strong>Bitcoin client support (regular and light)</strong></a></p><p>💰💰<strong> </strong><a href="#c25e"><strong>Dual Funded Channel</strong></a></p><p>💰💰💰<a href="#53ad"><strong>Multi-Funded Channel</strong></a></p><p><strong>🖊 </strong><a href="#b30b"><strong>Partially Signed Bitcoin Transactions (PSBT) Support</strong></a></p><p><strong>🗼</strong><a href="#6739"><strong>Watchtower Support</strong></a></p><p>🗄 <a href="#d08b"><strong>Database Required</strong></a></p><p><strong>🔑 </strong><a href="#c0f3"><strong>Keysend Support</strong></a></p><p><strong>📺 </strong><a href="#8dd5"><strong>Channel Backups</strong></a></p><h4><strong>💻 </strong>Platform Support</h4><p>Platform support is about where we can run these implementations, like can you run on a mobile Android, iOS, Linux Desktop, etc. This criterion is dependent on what hardware you have available and mostly what use case you’re trying to solve for.</p><h4>Bitcoin client support (regular and light)</h4><p>An implementation that supports both full and light (SPV) Bitcoin clients offers more flexibility. Full clients provide higher security but require more resources, whereas light clients are easier to run but might offer less security.</p><h4>💰💰Dual Funded Channels</h4><p>Dual-funded channels allow both parties to contribute to the funding transaction when initiating a channel. This brings lower transaction fees because they can jointly construct and sign the funding transactions and allows for a large payment capacity because both parties fund it. In a regular channel, only one party can fund the channel.</p><p><a href="https://thebitcoinmanual.com/articles/what-is-a-dual-funded-lightning-channel/">What Is A Dual Funded Lightning Channel? - The Bitcoin Manual</a></p><h4>💰💰💰Multi-Funded Channel</h4><p>A multi-funded channel is similar to a dual-funded channel, except now more than one party can contribute to the funding transaction when initiating a channel.</p><h4><strong>🖊 </strong>Partially Signed Bitcoin Transactions (PSBT) Support</h4><p>PSBTs are a binary transaction format that allows multiple parties to sign on the same transaction at different times and share information on the transaction. This is useful if another signer is offline (ex. they are using an air-gapped wallet or hardware wallet) or a watch-only wallet that just creates transactions but can’t sign.</p><h4><strong>🗼</strong>Watchtower Support</h4><p>Watchtowers act as third-party services that monitor the blockchain for malicious activities related to your Lightning channels. This adds a layer of security when you’re unable to actively monitor your channels.</p><p>Check out the description of Watchtower in the article below:</p><p><a href="https://medium.com/coinmonks/different-ways-to-close-a-lightening-payment-channel-a11bbe4ed486">Different Ways to Close a Lightning Payment Channel</a></p><h4>🗄 Database Required</h4><p>Many of these implementations use embedded databases but can use more robust database solutions like PostgreSQL. Databases in Lightning are used to manage transaction and channel state management, routing details, and auditing.</p><h4><strong>🔑 </strong>Keysend Support</h4><p>Keysend allows funds to be sent to a node without an invoice, which means you can spontaneously send someone funds without them ever asking for it. In non-keysend payments, the receiver needs to send an invoice presented by email or a QR code, with keysend payments this isn’t necessary, the receiver just has to share their node ID (a public key) once to receive payments.</p><p><strong>What is the difference between a regular transaction and a keysend transaction?</strong></p><p>In both cases, using onion routing helps preserve privacy by making it difficult for observers to see the identities of the sender and receiver and the payment amount. However, the use of keysend in the second transaction simplifies the process by allowing Bob to send the preimage directly to Alice’s node without the need for intermediate nodes to forward the packet.</p><blockquote><strong>Why you shouldn’t use the same pre-image?</strong></blockquote><blockquote>Using the same preimage can allow an observer to link multiple payments together. All those payments will be tied to the same hash value, and an observer can link the payments by identifying transactions that have the same hash value.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FzaBY9_eEQWE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DzaBY9_eEQWE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FzaBY9_eEQWE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f639474d2531421cb9d7fa0df3815aa0/href">https://medium.com/media/f639474d2531421cb9d7fa0df3815aa0/href</a></iframe><p><strong>Disadvantages of Keysend</strong></p><p>This all sounds wonderful, but there are disadvantages to using this approach. Accepting payments without an invoice can open you up to:</p><ul><li><a href="https://www.gemini.com/cryptopedia/crypto-dusting-attack-bitcoin">Dusting attacks</a> (a small amount of satoshis are sent to track an address),</li><li>Spammed wallet (someone from an unsanctioned country can send funds to your wallet and raise flags)</li><li>Lack of payment confirmation, since an invoice isn’t required, there is no way a sender can confirm that the payment received by the intended recipient</li></ul><h4><strong>📺 </strong>Channel Backup</h4><p>Data Loss Prevention is crucial when planning for your lightning node. To handle DLP scenarios, lightning has different channel backup strategies.</p><p><strong>Static Channel Backups (SCB): </strong>Backup files (in LND files called channel.backup) that are encrypted using a key derived from your wallet seed. This file will allow users to recover both their on-chain funds and funds settled (base commitment outputs but not HTLC’s) within their channels. It’s called static because the file is only obtained once and is valid till the channel is closed.</p><p><strong><em>Note: </em></strong><em>This file sits on the node, so there needs to be a script that copies this file whenever there are changes to another instance outside of the node.</em></p><p><a href="https://github.com/lightningnetwork/lnd/releases/tag/v0.6-beta">Release lnd v0.6-beta · lightningnetwork/lnd</a></p><p><strong>Dynamic channel backup:</strong> This is a more advanced method of backing up a channel that involves creating a backup channel that runs in parallel to the primary channel. The backup channel is updated with the latest state of the primary channel and can be used to recover funds in the event of a channel failure.</p><p><strong>Database backup: </strong>Some Lightning Network nodes offer a feature to automatically backup channel data to a database or other storage location. This can provide an easy way to recover channels in the event of a node failure or other issues.</p><p><strong>Offline storage: </strong>Another option is to back up the channel information to an offline storage device such as a USB drive or external hard drive. This can provide a secure backup that is not vulnerable to online attacks.</p><p><a href="https://plebnet.wiki/wiki/Backup/Recovery">Backup/Recovery</a></p><p>Below are instructions on how to recover funds when using the LND implementation:</p><p><a href="https://github.com/lightningnetwork/lnd/blob/master/docs/recovery.md">lnd/recovery.md at master · lightningnetwork/lnd</a></p><h3>Summary</h3><p>No single implementation reigns supreme; different implementations cater to various priorities and use cases. If features are your priority, then considerations like keysend, dual-channel, and multi-channel funding are crucial. For those prioritizing security, watchtower support, database management, Bitcoin client support, and channel backup are crucial. And if flexibility and use-case adaptability are paramount, then platform support is crucial.</p><h3>Resources</h3><p><strong>LDK Lightening Dev Kit</strong></p><p><a href="https://github.com/FulgurVentures/Lightning-Implementation-Features/blob/main/README.md">Lightning-Implementation-Features/README.md at main · FulgurVentures/Lightning-Implementation-Features</a></p><p><strong>Lightning Implementation Features by Fulgur Ventures (Inspiration for this blog)</strong></p><p><a href="https://github.com/FulgurVentures/Lightning-Implementation-Features/blob/main/README.md">Lightning-Implementation-Features/README.md at main · FulgurVentures/Lightning-Implementation-Features</a></p><p><strong>Keysend Payment</strong></p><p><a href="https://thebitcoinmanual.com/articles/keysend-payment/">What Is A Keysend Payment? - The Bitcoin Manual</a></p><p><strong>Voltage Keysend Payment Explained</strong></p><p><a href="https://voltage.cloud/blog/bitcoin-lightning-network/keysend-payments-explained-voltage-technical-series/">Lightning Keysend Payments Explained | Voltage</a></p><p><strong>PSBT Formats — BIP 174</strong></p><p><a href="https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki">bips/bip-0174.mediawiki at master · bitcoin/bips</a></p><p><strong>PSBT Version 2 — BIP 370</strong></p><p><a href="https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki">bips/bip-0370.mediawiki at master · bitcoin/bips</a></p><p><strong>BOLT Standards</strong></p><p><a href="https://medium.com/coinmonks/b-o-l-t-standards-56cb4e9ae50b">B.O.L.T. Standards</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c161d76a2a41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/choosing-the-right-lightening-network-implementation-c161d76a2a41">Choosing the Right Lightning Network Implementation</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[B.O.L.T. Standards]]></title>
            <link>https://mabeloza.medium.com/b-o-l-t-standards-56cb4e9ae50b?source=rss-bdd0b2ab4dde------2</link>
            <guid isPermaLink="false">https://medium.com/p/56cb4e9ae50b</guid>
            <category><![CDATA[lightning-network]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[bitcoin-payment]]></category>
            <category><![CDATA[payment-technology]]></category>
            <category><![CDATA[crypto-payment-gateway]]></category>
            <dc:creator><![CDATA[Mabel Oza]]></dc:creator>
            <pubDate>Wed, 24 May 2023 11:06:06 GMT</pubDate>
            <atom:updated>2023-05-24T19:07:47.219Z</atom:updated>
            <content:encoded><![CDATA[<p>B.O.L.T. stands for Basis of Lightning Technology (Lightning Network Specifications). Think of them like the 10 commandments of Bitcoin Lightning implementations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/0*g1NbloH14IkO-vER.jpg" /></figure><p>Any implementation (i.e. Rust LDK, LND, Eclair) that claims to be a lightning network implementation must follow B.O.L.T. standards. If they don’t, be wary. If you want the spark notes version of the BOLT standards, you can check out <a href="https://medium.com/u/94b37fabd4df">Rusty Russell</a>’s blog post series on the BOLT standards (FYI: Rusty Russell is also a contributor to the BOLT standards and a key contributor with the BOLT 12 standard).</p><p><a href="https://rusty-lightning.medium.com/the-bitcoin-lightning-spec-part-1-8-a7720fb1b4da">The #Bitcoin #Lightning Spec Part 1/8</a></p><p>The B.O.L.T. (Basis of Lightning Technology) standards define the protocols and specifications for any implementation of the Lightning Network. B.O.L.T. covers multiple topics around payments, routing, p2p interactions, messaging, and networking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uQgDT_O5-j1Cgpml" /><figcaption>Image: <a href="https://tobiojuolape.hashnode.dev/bolt-11-vs-bolt-12-whats-new-in-lightning">https://tobiojuolape.hashnode.dev/bolt-11-vs-bolt-12-whats-new-in-lightning</a></figcaption></figure><p>Here’s a list of the 10 BOLT standards.</p><ol><li><a href="https://github.com/lightning/bolts/blob/master/01-messaging.md">BOLT #1</a>: Base Protocol</li><li><a href="https://github.com/lightning/bolts/blob/master/02-peer-protocol.md">BOLT #2</a>: Peer Protocol for Channel Management</li><li><a href="https://github.com/lightning/bolts/blob/master/03-transactions.md">BOLT #3</a>: Bitcoin Transaction and Script Formats</li><li><a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md">BOLT #4</a>: Onion Routing Protocol</li><li><a href="https://github.com/lightning/bolts/blob/master/05-onchain.md">BOLT #5</a>: Recommendations for On-chain Transaction Handling</li><li><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md">BOLT #7</a>: P2P Node and Channel Discovery</li><li><a href="https://github.com/lightning/bolts/blob/master/08-transport.md">BOLT #8</a>: Encrypted and Authenticated Transport</li><li><a href="https://github.com/lightning/bolts/blob/master/09-features.md">BOLT #9</a>: Assigned Feature Flags</li><li><a href="https://github.com/lightning/bolts/blob/master/10-dns-bootstrap.md">BOLT #10</a>: DNS Bootstrap and Assisted Node Location</li><li><a href="https://github.com/lightning/bolts/blob/master/11-payment-encoding.md">BOLT #11</a>: Invoice Protocol for Lightning Payments</li></ol><blockquote>BOLT 6 (IRC Announcements) is missing because it was superseded by BOLT 7 (<a href="https://github.com/lightning/bolts/issues/551">https://github.com/lightning/bolts/issues/551</a>).</blockquote><p>In summary, the 10 B.O.L.T. standards can be summarized in 10 commandments.</p><p><strong>1. </strong><a href="#1422"><strong>Thou Shall Follow Messaging Formats</strong></a></p><p><strong>2. </strong><a href="#7982"><strong>Thou Shall Manage the Channel Lifecycle</strong></a></p><p><strong>3. </strong><a href="#d297"><strong>Thou Shall Transact with Bitcoin Properly</strong></a></p><p><strong>4. </strong><a href="#da40"><strong>Thou Shall Securely Route Transactions</strong></a></p><p><strong>5. </strong><a href="#c42b"><strong>Thou Shall Close the Channel</strong></a></p><p><strong>7. </strong><a href="#f1d1"><strong>Thou Shall Make Nodes &amp; Channels Discoverable</strong></a></p><p><strong>8. </strong><a href="#a93a"><strong>Thou Shall Encrypt and Authenticate</strong></a></p><p><strong>9. </strong><a href="#16dd"><strong>Thou Shall Support New Features</strong></a></p><p><strong>10. </strong><a href="#3ef0"><strong>Thou Shall Discover a Node Using DNS</strong></a></p><p><strong>11. </strong><a href="#251f"><strong>Thou Shall Send Proper Invoices</strong></a></p><p><strong>12. </strong><a href="#eee5"><strong>(Bonus) Thou Shall Provide Fresh Invoices</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Psytp_T-1NiYbAKzae3GA.png" /></figure><h3>Thou Shall Follow Messaging Formats</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*26b3mn7-QTGY5EOK.jpg" /></figure><h4><a href="https://github.com/lightning/bolts/blob/master/01-messaging.md"><strong><em>BOLT 1: Base Protocol</em></strong></a></h4><p>It defines the messaging formats, data types, and connection handling between peers. Below are the topics this standard covers:</p><ul><li><a href="https://github.com/lightning/bolts/blob/master/01-messaging.md#connection-handling-and-multiplexing">Connection Handling and Multiplexing</a></li><li><a href="https://github.com/lightning/bolts/blob/master/01-messaging.md#lightning-message-format">Lightning Message Format</a></li><li><a href="https://github.com/lightning/bolts/blob/master/01-messaging.md#type-length-value-format">Type-Length-Value Format</a></li><li><a href="https://github.com/lightning/bolts/blob/master/01-messaging.md#fundamental-types">Fundamental Types</a></li><li><a href="https://github.com/lightning/bolts/blob/master/01-messaging.md#setup-messages">Setup Messages</a></li><li><a href="https://github.com/lightning/bolts/blob/master/01-messaging.md#control-messages">Control Messages</a></li></ul><h3>Thou Shall Manage Channel Lifecycle</h3><h4><a href="https://github.com/lightning/bolts/blob/master/02-peer-protocol.md"><strong><em>BOLT 2: Peer Protocol for Channel Management</em></strong></a></h4><p>This discusses channel operations like opening, closing, and managing it. Below are the topics this standard covers:</p><ul><li><a href="https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#definition-of-channel_id">Definition of the Channel ID</a></li><li><a href="https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#channel-establishment">Channel Establishment</a> (opening, accepting, funding, etc.)</li><li><a href="https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#channel-close">Channel Close</a></li><li><a href="https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#normal-operation">Channel Operation</a>s (HTLCs, updating fees, revoking &amp; acknowledging, CTLV expires, etc.)</li><li><a href="https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#message-retransmission">Message Retransmission</a></li></ul><h3>Thou Shall Transact with Bitcoin Properly</h3><h4><a href="https://github.com/lightning/bolts/blob/master/03-transactions.md"><strong>BOLT 3: Bitcoin Transaction and Script Formats</strong></a></h4><p>This tells us what the required formats of on-chain transactions with Bitcoin should look like. It includes funding, commitment, HTLC (Hash Time-Locked Contract) transactions, and key derivation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/0*o6585mwLDtw-g47t.jpg" /></figure><p>Below are the topics this standard covers:</p><ul><li><a href="https://github.com/lightning/bolts/blob/master/03-transactions.md#transaction-output-ordering">Transaction Output Ordering</a></li><li><a href="https://github.com/lightning/bolts/blob/master/03-transactions.md#use-of-segwit">Use of Segwit</a></li><li><a href="https://github.com/lightning/bolts/blob/master/03-transactions.md#funding-transaction-output">Funding Transaction Output</a></li><li><a href="https://github.com/lightning/bolts/blob/master/03-transactions.md#commitment-transaction">Commitment Transaction</a></li><li><a href="https://github.com/lightning/bolts/blob/master/03-transactions.md#htlc-timeout-and-htlc-success-transactions">HTLC-timeout and HTLC-success Transactions</a></li><li><a href="https://github.com/lightning/bolts/blob/master/03-transactions.md#closing-transaction">Closing Transaction</a></li><li><a href="https://github.com/lightning/bolts/blob/master/03-transactions.md#fees">Fees</a></li><li><a href="https://github.com/lightning/bolts/blob/master/03-transactions.md#dust-limits">Dust Limits</a></li><li><a href="https://github.com/lightning/bolts/blob/master/03-transactions.md#commitment-transaction-construction">Commitment Transaction Construction</a></li><li><a href="https://github.com/lightning/bolts/blob/master/03-transactions.md#keys">Keys</a></li></ul><h3>Thou Shall Securely Route Transactions</h3><h4><a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md"><strong>BOLT 4: Onion Routing Protocol</strong></a></h4><p>This standard describes the onion routing mechanism used for secure and private payment routing within the Lightning Network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jPafNdGQO48Y6Oy6" /></figure><p><strong>What are Onion Routes?</strong></p><p>Onion routes come from our days of illegally pirating music and movies from Torrent sites; it’s popularly used with Tor.</p><p><a href="https://blog.insiderattack.net/deep-dive-into-tor-the-onion-router-6de4c25beba7">Deep Dive Into TOR (The Onion Router)</a></p><p>The Lightning Network uses an onion routing technique, similar to the <a href="https://cypherpunks.ca/~iang/pubs/Sphinx_Oakland09.pdf">Sphinx</a> construction, to route transactions through multiple intermediate nodes, known as <strong>hops</strong>. An onion route packet is created by the origin node, which establishes a shared secret with each hop using the Diffie-Hellman key exchange (specifically, ECDH — Elliptic Curve Diffie-Hellman) and the public keys of the intermediate nodes.</p><p><a href="https://medium.com/coinmonks/diffie-hellman-and-why-its-needed-df558e808fea">Diffie Hellman and Why it’s Needed</a></p><p>The shared secret from Diffie Hellman is then used to create a stream of bytes that obfuscates the packets and a number of keys used to encrypt the payload and compute the HMACs.</p><p>Below are the topics this standard covers:</p><ul><li><a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md#conventions">Conventions</a></li><li><a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md#key-generation">Key Generation</a></li><li><a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md#pseudo-random-byte-stream">Pseudo-Random Byte Stream</a></li><li><a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md#packet-structure">Packet Structure</a> (<a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md#payload-format">Payload Format</a>ting, <a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md#basic-multi-part-payments">Basic Multi-Part Payments</a>, and <a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md#route-blinding">Route Blinding</a>)</li><li><a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md#accepting-and-forwarding-a-payment">Accepting and Forwarding a Payment</a></li><li><a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md#shared-secret">Shared Secret</a></li><li><a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md#blinding-ephemeral-keys">Blinding Ephemeral Keys</a></li><li><a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md#packet-construction">Packet Construction</a></li><li><a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md#packet-forwarding">Packet Forwarding</a></li><li><a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md#filler-generation">Filler Generation</a></li><li><a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md#returning-errors">Returning Errors</a></li><li><a href="https://github.com/lightning/bolts/blob/master/04-onion-routing.md#test-vector">Test Vector</a></li></ul><h3>Thou Shall Close the Channel</h3><h4><a href="https://github.com/lightning/bolts/blob/master/05-onchain.md"><strong>BOLT 5: Recommendations for On-chain Transaction Handling</strong></a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*QF0NQoeggYaSHOh6.jpg" /></figure><p>This standard goes over closing channels in the good (mutual close), bad (unilateral close), and ugly (revoked transaction) way. Check out the blog below for more details on channel closures.</p><p><a href="https://medium.com/coinmonks/different-ways-to-close-a-lightening-payment-channel-a11bbe4ed486">Different Ways to Close a Lightning Payment Channel</a></p><p>Below are the topics this standard covers:</p><ul><li><a href="https://github.com/lightning/bolts/blob/master/05-onchain.md#commitment-transaction">Commitment Transaction</a></li><li><a href="https://github.com/lightning/bolts/blob/master/05-onchain.md#failing-a-channel">Failing a Channel</a></li><li><a href="https://github.com/lightning/bolts/blob/master/05-onchain.md#mutual-close-handling">Mutual Close Handling</a></li><li><a href="https://github.com/lightning/bolts/blob/master/05-onchain.md#unilateral-close-handling-local-commitment-transaction">Unilateral Close Handling: Local Commitment Transaction</a></li><li><a href="https://github.com/lightning/bolts/blob/master/05-onchain.md#unilateral-close-handling-remote-commitment-transaction">Unilateral Close Handling: Remote Commitment Transaction</a></li><li><a href="https://github.com/lightning/bolts/blob/master/05-onchain.md#revoked-transaction-close-handling">Revoked Transaction Close Handling</a></li><li><a href="https://github.com/lightning/bolts/blob/master/05-onchain.md#generation-of-htlc-transactions">Generation of HTLC Transactions</a></li></ul><h3>Thou Shall Make Nodes &amp; Channels Discoverable</h3><h4><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md"><strong>BOLT 7: P2P Node and Channel Discovery</strong></a></h4><p>This standard defines the mechanisms for discovering Lightning nodes and channels on the network, including node announcements and channel updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EqLGzvFdlhxMRt2J.jpg" /></figure><p>Below are the topics this standard covers:</p><ul><li><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#definition-of-short_channel_id">Definition of </a><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#definition-of-short_channel_id">short_channel_id</a></li><li><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-announcement_signatures-message">The </a><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-announcement_signatures-message">announcement_signatures Message</a></li><li><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_announcement-message">The </a><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_announcement-message">channel_announcement Message</a></li><li><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-node_announcement-message">The </a><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-node_announcement-message">node_announcement Message</a></li><li><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message">The </a><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message">channel_update Message</a></li><li><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#query-messages">Query Messages</a></li><li><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#initial-sync">Initial Sync</a></li><li><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#rebroadcasting">Rebroadcasting</a></li><li><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#htlc-fees">HTLC Fees</a></li><li><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#pruning-the-network-view">Pruning the Network View</a></li><li><a href="https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#recommendations-for-routing">Recommendations for Routing</a></li></ul><h3>Thou Shall Encrypt and Authenticate</h3><h4><a href="https://github.com/lightning/bolts/blob/master/08-transport.md"><strong>BOLT 8: Encrypted and Authenticated Transport</strong></a></h4><p>It specifies the requirements for secure transport and message encryption between Lightning nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/0*ZiRtUim9A3iMBIxr" /></figure><p>Below are the topics this standard covers:</p><ul><li><a href="https://github.com/lightning/bolts/blob/master/08-transport.md#cryptographic-messaging-overview">Cryptographic Messaging Overview</a></li><li><a href="https://github.com/lightning/bolts/blob/master/08-transport.md#authenticated-key-exchange-handshake-specification">Authenticated Key Exchange Handshake Specification</a></li><li><a href="https://github.com/lightning/bolts/blob/master/08-transport.md#lightning-message-specification">Lightning Message Specification</a></li><li><a href="https://github.com/lightning/bolts/blob/master/08-transport.md#lightning-message-key-rotation">Lightning Message Key Rotation</a></li><li><a href="https://github.com/lightning/bolts/blob/master/08-transport.md#security-considerations">Security Considerations</a></li></ul><h3>Thou Shall Support New Features</h3><h4><a href="https://github.com/lightning/bolts/blob/master/09-features.md"><strong>BOLT 9: Assigned Feature Flags</strong></a></h4><p>This standard establishes a framework for assigning feature flags to enable optional protocol extensions within the Lightning Network.</p><p>Feature flags allow the network participants to signal their support for new or experimental features and provide a way to coordinate the activation of those features across the network. The flags are represented as bits, where the odd bits are optional features and the even bits compulsory features.</p><p>Feature flags usually are implemented through a consensus process, where participants in the network signal their readiness to support a particular feature by setting a specific flag in the protocol messages they exchange. Once a sufficient majority of participants have signaled their readiness, the feature can be activated on the network.</p><p>The use of feature flags allows for a more gradual and coordinated deployment of new features, ensuring compatibility and minimizing disruptions to the network. It also provides a mechanism for backward compatibility, as older implementations can still function without supporting the newly introduced features.</p><h3>Thou Shall Discover a Node Using DNS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K1wWeOmrWBLFHskM" /></figure><h4><a href="https://github.com/lightning/bolts/blob/master/10-dns-bootstrap.md"><strong>BOLT #10: DNS Bootstrap and Assisted Node Location</strong></a></h4><p>It defines a mechanism for Lightning nodes to discover initial peer connections using <a href="https://en.wikipedia.org/wiki/Domain_Name_System">DNS</a> records and assisted node location services. We use DNS to:</p><ul><li>Bootstrap: providing the initial node discovery for nodes that have no known contacts in the network</li><li>Assisted Node Location: supporting nodes in the discovery of the current network address of previously known peers</li></ul><p>Below are the topic this standard covers:</p><ul><li><a href="https://github.com/lightning/bolts/blob/master/10-dns-bootstrap.md#dns-seed-queries">DNS Seed Queries</a></li><li><a href="https://github.com/lightning/bolts/blob/master/10-dns-bootstrap.md#reply-construction">Reply Construction</a></li><li><a href="https://github.com/lightning/bolts/blob/master/10-dns-bootstrap.md#policies">Policies</a></li></ul><h3>Thou Shall Send Proper Invoices</h3><h4><a href="https://github.com/lightning/bolts/blob/master/11-payment-encoding.md"><strong>BOLT #11: Invoice Protocol for Lightning Payments</strong></a></h4><p>This standard specifies the format and semantics of Lightning Network invoices, which are used for requesting and receiving payments.</p><p>Below are the topics this standard covers:</p><ul><li><a href="https://github.com/lightning/bolts/blob/master/11-payment-encoding.md#encoding-overview">Encoding Overview</a></li><li><a href="https://github.com/lightning/bolts/blob/master/11-payment-encoding.md#human-readable-part">Human-Readable Part</a></li><li><a href="https://github.com/lightning/bolts/blob/master/11-payment-encoding.md#data-part">Data Part</a></li><li><a href="https://github.com/lightning/bolts/blob/master/11-payment-encoding.md#payer--payee-interactions">Payer / Payee Interactions</a></li></ul><p>Check out the article below to dive into invoices.</p><p><a href="https://medium.com/coinmonks/lightning-invoices-bd7210f25012">Lightning Invoices</a></p><h3>(Bonus) Thou Shall Provide Fresh Invoices</h3><h4>BOLT #12: Flexible Protocol for Lightning Payments (Offers)</h4><p>BOLT 12 aims to address the shortcoming of BOLT 11. Due to security concerns, BOLT 11 invoices can only be used once. So BOLT 12 saves the day by creating brand new invoices natively without the need for web servers (unlike LnURLs) in real-time. In BOLT 12, there is this concept of “Offers,” which can be shared publicly for donations or for merchants. Below is an example of an “Offer”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mipUqGv2r6J0yWeOP8DVKw.png" /><figcaption>Image: <a href="https://bootstrap.bolt12.org/examples">https://bootstrap.bolt12.org/examples</a></figcaption></figure><p><a href="https://bolt12.org/">bolt12.org: Lightning&#39;s Native Experience, Everywhere</a></p><p>Checkout Rusty Russell’s Git repo on BOLT</p><p><a href="https://github.com/rustyrussell/bolt12/">GitHub - rustyrussell/bolt12: Javascript Routines for the Lighting Network Protocol</a></p><p>There are two basic payment flows supported by BOLT 12:</p><p><strong>General User-Pays-Merchant Flow</strong></p><ol><li>A merchant publishes an <em>offer</em>, such as on a web page or a QR code.</li><li>Every user requests a unique <em>invoice</em> over the lightning network using the <em>invoice_request</em> message, which contains the offer fields.</li><li>The merchant replies with the <em>invoice</em>.</li><li>The user makes a payment to the merchant as indicated by the invoice.</li></ol><p><strong>Merchant-Pays-User Flow (e.g. ATM or refund)</strong></p><ol><li>The merchant publishes an <em>invoice_request</em> which contains offer fields that refer to its attempt to send money, including an amount.</li><li>The user sends an <em>invoice</em> over the lightning network for the amount in the <em>invoice_request</em> using a (possibly temporary) <em>invoice_node_id</em>.</li><li>The merchant confirms the <em>invoice_node_id</em> to ensure it’s about to pay the correct person and makes a payment to the invoice.</li></ol><h4>Why is it insecure reusing B.O.L.T. 11 Invoices?</h4><p>With invoices in BOLT 11, the payee can claim the payment by revealing the preimage (input). If you reused the invoice, you would be reusing the same hash, resulting in the same preimage.</p><p>This means anyone who previously saw the preimage (from the first time the invoice was paid) could intercept and claim future payments made to the same invoice.</p><p>They can potentially claim the funds if they set up their own HTLC (Hash Time Locked Contract) using the same hash and then unlock it using the preimage they already know. They can also track your payments across different channels and times, linking them together and reveal information about your finances.</p><p><strong><em>Disclaimer</em></strong><em>: Just knowing the preimage isn’t enough to intercept a transaction, the attacker would also need control over one of the nodes in the payment path that’s re-using the the same invoice. If the next node in the path (the one you received the HTLC from) sees on the blockchain that you broadcasted the old state you will be penalized.</em></p><blockquote><strong>A little bit about Pre-Images…</strong></blockquote><blockquote>The receiver when creating the invoice generates a random number and uses this number as input to a cryptographic hash function. The value yielded by the cryptographic hash function is the payment hash, and the random number in the input is the payment <a href="https://river.com/learn/terms/p/preimage#:~:text=A%20preimage%20is%20the%20data,hash%20of%20a%20public%20key">pre-image</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K7YkBZ63oHHWxiN7.png" /></figure><h4>Is B.O.L.T. 12 Used Today?</h4><p>B.O.L.T. 12 isn’t in the B.O.L.T. standards yet and is still in the experimentation and discussion phase. It was first implemented on C-Lightning and is currently on the roadmap for many of the popular implementations.</p><p>Here is the discussion on B.O.L.T. 12 on the LND Github repo:</p><p><a href="https://github.com/lightningnetwork/lnd/issues/5594">BOLT12 · Issue #5594 · lightningnetwork/lnd</a></p><p>Here is B.O.L.T. 12 on the Rust LDK roadmap for Q2&#39;23:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/0*aWko2MkMHKuLCA8r.png" /></figure><p><a href="https://www.nobsbitcoin.com/ldk-roadmap/">LDK Roadmap: LDK Node, BOLT 12, Anchor Outputs, Async Payments &amp; More</a></p><p>BOLT 12 is an exciting development and will be a critical piece in the evolution of the BOLT standards. BOLT 12 may not be perfect right now, but will eventually lead to an explosion of use Bitcoin Lightning use cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56cb4e9ae50b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Bitcoin Lightning Network]]></title>
            <link>https://medium.com/coinmonks/getting-started-with-bitcoin-lightning-network-5cd57e218463?source=rss-bdd0b2ab4dde------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cd57e218463</guid>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[bitcoin-lightning]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[layer-2]]></category>
            <category><![CDATA[payments-technology]]></category>
            <dc:creator><![CDATA[Mabel Oza]]></dc:creator>
            <pubDate>Wed, 17 May 2023 09:06:47 GMT</pubDate>
            <atom:updated>2023-10-21T15:37:55.128Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The Lightning Network is the layer-2 scaling solution for Bitcoin that was created to facilitate cheaper and faster transactions.</blockquote><h4>Bitcoin Lightning is similar to a bar tab…</h4><p>The lightning network acts as the tab running at a bar. The tab is a payment channel between you and the bar. When ordering the first drink, you provide a credit card, similar to initiating a payment channel. Then as the night proceeds, and you&#39;re having too much fun, you will order multiple drinks 🍻; these multiple drink orders are recorded transactions 📜. While going through these drinks, you haven&#39;t technically spent any money on these drinks. It&#39;s only until the end of the night when you pay for the drinks by closing out your tab.</p><p>With the lightning network, 2 transactions happen on the Bitcoin network, opening a payment channel (starting the tab) and closing a payment channel (closing out the tab).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/0*t6pdqyrL0BV3lW_i" /></figure><h4>Topics Covered:</h4><h4>⛈<strong> </strong><a href="#c409"><strong>What is Bitcoin Lightning?</strong></a></h4><h4>🤺<a href="#7433">Different Lightning Implementations</a></h4><h4>🌐<a href="#a085"><strong>Payment Channel Lifecycle</strong></a></h4><h4>🤔<a href="#7c9a">Analyzing a Lightning Payment Channel</a></h4><h4>👬<a href="#038d">Connecting to a Lightning Node via Docker</a></h4><h4>📚<a href="#d6fc">Resources</a></h4><h3>⛈ What is Bitcoin Lightning Network?</h3><p>The lightning network is built to facilitate cheaper transaction fees and faster transactions on the Bitcoin network.</p><h4>A Layer 2 Solution…</h4><p>It&#39;s a layer 2 solution, which means it&#39;s a child network to a major blockchain network. There are different variations to layer 2 networks, but the overall theme is that they are smaller versions of the network that write into the layer 1 network. Examples of other layer-2 solutions are Polygon for Ethereum, Loopring for Ethereum, and Lightning for Bitcoin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7sLFJ_E3EGyvNHDVJuVcA.png" /></figure><h4>Ingredients in the Lightning Network</h4><p>The Lightning Network consists of three key components: lightning nodes, payment channels, and routing nodes. <strong>Lightning nodes</strong> are the machines and software that allow organizations or people to participate. <strong>Payment channels</strong> are established between two nodes to allow for off-chain transactions with fast and low-cost settlements. <strong>Routing nodes</strong> are crucial in finding and forwarding payments across the network, ensuring that transactions can reach their intended destinations efficiently. These components create a scalable and efficient network for conducting fast and secure off-chain transactions.</p><h4>Lightning Nodes — The Building Blocks</h4><p>Lightning nodes are machines or instances that have lightning software installed. These nodes have a full Bitcoin node, a lightning client (see the Lightning Implementation section below), and a node wallet.</p><blockquote>A Lightning node is a piece of software that connects to the Lightning Network and allows users to transact with other nodes on the network. Anyone can run lightning nodes to send and receive payments and route payments for other users.</blockquote><p>Lightning nodes can be set up using a machine like raspberry pi (for experimental and learning purposes), on the cloud, or bought ready-made. Below is a guide on setting up a node:</p><p><a href="https://bitcoinmagazine.com/guides/how-to-set-up-a-lightning-network-node">How To Set Up A Lightning Network Node</a></p><p>Below is a link on whether you should buy or DIY a Bitcoin lightning node:</p><p><a href="https://bitcoinmagazine.com/reviews/buy-or-diy-an-overview-of-7-bitcoin-full-node-products">Buy or DIY? An Overview of 7 Bitcoin Full Node Products</a></p><h4>Payment Channels — Connecting Nodes</h4><p>The lightning network is made up of a collection of payment channels. A payment channel is a connection between two nodes that allows them to transact with each other off-chain without broadcasting their transactions to the main blockchain.</p><blockquote>A payment channel is a connection between two nodes that allows them to transact with each other off-chain without broadcasting their transactions to the main blockchain. This is the fundamental building block of the Lightning Network.</blockquote><p>Think of it like a Thanksgiving dining table. Bob is next to Carol, and Carol is next to Alice. Alice, Carol, and Bob will all be nodes in the lightning network. Alice and Carol have a payment channel, and Carol and Bob have a payment channel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDUNdPlRsgs3FTCS-sP3xQ.png" /></figure><p>Alice and Carol can have all the side conversations they want without sharing them with the group. There&#39;s no reason why Alice has to tell the group everything she wants to tell Carol and vice versa (unless she&#39;s roasting her). But if someone asks what they are talking about or Alice and Carol decide to bring in the group, they can summarize their conversation with the group. In this scenario, Alice and Carol have a payment channel.</p><p>With <strong>payment channels</strong>, nodes can transact with each other back and forth without ever sharing it with the larger Bitcoin network (all the nodes). The pieces they share are that they started a payment channel with each other and closed their channel with their final balances.</p><h4>Routing Nodes — Connecting Payment Channels</h4><p>The lightning network comprises multiple payment channels, mostly connected like a web. One party can connect with another party because the payment channels are all connected to each other.</p><blockquote>Routing nodes act as intermediaries and use their own payment channels to route transactions and relay payments to the final destination. Routing nodes are responsible for discovering and maintaining routes through the network and ensuring that transactions are processed quickly and efficiently.</blockquote><p>Going back to our Thanksgiving dinner… Even though Bob isn&#39;t sitting next to Alice, he can transact (give a slice of turkey 🦃) with Alice efficiently because he can go through Carol. Carol can agree to pass the turkey to Alice in exchange for payment. In this scenario, Carol would be called a <strong>routing node</strong>.</p><p>Over time as the network expands, all channels will be connected based on the theory of <a href="https://en.wikipedia.org/wiki/Six_degrees_of_separation">six degrees of separation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*cG_LIeLbTOCieNkwA6jTdQ.png" /></figure><p><strong>Onion Routing</strong></p><p>The technique used to route is <a href="https://www.geeksforgeeks.org/onion-routing/">onion routing</a>, developed in 1998 by DARPA (Defense Advanced Research Projects Agency) and has been commonly used in Tor Networks.</p><blockquote><strong>Onion routing </strong>applies anonymity to a network messages by wrapping each message in distinct layers of protection to hide the routing of the messages between a client device and a destination device.</blockquote><blockquote>The messages are encapsulated in layers of encryption, just like layers of an onion.</blockquote><p>In onion routing, each layer is encrypted with the public key of the next node in the route, including the final destination. The routing node receiving the onion packet only knows the address of the next node in the route, which is encrypted in the outer layer of the onion.</p><p>The routing node uses its routing table to determine the address of the next node to route the transaction and then decrypts the outer layer of the onion to reveal the address of the next node. It then encrypts the packet with the public key of the next node and sends it along to the next routing node. This process repeats until the packet reaches its final destination.</p><ul><li><a href="https://github.com/lightningnetwork/lightning-onion">GitHub - lightningnetwork/lightning-onion: Onion Routed Micropayments for the Lightning Network</a></li><li><a href="https://hackernoon.com/how-does-tor-really-work-5909b9bd232c">How does Tor actually work? | HackerNoon</a></li></ul><h3>🤺Different Lightning Implementations</h3><p>People and organizations use lightning implementations to interact with a lightning node and do all the necessary functions. All lightning network implementations must follow the specifications defined by B.O.L.T. (Basis of Lightning Technology).</p><p><a href="https://github.com/lightning/bolts">GitHub - lightning/bolts: BOLT: Basis of Lightning Technology (Lightning Network Specifications)</a></p><p>A few popular lightning networks that vary by language are C-Lightning, Eclair, LND, Rust LDK, and Electrum. C-Lightning is written in C, Eclair is written in Scala, LND is written in Go, Rust LDK is written in Rust, and Electrum is written in Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xc5z_Rugp6nA8YN1rEXCDA.png" /></figure><h3>🤔Analyzing a Lightning Payment Channel</h3><p>To truly understand a lightning network, it&#39;s crucial to analyze it in an explorer (i.e., <a href="https://mempool.space/">mempool.space</a>, <a href="https://1ml.com/">1ml.com</a>, or <a href="https://amboss.space/">amboss.space</a>).</p><p>Below is a snapshot taken from &quot;mempool.space&quot; on channel <a href="https://mempool.space/lightning/channel/805523109340971008">805523109340971008</a>, which is used by &quot;zero fee routing | CLN&quot; and &quot;BitcoinLightning.Network&quot;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DBHmisjSDlFqfcCttSVZcA.png" /><figcaption>This image was captured from <a href="https://mempool.space/lightning/channel/805523109340971008">https://mempool.space/lightning/channel/805523109340971008</a>.</figcaption></figure><p><strong>Key highlights about this network:</strong></p><ul><li>The lightning nodes involved in this channel are &quot;zero fee routing | CLN&quot; with the address <a href="https://mempool.space/lightning/node/038fe1bd966b5cb0545963490c631eaa1924e2c4c0ea4e7dcb5d4582a1e7f2f1a5">038fe1bd966b5cb0545963490c631eaa1924e2c4c0ea4e7dcb5d4582a1e7f2f1a5 </a>(Location is Germany with ISP <a href="https://mempool.space/lightning/nodes/isp/24940">Hetzner Online GmbH [ASN 24940]</a>) and &quot;BitcoinLightning.Network&quot; with the address <a href="https://mempool.space/lightning/node/023c55e8e1912096ed9ef4e18859de7fa652d713e5d1f2b83a3a8b845305a4287c">023c55e8e1912096ed9ef4e18859de7fa652d713e5d1f2b83a3a8b845305a4287c</a> (Location is unknown and Tor blocks the ISP)</li><li>&quot;BitcoinLightning.Network&quot; party put in all the sats to open this channel, 2,000,000 sats.</li><li>The Bitcoin network has the opening and closing transactions of the channels, respectively, <a href="https://mempool.space/tx/1b6869fbb7168da402396e1a477f7a35aa238cdbdccdda7ac6af81adf5f29bbb">1b6869fbb7168da402396e1a477f7a35aa238cdbdccdda7ac6af81adf5f29bbb</a> and <a href="https://mempool.space/tx/a3b23982331300ef8d23bd90b64e939758835515642a65ba64234bf2cae2ac7a">a3b23982331300ef8d23bd90b64e939758835515642a65ba64234bf2cae2ac7a</a>.</li><li>The fees to open and close this channel were $0.14 cents ($0.08 open txn fee + $0.06 close txn fee).</li><li>This channel ran for roughly 4 days.</li><li>During the 4 days, &quot;BitcoinLightning.Network&quot; sent &quot;zero fee routing | CLN&quot; 104,104 sats.</li><li>After the &quot;BitcoinLightning.Network&quot; transferred 104,104 sats, they were left with 1,895,896 sats (2,000,000 starting balance –104104 transferred balance). After paying the closing fee of 249 sats, they have a closing balance of 1,895,647 sats (1,895,896 balance after transfers in the channel — 249 closing fee).</li></ul><h3>🌐Payment Channel Lifecycle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72Z4kBHldFjxmjFJJ4rqXA.png" /></figure><h4>1. Create a Payment Channel</h4><p>We need to be part of a payment channel to do anything on the lightning network. To create a payment channel, we&#39;ll have Alice and Bob go through the following steps:</p><p><strong>Terms are Negotiated</strong></p><ol><li>Alice and Bob agree on the terms of the payment channel, including the amount of Bitcoin to be committed to the channel and the fees they will pay each other for routing payments.</li></ol><p><strong>Multi-Signature Wallet is Created</strong></p><ol><li>Alice <strong>creates a multi-signature wallet</strong> that requires both her and Bob&#39;s signatures to spend funds</li></ol><p><strong>Funding Transactions are Created &amp; Signed</strong></p><ol><li>Alice generates a funding transaction that allocates the agreed-upon amount of BTC from her wallet to the multi-sig wallet address. This transaction is not broadcast to the Bitcoin network yet.</li><li>Alice shares the funding transaction details with Bob, who verifies the details and adds his own input to the transaction.</li><li>Bob generates a signature for the funding transaction and shares it with Alice.</li><li>Alice adds her own signature to the funding transaction and broadcasts it to the Bitcoin network, making the funds available in the multi-sig wallet.</li><li>Bob creates his own funding transaction using the same multi-sig wallet address, allocates the agreed-upon amount of BTC from his wallet, and shares the funding transaction details with Alice.</li><li>Alice verifies the details and adds her own input to the transaction.</li><li>Alice generates a signature for the funding transaction and shares it with Bob.</li><li>Bob adds his own signature to the funding transaction and broadcasts it to the Bitcoin network, making the funds available in the multi-sig wallet.</li></ol><p><strong>Announcement Transactions</strong></p><ol><li>Alice creates a new transaction that spends from the funding transaction and sends the channel&#39;s capacity to a new public key (the channel ID).</li><li>Bob does the same and creates a new transaction with the same inputs and outputs but with his own public key as the channel ID.</li><li>Alice and Bob exchange their unsigned announcement transactions.</li><li>Alice signs Bob&#39;s announcement transaction with her private key and sends the signed transaction to Bob.</li><li>Bob signs Alice&#39;s announcement transaction with his private key and sends the signed transaction back to Alice.</li><li>Once both parties have fully signed announcement transactions, they can broadcast them to the Bitcoin network to publicly announce the existence of the new payment channel.</li></ol><h4>2. Exchange Funds in the Payment Channel</h4><ol><li>The recipient (Bob) generates an invoice that includes the payment amount and a payment hash.</li><li>The sender (Alice) uses her Lightning wallet to scan the invoice&#39;s QR code or copy the invoice details.</li><li>Alice&#39;s wallet decodes the invoice and verifies that it&#39;s valid.</li><li>Alice&#39;s wallet constructs a <a href="https://blog.nymtech.net/sphinx-tl-dr-the-data-packet-that-can-anonymize-bitcoin-and-the-internet-18d152c6e4dc">Sphinx packet</a> that includes the payment hash and encrypts it with Bob&#39;s public key.</li><li>Alice&#39;s wallet adds the Sphinx packet to a payment message that includes the payment amount and routes it through the Lightning network toward Bob&#39;s node.</li><li>The payment message is forwarded through intermediary nodes until it reaches Bob&#39;s node.</li><li>Bob&#39;s node decrypts the Sphinx packet with his private key to reveal the payment hash.</li><li>Bob&#39;s node looks up the <a href="https://river.com/learn/terms/p/preimage">preimage</a> corresponding to the payment hash and includes it in a Sphinx packet that is encrypted with the previous hop&#39;s public key.</li><li>Bob&#39;s node sends the Sphinx packet back through the network toward Alice&#39;s node.</li><li>The Sphinx packet is forwarded through intermediary nodes until it reaches Alice&#39;s node.</li><li>Alice&#39;s node decrypts the Sphinx packet with her private key to reveal the preimage.</li><li>Alice&#39;s node sends the preimage to Bob&#39;s node to prove the payment has been completed.</li><li>Bob&#39;s node verifies the preimage, and the payment is complete.</li></ol><p><strong>The Invoice</strong></p><p>All payments start with an invoice (unless it&#39;s <a href="https://docs.lightning.engineering/lightning-network-tools/lnd/send-messages-with-keysend">keysend</a>). The payee must put together an invoice. This tells the payer what network they want the payment in and the amount.</p><blockquote>A Lightning invoice is a payment request that includes a payment hash and a preimage, which the payer must provide to settle the invoice.</blockquote><blockquote>Lightning invoices are generated by the payee and are used to receive payments through the Lightning Network.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uh7r7vSjDa-tJNYwXNf0Dg.png" /></figure><p>Dive deeper into specifics around an invoice at the blog below:</p><p><a href="https://medium.com/coinmonks/lightning-invoices-bd7210f25012">Lightning Invoices</a></p><h4>3. Close the Payment Channel</h4><p>There are 3 ways to close a channel, a collaborative close, a force close, and a dispute close.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVupZgr2BFiy-9onAfv4rg.png" /></figure><p>Below are the steps at a high level:</p><ol><li>Either party initiates the closing process by sending a close transaction to the Bitcoin network.</li><li>The closing transaction spends the latest channel state, which includes the balance of each party.</li><li>The closing transaction is broadcast to the Bitcoin network and included in a block.</li><li>Once the closing transaction is confirmed, both parties can claim their respective channel balances on the Bitcoin network.</li></ol><blockquote>If one party does not agree with the channel state used in the closing transaction, they can broadcast a penalty transaction to the Bitcoin network. This penalty transaction claims all the funds in the channel for the non-compliant party.</blockquote><blockquote>If the penalty transaction is broadcast, it will invalidate the previous closing transaction and force the compliant party to wait until the penalty transaction confirms before claiming their funds.</blockquote><p>Check out the write-up below for a deeper dive into closing channels:</p><p><a href="https://mabeloza.medium.com/different-ways-to-close-a-lightening-payment-channel-a11bbe4ed486">Different Ways to Close a Lightening Payment Channel</a></p><h3>👬Connecting to a Lightning Node via Docker</h3><h4>Getting Started with the Lightning Network with Docker</h4><ol><li>Find your machine&#39;s IP address by running the command (macOS):</li></ol><pre>ipconfig getifaddr en0</pre><ol><li>Find your machine&#39;s IP address by running the command (windows):</li></ol><pre>ipconfig /all</pre><p>2. Set your IP address as an IP_ADDR variable. If your IP address is 192.xxx.x.xx, then run the command:</p><pre>IP_ADDR=192.xxx.x.xx</pre><p>3. Set a volume to store the data for the lightning node and name lnd-data:</p><pre>docker volume create lnd-data</pre><p>4. Run the following docker command:</p><pre>docker run -v lnd-data:/lnd --name=lnd-node -d \<br>  -p 9735:9735 \<br>  -p 10009:10009 \<br>  lnzap/lnd:latest \<br>  --bitcoin.active \<br>  --bitcoin.testnet \<br>  --debuglevel=info \<br>  --bitcoin.node=neutrino \<br>  --neutrino.connect=testnet1-btcd.zaphq.io \<br>  --neutrino.connect=testnet2-btcd.zaphq.io \<br>  --autopilot.active \<br>  --tlsextraip=$IP_ADDR \<br>  --externalip=$IP_ADDR:10009 \<br>  --rpclisten=0.0.0.0:10009</pre><h4>Breakdown of this Docker Command</h4><p>Below are a few highlights to notice in the docker command above.</p><p><strong>Using the Volume lnd-data</strong></p><pre>-v lnd-data:/lnd --name=lnd-node -d</pre><p>We are telling docker the node will use the volume created earlier (lnd-data)</p><p><strong>Pulling the Zap Lightning Network Image</strong></p><pre>lnzap/lnd:latest</pre><p>The image is lnzap/lnd, created by the open-source project, Zap (<a href="https://zaphq.io/">https://zaphq.io</a>).</p><p><a href="https://hub.docker.com/r/lnzap/lnd">Docker</a></p><p><strong>Using the Testnet Network</strong></p><pre>--bitcoin.testnet</pre><p>For learning purposes, we will only use Bitcoin testnet, so we&#39;re not using any real money.</p><p><strong>Connect to the Neutrino Public Client</strong></p><p>We will connect to a Neutrino public client using Zap&#39;s Neutrino testnet client <a href="https://zaphq.io/">https://zaphq.io/</a>.</p><blockquote><strong>A little bit about Neutrino…</strong></blockquote><blockquote>Neutrino came out of BIPs 157/158 (<em>Client-Side Block Filtering</em>), which is an improvement from Bloom Filters proposed in BIP 37.</blockquote><blockquote>Neutrino clients are lightweight Bitcoin clients that use simplified payment verification (SPV) and client-side filtering. Client-side filtering is used to to sync with the Bitcoin network and retrieve only the transactions relevant to the user’s wallet, without having to download and verify the entire blockchain.</blockquote><pre>--bitcoin.node=neutrino \<br>  --neutrino.connect=testnet1-btcd.zaphq.io \<br>  --neutrino.connect=testnet2-btcd.zaphq.io \</pre><p><strong>Checkout </strong><a href="https://medium.com/u/e56d3a55c1c9"><strong>Suredbits</strong></a><strong> explainer for a deeper dive into Neutrino:</strong></p><p><a href="https://suredbits.com/neutrino-what-is-it-and-why-we-need-it/">https://suredbits.com/neutrino-what-is-it-and-why-we-need-it/</a></p><p><strong>Automatically Open Channels with Other Channels</strong></p><p>This flag is used to activate the autopilot feature of the Lightning Network Daemon (LND). Autopilot is a feature that automatically opens channels with other nodes on the network based on certain criteria, such as channel size, uptime, and fees.</p><pre>--autopilot.active \</pre><p><strong>Set an Additional IP address to include in the TLS certificate</strong></p><p>The --tlsextraip flag adds an extra IP address to the TLS certificate that the LND node uses to establish secure connections. The $IP_ADDR variable should be replaced with the IP address of the node.</p><pre>--tlsextraip=$IP_ADDR \</pre><p><strong>Advertise IP Address and Port to the Network</strong></p><p>This tells the LND node to advertise itself to the network using the given IP address and port number ($IP_ADDR is the IP address of the node). This is useful if the node is behind a NAT or firewall and needs to be reachable from outside the network.</p><pre>--externalip=$IP_ADDR:10009 \</pre><p><strong>IP Address and Port for Incoming RPC Connections</strong></p><p>This sets the IP address and port number the LND node will listen to for incoming RPC connections. The 0.0.0.0 IP address means that the node will listen on all available network interfaces and $IP_ADDR:10009 specifies the port number to listen on.</p><pre>--rpclisten=0.0.0.0:10009</pre><h3>📚Obsessed? More Resources</h3><p><strong>Lightning Network Original Whitepaper</strong></p><p><a href="https://lightning.network/lightning-network-paper.pdf">https://lightning.network/lightning-network-paper.pdf</a></p><p><strong>Lightning Node Setup Guide (with Docker)</strong></p><p><a href="https://boxmining.com/lightning-node-guide/">Lightning Node Setup Guide (With Docker)</a></p><p><strong>History of the Lightning Network Infographic</strong></p><p><a href="https://i.redd.it/d4ulzl8s5oq21.png">https://i.redd.it/d4ulzl8s5oq21.png</a></p><p><a href="https://medium.com/@dougvk/run-your-own-mainnet-lightning-node-2d2eab628a8b"><strong>Doug von Kohorn&#39;s Run You Own Lightning Node</strong></a></p><p><a href="https://medium.com/@dougvk/run-your-own-mainnet-lightning-node-2d2eab628a8b">Run your own mainnet Lightning Node</a></p><p><strong>Bitcoin Magazine: Understanding the Lightning Network — Building a Bi-Directional Payment Channel</strong></p><p><a href="https://bitcoinmagazine.com/technical/understanding-the-lightning-network-part-building-a-bidirectional-payment-channel-1464710791">Understanding the Lightning Network, Part 1: Building a Bidirectional Bitcoin Payment Channel</a></p><p><strong>LNBook — Mastering Lightning Network</strong></p><p><a href="https://github.com/lnbook/lnbook">GitHub - lnbook/lnbook: Mastering the Lightning Network (LN)</a></p><p><strong>Coindesk Lightning Network Research — 2021.09</strong></p><p><a href="https://downloads.coindesk.com/research/Lightning+Network+-+CoinDesk+Research+-+2021.09.pdf">https://downloads.coindesk.com/research/Lightning+Network+-+CoinDesk+Research+-+2021.09.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cd57e218463" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/getting-started-with-bitcoin-lightning-network-5cd57e218463">Getting Started with Bitcoin Lightning Network</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lightning Invoices]]></title>
            <link>https://medium.com/coinmonks/lightning-invoices-bd7210f25012?source=rss-bdd0b2ab4dde------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd7210f25012</guid>
            <category><![CDATA[lightning-network]]></category>
            <category><![CDATA[bitcoin-lightning-network]]></category>
            <category><![CDATA[cryptopayments]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[payment-channels]]></category>
            <dc:creator><![CDATA[Mabel Oza]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 11:01:48 GMT</pubDate>
            <atom:updated>2023-05-17T05:40:46.965Z</atom:updated>
            <content:encoded><![CDATA[<p>All payments start with an invoice (unless it’s <a href="https://docs.lightning.engineering/lightning-network-tools/lnd/send-messages-with-keysend">keysend</a>). The payee must put together an invoice. This tells the payer what network they want the payment in and the amount.</p><blockquote>A Lightning invoice is a payment request that includes a payment hash and a preimage, which the payer must provide to settle the invoice.</blockquote><blockquote>Lightning invoices are generated by the payee and are used to receive payments through the Lightning Network.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xoxGA243I3bbmY8XCKPZmQ.png" /></figure><p>We’re going to dive into:</p><p><a href="#99ff"><strong>Anatomy of an Invoice</strong></a></p><ul><li><a href="#6a05">Human Readable Part</a></li><li><a href="#435a">Data Part</a></li></ul><p><a href="#a14b"><strong>Why Do Lightning Payments Need Invoices?</strong></a></p><p><a href="#6f92"><strong>Alternatives to Payments Without Invoices — Keysend</strong></a></p><h3>Anatomy of an Invoice</h3><p>The invoice is formatted in <a href="https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki">bech32 encoding</a>, already used for Bitcoin Segregated Witness. It’s broken up into 2 main parts: human-readable and data portions.</p><p>Below is an example of an invoice:</p><p><strong><em>lnbc15u</em></strong>1p3xnhl2<strong>p</strong>p5jptserfk3zk4qy42tlucycrfwxhydvlemu9pqr93tuzlv9cc7g3s<strong>d</strong>qsvfhkcap3xyhx7un8<strong>c</strong>qzpg<strong>x</strong>qzjc<strong>s</strong>p5f8c52y2stc300gl6s4xswtjpc37hrnnr3c9wvtgjfuvqmpm35evq<strong>9</strong>qyyssqy4lgd8tj637qcjp05rdpxxykjenthxftej7a2zzmwrmrl70fyj9hvj0rewhzj7jfyuwkwcg9g2jpwtk3wkjtwnkdks84hsnu8xps5vsq4gj5hs</p><h4><strong>Human Readable Part</strong></h4><p>The human-readable part has the network name and amount. In the example above <strong><em>lnbc15u </em></strong>is the human-readable part.</p><p><strong><em>Network</em></strong></p><p>All Lightning invoices start with the letters ln for Lightning Network. Then they are followed by a 2-letter code defined by <a href="https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki">BIP173</a> for the network. Below is a table with network prefixes. For example, an invoice that starts withln<strong>bc </strong>would be in the lightning mainnet because bc is after ln.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nq9oZTKYd_dg052mZSharw.png" /></figure><p><strong><em>Amount</em></strong></p><p>The amounts reference bitcoin, not satoshi. To save space for round invoices, an amount can be followed by a multiplier. For example, a single satoshi Lightning invoice would appear as 10n, a hundred satoshi as 1u, and a milli-satoshi as 10p. In the example above, the amount is 15u (15* 100 satoshis). Below is a table of the amount units.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l88YhZLqhloZxCgSfCmUJA.png" /></figure><h4><strong>Data Part</strong></h4><p>The data part is broken up into a timestamp, payment hash, description, min block height expiry (min final CLTV Expiry), expiry, payment secret (preimage),</p><p>An easy to know the different parts is by looking for the tags. P is the tag for payment hash, D is the tag</p><p>In the example above, the data part is:</p><p><strong>p</strong>p5jptserfk3zk4qy42tlucycrfwxhydvlemu9pqr93tuzlv9cc7g3s<strong>d</strong>qsvfhkcap3xyhx7un8<strong>c</strong>qzpg<strong>x</strong>qzjc<strong>s</strong>p5f8c52y2stc300gl6s4xswtjpc37hrnnr3c9wvtgjfuvqmpm35evq<strong>9</strong>qyyssqy4lgd8tj637qcjp05rdpxxykjenthxftej7a2zzmwrmrl70fyj9hvj0rewhzj7jfyuwkwcg9g2jpwtk3wkjtwnkdks84hsnu8xps5vsq4gj5hs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05EjUCGQ_J021jhy1bMauA.png" /></figure><p><strong><em>Timestamp</em></strong></p><p>In the example above, the timestamp is p3xnhl2, this is equivalent to the timestamp 1651105770, which is equivalent to Monday, May 2, 2022, at 8:29:30 AM UTC.</p><p><strong><em>Payment Hash</em></strong></p><p>In the example above, the payment hash (tagged with p) is <strong>p</strong>p5jptserfk3zk4qy42tlucycrfwxhydvlemu9pqr93tuzlv9cc7g3s. The payment hash is a 32-byte hash that uniquely identifies a Lightning Network payment. This hash is used to reference the payment throughout the payment’s lifecycle, from invoice creation to the payment&#39;s fulfillment.</p><p><strong><em>Description</em></strong></p><p>In the example above, the description (tagged with d) is <strong>d</strong>qsvfhkcap3xyhx7un8. The description can be any text note on the invoice. The description in the example is decoded to bolt11.org.</p><p><strong><em>Min Final CLTV Expiry</em></strong></p><p>In the example above, the minimum final CLTV (CheckLockTimeVerify) expiry (tagged with c) is cqzpg. The minimum final CLTV is the minimum block height at which the payment can be considered final. In this example, there is a requirement of a block height of 40 to be considered final.</p><p><strong><em>Expiry</em></strong></p><p>In the example above, the expiry (tagged with x) is xqzjc. The expiry is the number of seconds after which the invoice will expire if the payment has not been made. In this example, the invoice will expire in 600 seconds (10 minutes) if a payment hasn’t been made.</p><p><strong><em>Payment Secret</em></strong></p><p>In the example above, the payment secret (tagged with s) is sp5f8c52y2stc300gl6s4xswtjpc37hrnnr3c9wvtgjfuvqmpm35evq. The payment secret is a random 32-byte string that the payer generates, encrypted in the invoice using the shared secret. It is also known as the preimage or the payment hash preimage.</p><p>The recipient must decode the invoice to obtain the payment secret, which the payer later uses to prove the payment was successful and claim the funds in the payment channel.</p><p>The payment secret is crucial for the network’s security and privacy features because it prevents unwanted parties from intercepting or tampering with the payment.</p><p><strong><em>Feature Bits</em></strong></p><p>In the example above, the feature bits (tagged with 9) is 9qyyssq. Feature bits are optional or required features that can be included in the invoice to indicate to the payer which capabilities the payee’s Lightning node supports. In this example, the featured bits are:</p><pre>{<br>&quot;var_onion_optin&quot;: &quot;supported&quot;, <br>&quot;payment_secret&quot;: &quot;required&quot;, <br>&quot;basic_mpp&quot;: &quot;supported&quot;<br>} </pre><ul><li>“var_onion_optin”: indicates that the payee’s node supports using variable-length onion packets for routing the payment.</li><li>“payment_secret”: indicates that the payee requires the payer to include a payment secret in the payment hash.</li><li>“basic_mpp”: indicates that the payee’s node supports the use of basic multi-path payments, which allows a payment to be split across multiple routes.</li></ul><p><strong><em>Signature</em></strong></p><p>In the example above, the signature is y4lgd8tj637qcjp05rdpxxykjenthxftej7a2zzmwrmrl70fyj9hvj0rewhzj7jfyuwkwcg9g2jpwtk3wkjtwnkdks84hsnu8xps5vsq. A signature is a cryptographic signature created by the invoice issuer’s private key. It’s used to ensure the authenticity and integrity of the invoice. When the invoice recipient receives it, they can use the issuer’s public key to verify the signature and ensure that the invoice has not been tampered with.</p><p><strong><em>Checksum</em></strong></p><p>In the example above, the checksum is 4gj5hs. A checksum is a value calculated from a specific algorithm that is added to a Lightning invoice to ensure the integrity of the data and help detect errors.</p><h3>Why Do Lightning Payments Need Invoices?</h3><p>We need invoices in the Lightning Network to enable payments to be routed from the payer to the payee. Invoices contain important information such as the payment amount, payment hash, and other optional fields like the routing hints that enable intermediaries to discover the path to the payee. Routing nodes use invoices to determine the next hop in the payment path and forward the payment to the next node until it reaches the payee.</p><p>In addition, invoices also provide a way for the payee to request a specific payment amount and add additional metadata, such as an order number or customer ID, that can be useful for accounting or tracking purposes.</p><p>Without invoices, payers would have to manually construct payments and specify the routing path, which can be error-prone and time-consuming. Overall, invoices are critical in enabling efficient and reliable payment routing in the Lightning Network.</p><h3>Alternatives to Payments Without Invoices — Keysend</h3><p>Keysend is a feature introduced in the Lightning Network that allows for small and spontaneous payments without needing a Lightning invoice. With keysend, a payer can simply send a payment directly to the payee’s Lightning node by including the payment information, such as the payment amount and memo, in the onion routing packet.</p><p>To make a payment using keysend, the payer’s Lightning node generates a payment hash and constructs an onion routing packet with the payment information in the payload. The onion packet is then sent to the payee’s Lightning node, which decrypts the packet and retrieves the payment information. The payee’s Lightning node then constructs a Lightning invoice using the payment hash, which the payer’s node can use to claim the payment once they have the preimage corresponding to the payment hash.</p><p>Keysend allows for more spontaneous and efficient payments. It eliminates the need for the payee to generate a Lightning invoice and for the payer to scan the QR code or manually enter the payment information. However, it does raise some privacy concerns, as the payment information is included in the routing packet in plaintext and can be visible to all the nodes involved in routing the payment.</p><h3>Resources</h3><p><strong>Interactive Invoice BOLT 11</strong></p><p><a href="https://www.bolt11.org/">The Lightning Invoice</a></p><p><a href="https://medium.com/u/e56d3a55c1c9"><strong>Suredbits</strong></a><strong> on Lightning Invoices</strong></p><p><a href="https://medium.com/suredbits/lightning-101-what-is-a-lightning-invoice-d527db1a77e6">Lightning 101: What is a Lightning Invoice?</a></p><p><strong>BOLT11 Standards on Invoices in Github</strong></p><p><a href="https://github.com/lightning/bolts/blob/master/11-payment-encoding.md">bolts/11-payment-encoding.md at master · lightning/bolts</a></p><p><strong>Lightning Engineering — Understanding Lightining Invoices</strong></p><p><a href="https://docs.lightning.engineering/the-lightning-network/payment-lifecycle/understanding-lightning-invoices">Understanding Lightning Invoices</a></p><p><strong>Lightning Keysend — ReadTheDocs</strong></p><p><a href="https://lightning.readthedocs.io/lightning-keysend.7.html">lightning-keysend - Send funds to a node without an invoice - Core Lightning b8519a6-modded</a></p><p><strong>Voltage Keysend Payments</strong></p><p><a href="https://voltage.cloud/blog/bitcoin-lightning-network/keysend-payments-explained-voltage-technical-series/">Lightning Keysend Payments Explained | Voltage</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd7210f25012" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/lightning-invoices-bd7210f25012">Lightning Invoices</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lightning Network & Delays]]></title>
            <link>https://medium.com/coinmonks/lightning-network-delays-1208a463f9b6?source=rss-bdd0b2ab4dde------2</link>
            <guid isPermaLink="false">https://medium.com/p/1208a463f9b6</guid>
            <category><![CDATA[lightning-network]]></category>
            <category><![CDATA[cryptopayments]]></category>
            <category><![CDATA[bitcoin-lightning-network]]></category>
            <category><![CDATA[cryptocurrency-payment]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Mabel Oza]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 07:23:19 GMT</pubDate>
            <atom:updated>2023-04-14T05:54:56.232Z</atom:updated>
            <content:encoded><![CDATA[<p>Delays in the Lightning Network are security measures that prevent inaccuracies and cheating from being published on the mainnet Bitcoin network. These built-in delays are called <strong>time-lock</strong> (sometimes referred to as CSV) and <strong>revocation delays. </strong>They both involve using time to enforce security but serve different purposes. Time-lock (CSV) prevents premature channel closings, and revocation delays prevent old states from being used maliciously.</p><h4><strong>Time-Lock Delay</strong></h4><p>A time-lock delay is implemented using a CheckSequenceVerify (CSV) feature, which allows a party to set a delay on the transaction so that the other party cannot spend it until a certain amount of time has elapsed. This gives both parties time to resolve any issues that may arise, such as a channel closure or dispute over the transaction, before the funds are released.</p><h4>Revocation Delay</h4><p>A revocation delay is a security mechanism in the Lightning Network designed to prevent cheating in payment channel transactions. When a payment channel is opened, both parties commit to a set of transactions that can be used to close the channel and distribute the funds. The revocation delay is when one party can prove that the other party cheated by revealing a transaction that invalidates the previous transaction. If a party cheats, the other party can use this revealed transaction to claim all the funds in the channel, and the cheater is punished by losing their share of the funds.</p><h3>Difference between Time-lock/CSV and Revocation Delays</h3><p>Time locks/CSV determine how long a commitment transaction must be delayed, while revocation delays determine how long a revoked commitment transaction must be delayed before it can be broadcasted. The differences are subtle, so I captured them in the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*spcL9n74vI8sJdtcsAKsFg.png" /></figure><h3>Time-Lock/CSV and Revocation Delays in Code</h3><h4><strong><em>Time-lock/CSV</em></strong></h4><p>Time-locks/CSVs enforce the order and timing of transactions, preventing double-spending by either party in the channel. The time-lock/CSV value (number of blocks that acts as time) is set in every commitment transaction.</p><p>Below is an example of a regular off-chain commitment transaction using the LND implementation in Go. Here we are setting the csvTimeout to 144 blocks (roughly 1 day).</p><pre>// Set the CSV timeout to 144 blocks (roughly 1 day)<br>csvTimeout := uint32(144)</pre><p>After the csvTimeout is set, you can see it’s passed in as one of the values in CreateCommitTx (create a commitment transaction).</p><pre>// Create the commitment transaction<br>commitTx, err := lnwallet.CreateCommitTx(channelState.OurBalance,<br>                                         channelState.TheirBalance,<br>                                         ourPaymentBasePoint, theirPaymentBasePoint,<br>                                         ourHtlcBasePoint, theirHtlcBasePoint,<br>                                         csvTimeout, 0, channelState.FeePerKw,<br>                                         channelState.LocalChanCfg.DustLimit)<br>if err != nil {<br>    // handle error<br>}<br>// Sign the transaction<br>localFundingKey, err := channelState.LocalChanCfg.MultiSigKey.PubKey()<br>if err != nil {<br>    // handle error<br>}<br>sig, err := wallet.Cfg.Signer.SignOutputRaw(commitTx, 0, fundingScript, localFundingKey)<br>if err != nil {<br>    // handle error<br>}<br>commitTx.TxIn[0].Witness = lnwallet.CommitSpendTimeoutWitness(sig)</pre><p><strong><em>Revocation Delays</em></strong></p><p>Revocation delays prevent a counterparty from publishing an outdated channel state, preventing fraudulent activity. The revocation delay value (number of blocks that acts as time) is set when the channel is opened, and the initial commitment transaction is broadcasted to the network. The revocation delay is a fixed value and cannot be modified after the initial commitment transaction. Every commitment transaction has a new revocation key. The non-fraudulent party can use this key to reclaim their funds within a specific time period (revocation delay).</p><p>Below is an example of an initial commitment after a funding transaction using the LND implementation in Go. In this example, the revocation delay called RemoteCsvDelay, is set to 20 blocks.</p><pre>// Create the open channel request<br>openChanReq := &amp;lnrpc.OpenChannelRequest{<br>    NodePubkey:         remotePubKey.SerializeCompressed(),<br>    LocalFundingAmount: int64(fundingAmount),<br>    PushSat:            int64(lnd.Cfg.PushSat),<br>    TargetConf:         lnd.Cfg.RequiredConfirmations,<br>    SatPerByte:         int64(lnd.Cfg.FeePerKW),<br>    MinHtlcMsat:        int64(lnd.Cfg.MinHTLC),<br>    RemoteCsvDelay:     20,<br>}</pre><p>Once the open channel request is prepared, it’s sent using the LND client to be opened.</p><pre>// Send the open channel request<br>ctxb = context.Background()<br>response, err := lnd.Client.OpenChannel(ctxb, openChanReq)<br>if err != nil {<br>    log.Fatal(err)<br>}</pre><h3>In Conclusion…</h3><p>Regarding enforcement mechanism, Time-lock/CSV utilizes time-lock for CSV, while Revocation Delays use a revocation key. Time-lock/CSV applies to every transaction in the channel, while Revocation Delays apply only to the latest transaction in the channel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1208a463f9b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/lightning-network-delays-1208a463f9b6">Lightning Network &amp; Delays</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Different Ways to Close a Lightning Payment Channel]]></title>
            <link>https://mabeloza.medium.com/different-ways-to-close-a-lightening-payment-channel-a11bbe4ed486?source=rss-bdd0b2ab4dde------2</link>
            <guid isPermaLink="false">https://medium.com/p/a11bbe4ed486</guid>
            <category><![CDATA[lightning-network]]></category>
            <category><![CDATA[bitcoin-development]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[bitcoin-lightning]]></category>
            <category><![CDATA[payment-channels]]></category>
            <dc:creator><![CDATA[Mabel Oza]]></dc:creator>
            <pubDate>Fri, 24 Mar 2023 19:32:53 GMT</pubDate>
            <atom:updated>2023-04-03T13:14:02.104Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OIMQJ88-qxmDwwd6LT6sEg.png" /></figure><p>In the lightning network, payment channels can close in 3 different ways, and they&#39;re good, bad, and ugly. The good is a <strong><em>&quot;collaborative close&quot;</em></strong> when both parties work together to close the channel. The bad is a <strong><em>&quot;force close&quot;</em></strong> when one party can&#39;t close the channel. The ugly is a <strong><em>&quot;dispute close&quot;</em></strong> when there&#39;s a force close, but the other party comes back and disputes the close initiated by the other party.</p><h4>😃 <a href="#f241">Collaborative Close — Good</a></h4><ol><li><a href="#d20e"><strong>Negotiate the final channel balance</strong></a></li><li><a href="#176d"><strong>Initiate &amp; Exchange Close Requests</strong></a></li><li><a href="#9ea3"><strong>Sign, Exchange &amp; Broadcast Close Requests to the Network</strong></a></li><li><a href="#55df"><strong>Wait for Confirmations on the Network</strong></a></li><li><a href="#b7d3"><strong>Remove the Channel</strong></a></li></ol><p>💻 <a href="#ae6b"><strong>Code to do a Collaborative Close</strong></a></p><p><strong>📜 </strong><a href="#2371"><strong>Example of a Collaborative Close Transaction</strong></a></p><h4>😞 <a href="#c07d">Force Close — Bad</a></h4><ol><li><a href="#a03a"><strong>Initiate, Sign, and Broadcast the Force Close Request</strong></a></li><li><a href="#3a05"><strong>Wait for the Force Close to Confirm</strong></a></li><li><a href="#2e81"><strong>Remove the Channel</strong></a></li></ol><p>💻 <a href="#1b80"><strong>Code to do a Force Close</strong></a></p><p><strong>📜</strong> <a href="#a4db"><strong>Example Forced Close Transaction</strong></a></p><h4>😡 <a href="#1b00">Disputed Close — Ugly</a></h4><p><strong>💻 </strong><a href="#3a7b"><strong>Code of a Dispute Close Transaction</strong></a></p><p><strong>🗼</strong><a href="#cb66"><strong>Watch Tower</strong></a></p><h4>📚<a href="#bb7d">Hooked? Dive into the Rabbit Hole</a></h4><h3>😃 Collaborative Close</h3><p>A collaborative close in the Lightning Network is a channel closure where both parties agree to close the channel. With a collaborative close, both parties sign off on closing the payment channel and get their funds back immediately. Below are the steps to a collaborative close.</p><h4>1. Negotiate the Final Channel Balance</h4><p>Before initiating the channel closing, the parties should agree on the final balance. This can be done by exchanging commitment transactions until they reach a final balance that they both agree on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETQosk_05asbcLjUxGvgcQ.png" /></figure><h4>2. Initiate Close Channel Requests &amp; Exchange Requests</h4><p>Each party must initialize a close channel request in a collaborative close. Before the request is ever signed and broadcasted to the network, it must be exchanged to ensure everyone is on the right page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eklpy1IwNjG6gj0fkW2jhw.png" /></figure><p>An initialize request in LND implementation involves the following details:</p><ul><li><strong>Channel Point</strong>: a unique identifier for a payment channel established between two parties. It consists of the channel funding transaction hash and the index of the transaction output that funds the channel.</li><li><strong>Target Confirmations: </strong>How many blocks need to be mined after the close txn to consider the txn done?</li><li><strong>Sats Per Byte: </strong>This is the Bitcoin fee rate the party is willing to pay on the close transaction.</li><li><strong>Force: </strong>Since this is not a force close, force is set to false.</li><li><strong>Delivery Address: </strong>Specifies an address to receive the funds from the closed channel. If left empty, the funds will still be split between the two parties according to their channel balance, but any unspendable funds will go to the node that initiated (Alice) the channel closure request.</li></ul><p>Below is the code (using the LND go implementation) to initiate the close:</p><pre>// Initiate the cooperative channel close.<br>closeReq := &amp;lnrpc.CloseChannelRequest{<br>    ChannelPoint: channelPoint,<br>    TargetConf:   0, // Wait for the next block.<br>    SatPerByte:   1, // Set the fee rate.<br>    Force:        false, // Initiate a cooperative closure.<br>    DeliveryAddress: &quot;your_bitcoin_address&quot;, // Optional.<br>}<br>closeResp, err := client.CloseChannel(ctx, closeReq)<br>if err != nil {<br>    log.Fatal(err)<br>}<br>log.Printf(&quot;Close channel response: %v&quot;, closeResp)<br>closeChannelStream, err := client.CloseChannel(context.Background(), closeChannelReq)<br>if err != nil {<br>     log.Fatalf(&quot;could not initiate close: %v&quot;, err)<br>}</pre><p>Below is the code (using the LND go implementation) to receive the close request from the remote (other) party:</p><pre>// Receive close request from remote party.<br>closeRequest, err := closeChannelStream.Recv()<br>if err != nil {<br>     log.Fatalf(&quot;could not receive close request: %v&quot;, err)<br>}</pre><h4>3. Sign, Exchange &amp; Broadcast Requests to the Network</h4><p>Now that both parties agree on the close request, they can sign and broadcast their requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clCFxgCZ_rpAKRzKWtkk9w.png" /></figure><p>Below is the code (using the LND go implementation) to sign the request, send it to the remote (other) party, and receive the signed request from the remote (other) party.</p><pre>// Sign the close request.<br>    signedCloseReq, err := client.SignMessage(context.Background(), &amp;lnrpc.SignMessageRequest{<br>        Msg: closeRequest.SignedClosures[0].TxidBytes,<br>    })<br>    if err != nil {<br>        log.Fatalf(&quot;could not sign close request: %v&quot;, err)<br>    }<br>// Send the signed close request to the remote party.<br>    _, err = closeChannelStream.Send(&amp;lnrpc.CloseStatusUpdate{<br>        Update: &amp;lnrpc.CloseStatusUpdate_SignedClosingTx{<br>            SignedClosingTx: signedCloseReq.Signature,<br>        },<br>    })<br>    if err != nil {<br>        log.Fatalf(&quot;could not send signed close request: %v&quot;, err)<br>    }<br>    // Receive the fully signed close request from the remote party.<br>    closeRequest, err = closeChannelStream.Recv()<br>    if err != nil {<br>        log.Fatalf(&quot;could not receive fully signed close request: %v&quot;, err)<br>    }</pre><p>Below is the code (using the LND go implementation) to broadcast the close channel transaction to the Bitcoin network.</p><pre>// Broadcast the close transaction to the Bitcoin network.<br>    _, err = client.SendRawTransaction(context.Background(), &amp;lnrpc.SendRawTransactionRequest{<br>        TxHex: closeRequest.SignedClosures[0].TxidBytes,<br>    })<br>    if err != nil {<br>        log.Fatalf(&quot;could not broadcast close transaction: %v&quot;, err)<br>    }</pre><h4>4. Wait ⏰ for Confirmations on the Network</h4><p>Wait for the TargetConf stated during the initiation, these are the number of blocks that need to be added after the close transaction is committed to the Bitcoin network (in this example, Alice is waiting for 6 blocks).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwwWPmyopVoZHngrrRJFcw.png" /></figure><p>Below is the code (using the LND go implementation) to wait for the confirmations.</p><pre>// Wait for the channel to be closed and remove it from local storage.<br>    waitCloseReq := &amp;lnrpc.WaitForFinishedRequest{<br>        ChannelPoint: channelPoint,<br>    }<br>    _, err = client.WaitForChannelClosed(context.Background(), waitCloseReq)<br>    if err != nil {<br>        log.Fatalf(&quot;could not wait for channel to close: %v&quot;, err)<br>    }</pre><h4>5. Remove the Channel</h4><p>Most implementations handle the channel removal on the network automatically. But even though the channel is removed from the network, the channel&#39;s information will still exist in the network.</p><p>You may want to remove a channel from your Lightening node&#39;s storage to free up disk space, improve your node&#39;s performance, or reduce your configuration&#39;s complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqGg23BU21MjiRP61TPA0A.png" /></figure><p>Below is the code (using the LND go implementation) to remove the channel from local storage.</p><pre>_, err = client.RemoveChannel(context.Background(), &amp;lnrpc.RemoveChannelRequest{<br>        ChannelPoint: channelPoint,<br>    })<br>    if err != nil {<br>        log.Fatalf(&quot;could not remove channel: %v&quot;, err)<br>    }</pre><blockquote><strong>Warning — Loss of Information:</strong></blockquote><blockquote>Removing the channel state from your Lightning Network node will permanently delete all information associated with the closed channel, including the transaction history and any funds remaining in the channel.</blockquote><blockquote>This is why it’s important to make sure that the channel has been fully closed and settled on the Bitcoin network before removing the channel state from your node.</blockquote><blockquote><strong>Warning — Wait for Pending HTLC’s</strong></blockquote><blockquote>Wait for any pending HTLCs to expire: If there were any pending HTLCs (hash time-locked contracts) on the channel at closing, you should wait for them to expire before removing the channel state from your node.</blockquote><blockquote>This is because HTLCs have a time-out period during which the counterparty can redeem them. Once this time-out period has expired, the HTLCs will be resolved on-chain, and the remaining funds will be returned to the appropriate parties. Once all pending HTLCs have expired and been resolved, you can safely remove the channel state from your node.</blockquote><h4>Example Code to do a Collaborative Close</h4><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;fmt&quot;<br>    &quot;github.com/lightningnetwork/lnd/lnrpc&quot;<br>    &quot;google.golang.org/grpc&quot;<br>    &quot;log&quot;<br>)<br>func main() {<br>    // Set up a connection to the lnd instance running locally.<br>    conn, err := grpc.Dial(&quot;localhost:10009&quot;, grpc.WithInsecure())<br>    if err != nil {<br>        log.Fatalf(&quot;could not connect to lnd: %v&quot;, err)<br>    }<br>    defer conn.Close()<br>    client := lnrpc.NewLightningClient(conn)<br>    // Set the channel point you want to close.<br>    channelPoint := &amp;lnrpc.ChannelPoint{<br>        FundingTxidStr: &quot;funding_transaction_id&quot;,<br>        OutputIndex:    0,<br>    }<br>    // Start a cooperative close for the channel.<br>    closeChannelReq := &amp;lnrpc.CloseChannelRequest{<br>        ChannelPoint:  channelPoint,<br>        TargetConf:    6,<br>        SatPerByte:    1,<br>        DeliveryAddr:  &quot;&quot;, // Optional, if not provided the closing funds go to the channel initiator.<br>        Force:         false,<br>    }<br>    closeReq := &amp;lnrpc.CloseChannelRequest{<br>      ChannelPoint: channelPoint,<br>      TargetConf:   0, // Wait for the next block.<br>      SatPerByte:   1, // Set the fee rate.<br>      Force:        false, // Initiate a cooperative closure.<br>      DeliveryAddress: &quot;your_bitcoin_address&quot;, // Optional.<br>    }<br>    closeChannelStream, err := client.CloseChannel(context.Background(), closeChannelReq)<br>    if err != nil {<br>        log.Fatalf(&quot;could not initiate close: %v&quot;, err)<br>    }<br>    // Receive close request from remote party.<br>    closeRequest, err := closeChannelStream.Recv()<br>    if err != nil {<br>        log.Fatalf(&quot;could not receive close request: %v&quot;, err)<br>    }<br>    // Sign the close request.<br>    signedCloseReq, err := client.SignMessage(context.Background(), &amp;lnrpc.SignMessageRequest{<br>        Msg: closeRequest.SignedClosures[0].TxidBytes,<br>    })<br>    if err != nil {<br>        log.Fatalf(&quot;could not sign close request: %v&quot;, err)<br>    }<br>    // Send the signed close request to the remote party.<br>    _, err = closeChannelStream.Send(&amp;lnrpc.CloseStatusUpdate{<br>        Update: &amp;lnrpc.CloseStatusUpdate_SignedClosingTx{<br>            SignedClosingTx: signedCloseReq.Signature,<br>        },<br>    })<br>    if err != nil {<br>        log.Fatalf(&quot;could not send signed close request: %v&quot;, err)<br>    }<br>    // Receive the fully signed close request from the remote party.<br>    closeRequest, err = closeChannelStream.Recv()<br>    if err != nil {<br>        log.Fatalf(&quot;could not receive fully signed close request: %v&quot;, err)<br>    }<br>    // Broadcast the close transaction to the Bitcoin network.<br>    _, err = client.SendRawTransaction(context.Background(), &amp;lnrpc.SendRawTransactionRequest{<br>        TxHex: closeRequest.SignedClosures[0].TxidBytes,<br>    })<br>    if err != nil {<br>        log.Fatalf(&quot;could not broadcast close transaction: %v&quot;, err)<br>    }<br>    // Wait for the channel to be closed and remove it from local storage.<br>    waitCloseReq := &amp;lnrpc.WaitForFinishedRequest{<br>        ChannelPoint: channelPoint,<br>    }<br>    _, err = client.WaitForChannelClosed(context.Background(), waitCloseReq)<br>    if err != nil {<br>        log.Fatalf(&quot;could not wait for channel to close: %v&quot;, err)<br>    }<br>    _, err = client.RemoveChannel(context.Background(), &amp;lnrpc.RemoveChannelRequest{<br>        ChannelPoint: channelPoint,<br>    })<br>    if err != nil {<br>        log.Fatalf(&quot;could not remove channel: %v&quot;, err)<br>    }<br>    fmt.Println(&quot;Channel closed.&quot;)<br>}</pre><h4>Example of a Collaborative Close Transaction</h4><p>Transaction a3b23982331300ef8d23bd90b64e939758835515642a65ba64234bf2cae2ac7a is an example of a collaborative closure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K23VKCkLaEte0PQxUQ_vtQ.png" /><figcaption><a href="https://mempool.space/tx/a3b23982331300ef8d23bd90b64e939758835515642a65ba64234bf2cae2ac7a">https://mempool.space/tx/a3b23982331300ef8d23bd90b64e939758835515642a65ba64234bf2cae2ac7a</a></figcaption></figure><h3>Force Close</h3><p>A force close happens when one of the parties is offline, so the other party unilaterally forces the channel to close. There are fewer steps in a force close because there aren&#39;t exchanges between parties since it&#39;s a one-person show.</p><h4>1. Initiate, Sign, and Broadcast the Force Close</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*39mPisIq0dAOUSWZdw2GRw.png" /></figure><p>Below is the code (using the LND go implementation) to create the force close request. Notice that now the Force the field is marked true.</p><pre>// Create the force close channel request<br>    request := &amp;lnrpc.CloseChannelRequest{<br>        ChannelPoint:       channelPoint,        <br>        Force:              true,<br>        TargetConf:         6,<br>        SatPerByte:         10,<br>        DeliveryAddress:    &quot;&quot;,<br>        ForceTargetChanId:  0,<br>        Anchors:            false,<br>    }</pre><p>Below is the code (using the LND go implementation) to initiate the force close request. We are using the client to broadcast the close request here.</p><pre>// Initiate the force close request<br>    response, err := client.CloseChannel(context.Background(), request)<br>    if err != nil {<br>        log.Fatalf(&quot;could not initiate force close: %v&quot;, err)<br>    }<br>    log.Printf(&quot;force close initiated: %v&quot;, response)</pre><h4>2. Wait ⏰ for the Force Close to Confirm</h4><p>With force close, the party initiating the close has a waiting period (time lock), giving the counterparty enough time to respond.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCy4BVEkfH5EaIk2RIBTSA.png" /></figure><blockquote>Local and Remote Force Close</blockquote><blockquote>There are two types of forced closures, remote and local. It depends on who is initiating the forced closure. If you <strong>are initiating the forced closure, you are dealing with a local </strong>force close, and if you<strong> aren’t initiating the forced closure, then you are dealing with a remote </strong>force close.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6PFQBxwIHk7_GbKZd5lRQ.png" /></figure><p>This time lock prevents the funds from being spent for a certain period. This time lock is known as the CSV (<a href="https://academy.bit2me.com/en/que-es-checksequenceverify-csv/">Check Sequence Verify</a>) value, and it ensures that both parties can dispute the force close and prevent fraud.</p><p>Below is the code (using the LND go implementation) to enforce the time-lock/CSV.</p><pre>// Wait for the force close to be confirmed<br>    time.Sleep(10 * time.Minute)</pre><p>In the Lightning Network, security is enforced, and honesty is incentivized using delays. The Lightening Network has two types of delays time-lock and revocation delays. If you want to dive deeper into those concepts, check out the article below:</p><p><a href="https://mabeloza.medium.com/lightning-network-delays-1208a463f9b6">Lightning Network &amp; Delays</a></p><h4>3. Remove the Channel</h4><p>After the time-lock expires, the channel closure is complete, and now we can remove the channel from local storage.</p><p>Below is the code (using the LND go implementation) to remove the channel from local storage.</p><pre>// Remove the closed channel from the node&#39;s local storage<br>    _, err = client.RemoveChannel(context.Background(), &amp;lnrpc.RemoveChannelRequest{<br>        ChannelPoint: channelPoint,<br>    })<br>    if err != nil {<br>        log.Fatalf(&quot;could not remove channel: %v&quot;, err)<br>    }</pre><h4>Example Code to do a Force Close</h4><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;log&quot;<br>    &quot;time&quot;<br>    &quot;github.com/lightningnetwork/lnd/lnrpc&quot;<br>    &quot;google.golang.org/grpc&quot;<br>)<br>func main() {<br>    // Create a connection to the LND instance<br>    conn, err := grpc.Dial(&quot;localhost:10009&quot;, grpc.WithInsecure())<br>    if err != nil {<br>        log.Fatalf(&quot;could not connect to LND: %v&quot;, err)<br>    }<br>    defer conn.Close()<br>    // Create a new LND client<br>    client := lnrpc.NewLightningClient(conn)<br>    // Define the channel point to be closed<br>    channelPoint := &amp;lnrpc.ChannelPoint{<br>        FundingTxid: &amp;lnrpc.ChannelPoint_FundingTxidStr{<br>            FundingTxidStr: &quot;FUNDING_TXID&quot;,<br>        },<br>        OutputIndex: OUTPUT_INDEX,<br>    }<br>    // Create the force close channel request<br>    request := &amp;lnrpc.CloseChannelRequest{<br>        ChannelPoint:       channelPoint,<br>        Force:              true,<br>        TargetConf:         6,<br>        SatPerByte:         10,<br>        DeliveryAddress:    &quot;&quot;,<br>        ForceTargetChanId:  0,<br>        Anchors:            false,<br>    }<br>    // Initiate the force close request<br>    response, err := client.CloseChannel(context.Background(), request)<br>    if err != nil {<br>        log.Fatalf(&quot;could not initiate force close: %v&quot;, err)<br>    }<br>    log.Printf(&quot;force close initiated: %v&quot;, response)<br>    // Wait for the force close to be confirmed<br>    time.Sleep(10 * time.Minute)<br>    // Remove the closed channel from the node&#39;s local storage<br>    _, err = client.RemoveChannel(context.Background(), &amp;lnrpc.RemoveChannelRequest{<br>        ChannelPoint: channelPoint,<br>    })<br>    if err != nil {<br>        log.Fatalf(&quot;could not remove channel: %v&quot;, err)<br>    }<br>    log.Println(&quot;force close complete&quot;)<br>}</pre><h4>Example Forced Close Transaction</h4><p>Transaction f9b48496a3b16693460a447a224b102d4fb3d38bb9473dc865fb5ce6e71761bd is an example of forced closure. There are key features</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0Mv0Ry85NANkQuMsM5WSw.png" /><figcaption><a href="https://mempool.space/tx/f9b48496a3b16693460a447a224b102d4fb3d38bb9473dc865fb5ce6e71761bd">https://mempool.space/tx/f9b48496a3b16693460a447a224b102d4fb3d38bb9473dc865fb5ce6e71761bd</a></figcaption></figure><p>If you dig a little deeper and look at the lightning channel details, you can see that Bitcoin Revolution was the one that opened and closed the channel (<a href="https://mempool.space/lightning/channel/805523109340971008">704410x953x0</a>) unilaterally. Also, notice that the fees are considerably higher than a collaborative close. This transaction has a $0.67 fee, while the collaborative close (mentioned earlier) has a $0.06 fee. Force closes have higher fees because they use a time-critical pre-signed transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qln_txFX8L6StLvkzeHZuA.png" /><figcaption><a href="https://mempool.space/lightning/channel/774506985784147968">https://mempool.space/lightning/channel/774506985784147968</a></figcaption></figure><h3>Disputed Close</h3><p>Previously in the force close, Alice had to wait (time-lock/CSV) to give the other party a chance to come back on and dispute. In this scenario, the other party returned online within the wait time (time-lock/CSV) and disputed the force close.</p><p>In this example, Bob noticed that Alice made a force close request to the network. Luckily, Bob has the wait time (time-lock/CSV) ⏰ to dispute her close.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRgip58HyjUrxCu9AHoT7g.png" /></figure><p><strong><em>How would Bob dispute Alice&#39;s force close?</em></strong></p><p>Bob needs to publish the most recent state of the channel before the time lock expires. If Bob publishes the most recent state within the time-lock wait time, he can publish a <strong>justice transaction 🏛 👩‍ ⚖</strong>. The justice transaction <strong>🏛 👩‍ ⚖ </strong>will allow Bob to take everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*A0sVwzZRYNE40a99ReFMCQ.png" /></figure><p><strong><em>What are justice transactions?</em></strong></p><p>Justice transactions <strong>🏛 👩‍ ⚖ </strong>use game theory to secure the lightning network, and if you&#39;re dishonest, you can lose it all, so the incentive of being dishonest must outweigh the risk of losing all your funds. <a href="https://medium.com/u/94b52ae5502e">BitMEX</a> published research on the effectiveness of justice transactions.</p><p><a href="https://bitcoinmagazine.com/technical/bitmex-research-confirms-lightning-justice-works">BitMEX Research Confirms Lightning &#39;Justice&#39; Works</a></p><blockquote><strong>When does 🏛 👩‍ ⚖ justice transactions happen?</strong></blockquote><blockquote>After the breach close transaction is confirmed on the Bitcoin network, the channel will enter into the “Pending Force Close” state.</blockquote><blockquote>At this point, the justice transaction will be broadcasted by the LND node to claim the channel’s funds and penalize the counterparty.</blockquote><h4>Example Code of a Dispute Close Transaction</h4><p>The code below walks through the steps Bob needs to take using the LND implementation in Go.</p><pre>import (<br> &quot;context&quot;<br> &quot;log&quot;<br> &quot;github.com/lightningnetwork/lnd/lnrpc&quot;<br> &quot;google.golang.org/grpc&quot;<br>)<br>func main() {<br> // Create a connection to the LND instance<br> conn, err := grpc.Dial(&quot;localhost:10009&quot;, grpc.WithInsecure())<br> if err != nil {<br>  log.Fatalf(&quot;could not connect to LND: %v&quot;, err)<br> }<br> defer conn.Close()<br> // Create a new LND client<br> client := lnrpc.NewLightningClient(conn)<br> // Define the channel point to be disputed<br> channelPoint := &amp;lnrpc.ChannelPoint{<br>  FundingTxid: &amp;lnrpc.ChannelPoint_FundingTxidStr{<br>   FundingTxidStr: &quot;FUNDING_TXID&quot;,<br>  },<br>  OutputIndex: OUTPUT_INDEX,<br> }<br> // Create the breach close transaction request<br> request := &amp;lnrpc.BreachCloseChannelRequest{<br>  ChannelPoint: channelPoint,<br>  SweepAddress: &quot;YOUR_SWEEP_ADDRESS&quot;,<br> }<br> // Generate the breach close transaction<br> response, err := client.BreachCloseChannel(context.Background(), request)<br> if err != nil {<br>  log.Fatalf(&quot;could not generate breach close transaction: %v&quot;, err)<br> }<br> log.Printf(&quot;breach close transaction generated: %v&quot;, response)<br> // Broadcast the breach close transaction to the network<br> _, err = client.PublishTransaction(context.Background(), &amp;lnrpc.PublishTransactionRequest{<br>  Transaction: response.SignedTransaction,<br> })<br> if err != nil {<br>  log.Fatalf(&quot;could not publish transaction: %v&quot;, err)<br> }<br> log.Println(&quot;breach close transaction published to network&quot;)<br> // Wait for the breach close transaction to be confirmed<br> // TODO: implement waiting code<br> log.Println(&quot;dispute complete&quot;)<br>}</pre><h4>🗼Watch Tower</h4><p>In the scenario described above, Bob had to check the status of his payment channel continuously, or it might have been luck that he caught Alice the one time he checked his payment channel.</p><p>In most scenarios, it&#39;s advisable to use a watch tower to automate the monitoring of your payment channel and, in the case of fraudulence, publish the most recent state and a justice transaction. The watchtower does everything Bob was doing in the previous scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iastKIwV9-Y3Q6xQzPpaHA.png" /></figure><blockquote>🗼<strong>What is a Watchtower?</strong></blockquote><blockquote>Watchtower is a lightning node that watches the chain on behalf of a 3rd party that can send justice transactions when it detects a breach.</blockquote><blockquote>🗼<strong>How the Watchtower knows it should dispute the close?</strong></blockquote><blockquote>Every time the channel’s state is updated (Bob and Alice transact on the channel), Alice and Bob contact the watchtower with a status update.</blockquote><blockquote>The status update has a fixed-size encrypted blobs and is only able to decrypt and publish the justice transaction after the offending party has broadcast a revoked commitment state.</blockquote><blockquote><strong>🗼Could the Watchtower eavesdrop?</strong></blockquote><blockquote>Client communications with a watchtower are encrypted and authenticated using ephemeral (temporary) keypairs, mitigating the amount of tracking the watchtower can perform on its clients using long-term identifiers.</blockquote><p>Below is code using LND implementation in Go to implement a watchtower.</p><pre>import (<br> &quot;github.com/lightningnetwork/lnd/watchtower/client&quot;<br>)<br>// create a client config with the necessary parameters<br>config := client.Config{<br>    DialAddr:        &quot;localhost:9911&quot;,<br>    PubKey:          pubkey,<br>    PrivKey:         privkey,<br>    ChainHash:       chainhash,<br>    DB:              db,<br>    SessionBackup:   sessionBackup,<br>    SweepFeeRate:    sweepFeeRate,<br>    RewardAddress:   addr,<br>    Resolver:        resolver,<br>    Net:             net,<br>    EpochRegistrar:  epochRegistrar,<br>    DebugLogger:     logger,<br>    ErrorLogger:     logger,<br>}<br>// create a new watchtower client<br>watchtowerClient, err := client.New(config)<br>if err != nil {<br>    log.Fatalf(&quot;unable to create watchtower client: %v&quot;, err)<br>}<br>// create a new breach observer to watch for channel breaches<br>observer := watchtower.NewBreachObserver(watchtower.BreachObserverConfig{<br>    Backend:   backend,<br>    ChainHash: chainhash,<br>})<br>// start the observer and begin watching for breaches<br>if err := observer.Start(); err != nil {<br>    log.Fatalf(&quot;unable to start observer: %v&quot;, err)<br>}</pre><h3>In a Trusting World, Would We Only Use Collaborative Closes?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tdTlLUDT55rR2F9q" /><figcaption>Photo by <a href="https://unsplash.com/@miinyuii?utm_source=medium&amp;utm_medium=referral">Duy Pham</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Most likely, you will deal with forced closes. Collaborative closes require both nodes to always be up and running, and synchronization between the two nodes after transactions are complete.</p><p><strong>Constant Node Uptime is Unrealistic</strong></p><p>With node issues, network, and power outages, node uptime is a major issue. This isn&#39;t just a Bitcoin or Blockchain node issue but a major issue in tech; even giants like Amazon and Google cloud providers face these issues.</p><p><strong>Channel Nodes are Not Always in Communication</strong></p><p>There&#39;s a chance that one of the nodes in a payment channel goes MIA (missing in action). They may want their funds but forgot to close the channel or abandoned their node altogether. Think about all those unclaimed funds in your Venmo account. I know I am not the only one letting them sit there. Even though the other party may be happy to let their funds sit in the channel, the other party may have a greater urgency to close.</p><h3>📚Hooked? Dive into the Rabbit Hole</h3><p><strong>BOLT Rules on Closing Transactions</strong></p><p><a href="https://github.com/lightning/bolts/blob/d975de1ba5d3e8aca586154ae0cae8f1b3181495/02-peer-protocol.md#channel-close">bolts/02-peer-protocol.md at d975de1ba5d3e8aca586154ae0cae8f1b3181495 · lightning/bolts</a></p><p><strong>Bitcoin Lightning Transactions &amp; Protocol Deep Dive</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fto8XItlplac%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dto8XItlplac&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fto8XItlplac%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f19ed747f8a4a2245932b85e63918df3/href">https://medium.com/media/f19ed747f8a4a2245932b85e63918df3/href</a></iframe><p><strong>Ligthning Engineering</strong></p><p><a href="https://docs.lightning.engineering/the-lightning-network/payment-channels/lifecycle-of-a-payment-channel">Lifecycle of a Payment Channel</a></p><p><strong>L.N. Guide</strong></p><p><a href="https://bitcoiner.guide/lightning/">LN.Guide</a></p><p><a href="https://medium.com/u/93b8b62c15d8"><strong>Raphael Osaze Eyerin</strong></a><strong> Lightening Payment Channel</strong></p><p><a href="https://raphtyosaze.medium.com/lightning-payment-channels-138f72e90faa">Lightning Payment Channels</a></p><p><strong>The Bitcoin Manual</strong></p><p><a href="https://thebitcoinmanual.com/articles/close-lightning-channel/">How To Close A Lightning Channel? - The Bitcoin Manual</a></p><p><strong>BOLT to identify Justice Transactions</strong></p><p><a href="https://github.com/alexbosworth/bolt03/blob/master/breaches/is_remedy_witness.js">bolt03/is_remedy_witness.js at master · alexbosworth/bolt03</a></p><p><strong>How to Set up a Watchtower for an Umbrel Bitcoin Lightening Node</strong></p><p><a href="https://www.nasdaq.com/articles/how-to-set-up-a-watchtower-for-an-umbrel-bitcoin-lightning-node-2021-10-30">How To Set Up A Watchtower For An Umbrel Bitcoin Lightning Node</a></p><p><strong>LND Watchtower</strong></p><p><a href="https://github.com/lightningnetwork/lnd/blob/master/docs/watchtower.md">lnd/watchtower.md at master · lightningnetwork/lnd</a></p><p><strong>Lightening Network Watchtower</strong></p><p><a href="https://lightningnetwork.plus/watchtower">Lightning Network Watchtower * LightningNetwork+</a></p><p><strong>Decred Documentation on Watchtowers</strong></p><p><a href="https://docs.decred.org/lightning-network/watchtowers/">Watchtowers - Decred Documentation</a></p><blockquote><em>New to trading? Try </em><a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a"><em>crypto trading bots</em></a><em> or </em><a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c"><em>copy trading</em></a><em> on </em><a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769"><em>best crypto exchanges</em></a></blockquote><blockquote>Join Coinmonks<a href="https://t.me/coincodecap"> Telegram Channel</a> and<a href="https://www.youtube.com/c/coinmonks/videos"> Youtube Channel</a> get daily <a href="http://coincodecap.com/">Crypto News</a></blockquote><h3>Also, Read</h3><ul><li><a href="https://medium.com/coinmonks/free-crypto-signals-48b25e61a8da">Free Crypto Signals</a> | <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">Crypto Trading Bots</a></li><li>An ultimate guide to <a href="https://medium.com/coinmonks/leveraged-token-3f5257808b22">Leveraged Token</a></li><li><a href="https://medium.com/coinmonks/top-17-folding-electric-bikes-5e296f0918cb">16 Best Folding Electric Bikes</a></li><li><a href="https://medium.com/coinmonks/the-28-best-electric-bikes-review-and-buying-guide-in-2023-7bb3146cb403">28 Best Electric Bikes Review</a></li><li>Top 3 <a href="https://medium.com/coinmonks/top-3-binance-futures-trading-bots-e6031f84b3f9">Binance Futures Trading Bots</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a11bbe4ed486" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dipping into a Liquidity Pool]]></title>
            <link>https://medium.com/coinmonks/dipping-into-a-liquidity-pool-905a615f0758?source=rss-bdd0b2ab4dde------2</link>
            <guid isPermaLink="false">https://medium.com/p/905a615f0758</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[liquidity-pool]]></category>
            <category><![CDATA[decentralized-exchange]]></category>
            <category><![CDATA[dex]]></category>
            <category><![CDATA[amm]]></category>
            <dc:creator><![CDATA[Mabel Oza]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 15:01:51 GMT</pubDate>
            <atom:updated>2023-01-06T06:29:06.789Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Let’s dip our toes into the basics of liquidity pools and AMM (automated market making).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*7FVOycLLhsm9geUFwIq2Og.png" /></figure><h3>Topics</h3><p><a href="#39c7"><strong>🏊What are Liquidity Pools?</strong></a></p><p><a href="#9cda"><strong>💰Where are Liquidity Pools Used?</strong></a></p><p><a href="#ea11"><strong>🦄 Creating a Liquidity Pool</strong></a></p><p><a href="#57aa"><strong>🙅🏽‍♂️ Risks with Liquidity Pools — Impermanent Loss</strong></a></p><p><a href="#48d1"><strong>📈 Pricing with Liquidity Pools — Price Feed Oracles</strong></a></p><p><a href="#db63"><strong>📚Hooked More Resources on Liquidity Pools</strong></a></p><h3>🏊 What are Liquidity Pools?</h3><p>Liquidity pools are a collection of assets locked into a smart contract. This collection of assets provides decentralized financial (DeFi) products capital to execute transactions like derivatives, lending, and trading efficiently. In other words, they are the goods needed on the other side to make the transaction happen.</p><p>DeFi products want to continuously provide these products, so they need to preserve their liquidity pool over time. Liquidity pools maintain long-term liquidity using an algorithm that utilizes supply and demand principles. It will adjust the asset price depending on the supply of the token.</p><p>Liquidity pool instances are powered by a smart contract, AMM (automated market makers). An AMM is a smart contract with algorithms (constant product) that adjust the price to maintain the supply of a token.</p><h4><strong>What’s the difference between liquidity pools, AMM, and the constant product algorithm?</strong></h4><p>It can be confusing how liquidity pools and AMM are often used interchangeably, and AMM and constant product algorithms are used interchangeably.</p><p><strong>Liquidity pools</strong> are a concept of locking tokens into a smart contract to provide liquidity for a pair or set of assets.</p><p><strong>AMM</strong> is the smart contract that’s created for liquidity pools. Inside the AMM smart contract, there is an algorithm or set of algorithms used to set the price of the tokens.</p><p><strong>Constant Product Algorithms</strong> are the most popular algorithm used in AMM smart contracts.</p><p>In one of the most popular liquidity providers, Uniswap, the algorithm is called Constant Product. The algorithm(s) vary depending on the protocol, and the constant product mostly pertains to Uniswap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*Bi58iPzfhrYvLB47-ZpoOQ.png" /></figure><h4>Who can create a Liquidity Pool?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*woxdluC7nGY7sEKckxFe0w.png" /></figure><p>Anyone can become a liquidity provider (LP) for a pool by depositing an equivalent value of each underlying token in return for pool tokens. These tokens track pro-rata LP (liquidity pool) shares of the total reserves and can be redeemed for the underlying assets at any time.</p><h3>💰Where are Liquidity Pools Used?</h3><p>Liquidity pools are used across many products in the DeFi space, like derivatives, lending, and decentralized exchanges.</p><h4>Derivatives</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K232YFWANUBFP6qV.jpg" /><figcaption><a href="https://www.investopedia.com/terms/d/derivative.asp">https://www.investopedia.com/terms/d/derivative.asp</a></figcaption></figure><p>To cater to common derivative instruments like options, futures, and perpetual futures, crypto derivative platforms require liquidity locked in for a future date.</p><p>If the platform doesn’t have the promised funds on the set future date, it will default on its contract. Platforms that offer perpetual contracts must be consistently liquid because the future date is unknown.</p><p>With derivatives, there is a concept called liquidation event. With derivatives, any losses from the trade need to be funded from the margin. If the price moves against the trader’s open position, unrealized losses erode the margin provided by the trader. The trader&#39;s position must be liquidated when these losses become equal to the margin.</p><p>Long story short, derivative platforms need to be prepared to liquidate their customers at a moment’s notice.</p><blockquote>New to trading? Try <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">crypto trading bots</a> or <a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">copy trading</a> on <a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">best crypto exchanges</a></blockquote><p>More on Crypto Derivatives can be found here:</p><p><a href="https://www.machow.ski/posts/a-beginners-guide-to-crypto-derivatives/">A Beginners Guide to Crypto Derivatives</a></p><h4>Lending</h4><p>In lending protocols like Compound, that’s not peer-to-peer lending; funds are borrowed against liquidity pools. Lenders who lend their funds to the lending protocol create a <strong>single-asset liquidity pool</strong>.</p><p>In this single-asset liquidity pool, the funds deposited for lending becomes a fungible resource, and ERC20 tokens (“cTokens with Compound”) that represent the deposited funds are issued to the depositor. Depositors can redeem these cTokens at any time for their underlying tokens. As interest accrues over time, the depositor can redeem cTokens at an exchange rate relative to the supplied assets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*euochJLzmHEloQ5o.jpg" /><figcaption>Source: <a href="https://coinsutra.com/liquidity-pools-guide/">https://coinsutra.com/liquidity-pools-guide/</a></figcaption></figure><h4>Decentralized Exchanges</h4><p>In decentralized exchange protocols like Uniswap, that’s not peer-to-peer trading; funds are traded against liquidity pools. When a liquidity provider creates a liquidity pool with a pair of tokens, they create a <strong>dual asset liquidity pool</strong>.</p><p>A dual asset liquidity pool maintains a 50/50 ratio of the pair of tokens. Traders constantly need a way to liquidate their assets, and liquidity pools in DEXs ensure the asset will remain liquid by setting the price using AMM (automated market-making algorithms), which influences the supply.</p><p>This post will focus more on liquidity pools created for DEXs like Uniswap, and we will dive into details on AMM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iw78tqxlPC15ozdA.jpg" /><figcaption>Source: <a href="https://coinsutra.com/liquidity-pools-guide/">https://coinsutra.com/liquidity-pools-guide/</a></figcaption></figure><blockquote><strong>Note</strong>: There are liquidity pools for decentralized exchanges that can support liquidity pools of a maximum of 8 tokens like Balancer</blockquote><h3>🦄 Creating a Liquidity Pool</h3><p>To understand how Liquidity Pools are created, we will use the 50:50 dual liquidity pool often used by Uniswap. <strong>In 50:50 dual liquidity pools, each asset’s total value is equivalent to the other.</strong></p><p>Liquidity pools are like mini stores. Let’s say we have a store that doesn’t accept fiat cash; instead, you must buy apples for grapes and vice versa.</p><p>This store has 2 Apples and 8 Grapes, so we’re contributing 10 fruits. Each apple is equivalent to 4 grapes, and each grape equals 1/4th an apple.</p><p>Notice that each asset’s total value should be equivalent to each other, the 2 apples are equal to 8 grapes, and 8 grapes are equivalent to 2 apples. This is a key feature in 50:50 dual pools.</p><p>Below is an illustration of our liquidity pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BcjmWPLJpSVNGlAyFzbMyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bzLpEQukq0Cl04E52kg2Ww.png" /></figure><p>To create this liquidity pool, we need to create a smart contract and deploy that smart contract to a blockchain network. To create and deploy the liquidity pool contract, we use platforms like Uniswap or Balancer, which also act as DEXs (decentralized exchanges). These platforms require us to connect our wallets and fill out a form about our liquidity pool. Once that’s completed, the platform generates the smart contract and deploys it.</p><p>The article and video below break down how to create a liquidity pool on a platform like Uniswap:</p><p><a href="https://mabeloza.medium.com/deep-end-of-liquidity-pool-in-the-dex-space-f0576618a0ee">Deep End of Liquidity Pool in the DEX Space?</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIbVPuUeJ8LM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIbVPuUeJ8LM&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4f97a696f0d22727c83ee02f6d83234/href">https://medium.com/media/e4f97a696f0d22727c83ee02f6d83234/href</a></iframe><h4>Managing Supply &amp; Demand in the Liquidity Pool</h4><p>The goal is to keep this “store” liquidity pool useful for as long as possible, so we need to constantly adjust the price to maintain a sufficient supply of assets. We accomplish this with the constant product formula.</p><h4>Constant Product Formula</h4><p>The constant product formula uses the supply of both assets (apples and grapes) to preserve the constant supply.</p><p>Uniswap, one of the most popular liquidity pools and decentralized exchanges, uses the formula constant products.</p><pre>x * y = k</pre><pre>x = token x quantity, y = token y quantity, k = constant quantity</pre><p>The formula states that trades must not change the product (k) of a pair&#39;s reserve balances (x and y). Because k must remain unchanged, it is often referred to as invariant or constant.</p><h4>Defining our k, Constant/Invariant</h4><p>Our liquidity pool has 2 apples and 8 grapes, so using the formula above, the constant product would be 16.</p><pre>2 Apples * 8 Grapes = 16 = k</pre><p><strong>16 </strong>is our golden number, our constant, and we must maintain this constant throughout.</p><h4>Change in Supply &amp; Price</h4><p>Chef Alice wants to start creating her wine and needs four grapes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xhkK12cxgTFzm-UWJcDX3A.png" /></figure><p><strong>How many apples would 4 grapes cost?</strong></p><p>With liquidity pools, the price is determined by the amount that will be purchased. If Alice wanted to buy 1 grape or 5 grapes, the price per grape would be different because the price adjusts with the supply &amp; demand of the asset. It’s like surge pricing or how stocks are priced, they adjust in price throughout the day depending on different factors.</p><p>Right now, we have 8 grapes in total, and Alice wants 4 grapes for her wine, which would leave us with 4 grapes after her purchase.</p><p><strong><em>What are the remaining Grapes After Purchasing 4 Grapes? 4 Grapes</em></strong></p><pre>8 Total Grapes - 4 Grapes Taken = 4 Grapes Remaining</pre><p>After this order, we would have just 4 grapes left, if Chef Alice takes any more grapes, we’re out of business! So we need to increase 📈 the price of grapes.</p><p>To increase the price of grapes, we go back to our constant defined earlier, which is <strong>16</strong>. Remember the 1st rule of liquidity pools, we must always maintain our constant, that’s defined by x * y = k. To maintain our constant, we must figure out how many apples to fulfill Chef Alice&#39;s order of 4 grapes.</p><p><strong><em>How Many Apples Does the Pool Need for 4 Grapes? 4 Apples</em></strong></p><pre>16 / 4 Grapes Remaining After Order = 4 Apples Required in Pool</pre><p>If we have 4 grapes and 4 apples, we would be able to maintain our constant of 16.</p><p><strong><em>Would the New Supply Maintain the Constant, K? Yes</em></strong></p><pre>4 Grapes * 4 Apples = 16, our constant is preserved</pre><p><strong><em>How many Apples would 4 Grapes Cost? 2 Apples</em></strong></p><pre>4 Apples required - 2 Apples in Pool = 2 Apples Required for 4 Grapes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6W21fjvBkqlcB3iFRgFq2w.png" /></figure><p>The calculation above can be simplified to the formula below</p><pre>x = apple supply, y = grape supply, px = amount of x purchased, py = amount of y purchased</pre><pre>If x is being purchased<br>((x * y)/(x - px)) - y</pre><pre>If y is being purchased<br>((x * y)/(y - py)) - x</pre><p>So for our pool with 2 apples and 8 grapes, where Chef Alice is purchasing 4 grapes, the cost of 4 grapes would be 2 apples.</p><pre>((2 apples * 8 grapes)/(8 grapes - 4 grapes purchased)) - 2 apples= 2 grapes</pre><p>The price of the grapes is significantly much higher because this formula is ratio oriented. If there are more apples and grapes in the pool, the price of each asset won’t fluctuate as much. Let’s say we had 200 apples and 200 grapes. If chef Alice took 2 apples, the price of the 2 apples would only be 2 grapes.</p><pre>200 Apples * 200 Grapes = 40000 is the constant</pre><pre>200 Apples - 2 Apples for Alice&#39;s recipe = 198 remaining Apples</pre><pre>40000 / 198 Apples remaining = 202 Grapes are needed in the pool</pre><pre>202 Grapes needed in the pool - 200 Grapes in the pool = 2 Grapes is the price for 2 Apples</pre><p>We can also use our formula to determine how many apples it would cost the 2 grapes.</p><pre>((200 * 200)/(200 - 2) - 200 = ~2 Grapes is the cost for the 2 Apples</pre><p><strong>Slippage</strong></p><p>The increased quantity also provides a lower <strong><em>slippage</em></strong><em>, a difference between the executed and expected prices.</em> If someone leaked Alice’s wine recipe and everyone in town wanted to start buying grapes to try out her recipe, the price of grapes would fluctuate depending on how large the quantity is. <strong>High liquidity prevents slippage,</strong> so if the quantity is significantly larger than the orders coming in, the price wouldn’t fluctuate as much and will be more predictable.</p><blockquote><strong>Note: </strong>This is a very simplified run through of the Constant Product formula, to get into the details checkout Uniswap’s whitepaper:</blockquote><blockquote><a href="https://uniswap.org/whitepaper-v3.pdf">https://uniswap.org/whitepaper-v3.pdf</a></blockquote><h3>🙅🏽‍♂️Risks of Liquidity Pools — Impermanent Loss</h3><p>Impermanent loss is the biggest risk of being a liquidity provider (LP). Impermanent loss can be monitored, but it’s only a loss until you withdraw funds from your liquidity pool.</p><blockquote><strong>Impermanent Loss </strong>is the loss LP faces for putting their tokens into a liquidity pool instead of holding them.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*Sw1SKCR0AInL6Ys4QcRNWA.png" /></figure><h4>When does Impermanent Loss Occur?</h4><p>Impermanent loss occurs when the two tokens you added to the liquidity pool stray further away from their counterpart’s original price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*V5u5ey-O8s09ES5YIPyqLQ.png" /></figure><p>Think of the two tokens in the pool as friends; they always need to succeed and fail together. One can’t succeed while the other stays stagnant, and one can’t succeed, and the other fails.</p><p>If the price of the tokens is drifting off from each other, you’ll have a greater chance of experiencing impermanent loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KzCuCqB_P0BIIb0ikmF2Gw.png" /></figure><p>If the price of the tokens moves in the same direction, you have less chance of experiencing impermanent loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74Nh2WxjFl7686eitQLYSw.png" /></figure><blockquote><strong>Note: </strong>Depending on the fees collected for each trade, the liquidity mining options, and the degree to which the assets price moves, the impermanent loss may or not be significant or even be considered a loss.</blockquote><h4>Impermanent Loss in our Grape &amp; Apple Liquidity Pool</h4><p><strong>Refresher on Current Liquidity Pool State</strong></p><p>Before getting into impermanent loss, let’s refresh ourselves on the current state of our liquidity pool. After Chef Alice purchased 4 grapes, we now have 4 apples and 4 grapes in our liquidity pool, and we are still maintaining our k (constant) 16.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YAyHmB1D_uw24YajIlRD1g.png" /></figure><p><strong>The “Others” Contributing to Our Liquidity Pool</strong></p><p>Other people want to contribute to our liquidity pool and add their grape and apple tokens. They add 4 more apple tokens and 4 more grape tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*1kYtut4bJCj_TPNMdpmBZg.png" /></figure><p>With the additional 4 apples and 4 grape contributions, the grape and apple liquidity pool have 8 apples and 8 grapes. Since your contributions account for 50% of the pool, you will get LP Tokens representing a 50% share.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wAwNsrc1yNu4NhyVLFOvVA.png" /></figure><p><strong>Current Price of Apples</strong></p><p>Using the calculation we used in the above section, “Managing Supply &amp; Demand in the Liquidity Pool,” we can use the same calculations to determine the price of one Apple in our pool.</p><pre>If x is being purchased<br>((x * y)/(x - px)) - y</pre><pre>If y is being purchased<br>((x * y)/(y - py)) - x</pre><pre>(8 apples * 8 grapes) / (8 apples - 1 apple purchase) - 8 grapes = 1.14 grapes is the cost</pre><p>Or we can break down the calculations accordingly:</p><pre>With the additional 4 grapes and 4 apples, what is our constant? 64<br>8 apples * 8 grapes = 64 = k</pre><pre>After one apple is purchased, how many apples remain in the pool? 7<br>8 Apples in Pool - 1 Apple = 7 Apples Remaining</pre><pre>How many grapes would we need in the pool after selling 1 apple? 9.14<br>64 / 7 remaining Apples= ~9.14 grapes needed in pool</pre><pre>Does 9.14 grapes and 7 apples help us maintain our constant? Yes<br>9.14 grapes needed * 7 remaining apples = ~64</pre><pre>How many grapes would an apple cost? 1.14 grapes<br>9.14 grapes needed in pool - 8 grapes in pool = 1.14 grapes</pre><p><strong>The Price Hike</strong></p><p>Chef Alice decides to share her famous apple pie recipe, so now everyone and their mother wants to make her famous apple pie. This brings up the demand for apples, causing the price of each apple to increase from 1.14 grapes to 3 grapes, bringing a price increase of 60%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbiH5Oh1580LvVSb07uW6Q.png" /></figure><p>While the price of apples increased by 60%, the price of grapes stayed the same, making this situation a likely case of impermanent loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*bsCHhVK-RN9LGz0yRZyxVw.png" /></figure><p><strong>The Arbitrage Moment</strong></p><p>While most exchanges increased the price of apples from 1.14 to 3 grapes, your liquidity pool still has apples at 1.14 grapes. Now your apples are a discount compared to the price at most exchanges. Chef Bob sees this <strong><em>arbitrage</em></strong> opportunity and buys 2 apples from your pool for 1.14 grapes each and sells it to another in exchange for 3 grapes each, making a profit of 1.86 grapes for each apple and a total profit of 3.72 grapes.</p><pre>Bob spent 2.28 grapes for 2 apples<br>2 apples * 1.14 grapes ea. in your pool = 2.28 grapes for 2 apples from your pool</pre><pre>Bob made 6 grapes for selling 2 apples<br>2 apples * 3 grapes ea. in other exchange = 6 grapes for 2 apples in other exchange</pre><pre>Bob made a profit of 3.72 grapes in arbitrage<br>6 grapes from exchange - 2.28 grapes from your pool = 3.72 grapes in profits</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vI4tjPlQA6jXPEYT9ZCgzQ.png" /></figure><p>People like chef Bob will continue to buy apples from your pool until the global price matches your liquidity pool price. If the price is the same or slightly less, it wouldn’t make sense with the trading fees to go through this effort of buying from one exchange and selling to another.</p><h4>Calculating Impermanent Loss</h4><p>The formula below will help you calculate the impermanent loss.</p><p>We determine the number of assets we will withdraw from the pool using the formula below. We will measure the value of x against y, if we were to measure ETH against the dollar, then ETH would be x, and y would be the dollar.</p><pre>Assets you will you withdraw, y is the asset you measure value with<br>√(k/r) * lp share = x<br>√(k*r) * lp share = y</pre><p>Since we’re using a 50:50 pool, the value of both assets should be equivalent. So can calculate the value of asset y and multiply it by 2.</p><pre>In a 50:50 pool the value of x and y should equal each other<br>x * r = y</pre><pre>LP Value -&gt; Total value of assets withdrawn<br>(√(k*r) * lp share) * 2 = lp value</pre><p>Impermanent loss is the difference between the liquidity pool value of assets and the value of assets if they were just held (hodl), often this value is calculated as a percentage of difference.</p><pre>Hodl Value -&gt; Total value of assets initally put in with today&#39;s new price<br>(x * r) + y = hodl value</pre><pre>Impermanent Loss<br>(lp value - hodl value / hodl value) * 100</pre><p>Knowing all of this, we can summarize the formula for impermanent loss as the formula below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bn3QusMaVMJlr0wP2WVvIQ.png" /></figure><p>Let’s apply this to our scenario; if you were F12 on your browser and run the javascript formula below in your console, you would get the impermanent loss calculation.</p><pre>Math.abs(((Math.sqrt(64 * 3) * .50 * 2) - (4 * 3 + 4))/(4 * 3 + 4) * 100)</pre><p>Below we’ll go through how we got each value and break down the calculation.</p><p><strong>How many grapes and apples are left after the arbitrage process?</strong></p><pre>Ratio of Apples to Grapes (1 APL = 3 GRP), Ratio is y price in x<br>r is 3 = 3/1</pre><pre>How many apples are remaining after arbitrage? 4.62 apples<br>x = √(64/3) = 4.618802153517006</pre><pre>How many grapes are remaining after arbitrage? 13.86 grapes<br>y = √(64 * 3) = 13.856406460551018</pre><p><strong>How much do you get when you withdraw 50% from the pool?</strong></p><pre>You get 2.31 apples and 6.93 grapes when you withdraw<br>4.62 apples in pool * 0.5 = 2.31 apples is your share</pre><pre>13.86 grapes in pool * 0.5 = 6.93 grapes in your share</pre><p>In your initial deposit, you put in 4 apples and 4 grapes and leave with 1.69 fewer apples and 2.93 more grapes. So if you were to measure everything in grapes, <strong>are you walking away with more grapes</strong>?</p><pre>Are we following the 50:50 balance? Yes<br>2.31 apples * 3 grapes = 6.93 grapes <br>6.93 grapes from the value of apples = 6.93 grapes</pre><pre>How many total grapes did you withdraw? 13.86 grapes<br>6.93 grapes from Apples + 6.93 grapes in your share = 13.86 grapes</pre><pre>What if you just held your assets, how many grapes would you have today? 16 grapes<br>(4 apples * 3 grapes) + 4 grapes = 16 grapes</pre><pre>What is the difference if you held vs liquidity pool? 2.14 grapes<br>16 grapes if you held - 13.86 grapes from liquidity pool = 2.14 grapes</pre><pre>What is the impermanent loss? 13.38%<br>(2.14 grapes difference / 16 grapes if held) * 100 = 13.38%</pre><p>Using the formula, you can start to see a pattern that can be illustrated in the graph below. The graph shows that the loss increases steeply as the price change increases. If the price change is 2x, then there is a ~6% loss, 3x, then there is a ~12.5%; and if the price change is 5x, then there is a ~25% loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e1FArf0MreCKH-Ua" /></figure><p>Check out Eric <a href="https://medium.com/u/8d8d45d010e">Eric Falkenstein</a> substack on calculating impermanent loss for a deeper dive into the formula.</p><p><a href="https://efalken.substack.com/p/a-simpler-formula-for-impermanent">A Simpler Formula for Impermanent Loss</a></p><p>There are a lot of calculations here, but luckily there is a tool to help you manage your impermanent loss, APY.vision (<a href="https://app.apy.vision/">https://app.apy.vision/</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGqWzk_niuhdVH3tHsOfIQ.png" /><figcaption>Screenshot of my ORW (Orwell) and wETH LP Pool Analytics from APY.vision</figcaption></figure><blockquote>Note: This is an overly simplified example that excludes several market conditions below are different factors that affect impermanent loss. All these calculations exclude trading fees earned from each trade.</blockquote><p>More on impermanent loss:</p><ul><li><a href="https://chainbulletin.com/impermanent-loss-explained-with-examples-math">Impermanent Loss Explained With Examples &amp; Math - The Chain Bulletin</a></li><li><a href="https://pintail.medium.com/uniswap-a-good-deal-for-liquidity-providers-104c0b6816f2">Uniswap: A Good Deal for Liquidity Providers?</a></li></ul><h3>📈 Pricing with Liquidity Pools — Price Feed Oracles</h3><p>The by-product of liquidity pools is pricing oracles. Liquidity pools serving as pricing oracles offer access to historical price and liquidity data that enable other DeFi products.</p><blockquote><strong>A little bit about Oracles…</strong></blockquote><blockquote>Oracles are data feeds that bring data from off the blockchain (off-chain) data sources and puts it on the blockchain (on-chain) for smart contracts to use.</blockquote><h4>Types of Pricing Oracles</h4><p>Even though they all do the same job, they all come in different flavors and vary on the frequency data is extracted, the direction data flows, and the way the data is added to the smart contract. There are different price feed oracle design patterns, immediate read, publish-subscribe, and request response.</p><p>Below are a few of the popular implementations of price-feed oracles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRWx8_bkgEzzWYMY4gcXKg.png" /></figure><h4>Risks</h4><p>Price feeds come with several risks if they aren’t implemented correctly, the biggest being price manipulation. The biggest instance was the Harvest Finance exploit, resulting in a $33 million collective loss.</p><p>Check out Open Zeppelin’s write-up on price feeds:</p><p><a href="https://blog.openzeppelin.com/secure-smart-contract-guidelines-the-dangers-of-price-oracles/">Smart Contract Security Guidelines #3: The Dangers of Price Oracles - OpenZeppelin blog</a></p><h3>📚Hooked More Resources on Liquidity Pools</h3><p><strong>Comparison of Uniswap v1, v2, and v3</strong></p><p><a href="https://medium.com/auditless/uniswap-v1-to-v3-a-table-80d71d1303d2">Uniswap V1 to V3, a table</a></p><p><strong>TWAP Oracles vs. Chainlink Price Feeds: A Comparative Analysis</strong></p><p><a href="https://smartcontentpublication.medium.com/twap-oracles-vs-chainlink-price-feeds-a-comparative-analysis-8155a3483cbd">TWAP Oracles vs. Chainlink Price Feeds: A Comparative Analysis</a></p><p><strong>How to Retrieve Price Data in Smart Contracts</strong></p><p><a href="https://betterprogramming.pub/how-to-retrieve-price-data-in-smart-contracts-9e0467dfd280">How to Retrieve Price Data in Smart Contracts</a></p><p><strong>Uniswap Github</strong></p><p><a href="https://github.com/Uniswap">Uniswap Labs</a></p><p><strong>Balancer Github</strong></p><p><a href="https://github.com/balancer-labs/">Balancer Labs</a></p><p><strong>Curve Github</strong></p><p><a href="https://github.com/curvefi">Curve</a></p><p><strong>Deribit Education Liquidation</strong></p><p><a href="https://insights.deribit.com/education/liquidation/">Liquidation</a></p><p><strong>Uniswap: A Good Deal for Liquidity Providers</strong></p><p><a href="https://pintail.medium.com/uniswap-a-good-deal-for-liquidity-providers-104c0b6816f2">Uniswap: A Good Deal for Liquidity Providers?</a></p><p><strong>Why are you miscalculating your impermanent loss and how to stop doing it</strong></p><p><a href="https://blog.defiyield.app/why-are-you-miscalculating-your-impermanent-loss-and-how-to-stop-doing-it-866a7f1aa3a8">Why Are You Miscalculating Your Impermanent Loss And How To Stop Doing It</a></p><p><strong>Impermanent Loss Calculator</strong></p><p><a href="https://cryptocrab.io/impermanent-loss-calculator/">Impermanent Loss Calculator With APR, APY And Profit &amp; Loss - Crypto Crab</a></p><p><strong>What is Imperment Loss</strong></p><p><a href="https://www.finder.com/impermanent-loss">What Is Impermanent Loss? Examples &amp; How To Avoid It | Finder.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=905a615f0758" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/dipping-into-a-liquidity-pool-905a615f0758">Dipping into a Liquidity Pool</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep End of Liquidity Pool in the DEX Space?]]></title>
            <link>https://medium.com/coinmonks/deep-end-of-liquidity-pool-in-the-dex-space-f0576618a0ee?source=rss-bdd0b2ab4dde------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0576618a0ee</guid>
            <category><![CDATA[market-making]]></category>
            <category><![CDATA[dex]]></category>
            <category><![CDATA[liquidity-pool]]></category>
            <category><![CDATA[amm]]></category>
            <category><![CDATA[uniswap]]></category>
            <dc:creator><![CDATA[Mabel Oza]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 15:01:45 GMT</pubDate>
            <atom:updated>2023-01-06T06:28:46.368Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Liquidity pools enable individuals to become market makers in decentralized exchanges. Let’s deep dive into how that works.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ty5jvM7KnbMCoJSAv8STaQ.png" /></figure><p>Here we’ll take a deep dive into how decentralized exchanges works with liquidity pools and create a liquidity pool on Uniswap. If you’re not familiar with the fundamentals of liquidity pools then check out part 1, “Dipping into Liquidity Pools”</p><p><a href="https://mabeloza.medium.com/dipping-into-a-liquidity-pool-905a615f0758">Dipping into a Liquidity Pool</a></p><h3>Topics</h3><p><a href="#d775"><strong>How Centralized Exchanges Get Liquidity?</strong></a></p><p><a href="#51d3"><strong>How Decentralized Exchanges Get Liquidity?</strong></a></p><p><a href="#f28e"><strong>Where can you create a Liquidity Pool?</strong></a></p><p><a href="#579b"><strong>How to create a Liquidity Pool in Uniswap with your ERC20 Tokens?</strong></a></p><ol><li><a href="#cc25">Connect to Uniswap and go to the ‘Pool’ section</a></li><li><a href="#4d76">Import the chosen ERC20 Tokens into the Pool</a></li><li><a href="#b271">Setting the Fees</a></li><li><a href="#3727">Setting the Price</a></li><li><a href="#5593">Setting the Price Range</a></li><li><a href="#3b16">Depositing the Amounts</a></li><li><a href="#322d">Verifying Smart Contract Execution</a></li><li><a href="#3e8d">Managing the Liquidity Pool</a></li></ol><p><a href="#4265"><strong>Creating Liquidity Pools and Managing them Programmatically</strong></a></p><h3>How Centralized Exchanges Get Liquidity?</h3><p>Many of us have dealt with the complexities of exchanges since a young age, starting in the lunch room. A peer-to-peer exchange is like finding a friend willing to trade your lunch with theirs, this usually happens if you bring a commonly desired lunch item (for most North American school kids) like pudding or an apple. In this scenario, you are liquid.</p><blockquote>New to trading? Try <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">crypto trading bots</a> or <a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">copy trading</a> on <a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">best crypto exchanges</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/0*wZXnuEAu3KDTZJ-8" /></figure><p>But what if your mom or dad packed you something a little more ethnic, like a spicy samosa? As delicious as samosas are, finding a friend in a North American school willing to trade with you will be much more difficult. In this scenario, you face a risk of being illiquid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rGBIlhzYA6pVFQ3z.jpg" /></figure><p>Exchanges usually require both parties to agree on a buy/sell price, and we usually need these parties to agree fairly quickly. But what if both parties don’t agree on a buy/sell price, or if someone wants to trade their asset for another asset that isn’t available? Now our exchange is illiquid or exposes itself to liquidity risks, and people may be unable to offload their assets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V48-Nr5-GqES4bsQwNNDuw.png" /></figure><p>Exchanges limit their exposure to liquidity risks by turning to their rich friends (market makers) that have enough goods (liquidity) to make the deal happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kljef5HEkkjCM1Tyi9CGRw.png" /></figure><blockquote><strong>PFOF (Payment for Order Flow) </strong>is a rebate market makers send to brokerage firms to incentivize brokers to direct orders towards them. The reason they want to fulfill the orders is because the market makers make their revenue off the spread of the bid and ask price.</blockquote><p><strong>Fun Fact: </strong>PFOF was pioneered by the one and only… Bernie Madoff. He was known for his work around PFOF before he was known for his Ponzi scheme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*qJkNZs6xAu29xokE" /></figure><h3>How Decentralized Exchanges Get Liquidity?</h3><p>In a decentralized exchange, the order is fulfilled by a <strong>liquid provider</strong>, a group of people who pool their funds to provide liquidity for a pair of assets. These liquidity providers enter a smart contract when they create their liquidity pool. They agree to supply their assets to the DEX for a trading fee.</p><p>As the demand for the tokens increases, the DEX utilizes an algorithm that adjusts the price. This concept is called an Automated Market Market (AMM) because an algorithm does the market-making and figures out the price. For the most part, the AMM algorithm utilized is called constant product, but this isn’t the case for all liquidity pool protocols.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SoM0KxOFZuGWFdkavigjKA.png" /></figure><h3>Where can you create a Liquidity Pool?</h3><p>Some of the most popular liquidity pool platforms in the DEX space are <strong>Uniswap, Sushiswap, Curve, and Balancer</strong>, these platforms are consistently in the top 10 because of their TVL (Total Value Locked), volume traded, and support for a wide range of crypto assets. Today we will dive into Uniswap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9kynJBEAN4qj01kQ78NXMQ.png" /></figure><p>Below are the rankings of the top 10 platforms taken from Messari.</p><h4>Top 10 TVL (Total Value Locked)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OZcn2AtXP_LWu_ki2xB_mg.png" /><figcaption><a href="https://messari.io/protocol/uniswap-v3">https://messari.io/protocol/uniswap-v3</a> (10/1/22)</figcaption></figure><h4>Top 10 Volume Traded</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VIou1SICfE_5sWObtyptOQ.png" /><figcaption><a href="https://messari.io/protocol/uniswap-v3">https://messari.io/protocol/uniswap-v3</a> (10/1/22)</figcaption></figure><h3>How to create a Liquidity Pool in Uniswap with your ERC20 Tokens?</h3><p>Below is a video to see the whole process of creating a liquidity pool on Uniswap. We’ll walk through each step in detail in this blog.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIbVPuUeJ8LM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIbVPuUeJ8LM&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4f97a696f0d22727c83ee02f6d83234/href">https://medium.com/media/e4f97a696f0d22727c83ee02f6d83234/href</a></iframe><h4>Prerequisites</h4><p>Before we get started, you should have a solid understanding of the following:</p><ul><li>Setting up your wallet with testnet tokens</li></ul><p><a href="https://mabeloza.medium.com/setting-up-wallet-for-testnet-36c0ae4ce093">Setting Up Wallet for Testnet</a></p><ul><li>ERC20 Tokens and adding them to your wallet</li></ul><p><a href="https://vitto.cc/how-to-create-and-deploy-an-erc20-token-in-20-minutes/">How to Create and Deploy an ERC20 Token - In 20 minutes</a></p><p>You will need a plugin wallet with 2 Ethereum compatible tokens in a testnet network (preferably Goerli). One of them can be Ethereum, or both of them can be ERC20 tokens.</p><h4>1. Connect to Uniswap and go to the Pool section</h4><p>Go to the site <a href="https://uniswap.org/">https://uniswap.org/</a> and connect your web3 wallet (i.e., Exodus, Metamask, etc.) to the app. Then navigate to the Pool section of the app to create your liquidity pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8akarLX2s_Ku8eDqkW2jNQ.png" /></figure><h4>2. Import your ERC20 Tokens into the Pool</h4><p><strong>Get the Token Contract Address</strong></p><p>In your wallet, select a token. In this case, I selected the token APL. When you click on the 3 dots on the top, select the option “Token Details.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*oBoGHUESPtO98ik9L6tvKQ.png" /></figure><p>In the Token Details section, you will get a ‘Token contract address”. This is the address of the token APL’s contract address, which acts as an identifier of the token. Copy this address, we will use it to import your token into Uniswap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*7L790eJR9krar0BVn5u9KA.png" /></figure><p><strong>Import Token into Uniswap</strong></p><p>Back in Uniswap, please select one of the tokens; it should take you to a search bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*aKQOTW1R-eO3RIO8Y7dehg.png" /></figure><p>When you enter the token contract address, you will see the ERC20 token and its metadata. You can either import a pair of ERC20 tokens or just one ERC20 token and pair it against Ethereum. In this case, we’ll pair apples (APL) against grapes (GRP).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lgJKnzCGJSksPkF-9gfzIA.png" /></figure><h4>3. Setting the Fees</h4><p>After the tokens are added and paired with each other, the next step is to set a fee for the liquidity pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xWLORlsHIyZ4RCD6bvcvQ.png" /></figure><p>This is the fee the liquidity provider (you, in this case) will receive every time a trade is made against your pool.</p><ul><li>0.05% is often used for token pairs that correlate closely in prices like USDC and DAI, which are closely tied to $1.</li><li>0.3% is typically used for most pairs and has been the default in the previous versions.</li><li>1% is used for low-liquidity assets like meme coins.</li></ul><p>We choose the 0.3% fee to earn 0.3% of fees for every trade of apples or grapes from our liquidity pool.</p><h4>4. Setting the Price</h4><p>Here the price of an apple is four grapes, so in the section that says “Set Starting Price,” we set the current price of an APL (apple) to 4 GRPs (grapes).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKYY7P-ZputAUpw0iO8FFA.png" /></figure><h4>5. Setting the Price Range</h4><p>We need to set the price range; figuring out the range is based on how the market’s demand will change your asset price over time. The price range can’t be too narrow, and it can’t be too wide.</p><p><strong>What if the price range is too narrow?</strong></p><p>You won’t be paid the trade fee if your asset is priced outside the range. So if the price range is too narrow, the chances of earning fees decrease.</p><p>If you have a stablecoin and can guarantee that the price will always be within a dollar with a 5% margin going above and below a dollar, then you can have a narrow range.</p><p><strong>What if the price range is too wide?</strong></p><p>If your price range is too wide, you introduce market inefficiencies and high slippage (the difference between the expected and actual prices) to the traders. A wide range can increase your chance of earning fees, but the fees you earn will be less than if you had a narrow range. This is because the trading fees collected at a given price range are split pro-rata by LPs (Liquidity Providers) proportional to the amount of liquidity they contributed to that range.</p><p>Uniswap v3 addressed the risk of going out of range with narrow price ranges and market inefficiencies with wide price ranges by implementing <strong>concentrated liquidity</strong>. You can create multiple ranges that are narrow enough; check out the concept of <a href="https://docs.uniswap.org/protocol/concepts/V3-overview/concentrated-liquidity">Concentrated Liquidity</a>,</p><p><a href="https://uniswap.org/blog/uniswap-v3">Introducing Uniswap V3</a></p><p>We didn’t put too much analysis into figuring out the price range here and randomly selected a price range between ~2 and ~20.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8cgjd8IRdJcgWhpOaEq-A.png" /></figure><h4>6. Depositing the Amounts</h4><p>Now for the last step, we’re going to approve both the Apple and Grape tokens and deposit the tokens into the liquidity smart contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dV13GE0WRLKgjk5f0STtcg.png" /></figure><p>When we confirm the transaction using our wallet, we add tokens to the liquidity smart contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFpDOOc7nkYRquhq-5JXnQ.png" /></figure><h4>7. Verifying Contract Execution</h4><p>After the contract is deployed, you can verify the transaction details on Etherscan (a popular Ethereum blockchain explorer) using the transaction id provided by Uniswap (or link).</p><p>The “View on Etherscan” link will take you directly to your transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sebxNKFw-JCd1jFS565FwQ.png" /></figure><p>If you can find your transaction details on Etherscan and the status says “Success,” you know the transaction happened and is committed to the Ethereum network. Below you can see that 2 APL (apple tokens), and 4.22 GRP (grape tokens) were transferred to a smart contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9HCoCDpFTsUG755IhYPKQ.png" /></figure><p><strong>How do I know the address my tokens were transferred to is not just someone’s wallet but an actual contract?</strong></p><p>In the field called “Interacted With (To):” you can see the term “Contract” and an address of the contract, in this case the address in this picture is <a href="https://goerli.etherscan.io/address/0xc36442b4a4522e871399cd717abdd847ab11fe88">0xc36442b4a4522e871399cd717abdd847ab11fe88</a>. When you search this contract on Etherscan Goerli (or any blockchain explorer for the Goerli chain) you can go to the contract tab and view the contract code that was deployed on the chain. This is an assurance that your funds are locked into the smart contract and will only behave the way the contract intended to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LU-AmtbD7b6H3OQDEspkCQ.png" /></figure><h4>8. Managing Liquidity Pool</h4><p>Once your liquidity pool is created, you can manage it on Uniswap. You can either remove or increase liquidity and collect fees earned from trades. You can also monitor where your price currently sits within the set price range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9OhzHGtCF8_RpK4Co-gMuw.png" /></figure><h3>Creating Liquidity Pools and Managing them Programmatically</h3><p>If you’re a financial service firm that needs to create liquidity pools for multiple clients at a time with different criteria, using the interface may not be most efficient. So you would approach it programmatically, by either:</p><ol><li><strong>Creating a project by copying Uniswap’s set of smart contracts and deploy it using your own app</strong></li></ol><p>This approach will be difficult to maintain and is only advisable if the plan is to differ from the Uniswap protocol.</p><p><a href="https://github.com/Uniswap/v3-core">GitHub - Uniswap/v3-core: 🦄 🦄 🦄 Core smart contracts of Uniswap v3</a></p><p><strong>2. Use Uniswap’s SDK</strong></p><p>The easiest approach to get started with. The limitation is that the SDK is only available in Typescript and if you want to switch protocols then you would have to re-write your entire codebase.</p><p><a href="https://docs.uniswap.org/sdk/v3/overview">Overview | Uniswap</a></p><p><strong>3. Inheriting Uniswap’s smart contract (Recommended)</strong></p><p>This is the most recommended approach because you’re calling the continuously audited Uniswap protocol but also doing it within your smart contract and not your full stack.</p><p><a href="https://docs.uniswap.org/contracts/v3/guides/providing-liquidity/setting-up">Set Up Your Contract | Uniswap</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0576618a0ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/deep-end-of-liquidity-pool-in-the-dex-space-f0576618a0ee">Deep End of Liquidity Pool in the DEX Space?</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>