Merge pull request #1 from lnbook/develop

merge main
pull/610/head^2
Gustavo Silva 3 years ago committed by GitHub
commit d78c0f1027
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -33,9 +33,10 @@ The side effects of increasing the block size or decreasing the block time with
Let us assume the usage of Bitcoin grows so that the network has to process 40,000 transactions per second.
Assuming 250 Bytes on average per transaction this would result in a data stream of 10 Megabyte per second or 80 Mbit/s just to be able to receive all the transactions.
This does not include the traffic overhead of forwarding the transaction information to other peers.
While 10 MB/s does not seem extreme in the context of high-speed fibre and 5G mobile speeds, it would effectively exclude anyone who cannot meet this requirement from running a node, especially in countries where high-performance internet is not affordable or widely available.
Users also have many other demands on their bandwidth and cannot be expected to expend this much only to receive transactions.
Furthermore storing this information locally would result in 864,000 Megabytes per day. This is roughly 1 Terabyte of data or the size of a hard drive.
Furthermore storing this information locally would result in 864,000 Megabytes per day. This is roughly one Terabyte of data or the size of a hard drive.
While verifying 40,000 ECDSA signatures per second seems barely feasible (c.f.: https://bitcoin.stackexchange.com/questions/95339/how-many-bitcoin-transactions-can-be-verified-per-second) nodes could hardly catch up initial sync of the blockchain.
====
@ -130,10 +131,10 @@ web designer::
Saanvi is a web designer and developer in Bangalore, India. She accepts bitcoin for her work, but would prefer to get paid more frequently and so uses the Lightning Network to get paid incrementally for each small milestone she completes. With the Lightning Network, she can do more small jobs for more clients without worrying about fees or delays.
content creator / curator::
John is a 9-year-old boy from New Zealand, who wanted a games console just like his friends. However, his dad told him that in order to buy it, he had to earn the money himself. Now John is an aspiring artist, so he knows that while he is still improving, he can't charge much for his artwork.
John is a nine-year-old boy from New Zealand, who wanted a games console just like his friends. However, his dad told him that in order to buy it, he had to earn the money himself. Now John is an aspiring artist, so he knows that while he is still improving, he can't charge much for his artwork.
After learning about Bitcoin, he managed to set up a website to sell his drawings across the internet.
By using the Lightning Network, John was able to charge as little as $1 for one of his drawings, which would normally be considered a micro-payment and, as such, would typically be impossible on traditional systems.
Furthermore, most legacy financial systems wouldn't even allow a 9-year old like John to open an account!
Furthermore, most legacy financial systems wouldn't even allow a nine-year old like John to open an account!
By using a global currency such as bitcoin, John was able to sell his artwork to customers all over the world, store the money he's earned without a bank account and, in the end, buy the games console he so desperately wanted.
gamer::

@ -16,10 +16,11 @@ A Lightning network explorer is a useful tool to show the statistics of nodes, c
The below is an inexhaustive list (in alphanumerical order):
* https://1ml.com/, 1ML Lightning explorer
* https://explorer.acinq.co/, ACINQ's Lightning explorer, with fancy visualization
* https://lightblock.me/, Lightblock Lightning explorer
* https://hashxp.org/lightning/node/, hashXP Lightning explorer
* 1ML Lightning explorer, https://1ml.com/
* ACINQ's Lightning explorer, with fancy visualization, https://explorer.acinq.co/
* Fiatjaf's Lightning explorer with many diagrams, https://ln.bigsun.xyz/
* hashXP Lightning explorer, https://hashxp.org/lightning/node/
* Lightblock Lightning explorer, https://lightblock.me/
[TIP]
====
@ -60,9 +61,9 @@ Finally, those seeking simplicity and convenience, even at the expense of contro
There are many ways wallets can be characterized or categorized.
The most important questions to ask about a specific wallet are:
- Does this Lightning wallet have a full Lightning Node or does it use a third-party Lightning Node?
- Does this Lightning wallet have a full Bitcoin Node or does it use a third-party Bitcoin Node? footnote:[If a Lightning wallet uses a third-party Lightning node, it is this third-party Lightning node who decides how to communicate with Bitcoin. Hence, using a third-party Lightning node implies that you as a wallet user also use a third-party Bitcoin node. Only in the other case, when the Lightning wallet uses its own Lightning node, does the choice "full Bitcoin-node" vs. "third-party Bitcoin node" exist. ]
- Does this Lightning wallet store its own keys under user control (self-custody) or are the keys held by a third-party custodian?
. Does this Lightning wallet have a full Lightning Node or does it use a third-party Lightning Node?
. Does this Lightning wallet have a full Bitcoin Node or does it use a third-party Bitcoin Node? footnote:[If a Lightning wallet uses a third-party Lightning node, it is this third-party Lightning node who decides how to communicate with Bitcoin. Hence, using a third-party Lightning node implies that you as a wallet user also use a third-party Bitcoin node. Only in the other case, when the Lightning wallet uses its own Lightning node, does the choice "full Bitcoin-node" vs. "third-party Bitcoin node" exist. ]
. Does this Lightning wallet store its own keys under user control (self-custody) or are the keys held by a third-party custodian?
At the highest level of abstraction, questions 1 and 3 are the most elementary ones.
From these two questions, we can derive four possible categories.
@ -116,6 +117,7 @@ In <<lnwallet-examples>> we see some examples of currently popular Lightning nod
| Zeus | Mobile | Full Node | Bitcoin Core/btcd | Self-Custody
| lntxbot | Mobile | None | None | Custodial
| Blue Wallet | Mobile | None | None | Custodial
| Muun | Mobile | None | None | Self-Custody
|===
=== Balancing complexity and control
@ -220,7 +222,7 @@ Let's assume Alice has found a local Bitcoin ATM and has decided to buy some bit
[[bitcoin-atm]]
.A Lamassu Bitcoin ATM
image:images/bitcoin-atm.png[]
image:images/bitcoin-atm.png["Lamassu Bitcoin ATM"]
To receive the bitcoin in her Eclair Lightning wallet, Alice will need to present a _Bitcoin Address_ from the Eclair Lightning wallet to the ATM. The ATM can then send Alice's newly acquired bitcoin to this bitcoin address.
@ -228,7 +230,7 @@ To see a Bitcoin Address on the Eclair wallet, Alice must swipe to the left colu
[[eclair-receive]]
.Alice's bitcoin address, shown in Eclair
image:images/eclair-receive.png[]
image:images/eclair-receive.png["Eclair bitcoin address QR code"]
The QR code contains the same string of letters and numbers as shown below it, in an easy to scan format. This way, Alice doesn't have to type the Bitcoin Address. In the screenshot <<eclair-receive>>, we have purposely blurred both, to prevent readers from inadvertently sending bitcoin to this address.
@ -241,7 +243,7 @@ Alice can take her mobile device to the ATM and show it to the built-in camera,
[[bitcoin-atm-receive]]
.Bitcoin ATM scans the QR code.
image:images/bitcoin-atm-receive.png[]
image:images/bitcoin-atm-receive.png["Bitcoin ATM scans the QR code"]
Alice will see the transaction from the ATM in the "TRANSACTION HISTORY" tab of the Eclair wallet. While Eclair will detect the bitcoin transaction in just a few seconds, it will take approximately one hour for the bitcoin transaction to be "confirmed" on the Bitcoin blockchain. As you can see in <<eclair-tx1>>, Alice's Eclair wallet shows "6+ conf" below the transaction, indicating that the transaction has received the required minimum of six confirmations, and her funds are now ready to use.
@ -253,7 +255,7 @@ The number of "confirmations" on a transaction is the number of blocks mined sin
[[eclair-tx1]]
.Alice receives bitcoin
image:images/eclair-tx1-btc.png[]
image:images/eclair-tx1-btc.png["Bitcoin transaction received"]
While in this example Alice used an ATM to acquire her first bitcoin, the same basic concepts would apply even if she used one of the other methods in <<acquiring-bitcoin>>. For example, if Alice wanted to sell a product or provide a professional service in exchange for bitcoin, her customers could scan the Bitcoin Address with their wallets and pay her in bitcoin.
@ -286,7 +288,7 @@ Furthermore, Alice's channel peer can _forward_ payments via other channels furt
[TIP]
====
Not all channel peers are _good_ peers for routing payments. Well-connected peers will be able to route payements over shorter paths to the destination, increasing the chance of success. Channel peers with ample funds in their other channels will be able to route larger payments.
Not all channel peers are _good_ peers for routing payments. Well-connected peers will be able to route payments over shorter paths to the destination, increasing the chance of success. Channel peers with ample funds in their other channels will be able to route larger payments.
====
In other words: Alice needs one or more channels that connects her to one or more other nodes on the Lightning Network. She doesn't need a channel to connect her wallet directly to Bob's Cafe in order to send Bob a payment, though she can choose to open a direct channel too. Any node in the Lightning Network can be used for Alice's first channel. The more well-connected a node is the more people Alice can reach. In this example, since we want to also demonstrate payment routing, we won't have Alice open a channel directly to Bob's wallet. Instead, we will have Alice open a channel to a well-connected node and then later use that node to forward her payment, routing it through any other nodes as necessary to reach Bob.
@ -308,7 +310,7 @@ A "node URI" is a Universal Resource Identifier (URI) that identifies a specific
[[node-URI-QR]]
.node URI as a QR code
image:images/node-URI-QR.png[width=120]
image:images/node-URI-QR.png["Lightning node URI QR code",width=120]
[[node-URI-example]]
.node URI
@ -330,7 +332,7 @@ Alice allocates 0.018BTC of her 0.020 total to her channel and accepts the defau
[[eclair-open-channel]]
.Opening a Lightning Channel
image:images/eclair-open-channel-detail.png[]
image:images/eclair-open-channel-detail.png["Opening a Lightning Channel"]
Once she clicks "OPEN", her wallet constructs the special Bitcoin transaction that opens a Lightning channel, known as the _funding transaction_. The "on-chain" funding transaction is sent to the Bitcoin Network for confirmation.
@ -371,7 +373,7 @@ On the counter at Bob's Cafe, there is a tablet device showing <<bob-cafe-posapp
[[bob-cafe-posapp]]
.Bob's Point-of-Sale Application
image:images/bob-cafe-posapp.png[]
image:images/bob-cafe-posapp.png["Bob's Point-of-Sale Application"]
==== A Lightning Invoice
@ -379,13 +381,13 @@ Alice selects the "Cafe Latte" option from the screen and is presented with a _L
[[bob-cafe-invoice]]
.Lightning Invoice for Alice's latte
image:images/bob-cafe-invoice.png[]
image:images/bob-cafe-invoice.png["BTCPay Server Lightning invoice"]
To pay the invoice, Alice opens her Eclair wallet and selects the "Send" button (which looks like a right-facing arrow) under the "TRANSACTION HISTORY" tab, as shown in <<alice-send-start>>.
[[alice-send-start]]
.Alice Send
image:images/alice-send-start.png[width=300]
image:images/alice-send-start.png["Lightning transaction send",width=300]
[TIP]
====
@ -396,7 +398,7 @@ Alice selects the option to "scan a payment request" and scans the QR code displ
[[alice-send-detail]]
.Alice's Send Confirmation
image:images/alice-send-detail.png[width=300]
image:images/alice-send-detail.png["Lightning transaction send confirmation",width=300]
Alice presses "PAY," and a second later, Bob's tablet shows a successful payment. Alice has completed her first Lightning Network payment! It was fast, inexpensive, and easy. Now she can enjoy her latte which was purchased using a payment system that is fast, cheap and decentralized. And from now on, whenever Alice feels like drinking a coffee at Bob's Cafe she selects an item on Bob's tablet screen, scans the QR code with her cell phone, clicks pay, and is served a coffee, all within seconds and all without an "on-chain" transaction.

@ -20,7 +20,7 @@ There are several ways to describe a payment channel, depending on the context.
A payment channel is a _financial relationship_ between two nodes on the Lightning Network, called the "channel partners". The financial relationship allocates a _balance of funds_ (denominated in milli-satoshis), between the two channel partners.
The payment channel is managed by a _cryptographic protocol_, meaning a pre-defined process based on cryptography, used by the channel partners to re-distribute the balance of the channel in favor of one or the other channel partner. The cryptographic protocol ensures that one channel partner cannot cheat the other, so that the partners do not need to trust each other.
The payment channel is managed by a _cryptographic protocol_, meaning a pre-defined process based on cryptography is used by the channel partners to re-distribute the balance of the channel in favor of one or the other channel partner. The cryptographic protocol ensures that one channel partner cannot cheat the other, so that the partners do not need to trust each other.
The cryptographic protocol is established by the funding of a 2-of-2 _multi-signature address_ that requires the two channel partners to cooperate and prevents either channel partner from spending the funds unilaterally.
@ -28,7 +28,7 @@ To summarize:
A payment channel is a financial relationship between nodes, allocating funds from a multi-signature address, through a strictly defined cryptographic protocol.
=== Payment channels basics
=== Payment channel basics
Underlying the payment channel is simply a 2-of-2 multisignature address on the Bitcoin blockchain, for which you hold one key and your channel partner holds the other key.
@ -95,7 +95,7 @@ Payment channels have a few very interesting and useful properties:
* Payments made in a payment channel are only known to you and your partner. In that sense, you gain privacy compared to Bitcoin, where every transaction is public. Only the final balance, which is the aggregate of all payments in that channel, will become visible on the Bitcoin blockchain.
Bitcoin was about 5 years old when talented developers first figured out how payment channels could be constructed and by now there are at least 3 different methods known.
Bitcoin was about five years old when talented developers first figured out how payment channels could be constructed and by now there are at least three different methods known.
This chapter will focus on the channel construction method first described in the Lightning Network whitepaper by Joseph Poon and Thaddeus Dryja in 2015. These are known as _Poon-Dryja_ channels, and are the channel construction method currently used in the Lightning Network.
The other two proposed methods are _Duplex Micropayment_ channels, introduced by Christian Decker around the same time as the "Poon-Dryja" channels and _eltoo_ channels, introduced in 2018 by Christian Decker, Rusty Russel and (author of this book) Olaoluwa Osuntokun.
@ -103,7 +103,7 @@ Eltoo channels have some interesting properties and simplify the implementation
==== Multisig addresses
Payment channels are built on top of 2-of-2 multisignature addresses, timelocks and Segregated Witness transaction outputs. We will not revise these relatively advanced concepts of the Bitcoin system. Instead, in this section we will provide a high-level overview of multisignature scripts and how they allow us to construct payment channels.
Payment channels are built on top of 2-of-2 multisignature addresses, timelocks and Segregated Witness transaction outputs. We will not review these relatively advanced concepts of the Bitcoin system in depth. Instead, in this section we will provide a high-level overview of multisignature scripts and how they allow us to construct payment channels.
If you have already studied Bitcoin and are familiar with multisignature addresses, feel free to skip this section.
[TIP]
@ -266,11 +266,11 @@ Technologies such as Watchtower services or changing the channel construction pr
====
Alice can close the channel at any time if Bob does not respond, claiming her fair share of the balance.
After publishing the *last* commitment transaction on-chain Alice has to wait for the time lock to expire before she can spend her funds from the commitment transaction. As we will see later, there is an easier way to close a channel without waiting, as long as Alice and Bob are both online and cooperate to close the channel with the correct balance allocation. But the commitment transactions stored by each channel partner act as a failsafe, ensuring they do not lose funds if there is a problem with their channel partner.
After publishing the *last* commitment transaction on-chain Alice has to wait for the timelock to expire before she can spend her funds from the commitment transaction. As we will see later, there is an easier way to close a channel without waiting, as long as Alice and Bob are both online and cooperate to close the channel with the correct balance allocation. But the commitment transactions stored by each channel partner act as a failsafe, ensuring they do not lose funds if there is a problem with their channel partner.
==== Announcing the channel
Channels partners can agree to announce their channel to the whole Lightning Network, making it a _public channel_. To announce the channel, they use the Lightning Network's gossip protocol to tell other nodes about the existence, capacity and fees of the channel.
Channel partners can agree to announce their channel to the whole Lightning Network, making it a _public channel_. To announce the channel, they use the Lightning Network's gossip protocol to tell other nodes about the existence, capacity and fees of the channel.
Announcing channels publicly allows other nodes to use them for payment routing, thereby also generating routing fees for the channel partners.
@ -279,7 +279,7 @@ By contrast, the channel partners may decide not to announce the channel, making
[NOTE]
====
You may hear the term "private channel", used to describe an unannounced channel. We avoid using that term because it is misleading and creates a false sense of privacy. While an unannounced channel will not be known to others while it is in use, its existence and capacity will be revealed when the channel closes, because those details will be visible on-chain in the final settlement transaction. Its existence can also leak in a variety of other ways, so we avoid calling it "private"
You may hear the term "private channel", used to describe an unannounced channel. We avoid using that term because it is misleading and creates a false sense of privacy. While an unannounced channel will not be known to others while it is in use, its existence and capacity will be revealed when the channel closes, because those details will be visible on-chain in the final settlement transaction. Its existence can also leak in a variety of other ways, so we avoid calling it "private".
====
Unannounced channels are still used to route payments but only by the nodes which are aware of their existence, or given "routing hints" about a path that includes an unannounced channel.
@ -301,12 +301,12 @@ By re-balancing a channel, it can be kept open almost indefinitely and used for
However, sometimes closing a channel is desirable or necessary. For example:
* You want to reduce the balance held on your Lightning channels for security reasons and want to send funds to "cold storage"
* You want to reduce the balance held on your Lightning channels for security reasons and want to send funds to "cold storage".
* Your channel partner becomes unresponsive for a long time and you cannot use the channel anymore.
* The channel is not being used often because your channel partner is not a well-connected node, so you want to use the funds for another channel with a better-connected node.
* Your channel partner has breached the protocol either due to a software bug or on purpose forcing you to close the channel to protect your funds.
There are 3 ways to close a payment channel:
There are three ways to close a payment channel:
* Mutual close (the good way)
* Force close (the bad way)
@ -326,7 +326,7 @@ No new routing attempts will be accepted from either channel partner and any ong
Finalizing the routing attempts takes time, so a mutual close can also take some time to complete.
Once there are no pending routing attempts, the nodes cooperate to prepare a _closing transaction_.
This transaction is similar to the commitment transaction; it encodes the last balance of the channel but the outputs are NOT encumbered with a time lock.
This transaction is similar to the commitment transaction; it encodes the last balance of the channel but the outputs are NOT encumbered with a timelock.
The on-chain transaction fees for the closing transaction are paid by the channel partner who opened the channel and not by the one who initiated the closing procedure.
Using the on-chain fee estimator, the channel partners agree on the appropriate fee and both sign the closing transaction.
@ -343,7 +343,7 @@ This is usually in the case that one of the channel partners is unreachable, and
In this case, you would initiate a force close to unilaterally close the channel and "free" the funds.
To initiate a force close, you can simply publish the last commitment transaction your node has.
After all, that's what commitment transactions are for - they offer a guarantee that you don't need to trust your channel to retrieve the balance of your channel.
After all, that's what commitment transactions are for - they offer a guarantee that you don't need to trust your channel partner to retrieve the balance of your channel.
Once you broadcast the last commitment transaction to the Bitcoin network and it is confirmed, it will create two spendable outputs, one for you and one for your partner.
As we discussed previously, the Bitcoin network has no way of knowing if this was the most recent commitment transaction or an old one which was published to steal from your partner.
@ -353,7 +353,7 @@ In the case that you broadcasted an earlier commitment transaction, the timelock
When publishing a commitment transaction during a force close, the on-chain fees will be higher than a mutual close for several reasons:
. When the commitment transaction was negotiated, the channel partners didn't know how much the on-chain fees would be at the future time the transaction would be broadcast. Since the fees cannot be changed without changing the outputs of the commitment transaction (needs both signatures) and since the force close happens when a channel partner is not available to sign, the protocol developers decided to be very generous with the fee rate included in the commitment transactions. It can be up to 5 times higher than the fee estimators suggest at the time the commitment transaction is negotiated.
. When the commitment transaction was negotiated, the channel partners didn't know how much the on-chain fees would be at the future time the transaction would be broadcast. Since the fees cannot be changed without changing the outputs of the commitment transaction (needs both signatures) and since the force close happens when a channel partner is not available to sign, the protocol developers decided to be very generous with the fee rate included in the commitment transactions. It can be up to five times higher than the fee estimators suggest at the time the commitment transaction is negotiated.
. The commitment transaction includes additional outputs for any pending routing attempts (HTLCs), which makes the commitment transaction larger (in terms of bytes) than a mutual close transaction. Larger transactions incur more fees.
. Any pending routing attempts will have to be resolved on-chain causing additional on-chain transactions.
@ -377,8 +377,9 @@ You should consider a force close only as the last resort.
A Protocol Breach is when your channel partner tries to cheat you, whether deliberately or not, by publishing an outdated commitment transaction to the Bitcoin blockchain, essentially initiating a (dishonest) force close from their side.
Your node must be online and watching new blocks and transactions on the Bitcoin blockchain to detect this.
Because your channel partner's payment will be encumbered by a timelock, your node has some time to act.
You have until the time lock expires to detect a protocol breach and publish a _punishment transaction_.
Because your channel partner's payment will be encumbered by a timelock, your node has some time to act before the timelock expires to detect a protocol breach and publish a _punishment transaction_.
If you successfully detect the protocol breach and enforce the penalty, you will receive all of the funds in the channel, including your channel partner's funds.
In this scenario, the channel closure will be rather fast.
@ -428,7 +429,7 @@ An invoice is a simple payment instruction containing information such as a uniq
The most important part of the invoice is the payment hash, that allows the payment to travel across multiple channels in an _atomic_ way. Atomic, in computer science, means any action or state change that is either completed successfully or not at all - there is no possibility of an intermediate state or partial action. In the Lightning Network that means that the payment either travels the whole path or fails completely. It cannot be partially completed such that an intermediate node on the path can receive the payment and keep it.
There is no such thing as a "partial payment" or "partly successful payment".
Invoices are not communicated over the Lightning Network. Instead, they are communicated "out of band", using any other communication mechanism. This is similar to how Bitcoin addresses are communicated to senders outside the Bitcoin network, as a QR code, over email, or a text message. For example, Bob can present a Lightning invoice to Alice as a QR code, or send it via email, or any other message channel.
Invoices are not communicated over the Lightning Network. Instead, they are communicated "out of band", using any other communication mechanism. This is similar to how Bitcoin addresses are communicated to senders outside the Bitcoin network, as a QR code, over email, or a text message. For example, Bob can present a Lightning invoice to Alice as a QR code, send it via email, or any other message channel.
Invoices are usually encoded either as a long bech32-encoded string or as a QR code, to be scanned by a smartphone Lightning wallet. The invoice contains the amount of bitcoin that is requested and a signature of the recipient. The sender uses the signature to extract the public key (also known as the node ID) of the recipient so that the sender knows where to send the payment.
@ -584,7 +585,7 @@ The onion routing protocol used in Lightning has the following properties:
. The onions are constructed such that they will always have the same length independent of the position of the processing node along the path. As each layer is "peeled" the onion is padded with encrypted "junk" data to keep the size of the onion the same. This prevents intermediary nodes from knowing their position in the path.
. Onions have an HMAC (Hashed Message Authentication code) at each layer so that manipulations of onions are prevented and practically impossible
. Onions have an HMAC (Hashed Message Authentication code) at each layer so that manipulations of onions are prevented and practically impossible.
. Onions can have up to 20 hops or onion layers if you prefer. This allows for sufficiently long paths.
@ -644,7 +645,7 @@ Alice will need to have a small amount of trust in Bob.
Alice has been to Bob's Cafe and clearly Bob is interested in selling her coffee, so Alice can trust Bob in this sense.
There are mutual benefits to both Alice and Bob.
Alice decides that the reward is enough for her to take on the cost of the on-chain fee for creating a channel to Bob.
In contrast, Alice will not open a channel to someone unknown who just sent her an uninvitedly email asking her to open a channel to him.
In contrast, Alice will not open a channel to someone unknown who just uninvitedly sent her an email asking her to open a channel to him.
=== Comparison with Bitcoin
@ -777,7 +778,7 @@ The milli-satoshi unit cannot, of course, be settled on the Bitcoin blockchain a
==== Monetary Unit
Both the Bitcoin network and the Lightning network use the same monetary units: bitcoin. Lightning payments use the very same bitcoin as Bitcoin transactions. As an implication, because the monetary unit is the same, the monetary limit is the same: less than 21 million bitcoin. Of Bitcoin's 21 million total bitcoin, some are already allocated to 2-of-2 multi-signature addresses as part of payment channel on the Lightning Network.
Both the Bitcoin network and the Lightning network use the same monetary units: bitcoin. Lightning payments use the very same bitcoin as Bitcoin transactions. As an implication, because the monetary unit is the same, the monetary limit is the same: less than 21 million bitcoin. Of Bitcoin's 21 million total bitcoin, some are already allocated to 2-of-2 multi-signature addresses as part of payment channels on the Lightning Network.
==== Irreversibility and finality of payments
@ -799,6 +800,6 @@ Both, Bitcoin and Lightning are open-source software systems built by a decentra
=== Conclusion
In this chapter we looked at how the Lightning network actually works and all of the constituent components. We examined each step in constructing, operating and closing a channel. We looked at how payments are routed. Finally, we compared Lightning and Bitcoin and analyzed their differences and commonalities.
In this chapter we looked at how the Lightning network actually works and all of the constituent components. We examined each step in constructing, operating and closing a channel. We looked at how payments are routed and finally, we compared Lightning with Bitcoin and analyzed their differences and commonalities.
In the next several chapters we will revisit all these topics, but in much more detail.

@ -43,7 +43,7 @@ The current status of the book is "IN PROGRESS". See below for status of specifi
| [Lightning Applications (LApps)]() | # | :thought_balloon: |
| [LN's Future]() | # | :thought_balloon: |
Total Word Count: 83393
Total Word Count: 89705
Target Word Count: 100,000-120,000

@ -23,7 +23,7 @@ If you are new to the topic we highly encourage you to start there first.
If you however already know a fair share about bitcoin script, OP_CODES and protocol design it might be sufficient to skip the previous chapter and start here with us.
This books follows the construction of payment channels as described in BOLT 02 which is titled `peer protocol` and describes how two peers communicate to open, maintain and close a channel.
As stated we will only discuss opening and closing a channel in this chapter and
the operation and maintainance of a channel which means either attempting to make or forward a payment as well as failing or settling such attempts is the normal operation and will be discussed in the next chapter.
the operation and maintenance of a channel which means either attempting to make or forward a payment as well as failing or settling such attempts is the normal operation and will be discussed in the next chapter.
=== Summary of what you (should) know about payment channels and Bitcoin
@ -46,10 +46,10 @@ The private key allows the owner to produce a signature for a transaction that s
Thus 'ownership' of bitcoin can be defined as the ability to spend that bitcoin.
If you have an unpublished but signed transaction from a 2-of-2 multisignature address, where some outputs are sent to an address you own, and additionally you exclusively know one of the private keys of the multisignature address, then you effectively own the bitcoin of that output.
Without your help no other transaction from the 2-of-2 multisignature address can be produced (as only you possesess one of the needed keys to sign a transaction that spends from this address)
Without your help no other transaction from the 2-of-2 multisignature address can be produced (as only you possesses one of the needed keys to sign a transaction that spends from this address)
However, without the help of anybody else you can transfer the funds to an address which you control.
You do that by broadcasting the transaction to the bitcoin network which will accept it as it has valid signatures.
As the funds in this transaction go to a regular address for which you controll the private key you can again move the funds and thus you effectively own them.
As the funds in this transaction go to a regular address for which you control the private key you can again move the funds and thus you effectively own them.
On the Lightning Network ownership of your funds is almost always encoded with you having a pre-signed transaction spending from a 2-of-2 multisignature address.
While your funds on the Lightning Network are called to be "off-chain" they are actually very much on chain and very much owned by you just like you might own other bitcoin.
@ -127,7 +127,7 @@ Each channel partner has both signatures for one of the commitment transactions
The split of the capacity is realized by a `to_local` and a `to_remote` output that is part of every commitment transaction.
The `to_local` output goes to an address that is controlled by the peer that holds this fully signed commitment transaction.
`to_local` outputs, which also exist in the second stage HTLC transactions - which we discuss in the routing chapter - have two spending conditions.
The `to_local` output can be spent either at any time with the help of a revocation secret or after a timelock with the secret key that is controled by the peer holding this commitment transaction.
The `to_local` output can be spent either at any time with the help of a revocation secret or after a timelock with the secret key that is controlled by the peer holding this commitment transaction.
The revocation secret is necessary to economically disincentivice peers to publish previous commitment transactions.
Addresses and revokation secretes change with every new pair of commitment transactions that are being negotiated.
The Lightning Network as a protocol defines the communication protocols that are necessary to achieve this.

@ -31,7 +31,7 @@ As such, a zombie channel is technically still an open channel, but cannot be us
Zombie channels offer no benefit to the user but have several downsides:
* Any capacity you have locked in the channel is useless for routing payments and could be allocated elsehwere
* Any capacity you have locked in the channel is useless for routing payments and could be allocated elsewhere
* If you lose access to your own node and restore it with only your private key, you will lose access to funds in open zombie channels
* If you lose access to your own node and restore it with your private key and channel backups, you will not be able to contact your channel partner to cooperatively close the channel and may also lose the funds
* Public zombie channels are a burden on the network, as information about them is communicated to the rest of the network, but they cannot be used to route payments
@ -74,13 +74,13 @@ Well, verifying a channel is pretty important.
If Wei tries to forward any payments through a channel that doesn't exist, his payments are going to fail.
Even if the channel does exist, Wei still needs assurances that Bob and Alice actually control the funds inside of it.
Alice and Bob could potentially dupe him by claiming ownership of a channel that actually belongs to someone else.
So Wei will definintely want to verify before he updates his channel graph.
So Wei will definitely want to verify before he updates his channel graph.
Firstly, Wei will check the channel ID to discover which Bitcoin transaction contains the channel funds.
He will then look up this transaction on the Bitcoin blockchain and he should discover a P2WSH bitcoin UTXO that is signed by both Alice and Bob.
Secondly, Wei will verify the signatures in the channel annoucenment message and confirm that the two nodes who signed the channel announcement are actually Alice and Bob.
Secondly, Wei will verify the signatures in the channel announcement message and confirm that the two nodes who signed the channel announcement are actually Alice and Bob.
Once he's done so, he's convinced that the channel is funded and that Alice and Bob are the funders and owners of that channel.
If any of these checks fail, he'll ignore the channel announcement.
Once Wei is satisifed that the channel announcement checks out, he'll update his channel graph.
Once Wei is satisfied that the channel announcement checks out, he'll update his channel graph.
He will also send information about this channel to his peers, and they will verify it for themselves.

@ -108,7 +108,7 @@ Then it has included a signature for the entire commitment transaction.
As commitment transactions can have several HTLCs and HTLC success transactions need signatures which might not be provided at the time when they are needed those signatures are all already sent over to Bob.
If all signatures are valid Bob has a new commitment transaction.
At this time he would be able to publish either the old one or the new one without getting a penality as the old one is not yet revoked and invalidated.
However this is safe for Alice as Bob has less money in this old state and is economically not incentivised to publish the old commitment transaction.
However this is safe for Alice as Bob has less money in this old state and is economically not incentivized to publish the old commitment transaction.
Alice on the other side has no problem if Bob publishes the new commitment transaction as she wanted to send him money.
If Bob can provide the preimage he is by their agreement and expectation entitled to claim the HTLC output.
Should Bob decide to sabotage to future steps of the protocol Alice can publish her commitment transaction without Bob being able to punish her.

@ -96,7 +96,7 @@ This would be of particular benefit to online stores and exchanges that accept B
footnote:[One variant of this is called a "dust attack", whereby an attacker can send a very small amount of Bitcoin (called a "dust output") to an address it knows is owned by a store or exchange.
By monitoring where this small amount of bitcoin moves, it can determine which other addresses the exchange to store owns.
This kind of attack is not possible on the Lightning Network].
This is not possible on the Lightning Network
This is not possible on the Lightning Network.
**Multiplayer Games**: Lightning Payments can be integrated into online and collaborative games.
One example of this is _Satoshi's Place_, an online billboard where users can pay 1 satoshi to paint 1 pixel on a one-million-pixel canvas.
@ -125,4 +125,4 @@ The Lightning Network's principal object is to move payments across a network.
Could it move data other than payments across its network too? It can.
Some projects such as _Whatsat_, _Sphinx Chat_, and _Juggernaut_ are implementing instant messaging chat apps on top of the Ligtning Network.
One can imaging other types of data such as electronic tickets, QR codes, or other forms of tokens flowing across the Lightning Network as well.
The use cases are limited only by our imagination and reach beyond finance.
The use cases are limited only by our imagination and reach beyond finance.

@ -83,7 +83,7 @@ blockchain::
New blocks have a statistical probability of being produced every ten minutes.
BOLT::
BOLT, or Basics Of Lightning Technology, is the formal specification of the Lightning Network Protocol. It serves only as such without delving into implementation, unlike Bitcoin, in which both are one and the same. It is available in https://github.com/lightningnetwork/lightning-rfc.
BOLT, or Basis Of Lightning Technology, is the formal specification of the Lightning Network protocol. Unlike Bitcoin, which has a reference implementation that also serves as the protocol's specification the various Lightning Network implementations follow BOLT so they can work with one another to form the same network. It is available at https://github.com/lightningnetwork/lightning-rfc.
Breach Remedy Transaction::
A transaction claiming the outputs of a Revocable Sequence Maturity Contract with the help of the revocation key.
@ -182,6 +182,12 @@ ephemeral key::
This increases the security of transported messages or payments.
Even if an ephemeral key leaks, only information about a single payment becomes public.
feature bits::
A binary string that Lightning nodes use to communicate to each other which features they support.
Feature bits are included in many types of communication, such as invoices or channel announcements.
They can be decoded using BOLT #9, and will tell nodes which features the node has enabled, and whether these are backwards-compatible.
Also known as feature flags.
fees::
In the context of Bitcoin, the sender of a transaction includes a fee paid to miners for including the transaction in a block.
In the context of the Lightning Network, nodes will charge routing fees for forwarding other users' payments.
@ -282,7 +288,7 @@ A multipart payment (which is often also refered to as multipath payment) is a m
multisignature::
Multisignature (multisig) refers to requiring more than one key to authorize a Bitcoin transaction.
Payment channels are always encoded as multisignature addresses requiring one signature from each peer of the payment channel.
In the standard case of a two-party payment channel a 2-2 multisignature address is used.
In the standard case of a two-party payment channel a 2-of-2 multisignature address is used.
Neutrino::
Neutrino is a later alternative to SPV that also verifies whether certain transactions are contained in a block without downloading the entire block. However, it offers a number of improvements over SPV: Neutrino does not transmit any information that would allow a third party to determine users identities, it facilitates the use of non-custodial apps, and it reduces the computational load on full nodes. The trade-off for these improvements is that Neutrino requires more data from the full node than SPV.
@ -302,8 +308,7 @@ Noise_XK::
The template of the Noise protocol framework to establish an authenticated and encrypted communication channel between two peers of the Lightning Network.
X means that no public key needs to be known from the initiator of the connection.
K means that the public key of the receiver needs to be known.
More particular (from: http://www.noiseprotocol.org/noise.html) the protocol enables.
Encryption to a known recipient, strong forward secrecy. This payload is encrypted based on an ephemeral-ephemeral DH as well as an ephemeral-static DH with the recipient's static key pair. Assuming the ephemeral private keys are secure, and the recipient is not being actively impersonated by an attacker that has stolen its static private key, this payload cannot be decrypted. Sender authentication resistant to key-compromise impersonation (KCI). The sender authentication is based on an ephemeral-static DH ("es" or "se") between the sender's static key pair and the recipient's ephemeral key pair. Assuming the corresponding private keys are secure, this authentication cannot be forged.
More particular (from: http://www.noiseprotocol.org/noise.html) the protocol enables encryption to a known recipient and strong forward secrecy. This payload is encrypted based on an ephemeral-ephemeral DH as well as an ephemeral-static DH with the recipient's static key pair. Assuming the ephemeral private keys are secure, and the recipient is not being actively impersonated by an attacker that has stolen its static private key, this payload cannot be decrypted. Sender authentication resistant to key-compromise impersonation (KCI). The sender authentication is based on an ephemeral-static DH ("es" or "se") between the sender's static key pair and the recipient's ephemeral key pair. Assuming the corresponding private keys are secure, this authentication cannot be forged.
// the noise protocol documentation is according to their IPR section public domain. The author is Trevor Perrin (noise@trevp.net)
onion routing::

@ -0,0 +1,711 @@
# Channel Graph Discovery, Authentication & Maintenance
## Intro
As we have seen the Lightning Network uses a sourced base Onion Routing Protocol to deliver a payment from a sender to the recipient.
For this the sending node has to be able to construct a path of payment channels that connects it with the recipient.
Thus the sender has to be aware of the Channel Graph.
The channel graph is the interconnected set of publicly advertised channels (more on that later), and the nodes that these channels interlink.
As channels are backed by a funding transaction that is happening on chain one might falsely believe that Lightning Nodes could just extract the existing channels from the Bitcoin Blockchain.
However this only possible to a certain extend.
The Funding transactions are Pay to Whitness Script addresses and the nature of the script will only be revealed once the funding transaction output is spent.
Even if the nature of the script was known we emphasize that not all 2 - of - 2 multisignature scripts correspond to payment channels.
Since not even every Pay to Whitness Script address that we see in the Bitcoin Blockchain corresponds to a payment channel this approach is not helpful.
There are actually more reasons why looking at the Bitcoin Blockchain might not be helpful.
For example on the Lightnign Network the Bitcoin keys that are used for signing are rotated by the nodes for every channel and update.
Thus even if we could reliably detect funding transactions on the Bitcoin Blockchain we would not know which two nodes on the Lightning Network own that particular channel.
Thus we could node create the Channel Graph that would be used to create candidate paths during the payment delivery via onion routing.
The Lightning Network solves the afore mentioned problem by implementing a gossip protocol.
Gossip protocols are typical for peer 2 peer networks and are being used so that nodes can share information with other nodes without talking to those other nodes directly.
For that Lightning Nodes open encrypted peer 2 peer connections to each other and share novel information that they have received from other peers.
As soon as a node wants to share some information - for example about a newly created channel - it sends a message to all its peers.
Uppon receiving a message a node decides if the received message was novel and if so it will forward the information to its peers.
In this way if the peer 2 peer network is connected all new information that is necessary for the operation of the network will eventually be propagated to all other peers.
Obviously if a new peer initially wants to join the network it needs to know some other peers on the Network initially.
Only then the new peer could connect to them in order to learn about the existance of other peers.
In this chapter, we'll explore exactly _how_ Lightning nodes discover each
other, and also the channel graph itself.
When most refer to the _network_ part
of the Lightning Network, they're referring to the Channel Graph which itself
is a unique authenticated data structure _anchored_ in the base Bitcoin
blockchain.
However the Lightning network is also a peer to peer network of nodes that are have just opened an encrypted peer connection.
Usually for 2 peers to maintain a payment channel they need to talk to each other directly which means that there will be a peer connection between them.
This suggests that the Channel Graph is a subnetwork of the peer to peer network.
However this is not true.
As payment channels do not need to be closed if one or both peers are going offline they can continue to exist even though the peer connection is terminated.
It might be usefull to get familiar with the different terminology that we have used througout the book for similar concepts / actions depending on weather they happen on the Channel Graph or on the peer 2 peer network.
[[network-terminology]]
.Terminology of the different Networks
[options="header"]
|===
| | Channel Graph |peer to peer network
| Name | channel | connection
| initiate | open | (re)connect
| finalize | close| terminate
| technology | Bitcoin Blockchain | encrypted TCP/IP connection
| lifetime | until funding spent | while peers are online
|===
As the Lightning Network is a peer-to-peer network, some initial bootstrapping
is required in order for peers to discover each other. Within this chapter
we'll follow the story of a new peer connecting to the network for the first
time, and examine each step in the bootstrapping process from initial peer
discovery, to channel graph syncing and validation.
As an initial step, our new node needs to somehow _discover_ at least _one_
peer that is already connected to the network and has a full channel graph (as
we'll see later, there's no canonical version as the update dissemination
system is _eventually consistent_). Using one of many initial bootstrapping
protocols to find that first peer, after a connection is established, our new
peer now needs to _download_ and _validate_ the channel graph. Once the channel
graph has been fully validated, our new peer is ready to start opening channels
and sending payments on the network.
After initial bootstrap, a node on the network needs to continue to maintain
its view of the channel graph by: processing new channel routing policy
updates, discovering and validating new channels, removing channels that have
been closed on chain, and finally pruning channels that fail to send out a
proper "heartbeat" every 2 weeks or so.
Upon completion of this chapter, the reader will understand a key component of
the p2p Lightning Network: namely how peers discover each other and maintain a
personal view of the channel graph. We'll being our story with exploring the
story of a new node that has just booted up, and needs to find other peers to
connect to on the network.
## Peer Discovery
In this section, we'll begin to follow the story of Norman, a new Lightning
node that wishes to join the network as he sets out on his journey to which consists of 3 steps:
. discovery a set of bootstrap peers.
. download and validate the channel graph.
. begin the process of ongoing maintainance of the channel graph itself.
### P2P Boostrapping
Before doing any thing else, Norman first needs to discover a set of peers whom
are already part of the network. We call this process initial peer
bootstrapping, and it's something hat every peer to peer network needs to
implement properly in order to ensure a robust, healthy network. Bootstrapping
new peers to existing peer to peer networks is a very well studied problem with
several known solutions, each with their own distinct trade offs. The simplest
solution to this problem is simply to package a set of _hard coded_ bootstrap
peers into the packaged p2p node software. This is simple in that each new node
can find the bootstrap peer with nothing else but the software they're running,
but rather fragile given that if the set of bootstrap peers goes offline, then
no new nodes will be able to join the network. Due to this fragility, this
option is usually used as a fallback in case none of the other p2p bootstrapping
mechanisms work properly.
Rather than hard coding the set of bootstrap peers within the software/binary
itself, we can instead opt to devise a method that allows peers to dynamically
obtain a fresh/new set of bootstrap peers they can use to join the network.
We'll call this process initial peer discovery. Typically we'll leverage
existing Internet protocols to maintain and distribute a set of bootstrapping
peers. A non-exhaustive list of protocols that have been used in the past to
accomplish initial peer discovery include:
* DNS
* IRC
* HTTP
Similar to the Bitcoin protocol, the primary initial peer discovery mechanism
used in the Lightning Network happens via DNS. As initial peer discovery is a critical and
universal task for the network, the process has been _standardized_ in a
document that is a part of the Basis of Lightning Technology (BOLT)
specification. This document is [BOLT
10](https://github.com/lightningnetwork/lightning-rfc/blob/master/10-dns-bootstrap.md).
### DNS Bootstrapping via BOLT 10
The BOLT 10 document describes a standardized way of implementing peer
discovery using the Domain Name System (DNS). Lightning's flavor of DNS based
bootstrapping uses up to 3 distinct record types:
* `SRV` records for discovering a set of _node public keys_.
* `A` records for mapping a node's public key to its current `IPv4` address.
* `AAA` records for mapping a node's public key to its current `IPv6` address
(if one exists).
Those somewhat familiar with the DNS protocol may already be familiar with the
`A` and `AAA` record types, but not the `SRV` type. The `SRV` record type is
used less commonly by protocols built on DNS, that's used to determine the
_location_ for a specified service. In our context, the service in question is
a given Lightning node, and the location its IP address. We need to use this
additional record type as unlike nodes within the Bitcoin protocol, we need
both a public key _and_ an IP address in order to connect to a node. As we saw
in chapter XX on the transport encryption protocol used in LN, by requiring
knowledge of the public key of a node before one can connect to it, we're able
to implement a form of _identity_ hiding for nodes in the network.
// TODO(roasbeef): move paragraph below above?
#### A New Peer's Bootstrapping Workflow
Before diving into the specifics of BOLT 10, we'll first outline the high level
flow of a new node that wishes to use BOLT 10 to join the network.
First, a node needs to identify a single, or set of DNS servers that understand
BOLT 10 so they can be used for p2p bootstrapping.
While BOLT 10 uses lseed.bitcoinstats.com as the seed server as the example there exists no "official"
set of DNS seeds for this purpose, but each of the major implementations
maintain their own DNS seed, and cross query each other's seeds for redundancy
purposes.
[[dns seeds]]
.Table of known lightning dns seed servers
[options="header"]
|===
| dns server | Maintainer
| lseed.bitcoinstats.com | Christian Decker
| nodes.lightning.directory | lightning labs (Olaoluwa Osuntokun)
| soa.nodes.lightning.directory | lightning labs (Olaoluwa Osuntokun)
| lseed.darosior.ninja | Antoine Poinsot
|===
DNS seeds exist for both Bitcoin's mainnet and testnet. For the sake
of our example, we'll assume the existence of a valid BOLT 10 DNS seed at
`nodes.lightning.directory`.
Next, we'll now issue an `SRV` query to obtain a set of _candidate bootstrap
peers_. The response to our query will be a series of _bech32_ encoded public
keys. As DNS is a text based protocol, we can't send raw bytes, so an encoding
scheme is required. For this scheme BOLT 10 has selected _bech32_ due to its
existing propagation in the wider Bitcoin ecosystem. The number of encoded
public keys returned depends on the server returning the query, as well as all
the resolver that stand between the client and the authoritative server. Many
resolvers may filter out SRV records all together, or attempt to truncate the
response size itself.
Using the widely available `dig` command-line tool, we can query the _testnet_
version of the DNS seed mentioned above with the following command:
```
$ dig @8.8.8.8 test.nodes.lightning.directory SRV
```
We use the `@` argument to force resolution via Google's nameserver as they
permit our larger SRV query responses. At the end, we specify that we only want
`SRV` records to be returned. A sample response looks something like:
```
$ dig @8.8.8.8 test.nodes.lightning.directory SRV
; <<>> DiG 9.10.6 <<>> @8.8.8.8 test.nodes.lightning.directory SRV
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 43610
;; flags: qr rd ra; QUERY: 1, ANSWER: 25, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;test.nodes.lightning.directory. IN SRV
;; ANSWER SECTION:
test.nodes.lightning.directory. 59 IN SRV 10 10 9735 ln1qfkxfad87fxx7lcwr4hvsalj8vhkwta539nuy4zlyf7hqcmrjh40xx5frs7.test.nodes.lightning.directory.
test.nodes.lightning.directory. 59 IN SRV 10 10 15735 ln1qtgsl3efj8verd4z27k44xu0a59kncvsarxatahm334exgnuvwhnz8dkhx8.test.nodes.lightning.directory.
<SNIP>
;; Query time: 89 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Thu Dec 31 16:41:07 PST 2020
```
We've truncated the response for brevity. In our truncated responses, we can
see two responses. Starting from the right-most column, we have a candidate
"virtual" domain name for a target node, then to the left we have the _port_
that this node can be reached using. The first response uses the standard port
for LN: `9735`. The second response uses a custom port which is permitted by
the protocol.
Next, we'll attempt to obtain the other piece of information we need to connect
to a node: it's IP address. Before we can query for this however, we'll fist
_decode_ the returned sub-domain for this virtual host name returned by the
server. To do that, we'll first encoded public key:
```
ln1qfkxfad87fxx7lcwr4hvsalj8vhkwta539nuy4zlyf7hqcmrjh40xx5frs7
```
Using `bech32`, we can decode this public key to obtain the following valid
`secp256k1` public key:
```
026c64f5a7f24c6f7f0e1d6ec877f23b2f672fb48967c2545f227d70636395eaf3
```
Now that we have the raw public key, we'll now ask the DNS server to _resolve_
the virtual host given so we can obtain the IP information for the node:
```
$ dig ln1qfkxfad87fxx7lcwr4hvsalj8vhkwta539nuy4zlyf7hqcmrjh40xx5frs7.test.nodes.lightning.directory A
; <<>> DiG 9.10.6 <<>> ln1qfkxfad87fxx7lcwr4hvsalj8vhkwta539nuy4zlyf7hqcmrjh40xx5frs7.test.nodes.lightning.directory A
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 41934
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;ln1qfkxfad87fxx7lcwr4hvsalj8vhkwta539nuy4zlyf7hqcmrjh40xx5frs7.test.nodes.lightning.directory. IN A
;; ANSWER SECTION:
ln1qfkxfad87fxx7lcwr4hvsalj8vhkwta539nuy4zlyf7hqcmrjh40xx5frs7.test.nodes.lightning.directory. 60 IN A X.X.X.X
;; Query time: 83 msec
;; SERVER: 2600:1700:6971:6dd0::1#53(2600:1700:6971:6dd0::1)
;; WHEN: Thu Dec 31 16:59:22 PST 2020
;; MSG SIZE rcvd: 138
```
In the above command, we've queried the server so we can obtain an `IPv4`
address for our target node. Now that we have both the raw public key _and_ IP
address, we can connect to the node using the `brontide` transport protocol at:
`026c64f5a7f24c6f7f0e1d6ec877f23b2f672fb48967c2545f227d70636395eaf3@X.X.X.X`.
Querying for the curent `A` record for a given node can also be used to look up
the _latest_ set of addresses for a given node. Such queries can be used to
more quickly (compared to waiting on gossip as we'll cover later) sync the
latest addressing information for a node.
At this point in our journey, Norman our new Lightning Node has found its first
peer and established its first connect! Now we can being the second phase of
new peer bootstrapping: channel graph synchronization and validation, but
first, we'll explore more of the intricacies of BOLT 10 itself to take a deeper
look into how things work under the hood.
### A Deep Dive Into BOLT 10
As we learned earlier in the chapter, BOLT 10 describes the standardized
protocol for boostrapping new peer suing the DNS protocol. In this section,
we'll dive into the details of BOLT 10 itself in order to explore exactly how
bootstrapping queries are made, and also the additional set of options
available for querying.
#### SRV Query Options
The BOLT 10 standard is highly extensible due to its usage of nested
sub-domains as a communication layer for additional query options. The
bootstrapping protocol allows clients to further specify the _type_ of nodes
they're attempting to query for vs the default of receiving a random subset of
nodes in the query responses.
The query option sub-domain scheme uses a series of key-value pairs where the
key itself is a _single letter_ and the remaining set of text is the value
itself. The following query types exist in the current version of the BOLT 10
standards document:
* `r`: The "realm" byte which is used to determine which chain or realm
queries should be returned for. As is, the only value for this key is `0`
which denotes Bitcoin itself.
* `a`: Allows clients to filter out returned nodes based on the _types_ of
addresses they advertise. As an example, this can be used to only obtain
nodes that advertise a valid IPv6 address.
* The value that follows this type is based on a bitfled that _indexes_
into the set of specified address _type_ which are defined in BOLT 7.
We'll cover this material shortly later in this chapter once we examine
the structure of the channel graph itself.
* The default value for this field is `6`, which is `2 || 4`, which denotes
bit 1 and 2, which are IPv4 and IPv6.
* `l`: A valid node public key serialized in compressed format. This allows a
client to query for a specified node rather than receiving a set of random
nodes.
* `n`: The number of records to return. The default value for this field is
`25`.
An example query with additional query options looks something like the following:
```
r0.a2.n10.nodes.lightning.directory
```
Breaking down the query one key-value pair at a time we gain the following
insights:
* `r0`: The query targets the Bitcoin realm.
* `a2`: The query only wants IPv4 addresses to be returned.
* `n10`: The query requests
## Channel Graph: Structure and Attributes
Now that Norman is able to use the DNS boostrapping protocol to connect to his
very first peer, we can now start to sync the channel graph! However, before we
sync the channel graph, we'll need to learn exactly _what_ we mean by the
channel graph. In this section we'll explore the precise _structure_ of the
channel graph and examine the unique aspects of the channel graph compared to
the typical abstract "graph" data structure which is well known/used in the
field of Computer Science.
### The Channel Graph as a Directed Overlay Data Structure
A graph in computer science is a special data structure composed of vertices
(typically referred to as nodes) and edges (also known as links). Two nodes may
be connected by one or more edges. The channel graph is also _directed_ given
that a payment is able to flow in either direction over a given edge (a
channel). As we're concerned with _routing payments_, in our model a node with
no edges isn't considered to be a part of the graph as it isn't "productive".
In the context of the Lightning Network, our vertices are the Lightning nodes
themselves, with our edges being the channels that _connect_ these nodes. As
channels are themselves a special type of multi-sig UTXO anchored in the base
Bitcoin blockchain, possible to scan the chain (with the assistance of special
meta data proofs) and re-derive the channel graph first-hand (though we'd be
missing some information as we see below).
As channels themselves are UTXOs, we can view the channel graph as a special
sub-set of the UTXO set, on top of which we can add some additional information
(the nodes, etc) to arrive at the final overlay structure which is the channel
graph. This anchoring of fundamental components of the cahnnel graph in the
base Bitcoin blockchain means that it's impossible to _fake_ a valid channel
graph, which has useful properties when it comes to spam prevention as we'll
see later. The channel graph in the Lightning Network is composed of 3
individual components which are described in BOLT 7:
* `node_announcement`: The vertex in our graph which communicates the public
key of a node, as well as how to reach the node over the internet and some
additional metadata describing the set of _features_ the node supports.
* `channel_announcement`: A blockchain anchored proof of the existence of a
channel between two individual nodes. Any 3rd party can verify this proof in
order to ensure that a _real_ channel is actually being advertised. Similar
to the `node_announcement` this message also contains information describing
the _capabilities_ of the channel which is useful when attempting to route a
payment.
* `channel_update`: A _pair_ of structures that describes the set of _routing
policies_ for a given channel. `channel_update`s come in a _pair_ as a
channel is a directed edge, so both sides of the channel are able to specify
their own custom routing policy. An example of a policy communicated in a
It's important to note that each of components of the channel graph are
themselves _authenticated_ allowing a 3rd party to ensure that the owner of a
channel/update/node is actually the one sending out an update. This effectively
makes the Channel Graph a unique type of _authenticated data structure_ that
cannot be counterfeited. For authentication, we use an `secp256k1` ECDSA
digital signature (or a series of them) over the serialized digest of the
message itself. We won't get into the specific of the messaging
framing/serialization used in the LN in this chapter, as we'll cover that
information in Chapter XX on the wire protocol used in in the protocol.
With the high level structure of the channel graph laid out, we'll now dive
down into the precise structure of each of the 3 components of the channel
graph. We'll also explain how one can also _verify_ each component of the
channel graph as well.
#### Node Announcement: Structure & Validation
First, we have the `node_announcement` which plays the role of the vertex in
the channel graph. A node's announcement in the network serves to primary
purposes:
1. To advertise connection information so other nodes can connect to it,
either to bootstrap to the network, or to attempt to establish a set of new
channels.
2. To communicate the set of features protocol level features a node
understands. This communication is critical to the decentralized
de-synchronized update nature of the Lightning Network itself.
Unlike channel announcements, node announcements aren't actually anchored in
the base blockchain. As a result, advertising a node announcement in isolation
bares no up front cost. As a result, we require that all node announcements are
only considered "valid" if it has propagated with a corresponding channel
announcement as well. In other words, we always reject unconnected nodes in
order to ensure a rogue peer can't fill up our disk with bogus nodes that may
not actually be part of the network.
##### Structure
The node announcement is a simple data structure that needs to exist for each
node that's a part of the channel graph. The node announcement is comprised of
the following fields, which are encoded using the wire protocol structure
described in BOLT 1:
* `signature`: A valid ECDSA signature that covers the serialized digest of
all fields listed below. This signature MUST be venerated by the private
key that backs the public key of the advertised node.
* `features`: A bit vector that describes the set of protocol features that
this node understands. We'll cover this field in more detail in Chapter XX
on the extensibility of the Lightning Protocol. At a high level, this field
carries a set of bits (assigned in pairs) that describes which new features
a node understands. As an example, a node may signal that it understands
the latest and greatest channel type, which allows peers that which
bootstrap to the network to filter out the set of nodes they want to connect
to.
* `timestamp`: A timestamp which should be interpreted as a unix epoch
formatted timestamp. This allows clients to enforce a partial ordering over
the updates to a node's announcement.
* `node_id`: The `secp256k1` public key that this node announcement belongs
to. There can only be a single `node_announcement` for a given node in the
channel graph at any given time. As a result, a `node_announcement` can
superseded a prior `node_announcement` for the same node if it carries a
higher time stamp.
* `rgb_color`: A mostly unused field that allows a node to specify an RGB
"color" to be associated with it.
* `alias`: A UTF-8 string to serve as the nickname for a given node. Note
that these aliases aren't required to be globally unique, nor are they
verified in any shape or form. As a result, they are always to be
interpreted as being "unofficial".
* `addresses`: A set of public internet reachable addresses that are to be
associated with a given node. In the current version of the protocol 4
address types are supported: IPv4 (1), IPv6 (2), Tor V2 (3), Tor V3 (4). On
the wire, each of these address types are denoted by an integer type which
is included in parenthesis after the address type.
##### Validation
Validating an incoming `node_announcement` is straight forward, the following
assertions should be upheld when examining a node announcement:
* If an existing `node_announcement` for that node is already known, then the
`timestamp` field of a new incoming `node_announcement` MUST be greater
than the prior one.
* With this constraint, we enforce a forced level of "freshness".
* If no `node_announcement` exist for the given node, then an existing
`channel_announcement` that refernces the given node (more on that later)
MUST already exist in one's local channel graph.
* The included `signature` MUST be a valid ECDSA signature verified using the
included `node_id` public key and the double-sha256 digest of the raw
message encoding (mins the signature and frame header!) as the message.
* All included `addresses` MUST be sorted in ascending order based on their
address identifier.
* The included `alias` bytes MUST be a valid UTF-8 string.
#### Channel Announcement: Structure & Validation
Next, we have the `channel_announcement`. This message is used to _announce_ a
new _public_ channel to the wider network. Note that announcing a channel is
_optional_. A channel only needs to be announced if its intended to be used for
routing by the public network. Active routing nodes may wish to announce all
their channels. However, certain nodes like mobile nodes likely don't have the
uptime or desire required to be an active routing node. As a result, these
mobile nodes (which typically use light clients to connect to the Bitcoin p2p
network), instead may have purely _unadvertised_ channels.
##### Unadvertised Channels & The "True" Channel Graph
An unadvertised channel isn't part of the known public channel graph, but can
still be used to send/receive payments. An astute reader may now be wondering
how a channel which isn't part of the public channel graph is able to receive
payments. The solution to this problem is a set of "path finding helpers" that
we call "routing hints. As we'll see in Chapter XX on the presentation/payment
layer, invoices created by nodes with unadvertised channels will include
auxiliary information to help the sender route to them assuming the no has at
least a single channel with an existing public routing node.
Due to the existence of unadvertised channels, the _true_ size of the channel
graph (both the public and private components) is unknown. In addition, any
snapshot of the channel graph that doesn't come directly from one's own node
(via a Block Explorer or the like) is to be considered non-canonical as
updates to the graph are communicated using a system that only is able to
achieve an eventually consistent view of the channel graph.
##### Locating Channel In the Blockchain via Short Channel IDs
As mentioned earlier, the channel graph is authenticated due to its usage of
public key cryptography, as well as the Bitcoin blockchain as a spam prevention
system. In order to have a node accept a new `channel_announcement`, the
advertise must _prove_ that the channel actually exists in the Bitcoin
blockchain. This proof system adds an upfront cost to adding a new entry to the
channel graph (the on-chain fees on must pay to create the UTXO of the
channel). As a result, we mitigate spam and ensure that another node on the
network can't costless fill up the disk of an honest node with bogus channels.
Given that we need to construct a proof of the existence of a channel, a
natural question that arises is: how to we "point to" or reference a given
channel for the verifier? Given that a channel MUST be a UTXO, an initial
thought might be to first attempt to just advertise the full outpoint
(`txid:index`) of the channel. Given the outpoint of a UTXO is globally unique
one confirmed in the chain, this sounds like a good idea, however it has one
fatal flow: the verifier must maintain a full copy of the UTXO set in order to
verify channels. This works fine for full-node, but light clients which rely on
primarily PoW verification don't typically maintain a full UTXO set. As we want
to ensure we can support mobile nodes in the Lightning Network, we're forced to
find another solution.
What if rather than referencing a channel by its UTXO, we reference it based on
its "location" in the chain? In order to do this, we'll need a scheme that
allows us to "index" into a given block, then a transaction within that block,
and finally a specific output created by that transaction. Such an identifier
is described in BOLT 7 and is referred to as a: short channel ID, or `scid`.
The `scid` is used both in `channel_announcement` (and `channel_update`) as
well as within the onion encrypted routing packet included within HTLCs as we
learned in Chapter XX.
###### The Short Channel ID Identifier
Based on the information above, we have 3 piece of information we need to
encode in order to uniquely reference a given channel. As we want to very
compact representation, we'll attempt to encode the information into a _single_
integer using existing known bit packing techniques. Our integer format of
choice is an unsigned 64-bit integer, which is comprised of 8 logical bytes.
First, the block height. Using 3 bytes (24-bits) we can encode 16777216 blocks,
which is more than double the number of blocks that are attached to the current
mainnet Bitcoin blockchain. That leaves 5 bytes left for us to encode the
transaction index and the output index respectively. We'll then use the next 3
bytes to encode the transaction index _within_ a block. This is more than
enough given that it's only possible to fix tens of thousands of transactions
in a block at current block sizes. This leaves 2 bytes left for us to encode
the output index of the channel within the transaction.
Our final `scid` format resembles:
```
block_height (3 bytes) || transaction_index (3 bytes) || output_index (2 byes)
```
Using bit packing techniques, we first encode the most significant 3 bytes as
the block height, the next 3 bytes as the transaction index, and the least
significant 2 bytes as the output index of that creates the channel UTXO.
A short channel ID can be represented as a single integer
(`695313561322258433`) or as a more human friendly string: `632384x1568x1`.
Here we see the channel was mined in block `632384`, was the `1568` th
transaction in the block, with the channel output being found as the second
(UTXOs are zero-indexed) output produced by the transaction.
Now that we're able to succinctly defence a given channel in the chain, we can
now examine the full structure of the `channel_announcement` message, as well
as how to verify the proof-of-existence included within the message.
##### Channel Announcement Structure
A channel announcement primarily communicates two aspects:
1. A proof that a channel exists between Node A and Node B with both nodes
controlling the mulit-sig keys in the refracted channel output
2. The set of capabilities of the channel (what types of HTLCs can it route,
etc)
When describing the proof, we'll typically refer to node `1` and node `2`. Out
of the two nodes that a channel connects, the "first" node is the node that has
a "lower" public key encoding when we compare the public key of the two nodes
in compressed format hex-encoded in lexicographical order. Correspondingly, in
addition to a node public key on the network, each node should also control a
public key within the Bitcoin blockchain.
Similar to the `node_announcement` message, all included signatures of the
`channel_announcement` message should be signed/verified against the raw
encoding of the message (minus the header) that follows _after_ the final
signature (as it isn't possible for a signature to sign itself..)
With that said, a `channel_announcement` message (the edge descriptor in the
channel graph) has the following attributes:
* `node_signature_1`: The signature of the first node over the message digest.
* `node_signature_2`: The signature of the second node over the message
digest.
* `bitcoin_signature_1`: The signature of the multi-sig key (in the funding
output) of the first node over the message digest.
* `bitcoin_signature_2`: The signature of the multi-sig key (in the funding
output) of the second node over the message digest.
* `features`: A feature bitvector that describes the set of protocol level
features supported by this channel.
* `chain_hash`: A 32 byte hash which is typically the genesis block hash of
the chain the channel was opened within.
* `short_channel_id`: The `scid` that uniquely locates the given channel
within the blockchain.
* `node_id_1`: The public key of the first node in the network.
* `node_id_2`: The public key of the second node in the network.
* `bitcoin_key_1`: The raw multi-sig key for the channel funding output for
the first node in the network.
* `bitcoin_key_2`: The raw multi-sig key for the channel funding output for
the second node in the network.
##### Channel Announcement Validation
Now that we know what a `channel_announcement` contains. We can now move onto
to exactly _how_ to verify such an announcement.
#### Channel Update: Structure & Validation
// TODO(roasbeef): rename to "the structure of the channel graph"?
## Syncing the Channel Graph
* introduce the NodeAnnouncement (purpose structure validation)
* go thru fields, ref ability to use Tor, etc
* ref feature bits at high level, say will be covered in later chapter
* node announcement validation
* acceptance critera
### Channel Announcement
## Ongoing Channel Graph Maintenance
### Gossip Protocols in the Abstract
* what is a gossip protocol?
* why are they used?
* what other famous uses of gossip protocols are out there?
* when does it make sense to use a gossip protocol?
* what are some use a gossip protocol?
* why does LN uise
* questions to ask for gossip rptocol
* what is being gossiped
* what is the expected delay bound?
* how is DoS prevented
## Gossip in LN
### Channel Announcements
### Purpose
### Structure
### Validation
### Channel Updates
### Purpose
### Structure
### Validation
### Node Announcements
### Purpose
### Structure
### Validation
* anser the three quesitons above
* what: node info, chan info, channel updates
* delay: 2 week liveness assumption, otherwise pruned, keep alive updates
* DoS: real channel, proper validation of sigs, etc
# Conlusion

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 KiB

@ -1,7 +1,7 @@
[[set_up_a_lightning_node]]
== Lightning Node Software
As we have seen in previous chapters, a Lightning node is a computer system that participates in the Lightning Network. The Lightning Network is not a product or company, it is a set of open standards that define a baseline for interoperability. As such, Lightning node software has been built by a variety of companies and community groups. The vast majority of Lightning software is _open source_, meaning that the source code is open and licensed in such a way as to enable collaboration, sharing and community participation in the development process. Similarly, the Lightning node implementations we will present in this chapter are all open source and collaborative developed.
As we have seen in previous chapters, a Lightning node is a computer system that participates in the Lightning Network. The Lightning Network is not a product or company, it is a set of open standards that define a baseline for interoperability. As such, Lightning node software has been built by a variety of companies and community groups. The vast majority of Lightning software is _open source_, meaning that the source code is open and licensed in such a way as to enable collaboration, sharing and community participation in the development process. Similarly, the Lightning node implementations we will present in this chapter are all open source and are collaboratively developed.
Unlike Bitcoin, where the standard is defined by a _reference implementation_ in software (Bitcoin Core), in Lightning the standard is defined by a series of standards documents called _Basis of Lightning Technology (BOLT)_, found at the _lightning-rfc_ repository at:
@ -886,7 +886,7 @@ $ mvn package
[INFO] eclair-node-gui [jar]
[INFO]
[INFO] --------------------< fr.acinq.eclair:eclair_2.13 >---------------------
[INFO] Building eclair_2.13 0.4.1-SNAPSHOT [1/4]
[INFO] Building eclair_2.13 0.4.3-SNAPSHOT [1/4]
[INFO] --------------------------------[ pom ]---------------------------------
[...]
@ -899,12 +899,16 @@ $ mvn package
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:06 min
[INFO] Finished at: 2020-06-26T09:43:21-04:00
[INFO] Finished at: 2020-12-12T09:43:21-04:00
[INFO] ------------------------------------------------------------------------
----
After several minutes the build of the Eclair package will complete. You will find the Eclair server node under +eclair-node/target+, packaged as a zip file. Unzip and run it, by following the instructions found here:
The build logs above contain "2.13", for building a commit around version 0.4.3, this is expected.
After several minutes the build of the Eclair package should complete. But the "package" action will also run tests, and some of them connect to the internet, which could fail. If you want to skip tests, add +-DskipTests+ to the command.
Now, unzip and run the built package, by following the instructions found here:
https://github.com/ACINQ/eclair#installing-eclair

@ -25,7 +25,7 @@ Let's get started!
It is important that one sets her or his own expectations correctly on accurate facts.
If one plans to operate a Lightning node _solely_ to gain income by earning routing fees,
please do your homework diligently first. Running a profitable business by operating a Lighning node is
defintely _not_ easy. Calculate all your initial and ongoing costs in a spreadsheet. Study Lightning Network statistics carefully.
definitely _not_ easy. Calculate all your initial and ongoing costs in a spreadsheet. Study Lightning Network statistics carefully.
What is the current payment volume? What is the volume per node? What are the current average routing fees? Consult forums and ask
for advice or feedback from other community members who have already gained real-world experience. Form your own educated opinion only
_after_ you have done this due-diligence exercise. Most people will find their motivation for running a node not in financial gain
@ -156,6 +156,28 @@ In addition to a Bitcoin and Lightning node, MyNode can optionally install a var
- lndmanage (CLI management tool)
- btc-rpc-explorer (A Bitcoin blockchain explorer)
==== Umbrel
Famous for their UX/UI, _Umbrel_ provides a very easy and accessible way to get your Bitcoin and Lightning node up and running in no time, especially for beginners. A very distinctive feature is that _Umbrel_ utilizes Neutrino/SPV during the IBD (Inital Blockchain Download) so you can instantly start using your node. Once Bitcoin Core is fully synced in the background it automatically switches over and disables SPV mode. Umbrel OS supports the Raspberry Pi 4 and can also be installed on any Linux-based OS or on a virtual machine on macOS or Windows. You can also connect any wallet that supports Bitcoin Core P2P, Bitcoin Core RPC, the Electrum protocol or lndconnect.
No need to wait for a rainy day, you can find the project here: https://getumbrel.com
image::images/umbrel.png[]
In addition to a Bitcoin and Lightning node, Umbrel introduced the Umbrel App Store, where you can easily install additional services, such as:
* Lightning Terminal (Interface for managing channel liquidity, loop-in & loop-out)
* Ride The Lightning (Lightning Node Management GUI)
* Specter Desktop (watch-only coordinator for multi-signature and single-key Bitcoin wallets)
* BTCPayServer (Cryptocurrency Payment Processor)
* BTC-RPC-Explorer (Bitcoin Blockchain Explorer)
* ThunderHub (Monitor and manage your node)
* Sphinx Relay (Handling connectivity and storage for Sphinx chat)
* mempool.space (Mempool visualizer and block explorer)
* LNbits (Lightning wallet/accounts System)
Currently still in beta and not considered secure.
==== BTCPay Server
While not initially designed as an installation "helper", the e-commerce and payment platform _BTCPay Server_ has an incredibly easy installation system that uses docker containers and +docker-compose+ to install a Bitcoin node, Lightning node, and payment gateway, among many other services. It can be installed on a variety of hardware platforms, from a simple Raspberry Pi 4 (4GB recommended) to a mini-PC, old laptop, desktop or server.
@ -255,10 +277,10 @@ In addition, if you have connected an external drive, you will need to tell the
On most Linux systems you can create a new user with the +useradd+ command, like this:
----
$ sudo useradd -d /external_drive/bitcoin -s /dev/null bitcoin
$ sudo useradd -m -d /external_drive/bitcoin -s /dev/null bitcoin
----
The +d+ flag assigns the user's home directory. In this case, we put it on the external drive. The +s+ flag assigns the user's interactive shell. In this case we set it to +/dev/null+ to disable interactive shell use. The last argument is the new user's username +bitcoin+.
The +m+ and +d+ flags create the user's home directory as specified by /external_drive/bitcoin in this case. The +s+ flag assigns the user's interactive shell. In this case we set it to +/dev/null+ to disable interactive shell use. The last argument is the new user's username +bitcoin+.
==== Node startup

Loading…
Cancel
Save