📜 ⬆️ ⬇️

Lightning Network In Depth, part 2: HTLC And Payment Routing

In the last article, we discussed in detail the work of payment channels, as well as several different methods to ensure the security of payments passing through them, but this is still not enough to build a working network of channels: even if we are sure that everyone plays within each channel honestly, we can not guarantee the delivery of funds through the chain through a number of channels. And here we come to the aid of smart contracts, called HTLC (hash-time-lock-contracts). In this article we will examine the principle of their work, and discuss how the payment goes through the Lightning network.


Lightning network


Table of contents



Hash time lock contracts (HTLC)


HTLC contracts are an uncomplicated, but at the same time very effective, design that allows you to create payments with a specific "shelf life". As you probably already guessed, the htlc-contract consists of 2 parts: checking the hash and checking the expiration of a certain time.


Let's start the analysis with the hash. To create an HTLC payment, the secret R must first be created and then its hash calculated. Anything can act as a secret - a number or a word, in any case it is just a set of bytes.


H = Hash(R) 

This H hash will be included in the locking script. Thus, only those who know the secret whose hashing has been obtained by H can use the payment. The secret R is also called the preimage.


The second part of the htlc contract is to check the expiration of the payment blocking time. If the secret was not revealed on time and the payment was not used, the sender can return all funds to himself.


Consider the example of a HTLC payment intended for a specific person:


 # check if secret R is preimage of H HASH160 <H> EQUAL IF # check if person, who revealed secret is intended payee <Payee Public key> CHECKSIG ELSE # check if time-lock is ended <locktime> CHECKLOCKTIMEVERIFY # check that person that requested refund is original payer <Payer Public Key> CHECKSIG ENDIF 

By providing the right secret R, which is a prototype of the H hash, we get into the flow of IF, where the next check is: is the person who has found the secret of R really the one to whom the payment is intended? To spend this payment, the recipient needs to provide a fairly simple unlocking script:


 <sig> <secret R> 

If the provided secret R is incorrect, we get into the ELSE stream, where it is first checked whether the allotted amount of time has passed, and if so, the return payment can return all funds. The unlocking script for a refund is no different, except for the fact that we have to specifically provide the wrong secret in order to get into the ELSE stream:


 <sig> <wrong secret> 

Of course, this is a very basic implementation of the HTLC contract, which is a regular time-lock payment. You can add as many different conditions to the script: by removing, for example, checking the public key in the IF stream, we can make the payment available to anyone who knows the secret or, instead of a single signature, require several, like in multisige and so on.


Ps Here we used the opcode CHECKLOCKTIMEVERIFY , which uses an absolute value to set the blocking time, for example, "This output cannot be spent until # 546212 block". In Lightning Network, in addition to it, another, more “flexible” version is used - CHECKSEQUENCEVERIFY , it sets the blocking time relatively, that is, the following option is possible: "This output cannot be spent until 1000 blocks have passed since the transaction was sent to the network. " .


Lightning Network Example


Now that we have finally disassembled all the components, we can take a look at the whole picture, namely, how the Lightning Network still works. In this example, we will have 5 participants: Alice, Bob, Carol, Diana and Eric, who have open payment channels between each other with a balance of 2 bitcoins each on each channel where they are one of the parties. Thus, having a chain of channels, we will try to make a payment from Alice to Eric.


A series of bi-directional payment channels


Suppose Alice wants to translate Eric 1 Bitcoin. However, as we see, they are not directly connected by a channel, and the opening of a new channel requires time and money. Fortunately, Alice is connected to the Lightning network and can make a payment indirectly using a series of HTLC contracts. Consider the steps as it happens.


Step-by-step payment routing through a Lightning Network


  1. Erik creates a secret R and tells it to Alice hash (he doesn’t reveal the secret to anyone yet).
  2. Alice creates this HTLC hash with blocking 10 blocks ahead for a total of 1.003. An additional 0.003 will be used as a reward for intermediate participants for participating in the chain. Thus, Alice locks up her 1.003 BTC balance at the HTLC, with the following rule: "Alice will pay Bob 1.003 Bitcoin if he learns the secret R within 10 blocks, otherwise the funds will return to Alice.". The channel balance was changed by a commit transaction and now represents the following: 2 BTC at Bob, 0.997 at Alice, and 1.003 locked in HTLC.
  3. Bob, having Alice's commit transaction (HTLC sent to the channel between them), in turn also creates HTLC on the channel between him and Carol in the amount of 1.002 BTC with the lock already 9 blocks ahead. In doing so, it uses the same hash that Alice used. Bob knows that Carol will need to find the secret R to unlock the HTLC sent to them, and as soon as she does, he will also recognize him, which means he can unlock the 1.003 BTC sent to him by Alice. If Carol cannot find R, the means of Bob and Alice will simply return to them after the locks expire. Also note that the amount sent by Bob is 0.001 less than what he received - this is the commission he took for participating in the chain. The channel balance between Bob and Carol is now: 2 BTC at Carol, 0.998 BTC at Bob, and 1.002 BTC locked in HTLC.
  4. Carol, after receiving a Bob commit-transaction, creates an HTLC (using the hash used by Bob) on the channel with Diana for the sum of 1.001 BTC and blocking for 8 blocks. If Diana can find the secret R within 8 blocks and unlock the HTLC to get 1.001 BTC, Carol also learns the secret, which means she can unlock the 1.002 BTC sent by Bob to her and thus earn 0.001 BTC. The balance of the channel between Carol and Diana is now: 2 BTC at Diana, 0.999 BTC at Carol and 1.001 BTC locked in HTLC.
  5. Finally, Diana sends HTLC (all with the same hash) to her channel with Eric in the amount of 1 BTC and with blocking for 7 blocks. The balance of their channel is now: 2 BTC at Eric, 1 BTC at Diana and 1 BTC locked in the HTLC.
  6. Now, we have reached the end of our chain. Eric, having a secret R, the hash of which was used in all HTLC commit transactions, can unblock the HTLC sent to him by Diana and receive 1 BTC. Once Eric uses the secret to get the funds, he will also open it to Diana. The balance of the channel between Eric and Diana is now: 3 BTC for Eric and 1 BTC for Diana.
  7. Diana, having received the secret, unlocks 1.001 BTC, sent by Carol and thereby opens the secret to her. The balance of the channel between them is now: 3.001 BTC for Diana and 0.999 BTC for Carol.
  8. Carol, having received the secret, unlocks 1.002 BTC, sent by Bob and opens the secret to him. The channel balance between them is now: 3.002 BTC at Carol and 0.998 at Bob.
  9. In the final step, Bob, using a secret, gets 1.003 BTC on the channel between him and Alice. The balance of their channel is now: 3.003 BTC for Bob, 0.997 for Alice.

