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

Original author: Softblocks Co
  • Transfer

In the last article, we discussed in detail the work of payment channels, as well as several different methods for ensuring 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 cannot guarantee the delivery of funds through the chain through a number of channels. And here smart contracts called HTLC (hash-time-lock-contracts) come to our aid. In this article we will analyze the principle of their work, and we will demonstrate how the payment goes on in the Lightning network.

Lightning network

Table of contents

  • HTLC
  • Lightning network example
  • Clearing out failure
  • Transport protocol
  • Benefits and use cases
  • Conclusion
  • Links

Hash time lock contracts (HTLC)

HTLC contracts are a simple but very effective design that allows you to create payments with a certain "expiration date". As you probably already guessed, the htlc contract consists of 2 parts: hash checks and checks for the expiration of a certain time.

Let's start the analysis with a 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 digit or a word, in any case it is just a set of bytes.

H = Hash(R)

This hash H will be included in the locking script. Thus isplzovat payment can only one who knows the secret, hashing, which was received by H. Secret R is also referred to as prototype (preimage).

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

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

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

When providing the correct secret R, which is the prototype of the hash H, we get into the IF stream, where the check goes further: whether the person who has found the secret R is 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, then sending the payment can return all the funds. The unlocking script for a refund is no different, except that we must specifically specify the wrong secret in order to get into the ELSE stream:

<sig> <wrong secret>

Of course, this is a very basic implementation of an HTLC contract, which is a regular time-lock payment. You can add any number of 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 one signature, require several, as in multisig and so on.

P.s Здесь мы использовали опкод CHECKLOCKTIMEVERIFY , который использует абсолютное значение для задания времени блокировки, например "Этот выход не может быть потрачен до блока #546212". In addition to it, the Lightning Network also uses another, more “flexible” option - CHECKSEQUENCEVERIFY , it sets the blocking time relatively, that is, this 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’ve finally taken apart all the components, you can take a look at the whole picture, namely, how the Lightning Network 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 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 linked to form a Lightning Network

Let's say Alice wants to transfer Erica 1 bitcoin. However, as we see, they are not directly connected by the channel, and opening a new channel takes time and money. Fortunately, Alice is connected to the Lightning network and can make an indirect payment using a series of HTLC contracts. Let's take a look at the steps of how this will happen.

Step-by-step payment routing through a Lightning Network

  1. Eric creates a secret R and gives his hash to Alice (he doesn’t show anyone the secret).
  2. Alice creates an HTLC with this lock with 10 blocks in advance for the amount of 1.003. An extra 0.003 will be used as a reward to intermediate members for participating in the chain. Thus, Alice locks her 1.003 BTC balance into 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 for Bob, 0.997 for Alice and 1.003 locked in HTLC.
  3. Bob, holding Alice’s commit transaction (an HTLC sent to the channel between them), in turn, also creates an HTLC on the channel between him and Carol in the amount of 1.002 BTC with a lock of 9 blocks forward. In doing so, he uses the same hash that Alice used. Bob knows that Carol will need to find the secret of R in order to unlock the HTLC sent by him, and as soon as she does, he will also recognize him, which means he will be able to unlock 1.003 BTC sent by Alice. If Carol cannot find R, Bob and Alice’s funds will simply return to them after the locks expire. Also note that the amount that Bob sent is 0.001 less than what he received - this is the commission that he took for participating in the chain. The channel balance between Bob and Carol is now: 2 BTC for Carol, 0.998 BTC for Bob and 1.002 BTC is locked in the HTLC.
  4. Carol, having received Bob’s commit transaction, creates an HTLC (using the hash used by Bob) on the channel with Diana in the amount of 1.001 BTC and is blocked by 8 blocks. If Diana can find the R secret for 8 blocks and unlock the HTLC to get 1.001 BTC, Carol also finds out the secret, which means she can unlock the 1.002 BTC sent by Bob and thus earn 0.001 BTC. The channel balance between Carol and Diana is now now: 2 BTC for Diana, 0.999 BTC for Carol and 1.001 BTC are locked in HTLC.
  5. Finally, Diana sends an HTLC (all with the same hash) to her channel with Eric in the amount of 1 BTC and with a lock of 7 blocks. Their channel balance is now: 2 BTC for Eric, 1 BTC for Diana and 1 BTC locked in HTLC.
  6. Now, we have reached the end of our chain. Eric, having a secret R whose hash was used in all HTLC commit transactions, can unlock the HTLC sent to him by Diana and get 1 BTC. As soon as Eric uses the secret to receive funds, he will also reveal it to Diana. The channel balance 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 reveals the secret to her. The channel balance between them is now: 3.001 BTC for Diana and 0.999 BTC for Carol.
  8. Carol, having received the secret, will unlock 1.002 BTC sent by Bob and will reveal the secret to him. The channel balance between them is now: 3.002 BTC for Carol and 0.998 for Bob.
  9. In the last step, Bob secrets 1.003 BTC on the channel between him and Alice using a secret. Their channel balance 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 their part, no one would lose their funds, but only temporarily (at the time of blocking) froze them.

