<?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 Y. on Medium]]></title>
        <description><![CDATA[Stories by Y. on Medium]]></description>
        <link>https://medium.com/@yyforyongyu?source=rss-d24242cc1c1b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*0VcVf4vP-pbgrfWC8oUSUA.jpeg</url>
            <title>Stories by Y. on Medium</title>
            <link>https://medium.com/@yyforyongyu?source=rss-d24242cc1c1b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:21:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yyforyongyu/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[Till it’s lightning-fast — Uncover the Lightning Network Transactions]]></title>
            <link>https://medium.com/@yyforyongyu/till-its-lightning-fast-uncover-the-lightning-network-transactions-f3180e467857?source=rss-d24242cc1c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3180e467857</guid>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[lightning-network]]></category>
            <dc:creator><![CDATA[Y.]]></dc:creator>
            <pubDate>Mon, 04 Nov 2019 17:18:08 GMT</pubDate>
            <atom:updated>2020-07-02T20:11:42.080Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Till it’s lightning-fast — Uncover the Lightning Network Transactions</h3><blockquote>A down-to-earth explanation of how the <a href="https://github.com/lightningnetwork/lightning-rfc">implementation</a> of the lightning network works. Prior knowledge of the <a href="https://blog.goodaudience.com/till-its-lightning-fast-uncover-bitcoin-transactions-9c2a5cc94144">UTXO, Bitcoin Script, and digital signature</a> are required. A good understanding of the <a href="https://blog.goodaudience.com/till-its-lightning-fast-uncover-the-development-of-the-lightning-network-fbd01bc0ea80">rationality of the Revocable Sequence Maturing Contract and Hash Time Locked Contract</a> is recommended.</blockquote><blockquote>The lightning network, like Bitcoin, is a masterpiece created by the open source community. The <a href="https://github.com/lightningnetwork/lightning-rfc">Lightning Network Specifications</a> guide the deployment of the network, while few educational resources can be found online. This article is meant to be a supplement, explaining in detail how and why the transaction works in the lightning network.</blockquote><h3>Overview</h3><p>The transactions in the lightning network are no more than <strong>a chain of commitment transactions spending the outputs in the funding transaction</strong>. Today’s lightning network took the idea of the RSMC and made several enhancements. First, it applied a <a href="https://en.wikipedia.org/wiki/Commitment_scheme">commitment scheme</a>(the <a href="https://medium.com/swlh/till-its-lightning-fast-uncover-the-development-of-the-lightning-network-fbd01bc0ea80">hide-and-reveal</a> scheme) to enable payment forwarding. Second, it replaced the multisig function with <a href="https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication">elliptic curve point multiplication</a> in revocations.</p><h3>Structure of Transactions</h3><p>There are four types of transactions in the lightning network, two of them transfer money between the lighting network and the Bitcoin network(cross-layer transactions), the other two update balances in the lightning network(layer-two transactions).</p><ol><li><strong>Funding transaction</strong>. A funding transaction is created during the channel opening. It moves money from the Bitcoin network into the lightning network and puts the funds into a multisig address.</li><li><strong>Commitment transaction and HTLC transactions</strong>. The commitment transaction serves as the building block of the lightning network. Whenever a balance update is made, commitment transactions are created. HTLC transactions, or the HTLC-Success and HTLC-Timeout transactions, were <a href="https://medium.com/@rusty_lightning/the-bitcoin-lightning-spec-part-3-8-peer-protocol-for-channel-management-3de0996cd4c">originally put in the commitment transaction and taken out in the final design</a>. As explained later, HTLC transactions can be viewed as part of the commitment transaction as it’s their mere purpose to spend the outputs specified in the commitment transaction.</li><li><strong>Closing transaction</strong>. A closing transaction is created when two participants decide to close the channel corporately. It moves money from the lightning network into the Bitcoin network.</li></ol><h4>Commitment Transaction as A Means of Accounting</h4><p>A commitment transaction has two to four types of outputs, depending on whether it’s forwarding payments or not, and listed as below,</p><ul><li>Local Output, which records how much money the local participant has.</li><li>Remote Output, which records how much money the remote participant has.</li><li>Credit Output, or the incoming HTLC, the received HTLC, which records how much money the local participant is receiving.</li><li>Debit Output, or the outgoing HTLC, the offered HTLC, which records how much money the local participant is sending.</li></ul><p>Credit Output and Debit Output are created when the participant is making or forwarding payments to others. To visualize,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*4rK6pZ5s2L-5ajmm9rC6nA.png" /><figcaption><em>Outputs 2 and 3(credit and debit) are possible fields</em></figcaption></figure><p>The lightning network has intensively worked on the Bitcoin scripts, securing the outputs to make sure they will be spent as intended.</p><h3>Revocation — Keys and More Keys</h3><p>Overall, for a layer-two transaction to function, it shall be refundable and revocable, which corresponding to two scenarios,</p><ul><li>When one participant stays unresponsive for a given period, the counterparty gets refunded.</li><li>When a new transaction is made, the old transaction gets revoked.</li></ul><p>The revocation transaction, sometimes called the <em>Breach Remedy Transaction</em>, exists to be the deterrence against any malicious activities, which is the core element that makes the lightning network safe.</p><p>The implementation of the lightning network uses revocation key pairs instead of the multisig function. The cryptographic hash function involved is the <a href="https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm">Elliptic Curve Digital Signature Algorithm</a>(ECDSA), along with the <a href="https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication">Elliptic Curve Point Multiplication</a>. The process is as follows,</p><p>Alice and Bob each generate a private-public key pair based on the ECDSA, marked as alice_public_key, alice_secret_key, bob_public_key and bob_secret_key.</p><p>A revocation_public_key is constructed using alice_public_key and bob_public_key. For simplicity, it’s formula can be viewed as,</p><pre>revocation_public_key = alice_public_key + bob_public_key</pre><p>And it’s corresponding private key revocation_private_key is calculated as</p><pre>revocation_private_key = alice_private_key + bob_private_key</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAAc8d-uU-Q4XdORSA9O8w.png" /><figcaption><em>Relationship of the keys</em></figcaption></figure><p>Since it’s a private-public key pair, messages signed by the revocation_private_key will produce a revocation_signature, and anyone can verify the signature by looking at the revocation_public_key with the message. While the math is different, it requires keys from both Alice and Bob to generate a valid signature like the multisig function. This method is more favorable because it’s believed to be <a href="https://github.com/ElementsProject/lightning/blob/master/doc/deployable-lightning.pdf">more intuitive and efficient</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxLgWfy9V-UeJw4reVnenQ.png" /><figcaption><em>Usage of the revocation keys. A private key can be used to sign an arbitrary number of messages, producing signatures with a one-to-one relationship with the messages.</em></figcaption></figure><p>With the above background, we will analyze how the open/update/close a channel works in detail.</p><h3>Open A Channel — Funding Transaction and the First Commitment Transaction</h3><p>The process to open a channel between Alice and Bob with Alice funding 1 BTC is as follows,</p><p>First, before any transactions, initial settings of the channel are negotiated and settled, such as the minimal confirmations needed for the funding transaction and public keys for producing the revocation keys, which,</p><ul><li>For Alice, she creates public keys alice_pubkey_tx_a1 and alice_pubkey_tx_b1, sends them to Bob. The corresponding private keys alice_prikey_tx_a1 and alice_prikey_tx_b1 are kept to herself.</li><li>For Bob, he creates public keys bob_pubkey_tx_a1 and bob_pubkey_tx_b1, sends them to Alice. The private keys bob_prikey_tx_a1 and bob_prikey_tx_b1 are kept to himself.</li><li>Alice uses alice_pubkey_tx_a1 and bob_pubkey_tx_a1 to generate the revocation_pubkey_tx_a1, which can validate revocation_sig_tx_a1.</li><li>Bob uses alice_pubkey_tx_b1 and bob_pubkey_tx_b1 to generate the revocation_pubkey_tx_b1, which can validate revocation_sig_tx_b1.</li></ul><p>Second, Alice creates a funding transaction, signs it, and shares its Transaction ID and Output Number with Bob.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*KpwZnLyFCBkeIUi-ffqXbw.png" /><figcaption><em>Alice’s funding transaction</em></figcaption></figure><p>Third, Alice and Bob each create the first commitment transaction based on the funding transaction, sign it, and exchange their signatures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*lF3zRCp2tMiuYCDXDvaMwQ.png" /><figcaption><em>Alice’s first commitment transaction. Notice that there is no remote balance.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*WiRyPbdYKwVqq8B0_J_41g.png" /><figcaption><em>Bob’s first commitment transaction. Notice that there is no local balance.</em></figcaption></figure><p>Finally, Alice confirms the signatures match and broadcasts the funding transaction.</p><blockquote><strong>About the naming of the keys</strong></blockquote><blockquote>Abbreviations are used to shorten the names of the keys. Public key is abbreviated as <em>pubkey</em>, private key is abbreviated as <em>prikey</em>, and signature is <em>sig</em>. For example, <em>alice_funding_sig</em> means the signature used for unlocking the funding transaction from Alice.</blockquote><blockquote>Whenever there is a <em>revocation_</em> in a key, it means it’s generated from Alice and Bob’s keys. For example, a <strong><em>revocation_pubkey</em></strong><em>_tx_a1</em> is generated using <strong><em>alice_pubkey</em></strong><em>_tx_a1</em> and <strong><em>bob_pubkey</em></strong><em>_tx_a1</em>. A <strong><em>revocation_prikey</em></strong><em>_tx_a1</em> is generated using <strong><em>alice_prikey</em></strong><em>_tx_a1</em> and <strong><em>bob_prikey</em></strong><em>_tx_a1</em>.</blockquote><blockquote>Whenever there is a <em>tx_</em> in the revocation key, it means the key is used to revoke that particular transaction. For example, <em>revocation_sig_</em><strong><em>tx_a1</em></strong> is used to revoke Alice’s transaction <strong><em>TX A01</em></strong> . For now, Bob’s transactions do not incorporate revocation yet, but soon it will be used.</blockquote><blockquote>Finally, a <em>revocation_</em><strong><em>sig</em></strong><em>_tx_a1</em> is produced by <em>revocation_</em><strong><em>prikey</em></strong><em>_tx_a1</em>, and can be validated using <em>revocation_</em><strong><em>pubkey</em></strong><em>_tx_a1</em>.</blockquote><p>Once the funding transaction gets the minimal N confirmations, the channel is established and remains open. The value N is proposed by Alice and can get rejected by Bob if it’s unreasonably large.</p><p>A Remote Output is treated differently compared to a Local Output, as a local participant a) cannot spend a Remote Output and b) has no interest in broadcasting it. For example, Bob has no interest in broadcasting TX B01, as doing so won’t do him any good and that’s why a revocation key(revocation_sig_tx_b1) is not put. However, a Local Output needs to have both revocation and timeout because the local participant has the motivation to cheat while the ability to refund is required in case the remote participant becomes unresponsive. The rationality is illustrated in the following section.</p><h3>Update Channel Balances — the Second and Many Commitment Transactions</h3><p>The most complicated process happens during updating channel balances. When the channel balances change, it’s reflected in the new commitment transactions. The money received/sent is recorded in the Credit/Debit Outputs, and their old revocation-related private keys are exchanged.</p><p>For instance, if Alice sends Bob 0.1 BTC, they will both create new transactions and exchange keys. First is their old revocation-related private keys, alice_prikey_tx_a1 and bob_prikey_tx_b1 are exchanged. Now that Bob has the alice_prikey_tx_a1, he can derive the revocation_prikey_tx_a1 to generate revocation_sig_tx_a1, which unlocks the Local Output in TX A01. Second is their new revocation-related public keys, alice_pubkey_tx_a2, alice_pubkey_tx_b2, bob_pubkey_tx_a2 and bob_pubkey_tx_b2 are exchanged to produce revocation_pubkey_tx_a2 and revocation_pubkey_tx_b2, which are used in their new commitment transactions.</p><p>In Alice new commitment transaction, TX A02, it has two outputs,</p><ul><li>A Local Output, which records her current balance, 0.9 BTC.</li><li>A Debit Output, which records the money she has sent to Bob, the 0.1 BTC.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSbsa467ADM0HG0YhV2tFA.png" /><figcaption><em>Alice’s second commitment transaction. Notice the commitment transaction always references the funding transaction.</em></figcaption></figure><p>And for Bob, TX B02, similarly,</p><ul><li>A Remote Output, which records Alice’s balance, 0.9 BTC.</li><li>A Credit Output, which records the money he has received, the 0.1 BTC.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V7u1Kk_hCAEaSDzMA_BZYw.png" /><figcaption><em>Bob’s second commitment transaction. Notice the commitment transaction always references the funding transaction.</em></figcaption></figure><p>Before tackling the design of the Credit/Debit Outputs, let’s first review why the Local and Remote Outputs are solid.</p><h4>Secure Local and Remote Outputs</h4><p>It’s clear that Bob has no motivation to broadcast the older transaction TX B01 because his money is in TX B02. However, for Alice</p><ul><li>If Bob disappears, she can broadcast TX A02 to refund herself and spend the money in two weeks.</li><li>If Alice broadcasts TX A02, Bob has no way to spend its Local Output because he doesn’t have revocation_prikey_tx_a2, which is derived from alice_prikey_tx_a2 and bob_prikey_tx_a2.</li><li>If Alice broadcasts TX A01, she has to wait two weeks before it’s spendable. Meanwhile, Bob will use alice_prikey_tx_a1 and bob_prikey_tx_a1 to derive revocation_prikey_tx_a1, which can produce revocation_sig_tx_a1 to unlock the output, and take all the money as a penalty to Alice.</li></ul><p>Thus updating Local and Remote Outputs is safe. The receiver won’t worry the sender will cheat, and the sender won’t worry the receiver may disappear(a detailed analysis is covered in <a href="https://blog.goodaudience.com/till-its-lightning-fast-uncover-the-development-of-the-lightning-network-fbd01bc0ea80">Till it’s lightning-fast — Uncover the Development of the Lightning Network</a>, check the <em>Update Channel Balances</em> part if needed).</p><p>The harder question is how can we secure the Credit/Debit Outputs?</p><h4>Make Payments with Revocation</h4><p>Suppose Bob has a golden goose and agrees to sell it to Alice for 0.1 BTC(why? <a href="https://www.youtube.com/watch?v=RUOZU2iubR0">Because chicken is our best friend!</a>). It’s up to Bob to initiate the payment request. The process is as follows,</p><ol><li>Bob generates a secret payment_secret and keeps it to himself.</li><li>Bob hashes the payment_secret to produce a payment_hash and sends it to Alice.</li><li>Alice creates a new commitment transaction, in which the Debit Output can be spent with either condition — if 3 days passed, Alice gets the money or if Bob can provide the payment_secret, Bob gets the money.</li><li>Bob creates a new commitment transaction, in which the Credit Output can be spent with the same conditions.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*BPuhjagHPOFrpGII_J3yog.png" /><figcaption><em>Alice’s Debit Output in </em><strong><em>TX A02</em></strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*Q4eE78urlVmC4hlsr_F-8Q.png" /><figcaption><em>Bob’s Credit Output in </em><strong><em>TX B02</em></strong><em>, which is the same as Alice’s Debit Output at the moment.</em></figcaption></figure><p>Keep in mind that,</p><ul><li>If Bob provides payment_secret in 3 days, he shall get the money. If 3 days passed, even if Bob provides payment_secret, he shall not get the money. In other words, the condition for Bob to own the money needs a) he knows payment_secret and b) he reveals it to Alice within 3 days. In our case, since Bob generated the payment_secret, he knew the value from the beginning.</li><li>If 3 days passed, the money shall go to Alice, under the condition that Bob cannot provide the payment_secret in 3 days. In other words, if Bob reveals the payment_secret within 3 days but he doesn’t spend the output, Alice shall not own the money when 3 days passed.</li></ul><p>It’s perplexing, I know. As the principle of the lightning network is to make sure the transactions hit the Bitcoin network as infrequent as possible, we want to design a way that Alice and Bob can both feel safe about their money <strong>without</strong> broadcasting their commitment transactions and keep the channel long open. In our case, if Bob knows the payment_secret within 3 days, <strong>it doesn’t require him to broadcast the transaction to prove that statement</strong>.</p><p>So before Bob ships his beloved golden goose, we need to understand the timelock in depth.</p><h4>Timelock in Bitcoin</h4><p>Two types of timelock are used in Bitcoin, one is an absolute timelock, the other is a relative one. Their difference is as simple as “meet me at 3:00 p.m.” verses “meet me in 2 hours”, with the relative timelock starts the countdown when the transaction is mined. Depending on where the timelock is placed, it can control when a transaction can be broadcasted or its outputs can be spent. Inside each transaction, three locations are used to specify a timelock,</p><ul><li>In the input section, each input has a nSequence field that is used to specify a relative timelock.</li><li>In the output section, inside each output’s locking script, a CheckLockTimeVerify (CLTV) specifies an absolute timelock, and a CheckSequenceVerify (CSV) specifies a relative timelock.</li><li>In the transaction level, an nLocktime is used to specify an absolute timelock.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*egPWop0G63JFtFlw9J4LkA.png" /><figcaption><em>A transaction highlights the positions of timelocks.</em></figcaption></figure><p>The lightning network has implemented nLocktime, CheckSequenceVerify and CheckLockTimeVerify in its design. An nLocktime controls when a transaction can enter the blockchain. If a transaction with nLocktime, 2140/01/01 12am is encoded, it cannot be broadcasted until over a hundred years later. CheckSequenceVerify and CheckLockTimeVerify control when outputs can be spent. If a CheckSequenceVerify with 30 days is put, the transaction outputs cannot be spent until 30 days later. If a CheckLockTimeVerify with 2140/01/01 12am is put, the outputs cannot be spent unless the time 2140/01/01 12am has reached. Simply put, an nLocktime controls the transaction’s broadcast time, while CheckSequenceVerify and CheckLockTimeVerify control the outputs’ spend time.</p><h4>Timelock used in the outputs</h4><p>Outputs with revocation, i.e., the Local and Remote Outputs, use relative timelock because the act of broadcasting an old transaction needs to be exposed. Therefore it will only make sense to start the countdown when an old transaction is broadcasted and mined. For instance, if Alice decides to cheat by broadcasting TX A01, the moment the transaction gets mined by the miners, she has to wait an extra two weeks to spend its outputs, which leaves time for Bob to react. However, if an absolute timelock is used, e.g., 2019/12/31 23:59:59, she can wait till the New Year’s Eve, broadcasts and spends it immediately, without Bob’s notice.</p><p>Outputs for recording payments, i.e., the Credit and Debit Outputs use the absolute timelock because it’s meant to place pressure on payment claimers(e.g., Bob) without broadcasting the transaction. If Bob cannot provide the payment_secret before an absolute time, say 6pm today, Alice will retain the ability to spend the money after 6 p.m. If a relative timelock 3 days, is used, Bob would be in no rush unless he sees the transaction being broadcasted by Alice, which she cannot spend the outputs until 3 days have passed. Suppose they make this payment at 8:00 am today, and Alice gives Bob 10 hours to reveal his payment_secret, our updated outputs now look like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*ytD__11AGR9tb61oaDKzNg.png" /><figcaption><em>Alice’s Debit Output in </em><strong><em>TX A02</em></strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*ZZ74_Syveg7w5A5YL-qZKA.png" /><figcaption><em>Bob’s Credit Output in </em><strong><em>TX B02</em></strong><em>, which is the same as Alice’s Debit Output at the moment.</em></figcaption></figure><p>The timelock can solve the aforementioned problem, as neither participant needs to prove their statements by broadcasting their transactions.</p><h4>Secure Credit and Debit Outputs</h4><p>It’s already at 5 p.m. Just one hour away, Alice can take the money back by spending her Debit Output in TX A02. Although Bob has the payment_secret, it seems that he has to broadcast TX B02 to secure his payment as he has already shipped his golden goose to Alice. Is there a way to stop Alice from cheating? Sure thing. Alice’s Debit Output can be further locked with a relative timelock, say 2 weeks, as shown below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*AZatE0chJsqugkAiCamEtQ.png" /><figcaption><em>Alice’s Debit Output in </em><strong><em>TX A02</em></strong></figcaption></figure><p>If Alice broadcasts TX A02, she has to wait two weeks to spend her money. Meanwhile, once Bob monitors the Bitcoin network and finds out, he will spend the Debit Output immediately with his payment_secret. Now it’s Alice’s turn to worry. After 6 p.m., if Alice broadcasts TX A02, Bob with the payment_secret can still spend the Debit Output, while he is only designed to spend it before 6 p.m. Is there a way to stop Bob from spending it after 6 p.m.?</p><p>Instead of putting a timelock in the Debit Output, Alice can spend it anytime she wants, with one condition — she has to create a special transaction to spend it, the HTLC-Timeout transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*GtI0fT90PhEqDCKurnfH8w.png" /><figcaption><em>Alice’s HTLC-Timeout Transaction, whose outputs can only be spent by Alice.</em></figcaption></figure><p>An HTLC-Timeout transaction uses an absolute timelock(nLocktime), as shown above,</p><ul><li>It consumes an output from TX A02, Output Number 1, which is Alice’s Debit Output.</li><li>It has an nLocktime of 6 p.m. today, which means this transaction cannot be broadcasted before 6 p.m.</li></ul><p>The Debit Output is also changed,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*wSAqk4UGINOt0EGDm9irww.png" /><figcaption><em>Alice’s Debit Output in </em><strong><em>TX A02</em></strong></figcaption></figure><p>The problem is <strong>almost</strong> solved. For Alice to claim her money, two steps are involved,</p><ol><li>She needs to broadcast TX A02 first.</li><li>After 6 p.m., she needs to broadcast her HTLC-Timeout transaction.</li></ol><p>Before 6 p.m., Alice has no interest in broadcasting TX A02 because she cannot spend its outputs via an HTLC-Timeout transaction due to the nLocktime and Bob will take the money using the payment_secret. Once 6 p.m. has passed, even Bob has the payment_secret, he cannot spend it because the Debit Output has already been consumed by Alice’s HTLC-Timeout transaction. Essentially, the Bitcoin network makes sure every transaction output can only be spent once, although the locking script provides two possible scenarios.</p><p>However, the TX A02 and HTLC-Timeout transactions are created by Alice, why would she follow the specified scheme to create the locking scripts?</p><p>She won’t, and there is a final change which enables Bob to check the transactions created by Alice are as expected. If Alice wants to spend the Debit Output via an HTLC-Timeout transaction, she will need Bob’s approval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5F9oE32XhMb2pgj9CqXgg.png" /><figcaption><em>Alice’s commitment transaction </em><strong><em>TX A02</em></strong><em>. Notice that a multisig function is used in the Debit Output’s locking script, which requires </em><strong><em>alice_htlc_sig</em></strong><em> and </em><strong><em>bob_htlc_sig</em></strong><em> to unlock.</em></figcaption></figure><p>When creating TX A02, it consumes an output from the funding transaction, which requires both Alice and Bob’s signatures(alice_funding_sig and bob_funding_sig) to unlock. Thus Bob can check TX A02 is created as intended before signing TX A02 and sending his signature bob_funding_sig to Alice.</p><p>The new HTLC-Timeout transaction,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*i4j9-O1egf0-zbanZDlTaQ.png" /><figcaption><em>Alice’s HTLC-Timeout Transaction</em></figcaption></figure><p>When creating the HTLC-Timeout transaction, it consumes the Debit Output from TX A02, which requires both Alice and Bob’s signatures(alice_htlc_sig and bob_htlc_sig) to unlock. Bob can then check it’s created as intended before signing the HTLC-Timeout transaction and sending his signature bob_htlc_sig to Alice. This way, Alice will always behave as expected. Overall, we want the participants to feel safe about their money without broadcasting their transactions, thus a great effort has been spent to develop such a complicated scheme. For transaction TX A02 and the HTLC-Timeout, it works as,</p><ul><li>If Bob has the payment_secret, he knows for sure that he can get his money before 6 p.m. Because Alice cannot spend the Local Output in TX A02 even if she is willing to broadcast it.</li><li>After 6 p.m., Bob won’t be able to spend the output because it will be spent by Alice’s HTLC-Timeout transaction.</li></ul><p>By this design, Alice will have no interest in broadcasting TX A02 unless necessary. For Bob, the transaction TX B02 will have a similar structure, followed by an HTLC-Success transaction much like the HTLC-Timeout Transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5BHC2inIDADRzquzZHJr4Q.png" /><figcaption><em>Bob’s commitment transaction </em><strong><em>TX B02</em></strong><em>. Notice that a multisig function is used in the Credit Output’s locking script, which requires </em><strong><em>alice_htlc_sig</em></strong><em> and </em><strong><em>bob_htlc_sig</em></strong><em> to unlock.</em></figcaption></figure><p>Bob’s Credit Output can be spent with payment_secret, alice_htlc_sig and bob_htlc_sig together via an HTLC-Success transaction. Like Alice’s HTLC-Timeout transaction, the HTLC-Success is checked and signed by Alice to ensure it’s created as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*xJL4ooIUm8EFsLgnQyFGSg.png" /><figcaption><em>Bob’s HTLC-Success Transaction</em></figcaption></figure><p>For Bob to claim his money, he needs to broadcast both TX B02 and HTLC-Success transaction before 6 p.m. Otherwise, Alice can take the money once it’s after 6 p.m.</p><h4>Update Credit and Debit Balances</h4><p>Being able to record balances is not enough, we need to update them too. Back to our golden goose case, now Alice is interested in Bob’s golden eggs and she will buy them for 0.05 BTC. To make the deal happen, Alice and Bob have each created the transaction TX A03 and TX B03 to reflect their latest balances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WrXSC74LaKrriuO7XeHPrA.png" /><figcaption><em>Alice and Bob’s balances</em></figcaption></figure><p>Similar to how the local and remote balances are secured, the timelock and revocation are used in the Debit and Credit Outputs too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*QBqOteKQwANMCVlwUBIE-Q.png" /><figcaption><em>Alice’s Debit Output in </em><strong><em>TX A02</em></strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*JURJOkIB-VvM_Ygblrs8Fw.png" /><figcaption><em>Bob’s Credit Output in </em><strong><em>TX B02</em></strong></figcaption></figure><p>Prior to the creation of TX A03 and TX B03, Alice and Bob would exchange their corresponding private keys — Alice gives Bob alice_prikey_tx_a2 and Bob gives Alice bob_prikey_tx_b2. For TX A02, the revocation can only be invoked by Bob as Alice doesn’t have the private key bob_prikey_tx_a2. For TX B02, it’s reversed as Bob doesn’t have the private key alice_prikey_tx_b2, the revocation can only be invoked by Alice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wRVSnxEGUAc8H2NXQRaOkA.png" /><figcaption><em>Alice has the keys </em><strong><em>alice_prikey_tx_b2</em></strong><em> and </em><strong><em>bob_prikey_tx_b2</em></strong><em> to derive the </em><strong><em>revocation_prikey_tx_b2</em></strong><em>, which generates the signature </em><strong><em>revocation_sig_tx_b2</em></strong><em> that can revoke </em><strong><em>TX B02</em></strong><em>. If Bob broadcasts </em><strong><em>TX B02</em></strong><em>, all his money in the Credit Output will be taken by Alice as a penalty.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8D5K74YiTXiQzOPuV3Uvkw.png" /><figcaption><em>Bob has the keys </em><strong><em>alice_prikey_tx_a2</em></strong><em> and </em><strong><em>bob_prikey_tx_a2</em></strong><em> to derive the </em><strong><em>revocation_prikey_tx_a2</em></strong><em>, which generates the signature </em><strong><em>revocation_sig_tx_a2</em></strong><em> that can revoke </em><strong><em>TX A02</em></strong><em>. If Alice broadcasts </em><strong><em>TX A02</em></strong><em>, all her money in the Debit Output will be taken by Bob as a penalty.</em></figcaption></figure><p>Revocation also goes for the HTLC-Timeout and HTLC-Success transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*SoA3aqqzo09v-JP7VR0PQQ.png" /><figcaption><em>Alice’s HTLC-Timeout Transaction</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*8S_l4GMvbKPA9pTvjYhgXQ.png" /><figcaption><em>Bob’s HTLC-Success Transaction</em></figcaption></figure><p><a href="https://bitcoin.stackexchange.com/questions/91344/why-do-we-need-revocation-in-both-the-offered-received-htlc-outputs-and-htlc-tim"><em>Why revocation at two places?</em></a></p><p><em>Notice that the revocation has to exist in both Credit/Debit Outputs and HTLC-Timeout/Success outputs. If only the Debit output has the revocation, Alice could broadcast the old transaction </em><em>TX A02 and spend its outputs with her HTLC-Timeout transaction. Although Bob can revoke </em><em>TX A02, by the time he noticed, the Debit Output would have already been consumed by Alice’s HTLC-Timeout transaction. On the other hand, if only the HTLC-Timeout/Success transactions have the revocation, Alice can broadcast </em><em>TX A02 only, causing Bob’s money being locked for a while(</em><a href="https://bitcoin.stackexchange.com/questions/91344/why-do-we-need-revocation-in-both-the-offered-received-htlc-outputs-and-htlc-tim"><em>check the ongoing discussion if interested</em></a><em>).</em></p><h3>Close the Channel — Hit the Bitcoin Network</h3><p>There are <a href="https://github.com/lightningnetwork/lightning-rfc/blob/master/05-onchain.md">three ways to close the channel</a>, for Alice and Bob, they can,</p><ol><li>Mutual close, the good way. Alice and Bob can make a closing transaction to close the channel and collect their money immediately.</li><li>Unilateral close via timeout or payment hash, which is considered the bad way as it requires funds being locked for a given time. In our case, Alice can broadcast TX A03 or Bob can broadcast TX B03 to collect their money, but they have to wait 2 weeks before it’s spendable.</li><li>Revocation, the ugly way. If anyone broadcasts an older transaction, the counterparty will use the revocation key to collect the money as a punishment to the cheater.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1ZALnZ529CmMYsYtGsbaQ.png" /><figcaption><em>Alice and Bob will sign the closing transaction together, negotiate the fees and broadcast it.</em></figcaption></figure><h3>The Final Analysis — Forwarding Payments</h3><p>A great effort has been put into the design of HTLC outputs so that the lightning network can forward payments seamlessly. Suppose there are two channels, one between Alice and Bob with Alice’s fund 1 BTC, the other between Bob and Charlie with Bob’s fund 2 BTC. Alice wants to send Charlie 0.1 BTC via Bob, here’s what they need to do.</p><p>Between Bob and Charlie,</p><ol><li>Charlie generates a payment_charlie_secret, hashes it to produce the payment_charlie_secret.</li><li>Charlie and Bob create similar commitment transactions — Charlie has a Credit Output(the offered HTLC output) of 0.1 BTC and Bob has a Debit Output(the received HTLC output) of 0.1 BTC.</li><li>Charlie has to reveal the payment_charlie_secret to Bob before 5 p.m., otherwise, Bob will take back his money.</li><li>Charlie and Bob create similar HTLC-Timeout and HTLC-Success transactions.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sEdDTrf3KivKYxGcGiZvAw.png" /><figcaption><em>Bob’s commitment transaction, where he pays Charlie 0.1 BTC.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*wKPJCQ6UvaAfO7UfNEca-Q.png" /><figcaption><em>Bob’s HTLC-Timeout transaction, where he can spend the output after 5 p.m.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_IWVG4eTQRhusbIdIUHlQ.png" /><figcaption><em>Charlie’s commitment transaction, where he gets 0.1 BTC from Bob.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*OsbfSGvPaW8Z-9mxfOxnDg.png" /><figcaption><em>Charlie’s HTLC-Success transaction</em></figcaption></figure><p>Between Alice and Bob, they will repeat the process, while Bob now becomes the debt collector. In their commitment transactions,</p><ul><li>Bob has a Credit Output(the offered HTLC output) of 0.1 BTC.</li><li>Alice has a Debit Output(the received HTLC output) of 0.1 BTC.</li><li>Bob has to reveal the payment_charlie_secret before 6 p.m., otherwise, Alice will take her money back.</li></ul><p>Bob and Alice will create similar HTLC-Timeout and HTLC-Success transactions.</p><p>To fulfill the payment,</p><ol><li>Charlie reveals the payment_charlie_secret to Bob before 5 p.m. to claim his money from Bob.</li><li>Bob reveals the payment_charlie_secret before 6 p.m. to claim his money from Alice.</li></ol><p>In reality, Bob, who forwards the payment, may charge a small fee in terms of his service. Though the technology is already in use today, it’s fascinating to see what economic and political effects it will eventually play out!</p><h3>Clarifications — For Developer/Researcher</h3><p>For brevity, I’ve deliberately shortened the <strong>locking script</strong> to focus on a bigger picture. Still, I think it would be nice to clarify the actual script used, especially if you are a developer/researcher.</p><p>When we say “check Alice’s signature is presented” in the <strong>locking script</strong>, what’s been put in the script is &lt;Alice&#39;s public key&gt; OP_CHECKSIG. When Alice wants to spend it, she then put &lt;Alice&#39;s signature&gt; in the input of the spending transaction. The same goes for the revocation signature and payment secret too. Please check the <strong>Notes and References</strong> to find all the details.</p><p>Another clarification is the algorithm used to derive the revocation key pairs. Previously it’s described as simple addition, while the actual math is as follows,</p><pre>revocation_public_key = bob_public_key * SHA256(bob_public_key || alice_public_key) + alice_public_key * SHA256(alice_public_key || bob_public_key)</pre><pre>revocation_private_key = bob_secret_key * SHA256(bob_public_key || alice_public_key) + alice_secret_key * SHA256(alice_public_key || bob_public_key)</pre><p>If name mapping to the <a href="https://github.com/lightningnetwork/lightning-rfc/blob/master/03-transactions.md#revocationpubkey-derivation">RFC</a> is wanted, suppose Bob being the local node and Alice being remote, replace them as following,</p><ul><li>bob_public_key is revocation_basepoint.</li><li>bob_secret_key is revocation_basepoint_secret.</li><li>alice_public_key is per_commitment_point.</li><li>alice_secret_key is per_commitment_secret.</li></ul><p>You will get the same formula as specified.</p><h4>Notes and References</h4><ol><li><a href="http://lightning.network/lightning-network-paper.pdf">The Bitcoin Lightning Network: Scalable Off-Chain Instant Payments, Joseph Poon, Thaddeus Dryja</a></li><li><a href="https://github.com/ElementsProject/lightning/blob/master/doc/deployable-lightning.pdf">Reaching the ground with lightning, Rusty Russell</a></li><li><a href="https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication">Elliptic Curve Point Multiplication</a></li><li><a href="https://github.com/lightningnetwork/lightning-rfc">The Lightning Network Specifications</a> is a great place to find all the details, though it’s difficult to read. Regarding how transactions work, <a href="https://github.com/lightningnetwork/lightning-rfc/blob/master/02-peer-protocol.md#the-open_channel-message">BOLT #2: Peer Protocol for Channel Management</a>, <a href="https://github.com/lightningnetwork/lightning-rfc/blob/master/03-transactions.md">BOLT #3: Bitcoin Transaction and Script Formats</a> and <a href="https://github.com/lightningnetwork/lightning-rfc/blob/963b10311383f97e2a72f94e867c1111dd8e8e77/05-onchain.md#on-chain-htlc-output-handling-our-offers">BOLT #5: Recommendations for On-chain Transaction Handling</a> explain it in technical detail.</li><li>Rene Pickhardt, who works with Andreas M. Antonopoulos to write the book, <a href="https://github.com/lnbook/lnbook">Mastering the Lightning Network</a>. He has helped to explain the <a href="https://bitcoin.stackexchange.com/a/89544/82834">general process of the transaction</a>, <a href="https://bitcoin.stackexchange.com/a/88009/82834">how the keys exchanged</a> and created <a href="https://upload.wikimedia.org/wikipedia/commons/b/b7/Introduction_to_the_Lightning_Network_Protocol_and_the_Basics_of_Lightning_Technology_%28BOLT_aka_Lightning-rfc%29.pdf">this presentation</a>, which I found very helpful.</li><li>Hongchao wrote <a href="http://hongchao.me/lightning/">Payment Channels in Lightning Network</a> which gave an overview of how the lightning network works, it’s easy to understand for readers with knowledge on Bitcoin script.</li><li>Rusty Russell(the main contributor to the lightning-RFC) has summarized the rationality behind the two-stage HTLC outputs design in his blog, <a href="https://medium.com/@rusty_lightning/the-bitcoin-lightning-spec-part-3-8-peer-protocol-for-channel-management-3de0996cd4c">The #Bitcoin #Lightning Spec Part 3/8: Peer Protocol for Channel Management</a>.</li><li>About the timelock, James Prestwich’s <a href="https://medium.com/summa-technology/bitcoins-time-locks-27e0c362d7a1">Bitcoin’s Time Locks</a> has provided great insight, in addition to the <a href="https://bitcoin.org/en/transactions-guide#locktime-and-sequence-number">Bitcoin Developer Guide</a> and Andreas M. Antonopoulos’s Mastering Bitcoin, <a href="https://github.com/bitcoinbook/bitcoinbook/blob/22a5950abfdd3dbd629c88534e50472822f0e356/ch07.asciidoc#relative-timelocks">Advanced Transactions and Scripting</a>.</li><li>I’ve set up a testing environment using <a href="https://github.com/bitcoin/bitcoin">bitcoind</a> and <a href="https://github.com/lightningnetwork/lnd">lnd</a> to help me understand the whole process. Here’s <a href="https://gist.github.com/yyforyongyu/67596108f3c60172771141de22d9a0b4">the gist of the trimmed log</a> generated from lnd, which recorded how Alice sent Bob money.</li><li>A clarification on the locking scripts. The red boxes represent the actual format of the locking script. To unlock it, you need to supply the unlocking script in the corresponding green box.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g72EoS81PXzEFGaRT2A9iw.png" /><figcaption><em>The items highlighted in green in the red boxes(locking script) are shared in public.</em></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3180e467857" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Till it’s lightning-fast — Uncover the Development of the Lightning Network]]></title>
            <link>https://medium.com/swlh/till-its-lightning-fast-uncover-the-development-of-the-lightning-network-fbd01bc0ea80?source=rss-d24242cc1c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbd01bc0ea80</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[lightning-network]]></category>
            <category><![CDATA[htlc]]></category>
            <dc:creator><![CDATA[Y.]]></dc:creator>
            <pubDate>Thu, 31 Oct 2019 13:01:42 GMT</pubDate>
            <atom:updated>2021-01-10T10:39:59.395Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Till it’s lightning-fast — Uncover the Development of the Lightning Network</h3><blockquote>A step by step guide to the development of the lightning network. It is assumed that you have a good understanding of the concepts of UTXO, Bitcoin Script, and digital signature. Otherwise, please check part one, <a href="https://blog.goodaudience.com/till-its-lightning-fast-uncover-bitcoin-transactions-9c2a5cc94144">Till it’s lightning-fast — Uncover Bitcoin Transactions</a>.</blockquote><p>The idea of the lightning network is to create a system aside from the Bitcoin network. As the transactions in the Bitcoin network are heavily yet necessarily restricted within a very limited time and space, that roughly only 2MB data can be transferred every 10 minutes, the lightning network breaks the restrictions by moving bitcoins into its network and circulating them under a different rule.</p><p>If two participants decide to join the lightning network, the first step for them is to create a multisig address to build a mutual account, i.e., open a channel between them. Once established, the channel will be maintained for transferring money within the network. If for any reason, the money needs to be pulled out into the Bitcoin network, the participants can close the channel cooperatively. Money flows from the Bitcoin network to the lightning network if people decide to open channels, and it should never flow reversely unless people want to close their channels. Generally speaking, the two anticipated scenarios when cross-layer transaction shall happen are opening and closing a channel, with the exception that, when a participant becomes unresponsive or malicious, other related participants can unilaterally close the channel.</p><h3>Build the Mutual Account</h3><p>To use the lightning network, the first step is to move some bitcoins into it. The participants will create multisig addresses together, to which the funds will be sent. For instance, Alice and Bob decide to open a channel with a total balance of 1.5 BTC, to which Alice will contribute 0.5 BTC and Bob will contribute 1 BTC.</p><p>Each of them will create a transaction to fund this channel and the money locked in this address cannot be spent unless both of them agree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*QTD6GpqV89KNURZQ3XPHCA.png" /><figcaption><em>Transaction ID and Output Number in Inputs are omitted for the sake of demonstration.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*ASf7thcmUxHMU3IRhrKVBw.png" /><figcaption><em>Transaction ID and Output Number in Inputs are omitted for the sake of demonstration.</em></figcaption></figure><p>Now consider the following scenarios,</p><ul><li>What if one of the participants refuses to cooperate?</li><li>What if Alice, or Bob, or both decide to close the channel and reclaim their money?</li><li>What if the channel balance needs to be updated? Say, Alice pays Bob 0.1 BTC for something she buys from Bob?</li></ul><p>Before tackling these issues, it should be emphasized that the lightning network shall be designed in a way that provides security while maintaining its decentralization. It should remain a trustless network like the Bitcoin network itself — you don’t rely on the integrity of anyone or any organization to successfully transfer money. As such, a more sophisticated design using Bitcoin Script is needed. <strong>Unlike the Bitcoin network, where security relies on computation power, the lightning network will secure itself by introducing punishments in its system</strong>.</p><p>Let’s solve the funding issue first. Keep in mind that, a layer-one transaction is done in three steps,</p><ol><li>Create the transaction;</li><li>Sign the transaction, or, in a more general term, provide the unlocking script;</li><li>Broadcast the signed transaction;</li></ol><p>Maybe there’s a genius design we can devise in-between the steps?</p><h4>Funding without Signing</h4><p>Alice and Bob can create the same transactions aforementioned <strong>without</strong> signing them. The purpose of staying unsigned is to leave room for exit in case anyone refuses to cooperate. Because the transactions are unsigned, no one has committed to anything thus no harm can be done at the moment. By referencing the unsigned transactions, Alice and Bob can create a new transaction to decide where the funds locked in the multisig address should go. In the current situation, it should give 0.5 BTC to Alice and 1 BTC to Bob.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*Fx3TxJCM6A0MrMfR7tbCUQ.png" /></figure><p>Once created, two questions relating to this transaction should be asked,</p><p>1. Should they sign the new transaction? Yes. At this moment, no one is risking losing money. If Alice signed the transaction but Bob refused, she could immediately abort the cooperation at no cost and vice versa.</p><p>2. Should they broadcast the new transaction? No. The purpose of the new transaction is to prevent loss caused by unresponsive participants. Unless the other side becomes unresponsive, or the participants decide the close the channel, this new transaction shall never be broadcasted.</p><p>What should be signed and broadcasted instead is the original funding transaction, once Alice and Bob each have a copy of the fully signed new transaction. This new transaction is functioning similarly to the security deposit when renting an apartment — you place it to show your commitment to the contract and get refunded when the contract is voided. Thus, this new transaction is often referred to as the commitment transaction.</p><p>To summarize, the procedure for Alice and Bob to securely open a channel is as follows,</p><ol><li>Alice and Bob each create a funding transaction without signing it.</li><li>Alice and Bob create and sign a commitment transaction based on the funding transaction. For instance, Alice creates the commitment transaction, signs it, sends it to Bob, and Bob will send it back with his signature. Or they could exchange their signatures for this particular transaction. Either way, the result is that they both have the same spendable commitment transaction.</li><li>Alice and Bob will broadcast their funding transactions.</li></ol><p>Once their funding transactions are confirmed, the channel would be funded and they need to find a way to send bitcoins. However, before crafting the Bitcoin Script to make the balance update feasible, a crucial question here is, how can we create the funding transaction?</p><h4>The Alternative — Unilateral Funding</h4><p>Instead of the dual funding process shown above, the actual implementation of the lightning network uses unilateral funding by applying a clever twist in how the funding transaction is signed and broadcasted. To begin with, either participant can be the funder. Maybe Alice decides to purchase from Bob, she can treat the payment as the funds to open a channel with Bob. Later on, when Bob makes a purchase from others, he can then use the money in the channel without interacting with the Bitcoin network. As the number of channels increases, every participant will end up having some balance in its account, making it equivalent to have dual funding in the first place.</p><p>If Alice was to be the initial funder, it’s critical to ensure that when Bob becomes unresponsive, her funding transaction is recoverable.</p><p>When constructing transactions in Bitcoin, it’s the referenced <em>transaction ID</em> and the <em>output number</em> are needed in the input sections. Hence, it’s perfectly safe for Alice to create her funding transaction without broadcasting it first, and share her funding <em>transaction ID</em> and <em>output number</em> with Bob. When Bob gets the information, because he doesn’t have the signature from Alice, there’s nothing he can do with Alice’s funding transaction but to create a commitment transaction, which will refund Alice the money. The steps are summarized as follows,</p><ol><li>Alice creates a funding transaction, signs it, and shares the <em>transaction ID</em> and <em>output number</em> with Bob.</li><li>Alice and Bob create and sign a commitment transaction based on the funding transaction’s ID and <em>output number</em>. Notice that the funding transaction puts Alice’s money into a multisig address, which requires both Alice and Bob’s signatures if they want to send it back to Alice using the commitment transaction.</li><li>Alice broadcasts her funding transaction. At this point, if Bob becomes unresponsive, Alice can broadcast the commitment transaction to recover her funds.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*lfCFrJOgNjseyL1J401v5A.png" /><figcaption><em>Alice’s funding transaction remains unchanged. However, she won’t broadcast it, nor share the signed transaction with Bob, but only give Bob the </em><strong><em>transaction ID</em></strong><em>(00) and the </em><strong><em>output number</em></strong><em>(0).</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*g1NNEakr1a8t_rJbcSdghg.png" /></figure><p>This unilateral funding scheme removes the risk of fund loss for the funder, thanks to how Bitcoin spends a UTXO in its transactions. Although the scheme can be further expanded into dual funding, <a href="https://github.com/lightningnetwork/lightning-rfc/blob/master/02-peer-protocol.md">the actual lightning protocol</a> chose the unilateral funding. While not explicitly explained, the reason might be it requires less communication between nodes if funded unilaterally. As for the dual funding, there is an <a href="https://github.com/lightningnetwork/lightning-rfc/pull/524">ongoing discussion</a> on how to implement it.</p><h3>Update Channel Balances</h3><p>Now we have an account that is terminable, how about making updates? Alice has put down 0.5 BTC to open the channel, she will send 0.1 BTC to Bob in exchange for his laptop, how should they do that within the lightning network?</p><p>A trivial solution would be that Alice and Bob can create new transactions to reflect their latest balance.</p><p>For Alice, she will create a transaction as follows, sign it, and send it to Bob. Because it’s already signed by Alice, Bob can sign the transaction and broadcast it at his will.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oELum8eMIX0pFLj6g7QDnQ.png" /><figcaption><em>Notice that we are referencing Alice’s funding transaction, not the commitment transaction.</em></figcaption></figure><p>For Bob, it’s the same except that he will sign and send the transaction to Alice. Currently, both of the participants have two valid transactions in parallel, together we’ve seen five transactions so far, listed as follows,</p><ul><li>The funding transaction from Alice, which has been broadcasted already;</li><li>The commitment transaction for Alice, which gives her money back, we label it TX A1.</li><li>Bob also has a copy of the commitment transaction, we label it TX B1.</li><li>The newly created transaction for Alice, which updates the balance and gives Alice 0.4 BTC and Bob 0.1 BTC, we label it TX A2.</li><li>Bob also has a copy of the newly created transaction, labeled as TX B2.</li></ul><p>The transactions are simplified as follows,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0TKvmDS30fPZ51--T0mstg.png" /></figure><p>All four transactions are valid before entering the Bitcoin network and have equal chances of being accepted by the miners if broadcasted simultaneously. If you find it confusing, think of Bitcoin as your uncle Tom, who is a bookkeeper that updates the ledger based on the firstly heard transaction and discards the later ones.</p><p>In the current case, speaking as economically rational beings, it would be Alice’s best interest to broadcast TX A1 to steal the 0.1 BTC she promised to pay Bob. For Bob, he’d rather broadcast TX B2 since he will get 0.1 BTC instead of nothing. If the two transactions are broadcasted at the same time, it’s a fifty-fifty chance that this is a fair trade, which is considered unacceptable.</p><p>How can we solve the problem? Specifically, how can we ensure that all the participants always broadcast the latest transaction but not the older ones?</p><p>Before moving on, let’s recall the types of transactions here as it’s easy to get perplexed when looking into all the transactions that happened in the lightning network.</p><ul><li>If the transaction has nothing to do with the lightning network, in other words, it only happens in the Bitcoin network, then it’s called the layer-one transaction.</li><li>If the transaction will bring money from the Bitcoin network into the lightning network, i.e., open a channel, or bring money from the lightning network to the Bitcoin network, i.e., close a channel, then it’s called the cross-layer transaction as it’s interacting with both networks.</li><li>If the transaction is meant to stay in the lightning network, then it’s called the layer-two transaction. Although, if a layer-two transaction is maliciously or accidentally broadcasted to the Bitcoin network, it becomes a cross-layer transaction. The lightning network is all about making sure layer-two transactions stay uncrossed.</li></ul><p>Essentially, transactions made in the lightning network can legitly be broadcasted into the Bitcoin network, which means the layer-two transaction can be viewed as a specialized layer-one transaction. Because the Bitcoin network is slow and the lightning network is fast, the whole design is to make sure layer-one transactions happen as infrequently as possible.</p><h4>Upgrading the Locking Script</h4><p>Previously, all the locking scripts involved simply applied a multisig function. Now we want to see if we could find a secure way to update the balances by manipulating the output sections in those transactions. The goal is straightforward, we will implement punishment on the cheaters, <strong>which are defined as anyone who broadcasts old transactions</strong>. Without diving into various possible ways of punishment, what the lightning network uses is to make the adversary lose its money once the other side notices the malicious activity within a time window.</p><p>Back to our example, if Alice tries to broadcast TX A1, which credits her 0.5 BTC, we want to incorporate a design so that Bob will have enough time to notice and act upon by taking all Alice’s money as a punishment.</p><p>And the <a href="https://en.bitcoin.it/wiki/Timelock">timelock</a> comes into play, particularly, OP_CHECKSEQUENCEVERIFY. What it does is to begin the countdown when the transaction is broadcasted(or more precisely, accepted by the miners) and lock the funds until the specified time range has passed. If a transaction with 40 days sequence timelock is broadcasted today, then it cannot be spent until 40 days later. If it was broadcasted a year later, then it cannot be spent until a year plus 40 days later. This relative timelock can be incorporated into our new locking script,</p><ul><li>Alice can broadcast TX A1 to claim her money in case Bob becomes unresponsive.</li><li>She has to wait for 2 weeks before she is able to spend the UTXO presented in TX A1 if broadcasted.</li><li>If Bob is not unresponsive and finds Alice has broadcasted TX A1, he can take all the money as punishment to her.</li></ul><p>The upgraded TX A1 looks like(we only focus on the output sections),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWqWxFITNSgiSgL2xGSBow.png" /></figure><p>If Alice tries to make a cross-layer transaction on TX A1 she cannot get the money until two weeks have passed, which is enforced by a timelock. Meanwhile, if Bob monitors the Bitcoin network and finds out TX A1 has been broadcasted, he can immediately spend the 0.5 BTC.</p><p>The current design will make sure if an older transaction was broadcasted, Alice’s money will be taken as a penalty. On the other hand, it grants Bob too much power since his mere signature can spend all the money, which encourages him to be the bad guy (<a href="https://www.youtube.com/watch?v=FxQTY-W6GIo">when your fans become your haters</a>). The intention of having Alice being able to get her 0.5 BTC back is to protect her from suffering from an unresponsive participant. Nonetheless, Bob will be motivated to trick Alice into broadcasting it by deliberately being unresponsive and take all the money thereafter.</p><p>We have to escalate our design.</p><h4>Much keys, many confusion — the Historical RSMC</h4><p>When we use phrases like <em>Alice’s signature</em>, what we are referring to is a signature generated by one of the keys controlled by Alice. There is the concept of Alice’s signature, while in essence, there is always a private key creating this signature. On the other hand, Alice can create as many private keys as needed. This is important because it’s an integral property that can diminish the advantage for Bob created by the previous design.</p><p>Instead of asking for Bob’s signature in the locking script, a multisig function is applied to stop Bob from stealing the money. When the participants agree to update their balances by creating new transactions, the private keys specified by the multisig function from the old transactions are exchanged.</p><p>For the sake of demonstration, the private keys are named to be kept on track. As a starting point, Alice will generate four private keys, A1, Rick, Batman and Tom. For Bob, respectively, B1, Morty, Robin and Jerry.</p><p>For Alice, the new TX A1 looks like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iHX6ULAnQd6Dr0xX269S9A.png" /></figure><p>For Bob, the locking script in TX B1 is simple as he has no motivation to broadcast it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUQq1Isws61EIRjj_TLpDQ.png" /></figure><p>By applying a multisig function in TX A1, Bob’s advantage has been taken away. If no updates are made, i.e., TX A2 and TX B2 do not exist at the moment, Alice’s fund stays protected even if Bob becomes unresponsive because he doesn’t have the key Rick. If they want to further update their balances, they can create new transactions with similar locking scripts. <strong>During the creation, they will exchange their private keys specified in the last transactions</strong>. Particularly, Alice will send Bob the private key Rick when creating TX A2. This move is a game-changer because it destroys Alice’s motivation to broadcast TX A1, as doing so will cause her to lose all the money to Bob since Bob will use Rick and Morty to unlock the script.</p><p>For Alice, the new TX A2 looks like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eTuCv3KPc5shQuAW7g9V9w.png" /></figure><p>And for Bob, TX B2 is similar,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vw6xsWxRO0AbrXQ7c9xl9Q.png" /></figure><p>If Alice decides to make another update that pays Bob 0.2 BTC, the steps are as follows,</p><ol><li>Create new transactions. Both Alice and Bob will generate new private keys to create similar transactions shown above. The new transactions, TX A3 and TX B3 will credit Alice 0.2 BTC and Bob 0.3 BTC.</li><li>Exchange old private keys. Alice will give Bob the private key Batman, and Bob will give Alice the private key Jerry. This way, no one will be interested in broadcasting old transactions as the other side will take all the money.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qn4_hlhNNPzfQAQOCANcg.png" /></figure><p>Again, Bob has no interest in broadcasting the older transaction TX B2. If Alice decides to cheat by broadcasting TX A2, she will have to wait for two weeks before she could spend the money. However, because Bob has the private key Batman, which was given by Alice when updating their balances, and Robin, which was controlled by him, he can spend the money immediately. It’s Alice’s best interest to not broadcast an older transaction, and Bob must monitor the blockchain to check whether Alice has cheated or not. The problem is solved, as long as everyone is acting out of their best interests, no one will cheat. This sophisticated, economical incentive-driven design is what’s called RSMC, Revocable Sequence Maturing Contract, which serves as the inspiration for the development of the lightning network.</p><p>As its name indicates, it’s revocable because a layer-two transaction can be replaced by a newer one. It uses the timelock function OP_CHECKSEQUENCEVERIFY, so there is a sequence, which represents the time in the blockchain(<a href="https://en.bitcoin.it/wiki/NLockTime">as in block height or timestamp</a>). Because the money is locked in time, it’s maturing till it becomes spendable when enough time has passed. Together this design was given the name Revocable Sequence Maturing Contract.</p><p>RSMC has its limitations as it can only serve two participants at a time. What we want is to expand the network so that people can make payments on the lightning network seamlessly. With a little tweak on RSMC, we will reach the foundation of the lightning network, the HTLC, Hashed Time Lock Contract.</p><h3>Hashed Time Lock Contract</h3><p>Imagine we have three participants and two channels. One channel is open between Alice and Bob, the other is open between Bob and Charlie. If Alice wants to send Charlie some coins, there are two options,</p><ol><li>Alice and Charlie can open a channel and make the transaction;</li><li>Alice and Charlie can take advantage of the current channels.</li></ol><p>The first approach seems to work but it doesn’t solve the problem when the number of participants grows. Let’s do the simple math.</p><ul><li>For 3 participants, we need 3 channels;</li><li>For 4 participants, we need 6;</li><li>For 10 participants, we need 45;</li><li>For 1000 participants, we need 499,500 channels!</li></ul><p>That is just too many channels(the formula for calculation is Cn2). Compared to the alternative in which Alice and Charlie ask Bob for help, this approach is much less favorable and feasible. Since they each have already built a channel with Bob, why not further develop it into a route to transfer the money back and forth?</p><h4>About the Cryptographic Hash Function</h4><p>To implement a route among channels, we need to borrow a tool from cryptography — a cryptographic hash function and understand its instincts and properties.</p><p>A hash function simply maps any inputs into a fixed size output. For example, a stupid hash function can be, take a word and group them by the first letters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m81mPXBusdD8X59SA62erQ.png" /></figure><p>The inputs are the words(<em>apple</em>, <em>agent</em>), and the outputs are the letters(<em>a</em>). Another naive hash function can be a simple <a href="https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/what-is-modular-arithmetic">modulo operation</a>. For instance, we can define a hash function that accepts any arbitrary number as inputs, mod them by <em>7</em> to produce the outputs. All the outputs will have a fixed range between 0 and 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VjYos7y4bWm511cPWsQjLg.png" /></figure><p>These hash functions are used here to demonstrate the two properties of a cryptographic hash function,</p><ul><li><a href="https://en.wikipedia.org/wiki/One-way_function">One-way function</a>, meaning given the output, it’s hard to find the input. If the output is <em>1</em>, it’s difficult to find whether the input value is <em>2</em>, <em>9</em>, or any number that produces the remainder <em>1</em>. Or, given the letter <em>a</em>, it’s difficult to determine whether the input is <em>apple</em> or <em>agent</em>.</li><li><a href="https://en.wikipedia.org/wiki/Collision_resistance">Collision resistance</a>, meaning it’s hard to find two inputs that produce the same output. Our dumb hash functions don’t have this property as it’s easy to find that both <em>2</em> and <em>9</em> produce the same result <em>2</em> and both <em>apple</em> and <em>agent</em> are hashed into the letter <em>a</em>.</li></ul><p>Cryptographic hash functions achieved these properties by applying complicated mathematical functions. Without going down the rabbit hole, the instincts behind their design can be easily understood. To build a one-way function, it requires a mathematical function that is easy to verify when answers are supplied, but hard to solve. Or, more precisely, it is harder to find a valid answer than to verify it. In cryptography, being harder implies more computing power and time are needed. Factorization is a good example. Consider the following,</p><ul><li>Challenge one, find two numbers that can be multiplied into 2449.</li><li>Challenge two, confirm that 31 x 79 equals 2449.</li></ul><p>It’s not hard to conclude that solving challenge two is easier than challenge one. Though cryptography relies on complicated mathematical models(e.g., <a href="https://en.wikipedia.org/wiki/Discrete_logarithm">discrete logarithm</a>), the very principle stays unchanged. On the other hand, to achieve collision resistance, the size of possible unique outputs needs to be substantially increased so that different inputs are less likely to collide to generate the same output. One of the commonly used algorithms, SHA256, produces 2²⁵⁶ possible outputs, which is <a href="https://www.youtube.com/watch?v=S9JGmA5_unY">an astronomical number that’s beyond imagination</a>.</p><p>A simple use case of cryptographic hash functions is to hide a secret and later reveal it(<a href="https://en.wikipedia.org/wiki/Zero-knowledge_proof#targetText=In%20cryptography%2C%20a%20zero%2Dknowledge,they%20know%20the%20value%20x.">zero-knowledge proof</a>). A bizarre example would be, Alice claims she is the first person ever knows a magic note that will make people billionaires but Charlie doesn’t buy it. If Alice tells Charlie the message directly, Bob will jump out to claim that he owns the authenticity. To avoid intellectual property theft, Alice will apply a cryptographic hash function on the magic note, share the results with everyone, and claim she knows the secret note without revealing it first.</p><p>She uses SHA256 to <a href="https://cryptii.com/pipes/hash-function">hash her secret note, which generates an output</a>,</p><pre>8816cee3feb85ccaad0557ffb2f6b38947a27bea4ccdea1835fded53ad71c31a</pre><p>Alice then shares it with Charlie. Charlie can now ask Bob to show the original message corresponding to this output. Of course, Bob doesn’t know the answer, nor can he fake it. Now it’s safe for Alice to reveal the secret note,</p><blockquote>money is a social construct</blockquote><h4>A Naive Design — Hide and Reveal a Secret</h4><p>It would be naive to simply ask Bob to pass the money if Alice wants to send 1 BTC to Charlie. Bob would have all the reasons to take the money himself. To solve this issue, a cryptographic hash function is applied in the design. If Alice wants to send 1 BTC to Charlie, it’s up to Charlie to initiate a payment request. Here’s what he needs to do,</p><ol><li>Charlie will generate a random number r and keep it to himself as a secret.</li><li>Charlie will apply the cryptographic function to hash the secret r, and send the hashed result R along with the request <em>charge Alice for 1 BTC</em> to Bob.</li><li>Charlie will wait for Bob to pay him 1 BTC.</li></ol><p>Once Bob receives the payment request along with the hashed value R, he will forward them to Alice and ask her to send him 1 BTC by making a transaction with the following locking script,</p><ul><li>If 3 days passed, and the signature from Alice is presented, then Alice gets the money back.</li><li>Else, if the signature from Bob and the value can be hashed into R(which is the secret r) are presented, then Bob gets the money.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxo42IhRplJuhE54U5BN9Q.png" /></figure><p>If Bob can get the secret r from Charlie then he will be able to unlock the transaction and spend the UTXO. Otherwise, once 3 days passed, Alice will be able to get her 1 BTC back. The 3 days condition is an absolute timelock differing from the previous one. It allows Alice to take her money back if Bob cannot provide the secret in 3 days. Now that Bob is resting assured he will get the 1 BTC from Alice if he learns the value of r, he can then send Charlie 1 BTC by creating a similar transaction with the locking script as follows,</p><ul><li>If 2 days passed, and the signature from Bob is presented, then Bob gets the money back.</li><li>Else, if signature from Charlie and the value can be hashed into R are presented, then Charlie gets the money.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ExkqGX4UrrirmDzBoNpUmQ.png" /></figure><p>To claim the money, Charlie has to reveal the secret value of r to Bob. Once Bob knows the value of r, he can spend the transaction created between him and Alice. The length of the locked time decreases as it moves closer to the final recipient, i.e., Charlie has 2 days to reveal the value r, while Bob has 3 days so that each participant will have enough time to act. The act of revealing the secret r to Alice from Bob proves that he has sent his 1 BTC to Charlie because that’s the only way Bob learns what the value is.</p><p>But can anyone cheat?</p><p>Alice’s money is solely constrained by the 3-day period. Once the timelock is unlocked, Alice is free to spend the money no matter Bob has the secret or not. As for Bob, his knowledge of the secret r exclusively determines the ability to spend the output. Even if 3 days have passed, the money remains spendable for Bob as long as he can provide the secret r. Regardless of updating balances, the current design seems fine if,</p><ul><li>Bob will spend his UTXO as soon as he learns the secret r , which means he will broadcast this transaction within 3 days if possible.</li><li>Alice will spend her UTXO as soon as 3 days passed, which means she will broadcast this transaction 3 days later if applicable.</li></ul><p>However, it becomes a cross-layer transaction and hits the Bitcoin network if a layer-two transaction is broadcasted, which violates the principle of the lightning network — to keep the transactions within it as much as possible. Therefore, a new design that has similar effects produced by an RSMC is needed — we don’t rely on people behaving honestly, rather, we will punish those who don’t.</p><p>With these backgrounds, it’s time to check the grand design — <a href="https://medium.com/@yyforyongyu/till-its-lightning-fast-uncover-the-lightning-network-transactions-f3180e467857">the actual implementation of the lightning network</a>.</p><h4>Notes and References</h4><ol><li><a href="http://lightning.network/lightning-network-paper.pdf">The Bitcoin Lightning Network: Scalable Off-Chain Instant Payments, Joseph Poon, Thaddeus Dryja</a></li><li><a href="https://github.com/ElementsProject/lightning/blob/master/doc/deployable-lightning.pdf">Reaching the ground with lightning, Rusty Russell</a></li><li><a href="https://en.wikipedia.org/wiki/Cryptographic_hash_function">Cryptographic Hash Function</a></li><li><a href="https://tik-old.ee.ethz.ch/file/716b955c130e6c703fac336ea17b1670/duplex-micropayment-channels.pdf">A Fast and Scalable Payment Network with Bitcoin Duplex Micropayment Channels, Christian Decker, Roger Wattenhofer</a></li><li><a href="https://github.com/lightningnetwork/lightning-rfc">The Lightning Network Specifications</a> has all the implementation details. The actual locking scripts used are specified in <a href="https://github.com/lightningnetwork/lightning-rfc/blob/master/03-transactions.md">BOLT #3: Bitcoin Transaction and Script Formats</a></li><li>I’ve set up a testing environment using <a href="https://github.com/bitcoin/bitcoin">bitcoind</a> and <a href="https://github.com/lightningnetwork/lnd">lnd</a> to help me understand the whole process. <a href="https://gist.github.com/yyforyongyu/d2870b422c86f62930790e1c64f8689a">Here’s the gist of the trimmed log generated from lnd, which recorded how Alice and Bob opened a channel.</a></li><li><a href="https://github.com/bcongdon/awesome-lightning-network">A curated list of awesome Lightning Network projects for developers and crypto enthusiasts</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbd01bc0ea80" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/till-its-lightning-fast-uncover-the-development-of-the-lightning-network-fbd01bc0ea80">Till it’s lightning-fast — Uncover the Development of the Lightning Network</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Till it’s lightning-fast — Uncover Bitcoin Transactions]]></title>
            <link>https://medium.com/@yyforyongyu/till-its-lightning-fast-uncover-bitcoin-transactions-9c2a5cc94144?source=rss-d24242cc1c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c2a5cc94144</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[lightning-network]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[bitcoin-script]]></category>
            <category><![CDATA[utxo]]></category>
            <dc:creator><![CDATA[Y.]]></dc:creator>
            <pubDate>Fri, 27 Sep 2019 22:41:11 GMT</pubDate>
            <atom:updated>2019-11-04T07:39:40.607Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Till it’s lightning-fast — Uncover Bitcoin Transactions</h3><blockquote>To understand how the lightning network works, one needs to first understand how a Bitcoin transaction works, what UTXO and Bitcoin Script is. A careful design thereafter with some sophisticated coding, an incentive-oriented network named the lightning network is then shown.</blockquote><h3>Overview — Two Systems and Three Transactions</h3><p>The motivation behind the creation of the lightning network is straightforward. If you cook two eggs for breakfast, you won’t drive to Costco every morning to purchase the two eggs. Instead, you’d buy dozens of eggs in stock, one at a time, to avoid the nuisance of going to Costco on a daily basis. Bitcoin is intrinsically slow as a money transfer service, relatively speaking. <a href="https://en.wikipedia.org/wiki/Bitcoin_scalability_problem">It can only serve roughly seven transactions per second</a>, which is extremely slow compared to other payment networks such as Visa or Mastercard. To tackle this issue, analogous to food stocking, we can stock some coins off the Bitcoin network, building a payment system thereafter, which leads us to the lightning network.</p><p>There are two systems to be focused on here, one is the original Bitcoin network, the other is the lightning network. Both systems are circulating bitcoins by making different types of transactions, depending on where the money flows, they can be categorized into,</p><ul><li>Within the Bitcoin network, which is how most bitcoins are currently transferred, we call it the Layer One Transaction.</li><li>Within the lightning network, which is a faster way of transferring bitcoins, we call it the Layer Two Transaction.</li><li>In-between the lightning network and the Bitcoin network, which we will refer to as the Cross-Layer Transaction. Later on, as we will see, the cross-layer transaction is essentially a layer one transaction, with the lightning network as an individual entity of the blockchain.</li></ul><p>We will talk about the three types of transactions thoroughly throughout this series.</p><h3>The Layer One Transaction</h3><p>Bitcoin is described as a distributed ledger, which means it’s a ledger book recording everyone’s account information and everyone has a copy of it. But what’s in it? How is it recorded? In what format? Before moving forward, a few things to be noted here, so we know where to put our focus. We don’t care how bitcoins are generated, i.e., we won’t cover how mining works but assume there is an initial account with some money in it(<a href="https://blog.goodaudience.com/https-medium-com-yyforyongyu-using-blockhash-as-a-randomness-source-b68d506450a7">if interested, you can read how mining works here</a>). We care less about why cryptography works than how well it has stood the test of time. It is postulated that the cryptographic functions adopted by Bitcoin are legit, which, by the way, no scientists or mathematicians can prove to be foolproof. <a href="https://www.youtube.com/watch?v=HDsSbcoBV7w">It’s the fact that we have very smart people who tried but failed to break them gives us the confidence that those cryptographic functions work</a>. We don’t care about these topics here because you can perfectly understand how the lightning network works without the knowledge ahead. However, they will be mentioned as what they are, not why/how they are and, I guess you have to take them for granted at the moment. A more thorough introduction to Bitcoin will be presented as a series later.</p><h4>What is UTXO anyway — Tree and Linked List</h4><p>Ever wonder how a computer stores its data? It cannot put down a piece of information arbitrarily, just like books cannot be thrown randomly in the library. A computer needs to arrange the data in a way so that it can manage them better. This is where data structures come into play. Computers need to place the data in an orderly fashion by using a different set of predefined formats based on specific circumstances. The two formats, i.e., the data structures we need to understand are linked list and tree.</p><p>A tree structure is like a family tree when we focus on the mothers and their children.</p><figure><img alt="A family tree" src="https://cdn-images-1.medium.com/max/562/1*6z3U9X-fTuMCKJSZoeAf7g.png" /></figure><p>In the graph shown above, in computer science terms, the top item is called the ‘root’ of the tree(grandmother), the bottom items are called the ‘leaves’ of the tree(your cousins, siblings and you). A linked list is a special tree, which can be viewed as a piece of information taken from the tree, traversing one of its leaves back to its root. For example, if you want to list all the birth givers contributed to you, it will be like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*wBMmnHTnPGU6W-_ERIlgDw.png" /></figure><p>Which can be represented like a list with chained items,</p><figure><img alt="A linked list" src="https://cdn-images-1.medium.com/max/321/1*AwFWNokQ7YvT0aIKvprM3w.png" /></figure><p>Now let’s see how Bitcoin applies the tree and linked list in its design.</p><p>Typically, when you do a bank transfer, say, you want to send Alice 100 bucks. What happens is that the money will be deducted from your bank account and Alice’s account balance will be increased accordingly. It’s treated as if the money flew from one account to another, which is not the case in Bitcoin. In Bitcoin, you don’t have accounts, you only have records of transactions. For instance, Bob, as a miner, has a record of 25 bitcoins belonging to him, the record will be naively written as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*RkJrWkDneGrL1h9eWItRKg.png" /></figure><p>When Bob decides to spend his money, he will have to treat it as the root and make a tree structure out of it. If he wants to buy a Tesla from Elon at the cost of 1 BTC, he will make three new records,</p><ul><li>the amount paid to Elon, which is 1 BTC;</li><li>the transaction fees paid to the miners, we’ll assume it’s 0.00001 BTC;</li><li>the rest of the money transferred back to himself as the change, which is 23.99999.</li></ul><p>The records will be put into a tree,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*z3i9uLP3NU8e8Vy-Tth6_g.png" /></figure><p>Once this new tree is made, Bob will broadcast it, which means to tell other Bitcoin ledger owners(Bitcoin nodes) to update their books so that everyone knows Bob has sent Elon 1 BTC. But how do we ensure others won’t cheat? It seems that there are no protections against rewriting the records made, can others simply change the owners to themselves thus steal the money? That’s a problem and we will get back to it later.</p><p>Once Elon heard the broadcast and was happy with the <a href="https://en.bitcoin.it/wiki/Confirmation">number of confirmations</a> he got, he can now ship the Tesla to Bob. Ok, <a href="https://www.youtube.com/watch?v=a8uyilHatBA">now Elon’s bored</a>, he decides to buy some marijuana from two dealers, 50 Cent and Snoop Lion, pays to each 0.001 BTC, Elon will update the record the way Bob just did, making a tree using the 1 BTC as the root, which looks like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*_U_hZ58Nv-AfoAf_Y0KrCw.png" /></figure><p>and the full ledger now looks like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cl6WhCXE409f77gBTPtDng.png" /></figure><p>If Bob, at this moment, decides to cheat by spending the record of 25 BTC again, can he do that? He can, of course, draw the tree any way he likes. However, since everyone already has a copy of the original records stating that Bob has spent that 25 BTC, if Bob tries to broadcast a forged record the whole network will reject it as it differs from the ‘real’ history. To successfully make a layer one transaction it always involves three steps.</p><ol><li>create the transaction, which is to draw an updated version of the old tree.</li><li>sign the transaction, which is to claim that the money you spend belongs to you. Currently, we are using the <em>Owner</em> field to indicate ownership. Later on, as we will see, we need to put our signatures in the records to spend the money.</li><li>broadcast it, i.e., send it to the Bitcoin network so that others can validate, confirm and update their records.</li></ol><p>This process is like transferring money using checks. Anyone can write the amount in the check, while it’s only valid when signed by you, and the recipient needs to deposit it into an ATM to finalize the payment. You can, although unnecessary, write and sign as many checks as you want, as long as there is only one check gets deposited. In Bitcoin, you can create as many transactions as you want from the same record without broadcasting them. Once broadcasted, one and only one transaction will be accepted(confirmed). This feature is what makes the lightning network possible, which, most of the time, what the lightning network does is to create transactions without broadcasting them.</p><h4>A minor modification</h4><p>In real Bitcoin transactions, we won’t explicitly make a record of how much transaction fees to be paid. Rather, the transaction fee is implicitly given. When new transactions are made, we enforce one rule that the total amount of bitcoins from the new records cannot be greater than the old ones. The transaction fees paid is calculated by subtracting the new total from the old. In Bob’s case, it’s 25–23.99999 — 1 = 0.00001 BTC. An updated version of the ledger data is shown below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPCyho2abAi1eMjDlLWemQ.png" /></figure><p>Technically, this also means that you can choose to pay zero transaction fee, while no one’s doing it because it would cause your transaction to hung in the air forever.</p><h4>The Inputs and Outputs</h4><p>So far we’ve only mentioned the individual records and the tree they form. But what is a transaction anyway?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*9W-S8HSPAlPJUdIUEm4Scw.png" /></figure><p>In our case, if Bob decides to spend Bitcoin again, he will follow a procedure as below,</p><ol><li>He will search in the whole tree to find a record that a) belongs to him(Owner: Bob) and b) he hasn’t spent yet, in our example, it’s 23.9999 BTC.</li><li>He will treat the record as the root and draw a new subtree upon it, whose leaves are the records addressed to the recipients.</li><li>He will broadcast the newly created subtree into the network, once it’s validated, the subtree will be included in the whole tree, which is the ledger book shared by everyone.</li></ol><p>Based on our example, the subtree is the closest thing to represent a transaction. If we view the process as a pipeline, then we can treat the unspent records as inputs, the newly created records as outputs, a transaction is then a piece of information converting the inputs and outputs, answering the question of where the money is from and where the money is going. This also indicates that we can have multiple inputs at the same time. If Bob has multiple unspent records in the tree, it would be a tedious experience to use the money if he is restricted to spend one record at a time. So while the structure of the ledger remains the same, the transaction data is different, as shown below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g05UnKd25V4FcCLS5ER6pA.png" /><figcaption>This is Bob’s transaction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*zD8wt1JulUiMlEGlhTmhAg.png" /><figcaption>This is Elon’s transaction</figcaption></figure><p>In case you are wondering how Bob got his money, here’s a coinbase transaction that generates bitcoins to the system,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PnWKJT6B0IZl30fuqHv8xg.png" /><figcaption>A coinbase transaction</figcaption></figure><p>For anyone who spends Bitcoin, he/she will always have to find the unspent record from the outputs section in a transaction. In Bitcoin, the concept of accounts doesn’t exist. Rather, a spendable unit is one output from a transaction that hasn’t been spent yet, so we name it the Unspent Transaction Output, or in short, UTXO. On the other hand, the concept of Record ID can be thrown away at this stage. If you check from Transaction 00 to Transaction 02, all the outputs are sitting in a transaction, all the inputs are references of the outputs from an older transaction, thus it’s unnecessary to give each output unique ID. Rather, we can simply reference the output by stating a sequence number in a transaction, i.e., <em>the second output in </em><em>Transaction 00</em> or <em>the third output in </em><em>Transaction 02</em>. This gives us a final version of the transaction data,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zQE4ar0O3lAOoptRoFoQFA.png" /><figcaption>This is Bob’s transaction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJ6S-DKQwnbAhcUjO7b3Dw.png" /><figcaption>This is Elon’s transaction</figcaption></figure><p>There you have it, a transaction-based system called Bitcoin. Now we will dive into the details of how we can ensure the security of the transactions.</p><h4>Bitcoin Script — the Fundamentals</h4><p>In our previous example, when sending money, you simply write down the name of the recipient in the owner field, with the hope that the rest of the ledger keepers won’t manipulate it. This is not how the world works. Traditionally, it’s impossible to build trust without a third party’s interference/supervision/administration. Bitcoin solved it by using a puzzle-solution pair, which, the sender creates a puzzle and anyone who can provide the solution gets to spend the money. For instance, if Alice wants to send Bob 1 BTC, she will use one of her UTXOs, and creates a transaction looks like the following,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*afYQ5HzG9uH7SEkK-GbzKw.png" /><figcaption>Alice sends 1 BTC to Bob</figcaption></figure><p>Once Alice broadcasts this transaction, the network will recognize that Alice’s UTXO has been spent, and whoever is able to solve the puzzle owns the money. When Bob hears from the network that Alice has made her payment, he can now delivery whatever goods/services promised beforehand.</p><p>Now if Bob wants to spend all his money and send it to Charlie, he needs to,</p><ol><li>Provide a solution to the old puzzle specified in the UTXO, which is like unlocking money that belongs to him.</li><li>Provide a new puzzle that only Charlie knows the answer to, which is like locking the money up/in using Charlie’s lock.</li></ol><p>The simplified transaction is shown below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*RzWeAYLdpD6e3hwt2i-SfA.png" /><figcaption>Bob sends 1 BTC to Charlie</figcaption></figure><p>When Charlie wants to use his UTXO, he would go through the same process. Of course, Alice’s UTXO is also from someone else(or herself), and when she uses it, she too needs to provide a solution to the specified puzzle. The full picture now looks like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*RVqkFYiQMWkDRZIohvzF-g.png" /><figcaption>A list of UTXOs linked together</figcaption></figure><p>Now you have it. At this moment, you can think that a UTXO is made of three parts,</p><ul><li>A solution from the previous owner;</li><li>The number of bitcoins;</li><li>The new puzzle for the current owner.</li></ul><p>Soon we will map the three parts into the full picture of a transaction.</p><h4>Validate Transactions</h4><p>The puzzle here is functioning as a lock, ensuring it can only be unlocked by the dedicated owner. However, as a receiver, how do you know for sure you’ve got the money?</p><p>Let’s take a look at our previous example, with a simplified tree structure,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ndm8HKbYj3pCRMk87EDNDA.png" /></figure><p>If 50 cent wants to check whether the money he got from Elon is legit, he would need to focus on a linked list derived from this tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*chbfCAmq5THTieGnP_vbFg.png" /></figure><p>He needs to validate all the puzzle-solution pairs in this linked list. In descending order, it would be like,</p><ul><li>Check the solution provided by Elon(in the blue box) can solve the puzzle for Elon(in the brown box);</li><li>Check the solution provided by Bob(in the brown box) can solve the puzzle for Bob(in the gray box);</li><li>Check the solution provided by miners(which is Bob in the gray box) can solve the puzzle for miners.</li></ul><p>Once all the validation passed, he can ensure this transaction is legit. For all the ledger bookkeepers, i.e., Bitcoin nodes, whenever they hear new transactions, this is the validation process they need to have before updating their copies of data. A final step for 50 Cent is to check the puzzle to make sure the money is dedicated to him. If so, he waits a while until this transaction gets enough confirmations. Once reached, he can be certain that this money belongs to him.</p><h4>What is the puzzle, anyway?</h4><p>The puzzles could be anything as long as it’s computable. For instance, provide two numbers so that their sum equals 4, is a naive yet valid puzzle. On the other hand, questions like what is the purpose of the universe cannot be a puzzle because there is no answer to that, at least not in a deterministic fashion.</p><p>So what is the puzzle, structurally and semantically, anyway?</p><p>To understand it, the first step is to understand the language the puzzles use. When you ask the computer to do something for you, you need to speak a language that it can understand. Bitcoin lives in computers. When you want to make a puzzle in Bitcoin, you have to speak the language it understands. In this case, it’s a language named <a href="https://en.bitcoin.it/wiki/Script">Bitcoin Script</a>.</p><p>You may be hesitant to learn a foreign language at this moment while knowing just the basics enables you to grasp what makes Bitcoin so powerful. Plus, it’s a fairly straightforward language, and I will only demonstrate what it is instead of explaining the whys or the hows here, which is enough for anyone to understand how the lightning network works. If interested, <a href="https://www.youtube.com/watch?v=8FeAXjkmDcQ">here’s a good lecture</a>, and <a href="https://github.com/ChristopherA/Learning-Bitcoin-from-the-Command-Line">here is a good book</a>.</p><h4>Bitcoin Script — the magic</h4><p>On paper, when you do addition, say two plus three, you simply write,</p><p>2 + 3 = 5</p><p>In Bitcoin Script, here’s what you write,</p><p>2 3 OP_ADD</p><p>If you are like most of us, reading from left to right, top to bottom, then you may be confused with the ordering here. The order is written as such because, as a computer, it understands things differently.</p><p>One way to understand how Bitcoin Script works is to think of an image of the old school game, towers of Hanoi.</p><figure><img alt="Tower of Hanoi" src="https://cdn-images-1.medium.com/max/300/1*A42dG5EKUCd7qNM9fB7jKA.jpeg" /></figure><p>Rather than playing the original, we have a variation here. On the left stick, you have a stack of boxes that resemble the instructions in Bitcoin Script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*AxlKSYDi_cmZp3ftT-1hjg.png" /></figure><p>When Bitcoin processes its scripts, what it does is a dumb but rather strict procedure. Each time, it will take one and only one box out of the left stick and put it into the right. Depending on what the instructions say, it may do extra work with predefined rules. For example, the addition script mentioned above can be represented as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*Y8wieSKl1kOsxQmx-HPI8g.png" /></figure><p>The procedure is as follows,</p><ol><li>The computer works on the topmost box. In this case, the integer 2 is taken out and put to the right.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*QTKdfsaK29TO3VFf4X8RXw.png" /></figure><p>2. It fetches again the topmost box on the left, which is the integer 3, and put it on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*Gh34m1nShhEvE8sBG5zY2g.png" /></figure><p>3. It keeps working on the topmost box until there is none. The final box, OP_ADD, which stands for Operation Addition, is taken out and put to the right. The OP_ADD is a predefined instruction, what it does is to consume two boxes below itself, adding them together, removing them, and creates a new box to give the sum back. So we ended with a box of 5 left on the right stick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*n4KXs-36QmdtXakFld1Llg.png" /></figure><p>I’ve made a lousy GIF to demonstrate the whole process, bear with me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*3kn5uB_ceZI0jyZr0tv0qA.gif" /></figure><p>OP_ADD is one of the many predefined instructions, together we name them instruction sets, or Opcodes. <a href="https://en.bitcoin.it/wiki/Script">The full instruction sets can be found here</a>. In this post, we only care about a few which enable the lightning network to work.</p><p><em>Don’t get confused!</em></p><p><em>The language Bitcoin used is called Bitcoin Script, or Script. However, when a group of instructions is put together to form a piece of code, we call it a script. If the Opcodes in Bitcoin are put together, we also name it a script, or more specific, a Bitcoin script.</em></p><h4>The Scripts</h4><p>It’s time to uncover the puzzle and solution pair aforementioned, which served as the lock and key, written in a language called Bitcoin Script. The technical terms for them are locking script(puzzle) and unlocking script(solution). When being validated, we would put the unlocking script on top of the locking script, and run it through a Bitcoin client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*y5ZZrO1rm4pqK5htFl8TZw.png" /></figure><p>If the result turns out to be false, which is represented using the number 0, it generally means the provided unlocking script(solution) is incorrect, thus the transaction is invalid. Otherwise, if it’s true, which are any integers other than 0, you can rest assured its validity.</p><p>In our previous example, the script 2 3 OP_ADD would be a bad locking script as it returns the number 5 already, which means the validation result is always true, thus it can be spent by anyone. If Bob receives a transaction from Alice, he wants to be sure that the locking script provided by Alice can only be unlocked by him.</p><p>Such a requirement is met by using a cryptographic application named the digital signature, which is a widely used tool across the Internet today. There are four components to be focused on when talking about the digital signature,</p><ul><li>The message to be signed, which can be anything from a sentence to a document. It’s something that Bob wants to claim ownership of. In this case, it’s a UTXO sent by Alice wrapped in a transaction.</li><li>The private key, which is kept as a secret by Bob. He uses the private key to sign the message, which involves a complicated mathematical process and outputs the signature.</li><li>The signature, which is the result of signing using the private key over a message.</li><li>The public key, which has a one-to-one relationship with the private key. Each public key is mapped to one and only one private key. As its name indicates, it’s put in public so everyone knows what Bob’s public key is.</li></ul><p>Everything is placed in public except for Bob’s private key. There is a magic relationship among the original message, the signature, and the public key. Without revealing the private key, anyone can validate whether the signature is signed by the private key or not, with the knowledge of the public key and the original message. Since it’s the age of the internet, everyone’s hiding something, therefore Bob’s name won’t be shown. Instead, all he needs to reveal are his signature and his public key. In Bitcoin, the public key is his identity. And it has another name, once encoded differently, the Bitcoin address.</p><p>Let’s take a look at what we have so far. Bitcoin transactions are made of UTXOs by taking old UTXOs as inputs and create new UTXOs. To spend a UTXO, you need to provide an unlocking script to solve the puzzle places in the locking script and create new locking scripts for your recipient. Structurally, we put the unlocking script in the inputs section and the new locking script in the outputs section. A common usage is to send money to a particular receiver, which involves applying a digital signature. For example, if Bob sends Alice 1 BTC, a full transaction made by Bob now looks like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*0N9ZZjICMlFyAlAgz5p-dQ.png" /></figure><p>Aside from applying digital signatures in the scripts, people have been putting up all kinds of <a href="https://www.reddit.com/r/bitcoinpuzzles/">challenging puzzles</a>. The Bitcoin Script is indeed powerful, and the lightning network has surely taken advantage of it by incorporating an interesting design with it, which eventually makes Bitcoin transactions lightning fast.</p><p><em>A real example</em></p><p><a href="https://btc.com/37e0ab41ada62a7eddac77d47d3ce9b089cc34a1ac2d0b66bc7e00f4f9946a76">Let’s take a look at a real transaction</a>,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKIhno41LyhtRiEB8UsnYQ.png" /></figure><p>Notice the sections at the bottom, <em>Input Scripts</em> and <em>Output Scripts</em>, which are the unlocking scripts for the spent UTXOs and the locking scripts for the new UTXOs.</p><p>A detailed decoded transaction is shown as below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kz0myZgWklRMKFvKN8IbUA.png" /></figure><h4>More Gimmicks — Multisig and the Time Lock</h4><p>Among all the Bitcoin Scripts, there are three scripting functions you need to specifically pay attention to, the digital signature aforementioned, the multisig, and the time lock.</p><p>Multisig is short for multiple signatures(OP_CHECKMULTISIG), as the name suggests, is a function that involves validating with multiple signatures. It checks the presented signatures and returns true if the signatures match. Multisig behaves like the ancient <a href="https://en.wikipedia.org/wiki/Fu_(tally)">Chinese tiger tallies</a>, which is essentially a special lock that can only be unlocked if required keys are presented.</p><p>In Bitcoin, when used, the multisig function is placed in the locking script, specifying signatures needed to unlock it. In the unlocking script, the spenders would need to provide their signatures together to unlock the script so that they can spend the UTXO.</p><p>For example, if Alice and Bob decide to create a mutual account, which requires consensus to spend money from, each of them will create a new UTXO, respectively, as follows,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6PIgHpmAG-2C39F9LAxFA.png" /></figure><p>This way, a mutual account with a balance of 2 BTC is created, and it’s up to Alice and Bob’s decision on how to spend it.</p><p>Time lock functions like a timer in Bitcoin. It will check the preset date against the current time, and won’t proceed with the procedure until the given time has passed. A peculiar example would be if we decide that we won’t do the calculation of 2 + 3until the DateTime 2099/01/01 00:00:00, we would create something like, 2099/01/01 00:00:00, check time lock, 2, 3, OP_ADD which can be represented as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*Sx6IOUGN74ZKIIo03TlsiQ.png" /></figure><p>When we run this script, because the specified time 2099/01/01 00:00:00 has not been reached yet, the rest of the steps won’t proceed. One practical usage of the time lock function would be delaying a payment. If Bob wants to send Alice 1 BTC, but he doesn’t want Alice to spend it unless 1 week has passed, he could put a time constraint in the locking script,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TK6JlFkTT4a5mkSwSe9IBw.png" /></figure><p>When Alice receives this UTXO, she has to wait one week for step 1 to be validated as true, then provides her signature to spend the UTXO. In Bitcoin Script, there are several ways to achieve the functionality of a time lock. In particular, what the lightning network uses are OP_CHECKLOCKTIMEVERIFY and OP_CHECKSEQUENCEVERIFY. They almost function the same way except the former uses an absolute time(e.g., at 2019/09/23 00:00:00) provided in a Bitcoin block, while the latter uses a relative one(e.g., 3 days in the future).</p><p>With the understanding of Bitcoin UTXO and Bitcoin Script, we can now take a look at <a href="https://medium.com/@yyforyongyu/till-its-lightning-fast-uncover-the-development-of-the-lightning-network-fbd01bc0ea80">how the lightning network works</a>.</p><h4><em>References</em></h4><ol><li><a href="https://github.com/ChristopherA/Learning-Bitcoin-from-the-Command-Line">Programming with Bitcoin Core and Lightning, Christopher Allen</a></li><li><a href="https://www.youtube.com/watch?v=8FeAXjkmDcQ">Advanced Bitcoin Scripting — Part 1: Transactions &amp; Multisig, Andreas M. Antonopoulos</a></li><li><a href="https://www.youtube.com/watch?v=pQbeBduVQ4I">Advanced Bitcoin Scripting — Part 2: SegWit, Consensus, &amp; Trustware, Andreas M. Antonopoulos</a></li><li><a href="https://en.bitcoin.it/wiki/Timelock">Timelock</a></li><li><a href="https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki">BIP112</a></li><li><a href="http://lightning.network/lightning-network-paper.pdf">The Bitcoin Lightning Network: Scalable Off-Chain Instant Payments, Joseph Poon, Thaddeus Dryja</a></li><li><a href="https://www.udacity.com/course/applied-cryptography--cs387">Applied Cryptography, Dave Evans</a></li><li><a href="https://en.bitcoin.it/wiki/Script">Bitcoin Script</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c2a5cc94144" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>