Thus, Alice paid Eric 1 BTC without opening a new channel between them. None of the participants in the chain was obliged to trust each other, and for providing their services as "intermediaries", they earned a commission of 0.001 BTC. In the event that someone from the chain could not fulfill his part, no one would lose his money, but only temporarily (for the time of blocking) he froze them.


Clearing out failure


In our example, everything went smoothly, but in real life everything is subject to Murphy's law, and if something can break, then it will do just that, so let's take a look at the work of the “protection” mechanisms of the Lightning Network.


Obviously, the longer the chain through which the funds are delivered, the higher the likelihood that the funds will not reach the end - one of the participants may close the channel, and someone may simply disconnect the Internet. Consider 2 options for events where something went wrong.


Broken channel


In the first case, let us imagine that the funds successfully reached the end of the chain, but on the reverse path (when the secret should return to the very beginning) the problem arose - one of the participants refused or could not cooperate - in our example it is Bob.


Lightning network. Failure in funds delivery.


Diana, as soon as the chain reached her, immediately withdraws her money using a secret, revealing Carol along the way. Carol also wants to get her money from Bob, but he doesn’t respond, so in order not to risk, she closes the channel, sending the last channel commit transaction (HTLC contract sent by Bob earlier) to the blockchain, and using a secret, takes the money . In this case, Bob still has 3 days to get in touch and take her money from Alice (since the transaction went to the blockchain, he can safely find her and see R), otherwise after this period she will be able to return everything own funds.


As you can see, in this case, if one of the participants in the chain for any reason fails, he is the only one who can lose money, all the rest are safe.


Rerouting


In the second case, consider the situation where the funds did not reach the end of the chain, again due to the inoperability of one of the participants. Now it is Carol.


The first and most obvious way is to simply wait until the blockade of HTLC contracts expires and you can return the funds back to send a new payment.


Lightning network. One of the nodes in the payment route is unresponsive.


But what if Alice is in a hurry? Of course, you can not wait until the funds return and just send another 1 payment already in a different chain, but if Carol suddenly returns, will she contact Bob and finish the chain? In this case, Alice will send double the amount of money.


Lightning network. Alice have built another payment route.


So really, every time we fail, we have to wait before sending a new one? Fortunately, in order not to wait until the end of the blocking, we can "reset" the previous payment. To do this, Diana (the recipient of funds) must send a payment of an equivalent amount to Alice, using the same hash as the first time, and the chain should not be the same at all. Now, if Carol returns and completes her part of the job, the money will simply go around the circle. Thus, a failed payment can be considered canceled and calmly send a new payment through another chain.


Lightning network. Alice “canceled”.


Payment amount


I think you noticed that even though Alice "canceled" the first payment and can now send a new one, this does not change the fact that the funds are still frozen there and she may simply not have enough money to repeat the operation, therefore in Lightning Network it is preferable to send small amount for one htlc. Since commit transactions do not “hit” the blockchain, you can divide the amount into extremely small parts. Thus, as soon as the chain stops working, only a small part of the payment sent last remains frozen.


Transport protocol


Also here it is worth mentioning a very important property of the Lightning Network - all information about the payment chain is completely anonymous. This means that each member of the chain knows only about his “plot”: for Carol, for example, the payment looks like a transfer of funds from Bob to Diana, she does not know that Bob in turn received money from Alice, or that Diana should further transfer Erik's money.


Lightning uses the Sphinx multilayer message encryption protocol for packaging such messages. Using it, Alice wraps each section of the chain in an encryption layer, starting at the end of the chain. She encrypts the message for Eric using his public key. This message is included in the message for Diana, which in turn will also be encrypted with her key, and the message for Diana will be included in the message for Carol, again encrypted with the appropriate key and so on until the very beginning of the chain. Thus, Bob will be able to decipher only the topmost layer of the message, which is addressed to him and forwards the message to Carol, etc. .. At each stage, only the necessary information is revealed: the number of funds that must be sent, the amount of commission, the time of blocking, and so on.


Also, so that it was impossible to guess the length of the chain by the weight of the message, it always has a fixed size, as if 20 people were involved in the chain. Each participant, except the last, sees a message of the same size and thinks that there are 20 more participants ahead.


Benefits and use cases


Of course, the advantages of the Lightning Network are not limited to bitcoin scaling, as many people think. Consider some of the opportunities that Lightning opens up for us.



Conclusion


This concludes our analysis of the Lightning Network. In the following articles, we will tell you how to cross-chain atomic swap between bitcoin and lightcoin using HTLC contracts.




')

Source: https://habr.com/ru/post/350790/


All Articles