In-depth interpretation of Lightning Network (Part 2): HTLC and payment routing

In the previous article, we explained in detail the operation of payment channels and various methods to ensure that payments occur safely. However, these functions are not enough to support an available payment channel network: even if we are sure that each participant in each channel is honest and trustworthy, there is no guarantee that payments through multiple channels are equally safe. This is why we need the “HTLC (Hash-Time Lock-Contract)” smart contract. In this article, we will explain how HTLC works and use an example to show how multi-hop payment is implemented in the Lightning Network.

Hash Time Lock Contract (HTLC)

The structure of HTLC is not complicated, but it is very efficient. It allows us to create payments with a clear “expiration time”. As you might guess, the HTLC contract consists of two parts: hash verification and expiration verification.

Let’s start with the hash value (hash). To create a payment transaction with HTLC, you must first generate a  secret value  R, and then calculate its hash value. Any word and any number can serve as the secret value, because for the hash function, they are all combinations of a bunch of data, and there is no difference.

  • H = Hash(R)

This hash value H will be placed in the lock script of the transaction output. In this way, only those who know the secret value corresponding to H can use this output. And R is the so-called “preimage”.

The second part of HTLC is the verification of expiration time. If the secret value is not disclosed in time, the payment will not be used, and the sender will recover all the funds.

Let’s consider a H LTC payment transaction sent to someone :

# Check whether the provided R is the original image of H HASH160 <H> EQUALIF # Check whether the person who discloses R is the original recipient of the transaction <Payee Public key> CHECKSIGELSE # Check whether the time lock has expired <locktime> CHECKLOCKTIMEVERIFY # Check the request Is the return of funds the original sender of the transaction <Payer Public Key> CHECKSIGENDIF

在正确的 R(哈希值 H 的原像)公开之后,我们进入 IF 流程,进一步验证提供 R 的是不是这笔支付事务一开始的支付对象。在花费这个输出时,接收方只需提供一个非常简单的解锁脚本:

  • <sig> <secret R>

If the R provided by the unlocking script is wrong, we jump to the ELSE process and first verify that the time lock is unlocked. If the time lock is unlocked, the sender can withdraw all funds. The unlocking script for the operation of recovering funds is similar. The only difference is that in order to enter the ELSE process, an incorrect secret value needs to be provided:

  • <sig> <wrong secret>

Of course, this is just a very basic implementation of HTLC, which represents an ordinary time lock payment. You can add any number of other conditions to the script, for example, remove the public key verification in the IF process, so that anyone who knows the secret value R can use this output; you can also add a multi-signature restriction to it, and ask for it The signature of multiple preset private keys can be unlocked.

One more thing, in this case, the opcode we used is  CHECKLOCKTIMEVERIFY . This opcode uses an absolute value to define the time lock, meaning like: “This output is unavailable before block #546212”. In the Lightning Network, another time lock is also used, a more “flexible” one: CHECKSEQUENCEVERIFY , which uses a relative value, meaning close to: “This output is after the transaction that uses it is chained It’s not available within 1000 blocks of “(Translator’s Note: The values ​​here are examples, of course other values ​​can be used in practice).

Lightning Network Case

Now that we have finally explained all the elements, we can try to understand the panorama of the operation of the Lightning Network.

We assume that there are 5 participants in the Lightning Network: Alice, Bob, Carol, Diana, and Eric. They are each connected to a payment channel, and each side of each channel has a balance of 2 btc available. Now, we try to make Alice pay Eric through the channel chain.

In-depth interpretation of Lightning Network (Part 2): HTLC and payment routing

A series of connected two-way payment channels form the Lightning Network, which can refer Alice’s payment to Eric

Suppose Alice now wants to pay Eric 1 btc. However, as we have seen, they are not connected by a direct channel, and opening a channel requires time and money. Fortunately, Alice is connected to the Lightning Network and can complete indirect payments with the help of a series of HTLC contracts. Let’s take it apart step by step.

In-depth interpretation of Lightning Network (Part 2): HTLC and payment routing

