Peter Tyonum
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Routing Payments in Lightning Network using HTLCs Recall that in [this](https://dev.to/tvpeter/understanding-how-payment-channels-work-in-lightning-network-30ia) article, we discussed how peers on the Lightning Network (LN) establish a channel to make numerous payments without announcing them to the network. However, if every payment requires setting up a channel between nodes on the LN, then there will be delays in the first payment as the transaction establishing a channel has to be broadcasted and confirmed on-chain. Also, there are on-chain transaction fees and the challenge of managing multiple channels. Alternatively, nodes may choose to route payment across the network to a destination node. In this article, we will discuss how a payment can be routed through other nodes in LN to a destination node in the same trustless manner using Hash Time Lock Contracts (HTLCs). The first step in routing a payment using HTLCs is for the receiver node to generate a payment invoice and send it to the payer. The invoice contains the amount, a payment hash, the receiver identity on the LN, an optional description, timelock, request expiration, and an on-chain fallback address. The most vital data on the invoice is the receiver node identity and the payment hash as this is all the information the sender is given about the identity of the recipient. The identity is a `secp256k1` public key of the node, which uniquely identifies the node on the network. The receiver node generates the payment hash by first generating a 32-byte random number called a `preimage`. The preimage remains a secret. It is then hashed using the `SHA256` hash algorithm to generate a payment hash for the invoice. Recall that, `SHA256` is a one-way hash function whose input cannot be calculated from the result. The recipient node may also optionally include routing hints in the payment invoice. These hints enable the sender to include unannounced channels while constructing a route to the recipient. Also optionally included in the invoice is the timestamp which enables the sender to know how old the invoice is, and also permits the receiver to enforce the expiration of the payment invoice. Alongside other earlier stated information, the payment invoice is signed by the receiver node. `BOLT11` invoice can also include the recipient pubkey as a tagged field which is covered by the signature. However, it's also possible to omit the recipient pubkey and to perform [pubkey recovery](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm#Public_key_recovery) on the signature itself to extract the pubkey it was signed with. As we will see later in the article, payment invoices are meant to be used once and never to be reused, though new LN specifications exist that make it possible to reuse invoices (those are not covered in this article). The signed invoice is then communicated to the sender. This is often done outside the LN through emails and QR codes or fetched via a webserver e.g. during a checkout process, though new specifications include using LN onion messages. Once the sender node receives the invoice, it first computes a path to send the payment to the recipient. This path is constructed by examining the information the sender node has about the network. (Recall that, when channels are created, they are announced to the network and nodes keep this information to represent the state of the network called the network graph). Provided the sender and recipient nodes are connected with channels that have enough capacity, the sender node will create a list of possible paths, and attempt to deliver payment in a trial and error loop until a path is found that can deliver the payment. Whilst the network graph includes **total channel capacity** for each channel, nobody except the two nodes in each channel knows how that capacity is distributed within the channel, i.e. what the _balance_ at each side of the channel is. ### ROUTING A PAYMENT When the sender node identifies a path to deliver payment to the recipient, it will encrypt a payment instruction containing the invoice’s payment hash in nested layers (like an onion) and send it to the first (intermediary) node on the path (hop). The intermediary node will unwrap the outermost layer of the payment instruction, identify and send it to the next hop along the path. This approach is called source-based onion routing (SPHINX), and each hop can only decrypt one layer at a time to reveal the next hop to forward the payment. Intermediate nodes only gain knowledge of `previous_hop` and `next_hop` relative to themselves, so if there is more than 1 hop in the path then nobody other than the sender will ever know the complete path. The final recipient will only ever know `previous_hop` and then that the payment was destined for them. As illustrated below, let’s assume Alice wants to send a letter to Chan through Bob (i.e, Alice is connected to Bob who is then connected to Chan). She will write the letter and seal the letter in an envelope addressed to Chan which only Chan can open. But because Alice is not connected to Chan directly, she will put the first envelope and the instruction inside another envelope and address it to Bob. When Alice delivers the entire packaged letters, Bob will open the first outer envelope which reveals the instruction TO CHAN. Bob will then forward the letter to Chan, the intended receiver. ![](https://i.imgur.com/65WTtvx.png) Developing on the above illustration further, the intermediary (Bob) might decide to charge a fee for forwarding the payment instruction to the next hop on the path (in this example Chan). So Alice will pledge to pay Bob an additional 100sats for forwarding the instruction. However, the payment will only be made if and only if Chan will share a secret number (the preimage discussed earlier) with Bob that can be hashed to result in the payment hash stated on the payment invoice. With this pledge, Bob will also pledge to Chan that he will pay Chan an amount less than 100sats if Chan will present a preimage that Bob can hash that will result in the payment hash. Once Chan reveals the preimage, Bob will verify by hashing the preimage and if the result matches the payment hash, Bob will then pay Chan the amount stated on the payment instruction. Bob will then share the preimage with Alice who pledged to pay Bob the amount and an additional 100sats if Bob shares the secret hashing to the payment hash. Once Alice verifies by hashing the preimage and it results in the payment hash, she will pay Bob the amount she pledged earlier, which is the invoice amount + 100sats. The above illustration has a single hop between the sender and recipient. Whilst the specification currently allows for a maximum of 27 hops in the route, in normal usage more than 7 hops would be considered unusual. In computing a path, the sender often optimizes for fewer hops to reduce the chance for failure and routing fees. So, how does Alice (our payment sender) knows what fee to pay to each hop (fee_base_msat) and whether a channel exists between nodes capable of forwarding this payment? This is the information Alice sought during the path-finding phase. She is also aware of how long it will take for Bob to pay Chan the agreed amount (cltv_expiry_delta). All this information aids the sender to construct a payment instruction that will pass through each intermediary with minimal chance of failure. Also, as illustrated in our example, the sender starts constructing the payment instruction from the destination backward to them. Each layer of the onion is encrypted in such a way that only the node meant to read it can be able to read. The sender achieves this using the intermediate node’s public key and the Elliptic Curve Diffie–Hellman (ECDH) on Bitcoin’s secp256k1 curve. And the message can be checked that it has not been modified. Also, the sender generates a temporal key for the entire session so that no other node can identify her node as the sender of the payment instruction. All these measures ensure the integrity of messages and the privacy of the nodes. If for any reason, the payment instruction could not go through at any point, it will fail and the failed status will propagate backward along the same path so that any pledged payment will be canceled. As we have seen, sending payments this way on the LN is both beneficial and safe for everyone involved (the sender, the intermediary nodes, and the recipient). Intermediary nodes earn fees for forwarding payment instructions. The sender pays the recipient within a short time and with a minimal fee. The recipient node receives its payment within a short time without risk. This enables payments to be made on the LN without establishing channels between nodes for each payment. References: - [Mastering Lightning Network](https://github.com/lnbook/lnbook): By Andreas M. Antonopoulos (@aantonop), Olaoluwa Osuntokun (@roasbeef), Rene Pickhardt (@renepickhardt). - Public Key Recovery question on Stackoverflow explanation [here](https://bitcoin.stackexchange.com/questions/96204/what-is-signature-recovery) - [Bolt11 Invoice for Lightning Payment](https://github.com/lightning/bolts/blob/master/11-payment-encoding.md) Specifications.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully