├── .gitignore ├── 404.html ├── Gemfile ├── Gemfile.lock ├── README.md ├── _config.yml ├── _includes ├── footer.html ├── head.html ├── header.html └── icon-github.html ├── _layouts └── home.html ├── _pages ├── contribute.md ├── lapps.md ├── overview.md └── resources.md ├── _posts └── 2017-06-26-welcome-to-jekyll.markdown ├── _sass ├── .DS_Store ├── minima.scss └── minima │ ├── .DS_Store │ ├── _base.scss │ └── _layout.scss ├── assets ├── dropdown.css └── lapps │ ├── lnd.fun.png │ ├── lnd_desktop_app.png │ ├── thunderdice.png │ ├── yalls.png │ └── zap.png ├── deploy.sh ├── error.html ├── guides ├── docker.md ├── index.md ├── installation.md ├── javascript-grpc.md └── python-grpc.md ├── index.md ├── render.py ├── templates ├── base.md └── installation_footer.md ├── tutorial ├── 01-lncli.md ├── 02-web-client.md ├── 03-rpc-client.md ├── 04-webapp-integration.md └── index.md └── update_and_render.sh /.gitignore: -------------------------------------------------------------------------------- 1 | # Vim 2 | *.swp 3 | 4 | # Jekyll 5 | _site/ 6 | .sass-cache/ 7 | .jekyll-metadata 8 | -------------------------------------------------------------------------------- /404.html: -------------------------------------------------------------------------------- 1 | --- 2 | layout: default 3 | --- 4 | 5 | 18 | 19 |
20 |

404

21 | 22 |

