Merge branch 'develop'

pull/649/head
Andreas M. Antonopoulos 3 years ago
commit 6258790ac7

@ -2,106 +2,228 @@
[[intro_what_is_the_lightning_network]]
== Introduction
Welcome to Mastering the Lightning Network!
Welcome to _Mastering the Lightning Network_!
The Lightning Network, abbreviated with LN, is a protocol for using Bitcoin in a smart and non-obvious way.
Thus it is a second layer technology on top of Bitcoin.
It is changing the way people exchange value online and it's one of the most exciting advancements to happen to the Bitcoin network over the past few years. Right now, the Lightning Network is in its infancy. In concept it's about 5 years old, in implementation about 3 years old. We're only beginning to see the opportunities the Lightning Network provides including improved privacy, speed, and scale. With core knowledge of the Lightning Network, you can help shape the future of the network while building opportunities for yourself as well. Some basic knowledge about Bitcoin is assumed but can be readily acquired by reading the first two chapters of _Mastering Bitcoin_ which are available for free online.
The Lightning Network, often abbreviated as "LN", is changing the way people exchange value online and it's one of the most exciting advancements to happen in Bitcoin's history.
Today, in 2021, the Lightning Network is still in its infancy. The Lightning Network is a protocol for using Bitcoin in a smart and non-obvious way. It is a second layer technology on top of Bitcoin.
While the bulk of this book is written for programmers, the first two chapters are written to be approachable by anyone regardless of technical experience. In order to better understand how the technology actually works, and why people use it, we'll be following a number of users and their stories. But first, we'll introduce some of the key concepts in the Lightning Network. Let's get started with why the Lightning Network was proposed in the first place.
The concept of the Lightning Network was proposed in 2015 and the first implementation was launched in 2018. As of 2021, we're only beginning to see the opportunities the Lightning Network provides to Bitcoin including improved privacy, speed, and scale.
With core knowledge of the Lightning Network, you can help shape the future of the network while also building opportunities for yourself.
=== Motivation for the Lightning Network
We assume you already have some basic knowledge about Bitcoin but if not don't worry, we will explain the most important Bitcoin concepts, those you must know to understand the Lightning Network, in <<bitcoin_fundamentals>>. If you want to learn more about Bitcoin, you can read _Mastering Bitcoin_, available for free online.
While the bulk of this book is written for programmers, the first few chapters are written to be approachable by anyone regardless of technical experience. In this chapter, we'll start with some terminology, then move to looking at trust and its application in these systems, and finally we'll discuss the history and future of the Lightning Network. Let's get started.
=== Lightning Network Basic Concepts
As we explore how the Lightning Network actually works, we will encounter some technical terminology that might, at first, be a bit confusing. While all of these concepts and terms will be explained in detail as we progress through the book, and are defined in the glossary, some basic definitions now will make it easier to understand the concepts in the next two chapters. If you don't understand all of the words in these definitions yet, that's okay. You'll understand more as you move through the text.
Node:: A computer that participates in a network. A Lightning node is a computer that participates in the Lightning Network. A Bitcoin node is a computer that participates in the Bitcoin Network. Typically a Lightning Network user will run a Lightning node _and_ a Bitcoin node.
Blockchain:: A distributed transaction ledger, produced by a network of computers. Bitcoin, for example, is a system that produces a blockchain. The Lightning Network is not itself a blockchain, nor does it produce a blockchain. It is a network that relies on an existing external blockchain for its security.
Transaction:: A data structure that records the transfer of control over some funds (e.g. some bitcoin). The Lightning Network relies on Bitcoin transactions (or those of another blockchain) to track control of funds.
Payment:: When value is exchanged on the Lightning Network we call this a "payment" as compared to a "transaction" on the Bitcoin Blockchain.
As Bitcoin and the demand for transactions grows, the number of transactions in each block will increase until it eventually hits the block size limit. When blocks are full, excess transactions are left to wait in a queue. Many users increase the fees they're willing to pay in order to buy space for their transaction in the next block. At the same time, an increasing number of users are left behind. Their transactions, e.g. microtransactions such as common small spendings, are not economically qualified to be on the network. However, increasing block size simply shifts the problem to node operators, where each increase in blocksize results in a resource increase multiplied by an order of magnitude.
Payment Channel:: A _financial relationship_ between two nodes on the Lightning Network, typically implemented by multi-signature Bitcoin transactions that share control over bitcoin between the two Lightning nodes.
Routing vs Sending:: Unlike Bitcoin where transactions are "sent" by broadcasting them to everyone, Lightning is a routed network where payments are "routed" across one or more payment channels following a _path_ from sender to recipient.
On-Chain vs. Off-Chain:: A payment is "on-chain" if it is recorded as a transaction on the Bitcoin (or other underlying) blockchain. Payments sent via payment channels between Lightning nodes, and which are not visible in the underlying blockchain, are called "off-chain" payments. Usually in the Lightning Network, the only on-chain transactions are those used to open and close a Lightning payment channel.
Because blockchains are gossip protocols, each node is required to know and validate every single transaction that occurs on the network. Furthermore, once validated, each transaction and block must be propagated to the node's "neighbors", multiplying the bandwidth requirements. As such, the greater the block size, the greater the bandwidth, processing, and storage requirements for each individual node, effectively limiting the amount of scaling that can be done this way. Furthermore, scaling in this fashion has an undesirable side effect of centralizing the network by reducing the number of nodes and node operators. Since node operators are not compensated for running nodes, if nodes are very expensive to run, only a few well funded node operators will continue to run nodes.
More detailed definitions of these and many other terms can be found in the <<glossary>>. Throughout this book, we will explain what these concepts mean and how these technologies actually work.
[NOTE]
[TIP]
====
The side effects of increasing the block size or decreasing the block time with respect to centralization of the network are severe as a few calculations with the numbers show.
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 single hosts on the internet could handle such a load of traffic our current internet would not be able to support this traffic for a large fraction of hosts.
Also storing this information locally would result in 864,000 Megabyte per day. This is roughly 1 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.
Throughout this book, you will see "Bitcoin" with the first letter capitalized, which refers to the _Bitcoin System_ and is a proper noun. You will also see "bitcoin", with a lower-case _b_, which refers to the currency unit. Each bitcoin is further subdivided into 100 million units each called a "satoshi" (singular) or "satoshis" (plural)
====
But what if each node wasn't required to know and validate every single transaction? What if there was a way to have scalable off-chain transactions, without losing the security of the Bitcoin network?
Now that you're familiar with these basic terms, let's move to a concept you are already comfortable with: trust.
In February 2015, Joseph Poon and Thaddeus Dryja proposed a possible solution to the Bitcoin Scalability Problem, with the publication of _"The Bitcoin Lightning Network: Scalable Off-Chain Instant Payments"_ footnote:[Joseph Poon, Thaddeus Dryja - "The Bitcoin Lightning Network:
Scalable Off-Chain Instant Payments" (https://lightning.network/lightning-network-paper.pdf).] In the meanwhile outdated whitepaper, Poon and Dryja estimate that in order for Bitcoin to reach the 47,000 transactions per second processed at peak by Visa, it would require 8 GB blocks. This would make running a node completely untenable for anyone but large scale enterprises and industrial grade operations. The result would be a network in which only a few users can actually validate the state of the ledger, which ultimately breaks the trust model of Bitcoin.
The Lightning Network proposes a new network, a "second layer", where users can make payments to each other peer-to-peer, without the necessity to publish a transaction to the Bitcoin blockchain for each payment.
Users may pay each other on the Lightning Network as many times as they want, making use of the Bitcoin blockchain only in order to load bitcoin onto the Lightning network initially and to "settle", that is: remove bitcoin from the Lightning Network.
The result is that many more Bitcoin payments can take place "off-chain", with only the initial loading and final settlement transactions needing to be validated and stored by Bitcoin nodes.
Aside from reducing the burden on nodes, payments on the Lightning Network will be cheaper for users as they do not need to pay blockchain fees, and more private for users as they are not published to all participants of the network and furthermore not stored permanently.
=== Trust in decentralized networks
While the Lightning Network was initially conceived for Bitcoin, it can be implemented on any blockchain that meets its technical requirements.
You will often hear people calling Bitcoin and the Lightning Network "trustless". At first glance this is confusing. After all, isn't trust a good thing? Banks even use it in their names! Isn't a "trustless" system, a system devoid of trust, a bad thing?
=== Lightning Network Basic Concepts
The use of the the word "trustless" is intended to convey the ability to operate without _needing_ trust in the other participants in the system. In a decentralized system like Bitcoin you can always choose to transact with someone you trust. However, the system ensures you can't be cheated even if you can't trust the other party in a transaction. Trust is a nice-to-have instead of a must-have property of the system.
As we start exploring the Lightning Network, we will encounter some technical terminology that might, at first, be confusing and a bit difficult to understand. While all of these concepts and terms will be explained in detail as we progress through the book, and are defined in the glossary, we need some basic clarifications to get started. Here are some of the concepts you will encounter in the first two chapters of this book:
Contrast that to traditional systems, like banking where you _must_ place your trust in a third party, since they control your money. If the bank violates your trust you may be able to find some recourse from a regulator or court, but at an enormous cost of time, money, and effort.
Node:: A computer that participates in a network. A Lightning node is a computer that participates in the Lightning Network. A Bitcoin node is a computer that participates in the Bitcoin Network. Typically a Lightning Network user will run a Lightning node and a Bitcoin node.
Trustless does not mean devoid of trust. It means that trust is not a necessary prerequisite to all transactions and that you can transact even with people you don't trust because the system prevents cheating.
Blockchain:: A distributed transaction ledger, produced by a network of computers. Bitcoin, for example, is a system that produces a blockchain. The Lightning Network is not itself a blockchain, nor does it produce a blockchain. It is a network that relies on an existing external blockchain for its security.
Before we get into how the Lightning Network works, it's important to understand one basic concept that underlies Bitcoin, the Lightning Network and many other such systems: something we call a _fairness protocol_. A fairness proctocol is a way to
Transaction:: A data structure that records the transfer of control over some funds (e.g. some bitcoin). The Lightning Network relies moreover on Bitcoin transactions (or those of another blockchain) to track control of funds.
_achieve fair outcomes between participants, who do not need to trust each other, without the need for a central authority_ and it is the backbone of decentralized systems like Bitcoin.
Payment:: When value is exchanged on the Lightning Network we call this a payment as the term Transaction is the technical term for entries on the Bitcoin Blockchain.
Payment Channel:: A _financial relationship_ between two nodes on the Lightning Network, typically implemented by multi-signature Bitcoin transactions that share control over bitcoin between the two Lightning nodes.
=== Fairness without central authority
On-Chain vs. Off-Chain:: A payment is "on-chain" if it is recorded as a transaction on the Bitcoin (or other underlying) blockchain. Payments sent via payment channels between Lightning nodes, and which are not visible in the underlying blockchain, are called "off-chain" payments.
When people have competing interests, how can they establish enough trust to engage in some cooperative or transactional behavior? The answer to this question lies at the core of several scientific and humanistic disciplines, such as economics, sociology, behavioral psychology, and mathematics. Some of those disciplines give us "soft" answers, that depend on concepts such as reputation, fairness, morality, even religion. Other disciplines give us concrete answers that depend only on the assumption that the participants in these interactions will act rationally, with their self-interest as the main objective.
More detailed definitions of these and many other terms can be found in the <<glossary>>. Throughout this book we will explain what these concepts mean and how these technologies actually work.
In broad terms there are a handful of ways to ensure fair outcomes in interactions between individuals who may have competing interests:
[TIP]
* Require trust - you only interact with people who you already trust, due to prior interactions, reputation, or familial relationships. This works well enough at small scale, especially within families and small groups, that it is the most common basis for cooperative behavior. Unfortunately, it doesn't scale and it suffers from tribalist (in-group) bias.
* Rule of law - establish rules for interactions that are enforced by an institution. This scales better, but it cannot scale globally due to differences in customs and traditions, as well as the inability to scale the institutions of enforcement. One nasty side-effect of this solution is that the institutions become more and more powerful as they get bigger and that may lead to corruption.
* Trusted third parties - put an intermediary in every interaction to enforce fairness. Combined with the "rule of law" to provide oversight of intermediaries, this scales better, but suffers from the same imbalance of power: the intermediaries get very powerful and may attract corruption. Concentration of power leads to systemic risk and systemic failure ("Too big to fail").
* Game theoretical fairness protocols - this last category emerges from the combination of the internet and cryptography and is the subject of this section. Let's see how it works and what its advantages and disadvantages are.
==== Trusted protocols without intermediaries
Cryptographic systems like Bitcoin and the Lightning Network are systems that allow you to transact with people (and computers) that you don't trust. This is often referred to as "trustless" operation, even though it is not actually trustless. You have to trust in the software that you run and you have to trust that the protocol implemented by that software will result in fair outcomes.
The big distinction between a cryptographic system like this and a traditional financial system, is that in traditional finance you have a _trusted third party_, for example a bank, to ensure that outcomes are fair. A significant problem with such systems is that they give too much power to the third party and they are also vulnerable to a _single point of failure_. If the trusted third party itself violates trust or attempts to cheat, the basis of trust breaks.
As you study cryptographic systems, you will notice a certain pattern: instead of relying on a trusted third party, these systems attempt to prevent unfair outcomes by using a system of incentives and disincentives. In cryptographic systems you place trust in the _protocol_, which is effectively a system with a set of rules that, if properly designed, will correctly apply the desired incentives and disincentives. The advantage of this approach is two fold. Not only do you avoid trusting a third party, you also reduce the need to enforce fair outcomes. So long as the participants follow the agreed protocol and stay within the system, the incentive mechanism in that protocol achieves fair outcomes without enforcement.
The use of incentives and disincentives to achieve fair outcomes is one aspect of a branch of mathematics called _game theory_, which studies "models of strategic interaction among rational decision makers" footnote:[Wikipedia "Game Theory": https://en.wikipedia.org/wiki/Game_theory]. Cryptographic systems that control financial interactions between participants, such as Bitcoin and the Lightning Network rely heavily on game theory to prevent participants from cheating and allow participants who don't trust each other to achieve fair outcomes.
While game theory and its use in cryptographic systems may appear confounding and unfamiliar at first, chances are you're already familiar with these systems in your everyday life, you just don't recognize them yet. Below we'll use a simple example from childhood to help us identify the basic pattern. Once you understand the basic pattern you will see it everywhere in the blockchain space and you will come to recognize it quickly and intuitively.
In this book, we call this pattern a _Fairness Protocol_ defined as a process that uses a system of incentives and/or disincentives to ensure fair outcomes for participants who don't trust each other. Enforcement of a fairness protocol is only necessary to ensure that the participants can't escape the incentives or disincentives.
==== A fairness protocol in action
Let's look at an example of a fairness protocol, which you may already be familiar with.
Imagine a family lunch, with a parent and two children. The children are fussy eaters and the only thing they will agree to eat is fried potatoes. The parent has prepared a bowl of fried potatoes ("french fries" or "chips" depending on which English dialect you use). The two siblings must share the plate of chips. The parent must ensure a fair distribution of chips to each child, otherwise the parent will have to hear constant complaining (maybe all day) and there's always a possibility of an unfair situation escalating to violence. What is a parent to do?
There are a few different ways that fairness can be achieved in this strategic interaction between two siblings that do not trust each other and have competing interests. The naive but commonly used method is for the parent to use their authority as a trusted third party: they split the bowl of chips into two servings. This is similar to traditional finance, where a bank, accountant or lawyer acts as a trusted third party to prevent any cheating between two parties who want to transact.
The problem with this scenario is that it vests a lot of power and responsiblity in the hands of the trusted third party. In this example, the parent is fully responsible for the equal allocation of chips, the parties merely wait, watch, and complain. The children accuse the parent of playing favorites and not allocating the chips fairly. The siblings fight over the chips, yelling "that chip is bigger!", and dragging the parent into their fight. It sounds awful, doesn't it? Should the parent yell louder? Take all of the chips away? Threaten to never make chips again and let those ungrateful children go hungry?
A much better solution exists: the siblings are taught to play a game called "split and choose". At each lunch one sibling splits the bowl of chips into two servings and the *other* sibling gets to choose which serving they want. Almost immediately, the siblings figure out the dynamic of this game. If the one splitting makes a mistake or tries to cheat, the other sibling can "punish" them by choosing the bigger bowl. It is in the best interest of both siblings, but especially the one splitting the bowl, to play fair. Only the cheater loses in this scenario. The parent doesn't even have to use their authority or enforce fairness. All the parent has to do is _enforce the protocol_; as long as the siblings cannot escape their assigned roles of "splitter" and "chooser", the protocol itself ensures a fair outcome without the need for any intervention. The parent can't play favorites or distort the outcome.
[WARNING]
====
Throughout this book you will see "Bitcoin" with the first letter capitalized, which refers to the _Bitcoin System_ and is a proper noun. You will also see "bitcoin", with a lower-case _b_, which refers to the currency unit.
While the infamous chip battles of the 1980's neatly illustrate the point, any similarity between the scenario above and any of the authors' actual childhood experiences with their cousins is entirely coincidental... Or is it?
====
=== What is the Lightning Network?
==== Security primitives as building blocks
In order for a fairness protocol like this to work, there need to be certain guarantees, or _security primitives_ that can be combined to ensure enforcement. The first security primitive is _strict time ordering/sequencing_: the "splitting" action must happen before the "choosing" action. It's not immediately obvious, but unless you can guarantee that action A happens before action B, then the protocol falls apart. The second security primitive is _commitment with non-repudiation_. Each sibling must commit to their choice of role: either splitter or chooser. Also, once the splitting has been completed, the splitter is committed to the split they created - they cannot repudiate that choice and go try again.
Cryptographic systems offer a number of security primitives that can be combined in different ways to construct a fairness protocol. In addition to sequencing and commitment, we can also use many other tools:
- Hash functions to fingerprint data, as a form of commitment, or as the basis for a digital signature.
- Digital signatures for authentication, non-repudiation, and proof of ownership of a secret.
- Encryption/decryption to restrict access to information to authorized participants only.
This is only a small list of a whole "menagerie" of security and cryptographic primitives that are in use. More basic primitives and combinations are invented all the time.
In our real-life example, we saw one form of fairness protocol called "split and choose". This is just one of a myriad different fairness protocols that can be built by combining the building blocks of security primitives in different ways. But the basic pattern is always the same: two or more participants interact without trusting each other, by engaging in a series of steps that are part of an agreed protocol. The protocol's steps arrange incentives and disincentives to ensure that if the participants are rational, cheating is counter-productive and fairness is the automatic outcome. Enforcement is not necessary to get fair outcomes - it is only necessary to keep the participants from breaking out of the agreed protocol.
Now that you understand this basic pattern, you will start seeing it everywhere in Bitcoin, the Lightning Network and many other systems. Let's look at some specific examples, next.
==== Example of the fairness protocol
The most prominent example of a "fairness protocol", is Bitcoin's consensus algorithm _Proof of Work_ (PoW). In Bitcoin, miners compete to verify transactions and aggregate them in blocks. To ensure that the miners do not cheat, without entrusting them with authority, Bitcoin uses a system of incentives and disincentives. Miners have to use a lot of electricity doing "work", that is embedded as a "proof" inside every block. This is achieved because of a property of hash functions where the output value is randomly distributed across the entire range of possible outputs. If miners succeed in producing a valid block fast enough, they are rewarded by earning the block reward for that block. Forcing miners to use a lot of electricity before the network considers their blocks means that they have an incentive to correctly validate the transactions in the block. If they cheat or make any kind of mistake, their block is rejected and the electricity they used to "prove" it is wasted. No one needs to force miners to produce valid blocks, the reward and punishment incentivize them to do so. All the protocol needs to do is ensure that only valid blocks with proof of work are accepted.
The "fairness protocol" pattern can also be found in many different aspects of the Lightning Network:
* Those who fund channels make sure that they have a refund transaction signed before they publish the funding transaction.
* Whenever a channel is moved to a new state, the old state is "revoked" by ensuring that if anyone tries to broadcast it, they lose the entire balance and get punished.
* Those who forward payments know that if they commit funds forward, they can either get a refund or they get paid by the node preceding them.
Again and again, we see this pattern. Fair outcomes are not enforced by any authority. They emerge as the natural consequence of a protocol that rewards fairness and punishes cheating. A fairness protocol that harnesses self-interest by directing it towards fair outcomes.
Bitcoin and the Lightning Network are both implementations of fairness protocols. So why do we need the Lightning Network? Isn't Bitcoin enough?
=== Motivation for the Lightning Network
Bitcoin is a system that records transactions on a globally replicated public ledger. Every transaction is seen, validated and stored by every participating computer. As you can imagine, this generates a lot of data and is difficult to scale.
As Bitcoin and the demand for transactions grew, the number of transactions in each block increased until it eventually reached the block size limit.
Once blocks are "full", excess transactions are left to wait in a queue.
Many users will increase the fees they're willing to pay in order to buy space for their transactions in the next block.
If demand continues to outpace the capacity of the network, an increasing number of user's transactions are left waiting unconfirmed. Competition for fees also increases the cost of each transaction, making many smaller-value transactions (e.g. micro-transactions) completely uneconomical during these periods of high demand.
To solve this problem, we could increase the block size limit to create space for more transactions. An increase in the "supply" of block space will lead to a lower price equilibrium for transaction fees.
However, increasing block size shifts the cost to node operators, and requires them to expend more resources to validate and store the blockchain. Because blockchains are gossip protocols, each node is required to know and validate every single transaction that occurs on the network. Furthermore, once validated, each transaction and block must be propagated to the node's "neighbors", multiplying the bandwidth requirements. As such, the greater the block size, the greater the bandwidth, processing, and storage requirements for each individual node. Increasing transaction capacity in this way has the undesirable effect of centralizing the system by reducing the number of nodes and node operators. Since node operators are not compensated for running nodes, if nodes are very expensive to run, only a few well funded node operators will continue to run nodes.
.Scaling Blockchains
****
The side effects of increasing the block size or decreasing the block time with respect to centralization of the network are severe as a few calculations with the numbers show.
Let us assume the usage of Bitcoin grows so that the network has to process 40,000 transactions per second, which is the approximate transaction processing level of the VISA network during peak usage.
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 fiber optic 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 864GB Megabytes per day. This is roughly one Terabyte of data or the size of a hard drive.
Verifying 40,000 ECDSA signatures per second is also barely feasible (c.f.: https://bitcoin.stackexchange.com/questions/95339/how-many-bitcoin-transactions-can-be-verified-per-second) making the _Initial Blockchain Download (IBD)_ of the Bitcoin blockchain (synchronizing and verifying everything starting from the genesis block) almost impossible without very expensive hardware.
While 40,000 transactions per second seems like a lot it only achieves parity with traditional financial payment networks at peak times. Innovations in machine-to-machine payments, micro-transactions and other applications are likely to push demand to many orders higher than that.
Simply put: You can't scale a blockchain to validate the entire world's transactions in a decentralized way.
****
But what if each node wasn't required to know and validate every single transaction? What if there was a way to have scalable off-chain transactions, without losing the security of the Bitcoin network?
In February 2015, Joseph Poon and Thaddeus Dryja proposed a possible solution to the Bitcoin Scalability Problem, with the publication of _"The Bitcoin Lightning Network: Scalable Off-Chain Instant Payments"_
footnote:[Joseph Poon, Thaddeus Dryja - "The Bitcoin Lightning Network: Scalable Off-Chain Instant Payments" (https://lightning.network/lightning-network-paper.pdf).]
In the (now outdated) whitepaper, Poon and Dryja estimate that in order for Bitcoin to reach the 47,000 transactions per second processed at peak by Visa, it would require 8 GB blocks.
This would make running a node completely untenable for anyone but large scale enterprises and industrial grade operations.
The result would be a network in which only a few users can actually validate the state of the ledger.
Bitcoin relies on users validating the ledger for themselves, without explicitly trusting third parties, in order to stay decentralized.
Pricing users out of running nodes forces the average user to trust third parties to discover the state of the ledger, ultimately breaking the trust model of Bitcoin.
The Lightning Network proposes a new network, a "second layer", where users can make payments to each other peer-to-peer, without the necessity to publish a transaction to the Bitcoin blockchain for each payment.
Users may pay each other on the Lightning Network as many times as they want, without creating additional Bitcoin transactions or incurring on-chain fees.
They will only make use of the Bitcoin blockchain in order to load bitcoin onto the Lightning network initially and to "settle", that is: remove bitcoin from the Lightning Network.
The result is that many more Bitcoin payments can take place "off-chain", with only the initial loading and final settlement transactions needing to be validated and stored by Bitcoin nodes.
Aside from reducing the burden on nodes, payments on the Lightning Network will be cheaper for users as they do not need to pay blockchain fees, and more private for users as they are not published to all participants of the network and furthermore not stored permanently.
While the Lightning Network was initially conceived for Bitcoin, it can be implemented on any blockchain that meets some basic technical requirements. Other blockchains, such as Litecoin, already support the Lightning Network. Additionally, several other blockchains are developing similar "second layer" or "layer 2" solutions to help them scale.
=== The Lightning Network's defining features
The Lightning Network is a network that operates as a "second layer" protocol on top of Bitcoin and other blockchains. The Lightning Network enables fast, secure, private, trustless, and permissionless payments. Here are some of the features of the Lightning Network:
* Users of the Lightning Network can route payments to each other for low cost and in real time.
* Users of the Lightning Network can route payments to each other for low cost and in real-time.
* Users who exchange value over the Lightning Network do not need to wait for block confirmations for payments.
* Once a payment on the Lightning Network has completed, usually within a few seconds, it is final and cannot be reversed. Like a Bitcoin transaction, a payment on the Lightning Network can only be refunded by the recipient.
* While "on-chain" Bitcoin transactions are broadcast and verified by all nodes in the network, payments routed on the Lightning Network are transmitted between pairs of nodes and are not visible to everyone, resulting in much greater privacy.
* Unlike transactions on the Bitcoin Network, payments routed on the Lightning Network do not need to be stored permanently. Lightning thus uses fewer resources, hence it is cheaper. This property also has benefits for privacy.
* The Lightning Network uses onion routing, similar to the protocol used by The Onion Router (TOR) privacy network, so that even the nodes involved in routing a payment are only directly aware of their predecessor and successor in the payment route.
* While "on-chain" Bitcoin transactions are broadcast and verified by all nodes in the network, payments routed on the Lightning Network are transmitted between pairs of nodes and are not visible to everyone, resulting in much greater privacy.
* Unlike transactions on the Bitcoin Network, payments routed on the Lightning Network do not need to be stored permanently. Lightning thus uses fewer resources, hence it is cheaper. This property also has benefits for privacy.
* The Lightning Network uses onion routing, similar to the protocol used by The Onion Router (Tor) privacy network, so that even the nodes involved in routing a payment are only directly aware of their predecessor and successor in the payment route.
[[user-stories]]
=== Lightning Network Use Cases, Users, and Their Stories
As an electronic cash system, Bitcoin preserves the three most important properties of money (medium of exchange, store of value, and unit of account). Other relevant properties of digital payment systems include the ability of third parties to use them as a method of control and/or a tool of surveillance.
The invention of money (and in particular Bitcoin) was primarily made to facilitate trade and enable the exchange of value between people. However, without the Lightning Network (or another second layer or scaling solution), it would be infeasible for millions of people to concurrently use Bitcoin as a medium of exchange because the network itself would become overloaded, slow, and costly.
In order to better understand how the Lightning Network actually works, and why people use it, we'll be following a number of users and their stories.
To date, Bitcoin is the longest running, most secure cryptocurrency or electronic cash system and many people believe it represents the most stable store of value of all of the current cryptocurrencies. The Lightning Network allows people to send and receive bitcoin, without the overhead associated with on-chain transactions. This might seem confusing at first. You might be wondering how can the Lightning Network actually achieve this? While we could explain the network in computer science terms, it will be much easier to understand if we examine it from the perspective of people using it. In our examples, some of the people have already used Bitcoin and others are completely new to the Bitcoin network. Each of the people and their stories, as listed here, illustrates one or more specific use cases. We'll be revisiting them throughout this book:
In our examples, some of the people have already used Bitcoin and others are completely new to the Bitcoin network. Each of the people and their stories, as listed here, illustrates one or more specific use cases. We'll be revisiting them throughout this book:
consumer::
Alice is a Bitcoin user who wants to make fast, secure, cheap, and private payments for small retail purchases. She buys coffee with bitcoin, using the Lightning Network.
merchant::
Bob owns a coffee shop, "Bob's Cafe". "On-chain" bitcoin payments don't scale for small amounts like a cup of coffee, so he uses the Lightning Network to accept bitcoin payments almost instantaneously and for low fees.
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.
Bob owns a coffee shop, "Bob's Cafe". "On-chain" Bitcoin payments don't scale for small amounts like a cup of coffee, so he uses the Lightning Network to accept Bitcoin payments almost instantaneously and for low fees.
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. 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, not possible with other payment methods. Furthermore, by using a global currency such as bitcoin, John was able to sell his artwork to customers all over the world and, in the end, buy the games console he so desperately wanted.
software service business::
Chan is a Chinese entrepreneur who sells information services related to the Lightning Network, as well as Bitcoin and other cryptocurrencies. Chan is selling these information services over the Internet by implementing micro-payments over the Lightning Network. Additionally, Chan has implemented a liquidity provider service that rents inbound channel capacity on the Lightning Network, charging a small bitcoin fee for each rental period.
gamer::
Gloria is a teenage gamer from the Philippines. She plays many different computer games, but her favorite ones are those that have an "in-game economy" based on real money. As she plays games, she also earns money by acquiring and selling virtual in-game items. The Lightning Network allows her to transact in small amounts for in-game items as well as earn small amounts for completing quests.
Dina is a teenage gamer from Russia. She plays many different computer games, but her favorite ones are those that have an "in-game economy" based on real money. As she plays games, she also earns money by acquiring and selling virtual in-game items. The Lightning Network allows her to transact in small amounts for in-game items as well as earn small amounts for completing quests.
migrant::
Farel is an immigrant who works in the Middle East and sends money home to his family in Indonesia. Remittance companies and banks charge high fees, and Farel prefers to send smaller amounts more often. Using the Lightning Network, Farel can send bitcoin as often as he wants, with negligible fees.
=== Chapter Summary
software service business::
Wei is an entrepreneur who sells information services related to the Lightning Network, as well as Bitcoin and other cryptocurrencies. Wei is monetizing his API endpoints by implementing micro-payments over the Lightning Network. Additionally, Wei has implemented a liquidity provider service that rents inbound channel capacity on the Lightning Network, charging a small bitcoin fee for each rental period.
In this chapter, we talked about the fundamental concept that underlies both Bitcoin and the Lightning Network: the fairness protocol.
=== Chapter Summary
We looked at the history of the Lightning Network and the motivations behind second layer scaling solutions for Bitcoin and other blockchain based networks.
We learned basic terminology including node, payment channel, on-chain transactions, and off-chain payments.
In this chapter we looked at the history of the Lightning Network and the motivations behind second layer scaling solutions for Bitcoin and other blockchain based networks. We learned basic terminology including node, payment channel, on-chain transactions, and off-chain payments. Finally, we met Alice, Bob, Saanvi, John, Gloria, Farel, and Wei who we'll be following throughout the rest of the book. In the next chapter we'll meet Alice and walk through her thought process as she selects a Lightning wallet and prepares to make her first Lightning payment to buy a cup of coffee from Bob's Cafe.
Finally, we met Alice, Bob, Chan and Dina who we'll be following throughout the rest of the book. In the next chapter, we'll meet Alice and walk through her thought process as she selects a Lightning wallet and prepares to make her first Lightning payment to buy a cup of coffee from Bob's Cafe.

@ -5,27 +5,32 @@ In this chapter, we will begin where most people start when encountering the Lig
=== Lightning Nodes
The Lightning Network is accessed via software applications that can speak the Lightning Network protocol. A _Lightning Network Node_ (or simply "node") is a software application that has three important characteristics. First, nodes must communicate on a peer-to-peer basis with other Lightning nodes creating the network. Nodes also include "wallet" functionality, so they can send and receive payments over the Lightning Network as well as on the Bitcoin network. Finally, Lightning nodes also need access to the Bitcoin blockchain (or other blockchains for other cryptocurrencies) to secure the funds used for payments.
The Lightning Network is accessed via software applications that can speak the Lightning Network protocol. A _Lightning Network Node_ (or simply "node") is a software application that has three important characteristics. First, Lightning nodes are "wallets", so they send and receive payments over the Lightning Network as well as on the Bitcoin network. Second, nodes must communicate on a peer-to-peer basis with other Lightning nodes creating the network. Finally, Lightning nodes also need access to the Bitcoin blockchain (or other blockchains for other cryptocurrencies) to secure the funds used for payments.
Users have the highest degree of control by running their own Bitcoin node and Lightning node. However, Lightning nodes can also use a lightweight Bitcoin client (commonly referred to as Simplified Payment Verification (SPV)) to interact with the Bitcoin blockchain.
[[ln_explorer]]
=== Lightning Explorer
A Lightning network explorer is a useful tool to show the statistics of nodes, channels and network capacity.
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]
====
Note that if using Lightning explorers, just like in existing block explorers,
the privacy can be a concern because, if users are careless, the website may track their IP addresses and collect their behavior records (for example, the nodes users are interested in).
Note that when using Lightning explorers, just like with existing block explorers, privacy can be a concern.
If users are careless, the website may track their IP addresses and collect their behavior records (for example, the nodes users are interested in).
Also what should be noted is that, as there is no global consensus of the current Lightning graph, nor the current state of any existing channel policy, users should never rely on Lightning explorers to retrieve the most updated information. That is, Lightning explorers should only be used to gather loosely statistics of Lightning Network.
Also, it should be noted that as there is no global consensus of the current Lightning graph or the current state of any existing channel policy, users should never rely on Lightning explorers to retrieve the most updated information.
Furthermore as users open, close, and update channels, the graph will change and individual Lightning explorers may not be up to date.
Use Lightning explorers to visualize the network or gather information, but not as an authoritative source of what is happening on the Lightning Network.
To have an authoritative view of the Lightning Network, run your own Lightning node that will build a channel graph and collect various statistics, which you can view with a web-based interface.
====
=== Lightning Wallets
@ -36,20 +41,18 @@ The term "Lightning Wallet" is somewhat ambiguous, as it can describe a broad va
* A Lightning Network node (Lightning node) that communicates on the Peer-to-Peer network, as described previously.
* A Bitcoin node that stores blockchain data and communicates with other Bitcoin nodes.
* A database "map" of nodes and channels that are announced on the Lightning network.
* A "gossip" participant that learns about nodes and channels on the network to construct the "map" of the network.
* A channel data store containing state about channels on the Lightning Network as well as signatures to settle them.
* A channel manager that can open and close Lightning Network channels.
* A path-finding system that can identify a path of connected channels from payment source to payment destination.
* A path-finding system that can find a path of connected channels from payment source to payment destination.
A Lightning wallet may contain all of these functions, acting as a "full" wallet, with no reliance on any third-party services. Or, one or more of these components may rely (partially or entirely) on third-party services that mediate those functions.
A key distinction (pun intended) is whether the keystore function is internal or outsourced. In blockchains, control of keys determines custody of funds, as memorialized by the phrase "your keys, your coins; not your keys, not your coins". Any wallet that outsources management of keys is called a "custodial" wallet because a third party acting as custodian has control of the user's funds, not the user himself. A "non-custodial" or "self-custody" wallet, by comparison, is one where the keystore is part of the wallet, and keys are controlled directly by the user. The term "non-custodial" wallet just implies that the keystore is local and under the user's control. However, one or more of the other wallet components might or might not be outsourced and rely on some trusted third parties even if some of the components (other than the keystore) rely on some trusted third parties.
A _key_ distinction (pun intended) is whether the keystore function is internal or outsourced. In blockchains, control of keys determines custody of funds, as memorialized by the phrase "your keys, your coins; not your keys, not your coins". Any wallet that outsources management of keys is called a "custodial" wallet because a third party acting as custodian has control of the user's funds, not the user himself. A "non-custodial" or "self-custody" wallet, by comparison, is one where the keystore is part of the wallet, and keys are controlled directly by the user. The term "non-custodial" wallet just implies that the keystore is local and under the user's control. However, one or more of the other wallet components might or might not be outsourced and rely on some trusted third parties even if some of the components (other than the keystore) rely on some trusted third parties.
Blockchains, especially open blockchains like Bitcoin, attempt to minimize or eliminate trust in third parties and empower users. This is often called a "trustless" model, though "trust-minimized" is a better term. In such systems, the user trusts the software rules, not third parties. Therefore, the issue of control over keys is a principal consideration when choosing a Lightning wallet.
Every other component of a Lightning wallet brings similar considerations of trust. If all the components are under the control of the user, then the amount of trust in third parties is minimized, bringing maximum power to the user. Of course, this brings a direct trade-off, as with that power comes the corresponding responsibility to manage complex software.
Every user must consider their own technical skills before deciding what type of Lightning wallet to use. Those with strong technical skills should use a Lightning wallet that puts all of the components under the direct control of the user. Those with fewer technical skills but a desire to control their funds, should choose a _non-custodial_ Lightning wallet.
Every user must consider their own technical skills before deciding what type of Lightning wallet to use. Those with strong technical skills should use a Lightning wallet that puts all of the components under the direct control of the user. Those with fewer technical skills but a desire to control their funds should choose a _non-custodial_ Lightning wallet.
Often the trust in those cases relates to privacy.
If users decide to outsource some functionality to a third party they usually give up some privacy as the third party will learn some information about them.
@ -58,9 +61,14 @@ 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?
. Does this Lightning wallet store its own keys under user control (self-custody) or are the keys held by a third-party custodian?
[TIP]
====
If a Lightning wallet uses a third-party Lightning node, it is this third-party Lightning node that decides how to communicate with Bitcoin. Hence, using a third-party Lightning node implies that you are also using a third-party Bitcoin node. Only when when the Lightning wallet uses its own Lightning node, does the choice "full Bitcoin-node" vs. "third-party Bitcoin node" exist.
====
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.
@ -79,21 +87,21 @@ But remember that this is just one way of categorizing Lightning wallets.
Q3, quadrant 3, where a full Lightning node is used but the keys are held by a custodian is currently not common.
Future wallets from that quadrant would let a user worry about the operational aspects of their node, but then delegate the access to the keys to a third party which may use primarily cold storage.
Lightning wallets can be installed on a variety of devices, including laptops, servers, and mobile devices. To run a full Lightning node (one that participates in "gossip" and creates its own map of the network for path finding and routing) you will need to use a server or desktop computer, as mobile devices and laptops are usually not powerful enough in terms of capacity, processing, battery life, and connectivity.
Lightning wallets can be installed on a variety of devices, including laptops, servers, and mobile devices. To run a full Lightning node you will need to use a server or desktop computer, as mobile devices and laptops are usually not powerful enough in terms of capacity, processing, battery life, and connectivity.
The category "Third-party Lightning Nodes" can again be subdivided into:
- Lightweight: means that the Lightning Node is operated by a third party and that the wallet obtains the required information through an API that connects wallet and third-party Lightning node.
- None: means that not only is the Lightning Node operated by a third party but most of the wallet is operated by a third party in the cloud such that the wallet does not even need to make calls on a Lightning node API.
- Lightweight: means that the wallet does not operate a Lightning node and so needs to obtain information about the Lightning Network over the Internet from someone else's Lightning node.
- None: means that not only is the Lightning Node operated by a third party but most of the wallet is operated by a third party in the cloud. This is a "custodial" wallet where someone else controls the custody of funds.
These subcategories are used in Table <<lnwallet-examples>>.
Other terms that need explanation in Table <<lnwallet-examples>> in column "Bitcoin Node" are:
- Neutrino: Neutrino is a specific implementation of a protocol to get data from Bitcoin as outlined in BIP 157 and BIP 158. The Bitcoin Node is run by a third-party and accessed via "neutrino".
- Electrum: This means the wallet connects to an Electrum Server. The Bitcoin Node is run by a third-party and accessed via the "Electrum" protocol.
- Bitcoin Core: implementation of Bitcoin full node
- btcd: another implementation of Bitcoin full node
- Neutrino: This wallet does not operate a Bitcoin Node. Instead, a Bitcoin Node operated by someone else (third-party) is accessed via the "Neutrino" protocol.
- Electrum: This wallet does not operate a Bitcoin Node. Instead, a Bitcoin Node operated by someone else (third-party) is accessed via the "Electrum" protocol.
- Bitcoin Core: implementation of a Bitcoin Node
- btcd: another implementation of Bitcoin Node
In <<lnwallet-examples>> we see some examples of currently popular Lightning node and wallet applications for different types of devices.
@ -103,14 +111,18 @@ In <<lnwallet-examples>> we see some examples of currently popular Lightning nod
[options="header"]
|===
| Application | Device | Lightning Node | Bitcoin Node | Keystore
| lnd | Server | Full Node | Bitcoin Core/btcd | Self-Custody
| c-lightning | Server | Full Node | Bitcoin Core | Self-Custody
| Eclair Server | Server | Full Node | Bitcoin Core/Electrum | Self-Custody
| Zap Desktop | Desktop | Full Node | Neutrino | Self-Custody
| Eclair Mobile | Mobile | Lightweight | Electrum | Self-Custody
| Breez Wallet | Mobile | Full Node | Neutrino | Self-Custody
| Phoenix Wallet | Mobile | Lightweight | Electrum | Self-Custody
| 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
| Zap Desktop | Desktop | Full Node | Neutrino | Self-Custody
| Electrum | Desktop | Full Node | Bitcoin Core/Electrum | Self-Custody
| lnd | Server | Full Node | Bitcoin Core/btcd | Self-Custody
| c-lightning | Server | Full Node | Bitcoin Core | Self-Custody
| Eclair Server | Server | Full Node | Bitcoin Core/Electrum | Self-Custody
|===
=== Balancing complexity and control
@ -139,7 +151,7 @@ Alice uses an Android device and will use the Google Play Store to download and
.Eclair Mobile in the Google Play Store
image:images/eclair-playstore.png["Eclair wallet in the Google Play Store"]
Alice notices a few different elements on this page, that help her ascertain that this is, most likely, the correct "Eclair Mobile" wallet she is looking for. Firstly, the organization "ACINQ" footnote:[ACINQ: Developers of the Eclair Mobile Lightning wallet (https://acinq.co/).] is listed as the developer of this mobile wallet, which Alice knows from her research is the correct developer. Secondly, the wallet has been installed "10,000+" times and has more than 320 positive reviews. It is unlikely this is a rogue app that has snuck into the Play Store. As third step, she goes to the ACINQ website (https://acinq.co/). She verifies that the webpage is secure (https, not http) which is shown as a green lock by some browsers. On the website she goes to the Download section or looks for the link to the Google App store. She finds the link and clicks it. She compares that this link brings her to the very same app in the Google App Store. Satisfied by these findings, Alice installs the Eclair app on her mobile device.
Alice notices a few different elements on this page, that help her ascertain that this is, most likely, the correct "Eclair Mobile" wallet she is looking for. Firstly, the organization "ACINQ" footnote:[ACINQ: Developers of the Eclair Mobile Lightning wallet (https://acinq.co/).] is listed as the developer of this mobile wallet, which Alice knows from her research is the correct developer. Secondly, the wallet has been installed "10,000+" times and has more than 320 positive reviews. It is unlikely this is a rogue app that has snuck into the Play Store. As a third step, she goes to the ACINQ website (https://acinq.co/). She verifies that the webpage is secure by checking that the address begins with HTTPS, or prefixed by a padlock in some browsers. On the website she goes to the Download section or looks for the link to the Google App store. She finds the link and clicks it. She compares that this link brings her to the very same app in the Google App Store. Satisfied by these findings, Alice installs the Eclair app on her mobile device.
[WARNING]
====
@ -152,7 +164,7 @@ When Alice opens the Eclair Mobile app for the first time, she is presented with
==== Responsibility with Key Custody
As we mentioned in the beginning of this section, Eclair is a _non-custodial_ wallet, meaning that Alice has sole custody of the keys used to control her bitcoin. This also means that Alice is responsible for protecting and backing up those keys. If Alice loses the keys, no one can help her recover the bitcoin, and they will be lost forever.
As we mentioned at the beginning of this section, Eclair is a _non-custodial_ wallet, meaning that Alice has sole custody of the keys used to control her bitcoin. This also means that Alice is responsible for protecting and backing up those keys. If Alice loses the keys, no one can help her recover the bitcoin, and they will be lost forever.
[WARNING]
====
@ -161,11 +173,11 @@ With the Eclair Mobile wallet, Alice has custody and control of the keys and, th
==== Mnemonic Words
Similar to most Bitcoin wallets, Eclair Mobile provides a _mnemonic phrase_ for Alice to back up. The mnemonic phrase consists of 24 English words, selected randomly by the software, and used as the basis for the keys that are generated by the wallet. The mnemonic phrase can be used by Alice to restore all the transactions and funds in the Eclair Mobile wallet in the case of an event such as a lost mobile device, a software bug, or memory corruption.
Similar to most Bitcoin wallets, Eclair Mobile provides a _mnemonic phrase_ (also sometimes called a "seed" or "seed phrase") for Alice to back up. The mnemonic phrase consists of 24 English words, selected randomly by the software, and used as the basis for the keys that are generated by the wallet. The mnemonic phrase can be used by Alice to restore all the transactions and funds in the Eclair Mobile wallet in the case of an event such as a lost mobile device, a software bug, or memory corruption.
[TIP]
====
The _mnemonic phrase_ is often mistakenly called a "seed". In fact, a seed is constructed _from the mnemonic_ and is something different.
The correct term for these backup words is "mnemonic phrase". We avoid the use of the term "seed" to refer to a mnemonic phrase, because even though its use is common it is incorrect.
====
When Alice chooses to "Create a New Wallet", she will be shown a screen with her mnemonic phrase, which looks like the screenshot in <<eclair-mnemonic>>.
@ -201,21 +213,41 @@ Alice now has a Lightning wallet. But, it's empty! She now faces one of the more
There are several ways Alice can acquire bitcoin:
* She can exchange some of her national currency (e.g. USD) at a crypto-currency exchange
* She can exchange some of her national currency (e.g. USD) at a cryptocurrency exchange
* She can buy some from a friend, or an acquaintance from a Bitcoin Meetup, in exchange for cash
* She can find a _Bitcoin ATM_ in her area, which acts as a vending machine, selling bitcoin for cash
* She can offer her skills or a product she sells and accepts payment in bitcoin
* She can ask her employer or clients to pay her in bitcoin
All of these methods have varying degrees of difficulty, and many will involve paying a fee. Some will also require Alice to provide identification documents to comply with local banking regulations. However, with all these methods, Alice will be able to receive bitcoin.
[[testnet-bitcoin]]
==== Testnet Bitcoin
The Bitcoin system offers an alternative chain for testing purposes called a _testnet_, in contrast with the "normal" Bitcoin chain which is referred to as "mainnet". On testnet, the currency is _testnet bitcoin (TBTC)_, which is a worthless copy of bitcoin used exclusively for testing. Every function of Bitcoin is replicated exactly, but the money is worth nothing, so you literally have nothing to lose!
Somme Lightning wallets can also operate on testnet, allowing you to make Lightning payments with testnet bitcoin, without risking real funds. This is a great way to experiment with Lightning safely. Eclair mobile, which Alice uses in this chapter, is one example of a Lightning wallet that supports testnet operation.
You can get some TBTC to play with from a _testnet bitcoin faucet_, which gives out free TBTC on demand. Here are a few testnet faucets:
https://coinfaucet.eu/en/btc-testnet/
https://testnet-faucet.mempool.co/
https://bitcoinfaucet.uo1.net/
https://testnet.help/en/btcfaucet/testnet
All of the examples in this book can be replicated exactly on testnet with TBTC, so you can try and follow along if you want without risking real money.
==== Receiving Bitcoin
Let's assume Alice has found a local Bitcoin ATM and has decided to buy some bitcoin in exchange for cash. An example of a Bitcoin ATM, one built by the Lamassu company, is shown in <<bitcoin-atm>>. Such Bitcoin ATMs accept national currency (cash) through a cash slot and send bitcoin to a Bitcoin Address scanned from a user's wallet using a built-in camera.
[[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.
@ -223,7 +255,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.
@ -236,21 +268,30 @@ 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.
[TIP]
====
The number of "confirmations" on a transaction is the number of blocks mined since (and inclusive of) the block that contained that transaction. Six confirmations is best practice, but different Lightning wallets can consider a channel open after any number of confirmations. Some wallets even scale up the number of expected confirmations by the monetary value of the channel.
====
[[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.
Similarly, if she billed a client for a service offered over the Internet, Alice could send an email or instant message with the Bitcoin Address or the QR code to her client, and they could paste or scan the information into a Bitcoin wallet to pay her.
Alice could even print the QR code and affix it to a sign and display it publicly to receive tips. For example, she could have a QR code affixed to her guitar and receive tips while performing on the street!
footnote:[It is generally not advisable to reuse the same Bitcoin address for multiple payments as all Bitcoin transactions are public.
A nosy person passing by could scan Alice's QR code and see how many tips Alice has already received to this address on the Bitcoin blockchain.
Fortunately, the Lightning Network offers more private solutions to this, discussed later in the book!]
Finally, if Alice bought bitcoin from a crypto-currency exchange, she could (and should) "withdraw" the bitcoin by pasting her Bitcoin Address into the exchange website. The exchange will then send the bitcoin to her address directly.
Finally, if Alice bought bitcoin from a cryptocurrency exchange, she could (and should) "withdraw" the bitcoin by pasting her Bitcoin Address into the exchange website. The exchange will then send the bitcoin to her address directly.
=== From Bitcoin to Lightning Network
@ -268,7 +309,12 @@ Let's review the definition of a "Lightning Network Channel" at this point, to m
The wallet or _node_ that Alice opens a channel to is called her _channel peer_. Once "opened", a channel can be used to send many payments back and forth between Alice's wallet and her channel peer.
Furthermore, Alice's channel peer can _forward_ payments via other channels further into the Lightning Network. This way, Alice can _route_ a payment to any wallet (e.g. Bob's Lightning wallet) as long as Alice's wallet can find a _path_ made by hopping from channel to channel, all the way to Bob's wallet.
Furthermore, Alice's channel peer can _forward_ payments via other channels further into the Lightning Network. This way, Alice can _route_ a payment to any wallet (e.g. Bob's Lightning wallet) as long as Alice's wallet can find a viable _path_ made by hopping from channel to channel, all the way to Bob's wallet.
[TIP]
====
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.
@ -289,7 +335,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
@ -299,19 +345,19 @@ image:images/node-URI-QR.png[width=120]
While Alice could select a specific Lightning node, or use the "Random node" option to have the Eclair wallet select a node at random, she will select the "ACINQ Node" option to connect to one of ACINQ's well-connected Lightning nodes.
Choosing the ACINQ node will slightly reduce Alice's privacy, as it will give ACINQ the ability to see all of Alice's transactions. It will also create a Single Point of Failure, since Alice will only have one channel, and if the ACINQ node is not available, Alice will not be able to make payments. To keep things simple at first, we will accept these trade-offs. In subsequent chapters we will gradually learn how to gain more independence and make fewer trade-offs!
Choosing the ACINQ node will slightly reduce Alice's privacy, as it will give ACINQ the ability to see all of Alice's transactions. It will also create a Single Point of Failure, since Alice will only have one channel, and if the ACINQ node is not available, Alice will not be able to make payments. To keep things simple at first, we will accept these trade-offs. In subsequent chapters, we will gradually learn how to gain more independence and make fewer trade-offs!
Alice selects "ACINQ Node" and is ready to open her first channel on the Lightning network.
==== Opening a Lightning Channel
When Alice selects a node to open a new channel, she is asked to select how much bitcoin she wants to allocate to this channel. In subsequent chapters, we will discuss the implications of these choices, but for now, Alice will allocate almost all her funds to the channel. Since she will have to pay transaction fees to open the channel, she will select an amount a few dollars (or a few thousandths of a bitcoin) less than her total balance.
When Alice selects a node to open a new channel, she is asked to select how much bitcoin she wants to allocate to this channel. In subsequent chapters, we will discuss the implications of these choices, but for now, Alice will allocate almost all her funds to the channel. Since she will have to pay transaction fees to open the channel, she will select an amount slightly less than her total balance footnote:[The Eclair wallet doesn't offer an option to automatically calculate the necessary fees and allocate the maximum amount of funds to a channel, so Alice has to calculate this herself.]
Alice allocates 0.018BTC of her 0.020 total to her channel and accepts the default fee rate, as shown in <<eclair-open-channel>>.
[[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.
@ -329,7 +375,7 @@ image:images/eclair-channel-open.png["Channel is Open"]
[TIP]
====
Did you notice that the channel amount seems to have changed? It hasn't: the channel contains 0.018 BTC, but in the time between screenshots the BTC exchange rate changed, so the USD value is different. You can choose to show balances in BTC or USD, but keep in mind that USD values are calculated in real time and will change!
Did you notice that the channel amount seems to have changed? It hasn't: the channel contains 0.018 BTC, but in the time between screenshots the BTC exchange rate changed, so the USD value is different. You can choose to show balances in BTC or USD, but keep in mind that USD values are calculated in real-time and will change!
====
=== Buying a Cup of Coffee
@ -340,7 +386,7 @@ Alice grabs her mobile device and runs to Bob's Cafe in her neighborhood. She is
==== Bob's Cafe
Bob has a simple Point-of-Sale (PoS) application for the use of any customer who wants to pay with bitcoin over the Lightning Network. As we will see in the next chapter, Bob uses the popular open source platform _BTCPay Server_ which contains all the necessary components for an e-commerce or retail solution, such as:
Bob has a simple Point-of-Sale (PoS) application for the use of any customer who wants to pay with bitcoin over the Lightning Network. As we will see in the next chapter, Bob uses the popular open-source platform _BTCPay Server_ which contains all the necessary components for an e-commerce or retail solution, such as:
* A Bitcoin Node using the Bitcoin Core software
* A Lightning Node using the c-lightning software
@ -352,29 +398,34 @@ 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
Alice selects the "Cafe Latte" option from the screen and is presented with a _Lightning Invoice_ as shown in <<bob-cafe-invoice>>
Alice selects the "Cafe Latte" option from the screen and is presented with a _Lightning Invoice_ (also known as a "payment request") as shown in <<bob-cafe-invoice>>
[[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]
====
The term "payment request" can refer to a Bitcoin payment request or a Lightning invoice and the terms "invoice" and "payment request" are often used interchangeably. The correct technical term is "Lightning invoice", regardless of how it is named in the wallet.
====
Alice selects the option to "scan a payment request" and scans the QR code displayed on the screen of the tablet (see <<bob-cafe-invoice>>), and is prompted to confirm her payment, as shown in <<alice-send-detail>>:
[[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 the most advanced payment technology in the world. 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 "on-chain" transaction.
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.
=== Conclusion

@ -14,12 +14,30 @@ We'll start with a one sentence definition of what the Lightning Network (LN) is
**The Lightning Network (LN) is a peer-to-peer network of _payment channels_ implemented as smart contracts on the _Bitcoin blockchain_ as well as a communication protocol that defines how participants set up and execute these smart contracts**
=== Payment channels basics
=== What is a payment channel?
There are several ways to describe a payment channel, depending on the context. Let's start at a high level and then add some more detail.
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 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.
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 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.
We will see that a payment channel is simply a 2-of-2 multisignature address on Bitcoin, for which you hold one key and your channel partner holds the other key.
You and your channel partner negotiate a sequence of transactions that spend from this multisignature address. Instead of transmitting and recording these transactions on the Bitcoin blockchain, you both hold on to them, unspent.
The latest transaction in that sequence encodes the balance of the channel and defines how that balance is divided between you and your channel partner.
Thus, adding a new transaction to this sequence is equivalent to moving some part of the channel balance from one channel partner to the other, without the Bitcoin network being aware of it. As you negotiate each new transaction, changing the allocation of funds in the channel, you also revoke the previous transaction, so that neither party can regress to a previous state.
Each transaction in the sequence makes use of Bitcoin's scripting language, and thus the negotiation of funds between you and your channel partner is managed by a Bitcoin smart contract.
The smart contract is set up to penalize a channel member if they try to submit a previously revoked state of the channel.
@ -32,7 +50,7 @@ The ability to hold a partially-signed transaction, offline and unpublished, wit
=== Routing payments across channels
Once several participants have channels from one party to another, a payment can also be "forwarded" from payment channel to payment channel, by setting up a _path_ across the network connecting several payment channels together.
Once several participants have channels from one party to another, payment can also be "forwarded" from payment channel to payment channel, by setting up a _path_ across the network connecting several payment channels together.
For example, Alice can send money to Charlie if Alice has a channel with Bob and Bob has a channel with Charlie.
@ -47,22 +65,24 @@ However, the Lightning Network is so much more than the cryptographic protocols
It is a comprehensive communication protocol that allows peers to exchange Lightning messages to achieve the transfer of bitcoin.
The communication protocol defines how Lightning messages are encrypted and exchanged.
The Lightning Network also uses a "gossip" protocol to distribute public information about the channels (network topology) to all the participants.
The Lightning Network also uses a "gossip" protocol to distribute public information about the channels (network topology) to all the participants.
Alice, for example, needs the network topology information to be aware of the channel between Bob and Charlie, so that she can construct a route to Charlie.
Last but not least, it is important to understand that the Lightning Network is nothing more than an application on top of Bitcoin, using Bitcoin transactions and Bitcoin Script. There is no "Lightning coin" or "Lightning blockchain".
Beyond all the technical primitives, the Lightning Network protocol is a creative way to get more benefits out of Bitcoin by allowing an arbitrary amount of instant payments with instant settlements without the necessity to trust anyone else but the Bitcoin network.
Beyond all the technical primitives, the Lightning Network protocol is a creative way to get more benefits out of Bitcoin by allowing an arbitrary amount of instant payments with instant settlements without the necessity of having to trust anyone else but the Bitcoin network.
=== Payment channels
As we saw in the previous chapter, Alice used her wallet software to create a payment channel between her and another Lightning Network participant.
From a computer science perspective, a payment channel is a cryptographic communication protocol between you and your channel partner.
It allows the channel partners to send funds back and forth as often as they wish.
A channel is only limited by two things:
First, the time it takes for the internet to transfer the few bytes of data that the protocol requires to move funds from one end of the channel to the other.
Second, the capacity of the channel, meaning the amount of bitcoin that is committed to the channel when it is opened.
A channel is only limited by three things:
* First, the time it takes for the internet to transfer the few hundred bytes of data that the protocol requires to move funds from one end of the channel to the other.
* Second, the capacity of the channel, meaning the amount of bitcoin that is committed to the channel when it is opened.
* Third, the maximum size limit of a Bitcoin transaction also limits the number of incomplete (in progress) routed payments that can be carried simultaneously over a channel.
Payment channels have a few very interesting and useful properties:
@ -72,18 +92,18 @@ Payment channels have a few very interesting and useful properties:
* The cryptographic protocol is constructed such that there is little to no trust needed between you and your channel partner. If your partner becomes unresponsive or tries to cheat you, you can ask the Bitcoin system to act as a "court" resolving the smart contract you and your partner have previously agreed upon.
* 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.
* 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.
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.
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 https://lightning.network/lightning-network-paper.pdf[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.
Eltoo channels have some interesting properties and simplify the implementation of payment channels. However, eltoo channels require a change in the Bitcoin scripting language and therefore cannot be implemented on the Bitcoin mainnet at this time.
Eltoo channels have some interesting properties and simplify the implementation of payment channels. However, eltoo channels require a change in the Bitcoin scripting language and therefore cannot be implemented on the Bitcoin mainnet as of 2020.
==== 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]
@ -102,18 +122,18 @@ The Bitcoin scripting language provides a multisignature building block (primiti
The script for an K-of-N multisignature is:
----
K <PubKey1> <PubKey2> ... PubKeyN N CHECKMULTISIG
K <PubKey1> <PubKey2> ... <PubKeyN> N CHECKMULTISIG
----
where N is the total number of listed public keys (Public Key 1 through Public Key N) and K is the threshold of required signatures to spend the output.
The Lightning Network uses a 2-of-2 multisignature scheme to build a payment channel. For example, a payment channel between Alice and Bob would be build on a 2-of-2 multisignature like this:
The Lightning Network uses a 2-of-2 multisignature scheme to build a payment channel. For example, a payment channel between Alice and Bob would be built on a 2-of-2 multisignature like this:
----
2 <PubKey Alice> <PubKey Bob> 2 CHECKMULTISIG
----
The preceding locking script can be satisfied with an unlocking script containing a pair of signatures:
The preceding locking script can be satisfied with an unlocking script containing a pair of signatures: footnote:[The first argument (0) does not have any meaning but is required due to a bug in Bitcoin's multisignature implementation. This issue is described in Mastering Bitcoin, Chapter 7.]
----
0 <Sig Alice> <Sig Bob>
@ -126,16 +146,16 @@ The two scripts together would form the combined validation script:
==== Funding Transaction
The fundamental building block of a payment channel, is a 2-of-2 multisignature address. The two channel partners fund the payment channel by sending bitcoin to the multisignature address. This transaction is called the _funding transaction_, and is recorded on the Bitcoin blockchain.
The fundamental building block of a payment channel, is a 2-of-2 multisignature address. The two channel partners fund the payment channel by sending bitcoin to the multisignature address. This transaction is called the _funding transaction_, and is recorded on the Bitcoin blockchain. footnote:[While the original Lightning whitepaper described channels funded by both channel partners, the current specification, as of 2020, assumes that just one partner commits funds to the channel.]
Even though the funding transaction is public, it is not obvious that it is a Lightning payment channel until it is closed. Furthermore, channel payments are still not visible to anyone other than the channel partners, nor is the distribution of the channel balance between them.
The amount deposited in the multisignature address is the called the _channel capacity_ and sets the maximum amount that can be sent across the payment channel. However, since funds can be sent back and forth, the channel capacity is not the upper limit on how much value can flow across the channel. That's because if the channel capacity is exhausted with payments in one direction, it can be used to send payments in the opposite direction again.
The amount deposited in the multisignature address is called the _channel capacity_ and sets the maximum amount that can be sent across the payment channel. However, since funds can be sent back and forth, the channel capacity is not the upper limit on how much value can flow across the channel. That's because if the channel capacity is exhausted with payments in one direction, it can be used to send payments in the opposite direction again.
[NOTE]
====
The funds sent to the multisignature address in the funding transaction are sometimes referred to as "locked in a Lightning channel". However in practice, funds in a Lightning channel are not "locked" but rather "unleashed". Lightning channel funds are more liquid than funds on the Bitcoin blockchain as they can be spent faster, cheaper and more privately. Opening a Lightning channel unleashes your Bitcoin!
The funds sent to the multisignature address in the funding transaction are sometimes referred to as "locked in a Lightning channel". However, in practice, funds in a Lightning channel are not "locked" but rather "unleashed". Lightning channel funds are more liquid than funds on the Bitcoin blockchain as they can be spent faster, cheaper and more privately. There are some disadvantages to moving funds into the Lightning Network (such as the need to keep them in a "hot" wallet), but the idea of "locking funds" in Lightning is misleading.
====
===== Example of a poor channel opening procedure
@ -146,9 +166,9 @@ Alice and Bob want to create a payment channel. They each create a private/publi
Next, Alice constructs a Bitcoin transaction sending a few mBTC to the multisignature address created from Alice's and Bob's public keys. If Alice doesn't take any additional steps and simply broadcasts this transaction, she has to trust that Bob will provide his signature to spend from the multisignature address. Bob on the other hand has the chance to blackmail Alice by withholding his signature and denying Alice access to her funds.
In order to prevent this, Alice will need to create an additional transaction which spends from the multisignature address, refunding her mBTC. Alice then has Bob sign the refund transaction _before_ broadcasting her funding transaction to the Bitcoin network. This way, Alice can get a refund even if Bob disappears or fails to cooperate.
In order to prevent this, Alice will need to create an additional transaction that spends from the multisignature address, refunding her mBTC. Alice then has Bob sign the refund transaction _before_ broadcasting her funding transaction to the Bitcoin network. This way, Alice can get a refund even if Bob disappears or fails to cooperate.
The "refund" transaction that protects Alice is the first of a class of transactions called _commitment transactions_, which we will examine in more detail next.
The "refund" transaction that protects Alice is the first of a class of transactions called _commitment transactions_, which we will examine in more detail next.
==== Commitment Transaction
@ -159,7 +179,7 @@ By holding a signed commitment transaction, each channel partner can get their f
The commitment transaction that Alice prepared in the previous example, was a "refund" of her initial payment to the multisignature address. More generally however, a commitment transaction splits the funds of the payment channel, paying the two channel partners according to the distribution (balance) they each hold. At first, Alice holds all the balance, so it is a simple refund. But as funds flow from Alice to Bob, they will exchange signatures for new commitment transactions that represent the new balance distribution, with some part of the funds paid to Alice and some paid to Bob.
Let us assume Alice opens a channel with a capacity of 100k satoshi with Bob.
Initially Alice owns 100k satoshi, the entirety of the funds in the channel. Here's how the payment channel protocol would work:
Initially, Alice owns 100k satoshi, the entirety of the funds in the channel. Here's how the payment channel protocol would work:
. Alice creates a new private / public key pair and informs Bob that she wishes to open a channel via the `open_channel` message (a message in the Lightning Network protocol).
. Bob also creates a new private / public key pair and agrees to accept a channel from Alice, sending his public key to Alice via the `accept_channel` message.
@ -187,7 +207,7 @@ Now that we understand commitment transactions, let's look at some of the more s
How many commitment transactions does Alice hold after she pays 30k satoshi to Bob? She holds two: the original one paying her 100k satoshi and the more recent one, paying her 70k satoshi and Bob 30k satoshi.
In the channel protocol we have seen so far, nothing stops Alice from publishing a previous commitment transaction. A cheating Alice could publish the commitment transaction which grants her 100k satoshi.
Since that commitment transaction was signed by Bob he can't prevent Alice from transmitting it.
Since that commitment transaction was signed by Bob he can't prevent Alice from transmitting it.
Some mechanism is needed to prevent Alice from publishing an old commitment transaction. Let us now find out how this can be achieved and how it enables the Lightning Network to operate without requiring any trust between Alice and Bob.
@ -195,10 +215,15 @@ Because Bitcoin is censorship resistant, no one can prevent someone from publish
The way the penalty works is by giving the cheated party an opportunity to claim the balance of the cheater. So if someone attempts to cheat by broadcasting an old commitment transaction, in which they are paid a higher balance than they are due, the other party can punish them by taking *both* their own balance and the balance of the cheater. The cheater loses everything.
[TIP]
====
You might notice that if Alice drains her channel balance almost completely, she could then risk cheating with little risk. Bob's penalty wouldn't be so painful if her channel balance is low. To prevent this, the Lightning protocol requires each channel partner to keep a minimum balance in the channel (called the "reserve") so they always have "skin in the game".
====
Let us go through the channel construction scenario again, adding a penalty mechanism to protect against cheating:
* Alice creates a channel with Bob and put 100k satoshi into it.
* Alice send 30k satoshi to Bob.
* Alice creates a channel with Bob and puts 100k satoshi into it.
* Alice sends 30k satoshi to Bob.
* Alice tries to cheat Bob out of his earned 30k satoshi by publishing an old commitment transaction claiming the full 100k satoshi for herself.
* Bob detects the fraud and punishes Alice by taking the full 100k satoshi for himself.
* Bob ends up with 100k satoshi, gaining 70k satoshi for catching Alice cheat.
@ -209,21 +234,23 @@ With a strong penalty mechanism, Alice is not tempted to cheat by publishing an
[NOTE]
====
In Mastering Bitcoin Andreas states it very elegantly:
In Mastering Bitcoin, Andreas Antonopoulos (the author of this book) states it as follows:
"A key characteristic of bitcoin is that once a transaction is valid, it remains valid and does not expire. The only way to cancel a transaction is by double-spending its inputs with another transaction before it is mined."
====
Now that we understand _why_ a penalty mechanism is needed and how it will prevent cheating, let's see _how_ it works in detail.
Usually, the commitment transaction has at least two outputs, paying each channel partner. We change this to add a _timelock delay_ and a _revocation secret_, to one of the payments. The timelock prevents the owner of the output from spending it immediately once the commitment transaction is included in a block. The revocation secret, allows either party to immediately spend that payment, bypassing the timelock.
Usually, the commitment transaction has at least two outputs, paying each channel partner. We change this to add a _timelock delay_ and a _revocation secret_, to one of the payments. The timelock prevents the owner of the output from spending it immediately once the commitment transaction is included in a block. The revocation secret allows either party to immediately spend that payment, bypassing the timelock.
So, in our example, Bob holds a commitment transaction that pays Alice _immediately_, but his own payment is delayed and revocable. Alice also holds a commitment transaction, but hers is the opposite: it pays Bob immediately but her own payment is delayed and revocable.
So, in our example, Bob holds a commitment transaction which pays Alice _immediately_, but his own payment is delayed and revocable. Alice also holds a commitment transaction, but hers is the opposite: it pays Bob immediately but her own payment is delayed and revocable.
The two channel partners hold half of the revocation secret, so that neither one knows the whole secret. If they share their half, then the other channel partner has the full secret and can use it to exercise the revocation condition. When signing a new commitment transaction, each channel partner revokes the previous commitment by giving the other party their half of the revocation secret.
The two channel partners hold half of the revocation secret, so that neither one knows the whole secret. If they share their half, then the other channel partner has the full secret and can use it to exercise the revocation condition. When signing a new commitment transaction, they revoke the previous commitment by exchanging the signature for the revocation secret.
We will examine the revocation mechanism in more detail in <<channel_operation>>, where we will learn the details of how revocation secrets are constructed and used.
In simple terms, Alice signs Bob's new commitment transaction only if Bob offers his half of the revocation secret for the previous commitment. Bob only signs Alice's new commitment transaction if she gives him her half of the revocation secret from the previous commitment.
With each new commitment, they exchange the necessary "punishment" secret that allows them to effectively _revoke_ the prior commitment transaction by making it unprofitable to transmit. Essentially, they destroy the ability to use the old commitments as they sign the new ones. footnote:[It is still technically possible to use old commitments, but the penalty mechanism makes it economically irrational to do so.]
With each new commitment, they exchange the necessary "punishment" secret that allows them to effectively _revoke_ the prior commitment transaction by making it unprofitable to transmit. Essentially, they destroy the ability to use old commitments as they sign the new ones. What we mean is that while it still technically possible to use old commitments, the penalty mechanism makes it economically irrational to do so.
The timelock is set to a number of blocks, up to 2016 (approximately two weeks). If either channel partner publishes a commitment transaction without cooperating with the other partner, they will have to wait for that number of blocks (e.g. 2 weeks) to claim their balance. The other channel partner can claim their own balance at any time. Furthermore, if the commitment they published was previously revoked, the channel partner can *also* immediately claim the cheating party's balance, bypassing the timelock and punishing the cheater.
@ -239,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.
@ -252,102 +279,141 @@ 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, it's existence and capacity will be revealed when the channel closes, because those details will be visible on-chain in the final settlement transaction. It's 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.
When a channel and its capacity is publicly announced using the gossip protocol, the announcement can also include information about the channel (metadata), such as it's routing fees and timelock duration.
When a channel and its capacity is publicly announced using the gossip protocol, the announcement can also include information about the channel (metadata), such as its routing fees and timelock duration.
When new nodes join the Lightning Network they collect the channel announcements propagated via the gossip protocol from their peers, building an internal "map" of the Lightning Network. This map can then be used to find paths for payments, connecting channels together end-to-end.
==== Closing the channel
The best way to close a channel is... to not close it! Opening and closing channels requires an on-chain transaction, which will incur transaction fees. So it's best to keep channels open as long as possible. You can keep using your channel to make and forward payments, as long as you have sufficient capacity on your end of the channel. But even if you send all the balance to the other end of the channel, you can then use the channel to receive payments from your channel partner. This concept of using a channel in one direction and then using it in the opposite direction is called "re-balancing" and we will examine it in more detail in another chapter. By re-balancing a channel, it can be kept open almost indefinitely and used for thousands of payments.
The best way to close a channel is... to not close it!
Opening and closing channels require an on-chain transaction, which will incur transaction fees.
So it's best to keep channels open as long as possible.
You can keep using your channel to make and forward payments, as long as you have sufficient capacity on your end of the channel.
But even if you send all the balance to the other end of the channel, you can then use the channel to receive payments from your channel partner.
This concept of using a channel in one direction and then using it in the opposite direction is called "re-balancing" and we will examine it in more detail in another chapter.
By re-balancing a channel, it can be kept open almost indefinitely and used for essentially unlimited number of payments.
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)
* Protocol breach (the ugly way)
* The good way - Mutual close
* The bad way - Force close
* The ugly way - Protocol breach
Each of these methods is useful for different circumstances which we will explore in the next section of this chapter.
For example, if your channel partner is offline you will not be able to follow "the good way" because a mutual close cannot be done without a cooperating partner.
Usually, your Lightning Network software will automatically select the best closing mechanism available under the circumstances.
===== Mutual close (the good way)
Which way you close a channel will depend on the circumstances. For example, if your channel partner is offline you will not be able to follow "the good way" because a mutual close cannot be done without a cooperating partner.
Usually, you Lightning Network software will automatically select the best closing mechanism available under the circumstances.
Mutual Close is when both channel partners agree to the closure of a channel and is the preferred method of channel close.
Whether you (the user) issue a command to close a channel or the Lightning Network software automatically closes a channel due to a detected anomaly (e.g. cheating partner), it is usually the Lightning Network software that chooses the appropriate way to close the channel.
When you decide that you want to close a channel, your Lightning Network node will inform your channel partner about your intention.
Now both your node and the channel parter's node work together to close the channel.
No new routing attempts will be accepted from either channel partner and any ongoing routing attempts will be settled or removed after they time-out.
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 timelock.
===== The good way - Mutual close
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.
The good way to close a channel is the mutual close and this way is always preferred, if possible. When you decide that you want to close a channel, your Lightning Network node will inform your channel partner about your intention. Now both your node and the channel parter's node work together to close the channel. No new routing attempts will be accepted from either channel partner and any ongoing routing attempts will be settled or removed after they time-out. Finalizing the routing attempts takes time, so a mutual close can also take some time to complete.
Once the closing transaction is broadcast and confirmed by the Bitcoin network, the channel is effectively closed and each channel partner has received their share of the channel balance.
Despite the waiting time, a mutual close is typically faster than a force close.
Once there are no pending routing attempts, the nodes cooperate to prepare a _closing transaction_. This transaction is similar to the commitment transaction, in that it distributes the channel balance to each channel partner according to their last commitment. Unlike the last commitment transaction, the outputs are not encumbered with a time lock.
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.
===== Force close (the bad way)
Once the closing transaction is broadcast and confirmed by the Bitcoin network, the channel is effectively closed and each channel partner has received their share of the channel balance. A mutual close is usually the fastest way to close a channel.
A Force Close is when one channel partner attempts to close a channel without the other channel partner's consent.
===== The bad way - Force close
This is usually in the case that one of the channel partners is unreachable, and so a mutual close is not possible.
In this case, you would initiate a force close to unilaterally close the channel and "free" the funds.
Mutual close is not always possible. Sometimes, for example if your channel partner cannot be reached, you have to unilaterally close the channel in order to "free" the funds. Closing the channel unilaterally is called a _force close_. To do a force close, Alice can simply publish the last commitment transaction. After all, that's what commitment transactions are for - they offer a guarantee that Alice doesn't need to trust Bob to retrieve the balance of the channel that belongs to her.
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 partner to retrieve the balance of your channel.
Once Alice broadcasts the last commitment transaction she has to the Bitcoin network and it is confirmed, it will create two spendable outputs, one for Alice and one for Bob. As we discussed previously, because this commitment transaction is held by Alice, it gives a slight "advantage" to Bob. Alice's output will have a timelock delay and Bob's will be spendable immediately. This is to protect Bob, so that Alice can't broadcast an old commitment transaction and steal some of the balance. The timelock delay gives Bob the opportunity to "dispute" the transaction using the revocation secret and punish Alice for cheating.
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.
Hence this commitment transaction will give a slight "advantage" to your partner.
The partner who initiated the force close will have their output encumbered by a timelock, and the other partner's output will be spendable immediately.
In the case that you broadcasted an earlier commitment transaction, the timelock delay gives your partner the opportunity to "dispute" the transaction using the revocation secret and punish you for cheating.
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.
. The commitment transaction includes additional outputs for any pending routing attempts (HTLCs), which makes the commitment transaction bigger than a mutual close transaction. Bigger transactions incur more fees.
. 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.
[NOTE]
====
Hash Time-Locked Contracts (HTLCs) will be covered in detail in <<htlcs>>. For now, assume that these are payments that are routed across the Ligntning Network, rather than payments made directly between the two channel partners. These HTLCs are carried as additional outputs in the commitment transactions, thereby increasing the transaction size and on-chain fees.
Hash Time-Locked Contracts (HTLCs) will be covered in detail in <<htlcs>>.
For now, assume that these are payments that are routed across the Lightning Network, rather than payments made directly between the two channel partners.
These HTLCs are carried as additional outputs in the commitment transactions, thereby increasing the transaction size and on-chain fees.
====
In general, you should not do a "force close" unless absolutely necessary. Your funds will be locked for a longer time and the person who opened the channel will have to pay higher fees. Furthermore, you might have to pay on-chain fees to abort or settle routing attempts even if you haven't opened the channel.
In general, a force close is not recommended unless absolutely necessary.
Your funds will be locked for a longer time and the person who opened the channel will have to pay higher fees.
Furthermore, you might have to pay on-chain fees to abort or settle routing attempts even if you didn't open the channel.
If the channel partner is known to you, you might consider contacting that individual or company and inquire why their Lightning Node is down and request that they restart it so that you can achieve a mutual close of the channel.
You should consider a force close, only as the last resort.
You should consider a force close only as the last resort.
===== The ugly way - Protocol breach
===== Protocol Breach (the ugly way)
If your channel partner broadcasts an old (revoked) commitment transaction - whether deliberately or not - your node should be able to detect this protocol breach. 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, before your channel partner can spend the payment and profit from the protocol breach.
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.
During the timelock, your node can broadcast a _punishment transaction_ that takes your own balance and uses the revocation secret to also take the balance of your channel partner.
Your node must be online and watching new blocks and transactions on the Bitcoin blockchain to detect this.
In this scenario the channel closure will be rather fast. You will have to pay on-chain fees to publish the punishment transaction, but your node can set these fees according to the fee estimation and not overpay. Furthermore, you will be taking the funds from your channel partner's balance too, so in a way the fees are unlikely to be a factor.
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 your node is not online and the timelock expires, your channel partner will be able to take whatever balance was allocated to them in that old commitment, perhaps as much as the entire channel balance. If there is any balance allocated to you, you will have to pay on-chain fees to collect that balance.
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.
Also all pending routing attempts will have to be resolved just as we saw in the force close scenario.
In this scenario, the channel closure will be rather fast.
You will have to pay on-chain fees to publish the punishment transaction, but your node can set these fees according to the fee estimation and not overpay.
You will generally want to pay higher fees to guarantee confirmation as soon as possible.
However, as you will eventually receive all of the cheater's funds, it is essentially the cheater who will be paying for this transaction.
The "ugly way" of channel closure can be executed faster than both the "good" and "bad" ways, because you can immediately publish the punishment transaction and collect all the funds.
If you fail to detect the protocol breach and the timelock expires, you will receive only the funds allocated to you by the commitment transaction your partner published.
Any funds you received after this will have been stolen by your partner.
If there is any balance allocated to you, you will have to pay on-chain fees to collect that balance.
Game theory predicts that cheating is not a successful strategy because it is easy to detect a cheater and the cheater will lose all funds committed in the channel.
As with a force close, all pending routing attempts will also have to be resolved in the commitment transaction.
Hence, we do not recommend cheating. We do, however, recommend that anyone catching a cheater punish them by taking their funds.
A Protocol Breach can be executed faster than a mutual close, as you do not wait to negotiate a close with your partner, and faster than a force close as you do not need to wait for your timelock to expire.
So, how do you catch a cheat or a protocol breach in your day-to-day activities?
Game theory predicts that cheating is not an appealing strategy because it is easy to detect a cheater, and the cheater risks losing _all_ of their funds while only standing to gain what they had in an earlier state.
Furthermore, as the Lightning Network matures, and watchtowers become widely available, cheaters will be able to be detected by a third party even if the cheated channel partner is offline.
You do so by running software that monitors the public Bitcoin blockchain for on-line transactions that correspond to any commitment transactions for any of your channels. This software is either:
Hence, we do not recommend cheating.
We do, however, recommend that anyone catching a cheater punish them by taking their funds.
* A properly maintained Lightning node, running 24x7.
So, how do you catch a cheat or a protocol breach in your day-to-day activities?
You do so by running software that monitors the public Bitcoin blockchain for on-chain transactions that correspond to any commitment transactions for any of your channels.
This software is either:
* A properly maintained Lightning node, running 24/7.
* A single-purpose _watchtower_ node that you run to watch your channels.
* A third-party watchtower node that you pay to watch your channels.
We will look at watchtowers in more detail in <<watchtowers>>.
Remember that the commitment transaction has a timeout period specified in a given number of blocks, up to a maximum of 2016.
As long as you run your Lightning node once before the timeout period is reached, it will catch all cheats. It is not advisable to take this kind of risk; it is just as easy to keep a well maintained node running continuously.
Remember that the commitment transaction has a timeout period specified in a given number of blocks, up to a maximum of 2016 blocks.
As long as you run your Lightning node once before the timeout period is reached, it will catch all cheating attempts.
It is not advisable to take this kind of risk; it is important to keep a well maintained node running continuously (See <<node_operations>>).
=== Invoices
@ -360,10 +426,10 @@ There is a way to send an "unsolicited" payment without an invoice, using a work
An invoice is a simple payment instruction containing information such as a unique payment identifier, called a payment hash, a recipient, an amount, and an optional text description.
The most important part of the invoice is the payment hash, that allows the payment to travel across multiple channel 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.
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.
@ -387,11 +453,11 @@ There is no known way to find the inverse of SHA256 (compute a preimage from a h
The payment process of the Lightning Network is only secure if +r+ is chosen completely randomly and is not predictable. This security relies on the fact that hash functions cannot be inverted or feasibly brute-forced and therefore no one can find +r+ from +H+.
==== Additional Meta Data
==== Additional Metadata
Invoices can optionally include other useful meta data such as a short text description. If a user has several invoices to pay, the user can read the description and be reminded what the invoice is about.
Invoices can optionally include other useful metadata such as a short text description. If a user has several invoices to pay, the user can read the description and be reminded of what the invoice is about.
The invoice can also include some _routing hints_, which are unannounced channels that have not been publicly announced, but can be used by the sender to construct a route to the recipient. Routing hints can also be used to suggest public channels, for example channels known by the recipient to have enough inbound capacity to route the payment.
The invoice can also include some _routing hints_, which allow the sender to use unannounced channels to construct a route to the recipient. Routing hints can also be used to suggest public channels, for example channels known by the recipient to have enough inbound capacity to route the payment.
In case the sender's Lightning node is unable to send the payment over the Lightning Network, invoices can optionally include an on-chain Bitcoin address as a fallback.
@ -407,7 +473,7 @@ Lightning invoices contain an expiry date. Since the recipient must keep the pre
We have seen how the recipient creates an invoice that contains a payment hash. This payment hash will be used to move the payment across a series of payment channels, from sender to recipient, even if they do not have a direct payment channel between them.
In the next few sections we will dive into the ideas and methods that are being used to deliver a payment over the Lightning Network and use all the concepts we have presented so far.
In the next few sections, we will dive into the ideas and methods that are being used to deliver a payment over the Lightning Network and use all the concepts we have presented so far.
First, let's look at the Lightning network's communication protocol.
@ -419,15 +485,15 @@ Channel announcements are communicated over a peer-to-peer _gossip protocol_. A
After opening a channel, a node may choose to send out an announcement of the channel via the `channel_announcement` message to its peers.
Every peer validates the information from the `channel_announcement` message and verifies that the funding transaction is confirmed on the Bitcoin blockchain.
After verification the node will forward the gossip message to its own peers, and they will forward to their peers and so on, spreading the announcement across the entire network.
After verification the node will forward the gossip message to its own peers, and they will forward it to their peers and so on, spreading the announcement across the entire network.
In order to avoid excessive communication the channel announcement is only forwarded by each node if it has not already forwarded that announcement previously.
The gossip protocol is also used to announce information about known nodes, with the `node_announcement` message.
For this message to be forwarded a node has to have at least one public channel announced on the gossip protocol, again to avoid excessive communication traffic.
Payment channels have various meta data that are useful for other participants of the network.
This meta data is mainly used for making routing decisions.
Since nodes might occasionally change the meta data of their channels, this information is shared in a `channel_update` message.
Payment channels have various metadata that are useful for other participants of the network.
This metadata is mainly used for making routing decisions.
Since nodes might occasionally change the metadata of their channels, this information is shared in a `channel_update` message.
These messages will only be forwarded approximately four times a day (per channel) to prevent excessive communication.
The gossip protocol also has a variety of queries and messages to initially synchronize a node with the view of the network or to update the node's view after being offline for a while.
@ -440,7 +506,7 @@ While Lightning could have been designed to share balance information of channel
. To protect the privacy of the users and not shout out every financial transaction and payment that is being conducted. Channel balance updates would reveal that a payment has moved across the channel. This information could be correlated to reveal all payment sources and destinations.
. To scale the amount of payments that can be conducted with the Lightning Network. Remember that the Lightning Network was created in the first place because notifying every participant about every payment does not scale well. Thus, the Lightning Network cannot be designed in a way that balance updates of channels are shared among participants.
. To scale the amount of payments that can be conducted with the Lightning Network. Remember that the Lightning Network was created in the first place because notifying every participant about every payment does not scale well. Thus, the Lightning Network cannot be designed in a way that balance updates of channels are shared among participants.
. The Lightning Network is a dynamic system. It changes constantly and frequently. Nodes are being added, other nodes are being turned off, balances change, etc. Even if everything is always communicated, the information will be valid only for a short amount of time. As a matter of fact, information is often outdated by the time it is received.
@ -450,59 +516,59 @@ For now, it is only important to know that the gossip protocol exists and that i
This topology information is crucial for delivering payments through the network of payment channels.
==== Path finding and routing
==== Pathfinding and routing
Payments on the Lightning Network are forwarded along a _path_ made of channels linking one participant to another, from the payment source to the payment destination. The process of finding a path from source to destination is called _path finding_. The process of using that path to make the payment is called _routing_.
Payments on the Lightning Network are forwarded along a _path_ made of channels linking one participant to another, from the payment source to the payment destination. The process of finding a path from source to destination is called _pathfinding_. The process of using that path to make the payment is called _routing_.
[NOTE]
====
A frequent criticism of the Lightning network is that "routing" is not solved, or even is an "unsolvable" problem. In fact, routing is trivial. Path finding, on the other hand, is a difficult problem. The two terms are often confused and need to be clearly defined to identify which problem we are attempting to solve.
A frequent criticism of the Lightning network is that "routing" is not solved, or even is an "unsolvable" problem. In fact, routing is trivial. Pathfinding, on the other hand, is a difficult problem. The two terms are often confused and need to be clearly defined to identify which problem we are attempting to solve.
====
As we will see next, the Lightning Network currently uses a _source-based_ protocol for path finding and an _onion routed_ protocol for routing payments. Source-based means that the sender of the payment has to find a path through the network to the intended destination. Onion-routed means that the elements of the path are layered (like an onion), with each layer encrypted so that it can only be seen by one node at a time. We will discuss onion routing in the next section.
As we will see next, the Lightning Network currently uses a _source-based_ protocol for pathfinding and an _onion routed_ protocol for routing payments. Source-based means that the sender of the payment has to find a path through the network to the intended destination. Onion-routed means that the elements of the path are layered (like an onion), with each layer encrypted so that it can only be seen by one node at a time. We will discuss onion routing in the next section.
=== Source-based Path Finding
=== Source-based Pathfinding
If we knew the exact channel balances of every channel we could easily compute a payment path using any of the standard path finding algorithms taught in any computer science program. This could even be solved in a way that optimizes the fees paid to nodes for forwarding the payment.
If we knew the exact channel balances of every channel we could easily compute a payment path using any of the standard pathfinding algorithms taught in any computer science program. This could even be solved in a way that optimizes the fees paid to nodes for forwarding the payment.
However, the balance information of all channels is not and cannot be known to all participants of the network. We need more innovative path finding strategies.
However, the balance information of all channels is not and cannot be known to all participants of the network. We need more innovative pathfinding strategies.
With only partial information about the network topology, path finding is a real challenge and active research is still being conducted into this part of the Lightning Network. The fact that the path finding problem is not "fully solved" in the Lightning Network is a major point of criticism towards the technology.
With only partial information about the network topology, pathfinding is a real challenge and active research is still being conducted into this part of the Lightning Network. The fact that the pathfinding problem is not "fully solved" in the Lightning Network is a major point of criticism towards the technology.
[NOTE]
====
One common criticism of path-finding in the Lightning network is that it is unsolvable because it is equivalent to the NP-complete _Traveling Salesperson Problem_, a fundamental problem in computational complexity theory. In fact, path finding in Lightning is not equivalent to TSP and falls into a different class of problems. We successfully solve these types of problems (path finding in graphs with incomplete information) every time we ask Google to give us driving directions with traffic avoidance. We also successfully solve this problem every time we route a payment on the Lightning network.
One common criticism of path-finding in the Lightning network is that it is unsolvable because it is equivalent to the NP-complete _Traveling Salesperson Problem_, a fundamental problem in computational complexity theory. In fact, pathfinding in Lightning is not equivalent to TSP and falls into a different class of problems. We successfully solve these types of problems (pathfinding in graphs with incomplete information) every time we ask Google to give us driving directions with traffic avoidance. We also successfully solve this problem every time we route a payment on the Lightning network.
====
Path finding and routing can be implemented in a number of different ways and multiple path-finding and routing algorithms can co-exist on the Lightning network, just as multiple routing algorithms exist on the internet. Source-based routing is one of many possible solutions and is successful at the current scale of the Lightning network.
Pathfinding and routing can be implemented in a number of different ways and multiple path-finding and routing algorithms can co-exist on the Lightning network, just as multiple path-finding and routing algorithms exist on the internet. Source-based pathfinding is one of many possible solutions and is successful at the current scale of the Lightning network.
The path finding strategy currently implemented by Lightning nodes is to "probe" paths until one is found that has enough liquidity to forward the payment. This is an iterative process of trial and error, until success is achieved or no path is found. The algorithm currently does not necessarily result in the path with the lowest fees. While this is not optimal and certainly can be improved, even this simplistic strategy works quite well.
The pathfinding strategy currently implemented by Lightning nodes is to "probe" paths until one is found that has enough liquidity to forward the payment. This is an iterative process of trial and error, until success is achieved or no path is found. The algorithm currently does not necessarily result in the path with the lowest fees. While this is not optimal and certainly can be improved, even this simplistic strategy works quite well.
This "probing" is done by the Lightning node or wallet and is not directly seen by the user.
The user might only realize that probing is taking place if the payment does not complete instantly.
[NOTE]
====
On the Internet we use the internet protocol and an IP forwarding algorithm to forward internet packages from the sender to the destination. While these protocols have the nice property of allowing internet hosts to collaboratively find a path for information flow through the internet, we cannot reuse and adopt this protocol for forwarding payments on the Lightning Network. Unlike the internet, Lightning payments have to be _atomic_ and channel balances have to remain _private_. Furthermore, the channel capacity in Lightning changes frequently, unlike the Internet where connection capacity is relatively static. These constraints require novel strategies.
On the Internet we use the internet protocol and an IP forwarding algorithm to forward internet packages from the sender to the destination. While these protocols have the nice property of allowing internet hosts to collaboratively find a path for information flow through the internet, we cannot reuse and adopt this protocol for forwarding payments on the Lightning Network. Unlike the internet, Lightning payments have to be _atomic_ and channel balances have to remain _private_. Furthermore, the channel capacity in Lightning changes frequently, unlike the Internet where connection capacity is relatively static. These constraints require novel strategies.
====
Of course, path finding is trivial if we want to pay our direct channel partner and we have enough balance on our side of the channel to do so. In all other cases, our node uses information from the gossip protocol to do path finding. This includes currently known public payment channels, known nodes, known topology (how known nodes are connected), known channel capacities, and known fee policies set by the node owners.
Of course, pathfinding is trivial if we want to pay our direct channel partner and we have enough balance on our side of the channel to do so. In all other cases, our node uses information from the gossip protocol to do pathfinding. This includes currently known public payment channels, known nodes, known topology (how known nodes are connected), known channel capacities, and known fee policies set by the node owners.
==== Onion routing
The Lightning Network uses an _onion routing protocol_ similar to the famous TOR (The Onion Router) network.
The Lightning Network uses an _onion routing protocol_ similar to the famous Tor (The Onion Router) network.
The onion routing protocol used in Lightning is called the _SPHINX mixformat_ and will be explained in detail in a later chapter.
[NOTE]
====
Lightning's onion routing SPHINX mixformat is only similar to the TOR network routing in concept, but both the protocol and the implementation are entirely different from those use in the TOR network.
Lightning's onion routing SPHINX mixformat is only similar to the Tor network routing in concept, but both the protocol and the implementation are entirely different from those used in the Tor network.
====
A payment package used for routing is called an "onion". footnote:[The term "onion" was originally used by the TOR project. Moreover, the Tor network is also called the Onion network and the project uses an onion as its logo. The top level domain name used by TOR services on the internet is ".onion".]
A payment package used for routing is called an "onion". footnote:[The term "onion" was originally used by the Tor project. Moreover, the Tor network is also called the Onion network and the project uses an onion as its logo. The top level domain name used by Tor services on the internet is ".onion".]
Let's use the onion analogy to follow a routed payment. On its route from payment sender (payer) to payment destination (payee) the onion is passed from node to node along the path. The sender constructs the entire onion, from the center out. First, the sender creates the payment information for the (final) recipient of the payment and encrypts it with a layer of encryption that only the recipient can decrypt. Then, the sender wraps that layer with instructions for the node in the path _immediately preceding the final recipient_ and encrypts with a layer that only that node can decrypt.
The layers are built up with instructions working backwards until the entire path is encoded in layers. The sender then gives the complete onion to the first node in the path that can only read the outermost layer. Each node peels a layer, and finds instructions inside revealing the next node in the path and passes the onion on. As each node peels one layer, it can't read the rest of the onion. All it knows is where the onion came from and where it is going next, without any indication as to who is the original sender or the ultimate recipient.
The layers are built up with instructions working backward until the entire path is encoded in layers. The sender then gives the complete onion to the first node in the path that can only read the outermost layer. Each node peels a layer, and finds instructions inside revealing the next node in the path and passes the onion on. As each node peels one layer, it can't read the rest of the onion. All it knows is where the onion came from and where it is going next, without any indication as to who is the original sender or the ultimate recipient.
This continues until the onion reaches the payment destination (payee). Then, the destination node opens the onion and finds there are no further layers to decrypt and can read the payment information inside.
@ -519,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.
@ -565,7 +631,7 @@ All communication between peers is sent via messages called _Lightning Messages_
https://noiseprotocol.org/
The use of the Noise Protocol Framework in the Lightning Network ensures that every message on the network is both authenticated and encrypted, increasing the privacy of the network and its resistance to traffic analysis, deep packet inspection and eavesdropping. However, as a side-effect, this makes protocol development and testing a bit tricky as one can't simply observe the network with a packet capture or network analysis tool such as wireshark. Instead, developers have to use specialized plugins that decrypt the protocol from the perspective of one node, such as the _lightning dissector_, a wireshark plugin:
The use of the Noise Protocol Framework in the Lightning Network ensures that every message on the network is both authenticated and encrypted, increasing the privacy of the network and its resistance to traffic analysis, deep packet inspection and eavesdropping. However, as a side-effect, this makes protocol development and testing a bit tricky as one can't simply observe the network with a packet capture or network analysis tool such as Wireshark. Instead, developers have to use specialized plugins that decrypt the protocol from the perspective of one node, such as the _lightning dissector_, a Wireshark plugin:
https://github.com/nayutaco/lightning-dissector
@ -573,23 +639,23 @@ https://github.com/nayutaco/lightning-dissector
As long as a person follows the protocol and has their node secured, there is no major risk of losing funds when participating in the Lightning Network.
However, there is the cost of paying on-chain fees when opening a channel.
Any cost should come with a corresponding benefit.
In our case the reward for Alice for bearing the cost of opening a channel is that Alice can send and receive payments of bitcoin on the Lightning Network at any time and that she can earn fees in bitcoin by forwarding payments for other people.
In our case the reward for Alice for bearing the cost of opening a channel is that Alice can send and, after moving some the coins to the other end of the channel, receive payments of bitcoin on the Lightning Network at any time and that she can earn fees in bitcoin by forwarding payments for other people.
Alice knows that in theory Bob can close the channel immediately after opening resulting in on-chain closing fees for Alice.
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 in a foreign country 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
While the Lightning Network is built on top of Bitcoin and inherits many of its features and properties, there are important differences that users of both networks need to be aware of.
Some of these differences are differences of terminology. There are also architectural differences and differences in the user experience. In the next few sections we will examine the differences and similarities, explain the terminology and adjust our expectations.
Some of these differences are differences in terminology. There are also architectural differences and differences in the user experience. In the next few sections we will examine the differences and similarities, explain the terminology and adjust our expectations.
==== Addresses vs Invoices, Transactions vs Payments
In typical payment using Bitcoin, a user receives a Bitcoin address (e.g. scanning a QR code on a webpage, or receiving it in an instant message or email from a friend). They then use their Bitcoin wallet to create a transaction to send funds to this address.
In a typical payment using Bitcoin, a user receives a Bitcoin address (e.g. scanning a QR code on a webpage, or receiving it in an instant message or email from a friend). They then use their Bitcoin wallet to create a transaction to send funds to this address.
On the Lightning Network, the recipient of a payment creates an invoice. A Lightning invoice can be seen as analogous to a Bitcoin address. The intended recipient gives the Lightning invoice to the sender, as a QR code or character string, just like a Bitcoin address.
@ -605,7 +671,7 @@ In order to make a payment on the Bitcoin network, a sender needs to consume one
If a user has multiple UTXOs, they (or rather their wallet) will need to select which UTXO(s) to send.
For instance, a user making a payment of 1 BTC can use a single output with value 1 BTC, two outputs with value 0.25 BTC and 0.75 BTC, or four outputs with value 0.25 BTC each.
On Lightning, payments do not require inputs to be consumed, Instead each payment results in an update of the channel balance, redistributing it between the two channel partners. The sender experiences this as "moving" channel balance from their end of a channel to the other end, to their channel partner. Lightning payments use a series of channels to route from sender to recipient. Each of these channels must have sufficient capacity to route the payment.
On Lightning, payments do not require inputs to be consumed, Instead, each payment results in an update of the channel balance, redistributing it between the two channel partners. The sender experiences this as "moving" channel balance from their end of a channel to the other end, to their channel partner. Lightning payments use a series of channels to route from sender to recipient. Each of these channels must have sufficient capacity to route the payment.
As many possible channels and paths can be used to make a payment, the Lightning user's choice of channels and paths is somewhat analogous to the Bitcoin user's choice of UTXO.
@ -636,7 +702,7 @@ If there are more transactions in the queue (called the mempool) than can fit in
Thus, when there are many transactions in the queue, users have to pay a higher fee to be included in the next block, or they have to wait until there are fewer transactions in the queue.
This naturally leads to the emergence of a fee market where users pay based on how urgently they need their transaction included in the next block.
The scarce resource on the Bitcoin network is the space in the blocks. Bitcoin users compete for block space. And the Bitcoin fee market is based on available block space. The scarce resource in the Lightning network is the channel liquidity (capacity of funds available for routing in channels) and channel connectivity (how many and well connected nodes your channels can reach). Lightning users compete for capacity and connectivity and therefore the Lightning fee market is driven by capacity and connectivity.
The scarce resource on the Bitcoin network is the space in the blocks. Bitcoin users compete for block space. And the Bitcoin fee market is based on available block space. The scarce resource in the Lightning network is the channel liquidity (capacity of funds available for routing in channels) and channel connectivity (how many well connected nodes your channels can reach). Lightning users compete for capacity and connectivity and therefore the Lightning fee market is driven by capacity and connectivity.
On the Lightning Network, users are paying fees to the users routing their payments. Routing a payment, in economic terms, is nothing more than providing and assigning capacity to the sender. Naturally, routers who charge lower fees for the same capacity will be more attractive to route through. Thus a fee market exists where routers are in competition with each other over the fees they charge to route payments through their channels.
@ -647,7 +713,7 @@ In addition, blockchain surveillance companies collect and analyze this data en-
Lightning Network payments, on the other hand, are almost completely private. Typically only the sender and the recipient are fully aware of the source, destination, and amount transacted in a particular payment. Furthermore, the receiver may not even know the source of the payment. As payments are onion-routed, the users who route the payment are only aware of the amount of the payment, but can neither determine the source nor the destination.
In summary, Bitcoin transactions are broadcast publicly and stored forever. Lightning payments are executed between a few selected peers and information about them is privately stored and only until the channel is closed. Creating mass surveillance and analysis tools equivalent to those used on Bitcoin will be impossible on Lightning.
In summary, Bitcoin transactions are broadcast publicly and stored forever. Lightning payments are executed between a few selected peers and information about them is privately stored and only until the channel is closed. Creating mass surveillance and analysis tools equivalent to those used on Bitcoin will be much harder on Lightning.
==== Waiting for Confirmations vs Instant Settlement
@ -673,7 +739,7 @@ Hence, capacity and connectivity are critical and scarce resources in the Lightn
==== Incentives for Large Value Payment vs. Small Value Payments
The fee structure in Bitcoin is independent of the transaction value.
A $1 million transaction has the same fee as a $1 transaction on Bitcoin, assuming similar transaction size in bytes.
A $1 million transaction has the same fee as a $1 transaction on Bitcoin, assuming a similar transaction size in bytes.
In Lightning the fee is a fixed base fee plus a percentage of the transaction value.
Therefore, in Lightning the payment fee increases with payment value.
These opposing fee structures create different incentives and lead to different usage in regards to transaction value.
@ -706,13 +772,15 @@ The synchronous and always-online nature of the Lightning network is probably th
On Bitcoin the smallest amount is a _satoshi_ which cannot be divided any further. Lightning is a bit more flexible, and Lightning nodes work with _milli-satoshis_ (thousandths of a satoshi). This allows tiny payments to be sent via Lightning. A single milli-satoshi payment can be sent across a payment channel, an amount so small it should properly be characterized as a _nanopayment_.
The milli-satoshi unit cannot, of course, be settled on the Bitcoin blockchain at that granularity. Upon channel closure, balances are rounded to the nearest satoshi. But over the lifetime of a channel, millions of nanopayments are possible at milli-satoshi levels. The Lightning network breaks throught the micropayment barrier.
The milli-satoshi unit cannot, of course, be settled on the Bitcoin blockchain at that granularity. Upon channel closure, balances are rounded to the nearest satoshi. But over the lifetime of a channel, millions of nanopayments are possible at milli-satoshi levels. The Lightning network breaks through the micropayment barrier.
=== Commonality of Bitcoin and Lightning
While the Lightning Network differs from Bitcoin in a number of ways, including in architecture and user experience, it is built from Bitcoin and retains many of Bitcoins core features.
==== 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
@ -720,7 +788,7 @@ Both Bitcoin transactions and Lightning payments are irreversible and immutable.
==== Trust and counterparty risk
Just as Bitcoin, Lightning requires the user only to trust mathematics, encryption, and that the software does not have any critical bugs. Neither Bitcoin nor Lightning require the user to trust a person, a company, an institution, or a government.
Just as Bitcoin, Lightning requires the user only to trust mathematics, encryption, and that the software does not have any critical bugs. Neither Bitcoin nor Lightning requires the user to trust a person, a company, an institution, or a government.
Since Lightning sits on top of Bitcoin and relies on Bitcoin as its underlying base layer, it is clear that the security model of Lightning reduces to the security of Bitcoin. This means that Lightning offers broadly the same security as Bitcoin under most circumstances, with only a slight reduction in security under some narrow circumstances.
==== Permissionless operation
@ -734,6 +802,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 Lightinng 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.

@ -78,6 +78,10 @@ All submission should use Unix-like line endings: LF (not CR, not CR/LF). All th
If you are unsure or your OS makes things difficult, consider using a developer's text editor such as Atom.
## Spelling
US English spelling standards should be used for contributions to the text.
## Thanks
We are very grateful for the support of the entire Lightning Network community. With your help, this will be a great book that can help thousands of developers get started and eventually "master" LN. Thank you!

@ -5,7 +5,7 @@
<img src="images/cover_thumb.png" width=200 alt="Mastering Lightning Cover">
## About
Mastering the Lightning Network is an O'Reilly Media book, due for publication in Q4'2020, and announced on August 28th by authors Andreas M. Antonopoulos ([@aantonop](https://twitter.com/aantonop)), Olaoluwa Osuntokun ([@roasbeef](https://twitter.com/roasbeef)), Rene Pickhardt ([@renepickhardt](https://twitter.com/renepickhardt)).
Mastering the Lightning Network is an O'Reilly Media book, due for publication in Q2'2021, and announced in August 2019 by authors Andreas M. Antonopoulos ([@aantonop](https://twitter.com/aantonop)), Olaoluwa Osuntokun ([@roasbeef](https://twitter.com/roasbeef)), Rene Pickhardt ([@renepickhardt](https://twitter.com/renepickhardt)).
The book describes the Lightning Network (LN), a Peer-to-Peer protocol running on top of Bitcoin and other blockchains, which provides near-instant, secure, micro-payments.
@ -25,23 +25,25 @@ The current status of the book is "IN PROGRESS". See below for status of specifi
| Section | Length (Word Count) | Status |
|-------|------|:------:|
| [Preface and Acknowledgments](preface.asciidoc) | ### | :arrows_clockwise: |
| [Glossary](glossary.asciidoc) | ############# | :arrows_clockwise: |
| [Introduction](01_introduction.asciidoc) | ##### | :mag: |
| [Getting Started](02_getting_started.asciidoc) | ########### | :mag: |
| [LN Basics (How LN Works)](03_how_ln_works.asciidoc) | ########################## | :mag: |
| [Intro to LN Routing (HTLCs)](routing.asciidoc) | ###################### | :lock_with_ink_pen: |
| [Preface and Acknowledgments](preface.asciidoc) | #### | :arrows_clockwise: |
| [Glossary](glossary.asciidoc) | ############## | :arrows_clockwise: |
| [Introduction](01_introduction.asciidoc) | ###### | :mag: |
| [Getting Started](02_getting_started.asciidoc) | ############ | :mag: |
| [LN Basics (How LN Works)](03_how_ln_works.asciidoc) | ########################### | :mag: |
| [Nodes (LN Clients)](node_client.asciidoc) | #################### | :mag: |
| [Operating a Node](node_operations.asciidoc) | ################# | :bookmark_tabs: |
| [P2P Communication](p2p.asciidoc) | # | :bookmark_tabs: |
| [Channel Construction in Detail](channel-construction.asciidoc) | ######### | :lock_with_ink_pen: |
| [Channel Graph and Gossip Layer](channel-graph.asciidoc) | # | :bookmark_tabs: |
| [Payment Path Finding](path-finding.asciidoc) | ############## | :bookmark_tabs: |
| [End-to-End Payment Presentation Layer](e2e-presentation-layer.asciidoc) | ## | :bookmark_tabs: |
| [Operating a Node](node_operations.asciidoc) | ############################ | :mag: |
| PART 2 | PART 2 | PART2 |
| [Intro to LN Routing (HTLCs)](routing.asciidoc) | #################### | :lock_with_ink_pen: |
| [Channel Construction in Detail](channel-construction.asciidoc) | ########### | :lock_with_ink_pen: |
| [Channel operation with HTLCs and Statemachine](channel-operation.asciidoc) | ###### | :lock_with_ink_pen: |
| [Payment Path Finding](path-finding.asciidoc) | ############### | :lock_with_ink_pen: |
| [P2P Communication](p2p.asciidoc) | ### | :bookmark_tabs: |
| [Channel Graph and Gossip Layer](channel-graph.asciidoc) | ### | :bookmark_tabs: |
| [End-to-End Payment Presentation Layer](e2e-presentation-layer.asciidoc) | ### | :bookmark_tabs: |
| [Lightning Applications (LApps)]() | # | :thought_balloon: |
| [LN's Future]() | # | :thought_balloon: |
Total Word Count: 71133
Total Word Count: 89705
Target Word Count: 100,000-120,000

@ -1,46 +1,43 @@
Payment channels are the core and most fundamental building block of the Lightning Network.
After you have learnt about payment channels in the first half of the book and after we explained how they can be connected to a network we want to finally dig down and explain the construction of payment channels in detail.
Of course, every detail of a technology exists for a reason and is important.
However the Lightning Network is literally built around the idea and concept of payment channels.
But we believe that payment channels are the core and most fundamental building block of the Lightning Network around.
It is literally built around the idea and concept of payment channels.
Thus in order master the Lightning Network you should be able to understand how payment channels will be constructed.
As several methods for channels exist we stress that it is not important to remember all the details of every method.
As with most technologies it is important to understand the core concepts and building blocks which we will try to lay out for you as clearly as possible while still emphasizing on the technical details.
In the previous chapters you have already learned that payment channels
* allow two peers who created it to send and receive Bitcoin up to the amount specified by the capacity of the channel as often as they want to.
* split the capacity of the channel into a balance between the two peers which - as long as the channel is open is only known by the owners of the channel and increases privacy.
* split the capacity of the channel into a balance between the two peers which - as long as the channel is open - is only known by the owners of the channel and increases privacy.
* do not require peers to do any additional onchain transactions other than the one needed to open and - potentially at a later state - to close the channel.
* can stay open for an arbitrary time. Potentially in the best case forever.
* do not require peers to trust each other as any attempt by a peer to cheat would enable the other peer to receive all the funds in the channel as a panality.
* can be connected to a network and allow peers to send money a long a path of connected channels without the necessity to trust the intermediary nodes as they have no ability to steal the Bitcoin that are being forwarded.
*
* do not require peers to trust each other as any attempt by a peer to cheat would enable the other peer to take all the funds in the channel as a penalty.
* can be connected to a network and allow peers to send money along a path of connected channels without the necessity to trust the intermediary nodes as they do not have the ability to steal the Bitcoin that are being forwarded.
In this chapter we will dig deeper into the protocol details that are needed to open and close payment channels.
Working through this rather technical chapter you will be able to understand how the protocol design achieves the properties of payment channels.
Especially with the opening part of a payment channel the ideas for updating a channel should already become clear but we will defer to explain the details how HTLCs are being used in the channel operation chapter which comes directly after this chapter.
Working through this rather technical chapter you will be able to understand how the protocol design achieves the main properties of payment channels.
Where necessary some information from the first chapters of this book will be repeated.
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.
There will be one big difference though.
We will only discuss opening and closing a channel.
The operation and maintainance of a channel which means either making or forwarding a payment is discussed in our chapter about routing.
Also other constructions of payment channels are known and being discussed by the developers.
Historically speaking these are the Duplex Micropayment channels introduced by Christian Decker during his time as a PhD student at ETH Zuric and the eltoo channels which where also introduced by Christian Decker.
The eltoo channels are certainly a more elgant and cleaner why of achieving payment channels with the afore mentioned properties.
However they require the activation of BIP 118 and a softfork and are - at the time of writing - a potential future protocol change.
Thus this chapter will only focus on the pentalty based channels as described in the Lightning Network Whitepaper and specified in BOLT 02 which are currently supported by the protocol and the implementations.
As stated we will only discuss opening and closing a channel in this chapter and
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.
[NOTE]
====
The Lightning Network does not need consensus of features across it's participants.
If the Bitcoin Softfork related to BIP 118 activates and people implement eltoo channels nodes that support eltoo can create payment channels and the onion routing of payments a long a path of channels would work just fine even if some of the channels are the modern eltoo channels or some channels are the legacy channels.
Actually when Lightning network connections are established nodes signal feature bits of global and local features that they support.
Thus havning the ability to create eltoo channels would just be an additional feature bit.
In this sense upgrading the Lightnign Network is much easier than upgrading Bitcoin where consensus among all stakeholders is needed.
====
=== Summary of what you (should) know about payment channels and Bitcoin
Let's quickly summarize what you hopefully already know about payment channels on a technical level after reading the book thus far.
Let us emphasize that knowing does not necessarily mean understanding yet.
Let's quickly summarize what you should already know about payment channels on a technical level and for what you will learn the details in this chapter.
A payment channel is encoded as an unspent 2-of-2 multisignature transaction output.
The capacity of the channel relates to the amount that is bound to the unspent 2-of-2 multisignature transaction output.
It is opened with the help of a funding transaction that sends bitcoin to a 2-of-2 multisignature output together with a communication protocol that helps to initialize and maintain its state.
The balance of the channel encodes how the capacity is split between the two peers who maintain the channel.
Technically the balance is encoded by a the most recent pair of a sequence of pairs of similar (but not equal) presigned commitment transactions.
1. A payment channel is encoded as an unspent 2-of-2 multisignature transaction output.
2. The capacity of the channel relates to the amount that is bound to the unspent 2-of-2 multisignature transaction output.
3. It is opened with the help of a funding transaction that sends bitcoin to a 2-of-2 multisignature output.
4. The funding tx can only be broadcasted to the Bitcoin network if a refund or settlement transaction exist.
5. The channel also consists of a communication protocol that helps to initialize and maintain its state.
6. The balance of the channel encodes how the capacity is split between the two peers who maintain the channel. Technically the balance is encoded by the most recent pair of a sequence of pairs of similar (but not equal) presigned commitment transactions.
7. The commitment transaction will include scripts and contracts that allow owners of the channel to take all funds in case the other party tries breach the protocol
8. There are three ways of closing a channel, the good, the bad and the ugly which refer to the mutual close, forced close and the penalty close respectively.
.Bitcoin, Lightning and "Ownership" of funds
****
@ -48,37 +45,106 @@ When someone says they 'own' bitcoin they typically mean that they know the priv
The private key allows the owner to produce a signature for a transaction that spends the bitcoin by sending it to a different address.
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 own 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.
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 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 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.
One thing about the Lightning Network is however messing with this understanding of ownership.
On the Lightning Network there exist several presigned Transactions which allocate some of the bitcoin to you and some to your channel partner.
Without the the ability to sequence transaction and invalidate old ones via the penalty based revocation mechanism (or other techniques) we could not define clear ownership as the funds would be distributed among its two owners according to which ever transaction would first be broadcasted and successfully mined.
If the last paragraph of this summary was confusing: No worries! We are getting there now!
****
These commitment transactions should never hit the blockchain and serve as a safty net for the participants in case the channel partner becomes unresponsive of disappears.
They are also the reason why the Lightning Network is called an offchain scaling solution.
## Opening a channel
A payment channel needs to be established before it can be utilized to send, receive and route bitcoin.
There is always liquidity tied to the payment channel.
This liquidity is provided by the person who initiates the opening of the channel.
We call that person the funder of the channel.
At the time of writing this book the protocol only supports funding of a payment channel by the peer who initiates the opening of the channel.
The funding of the payment channel happens by a regular on chain transaction.
This funding transaction sends Bitcoin which the funder controlled to a 2-of-2 multisignature output that is controlled by both peers of the channel.
In order to safely do so several things had to be prepared:
. Both peers needed to have a secure communication channel established.
. The funder needs to know the public key that is used by the other peer for their multisig address.
. There needs to be a revokable refund transaction available that sends all the funds back to the funder in case the other peer becomes irresponsive.
We will assume that the secure communication channel has already been established.
You can learn more about this in the chapter about peer connection establishing.
The second and third points are exactly why a channel opening protocol must exist and cannot be as easy as just sending bitcoin to a 2-of-2 multisig output.
Especially the third point makes heavy use of the segwit upgrade but we will come to that.
The entire channel opening protocol requires a 6 - way handshake and is thus considerably more complex than establishing a TCP connection.
The Protocol goes in a sequential way in which every peer sends 3 messages.
We can see an overview in this diagram (which was taken directly from BOLT2 of the Lightning-rfc):
+-------+ +-------+
| |--(1)--- open_channel ----->| |
| |<-(2)-- accept_channel -----| |
| | | |
| A |--(3)-- funding_created --->| B |
| |<-(4)-- funding_signed -----| |
| | | |
| |--(5)--- funding_locked ---->| |
| |<-(6)--- funding_locked -----| |
+-------+ +-------+
### Step1: Signaling the intent to open a channel.
When Alice wishes to open a channel with Bob she sends an `open_channel` message to Bob.
This message tells Bob that Alice wishes to create a channel.
While there is obviously not a unique way of designing a protocol we can think about what kind of information Alice might have to change with Bob, so that they can safely operate a payment channel together.
In order to find a good answer we remind ourselves that in order for Alice and Bob to safely operate the channel each of them needs to control a presigned commitment transaction that spends from the output of the funding transaction.
As the funding transaction will send the funds of the channel to a 2-of-2 multisig output it is very reasonable that Alice needs to tell Bob at some point in the protocol, what her key for that address looks like.
Thus she can already put that information into the `open_channel` message via the `funding_pubkey` field.
While the Lightning Network Protocol was created to scale Bitcoin the principles of the Protocol can be used on top of other blockchains as well.
Thus Alice needs to inform Bob that she will use the Bitcoin Blockchain to secure this channel.
She can do so by putting the hash of the bitcoin genesis block into the `chain_hash` field of the funding transaction.
Obviously Alice needs to share some information with Bob about the channel that she wishes to create.
Thus this message contains
[NOTE]
====
These commitment transactions should never hit the blockchain and serve as a safety net for the participants in case the channel partner becomes unresponsive of disappears.
They are also the reason why the Lightning Network is called an off-chain scaling solution.
Each channel partner has both signatures for one of the commitment transactions from the sequence of pairs.
====
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 secrete or after a timelock with the secret key that is controled by the peer holding this commitment transaction.
The revocation secrete 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 `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 disincentive peers to publish previous commitment transactions.
Addresses and revocation 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.
### Security of a Payment channel
While the BOLTs introduce payment channels directly with the opening protocol we have decided to talk about the security model first.
The security of payment channels come through a penalty based revocation system which help two parties to split the capacity of the payment channel into a balance sheet without the necessity to trust each other.
In this chapter we start from an insecure approach of creating a payment channel and explain why it is insecure.
We will then explain how time locks are being used to create revokable sequence maturity contracts that create the penality based revokation system which economically incentivizes people maintain the most recent state.
We will then explain how time locks are being used to create revokable sequence maturity contracts that create the penalty based revocation system which economically incentivize people maintain the most recent state.
After you understood these concepts we will quickly walk you through the technical details of opening and closing a channel.
Any known payment channel constuction uses a 2-of-2 multisgnature output as the basis of the payment channel.
Any known payment channel construction uses a 2-of-2 multisgnature output as the basis of the payment channel.
We call the amount that is attached to this output the capacity of the channel.
In every case, both channel partners hold 1 secret key of the multisignature address which means that they can only collaboratively control the funds.
#### An example for a highly insecure payment channel construction
Let us assume Alice does not know the details about the Lightning Network and naivly tries to open a payment channel in a way that will likely lead to the loss of her funds.
Let us assume Alice does not know the details about the Lightning Network and naively tries to open a payment channel in a way that will likely lead to the loss of her funds.
Alice has heard that payment channel are 2-of-2 multisignature outputs.
As she wants to have a channel with Bob and since she knows a public key from Bob she decides to open a channel by sending money to a 2-of-2 multisignature address that comes from Bob's and her key.
We call the transaction that Alices used a **funding transaction** as it is supposed to fund the payment channel.
@ -89,7 +155,7 @@ That is because the coins would be stuck in the 2-of-2 multisignature address to
Luckily Alice has previously read Mastering Bitcoin and she knows all the properties of Bitcoin script and is aware of the risks that are involved with sending Bitcoins to a 2-of-2 multisignature address to which she does not control both keys.
She is also aware of the "Don't trust. Verify" principle that Bitcoiners follow and doesn't want to trust Bob to help her moving or accessing her coins.
She would much more prefere to keep control over her coins even though they shall be stored in this 2-of-2 multisignature address.
She would much more prefer to keep control over her coins even though they shall be stored in this 2-of-2 multisignature address.
While this seems like an impossible problem, Alice has an idea:
What if she could already prepare a refund transaction (which we call commitment transaction in future) that sends all the bitcoin back to an address that she controls?
@ -105,15 +171,15 @@ On the other side you as a reader might think:
Why would Alice send money to a multisignature address just to prepare a transaction that sends the money back to her?
We really hope you have wondered about this because this is really the point where the innovation begins.
Just because in general people are expected to broadcast a transaction to the bitcoin network as soon as they have signed it noone forces you to do that.
Just because in general people are expected to broadcast a transaction to the bitcoin network as soon as they have signed it no one forces you to do that.
As Alice would loose access of her Bitcoins once she sends it to a 2-of-2 multisignature output for which she only controls one key, she needs to make sure that she will be able to regain access of her coins in case Bob becomes unresponisive.
As Alice would loose access of her Bitcoins once she sends it to a 2-of-2 multisignature output for which she only controls one key, she needs to make sure that she will be able to regain access of her coins in case Bob becomes unresponsive.
Thus before Alice publishes the funding transaction she will create another transaction that sends all the bitcoin from the 2-of-2 multisignature output back to an address which she controls.
.The situation can be seen in the following picture
image:channel-construction-opening-1.png[]
image:images/channel-construction-opening-1.png["Channel construction..."]
Of course for the commitment transaction Alice would need to get a signature from Bob before she can safely broadcast the funding transaction.
After publishing the funding transaction instead of braodcasting the commitment transaction she will keep it in a safe place.
After publishing the funding transaction instead of broadcasting the commitment transaction she will keep it in a safe place.
For this to work Alice needs to be sure that the funding transaction could not be published with a different transaction id.
This malleability was possible before the Segwit upgrade of Bitcoin.
We will discuss the details later but didn't want to leave them out here.
@ -129,7 +195,7 @@ We have seen the first of three main properties that commit transactions fulfill
Commitment Transactions refund channel participants in case the other side becomes irresponsive.
The second purpose was implicitely defined by the first purpose:
The second purpose was implicitly defined by the first purpose:
Commitment Transactions split the capacity of the channel into a balance which is owned by each partner.
@ -141,7 +207,7 @@ Let us assume as an example that Alice wants to send 30k Satoshi to Bob.
For now we can assume that through some communication protocol Alice and Bob would negotiate a double spent of the funding transaction output of 100k satoshi.
The new commitment transaction for which Alice and Bob would exchange signatures would send 70k satoshi to Alice and 30k Satoshi to Bob.
The situation can be seen in the following picture
image:channel-construction-opening-2.png[]
image:images/channel-construction-opening-2.png["A new balance in an insecure payment channel"]
Whenever Alice and Bob want to change the balance of the payment channel they will negotiate a new commitment transaction.
Effectively they double spend the funding transaction output.
But as the commitment transactions are not broadcasted - as long as the channel stays open - they will be able to do that.
@ -159,7 +225,7 @@ But similarly Alice could broadcast the first commitment transaction and transfe
As Bitcoin prevents double spending of the funding transaction miners will include only one of the two commitment transactions.
Thus we need to adapt the idea with the commitment transactions to create the ability to revoke an old commitment transaction.
Regarding the fact that Bob and Alice both have a copy of the transaction and that Bob cannot control the data that Alice has stored on her hardware, it seems pretty hopeless.
Luckily, the scripting language in Bitcoin allows at least for changing commitment transactions in a way that economically disincentivises channel partners from publish an outdated balances after they have negotated a new balance.
Luckily, the scripting language in Bitcoin allows at least for changing commitment transactions in a way that economically disincentives channel partners from publish an outdated balances after they have negotiated a new balance.
#### Secure Payment channels via Revokable Commitment transactions
@ -169,7 +235,7 @@ Luckily, the scripting language in Bitcoin allows at least for changing commitme
In summary we can conclude that commitment transactions fulfill three purposes:
1. Refund channel participants in case the other side becomes irresponsive
2. Split the capacity of the channel into the current balance that peers have agreed upon.
3. Allow revocation of old state through the means of a penality via a revocable sequence maturity contract.
3. Allow revocation of old state through the means of a penalty via a revocable sequence maturity contract.
====
We have not yet explained how channel partners actually communicate to negotiate a new balance.
@ -181,7 +247,7 @@ That is why we only explain this in the routing chapter and ask you to stay pati
[NOTE]
====
*TODO: Move this note to routing chapter?*
HTLCS fullfill the following purposes:
HTLCS fullfil the following purposes:
1. Make a conditional payment.
2. Help to update a new balance in a channel
3. Make payments through a path of channel atomic, meaning that peers along the path cannot steal funds.
@ -207,10 +273,10 @@ Even though Alice and Bob both have a public node key to which they own the priv
Let us assume for a moment that Alice would send 100k Satoshi to the Multisig address resulting from hers and Bob's public node id.
In that case Alice will never be able to maintain her funds back without the help of Bob.
Of course we want our payment channels to work in a way that Alice does not need to trust Bob.
Bob could however refuse to sign a transaction that sends all those outputs back to an address that is controled by Alice.
He would be able to blackmail Alice to assign a significant amount of those Bitcoin to an output address that is controled by him.
Bob could however refuse to sign a transaction that sends all those outputs back to an address that is controlled by Alice.
He would be able to blackmail Alice to assign a significant amount of those Bitcoin to an output address that is controlled by him.
Thus Bob can't steel the coins from Alice directly but he can threten Alice to have her coins lost forever.
This example shows that unfortunatelly opening a channel will be a little bit more complex than just sending Bitcoins to a multisignature address.
This example shows that unfortunately opening a channel will be a little bit more complex than just sending Bitcoins to a multisignature address.
====
@ -242,26 +308,45 @@ While the Lightning Network was certainly invented to scale the amount of paymen
If a node has channels with more than one currency it is even possible to route payments through multi asset channels.
However this turns out to be a little bit tricky in reality as the exchange rate between currencies might change which might lead the forwarding node to wait for a better exchange rate to settle or to abort the payment process.
For the opening process the final channel id cannot be determined yet thus Alice needs to select a random channel id with Bob that she can use to identify the messages for this channel during the opening phase.
This design descision allows multiple channels to exist between two nodes - though currently only LND supports this feature.
This design decision allows multiple channels to exist between two nodes - though currently only LND supports this feature.
Alice tells Bob for how many satoshis she wishes to open the channel.
This information is necessary to construct the commitment transaction ...
Once the channel is open Alice will be able to send 99k satoshi along this channel.
Bob on the other side will be able to receive 99k satoshi along that channel.
This means that initially Alice will not be able to recieve Bitcoins on this channel and that Bob initially will not be able to send Bitcoin along that channel.
This means that initially Alice will not be able to receive Bitcoins on this channel and that Bob initially will not be able to send Bitcoin along that channel.
== Other payment channel constuctions
Other constructions of payment channels are known and being discussed by the developers.
Historically speaking these are the Duplex Micropayment channels introduced by Christian Decker during his time as a PhD student at ETH Zurich and the eltoo channels which where also introduced by Christian Decker.
The eltoo channels are certainly a more elgant and cleaner way of achieving payment channels with the afore mentioned properties.
However they require the activation of BIP 118 and a softfork and are - at the time of writing - a potential future protocol change.
Thus this chapter will only focus on the penalty based channels as described in the Lightning Network Whitepaper and specified in BOLT 02 which are currently supported by the protocol and the implementations.
[NOTE]
====
The Lightning Network does not need consensus of features across it's participants.
If the Bitcoin Softfork related to BIP 118 activates and people implement eltoo channels nodes that support eltoo can create payment channels and the onion routing of payments along a path of channels would work just fine even if some of the channels are the modern eltoo channels or some channels are the legacy channels.
Actually when Lightning Network connections are established nodes signal feature bits of global and local features that they support.
Thus having the ability to create eltoo channels would just be an additional feature bit.
In this sense upgrading the Lightning Network is much easier than upgrading Bitcoin where consensus among all stakeholders is needed.
====
=== Multiparty channels and channel factories
The current construction could be generalized to multiparty channels and channel factories.
However the communication protocol would suffer from increased complexity.
====
Especially the simplifications in the protocol that might result from eltoo will lead to such features.
A channel factory is a...
A multi party channel is a...
Chapter overview:
* describes how channels are put together at the script+transaction level
* details how a channel if funded in the protocol
** including Key derrivation!
** including Key derivation!
* details how a channel is updated in the protocol (moved to routing!)
* describes what needs to happen when a channel is force closed

@ -19,5 +19,68 @@ Relevant questions to answer:
- What is the "gossip query" system?
- Does a node need to keep up with all gossip updates? Does this change if they're a routing node or mobile client?
* Protocol Extensions via Feature Bits and TLV:
- How can the channel graph be upgraded using feature bits and TLV fields?
- How does a receiver signal that they can accept MPP/AMP payments?
* How can the channel graph be upgraded using feature bits and TLV fields?
* How does a receiver signal that they can accept MPP/AMP payments?
### What are "Zombie" channels and why do they matter?
A zombie channel can be defined as a channel in which your channel partner has been inactive for so long, that you do not expect them come back online in the future.
This could be because your channel partner has lost access to their or has permanently shut down that node.
As such, a zombie channel is technically still an open channel, but cannot be used to route payments.
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 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
Identifying zombie channels is a challenge as it is not always clear if the channel partner is permanently offline.
A partner node that is offline for a long period may eventually return online in the future.
However, once a zombie channel is identified, it is recommended to close them and a force close is generally required.
### Gossip Announcements
#### How does a peer announce a new channel to the network?
Let's assume that Alice and Bob have just opened a channel together.
How do they let the rest of the network know, so that the channel can be used for forwarding payments?
Well firstly, they don't need to.
Alice and Bob can choose not to announce the channel and simply use it to transfer bitcoin between each other.
In this case, they won't earn any fees for forwarding payments.
However, assuming they do want the channel to be public, they will have marked the channel as public when they initially agreed to open it.
First, they'll have to wait until the funding transaction is confirmed (usually six confirmations).
Once it's confirmed, Alice's and Bob's nodes will now use the `channel_announcement` message to let the rest of the network know the good news.
This announcement message contains some important information:
* *Channel ID*: a short description of the channel that tells users which outputs in which transaction in which Bitcoin block were used to fund the channel
* *Signatures from Alice and Bob*: Remember that the channel funds are locked in a 2-of-2 multisignature address, for which Alice and Bob each hold one of the two keys.
Alice and Bob will each sign from their key, proving that their nodes control the funds in the channel.
They will then send this `channel_announcement` message to each of their peers.
Note that while the `channel_announcement` message makes their peers aware of their channel, their peers won't yet be able to use the channel for forwarding payments.
First, Alice or Bob will have to communicate other information, such as their fee policy, which we will discuss below.
But first, how do their peers verify that the channel announcement is legitimate?
#### Verifying the channel
Let's assume Chan receives this announcement from Bob.
How does he know that this is a real channel, and why should he even bother to check it?
Well, verifying a channel is pretty important.
If Chan tries to forward any payments through a channel that doesn't exist, his payments are going to fail.
Even if the channel does exist, Chan 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 Chan will definitely want to verify before he updates his channel graph.
Firstly, Chan 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, Chan 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 Chan 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.

@ -0,0 +1,212 @@
[[channel_operation]]
== Channel Operation and Payment Forwarding
=== Forwarding payments with HTLCs
In previous chapters we have seen that payment channels are maintained by two nodes by keeping two disjoint sequences of commitment transactions.
The pair of latest commitment transactions in both sequences encodes the current, agreed upon balance in the channel.
We have stated that two channel partners negotiate a new commitment transaction in order to change the balance and conduct a payment from one to another.
We are finally at the point to explain the communications protocol via Lightning messages and the usage of HTLCs that is executed within a payment channel to change the balance.
The same protocol will be executed along a path of channels if the network of channels is being utilized to make a payment between two participants without requiring them to have a dedicated payment channel connecting them directly.
Let us start with the payment channel with a capacity of 100 mBTC between Alice and Bob.
At its current state Alice and Bob have agreed that 20 mBTC belong to Bob and 80 mBTC belong to Alice.
As Alice bought a coffee flatrate for the week she has to pay 15 mBTC to Bob and wants to use this channel.
Just creating a new pair of commitment transactions and signing them is not so easy as the old ones have to be invalidated by sharing the revocation secret.
This process should be executed in a way that it is atomic meaning the nodes will either be able to negotiate a new state without giving the other side the chance to play tricks or it should fail.
[[routing-setup-htlc-0]]
.Let us look at the initial pair of most recent commitment transactions for Alice and Bob:
image:images/routing-setup-htlc-0.png[]
Alice sends the `update_add_HTLC` Lightning message to Bob.
The message type is 128 and has the following data fields:
* [`channel_id`:`channel_id`]
* [`u64`:`id`]
* [`u64`:`amount_msat`]
* [`sha256`:`payment_hash`]
* [`u32`:`cltv_expiry`]
* [`1366*byte`:`onion_routing_packet`]
As Bob and Alice might have more than one channel thus the `channel_id` is included to the message.
The `id` counter counts starts with 0 for the first HTLC that Alice offers to Bob and is increased by 1 with every subsequent offer.
The id of the HTLC is used to compute the derivation path of the bitcoin key that is used for the output of this particular HTLC.
In this way addresses change with every payment and cannot be monitored by a third party.
Next the amount that Alice wants to send to Bob is entered to the `amount_msat` field.
As the name suggests the amount is depicted in millisatoshi even those cannot be enforced within the commitment transaction and within bitcoin.
Still Lightning nodes keep track of subsatoshi amounts to avoid rounding issues.
As in the offline example Alice includes the `payment_hash` in the next data field.
This was told to Alice by Bob in case she wants to just send money to him.
If Alice was to send Money to Dina the payment hash would have been given to Alice by Dina.
We discussed the potential of time lock or deadline of the contract.
This is encoded in the `cltv_expiry`.
cltv stands for OP_CHECKTIMELOCKVERIFY and is the OP_CODE that will be used in the HTLC output and serve as the deadline in which the contract is valid.
Finally in the last data field there are 1336 Bytes of data included which is an `onion routing packet`.
The format of this packet will be discussed in the last section of this chapter.
For now it is important to note that it includes encrypted routing hints and information of the payment path that can only be partially decrypted by the recipient of the onion routing packet to extract information to whom to forward the payment or to learn that one as the final recipient.
In any case the onion routing packet is always of the same size preventing the possibility to guess the position of an intermediary node within a path.
In our particular case Bob will be able to decrypt the first couple bytes of the onion routing packet and learn that the payment is not to be forwarded but intended to be for him.
The received information is enough for Bob to create a new commitment transaction.
This commitment transaction now has not only 2 outputs encoding the balance between Alice and Bob but a third output which encodes the hashed time locked contract.
[[routing-setup-htlc-1]]
.Lets look at the newly created commitment transaction for Bob:
image:images/routing-setup-htlc-1.png[]
We can see that Bob Assumes that Alice will agree to lock 15 mBTC of her previous balance and assign it to the HTLC output.
Creating this HTLC output can be compared to giving Alice golden coins to the escrow service.
In our situation the bitcoin network can enforce the HTLC as Bob and Alice have agreed upon.
Bob's Balance has not changed yet.
In Bitcoin outputs are mainly described by scripts.
The received HTLC in Bob's commitment transaction will use the following bitcoin script to define the output:
# To remote node with revocation key
OP_DUP OP_HASH160 <RIPEMD160(SHA256(revocationpubkey))> OP_EQUAL
OP_IF
OP_CHECKSIG
OP_ELSE
<remote_HTLCpubkey> OP_SWAP OP_SIZE 32 OP_EQUAL
OP_IF
# To local node via HTLC-success transaction.
OP_HASH160 <RIPEMD160(payment_hash)> OP_EQUALVERIFY
2 OP_SWAP <local_HTLCpubkey> 2 OP_CHECKMULTISIG
OP_ELSE
# To remote node after timeout.
OP_DROP <cltv_expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
OP_CHECKSIG
OP_ENDIF
OP_ENDIF
We can see that there are basically three conditions to claim the output.
1. Directly if a revocation key is known. This would happen if at a later state Bob fraudulently publishes this particular commitment transaction. As a newer state could only be agreed upon if Alice has learnt Bob's half of the revocation secret she could directly claim the funds and keep them even if Bob was later able to provide a proof of payment. This is mainly described in this line `OP_DUP OP_HASH160 <RIPEMD160(SHA256(revocationpubkey))> OP_EQUAL` and can be down by using `<revocation_sig> <revocationpubkey> as a witness script.
2. If Bob has successfully delivered the payment and learnt the preimage he can spend the HTLC output with the help of the preimage and his `local_HTLC_secret`. This is to make sure that only Bob can spend this output if the commitment transaction hits the chain and not any other third party who might know the preimage because they had been included in the routing process. Claiming this output requires an HTLC-success transaction which we describe later.
3. Finally Alice can use her `remote_HTLC_secret` to spend the HTLC output after the timeout of `cltv_expiry` was passed by using the following witness script `<remoteHTLCsig> 0`
As the commitment transaction spends the 2 out of 2 multisig funding transaction Bob needs two signatures after he constructed this commitment transaction.
He can obviously compute his own signature but he needs also the signature from Alice.
As Alice initiated the payment and wanted the HTLC to be set up she will be reluctant to provide a signature.
[[routing-setup-htlc-2]]
.Alice sends the `commitment_signed` Lightning Message to Bob:
image:images/routing-setup-htlc-2.png[]
We can see in the diagram that Bob now has two valid commitment transactions.
Let us have a quick look at the `commitment_signed` Lightning message which has the type 132.
It has 4 data fields:
* [`channel_id`:`channel_id`]
* [`signature`:`signature`]
* [`u16`:`num_HTLCs`]
* [`num_HTLCs*signature`:`HTLC_signature`]
First it again states which for which of the channels between Alice and Bob this message is intended.
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 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.
He will just not have received the funds from Alice.
This is important!
Despite the fact that Bob has a new commitment transaction with two valid signatures and an HTLC output inside he cannot consider his HTLC as being set up successfully.
He first needs to have Alice invalidate her old state.
That is why - in the case that he is not the final recipient of the funds - he should not forward the HTLC yet by setting up a new HTLC on the next channel with Chan.
Alice will not invalidate her commitment transaction yet as she has to first get her new commitment transaction and she wants Bob to invalidate his old commitment transaction which he can safely do at this time.
[[routing-setup-htlc-3]]
.Bob sends a `revoke_and_ack` Lighting message to Alice:
image:images/routing-setup-htlc-3.png[]
The `revoke_and_ack` Lightning message contains three data fields.
* [`channel_id`:`channel_id`]
* [`32*byte`:`per_commitment_secret`]
* [`point`:`next_per_commitment_point`]
While it is really simple and straight forward it is very crucial.
Bob shares the the `per_commitment_secret` of the old commitment transaction which serves as the revocation key and would allow Alice in future to penalize Bob if he publishes the old commitment transaction without the HTLC output.
As in a future Alice and Bob might want to negotiate additional commitment transactions he already shares back the `next_per_commitment_point` that he will use in his next commitment transaction.
Alice checks that the `per_commitment_secret` produces the last `per_commitment_point` and constructs her new commitment transaction with the HTLC output.
Alice's version of the HTLC output is slightly different to the one that Bob had.
The reason is the asymmetries of the penalty based payment channel construction protocol.
Alice is offering in her commitment transaction an HTLC to the `remote` partner of the channel while Bob as accepting and offered HTLC to himself the `local` partner of the channel.
Thus the Bitcoin script is adapted slightly.
It is a very good exercise to go through both scripts and see where they differ.
You could also try to use Bob's HTLC output script to come up with Alice's and vice versa and check your result with the following script.
# To remote node with revocation key
OP_DUP OP_HASH160 <RIPEMD160(SHA256(revocationpubkey))> OP_EQUAL
OP_IF
OP_CHECKSIG
OP_ELSE
<remote_HTLCpubkey> OP_SWAP OP_SIZE 32 OP_EQUAL
OP_NOTIF
# To local node via HTLC-timeout transaction (timelocked).
OP_DROP 2 OP_SWAP <local_HTLCpubkey> 2 OP_CHECKMULTISIG
OP_ELSE
# To remote node with preimage.
OP_HASH160 <RIPEMD160(payment_hash)> OP_EQUALVERIFY
OP_CHECKSIG
OP_ENDIF
OP_ENDIF
Bob can redeem the HTLC with `<remoteHTLCsig> <payment_preimage>` as the witness script and in case the commitment transaction is revoked but published by Alice, Bob can trigger the penality by spending this output immediately with the following witness script `<revocation_sig> <revocationpubkey>`.
[[routing-setup-htlc-4]]
.Bob knows how Alice's commitment transaction will look like and sends over the necessary signatures.
image:images/routing-setup-htlc-4.png[]
This process is completely symmetrical to the one where Alice sent her signatures for Bob's new commitment transaction.
Now Alice is the one having two valid commitment transactions.
Technically she can still abort the payment by publishing her old commitment transaction to the bitcoin network.
No one would lose anything as Bob knows that the contract is still being set up and not fully set up yet.
This is a little bit different than how the situation would look like in a real world scenario.
Recall Alice and Bob both have set up a new commitment transaction and have exchanged signatures.
In the real world one would argue that this contract is now valid.
[[routing-setup-htlc-5]]
.However Bob knows that Alice has to invalidate her previous commitment transaction which she does
image:images/routing-setup-htlc-5.png[]
Now Bob and Alice both have a new commitment transaction with and additional HTLC output and we have achieved a major step towards updating a payment channel.
The new Balance of Alice and Bob does not reflect yet that Alice has successfully send 15 mBTC to Bob.
However the hashed time locked contracts are now set up in a way that secure settlement in exchange for the proof of payment will be possible.
This yields another round of communication with Lightning messages and setting up additional commitment transactions which in case of good cooperation remove the outstanding HTLCs.
Interestingly enough the `commitment_signed` and `revoke_and_ack` mechanism that we described to add an HTLC can be reused to update the commitment transaction.
If Bob was the recipient of the 15 mBTC and knows the preimage to the payment hash Bob can settle the HTLCs by sending and `update_fulfill_htlc` Lightning message to Alice.
This message has the type 130 and only 3 data fields:
* [`channel_id`:`channel_id`]
* [`u64`:`id`]
* [`32*byte`:`payment_preimage`]
As other messages Bob uses the `channel_id` field to indicates for which channel he returns the preimage.
The htlc that is being removed is identified by the same `id` that was used to set up the HTLC in the commitment transaction initially.
You might argue that Alice would not need to know the id of the HTLC for which Bob releases the preimage as the preimage and payment hash could be unique.
However with this design the protocol supports that a payment channel has several htlcs with the same preimage but only settles one.
One could argue that this does not make too much sense and it is good to be critical but this is how the protocol is designed and what it supports.
Finally in the last field Bob provides the `payment_preimage` which Alice can check hashes to the payment hash.
[WARNING]
====
When designing, implementing or studying a protocol one should ask: Is it safe to this or that in this moment of the protocol and can this be abused. We discussed for example the messages that where necessary for an HTLC to become valid. We pointed out that Bob should not see the received HTLC as valid even though he already has a new commitment transaction with signatures and invalidated his old commitment transaction before Alice also revoked her old commitment transaction. We also saw that no one is able to mess with the protocol of setting up a commitment transaction as in the worst case the protocol could be aborted and any dispute could be resolved by the Bitcoin Network. In the same way we should ask ourselves is it safe for Bob to just send out and release the preimage even though neither he nor Alice have created the new pair of commitment transactions in which the HTLCs are removed. It is important to take a short break and ask yourself if Bob will in any case be able to claim the funds from the HTLC if the preimage is correct?
====
It is safe for Bob to tell Alice the preimage.
Imagine Alice decides that she would not want to pay Bob anymore and does not respond anymore to create a new pair of commitment transactions with the removed HTLC and the Balance on Bob's end.
In that case Bob could just force close the channel and publish his latest version of the commitment transaction.
As the time lock of the HTLC is not over yet with an onchain success transaction Bob would be able to claim and settle his 15 mBTC as he is the only person who is able to spend the HTLC output in the commitment transaction.
The other way around meaning Bob and Alice would negotiate a new commitment transaction with the removed HTLC would never be save for Alice.
If the signatures for the new commitment transaction are exchanged Bob has received the money and could decide not to release the preimage.
[NOTE]
====
Isn't it remarkable that even though the process of exchanging funds for an preimage seems to be happening concurrently at the same moment in time in reality it is actually happening one step after another but in the right order.
====

@ -3,7 +3,7 @@ FROM ubuntu:20.04 AS bitcoind-base
RUN apt update && apt install -yqq \
curl gosu jq bash-completion
ENV BITCOIND_VERSION 0.20.0
ENV BITCOIND_VERSION 0.21.0
# Install binaries for Bitcoin Core
ADD https://bitcoincore.org/bin/bitcoin-core-${BITCOIND_VERSION}/bitcoin-${BITCOIND_VERSION}-x86_64-linux-gnu.tar.gz /usr/local
RUN cd /usr/local/ \

@ -15,6 +15,7 @@ echo "Importing demo private key"
echo "Bitcoin address: " ${address}
echo "Private key: " ${privkey}
echo "================================================"
bitcoin-cli -datadir=/bitcoind createwallet regtest
bitcoin-cli -datadir=/bitcoind importprivkey $privkey
# Executing CMD

@ -5,9 +5,10 @@ RUN apt update && apt install -yqq \
software-properties-common
# c-lightning
ENV C_LIGHTNING_VER 0.9.2~0~ubuntu18.04.1
RUN add-apt-repository -u ppa:lightningnetwork/ppa
RUN apt-get install -yqq \
lightningd
lightningd=${C_LIGHTNING_VER}
ADD https://raw.githubusercontent.com/ElementsProject/lightning/master/contrib/lightning-cli.bash-completion /usr/share/bash-completion/completions/lightning-cli

@ -0,0 +1,8 @@
#!/bin/bash
# a small script to help sanity check the versions of the different node implementations
dockerfiles=$(find . -name 'Dockerfile')
# print location of dockerfiles
echo $dockerfiles
# print variables
awk '/ENV/ && /VER|COMMIT/' $dockerfiles

@ -14,6 +14,7 @@ services:
- "18443"
- "12005"
- "12006"
restart: always
Alice:
container_name: Alice
@ -24,6 +25,7 @@ services:
- lnnet
expose:
- "9735"
restart: always
Bob:
container_name: Bob
@ -34,9 +36,10 @@ services:
- lnnet
expose:
- "9735"
restart: always
Wei:
container_name: Wei
Chan:
container_name: Chan
build:
context: eclair
image: lnbook/eclair:latest
@ -44,9 +47,10 @@ services:
- lnnet
expose:
- "9735"
restart: always
Gloria:
container_name: Gloria
Dina:
container_name: Dina
build:
context: lnd
image: lnbook/lnd:latest
@ -54,3 +58,4 @@ services:
- lnnet
expose:
- "9735"
restart: always

@ -9,8 +9,8 @@ RUN apt update && apt install -yqq \
COPY --from=lnbook/bitcoind /usr/local/ /usr/local/
# Install eclair
ENV ECLAIR_VER 0.4
ENV ECLAIR_COMMIT 69c538e
ENV ECLAIR_VER 0.4.2
ENV ECLAIR_COMMIT 52444b0
WORKDIR /usr/src
RUN curl -sLO https://github.com/ACINQ/eclair/releases/download/v${ECLAIR_VER}/eclair-node-${ECLAIR_VER}-${ECLAIR_COMMIT}-bin.zip \
&& unzip eclair-node-${ECLAIR_VER}-${ECLAIR_COMMIT}-bin.zip \

@ -23,6 +23,11 @@ eclair {
zmqblock = "tcp://bitcoind:12005"
zmqtx = "tcp://bitcoind:12006"
}
on-chain-fees.max-feerate-mismatch = 100
on-chain-fees {
feerate-tolerance {
ratio-low = 0.000001
ratio-high = 1000000
}
}
}

@ -2,4 +2,5 @@
set -Eeuo pipefail
# Show LND log from beginning and follow
touch /eclair/eclair.log
tail -n +1 -f /eclair/eclair.log || true

@ -4,8 +4,10 @@ ENV GOPATH /go
WORKDIR $GOPATH/src
# LND
ENV LND_VER v0.11.1-beta
RUN go get -d github.com/lightningnetwork/lnd
WORKDIR $GOPATH/src/github.com/lightningnetwork/lnd
RUN git checkout tags/${LND_VER}
RUN make && make install
FROM ubuntu:20.04 AS lnd-run

@ -1,53 +1,37 @@
#!/bin/bash
echo Getting node IDs
alice_address=$(docker-compose exec -T Alice bash -c "lncli -n regtest getinfo | jq .identity_pubkey")
bob_address=$(docker-compose exec -T Bob bash -c "lightning-cli getinfo | jq .id")
wei_address=$(docker-compose exec -T Wei bash -c "eclair-cli -s -j -p eclair getinfo| jq .nodeId")
gloria_address=$(docker-compose exec -T Gloria bash -c "lncli -n regtest getinfo | jq .identity_pubkey")
# The jq command returns JSON strings enclosed in double-quote characters
# These will confuse the shell later, because double-quotes have special
# meaning in a bash script.
# We remove the double-quote character by using the shell string manipulation
# expression: // removes the " character. Even here, we have to escape the "
# character with a backslash because otherwise bash will interpret it as a
# string closure.
# A bit messy, but it works!
alice_address=${alice_address//\"}
bob_address=${bob_address//\"}
wei_address=${wei_address//\"}
gloria_address=${gloria_address//\"}
alice_address=$(docker-compose exec -T Alice bash -c "lncli -n regtest getinfo | jq -r .identity_pubkey")
bob_address=$(docker-compose exec -T Bob bash -c "lightning-cli getinfo | jq -r .id")
chan_address=$(docker-compose exec -T Chan bash -c "eclair-cli -s -j -p eclair getinfo| jq -r .nodeId")
dina_address=$(docker-compose exec -T Dina bash -c "lncli -n regtest getinfo | jq -r .identity_pubkey")
# Let's tell everyone what we found!
echo Alice: ${alice_address}
echo Bob: ${bob_address}
echo Wei: ${wei_address}
echo Gloria: ${gloria_address}
echo Alice: ${alice_address}
echo Bob: ${bob_address}
echo Chan: ${chan_address}
echo Dina: ${dina_address}
echo Setting up channels...
echo Alice to Bob
docker-compose exec -T Alice lncli -n regtest connect ${bob_address}@Bob
docker-compose exec -T Alice lncli -n regtest openchannel ${bob_address} 1000000
echo Bob to Wei
docker-compose exec -T Bob lightning-cli connect ${wei_address}@Wei
docker-compose exec -T Bob lightning-cli fundchannel ${wei_address} 1000000
echo Bob to Chan
docker-compose exec -T Bob lightning-cli connect ${chan_address}@Chan
docker-compose exec -T Bob lightning-cli fundchannel ${chan_address} 1000000
echo Wei to Gloria
docker-compose exec -T Wei eclair-cli -p eclair connect --uri=${gloria_address}@Gloria
docker-compose exec -T Wei eclair-cli -p eclair open --nodeId=${gloria_address} --fundingSatoshis=1000000
echo Chan to Dina
docker-compose exec -T Chan eclair-cli -p eclair connect --uri=${dina_address}@Dina
docker-compose exec -T Chan eclair-cli -p eclair open --nodeId=${dina_address} --fundingSatoshis=1000000
echo Get 10k sats invoice from Gloria
gloria_invoice=$(docker-compose exec -T Gloria bash -c "lncli -n regtest addinvoice 10000 | jq .payment_request")
echo Get 10k sats invoice from Dina
dina_invoice=$(docker-compose exec -T Dina bash -c "lncli -n regtest addinvoice 10000 | jq -r .payment_request")
# Remove quotes
gloria_invoice=${gloria_invoice//\"}
echo Gloria invoice ${gloria_invoice}
echo Dina invoice ${dina_invoice}
echo Wait for channel establishment - 60 seconds for 6 blocks
sleep 60
echo Alice pays Gloria 10k sats, routed around the network
docker-compose exec -T Alice lncli -n regtest payinvoice --json --inflight_updates -f ${gloria_invoice}
echo Alice pays Dina 10k sats, routed around the network
docker-compose exec -T Alice lncli -n regtest payinvoice --json --inflight_updates -f ${dina_invoice}

@ -0,0 +1,74 @@
=== Trust, Fairness and Enforcement
When people have competing interests, how can they establish enough trust to engage in some cooperative or transactional behavior? The answer to this question lies at the core of several scientific and humanistic disciplines, such as economics, sociology, behavioral psychology, and mathematics. Some of those disciplines give us "soft" answers, that depend on concepts such as reputation, fairness, morality, even religion. Other disciplines give us concrete answers that depend only on the assumption that the participants in these interactions will act rationally.
In broad terms there are a handful of ways to ensure fair outcomes in interactions between individuals who may have competing interests:
* Require trust - you only interact with people who you already trust, due to prior interactions, reputation, or familial relationships. This works well enough at small scale, especially within families and small groups, that it is the most common basis for cooperative behavior. Unfortunately, it doesn't scale and it suffers from tribalist (in-group) bias.
* Rule of law - establish rules for interactions that are enforced by an institution. This scales better, but it cannot scale globally due to differences in customs and traditions, as well as the inability to scale the institutions of enforcement. Nasty side-effect: the institutions become more and more powerful as they get bigger and that leads to corruption.
* Trusted third parties - put an intermediary in every interaction to enforce fairness. Combined with the "rule of law" to provide oversight of intermediaries, this scales better, but suffers from the same imbalance of power: the intermediaries get very powerful and attract corruption. Concentration of power leads to systemic risk and systemic failure ("Too big to fail").
* Game theoretical fairness protocols - this last category emerges from the combination of the internet and cryptography and is the subject of this section. Let's see how it works and what its advantages and disadvantages are.
==== Trusted protocols without intermediaries
Cryptographic systems like Bitcoin and the Lightning Network are systems that allow you to transact with people (and computers) that you don't trust. This is often referred to as "trustless" operation, even though it is not actually trustless. You have to trust in the software that you run and you have to trust that the protocol implemented by that software will result in fair outcomes.
The big distinction between a cryptographic system like this and a traditional financial system, is that in traditional finance you have a _trusted third party_, for example a bank, to ensure that outcomes are fair. A significant problem with such systems is that they give too much power to the third party and they are also vulnerable to a _single point of failure_. If the trusted third party itself violates trust or attempts to cheat, the basis of trust breaks.
As you study cryptographic systems, you will notice a certain pattern: instead of relying on a trusted third party, these systems attempt to prevent unfair outcomes by using a system of incentives and disincentives. In cryptographic systems you place trust in the _protocol_, which is effectively a system with a set of rules that, if properly designed, will correctly apply the desired incentives and disincentives. The advantage of this approach is two fold. Not only do you avoid trusting a third party, you also reduce the need to enforce fair outcomes. So long as the participants follow the agreed protocol and stay within the system, the incentive mechanism in that protocol achieves fair outcomes without enforcement.
The use of incentives and disincentives to achieve fair outcomes is one aspect of a branch of mathematics called _game theory_, which studies "models of strategic interaction among rational decision makers" footnote:[Wikipedia "Game Theory": https://en.wikipedia.org/wiki/Game_theory]. Cryptographic systems that control financial interactions between participants, such as Bitcoin and the Lightning Network rely heavily on game theory to prevent participants from cheating and allow participants who don't trust each other to achieve fair outcomes.
While game theory and its use in cryptographic systems may appear confounding and unfamiliar at first, chances are you're already familiar with these systems in your everyday life, you just don't recognize them yet. Below we'll use a simple example from childhood to help us identify the basic pattern. Once you understand the basic pattern you will see it everywhere in the blockchain space and you will come to recognize it quickly and intuitively.
In this book, we call this pattern a _Fairness Protocol_ defined as a process that uses a system of incentives and/or disincentives to ensure fair outcomes for participants who don't trust each other. Enforcement of a fairness protocol is only necessary to ensure that the participants can't escape the incentives or disincentives.
==== A fairness protocol in action
Let's look at an example of a fairness protocol, which may be familiar to any reader, perhaps as a memory from their childhood.
Imagine a family lunch, with a parent and two children. The parent has prepared a bowl of fried potatoes ("french fries" or "chips" depending on which English dialect you use). The two siblings must share the plate of chips. The parent must ensure a fair distribution of chips to each child, otherwise the parent will have to hear constant complaining (maybe all day) and there's always a possibility of the unfair situation escalating to violence. What is a parent to do?
[NOTE]
====
Any similarity between the scenario above and Andreas' childhood experiences with his two cousins is entirely coincidental and should not be mentioned again. The battles of the french fries created enough drama and should be left in the past.
====
There are a few different ways that fairness can be achieved in this strategic interaction between two siblings that do not trust each other and have competing interests. The naive but commonly used method is for the parent to use their authority as a trusted third party: they split the bowl of chips into two servings. This is similar to traditional finance, where a bank, accountant or lawyer acts as a trusted third party to prevent any cheating between two parties who want to transact.
The problem with this scenario is that this puts a lot of power in the hands of the trusted third party. The parent is accused of playing favorites and not sharing the chips equally. The siblings may fight over the chips, dragging the parent into their fight. Eventually the parent threatens to never again cook french fries if it always results in fights. It is an empty threat, and so the cycle repeats daily.
But a much better solution exists: the siblings are taught to play a game called "split and choose". At each lunch one sibling splits the bowl of chips into two servings and the *other* sibling gets to choose which serving they want. Almost immediately, the siblings figure out the dynamic of this game. If the one splitting makes a mistake or tries to cheat, the other sibling can "punish" them by choosing the bigger bowl. It is in the best interest of both siblings, but especially the one splitting the bowl, to play fair. Only the cheater loses in this scenario. The parent doesn't even have to use their authority or enforce fairness. All the parent has to do is _enforce the protocol_; as long as the siblings cannot escape their assigned roles of "splitter" and "chooser", the protocol itself ensures a fair outcome without the need for any intervention. The parent can't play favorites or distort the outcome.
==== Security primitives as building blocks
In order for a fairness protocol like this to work, there need to be certain guarantees, or _security primitives_ that can be combined to ensure enforcement. The first security primitive is _strict time ordering/sequencing_: the "splitting" action must happen before the "choosing" action. It's not immediately obvious, but unless you can guarantee that action A happens before action B, then the protocol falls apart. The second security primitive is _commitment with non-repudiation_. Each sibling must commit to their choice of role: either splitter or chooser. Also, once the splitting has been completed, the splitter is committed to the split they created - they cannot repudiate that choice and go try again.
Cryptographic systems offer a number of security primitives that can be combined in different ways to construct a fairness protocol. In addition to sequencing and commitment, we can also use many other tools:
- Hash functions to fingerprint data, as a form of commitment, or as the basis for a digital signature.
- Digital signatures for authentication, non-repudiation, and proof of ownership of a secret.
- Encryption/decryption to restrict access to information to authorized participants only.
This is only a small list of a whole "menagerie" of security and cryptographic primitives that are in use. More basic primitives and combinations are invented all the time.
In our real-life example, we saw one form of fairness protocol called "split and choose". This is just one of a myriad different fairness protocols that can be built by combining the building blocks of security primitives in different ways. But the basic pattern is always the same: two or more participants interact without trusting each other, by engaging in a series of steps that are part of an agreed protocol. The protocol's steps arrange incentives and disincentives to ensure that if the participants are rational, cheating is counter-productive and fairness is the automatic outcome. Enforcement is not necessary to get fair outcomes - it is only necessary to keep the participants from breaking out of the agreed protocol.
Now that you understand this basic pattern, you will start seeing it everywhere in Bitcoin, the Lightning Network and many other systems. Let's look at some specific examples, next.
==== Example of the fairness protocol
The most prominent example of a "fairness protocol", is Bitcoin's consensus algorithm _Proof of Work_ (PoW). In Bitcoin, miners compete to verify transactions and aggregate them in blocks. To ensure that the miners do not cheat, without entrusting them with authority, Bitcoin uses a system of incentives and disincentives. Miners have to use a lot of electricity doing "work", that is embedded as a "proof" inside every block. This is achieved because of a property of hash functions where the output value is randomly distributed across the entire range of possible outputs. If miners succeed in producing a valid block fast enough, they are rewarded by earning the block reward for that block. Forcing miners to use a lot of electricity before the network considers their blocks means that they have an incentive to correctly validate the transactions in the block. If they cheat or make any kind of mistake, their block is rejected and the electricity they used to "prove" it is wasted. No one needs to force miners to produce valid blocks, the reward and punishment incentivize them to do so. All the protocol needs to do is ensure that only valid blocks with proof of work are accepted.
The "fairness protocol" pattern can also be found in many different aspects of the Lightning Network:
* Those who fund channels make sure that they have a refund transaction signed before they publish the funding transaction.
* Whenever a channel is moved to a new state, the old state is "revoked" by ensuring that if anyone tries to broadcast it, they lose the entire balance and get punished.
* Those who forward payments know that if they commit funds forward, they can either get a refund or they get paid by the node preceding them.
Again and again, we see this pattern. Fair outcomes are not enforced by any authority. They emerge as the natural consequence of a protocol that rewards fairness and punishes cheating. A fairness protocol that harnesses self-interest by directing it towards fair outcomes.

@ -1,15 +1,17 @@
Chapter overview:
* presentation layer, applications, how payment details are exchanged
Relevant questions to answer:
* What is BOLT 11?
* What information does an invoice contain?
* How can invoices be extended to integrate new protocol features?
* What are some unique things that can be done with LN?
* recurring payments
* donation addrs
* keysend
* custom data
- recurring payments
- donation addrs
- keysend
- custom data
=== What information does an invoice contain?
@ -76,41 +78,51 @@ If we enter the above invoice into a invoice decoding tool, such as https://lnde
=== What are some unique things that can be done with LN?
**Micropayments**: The current financial system in most countries is divisible to a certain extent and not lower (E.g. $1 = 100c).
However it is usually not viable to send small amounts, e.g. $1 and less, due to transaction fees and other friction in the system.
**Micropayments**: The currencies in most countries are divisible to a certain extent and not lower (e.g. $1 = 100c).
However, it is usually not viable to send small amounts, e.g. $1 and less, due to transaction fees and other friction in the system.
Bitcoin has similar issues due to transaction fees, and fees are likely to increase in the long-term.
The Lightning Network can reasonably accommodate payments of the value of 1 satoshi i.e. one hundred millionth of a Bitcoin.
The Lightning Network can reasonably accommodate payments of the value of 1 satoshi, i.e. one hundred millionth of a Bitcoin.
Even at an obscenely high Bitcoin value of $1m per Bitcoin, this would still allow the transfer of 1 US cent worth of value.
As many Lightning implementations track values to the thousandth of a Satoshi (i.e. one milli-satoshi), payments could conceivably be even smaller than this.
This would allow for micropayment business models such as "pay-per-article", which are not viable in the current system.
This would allow for micropayment business models such as "pay-per-article" or "pay-per-minute", which are not viable in the current financial system.
**Anonymous Payments**: Bitcoin is pseudonymous at best and transactions are permanently stored on the public Bitcoin blockchain.
Hence there is always a risk that transactions can be linked back to users post-hoc.
Hence, there is always a risk that transactions can be linked back to users post-hoc.
Technologies like CoinJoin and Pay-to-EndPoint can assist in giving Bitcoin users a greater degree of anonymity but cannot completely solve this problem.
In contrast, users of the Lightning Network are not aware of other users' payments and, since channels can be private, they may not even be aware of other users' channels.
Users are only aware of other users' payments insofar as they assist in routing payments; in this case they are unaware of both the source and the destination of the payment.
As such, the Lightning Network has a strong use case for anonymous purchases.
This would be of particular benefit to online stores and exchanges that accept Bitcoin as malicious attackers can monitor their addresses on the Bitcoin network to try and determine how much bitcoin the businesses owns; something that is not possible on the Lightning Network
As such, the Lightning Network provides for strong use cases for anonymous purchases.
This would be of particular benefit to online stores and exchanges that accept Bitcoin as malicious attackers can monitor their addresses on the Bitcoin network to try and determine how much bitcoin the businesses owns
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.
**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 million pixel canvas.
What emerges is a constantly changing picture where anyone add, remove, or paint over by paying.
This example can be extended to many other kinds of collaborative games where users can pay to participate.
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.
What emerges is a constantly changing picture, where anyone can add, remove, or paint over pixels by paying.
This example can be extended to many other kinds of collaborative games, where users can pay to participate.
The Lightning Network can also be implemented directly into online games, such as MMORPGs, to facilitate in-game transactions.
As Lightning wallets and Lightning invoices can be built directly into the games themselves, this completely bypasses the need for the credit cards and the traditional financial system.
As Lightning wallets and Lightning invoices can be built directly into the games themselves, this completely bypasses the need for credit cards and the traditional financial system.
While all of this is technically possible on Bitcoin, confirmation times and fees make this unfeasible.
Transactions are confirmed on average every ten minutes, although it could potentially take even longer.
Bitcoin transactions are confirmed on average every ten minutes, although it could potentially take even longer.
This exposes the merchant to the risk of accepting unconfirmed transactions.
Lightning transactions, on the other hand, settle instantly and so are better from a user experience standpoint for.
Lightning transactions, on the other hand, settle instantly and so are better from a user experience standpoint.
**Earning "interest" on Bitcoin trustlessly**
While Bitcoin may increase or decrease in value in terms of fiat currencies, it is an asset that does not offer a return in and off itself simply by holding it.
The amount of Bitcoin one holds remains constant, and actually decreases as one moves it around due to transaction fees.
Those wishing to earn a return on their holdings in Bitcoin terms can do so by opening channels and routing payments in return for routing fees.
In this way, users can earn a return (i.e. "interest") by locking their Bitcoin into channels and offering liquidity to other users wishing to transact on the Lightning Network.
Users doing so will need to pay the fees to open and close channels, as well as the cost of maintaining any hardware to run a Lightning Node.
However, as channels can be left open indefinitely, they could earn a profit as long as there are sufficient users of the Lightning Network such that their routing fees are in excess of their channel fees and maintenance costs over the long term.
This is trustless as users do not need to loan or send anyone their Bitcoin; they only need to take the risks of operating a Lightning node and storing Bitcoin in a hot wallet.
Third-party services exist that provide interest on Bitcoin, but these services are in general not trustless.
Those wishing to earn a return on their Bitcoin holdings _trustlessly_ can do so by opening channels and routing payments in return for routing fees.
This way, users can earn a return (i.e. "interest") by locking their Bitcoin into channels and offering liquidity to other users wishing to transact on the Lightning Network.
Users doing so will need to pay the fees to open and close channels, as well as the cost of maintaining any hardware and network infrastructure to run a Lightning Node.
However, as channels can be left open indefinitely, they _could_ earn a profit as long as there are sufficient users of the Lightning Network such that their routing fees are in excess of their channel fees and maintenance costs over the long term.
This is trustless as users do not need to loan or send anyone their Bitcoin. Users only need to take on the efforts and risks of operating a Lightning node and storing Bitcoin in a hot wallet.
**Use Cases outside of Finance**
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.

@ -34,12 +34,7 @@ address::
A Bitcoin address looks like +1DSrfJdB2AnWaFNgSbv3MZC2m74996JafV+. It consists of a string of letters and numbers. It's really an encoded base58check version of a public key 160-bit hash. Just as you ask others to send an email to your email address, you would ask others to send you bitcoin to one of your Bitcoin addresses.
AMP::
Atomic Multipath Payments.
A method for payments where the sender can use more than one of their channels to forward a payment.
By default, a sender uses one channel to forward payment.
This can cause issues, for example, where a sender has an two channels with an outgoing capacity of 0.5 BTC but wishes to forward a payment of 0.8 BTC.
By default, this payment would fail without rebalancing.
With AMP, the sender can split the payment between these channels and either have the entire payment succeed or fail, with no partial payment possible.
Atomic Multipath Payments was an early suggestion for a multipart payment protocol which did not get implemented but introduced the idea of splitting a single payment into multiple parts and send them along potentially different paths.
Asymmetric Cryptographic System::
Asymmetric cryptography, or public-key cryptography, is a cryptographic system that uses pairs of keys: public keys which may be disseminated widely, and private keys which are known only to the owner.
@ -53,14 +48,14 @@ Autopilot::
Autopilots are not part of the Lightning Network Protocol.
balance::
The balance of a payment channel is encoded by the most recent commitment transaction.
The balance states the amount of bitcoin that belongs to each channel partner and the amount that are in flying HTLCs (HTLCs which are currently in the routing process and have not been settled yet).
The sum of the balance sheet equals the capacity.
The channel balance is only known by the channel partners.
If the channel balance is completely on one side of the channel, i.e. one channel partner has all of the bitcoin in the channel, this particular partner cannot receive any payments through this channel. This partner can, however, send payments and forward HTLCs.
The balance that a node has on its own side of the channel (and is thus able to spend) is called the outbound capacity.
The node's channel partner would refer to that balance as its inbound capacity, i.e. the amount that it is able to receive.
Nodes should aim to have balanced channels with similar inbound and outbound capacities.
The balance of a payment channel is the amount of bitcoin that belongs to each channel partner.
For example, Alice could open a channel with Bob for the value of 1 BTC.
The channel balance is then 1 BTC to Alice and 0 BTC to Bob.
As the users transact the channel balance will update.
For e.g. if Alice sends 0.2 BTC to Bob, then the balance is now 0.8 BTC to Alice and 0.2 to Bob.
When the channel is closed the bitcoin in the channel will be divided between the two channel partners according to the latest balance encoded in the commitment transaction.
In the Lightning Network the ability to send and receive payments is limited by channel balances.
See _capacity_.
bech32::
A checksummed base32 address format, at most 90 characters long, and capable of error correction. It is native to segregated witness (BIP173). Also referred to as "bc1" because of the current starting values of each address. Transactions made using bech32 are smaller in most cases, and therefore, may only require a lower fee.
@ -72,9 +67,10 @@ bitcoin, Bitcoin::
Depending on context, could refer to the name of the currency unit (the coin), the network or the underlying enabling protocol. Written as bitcoin with a lowercase "b" usually refers to the currency unit. Bitcoin with an uppercase "B" usually refers to the protocol. See https://www.bitcoin.org for general information. The source code can be found at https://github.com/bitcoin/bitcoin.
Bitcoin mining::
Bitcoin mining serves two purposes.
Firstly, Bitcoin transactions are validated and fixed in the sense that they cannot be double-spent.
Secondly, new bitcoin are being created within the coinbase of each block.
Bitcoin mining is the process of constructing a block from recent Bitcoin transactions and then solving a computational problem required as Proof of Work.
It is the process by which the shared bitcoin ledger (i.e. the bitcoin blockchain) is updated and by which new transactions are included in the ledger.
It is also the process by which new bitcoin is issued.
Every time a new block is created, the mining node will receive new bitcoin created within the coinbase transaction of that block.
block::
A grouping of transactions, marked with a timestamp, and a fingerprint of the previous block. The block header is hashed to produce a proof of work, thereby validating the transactions. Valid blocks are added to the main blockchain by network consensus.
@ -82,12 +78,12 @@ block::
blockchain::
The blockchain is an irreversible distributed database storing all Bitcoin transactions.
The irreversibility comes from the fact that each group of transactions, referred to as a block, is validated by solving a Proof of Work riddle and including the hash of the previous block.
Thus the data can only be changed by an entity providing more than 51% of the computational power of the Bitcoin network.
Thus, the data can only be changed by an entity providing more than 51% of the computational power of the Bitcoin network.
Blocks currently have a size limit of 1 MB.
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.
@ -186,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.
@ -195,7 +197,7 @@ funding transaction::
The funding transaction is used to open a payment channel.
From the perspective of the Bitcoin network, the process of opening a channel by creating a RSMC is started by creating the funding transaction and finished by broadcasting it to the Bitcoin network and have it included in the blockchain.
The value of the funding transaction is exactly the capacity of the payment channel.
The output of the funding transaction is a 2-out-of-2 multisignature script (multisig) where each channel partner controls one key.
The output of the funding transaction is a 2-of-2 multisignature script (multisig) where each channel partner controls one key.
It is supposed to be spent by the commitment transactions or by the closing transaction.
Due to its multisig nature, it can only be spent mutually.
It is part of the RSMC to ensure that either side of the channel can withdraw their funds without the necessity to trust the channel partner.
@ -279,10 +281,14 @@ Locktime::
millisatoshi::
The smallest unit of account on the Lightning Network. A millisatoshi is one hundred billionth of a single bitcoin. A millisatoshi is one thousandth of one Satoshi. Millisatoshis do not exist, nor can they be settled on the Bitcoin network.
mpp::
A multipart payment (which is often also refered to as multipath payment) is a method for payments where the sender can split the payment amount into multiple smaller parts and deliver them potentially along multiple potentially disjoint paths. As the MPP strategies do not require one to send the smaller splits along different paths we find the term multipart payment more accurate than multipath payment.
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.
@ -291,15 +297,18 @@ node::
See Lightning Network Node
network capacity::
Lightning network capacity is the value of bitcoin locked and circulated inside Lightning Network and is the sum of capacities of each channel.
It is a mesurement of the maximum value a user can transfer in Lightning Network because routing nodes will need to have sufficient balances. It also reflects the usage of Lightning Network to some extent, because the higher value is circulated inside Lightning Network the more likely that more people are using it.
Lightning network capacity is the total amount of bitcoin locked and circulated inside the Lightning Network.
It is the sum of capacities of each public channel.
It reflects the usage of the Lightning Network to some extent because we expect that people lock bitcoin into Lightning channels in order to spend it or forward other users' payments.
Hence the higher the amount of bitcoin locked in channels, the higher the expected usage of the Lightning Network.
Note that since only public channel capacity can be observed, the true network capacity is unknown.
See private channel.
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::
@ -312,7 +321,11 @@ onion routing::
https://en.wikipedia.org/w/index.php?title=Onion_routing&oldid=870849217
output::
Output, transaction output, or TxOut is an output in a transaction which contains two fields: a value field for transferring zero or more satoshis and a pubkey script for indicating what conditions must be fulfilled for those satoshis to be further spent.
The output of a Bitcoin transaction, also called an "Unspent Transaction Output" or "UTXO"
An output is essentially an amount of bitcoin that can be spent, as well as a script that defines what conditions need to be fulfilled for that bitcoin to be spent.
Every Bitcoin transaction consumes the outputs of the sender and creates new outputs that can be spent later by the receiver.
A typical bitcoin output will require the signature of the owner to be spent, but outputs can require the fulfillment of more complex scripts.
For example, a multisignature script requires that two or more users to sign before an ouput can be spent, which is a fundamental building block of the Lightning Network.
P2PKH::
P2PKH or Pay-to-PubKey-Hash is a type of transaction that pays a Bitcoin address that contain P2PKH scripts.
@ -337,25 +350,28 @@ payment::
The invoice includes a payment hash which is the hash of a secret preimage.
This payment hash is used by the Hashed Time Lock Contracts during the routing process.
payment channels::
A micropayment channel or payment channel is a class of techniques designed to allow users to make multiple Bitcoin transactions without committing all of the transactions to the Bitcoin blockchain. In a typical payment channel, only two transactions are added to the blockchain, but an unlimited or nearly unlimited number of payments can be made between the participants.
payment channel::
Payment channels are the core building blocks of the Lightning Network.
They can be used to send a predefined amount of bitcoin back and forth between two parties.
Sending bitcoin over a payment channel happens off chain, so only the funding transaction and either the commitment or closing transaction is stored in the blockchain.
There are currently three methods known to construct a fully duplex bidirectional payment channel.
Christian Decker proposed a method in his PhD thesis based on invalidation trees.
In the Lightning Network whitepaper, Joseph Poon and Tadge Dryja describe the Revocable Sequence Maturity Contract based method that is currently being implemented on the Lightning Network.
Recently Christian Decker et al. came up with the Eltoo mechanism which would require a Bitcoin softfork.
A payment channel is a financial relationship between two nodes on the Lightning Network, created using a multisignature Bitcoin transaction.
The channel partners can use the channel to send Bitcoin back and forth between each other without committing all of the transactions to the Bitcoin blockchain.
In a typical payment channel only two transactions, the funding transaction and the commitment transaction, are added to the blockchain.
The other transactions are not included in the blockchain and are said to occur "off-chain".
There are various methods of constructing a payment channel discussed further in the chapter on channel construction.
peer::
Two parties which form a payment channel are called peers.
In particular, they are connected via an encrypted, authenticated communication over a TCP Socket.
Penalty Transaction::
penalty transaction::
Look at the Breach Remedy Transaction.
private channel:
A channel not announced to the rest of the network.
Technically "private" is a misnomer as these channels can still be identified through routing hints and commitment transactions.
We suggest they are better described as "unannounced" channels.
With an unannounced channel, the channel partners can send and receive payments between each other as normal.
However the rest of the network will not be aware of it and so cannot typically use it to route payments.
As the number of and capacity of unanounced channels is unknown, the total public channel count and capacity only accounts for a portion of the total Lightning Network.
preimage::
In mathematics, given a function $f$ and a value $h$ the preimage of $h$ with respect to $f$ is the set of values $R = \{r_1,r_2,...\}$ such that $f(r_i) = h$ for all $\r_i \in R$.
In layman's terms, it is the set of values which is mapped to $h$ by the function $f$.
@ -364,8 +380,11 @@ preimage::
Cryptographers use the term preimage for an arbitrary element of $R$.
In particular, when using SHA-256 we should state that each element has an infinite amount of preimages.
Yet it is still believed to be computationally hard to find such a preimage.
proof of work::
A piece of data that requires significant computation to find. In Bitcoin, miners must find a numeric solution to the SHA256 algorithm that meets a network-wide target, the difficulty target.
A piece of data that requires significant computation to find.
In Bitcoin, miners must find a numeric solution to the SHA256 algorithm that meets a network-wide target, called the difficulty target.
See _bitcoin mining_
Relative Timelock::
Relative Timelock is a kind of timelock that allows an input to specify the earliest time it can be added to a block based on how long ago (which is relative) the output referred by that input was included in a block. Such a feature is jointly achieved by nSequence field and CheckSequenceVerify opcode, which are introduced by BIP68/112/113.
@ -479,7 +498,7 @@ transport layer::
The transport layer provides communication services between computers such as flow control, verification, and multiplexing (to allow multiple applications to work on a computer at the same time).
unspent transaction output (UTXO)::
UTXO is an unspent transaction output that can be spent as an input to a new transaction.
See _output_
upstream payment::
TBD.

@ -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.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 155 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 175 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

After

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 110 KiB

After

Width:  |  Height:  |  Size: 182 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 130 KiB

After

Width:  |  Height:  |  Size: 217 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 150 KiB

After

Width:  |  Height:  |  Size: 245 KiB

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 as 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:
@ -44,7 +44,7 @@ To make a local copy of the repository on your computer, run the git command as
[git-clone-lnbook]
----
$ git clone git@github.com:lnbook/lnbook.git
$ git clone https://github.com/lnbook/lnbook.git
----
You now have a complete copy of the book repository in a folder called +lnbook+. All subsequent examples will assume that you are running commands from that folder.
@ -59,12 +59,18 @@ Docker containers are often optimized to be small, i.e. occupy the minimum disk
You can find the latest container definitions and build configurations in the book's repository under the +code/docker+ folder. Each container is in a separate folder as can be seen below:
//// $ tree -F --charset=asciii code
[tree]
----
$ tree -F --charset=asciii code
----
[docker-dir-list]
----
code
`-- docker/
|-- Makefile
|-- bitcoind/
| |-- Dockerfile
| |-- bashrc
| |-- bitcoind/
| | |-- bitcoin.conf
@ -73,37 +79,35 @@ code
| | |-- demo_mnemonic.txt
| | `-- demo_privkey.txt
| |-- bitcoind-entrypoint.sh
| |-- Dockerfile
| `-- mine.sh*
|-- c-lightning/
| |-- Dockerfile
| |-- bashrc
| |-- c-lightning-entrypoint.sh
| |-- Dockerfile
| |-- fund-c-lightning.sh
| |-- lightningd/
| | `-- config
| |-- logtail.sh
| `-- wait-for-bitcoind.sh
|-- docker-compose.yml
|-- eclair/
| |-- bashrc
| |-- Dockerfile
| |-- bashrc
| |-- eclair/
| | `-- eclair.conf
| |-- eclair-entrypoint.sh
| |-- logtail.sh
| `-- wait-for-bitcoind.sh
|-- lnbook-app/
| |-- docker-compose.yml
| `-- setup-channels.sh
`-- lnd/
|-- bashrc
|-- Dockerfile
|-- fund-lnd.sh
|-- lnd/
| `-- lnd.conf
|-- lnd-entrypoint.sh
|-- logtail.sh
`-- wait-for-bitcoind.sh
|-- lnd/
| |-- Dockerfile
| |-- bashrc
| |-- fund-lnd.sh
| |-- lnd/
| | `-- lnd.conf
| |-- lnd-entrypoint.sh
| |-- logtail.sh
| `-- wait-for-bitcoind.sh
`-- setup-channels.sh
----
==== Installing Docker
@ -161,7 +165,7 @@ docker exec cname command
...where +cname+ is the name we gave the container in the +run+ command, and +command+ is an executable or script that we want to run inside the container.
*Stopping a container*
*Stopping and starting a container*
In most cases, if we are running a container in an _interactive_ as well as _terminal_ mode, i.e. with the +i+ and +t+ flags (combined as +-it+) set, the container can be stopped by simply pressing +CTRL-C+ or by exiting the shell with +exit+ or +CTRL-D+. If a container does not terminate, you can stop it from another terminal like this:
@ -169,11 +173,16 @@ In most cases, if we are running a container in an _interactive_ as well as _ter
docker stop cname
----
...where +cname+ is the name we gave the container when we ran it.
To resume an already existing container use the `start` command, like so:
----
docker start cname
----
*Deleting a container by name*
If you name a container instead of letting docker name it randomly, you cannot reuse that name until the container is deleted. Docker will return an error like this:
[source,bash]
----
docker: Error response from daemon: Conflict. The container name "/bitcoind" is already in use...
----
@ -208,6 +217,7 @@ The container for Bitcoin Core is +bitcoind+. It is configured to run Bitcoin Co
Let us start by building and running the +bitcoind+ container. First, we use the +docker build+ command to build it:
[source,bash]
----
$ cd code/docker
$ docker build -t lnbook/bitcoind bitcoind
@ -229,6 +239,7 @@ Successfully tagged lnbook/bitcoind:latest
Next, let's run the +bitcoind+ container and have it mine some blocks. We use the +docker run+ command, with the flags for _interactive (i)_ and _terminal (t)_, and the +name+ argument to give the running container a custom name:
[source,bash]
----
$ docker run -it --name bitcoind lnbook/bitcoind
Starting bitcoind...
@ -277,6 +288,7 @@ Running the interactive shell puts us "inside" the container. It logs in as user
Instead of running an interactive shell, we can also issue a single command that is executed inside the container. In the following example we run the +bitcoin-cli+ command to obtain information about the current blockchain state:
[source,bash]
----
$ docker exec bitcoind bitcoin-cli -datadir=/bitcoind getblockchaininfo
{
@ -295,12 +307,13 @@ As you can see, we need to tell +bitcoin-cli+ where the bitcoind data directory
All our docker containers have a command-line JSON encoder/decoder named +jq+ preinstalled. +jq+ helps us to process JSON-formatted data via the command-line or from inside scripts. You can send the JSON output of any command to +jq+ using the +|+ character. This character as well as this operation is called a "pipe". Let's apply a +pipe+ and +jq+ to the previous command as follows:
[source,bash]
----
$ docker exec bitcoind bash -c "bitcoin-cli -datadir=/bitcoind getblockchaininfo | jq .blocks"
189
----
+jq .blocks+ instructs the +jq+ JSON decoder to extract the field +blocks" from the +getblockchaininfo+ result. In our case, it extracts and prints the value of 189 which we could use in a subsequent command.
+jq .blocks+ instructs the +jq+ JSON decoder to extract the field +blocks+ from the +getblockchaininfo+ result. In our case, it extracts and prints the value of 189 which we could use in a subsequent command.
As you will see in the following sections, we can run several containers at the same time and then interact with them individually. We can issue commands to extract information such as the Lightning node public key or to take actions such as opening a Lightning channel to another node. The +docker run+ and +docker exec+ commands together with +jq+ for JSON decoding are all we need to build a working Lightning Network that mixes many different node implementations. This enables us to try out diverse experiments on our own computer.
@ -318,6 +331,7 @@ The c-lightning software distribution has a docker container, but it is designed
We start by building the c-lightning docker container from the book's files which you previously downloaded into a directory named +lnbook+. As before, we will use the +docker build+ command in the +code/docker+ sub-directory. We will tag the container image with the tag +lnbook/c-lightning+ like this:
[source,bash]
----
$ cd code/docker
$ docker build -t lnbook/c-lightning c-lightning
@ -369,6 +383,7 @@ $ docker run -it --network lnbook --name bitcoind lnbook/bitcoind
You should see bitcoind start up and start mining blocks every 10 seconds. Leave it running and open a new terminal window to start c-lightning. We use a similar +docker run+ command with the +network+ and +name+ arguments to start c-lightning as follows:
[source,bash]
----
$ docker run -it --network lnbook --name c-lightning lnbook/c-lightning
Waiting for bitcoind to start...
@ -387,6 +402,7 @@ The c-lightning container starts up and connects to the bitcoind container over
As we demonstrated with the bitcoind container, we can issue commands to our c-lightning container in another terminal in order to extract information, open channels etc. The command that allows us to issue command-line instructions to the c-lightning node is called +lightning-cli+. To get the node info use the following +docker exec+ command in another terminal window:
[source,bash]
----
$ docker exec c-lightning lightning-cli getinfo
{
@ -434,6 +450,7 @@ https://github.com/ElementsProject/lightning/blob/master/doc/INSTALL.md
The common first step is the installation of prerequisite libraries. We use the +apt+ package manager to install these:
[source,bash]
----
$ sudo apt-get update
@ -474,6 +491,7 @@ After a few minutes and a lot of on-screen activity, you will have installed all
Next, we will copy the latest version of c-lightning from the source code repository. To do this, we will use the +git clone+ command which clones a version-controlled copy onto your local machine thereby allowing you to keep it synchronized with subsequent changes without having to download the whole repository again:
[source,bash]
----
$ git clone https://github.com/ElementsProject/lightning.git
Cloning into 'lightning'...
@ -492,13 +510,14 @@ We now have a copy of c-lightning cloned into the +lightning+ subfolder, and we
==== Compiling the c-lightning source code
Next, we use a set of _build scripts_ that are commonly available in many open source projects. These _build scripts_ use the +configure+ and +make+ commandos which allow us to:
Next, we use a set of _build scripts_ that are commonly available in many open source projects. These _build scripts_ use the +configure+ and +make+ commands which allow us to:
* Select the build options and check necessary dependencies (+configure+).
* Build and install the executables and libraries (+make+).
Running the +configure+ with the +help+ option will show us all the available options:
[source,bash]
----
$ ./configure --help
Usage: ./configure [--reconfigure] [setting=value] [options]
@ -543,6 +562,7 @@ $
Next, we use the +make+ command to build the libraries, components, and executables of the c-lightning project. This part will take several minutes to complete and will use your computer's CPU and disk heavily. Expect some noise from the fans! Run +make+:
[source,bash]
----
$ make
@ -629,6 +649,7 @@ $ docker run -it --network lnbook --name bitcoind lnbook/bitcoind
Next, we start the LND container we just built. As done before we need to attach it to the +lnbook+ network and give it a name:
[source,bash]
----
$ docker run -it --network lnbook --name lnd lnbook/lnd
Waiting for bitcoind to start...
@ -648,6 +669,7 @@ The LND container starts up and connects to the bitcoind container over the dock
As we demonstrated previously, we can issue commands to our container in another terminal in order to extract information, open channels etc. The command that allows us to issue command-line instructions to the +lnd+ daemon is called +lncli+. Let's get the node info using the +docker exec+ command in another terminal window:
[source,bash]
----
$ docker exec lnd lncli -n regtest getinfo
{
@ -699,8 +721,8 @@ go version go1.13.4 linux/amd64
We have 1.13.4, so we're ready to... Go! Next we need to tell any programs where to find the Go code. This is accomplished by setting the environment variable +GOPATH+. Usually the Go code is located in a directory named +gocode+ directly in the user's home directory. With the following two commands we consistently set the +GOPATH+ and make sure your shell adds it to your executable +PATH+. Note that the user's home directory is referred to as +~+ in the shell.
----
export GOPATH=~/gocode
export PATH=$PATH:$GOPATH/bin
$ export GOPATH=~/gocode
$ export PATH=$PATH:$GOPATH/bin
----
To avoid having to set these environment variables every time you open a shell, you can add those two lines to the end of your bash shell configuration file +.bashrc+ in your home directory, using the editor of your choice.
@ -720,12 +742,13 @@ Once +go get+ finishes, you will have a sub-directory under +GOPATH+ that contai
LND uses the +make+ build system. To build the project, we change directory to LND's source code and then use +make+ like this:
----
cd $GOPATH/src/github.com/lightningnetwork/lnd
make && make install
$ cd $GOPATH/src/github.com/lightningnetwork/lnd
$ make && make install
----
After several minutes you will have two new commands +lnd+ and +lncli+ installed. Try them out and check their version to ensure they are installed:
[source,bash]
----
$ lnd --version
lnd version 0.10.99-beta commit=clock/v1.0.0-106-gc1ef5bb908606343d2636c8cd345169e064bdc91
@ -748,6 +771,7 @@ In the next few sections we will build a docker container to run Eclair, as we d
By now, you are almost an expert in the basic operations of docker! In this section we will repeat many of the previously seen commands to build the Eclair container. The container is located in +code/docker/eclair+. We start in a terminal, by switching the working directory to +code/docker+ and issuing the +docker build+ command:
[source,bash]
----
$ cd code/docker
$ docker build -t lnbook/eclair eclair
@ -804,6 +828,7 @@ The Eclair container starts up and connects to the bitcoind container over the d
As we demonstrated previously, we can issue commands to our container in another terminal in order to extract information, open channels etc. The command that allows us to issue command-line instructions to the +eclair+ daemon is called +eclair-cli+. The +eclair-cli+ command expects a password which we have set to "eclair" in this container. We pass the password +eclair+ to the +eclair-cli+ command via the +p+ flag. Using the +docker exec+ command in another terminal window we get the node info from Eclair:
[source,bash]
----
$ docker exec eclair eclair-cli -p eclair getinfo
{
@ -835,16 +860,17 @@ In this section we will build Eclair from scratch. Eclair is written in the Scal
https://github.com/ACINQ/eclair/blob/master/BUILD.md
The required Java compiler is part of OpenJDK 11. We will also need a buid framework called Maven, version 3.6.0 or above.
The required Java compiler is part of OpenJDK 11. We will also need a build framework called Maven, version 3.6.0 or above.
On a Debian/Ubuntu Linux system we can use the +apt+ command to install both OpenJDK11 and Maven as shown below:
----
$ sudo apt install -y openjdk-11-jdk maven
$ sudo apt install openjdk-11-jdk maven
----
Verify that you have the correct version installed by running:
[source,bash]
----
$ javac -version
javac 11.0.7
@ -862,7 +888,7 @@ We have OpenJDK 11.0.7 and Maven 3.6.1, so we're ready.
The source code for Eclair is on Github. The +git clone+ command can create a local copy for us. Let's change to our home directory and run it there:
----
$ cd
$ cd ~
$ git clone https://github.com/ACINQ/eclair.git
----
@ -886,7 +912,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 +925,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
@ -914,7 +944,7 @@ Congratulations! You have built Eclair from source and you are ready to code, te
Our final example, presented in this section, will bring together all the various containers we have built to form a Lightning network made of diverse (LND, c-lightning, Eclair) node implementations. We will compose the network by connecting the nodes together and opening channels from one node to another. As the final step we route a payment across these channels.
In this example, we will replicate the Lighting network example from <<routing_on_a_network_of_payment_channels>>. Specifically, we will create four Lightning nodes named Alice, Bob, Wei, and Gloria. We will connect Alice to Bob, Bob to Wei, and Wei to Gloria. Finally, we will have Gloria create an invoice and have Alice pay that invoice. Since Alice and Gloria are not directly connected, the payment will be routed as an HTLC across all the payment channels.
In this example, we will replicate the Lighting network example from <<routing_on_a_network_of_payment_channels>>. Specifically, we will create four Lightning nodes named Alice, Bob, Chan, and Dina. We will connect Alice to Bob, Bob to Chan, and Chan to Dina. Finally, we will have Dina create an invoice and have Alice pay that invoice. Since Alice and Dina are not directly connected, the payment will be routed as an HTLC across all the payment channels.
==== Using docker-compose to orchestrate docker containers
@ -961,7 +991,7 @@ services:
container_name: Alice
----
The fragment above defines a network called +lnnet+ and a container called +bitcoind+ which will attach to the +lnnet+ network. The container is the same one we built at the beginning of this chapter. We expose three of the container's ports allowing us to send commands to it and monitor blocks and transactions. Next, the configuration specifies an LND container called "Alice". Further down you will also see specifications for containers called "Bob" (c-lightning), "Wei" (Eclair) and "Gloria" (LND again).
The fragment above defines a network called +lnnet+ and a container called +bitcoind+ which will attach to the +lnnet+ network. The container is the same one we built at the beginning of this chapter. We expose three of the container's ports allowing us to send commands to it and monitor blocks and transactions. Next, the configuration specifies an LND container called "Alice". Further down you will also see specifications for containers called "Bob" (c-lightning), "Chan" (Eclair) and "Dina" (LND again).
Since all these diverse implementations follow the Basis of Lightning Technologies (BOLT) specification and have been extensively tested for interoperability, they have no difficulty working together to build a Lightning network.
@ -980,16 +1010,16 @@ To start the example, we switch to the directory that contains the +docker-compo
$ cd code/docker
$ docker-compose up
Creating network "docker_lnnet" with the default driver
Creating Wei ... done
Creating Chan ... done
Creating Bob ... done
Creating Gloria ... done
Creating Dina ... done
Creating Alice ... done
Creating bitcoind ... done
Attaching to Wei, Bob, Gloria, Alice, bitcoind
Attaching to Chan, Bob, Dina, Alice, bitcoind
Bob | Waiting for bitcoind to start...
Wei | Waiting for bitcoind to start...
Chan | Waiting for bitcoind to start...
Alice | Waiting for bitcoind to start...
Gloria | Waiting for bitcoind to start...
Dina | Waiting for bitcoind to start...
bitcoind | Starting bitcoind...
[...]
@ -1014,25 +1044,26 @@ Before running the +setup-channels.sh+ script note the following: Wait a minute
Let's run the script to see its effect and then we will look at how it works internally. We use +bash+ to run it as a command:
[source,bash]
----
$ cd code/docker
$ bash setup-channels.sh
Getting node IDs
Alice: 02c93da7a0a341d28e6d7742721a7d182f878e0c524e3666d80a58e1406d6d9391
Bob: 0343b8f8d27a02d6fe688e3596b2d0834c576672e8750106540617b6d5755c812b
Wei: 03e17cbc7b46d553bade8687310ee0726e40dfa2c629b8b85ca5d888257757edc1
Gloria: 038c9dd0f0153cba3089616836936b2dad9ea7f97ef839f5fbca3a808d232db77b
Chan: 03e17cbc7b46d553bade8687310ee0726e40dfa2c629b8b85ca5d888257757edc1
Dina: 038c9dd0f0153cba3089616836936b2dad9ea7f97ef839f5fbca3a808d232db77b
Setting up channels...
Alice to Bob
Bob to Wei
Bob to Chan
Wei to Gloria
Chan to Dina
Get 10k sats invoice from Gloria
Get 10k sats invoice from Dina
Gloria invoice lnbcrt100u1p00w5sypp5fw2gk98v6s4s2ldfwxa6jay0yl3f90j82kv6xx97jfwpa3s964vqdqqcqzpgsp5jpasdchlcx85hzfp9v0zc7zqs9sa3vyasj3nm0t4rsufrl7xge6s9qy9qsqpdd5d640agrhqe907ueq8n8f5h2p42vpheuzen58g5fwz94jvvnrwsgzd89v70utn4d7k6uh2kvp866zjgl6g85cxj6wtvdn89hllvgpflrnex
Dina invoice lnbcrt100u1p00w5sypp5fw2gk98v6s4s2ldfwxa6jay0yl3f90j82kv6xx97jfwpa3s964vqdqqcqzpgsp5jpasdchlcx85hzfp9v0zc7zqs9sa3vyasj3nm0t4rsufrl7xge6s9qy9qsqpdd5d640agrhqe907ueq8n8f5h2p42vpheuzen58g5fwz94jvvnrwsgzd89v70utn4d7k6uh2kvp866zjgl6g85cxj6wtvdn89hllvgpflrnex
Wait for channel establishment - 60 seconds for 6 blocks
@ -1042,11 +1073,12 @@ As you can see from the output, the script first gets the node IDs (public keys)
Looking inside the script, we see the part that gets all the node IDs and stores them in temporary variables so that they can be used in subsequent command. It looks like this:
[source,bash]
----
alice_address=$(docker-compose exec -T Alice bash -c "lncli -n regtest getinfo | jq .identity_pubkey")
bob_address=$(docker-compose exec -T Bob bash -c "lightning-cli getinfo | jq .id")
wei_address=$(docker-compose exec -T Wei bash -c "eclair-cli -s -j -p eclair getinfo| jq .nodeId")
gloria_address=$(docker-compose exec -T Gloria bash -c "lncli -n regtest getinfo | jq .identity_pubkey")
chan_address=$(docker-compose exec -T Chan bash -c "eclair-cli -s -j -p eclair getinfo| jq .nodeId")
dina_address=$(docker-compose exec -T Dina bash -c "lncli -n regtest getinfo | jq .identity_pubkey")
----
If you have followed the first part of the chapter you will recognise these commands and be able to "decipher" their meaning. It looks quite complex, but we will walk through it step-by-step and you'll quickly get the hang of it.
@ -1057,6 +1089,7 @@ The following three lines do the same for each of the other nodes. Because they
Next, we tell each node to establish a network connection to the next node and open a channel:
[source,bash]
----
docker-compose exec -T Alice lncli -n regtest connect ${bob_address//\"}@Bob
docker-compose exec -T Alice lncli -n regtest openchannel ${bob_address//\"} 1000000
@ -1071,36 +1104,40 @@ Now that +Alice+ is connected, we open a 1,000,000 satoshi channel to +Bob+ with
We do the same with the other nodes, setting up connections and channels. Each node type has a slightly different syntax for these commands, but the overall principle is the same:
To Bob's node (c-lightning) we send these commands:
[source,bash]
----
docker-compose exec -T Bob lightning-cli connect ${wei_address//\"}@Wei
docker-compose exec -T Bob lightning-cli fundchannel ${wei_address//\"} 1000000
docker-compose exec -T Bob lightning-cli connect ${chan_address//\"}@Chan
docker-compose exec -T Bob lightning-cli fundchannel ${chan_address//\"} 1000000
----
To Wei's node (Eclair) we send:
To Chan's node (Eclair) we send:
[source,bash]
----
docker-compose exec -T Wei eclair-cli -p eclair connect --uri=${gloria_address//\"}@Gloria
docker-compose exec -T Wei eclair-cli -p eclair open --nodeId=${gloria_address//\"} --fundingSatoshis=1000000
docker-compose exec -T Chan eclair-cli -p eclair connect --uri=${dina_address//\"}@Dina
docker-compose exec -T Chan eclair-cli -p eclair open --nodeId=${dina_address//\"} --fundingSatoshis=1000000
----
At this point we create a new invoice for 10,000 satoshis on Gloria's node:
At this point we create a new invoice for 10,000 satoshis on Dina's node:
[source,bash]
----
gloria_invoice=$(docker-compose exec -T Gloria lncli -n regtest addinvoice 10000 | jq .payment_request)
dina_invoice=$(docker-compose exec -T Dina lncli -n regtest addinvoice 10000 | jq .payment_request)
----
The +addinvoice+ command creates an invoice for the specified amount in satoshis and produces a JSON object with the invoice details. From that JSON object we only need the actual bech32-encoded payment request, which we extract with +jq+.
Next, we have to wait. We just created a bunch of channels. Hence, our nodes broadcast several funding transactions. The channels can't be used until the funding transactions are mined and collect 6 confirmations. Since our Bitcoin +regtest+ blockchain is set to mine blocks every ten seconds, we have to wait 60 seconds for all the channels to be ready to use.
The final command is the actual invoice payment. We connect to Alice's node and present Gloria's invoice for payment.
The final command is the actual invoice payment. We connect to Alice's node and present Dina's invoice for payment.
[source,bash]
----
docker-compose exec -T Alice lncli -n regtest payinvoice --json --inflight_updates -f ${gloria_invoice//\"}
docker-compose exec -T Alice lncli -n regtest payinvoice --json --inflight_updates -f ${dina_invoice//\"}
----
We ask Alice's node to pay the invoice, but also ask for +inflight_updates+ in +json+ format. That will give us detailed output about the invoice, the route, the HTLCs, and the final payment result. We can study this additional output and learn from it!
Since Alice's node doesn't have a direct channel to Gloria, her node has to find a route. There is only one viable route here (Alice->Bob->Wei->Gloria), which Alice will be able to discover now that all the channels are active and have been advertised to all the nodes by the Lightning gossip protocol. Alice's node will construct the route and create an onion packet to establish HTLCs across the channels. All of this happens in a fraction of a second and Alice's node will report the result of the payment attempt. If all goes well, you will see the last line of the JSON output showing:
Since Alice's node doesn't have a direct channel to Dina, her node has to find a route. There is only one viable route here (Alice->Bob->Chan->Dina), which Alice will be able to discover now that all the channels are active and have been advertised to all the nodes by the Lightning gossip protocol. Alice's node will construct the route and create an onion packet to establish HTLCs across the channels. All of this happens in a fraction of a second and Alice's node will report the result of the payment attempt. If all goes well, you will see the last line of the JSON output showing:
----
"failure_reason": "FAILURE_REASON_NONE"

@ -7,7 +7,7 @@ There are many reasons why you might want to set up your own Lightning node. The
* To be a full, active participant in the Lightning Network, not just an end-user.
* To run an e-commerce store or receive income via Lightning payments.
* To earn income from Lightning routing fees.
* To earn income from Lightning routing fees or by renting channel liquidity.
* To develop new services, applications, or plugins for the Lightning Network.
* To increase your financial privacy while using Lightning.
* To use some apps built on top of Lightning, like Lightning-powered Instant Messaging apps.
@ -20,6 +20,18 @@ But the skills you will learn from this experience are valuable and can be appli
Let's get started!
[NOTE]
====
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
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
but somewhere else.
====
=== Choosing your platform
There are many ways you can run a Lightning node ranging from a small mini-PC hosted in your home or a dedicated server to a hosted server in the cloud. The method you choose will depend on the resources you have and how much money you want to spend.
@ -27,7 +39,7 @@ There are many ways you can run a Lightning node ranging from a small mini-PC ho
==== Why is reliability important for running a Lightning Node?
In Bitcoin hardware is not particularly important unless one is specifically running a mining node.
In Bitcoin, hardware is not particularly important unless one is specifically running a mining node.
The Bitcoin Core node software can be run on any machine that meets its minimum requirements and does not need to be online to receive payments; only to send them.
If a Bitcoin node goes down for an extended period of time, the user can simply reboot the node and once it connects to the rest of the network, it will re-sync the blockchain.
@ -40,7 +52,9 @@ There are also the issues of hardware failure and loss of data. In Bitcoin, a ha
In contrast, in Lightning the information about the user's channels, including the commitment transactions and revocation secrets, are not publicly known and are only stored on the individual user's hardware.
Thus, software and hardware failures in the Lightning Network can easily result in loss of funds.
==== What are the types of hardware Lightning Nodes?
==== Types of hardware Lightning Nodes
There are three main types of hardware Lightning nodes:
* **General Purpose Computers**: a Lightning Network node can be run on a home computer or laptop running Windows, Mac OS, or Linux. Typically this is run alongside a Bitcoin node.
* **Dedicated Hardware**: a Lightning Node can also be run on dedicated hardware like a Raspberry Pi, Rock64, or mini-PC. This setup would usually run a software stack including a Bitcoin node and other applications. This setup is popular as the hardware is dedicated to running and maintaining the Lightning node only and is usually set up with an installation "helper".
@ -51,7 +65,7 @@ Thus, software and hardware failures in the Lightning Network can easily result
_Virtual Private Server_ (VPS) and "cloud computing" services such as Microsoft Azure, Google Cloud, Amazon Web Services (AWS), or DigitalOcean are quite affordable and can be set up very quickly. A Lightning node can be hosted for between $20 and $40 per month on such a service.
However, as the saying goes, "'Cloud' is just other people's computers". Using these services means running your node on other people's computers. This brings along the corresponding advantages and disadvantages. The key advantages are convenience, efficiency, uptime, and possibly even cost. The cloud operator manages and runs the node to a high degree automatically providing you with convenience and efficiency. They provide excellent uptime and availability, often much better than what an individual can achieve at home. If you consider that just the electricity cost of running a server in many western countries is around $10 per month, then add to that the cost of network bandwidth and the hardware itself, the VPS offering becomes financially competetive. Lastly, with a VPS you need no space for a PC at home, and don't have any issues with PC noise or heat.
On the other hand there are several notable disadvantages. A Lightning node running in the "cloud" will always be less secure and less private that one running on your own computer. Additionally, these cloud computing services are very centralized. The vast majority of Bitcoin and Lightning nodes running on such services are located in a handful of data centers in Virginia, Sunnyvale, Seattle, London, and Frankfurt. When the networks or data centers of these providers have service problems, it affects thousands of nodes on so-called "decentralized" networks.
On the other hand there are several notable disadvantages. A Lightning node running in the "cloud" will always be less secure and less private than one running on your own computer. Additionally, these cloud computing services are very centralized. The vast majority of Bitcoin and Lightning nodes running on such services are located in a handful of data centers in Virginia, Sunnyvale, Seattle, London, and Frankfurt. When the networks or data centers of these providers have service problems, it affects thousands of nodes on so-called "decentralized" networks.
If you have the possibility and capacity of running a node on your own computer at home or in your office, then this might be preferable to running it
in the cloud. Nonetheless, if running your own server is not an option, by all means consider running one on a VPS.
@ -61,10 +75,10 @@ in the cloud. Nonetheless, if running your own server is not an option, by all m
If you have a reasonable capacity internet link at home or in your office, you can certainly run a Lightning node there. Any "broadband" connection is sufficient for the purpose of running a lightweight node, and a fast connection will allow you to run a Bitcoin full node too.
While you can run a Lightning node (and even a Bitcoin node) on your laptop, it will become annoying quite fast. These programs consume your computer's resources and need to run 24/7. Your user applications like your browser or your spreadsheet will find themselves competing against the Lightning background services for your computer's resources. In other words, your browser and other desktop workloads will be slowed down.
And when your word processing app freezes up your laptop, your Lightning node will go down as well. Furthermore, you should never turn off your laptop.
And when your word processing app freezes up your laptop, your Lightning node will go down as well leaving you unable to receive transactions and potentially vulnerable to attacks. Furthermore, you should never turn off your laptop.
All this combined together results in a set-up that is not ideal. The same will apply to your daily-use personal desktop PC.
Instead, most users will choose to run a node on a dedicated computer. Fortunately, you don't need a "server" class computer to do this. You can run a Lightning node on a mini-PC, such as a Raspberry Pi or an Atom-based fanless PC. These are simple computers which are commonly used as a media server or home automation hub. They are relatively inexpensive, costing between $50 and $150 USD at that time of this writing. To run on a mini-PC, you will need an external USB hard drive, which again is relatively inexpensive, costing approximately $50 USD. The advantage of a dedicated mini-PC as a platform for Lightning and Bitcoin nodes is that it can run continuously, silently, and unobtrusively on your home WiFi network, tucked behind your router or TV. No one will even know that this little box is actually part of a global banking system!
Instead, most users will choose to run a node on a dedicated computer. Fortunately, you don't need a "server" class computer to do this. You can run a Lightning node on a mini-PC, such as a Raspberry Pi or an Atom-based fanless PC. These are simple computers which are commonly used as a media server or home automation hub. They are relatively inexpensive, costing between $50 and $150 USD at the time of this writing. To run on a mini-PC, you will need an external USB hard drive, which again is relatively inexpensive, costing approximately $50 USD. The advantage of a dedicated mini-PC as a platform for Lightning and Bitcoin nodes is that it can run continuously, silently, and unobtrusively on your home network, tucked behind your router or TV. No one will even know that this little box is actually part of a global banking system!
==== What hardware is required to run a Lightning node?
@ -74,9 +88,9 @@ At a minimum, the following will be required to run a Lightning Node:
* **RAM**: a system with 2GB of RAM will _barely_ run both Bitcoin and Lightning nodes. It will perform much better with at least 4GB of RAM. The Initial Block Download will be especially challenging with less than 4GB of RAM. More than 8GB of RAM is unnecessary, because the CPU is the greater bottleneck for these types of services, due to cryptographic operations such as signature validation.
* **Storage Drive**: this can be a Hard Drive or an Solid State Drive (SSD). An SSD will be significantly quicker for running a Bitcoin node. Most of the storage is used for the Bitcoin blockchain, which occupies more than 340GB (as of September 2020).
* **Storage Drive**: this can be a Hard Drive or an Solid State Drive (SSD). An SSD will be significantly quicker for running a Bitcoin node. Most of the storage is used for the Bitcoin blockchain, which occupies more than 320GB (as of January 2021).
* **Internet Connection**: a reliable internet connection will be required to download new Bitcoin blocks, as well as to communicate with other Lightning peers. During operation the estimated data use ranges from 10GB to 100GB per month, depending on configuration. At startup a Bitcoin full node downloads the full blockchain, 340GB as of September 2020.
* **Internet Connection**: a reliable internet connection will be required to download new Bitcoin blocks, as well as to communicate with other Lightning peers. During operation the estimated data use ranges from 10GB to 100GB per month, depending on configuration. At startup a Bitcoin full node downloads the full blockchain, 324GB as of January 2021.
* **Power Supply**: a reliable power supply is required as Lightning nodes need to be online at all times. A power failure will cause in-progress payments to fail. For heavy duty routing nodes, a backup or uninterruptible power supply (UPS) is useful in the case of power outages.
Ideally, you should connect your Internet router to this UPS as well.
@ -101,7 +115,7 @@ Traditional SATA-based SSDs are cheaper, but not as fast. SATA SSDs perform suff
Smaller computers might not be able to take advantage of NVMe SSDs.
For example, the Raspberry Pi 4 cannot benefit from them because of the limited bandwidth of its USB port.
To choose the size, let's look at the Bitcoin blockchain. As of September 2020 its size is 340GB including the transaction index. If you want to have some margin available for future growth or to install other data on your node, purchase at least a 512GB drive or better yet a 1TB drive.
To choose the size, let's look at the Bitcoin blockchain. As of January 2021 its size is 324GB including the transaction index and grows by roughly 60GB/year. If you want to have some margin available for future growth or to install other data on your node, purchase at least a 512GB drive or better yet a 1TB drive.
=== Using an installer or helper
@ -109,11 +123,11 @@ Installing a Lightning node or a Bitcoin node may be daunting if you are not fam
==== RaspiBlitz
One of the most popular and complete "helper" is _RaspiBlitz_, a project built by Christian Rootzoll. It is intended to be installed on a Raspberry Pi 4. RaspiBlitz comes with a recommended hardware "kit" that you can build in a matter of hours or at most a weekend. If you attend a Lightning "hackathon" in your city, you are likely to see many people working on their RaspiBlitz setup, swapping tips, and helping each other. You can find the RaspiBlitz project here:
One of the most popular and complete "helper" is _RaspiBlitz_, a project built by Christian Rotzoll. It is intended to be installed on a Raspberry Pi 4. RaspiBlitz comes with a recommended hardware "kit" that you can build in a matter of hours or at most a weekend. If you attend a Lightning "hackathon" in your city, you are likely to see many people working on their RaspiBlitz setup, swapping tips, and helping each other. You can find the RaspiBlitz project here:
https://github.com/rootzoll/raspiblitz
image::[images/raspiblitz.jpg]
image::images/raspiblitz.jpg[]
In addition to a Bitcoin and Lightning node, RaspiBlitz can install a number of additional services, such as:
@ -121,6 +135,7 @@ In addition to a Bitcoin and Lightning node, RaspiBlitz can install a number of
* ElectRS (Electrum Server in Rust)
* BTCPayServer (Cryptocurrency Payment Processor)
* BTC-RPC-Explorer (Bitcoin Blockchain Explorer)
* Ride The Lightning (Lightning Node Management GUI)
* LNbits (Lightning wallet/accounts System)
* SpecterDesktop (Multisig Trezor, Ledger, Coldcard Wallet & Specter-DIY)
* LNDmanage (Advanced Channel Management CLI)
@ -130,7 +145,7 @@ In addition to a Bitcoin and Lightning node, RaspiBlitz can install a number of
==== MyNode
_MyNode_ is another popular open source "helper" project including a lot of Bitcoin related software. Is is easy to install: you "flash" the installer onto an SD card and boot your mini-PC from the SD card. You do not need any monitor to use myNode as the administrative tools are accessible remotely from a browser. If your mini-PC has no monitor, mouse, or keyboard, you can manage it from another computer or even from your smartphone. Once installed, go to http://mynode.local/ and create a Lightning wallet and node in two clicks.
_MyNode_ is another popular open source "helper" project including a lot of Bitcoin related software. It is easy to install: you "flash" the installer onto an SD card and boot your mini-PC from the SD card. You do not need any monitor to use myNode as the administrative tools are accessible remotely from a browser. If your mini-PC has no monitor, mouse, or keyboard, you can manage it from another computer or even from your smartphone. Once installed, go to http://mynode.local/ and create a Lightning wallet and node in two clicks.
You can find the MyNode project here:
@ -143,6 +158,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.
@ -181,7 +218,7 @@ The bottom line for this decision is: If you can afford a disk larger than 500GB
==== Operating system choice
The next step is to select an operating system for your nodes. The vast majority of internet servers run on some variant of Linux. Linux is the platform of choice for the internet because it is a powerful, open-source operating system. Linux, however, has a steep learning curve and requires familiarity with a command-line environment. It is often intimidating for new users.
The next step is to select an operating system for your node. The vast majority of internet servers run on some variant of Linux. Linux is the platform of choice for the internet because it is a powerful, open-source operating system. Linux, however, has a steep learning curve and requires familiarity with a command-line environment. It is often intimidating for new users.
Ultimately, most of the services can be run on any modern POSIX operating system, which includes Mac OS, Windows, and of course Linux. Your choice should be driven more by your familiarity and comfort with an operating system and your learning objectives. If you want to expand your knowledge and learn how to operate a Linux system, this is a great opportunity to do so with a specific project and a clear goal. If you just want to get a node up and running, go with what you know.
@ -222,7 +259,7 @@ You decided not to use an installation "helper" and instead to dive into the com
[WARNING]
====
This section will delve into the advanced topic of system administration from the command-line. You will need to do additional research and learn more skills not covered here. Linux administration is a complicated topic and there are many pitfalls. Proceed with caution!
This section will delve into the advanced topic of system administration from the command-line. Linux administration is its own skill set that is outside the scope of this book. It is a complicated topic and there are many pitfalls. Proceed with caution!
====
In the next few sections we will briefly describe how to install and configure a Bitcoin and Lightning node on a Linux operating system. You will need to review the installation instructions for the specific Bitcoin and Lightning node applications you decided to use. You can usually find these in a file called +INSTALL+ or in the +docs+ sub-directory of each project. We will only describe some of the common steps that apply to all such services, and the instructions we offer will be necessarily incomplete.
@ -242,10 +279,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
@ -351,7 +388,7 @@ rpcpassword=PASSWORD
Even the +txindex+ option is not strictly necessary, though it will ensure your Bitcoin node creates an index of all transactions, which is required for some applications. The +txindex+ option is not required to run a Lightning node.
A c-lightning Lightning node running on the same server also only requires a few lines in the configuration:
A c-lightning Lightning node running on the same server also requires only a few lines in the configuration:
----
network=mainnet
@ -395,7 +432,7 @@ https://www.whatismyip.com/port-scanner/
By default, these services only allow you to check incoming connections to the IP address from which you are connecting. This is done to prevent you from using the service to scan other people's networks and computers. You will see your router's external IP address and a field for entering a port number. If you haven't changed the default ports in your node configuration, try port 8333 (Bitcoin) and/or 9735 (Lightning).
[[ln_port_check]]
. Checking for incoming port 9735
.Checking for incoming port 9735
image::images/ln_port_check.png[]
In <<ln_port_check>> you can see the result of checking port 9735 on a server running Lightning, using the +whatismyip.org+ port scanner tool. It shows that the server is accepting incoming connections to the Lightning port. If you see a result like this, you are all set!
@ -464,7 +501,7 @@ Once done reconfiguring, repeat the port check using one of the websites from th
=== Security of your node
A Lightning node is, by definition, a hot-wallet. That means that the funds (both on-chain and off-chain) controlled by a Lightning node are directly controlled by keys that are loaded in the node's memory. If a Lightning node is compromised, it is trivial to create on-chain or off-chain transactions to drain its funds. It is therefore critically important that you protect it from unauthorized access.
A Lightning node is, by definition, a hot-wallet. That means that the funds (both on-chain and off-chain) controlled by a Lightning node are directly controlled by keys that are loaded in the node's memory or stored on the node's hard disk. If a Lightning node is compromised, it is trivial to create on-chain or off-chain transactions to drain its funds. It is therefore critically important that you protect it from unauthorized access.
Security is a holistic effort, meaning that you have to secure every layer of a system. As the saying goes: the chain is only as strong as the weakest link. This is an important concept in information security and we will apply it to our node.
@ -477,111 +514,112 @@ Securing an operating system is a vast topic that is beyond the scope of this bo
To secure your operating system, here are some of the top items to consider:
. Provenance - Start by ensuring that you are downloading the correct operating system image and verify any signatures or checksums before installing it.
. Provenance - Start by ensuring that you are downloading the correct operating system image and verify any signatures or checksums before installing it. Extend this to any software that you install. Double-check any source or URL from where you download. Verify the integrity and correctness of the downloaded software via signature and checksum verification.
. Maintenance - Make sure that you keep your operating system up to date. Enable automated daily or weekly installation of security updates.
. Least Privilege - Set up users for specific processes and give them the least access needed to run a service. Do not run processes with admin privileges (e.g. root).
. Process Isolation - Use the operating system features to isolate processes from each other.
. File System Permissions - Configure the file system carefully, on the least-privilege principle. Do not make files readable or writeable by everyone.
. Strong Authentication - Use strong randomly generated passwords, or whenever possible public-key authentication e.g. with Secure Shell (SSH) instead of passwords.
. Two-factor Authentication (2FA) - Use two-factor authentication wherever possible, including Universal 2-Factor (U2F) with hardware security keys.
. Backup - Make backups of your system, but make sure you protect the backups with encryption too.
. Strong Authentication - Use strong randomly generated passwords or, whenever possible, public-key authentication. E.g. it is safer to use Secure Shell (SSH) with a cryptographic key pair instead of a password.
. Two-factor Authentication (2FA) - Use two-factor authentication wherever possible, including Universal 2-Factor (U2F) with hardware security keys. This applies to all external services you might be using such as your cloud service provider. But you can apply this also to your own set-up such as your own SSH configuration. Use 2FA also for indirect services. Say you are using a cloud service. You gave your cloud service provider an email address. Also protect your email address with 2FA.
. Backup - Make backups of your system, but make sure you protect the backups with encryption too. Perform these backups periodically. At least once test if you can restore your backup and that your backup is complete and accessible. If possible, keep one copy of your backups on a different disk to avoid that a single hard disk failure destroys _both_ your active node as well as your backup copies.
. Vulnerability & Exposure Management - Use remote scanning to ensure you have minimized the attack surface of your system. Close any unnecessary services or ports.
- Minimize - Install only software and packages that you really need and use. Uninstall packages that you no longer use. It is recommended that you do _not_ use your node computer for non-node activities that you can perform on another of your computers. Especially, if you can, do _not_ use your node computer for browsing, surfing the internet, or reading your email.
This is a list of basic security measures, not an exhaustive list.
This is a list of the most basic security measures. It is by no means exhaustive.
==== Node Access
Your Lightning node will expose a Remote Procedure Call (RPC) Application Programming Interface (API). This means that your node can be controlled by commands sent to a specific TCP port. Control of that RPC API is achieved by some form of user authentication. Depending on the type of Lightning node you set up, this will either be done by username/password authentication, or by a mechanism called an authentication _macaroon_. A macaroon is a more sophisticated type of cookie, as the name implies. Unlike a cookie, it is cryptographically signed and can express a set of access capabilities.
Your Lightning node will expose a Remote Procedure Call (RPC) Application Programming Interface (API). This means that your node can be controlled remotely by commands sent to a specific TCP port. Access control to that RPC API is achieved by some form of user authentication. Depending on the type of Lightning node you set up, this will either be done by username/password authentication or by a mechanism called an authentication _macaroon_. As the name implies, a macaroon is a more sophisticated type of cookie. Unlike a cookie, it is cryptographically signed and can express a set of access capabilities.
For example, LND uses macaroons to grant access to the RPC API. By default the LND software creates three macaroons with different levels of access, called +admin+, +invoice+ and +readonly+. Depending on which macaroon you copy and use in your RPC client, you either have "readonly" access, "invoice" access (which includes the "readonly" capabilities), or "admin" access which gives you full control. There's also a macaroon "bakery" function in LND that can construct macaroons with any combination of capabilities with very fine-grained control.
For example, LND uses macaroons to grant access to the RPC API. By default, the LND software creates three macaroons with different levels of access, called +admin+, +invoice+, and +readonly+. Depending on which macaroon you copy and use in your RPC client, you either have "readonly" access, "invoice" access (which includes the "readonly" capabilities), or "admin" access which gives you full control. There is also a macaroon "bakery" function in LND that can construct macaroons with any combination of capabilities with very fine-grained control.
If you use a username/password authentication model, make sure you select a long and random password. You will not have to type this password often as it will be stored in the configuration files. You can therefore pick one that cannot be guessed. Many of the examples you will see include poorly chosen passwords and often people copy these into their own systems, giving an easy backdoor to anyone. Don't do that. Use a password manager to generate a random alpha-numeric password. Since certain special characters can interfere with the command line (e.g. $/!*\&%), it is best to avoid them for passwords that will be used in a shell environment and may end up being passed as command-line parameters.
If you use a username/password authentication model, make sure you select a long and random password. You will not have to type this password often as it will be stored in the configuration files. You should therefore pick one that cannot be guessed. Many of the examples you will see include poorly chosen passwords, and often people copy these into their own systems, proving easy access to anyone. Don't do that! Use a password manager to generate a long random alpha-numeric password. Since certain special characters such as these +$?/!*\&%`"'+ can interfere with the command line, it is best to avoid those for passwords that will be used in a shell environment. To avoid problems stick with long random alpha-numeric password.
A plain alphanumeric sequence that is longer than 12 characters and randomly generated is usually sufficient. If you plan to store large amount of money on your Lightning node and are concerned about remote brute-force attacks, select a length of more than 20 characters that makes such attacks practically infeasible.
A plain alphanumeric sequence that is longer than 12 characters and randomly generated is usually sufficient. If you plan to store large amounts of money on your Lightning node and are concerned about remote brute-force attacks, select a password length of more than 20 characters to make such attacks practically infeasible.
=== Node and channel backups
A very important consideration when running a Lightning node is the issue of backups. Unlike a Bitcoin wallet, where a BIP39 mnemonic phrase can recover all the state of the wallet, in Lightning this is not sufficient.
A very important consideration when running a Lightning node is the issue of backups. Unlike a Bitcoin wallet, where a BIP39 mnemonic phrase can recover all the state of the wallet, in Lightning this is _not_ the case.
Lightning wallets do use a BIP39 mnemonic phrase backup for the on-chain wallet. However, due to the way channels are constructed, the mnemonic phrase is not sufficient to restore a Lightning node. An additional layer of backup is needed, which is called the _Static Channel Backup (SCB)_. Without a SCB, a Lightning node operator may lose all the funds that are in channels if they lose the Lightning node data store.
Lightning wallets do use a BIP39 mnemonic phrase backup, but only for the on-chain wallet. However, due to the way channels are constructed, the mnemonic phrase is _not_ sufficient to restore a Lightning node. An additional layer of backups is needed, which is called the _Static Channel Backup (SCB)_. Without an SCB, a Lightning node operator may lose _all_ the funds that are in channels if they lose the Lightning node data store.
[WARNING]
====
Do not fund channels until you have created a system to continuously backup your channel state. Your backups should be moved "offsite" to a different system and location from your node, so that they can survive a variety of system failures (power loss, data corruption etc.) or natural disasters (flood, fire etc.)
Do _not_ fund channels until you have put a system in place to continuously backup your channel state. Your backups should be moved "offsite" to a different system and location from your node, so that they can survive a variety of system failures (power loss, data corruption, etc.) or natural disasters (flood, fire, etc.).
====
Static Channel Backups are not a panacea. First, the state of each channel needs to be backed up every time there is a new commitment transaction. Second, restoring from a channel backup is dangerous. If you do not have the _last_ commitment transaction and you accidentally broadcast an old (revoked) commitment, your channel peer will assume you are trying to cheat and take the entire channel balance with a penalty transaction. To make sure you are closing the channel, you need to do a cooperative close. But a malicious peer could mislead your node into broadcasting an old commitment during that cooperative close, thereby cheating you by making your node inadvertently try to "cheat".
Static Channel Backups are not a panacea. First, the state of each channel needs to be backed up every time there is a new commitment transaction. Second, restoring from a channel backup is dangerous. If you do not have the _last_ commitment transaction and you accidentally broadcast an old (revoked) commitment, your channel peer will assume you are trying to cheat and claim the entire channel balance with a penalty transaction. To make sure you are closing the channel, you need to do a _cooperative close_. But a malicious peer could mislead your node into broadcasting an old, revoked commitment during that cooperative close, thereby cheating you by making your node inadvertently try to "cheat".
Additionally, the backups of your channels need to be encrypted to maintain your privacy and your channel security. Otherwise, anyone who finds the backups can not only see all your channels, they could use the backups to close all your channels in a way that hands over the balance to your channel peers.
Furthermore, the backups of your channels need to be encrypted to maintain your privacy and your channel security. Otherwise, anyone who finds the backups can not only see all your channels, they could use the backups to close all your channels in a way that hands over the balance to your channel peers. In other words, a malicious person that gets access to your backups can cause you to lose all your channel funds.
SCB are therefore a weak compromise because they swap one type of risk (data corruption or loss) for another type of risk (malicious peer). To restore from a static channel backup, you have to interact with your channel peers and hope they don't try to cheat (either by giving you an old commitment, or by fooling your node into broadcasting a revoked commitment so they can penalize you). Ultimately, this is less of a risk than the risk of losing all funds committed to a channel because of data corruption. Since data corruption leads to the same outcome as if every one of your peers cheat, you are better off backing up and taking the chance that some of your peers will act honestly.
You can see that SCBs are not a fool-proof safeguard. They are a weak compromise because they swap one type of risk (data corruption or loss) for another type of risk (malicious peer). To restore from a static channel backup, you have to interact with your channel peers and hope they don't try to cheat you by either giving you an old commitment or by fooling your node into broadcasting a revoked commitment so they can penalize you. Despite the weaknesses of SCB, SCBs do make sense and you should perform them. If you do not perform SCBs and you lose your node data, you lost your channel funds forever. Guaranteed! However, if you _do_ perform SCBs and you lose your node data, then you have a reasonable chance that some of your peers are honsest and that you can recuperate some of your channel funds. If you are lucky, you might recover all your funds. In conclusion, it is best for you to perform continuous Static Channel Backups to a disk other than the primary node hard disk.
Channel backup mechanisms are still a work-in-progress and a weakness in most Lightning implementations.
==== Static Channel Backups (SCB)
At the time of writing this book, only LND offers a built-in mechanism for channel backups. Eclair has no backup on the server side, although Eclair mobile does offer optional backup to a Google Drive. C-lightning recently merged the necessary interfaces for a plugin to implement channel backups, but there is no agreed on backup mechanism.
At the time of writing this book, only LND offers a built-in mechanism for channel backups. Eclair has no backup on the server side, although Eclair mobile does offer optional backup to a Google Drive. C-lightning recently merged the necessary interfaces for a plugin to implement channel backups. Unfortunately, there is no consistent, agreed upon backup mechanism across different node implementations.
File-based backups of the Lightning node databases are partial solution, but you run the risk of data corruption because those backups may not reliably catch the latest state commitments. It is much better to have a backup mechanism that is triggered every time there is a state change in a channel, ensuring data consistency.
File-based backups of the Lightning node databases are at best a partial solution because you run the risk of backing up an inconsistent database state. In addition, you may not reliably catch the latest state commitments. It is much better to have a backup mechanism that is triggered every time there is a state change in a channel, thereby ensuring data consistency.
To set up static channel backups in LND, set the +backupfilepath+ parameter, either on the command-line or in the configuration file. LND will then save an SCB file in that directory path. Of course, that's only part of the solution. Now, you have to setup a mechanism that copies that file off-site each time it changes, which is beyond the scope of this book. Any sophisticated backup solution should be able to handle this.
To set up static channel backups in LND, set the +backupfilepath+ parameter either on the command-line or in the configuration file. LND will then save an SCB file in that directory path. Of course, that's only the first step of the solution. Now, you have to setup a mechanism that monitors this file for changes. Each time the file changes the backup mechanism must copy this file to another, possibly "off-site" disk. Such backup mechanisms are beyond the scope of this book. Nonetheless, any sophisticated backup solution should be able to handle this sceanrio. Recall, the backup files should be encrypted too.
==== Hot wallet risk
As we've discussed previously, the Lightning Network consists of a network of _hot wallets_. The funds you store in a Lightning wallet are *online all the time*. You should not store large amounts in a Lightning wallet, as it is quite vulnerable. Large amounts should be kept in a cold wallet that is not online and transacts on-chain.
As we've discussed previously, the Lightning Network consists of a network of _hot wallets_. The funds you store in a Lightning wallet are *online all the time*. This makes them vulnerable. Hence, you should not store large amounts in a Lightning wallet. Large amounts should be kept in a _cold_ wallet that is _not_ online and can transact only on-chain.
But given that warning, you may still find you have a significant amount of money in a Lightning wallet. Such is the case for example if you use a Lightning node for e-commerce operations like running a shop, while not having significant expenses you can pay on Lightning. If that is the case, your wallet will likely receive funds often but send funds rarely. You will therefore have two problems simultaneously: Your channels will be imbalanced inwards (more local balance than remote balance) and you will have too much money in the wallet. Fortunately, you can solve both of these problems simultaneously.
Even if you start small, as time passes you may still find you have a significant amount of money in a Lightning wallet. This is a typical scenario for store owners. If you use a Lightning node for an e-commerce operations, your wallet will likely receive funds often but send funds rarely. You will therefore end up having two problems simultaneously: First, your channels will be imbalanced with large local balances outweighing small remote balances. Secondly, you will have too much money in the wallet. Fortunately, you can solve both of these problems simultaneously.
Let's look at some of the solutions you can use to reduce the funds exposed on a hot wallet.
Let's look at some of the solutions you can use to reduce the funds exposed in a hot wallet.
==== Sweeping funds
If you Lightning wallet balance becomes too large for your risk appetite, you will need to "sweep" funds out of the wallet. You can do so in three ways: on-chain, off-chain, and loop-out. Let's look at each of those in the next few sections.
If your Lightning wallet balance becomes too large for your risk tolerance, you will need to "sweep" funds out of the wallet. You can do so in three ways: on-chain, off-chain, and loop-out. Let's look at each one of these options in the next few sections.
===== On-chain sweep
Sweeping funds on-chain, is accomplished moving the funds from the Lightning wallet to a Bitcoin wallet (presumably a more secure hardware wallet or cold storage). You do that by closing channels. When you close a channel, all funds from your local balance are "swept" to a Bitcoin address. The Bitcoin address for on-chain funds is usually generated by your Lightning wallet so it is still a hot-wallet. You may need to do an additional transaction to move the funds to a more secure address, such as one generated on your hardware wallet.
Sweeping funds on-chain is accomplished by moving the funds from the Lightning wallet to a presumably more secure Bitcoin wallet such as a hardware wallet or cold storage. You do that by closing channels. When you close a channel, all funds from your local balance are "swept" to a Bitcoin address. The Bitcoin address for on-chain funds is usually generated by your Lightning wallet. So it is still a hot-wallet. You may need to do an additional on-chain transaction to move the funds to a more secure address, such as one generated on your hardware wallet.
Closing channels will incur an on-chain fee and will reduce your Lightning node's capacity and connectivity. However, if you run a popular e-commerce node you will not lack incoming capacity and can strategically close channels with large local balances, essentially "batching" your funds for movement on-chain. You may need to use some channel re-balancing techniques (see <<channel_rebalancing>>) before you close channels to maximize the benefit of this strategy.
Closing channels will incur an on-chain fee and will reduce your Lightning node's capacity and connectivity. However, if you run a popular e-commerce node you will not lack incoming capacity and can strategically close channels with large local balances, essentially "bundling" your funds for movement on-chain. You may need to use some channel re-balancing techniques (see <<channel_rebalancing>>) before you close channels to maximize the benefit of this strategy.
===== Off-chain sweep
Another technique you can use involves running a second Lightning node that is not advertised on the network. You can establish large capacity channels from your public node (e.g. the one running you shop) to your less-public (hidden) node. On a regular basis, "sweep" funds by making a Lightning payment to your hidden node.
Another technique you can use involves running a second Lightning node that is not advertised on the network. You can establish large capacity channels from your public node (e.g. the one running your shop) to your unadvertised (hidden) node. On a regular basis, "sweep" funds by making a Lightning payment to your hidden node.
The avantage of this technique lies in the fact that the Lightning node that receives payments for your shop will be publicly known. This makes it a target for hackers, as any Lightning node associated with a shop would be assumed to have large amounts of money in its balance. A second node that is not associated with your shop will not easily be identified as a valuable target.
The advantage of this technique lies in the fact that the Lightning node that receives payments for your shop will be publicly known. This makes it a target for hackers, as any Lightning node associated with a shop would be assumed to have a large balance. A second node that is not associated with your shop will not easily be identified as a valuable target.
As an additional measure of security, you can make your second node a hidden TOR service, so that it's IP address is not known. That further reduces the opportunity for attack and increases your privacy.
As an additional measure of security, you can make your second node a hidden TOR service so that its IP address is not known. That further reduces the opportunity for attacks and increases your privacy.
You will need to setup a script that runs at regular intervals that creates an invoice on your hidden node and then pays that invoice from your shop node, thereby shifting the funds over to your hidden node.
You will need to set up a script that runs at regular intervals. The purpose of this script is to creates an invoice on your hidden node and to pay that invoice from your shop's node, thereby shifting funds over to your hidden node.
Keep in mind that this technique does not move funds into cold storage. Both Lightning nodes are hot wallets. The effect of this is to move funds from a very well known hot wallet to an obscure hot wallet.
Keep in mind that this technique does not move funds into cold storage. Both Lightning nodes are hot wallets. The objective of this sweep is to move funds from a very well known hot wallet to an obscure hot wallet.
===== Submarine swap sweep
Another way to reduce your Lightning hot-wallet balance is to use a technique called a _submarine swap_. Submarine swaps, conceptualized by co-author Olaoluwa Osuntokun and Alex Bosworth, allow on-chain Bitcoin to be exchanged for Lightning payments and vice versa.
Another way to reduce your Lightning hot-wallet balance is to use a technique called a _submarine swap_. Submarine swaps, conceptualized by co-author Olaoluwa Osuntokun and Alex Bosworth, allow the exchange of on-chain bitcoin for Lightning payments and vice versa.
A node operator can initiate a submarine swap and send all available channel balance to the other party, who will then send them on-chain Bitcoin in exchange.
A node operator can initiate a submarine swap and send all available channel balances to the other party who will send them as a result on-chain bitcoin in exchange.
In the future this could be a paid service offered by nodes on the Lightning Network who advertise exchange rates or charge a flat fee for the conversion.
The advantage of a submarine swap for sweeping funds is that we do not close a channel. That means that we preserve our channel capacity and re-balance our channels through this operation. As we send a Lightning payment out, we shift balance from local to remote on one or more of our channels. Not only does that reduce the balance exposed in our node's hot wallet, it also increases the balance available for future incoming payments.
The advantage of a submarine swap for sweeping funds is that no channel needs to be closed. That means that we preserve our channels and only re-balance our channels through this operation. As we send a Lightning payment out, we shift some balance from local to remote on one or more of our channels. Not only does that reduce the balance exposed in our node's hot wallet, it also increases the balance available for future incoming payments.
Now, you could do this by trusting the intermediary to act as a gateway for your funds and not steal them. But in the case of a submarine swap, the operation does not require trust. Submarine swaps are non-custodial _atomic_ operations. That means that the intermediary cannot steal your funds, because the on-chain payment depends on the completion of the off-chain payment and vice-versa. We will discuss submarine swaps in more detail in <<submarine_swaps>>.
You could do this by trusting an intermediary to act as a gateway for your funds and not steal them. But in the case of a submarine swap, the operation does not require trust. Submarine swaps are non-custodial _atomic_ operations. That means that the counterparty in your submarine swap cannot steal your funds because the on-chain payment depends on the completion of the off-chain payment and vice-versa. We will discuss submarine swaps in more detail in <<submarine_swaps>>.
===== Submarine swaps with Loop
One example of a submarine swap service is _Loop_ by Lightning Labs, the company that builds the LND Lightning node. Loop comes in two variations: _Loop In_, which accepts a Bitcoin on-chain payment and converts it into a Lightning off-chain payment and _Loop Out_, which converts a Lightning payment to a Bitcoin payment.
One example of a submarine swap service is _Loop_ by Lightning Labs, the company that builds the LND Lightning node. Loop comes in two variations: _Loop In_ and _Loop Out_. _Loop In_ accepts a Bitcoin on-chain payment and converts it into a Lightning off-chain payment. _Loop Out_ converts a Lightning payment into a Bitcoin payment.
[NOTE]
====
To use Loop, you must be running an LND Lightning node.
To use the _Loop_ service you must be running an LND Lightning node.
====
For the purpose of reducing the balance of our Lightning hot wallet, we would use the Loop Out service. To use the Loop service, we need to install some additional software on our node. The Loop software runs alongside your LND node and provides some command-line tools to execute submarine swaps. You can find the Loop software and installation instructions here:
For the purpose of reducing the balance of your Lightning hot wallet, you would use the Loop Out service. To use the Loop service, you need to install some additional software on your node. The Loop software runs alongside your LND node and provides some command-line tools to execute submarine swaps. You can find the Loop software and installation instructions here:
https://github.com/lightninglabs/loop
Once you have the software installed and running, a Loop-Out operation is as simple as running a single command:
Once you have the software installed and running, a Loop Out operation is as simple as running a single command:
----
loop out --amt 501000 --conf_target 400
@ -605,35 +643,47 @@ Note that your maximum fee, which represents a worst-case scenario, will depend
=== Lightning node uptime and availability
Unlike Bitcoin, Lightning nodes need to be online almost continuously. Your node needs to be online to receive payments, open channels, close channels (cooperatively) and monitor protocol violations. Node availability is such an important requirement in the Lightning Network, that it is a metric used by various automatic channel management tools (e.g. autopilot) to decide with which nodes to open channels. You can even see "availability" as a node metric on popular node explorers such as +1ml.com+.
Unlike Bitcoin, Lightning nodes need to be online almost continuously. Your node needs to be online to receive payments, open channels, close channels (cooperatively), and monitor protocol violations. Node availability is such an important requirement in the Lightning Network that it is a metric used by various automatic channel management tools (e.g. +autopilot+) to decide with which nodes to open channels. You can also see "availability" as a node metric on popular node explorers (see <<ln_explorer>>) such as +1ml.com+.
Node availability is especially important to mitigate and resolve potential protocol violations (i.e. revoked commitments). While you can afford short interruptions from an hour up to one or two days, you cannot have your node offline for longer periods of time without risking loss of funds.
Keeping a node online continuously is not easy, as various bugs and resource limitations can and will occasionally cause downtime. Especially if you run a busy and popular node, you will run into limitations of memory, swap space, number of open files, disk space, and so forth. A whole host of different problems will cause your node or your server to crash.
==== Tolerate faults and automate
If you have the time and skills you should test some basic fault scenarios on the Lightning testnet. On the testnet you will learn valuable lessons without risking any funds. Any step you perform to automate your system will improve your availability.
- Automatic computer server restart: What happens when your server or the operating system crashes? What happens when there is a power outage? Simulate this fault by pressing the "reset" button on your PC or by unplugging the power cable. After crash, reset, or power failure the computer should automatically restart itself. Some computers have a setting in their BIOS to specify how the computer should react on power failures. Test it to make sure the computer really restarts automatically on power failure without human intervention.
Node availability is especially important because of potential protocol violations (i.e. revoked commitments). While you can afford short interruptions (hour or days), you cannot have your node offline for longer periods of time without risking loss of funds.
- Automatic node restart: What happens when your node or one of your nodes crashes? Simulate this fault by killing the corresponding node processes. If a node crashes it should automatically restart itself. Test it to make sure the node or nodes really restart automatically on failure without human intervention. If this is not the case, most likely your node is not set up correctly as an operating system service.
Keeping a node online is not easy, as various bugs and resource limitations will occasionally cause downtime. Especially if you run a busy and popular node, you will run into limitations of memory, swap space, number of open files, disk space etc. A whole host of different problems will cause your node or your server to crash.
- Automatic network reconnection: What happens if your network goes down? What happens when your ISP goes temporarily down? What happens when your ISP assigns a new IP address to your router or your computer? When the network comes back, does the node or do the nodes automatically reconnect to the network? Simulate this fault by unplugging and later re-plugging the Ethernet cable from and to your PC. The nodes should automatically reconnect and continue operation without human intervention.
- Configure your log files: All of the above failures should leave textual entries behind in the corresponding log files. Turn up the verbosity of logging if needed. Find these error entries in the log files and use them for monitoring.
==== Monitoring node availability
Monitoring your node is an important part of keeping it running. You need to monitor not only the availability of the computer itself, but also the availability and correct operation of the Lightning node software.
There are a number of ways to do this, but most require some customization. You can use generic infrastructure monitoring or application monitoring tools, but you have to customize them specifically to query the Lightning node API, to ensure it is running, synchronized to the blockchain and connected to channel peers.
There are a number of ways to do this, but most require some customization. You can use generic infrastructure monitoring or application monitoring tools, but you have to customize them specifically to query the Lightning node API to ensure the node is running, synchronized to the blockchain, and connected to channel peers.
There is a specialized service that offers Lightning node monitoring, using a Telegram bot to notify you of any interruptions in service. This is a free service, though you can pay (over Lightning of course) to get faster alerts. Find more information at:
There is a specialized service that offers Lightning node monitoring. It uses a Telegram bot to notify you of any interruptions in service. This is a free service, though you can pay (over Lightning of course) to get faster alerts. Find more information at:
https://lightning.watch
Over time, we expect more third-party services to provide specialized Lightning node monitoring, most likely charging a micro-payment. Perhaps such services and their APIs will become standardized and be directly supported by Lightning node software.
Over time, we expect more third-party services to provide specialized Lightning node monitoring payable via micro-payments. Perhaps such services and their APIs will become standardized and will one day be directly supported by Lightning node software.
==== Watchtowers
Watchtowers are a mechanism for outsourcing the monitoring and penalty resolution of Lightning protocol violations.
_Watchtowers_ are a mechanism for outsourcing the monitoring and penalty resolution of Lightning protocol violations.
As we mentioned in previous chapters, the Lightning protocol maintains security through a penalty mechanism. If one of your channel partners broadcasts an old commitment transaction, your node will need to exercise the revocation clause and broadcast a penalty transaction to avoid losing money. But if your node is down during the protocol violation, you might lose money.
To solve this problem, we can use one or more _watchtowers_ to outsource the job of monitoring protocol violations and issuing penalty transactions. There are two parts to a watchtower setup: a watchtower server (or simply "watchtower") that monitors the blockchain and a watchtower client that asks the watchtower server for monitoring service.
To solve this problem, we can use one or more _watchtowers_ to outsource the job of monitoring protocol violations and issuing penalty transactions. There are two parts to a watchtower setup: a watchtower server (or simply "watchtower") that monitors the blockchain and a watchtower client that asks the watchtower server for this monitoring service.
Watchtower technology, is still in the early stages of development and is not widely supported. However there are some experimental implementations that you can try, below.
Watchtower technology is still in the early stages of development and is not widely supported. However, below we list some experimental implementations that you can try.
LND can run both a watchtower server and a watchtower client. You can activate the watchtower server by adding the following configuration options:
LND software includes both a watchtower server and a watchtower client. You can activate the watchtower server by adding the following configuration options:
----
[watchtower]
@ -673,78 +723,79 @@ OPTIONS:
C-lightning has the API hooks necessary for a watchtower client plugin, though no such plugin has been implemented yet.
Finally, a popular standalone watchtower server is The Eye of Satoshi (TEOS), which can be found here:
Finally, a popular standalone watchtower server is _The Eye of Satoshi_ (TEOS). It can be found here:
https://github.com/talaia-labs/python-teos
=== Channel management
As a Lightning node operator, one of the recurring tasks you will need to perform is management of your channels. This means opening outbound channels from your node to other nodes, as well as getting other nodes to open inbound channels to your node. In the future, cooperative channel construction may be possible, so you can open symmetric channels that have funds committed on both ends. For now however, new channels only have funds on one end - on the originator's side. So to make your node _balanced_ with both inbound and outbound capacity, you need to open channels to others and entice others to open channels towards your node.
As a Lightning node operator, one of the recurring tasks you will need to perform is management of your channels. This means opening outbound channels from your node to other nodes, as well as getting other nodes to open inbound channels to your node. In the future, cooperative channel construction may be possible, so you can open symmetric channels that have funds committed on both ends on creation. For now, however, new channels only have funds on one end, on the originator's side. Hence, to make your node _balanced_ with both inbound and outbound capacity, you need to open channels to others and entice others to open channels to your node.
==== Opening outbound channels
As soon as you get your Lightning node up and running, you can fund its Bitcoin wallet and then start opening channels with those funds.
This task can be automated, somewhat, with the use of an _autopilot_, which is software that opens channels automatically based on some heuristic rules. Autopilot software is still relatively new and it doesn't always select the best channel partners for you. It might be better, especially in the beginning, to open channels manually.
This task can be partially automated with the use of an _autopilot_, which is a software module that opens channels automatically based on some heuristic rules. Autopilot software is still in its infancy and it doesn't always select the best channel partners for you. It might be better, especially in the beginning, to open channels manually.
You must choose channel partners carefully, as your node's ability to send payments depends on who your channel partners are and how well connected they are to the rest of the Lightning Network. You also want to have more than one channel - so your node isn't susceptible to single point of failure. Since Lightning now supports multi-path payments, you can split your initial funds into several channels and route bigger payments by combining their capacity. Don't make your channels too small, however. Since you need to pay Bitcoin transaction fees to open and close a channel, the channel balance should not be so small that the on-chain fees consume a big portion. It's all about balance!
You must choose channel partners carefully as your node's ability to send payments depends on who your channel partners are and how well connected they are to the rest of the Lightning Network. You also want to have more than one channel to avoid being susceptible to a single point of failure. Since Lightning now supports multi-path payments, you can split your initial funds into several channels and route bigger payments by combining their capacity. At the same time, avoid making your channels too small. Since you need to pay Bitcoin transaction fees to open and close a channel, the channel balance should not be so small that the on-chain fees consume a significant portion. It's all about balance!
To summarize:
* Find a few well connected nodes
* Connect to a few well connected nodes
* Open more than one channel
* Don't open too many channels
* Don't make the channels too small
One way to find well connected nodes is to open a channels to merchants selling something on the Lightning Network. These nodes tend to be well funded and well connected. So when you are ready to make your first payment, you can open a channel directly to the merchant's node. The merchant's node ID will be in the invoice you will receive when you try to buy something, so that makes it easy.
One way to find well connected nodes is to open a channel to a popular merchant selling products on the Lightning Network. These nodes tend to be well funded and well connected. So, when you are ready to buy something online via Lightning, you can open a channel directly to the merchant's node. The merchant's node ID will be in the invoice you will receive when you try to buy something. That makes it easy.
Another way to find well connected nodes is to use a Lightning Explorer, such as +1ml.com+ and browse the list of nodes sorted by channel capacity and number of channels. Don't go for the biggest nodes, as that encourages centralization. Go for a node in the middle of the list, so that you can help them grow.
Another way to find well connected nodes is to use a Lightning Explorer (see <<ln_explorer>>) such as +1ml.com+ and browse the list of nodes sorted by channel capacity and number of channels. Don't go for the biggest nodes as that encourages centralization. Go for a node in the middle of the list, so that you can help them grow. Another factor to consider might be the time span a node is in operation. Nodes having been established more than a year ago tend to be more reputable and less risky than nodes that started operation a week ago.
===== Autopilot
The task of opening channels can be automated, somewhat, with the use of an _autopilot_, which is software that opens channels automatically based on some heuristic rules. Autopilot software is still relatively new and it doesn't always select the best channel partners for you. It might be better, especially in the beginning, to open channels manually.
The task of opening channels can be partially automated with the use of an _autopilot_, which is software that opens channels automatically based on some heuristic rules. Autopilot software is still relatively new and it doesn't always select the best channel partners for you. Especially in the beginning it might be better to open channels manually.
Autopilots currently exist in 3 forms.
- Originally lnd published an autopilot that is fully integrated with lnd and runs constantly in the background while it is turned on.
- lib_autopilot.py can technically offer autopilot computations on the gossip and channel data from any implementation.
- A clighting plugin based on lib_autopilot.py exists that provides an easy to use interface for c-lightning users.
- +lnd+ incorporates an autopilot that is fully integrated with +lnd+ and runs constantly in the background while turned on.
- +lib_autopilot.py+ can offer autopilot computations for any node implementation based on the gossip and channel data.
- A +c-lighting+ plugin based on +lib_autopilot.py+ exists that provides an easy to use interface for +c-lightning+ users.
Be aware that the +lnd+ autopilot will start running in the background as soon as it is turned on via the config file. As a result it will start opening channels immediately if you have onchain outputs in your +lnd+ wallet.
If you want to have full control over the bitcoin transactions that you make and the channels that you open, make sure to turn the autopilot off _before_ you load your +lnd+ wallet with bitcoin funds.
If the autopilot was previously turned on, you might have to restart your +lnd+ before you top up your wallet with an on-chain transaction or before you close channels, which effectively gives you on-chain funds again.
It is crucial that you set key configuration values if you want to run the autopilot.
Have a look at this example configuration:
The main thing to watch out when running the lnd autopilot is that as soon as it is turned on via the config file it will automatically run in the background and it will start to open channels if you have onchain outputs in your lnd wallet.
If you want to have full controll over the bitcoin transactions that you make and the channels that you open make sure to turn off the autopilot before you load your lnd wallet with bitcoin funds.
If the autopilot was previously turned on you might have to restart your lnd before you top up your wallet with an onchain transaction or before you lose channels which effectively gives you on chain funds again..
Another thing to keep in mind is to set the most important config values if you want to run the autopilot.
here you can find an example configuration:
----
[lnd-autopilot]
autopilot.active=1
autopilot.maxchannels=40
autopilot.allocation=0.70
autopilot.maxchansize=500000
autopilot.minchansize=5000000
autopilot.minchansize=500000
autopilot.maxchansize=5000000
autopilot.heuristic=top_centrality:1.0
----
This config file would activate the autopilot.
This configuration file would activate the autopilot.
It would open channels as long as the following two conditions are met:
1. The amount of channels that your node currently has open does not exceed 40.
2. Not more than 70% of your total funds are offchain in payment channels.
1. Your node has currently less than 40 channels open.
2. Less than 70% of your total funds are off-chain in payment channels.
The numbers 40 and 0.7 are chosen completely arbitrary here as we cannot really make a recommendation that goes for everyone about how many channels one should have and how many percent of their funds should be off chain.
The autopilot in lnd will not take into account to run when onchain fees are low.
Thus you might spend quite some funds on transactions fees.
It will make channel recommendations when ever the conditions are met and will directly try to open a channel by using the appropriate fees.
According to this configuration file channels will be between 5 and 50 mBTC.
The size is actually as most of the time on the lightning network depicted in satoshi but we converted the amount for you.
It has become clear that too small channels below 1 mBTC are not very usefull and we do not recommend to open too small channels.
With the wider adoption of multipath payments smaller channels are less of a burden but we still stick to our recommendation.
The numbers 40 and 0.7 are chosen completely arbitrarily here as we cannot make any recommendations that are valid for everyone about how many channels one should have open and what percentage of one's funds should be off chain.
The autopilot in +lnd+ will not take into account on-chain fees. In other words, it will not delay opening channels to a time period when fees are low.
To reduce fees you can manually open channels during a time period when fees are low, e.g. during the weekend.
The autopilot will make channel recommendations whenever the conditions are met and will immediately try to open a channel by using the appropriate current fees.
According to the above configuration file, the channels will be between 5 mBTC (minchansize=500000 satoshi) and 50 mBTC (maxchansize=5000000 satoshi) in size.
As is common, the amounts in the configuration file are enumerated in satoshis.
Currently channels below 1 mBTC are not very useful and we do not recommend to open channels that are too small and below this amount.
With the wider adoption of multipath payments smaller channels are less of a burden but for the time being this is our recommendation.
The c-lightning plugin works very differently in comparison to the lnd autopilot.
Not only from the used algorithms to make the recommendations - which we do not discuss here - but also from the user interface.
First you will need to download the autopilot plugin from the c-lightning plugin repository at https://github.com/lightningd/plugins/tree/master/autopilot and activate it.
We have already explained how to activate plugins in c-lightning.
The autopilot in c-lightning now gets 3 configuration values which can be set in the config file or as command line arguments when you start lightningd
The +c-lightning+ plugin works very differently in comparison to the +lnd+ autopilot.
First, it differs in the algorithms used to make the recommendations. We will not cover this here. Secondly, it differs in its user interface.
You will need to download the _autopilot plugin_ from the +c-lightning+ plugin repository at https://github.com/lightningd/plugins/tree/master/autopilot and activate it.
We have already explained how to activate plugins in +c-lightning+.
The autopilot in +c-lightning+ is controlled via 3 configuration values which can be set in the config file or as command line arguments when you start +lightningd+.
----
[c-lightning-autopilot]
@ -754,22 +805,23 @@ autopilot-min-channel-size-msat=100000000msat
----
These values are the actual default config and you do not need to set them at all.
The autopilot will not autoamatically run in the background like lnd.
Instead you have to start a run specifically with `lightning-cli autopilot-run-once` if you do not want the autopilot to open the recommended channels.
But if you want it to just make recommendations to you from which you can handpick the nodes you can add the optional `dryrun` argument.
A key difference between the lnd and the c-lightning autopilot is that the c-lightning autopilot will also make a recommendation for the channel size.
For example if the autopilot recommends to open a channel with a small node that only has small channels it will not recommend to open a large channel.
However if it opens a channel with a well connected node that also has many large channels it will probably recommend a larger channel size.
The autopilot will not automatically run in the background like in +lnd+.
Instead, you have to start a run specifically with `lightning-cli autopilot-run-once` if you want the autopilot to open the recommended channels.
But if you want it to just provide you with recommendations, from which you can handpick the nodes, you can append the optional `dryrun` argument.
A key difference between the +lnd+ and the +c-lightning+ autopilots is that the +c-lightning+ autopilot will also make a recommendation for the channel size.
For example, if the autopilot recommends to open a channel with a small node that only has small channels, it will not recommend to open a large channel.
However, if it opens a channel with a well connected node that also has many large channels, it will probably recommend a larger channel size.
As you can see the c-lightning autopilot is not as automatic as lnd but gives you a little bit more control.
These differences are of personal preference and could actually be the deciding factor for you why you chose one implementation over the other.
As you can see the +c-lightning+ autopilot is not as automatic as +lnd+'s, but it gives you a little bit more control.
These differences reflect personal preferences and could actually be the deciding factor for you to chose one implementation over the other.
Keep in mind that current autopilots will mainly use public information from the gossip protocol about the current topology of the lightning network.
It is very obvious that your personal requirements for channels can and will only be reflected to a certain degree.
More advanced autopilots would use information that your node already has gatherd by running in the past about routing successes and who you have paid in the past.
Such autopilots might in the future also use the knowledge and statistics that they have collected to make recommendations to close channels and allocate the funds in another way.
We mention these things to you as a word of warning to not really to heavily on the autopilot feature at the time of writing this book.
Keep in mind that current autopilots will primarily use public information from the gossip protocol about the current topology of the Lightning network.
It is obvious that your personal requirements for channels can and will be reflected only to a certain degree.
More advanced autopilots would use historical and usage information that your node has gathered by running in the past, including information about routing successes, whom you have paid in the past, and who paid you.
Such improved autopilots might in the future use this collected data to also make recommendations on closing channels and re-allocating funds.
Take this as a word of caution to not depend or rely too heavily on the autopilot feature at the time of writing of this book.
==== Getting inbound liquidity
@ -777,52 +829,52 @@ In the current design of the Lightning Network, it is more typical for users to
They will do so by opening a channel with another node, and more often they'll be able to spend Bitcoin before they can receive it.
There are three typical ways of getting inbound liquidity:
* Open a channel with outbound liquidity, and then spend some of those funds. Now the balance is on the other end of the channel, which means it can be used to send payments to you.
* Open a channel with outbound liquidity and then spend some of those funds. Now the balance is on the other end of the channel, which means that you can receive payments.
* Ask someone to open a channel to your node. Offer to reciprocate, so that both of your nodes become better connected and balanced.
* Use a submarine swap (e.g. Loop-In) to exchange on-chain BTC for an inbound channel to your node.
* Use a _submarine swap_ (e.g. +Loop-In+) to exchange on-chain BTC for an inbound channel to your node.
* Pay a third party service to open a channel with you. Several such services exist, some charging a fee to provide liquidity, some for free.
* Pay a third party service to open a channel with you. Several such services exist. Some charge a fee to provide liquidity, some are free.
Here's a list of currently available liquidity providers who (for a fee) will open a channel to your node:
Here is a list of currently available liquidity providers who will open a channel to your node for a fee:
* Bitrefill's Thor service at https://www.bitrefill.com/thor-lightning-network-channels/
* Bitrefill's _Thor_ service at https://www.bitrefill.com/thor-lightning-network-channels/
* Lightning To Me at https://lightningto.me/
* _Lightning To Me_ at https://lightningto.me/
* LNBig at https://lnbig.com/
* _LNBig_ at https://lnbig.com/
* Lightning Conductor at https://lightningconductor.net/channels
* _Lightning Conductor_ at https://lightningconductor.net/channels
Creating inbound liquidity is challenging from both a practical and user experience perspective. Inbound liquidity does not happen automatically, so you have to find ways to build it for your node. This asymmetry of payment channels is also not intuitive - after all in most payment systems you get paid first (inbound) before you pay others (outbound).
Creating inbound liquidity is challenging from both a practical and user experience perspective. Inbound liquidity does not happen automatically, so you have to find ways to build it for your node. This asymmetry of payment channels is also not intuitive. In most other payment systems you get paid first (inbound) before you pay others (outbound).
The challenge of creating inbound liquidity is most noticeable if you are a merchant or sell your services for Lightning payments. In that case, you need to be vigilant to ensure that you have enough inbound liquidity to be able to continue to receive payments. What if there is a surge of buyers on your store, but they can't actually pay you because there's no more inbound capacity?
The challenge of creating inbound liquidity is most noticeable if you are a merchant or sell your services for Lightning payments. In that case, you need to be vigilant to ensure that you have enough inbound liquidity to be able to continue to receive payments. What if there is a surge of buyers on your store, but they can't actually pay you because there is no more inbound capacity?
In the future these challenges can be partially mitigated by the implementation of dual-funded channels, which are funded from both sides and offer balanced inbound and outbound capacity. This could also be mitigated by more sophisticated autopilot software, which could request and pay for inbound capacity as needed.
In the future these challenges can be partially mitigated by the implementation of dual-funded channels, which are funded from both sides and offer balanced inbound and outbound capacity. The burden could also be mitigated by more sophisticated autopilot software, which could request and pay for inbound capacity as needed.
Ultimately, however, Lightning users need to be strategic about channel management to ensure that sufficient inbound capacity is available to meet their needs.
Ultimately, Lightning users need to be strategic and proactive about channel management to ensure that sufficient inbound capacity is available to meet their needs.
==== Closing channels
As discussed earlier in the book, Mutual Close is the preferred way of closing a channel, however there are instances where a Force Close is neccessary.
As discussed earlier in the book, a _Mutual Close_ is the preferred way of closing a channel. However, there are instances where a _Force Close_ is neccessary.
Some examples:
* Your channel partner is offline and cannot be contacted to initiate a mutual close
* Your channel partner is online, but is not responding to requests to initiate a mutual close
* Your channel partner is online, and your nodes are negotiating a mutual close, but they become stuck and cannot reach a resolution.
* Your channel partner is offline and cannot be contacted to initiate a mutual close.
* Your channel partner is online, but is not responding to requests to initiate a mutual close.
* Your channel partner is online and your nodes are negotiating a mutual close, but they become stuck and cannot reach a resolution.
==== Re-balancing channels
In the course of transacting and routing payments on Lightning, the combination of inbound and outbound capacity can become unbalanced.
In the course of transacting and routing payments on Lightning, the combination of inbound and outbound capacities can become unbalanced.
For example, if one of your channel partners is frequently routing payments through your node, you will exhaust the inbound capacity on that channel, while also exhausting the outbound capacity on the outgoing channels. Once that happens, you can no longer route payments through that route.
There are many ways to re-balance channels, with different advantages and disadvantages. One way is to use a submarine swap (e.g. Loop-out), as described previously in this chapter. Another way to re-balance is to wait for routed payments that flow in the opposite direction. If your node is well connected, when a specific route becomes exhausted in one direction, the opposite-direction route becomes available. Other nodes may "discover" that opposite-direction route and use it as part of their payment path, re-balancing the funds again.
There are many ways to re-balance channels, each with different advantages and disadvantages. One way is to use a _submarine swap_ (e.g. +Loop-Out+) as described previously in this chapter. Another way to re-balance is to simply wait for routed payments that flow in the opposite direction. If your node is well connected, when a specific route becomes exhausted in one direction, the same route becomes available in the opposite direction. Other nodes may "discover" that route in the opposite direction and start using it as part of their payment path, thereby re-balancing the funds again.
Another way to re-balance channels is to purposely create a _circular route_ that sends a payment from your node to your node, via the Lightning Network. By sending a payment out on a channel with large local capacity and arranging the path so that it returns to your node on a channel with large remote capacity, both of those channels will become more balanced. An example of a circular route re-balancing strategy can be seen in <<circular-rebalancing>>.
A third way to re-balance channels is to purposefully create a _circular route_ that sends a payment from your node back to your node, via the Lightning Network. By sending a payment out on a channel with large local capacity and arranging the path so that it returns to your node on a channel with large remote capacity, both of those channels will become more balanced. An example of a circular route re-balancing strategy can be seen in <<circular-rebalancing>>.
[[circular-rebalancing]]
.Circular route re-balancing
@ -838,35 +890,37 @@ Running a Lightning node allows you to earn fees by routing payments across your
Nodes compete for routing fees by setting their desired fee rate on each channel. Routing fees are set by two parameters on each channel: a fixed _base fee_ that is charged for any payment and an additional variable _fee rate_ that is proportional to the payment amount.
When sending a Lightning payment, a node will select a path so as to minimize fees, minimize hops or both. As a result, a routing fee market emerges from these interactions. There are many nodes that charge very low or no fees for routing, creating downward pressure on the routing fee "market".
When sending a Lightning payment, a node will select a path so as to minimize fees, minimize hops, or both. As a result, a routing fee market emerges from these interactions. There are currently many nodes that charge very low or no fees for routing, creating downward pressure on the routing fee "market".
If you make no choices, your Lightning node will set a default base fee and fee rate for each new channel. The default values depend on the node implementation you use. Routing fees are set as millisatoshi (thousandths of a satoshi) for the base fee and millionths per satoshi for the proportional fee rate. For example, a base fee of 1000 (millisatoshi) and fee rate of 10 (millionths) would result in the following charges for a 100,000 satoshi payment:
If you make no choices, your Lightning node will set a default base fee and fee rate for each new channel. The default values depend on the node implementation you use.
The _base fee_ is set in the unit of _millisatoshi_ (thousandths of a satoshi). The proportional _fee rate_ is set in the unit of _millionths_ and is applied to the payment amount.
The unit of _millionths_ is often abbreviated with _ppm_ (parts per million).
For example, a _base fee_ of 1,000 (millisatoshi) and a _fee rate_ of 1,000 ppm (millionths) would result in the following charges for a 100,000 satoshi payment:
[latexmath]
====
P = 100,000
P = 100,000 satoshi
F_base = 1000 millisatoshi
F_base = 1,000 millisatoshi = 1 satoshi
F_rate = 10/1,000,000 * payment size
F_rate = 1,000 ppm = 1,000/1,000,000 = 1/1,000 = 0.001 = 0.1%
F_total = F_base + F_rate * P
F_total = F_base + ( P * F_rate )
\Rightarrow F_total = 1 satoshi + 100 satoshi
\Rightarrow F_total = 101 satoshi
\Rightarrow F_total = 1 satoshi + ( 100,000/1,000 ) satoshi
\Rightarrow F_total = 1 satoshi + 100 satoshi = 101 satoshi
====
Broadly speaking, you can take one of two approaches to routing fees. You can route lots of payments with low fees, making up for low fees by lots of volume. Or you can choose to charge higher fees, expecting you will route fewer payments. If you choose to set higher fees your node will be selected only when other cheaper routes don't exist. Therefore, you will route less often but earn more per successful routing.
Broadly speaking, you can take one of two approaches to routing fees. You can route lots of payments with low fees, making up for low fees by high volume. Alternatively, you can choose to charge higher fees. If you choose to set higher fees, your node will be selected only when other cheaper routes don't exist. Therefore, you will route less frequently but earn more per successful routing.
For most nodes, it is usually best to leave the default routing fee values, so that your node is competing on a mostly level playing field with other nodes who use the default values.
For most nodes, it is usually best to use the default routing fee values. This way, your node is competing on a mostly level playing field with other nodes who use the default values.
You can also use the routing fee settings to re-balance channels. If most of your channels have the default fees but you want to rebalance a channel, just decrease the fees on that channel to zero or very low rates. Then sit back and wait for someone to route a payment over your "cheap" route and re-balance your channels for you as a side-effect.
You can also use the routing fee settings to re-balance channels. If most of your channels have the default fees but you want to rebalance a particular channel, just decrease the fees on that specific channel to zero or to very low rates. Then sit back and wait for someone to route a payment over your "cheap" route and re-balance your channels for you as a side-effect.
=== Node management
Managing your Lightning node on the command-line is obviously not easy. It gives you the full flexibility of the node's API and the ability to write your own custom scripts to achieve whatever goals you want. But if you don't want to deal with the complexity of the command line and only need some basic node management capabilities, you should consider installing a web-based user interface that makes node management much easier.
Managing your Lightning node on the command-line is obviously not easy. It gives you the full flexibility of the node's API and the ability to write your own custom scripts to satisfy your personal requirements. But if you don't want to deal with the complexity of the command line and only need some basic node management capabilities, you should consider installing a web-based user interface that makes node management easier.
There are a number of competing projects that offer web-based Lightning node management. Some of the most popular ones are described below.
@ -874,22 +928,27 @@ There are a number of competing projects that offer web-based Lightning node man
RTL is web graphical user interface to help users to manage lightning node operations for the three main lightning implementations (LND, c-lightning and Eclair), RTL is an open source project developed by Suheb, Shahana Farooqi and many other contributors. You can find the RTL software here:
_RTL_ is a graphical web user interface to help users manage Lightning node operations for the three main Lightning node implementations (LND, c-lightning, and Eclair). RTL is an open source project developed by Suheb, Shahana Farooqui, and many other contributors. You can find the RTL software here:
https://github.com/Ride-The-Lightning/RTL
Here's an example of RTL's web interface, as provided on the project repository:
Here is an example screenshot of RTL's web interface, as provided on the project repository:
.Example RTL web interface
image::images/RTL-LND-Dashboard.png[]
==== LNDMon
Lightning Labs, the makers of LND provide a web based graphical user interface called +lndmon+ to monitor the various metrics of an LND Lightning node. The lndmon interface only works with LND nodes, and is a read-only interface that does not allow you to manage the node directly (e.g. open channels and make payments). Find lndmon here:
Lightning Labs, the makers of LND provide a web-based graphical user interface called +lndmon+ to monitor the various metrics of an LND Lightning node. +lndmon+ only works with LND nodes. It is a read-only interface for monitoring and as such does not allow you to actively manage the node. It cannot open channels or make payments. Find +lndmon+ here:
https://github.com/lightninglabs/lndmon
=== Thunderhub
A very aestheticaly pleasing web-based graphical user interface similar to RTL but exclusive to LND. It can be used to make payments, rebalance channels and manage the node through a varitey of features. Find +Thunderhub+ here:
https://thunderhub.io
=== Conclusion
As you grow and maintain your node you will learn a lot about the Lightning Network. It is a challenging but rewarding task. Mastering these skills will allow you to contribute to the growth and development of this technology and the Lightning Network itself. You will also gain the ability to send and receive Lightning payments with the greatest degree of control and ease, as your node will be a central part of the network's infrastructure and not just a participant on the edges.
As you maintain your node and gain experiences you will learn a lot about the Lightning Network. Being a node operator is a challenging but rewarding task. Mastering these skills will allow you to contribute to the growth and development of this technology and the Lightning Network itself. You will furthermore gain the ability to send and receive Lightning payments with the greatest degree of control and ease. You will play a central role in the network's infrastructure and not just be a participant on the edges.

@ -46,3 +46,79 @@ Relevant questions to answer:
- How can TLV fields be used to extend the protocol, existing messages, and the onion itself?
- Sidenote that TLV can be used by upcoming Instant Messaging chat apps like `Whatsat`, `Sphinx Chat` or `Juggernaut`
### Feature Bits
#### What is are Feature Bits and why do we need them?
Feature bits, or feature flags, are a string of 1s and 0s that Lightning nodes use to communicate to each other which features and upgrades they have enabled.
But why would they need to do this?
As discussed in earlier chapters, the Lightning Network protocol does not require all nodes to be in agreement on a common ruleset and list of features, which is quite different to the Bitcoin protocol.
If someone wants to introduce a new feature into Bitcoin (such as Replace-by-Fee) then either all nodes will need to accept this feature or the feature needs to be backwards-compatible.
However, if a new feature is introduced into the Lightning Network, Lightning users don't need to wait for the rest of the network to upgrade.
They can start using the new feature immedietely.
Even if that feature is still in development, they can implement it as long as they can find other users willing to implement the feature along with them
footnote:[The Lightning Network itself was famously put into use before it's official "launch". Despite LN developers warning users that the software was still in beta and had bugs, users around the world set up their own nodes and used the software recklessly].
One example of a feature would be multi-part payments, discussed in the chapter on Path-Finding.
Despite being a feature still in development at the time of writing, it was already deployed by some nodes.
Given the inherent freedom in the Lightning Network's design there will never be a global consensus on the Lightning Network as to which features are supported and which aren't.
Some nodes may support multi-part payments, some may not, and some may never decide to support them.
As such, nodes need of a way of signalling to each other which features they support and which they do not.
They do so using pairs of 1s and 0s called Feature Bits.
#### How do Feature Bits work?
Whenever nodes communicate with each other, whether through invoices or other methods, a part of that message is reserved to signal which features the node has enabled.
For example, the `channel_announcement` and `node_announcement` messages described in BOLT #7 have a predefined `features` field reserved for this information.
The `features` field will take the form of a string of paired bits that will look something like this:
[feature-bits-example]
----
00101000001000000000
----
Flags are numbered from the least-significant bit (i.e. from right from left), starting from 0.
Flags are also paired, so that bits 0 and 1 form a pair, 2 and 3 form a pair, and so on.
BOLT #9 contains the full list of which digits stand for which features
footnote:[https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md].
An odd-numbered bit pair (01) communicates that the feature is backwards-compatible.
An even-numbered bit pair (10) communicates that the feature is mandatory.
The rule of thumb is: "it's ok to be odd".
Using BOLT #9 we can break down the above string as follows:
[[feature-bits-breakdown]]
.Breakdown of a feature bit string
[options="header"]
|===
| Bit Number | Feature | Feature Bits | Status
| 0/1 | `option_data_loss_protect` | 00 | Not enabled
| 2/3 | `initial_routing_sync` | 00 | Not enabled
| 4/5 | `option_upfront_shutdown_script` | 00 | Not enabled
| 6/7 | `gossip_queries` | 00 | Not enabled
| 8/9 | `var_onion_optin` | 01 | Enabled (Backwards-Compatible)
| 10/11 | `gossip_queries_ex` | 00 | Not enabled
| 12/13 | `option_static_remotekey` | 00 | Not enabled
| 14/15 | `payment_secret` | 01 | Enabled (Backwards-Compatible)
| 16/17 | `basic_mpp` | 01 | Enabled (Backwards-Compatible)
| 18/19 | `option_support_large_channel` | 00 | Not enabled
|===
If Alice sees this string in a node announcement message from Bob's node, then she knows from bits 16 and 17 that Bob's node supports multi-part payments.
And because the pair is odd, Alice knows that the feature is backwards-compatible.
If Alice also has multi-part payments enabled, then Alice and Bob can make use of this feature.
If Alice does not have multi-part payments enabled, she can simply ignore this and get on with her life.
She could still open a channel with Bob without having the feature enabled herself.
However, if the feature bits were even then the feature would be mandatory.
If Alice did not also have this feature enabled, she would have to find another node to open a channel with.
Alice also knows from bits 18 and 19 that Bob does not have large channels enabled.
If she would like to open a large channel, then she would have to find someone else who has large channels enabled to open it with.
In this way, upgrades and new features can be rolled out on the Lightning Network in an asynchronous bottom-up way.
Users can enable the features they want when they are ready to do so.
Power users can use and test features without waiting for them to be formally released, and more conservative users are not pressured into using a new feature before they are comfortable to do so.
Users can simply signal to each other which features they support, and even if they do not agree on the feature set, they can still connect and transact as long they agree on all mandatory features.

@ -2,6 +2,7 @@
* How path finding works in the network
Relevant questions to answer:
* What is packet switching? What is circuit switching? Which one does LN use today?
* In the abstract what is path finding?
* What is dijkstra's? What modifications need to be made to apply it to this domain?
@ -17,73 +18,80 @@ Relevant questions to answer:
Payments on the Lightning Network are forwarded along a path of channels from one participant to another.
Thus, a path of payment channels has to be selected.
If we knew the exact channel balances of every channel we could easily compute a payment path using any of the standard path finding algorithms taught in any computer science program.
Actually when we consider multipath payments it is rather a flow problem than a path finding problem.
If we knew the exact channel balances of every channel, we could easily compute one or more payment paths using any of the standard path finding algorithms taught in good computer science programs.
Actually, when we consider multipath payments, it is rather a flow problem than a path finding problem.
Since flows consist of several paths we conveniently talk about path finding.
With exact information about channel balances available we could solve those problems in a way to optimize the fees that would have to be paid by the payer to the nodes that kindly forward the payment.
However, as discussed the balance information of all channels is and cannot be available to all participants of the network.
Thus, we need to have one or more innovative path finding strategy.
If exact information about channel balances were available, we could solve those problems in a way as to minimize the fees that would have to be paid by the payer to the nodes forwarding the payment.
However, as discussed, the balance information of all channels cannot be available to all participants of the network.
Thus, we need to have one or more innovative path finding strategies.
These strategies must relate closely to the routing algorithm that is used.
As we will see in the next section, the Lightning Network uses a source based onion routing protocol for routing payments.
This means in particular that the sender of the payment has to find a path through the network.
As we will see in the next section, the Lightning Network uses a source-based onion-routing protocol for routing payments.
In such a protocol it is the responsibility of the sender, i.e. payer, to find a path through the network.
With only partial information about the network topology available this is a real challenge and active research is still being conducted into optimizing this part of the Lightning Network implementations.
The fact that the path finding problem is not fully solved for the case of the Lightning Network is a major point of criticism towards the technology.
The fact that the path finding problem in the Lightning Network is not fully solved is a major point of criticism towards the technology.
The path finding strategy currently implemented in Lightning nodes is to probe paths until one is found that has enough liquidity to forward the payment.
While this is not optimal and certainly can be improved, it should be noted that even this simplistic strategy works well.
While this is not optimal and leaves ample room for improvements, it should be noted that even this simplistic strategy works well.
This probing is done by the Lightning node or wallet and is not directly seen by the user of the software.
The user might only realize that probing is taking place if the payment is not going through instantly.
The algorithm currently also does not necessarily result in the path with the lowest fees.
The user might suspect that probing is taking place if the payment is not going through instantly.
The current algorithm also does not necessarily result in the path with the lowest fees.
=== What is "Source-Based" routing and why does the Lightning Network use it?
Source-based routing is a method of path-finding where the sender (i.e. the source) plans the path from itself, through the intermediary nodes, and finally to the destination.
Once a path has been selected, the sender sends the payment to the first intermediary node, who sends it to the second intermediary node and so on, until it reaches the destination.
While a payment is in-flight along a path, the path typically does not get changed by any of the intermediary nodes, even if a shorter path or a cheaper path (in terms of routing fees) exists.
_Source-based routing_ is a method of path-finding where the sender, i.e. the source, plans the path from itself, through the intermediary nodes, to the final destination.
Once a path has been found and selected, the sender sends the payment to the first intermediary node, who sends it to the second intermediary node, and so on until it reaches the destination.
While a payment is traveling along a path, the path typically does not get changed by any of the intermediary nodes, even if a shorter path or a cheaper path (in terms of routing fees) exists.
The Lightning Network uses source-based routing at the time of writing in order to protect user privacy.
As discussed in the chapter on Onion Routing, the intermediary nodes transmitting the payment are not aware of the full path of the payment; they only know the node they received it from and the node they are sending it to.
One of the reasons the Lightning Network uses source-based routing is to protect user privacy.
As discussed in the chapter on _Onion Routing_, the intermediary nodes transmitting the payment are not aware of the full path of the payment. They only know the node they received it from and the node they are sending it to.
We also cannot expect the destination to find a path.
The destination, i.e. the payment recipient, is less able to find a good path.
Even if it specifies a path in the invoice, that path may no longer be viable by the time the invoice is paid, which could be several minutes or several days later.
The recipient can, however, specify "routing hints" in the invoice that may assist the sender in finding a possible path.
Furthermore, source-based routing comes with some inherent drawbacks.
The sender chooses the path based on their current understanding of the topological map of the Lightning network.
As discussed in previous chapters, this map is necessarily incomplete; the sender may not be aware of all the channels, and even if they are they will almost certainly not know the latest balances in each of the channels.
And even if the sender did have a complete topological map at one point in time, the balances of channels change with every payment, and so in a short space of time the map would become obsolete.
The standard path finding mechanism with source based onion routing that is implemented in all Lightning Network implementations is the following:
. Select an arbitrary path of payment channels which connects sender and receiver of the payment and for which all channels have a capacity of at least the payment amount and accept HTLCs of this amount.
. Construct the onion from destination to sender according to the meta data (basefee, feerate, CLTV delta) of the channels.
. Send out the onion and see if the payment settles by nodes sending back preimages or if the payment fails.
. If the payment fails use this knowledge to select a different path by starting at step 1.
This means that with every attempted payment nodes actually probe the network and will also learn some information about how balances are distributed.
Implementations will usually prioritise cheaper paths or exclude channels which recently have failed.
The recipient can, however, specify "routing hints" in the invoice to assist the sender in finding a possible path.
On the other hand, source-based routing comes with some inherent drawbacks.
The sender chooses the path based on its current understanding of the topological map of the Lightning network.
As discussed in previous chapters, this map is necessarily incomplete. The sender cannot be aware of all the channels. And even if it is aware of them, it will not always know their latest balances.
The balances of channels change with every payment. Consequently, any topological knowledge becomes obsolete in a short space of time.
The standard path finding mechanism in source-based onion-routing that is implemented in all Lightning Network implementations is the following:
. Given the limited local topological knowledge the sender tries to find one or more routing paths.
. Select an arbitrary path of payment channels which satisfies 3 conditions:
* path connects sender and receiver of the payment,
* all channels on path have a presumed capacity of at least the payment amount,
* all channels on path accept HTLCs of the payment amount.
. Construct the "onion" from destination to sender according to the meta data of the channels (base fee, fee rate, CLTV delta).
. Send out the "onion" and expect one of two possible results returned:
* Preimages are returned by nodes if the payment settles successfully
* Error is returned if the payment fails.
. If the payment settles, the sender updates its topological knowledge based on this new information for future payments. The algorithm terminates.
. If the payment fails, the sender updates its topological knowledge based on this new information. It then selects a different path and starts the process again from the beginning.
This means that with every attempted payment nodes actually probe the network and also learn some information about how balances are distributed.
Implementations will usually prioritise cheaper paths or exclude channels which have recently failed.
In that sense the selection is not completely arbitrary.
Still even with such heuristics in place it could still be considered as a random process or random walk through the channel graph.
There can be several reasons why the payment may fail along the way.
For example one of the nodes becomes unreachable, doesn't have the channel balance, can't accept new htlcs, has updated its fees to a higher amount, or the channel is closed in the interim.
Furthermore, there is no guarantee that the route chosen was the cheapest in terms of fees, or if a shorter path existed.
As at the time of writing, this is a design trade-off made to protect user privacy.
=== Paths are constructed from Destination to Source
Let us assume our standard example in which Alice wants to send a payment of 100k satoshi on a path via Bob and Wei to Gloria.
The Path obviously looks like (Alice)-->(Bob)-->(Wei)-->Gloria.
However Bob and Wei will charge routing fees to forward the onion.
As you already know nodes can charge two types of fees.
First the base fee that will be charged for any successfull forwarding and settlement of and htlc.
This fee is constant and does not depend on the amount that the node is supposed to forward.
Additionally nodes might charge a freerate.
The name rate alredy indicates that this fee depends on the amount that a node is supposed to forward.
Let us for the simplicity of assume that the feerate of Bob and Wei is very expensive with 1% for Bob and 2% for Wei.
However Bob and Wei will not take a base fee to keep things simple in our example.
If Alice constructs the Onion she has to include the routing fees as the differnce of the incoming htlc and the outgoing htlc.
Let us assume she falsely computes the following to construct the onions with the routing fees.
Even with such primitive heuristics in place it could still be considered a random process or a random walk through the channel graph.
There can be several reasons why a payment may fail along the way.
Reasons for failure include: a routing node became unreachable, a routing channel no longer has the required balance, a routing node doesn't accept new HTLCs, the owner of a channel increased the channel fees, or the channel was closed in the interim.
Furthermore, there is no guarantee that the route chosen was the cheapest in terms of fees or the shortest in terms of channels involved.
At the time of writing this book, this is a design trade-off made to protect user privacy.
=== Paths are constructed from destination to source
Let us use our standard example in which Alice wants to send a payment of 100k satoshi on a path via Bob and Chan to Dina.
The _path_ obviously looks like (Alice)-->(Bob)-->(Chan)-->Dina.
Bob and Chan will charge routing fees to forward the _onion_.
As you already know, nodes can charge two types of fees.
First, the _base fee_ will be charged for any successful forwarding and settlement of an HTLC.
This fee is constant and independent of the amount that the node is forwarding.
Secondly, nodes might charge a _fee rate_ which is proportional to the forwarded amount.
For simplicity assume that the fee rate of Bob and Chan is expensive with 1% for Bob and 2% for Chan.
For simplicity furthermore assume neither Bob nor Chan take a base fee.
When Alice constructs the onion she has to include the routing fees as the difference of the incoming HTLC and the outgoing HTLC.
Let us assume she computes the routing fees for the onion incorrectly.
Alice knows that 1% of 100k satoshi is 1k satoshi which she belives she should include in Bob's onion.
Similarly she knows that 1% of 100k satoshi is 2k satoshi which she belives she should include in Wei's onion.
She would find out that Bob would not forward the onion, if she believed that she would have to pay a total of 3k satoshi and construct an onion that looks like this:
Similarly she knows that 2% of 100k satoshi is 2k satoshi which she belives she should include in Chan's onion.
An inexperienced Alice would incorrectly believe her total fee to be 3k satoshi. But she is wrong.
Look at the incorrect onion from our naive Alice. Bob would reject this onion.
----
"route": [
@ -92,17 +100,19 @@ She would find out that Bob would not forward the onion, if she believed that sh
"channel": "357",
"direction": 1,
"satoshi": 103000,
"forward": 102000,
"dealy": 187,
},
{
"id": "Wei",
"id": "Chan",
"channel": "74",
"direction": 1,
"satoshi": 102000,
"forward": 100000,
"dealy": 183,
},
{
"id": "Gloria",
"id": "Dina",
"channel": "452",
"direction": 0,
"satoshi": 100000,
@ -113,188 +123,204 @@ She would find out that Bob would not forward the onion, if she believed that sh
----
The reason for Bob to not forward the onion is that he expects the incoming amount to be 1% larger then the amount he is supposed to forward.
Thus he would like to have an incoming ammount of `103020` satoshi which is 20 satoshi more than Alice sent him.
According to his fee schedual Bob will have to reject the Onion.
If Alice constructed the onion from she would have computed 1% of the to forward amount correctly as 1% from 102k satoshi which is 1020 sat.
Adding 1020 to the 102000 satoshi that Wei needs to have on his incoming channel will result in the right value of 103020 satoshi that Bob requires.
As the routing fees can increase the amount that is being forwarded even beyond the capacity of small channels it makes sense to start the construction of the onion and the pathfinding from the destination to the sender.
Thus he would like to receive an incoming ammount of `103020` satoshi (102000 + 1%) which is 20 satoshi more than our uninformed Alice actually sent him.
According to Bob's fee schedule Bob will reject this onion.
If Alice constructed the onion from the destinatin towards the source, she would have started with 100k satoshi for Dina.
In the next step she would have added Chan's 2% fee to compute 102k for Chan's input.
In the last step she would have applied Bob's fee (1%) to 102k to derive 102k + 1020 satoshi.
That makes a total of 103,020 satoshi that she needs to send to Bob.
As the routing fees can increase the amount that is being forwarded even beyond the capacity of small channels, it makes sense to start the construction of the onion and the path finding at the destination and work from the destination back towards the sender.
[NOTE]
====
While onions are also constructed from inside to outside and thus start with the destination this is not the reason why pathfinding has to start with the destination node.
Onions are constructed from the inside to the outside. Hence, onions are built starting with the destination.
However, this is not the reason why path finding has to start with the destination node.
====
=== Fundamentals about path finding
Finding a path through a graph is a problem modern computers can solve rather efficiently.
Mostly developers choose bredth first search (if the edges are all of equal weight) or the Dijkstra Algorithm in cases where the edges are not of equal weight.
In our case the weights of the edges could be the routing fees and only edges will be included where the capacity is larger than the amount that is to be sent.
In this basic form pathfinding on the lightning network is very simple and straight forward.
However as we have already discussed in the introduction channel balances cannot be shared with every participant every time a payment takes place as the system would not scale.
Thus our easy computer science problem for which we know a solution turns into a rather complex problem.
We now have to solve a path finding problem with only partial knowledge.
For example we know which edges might be able to forward a payment because their capacity seems big enough but we can't know it for sure
unless we try it out or ask the channel owners directly.
Even if we where able to ask the channel owners directly their balance might change by the time we have asked others, computed a path, constructed an onion and send it along.
Thus we do not only have partial information but the information we have is highly dynamic and might change before we can use it.
One general observation that everyone can easily make is that if every node along a path is able to forward a certain amount of satoshis these nodes will also be able to forward a lower amount of satoshis.
This is why many people intuitively belive that multipath payments might be a good strategy.
Instead of finding one path where every node owns a large amount of liquidity the task is split into smaller ones.
Another reason is of course that the sender of a payment might just not have the amount they wish to send in one single channel but split over several channels.
Developers mainly choose breadth-first search if the edges are all of equal weight.
In cases where the edges are not of equal weight the Dijkstra Algorithm is used.
In our case the weights of the edges could represent the routing fees.
Only edges with a capacity larger than the amount to be sent will be included in the search.
In this basic form pathfinding in the Lightning network is very simple and straight forward.
However, as we have already discussed in the introduction, channel balances cannot be shared with every participant every time a payment takes place as this would prevent scaling the network.
This turns our easy theoretical computer science problem into a rather complex real-world problem.
We now have to solve a pathfinding problem with only partial knowledge.
For example, we suspect which edges might be able to forward a payment because their capacity seems big enough.
But we can't be certain unless we try it out or ask the channel owners directly.
Even if we were able to ask the channel owners directly, their balance might change by the time we have asked others, computed a path, constructed an onion and send it along.
Not only do we have soley limited information but the information we have is highly dynamic and might change at any point in time without our knowledge.
One general observation that everyone can easily make is that if every node along a path is able to forward a certain amount of satoshis, these nodes will also be able to forward a lower amount of satoshis.
This is why many people intuitively believe that multipath payments might be a good strategy.
Instead of finding one path where every node has a large amount of liquidity the task is split into smaller ones.
Another reason is of course that the sender of a payment might just not have the amount they wish to send available in one single channel but distributed over several of his channels.
We leave it to later sections of this chapter to discuss the strengths and weaknesses of multipath payments.
However we note that multi path payments are equivalent to finding a flow between the source and the destination.
While finding flows in a graph with full knowledge that is static is computationally a little bit more heavy than computing a shortest path it still seams to be a feasable problem.
Given the reality of the Lightning Network and the fact that we do not need to compute a max flow we currently do not know if the problem is more or less difficult as finding a path.
It seems to be about equally difficult and the problems are somewhat connect as we will see in the following sections.
=== Probing based path finding algorithm on the Lightning Network
As discussed in order to reliably find a path nodes would need to know the balance of remote payment channels and the balances would have to be static.
As both is not given nodes currently use a probing based algorithm.
We simply note that multipath payments are equivalent to finding a flow between the source and the destination.
Finding flows in a static graph with full knowledge is computationally marginally more expensive than computing a shortest path.
On the other hand, given the dynamic reality of the Lightning Network and the fact that we do not need to compute a maximum flow, it is currently not known if the flow problem is more or less difficult than finding a path.
Both problems seem to have about the same difficulty and the problems are partially related as we will see in the following sections.
=== Probing-based pathfinding algorithm on the Lightning Network
In order to deterministically find a path nodes would need to know the balances of remote payment channels and these balances would have to be static.
As this is not the case in the Lightning Network, nodes use a probing-based algorithm.
In its most basic form the algorithm works as follows:
. Select a random path to the destination node
. Construct and send the onion
. wait for the response of the onion
. If response == preimage -> success
. If response == feilure -> start over from step one.
. If response is a valid preimage, then routing was successful and the algorithm terminates.
. If response is a failure notification, then start over from step 1.
Nodes will use various sources of information to improve the selection of a random path.
The main source of information is the gossip protocol.
From the gossip protocol a node learns which other nodes exist and which channels have been opened.
This will basically provide a network view that can be used to run graph algorithms that generate plausible paths.
For example a breadth first seach traversal.
The graph algorithm will usually be constrained to channels that have at least the capacity of the amount to be sent.
In practice due to channel reserve and the assumption that the capacity in the channel will not be sitting completely on one side it is saver to prefer larger channels.
One fitting algorithm is the breadth-first seach traversal.
The graph algorithm will usually be constrained to channels whose capacity exceeds the payment amount.
In practice, due to channel reserve and the assumption that the capacity in the channel will not be sitting completely on one side, it is smarter to prefer larger channels.
The second source of information is the blockchain itself.
If channels are closed this is not announced via the gossip protocol.
However as the funding transaction is encoded by the short channel id of the channel and as it will be spent if the channel is closed nodes have to use this information to update their knowledge about the network of channels.
Channel closings are not announced via the gossip protocol.
However, as the funding transaction is encoded by the short channel id of the channel and as it will be spent on closing the channel, nodes can use this on-chain information to update their knowledge about the network of channels.
Another source of information are the past payments themselves.
Past payments form a third source of information.
Onions can return with errors.
Knowing for example that the third hop along a path returns an error means that the first two channels had enough balance and that the third channel - depending on the error - did not have enough balance.
Such edges can be removed from the set of edges similarly to the edges that do not have enough capacity.
Similarly nodes could use such information from previous payment attempts.
It is important that nodes are carefull with this data.
As the capacity information of channels from the gossip protocol and blockchain data is verifiably correct the data from our third source of information can be incorrect.
Nodes might just send an error back because they do not want to reveal balance information.
Also the data might just change over time as the balances in the lightning network are not static and changing with every payment attempt that is being made.
Thus nodes should only use such data if it is not to far in the past or use it only with a certain confidence.
The fourth source of information that the node will use are the routing hints in the BOLT 11 invoice.
Remember that a regular payment process starts with the person who wants to receive money coming up with a random secret and hashing it as the payment hash.
Knowing for example that the third hop along a path returns an error of _insufficient balance_ means that the first two channels had enough balance and that the third channel did not have enough balance.
In general, edges with errors can be removed from the set of edges similarly to the edges with insufficient capacity.
Nodes can accumulate knowledge and update their knowledge with every failed or successful payment attempt.
It is important that nodes are careful with this data.
As the capacity information of channels from the gossip protocol and the blockchain data are verifiably correct, the data returned in failed onions can be incorrect.
Nodes might simply send an error back because they do not want to reveal balance information.
Besides, channel data continuously changes over time as the Lightning Network is very dynamic.
This implies that nodes should only use such data if it is not too old or use it only with limited confidence.
As time advances this information becomes stale and outdated and the confidence in this data diminishes.
The fourth source of information that the node can use are the routing hints in the BOLT 11 invoices.
Remember that a regular payment process starts with the person who wants to receive money producing a random secret and hashing it to derive the payment hash.
This hash is usually transported to the sender via an invoice.
Invoices usually contain some meta data and in particular routing hints.
This is necessary if the person who wants to be paid does not have announced channels. In that case it will speciefie some unannounced channels within the invoice.
Otherwise the payer would not even be able to find a path to the "hidden" node.
Routing hints might also be used by the receiving node to indicate which public channels have enough inbound capacity for the payment and thus the ability to receive funds.
In general the further away from the originating peer the payment goes the more likely it becomes to select a channel with insufficient balance.
Thus indicating on which channels a node wishes to receive funds would actually be quite nice for the sender.
Invoices typically contain some meta data including some routing hints.
This is imperative if the person who wants to be paid does not have announced channels. In that case some unannounced channels will be specified within the invoice.
Otherwise the payer would not even be able to find a path to the "hidden" destination node.
Routing hints might also be used by the receiving node to indicate which public channels have enough inbound capacity to forward the payment.
In general, the longer a payment path is, the more likely it becomes that a channel with insufficient balance is selected.
Thus, receiving hints from the receiver indicating on which channels it wishes to receive funds is definitely helpful for the sender.
=== Improvements on Source based onion routing
=== Improvements on source-based onion-routing
The probing based approach that is used in the Lightning Network has several flaws.
Sending out an onion usually takes a certain amount of time.
The time depends on how many hops the onion is supposed to be forwarded and of course on the speed of nodes processing the onion and the topology on the web.
In the following diagram you can see how the time for onions to return in general increase with the amount of hops that the onion has encoded.
The probing-based approach that is used in the Lightning Network has several shortcomings.
Sending out an onion takes a certain amount of time.
The time depends on how many hops the onion is supposed to be forwarded, on the speed of nodes processing the onion, and on the topology on the network.
In the following diagram you can see how the round-trip time for onions in general increases with the amount of hops that the onion has encoded.
[[pathfinding-probing]]
.Research showing the times that onions take to return depending on the distance (CC-BY-SA Tikhomirov, Sergei & Pickhardt, Rene & Biryukov, Alex & Nowostawski, Mariusz. (2020). Probing Channel Balances in the Lightning Network.)
.Research shows that the onion round-trip time depends on the distance (CC-BY-SA Tikhomirov, Sergei & Pickhardt, Rene & Biryukov, Alex & Nowostawski, Mariusz. (2020). Probing Channel Balances in the Lightning Network.)
image:images/probingtimes.ppm[]
Of course this diagram was just a snapshot from an experiment in early 2020 and things might change.
We can learn from the Diagram that payments can take several seconds while the node tries to probe several paths.
This is due to the fact that the fact that single onions can easily take a few seconds to return and a sender might have to send several onions in a row while probing for a sucessfull path.
in generall this will still be much faster than waiting for confirmations on a bitcoin block but it is not sufficient in an environment where payments need to settle fast.
If people stand in a line at the cash register for their groceries this would be such a setting.
Thus lightnign developers
==== Probing based improvements
The last source of information that nodes could use is to probe the network themselves.
Instead of making the actual payment nodes could send out many fake payments which are onions to a random payment hash.
Given the properties of the hashfunction it is save to assume that noone would know the preimage.
In that sense the payment will only fail at the destination and nodes can learn a lot about the balances.
Of course this produces spam and heavy load on the network and it is not recommended that nodes do this.
However participants cannot really be stopped from doing this.
unless channel partners see a lot of traffic coming on a channel which always fails and never settles.
In this case channel partners could decide to close the channel.
This diagram is just a snapshot from an experiment in early 2020 and results might change.
We learn from the diagram that payments can take several seconds while the node probes several paths.
This is due to the fact that a single onion can easily take a few seconds to return and a sender might have to send several onions sequentially while probing for a successful path.
In comparison, this will still be much faster than waiting for confirmations on a Bitcoin block; but it is not performant enough in an environment where payments need to settle fast.
People standing in a line at the grocery store cash register prefer not to wait several seconds.
Thus, Lightning developers have come up and implemented the following improvements to the probing algorithms.
We are also hopeful that additional improvements and optimizations can be discovered in the future.
==== Improvements to probing
Nodes ordinarily probe the network when making a payment. But nothing prevents them from probing the network periodically.
Instead of making a real payment, nodes could send out one or multiple _fake_ payments.
A fake payment is nothing but an onions with a random payment hash.
Given the properties of the hash function, it is save to assume that nobody knows the preimage.
If the payment amount is small enough, a fake payment will fail at the destination and this allows the sending node to learn about the balances on the path.
There are clear downsides to this approach.
It produces spam and heavy network load and therefore this behaviour is discouraged.
However, participants cannot easily be stopped from doing this.
Channel partners can detect this type of abuse by observing frequent payments that always fail.
As punishment channel partners can decide to produce errors right away without providing balance information
or they can decide to close the abused channel.
[Note]
====
We want you to understand that Lightning Network by design does not have perfect privacy.
While a lot of information is not easily accessible every time a path is probed the node learns something about the state of the network at that point in time.
While a lot of information is not easily accessible, every time a path is probed the node learns something about the state of the network at that point in time.
====
We note that one should not send two onions at the same time with the same payment hash for which the recipient knows the preimage.
As long as the onion is being processed and routed the payment is out of controll of the sender.
In case two onions are sent at the same time the recipient could very well release the preimage twice and get paid twice.
That was the reason why probing should be conducted with a fake payment hash.
in that case the sender can probe concurrently as long as the sender has enough funds to pay for all the HTLCs.
However there is a problem.
Assume an onion returns indicating that the payment hash was unknown to the recipient but otherwise the path would have been possible.
The sender would now use this exact path to send the payment with the corrent payment hash.
Meanwhile the balances of some channels along the path might have changed and the path does not exist anymore.
In this case the sender would have to start from the beginning all over again.
Admittedly the risk for this to happen is rather small but there is a chance.
A better way and potential improvement for the future of the Lightning network are stuckless payments.
There is a proposal for a system called stuckless payments that receives high appriciation by developers.
This proposal will probably not be implemented before the lightning network switches from Hashed Timelocked Contracts to Point time locked contracts which won't come before Schnorr Signatures are activated on the Bitcoin Network.
What stuckless payments can do is to give controll back to the sender of an Onion.
Without explaining the details here we just say that the sender can now cancle an onion.
Please note that one should never send two onions at the same time with the same payment hash for which the recipient knows the preimage.
As long as the onion is being processed and routed the payment is out of control of the sender.
In case two onions are sent at the same time, the recipient could very well release the preimage twice and get paid twice.
This is the reason why arbitrary probing should be conducted with a fake, i.e. purely random, payment hash.
With fake payment hashes the sender can probe concurrently as long as the sender has enough funds to pay for all the HTLCs.
Successful probing does not guarantee a following successful payment.
Assume a fake onion returns indicating that the payment hash was unknown to the recipient but otherwise the path has been possible.
The sender now uses the same path to send the payment with the corrent payment hash.
In the interim, the balance of a channel along the path changes rendering the path unworkable.
In this case the sender has to start all over again.
Admittedly the risk for this to happen is rather small but the possibility exists.
A potential improvement has been outlined by a suggested mechanism labelled as _stuckless payments_.
The proposal of _stuckless payments_ received positive feedback from developers.
It is unlikely that the mechanism is implemented before the Lightning Network switches from _Hashed Timelock Contracts_ (HTLCs) to _Point Timelock Contracts_ (PTLCs). PTLCs in turn will only be implemented after _Schnorr Signatures_ are activated on the Bitcoin Network.
Stuckless payments give control back to the sender of an onion.
We don't explain the details here, but stuckless payments empower the sender to cancel an onion.
This is great for redundant and concurrent pathfinding.
The sender could send out several real onions.
The first ones that arrives at the recipient will be settled.
All others will be cancled.
The sender can now send out several _real_ onions without fear of being charged multiple times.
The first onion that arrives at the recipient will be settled.
All others will be canclled.
This increases the usuability of the Lightning Network on several levels.
One advantage is that the sender can try several paths at the same time.
The second advantage is that the path is locked after it is found and until it is settled.
This means that the sender can either cancle the onion or help to release the preimage (as senders have to do with the stuckless payment construction)
In particular the probed path cannot change or used by other routing requests between probing and setting up the htlcs that are used to fullfill the request.
The time for a a successfull payment will reduce drastically.
The distadvante is that the sender has to lock more bitcoin during the path finding process.
Due to timeouts these bitcoin can be locked for a couple of days before they can be used again.
This should not happen too often.
Also it utilizes more resources of other nodes.
The second advantage is that the path is locked, i.e. reserved, after it is found until it is settled.
This means that the sender can either cancel the onion or bring the onion to a successful conclusion.
In particular, the probed path once locked cannot change or be used by other routing requests in the interim between probing and setting up the HTLCs that are used to fulfill the request. The found path remains reserved until cancelled or the payment is successfully completed.
Using stuckless payments the time for a successful payment will reduce drastically.
The distadvantage is that the sender has to lock more bitcoin during the pathfinding process.
Due to timeouts these bitcoin can remain locked for several days before being released again.
Although this should not happen too frequently.
Another drawback is that the execution of this mechanism utilizes more resources of routing nodes.
==== Multipath payments
Everyone can easily make the following observation:
----
Let's say your node has discovered a path along which a certain amount of Satoshis for example 100k could be routed.
Then any onion along that path on the same time with an lower amount of Satoshis would also have been successfull.
One can easily conclude that lower amounts have a higher likelyhood to be routed successfully to the destination than larger amounts.
Let's say your node has discovered a path along which a certain amount of Satoshis can be routed.
If so, then any onion with an smaller amount of Satoshis can also be routed successfully along that path at the given time.
One can conclude that a smaller amount has a higher likelihood to be routed successfully to the destination than a larger amount.
----
Researchers and developers have already tested and confirmed this emperically over and over again.
This supposition ignores some edge cases which we ignore for this discussion. The above observation might not hold true
for small amounts of Satoshis. Certain node operators might not be interested in routing small amounts because they might
consider them as "not profitable enough". Node operators might weigh other node resources against the tiny profit of a
small payment and simply reject payments below a given threshold or minimum. What is "small" and what to reject will
be defined by each operator on its personal preferences.
But for the general case, researchers and developers have already tested this postulate and confirmed it multiple times emperically.
With this assumption in mind it seems natural to split a payment amount and send several smaller payments along various paths.
With if a small payment fails it will be retried and probed just as one would do with a single larger payment.
While the main idea is very easy to understand we want to discuss the details, advantages and disadvantages of this mechanism in the following.
When one of the smaller payments fails it will be retried and probed just as one would do with a single larger payment.
While the main idea is easy to understand, we want to discuss the details, advantages, and disadvantages of this mechanism further.
Usually a receiving node will see an incoming HTLC for a certain payment hash.
If the onion signals that the node is the final recipient and that the amount of the HTLC is less than the one specified in the invoice the node would not accept the HTLC and send back an erring onion.
However with the TLV format of onions a sender can specify the total_amount of the payment which can be bigger than the HTLC.
The recipient can safely accept the HTLC and wait for more HTLCs to arrive.
In this way all parts of the payment will use the same payment hash.
The recipient will only release the preimage if the sum of all incoming HTLCs is at least the speciefied payment amount.
A receiving node will see an incoming HTLC for a certain payment hash.
If the onion signals that the node is the final recipient and if the amount of the HTLC is less than the one specified in the invoice, the node would normally not accept the HTLC and send back an error notification.
However, using the _Total Value Locked_ (TLV) format of onions a sender can specify a total amount of the payment which is bigger than the HTLC.
In the TLV case, the recipient can safely accept the HTLC and wait for more HTLCs to arrive.
All parts of the payment will use the same payment hash.
The recipient will only release the preimage if the sum of all incoming HTLCs is at least the specified payment amount.
[Note]
====
**Multi path or multi part payments?** You might have realized that we named the chapter multipath payments but mentioned in the last paragraph that such a payment consists of several parts.
The protocol specification uses the abbrivation MPP for multi part payments.
This is in fact always correct as all parts could technically - though this would not make much sense - be delivered over the same path.
As we are introducing MPP in the pathfinding section of the book and as they are also used for path finding we take the liberty to also abbriviate multi path payments with MPP.
**Multipath or multipart payments?** You might have noticed that we named the chapter "multipath" payments but mentioned in the last paragraph that such a payment consists of several parts.
The protocol specification uses the abbrivation _MPP_ for _multipart payments_.
Multipath is just a special case of multipart.
Multipart covers all the cases of multipath plus the unusual case where multiple parts use the same path.
For simplicity we take the liberty to also abbriviate multipath payments with MPP.
====
It is important to recognize that a node that forwards HTLCs via onions does not have to bother if the payment is a single payment or one of several multi part payments.
The only node who needs to be ready to accept multi part payments is the receiving node.
In the BOLT 11 invoice there is space for feature bits.
If ia node wishes to accept multipart payments it has to signal this by setting the corresponding feature bit (16 / 17).
If a node wishes to send a multi part payment it can also do so if the receiving node has signaled their willingess to accept such payments.
Currently there is no way for routing nodes to split the payment amount and onion into several parts or merge several incoming HTLCs into a single path.
It is important to recognize that a node that forwards HTLCs does not have to distinguish a single full payment from a partial multipart payment.
Only the receiving node needs to distinguish the two cases. Only the receiver needs to be ready to accept multipart payments.
In the BOLT 11 invoice specification there is a field for _feature bits_.
If a node wishes to accept multipart payments it must signal this by setting the corresponding feature bit (bit 16 of 17).
If a node wishes to send a multipart payment it can do so if the receiving node has signaled their willingess to accept such payments.
Currently there is no mechanism for routing nodes to split the payment amount and onion into several parts or merge several incoming HTLCs into a single onion.
Besides the potentially better chances to find smaller routes the sender might want to use a multipart payment because it does not have enough balance in a single payment channel.
If the channel had enough capacity this could be resolved with a circular rebalancing - which we will discuss in the next section.
@ -352,15 +378,15 @@ It is quite clear that after already one single payment such a 50 - 50 state wou
You can see this in the following graph.
[[rebalancing-2]]
.The Bob - Wei channel becomes now imbalanced
.The Bob - Chan channel becomes now imbalanced
image:images/rebalancing-2.png[]
you can see that after Bob made a payment of 1 million satoshi to Wei the channel balance was shifted.
Bob now has 1.5 million satoshi on the channel and wei has 3.5 million satoshi on the channel.
you can see that after Bob made a payment of 1 million satoshi to Chan the channel balance was shifted.
Bob now has 1.5 million satoshi on the channel and chan has 3.5 million satoshi on the channel.
The balance ratio went from 50/50 to 30/70.
The other 2 channels however styed with 50/50.
Wei decides that he wants to have a 50/50 channel with Bob.
Chan decides that he wants to have a 50/50 channel with Bob.
There are 3 ways of how he can achieve this.
. He can send back 1 milion satoshi to Bob
@ -370,21 +396,21 @@ There are 3 ways of how he can achieve this.
Sending back the money would be quite expensive and does not seem to be a realistic option.
Using an onchain swapping service after every payment to rebalance channels seems also problematic.
The entire idea of creating the Lightning Network was to have less on chain transaction and be able to send money between people without the necessity to do on chain transactions.
Thus there is only the last option which means that Wei could move the money from the Bob-Wei channel via the Bob-Erica channel to hhis Erica-Wei channel.
Thus there is only the last option which means that Chan could move the money from the Bob-Chan channel via the Bob-Erica channel to hhis Erica-Chan channel.
[[rebalancing-4]]
.Wei tries to rebalance the Bob-Wei channel in the unbalanced network via a circular onion of 1 mio Satoshi.
.Chan tries to rebalance the Bob-Chan channel in the unbalanced network via a circular onion of 1 mio Satoshi.
image:images/rebalancing-4.png[]
The problem in the new network can easily be seen on the next picture.
While the Bob-Wei channel now becomes 50/50 again all the other channel turned into a 30/70 split ratio.
While the Bob-Chan channel now becomes 50/50 again all the other channel turned into a 30/70 split ratio.
[[rebalancing-5]]
.Rebalancing one channel produces imbalanced other channels
image:images/rebalancing-5.png[]
An interesting oversvation about this rebalancing can be made though!
After the payment and the rebalancing it looked like Bob initially had sent Money not via the Bob-Wei channel but via the path along Erica.
After the payment and the rebalancing it looked like Bob initially had sent Money not via the Bob-Chan channel but via the path along Erica.
[[rebalancing-6]]
.Rebalancing is equivalent to having selected a different payment path to begin with.
@ -397,7 +423,7 @@ However this is not true!
When rebalancing comes into place we can use the local knowledge of the distribution of balances that nodes might have to help with selection of paths and finding a total payment path / multi path or flow.
We will explore this idea a little bit more in the upcoming section about JIT routing.
Remember in our example after Bob has paid Wei Bob had a total amount of 4 million satoshi, Wei had a total of 6 million satoshi and Erica still had 5 million satoshi as before.
Remember in our example after Bob has paid Chan Bob had a total amount of 4 million satoshi, Chan had a total of 6 million satoshi and Erica still had 5 million satoshi as before.
Of course it would be possible to have payment channels between these three people with that distribution of funds so that everyone has 50% of the capacity on their side of the payment channel.
[[rebalancing-7]]
@ -458,9 +484,9 @@ The just in time Routing scheme has 2 major advantages over source based routing
. It increases the privacy of channels. If nodes that do not have sufficient liquidity return the onions an attacker can use that behavior to probe for the channel balance. However if nodes rebalance their channels they will always be able to forward the payment and protect themselves from probing attacks.
. More importantly it resembles multipart payments in which the splitting of the payment is not been decided by the sender who would not know how balances remotely are distributed but the splitting would be achieved by the routing node that knows its local topology.
Let us elaborate on the second point and take the example in which Bob was supposed to forward the onion from Alice to Wei but does have enough liquidity on the channel with Wei.
Let us elaborate on the second point and take the example in which Bob was supposed to forward the onion from Alice to Chan but does have enough liquidity on the channel with Chan.
If Bob now does a cebalancing operation through Erica and is able to afterwards forward the payment along to Bob he has effectively split the payment at his node to flow along two paths.
One part flows directly to Wei and the other part takes the path over Erica to Wei.
One part flows directly to Chan and the other part takes the path over Erica to Chan.
It is obvious that splitting a payment at the node that can't forward the entire payment is much more reliable and effective than letting the sender decide how to split a payment and into which amounts.
We thus can see that with the help of JIT-Routing rebalancing and multipart payments are actually not so different concepts and ideas.

@ -175,6 +175,8 @@ Many contributors offered comments, corrections, and additions to the book as it
Following is an alphabetically sorted list of all the GitHub contributors, including their GitHub IDs in parentheses:
* 8go (@8go)
* Aaqil Aziz (@batmanscode)
* Alexander Gnip (@quantumcthulhu)
* Alpha Q. Smith (@alpha_github_id)
* Brian L. McMichael (@brianmcmichael)
* Darius E. Parvin (@DariusParvin)
@ -182,16 +184,21 @@ Following is an alphabetically sorted list of all the GitHub contributors, inclu
* Eduardo Lima III (@elima-iii)
* Emilio Norrmann (@enorrmann)
* Francisco Calderón (@grunch)
* Gustavo Silva (@GustavoRSSilva)
* Haoyu Lin (@HAOYUatHZ)
* Hatim Boufnichel (@boufni95)
* Imran Lorgat (@ImranLorgat)
* John Davies (@tigeryant)
* Julien Wendling (@trigger67)
* Kory Newton (@korynewton)
* Luigi (@gin)
* Omega X. Last (@omega_github_id)
* Patrick Lemke (@PatrickLemke)
* Paul Wackerow (@wackerow)
* René Köhnke (@rene78)
* Ricardo Marques (@RicardoM17)
* Sergei Tikhomirov (@s-tikhomirov)
* Simone Bovi (@SimoneBovi)
* Omega X. Last (@omega_github_id)
* Umar Bolatov (@bolatovumar)
Without the help offered by everyone listed above, this book would not have been possible. Your contributions demonstrate the power of open source and open culture, and we are eternally grateful for your help.
@ -202,5 +209,12 @@ Thank you.
This book references various public and open-licensed sources:
_ION Lightning Network Wiki_
https://wiki.ion.radar.tech/
_Lightning 101: What is a Lightning Invoice?_ by suredbits
https://medium.com/suredbits/lightning-101-what-is-a-lightning-invoice-d527db1a77e6
_Lightning Network Specifications Github_
https://github.com/lightningnetwork/lightning-rfc/::
Creative Commons Attribution (CC-BY 4.0)

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save