Clearing out failure

In our example, everything went smoothly, but in real life everything obeys Murphy’s law, and if something can break, it will do so, so let's analyze the work of the “protection” mechanisms of the Lightning Network.

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

Broken channel

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

Lightning network. Failure in funds delivery due to one of the channels closing.

Diana, as soon as the chain reached her, immediately takes her funds, using the secret, simultaneously revealing it to Carol. Carol also wants to get her money from Bob, but he does not answer, so in order not to risk, she closes the channel by sending the channel’s last commit transaction (the HTLC contract sent by Bob earlier) to the blockchain, and, using a secret, takes the funds . In this case, Bob still has 3 days to get in touch and collect his money from Alice (since the transaction went to the blockchain, he can easily find it 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 fails for any reason, he is the only one who can lose money, all the rest are safe.


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

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

Lightning network. One of nodes in 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 on a different chain, but if Carol suddenly returns, will he contact Bob and finish the chain? In this case, Alice will send a double amount of money.

Lightning network. Alice have built another payment route.

So is it every time that the operation fails, we have to wait before sending a new one? Fortunately, in order not to wait until the lock ends, we can “reset” the previous payment. To do this, Diana (the recipient of the funds) must send the payment of the equivalent amount to Alice, using the same hash as the first time, while the chain should not be the same at all. Now, if Carol returns and completes her part of the job, the money will just go around and around. Thus, a failed payment can be considered canceled and calmly send a new payment through another chain.

Lightning network. Alice

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 just not have enough money to repeat the operation, so it’s preferable to send to the Lightning Network 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

It is also worth mentioning a very important property of the Lightning Network - all information about the payment chain is completely anonymous. This means that each participant in the chain knows only about his "site": 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 transfer further money to Eric.

Lightning uses Sphinx message encryption protocol to pack such messages. Using it, Alice wraps each section of the chain in the “layer” of encryption, 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 corresponding key, and so on until the very beginning of the chain. Thus, Bob will be able to decrypt only the topmost layer of the message, which is addressed to him and will send a message to Carol, etc. .. At each stage, only the necessary information is disclosed: the amount of funds to be sent, the amount of commission, blocking time, etc.

Also, in order to not be able to guess the length of the chain by the weight of the message, it always has a fixed size, as if 20 people participate in the chain. Each participant, except the last one, sees a message of the same size and thinks that there are another 20 participants ahead.

Benefits and use cases

Of course, the benefits of the Lightning Network are not limited to just scaling bitcoin, as many people think. Let's look at some of the opportunities that Lightning offers us.

  • Instant transactions . Using Lighting, transactions are almost instantaneous. With it, paying for coffee with Bitcoin becomes possible.
  • Arbitration . At the moment, a quick transfer of money from one exchange to another is not possible, since 3-6 blocks are required to confirm the transaction. If exchanges use lightning, then users will be able to transfer funds instantly, which will allow for arbitrage transactions. Also, exchanges will not need to keep 'cold' wallets to store funds, which will greatly reduce the likelihood of theft.
  • Micropayments . Bitcoin transaction fee is too high to make micropayments. It is unlikely that someone will want to pay 0.001 in order to transfer the same or even less. With Lightning, you will be able to transfer any amount instantly, so that you can, for example, pay online megabytes.
  • Financial smart contracts and transactions . Financial contracts are particularly time sensitive and often require a lot of calculation. Moving most of them 'out', we get the opportunity to create extremely complex transactions and contracts without writing them to the blockchain.
  • Cross-chain payments . If blockchains with different consensus rules have similar hash functions, then it is possible to conduct transactions between them. Participants will not need to trust each other or use an intermediary.
  • Privacy . Transactions in Lightning are much more anonymous than in the Bitcoin blockchain, since participants in the chains along which payment is being made cannot see the sender or recipient.


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