Gradually decompose payment routing in the Lightning Network 

  1. Eric generates a secret value R and sends its hash value to Alice (he will not show R to others)
  2. Alice uses this hash value to create an HTLC, and the time lock is set to 10 blocks in the future, and the output amount is 1.003 btc. This additional 0.003 btc is a handling fee for the middle party of the payment channel chain. So, Alice now uses HTLC to lock 1.003 btc, and the specific conditions of HTCL are expressed in vernacular as follows: “Alice will pay Bob 1.003 btc, as long as he can hand over the secret value R within 10 blocks, otherwise the money Will return to Alice”. The balance of the channel between them will also change as a result of this commitment transaction. Now Bob has 2 btc in the channel, Alice has 0.997 btc, and 1.003 btc is locked in the HTLC.
  3. When Bob is here, he can dispose of Alice’s promised transaction at will (this HTLC transaction is sent through the channel between them). He created an HTLC output in his channel with Carol, the amount is 1.002, the time lock is set to 9 blocks, and the same hash value as provided by Alice is used. Bob knows that if Carol wants to get the money, he has to find the secret value R to unlock the HTLC, and once she does this, he will know this R, so he can also unlock Alice’s HTLC and get 1.003 btc. If Carol can’t find the secret value R, both Bob and Alice can get their money back after the time lock is unlocked. Note that the amount of funds sent by Bob is 0.001 btc less than the amount he can get, and this is the amount of handling fees he charges. The balance of Bob and Carol in the channel becomes: Carol owns 2btc, Bob owns 0.998 btc, and 1.002 btc is locked in HTLC
  4. After Carol obtained the promised transaction from Bob, he followed the same pattern and created an HTLC in the channel with Diana. The hash value used was the same as that provided by Bob. The time lock was set to 8 blocks and the amount was 1.001 btc. If Diana can reveal the secret value R within 8 blocks, he can unlock the HTLC and get 1.001 btc. Correspondingly, Carol will also know the secret value, unlock the HTLC Bob gave her, get 1.002 btc, and earn 0.001 btc. The balance in the Carol and Diana channels becomes: Diana owns 2btc, Carol owns 0.999 btc, and 1.001 btc is locked in HTLC
  5. Finally, when Diana sends an HTLC (using the same hash value as the lock) to Eric through the channel, she sets the value to 1 btc and the time lock to 7 blocks. The balance in the channel of Diana and Eric becomes: Eric owns 2btc, Diana owns 1 btc, and 1 btc is locked in the HTLC
  6. Now, we have come to the end of this chain payment. Eric owns the secret value R, and the hash value of R is used in all HTLC committed transactions. Eric can unlock the HTLC sent to him by Diana and get 1 btc; and after Eric retrieves the funds, Diana will also know this R. The balance in the channel between Diana and Eric will become: Eric owns 3 btc and Diana owns 1 btc.
  7. After receiving the secret, Diana also used it to unlock the HTLC that Carol sent her, and obtained 1.001 btc and also disclosed the secret value to Carol. The balance in their channel has become: Diana owns 3.001 btc, Carol owns 0.999 btc.
  8. After Carol received the secret value R, he unlocked the 1.001 btc sent by Bob, so Bob also knew the secret value. The balance in their channel becomes: Carol has 3.002 btc and Bob has 0.998 btc
  9. Finally, Bob uses the secret value R to obtain 1.003 btc in the channel with Alice. So the balance in the channel becomes: Bob owns 3.003 btc, and Alice owns 0.997.

After such a process, Alice paid Eric 1 btc without having to open another directly connected channel between each other. In the entire payment chain, no one needs to trust another person, and they also earn 0.001 btc because of intermediary services. Even if the payment is stuck in a certain link, no one will suffer a loss because the funds are still locked there and can be retrieved after time has passed.

Clear fault

In our example, the entire process is smooth and unobstructed, but in real life it is like the so-called “Murphy’s Law”: if something bad can happen, then this bad thing will happen. So we have to consider the “protection” mechanism of the Lightning Network.

From a practical point of view, the longer the payment chain, the greater the probability that funds will not be delivered in the end: some participants may close the channel, or some nodes will be dropped. Let us consider two possible error scenarios.

Channel failure

Consider a situation first: we assume that the funds have reached the destination, but in the process of returning the secret value all the way to the starting point of payment, a participant refuses to cooperate or is unable to cooperate. Suppose it is Bob.

In-depth interpretation of Lightning Network (Part 2): HTLC and payment routing

Because a channel is closed, the funds cannot be delivered 

When Diana received the secret value, she immediately retrieved the funds and exposed the secret value to Carol. Carol also wanted to get the funds back from the HTLC sent by Bob, but Bob did not respond. In order to avoid risks, she closed the channel and took the last committed transaction (that is, the one previously issued by Bob with HTCL output). The transaction) is broadcast to the Bitcoin network, and because she knows the secret value, she can retrieve the funds. At this point, Bob has three days to get his money back from Alice (because Carol’s transaction is already on the chain, Bob can easily know the value of R). Otherwise, as soon as the time lock is unlocked, Alice can recover the funds.

It can be seen that even if a participant leaves the network for some reason, TA himself is the only person who may lose funds, and the funds of others are safe.


In the second scenario, we assume that the funds cannot reach the destination, but also because some participant made a mistake. Suppose it is Carol.

The first and most obvious solution is to wait for the HTLC time lock to expire, and then each participant gets his own funds back.

In-depth interpretation of Lightning Network (Part 2): HTLC and payment routing

A node in the payment path does not respond 

But what if Alice is in a hurry to pay? Of course, Alice can initiate a new payment through another path, without waiting for the funds to return, but what if Carol suddenly comes back and renews the chain with Bob? Didn’t Alice send twice the funds?

In-depth interpretation of Lightning Network (Part 2): HTLC and payment routing

If Alice uses another path 

Does this mean that whenever a payment fails, one should obediently wait for the time lock to expire before initiating a new payment?

Fortunately, to avoid this waiting, we can “cancel” this payment. Diana (the payee) wants to send the same amount of funds to Alice, also using the same hash value as the original, or using another path. Now, if Carol goes online again and participates in the intermediary, then the funds will complete a loop, which means that the original failed payment has been offset, and Alice can safely use another path to pay.

In-depth interpretation of Lightning Network (Part 2): HTLC and payment routing

Alice “cancelled” the old payment, and the new payment can now be sent safely 

Payment amount

You can also notice that when Alice “cancelled” her first payment, it is indeed safe to initiate a new payment, but this does not change the fact that her first payment is still the same. Locked, and she may not have enough money to initiate a second payment. This is why when using the Lightning Network, the amount of funds should be smaller when using HTLC to pay. Because the committed transaction will not be chained, the amount can be divided into multiple small amounts. In this way, whenever a path fails, only a small part of the funds will be frozen (the last one sent).

Transfer Protocol

Another very important feature of the Lightning Network is that all information about this path is completely anonymous. This means that for any participant, TA only knows the part related to him. For example, for Carol, this payment is like Bob transferring money to Diana. She doesn’t know that Bob will be from Alice. After receiving the funds, I don’t know that Diana will continue to transfer the funds to Eric.

Lightning Network uses Sphinx multiple encryption protocol. When using the Lightning Network, Alice will do a layer of encryption for each part of the network, starting from the end of the payment path. She uses Eric’s public key to encrypt the message for Eric. This encrypted message will be nested in the message to Diana, and the entire message will be encrypted again with Diana’s public key. Then, this message for Diana will be nested in the message for Carol, and Carol’s public key will be used to encrypt the entire message again. Repeat this repeatedly to get a message that can be passed on to the next person. In this way, Bob can only decrypt the outermost layer of the message and get the content intended for him; then forward the message to Carol; the same is true for Carol. Every time someone passes by, only the absolutely necessary information will be disclosed: the amount of the payment, the amount of the commission, the content of the time lock, and so on.

In order to make it impossible for people to infer the length of the chain from the length of the message, the length of the message is always the same, always as if there are 20 people participating in the chain. Everyone, including the last one, gets an image of the same size, thinking that there are 20 partners besides themselves.

Benefits and application scenarios of Lightning Network

Of course, the benefits of the Lightning Network are not as many people think, only scalability. Let’s think about what possibilities the Lightning Network brings.

  • Instant transactions . When using the Lightning Network, transactions are completed almost instantly. So using Bitcoin to buy coffee becomes feasible
  • Exchange arbitrage . At present, it is very inconvenient to transfer funds from one exchange to another exchange. It is necessary to wait for 3 to 6 blocks to confirm the transaction. If the exchange can use the Lightning Network, then users can instantly transfer funds and participate in arbitrage. Exchanges no longer need cold wallets to store funds, which greatly reduces the risk of theft.
  • Small payments . The transaction fee of the Bitcoin blockchain is too high for small payments. It is difficult to imagine who would be willing to pay 0.001 btc just to transfer the same amount or even less. With the Lightning Network, you can instantly transfer any amount of money, for example, you can pay network fees in MB.
  • Financial smart contracts and transactions . Financial contracts are extremely sensitive to time delay and usually require a lot of calculations. By moving most of the burden outside the blockchain, we have the opportunity to create very complex transactions and contracts without having to record them all on the blockchain.
  • Cross-chain payment . If blockchains with different consensus rules use the same hash function, it is possible to use the Lightning Network to make cross-chain payments. Participants do not need to trust anyone, nor do they need to use an intermediary.
  • Privacy . In the Lightning Network, transactions are more secretive than on the Bitcoin blockchain, because the participants in the payment chain do not know the originator and destination of the transaction.

in conclusion

We have finished talking about the Lightning Network. In the next article, I will show you how to use HTLC to perform a cross-chain atomic swap, using btc for ltc.


Posted by:CoinYuppie,Reprinted with attribution to:
Coinyuppie is an open information publishing platform, all information provided is not related to the views and positions of coinyuppie, and does not constitute any investment and financial advice. Users are expected to carefully screen and prevent risks.

Like (0)
Donate Buy me a coffee Buy me a coffee
Previous 2021-09-15 12:34
Next 2021-09-15 12:36

Related articles