Page not found :(

23 |

The requested page could not be found.

24 |
25 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | # Hello! This is where you manage which Jekyll version is used to run. 4 | # When you want to use a different version, change it below, save the 5 | # file and run `bundle install`. Run Jekyll with `bundle exec`, like so: 6 | # 7 | # bundle exec jekyll serve 8 | # 9 | # This will help ensure the proper Jekyll version is running. 10 | # Happy Jekylling! 11 | gem "jekyll", "3.5.0" 12 | 13 | # This is the default theme for new Jekyll sites. You may change this to anything you like. 14 | gem "minima", "~> 2.0" 15 | 16 | # If you want to use GitHub Pages, remove the "gem "jekyll"" above and 17 | # uncomment the line below. To upgrade, run `bundle update github-pages`. 18 | # gem "github-pages", group: :jekyll_plugins 19 | 20 | # If you have any plugins, put them here! 21 | group :jekyll_plugins do 22 | gem "jekyll-feed", "~> 0.6" 23 | end 24 | 25 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem 26 | gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] 27 | 28 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | addressable (2.5.1) 5 | public_suffix (~> 2.0, >= 2.0.2) 6 | colorator (1.1.0) 7 | ffi (1.9.18) 8 | forwardable-extended (2.6.0) 9 | jekyll (3.5.0) 10 | addressable (~> 2.4) 11 | colorator (~> 1.0) 12 | jekyll-sass-converter (~> 1.0) 13 | jekyll-watch (~> 1.1) 14 | kramdown (~> 1.3) 15 | liquid (~> 4.0) 16 | mercenary (~> 0.3.3) 17 | pathutil (~> 0.9) 18 | rouge (~> 1.7) 19 | safe_yaml (~> 1.0) 20 | jekyll-feed (0.9.2) 21 | jekyll (~> 3.3) 22 | jekyll-sass-converter (1.5.0) 23 | sass (~> 3.4) 24 | jekyll-watch (1.5.0) 25 | listen (~> 3.0, < 3.1) 26 | kramdown (1.14.0) 27 | liquid (4.0.0) 28 | listen (3.0.8) 29 | rb-fsevent (~> 0.9, >= 0.9.4) 30 | rb-inotify (~> 0.9, >= 0.9.7) 31 | mercenary (0.3.6) 32 | minima (2.1.1) 33 | jekyll (~> 3.3) 34 | pathutil (0.14.0) 35 | forwardable-extended (~> 2.6) 36 | public_suffix (2.0.5) 37 | rb-fsevent (0.9.8) 38 | rb-inotify (0.9.10) 39 | ffi (>= 0.5.0, < 2) 40 | rouge (1.11.1) 41 | safe_yaml (1.0.4) 42 | sass (3.4.24) 43 | 44 | PLATFORMS 45 | ruby 46 | 47 | DEPENDENCIES 48 | jekyll (= 3.5.0) 49 | jekyll-feed (~> 0.6) 50 | minima (~> 2.0) 51 | tzinfo-data 52 | 53 | BUNDLED WITH 54 | 1.15.1 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Lightning Network Daemon Developer Site 2 | Developer guides and resources for the Lightning Network Daemon 3 | 4 | ## Overview 5 | 6 | This repository contains functionality for programmatically pulling guides from 7 | the lnd repo, using a Python script and Jinja2 templates to output markdown 8 | files, which are the corresponding pages in the fully rendered Jekyll static 9 | site. 10 | 11 | Pay special attention to these files: 12 | - `templates/base.md`: The Jinja2 template fed into the Python 13 | script, holding the Jeykll header to be prepended to the guide content pulled 14 | from Github. The `templates` dir also holds the templates for special cases 15 | where for example a dev site-specific footer needs to be appended 16 | - `update_and_render.sh`: Update local guides to the latest version available 17 | - `render.py`: The Python script that uses local guides and Jinja template to 18 | strip out redundant titles, add page headers/footers, and output Jekyll 19 | markdown 20 | - `deploy.sh`: Build static site from Jekyll markdown and deploy to Google Cloud 21 | Platform 22 | 23 | The rest of the files in this repo are the standard Jekyll site files. 24 | 25 | ## Running the site locally 26 | 27 | ### Prerequisites 28 | 29 | You're going to need: 30 | 31 | - **Linux or OS X** — Windows may work, but is unsupported. 32 | - **Ruby, version 2.2.5 or newer** 33 | - **Bundler** — If Ruby is already installed, but the `bundle` command doesn't work, just run `gem install bundler` in a terminal. 34 | 35 | ### Running locally 36 | 37 | ```shell 38 | git clone https://github.com/lightninglabs/lightning-dev-site 39 | ``` 40 | Install Jekyll: 41 | ``` 42 | $ gem install jekyll bundler 43 | ``` 44 | Run the site and watch for changes: 45 | ``` 46 | $ bundle exec jekyll serve 47 | ``` 48 | * If running remotely add: `--host=0.0.0.0` 49 | 50 | 51 | ## Regenerating documentation 52 | 53 | ```shell 54 | # Install Jinja for python templating 55 | pip install Jinja2 56 | ``` 57 | 58 | ### Get the latest INSTALL.md 59 | ```shell 60 | curl -o INSTALL.md -s https://raw.githubusercontent.com/lightningnetwork/lnd/master/docs/INSTALL.md 61 | ``` 62 | 63 | ### Fetch the latest Docker guide 64 | ```shell 65 | curl -o DOCKER-README.md -s https://raw.githubusercontent.com/lightningnetwork/lnd/master/docker/README.md 66 | ``` 67 | 68 | ### Get the latest gRPC guides 69 | ```shell 70 | curl -o python.md -s https://raw.githubusercontent.com/lightningnetwork/lnd/master/docs/grpc/python.md 71 | curl -o javascript.md -s https://raw.githubusercontent.com/lightningnetwork/lnd/master/docs/grpc/javascript.md 72 | ``` 73 | 74 | Let's run the script to render the guides: 75 | ```shell 76 | python render.py 77 | ``` 78 | 79 | Now that you're all set up, you can just run `./update_and_render.sh` to 80 | automatically pull the latest markdown files and render the local Jekyll docs. 81 | 82 | ## Deployment 83 | 84 | The Lightning API is deployed with Google Cloud Platform. Visit [this blog 85 | post](https://little418.com/2015/07/jekyll-google-cloud-storage.html) for more 86 | information. 87 | 88 | ### Steps 89 | 90 | 1. Install Google Cloud SDK and authenticate into it: 91 | ```bash 92 | brew cask install google-cloud-sdk 93 | gcloud auth login 94 | ``` 95 | 96 | 2. Build 97 | ```bash 98 | bundle exec jekyll build 99 | ``` 100 | 101 | 3. Push to Google Cloud Bucket 102 | ```bash 103 | # -m use faster multithreaded uploads 104 | # -d delete remote files that aren't in the source 105 | # -r recurse into source subdirectories 106 | gsutil -m rsync -d -r ./_site gs://dev.lightning.community 107 | ``` 108 | 109 | In the future, you can just run `./deploy.sh` to deploy automatically. 110 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | # Welcome to Jekyll! 2 | # 3 | # This config file is meant for settings that affect your whole blog, values 4 | # which you are expected to set up once and rarely edit after that. If you find 5 | # yourself editing this file very often, consider using Jekyll's data files 6 | # feature for the data you need to update frequently. 7 | # 8 | # For technical reasons, this file is *NOT* reloaded automatically when you use 9 | # 'bundle exec jekyll serve'. If you change this file, please restart the server process. 10 | 11 | # Site settings 12 | # These are used to personalize your new site. If you look in the HTML files, 13 | # you will see them accessed via {{ site.title }}, {{ site.email }}, and so on. 14 | # You can create any custom variable you would like, and they will be accessible 15 | # in the templates via {{ site.myvariable }}. 16 | title: Lightning Network Developers 17 | email: hello@lightning.engineering 18 | description: > # this means to ignore newlines until "baseurl:" 19 | Developer resources and documentation for the Lightning Network Daemon. 20 | baseurl: "" # the subpath of your site, e.g. /blog 21 | url: "http://dev.lightning.community" # the base hostname & protocol for your site, e.g. http://example.com 22 | twitter_username: lightning 23 | github_username: lightningnetwork/lnd 24 | 25 | # Build settings 26 | markdown: kramdown 27 | theme: minima 28 | plugins: 29 | - jekyll-feed 30 | include: ['_pages'] 31 | permalink: pretty 32 | 33 | # Exclude from processing. 34 | # The following items will not be processed, by default. Create a custom list 35 | # to override the default setting. 36 | exclude: 37 | - Gemfile 38 | - Gemfile.lock 39 | - node_modules 40 | - vendor/bundle/ 41 | - vendor/cache/ 42 | - vendor/gems/ 43 | - vendor/ruby/ 44 | - templates 45 | - render.py 46 | - update_and_render.sh 47 | - s3_website.yml 48 | -------------------------------------------------------------------------------- /_includes/footer.html: -------------------------------------------------------------------------------- 1 | 50 | -------------------------------------------------------------------------------- /_includes/head.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | {% if page.title %}{{ page.title | escape }}{% else %}{{ site.title | escape }}{% endif %} 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | {% if jekyll.environment == 'production' and site.google_analytics %} 15 | {% include google-analytics.html %} 16 | {% endif %} 17 | 18 | -------------------------------------------------------------------------------- /_includes/header.html: -------------------------------------------------------------------------------- 1 | 39 | -------------------------------------------------------------------------------- /_includes/icon-github.html: -------------------------------------------------------------------------------- 1 | {% include icon-github.svg %}lnd 2 | -------------------------------------------------------------------------------- /_layouts/home.html: -------------------------------------------------------------------------------- 1 | --- 2 | layout: default 3 | --- 4 | 5 |
6 | 7 |

LND Developer Site

8 | 9 |
10 |

Resources and documentation for the 11 | Lightning Network Daemon (LND) 12 |

13 |
14 | 15 |
16 |

Learn

17 |

New to LND? 18 | Overview, 19 | Installation, and 20 | Tutorial 21 |

22 |

Curious about the Lightning Network? Resources

23 |
24 | 25 |
26 |

Develop

27 |

Looking for detailed dev manuals? Developer Guides

28 |

API Reference Documentation? API site

29 |

Want to help build the future? Contribute

30 |

Looking to read the code? Github

31 |
32 | 33 |
34 |

Community

35 |

Follow the 36 | Lightning Labs community blog 37 | to keep posted about LND. 38 |

39 |

Join the 40 | LND Developer Slack 41 | to meet the team, discuss development, and hang out! 42 |

43 |
44 | 45 |
46 |

Ecosystem

47 |

See the cool apps and wallets built on Lightning: Lapp directory

48 |
49 | 50 |
51 |

Overview

52 |

53 | The Lightning Network scales blockchains and enables trustless instant 54 | payments by keeping most transactions off-chain and leveraging the 55 | security of the underlying blockchain as an arbitration layer. 56 |

57 |

58 | This is accomplished primarily through "payment-channels", wherein two 59 | parties commit funds and pay each other by updating the balance 60 | redeemable by either party in the channel. This process is instant and 61 | saves users from having to wait for block confirmations before they can 62 | render goods or services. 63 |

64 |

65 | Payment channels are trustless, since any attempt to defraud the current 66 | agreed-upon balance in the channel results in the complete forfeiture of 67 | funds by the liable party. 68 |

69 |

70 | By moving payments off-chain, the cost of opening and closing channels 71 | (in the form of on-chain transaction fees) is ammortized over the volume 72 | of payments in that channel, enabling micropayments and small-value 73 | transactions for which the on-chain transaction fees would otherwise be 74 | too expensive to justify. Furthermore, the Lightning Network scales not 75 | with the transaction throughput of the underlying blockchain, but with 76 | modern data processing and latency limits - payments can be made nearly 77 | as quickly as packets can be sent. 78 |

79 |

80 | Hash Time-Locked Contracts (HTLCs) allow transactions to be sent between 81 | parties who do not have a direct channels by routing it through multiple 82 | hops, so anyone connected to the Lightning Network is part of a single, 83 | interconnected global financial system. 84 |

85 |

86 | In short, the Lightning Network enables scalable blockchains through a 87 | high-volume of instant transactions not requiring custodial delegation. 88 |

89 |

90 | Continue reading at the full LND Overview and 91 | Developer Guide. 92 |

93 |
94 | 95 |
96 | -------------------------------------------------------------------------------- /_pages/contribute.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: page 3 | title: Code Contribution Guidelines 4 | permalink: /contribute/ 5 | --- 6 | 7 | ### Table of Contents 8 | 1. [Overview](#Overview)
9 | 2. [Minimum Recommended Skillset](#MinSkillset)
10 | 3. [Required Reading](#ReqReading)
11 | 4. [Development Practices](#DevelopmentPractices)
12 | 4.1. [Share Early, Share Often](#ShareEarly)
13 | 4.2. [Testing](#Testing)
14 | 4.3. [Code Documentation and Commenting](#CodeDocumentation)
15 | 4.4. [Model Git Commit Messages](#ModelGitCommitMessages)
16 | 4.5. [Ideal Git Commit Structure](#IdealGitCommitStructure)
17 | 4.6. [Code Spacing](#CodeSpacing)
18 | 4.7. [Protobuf Compilation](#Protobuf)
19 | 4.8. [Additional Style Constraints On Top of gofmt](ExtraGoFmtStyle)
20 | 5. [Code Approval Process](#CodeApproval)
21 | 5.1. [Code Review](#CodeReview)
22 | 5.2. [Rework Code (if needed)](#CodeRework)
23 | 5.3. [Acceptance](#CodeAcceptance)
24 | 6. [Contribution Standards](#Standards)
25 | 6.1. [Contribution Checklist](#Checklist)
26 | 6.2. [Licensing of Contributions](#Licensing)
27 | 28 | 29 | 30 | ### 1. Overview 31 | 32 | Developing cryptocurrencies is an exciting endeavor that touches a wide variety 33 | of areas such as wire protocols, peer-to-peer networking, databases, 34 | cryptography, language interpretation (transaction scripts), adversarial 35 | threat-modeling, and RPC systems. They also represent a radical shift to the 36 | current fiscal system and as a result provide an opportunity to help reshape 37 | the entire financial system. With the advent of the [Lightning Network 38 | (LN)](https://lightning.network/), new layers are being constructed upon the 39 | base blockchain layer which have the potential to alleviate many of the 40 | limitations and constraints inherent in the design of blockchains. There are 41 | few projects that offer this level of diversity and impact all in one code 42 | base. 43 | 44 | However, as exciting as it is, one must keep in mind that cryptocurrencies 45 | represent real money and introducing bugs and security vulnerabilities can have 46 | far more dire consequences than in typical projects where having a small bug is 47 | minimal by comparison. In the world of cryptocurrencies, even the smallest bug 48 | in the wrong area can cost people a significant amount of money. For this 49 | reason, the Lightning Network Daemon (`lnd`) has a formalized and rigorous 50 | development process (heavily inspired by 51 | [btcsuite](https://github.com/btcsuite)) which is outlined on this page. 52 | 53 | We highly encourage code contributions, however it is imperative that you adhere 54 | to the guidelines established on this page. 55 | 56 | 57 | 58 | ### 2. Minimum Recommended Skillset 59 | 60 | The following list is a set of core competencies that we recommend you possess 61 | before you really start attempting to contribute code to the project. These are 62 | not hard requirements as we will gladly accept code contributions as long as 63 | they follow the guidelines set forth on this page. That said, if you don't have 64 | the following basic qualifications you will likely find it quite difficult to 65 | contribute to the core layers of Lightning. However, there are still a number 66 | of low hanging fruit which can be tackled without having full competency in the 67 | areas mentioned below. 68 | 69 | - A reasonable understanding of bitcoin at a high level (see the 70 | [Required Reading](#ReqReading) section for the original white paper) 71 | - A reasonable understanding of the Lightning Network at a high level 72 | - Experience in some type of C-like language 73 | - An understanding of data structures and their performance implications 74 | - Familiarity with unit testing 75 | - Debugging experience 76 | - Ability to understand not only the area you are making a change in, but also 77 | the code your change relies on, and the code which relies on your changed code 78 | 79 | Building on top of those core competencies, the recommended skill set largely 80 | depends on the specific areas you are looking to contribute to. For example, 81 | if you wish to contribute to the cryptography code, you should have a good 82 | understanding of the various aspects involved with cryptography such as the 83 | security and performance implications. 84 | 85 | 86 | 87 | ### 3. Required Reading 88 | 89 | - [Effective Go](http://golang.org/doc/effective_go.html) - The entire `lnd` 90 | project follows the guidelines in this document. For your code to be accepted, 91 | it must follow the guidelines therein. 92 | - [Original Satoshi Whitepaper](https://bitcoin.org/bitcoin.pdf) - This is the white paper that started it all. Having a solid 93 | foundation to build on will make the code much more comprehensible. 94 | - [Lightning Network Whitepaper](https://lightning.network/lightning-network-paper.pdf) - This is the white paper that kicked off the Layer 2 revolution. Having a good grasp of the concepts of Lightning will make the core logic within the daemon much more comprehensible: Bitcoin Script, off-chain blockchain protocols, payment channels, bi-directional payment channels, relative and absolute time-locks, commitment state revocations, and Segregated Witness. 95 | - The original LN was written for a rather narrow audience, the paper may be a bit unapproachable to many. Thanks to the Bitcoin community, there exist many easily accessible supplemental resources which can help one see how all the pieces fit together from double-spend protection all the way up to commitment state transitions and Hash Time Locked Contracts (HTLCs): 96 | - [Lightning Network Summary](https://lightning.network/lightning-network-summary.pdf) 97 | - [Understanding the Lightning Network 3-Part series](https://bitcoinmagazine.com/articles/understanding-the-lightning-network-part-building-a-bidirectional-payment-channel-1464710791) 98 | - [Deployable Lightning](https://github.com/ElementsProject/lightning/blob/master/doc/deployable-lightning.pdf) 99 | 100 | 101 | Note that the core design of the Lightning Network has shifted over time as 102 | concrete implementation and design has expanded our knowledge beyond the 103 | original white paper. Therefore, specific information outlined in the resources 104 | above may be a bit out of date. Many implementers are currently working on an 105 | initial [Lightning Network Specifications](https://github.com/lightningnetwork/lightning-rfc). 106 | Once the specification is finalized, it will be the most up-to-date 107 | comprehensive document explaining the Lightning Network. As a result, it will 108 | be recommended for newcomers to read first in order to get up to speed. 109 | 110 | 111 | 112 | ### 4. Development Practices 113 | 114 | Developers are expected to work in their own trees and submit pull requests when 115 | they feel their feature or bug fix is ready for integration into the master 116 | branch. 117 | 118 | 119 | 120 | #### 4.1. Share Early, Share Often 121 | 122 | We firmly believe in the share early, share often approach. The basic premise 123 | of the approach is to announce your plans **before** you start work, and once 124 | you have started working, craft your changes into a stream of small and easily 125 | reviewable commits. 126 | 127 | This approach has several benefits: 128 | 129 | - Announcing your plans to work on a feature **before** you begin work avoids 130 | duplicate work 131 | - It permits discussions which can help you achieve your goals in a way that is 132 | consistent with the existing architecture 133 | - It minimizes the chances of you spending time and energy on a change that 134 | might not fit with the consensus of the community or existing architecture and 135 | potentially be rejected as a result 136 | - The quicker your changes are merged to master, the less time you will need to 137 | spend rebasing and otherwise trying to keep up with the main code base 138 | 139 | 140 | 141 | #### 4.2. Testing 142 | 143 | One of the major design goals of all of `lnd`'s packages and the daemon itself is 144 | to aim for a high degree of test coverage. This is financial software so bugs 145 | and regressions in the core logic can cost people real money. For this reason 146 | every effort must be taken to ensure the code is as accurate and bug-free as 147 | possible. Thorough testing is a good way to help achieve that goal. 148 | 149 | Unless a new feature you submit is completely trivial, it will probably be 150 | rejected unless it is also accompanied by adequate test coverage for both 151 | positive and negative conditions. That is to say, the tests must ensure your 152 | code works correctly when it is fed correct data as well as incorrect data 153 | (error paths). 154 | 155 | 156 | Go provides an excellent test framework that makes writing test code and 157 | checking coverage statistics straightforward. For more information about the 158 | test coverage tools, see the [golang cover blog post](http://blog.golang.org/cover). 159 | 160 | A quick summary of test practices follows: 161 | - All new code should be accompanied by tests that ensure the code behaves 162 | correctly when given expected values, and, perhaps even more importantly, that 163 | it handles errors gracefully 164 | - When you fix a bug, it should be accompanied by tests which exercise the bug 165 | to both prove it has been resolved and to prevent future regressions 166 | - Changes to publicly exported packages such as 167 | [brontide](https://github.com/lightningnetwork/lnd/tree/master/brontide) should 168 | be accompanied by unit tests exercising the new or changed behavior. 169 | - Changes to behavior within the daemon's interaction with the P2P protocol, 170 | or RPC's will need to be accompanied by integration tests which use the 171 | [`networkHarness`framework](https://github.com/lightningnetwork/lnd/blob/master/lntest/harness.go) 172 | contained within `lnd`. For example integration tests, see 173 | [`lnd_test.go`](https://github.com/lightningnetwork/lnd/blob/master/lntest/itest/lnd_test.go#L203). 174 | 175 | Throughout the process of contributing to `lnd`, you'll likely also be 176 | extensively using the commands within our `Makefile`. As a result, we recommend 177 | [perusing the make file documentation](https://github.com/lightningnetwork/lnd/blob/master/docs/MAKEFILE.md). 178 | 179 | 180 | 181 | #### 4.3. Code Documentation and Commenting 182 | 183 | - At a minimum every function must be commented with its intended purpose and 184 | any assumptions that it makes 185 | - Function comments must always begin with the name of the function per 186 | [Effective Go](http://golang.org/doc/effective_go.html) 187 | - Function comments should be complete sentences since they allow a wide 188 | variety of automated presentations such as [godoc.org](https://godoc.org) 189 | - The general rule of thumb is to look at it as if you were completely 190 | unfamiliar with the code and ask yourself, would this give me enough 191 | information to understand what this function does and how I'd probably want 192 | to use it? 193 | - Exported functions should also include detailed information the caller of the 194 | function will likely need to know and/or understand:

195 | 196 | **WRONG** 197 | ```go 198 | // generates a revocation key 199 | func DeriveRevocationPubkey(commitPubKey *btcec.PublicKey, 200 | revokePreimage []byte) *btcec.PublicKey { 201 | ``` 202 | **RIGHT** 203 | ```go 204 | // DeriveRevocationPubkey derives the revocation public key given the 205 | // counterparty's commitment key, and revocation preimage derived via a 206 | // pseudo-random-function. In the event that we (for some reason) broadcast a 207 | // revoked commitment transaction, then if the other party knows the revocation 208 | // preimage, then they'll be able to derive the corresponding private key to 209 | // this private key by exploiting the homomorphism in the elliptic curve group: 210 | // * https://en.wikipedia.org/wiki/Group_homomorphism#Homomorphisms_of_abelian_groups 211 | // 212 | // The derivation is performed as follows: 213 | // 214 | // revokeKey := commitKey + revokePoint 215 | // := G*k + G*h 216 | // := G * (k+h) 217 | // 218 | // Therefore, once we divulge the revocation preimage, the remote peer is able to 219 | // compute the proper private key for the revokeKey by computing: 220 | // revokePriv := commitPriv + revokePreimge mod N 221 | // 222 | // Where N is the order of the sub-group. 223 | func DeriveRevocationPubkey(commitPubKey *btcec.PublicKey, 224 | revokePreimage []byte) *btcec.PublicKey { 225 | ``` 226 | - Comments in the body of the code are highly encouraged, but they should 227 | explain the intention of the code as opposed to just calling out the 228 | obvious

229 | 230 | **WRONG** 231 | ```Go 232 | // return err if amt is less than 546 233 | if amt < 546 { 234 | return err 235 | } 236 | ``` 237 | **RIGHT** 238 | ```go 239 | // Treat transactions with amounts less than the amount which is considered dust 240 | // as non-standard. 241 | if amt < 546 { 242 | return err 243 | } 244 | ``` 245 | **NOTE:** The above should really use a constant as opposed to a magic number, 246 | but it was left as a magic number to show how much of a difference a good 247 | comment can make. 248 | 249 |
250 | 251 | #### 4.4. Model Git Commit Messages 252 | 253 | This project prefers to keep a clean commit history with well-formed commit 254 | messages. This section illustrates a model commit message and provides a bit 255 | of background for it. This content was originally created by Tim Pope and made 256 | available on his website, however that website is no longer active, so it is 257 | being provided here. 258 | 259 | Here’s a model Git commit message: 260 | 261 | ``` 262 | Short (50 chars or less) summary of changes 263 | 264 | More detailed explanatory text, if necessary. Wrap it to about 72 265 | characters or so. In some contexts, the first line is treated as the 266 | subject of an email and the rest of the text as the body. The blank 267 | line separating the summary from the body is critical (unless you omit 268 | the body entirely); tools like rebase can get confused if you run the 269 | two together. 270 | 271 | Write your commit message in the present tense: "Fix bug" and not "Fixed 272 | bug." This convention matches up with commit messages generated by 273 | commands like git merge and git revert. 274 | 275 | Further paragraphs come after blank lines. 276 | 277 | - Bullet points are okay, too 278 | - Typically a hyphen or asterisk is used for the bullet, preceded by a 279 | single space, with blank lines in between, but conventions vary here 280 | - Use a hanging indent 281 | ``` 282 | 283 | Here are some of the reasons why wrapping your commit messages to 72 columns is 284 | a good thing. 285 | 286 | - git log doesn't do any special wrapping of the commit messages. With 287 | the default pager of less -S, this means your paragraphs flow far off the edge 288 | of the screen, making them difficult to read. On an 80 column terminal, if we 289 | subtract 4 columns for the indent on the left and 4 more for symmetry on the 290 | right, we’re left with 72 columns. 291 | - git format-patch --stdout converts a series of commits to a series of emails, 292 | using the messages for the message body. Good email netiquette dictates we 293 | wrap our plain text emails such that there’s room for a few levels of nested 294 | reply indicators without overflow in an 80 column terminal. 295 | 296 | In addition to the Git commit message structure adhered to within the daemon 297 | all short-[commit messages are to be prefixed according to the convention 298 | outlined in the Go project](https://golang.org/doc/contribute.html#change). All 299 | commits should begin with the subsystem or package primarily affected by the 300 | change. In the case of a widespread change, the packages are to be delimited by 301 | either a '+' or a ','. This prefix seems minor but can be extremely helpful in 302 | determining the scope of a commit at a glance, or when bug hunting to find a 303 | commit which introduced a bug or regression. 304 | 305 | 306 | 307 | #### 4.5. Ideal Git Commit Structure 308 | 309 | Within the project we prefer small, contained commits for a pull request over a 310 | single giant commit that touches several files/packages. Ideal commits build on 311 | their own, in order to facilitate easy usage of tools like `git bisect` to `git 312 | cherry-pick`. It's preferred that commits contain an isolated change in a 313 | single package. In this case, the commit header message should begin with the 314 | prefix of the modified package. For example, if a commit was made to modify the 315 | `lnwallet` package, it should start with `lnwallet: `. 316 | 317 | In the case of changes that only build in tandem with changes made in other 318 | packages, it is permitted for a single commit to be made which contains several 319 | prefixes such as: `lnwallet+htlcswitch`. This prefix structure along with the 320 | requirement for atomic contained commits (when possible) make things like 321 | scanning the set of commits and debugging easier. In the case of a change that 322 | touches several packages, and can only compile with the change across several 323 | packages, a `multi: ` prefix should be used. 324 | 325 | 326 | 327 | #### 4.6. Code Spacing 328 | 329 | Blocks of code within `lnd` should be segmented into logical stanzas of 330 | operation. Such spacing makes the code easier to follow at a skim, and reduces 331 | unnecessary line noise. Coupled with the commenting scheme specified above, 332 | proper spacing allows readers to quickly scan code, extracting semantics quickly. 333 | Functions should _not_ just be laid out as a bare contiguous block of code. 334 | 335 | **WRONG** 336 | ```go 337 | witness := make([][]byte, 4) 338 | witness[0] = nil 339 | if bytes.Compare(pubA, pubB) == -1 { 340 | witness[1] = sigB 341 | witness[2] = sigA 342 | } else { 343 | witness[1] = sigA 344 | witness[2] = sigB 345 | } 346 | witness[3] = witnessScript 347 | return witness 348 | ``` 349 | **RIGHT** 350 | ```go 351 | witness := make([][]byte, 4) 352 | 353 | // When spending a p2wsh multi-sig script, rather than an OP_0, we add 354 | // a nil stack element to eat the extra pop. 355 | witness[0] = nil 356 | 357 | // When initially generating the witnessScript, we sorted the serialized 358 | // public keys in descending order. So we do a quick comparison in order 359 | // to ensure the signatures appear on the Script Virtual Machine stack in 360 | // the correct order. 361 | if bytes.Compare(pubA, pubB) == -1 { 362 | witness[1] = sigB 363 | witness[2] = sigA 364 | } else { 365 | witness[1] = sigA 366 | witness[2] = sigB 367 | } 368 | 369 | // Finally, add the preimage as the last witness element. 370 | witness[3] = witnessScript 371 | 372 | return witness 373 | ``` 374 | 375 | 376 | 377 | #### 4.7. Protobuf Compilation 378 | 379 | The `lnd` project uses `protobuf`, and its extension [`gRPC`](https://www.grpc.io/) in 380 | several areas and as the primary RPC interface. In order to ensure uniformity 381 | of all protos checked, in we require that all contributors pin against the 382 | _exact same_ version of `protoc`. As of the writing of this article, the `lnd` 383 | project uses [v3.4.0](https://github.com/google/protobuf/releases/tag/v3.4.0) 384 | of `protoc`. 385 | 386 | The following commit hashes of related projects are also required in order to 387 | generate identical compiled protos and related files: 388 | * grpc-ecosystem/grpc-gateway: `f2862b476edcef83412c7af8687c9cd8e4097c0f` 389 | * golang/protobuf: `ab9f9a6dab164b7d1246e0e688b0ab7b94d8553e` 390 | 391 | For detailed instructions on how to compile modifications to `lnd`'s `protobuf` 392 | definitions, check out the [lnrpc README](https://github.com/lightningnetwork/lnd/blob/master/lnrpc/README.md). 393 | 394 | Additionally, in order to maintain a uniform display of the RPC responses 395 | rendered by `lncli`, all added or modified `protof` definitions, _must_ attach 396 | the proper `json_name` option for all fields. An example of such an option can 397 | be found within the definition of the `DebugLevelResponse` struct: 398 | 399 | ```protobuf 400 | message DebugLevelResponse { 401 | string sub_systems = 1 [ json_name = "sub_systems" ]; 402 | } 403 | 404 | ``` 405 | 406 | Notice how the `json_name` field option corresponds with the name of the field 407 | itself, and uses a `snake_case` style of name formatting. All added or modified 408 | `proto` fields should adhere to the format above. 409 | 410 | 411 | 412 | #### 4.8. Additional Style Constraints On Top of `gofmt` 413 | 414 | Before a PR is submitted, the proposer should ensure that the file passes the 415 | set of linting scripts run by `make lint`. These include `gofmt`. In addition 416 | to `gofmt` we've opted to enforce the following style guidelines. 417 | 418 | * ALL columns (on a best effort basis) should be wrapped to 80 line columns. 419 | Editors should be set to treat a tab as 4 spaces. 420 | * When wrapping a line that contains a function call as the unwrapped line 421 | exceeds the column limit, the close paren should be placed on its own 422 | line. Additionally, all arguments should begin in a new line after the 423 | open paren. 424 | 425 | **WRONG** 426 | ```go 427 | value, err := bar(a 428 | a, b, c) 429 | ``` 430 | 431 | **RIGHT** 432 | ```go 433 | value, err := bar( 434 | a, a, b, c, 435 | ) 436 | ``` 437 | 438 | 439 | 440 | ### 5. Code Approval Process 441 | 442 | This section describes the code approval process that is used for code 443 | contributions. This is how to get your changes into `lnd`. 444 | 445 | 446 | 447 | #### 5.1. Code Review 448 | 449 | All code which is submitted will need to be reviewed before inclusion into the 450 | master branch. This process is performed by the project maintainers and usually 451 | other committers who are interested in the area you are working in as well. 452 | 453 | ##### Code Review Timeframe 454 | 455 | The timeframe for a code review will vary greatly depending on factors such as 456 | the number of other pull requests which need to be reviewed, the size and 457 | complexity of the contribution, how well you followed the guidelines presented 458 | on this page, and how easy it is for the reviewers to digest your commits. For 459 | example, if you make one monolithic commit that makes sweeping changes to things 460 | in multiple subsystems, it will obviously take much longer to review. You will 461 | also likely be asked to split the commit into several smaller, and hence more 462 | manageable, commits. 463 | 464 | Keeping the above in mind, most small changes will be reviewed within a few 465 | days, while large or far reaching changes may take weeks. This is a good reason 466 | to stick with the [Share Early, Share Often](#ShareEarly) development practice 467 | outlined above. 468 | 469 | ##### What is the review looking for? 470 | 471 | The review is mainly ensuring the code follows the [Development Practices](#DevelopmentPractices) 472 | and [Code Contribution Standards](#Standards). However, there are a few other 473 | checks which are generally performed as follows: 474 | 475 | - The code is stable and has no stability or security concerns 476 | - The code is properly using existing APIs and generally fits well into the 477 | overall architecture 478 | - The change is not something which is deemed inappropriate by community 479 | consensus 480 | 481 | 482 | 483 | #### 5.2. Rework Code (if needed) 484 | 485 | After the code review, the change will be accepted immediately if no issues are 486 | found. If there are any concerns or questions, you will be provided with 487 | feedback along with the next steps needed to get your contribution merged with 488 | master. In certain cases the code reviewer(s) or interested committers may help 489 | you rework the code, but generally you will simply be given feedback for you to 490 | make the necessary changes. 491 | 492 | During the process of responding to review comments, we prefer that changes be 493 | made with [fixup commits](https://thoughtbot.com/blog/autosquashing-git-commits). 494 | The reason for this is two fold: it makes it easier for the reviewer to see 495 | what changes have been made between versions (since Github doesn't easily show 496 | prior versions like Critique) and it makes it easier on the PR author as they 497 | can set it to auto squash the fix up commits on rebase. 498 | 499 | This process will continue until the code is finally accepted. 500 | 501 | 502 | 503 | #### 5.3. Acceptance 504 | 505 | Once your code is accepted, it will be integrated with the master branch. After 506 | 2+ (sometimes 1) LGTM's (approvals) are given on a PR, it's eligible to land in 507 | master. At this final phase, it may be necessary to rebase the PR in order to 508 | resolve any conflicts and also squash fix up commits. Ideally, the set of 509 | [commits by new contributors are PGP signed](https://git-scm.com/book/en/v2/Git-Tools-Signing-Your-Work), 510 | although this isn't a strong requirement (but we prefer it!). In order to keep 511 | these signatures intact, we prefer using merge commits. PR proposers can use 512 | `git rebase --signoff` to sign and rebase at the same time as a final step. 513 | 514 | Rejoice as you will now be listed as a [contributor](https://github.com/lightningnetwork/lnd/graphs/contributors)! 515 | 516 | 517 | 518 | ### 6. Contribution Standards 519 | 520 | 521 | 522 | #### 6.1. Contribution Checklist 523 | 524 | - [  ] All changes are Go version 1.11 compliant 525 | - [  ] The code being submitted is commented according to the 526 | [Code Documentation and Commenting](#CodeDocumentation) section 527 | - [  ] For new code: Code is accompanied by tests which exercise both 528 | the positive and negative (error paths) conditions (if applicable) 529 | - [  ] For bug fixes: Code is accompanied by new tests which trigger 530 | the bug being fixed to prevent regressions 531 | - [  ] Any new logging statements use an appropriate subsystem and 532 | logging level 533 | - [  ] Code has been formatted with `go fmt` 534 | - [  ] For code and documentation: lines are wrapped at 80 characters 535 | (the tab character should be counted as 8 characters, not 4, as some IDEs do 536 | per default) 537 | - [  ] Running `make unit` and `make itest` do not fail any tests 538 | - [  ] Running `go vet` does not report any issues 539 | - [  ] Running `make lint` does not report any **new** issues that 540 | did not already exist 541 | 542 | 543 | 544 | #### 6.2. Licensing of Contributions 545 | **** 546 | All contributions must be licensed with the 547 | [MIT license](https://github.com/lightningnetwork/lnd/blob/master/LICENSE). This is 548 | the same license as all of the code found within lnd. 549 | 550 | 551 | ## Acknowledgements 552 | This document was heavily inspired by a [similar document outlining the code 553 | contribution](https://github.com/btcsuite/btcd/blob/master/docs/code_contribution_guidelines.md) 554 | guidelines for btcd. 555 | -------------------------------------------------------------------------------- /_pages/lapps.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: page 3 | title: Lightning App Directory 4 | permalink: /lapps/ 5 | --- 6 | 7 | ### Introduction 8 | 9 | This page lists wallets and Lightning apps ("lapps") built on LND, along with several 10 | compatible apps built on Eclair and c-lightning. 11 | 12 | ### Wallets 13 | 14 | * [Lightning App](https://github.com/lightninglabs/lightning-app) by Lightning Labs: 15 | a cross-platform wallet powered by `lnd`. See the announcement for 16 | [desktop](https://blog.lightning.engineering/announcement/2019/04/23mainnet-app.html) 17 | and [mobile](https://blog.lightning.engineering/announcement/2019/06/19/mobile-app.html) 18 | for more information. Checkout the [code](https://github.com/lightninglabs/lightning-app) 19 | and find the releases for 20 | [desktop](https://github.com/lightninglabs/lightning-app/releases), 21 | [Android](https://play.google.com/apps/testing/engineering.lightning.LightningMainnet) 22 | and [iOS](https://testflight.apple.com/join/xx23MrBp). 23 | Screenshot of Lightning Desktop App 24 | 25 | * [Zap](https://zap.jackmallers.com/) Wallet by Jack Mallers: a mobile and desktop app focused on ease of 26 | use and general user experience. Check out the [Zap website](https://zap.jackmallers.com/) or read the code on 27 | [GitHub](https://github.com/LN-Zap). 28 | Zap Wallet payment request view 29 | 30 | * [HTLC.me](https://htlc.me/): Hosted wallet great for quickly trying out 31 | Lightning payments on the Bitcoin testnet. 32 | * [ZeusLN](https://zeusln.app/): 33 | A mobile Bitcoin app for Lightning Network Daemon (lnd) node operators. Runs on Android and iOS. 34 | * [Breez](https://breez.technology/): Breez is a Lightning Network mobile client and a hub. 35 | It provides a platform for simple, instantaneous bitcoin payments. Supports Android and iOS. 36 | 37 | ### Integrations 38 | 39 | * [Bitrefill](https://en.bitrefill.com/): Recharge prepaid phone cards with 40 | Bitcoin and Litecoin 41 | * [Y'alls](http://yalls.org/): Read and write articles, with Lightning Network 42 | micropayments 43 | Screenshot of Yalls home view 44 | * [LNCast](http://lncast.com/): Lightning Network Podcasts 45 | * [Bard](https://www.bard.fun/): Simple paywall for watching a music visualizer 46 | * [HodlHodl.com](https://hodlhodl.com/?set_asset=btcln): Peer-to-peer cryptocurrency 47 | exchange with Lightning integration 48 | * [Zigzag.io](https://zigzag.io/#/): Cryptocurrency trading using Lightning 49 | (custodial) 50 | * [lntxbot](https://telegram.me/lntxbot) Lightning integration to Telegram with 51 | tipping, send and receive and satellite API usage (custodial) 52 | * [paywall.link](https://paywall.link/) Put any website behind a paywall and pay with Lightning 53 | 54 | ### Lightning network explorers 55 | 56 | * [1ml.com](https://1ml.com/) 57 | * [explore.casa](https://explore.casa/) 58 | * [explorer.acinq.co](https://explorer.acinq.co/) 59 | * [ln.alhur.es](https://ln.alhur.es/) 60 | 61 | ### Protocol Services 62 | 63 | * [Lightning Faucet](https://faucet.lightning.community/): Receive free testnet 64 | Bitcoin 65 | * [lnd.fun](http://lnd.fun/): Panel for webmasters to manage their full lightning node 66 | Screenshot of lnd.fun dashboard home view 67 | 68 | ### Developer Tools 69 | 70 | * [WooCommerce 71 | Plugin](https://github.com/joaodealmeida/woocommerce-gateway-lightning): 72 | Gateway plugin to accept Lightning payments at WooCommerce stores 73 | * [LND Explorer](https://demo1.lndexplorer.com/): demo for a web interface for 74 | LND. Code on [Github](https://github.com/altangent/lnd-explorer) 75 | * [Light-weight LND Dashboard](https://github.com/mably/lncli-web): A 76 | lightweight web client for LND 77 | * [LightningJ](http://www.lightningj.org/): A project intending to simplify the 78 | integration of Lightning implementations for Java developers, containing 79 | simple to use API implementations and converters between JSON and XML. 80 | 81 | ### Tipping 82 | * [LightningTip](https://github.com/michael1011/lightningtip): Library to accept 83 | tips via the Lightning Network 84 | * [Slack tipbot](https://github.com/CryptoFR/ln-tip-slack): Custodial Slack 85 | tipbot 86 | * [LightningPay-PHP](https://github.com/robclark56/lightningPay-PHP): PHP plugin 87 | for eCommerce website to add _Pay by Lightning_ to accept order payments via the 88 | Lightning Network. 89 | * [Tippin.me](https://tippin.me/) LN tips integrated to Twitter (custodial) 90 | * [Lightning Gifts](https://lightning.gifts/) Create fee-less Bitcoin gift 91 | vouchers to share with friends, family, and your haters. Powered by the Lightning Network ⚡ 92 | 93 | ### Gaming 94 | * [Lightning Gem](https://lightninggem.com/): Betting game using Lightning for 95 | payments 96 | * [Kriptode.com](https://kriptode.com/) Lightning based games and more. 97 | * [Satoshis.place](https://satoshis.place/) Internet graffiti paid with Lightning 98 | 99 | ### Physical applications 100 | * [Ben Arc](https://twitter.com/BTCSocialist)'s various [projects](https://github.com/arcbtc/) 101 | based on Arduino, ESP32 and the M5Stack. 102 | * [M5StackSats](https://github.com/arcbtc/M5StackSats): 103 | A bitcoin point of sale terminal using the ESP32 based M5Stack 104 | * [Physically faucet](https://github.com/arcbtc/physically-faucet): 105 | A Lightning Network bitcoin faucet using the api 106 | * [Flux capacitor](https://github.com/arcbtc/flux-capacitor): 107 | A dynamic Lightning Network point of sale device 108 | * [The Fossa](https://github.com/arcbtc/The-Fossa): 109 | The Free and Open Source Software (FOSS) ATM, dump that stinky loose fiat change for glorious sats! 110 | * [LightningATM](https://github.com/21isenough/LightningATM): 111 | This ATM accepts coins and sends bitcoin over the Lightning Network 112 | 113 | ### Eclair Lapps 114 | 115 | Eclair is a Scala implementation of the Lightning Network built by [ACINQ](https://acinq.co/) 116 | 117 | * [Eclair](https://github.com/ACINQ/eclair) app: on 118 | [desktop](https://github.com/ACINQ/eclair/releases) and 119 | [Android](https://play.google.com/store/apps/details?id=fr.acinq.eclair.wallet.mainnet2) 120 | * [Starblocks](https://starblocks.acinq.co/#/): Virtual coffee shop 121 | * [Strike](https://strike.acinq.co/#/): Stripe-like Lightning payment aggregator 122 | API (custodial) 123 | * [Lightning Conductor](http://lightningconductor.net/): A service for 124 | converting Lightning balances to BTC and back without having to close 125 | or open channels, currently on testnet. 126 | 127 | ### c-Lightning Lapps 128 | 129 | c-lightning is a specification-compliant LN implementation in C, under the 130 | [Elements Project](https://elementsproject.org/) 131 | 132 | * [Blockstream store](https://store.blockstream.com/) (mainnet): Bitcoin 133 | paraphernalia that can only be purchased over LN. 134 | * [Lightning Charge](https://github.com/ElementsProject/lightning-charge): A 135 | drop-in solution for accepting lightning payments 136 | * [WooCommerce 137 | Plugin](https://github.com/ElementsProject/woocommerce-gateway-lightning): 138 | Original c-lightning version of the Gateway plugin to accept Lightning 139 | payments at WooCommerce stores, based on Lightning Charge. 140 | * [Week of 141 | Lapps](https://blockstream.com/2018/03/29/blockstreams-week-of-lapps-ends.html) 142 | built on Lightning Charge by Nadav Idgi. 143 | * [Nanopos](https://github.com/ElementsProject/nanopos): A simple 144 | point-of-sale system for fixed-price goods 145 | * [FileBazaar](https://github.com/ElementsProject/filebazaar): A system for 146 | selling files such as documents, images, and videos 147 | * [Lightning Publisher for 148 | WordPress](https://github.com/ElementsProject/wordpress-lightning-publisher): 149 | A patronage model for unlocking WordPress blog entries 150 | * [Paypercall](https://github.com/ElementsProject/paypercall): A programmer’s 151 | toolkit for Lightning that enables micropayments for individual API calls 152 | * [Ifpaytt](https://github.com/ElementsProject/ifpaytt): An extension of 153 | paypercall that allows web developers using IFTTT to request payments for 154 | service usage 155 | * [Lightning Jukebox](https://github.com/ElementsProject/lightning-jukebox): 156 | A fun demo that reimagines a classic technology for the Lightning Network 157 | * [Nanotip](https://github.com/ElementsProject/nanotip): The simple tip jar, 158 | rebuilt to issue Lightning Network invoices 159 | * [Elaine Ou's projects](https://elaineou.com/shop/): 160 | * [Lightning-powered vending machine](https://github.com/elaineo/Jellybean) 161 | * [Bitcoin-payable Twitter bot with Lightning Charge](https://github.com/elaineo/lightningbot) 162 | * [Twitter relay for Lightning JSON-RPC interface](https://github.com/elaineo/LightningBuddy) 163 | 164 | ### Requests 165 | 166 | If you would like a Lightning app considered for this page, please send a 167 | link and a one sentence description to . 168 | If applicable, please specify which Lightning implementation it is built on. 169 | -------------------------------------------------------------------------------- /_pages/overview.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: page 3 | title: LND Overview and Developer Guide 4 | permalink: /overview/ 5 | --- 6 | 7 | ### Introduction 8 | 9 | The LND Overview and Developer Guide aims to provide *just* enough information 10 | about LND to enable readers to build applications. It starts with a conceptual 11 | review of the Lightning Network, before jumping into the important aspects of 12 | working specifically with LND. If you are already comfortable with how the 13 | Lightning Network works, feel free to skip down to the [Components](#components) 14 | section. The command line examples are for illustrative purposes only and will 15 | be covered in more depth in the [installation guide](/guides/installation/) and 16 | [tutorial](/tutorial/). 17 | 18 | #### Preliminaries 19 | 20 | This overview assumes basic knowledge of Bitcoin mechanics. If terms like "UTXO" 21 | and "locktime" are unfamiliar to you, you should refer to the [Bitcoin developer 22 | guide](https://bitcoin.org/en/developer-guide), which serves a similar purpose. 23 | 24 | ### Table of Contents 25 | * [Lightning Network](#lightning-network) 26 | * [Payment Channels](#payment-channels) 27 | * [Channel Updates](#channel-updates) 28 | * [Multihop payments](#multihop-payments) 29 | * [Network Topology](#network-topology) 30 | * [Integration Guidelines](#integration-guidelines) 31 | * [Components](#components) 32 | * [Network Layers](#network-layers) 33 | * [Software Components](#software-components) 34 | * [LND Interfaces](#lnd-interfaces) 35 | * [Channel Lifecycle](#channel-lifecycle) 36 | * [Payment Lifecycle](#payment-lifecycle) 37 | * [Payment Requests](#payment-requests) 38 | * [Payment flow](#payment-flow) 39 | * [Conclusion](#conclusion) 40 | 41 | ![Lightning Network Graph](http://imgur.com/xqfllBI.png) 42 | 43 | ### Lightning Network 44 | 45 | The Lightning Network scales blockchains and enables trustless instant payments 46 | by keeping most transactions off-chain and leveraging the security of the 47 | underlying blockchain as an arbitration layer. 48 | 49 | This is accomplished primarily through "payment-channels", wherein two parties 50 | commit funds and pay each other by updating the balance redeemable by either 51 | party in the channel. This process is instant and saves users from having to 52 | wait for block confirmations before they can render goods or services. 53 | 54 | Payment channels are trustless, since any attempt to defraud the current 55 | agreed-upon balance in the channel results in the complete forfeiture of funds 56 | by the liable party. 57 | 58 | By moving payments off-chain, the cost of opening and closing channels (in the 59 | form of on-chain transaction fees) is ammortized over the volume of payments in 60 | that channel, enabling micropayments and small-value transactions for which the 61 | on-chain transaction fees would otherwise be too expensive to justify. 62 | Furthermore, the Lightning Network scales not with the transaction throughput of 63 | the underlying blockchain, but with modern data processing and latency limits - 64 | payments can be made nearly as quickly as packets can be sent. 65 | 66 | Hash Time-Locked Contracts (HTLCs) allow transactions to be sent between parties 67 | who do not have a direct channel by routing them through multiple hops, so anyone 68 | connected to the Lightning Network is part of a single, interconnected global 69 | financial system. 70 | 71 | In short, the Lightning Network enables scalable blockchains through a 72 | high-volume of instant transactions not requiring custodial delegation. 73 | 74 | ### Payment Channels 75 | 76 | Payment channels are the main workhorse of the Lightning Network. They allow 77 | multiple transactions to be aggregated into just a few on-chain transactions. 78 | 79 | In the vast majority of cases, someone only needs to broadcast the first and 80 | last transaction in the channel. 81 | - The Funding Transaction creates the channel. During this stage, funds 82 | are sent into a multisig address controlled by both Alice and Bob, the 83 | counterparties to the channel. This address can be funded as a single-payer 84 | channel or by both Alice and Bob. 85 | - The Closing Transaction closes the channel. When broadcast, the multisig 86 | address spends the funds back to Alice and Bob according to their agreed-upon 87 | channel amount. 88 | 89 | ![Commitment transaction Alice 5BTC Bob 5BTC](http://imgur.com/rqHWEoC.png) 90 | 91 | In the case where either party attempts to defraud the other, a third 92 | transaction, which punishes the attacker, will end up being broadcasted 93 | on-chain. Let's investigate how this is possible by the way Lightning does 94 | channel updates. 95 | 96 | #### Channel Updates 97 | 98 | In between the opening and closing transactions broadcast to the blockchain, 99 | Alice and Bob can create a near infinite number of intermediate closing 100 | transactions that gives different amounts to the two parties. 101 | 102 | For example, if the initial state of the channel credits both Alice and Bob with 103 | 5BTC out of the 10BTC total contained in the multisig address, Alice can make a 104 | 1BTC payment to Bob by updating the closing transaction to pay 4BTC/6BTC, where 105 | Alice is credited with 4BTC and Bob with 6BTC. Alice will give the signed 106 | transaction to Bob, which is equivalent to payment, because Bob can broadcast it 107 | at any time to claim his portion of the funds. Similarly, Alice is also able to 108 | broadcast the closing transaction at any time to claim her funds. 109 | 110 | ![Channel Update Alice 4BTC Bob 6BTC](http://imgur.com/auACasH.png) 111 | 112 | To prevent an attack where Alice voids her payment by broadcasting the initial 113 | state of 5BTC/5BTC, there needs to be a way to revoke prior closing 114 | transactions. Payment revocation roughly works like the following. 115 | 116 | When Alice broadcasts a closing transaction to the blockchain, she is attesting 117 | to the current state of the chain. But since there may be millions of closing 118 | transactions in a channel, all of which are valid, the blockchain itself can't 119 | tell if what Alice attested to was indeed the correct state. Therefore, Alice 120 | must wait 3 days after broadcasting the closing transaction before she can 121 | redeem her funds. During this time, Bob is given a chance to reveal a secret 122 | that will allow him to sweep Alice's funds immediately. Alice can thus revoke 123 | her claim to the money in some state by giving Bob the secret to the closing 124 | transaction. This allows Bob to take all of Alice's money, but only if Alice 125 | attest to this old state by broadcasting the corresponding closing transaction 126 | to the blockchain. 127 | 128 | Channel updates are thus fully trustless. When making an update, both parties 129 | exchange the secrets for the prior state, so that all prior states will have 130 | been revoked except for the current state. Both parties will never broadcast an 131 | old state, because they know the other party can take all their money if they 132 | do so. 133 | 134 | ### Multihop payments 135 | 136 | Single channels work well if you have a financial relationship with some entity 137 | where you make payments frequently or in metered amounts. But most payments, 138 | like purchasing an umbrella from a corner store because you lost it again, are 139 | one-off. For Lightning to help Bitcoin scale for general use cases, there needs 140 | to be a way for the whole network to forward payments through channels that 141 | already exist. Furthermore, this process should retain the trustless nature of 142 | individual channels, otherwise it becomes too hard to identify dishonest actors 143 | amongst a large number of hops. 144 | 145 | Once you don't have to trust the intermediaries, you no longer even care who 146 | they are. This allows Lightning nodes to be fully anonymous, which is a huge win 147 | for privacy. 148 | 149 | Concretely, Suppose Alice has a channel with Bob, who has a channel with Carol, 150 | who has a channel with Dave: `A<->B<->C<->D`. How can Alice pay Dave? 151 | 152 | Alice first notifies Dave that she wants to send him some money. 153 | 154 | In order for Dave to accept this payment, he must generate a random number `R`. 155 | He keeps `R` secret, but hashes it and gives the hash `H` to Alice. 156 | 157 | ![Dave gives hash H to Alice](http://imgur.com/sXuL8Tn.png) 158 | 159 | Alice tells Bob: "I will pay you if you can produce the preimage of `H` within 3 160 | days." In particular, she signs a transaction where for the first three days 161 | after it is broadcast, only Bob can redeem it with knowledge of R, and 162 | afterwards it is redeemable only by Alice. This transaction is called a Hash 163 | Time-Locked Contract (HTLC) and allows Alice to make a conditional promise to 164 | Bob while ensuring that her funds will not be accidentally burned if Bob never 165 | learns what R is. She gives this signed transaction to Bob, but neither of them 166 | broadcast it, because they are expecting to clear it out later. 167 | 168 | ![Alice creates HTLC with Bob](http://imgur.com/aNQoA9Z.png) 169 | 170 | Bob, knowing that he can pull funds from Alice if he knows R, now has no issue 171 | telling Carol: "I will pay you if you can produce the preimage of H within *2* 172 | days." 173 | 174 | Carol does the same, making an HTLC that will pay Dave if Dave can produce R 175 | within 1 day. However, Dave does in fact know R. Because Dave is able to pull 176 | the desired amount from Carol, Dave can consider the payment from Alice 177 | completed. Now, he has no problem telling R to Carol and Bob so that they are 178 | able to collect their funds as well. 179 | 180 | ![Dave distributes R](http://imgur.com/nTLWBbm.png) 181 | 182 | Now, everyone can clear out, because they have a guaranteed way to pull their 183 | deserved funds by broadcasting these HTLCs onto Bitcoin's network (i.e. 184 | on-chain). They would prefer not to do that though, since broadcasting on-chain 185 | is more expensive, and instead settle each of these hops off chain. Alice knows 186 | that Bob can pull funds from her since he has `R`, so she tells Bob: "I'll pay 187 | you, regardless of `R`, and in doing so we'll terminate the HTLC so we can 188 | forget about R." Bob does the same with Carol, and Carol with Dave. 189 | 190 | ![Everyone terminates their HTLCs](http://imgur.com/iRx4bf5.png) 191 | 192 | Now, what if Dave is uncooperative and refuses to give `R` to Bob and Carol? 193 | Note that Dave must broadcast the transaction from Carol within 1 day, and in 194 | doing so must reveal R in order to redeem the funds. Bob and Carol can simply 195 | look at the blockchain to determine what R is and settle off-chain as well. 196 | 197 | We have shown how to make a payment across the Lightning Network using only 198 | off-chain transactions, without requiring direct channel links or trusting any 199 | intermediaries. As long as there is a path from the payer to the payee, payments 200 | can be routed, just like the Internet. 201 | 202 | ### Network Topology 203 | 204 | The expected shape / network topology of the Lightning Network will depend on 205 | behavior implemented in the varying Lightning implementations as well as actual 206 | usage. Users do not have to manually manage their channels, since `lnd` has an 207 | 'autopilot' feature including settings optimizing for both everyday use and fee 208 | revenue. And of course, channels can be opened on demand via the standard 209 | command line, gRPC, and REST interfaces. 210 | 211 | ### Integration guidelines 212 | 213 | When integrating `lnd`, hot and cold storage must be considered. To maximize 214 | security, we generally want to keep as little as possible in hot wallets, and as 215 | much as possible in cold wallets. 216 | 217 | It is possible to construct Lightning channels where the keys are cold, but they 218 | would need to be brought back online to conduct a channel update. Only with hot 219 | wallets can the Lightning Network attain a high volume of transactions. 220 | 221 | This is only a surface level introduction to Lightning integration. For a more 222 | illustrative example of how Lightning Network may work in production, check out 223 | the "Integration Components" and "Security Considerations" sections of the 224 | [Exchange Integration Document](https://docs.google.com/document/d/1r38-_IgtfOkhJh4QbN7l6bl7Rol05qS-i7BjM3AjKOQ/edit) 225 | maintained by Bryan Vu. 226 | 227 | ### Components 228 | 229 | #### Network Layers 230 | 231 | The Lightning Network is an *overlay* network on top of another blockchain. To 232 | avoid confusion it is crucial to differentiate between the following network 233 | layers we encounter when reasoning about `lnd`: 234 | - Bitcoin/Litecoin Network: This is the underlying blockchain that `lnd` rests 235 | on top of. `lnd` needs a way to communicate with the underlying blockchain in 236 | order to send on-chain payments, create channel open/close transactions, and 237 | watch for events on the blockchain. 238 | - P2P Network: This is the peer layer where `lnd` nodes add each other as peers 239 | so they can send messages between one another via an [encrypted 240 | connection](https://github.com/lightningnetwork/lightning-rfc/blob/master/08-transport.md). 241 | For example, the `lncli connect` adds a peer, which are identified by identity 242 | pubkey and IP address. 243 | - Payment channel network: This is the layer where nodes are connected by 244 | payment channels. For example, the `lncli openchannel` command opens a 245 | channel with a node that was already connected at the peer layer, and the 246 | `lncli describegraph` command returns the list of edges and vertices of the 247 | payment channel graph. 248 | 249 | #### Software Components 250 | 251 | There are distinct software components we should be aware of when developing on 252 | - [`btcd`](https://github.com/btcsuite/btcd) or [`bitcoind`](https://github.com/bitcoin/bitcoin) is used by `lnd` to interface with the underlying blockchain. 253 | - `lnd` / `lncli`: LND stands for Lightning Network Daemon and serves as the 254 | main software component driving the Lightning Network. It manages a database, 255 | connects to peers, opens / closes channels, generates payment invoices, sends, 256 | forwards, and revokes payments, responds to potential breaches, and more. 257 | `lncli` opens up a command line interface for driving `lnd`. 258 | - [Neutrino](https://github.com/lightninglabs/neutrino) is an experimental 259 | Bitcoin light client designed to support Lightning mobile clients. This is a 260 | wallet UI usable with `lnd`. Neutrino is not required from an application 261 | development standpoint, but can be regarded as the primary way for an 262 | end-user of `lnd` to interact with the Bitcoin Network and the applications 263 | built on top of it. 264 | 265 | #### LND Interfaces 266 | 267 | There are several ways to drive `lnd`. 268 | 269 | - `lncli` is the `lnd` command line tool. All commands are executed 270 | instantaneously. A full list of commands can be viewed with `lncli --help`. 271 | To see a breakdown of the parameters for a particular command, run 272 | `lncli --help` 273 | - gRPC is the preferred programmatic way to interact with `lnd`. It includes simple 274 | methods that return a response immediately, as well as response-streaming and 275 | bidrectional streaming methods. Check out the guides for working with gRPC for 276 | [Python](/guides/python-grpc/) and [Javascript](/guides/javascript-grpc/) 277 | - LND also features a REST proxy someone can use if they are accustomed to 278 | standard RESTful APIs. However, REST does not have full streaming RPC coverage. 279 | 280 | All of these LND interfaces are documented in the [API 281 | Reference](//api.lightning.community), featuring a description of the 282 | parameters, responses, and code examples for Python, Javascript, and command 283 | line arguments if those exist. 284 | 285 | ### Channel Lifecycle 286 | 287 | To better understand the development workflow around Lightning channels, it is 288 | worthwhile to examine step by step the lifecycle of a payment channel. It 289 | contains roughly 4 steps: 290 | 291 | 1. **Adding a peer.** Before a channel can be opened between two Lightning 292 | nodes, they must first be able to securely communicate with each other. This 293 | is accomplished with the `ConnectPeer` RPC method or `connect` on `lncli`. 294 | ```shell 295 | lncli connect @: 296 | ``` 297 | 2. **Initiating Channel Opening.** The `OpenChannel` method begins the channel 298 | opening process with a connected peer. Lightning assumes that this is led by 299 | a single party. The opening party can specify a local amount, representing 300 | the funds they would like to commit to the channel, and a "push" amount, the 301 | amount of money that they would like to give to the other side as part of an 302 | initial commitment state. One could imagine that instead of sending a 303 | standard Bitcoin transaction to pay a merchant, they could instead open a 304 | channel with the push amount representing the amount they want to pay, and 305 | optionally add some funds of their own, so that both parties can benefit from 306 | having a channel available for payments in the future. 307 | ```shell 308 | lncli openchannel --node_key= --local_amt= 309 | ``` 310 | Lightning Wallet App Open Channel 311 | 3. **Wait for confirmations.** To prevent double spending attacks on the channel 312 | opening transaction, users should specify the `--block` `lncli` command line 313 | argument. So after initializing the channel opening process, it is often 314 | required to mine a few blocks: 315 | ```shell 316 | btcctl generate 6 317 | ``` 318 | 4. **Close Channel.** If either party in a channel no longer wants to keep it 319 | open, they can close it at any time with the `CloseChannel` method. 320 | ```shell 321 | lncli closechannel --funding_txid= --output_index= 322 | ``` 323 | 324 | ### Payment Lifecycle 325 | 326 | Because Lightning payments are instant, its API tends to be much simpler, since 327 | there is no need to wait for block confirmations before a payment is considered 328 | accepted. It resembles a fairly standard payment flow, but there are a few 329 | additional things to keep in mind. 330 | 331 | #### Payment Requests 332 | 333 | Payment requests, often also referred to as Invoices, are a simple, extensible 334 | protocol compatible with QR-codes. It includes a 6-character checksum in case 335 | there is a mistake with copy/paste or manual entry. 336 | 337 | Payment requests are composed of two sections: 338 | 1. **Human readable part:** Contains a prefix `ln` followed by an optional 339 | amount. 340 | 2. **Data part**: Contains a UTC Unix timestamp and optionally some tagged 341 | parts, as well as a signature over the human readable and data parts. 342 | - Tagged parts include a payment hash, the pubkey of the payee node, a 343 | description of the purpose of payment, an expiration time (default to 1 344 | hour if not specified), and extra routing information. Some tagged parts 345 | are required and others are not. 346 | 347 | Because the payment request contains the payment hash, **payment requests must 348 | be strictly single use**. After an invoice is fulfilled, the hash preimage 349 | becomes publically known. An attacker could save the preimages they've seen and 350 | reuse it for another payment that is reusing the invoice. Therefore, **failure 351 | to generate new payment requests means that an on-path attacker can steal the 352 | payment en route.** 353 | 354 | Another detail worth noting is that payees should not accept payments after the 355 | payment request has expired (`timestamp` + `expiry`), and payers likewise should 356 | not attempt them. This will affect any web application with `lnd` integration, 357 | since if an invoice for a good or service is not fulfilled within the given 358 | timeframe, a new one should be generated. 359 | 360 | Other possibly unexpected rules include that the payee should accept up to 361 | twice the amount encoded in the transaction, so that the payer can make payments 362 | harder to track by adding in small variations. 363 | 364 | A full specification of the payment request data format, required and optional 365 | parts, and required behavior can be found in [BOLT 366 | 11](https://github.com/lightningnetwork/lightning-rfc/blob/master/11-payment-encoding.md). 367 | 368 | #### Payment flow 369 | 370 | Let's now see what an ideal payment flow looks like. 371 | 372 | 1. **Create Invoice:** The recipient creates an invoice with a specified value, 373 | expiration time, and an optional memo. If there was already an invoice 374 | created for this good and it expired, or a sufficient amount of time has 375 | elapsed, a fresh invoice should be generated. 376 | ```shell 377 | lncli addinvoice --amt=6969 --memo="A coffee for Roger" 378 | ``` 379 | Lightning Wallet Generate Payment Request 380 | 2. **Check invoice:** The payer decodes the invoice to see the destination, 381 | amount and payment hash. This way, they can validate that the invoice was 382 | legitimate, and that they aren't being defrauded or overcharged. At this 383 | stage, the user should also check that the expiration time of the invoice has 384 | not passed 385 | ```shell 386 | lncli decodepayreq --pay_req= 387 | ``` 388 | 3. **Send payment:** The payer sends their payment, possibly routed through the 389 | Lightning Network. Developers can do this through an LND interface and end 390 | users can use the desktop or mobile app. 391 | ```shell 392 | lncli sendpayment --pay_req= 393 | ``` 394 | Lightning Wallet send payment screen 395 | 4. **Check payment:** The recipient checks that their invoice has been 396 | fulfilled. They make a call to the `LookupInvoice` command, which returns 397 | this information in the `settled` field. 398 | ```shell 399 | lncli lookupinvoice --rhash= 400 | ``` 401 | Lightning Wallet 5BTC Received 402 | 403 | We have now covered the basic workflow for generating invoices and 404 | sending/receiving payments. 405 | 406 | ### Conclusion 407 | 408 | You have completed the conceptual overview of LND and a high level primer on the 409 | components and workflows. To get started on developing, check out the 410 | [installation guide](/guides/installation/) and [tutorial](/tutorial/). 411 | -------------------------------------------------------------------------------- /_pages/resources.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: page 3 | title: Lightning Resources 4 | permalink: /resources/ 5 | --- 6 | 7 | ### Overview 8 | 9 | This page is for those seeking to develop on LND or enhance their conceptual 10 | understanding of the Lightning Network and associated technologies. It is not 11 | comprehensive, but a careful study of the materials below should be sufficient 12 | for anyone's needs. 13 | 14 | ### Lightning: Beginner 15 | 16 | * [What is the Lightning Network and how can it help Bitcoin scale?](https://coincenter.org/entry/what-is-the-lightning-network) 17 | article by Elizabeth Stark 18 | * Accessible article explanation of the Lightning Network by Elizabeth Stark, 19 | the CEO of Lightning Labs. 20 | 21 | * [The Blockchain and Us: Interview with Elizabeth Stark](https://www.youtube.com/watch?v=a3HulqfzyYE) 22 | * Quick 7 minute primer on the Lightning Network and its implications. 23 | 24 | * [Joseph Poon discusses Lightning 25 | at Construct 2017](http://www.coindesk.com/events/construct-2017/videos/) 26 | (ctrl+f for "Lightning") 27 | * In-depth spoken explanation of the Lightning Network for the general 28 | audience. Note that this video requires providing CoinDesk an email address. 29 | 30 | * ["Understanding the Lightning 31 | Network"](https://bitcoinmagazine.com/articles/understanding-the-lightning-network-part-building-a-bidirectional-payment-channel-1464710791/): 32 | Aaron van Wirdum's General Explainer Series 33 | * In-depth written explanation great for non-developers. 34 | * [Part 1](https://bitcoinmagazine.com/articles/understanding-the-lightning-network-part-building-a-bidirectional-payment-channel-1464710791/): 35 | Building a Bidirectional Bitcoin Payment Channel 36 | * [Part 2](https://bitcoinmagazine.com/articles/understanding-the-lightning-network-part-creating-the-network-1465326903/): 37 | Creating the Network 38 | * [Part 3](https://bitcoinmagazine.com/articles/understanding-the-lightning-network-part-completing-the-puzzle-and-closing-the-channel-1466178980/): 39 | Completing the Puzzle and Closing the Channel 40 | 41 | * [#bitcoin-lightning - Things to Know](https://medium.com/@rusty_lightning/bitcoin-lightning-things-to-know-e5ea8d84369f): 42 | Rusty Russell addresses FAQs about Lightning, including its requirements, 43 | limitations, segwit, and expected network dynamics. 44 | 45 | ### Lightning: Intermediate 46 | 47 | * [Lightning Network Tech 48 | Talk](https://www.youtube.com/watch?v=wIhAmTqXhZQ) at Coinbase January 49 | 2016 50 | * Spoken in-depth mechanics of bidirectional payment channels and multi-hop 51 | payments 52 | 53 | * [Lightning Networks](https://rusty.ozlabs.org/?p=450): 54 | Rusty Russell's Technical Explainer Series 55 | * In-depth explanation of Lightning, oriented towards developers. 56 | * [Part I](https://rusty.ozlabs.org/?p=450): Revocable Transactions 57 | * [Part II](https://rusty.ozlabs.org/?p=462): Hashed Timelock Contracts (HTLCs) 58 | * [Part III](https://rusty.ozlabs.org/?p=467): Channeling Contracts 59 | * [Part IV](https://rusty.ozlabs.org/?p=477): Summary 60 | 61 | * [Lightning Network Paper](https://lightning.network/lightning-network-paper.pdf) 62 | published February 2015, last updated January 2016 63 | * The protocol has changed since this original paper, but covers the mid-level 64 | mechanics of the Lightning Network with an emphasis on the smart contracts 65 | that make it trustless 66 | * Combines the HTLC and channel update concepts together 67 | * Explains how the Lightning Network is represented in Bitcoin transaction 68 | based contracts, and how the Lightning Network works with the UTXO model. 69 | 70 | * [Lightning Network Community Blog](http://lightning.community), managed by 71 | Lightning Labs. 72 | * Stay up to date with the latest about LND and the Lightning Network! 73 | 74 | ### Lightning: Advanced 75 | 76 | * Read the code on Github: [`lnd`](https://github.com/lightningnetwork/lnd) 77 | 78 | * [Basis Of Lightning 79 | Technology (BOLTs)](https://github.com/lightningnetwork/lightning-rfc/blob/master/00-introduction.md) 80 | * Full technical specification of the Lightning Network. BOLTs are the 81 | common standard enabling distinct, interoperable Lightning implementations. 82 | * [BOLT #0](https://github.com/lightningnetwork/lightning-rfc/blob/master/00-introduction.md): 83 | Introduction and Index 84 | * [BOLT #1](https://github.com/lightningnetwork/lightning-rfc/blob/master/01-messaging.md): 85 | Base Protocol 86 | * [BOLT #2](https://github.com/lightningnetwork/lightning-rfc/blob/master/02-peer-protocol.md): 87 | Peer Protocol for Channel Management 88 | * [BOLT #3](https://github.com/lightningnetwork/lightning-rfc/blob/master/03-transactions.md): 89 | Bitcoin Transaction and Script Formats 90 | * [BOLT #4](https://github.com/lightningnetwork/lightning-rfc/blob/master/04-onion-routing.md): 91 | Onion Routing Protocol 92 | * [BOLT #5](https://github.com/lightningnetwork/lightning-rfc/blob/master/05-onchain.md): 93 | Recommendations for On-chain Transaction Handling 94 | * [BOLT #6](https://github.com/lightningnetwork/lightning-rfc/blob/master/06-irc-announcements.md): 95 | Interim Node and Channel Discovery 96 | * [BOLT #7](https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md): 97 | P2P Node and Channel Discovery 98 | * [BOLT #8](https://github.com/lightningnetwork/lightning-rfc/blob/master/08-transport.md): 99 | Encrypted and Authenticated Transport 100 | * [BOLT #9](https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md): 101 | Assigned Feature Flags 102 | * [BOLT #11](https://github.com/lightningnetwork/lightning-rfc/blob/master/11-payment-encoding.md): 103 | Invoice Protocol for Lightning Payments 104 | 105 | * [Lightning Network Deep 106 | Dive](https://www.youtube.com/watch?v=b_szGaaPPFk) talk at SF Bitcoin Devs 107 | August 2016 108 | * Commitment scheme: Compact revocation derivation and storage 109 | * Revocation scheme: Pre-image derived revocation keys (homomorphic 110 | derivation) 111 | * Lightning Commitment Protocol: the fast link-layer protocol between two 112 | Lightning nodes 113 | * LND architecture 114 | 115 | * [Lightning Network as a Directed Graph: Single-Funded Channel Network 116 | Topology](https://www.youtube.com/watch?v=-lgYYz3y_hY) talk at SF Bitcoin Devs 117 | April 2016 118 | * Covers single funded channels and channel exhaustion 119 | * Covers how to construct sub-satoshi micropayments: "Pre-Image Length 120 | Probabilistic Payments" 121 | 122 | * [Onion Routing in Lightning](https://youtu.be/Gzg_u9gHc5Q?t=2m47s) - Laolu 123 | Osuntokun at Scaling Bitcoin Milan 2016 (starts at 2:47) 124 | * A way to preserve privacy in the Lightning Network 125 | * [Video](https://youtu.be/Gzg_u9gHc5Q?t=2m47s), 126 | [transcript](https://scalingbitcoin.org/transcript/milan2016/onion-routing-in-lightning) 127 | 128 | * [Outsourced Channel Monitoring](https://youtu.be/Gzg_u9gHc5Q?t=48m12s) - Tadge 129 | Dryja at Scaling Bitcoin Milan 2016 (starts at 48:12) 130 | * Outsourced channel monitoring: delegating the task of channel monitoring to 131 | a semi-trusted peer 132 | * [Video](https://youtu.be/Gzg_u9gHc5Q?t=48m12s), [slides](https://scalingbitcoin.org/milan2016/presentations/D1%20-%208%20-%20Tadge%20Dryja.pdf), [transcript](https://scalingbitcoin.org/transcript/milan2016/unlinkable-outsourced-channel-monitoring) 133 | 134 | ### LND Developer Tools 135 | 136 | * [Developer Guides](/guides/) 137 | * Guides walking you through installation, docker setup, Python / Javascript 138 | gRPC, and more 139 | * [API documentation](https://api.lightning.community) 140 | * API Reference documentation for the Lightning Network Daemon 141 | * Lightning Faucet for [Bitcoin testnet](https://faucet.lightning.community/) or 142 | [Litecoin testnet](https://ltc.faucet.lightning.community/) 143 | * To read more, build from source, or deploy your own faucet see the [Github 144 | repository](https://github.com/lightninglabs/lightning-faucet) 145 | * [LND Web Dashboard](https://github.com/mably/lncli-web) 146 | * A web client and dashboard made by Francis Mably. Useful as a more 147 | customizable client or as a starting point for a Lightning project 148 | * [Lightning Apps and the Emerging Developer Ecosystem on LND](http://lightning.community/software/lnd/lightning/2017/07/05/emerging-lightning-developer-ecosystem/) 149 | * A survey of existing apps built on Lightning, as of July 2017. Potentially 150 | useful as inspiration or code examples 151 | * Neutrino: A Bitcoin Light Client used in LND 152 | * [Compact Client Side Filtering for Light Clients](https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2017-June/014474.html) 153 | on Bitcoin Dev Mailing List 154 | * [Neutrino BIP (Bitcoin Improvement Proposal)](https://github.com/Roasbeef/bips/blob/master/gcs_light_client.mediawiki) 155 | * [Github repository](https://github.com/lightninglabs/neutrino) 156 | 157 | ### LND Community 158 | 159 | * LND Developer Slack 160 | * Come here to meet the Lightning community, ask for help, and hang out! 161 | * [invite link](https://join.slack.com/t/lightningcommunity/shared_invite/enQtMzQ0OTQyNjE5NjU1LWRiMGNmOTZiNzU0MTVmYzc1ZGFkZTUyNzUwOGJjMjYwNWRkNWQzZWE3MTkwZjdjZGE5ZGNiNGVkMzI2MDU4ZTE) 162 | 163 | * [#lnd](https://webchat.freenode.net/?channels=lnd) IRC 164 | * [![Irc](https://img.shields.io/badge/chat-on%20freenode-brightgreen.svg)](https://webchat.freenode.net/?channels=lnd) 165 | 166 | * [#lightning-dev](https://webchat.freenode.net/?channels=lightning-dev) IRC 167 | * [![Irc](https://img.shields.io/badge/chat-on%20freenode-brightgreen.svg)](https://webchat.freenode.net/?channels=lightning-dev) 168 | 169 | 170 | If something important is missing, or you feel that additional resources or 171 | links would be helpful, please send a message in the [LND Developer Slack](https://join.slack.com/t/lightningcommunity/shared_invite/enQtMzQ0OTQyNjE5NjU1LWRiMGNmOTZiNzU0MTVmYzc1ZGFkZTUyNzUwOGJjMjYwNWRkNWQzZWE3MTkwZjdjZGE5ZGNiNGVkMzI2MDU4ZTE) 172 | -------------------------------------------------------------------------------- /_posts/2017-06-26-welcome-to-jekyll.markdown: -------------------------------------------------------------------------------- 1 | --- 2 | layout: post 3 | title: "Welcome to Jekyll!" 4 | date: 2017-06-26 14:18:14 -0700 5 | categories: jekyll update 6 | --- 7 | You’ll find this post in your `_posts` directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but the most common way is to run `jekyll serve`, which launches a web server and auto-regenerates your site when a file is updated. 8 | 9 | To add new posts, simply add a file in the `_posts` directory that follows the convention `YYYY-MM-DD-name-of-post.ext` and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works. 10 | 11 | Jekyll also offers powerful support for code snippets: 12 | 13 | {% highlight ruby %} 14 | def print_hi(name) 15 | puts "Hi, #{name}" 16 | end 17 | print_hi('Tom') 18 | #=> prints 'Hi, Tom' to STDOUT. 19 | {% endhighlight %} 20 | 21 | Check out the [Jekyll docs][jekyll-docs] for more info on how to get the most out of Jekyll. File all bugs/feature requests at [Jekyll’s GitHub repo][jekyll-gh]. If you have questions, you can ask them on [Jekyll Talk][jekyll-talk]. 22 | 23 | [jekyll-docs]: https://jekyllrb.com/docs/home 24 | [jekyll-gh]: https://github.com/jekyll/jekyll 25 | [jekyll-talk]: https://talk.jekyllrb.com/ 26 | -------------------------------------------------------------------------------- /_sass/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lightninglabs/lightning-dev-site/a5c489b7467ccfe94e42d13997fde3a752186575/_sass/.DS_Store -------------------------------------------------------------------------------- /_sass/minima.scss: -------------------------------------------------------------------------------- 1 | @charset "utf-8"; 2 | 3 | // Define defaults for each variable. 4 | 5 | $base-font-family: "Helvetica Neue", Helvetica, Arial, sans-serif !default; 6 | $base-font-size: 16px !default; 7 | $base-font-weight: 400 !default; 8 | $small-font-size: $base-font-size * 0.875 !default; 9 | $base-line-height: 1.5 !default; 10 | 11 | $spacing-unit: 20px !default; 12 | 13 | $text-color: #111 !default; 14 | $background-color: #fdfdfd !default; 15 | $brand-color: #6a33e2 !default; 16 | $lightning-blue: #3a8aff !default; 17 | $lightning-dkpurple: #17062d !default; 18 | $lightning-white: white !default; 19 | 20 | $grey-color: #828282 !default; 21 | $grey-color-light: lighten($grey-color, 40%) !default; 22 | $grey-color-dark: darken($grey-color, 25%) !default; 23 | 24 | // Width of the content area 25 | $content-width: 800px !default; 26 | 27 | $on-palm: 600px !default; 28 | $on-laptop: 800px !default; 29 | 30 | // Use media queries like this: 31 | // @include media-query($on-palm) { 32 | // .wrapper { 33 | // padding-right: $spacing-unit / 2; 34 | // padding-left: $spacing-unit / 2; 35 | // } 36 | // } 37 | @mixin media-query($device) { 38 | @media screen and (max-width: $device) { 39 | @content; 40 | } 41 | } 42 | 43 | @mixin relative-font-size($ratio) { 44 | font-size: $base-font-size * $ratio; 45 | } 46 | 47 | // Import partials. 48 | @import 49 | "minima/base", 50 | "minima/layout", 51 | "minima/syntax-highlighting" 52 | ; 53 | -------------------------------------------------------------------------------- /_sass/minima/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lightninglabs/lightning-dev-site/a5c489b7467ccfe94e42d13997fde3a752186575/_sass/minima/.DS_Store -------------------------------------------------------------------------------- /_sass/minima/_base.scss: -------------------------------------------------------------------------------- 1 | /** 2 | * Reset some basic elements 3 | */ 4 | body, h1, h2, h3, h4, h5, h6, 5 | p, blockquote, pre, hr, 6 | dl, dd, ol, ul, figure { 7 | margin: 0; 8 | padding: 0; 9 | } 10 | 11 | 12 | 13 | /** 14 | * Basic styling 15 | */ 16 | body { 17 | font: $base-font-weight #{$base-font-size}/#{$base-line-height} $base-font-family; 18 | color: $text-color; 19 | background-color: $background-color; 20 | -webkit-text-size-adjust: 100%; 21 | -webkit-font-feature-settings: "kern" 1; 22 | -moz-font-feature-settings: "kern" 1; 23 | -o-font-feature-settings: "kern" 1; 24 | font-feature-settings: "kern" 1; 25 | font-kerning: normal; 26 | 27 | line-height: 23px; /*adjust as needed, slightly higher than default line-height will help with readability */ 28 | } 29 | 30 | 31 | 32 | /** 33 | * Set `margin-bottom` to maintain vertical rhythm 34 | */ 35 | h1, h2, h3, h4, h5, h6, 36 | p, blockquote, pre, 37 | ul, ol, dl, figure, 38 | %vertical-rhythm { 39 | margin-bottom: $spacing-unit; 40 | } 41 | 42 | 43 | 44 | /** 45 | * Images 46 | */ 47 | img { 48 | max-width: 100%; 49 | vertical-align: middle; 50 | } 51 | 52 | 53 | 54 | /** 55 | * Figures 56 | */ 57 | figure > img { 58 | display: block; 59 | } 60 | 61 | figcaption { 62 | font-size: $small-font-size; 63 | } 64 | 65 | 66 | 67 | /** 68 | * Lists 69 | */ 70 | ul, ol { 71 | margin-left: $spacing-unit; 72 | } 73 | 74 | li { 75 | > ul, 76 | > ol { 77 | margin-bottom: 0; 78 | } 79 | } 80 | 81 | 82 | 83 | /** 84 | * Headings 85 | */ 86 | h1, h2, h3, h4, h5, h6 { 87 | font-weight: $base-font-weight; 88 | } 89 | 90 | 91 | 92 | /** 93 | * Links 94 | */ 95 | a { 96 | color: $brand-color; 97 | text-decoration: none; 98 | 99 | /* Blue used for a:visited and text */ 100 | &:visited { 101 | color: $lightning-blue; 102 | } 103 | 104 | &:hover { 105 | // color: $text-color; 106 | // color: darken($brand-color, 15%); 107 | text-decoration: underline; 108 | } 109 | 110 | .social-media-list &:hover { 111 | text-decoration: none; 112 | 113 | .username { 114 | text-decoration: underline; 115 | } 116 | } 117 | } 118 | 119 | 120 | /** 121 | * Blockquotes 122 | */ 123 | blockquote { 124 | color: $grey-color; 125 | border-left: 4px solid $grey-color-light; 126 | padding-left: $spacing-unit / 2; 127 | @include relative-font-size(1.125); 128 | letter-spacing: -1px; 129 | font-style: italic; 130 | 131 | > :last-child { 132 | margin-bottom: 0; 133 | } 134 | } 135 | 136 | 137 | 138 | /** 139 | * Code formatting 140 | */ 141 | pre, 142 | code { 143 | @include relative-font-size(0.9375); 144 | border: 1px solid $grey-color-light; 145 | border-radius: 3px; 146 | background-color: #eef; 147 | } 148 | 149 | code { 150 | padding: 1px 5px; 151 | } 152 | 153 | pre { 154 | padding: 8px 12px; 155 | overflow-x: auto; 156 | 157 | > code { 158 | border: 0; 159 | padding-right: 0; 160 | padding-left: 0; 161 | } 162 | } 163 | 164 | 165 | 166 | /** 167 | * Wrapper 168 | */ 169 | .wrapper { 170 | max-width: -webkit-calc(#{$content-width} - (#{$spacing-unit} * 2)); 171 | max-width: calc(#{$content-width} - (#{$spacing-unit} * 2)); 172 | margin-right: auto; 173 | margin-left: auto; 174 | padding-right: $spacing-unit; 175 | padding-left: $spacing-unit; 176 | @extend %clearfix; 177 | 178 | @include media-query($on-laptop) { 179 | max-width: -webkit-calc(#{$content-width} - (#{$spacing-unit})); 180 | max-width: calc(#{$content-width} - (#{$spacing-unit})); 181 | padding-right: $spacing-unit / 2; 182 | padding-left: $spacing-unit / 2; 183 | } 184 | } 185 | 186 | 187 | 188 | /** 189 | * Clearfix 190 | */ 191 | %clearfix:after { 192 | content: ""; 193 | display: table; 194 | clear: both; 195 | } 196 | 197 | 198 | 199 | /** 200 | * Icons 201 | */ 202 | .icon > svg { 203 | display: inline-block; 204 | vertical-align: middle; 205 | 206 | path { 207 | fill: $grey-color; 208 | } 209 | } 210 | 211 | .social-media-list { 212 | .icon { 213 | padding-right: 5px; 214 | } 215 | 216 | li + li { 217 | padding-top: 5px; 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /_sass/minima/_layout.scss: -------------------------------------------------------------------------------- 1 | /** 2 | * Site header 3 | */ 4 | .site-header { 5 | border-top: 5px solid $grey-color-dark; 6 | border-bottom: 1px solid $grey-color-light; 7 | min-height: $spacing-unit * 1.865; 8 | 9 | // Positioning context for the mobile navigation icon 10 | position: relative; 11 | 12 | color: $lightning-white; 13 | background-color: $lightning-dkpurple; 14 | } 15 | 16 | .site-title { 17 | @include relative-font-size(1.625); 18 | font-weight: 300; 19 | 20 | line-height: $base-line-height * $base-font-size * 2.25; 21 | letter-spacing: -1px; 22 | margin-bottom: 0; 23 | float: left; 24 | 25 | &, 26 | &:visited { 27 | // color: $grey-color-dark; 28 | color: $lightning-white; 29 | } 30 | } 31 | 32 | .site-nav { 33 | float: right; 34 | line-height: $base-line-height * $base-font-size * 2.25; 35 | 36 | .nav-trigger { 37 | display: none; 38 | } 39 | 40 | .menu-icon { 41 | display: none; 42 | } 43 | 44 | .page-link { 45 | color: $lightning-white; 46 | // color: $text-color; 47 | 48 | line-height: $base-line-height; 49 | 50 | // Gaps between nav items, but not on the last one 51 | &:not(:last-child) { 52 | margin-right: 20px; 53 | } 54 | } 55 | 56 | @include media-query($on-palm) { 57 | position: absolute; 58 | top: 9px; 59 | right: $spacing-unit / 2; 60 | background-color: $background-color; 61 | border: 1px solid $grey-color-light; 62 | border-radius: 5px; 63 | text-align: right; 64 | 65 | label[for="nav-trigger"] { 66 | display: block; 67 | float: right; 68 | width: 36px; 69 | height: 36px; 70 | z-index: 2; 71 | cursor: pointer; 72 | } 73 | 74 | .menu-icon { 75 | display: block; 76 | float: right; 77 | width: 36px; 78 | height: 26px; 79 | line-height: 0; 80 | padding-top: 10px; 81 | text-align: center; 82 | 83 | > svg path { 84 | fill: $grey-color-dark; 85 | } 86 | } 87 | 88 | input ~ .trigger { 89 | clear: both; 90 | display: none; 91 | } 92 | 93 | input:checked ~ .trigger { 94 | display: block; 95 | padding-bottom: 5px; 96 | } 97 | 98 | .page-link { 99 | display: block; 100 | padding: 5px 10px; 101 | 102 | &:not(:last-child) { 103 | margin-right: 0; 104 | } 105 | margin-left: 20px; 106 | } 107 | } 108 | } 109 | 110 | 111 | 112 | /** 113 | * Site footer 114 | */ 115 | .site-footer { 116 | border-top: 1px solid $grey-color-light; 117 | padding: $spacing-unit 0; 118 | 119 | color: $lightning-white; 120 | background-color: $lightning-dkpurple; 121 | } 122 | 123 | .footer-heading { 124 | @include relative-font-size(1.125); 125 | margin-bottom: $spacing-unit / 2; 126 | } 127 | 128 | .contact-list, 129 | .social-media-list { 130 | list-style: none; 131 | margin-left: 0; 132 | } 133 | 134 | .footer-col-wrapper { 135 | @include relative-font-size(0.9375); 136 | // color: $grey-color; 137 | margin-left: -$spacing-unit / 2; 138 | @extend %clearfix; 139 | } 140 | 141 | .footer-col { 142 | float: left; 143 | margin-bottom: $spacing-unit / 2; 144 | padding-left: $spacing-unit / 2; 145 | } 146 | 147 | .footer-col-1 { 148 | width: -webkit-calc(35% - (#{$spacing-unit} / 2)); 149 | width: calc(35% - (#{$spacing-unit} / 2)); 150 | } 151 | 152 | .footer-col-2 { 153 | width: -webkit-calc(20% - (#{$spacing-unit} / 2)); 154 | width: calc(20% - (#{$spacing-unit} / 2)); 155 | } 156 | 157 | .footer-col-3 { 158 | width: -webkit-calc(45% - (#{$spacing-unit} / 2)); 159 | width: calc(45% - (#{$spacing-unit} / 2)); 160 | } 161 | 162 | @include media-query($on-laptop) { 163 | .footer-col-1, 164 | .footer-col-2 { 165 | width: -webkit-calc(50% - (#{$spacing-unit} / 2)); 166 | width: calc(50% - (#{$spacing-unit} / 2)); 167 | } 168 | 169 | .footer-col-3 { 170 | width: -webkit-calc(100% - (#{$spacing-unit} / 2)); 171 | width: calc(100% - (#{$spacing-unit} / 2)); 172 | } 173 | } 174 | 175 | @include media-query($on-palm) { 176 | .footer-col { 177 | float: none; 178 | width: -webkit-calc(100% - (#{$spacing-unit} / 2)); 179 | width: calc(100% - (#{$spacing-unit} / 2)); 180 | } 181 | } 182 | 183 | 184 | 185 | /** 186 | * Page content 187 | */ 188 | .page-content { 189 | padding: $spacing-unit 0; 190 | } 191 | 192 | .page-heading { 193 | @include relative-font-size(2.75); 194 | margin-top: 20px; 195 | margin-bottom: 20px; 196 | } 197 | 198 | .post-list { 199 | margin-left: 0; 200 | list-style: none; 201 | 202 | > li { 203 | margin-bottom: $spacing-unit; 204 | } 205 | } 206 | 207 | .post-meta { 208 | font-size: $small-font-size; 209 | color: $grey-color; 210 | } 211 | 212 | .post-link { 213 | display: block; 214 | @include relative-font-size(1.5); 215 | } 216 | 217 | 218 | 219 | /** 220 | * Posts 221 | */ 222 | .post-header { 223 | margin-bottom: $spacing-unit; 224 | } 225 | 226 | .post-title { 227 | @include relative-font-size(2.625); 228 | letter-spacing: -1px; 229 | line-height: 1; 230 | 231 | @include media-query($on-laptop) { 232 | @include relative-font-size(2.25); 233 | } 234 | } 235 | 236 | .post-content { 237 | margin-bottom: $spacing-unit; 238 | 239 | h2 { 240 | @include relative-font-size(2); 241 | 242 | @include media-query($on-laptop) { 243 | @include relative-font-size(1.75); 244 | } 245 | } 246 | 247 | h3 { 248 | @include relative-font-size(1.625); 249 | 250 | @include media-query($on-laptop) { 251 | @include relative-font-size(1.375); 252 | } 253 | } 254 | 255 | h4 { 256 | @include relative-font-size(1.25); 257 | 258 | @include media-query($on-laptop) { 259 | @include relative-font-size(1.125); 260 | } 261 | } 262 | } 263 | -------------------------------------------------------------------------------- /assets/dropdown.css: -------------------------------------------------------------------------------- 1 | /* Dropdown Button */ 2 | .dropbtn { 3 | background-color: #17062d; 4 | color: white; 5 | padding: 16px; 6 | font-size: 16px; 7 | border: none; 8 | cursor: pointer; 9 | } 10 | 11 | /* The container
- needed to position the dropdown content */ 12 | .dropdown { 13 | position: relative; 14 | display: inline-block; 15 | } 16 | 17 | /* Dropdown Content (Hidden by Default) */ 18 | .dropdown-content { 19 | display: none; 20 | position: absolute; 21 | background-color: #f9f9f9; 22 | min-width: 130px; 23 | box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); 24 | z-index: 1; 25 | } 26 | 27 | /* Links inside the dropdown */ 28 | .dropdown-content a { 29 | color: black; 30 | padding-left: 16px; 31 | padding-right: 20px; 32 | text-decoration: none; 33 | display: block; 34 | } 35 | 36 | /* Change color of dropdown links on hover */ 37 | .dropdown-content a:hover { 38 | background-color: #f1f1f1 39 | } 40 | 41 | /* Show the dropdown menu on hover */ 42 | .dropdown:hover .dropdown-content { 43 | display: block; 44 | } 45 | 46 | /* Change the background color of the dropdown button when the dropdown content is shown */ 47 | .dropdown:hover .dropbtn { 48 | background-color: #17062d; 49 | } 50 | -------------------------------------------------------------------------------- /assets/lapps/lnd.fun.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lightninglabs/lightning-dev-site/a5c489b7467ccfe94e42d13997fde3a752186575/assets/lapps/lnd.fun.png -------------------------------------------------------------------------------- /assets/lapps/lnd_desktop_app.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lightninglabs/lightning-dev-site/a5c489b7467ccfe94e42d13997fde3a752186575/assets/lapps/lnd_desktop_app.png -------------------------------------------------------------------------------- /assets/lapps/thunderdice.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lightninglabs/lightning-dev-site/a5c489b7467ccfe94e42d13997fde3a752186575/assets/lapps/thunderdice.png -------------------------------------------------------------------------------- /assets/lapps/yalls.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lightninglabs/lightning-dev-site/a5c489b7467ccfe94e42d13997fde3a752186575/assets/lapps/yalls.png -------------------------------------------------------------------------------- /assets/lapps/zap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lightninglabs/lightning-dev-site/a5c489b7467ccfe94e42d13997fde3a752186575/assets/lapps/zap.png -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | jekyll build 3 | 4 | # -m use faster multithreaded uploads 5 | # -d delete remote files that aren't in the source 6 | # -r recurse into source subdirectories 7 | gsutil -m rsync -d -r ./_site gs://dev.lightning.community 8 | -------------------------------------------------------------------------------- /error.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Lightning Network Dev 6 | 7 | 8 | 9 |

Oops! There was an error. Please navigate back to the main site.

10 | 11 | 12 | -------------------------------------------------------------------------------- /guides/docker.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: page 3 | title: Working with LND and Docker 4 | 5 | --- 6 | 7 | This document is written for people who are eager to do something with 8 | the Lightning Network Daemon (`lnd`). This folder uses `docker-compose` to 9 | package `lnd` and `btcd` together to make deploying the two daemons as easy as 10 | typing a few commands. All configuration between `lnd` and `btcd` are handled 11 | automatically by their `docker-compose` config file. 12 | 13 | ### Prerequisites 14 | Name | Version 15 | --------|--------- 16 | docker-compose | 1.9.0 17 | docker | 1.13.0 18 | 19 | ### Table of content 20 | * [Create lightning network cluster](#create-lightning-network-cluster) 21 | * [Connect to faucet lightning node](#connect-to-faucet-lightning-node) 22 | * [Questions](#questions) 23 | 24 | ### Create lightning network cluster 25 | This section describes a workflow on `simnet`, a development/test network 26 | that's similar to Bitcoin Core's `regtest` mode. In `simnet` mode blocks can be 27 | generated at will, as the difficulty is very low. This makes it an ideal 28 | environment for testing as one doesn't need to wait tens of minutes for blocks 29 | to arrive in order to test channel related functionality. Additionally, it's 30 | possible to spin up an arbitrary number of `lnd` instances within containers to 31 | create a mini development cluster. All state is saved between instances using a 32 | shared value. 33 | 34 | Current workflow is big because we recreate the whole network by ourselves, 35 | next versions will use the started `btcd` bitcoin node in `testnet` and 36 | `faucet` wallet from which you will get the bitcoins. 37 | 38 | In the workflow below, we describe the steps required to recreate the following 39 | topology, and send a payment from `Alice` to `Bob`. 40 | ``` 41 | + ----- + + --- + 42 | | Alice | <--- channel ---> | Bob | <--- Bob and Alice are the lightning network daemons which 43 | + ----- + + --- + create channels and interact with each other using the 44 | | | Bitcoin network as source of truth. 45 | | | 46 | + - - - - - + - - - - - - + 47 | | 48 | + --------------- + 49 | | Bitcoin network | <--- In the current scenario for simplicity we create only one 50 | + --------------- + "btcd" node which represents the Bitcoin network, in a 51 | real situation Alice and Bob will likely be 52 | connected to different Bitcoin nodes. 53 | ``` 54 | 55 | **General workflow is the following:** 56 | 57 | * Create a `btcd` node running on a private `simnet`. 58 | * Create `Alice`, one of the `lnd` nodes in our simulation network. 59 | * Create `Bob`, the other `lnd` node in our simulation network. 60 | * Mine some blocks to send `Alice` some bitcoins. 61 | * Open channel between `Alice` and `Bob`. 62 | * Send payment from `Alice` to `Bob`. 63 | * Close the channel between `Alice` and `Bob`. 64 | * Check that on-chain `Bob` balance was changed. 65 | 66 | Start `btcd`, and then create an address for `Alice` that we'll directly mine 67 | bitcoin into. 68 | ```bash 69 | # Init bitcoin network env variable: 70 | $ export NETWORK="simnet" 71 | 72 | # Run the "Alice" container and log into it: 73 | $ docker-compose run -d --name alice lnd_btc 74 | $ docker exec -i -t alice bash 75 | 76 | # Generate a new backward compatible nested p2sh address for Alice: 77 | alice$ lncli --network=simnet newaddress np2wkh 78 | 79 | # Recreate "btcd" node and set Alice's address as mining address: 80 | $ MINING_ADDRESS= docker-compose up -d btcd 81 | 82 | # Generate 400 blocks (we need at least "100 >=" blocks because of coinbase 83 | # block maturity and "300 ~=" in order to activate segwit): 84 | $ docker-compose run btcctl generate 400 85 | 86 | # Check that segwit is active: 87 | $ docker-compose run btcctl getblockchaininfo | grep -A 1 segwit 88 | ``` 89 | 90 | Check `Alice` balance: 91 | ``` 92 | alice$ lncli --network=simnet walletbalance 93 | ``` 94 | 95 | Connect `Bob` node to `Alice` node. 96 | 97 | ```bash 98 | # Run "Bob" node and log into it: 99 | $ docker-compose run -d --name bob lnd_btc 100 | $ docker exec -i -t bob bash 101 | 102 | # Get the identity pubkey of "Bob" node: 103 | bob$ lncli --network=simnet getinfo 104 | 105 | { 106 | ----->"identity_pubkey": "0343bc80b914aebf8e50eb0b8e445fc79b9e6e8e5e018fa8c5f85c7d429c117b38", 107 | "alias": "", 108 | "num_pending_channels": 0, 109 | "num_active_channels": 0, 110 | "num_inactive_channels": 0, 111 | "num_peers": 0, 112 | "block_height": 1215, 113 | "block_hash": "7d0bc86ea4151ed3b5be908ea883d2ac3073263537bcf8ca2dca4bec22e79d50", 114 | "synced_to_chain": true, 115 | "testnet": false 116 | "chains": [ 117 | "bitcoin" 118 | ] 119 | } 120 | 121 | # Get the IP address of "Bob" node: 122 | $ docker inspect bob | grep IPAddress 123 | 124 | # Connect "Alice" to the "Bob" node: 125 | alice$ lncli --network=simnet connect @ 126 | 127 | # Check list of peers on "Alice" side: 128 | alice$ lncli --network=simnet listpeers 129 | { 130 | "peers": [ 131 | { 132 | "pub_key": "0343bc80b914aebf8e50eb0b8e445fc79b9e6e8e5e018fa8c5f85c7d429c117b38", 133 | "address": "172.19.0.4:9735", 134 | "bytes_sent": "357", 135 | "bytes_recv": "357", 136 | "sat_sent": "0", 137 | "sat_recv": "0", 138 | "inbound": true, 139 | "ping_time": "0" 140 | } 141 | ] 142 | } 143 | 144 | # Check list of peers on "Bob" side: 145 | bob$ lncli --network=simnet listpeers 146 | { 147 | "peers": [ 148 | { 149 | "pub_key": "03d0cd35b761f789983f3cfe82c68170cd1c3266b39220c24f7dd72ef4be0883eb", 150 | "address": "172.19.0.3:51932", 151 | "bytes_sent": "357", 152 | "bytes_recv": "357", 153 | "sat_sent": "0", 154 | "sat_recv": "0", 155 | "inbound": false, 156 | "ping_time": "0" 157 | } 158 | ] 159 | } 160 | ``` 161 | 162 | Create the `Alice<->Bob` channel. 163 | ```bash 164 | # Open the channel with "Bob": 165 | alice$ lncli --network=simnet openchannel --node_key= --local_amt=1000000 166 | 167 | # Include funding transaction in block thereby opening the channel: 168 | $ docker-compose run btcctl generate 3 169 | 170 | # Check that channel with "Bob" was opened: 171 | alice$ lncli --network=simnet listchannels 172 | { 173 | "channels": [ 174 | { 175 | "active": true, 176 | "remote_pubkey": "0343bc80b914aebf8e50eb0b8e445fc79b9e6e8e5e018fa8c5f85c7d429c117b38", 177 | "channel_point": "3511ae8a52c97d957eaf65f828504e68d0991f0276adff94c6ba91c7f6cd4275:0", 178 | "chan_id": "1337006139441152", 179 | "capacity": "1005000", 180 | "local_balance": "1000000", 181 | "remote_balance": "0", 182 | "commit_fee": "8688", 183 | "commit_weight": "600", 184 | "fee_per_kw": "12000", 185 | "unsettled_balance": "0", 186 | "total_satoshis_sent": "0", 187 | "total_satoshis_received": "0", 188 | "num_updates": "0", 189 | "pending_htlcs": [ 190 | ], 191 | "csv_delay": 4 192 | } 193 | ] 194 | } 195 | ``` 196 | 197 | Send the payment from `Alice` to `Bob`. 198 | ```bash 199 | # Add invoice on "Bob" side: 200 | bob$ lncli --network=simnet addinvoice --amt=10000 201 | { 202 | "r_hash": "", 203 | "pay_req": "", 204 | } 205 | 206 | # Send payment from "Alice" to "Bob": 207 | alice$ lncli --network=simnet sendpayment --pay_req= 208 | 209 | # Check "Alice"'s channel balance 210 | alice$ lncli --network=simnet channelbalance 211 | 212 | # Check "Bob"'s channel balance 213 | bob$ lncli --network=simnet channelbalance 214 | ``` 215 | 216 | Now we have open channel in which we sent only one payment, let's imagine 217 | that we sent lots of them and we'd now like to close the channel. Let's do 218 | it! 219 | ```bash 220 | # List the "Alice" channel and retrieve "channel_point" which represents 221 | # the opened channel: 222 | alice$ lncli --network=simnet listchannels 223 | { 224 | "channels": [ 225 | { 226 | "active": true, 227 | "remote_pubkey": "0343bc80b914aebf8e50eb0b8e445fc79b9e6e8e5e018fa8c5f85c7d429c117b38", 228 | ---->"channel_point": "3511ae8a52c97d957eaf65f828504e68d0991f0276adff94c6ba91c7f6cd4275:0", 229 | "chan_id": "1337006139441152", 230 | "capacity": "1005000", 231 | "local_balance": "990000", 232 | "remote_balance": "10000", 233 | "commit_fee": "8688", 234 | "commit_weight": "724", 235 | "fee_per_kw": "12000", 236 | "unsettled_balance": "0", 237 | "total_satoshis_sent": "10000", 238 | "total_satoshis_received": "0", 239 | "num_updates": "2", 240 | "pending_htlcs": [ 241 | ], 242 | "csv_delay": 4 243 | } 244 | ] 245 | } 246 | 247 | # Channel point consists of two numbers separated by a colon. The first one 248 | # is "funding_txid" and the second one is "output_index": 249 | alice$ lncli --network=simnet closechannel --funding_txid= --output_index= 250 | 251 | # Include close transaction in a block thereby closing the channel: 252 | $ docker-compose run btcctl generate 3 253 | 254 | # Check "Alice" on-chain balance was credited by her settled amount in the channel: 255 | alice$ lncli --network=simnet walletbalance 256 | 257 | # Check "Bob" on-chain balance was credited with the funds he received in the 258 | # channel: 259 | bob$ lncli --network=simnet walletbalance 260 | { 261 | "total_balance": "10000", 262 | "confirmed_balance": "10000", 263 | "unconfirmed_balance": "0" 264 | } 265 | ``` 266 | 267 | ### Connect to faucet lightning node 268 | In order to be more confident with `lnd` commands I suggest you to try 269 | to create a mini lightning network cluster ([Create lightning network cluster](#create-lightning-network-cluster)). 270 | 271 | In this section we will try to connect our node to the faucet/hub node 272 | which we will create a channel with and send some amount of 273 | bitcoins. The schema will be following: 274 | 275 | ``` 276 | + ----- + + ------ + (1) + --- + 277 | | Alice | <--- channel ---> | Faucet | <--- channel ---> | Bob | 278 | + ----- + + ------ + + --- + 279 | | | | 280 | | | | <--- (2) 281 | + - - - - - - - - - - - - - + - - - - - - - - - - - - - + 282 | | 283 | + --------------- + 284 | | Bitcoin network | <--- (3) 285 | + --------------- + 286 | 287 | 288 | (1) You may connect an additional node "Bob" and make the multihop 289 | payment Alice->Faucet->Bob 290 | 291 | (2) "Faucet", "Alice" and "Bob" are the lightning network daemons which 292 | create channels to interact with each other using the Bitcoin network 293 | as source of truth. 294 | 295 | (3) In current scenario "Alice" and "Faucet" lightning network nodes 296 | connect to different Bitcoin nodes. If you decide to connect "Bob" 297 | to "Faucet" then the already created "btcd" node would be sufficient. 298 | ``` 299 | 300 | First of all you need to run `btcd` node in `testnet` and wait for it to be 301 | synced with test network (`May the Force and Patience be with you`). 302 | ```bash 303 | # Init bitcoin network env variable: 304 | $ export NETWORK="testnet" 305 | 306 | # Run "btcd" node: 307 | $ docker-compose up -d "btcd" 308 | ``` 309 | 310 | After `btcd` synced, connect `Alice` to the `Faucet` node. 311 | 312 | The `Faucet` node address can be found at the [Faucet Lightning Community webpage](https://faucet.lightning.community). 313 | 314 | ```bash 315 | # Run "Alice" container and log into it: 316 | $ docker-compose run -d --name alice lnd_btc; docker exec -i -t "alice" bash 317 | 318 | # Connect "Alice" to the "Faucet" node: 319 | alice$ lncli --network=testnet connect @ 320 | ``` 321 | 322 | After a connection is achieved, the `Faucet` node should create the channel 323 | and send some amount of bitcoins to `Alice`. 324 | 325 | **What you may do next?:** 326 | - Send some amount to `Faucet` node back. 327 | - Connect `Bob` node to the `Faucet` and make multihop payment (`Alice->Faucet->Bob`) 328 | - Close channel with `Faucet` and check the onchain balance. 329 | 330 | ### Questions 331 | [![Irc](https://img.shields.io/badge/chat-on%20freenode-brightgreen.svg)](https://webchat.freenode.net/?channels=lnd) 332 | 333 | * How to see `alice` | `bob` | `btcd` logs? 334 | ```bash 335 | docker-compose logs 336 | ``` 337 | 338 | 339 | -------------------------------------------------------------------------------- /guides/index.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: page 3 | title: Guides 4 | --- 5 | 6 | This page lists the writeups available on specific skills in and around LND. 7 | 8 | #### LND Overview and Developer Guide 9 | 10 | Modeled after the Bitcoin Developer Guide, the [LND Overview and Developer 11 | Guide](/overview/) will provide the necessary conceptual background for 12 | developers looking to build on LND. 13 | 14 | #### Installation 15 | 16 | The [installation guide](/guides/installation/) will get you set up to build and 17 | run `lnd` from the command line. 18 | 19 | #### Tutorial 20 | 21 | The [tutorial](/tutorial/) is a holistic tour that is intended to teach all the 22 | dev-specific skills necessary to work with `lnd`, by walking through a setup of 23 | `lnd`, a lnd client, RPC, and integration into a web application. This should be 24 | completed in tandem with the [LND Overview and Developer Guide](/overview/). 25 | 26 | #### gRPC Guides 27 | 28 | The gRPC guides will get you started sending command through gRPC. We have 29 | written language specific guides for Python and Javascript: 30 | 31 | * [Python](/guides/python-grpc/) 32 | * [Javascript](/guides/javascript-grpc/) 33 | 34 | #### Docker 35 | 36 | The [Docker guide](/guides/docker/) teaches you how to package `lnd` and `btcd` 37 | together to make deployment of multiple daemons a bit simpler. 38 | 39 | -------------------------------------------------------------------------------- /guides/installation.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: page 3 | title: Installation 4 | 5 | --- 6 | 7 | * [Installation](#installation) 8 | * [Preliminaries](#preliminaries) 9 | * [Installing lnd](#installing-lnd) 10 | * [Available Backend Operating Modes](#available-backend-operating-modes) 11 | * [btcd Options](#btcd-options) 12 | * [Neutrino Options](#neutrino-options) 13 | * [Bitcoind Options](#bitcoind-options) 14 | * [Using btcd](#using-btcd) 15 | * [Installing btcd](#installing-btcd) 16 | * [Starting btcd](#starting-btcd) 17 | * [Running lnd using the btcd backend](#running-lnd-using-the-btcd-backend) 18 | * [Using Neutrino](#using-neutrino) 19 | * [Using bitcoind or litecoind](#using-bitcoind-or-litecoind) 20 | * [Creating a Wallet](#creating-a-wallet) 21 | * [Macaroons](#macaroons) 22 | * [Network Reachability](#network-reachability) 23 | * [Simnet vs. Testnet Development](#simnet-vs-testnet-development) 24 | * [Creating an lnd.conf (Optional)](#creating-an-lndconf-optional) 25 | 26 | # Installation 27 | 28 | ### Preliminaries 29 | In order to work with [`lnd`](https://github.com/lightningnetwork/lnd), the 30 | following build dependencies are required: 31 | 32 | * **Go:** `lnd` is written in Go. To install, run one of the following commands: 33 | 34 | 35 | **Note**: The minimum version of Go supported is Go 1.13. We recommend that 36 | users use the latest version of Go, which at the time of writing is 37 | [`1.13`](https://blog.golang.org/go1.13). 38 | 39 | 40 | On Linux: 41 | 42 | (x86-64) 43 | ``` 44 | wget https://dl.google.com/go/go1.13.linux-amd64.tar.gz 45 | sha256sum go1.13.linux-amd64.tar.gz | awk -F " " '{ print $1 }' 46 | ``` 47 | 48 | The final output of the command above should be 49 | `68a2297eb099d1a76097905a2ce334e3155004ec08cdea85f24527be3c48e856`. If it 50 | isn't, then the target REPO HAS BEEN MODIFIED, and you shouldn't install 51 | this version of Go. If it matches, then proceed to install Go: 52 | ``` 53 | tar -C /usr/local -xzf go1.13.linux-amd64.tar.gz 54 | export PATH=$PATH:/usr/local/go/bin 55 | ``` 56 | 57 | (ARMv6) 58 | ``` 59 | wget https://dl.google.com/go/go1.13.linux-armv6l.tar.gz 60 | sha256sum go1.13.linux-armv6l.tar.gz | awk -F " " '{ print $1 }' 61 | ``` 62 | 63 | The final output of the command above should be 64 | `931906d67cae1222f501e7be26e0ee73ba89420be0c4591925901cb9a4e156f0`. If it 65 | isn't, then the target REPO HAS BEEN MODIFIED, and you shouldn't install 66 | this version of Go. If it matches, then proceed to install Go: 67 | ``` 68 | tar -C /usr/local -xzf go1.13.linux-armv6l.tar.gz 69 | export PATH=$PATH:/usr/local/go/bin 70 | ``` 71 | 72 | On Mac OS X: 73 | ``` 74 | brew install go@1.13 75 | ``` 76 | 77 | On FreeBSD: 78 | ``` 79 | pkg install go 80 | ``` 81 | 82 | Alternatively, one can download the pre-compiled binaries hosted on the 83 | [Golang download page](https://golang.org/dl/). If one seeks to install 84 | from source, then more detailed installation instructions can be found 85 | [here](https://golang.org/doc/install). 86 | 87 | At this point, you should set your `$GOPATH` environment variable, which 88 | represents the path to your workspace. By default, `$GOPATH` is set to 89 | `~/go`. You will also need to add `$GOPATH/bin` to your `PATH`. This ensures 90 | that your shell will be able to detect the binaries you install. 91 | 92 | ```bash 93 | export GOPATH=~/gocode 94 | export PATH=$PATH:$GOPATH/bin 95 | ``` 96 | 97 | We recommend placing the above in your .bashrc or in a setup script so that 98 | you can avoid typing this every time you open a new terminal window. 99 | 100 | * **Go modules:** This project uses [Go modules](https://github.com/golang/go/wiki/Modules) 101 | to manage dependencies as well as to provide *reproducible builds*. 102 | 103 | Usage of Go modules (with Go 1.12) means that you no longer need to clone 104 | `lnd` into your `$GOPATH` for development purposes. Instead, your `lnd` 105 | repo can now live anywhere! 106 | 107 | ### Installing lnd 108 | 109 | With the preliminary steps completed, to install `lnd`, `lncli`, and all 110 | related dependencies run the following commands: 111 | ``` 112 | go get -d github.com/lightningnetwork/lnd 113 | cd $GOPATH/src/github.com/lightningnetwork/lnd 114 | make && make install 115 | ``` 116 | 117 | **NOTE**: Our instructions still use the `$GOPATH` directory from prior 118 | versions of Go, but with Go 1.12, it's now possible for `lnd` to live 119 | _anywhere_ on your file system. 120 | 121 | For Windows WSL users, make will need to be referenced directly via 122 | /usr/bin/make/, or alternatively by wrapping quotation marks around make, 123 | like so: 124 | 125 | ``` 126 | /usr/bin/make && /usr/bin/make install 127 | 128 | "make" && "make" install 129 | ``` 130 | 131 | On FreeBSD, use gmake instead of make. 132 | 133 | Alternatively, if one doesn't wish to use `make`, then the `go` commands can be 134 | used directly: 135 | ``` 136 | GO111MODULE=on go install -v ./... 137 | ``` 138 | 139 | **Updating** 140 | 141 | To update your version of `lnd` to the latest version run the following 142 | commands: 143 | ``` 144 | cd $GOPATH/src/github.com/lightningnetwork/lnd 145 | git pull 146 | make clean && make && make install 147 | ``` 148 | 149 | On FreeBSD, use gmake instead of make. 150 | 151 | Alternatively, if one doesn't wish to use `make`, then the `go` commands can be 152 | used directly: 153 | ``` 154 | cd $GOPATH/src/github.com/lightningnetwork/lnd 155 | git pull 156 | GO111MODULE=on go install -v ./... 157 | ``` 158 | 159 | **Tests** 160 | 161 | To check that `lnd` was installed properly run the following command: 162 | ``` 163 | make check 164 | ``` 165 | 166 | # Available Backend Operating Modes 167 | 168 | In order to run, `lnd` requires, that the user specify a chain backend. At the 169 | time of writing of this document, there are three available chain backends: 170 | `btcd`, `neutrino`, `bitcoind`. All but neutrino (atm) can run on mainnet with 171 | an out of the box `lnd` instance. We don't require `--txindex` when running 172 | with `bitcoind` or `btcd` but activating the `txindex` will generally make 173 | `lnd` run faster. 174 | 175 | **NOTE: WE DO NOT FULLY SUPPORT PRUNED OPERATING MODES FOR FULL NODES.** It's 176 | possible to run a node in a pruned mode and have it serve lnd, however one must 177 | take care to ensure that `lnd` has all blocks on disk since the birth of the 178 | wallet, and the age of the earliest channels (which were created around March 179 | 2018). 180 | 181 | The set of arguments for each of the backend modes is as follows: 182 | 183 | ## btcd Options 184 | ``` 185 | btcd: 186 | --btcd.dir= The base directory that contains the node's data, logs, configuration file, etc. (default: /Users/roasbeef/Library/Application Support/Btcd) 187 | --btcd.rpchost= The daemon's rpc listening address. If a port is omitted, then the default port for the selected chain parameters will be used. (default: localhost) 188 | --btcd.rpcuser= Username for RPC connections 189 | --btcd.rpcpass= Password for RPC connections 190 | --btcd.rpccert= File containing the daemon's certificate file (default: /Users/roasbeef/Library/Application Support/Btcd/rpc.cert) 191 | --btcd.rawrpccert= The raw bytes of the daemon's PEM-encoded certificate chain which will be used to authenticate the RPC connection. 192 | ``` 193 | 194 | ## Neutrino Options 195 | ``` 196 | neutrino: 197 | -a, --neutrino.addpeer= Add a peer to connect with at startup 198 | --neutrino.connect= Connect only to the specified peers at startup 199 | --neutrino.maxpeers= Max number of inbound and outbound peers 200 | --neutrino.banduration= How long to ban misbehaving peers. Valid time units are {s, m, h}. Minimum 1 second 201 | --neutrino.banthreshold= Maximum allowed ban score before disconnecting and banning misbehaving peers. 202 | ``` 203 | 204 | ## Bitcoind Options 205 | ``` 206 | bitcoind: 207 | --bitcoind.dir= The base directory that contains the node's data, logs, configuration file, etc. (default: /Users/roasbeef/Library/Application Support/Bitcoin) 208 | --bitcoind.rpchost= The daemon's rpc listening address. If a port is omitted, then the default port for the selected chain parameters will be used. (default: localhost) 209 | --bitcoind.rpcuser= Username for RPC connections 210 | --bitcoind.rpcpass= Password for RPC connections 211 | --bitcoind.zmqpubrawblock= The address listening for ZMQ connections to deliver raw block notifications 212 | --bitcoind.zmqpubrawtx= The address listening for ZMQ connections to deliver raw transaction notifications 213 | ``` 214 | 215 | ## Using btcd 216 | 217 | ### Installing btcd 218 | 219 | On FreeBSD, use gmake instead of make. 220 | 221 | To install btcd, run the following commands: 222 | 223 | Install **btcd**: 224 | ``` 225 | make btcd 226 | ``` 227 | 228 | Alternatively, you can install [`btcd` directly from its 229 | repo](https://github.com/btcsuite/btcd). 230 | 231 | ### Starting btcd 232 | 233 | Running the following command will create `rpc.cert` and default `btcd.conf`. 234 | 235 | ``` 236 | btcd --testnet --rpcuser=REPLACEME --rpcpass=REPLACEME 237 | ``` 238 | If you want to use `lnd` on testnet, `btcd` needs to first fully sync the 239 | testnet blockchain. Depending on your hardware, this may take up to a few 240 | hours. Note that adding `--txindex` is optional, as it will take longer to sync 241 | the node, but then `lnd` will generally operate faster as it can hit the index 242 | directly, rather than scanning blocks or BIP 158 filters for relevant items. 243 | 244 | (NOTE: It may take several minutes to find segwit-enabled peers.) 245 | 246 | While `btcd` is syncing you can check on its progress using btcd's `getinfo` 247 | RPC command: 248 | ``` 249 | btcctl --testnet --rpcuser=REPLACEME --rpcpass=REPLACEME getinfo 250 | { 251 | "version": 120000, 252 | "protocolversion": 70002, 253 | "blocks": 1114996, 254 | "timeoffset": 0, 255 | "connections": 7, 256 | "proxy": "", 257 | "difficulty": 422570.58270815, 258 | "testnet": true, 259 | "relayfee": 0.00001, 260 | "errors": "" 261 | } 262 | ``` 263 | 264 | Additionally, you can monitor btcd's logs to track its syncing progress in real 265 | time. 266 | 267 | You can test your `btcd` node's connectivity using the `getpeerinfo` command: 268 | ``` 269 | btcctl --testnet --rpcuser=REPLACEME --rpcpass=REPLACEME getpeerinfo | more 270 | ``` 271 | 272 | ### Running lnd using the btcd backend 273 | 274 | If you are on testnet, run this command after `btcd` has finished syncing. 275 | Otherwise, replace `--bitcoin.testnet` with `--bitcoin.simnet`. If you are 276 | installing `lnd` in preparation for the 277 | [tutorial](https://dev.lightning.community/tutorial), you may skip this step. 278 | ``` 279 | lnd --bitcoin.active --bitcoin.testnet --debuglevel=debug --btcd.rpcuser=kek --btcd.rpcpass=kek --externalip=X.X.X.X 280 | ``` 281 | 282 | ## Using Neutrino 283 | 284 | In order to run `lnd` in its light client mode, you'll need to locate a 285 | full-node which is capable of serving this new light client mode. `lnd` uses 286 | [BIP 157](https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki) and [BIP 287 | 158](https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki) for its light client 288 | mode. A public instance of such a node can be found at 289 | `faucet.lightning.community`. 290 | 291 | To run lnd in neutrino mode, run `lnd` with the following arguments, (swapping 292 | in `--bitcoin.simnet` if needed), and also your own `btcd` node if available: 293 | ``` 294 | lnd --bitcoin.active --bitcoin.testnet --debuglevel=debug --bitcoin.node=neutrino --neutrino.connect=faucet.lightning.community 295 | ``` 296 | 297 | 298 | ## Using bitcoind or litecoind 299 | 300 | The configuration for bitcoind and litecoind are nearly identical, the 301 | following steps can be mirrored with loss of generality to enable a litecoind 302 | backend. Setup will be described in regards to `bitcoind`, but note that `lnd` 303 | uses a distinct `litecoin.node=litecoind` argument and analogous 304 | subconfigurations prefixed by `litecoind`. Note that adding `--txindex` is 305 | optional, as it will take longer to sync the node, but then `lnd` will 306 | generally operate faster as it can hit the index directly, rather than scanning 307 | blocks or BIP 158 filters for relevant items. 308 | 309 | To configure your bitcoind backend for use with lnd, first complete and verify 310 | the following: 311 | 312 | - Since `lnd` uses 313 | [ZeroMQ](https://github.com/bitcoin/bitcoin/blob/master/doc/zmq.md) to 314 | interface with `bitcoind`, *your `bitcoind` installation must be compiled with 315 | ZMQ*. Note that if you installed `bitcoind` from source and ZMQ was not present, 316 | then ZMQ support will be disabled, and `lnd` will quit on a `connection refused` error. 317 | If you installed `bitcoind` via Homebrew in the past ZMQ may not be included 318 | ([this has now been fixed](https://github.com/Homebrew/homebrew-core/pull/23088) 319 | in the latest Homebrew recipe for bitcoin) 320 | - Configure the `bitcoind` instance for ZMQ with `--zmqpubrawblock` and 321 | `--zmqpubrawtx`. These options must each use their own unique address in order 322 | to provide a reliable delivery of notifications (e.g. 323 | `--zmqpubrawblock=tcp://127.0.0.1:28332` and 324 | `--zmqpubrawtx=tcp://127.0.0.1:28333`). 325 | - Start `bitcoind` running against testnet, and let it complete a full sync with 326 | the testnet chain (alternatively, use `--bitcoind.regtest` instead). 327 | 328 | Here's a sample `bitcoin.conf` for use with lnd: 329 | ``` 330 | testnet=1 331 | server=1 332 | daemon=1 333 | zmqpubrawblock=tcp://127.0.0.1:28332 334 | zmqpubrawtx=tcp://127.0.0.1:28333 335 | ``` 336 | 337 | Once all of the above is complete, and you've confirmed `bitcoind` is fully 338 | updated with the latest blocks on testnet, run the command below to launch 339 | `lnd` with `bitcoind` as your backend (as with `bitcoind`, you can create an 340 | `lnd.conf` to save these options, more info on that is described further 341 | below): 342 | 343 | ``` 344 | lnd --bitcoin.active --bitcoin.testnet --debuglevel=debug --bitcoin.node=bitcoind --bitcoind.rpcuser=REPLACEME --bitcoind.rpcpass=REPLACEME --bitcoind.zmqpubrawblock=tcp://127.0.0.1:28332 --bitcoind.zmqpubrawtx=tcp://127.0.0.1:28333 --externalip=X.X.X.X 345 | ``` 346 | 347 | *NOTE:* 348 | - The auth parameters `rpcuser` and `rpcpass` parameters can typically be 349 | determined by `lnd` for a `bitcoind` instance running under the same user, 350 | including when using cookie auth. In this case, you can exclude them from the 351 | `lnd` options entirely. 352 | - If you DO choose to explicitly pass the auth parameters in your `lnd.conf` or 353 | command line options for `lnd` (`bitcoind.rpcuser` and `bitcoind.rpcpass` as 354 | shown in example command above), you must also specify the 355 | `bitcoind.zmqpubrawblock` and `bitcoind.zmqpubrawtx` options. Otherwise, `lnd` 356 | will attempt to get the configuration from your `bitcoin.conf`. 357 | - You must ensure the same addresses are used for the `bitcoind.zmqpubrawblock` 358 | and `bitcoind.zmqpubrawtx` options passed to `lnd` as for the `zmqpubrawblock` 359 | and `zmqpubrawtx` passed in the `bitcoind` options respectively. 360 | - When running lnd and bitcoind on the same Windows machine, ensure you use 361 | 127.0.0.1, not localhost, for all configuration options that require a TCP/IP 362 | host address. If you use "localhost" as the host name, you may see extremely 363 | slow inter-process-communication between lnd and the bitcoind backend. If lnd 364 | is experiencing this issue, you'll see "Waiting for chain backend to finish 365 | sync, start_height=XXXXXX" as the last entry in the console or log output, and 366 | lnd will appear to hang. Normal lnd output will quickly show multiple 367 | messages like this as lnd consumes blocks from bitcoind. 368 | - Don't connect more than two or three instances of `lnd` to `bitcoind`. With 369 | the default `bitcoind` settings, having more than one instance of `lnd`, or 370 | `lnd` plus any application that consumes the RPC could cause `lnd` to miss 371 | crucial updates from the backend. 372 | 373 | 374 | # Creating a wallet 375 | If `lnd` is being run for the first time, create a new wallet with: 376 | ``` 377 | lncli create 378 | ``` 379 | This will prompt for a wallet password, and optionally a cipher seed 380 | passphrase. 381 | 382 | `lnd` will then print a 24 word cipher seed mnemonic, which can be used to 383 | recover the wallet in case of data loss. The user should write this down and 384 | keep in a safe place. 385 | 386 | 387 | # Macaroons 388 | 389 | `lnd`'s authentication system is called **macaroons**, which are decentralized 390 | bearer credentials allowing for delegation, attenuation, and other cool 391 | features. You can learn more about them in Alex Akselrod's [writeup on 392 | Github](https://github.com/lightningnetwork/lnd/issues/20). 393 | 394 | Running `lnd` for the first time will by default generate the `admin.macaroon`, 395 | `read_only.macaroon`, and `macaroons.db` files that are used to authenticate 396 | into `lnd`. They will be stored in the network directory (default: 397 | `lnddir/data/chain/bitcoin/mainnet`) so that it's possible to use a distinct 398 | password for mainnet, testnet, simnet, etc. Note that if you specified an 399 | alternative data directory (via the `--datadir` argument), you will have to 400 | additionally pass the updated location of the `admin.macaroon` file into `lncli` 401 | using the `--macaroonpath` argument. 402 | 403 | To disable macaroons for testing, pass the `--no-macaroons` flag into *both* 404 | `lnd` and `lncli`. 405 | 406 | # Network Reachability 407 | 408 | If you'd like to signal to other nodes on the network that you'll accept 409 | incoming channels (as peers need to connect inbound to initiate a channel 410 | funding workflow), then the `--externalip` flag should be set to your publicly 411 | reachable IP address. 412 | 413 | # Simnet vs. Testnet Development 414 | 415 | If you are doing local development, such as for the tutorial, you'll want to 416 | start both `btcd` and `lnd` in the `simnet` mode. Simnet is similar to regtest 417 | in that you'll be able to instantly mine blocks as needed to test `lnd` 418 | locally. In order to start either daemon in the `simnet` mode use `simnet` 419 | instead of `testnet`, adding the `--bitcoin.simnet` flag instead of the 420 | `--bitcoin.testnet` flag. 421 | 422 | Another relevant command line flag for local testing of new `lnd` developments 423 | is the `--debughtlc` flag. When starting `lnd` with this flag, it'll be able to 424 | automatically settle a special type of HTLC sent to it. This means that you 425 | won't need to manually insert invoices in order to test payment connectivity. 426 | To send this "special" HTLC type, include the `--debugsend` command at the end 427 | of your `sendpayment` commands. 428 | 429 | 430 | There are currently two primary ways to run `lnd`: one requires a local `btcd` 431 | instance with the RPC service exposed, and the other uses a fully integrated 432 | light client powered by [neutrino](https://github.com/lightninglabs/neutrino). 433 | 434 | # Creating an lnd.conf (Optional) 435 | 436 | Optionally, if you'd like to have a persistent configuration between `lnd` 437 | launches, allowing you to simply type `lnd --bitcoin.testnet --bitcoin.active` 438 | at the command line, you can create an `lnd.conf`. 439 | 440 | **On MacOS, located at:** 441 | `/Users/[username]/Library/Application Support/Lnd/lnd.conf` 442 | 443 | **On Linux, located at:** 444 | `~/.lnd/lnd.conf` 445 | 446 | Here's a sample `lnd.conf` for `btcd` to get you started: 447 | ``` 448 | [Application Options] 449 | debuglevel=trace 450 | maxpendingchannels=10 451 | 452 | [Bitcoin] 453 | bitcoin.active=1 454 | ``` 455 | 456 | Notice the `[Bitcoin]` section. This section houses the parameters for the 457 | Bitcoin chain. `lnd` also supports Litecoin testnet4 (but not both BTC and LTC 458 | at the same time), so when working with Litecoin be sure to set to parameters 459 | for Litecoin accordingly. See a more detailed sample config file available 460 | [here](https://github.com/lightningnetwork/lnd/blob/master/sample-lnd.conf) 461 | and explore the other sections for node configuration, including `[Btcd]`, 462 | `[Bitcoind]`, `[Neutrino]`, `[Ltcd]`, and `[Litecoind]` depending on which 463 | chain and node type you're using. 464 | 465 | 466 | 467 | 468 | ### Next Steps 469 | 470 | * **[Tutorial](/tutorial/):** Get acquainted with the skills necessary for `lnd` development. 471 | * **[Developer Guides](/guides/):** Look through developer manuals on gRPC, 472 | Docker, and more. 473 | * **[Resources](/resources/):** Learn about the Lightning Network 474 | * **[Code Contribution Guidelines](/contribute/):** Contribute to `lnd` itself. 475 | 476 | -------------------------------------------------------------------------------- /guides/javascript-grpc.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: page 3 | title: How to write a Javascript gRPC client for the Lightning Network Daemon 4 | 5 | --- 6 | 7 | ### Setup and Installation 8 | 9 | First, you'll need to initialize a simple nodejs project: 10 | ``` 11 | npm init (or npm init -f if you want to use the default values without prompt) 12 | ``` 13 | 14 | Then you need to install the Javascript grpc library dependency: 15 | ``` 16 | npm install grpc --save 17 | ``` 18 | 19 | You also need to copy the `lnd` `rpc.proto` file in your project directory (or 20 | at least somewhere reachable by your Javascript code). 21 | 22 | The `rpc.proto` file is [located in the `lnrpc` directory of the `lnd` 23 | sources](https://github.com/lightningnetwork/lnd/blob/master/lnrpc/rpc.proto). 24 | 25 | In order for the auto-generated code to compile successfully, you'll need to 26 | comment out the following line: 27 | 28 | ``` 29 | //import "google/api/annotations.proto"; 30 | ``` 31 | 32 | #### Imports and Client 33 | 34 | Every time you work with Javascript gRPC, you will have to import `grpc`, load 35 | `rpc.proto`, and create a connection to your client like so: 36 | 37 | ```js 38 | var grpc = require('grpc'); 39 | var fs = require("fs"); 40 | 41 | // Due to updated ECDSA generated tls.cert we need to let gprc know that 42 | // we need to use that cipher suite otherwise there will be a handhsake 43 | // error when we communicate with the lnd rpc server. 44 | process.env.GRPC_SSL_CIPHER_SUITES = 'HIGH+ECDSA' 45 | 46 | // Lnd cert is at ~/.lnd/tls.cert on Linux and 47 | // ~/Library/Application Support/Lnd/tls.cert on Mac 48 | var lndCert = fs.readFileSync("~/.lnd/tls.cert"); 49 | var credentials = grpc.credentials.createSsl(lndCert); 50 | var lnrpcDescriptor = grpc.load("rpc.proto"); 51 | var lnrpc = lnrpcDescriptor.lnrpc; 52 | var lightning = new lnrpc.Lightning('localhost:10009', credentials); 53 | ``` 54 | 55 | ### Examples 56 | 57 | Let's walk through some examples of Javascript gRPC clients. These examples 58 | assume that you have at least two `lnd` nodes running, the RPC location of one 59 | of which is at the default `localhost:10009`, with an open channel between the 60 | two nodes. 61 | 62 | #### Simple RPC 63 | 64 | ```js 65 | > lightning.getInfo({}, function(err, response) { 66 | console.log('GetInfo:', response); 67 | }); 68 | ``` 69 | 70 | You should get something like this in your console: 71 | 72 | ``` 73 | GetInfo: { identity_pubkey: '03c892e3f3f077ea1e381c081abb36491a2502bc43ed37ffb82e264224f325ff27', 74 | alias: '', 75 | num_pending_channels: 0, 76 | num_active_channels: 1, 77 | num_inactive_channels: 0, 78 | num_peers: 1, 79 | block_height: 1006, 80 | block_hash: '198ba1dc43b4190e507fa5c7aea07a74ec0009a9ab308e1736dbdab5c767ff8e', 81 | synced_to_chain: false, 82 | testnet: false, 83 | chains: [ 'bitcoin' ] } 84 | ``` 85 | 86 | #### Response-streaming RPC 87 | 88 | ```js 89 | var call = lightning.subscribeInvoices({}); 90 | call.on('data', function(invoice) { 91 | console.log(invoice); 92 | }) 93 | .on('end', function() { 94 | // The server has finished sending 95 | }) 96 | .on('status', function(status) { 97 | // Process status 98 | console.log("Current status" + status); 99 | }); 100 | ``` 101 | 102 | Now, create an invoice for your node at `localhost:10009`and send a payment to 103 | it from another node. 104 | ```bash 105 | $ lncli addinvoice --amt=100 106 | { 107 | "r_hash": , 108 | "pay_req": 109 | } 110 | $ lncli sendpayment --pay_req= 111 | ``` 112 | Your Javascript console should now display the details of the recently satisfied 113 | invoice. 114 | 115 | #### Bidirectional-streaming RPC 116 | 117 | This example has a few dependencies: 118 | ```shell 119 | npm install --save async lodash bytebuffer 120 | ``` 121 | 122 | You can run the following in your shell or put it in a program and run it like 123 | `node script.js` 124 | 125 | ```js 126 | // Load some libraries specific to this example 127 | var async = require('async'); 128 | var _ = require('lodash'); 129 | var ByteBuffer = require('bytebuffer'); 130 | 131 | var dest_pubkey = ; 132 | var dest_pubkey_bytes = ByteBuffer.fromHex(dest_pubkey); 133 | 134 | // Set a listener on the bidirectional stream 135 | var call = lightning.sendPayment(); 136 | call.on('data', function(payment) { 137 | console.log("Payment sent:"); 138 | console.log(payment); 139 | }); 140 | call.on('end', function() { 141 | // The server has finished 142 | console.log("END"); 143 | }); 144 | 145 | // You can send single payments like this 146 | call.write({ dest: dest_pubkey_bytes, amt: 6969 }); 147 | 148 | // Or send a bunch of them like this 149 | function paymentSender(destination, amount) { 150 | return function(callback) { 151 | console.log("Sending " + amount + " satoshis"); 152 | console.log("To: " + destination); 153 | call.write({ 154 | dest: destination, 155 | amt: amount 156 | }); 157 | _.delay(callback, 2000); 158 | }; 159 | } 160 | var payment_senders = []; 161 | for (var i = 0; i < 10; i++) { 162 | payment_senders[i] = paymentSender(dest_pubkey_bytes, 100); 163 | } 164 | async.series(payment_senders, function() { 165 | call.end(); 166 | }); 167 | 168 | ``` 169 | This example will send a payment of 100 satoshis every 2 seconds. 170 | 171 | 172 | #### Using Macaroons 173 | 174 | To authenticate using macaroons you need to include the macaroon in the metadata of the request. 175 | 176 | ```js 177 | var fs = require('fs'); 178 | var grpc = require('grpc'); 179 | 180 | process.env.GRPC_SSL_CIPHER_SUITES = 'HIGH+ECDSA' 181 | 182 | // Lnd admin macaroon is at ~/.lnd/data/chain/bitcoin/simnet/admin.macaroon on Linux and 183 | // ~/Library/Application Support/Lnd/data/chain/bitcoin/simnet/admin.macaroon on Mac 184 | var m = fs.readFileSync('~/.lnd/data/chain/bitcoin/simnet/admin.macaroon'); 185 | var macaroon = m.toString('hex'); 186 | var meta = new grpc.Metadata().add('macaroon', macaroon); 187 | 188 | var lnrpcDescriptor = grpc.load("rpc.proto"); 189 | var lnrpc = lnrpcDescriptor.lnrpc; 190 | var client = new lnrpc.Lightning('some.address:10009', grpc.credentials.createInsecure()); 191 | 192 | client.getInfo({}, meta); 193 | ``` 194 | 195 | However, this can get tiresome to do for each request, so to avoid explicitly including the macaroon we can update the credentials to include it automatically. 196 | 197 | ```js 198 | var fs = require('fs'); 199 | var grpc = require('grpc'); 200 | 201 | process.env.GRPC_SSL_CIPHER_SUITES = 'HIGH+ECDSA' 202 | 203 | // Lnd admin macaroon is at ~/.lnd/data/chain/bitcoin/simnet/admin.macaroon on Linux and 204 | // ~/Library/Application Support/Lnd/data/chain/bitcoin/simnet/admin.macaroon on Mac 205 | var m = fs.readFileSync('~/.lnd/data/chain/bitcoin/simnet/admin.macaroon'); 206 | var macaroon = m.toString('hex'); 207 | 208 | // build meta data credentials 209 | var metadata = new grpc.Metadata() 210 | metadata.add('macaroon', macaroon) 211 | var macaroonCreds = grpc.credentials.createFromMetadataGenerator((_args, callback) => { 212 | callback(null, metadata); 213 | }); 214 | 215 | // build ssl credentials using the cert the same as before 216 | var lndCert = fs.readFileSync("~/.lnd/tls.cert"); 217 | var sslCreds = grpc.credentials.createSsl(lndCert); 218 | 219 | // combine the cert credentials and the macaroon auth credentials 220 | // such that every call is properly encrypted and authenticated 221 | var credentials = grpc.credentials.combineChannelCredentials(sslCreds, macaroonCreds); 222 | 223 | // Pass the crendentials when creating a channel 224 | var lnrpcDescriptor = grpc.load("rpc.proto"); 225 | var lnrpc = lnrpcDescriptor.lnrpc; 226 | var client = new lnrpc.Lightning('some.address:10009', credentials); 227 | 228 | client.getInfo({}, (err, res) => { ... }); 229 | ``` 230 | 231 | 232 | ### Conclusion 233 | 234 | With the above, you should have all the `lnd` related `gRPC` dependencies 235 | installed locally in your project. In order to get up to speed with `protobuf` 236 | usage from Javascript, see [this official `protobuf` reference for 237 | Javascript](https://developers.google.com/protocol-buffers/docs/reference/javascript-generated). 238 | Additionally, [this official gRPC 239 | resource](http://www.grpc.io/docs/tutorials/basic/node.html) provides more 240 | details around how to drive `gRPC` from `node.js`. 241 | 242 | 243 | -------------------------------------------------------------------------------- /guides/python-grpc.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: page 3 | title: How to write a Python gRPC client for the Lightning Network Daemon 4 | 5 | --- 6 | 7 | This section enumerates what you need to do to write a client that communicates 8 | with `lnd` in Python. 9 | 10 | ### Setup and Installation 11 | 12 | Lnd uses the gRPC protocol for communication with clients like lncli. gRPC is 13 | based on protocol buffers and as such, you will need to compile the lnd proto 14 | file in Python before you can use it to communicate with lnd. 15 | 16 | * Create a virtual environment for your project 17 | ``` 18 | $ virtualenv lnd 19 | ``` 20 | * Activate the virtual environment 21 | ``` 22 | $ source lnd/bin/activate 23 | ``` 24 | * Install dependencies (googleapis-common-protos is required due to the use of 25 | google/api/annotations.proto) 26 | ``` 27 | (lnd)$ pip install grpcio grpcio-tools googleapis-common-protos 28 | ``` 29 | * Clone the google api's repository (required due to the use of 30 | google/api/annotations.proto) 31 | ``` 32 | (lnd)$ git clone https://github.com/googleapis/googleapis.git 33 | ``` 34 | * Copy the lnd rpc.proto file (you'll find this at 35 | [lnrpc/rpc.proto](https://github.com/lightningnetwork/lnd/blob/master/lnrpc/rpc.proto)) 36 | or just download it 37 | ``` 38 | (lnd)$ curl -o rpc.proto -s https://raw.githubusercontent.com/lightningnetwork/lnd/master/lnrpc/rpc.proto 39 | ``` 40 | * Compile the proto file 41 | ``` 42 | (lnd)$ python -m grpc_tools.protoc --proto_path=googleapis:. --python_out=. --grpc_python_out=. rpc.proto 43 | ``` 44 | 45 | After following these steps, two files `rpc_pb2.py` and `rpc_pb2_grpc.py` will 46 | be generated. These files will be imported in your project anytime you use 47 | Python gRPC. 48 | 49 | #### Imports and Client 50 | 51 | Every time you use Python gRPC, you will have to import the generated rpc modules 52 | and set up a channel and stub to your connect to your `lnd` node: 53 | 54 | ```python 55 | import rpc_pb2 as ln 56 | import rpc_pb2_grpc as lnrpc 57 | import grpc 58 | import os 59 | 60 | # Due to updated ECDSA generated tls.cert we need to let gprc know that 61 | # we need to use that cipher suite otherwise there will be a handhsake 62 | # error when we communicate with the lnd rpc server. 63 | os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA' 64 | 65 | # Lnd cert is at ~/.lnd/tls.cert on Linux and 66 | # ~/Library/Application Support/Lnd/tls.cert on Mac 67 | cert = open(os.path.expanduser('~/.lnd/tls.cert'), 'rb').read() 68 | creds = grpc.ssl_channel_credentials(cert) 69 | channel = grpc.secure_channel('localhost:10009', creds) 70 | stub = lnrpc.LightningStub(channel) 71 | ``` 72 | 73 | ### Examples 74 | 75 | Let's walk through some examples of Python gRPC clients. These examples assume 76 | that you have at least two `lnd` nodes running, the RPC location of one of which 77 | is at the default `localhost:10009`, with an open channel between the two nodes. 78 | 79 | #### Simple RPC 80 | 81 | ```python 82 | # Retrieve and display the wallet balance 83 | response = stub.WalletBalance(ln.WalletBalanceRequest()) 84 | print(response.total_balance) 85 | ``` 86 | 87 | #### Response-streaming RPC 88 | 89 | ```python 90 | request = ln.InvoiceSubscription() 91 | for invoice in stub.SubscribeInvoices(request): 92 | print(invoice) 93 | ``` 94 | 95 | Now, create an invoice for your node at `localhost:10009`and send a payment to 96 | it from another node. 97 | ```bash 98 | $ lncli addinvoice --amt=100 99 | { 100 | "r_hash": , 101 | "pay_req": 102 | } 103 | $ lncli sendpayment --pay_req= 104 | ``` 105 | 106 | Your Python console should now display the details of the recently satisfied 107 | invoice. 108 | 109 | #### Bidirectional-streaming RPC 110 | 111 | ```python 112 | from time import sleep 113 | import codecs 114 | 115 | def request_generator(dest, amt): 116 | # Initialization code here 117 | counter = 0 118 | print("Starting up") 119 | while True: 120 | request = ln.SendRequest( 121 | dest=dest, 122 | amt=amt, 123 | ) 124 | yield request 125 | # Alter parameters here 126 | counter += 1 127 | sleep(2) 128 | 129 | # Outputs from lncli are hex-encoded 130 | dest_hex = 131 | dest_bytes = codecs.decode(dest_hex, 'hex') 132 | 133 | request_iterable = request_generator(dest=dest_bytes, amt=100) 134 | 135 | for payment in stub.SendPayment(request_iterable): 136 | print(payment) 137 | ``` 138 | This example will send a payment of 100 satoshis every 2 seconds. 139 | 140 | #### Using Macaroons 141 | 142 | To authenticate using macaroons you need to include the macaroon in the metadata of the request. 143 | 144 | ```python 145 | import codecs 146 | 147 | # Lnd admin macaroon is at ~/.lnd/data/chain/bitcoin/simnet/admin.macaroon on Linux and 148 | # ~/Library/Application Support/Lnd/data/chain/bitcoin/simnet/admin.macaroon on Mac 149 | with open(os.path.expanduser('~/.lnd/data/chain/bitcoin/simnet/admin.macaroon'), 'rb') as f: 150 | macaroon_bytes = f.read() 151 | macaroon = codecs.encode(macaroon_bytes, 'hex') 152 | ``` 153 | 154 | The simplest approach to use the macaroon is to include the metadata in each request as shown below. 155 | 156 | ```python 157 | stub.GetInfo(ln.GetInfoRequest(), metadata=[('macaroon', macaroon)]) 158 | ``` 159 | 160 | However, this can get tiresome to do for each request, so to avoid explicitly including the macaroon we can update the credentials to include it automatically. 161 | 162 | ```python 163 | def metadata_callback(context, callback): 164 | # for more info see grpc docs 165 | callback([('macaroon', macaroon)], None) 166 | 167 | 168 | # build ssl credentials using the cert the same as before 169 | cert_creds = grpc.ssl_channel_credentials(cert) 170 | 171 | # now build meta data credentials 172 | auth_creds = grpc.metadata_call_credentials(metadata_callback) 173 | 174 | # combine the cert credentials and the macaroon auth credentials 175 | # such that every call is properly encrypted and authenticated 176 | combined_creds = grpc.composite_channel_credentials(cert_creds, auth_creds) 177 | 178 | # finally pass in the combined credentials when creating a channel 179 | channel = grpc.secure_channel('localhost:10009', combined_creds) 180 | stub = lnrpc.LightningStub(channel) 181 | 182 | # now every call will be made with the macaroon already included 183 | stub.GetInfo(ln.GetInfoRequest()) 184 | ``` 185 | 186 | 187 | ### Conclusion 188 | 189 | With the above, you should have all the `lnd` related `gRPC` dependencies 190 | installed locally into your virtual environment. In order to get up to speed 191 | with `protobuf` usage from Python, see [this official `protobuf` tutorial for 192 | Python](https://developers.google.com/protocol-buffers/docs/pythontutorial). 193 | Additionally, [this official gRPC 194 | resource](http://www.grpc.io/docs/tutorials/basic/python.html) provides more 195 | details around how to drive `gRPC` from Python. 196 | 197 | 198 | -------------------------------------------------------------------------------- /index.md: -------------------------------------------------------------------------------- 1 | --- 2 | # You don't need to edit this file, it's empty on purpose. 3 | # Edit theme's home layout instead if you wanna make some changes 4 | # See: https://jekyllrb.com/docs/themes/#overriding-theme-defaults 5 | layout: home 6 | --- 7 | -------------------------------------------------------------------------------- /render.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python2.7 2 | from jinja2 import Environment, FileSystemLoader, select_autoescape 3 | 4 | 5 | def read_file_without_title(filename): 6 | """ 7 | Takes filename of markdown as input and returns the file contents as a 8 | utf-8 encoded string after stripping out the title 9 | """ 10 | file_lines = open(filename).readlines() 11 | 12 | while True: 13 | line = file_lines[0].decode('utf-8').strip() 14 | 15 | # If the line is empty or begins with a `# ` denoting a h1 md header 16 | if line == '' or line[:2] == '# ': 17 | # Remove the first line 18 | file_lines.pop(0) 19 | else: 20 | break 21 | 22 | # At this point, file_lines is stripped of the title. 23 | # Return the utf string 24 | return "".join(file_lines) 25 | 26 | 27 | def render(): 28 | """ 29 | Given the necessary markdown files that are maintained on Github in the 30 | `lnd` repo, renders the guides with Jekyll header. 31 | """ 32 | 33 | # Load the Jekyll header from the `templates` dir 34 | env = Environment( 35 | loader=FileSystemLoader('./templates'), 36 | autoescape=select_autoescape(['html', 'xml']) 37 | ) 38 | template = env.get_template('base.md') 39 | 40 | # Read INSTALL.md and output guides/installation.md 41 | installation_guide = template.render( 42 | title='Installation', 43 | permalink=None, 44 | content=read_file_without_title('INSTALL.md'), 45 | footer=open('templates/installation_footer.md').read(), 46 | ).encode('utf-8') 47 | installation_output = 'guides/installation.md' 48 | with open(installation_output, "wb") as file_out: 49 | file_out.write(installation_guide) 50 | print "Rendered {}".format(installation_output) 51 | 52 | # Read DOCKER-README.md and output guides/docker.md 53 | docker_guide = template.render( 54 | title='Working with LND and Docker', 55 | permalink=None, 56 | content=read_file_without_title('DOCKER-README.md'), 57 | ).encode('utf-8') 58 | docker_output = 'guides/docker.md' 59 | with open(docker_output, "wb") as file_out: 60 | file_out.write(docker_guide) 61 | print "Rendered {}".format(docker_output) 62 | 63 | # Read python.md and output guides/python-grpc.md 64 | python_grpc_guide = template.render( 65 | title='How to write a Python gRPC client for the Lightning Network Daemon', 66 | permalink=None, 67 | content=read_file_without_title('python.md'), 68 | ).encode('utf-8') 69 | python_grpc_output = 'guides/python-grpc.md' 70 | with open(python_grpc_output, "wb") as file_out: 71 | file_out.write(python_grpc_guide) 72 | print "Rendered {}".format(python_grpc_output) 73 | 74 | # Read javascript.md and output guides/javascript-grpc.md 75 | javascript_grpc_guide = template.render( 76 | title='How to write a Javascript gRPC client for the Lightning Network Daemon', 77 | permalink=None, 78 | content=read_file_without_title('javascript.md'), 79 | ).encode('utf-8') 80 | javascript_grpc_output = 'guides/javascript-grpc.md' 81 | with open(javascript_grpc_output, "wb") as file_out: 82 | file_out.write(javascript_grpc_guide) 83 | print "Rendered {}".format(javascript_grpc_output) 84 | 85 | 86 | if __name__ == '__main__': 87 | render() 88 | -------------------------------------------------------------------------------- /templates/base.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: page 3 | title: {{ title }} 4 | {% if permalink %}permalink: {{ permalink }} {% endif %} 5 | --- 6 | 7 | {{ content }} 8 | 9 | {% if footer %} 10 | {{ footer }} 11 | {% endif %} 12 | -------------------------------------------------------------------------------- /templates/installation_footer.md: -------------------------------------------------------------------------------- 1 | 2 | ### Next Steps 3 | 4 | * **[Tutorial](/tutorial/):** Get acquainted with the skills necessary for `lnd` development. 5 | * **[Developer Guides](/guides/):** Look through developer manuals on gRPC, 6 | Docker, and more. 7 | * **[Resources](/resources/):** Learn about the Lightning Network 8 | * **[Code Contribution Guidelines](/contribute/):** Contribute to `lnd` itself. 9 | -------------------------------------------------------------------------------- /tutorial/01-lncli.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: page 3 | title: Stage 1 - Setting up a local cluster 4 | --- 5 | ### Introduction 6 | 7 | In this stage of the tutorial, we will learn how to set up a local cluster of 8 | nodes `Alice`, `Bob`, and `Charlie`, have them talk to each other, set up 9 | channels, and route payments between one another. We will also establish a 10 | baseline understanding of the different components that must work together as 11 | part of developing on `lnd`. 12 | 13 | This tutorial assumes you have completed installation of Go, `btcd`, and `lnd` 14 | on simnet. If not, please refer to the [installation 15 | instructions](/guides/installation/). Note that for the purposes of this 16 | tutorial it is not necessary to sync testnet, and the last section of the 17 | installation instructions you'll need to complete is "Installing btcd." 18 | 19 | The schema will be the following. Keep in mind that you can easily extend this 20 | network to include additional nodes `David`, `Eve`, etc. by simply running more 21 | local `lnd` instances. 22 | 23 | [//]: # (TODO Max: Replace this with an actual image) 24 | ``` 25 | (1) (1) (1) 26 | + ----- + + --- + + ------- + 27 | | Alice | <--- channel ---> | Bob | <--- channel ---> | Charlie | 28 | + ----- + + --- + + ------- + 29 | | | | 30 | | | | 31 | + - - - - - - - - - - - - + - - - - - - - - - - - - - + 32 | | 33 | + --------------- + 34 | | BTC/LTC network | <--- (2) 35 | + --------------- + 36 | ``` 37 | 38 | ### Understanding the components 39 | 40 | #### LND 41 | 42 | `lnd` is the main component that we will interact with. `lnd` stands for 43 | Lightning Network Daemon, and handles channel opening/closing, routing and 44 | sending payments, and managing all the Lightning Network state that is separate 45 | from the underlying Bitcoin network itself. 46 | 47 | Running an `lnd` node means that it is listening for payments, watching the 48 | blockchain, etc. By default it is awaiting user input. 49 | 50 | `lncli` is the command line client used to interact with your `lnd` nodes. 51 | Typically, each `lnd` node will be running in its own terminal window, so that 52 | you can see its log outputs. `lncli` commands are thus run from a different 53 | terminal window. 54 | 55 | #### BTCD 56 | 57 | `btcd` represents the gateway that `lnd` nodes will use to interact with the 58 | Bitcoin / Litecoin network. `lnd` needs `btcd` for creating on-chain addresses 59 | or transactions, watching the blockchain for updates, and opening/closing 60 | channels. In our current schema, all three of the nodes are connected to the 61 | same `btcd` instance. In a more realistic scenario, each of the `lnd` nodes 62 | will be connected to their own instances of `btcd` or equivalent. 63 | 64 | We will also be using `simnet` instead of `testnet`. Simnet is a 65 | development/test network run locally that allows us to generate blocks at will, 66 | so we can avoid the time-consuming process of waiting for blocks to arrive for 67 | any on-chain functionality. 68 | 69 | ### Setting up our environment 70 | 71 | Developing on `lnd` can be quite complex since there are many more moving 72 | pieces, so to simplify that process, we will walk through a recommended 73 | workflow. 74 | 75 | #### Running btcd 76 | 77 | Let's start by running btcd, if you don't have it up already. Open up a new 78 | terminal window, ensure you have your `$GOPATH` set, and run: 79 | ```bash 80 | btcd --txindex --simnet --rpcuser=kek --rpcpass=kek 81 | ``` 82 | (Note: this tutorial requires opening quite a few terminal windows. It may be 83 | convenient to use multiplexers such as tmux or screen if you're familiar with 84 | them.) 85 | 86 | Breaking down the components: 87 | * `--txindex` is required so that the `lnd` client is able to query 88 | historical transactions from `btcd`. 89 | * `--simnet` specifies that we are using the `simnet` network. This can be 90 | changed to `--testnet`, or omitted entirely to connect to the actual Bitcoin 91 | / Litecoin network. 92 | * `--rpcuser` and `rpcpass` sets a default password for authenticating to the 93 | `btcd` instance. 94 | 95 | #### Starting lnd (Alice's node) 96 | 97 | Now, let's set up the three `lnd` nodes. To keep things as clean and separate 98 | as possible, open up a new terminal window, ensure you have `$GOPATH` set and 99 | `$GOPATH/bin` in your `PATH`, and create a new directory under `$GOPATH` called 100 | `dev` that will represent our development space. We will create separate 101 | folders to store the state for alice, bob, and charlie, and run all of our 102 | `lnd` nodes on different `localhost` ports instead of using 103 | [Docker](/guides/docker/) to make our networking a bit easier. 104 | 105 | ```bash 106 | # Create our development space 107 | cd $GOPATH 108 | mkdir dev 109 | cd dev 110 | 111 | # Create folders for each of our nodes 112 | mkdir alice bob charlie 113 | ``` 114 | 115 | The directory structure should now look like this: 116 | ```bash 117 | $ tree $GOPATH -L 2 118 | 119 | ├── bin 120 | │ └── ... 121 | ├── dev 122 | │ ├── alice 123 | │ ├── bob 124 | │ └── charlie 125 | ├── pkg 126 | │ └── ... 127 | ├── rpc 128 | │ └── ... 129 | └── src 130 | └── ... 131 | ``` 132 | 133 | Start up the Alice node from within the `alice` directory: 134 | ```bash 135 | cd $GOPATH/dev/alice 136 | alice$ lnd --rpclisten=localhost:10001 --listen=localhost:10011 --restlisten=localhost:8001 --datadir=data --logdir=log --debuglevel=info --bitcoin.simnet --bitcoin.active --bitcoin.node=btcd --btcd.rpcuser=kek --btcd.rpcpass=kek 137 | ``` 138 | The Alice node should now be running and displaying output ending with a line 139 | beginning with "Waiting for wallet encryption password." 140 | 141 | Breaking down the components: 142 | * `--rpclisten`: The host:port to listen for the RPC server. This is the primary way 143 | an application will communicate with `lnd` 144 | * `--listen`: The host:port to listen on for incoming P2P 145 | connections. This is at the networking level, and is distinct from the 146 | Lightning channel networks and Bitcoin/Litcoin network itself. 147 | * `--restlisten`: The host:port exposing a REST api for interacting with `lnd` over 148 | HTTP. For example, you can get Alice's channel balance by making a GET 149 | request to `localhost:8001/v1/channels`. This is not needed for this 150 | tutorial, but you can see some examples 151 | [here](https://gist.github.com/Roasbeef/624c02cd5a90a44ab06ea90e30a6f5f0). 152 | * `--datadir`: The directory that `lnd`'s data will be stored inside 153 | * `--logdir`: The directory to log output. 154 | * `--debuglevel`: The logging level for all subsystems. Can be set to 155 | `trace`, `debug`, `info`, `warn`, `error`, `critical`. 156 | * `--bitcoin.simnet`: Specifies whether to use `simnet` or `testnet` 157 | * `--bitcoin.active`: Specifies that bitcoin is active. Can also include 158 | `--litecoin.active` to activate Litecoin. 159 | * `--bitcoin.node=btcd`: Use the `btcd` full node to interface with the blockchain. 160 | Note that when using Litecoin, the option is `--litecoin.node=btcd`. 161 | * `--btcd.rpcuser` and `--btcd.rpcpass`: The username and password for 162 | the `btcd` instance. Note that when using Litecoin, the options are `--ltcd.rpcuser` 163 | and `--ltcd.rpcpass`. 164 | 165 | ### Starting Bob's node and Charlie's node 166 | 167 | Just as we did with Alice, start up the Bob node from within the `bob` 168 | directory, and the Charlie node from within the `charlie` directory. Doing so 169 | will configure the `datadir` and `logdir` to be in separate locations so that 170 | there is never a conflict. 171 | 172 | Keep in mind that for each additional terminal window you set, you will need to 173 | set `$GOPATH` and include `$GOPATH/bin` in your `PATH`. Consider creating a 174 | setup script that includes the following lines: 175 | ```bash 176 | export GOPATH=~/gocode # if you exactly followed the install guide 177 | export PATH=$PATH:$GOPATH/bin 178 | ``` 179 | and run it every time you start a new terminal window working on `lnd`. 180 | 181 | Run Bob and Charlie: 182 | ```bash 183 | # In a new terminal window 184 | cd $GOPATH/dev/bob 185 | bob$ lnd --rpclisten=localhost:10002 --listen=localhost:10012 --restlisten=localhost:8002 --datadir=data --logdir=log --debuglevel=info --bitcoin.simnet --bitcoin.active --bitcoin.node=btcd --btcd.rpcuser=kek --btcd.rpcpass=kek 186 | 187 | # In another terminal window 188 | cd $GOPATH/dev/charlie 189 | charlie$ lnd --rpclisten=localhost:10003 --listen=localhost:10013 --restlisten=localhost:8003 --datadir=data --logdir=log --debuglevel=info --bitcoin.simnet --bitcoin.active --bitcoin.node=btcd --btcd.rpcuser=kek --btcd.rpcpass=kek 190 | ``` 191 | 192 | ### Configuring lnd.conf 193 | 194 | To skip having to type out a bunch of flags on the command line every time, we 195 | can instead modify our `lnd.conf`, and the arguments specified therein will be 196 | loaded into `lnd` automatically. Any additional configuration added as a 197 | command line argument will be applied *after* reading from `lnd.conf`, and will 198 | overwrite the `lnd.conf` option if applicable. 199 | 200 | - On MacOS, `lnd.conf` is located at: `/Users/[username]/Library/Application\ Support/Lnd/lnd.conf` 201 | - On Linux: `~/.lnd/lnd.conf` 202 | 203 | Here is an example `lnd.conf` that can save us from re-specifying a bunch of 204 | command line options: 205 | ```bash 206 | [Application Options] 207 | datadir=data 208 | logdir=log 209 | debuglevel=info 210 | 211 | [Bitcoin] 212 | bitcoin.simnet=1 213 | bitcoin.active=1 214 | bitcoin.node=btcd 215 | 216 | [btcd] 217 | btcd.rpcuser=kek 218 | btcd.rpcpass=kek 219 | ``` 220 | 221 | Now, when we start nodes, we only have to type 222 | ```bash 223 | alice$ lnd --rpclisten=localhost:10001 --listen=localhost:10011 --restlisten=localhost:8001 224 | bob$ lnd --rpclisten=localhost:10002 --listen=localhost:10012 --restlisten=localhost:8002 225 | charlie$ lnd --rpclisten=localhost:10003 --listen=localhost:10013 --restlisten=localhost:8003 226 | ``` 227 | etc. 228 | 229 | ### Working with lncli and authentication 230 | 231 | Now that we have our `lnd` nodes up and running, let's interact with them! To 232 | control `lnd` we will need to use `lncli`, the command line interface. 233 | 234 | `lnd` uses [macaroons](https://github.com/lightningnetwork/lnd/issues/20) for 235 | authentication to the rpc server. `lncli` typically looks for an 236 | `admin.macaroon` file in the Lnd home directory, but since we changed the 237 | location of our application data, we have to set `--macaroonpath` in the 238 | following command. To disable macaroons, pass the `--no-macaroons` flag into 239 | both `lncli` and `lnd`. 240 | 241 | `lnd` allows you to encrypt your wallet with a passphrase and optionally encrypt 242 | your cipher seed passphrase as well. This can be turned off by passing 243 | `--noencryptwallet` into `lnd` or `lnd.conf`. We recommend going through this 244 | process at least once to familiarize yourself with the security and 245 | authentication features around `lnd`. 246 | 247 | We will test our rpc connection to the Alice node. Notice that in the following command we specify the 248 | `--rpcserver` here, which corresponds to `--rpcport=10001` that we set when 249 | starting the Alice `lnd` node. 250 | 251 | Open up a new terminal window, set `$GOPATH` and include `$GOPATH/bin` in your 252 | `PATH` as usual. Let's create Alice's wallet and set her passphrase: 253 | ```bash 254 | cd $GOPATH/dev/alice 255 | alice$ lncli --rpcserver=localhost:10001 --macaroonpath=data/chain/bitcoin/simnet/admin.macaroon create 256 | ``` 257 | You'll be asked to input and confirm a wallet password for Alice, which must be 258 | longer than 8 characters. You also have the option to add a passphrase to your 259 | cipher seed. For now, just skip this step by entering "n" when prompted about 260 | whether you have an existing mnemonic, and pressing enter to proceed without the 261 | passphrase. 262 | 263 | You can now request some basic information as follows: 264 | ```bash 265 | alice$ lncli --rpcserver=localhost:10001 --macaroonpath=data/chain/bitcoin/simnet/admin.macaroon getinfo 266 | ``` 267 | `lncli` just made an RPC call to the Alice `lnd` node. This is a good way to 268 | test if your nodes are up and running and `lncli` is functioning properly. Note 269 | that in future sessions you may need to call `lncli unlock` to unlock the node 270 | with the password you just set. 271 | 272 | Open up new terminal windows and do the same for Bob and Charlie. `alice$` or 273 | `bob$` denotes running the command from the Alice or Bob `lncli` window 274 | respectively. 275 | ```bash 276 | # In a new terminal window, setting $GOPATH, etc. 277 | cd $GOPATH/dev/bob 278 | bob$ lncli --rpcserver=localhost:10002 --macaroonpath=data/chain/bitcoin/simnet/admin.macaroon create 279 | # Note that you'll have to enter an 8+ character password and "n" for the mnemonic. 280 | 281 | # In a new terminal window: 282 | cd $GOPATH/dev/charlie 283 | charlie$ lncli --rpcserver=localhost:10003 --macaroonpath=data/chain/bitcoin/simnet/admin.macaroon create 284 | # Note that you'll have to enter an 8+ character password and "n" for the mnemonic. 285 | ``` 286 | 287 | To avoid typing the `--rpcserver=localhost:1000X` and `--macaroonpath` flag 288 | every time, we can set some aliases. Add the following to your `.bashrc`: 289 | ```bash 290 | alias lncli-alice="lncli --rpcserver=localhost:10001 --macaroonpath=data/chain/bitcoin/simnet/admin.macaroon" 291 | alias lncli-bob="lncli --rpcserver=localhost:10002 --macaroonpath=data/chain/bitcoin/simnet/admin.macaroon" 292 | alias lncli-charlie="lncli --rpcserver=localhost:10003 --macaroonpath=data/chain/bitcoin/simnet/admin.macaroon" 293 | ``` 294 | 295 | To make sure this was applied to all of your current terminal windows, rerun 296 | your `.bashrc` file: 297 | ```bash 298 | alice$ source ~/.bashrc 299 | bob$ source ~/.bashrc 300 | charlie$ source ~/.bashrc 301 | ``` 302 | For simplicity, the rest of the tutorial will assume that this step was 303 | complete. 304 | 305 | #### lncli options 306 | 307 | To see all the commands available for `lncli`, simply type `lncli --help` or 308 | `lncli -h`. 309 | 310 | ### Setting up Bitcoin addresses 311 | Let's create a new Bitcoin address for Alice. This will be the address that 312 | stores Alice's on-chain balance. `np2wkh` specifes the type of address and 313 | stands for Pay to Nested Witness Key Hash. 314 | 315 | ```bash 316 | alice$ lncli-alice newaddress np2wkh 317 | { 318 | "address": 319 | } 320 | ``` 321 | 322 | And for Bob and Charlie: 323 | ```bash 324 | bob$ lncli-bob newaddress np2wkh 325 | { 326 | "address": 327 | } 328 | 329 | charlie$ lncli-charlie newaddress np2wkh 330 | { 331 | "address": 332 | } 333 | ``` 334 | 335 | ### Funding Alice 336 | 337 | That's a lot of configuration! At this point, we've generated onchain addresses 338 | for Alice, Bob, and Charlie. Now, we will get some practice working with `btcd` 339 | and fund these addresses with some `simnet` Bitcoin. 340 | 341 | Quit btcd and re-run it, setting Alice as the recipient of all mining rewards: 342 | ```bash 343 | btcd --simnet --txindex --rpcuser=kek --rpcpass=kek --miningaddr= 344 | ``` 345 | 346 | Generate 400 blocks, so that Alice gets the reward. We need at least 100 blocks 347 | because coinbase funds can't be spent until after 100 confirmations, and we need 348 | about 300 to activate segwit. In a new window with `$GOPATH` and `$PATH` set: 349 | ```bash 350 | alice$ btcctl --simnet --rpcuser=kek --rpcpass=kek generate 400 351 | ``` 352 | 353 | Check that segwit is active: 354 | ```bash 355 | btcctl --simnet --rpcuser=kek --rpcpass=kek getblockchaininfo | grep -A 1 segwit 356 | ``` 357 | 358 | Check Alice's wallet balance. 359 | ```bash 360 | alice$ lncli-alice walletbalance 361 | ``` 362 | 363 | It's no fun if only Alice has money. Let's give some to Charlie as well. 364 | ```bash 365 | # Quit the btcd process that was previously started with Alice's mining address, 366 | # and then restart it with: 367 | btcd --txindex --simnet --rpcuser=kek --rpcpass=kek --miningaddr= 368 | 369 | # Generate more blocks 370 | btcctl --simnet --rpcuser=kek --rpcpass=kek generate 100 371 | 372 | # Check Charlie's balance 373 | charlie$ lncli-charlie walletbalance 374 | ``` 375 | 376 | ### Creating the P2P Network 377 | Now that Alice and Charlie have some simnet Bitcoin, let's start connecting 378 | them together. 379 | 380 | Connect Alice to Bob: 381 | ```bash 382 | # Get Bob's identity pubkey: 383 | bob$ lncli-bob getinfo 384 | { 385 | --->"identity_pubkey": , 386 | "alias": "", 387 | "num_pending_channels": 0, 388 | "num_active_channels": 0, 389 | "num_peers": 0, 390 | "block_height": 450, 391 | "block_hash": "2a84b7a2c3be81536ef92cf382e37ab77f7cfbcf229f7d553bb2abff3e86231c", 392 | "synced_to_chain": true, 393 | "testnet": false, 394 | "chains": [ 395 | "bitcoin" 396 | ], 397 | "uris": [ 398 | ], 399 | "best_header_timestamp": "1533350134", 400 | "version": "0.4.2-beta commit=7a5a824d179c6ef16bd78bcb7a4763fda5f3f498" 401 | } 402 | 403 | # Connect Alice and Bob together 404 | alice$ lncli-alice connect @localhost:10012 405 | { 406 | 407 | } 408 | ``` 409 | Notice that `localhost:10012` corresponds to the `--listen=localhost:10012` flag we set 410 | when starting the Bob `lnd` node. 411 | 412 | Let's check that Alice and Bob are now aware of each other. 413 | ```bash 414 | # Check that Alice has added Bob as a peer: 415 | alice$ lncli-alice listpeers 416 | { 417 | "peers": [ 418 | { 419 | "pub_key": , 420 | "address": "127.0.0.1:10012", 421 | "bytes_sent": "7", 422 | "bytes_recv": "7", 423 | "sat_sent": "0", 424 | "sat_recv": "0", 425 | "inbound": false, 426 | "ping_time": "0" 427 | } 428 | ] 429 | } 430 | 431 | # Check that Bob has added Alice as a peer: 432 | bob$ lncli-bob listpeers 433 | { 434 | "peers": [ 435 | { 436 | "pub_key": , 437 | "address": "127.0.0.1:60104", 438 | "bytes_sent": "318", 439 | "bytes_recv": "318", 440 | "sat_sent": "0", 441 | "sat_recv": "0", 442 | "inbound": true, 443 | "ping_time": "5788" 444 | } 445 | ] 446 | } 447 | ``` 448 | 449 | Finish up the P2P network by connecting Bob to Charlie: 450 | ```bash 451 | charlie$ lncli-charlie connect @localhost:10012 452 | ``` 453 | 454 | ### Setting up Lightning Network 455 | 456 | Before we can send payment, we will need to set up payment channels from Alice 457 | to Bob, and Bob to Charlie. 458 | 459 | First, let's open the Alice<-->Bob channel. 460 | ```bash 461 | alice$ lncli-alice openchannel --node_key= --local_amt=1000000 462 | ``` 463 | - `--local_amt` specifies the amount of money that Alice will commit to the 464 | channel. To see the full list of options, you can try `lncli openchannel 465 | --help`. 466 | 467 | We now need to mine six blocks so that the channel is considered valid: 468 | ```bash 469 | btcctl --simnet --rpcuser=kek --rpcpass=kek generate 6 470 | ``` 471 | 472 | Check that Alice<-->Bob channel was created: 473 | ```bash 474 | alice$ lncli-alice listchannels 475 | { 476 | "channels": [ 477 | { 478 | "active": true, 479 | "remote_pubkey": , 480 | "channel_point": "2622b779a8acca471a738b0796cd62e4457b79b33265cbfa687aadccc329023a:0", 481 | "chan_id": "495879744192512", 482 | "capacity": "1000000", 483 | "local_balance": "991312", 484 | "remote_balance": "0", 485 | "commit_fee": "8688", 486 | "commit_weight": "600", 487 | "fee_per_kw": "12000", 488 | "unsettled_balance": "0", 489 | "total_satoshis_sent": "0", 490 | "total_satoshis_received": "0", 491 | "num_updates": "0", 492 | "pending_htlcs": [ 493 | ], 494 | "csv_delay": 144, 495 | "private": false 496 | } 497 | ] 498 | } 499 | ``` 500 | 501 | ### Sending single hop payments 502 | 503 | Finally, to the exciting part - sending payments! Let's send a payment from 504 | Alice to Bob. 505 | 506 | First, Bob will need to generate an invoice: 507 | ```bash 508 | bob$ lncli-bob addinvoice --amt=10000 509 | { 510 | "r_hash": "", 511 | "pay_req": "", 512 | "add_index": 1 513 | } 514 | ``` 515 | 516 | Send the payment from Alice to Bob: 517 | ```bash 518 | alice$ lncli-alice sendpayment --pay_req= 519 | { 520 | "payment_error": "", 521 | "payment_preimage": "baf6929fc95b3824fb774a4b75f6c8a1ad3aaef04efbf26cc064904729a21e28", 522 | "payment_route": { 523 | "total_time_lock": 650, 524 | "total_amt": 10000, 525 | "hops": [ 526 | { 527 | "chan_id": 495879744192512, 528 | "chan_capacity": 1000000, 529 | "amt_to_forward": 10000, 530 | "expiry": 650, 531 | "amt_to_forward_msat": 10000000 532 | } 533 | ], 534 | "total_amt_msat": 10000000 535 | } 536 | } 537 | 538 | # Check that Alice's channel balance was decremented accordingly: 539 | alice$ lncli-alice listchannels 540 | 541 | # Check that Bob's channel was credited with the payment amount: 542 | bob$ lncli-bob listchannels 543 | ``` 544 | 545 | ### Multi-hop payments 546 | 547 | Now that we know how to send single-hop payments, sending multi hop payments is 548 | not that much more difficult. Let's set up a channel from Bob<-->Charlie: 549 | ```bash 550 | charlie$ lncli-charlie openchannel --node_key= --local_amt=800000 --push_amt=200000 551 | 552 | # Mine the channel funding tx 553 | btcctl --simnet --rpcuser=kek --rpcpass=kek generate 6 554 | ``` 555 | 556 | Note that this time, we supplied the `--push_amt` argument, which specifies the 557 | amount of money we want the other party to have at the first channel state. 558 | 559 | Let's make a payment from Alice to Charlie by routing through Bob: 560 | ```bash 561 | charlie$ lncli-charlie addinvoice --amt=10000 562 | alice$ lncli-alice sendpayment --pay_req= 563 | 564 | # Check that Charlie's channel was credited with the payment amount (e.g. that 565 | # the `remote_balance` has been decremented by 10000) 566 | charlie$ lncli-charlie listchannels 567 | ``` 568 | 569 | ### Closing channels 570 | 571 | For practice, let's try closing a channel. We will reopen it in the next stage 572 | of the tutorial. 573 | 574 | ```bash 575 | alice$ lncli-alice listchannels 576 | { 577 | "channels": [ 578 | { 579 | "active": true, 580 | "remote_pubkey": "0343bc80b914aebf8e50eb0b8e445fc79b9e6e8e5e018fa8c5f85c7d429c117b38", 581 | ---->"channel_point": "3511ae8a52c97d957eaf65f828504e68d0991f0276adff94c6ba91c7f6cd4275:0", 582 | "chan_id": "1337006139441152", 583 | "capacity": "1005000", 584 | "local_balance": "990000", 585 | "remote_balance": "10000", 586 | "unsettled_balance": "0", 587 | "total_satoshis_sent": "10000", 588 | "total_satoshis_received": "0", 589 | "num_updates": "2" 590 | } 591 | ] 592 | } 593 | ``` 594 | 595 | The Channel point consists of two numbers separated by a colon, which uniquely 596 | identifies the channel. The first number is `funding_txid` and the second 597 | number is `output_index`. 598 | ```bash 599 | # Close the Alice<-->Bob channel from Alice's side. 600 | alice$ lncli-alice closechannel --funding_txid= --output_index= 601 | 602 | # Mine a block including the channel close transaction to close the channel: 603 | btcctl --simnet --rpcuser=kek --rpcpass=kek generate 1 604 | 605 | # Check that Bob's on-chain balance was credited by his settled amount in the 606 | # channel. Recall that Bob previously had no on-chain Bitcoin: 607 | bob$ lncli-bob walletbalance 608 | { 609 | "total_balance": "20001", 610 | "confirmed_balance": "20001", 611 | "unconfirmed_balance": "0" 612 | } 613 | ``` 614 | 615 | At this point, you've learned how to work with `btcd`, `btcctl`, `lnd`, and 616 | `lncli`. In [Stage 2](/tutorial/02-web-client), we will learn how to set up and 617 | interact with `lnd` using a web GUI client. 618 | 619 | _In the future, you can try running through this workflow on `testnet` instead 620 | of `simnet`, where you can interact with and send payments through the testnet 621 | Lightning Faucet node. For more information, see the "Connect to faucet 622 | lightning node" section in the [Docker guide](/guides/docker/) or check out the 623 | [Lightning Network faucet 624 | repository](https://github.com/lightninglabs/lightning-faucet)._ 625 | 626 | [//]: # (TODO Max: Replace the link to Github LN Faucet to an internal guide for interacting with the Lightning Faucet) 627 | 628 | #### Navigation 629 | - [Proceed to Stage 2 - Web Client](/tutorial/02-web-client) 630 | - [Return to main tutorial page](/tutorial/) 631 | 632 | ### Questions 633 | - Join the #dev-help channel on our [Community 634 | Slack](https://join.slack.com/t/lightningcommunity/shared_invite/enQtMzQ0OTQyNjE5NjU1LWRiMGNmOTZiNzU0MTVmYzc1ZGFkZTUyNzUwOGJjMjYwNWRkNWQzZWE3MTkwZjdjZGE5ZGNiNGVkMzI2MDU4ZTE) 635 | - Join IRC: 636 | [![Irc](https://img.shields.io/badge/chat-on%20freenode-brightgreen.svg)](https://webchat.freenode.net/?channels=lnd) 637 | -------------------------------------------------------------------------------- /tutorial/02-web-client.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: page 3 | title: Stage 2 - Web Client 4 | --- 5 | 6 | In this section we will learn how to set up and interact with `lnd` using a 7 | [web client](https://github.com/mably/lncli-web) built by [Francois 8 | Mably](https://github.com/mably). Setup instructions are courtesy of the 9 | creator himself. Before beginning this step make sure you have `node` and `npm` 10 | [installed](https://nodejs.org/en/download/). 11 | 12 | ### Setting up the LND web client 13 | 14 | ```bash 15 | # Clone the repo and move into it: 16 | git clone https://github.com/mably/lncli-web $GOPATH/src/github.com/mably/lncli-web 17 | cd $GOPATH/src/github.com/mably/lncli-web 18 | 19 | # Install dependencies 20 | npm install 21 | 22 | # Setup default configuration files 23 | "./node_modules/.bin/gulp" bundle 24 | 25 | # Setup cert file 26 | # Enter the Lnd home directory, located by default at ~/.lnd on Linux or 27 | # /Users/[username]/Library/Application Support/Lnd/ on Mac OSX 28 | # $APPDATA/Local/Lnd on Windows. Also change '/CN=localhost/O=lnd' to '//CN=localhost\O=lnd' if you are using Git Bash. 29 | cd ~/.lnd 30 | openssl ecparam -genkey -name prime256v1 -out tls.key 31 | openssl req -new -sha256 -key tls.key -out csr.csr -subj '/CN=localhost/O=lnd' 32 | openssl req -x509 -sha256 -days 36500 -key tls.key -in csr.csr -out tls.cert 33 | rm csr.csr 34 | cp tls.cert $GOPATH/src/github.com/mably/lncli-web/lnd.cert 35 | 36 | # Start the server to point to our Alice node: 37 | cd $GOPATH/src/github.com/mably/lncli-web 38 | node server --lndhost=localhost:10001 39 | 40 | # Check out the available command line arguments 41 | node server --help 42 | ``` 43 | 44 | Open up [`http://localhost:8280/`](http://localhost:8280/) in your browser to see the web dashboard. 45 | 46 | ### Poking around 47 | 48 | Now would be a good time to reopen that channel we had between Alice and Bob. 49 | Except this time, we're going to do it through the web dashboard. Feel free to 50 | try this on your own - the web dashboard is intuitive enough that we don't need 51 | step by step instructions for it. 52 | 53 | Note: The Lightning desktop app is also available and is another good way to 54 | start experimenting with Lightning. You can find it 55 | [here](https://github.com/lightninglabs/lightning-app/releases). 56 | 57 | ### Moving on to Step 3 58 | 59 | By now, you should have gained familiarity with the web client. 60 | In [Stage 3](/tutorial/03-rpc-client), we will learn how to set up a gRPC 61 | client for programmatic access to our `lnd` nodes. 62 | 63 | #### Navigation 64 | - [Proceed to Stage 3 - RPC Client](/tutorial/03-rpc-client) 65 | - [Return to Stage 1 - Setting up a local cluster](/tutorial/01-lncli) 66 | - [Return to main tutorial page](/tutorial/) 67 | 68 | ### Questions 69 | - Join the #dev-help channel on our [Community 70 | Slack](https://join.slack.com/t/lightningcommunity/shared_invite/enQtMzQ0OTQyNjE5NjU1LWRiMGNmOTZiNzU0MTVmYzc1ZGFkZTUyNzUwOGJjMjYwNWRkNWQzZWE3MTkwZjdjZGE5ZGNiNGVkMzI2MDU4ZTE) 71 | - Join IRC: 72 | [![Irc](https://img.shields.io/badge/chat-on%20freenode-brightgreen.svg)](https://webchat.freenode.net/?channels=lnd) 73 | -------------------------------------------------------------------------------- /tutorial/03-rpc-client.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: page 3 | title: Stage 3 - RPC Client 4 | --- 5 | 6 | In this section, we will run the finished tutorial app and set up a gRPC client 7 | for programmatic access to our `lnd` nodes. 8 | 9 | ### Setting up our web development workspace 10 | 11 | Let's set up our news site. Before beginning, ensure that you are running 12 | Python 2.7 and that you have 13 | [`pip`](https://pip.pypa.io/en/stable/installing/) and 14 | [`virtualenv`](https://virtualenv.pypa.io/en/stable/installation/) installed. 15 | ```bash 16 | # Create a new workspace which will hold both the repo and the virtualenv. We 17 | # recommend running this in a new terminal window. 18 | mkdir ln-workspace 19 | cd ln-workspace 20 | 21 | # Clone the repo 22 | git clone https://github.com/MaxFangX/lightning-coindesk 23 | 24 | # Create virtualenv and activate it. Make sure to activate this environment 25 | # whenever you are working with the coindesk app. 26 | virtualenv deskenv 27 | source deskenv/bin/activate 28 | 29 | # Install webapp Python requirements 30 | cd lightning-coindesk 31 | pip install -r requirements.txt 32 | ``` 33 | 34 | Now, let's set up Python gRPC so that we can run our website 35 | ```bash 36 | # Install the dependencies required for gRPC 37 | pip install grpcio grpcio-tools googleapis-common-protos 38 | 39 | # Run our webserver 40 | python manage.py runserver 41 | ``` 42 | 43 | Notice that in `coindesk/settings.py` we have set 44 | `LND_RPCHOST = "localhost:10002"`. In other words, your server is connected to 45 | the "Bob" `lnd` node, and making payments to it is equivalent to making 46 | payments to Bob. 47 | 48 | ### Testing the app 49 | 50 | If everything went smoothly, you should now have a web server exposed at port 51 | 8000. 52 | ![lightning coindesk homepage](http://i.imgur.com/D2LgBUi.png) 53 | 54 | Feel free to click around the site. You will soon find that you need to log in 55 | and make a payment to view the articles. 56 | 57 | ![login page](http://i.imgur.com/zLTEYfk.png) 58 | 59 | To prevent `lnd` users from having to go through the hassle of signing up with 60 | an email address and password, we created an authentication scheme based on the 61 | user's `lnd` identity pubkey and logging in by signing an arbitrary message. In 62 | particular, we are signing the CSRF token sent along with the login POST 63 | request. This scheme is secure against replay attacks because Django generates 64 | a unique CSRF token for every login attempt, and never reuses CSRF tokens. 65 | 66 | Let's create a new account for Alice by logging in and supplying a username. 67 | Copy down the generated message (in the screenshot, it is `VcccAuMC...`) 68 | 69 | ```bash 70 | alice$ lncli-alice signmessage 71 | { 72 | "signature": 73 | } 74 | ``` 75 | 76 | Paste `` into the corresponding field and set `alice` as the desired 77 | username. You should now be logged in as Alice. 78 | 79 | ![logged in homepage](http://imgur.com/BGSunzy.png) 80 | 81 | Navigate to the sweet article and make a payment from the Alice node (you can 82 | use either the command line or the web GUI). Clicking "Complete" will prompt the 83 | webserver to check that the payment has been complete, and you can now enjoy 84 | reading through this sweet article. 85 | 86 | ### Setting up gRPC 87 | 88 | Let's practice running some commands on gRPC. Open up a new terminal window then proceed as follows: 89 | 90 | ```bash 91 | # Enter the development environment 92 | cd ln-workspace 93 | 94 | # Activate Python virtualenv 95 | source deskenv/bin/activate 96 | 97 | # Clone the Google API repository, which is required due to the use of 98 | # google/api/annotations.proto 99 | git clone https://github.com/googleapis/googleapis.git 100 | 101 | # Download the lnd rpc.proto file 102 | curl -o rpc.proto -s https://raw.githubusercontent.com/lightningnetwork/lnd/master/lnrpc/rpc.proto 103 | 104 | # Compile the proto file 105 | python -m grpc_tools.protoc --proto_path=googleapis:. --python_out=. --grpc_python_out=. rpc.proto 106 | ``` 107 | 108 | We have now generated the two files `rpc_pb2.py` and `rpc_pb2_grpc.py`, which 109 | you'll need to import into your Python code in order to use it with lnd. Let's move it into the coindesk folder for easy access 110 | ```bash 111 | mv rpc* lightning-coindesk/coindesk 112 | ``` 113 | 114 | We will now try a few commands with the Python gRPC client from the command 115 | line. 116 | ```bash 117 | # Optionally install ipython for prettier command line output 118 | pip install ipython 119 | 120 | # Open the Django shell. This is a standard Python shell that also allows access to Django objects. 121 | cd lightning-coindesk 122 | python manage.py shell 123 | ``` 124 | 125 | ```python 126 | # Import rpc files and grpc 127 | In [1]: from coindesk import rpc_pb2 as ln, rpc_pb2_grpc as lnrpc 128 | In [2]: import grpc, os 129 | 130 | # Establish a secure connection with our RPC server. We will first have to 131 | # gather our cert. Lnd cert is at ~/.lnd/tls.cert on Linux and 132 | # ~/Library/Application Support/Lnd/tls.cert on Mac 133 | In [3]: cert = open(os.path.expanduser('~/.lnd/tls.cert')).read() 134 | In [4]: creds = grpc.ssl_channel_credentials(cert) 135 | In [5]: channel = grpc.secure_channel('localhost:10009', creds) 136 | # Create a new 'stub' object that will allow us to interact with our "Bob" lnd node. 137 | In [6]: stub = lnrpc.LightningStub(channel) 138 | 139 | # Make a call to the ListChannels API. 140 | In [7]: listchannels_resp = stub.ListChannels(ln.ListChannelsRequest()) 141 | Out[7]: 142 | channels { 143 | active: true 144 | remote_pubkey: "02244b8eff01be9f7b4ec1d73ab10fc36da48b01a685ac90ed09a63fe94ec08d0a" 145 | channel_point: "2622b779a8acca471a738b0796cd62e4457b79b33265cbfa687aadccc329023a:0" 146 | chan_id: 495879744192512 147 | capacity: 1000000 148 | local_balance: 21001 149 | remote_balance: 970311 150 | commit_fee: 8688 151 | commit_weight: 724 152 | fee_per_kw: 12000 153 | total_satoshis_received: 21001 154 | num_updates: 8 155 | } 156 | channels { 157 | active: true 158 | remote_pubkey: "032eed260ef71110a02a5da44d82fef9628ffa51113a2d0b9524e7d3bff615a1cf" 159 | channel_point: "028088c354b26c33cfd5a5b2d4cca27c6e3a73b6752b5beff6f67ce779af5656:1" 160 | chan_id: 554153860464641 161 | capacity: 800000 162 | local_balance: 190000 163 | remote_balance: 601312 164 | commit_fee: 8688 165 | commit_weight: 724 166 | fee_per_kw: 12000 167 | total_satoshis_sent: 10000 168 | num_updates: 2 169 | } 170 | ``` 171 | What happened here? We constructed the request object for the list channels 172 | command with `ln.ListChannelsRequest()`, and passed it into the `ListChannels` 173 | function exposed by our stub. 174 | 175 | The response was saved into a `listchannels_resp` variable that holds all the 176 | information returned by the `listchannels` command. You can now access the 177 | individual properties of this object; for example, you can access the `chan_id` 178 | of Bob's first channel with `listchannels_resp.channels[0].chan_id`. 179 | 180 | ### Playing with gRPC 181 | 182 | To get a hang of the RPC documentation, try running a slightly more complex 183 | command like `GetChanInfo`, which requires passing in some parameters. The API 184 | docs are not yet complete, but you can refer to the [RPC documentation in 185 | lnd](https://github.com/lightningnetwork/lnd/blob/master/lnrpc/rpc.proto). 186 | 187 | Hint: look at the `GetChanInfo` object and the associated requests and 188 | responses. 189 | 190 | ### Moving on to Step 4 191 | 192 | By now, you should have at least a basic understanding of how to work with lnd 193 | from a gRPC client. In [Stage 4](/tutorial/04-webapp-integration), we will 194 | finally integrate `lnd` into our news site. 195 | 196 | #### Navigation 197 | - [Proceed to Stage 4 - Webapp Integration](/tutorial/04-webapp-integration) 198 | - [Return to Stage 2 - Web Client](/tutorial/02-web-client) 199 | - [Return to main tutorial page](/tutorial/) 200 | 201 | ### Questions 202 | - Join the #dev-help channel on our [Community 203 | Slack](https://join.slack.com/t/lightningcommunity/shared_invite/enQtMzQ0OTQyNjE5NjU1LWRiMGNmOTZiNzU0MTVmYzc1ZGFkZTUyNzUwOGJjMjYwNWRkNWQzZWE3MTkwZjdjZGE5ZGNiNGVkMzI2MDU4ZTE) 204 | - Join IRC: 205 | [![Irc](https://img.shields.io/badge/chat-on%20freenode-brightgreen.svg)](https://webchat.freenode.net/?channels=lnd) 206 | -------------------------------------------------------------------------------- /tutorial/04-webapp-integration.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: page 3 | title: Stage 4 - Webapp Integration 4 | --- 5 | 6 | In this stage, we will integrate Lightning micropayments into our server-side 7 | web application. 8 | 9 | ### Starting Afresh 10 | 11 | It's time to recreate the micropayments ourselves. Get the starter code: 12 | 13 | ```bash 14 | # Clear any local changes first and checkout the start tag 15 | git checkout -- . 16 | git checkout start 17 | ``` 18 | 19 | The starter code has stripped out all micropayments code, and we just also just 20 | reset our database state to the default. 21 | 22 | ### The models 23 | 24 | First, let's examine `coindesk/models.py` to understand our web app a little 25 | better. 26 | 27 | `coindesk/models.py` (cleaned up a little bit): 28 | {% raw %} 29 | ```python 30 | class Profile(models.Model): 31 | user = models.OneToOneField(User) 32 | created_at = models.DateTimeField(auto_now_add=True) 33 | modified_at = models.DateTimeField(auto_now=True) 34 | identity_pubkey = models.CharField(max_length=80, unique=True) 35 | # bitcoin_address = BitcoinAddressField() 36 | 37 | 38 | class Article(models.Model): 39 | 40 | ARTICLE_STATUS_CHOICES = ( 41 | ('visible', 'Visible'), 42 | ('deleted by admin', 'Deleted by admin'), 43 | ) 44 | 45 | title = models.CharField(max_length=191) 46 | text = models.TextField() 47 | created_at = models.DateTimeField(auto_now_add=True) 48 | status = models.CharField(max_length=50, default='visible', choices=ARTICLE_STATUS_CHOICES) 49 | 50 | @property 51 | def views(self): 52 | return self.payments.filter(status='complete', purpose='view').count() 53 | 54 | 55 | class Payment(models.Model): 56 | 57 | PAYMENT_STATUS_CHOICES = ( 58 | ('pending_invoice', 'Pending Invoice'), # Should be atomic 59 | ('pending_payment', 'Pending Payment'), 60 | ('complete', 'Complete'), 61 | ('error', 'Error'), 62 | ) 63 | 64 | PAYMENT_PURPOSE_CHOICES = ( 65 | ('view', 'View'), 66 | ('upvote', 'Upvote') 67 | ) 68 | 69 | user = models.ForeignKey(User) 70 | article = models.ForeignKey(Article, related_name='payments') 71 | purpose = models.CharField(max_length=10, choices=PAYMENT_PURPOSE_CHOICES) 72 | 73 | satoshi_amount = models.IntegerField() 74 | r_hash = models.CharField(max_length=64) 75 | payment_request = models.CharField(max_length=1000) 76 | 77 | status = models.CharField(max_length=50, default='pending_invoice', choices=PAYMENT_STATUS_CHOICES) 78 | created_at = models.DateTimeField(auto_now_add=True) 79 | modified_at = models.DateTimeField(auto_now=True) 80 | 81 | def generate_invoice(self, user, article): 82 | """ 83 | Generates a new invoice 84 | """ 85 | pass 86 | 87 | def check_payment(self): 88 | """ 89 | Checks if the Lightning payment has been received for this invoice 90 | """ 91 | pass 92 | ``` 93 | {% endraw %} 94 | 95 | Each `Profile` object is associated with one `User` object, and stores the 96 | identity pubkey of that user. 97 | 98 | The `Article` class has a title, text, a timestamp and some basic moderation 99 | functionality. Notice that the number of views for an article as counted as the 100 | number of completed payments associated with it. 101 | 102 | The `Payment` class represents a Lightning micropayment, and is going to be 103 | where we implement the bulk of our work. Each payment is associated with a particular user and a article. 104 | 105 | We have the `satoshi_amount`, `r_hash` and `payment_request` fields - the basic technical information 106 | required to conduct a Lightning payment. 107 | 108 | Each `Payment` goes through the 109 | following lifecycle, represented by the `status` field: 110 | 111 | 1. The payment is initially pending an invoice. Calling `generate_invoice` will 112 | generate an invoice for a user and a particular article they want to view. 113 | 2. After the invoice is generated, it is now pending payment. 114 | 3. `check_payment` will check if a payment has indeed been received by Bob 115 | node. Afterwards, this `Payment` counts as complete, and the user should be 116 | able to view the article. 117 | 118 | It will soon be up to us to implement the `generate_invoice` and 119 | `check_payment` functions. But first, let's add in some security. 120 | 121 | 122 | ### The views 123 | 124 | We also need to understand some of the wiring behind the app. 125 | 126 | Open `coindesk/views.py`. For our purposes, the `article` view is the most 127 | important since it is executed when we view an article and handles what to do 128 | with the different payment states. 129 | 130 | {% raw %} 131 | ```python 132 | def article(request, pk): 133 | 134 | try: 135 | article = Article.objects.filter(status='visible').get(id=pk) 136 | except Article.DoesNotExist: 137 | raise Exception("Article with id {} does not exist or is not visible".format(pk)) 138 | 139 | context = {'article': article} 140 | 141 | if not request.user.is_authenticated(): 142 | return render(request, 143 | template_name='article.html', 144 | context=context) 145 | 146 | qs = article.payments.filter(user=request.user, purpose='view') 147 | 148 | if qs.count() == 0: 149 | # Generate a new payment 150 | payment, _ = Payment.objects.get_or_create(user=request.user, 151 | article=article, 152 | purpose='view', 153 | satoshi_amount=settings.MIN_VIEW_AMOUNT, 154 | status='pending_invoice') 155 | payment.save() 156 | elif qs.count() == 1: 157 | payment = qs.last() 158 | else: 159 | # This should not happen because there should never be more than one view payment per article per person 160 | raise Exception("Multiple payments detected") 161 | 162 | # User client requests that we check if the payment has been made 163 | if request.GET.get('check'): 164 | print "Checking for payment {}".format(payment.payment_request) 165 | if payment.check_payment(): 166 | print "Payment succeeded!" 167 | else: 168 | print "Payment not received" 169 | 170 | if payment.status == 'pending_invoice': 171 | payment.generate_invoice(request.user, article) 172 | elif payment.status == 'pending_payment': 173 | # Do nothing; display the payment page to user 174 | pass 175 | elif payment.status == 'complete': 176 | # Do nothing; display the article to user 177 | pass 178 | elif payment.status == 'error': 179 | # TODO Optionally implement some kind of error resolution 180 | pass 181 | raise Exception("Payment error") 182 | else: 183 | context['payment_status'] = payment.status 184 | 185 | context['payment'] = payment 186 | 187 | return render(request, 188 | template_name='article.html', 189 | context=context) 190 | ``` 191 | {% endraw %} 192 | 193 | A quick breakdown of what's going on: 194 | 1. First, we try to find the appropriate `Article` by its id. If successful, we 195 | populate the `context` variable so that the template can work with it. 196 | 2. If the user is not logged in, we can't check for a payment from them because 197 | we don't know who they are, so we just direct them to the article page. 198 | 3. We attempt to find a `Payment` for this particular `User` and `Article`. If 199 | a `Payment` was not found, we generate a new one. The satoshi amount is set 200 | by `settings.MIN_VIEW_AMOUNT`, which defaults to 1000 satoshis. This newly 201 | created `Payment` has the initial state: `pending_invoice`. 202 | 4. If the user provides the `check` query parameter, we call the 203 | `check_payment` function, which will check if the payment was indeed 204 | complete and update the state if so. 205 | 5. If the payment is pending an invoice, we call the `generate_invoice` 206 | function, which will generate the invoice and update the Payment state. 207 | 6. If the payment is in any other state, we render `article.html` for the user 208 | or throw an error. 209 | 210 | ### Adding in a paywall 211 | 212 | Right now, all the articles in the app are freely viewable. We all know no one 213 | likes free stuff, so let's fix that. 214 | 215 | We will begin by adding some conditionals in the html where we are currently 216 | displaying the article content. 217 | 218 | In `coindesk/templates/article.html`, notice the following code: 219 | {% raw %} 220 | ```html 221 |
222 |
223 | {{ article.text }} 224 |
225 |
226 | ``` 227 | {% endraw %} 228 | 229 | {% raw %}`{{ article.text }}`{% endraw %} is the Django template variable 230 | representing the text of the website. We need to hide this for all 231 | non-authenticated users. Let's show them the `pay.html` page instead. And of 232 | course, users who have completed payments must be able to view the article 233 | text. 234 | 235 | Make the necessary edits: 236 | {% raw %} 237 | ```html 238 |
239 | {% if not request.user.is_authenticated %} 240 |

Make Payment

241 |

242 | To view this article, please log in and return to this page to make 243 | a payment. 244 |

245 |
Log in 246 | {% elif payment.status == "complete" %} 247 |
248 | {{ article.text }} 249 |
250 | {% else %} 251 |
252 | {% include "pay.html" %} 253 |
254 | {% endif %} 255 |
256 | ``` 257 | {% endraw %} 258 | 259 | As this is a Lightning tutorial, understanding the exact syntax is not 260 | important, but a quick clarification may be helpful: 261 | - The {% raw %}`{% if %}`{% endraw %} blocks are Django's way of adding 262 | conditionals in html templates. We are using this to determine if users are 263 | logged in or if the payment is complete. 264 | - `payment` is a context variable the template needs populated in order to 265 | render correctly and access the relevant information. This was done in the 266 | `article` view. 267 | - The {% raw %}`{% include %}`{% endraw %} tag adds in the template by the name 268 | of `pay.html`. 269 | 270 | We should now see something like this when we click on an article: 271 | ![logged out article page](http://i.imgur.com/bVc4M06.png) 272 | 273 | ### Generating an invoice 274 | 275 | Examine `coindesk/templates/pay.html`: 276 | {% raw %} 277 | ```html 278 |
279 |
280 |

Make Payment

281 |

To view this article, please pay 1000 satoshis via the request below:

282 |

{{ payment.payment_request }}


283 | Complete 284 |
285 |
286 | ``` 287 | {% endraw %} 288 | 289 | This template prompts the user to pay 1000 satoshis, and supplies a payment 290 | request. 291 | 292 | Log in as Alice. The page should look something like this: 293 | ![logged in article page with payment prompt missing payment 294 | request](http://i.imgur.com/FpyjezK.png) 295 | 296 | We are missing the payment request, so let's generate an invoice. 297 | 298 | Navigate to `generate_invoice` in `coindesk/models.py`. Modify it to the 299 | following: 300 | 301 | {% raw %} 302 | ```python 303 | def generate_invoice(self, user, article): 304 | """ 305 | Generates a new invoice 306 | """ 307 | assert self.status == 'pending_invoice', "Already generated invoice" 308 | channel = grpc.insecure_channel(settings.LND_RPCHOST) 309 | stub = lnrpc.LightningStub(channel) 310 | 311 | add_invoice_resp = stub.AddInvoice(ln.Invoice(amt=settings.MIN_VIEW_AMOUNT, memo="User '{}' | ArticleId {}".format(user.username, article.id))) 312 | r_hash_base64 = codecs.encode(add_invoice_resp.r_hash, 'base64') 313 | self.r_hash = r_hash_base64.decode('utf-8') 314 | self.payment_request = add_invoice_resp.payment_request 315 | self.status = 'pending_payment' 316 | self.save() 317 | ``` 318 | {% endraw %} 319 | 320 | Don't forget also to include the necessary imports at the top of the file: 321 | ```python 322 | from coindesk import rpc_pb2 as ln, rpc_pb2_grpc as lnrpc 323 | import grpc 324 | ``` 325 | 326 | Walking through the code: 327 | - We first check that this `Payment` is indeed pending an invoice, and throw an 328 | error otherwise. 329 | - Using gRPC, we add an invoice of the amount set by `MIN_VIEW_AMOUNT` in 330 | `settings.py`. 331 | - We set the `r_hash` and `payment_request` attributes and update the state of 332 | this `Payment` to now be pending payment. 333 | 334 | 335 | ### Checking for payment receipt 336 | 337 | The last piece needed for our fully functional Lightning Coindesk is to 338 | implement the `check_payment` function of the `Payment` class. Recall from 339 | `coindesk.views.` that `check_payment()` is called if the user passes along the 340 | `check` query parameter. For your convenience, we have already implemented this 341 | for you in the frontend: 342 | 343 | In `coindesk/templates/pay.html`: 344 | ```html 345 | Complete 346 | ``` 347 | 348 | Now, try to implement the `check_payment` function yourself. Here's some 349 | starter code to help you with the annoying and unimportant parts: 350 | 351 | ```python 352 | def check_payment(self): 353 | """ 354 | Checks if the Lightning payment has been received for this invoice 355 | """ 356 | if self.status == 'pending_invoice': 357 | return False 358 | 359 | # Prepare r_hash_bytes, which can be passed into the gRPC client 360 | r_hash_base64 = self.r_hash.encode('utf-8') 361 | r_hash_bytes = str(codecs.decode(r_hash_base64, 'base64')) 362 | 363 | # Implement this 364 | payment_settled = False 365 | 366 | if payment_settled: 367 | # Payment complete 368 | self.status = 'complete' 369 | self.save() 370 | return True 371 | else: 372 | # Payment not received 373 | return False 374 | ``` 375 | 376 | If you're absolutely stuck, you may refer to the [tutorial 377 | repo](https://github.com/MaxFangX/lightning-coindesk) for the final solution. 378 | 379 | ### Conclusion 380 | 381 | Congratulations! You have now built a working Lightning Coindesk app! If you 382 | are looking to take this tutorial to the next level, consider trying one or 383 | more of the following: 384 | 385 | - Integrate error handling in the webapp; see the TODO in 386 | `coindesk.views.article` 387 | - Add P2P payments through the app. Instead of paying the central server, 388 | distribute your micropayment equally between all the people who upvoted 389 | before you. The upvote functionality was intentionally left unimplemented for 390 | this purpose. 391 | - Run this application in a more "production" environment, by using `testnet` 392 | and deploying your webapp online 393 | - Allow the server to accept Litecoin in addition to Bitcoin. 394 | 395 | At this point, you're ready to build with `lnd`. Go forth and bring 396 | Bitcoin to the masses! 397 | 398 | #### Next Steps 399 | 400 | Read through the [LND Overview and Developer Guide](/overview/) to see best 401 | practices and guidelines for implementing LND in your own webapp, or for a 402 | conceptual brushup of the Lightning Network. 403 | 404 | Check out the accessible dev manuals available on our [Guides page](/guides/). 405 | 406 | #### Navigation 407 | - [Return to Stage 3 - RPC Client](/tutorial/03-rpc-client) 408 | - [Return to main tutorial page](/tutorial/) 409 | 410 | ### Questions 411 | - Join the #dev-help channel on our [Community 412 | Slack](https://join.slack.com/t/lightningcommunity/shared_invite/enQtMzQ0OTQyNjE5NjU1LWRiMGNmOTZiNzU0MTVmYzc1ZGFkZTUyNzUwOGJjMjYwNWRkNWQzZWE3MTkwZjdjZGE5ZGNiNGVkMzI2MDU4ZTE) 413 | - Join IRC: 414 | [![Irc](https://img.shields.io/badge/chat-on%20freenode-brightgreen.svg)](https://webchat.freenode.net/?channels=lnd) 415 | -------------------------------------------------------------------------------- /tutorial/index.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: page 3 | title: Tutorial 4 | --- 5 | 6 | ### Overview 7 | 8 | This tutorial will get you up to speed with all the skills necessary to work 9 | with [`lnd`](https://github.com/lightningnetwork/lnd). We will be building a 10 | Bitcoin micropayments paywall into a news site! 11 | 12 | Those seeking more conceptual familiarity with the Lightning Network can read 13 | through the [LND Overview and Developer Guide](/overview/). It also contains a 14 | more in-depth explanation of the components covered in this tutorial, and 15 | includes best practices for integrating LND. It is not required knowledge for 16 | completing this tutorial, but we recommend that you at least skim through the 17 | guide before attempting to build your own app. 18 | 19 | The tutorial assumes you have completed installation of Go, `btcd`, and `lnd` 20 | on simnet. If not, the [installation instructions](/guides/installation/) will 21 | guide you through the process. 22 | 23 | ### Stages 24 | 25 | Each of the different stages of this tutorial is oriented towards a specific 26 | skill. Beginners should start at [stage 1](/tutorial/01-lncli). Otherwise, jump 27 | wherever you want below! 28 | 29 | - **[Stage 1 - Setting up a local cluster](/tutorial/01-lncli)** 30 | - How to set up a local environment with three nodes that can make payments 31 | with and through one another. 32 | - Gain experience interacting with `lnd` from the command line. 33 | - **[Stage 2 - Web Client](/tutorial/02-web-client)** 34 | - How to run and use a `lnd` web GUI. 35 | - **[Stage 3 - RPC Client](/tutorial/03-rpc-client)** 36 | - How to set up and interact with `lnd` from an RPC client, specifically 37 | `gRPC`. 38 | - Exposure to `lnrpc` documentation 39 | - Set up web development workspace 40 | - **[Stage 4 - Webapp Integration](/tutorial/04-webapp-integration)** 41 | - Adding a micropayments paywall 42 | - Recommended next steps 43 | -------------------------------------------------------------------------------- /update_and_render.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Fetch the latest installation docs 4 | curl -o INSTALL.md -s https://raw.githubusercontent.com/lightningnetwork/lnd/master/docs/INSTALL.md 5 | # cp ~/lightning/ln-lnd/src/github.com/lightningnetwork/lnd/docs/INSTALL.md . 6 | 7 | # Fetch the latest Docker guide 8 | curl -o DOCKER-README.md -s https://raw.githubusercontent.com/lightningnetwork/lnd/master/docker/README.md 9 | # cp ~/lightning/ln-lnd/src/github.com/lightningnetwork/lnd/docker/README.md DOCKER-README.md 10 | 11 | # Fetch the latest RPC docs 12 | curl -o python.md -s https://raw.githubusercontent.com/lightningnetwork/lnd/master/docs/grpc/python.md 13 | # cp ~/lightning/ln-lnd/src/github.com/lightningnetwork/lnd/docs/grpc/python.md . 14 | 15 | curl -o javascript.md -s https://raw.githubusercontent.com/lightningnetwork/lnd/master/docs/grpc/javascript.md 16 | # cp ~/lightning/ln-lnd/src/github.com/lightningnetwork/lnd/docs/grpc/javascript.md . 17 | 18 | # Render docs 19 | ./render.py 20 | 21 | # Clean up 22 | rm INSTALL.md 23 | rm python.md 24 | rm javascript.md 25 | rm DOCKER-README.md 26 | --------------------------------------------------------------------------------