Merge pull request #144 from javiervargas/master

13_0_Understanding_Your_Lightning_Setup.md
This commit is contained in:
Shannon Appelcline 2020-08-18 11:55:58 -10:00 committed by GitHub
commit d76e5af67a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 1527 additions and 0 deletions

View File

@ -0,0 +1,34 @@
# Chapter Eighteen: Understanding Your Lighting Setup
> :information_source: **NOTE:** This is a draft in progress, so that I can get some feedback from early reviewers. It is not yet ready for learning.
In this chapter you'll be ready to begin working with the `lightning-cli` command-line interface. But that first requires that you understand your c-lightning setup and its features, which is what will be explained with some examples and basic configuration.
For this and future chapters, we presume that you have a VPS with c-lightning installed, running `lightningd` courtersy of [Bitcoin Standup Scripts](https://github.com/BlockchainCommons/Bitcoin-Standup-Scripts).
We also presume that you are connected to testnet, allowing for access to bitcoins without using real funds. You can either do this by hand, per [§2.1: Setting up a Bitcoin-Core VPS by Hand](02_1_Setting_Up_a_Bitcoin-Core_VPS_by_Hand.md), with Bitcoin Standup at Linode.com, per [§2.2: Setting up a Bitcoin-Core VPS with Bitcoin Standup](02_2_Setting_Up_a_Bitcoin-Core_VPS_with_StackScript.md), or via other means, per [§2.3: Setting up a Bitcoin-Core Machine via Other Means](02_3_Setting_Up_Bitcoin_Core_Other.md).
## Objectives for This Chapter
After working through this chapter, a developer will be able to:
* Demonstrate that their c-lightning Node is Installed and Up-to-date
* Use basic wallet Commands
* Setting up a channel.
* Pay an invoice
* Generate a payment request.
Supporting objectives include the ability to:
* Use Basic Informational Commands.
* Understand what a lightning channel is.
* Understand what a invoice is.
* Understand how to pay an invoice.
## Table of Contents
* [Section One: Verifying Your Lightning Setup](18_1_Verifying_Your_Lightning_Setup.md)
* [Section Two: Knowing Your Lightning Setup](18_2_Knowing_Your_lightning_Setup.md)
* [Section Three: Setting Up a channel](18_3_Setting_Up_a_Channel.md)
* [Section Four: Generate a payment request](19_1_Generate_a_Payment_Request.md)
* [Section Five: Paying an invoice](19_2_Paying_a_Invoice.md)
* [Section Five: Closing a Channel](19_3_Closing_a_Channel.md)

View File

@ -0,0 +1,373 @@
# 18.1: Verifying Your Lightning Setup
> :information_source: **NOTE:** This is a draft in progress, so that I can get some feedback from early reviewers. It is not yet ready for learning.
> :book: ***What is Lightning Network?***
Lightning Network is a decentralized network using smart contract functionality in the bitcoin blockchain to enable instant payments across a network of participants. Lightning is builded like a layer-2 protocol that interacts with Bitcoin to allow users to exchange their bitcoins "off-chain".
This tutorial uses the standard-compliant c-lightning implementation as its trusted Lightning server. Before you start playing with c-lightning, you should ensure that everything is setup correctly.
## C-lightning installation
As we said previous chapter you should have c-lightning installed courtesy BitcoinStandupScript, if not we describe here options and steps to install it.
### Ubuntu ppa
The first and fastest option is to use [Ubuntu ppa](https://launchpad.net/~lightningnetwork/+archive/ubuntu/ppa).
```
sudo apt-get install -y software-properties-common
sudo add-apt-repository -u ppa:lightningnetwork/ppa
sudo apt-get install lightningd
```
### Install pre-compiled binaries
Download and install binaries from [c-lightning](https://github.com/ElementsProject/lightning/releases) github repository.
### Compiling the source code
In this section we'll show you steps to compile c-lightning source code and running it.
* Get dependencies
```
c$ sudo apt-get install -y \
> autoconf automake build-essential git libtool libgmp-dev \
> libsqlite3-dev python3 python3-mako net-tools zlib1g-dev libsodium-dev \
> gettext
```
Output:
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
build-essential is already the newest version (12.1ubuntu2).
net-tools is already the newest version (1.60-26ubuntu1).
python3 is already the newest version (3.5.1-3).
python3-mako is already the newest version (1.0.3+ds1-1ubuntu1).
gettext is already the newest version (0.19.7-2ubuntu3.1).
The following packages were automatically installed and are no longer required:
glade2script glade2script-python3 pastebinit snapd-login-service
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
autotools-dev git-man liberror-perl libgmpxx4ldbl libltdl-dev m4
.......
```
* Clone repository
```
c$ git clone https://github.com/ElementsProject/lightning.git
c$ cd lightning
```
* Get additional dependencies for development or testing.
```
c$ sudo apt-get install -y valgrind python3-pip libpq-dev
```
Output:
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
glade2script glade2script-python3 pastebinit snapd-login-service
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
comerr-dev krb5-multidev libexpat1-dev libgssrpc4 libkadm5clnt-mit9 libkadm5srv-mit9 libkdb5-8 libpq5 libpython3-dev libpython3.5-dev libssl-dev libssl-doc
python-pip-whl python3-dev python3-setuptools python3-wheel python3.5-dev
Suggested packages:
krb5-doc krb5-user postgresql-doc-9.5 python-setuptools-doc valgrind-dbg kcachegrind alleyoop valkyrie
The following NEW packages will be installed:
comerr-dev krb5-multidev libexpat1-dev libgssrpc4 libkadm5clnt-mit9 libkadm5srv-mit9 libkdb5-8 libpq-dev libpq5 libpython3-dev libpython3.5-dev libssl-dev libssl-doc
python-pip-whl python3-dev python3-pip python3-setuptools python3-wheel python3.5-dev valgrind
0 upgraded, 20 newly installed, 0 to remove and 0 not upgraded.
Need to get 53,4 MB of archives.
After this operation, 137 MB of additional disk space will be used.
Get:1 http://es.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libgssrpc4 amd64 1.13.2+dfsg-5ubuntu2.1 [54,5 kB]
Get:2 http://es.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libkdb5-8 amd64 1.13.2+dfsg-5ubuntu2.1 [37,0 kB]
Get:3 http://es.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libkadm5srv-mit9 amd64 1.13.2+dfsg-5ubuntu2.1 [51,3 kB]
.......
```
* Install requirements
```
c$ pip3 install -r requirements.txt
```
Output
```
Collecting Flask==1.1.1 (from -r requirements.txt (line 1))
Downloading https://files.pythonhosted.org/packages/9b/93/628509b8d5dc749656a9641f4caf13540e2cdec85276964ff8f43bbb1d3b/Flask-1.1.1-py2.py3-none-any.whl (94kB)
100% |████████████████████████████████| 102kB 1.8MB/s
Collecting Sphinx==1.8.4 (from -r requirements.txt (line 2))
Downloading https://files.pythonhosted.org/packages/75/25/905f901fb749e45cb201f1d946e82f59d84730c430287ea7980b0bcbd2dc/Sphinx-1.8.4-py2.py3-none-any.whl (3.1MB)
100% |████████████████████████████████| 3.1MB 372kB/s
......
Running setup.py install for mako ... done
Running setup.py install for mistune-contrib ... done
Running setup.py install for py-cpuinfo ... done
Successfully installed Flask-1.1.1 Jinja2-2.11.2 Pygments-2.6.1 Sphinx-1.8.4 Werkzeug-1.0.1 alabaster-0.7.12 apipkg-1.5 attrs-19.3.0 babel-2.8.0 cheroot-8.2.1 click-7.1.2 commonmark-0.8.1 docutils-0.16 entrypoints-0.3 ephemeral-port-reserve-1.1.1 execnet-1.7.1 flake8-3.7.8 flaky-3.6.1 future-0.18.2 imagesize-1.2.0 importlib-metadata-1.7.0 itsdangerous-1.1.0 jaraco.functools-3.0.1 m2r-0.2.1 mako-1.0.14 mccabe-0.6.1 mistune-0.8.4 mistune-contrib-0.1 more-itertools-8.4.0 mrkd-0.1.6 packaging-20.4 pathlib2-2.3.5 plac-1.2.0 pluggy-0.13.1 psycopg2-binary-2.8.4 py-1.9.0 py-cpuinfo-7.0.0 pycodestyle-2.5.0 pyflakes-2.1.1 pytest-5.3.1 pytest-benchmark-3.2.2 pytest-forked-1.0.2 pytest-timeout-1.3.3 pytest-xdist-1.29.0 python-bitcoinlib-0.10.2 pytz-2020.1 recommonmark-0.5.0 snowballstemmer-2.0.0 sphinx-rtd-theme-0.4.2 sphinxcontrib-websupport-1.1.0 tqdm-4.32.2 wcwidth-0.2.5 zipp-3.1.0
You are using pip version 8.1.1, however version 20.1.1 is available.
```
* Build lightning
```
c$ ./configure
```
Output:
```
Compiling ccan/tools/configurator/configurator...done
checking for python3-mako... found
Making autoconf users comfortable... yes
checking for off_t is 32 bits... no
checking for __alignof__ support... yes
checking for asprintf() declaration... yes
checking for __attribute__((cold)) support... yes
checking for __attribute__((const)) support... yes
checking for __attribute__((deprecated)) support... no
checking for __attribute__((nonnull)) support... yes
checking for __attribute__((sentinel)) support... yes
checking for __attribute__((pure)) support... yes
checking for __attribute__((may_alias)) support... yes
checking for __attribute__((noreturn)) support... yes
checking for __attribute__ format printf support... yes
.......
Setting COMPAT... 1
Setting PYTEST... pytest
Setting STATIC... 0
Setting ASAN... 0
Setting TEST_NETWORK... regtest
c$
```
* Make
It will take some time depending your machine.
```
c$ make
```
Output:
```
CC: cc -DBINTOPKGLIBEXECDIR="../libexec/c-lightning" -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations -Wstrict-prototypes -Wold-style-definition -Werror -Wno-maybe-uninitialized -std=gnu11 -g -fstack-protector -Og -I ccan -I external/libwally-core/include/ -I external/libwally-core/src/secp256k1/include/ -I external/jsmn/ -I external/libbacktrace/ -I external/x86_64-linux-gnu/libbacktrace-build -I external/libsodium/src/libsodium/include -I external/libsodium/src/libsodium/include/sodium -I external/x86_64-linux-gnu/libsodium-build/src/libsodium/include -I . -I/usr/local/include -DSHACHAIN_BITS=48 -DJSMN_PARENT_LINKS -DCOMPAT_V052=1 -DCOMPAT_V060=1 -DCOMPAT_V061=1 -DCOMPAT_V062=1 -DCOMPAT_V070=1 -DCOMPAT_V072=1 -DCOMPAT_V073=1 -DCOMPAT_V080=1 -DCOMPAT_V081=1 -DCOMPAT_V082=1 -DCOMPAT_V090=1 -DBUILD_ELEMENTS=1 -c -o
LD: cc -Og -Lexternal/x86_64-linux-gnu -lwallycore -lsecp256k1 -ljsmn -lbacktrace -lsodium -L/usr/local/lib -lm -lgmp -lsqlite3 -lz -lpq -o
cc ccan/ccan/cdump/tools/cdump-enumstr.c
cc ccan/ccan/cdump/cdump.c
cc ccan/ccan/strmap/strmap.c
cc ccan/ccan/asort/asort.c
cc ccan/ccan/autodata/autodata.c
cc ccan/ccan/bitmap/bitmap.c
cc ccan/ccan/bitops/bitops.c
cc ccan/ccan/breakpoint/breakpoint.c
cc ccan/ccan/crc32c/crc32c.c
cc ccan/ccan/crypto/hmac_sha256/hmac_sha256.c
cc ccan/ccan/crypto/hkdf_sha256/hkdf_sha256.c
......
cc common/channel_id.c
cc common/daemon.c
cc common/daemon_conn.c
cc common/derive_basepoints.c
cc common/funding_tx.c
tools/generate-wire.py --page impl common/gen_status_wire.h status < common/status_wire.csv > common/gen_status_wire.c
cc common/gen_status_wire.c
cc common/hash_u5.c
cc common/key_derive.c
cc common/memleak.c
cc common/msg_queue.c
cc common/node_id.c
cc common/permute_tx.c
cc common/setup.c
cc common/status.c
cc common/status_wire.c
cc common/subdaemon.c
cc common/type_to_string.c
cc common/utils.c
cc common/utxo.c
cc common/version.c
cc common/withdraw_tx.c
cc bitcoin/base58.c
cc bitcoin/block.c
cc bitcoin/chainparams.c
cc bitcoin/feerate.c
cc bitcoin/locktime.c
cc bitcoin/preimage.c
cc bitcoin/privkey.c
cc bitcoin/psbt.c
cc bitcoin/pubkey.c
cc bitcoin/script.c
cc bitcoin/shadouble.c
cc bitcoin/short_channel_id.c
cc bitcoin/signature.c
cc bitcoin/tx.c
cc bitcoin/tx_parts.c
cc bitcoin/varint.c
cc wire/wire_sync.c
.......
cc lightningd/test/run-invoice-select-inchan.c
ld lightningd/test/run-invoice-select-inchan
cc lightningd/test/run-jsonrpc.c
ld lightningd/test/run-jsonrpc
cc cli/test/run-remove-hint.c
ld cli/test/run-remove-hint
cc cli/test/run-large-input.c
ld cli/test/run-large-input
if [ x"`git log doc/lightningd-config.5 | head -n1`" != x"`git log doc/lightningd-config.5.md | head -n1`" -o x"`git diff doc/lightningd-config.5.md`" != x"" ]; then mrkd doc/lightningd-config.5.md doc/lightningd-config.5; else touch doc/lightningd-config.5; fi
if [ x"`git log doc/lightning-hsmtool.8 | head -n1`" != x"`git log doc/lightning-hsmtool.8.md | head -n1`" -o x"`git diff doc/lightning-hsmtool.8.md`" != x"" ]; then mrkd doc/lightning-hsmtool.8.md doc/lightning-hsmtool.8; else touch doc/lightning-hsmtool.8; fi
(grep -v '^ lightning.*\.[0-9]\.md>$' doc/index.rst; for m in $(cd doc && ls lightningd*.[0-9].md lightning-*.[0-9].md); do echo " ${m%.[0-9].md} <$m>"; done |LC_ALL=C sort) > doc/index.rst.tmp.$$ && mv doc/index.rst.tmp.$$ doc/index.rst
rm external/x86_64-linux-gnu/libwally-core-build/src/secp256k1/libsecp256k1.la
c$
```
* Make Install
```
$ sudo make install
```
Output:
```
mkdir -p /usr/local/bin
mkdir -p /usr/local/libexec/c-lightning
mkdir -p /usr/local/libexec/c-lightning/plugins
mkdir -p /usr/local/share/man/man1
mkdir -p /usr/local/share/man/man5
mkdir -p /usr/local/share/man/man7
mkdir -p /usr/local/share/man/man8
mkdir -p /usr/local/share/doc/c-lightning
cp tools/hsmtool tools/lightning-hsmtool
install cli/lightning-cli lightningd/lightningd tools/lightning-hsmtool /usr/local/bin
install lightningd/lightning_channeld lightningd/lightning_closingd lightningd/lightning_connectd lightningd/lightning_gossipd lightningd/lightning_hsmd lightningd/lightning_onchaind lightningd/lightning_openingd /usr/local/libexec/c-lightning
[ -z "plugins/autoclean plugins/bcli plugins/fundchannel plugins/keysend plugins/pay" ] || install plugins/autoclean plugins/bcli plugins/fundchannel plugins/keysend plugins/pay /usr/local/libexec/c-lightning/plugins
install -m 644 doc/lightning-cli.1 /usr/local/share/man/man1
install -m 644 doc/lightningd-config.5 /usr/local/share/man/man5
install -m 644 doc/lightning-autocleaninvoice.7 doc/lightning-check.7 doc/lightning-checkmessage.7 doc/lightning-close.7 doc/lightning-connect.7 doc/lightning-createonion.7 doc/lightning-decodepay.7 doc/lightning-delexpiredinvoice.7 doc/lightning-delinvoice.7 doc/lightning-dev-sendcustommsg.7 doc/lightning-disconnect.7 doc/lightning-fundchannel.7 doc/lightning-fundchannel_start.7 doc/lightning-fundchannel_complete.7 doc/lightning-fundchannel_cancel.7 doc/lightning-getroute.7 doc/lightning-getsharedsecret.7 doc/lightning-invoice.7 doc/lightning-listchannels.7 doc/lightning-listforwards.7 doc/lightning-listfunds.7 doc/lightning-listinvoices.7 doc/lightning-listpays.7 doc/lightning-listpeers.7 doc/lightning-listsendpays.7 doc/lightning-newaddr.7 doc/lightning-pay.7 doc/lightning-plugin.7 doc/lightning-reserveinputs.7 doc/lightning-sendonion.7 doc/lightning-sendpay.7 doc/lightning-setchannelfee.7 doc/lightning-signmessage.7 doc/lightning-txprepare.7 doc/lightning-txdiscard.7 doc/lightning-txsend.7 doc/lightning-unreserveinputs.7 doc/lightning-waitinvoice.7 doc/lightning-waitanyinvoice.7 doc/lightning-waitblockheight.7 doc/lightning-waitsendpay.7 doc/lightning-withdraw.7 /usr/local/share/man/man7
install -m 644 doc/lightningd.8 doc/lightning-hsmtool.8 /usr/local/share/man/man8
install -m 644 README.md doc/INSTALL.md doc/HACKING.md LICENSE /usr/local/share/doc/c-lightning
```
You can check your installation using
```
c$ lightningd --help
```
Output:
```
lightningd: WARNING: default network changing in 2020: please set network=testnet in config!
Usage: lightningd
A bitcoin lightning daemon (default values shown for network: testnet).
--conf=<file> Specify configuration file
--lightning-dir=<dir> Set base directory: network-specific
subdirectory is under here
(default: "/home/javier/.lightning")
--network <arg> Select the network parameters (bitcoin,
testnet, regtest, litecoin or
litecoin-testnet) (default: testnet)
--testnet Alias for --network=testnet
--signet Alias for --network=signet
--mainnet Alias for --network=bitcoin
```
## Create Your Aliases
We suggest creating some aliases to make it easier to use c-lightning.
You can do so by putting them in your `.bash_profile`.
```
cat >> ~/.bash_profile <<EOF
alias lndir="cd ~/.lightning/" #linux default c-lightning path
alias lnc="lightning-cli"
alias lnd="lightningd"
alias lninfo='lightning-cli getinfo'
EOF
```
After you enter these aliases you can either `source .bash_profile` to input them or just log out and back in.
Note that these aliases includes shortcuts for running `lightning-cli`, for running `lightningd`, and for going to the c-lightning directory. These aliases are mainly meant to make your life easier. We suggest you create other aliases to ease your use of frequent commands (and arguments) and to minimize errors. Aliases of this sort can be even more useful if you have a complex setup where you regularly run commands associated with Mainnet, with Testnet, _and_ with Regtest, as explained further below.
With that said, use of these aliases in _this_ document might accidentally obscure the core lessons being taught about c-lightning, so the only alias directly used here is `lninfo` because it encapsulatea much longer and more complex command. Otherwise, we show the full commands; adjust for your own use as appropriate.
## Run lightningd
You'll begin your exploration of the Lightning network with the `lightning-cli` command. However, lightningd _must_ be running to use lightning-cli, as lightning-cli sends JSON-RPC commands to the lightningd. If you used our standard setup, lightningd should already be up and running. You can double check by looking at the process table.
```
$ ps auxww | grep lightningd
standup 7817 1.1 0.2 95280 8964 pts/18 D+ 14:13 0:00 lightningd --network=testnet
```
If it's not running, you'll want to run `lightningd --network=testnet` by hand.
## Verify your node
You should have an output like this indicating your node is ready if blockheight shows a height value that match with your most recent number getblockcount `bitcoin-cli getblockcount` command output.
```
$ lightning-cli --network=testnet getinfo
{
"id": "03fce2a20393a65b9d6cab5425f4cd33ddc621ade458efd69d652917e2b5eaf59c",
"alias": "VIOLENTIRON",
"color": "03fce2",
"num_peers": 0,
"num_pending_channels": 0,
"num_active_channels": 0,
"num_inactive_channels": 0,
"address": [],
"binding": [
{
"type": "ipv6",
"address": "::",
"port": 9735
},
{
"type": "ipv4",
"address": "0.0.0.0",
"port": 9735
}
],
"version": "v0.8.2-398-g869fa08",
"blockheight": 54959,
"network": "testnet",
"msatoshi_fees_collected": 0,
"fees_collected_msat": "0msat",
"lightning-dir": "/home/user/.lightning/testnet"
}
```
If node is still sycing with bitcoin network you should see a message like this.
```
"warning_bitcoind_sync": "Bitcoind is not up-to-date with network."
```
If your lightning daemon is not up-to-date, you'll get a message to you `getinfo command` like this:
```
"warning_lightningd_sync": "Still loading latest blocks from bitcoind."
```
## Optional: Know Your Server Types
> **TESTNET vs MAINNET:** When you set up your node, you choose to create it as either a Mainnet, Testnet, or Regtest node. Though this document presumes a testnet setup, it's worth understanding how you might access and use the other setup types — even all on the same machine! But, if you're a first-time user, skip on past this, as it's not necessary for a basic setup.
When lightningd starts up it usually reads a general configuration file located depending on the network you are using (default: $HOME/.lightning/testnet/config). This can be changed: see conf and lightning-dir.
The type of setup is mainly controlled through the ~/.lightning/config file. If you're running testnet, it probably will be located in ~/.lightning/testnet/config. In next section we will explain how to manage your lightning daemon options or general options.
```
~/.lightning/testnet$ ls -la config
-rw-rw-r-- 1 user user 267 jul 12 17:08 config
:~/.lightning/testnet$
```
If you want to run several different sorts of nodes simultaneously, you must leave the testnet (or regtest) flag out of your configuration file. You should then choose whether you're using the mainnet, the testnet, or your regtest every time you run lightningd or lightning-cli.
## Summary: Verifying your Lightning setup
Before you start playing with lightning, you should make sure that your aliases are set up, your lightningd is running, and your node is synced. You may also want to set up some access to alternative lightning setups, if you're an advanced user.
## What's Next?
Continue "Understanding Your Lightning Setup" with [§18.2: Knowing Your Lightning Setup](18_2_Knowing_Your_lightning_Setup.md).

View File

@ -0,0 +1,330 @@
# 18.2: Knowing Your Lightning Setup
> :information_source: **NOTE:** This is a draft in progress, so that I can get some feedback from early reviewers. It is not yet ready for learning.
Before you start playing with Lightning Network, you may always want to come to a better understanding of your setup.
## Know Your c-lightning Directory
To start with, you should understand where everything is kept: the `~/.lightning` directory.
The main directory just contains as many networks as configured, in this case we have testnet directory.
```
c$ ls ~/.lightning
testnet
```
In your ~/.lightning/testnet directory, you'll find that contains all of the guts:
```
c$ ls ~/.lightning/testnet3
config gossip_store hsm_secret lightningd.sqlite3 lightningd.sqlite3-journal lightning-rpc
```
> :link: **TESTNET vs MAINNET:** If you're using mainnet, then _everything_ will instead be placed in the main `~/.lightning/bitcoin` directory. These various setups _do_ elegantly stack, so if you are using mainnet, testnet, and regtest, you'll find that `~/.lightning/bitcoin` contains your config file and your mainnet data, the `~/.lightning/testnet` directory contains your testnet data, and the `~/.lightning/regtest` directory contains your regtest data.
## Know Your lightning-cli Commands
Most of your early work will be done with the `lightning-cli` command, which offers an easy interface to `lightningd`.
```
c$ lightning-cli help
lightning-cli: WARNING: default network changing in 2020: please set network=testnet in config!
=== bitcoin ===
feerates style
Return feerate estimates, either satoshi-per-kw ({style} perkw) or satoshi-per-kb ({style} perkb).
newaddr [addresstype]
Get a new {bech32, p2sh-segwit} (or all) address to fund a channel (default is bech32)
reserveinputs outputs [feerate] [minconf] [utxos]
Reserve inputs and pass back the resulting psbt
sendpsbt psbt
Finalize, extract and send a PSBT.
signpsbt psbt
Sign this wallet's inputs on a provided PSBT.
txdiscard txid
Abandon a transaction created by txprepare
txprepare outputs [feerate] [minconf] [utxos]
Create a transaction, with option to spend in future (either txsend and txdiscard)
txsend txid
Sign and broadcast a transaction created by txprepare
unreserveinputs psbt
Unreserve inputs, freeing them up to be reused
withdraw destination satoshi [feerate] [minconf] [utxos]
Send to {destination} address {satoshi} (or 'all') amount via Bitcoin transaction, at optional {feerate}
=== channels ===
close id [unilateraltimeout] [destination] [fee_negotiation_step]
Close the channel with {id} (either peer ID, channel ID, or short channel ID). Force a unilateral close after {unilateraltimeout} seconds (default 48h). If {destination} address is provided, will be used as output address.
fundchannel_cancel id
Cancel inflight channel establishment with peer {id}.
fundchannel_complete id txid txout
Complete channel establishment with peer {id} for funding transactionwith {txid}. Returns true on success, false otherwise.
fundchannel_start id amount [feerate] [announce] [close_to] [push_msat]
Start fund channel with {id} using {amount} satoshis. Returns a bech32 address to use as an output for a funding transaction.
getroute id msatoshi riskfactor [cltv] [fromid] [fuzzpercent] [exclude] [maxhops]
Show route to {id} for {msatoshi}, using {riskfactor} and optional {cltv} (default 9). If specified search from {fromid} otherwise use this node as source. Randomize the route with up to {fuzzpercent} (default 5.0). {exclude} an array of short-channel-id/direction (e.g. [ '564334x877x1/0', '564195x1292x0/1' ]) or node-id from consideration. Set the {maxhops} the route can take (default 20).
listchannels [short_channel_id] [source]
Show channel {short_channel_id} or {source} (or all known channels, if not specified)
listforwards
List all forwarded payments and their information
setchannelfee id [base] [ppm]
Sets specific routing fees for channel with {id} (either peer ID, channel ID, short channel ID or 'all'). Routing fees are defined by a fixed {base} (msat) and a {ppm} (proportional per millionth) value. If values for {base} or {ppm} are left out, defaults will be used. {base} can also be defined in other units, for example '1sat'. If {id} is 'all', the fees will be applied for all channels.
=== network ===
connect id [host] [port]
Connect to {id} at {host} (which can end in ':port' if not default). {id} can also be of the form id@host
disconnect id [force]
Disconnect from {id} that has previously been connected to using connect; with {force} set, even if it has a current channel
listnodes [id]
Show node {id} (or all, if no {id}), in our local network view
listpeers [id] [level]
Show current peers, if {level} is set, include logs for {id}
ping id [len] [pongbytes]
Send peer {id} a ping of length {len} (default 128) asking for {pongbytes} (default 128)
=== payment ===
createonion hops assocdata [session_key]
Create an onion going through the provided nodes, each with its own payload
decodepay bolt11 [description]
Decode {bolt11}, using {description} if necessary
delexpiredinvoice [maxexpirytime]
Delete all expired invoices that expired as of given {maxexpirytime} (a UNIX epoch time), or all expired invoices if not specified
delinvoice label status
Delete unpaid invoice {label} with {status}
invoice msatoshi label description [expiry] [fallbacks] [preimage] [exposeprivatechannels]
Create an invoice for {msatoshi} with {label} and {description} with optional {expiry} seconds (default 1 week), optional {fallbacks} address list(default empty list) and optional {preimage} (default autogenerated)
listinvoices [label]
Show invoice {label} (or all, if no {label})
listsendpays [bolt11] [payment_hash]
Show sendpay, old and current, optionally limiting to {bolt11} or {payment_hash}.
listtransactions
List transactions that we stored in the wallet
sendonion onion first_hop payment_hash [label] [shared_secrets] [partid]
Send a payment with a pre-computed onion.
sendpay route payment_hash [label] [msatoshi] [bolt11] [payment_secret] [partid]
Send along {route} in return for preimage of {payment_hash}
waitanyinvoice [lastpay_index] [timeout]
Wait for the next invoice to be paid, after {lastpay_index} (if supplied). If {timeout} seconds is reached while waiting, fail with an error.
waitinvoice label
Wait for an incoming payment matching the invoice with {label}, or if the invoice expires
waitsendpay payment_hash [timeout] [partid]
Wait for payment attempt on {payment_hash} to succeed or fail, but only up to {timeout} seconds.
=== plugin ===
autocleaninvoice [cycle_seconds] [expired_by]
Set up autoclean of expired invoices.
estimatefees
Get the urgent, normal and slow Bitcoin feerates as sat/kVB.
fundchannel id amount [feerate] [announce] [minconf] [utxos] [push_msat]
Fund channel with {id} using {amount} (or 'all'), at optional {feerate}. Only use outputs that have {minconf} confirmations.
getchaininfo
Get the chain id, the header count, the block count, and whether this is IBD.
getrawblockbyheight height
Get the bitcoin block at a given height
getutxout txid vout
Get informations about an output, identified by a {txid} an a {vout}
listpays [bolt11]
List result of payment {bolt11}, or all
pay bolt11 [msatoshi] [label] [riskfactor] [maxfeepercent] [retry_for] [maxdelay] [exemptfee]
Send payment specified by {bolt11} with {amount}
paystatus [bolt11]
Detail status of attempts to pay {bolt11}, or all
plugin subcommand=start|stop|startdir|rescan|list
Control plugins (start, stop, startdir, rescan, list)
sendrawtransaction tx
Send a raw transaction to the Bitcoin network.
=== utility ===
check command_to_check
Don't run {command_to_check}, just verify parameters.
checkmessage message zbase [pubkey]
Verify a digital signature {zbase} of {message} signed with {pubkey}
getinfo
Show information about this node
getlog [level]
Show logs, with optional log {level} (info|unusual|debug|io)
getsharedsecret point
Compute the hash of the Elliptic Curve Diffie Hellman shared secret point from this node private key and an input {point}.
help [command]
List available commands, or give verbose help on one {command}.
listconfigs [config]
List all configuration options, or with [config], just that one.
listfunds
Show available funds from the internal wallet
signmessage message
Create a digital signature of {message}
stop
Shut down the lightningd process
waitblockheight blockheight [timeout]
Wait for the blockchain to reach {blockheight}, up to {timeout} seconds.
=== developer ===
dev-listaddrs [bip32_max_index]
Show addresses list up to derivation {index} (default is the last bip32 index)
dev-rescan-outputs
Synchronize the state of our funds with bitcoind
---
run `lightning-cli help <command>` for more information on a specific command
```
## Optional: Know your lightning lnfo
A variety of lightning-cli commands can give you additional information on your lightning node. The most general ones are:
```
c$ lightning-cli listconfigs
c$ lightning-cli listfunds
c$ lightning-cli listtransactions
c$ lightning-cli listinvoices
c$ lightning-cli listnodes
```
For example `lightning-cli listconfigs` gives you a variety of information on your setup:
```
c$ lightning-cli --network=testnet listconfigs
{
"# version": "v0.8.2-398-g869fa08",
"lightning-dir": "/home/user/.lightning",
"network": "testnet",
"allow-deprecated-apis": true,
"rpc-file": "lightning-rpc",
"plugin": "/usr/local/bin/../libexec/c-lightning/plugins/fundchannel",
"plugin": "/usr/local/bin/../libexec/c-lightning/plugins/autoclean",
"plugin": "/usr/local/bin/../libexec/c-lightning/plugins/bcli",
"plugin": "/usr/local/bin/../libexec/c-lightning/plugins/pay",
"plugin": "/usr/local/bin/../libexec/c-lightning/plugins/keysend",
"plugins": [
{
"path": "/usr/local/bin/../libexec/c-lightning/plugins/fundchannel",
"name": "fundchannel"
},
{
"path": "/usr/local/bin/../libexec/c-lightning/plugins/autoclean",
"name": "autoclean",
"options": {
"autocleaninvoice-cycle": null,
"autocleaninvoice-expired-by": null
}
},
{
"path": "/usr/local/bin/../libexec/c-lightning/plugins/bcli",
"name": "bcli",
"options": {
"bitcoin-datadir": null,
"bitcoin-cli": null,
"bitcoin-rpcuser": null,
"bitcoin-rpcpassword": null,
"bitcoin-rpcconnect": null,
"bitcoin-rpcport": null,
"bitcoin-retry-timeout": null,
"commit-fee": "500"
}
},
{
"path": "/usr/local/bin/../libexec/c-lightning/plugins/pay",
"name": "pay"
},
{
"path": "/usr/local/bin/../libexec/c-lightning/plugins/keysend",
"name": "keysend"
}
],
"disable-plugin": [],
"always-use-proxy": false,
"daemon": "false",
"wallet": "sqlite3:///home/user/.lightning/testnet/lightningd.sqlite3",
"wumbo": false,
"wumbo": false,
"rgb": "03fce2",
"alias": "learningBitcoin",
"pid-file": "/home/user/.lightning/lightningd-testnet.pid",
"ignore-fee-limits": false,
"watchtime-blocks": 144,
"max-locktime-blocks": 720,
"funding-confirms": 3,
"commit-fee-min": 200,
"commit-fee-max": 2000,
"cltv-delta": 6,
"cltv-final": 10,
"commit-time": 10,
"fee-base": 1,
"rescan": 15,
"fee-per-satoshi": 10,
"max-concurrent-htlcs": 483,
"min-capacity-sat": 10000,
"offline": "false",
"autolisten": true,
"disable-dns": "false",
"enable-autotor-v2-mode": "false",
"encrypted-hsm": false,
"rpc-file-mode": "0600",
"log-level": "DEBUG",
"log-prefix": "lightningd"
}
```
## Summary: Knowing Your lightning Setup
The `~/.lightning` directory contains all of your files, while `lightning-cli help` and a variety of info commands can be used to get more information on how your setup and Lightning Network work.
## What's Next?
Continue "Understanding Your Lightning Setup" with [§18.3: Setting Up_a_Channel](18_3_Setting_Up_a_Channel.md).

View File

@ -0,0 +1,233 @@
# 18.3: Setting Up a Channel
> :information_source: **NOTE:** This is a draft in progress, so that I can get some feedback from early reviewers. It is not yet ready for learning.
You're now ready to your first lightning network channel. To begin with, you'll need to understand what is and how it's created an c-lightning channel.
> :book: ***What is a channel
In simple terms a lightning channel is a money tube that allows fast, cheap and private transfers of money without sending transactions to the blockchain.
More technically a channel is a 2-of-2 multisignature bitcoin onchain transaction that establishes a financial relationship between two agents without trust.
Channels on the Lightning Network always are created between two nodes. Although a Lightning channel only allows payment between two users, channels can be connected together to form a network that allows payments between members that doesn't have a direct channel between them. The channel mantains a local database with bitcoin balance for both parts keeping track of how much money they each have. The two users can then exchange bitcoins through their Lightning channel without ever writing to the Bitcoin blockchain. Only when they want to close out their channel do they settle their bitcoins, based on the final division of coins.
In this chapter we will use testnet network and will use c-lightning as **primary node** to show all processes related.
### Steps to create a channel
* Fund your c-lightning wallet with some satoshis.
* Connect to remote node as a peer.
* Open channel.
#### Fund you c-lightning wallet.
> :book: ***What is a c-lightning wallet?***
C-lightning standard implementation comes with a integrated bitcoin wallet that allows you send and receive bitcoin onchain transactions. This wallet will be used to create new channels. The first thing you need to do is send some satoshis to your c-lightning wallet. You can create a new address using `lightning-cli newaddr` command to use it later. The newaddr RPC command generates a new address which can subsequently be used to fund channels managed by the c-lightning node. This last transaction is called the [funding transaction](https://github.com/lightningnetwork/lightning-rfc/blob/master/03-transactions.md#funding-transaction-output) and it needs to be confirmed before funds can be used. You can specify the type of address wanted, if not specified the address generated will be a bech32.
```
c$ lightning-cli --network=testnet newaddr
{
"address": "tb1qefule33u7ukfuzkmxpz02kwejl8j8dt5jpgtu6",
"bech32": "tb1qefule33u7ukfuzkmxpz02kwejl8j8dt5jpgtu6"
}
```
We send some sats to this address in this transaction [11094bb9ac29ce5af9f1e5a0e4aac2066ae132f25b72bff90fcddf64bf2feb02](https://blockstream.info/testnet/tx/11094bb9ac29ce5af9f1e5a0e4aac2066ae132f25b72bff90fcddf64bf2feb02)
To check you local balance you should use `lightning-cli listfunds` command:
```
c$ lightning-cli --network=testnet listfunds
{
"outputs": [],
"channels": []
}
```
Since we still do not have 6 confirmations we do not have balance available, after 6 confirmations we should see balance:
```
c$ lightning-cli --network=testnet listfunds
{
"outputs": [
{
"txid": "11094bb9ac29ce5af9f1e5a0e4aac2066ae132f25b72bff90fcddf64bf2feb02",
"output": 0,
"value": 300000,
"amount_msat": "300000000msat",
"scriptpubkey": "0014ca79fcc63cf72c9e0adb3044f559d997cf23b574",
"address": "tb1qefule33u7ukfuzkmxpz02kwejl8j8dt5jpgtu6",
"status": "confirmed",
"blockheight": 1780680,
"reserved": false
}
],
"channels": []
}
```
Now that we have funded our c-lightning wallet we will get information about remote node to start creating channel process.
#### Connect to remote node
The first thing you need to do is connect your node to a peer. This is done with the `lightning-cli connect` command. Remember that if you want more information on this command, you should type `lightning-cli help connect`. The connect RPC command establishes a new connection with another node in the Lightning Network.
You have two options here, you could set up a Lightning node on a second machine using the Standup script and choose LND implementation or search a node to connect to.
To connect your node to a remote peer you need it's id that represents the target nodes public key. As a convenience, id may be of the form id@host or id@host:port. Using `lightning-cli listnodes` command you obtain all nodes available on the network and choose one.
```
c$ lightning-cli --network testnet listnodes
```
Output
```
{
"nodeid": "033c2c5eb5cc514b54264a838048b4e7194281e2dcd4ad03bab0198259df2dcbc7",
"alias": "shangoa0c8225d-d86b-4",
"color": "e20f00",
"last_timestamp": 1533416062,
"features": "",
"addresses": [
{
"type": "ipv4",
"address": "54.158.207.111",
"port": 9735
}
]
},
{
"nodeid": "03dc1ad7b657c4d7a042f1847ffcb953cd353bcfe818bce008c35abdcdc25a5257"
},
{
"nodeid": "030b3a8efb847f1c267172d7afbfe93bf501c44a76c6ac6294a8b6b59335d5cdcd",
"alias": "030b3a8efb847f1c2671",
"color": "3399ff",
"last_timestamp": 1558873572,
"features": "",
"addresses": [
{
"type": "ipv4",
"address": "167.99.231.18",
"port": 9735
}
]
},
{
**"nodeid": "0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84",**
"alias": "0302d48972ba7eef8b40",
"color": "3399ff",
"last_timestamp": 1594828492,
"features": "02a2a1",
"addresses": []
},
```
We've selected node with public key 0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84 and we'll connect it with `lightning-cli connect` command:
```
c$ lightning-cli --network=testnet connect 0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84@127.0.0.1:9736
{
"id": "0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84",
"features": "02a2a1"
}
```
To check out:
```
c$ lightning-cli --network=testnet listpeers
{
"peers": [
{
"id": "0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84",
"connected": true,
"netaddr": [
"127.0.0.1:9736"
],
"features": "02a2a1",
"channels": []
}
]
}
```
On success, an object with a “peers” key is returned containing a list distinct objects. Object features are bit flags showing supported features.
#### Open a channel
The fundchannel RPC command opens a payment channel with a peer by committing a funding transaction to the blockchain. You should use `lightning-cli fundchannel` command that receives this parameters:
* **id** is the peer id obtained from connect.
* **amount** is the amount in satoshis taken from the internal wallet to fund the channel. The value cannot be less than the dust limit, currently set to 546, nor more than 16777215 satoshi (unless large channels were negotiated with the peer).
* **feerate** is an optional feerate used for the opening transaction and as initial feerate for commitment and HTLC transactions.
* **announce** is an optional flag that triggers whether to announce this channel or not. Defaults to true. If you want to create an unannounced private channel put to false.
* **minconf** specifies the minimum number of confirmations that used outputs should have. Default is 1.
* **utxos** specifies the utxos to be used to fund the channel, as an array of “txid:vout”.
Now we open the channel like this:
```
c$ lightning-cli --network=testnet fundchannel 0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84 280000 urgent true 1
{
"tx": "0200000000010102eb2fbf64dfcd0ff9bf725bf232e16a06c2aae4a0e5f1f95ace29acb94b09110000000000feffffff02264b000000000000160014aa572371f29310cd677d039cdcd054156c1a9545c045040000000000220020c1ebc407d32cd1fdcd7c0deb6817243b2b982cdaf3c70413f9d3ead29c36f11f024730440220676592b102ee659dfe5ac3acddbe35885140a8476ae7dbbb2f53a939cc815ac0022057a66de1ea16644008791d5cd510439bac00def02cbaa46d04febfe1d5e7e1e001210284368eca82346929a1c3ee2625077571b434b4c8111b81a715dfce5ea86dce1f1f2c1b00",
"txid": "9843c037f54a4660b297a9f2454e11d26d8659f084a284a5740bb15cb1d97aa6",
"channel_id": "a67ad9b15cb10b74a584a284f059866dd2114e45f2a997b260464af537c04399"
}
```
To confirm channel status use `lightning-cli listfunds` command:
```
c$ lightning-cli --network=testnet listfunds
{
"outputs": [
{
"txid": "9843c037f54a4660b297a9f2454e11d26d8659f084a284a5740bb15cb1d97aa6",
"output": 0,
"value": 19238,
"amount_msat": "19238000msat",
"scriptpubkey": "0014aa572371f29310cd677d039cdcd054156c1a9545",
"address": "tb1q4ftjxu0jjvgv6emaqwwde5z5z4kp49299gmdpd",
"status": "confirmed",
"blockheight": 1780768,
"reserved": false
}
],
"channels": [
{
"peer_id": "0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84",
"connected": true,
"state": "CHANNELD_AWAITING_LOCKIN",
"channel_sat": 280000,
"our_amount_msat": "280000000msat",
"channel_total_sat": 280000,
"amount_msat": "280000000msat",
"funding_txid": "9843c037f54a4660b297a9f2454e11d26d8659f084a284a5740bb15cb1d97aa6",
"funding_output": 1
}
]
}
```
While the channel with 280.000 satoshis (Channel capacity) is confirmed its state will be CHANNELD_AWAITING_LOCKIN and we got an change output with 19238 sats.
As we're using testnet network these values are used as an example to show the different states that a channel can have. In a channel with real funds, the actual mining circumstances of the mainnet network must be taken into account.
The funding_txid onchain is [9843c037f54a4660b297a9f2454e11d26d8659f084a284a5740bb15cb1d97aa6](https://blockstream.info/testnet/tx/9843c037f54a4660b297a9f2454e11d26d8659f084a284a5740bb15cb1d97aa6)
#### Channel capacity
As we said before both sides of the channel own a portion of its capacity. The amount on your side of the channel is called *local balance* and the amount on your peers side is called *remote balance*. Both balances can be updated many times without closing the channel (sending final balance to the blockchain), but the channel capacity cannot change without closing or splicing it. The total capacity of a channel is the sum of the balance held by each participant in the channel.
Next chapter we will deep creating and paying invoices.
## Summary: Setting up a channel
You need to create a channel with remote nodes to be able to receive and send money over the lightning network. Further a maintenance task is required to the channels to keep them balanced.
## What's Next?
Continue "Understanding Your Lightning Setup" with [§19.1: Generate a Payment request](19_1_Generate_a_Payment_Request.md).

View File

@ -0,0 +1,129 @@
# 19.1: Generate a Payment request.
> :information_source: **NOTE:** This is a draft in progress, so that I can get some feedback from early reviewers. It is not yet ready for learning.
This chapter shows what is and how to create a payment request. We will explain briefly how works payments on the Lightning Network.
For this example we've created a second lightning node using LND implementation to create an invoice to be payed later using our main c-lighting installation in next chapter. We will refer to this instance using `lnd$ ` prompt shell to indicate place where we'll generate LND commands. If you want to reproduce this steps you should use Bitcoin Standup to create a second machine and install LND.
> :book: ***What is an invoice
Almost all payments made on the Lightning Network require an invoice, which is nothing more than a **request for payment** made by the recipient of the money and sent by different means to the user who will pay. The format for a Lightning invoice uses bech32 encoding, which is already used for Bitcoin Segregated Witness and all payment requests are single use.
An invoice is made up of two parts, one is human readable and other is
- Human readable part: `ln` + (`lnbc` for Bitcoin mainnet, `lntb` for Bitcoin testnet, and `lnbcrt` for Bitcoin regtest) + data amount
- Data part : UNIX Timestamp + tagged parts include a payment hash, the pubkey of the payee node, an optional description of the payment, an expiration time, and some extra routing information.
> :book: ***Conditional payments.
As we said in Setting a channel chapter and although the channels are created between two participants, the channels can be connected to each other forming a payment network to allow payments between all the network participants without having a direct channel between them using an smart contract called **Hashed Time Locked Contract**.
> :book: ***Hashed Time Locked Contract.
A Hashed Time Locked Contract is a conditional payment that use hashlocks and timelocks to ensure payment security. This means that receiver must presents a payment preimage or generate a cryptographic proof of payment before a given time otherwise the payer can cancel the contract by spending it. This contracts are created as outputs from the Commitment transaction.
> :book: ***Commitment transaction.
Commitment transaction is a transaction that spends the funding transaction. Each peer holds the other peer's signature meaning that either one can spent his commitment transaction whatever he wants. After each new commitment transaction is created the old one is revoked.
### Node information
In this second instance that we refer before you may get information about it using `lnd$lncli -n testnet getinfo` command. Remember identity_pubkey field, due it will be the same value when you pay the invoice.
**"identity_pubkey": "0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84"**
> :warning: **WARNING:** Notice this example is using an LND instance, if you want to reproduce this steps you should use Bitcoin Standup Script and install a new LND instance.
```
lnd$ lncli -n testnet getinfo
{
"version": "0.10.99-beta commit=clock/v1.0.0-171-g8cb1276dbf0bfd9fcbf599df87a43238e599eaac",
"commit_hash": "8cb1276dbf0bfd9fcbf599df87a43238e599eaac",
"identity_pubkey": "0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84",
"alias": "0302d48972ba7eef8b40",
"color": "#3399ff",
"num_pending_channels": 0,
"num_active_channels": 1,
"num_inactive_channels": 0,
"num_peers": 3,
"block_height": 1781444,
"block_hash": "0000000018655b27a1801e976c800be99c6f42c9bfcf122695a7ef5c0fa12e73",
"best_header_timestamp": "1595509101",
"synced_to_chain": true,
"synced_to_graph": true,
"testnet": true,
"chains": [
{
"chain": "bitcoin",
"network": "testnet"
}
],
"uris": [
"0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84@192.168.0.22:9736"
],
"features": {
"0": {
"name": "data-loss-protect",
"is_required": true,
"is_known": true
},
"5": {
"name": "upfront-shutdown-script",
"is_required": false,
"is_known": true
},
"7": {
"name": "gossip-queries",
"is_required": false,
"is_known": true
},
"9": {
"name": "tlv-onion",
"is_required": false,
"is_known": true
},
"13": {
"name": "static-remote-key",
"is_required": false,
"is_known": true
},
"15": {
"name": "payment-addr",
"is_required": false,
"is_known": true
},
"17": {
"name": "multi-path-payments",
"is_required": false,
"is_known": true
}
}
}
```
### Generate a Payment request.
Now you can create a payment request using `lnd$lncli -n testnet addinvoice` command. You can use --amt argument to indicate amount to be payed and add a description using --memo argument.
```
lnd$ lncli -n testnet addinvoice --amt 100000 --memo "First LN Payment - Learning Bitcoin and Lightning from the Command line."
{
"r_hash": "72fbf5c2baadc780b17a27d983bd685f7d6ddf682b028c6dc13a50976e9e6e6c",
"payment_request": "lntb1m1p03ft7lpp5zve4dsgwgdxekqqq39vhgcnv6gfa2g2ktqy9lf0aph60d0388xmqdqqcqzpgsp545a9fphd8m5ayplcu8m5845cr4m0zcnyxddwv4g3zm32yprkfd4q9qy9qsq3s4y6cmyvh0qw9qm0sf80llxyyjy9xwrjds7lpkqhzv247jsm6q5me8t9e6ftquma664gz5u4a2rvs0yf4f0mlwtwfs6as5uj5djzhcqpnqlcj",
"add_index": "1"
}
```
## Summary: Generating a Payment request.
In most cases you need to receive an invoice to use Lightning Network payments. In this example we've created on manually but in real cases you can buy products and services that will generate a respective invoice for it.
## What's Next?
Continue "Understanding Your Lightning Setup" with [§19.2: Paying_a_Invoice](19_2_Paying_a_Invoice.md).

151
19_2_Paying_a_Invoice.md Normal file
View File

@ -0,0 +1,151 @@
# 19.2: Paying a Invoice
> :information_source: **NOTE:** This is a draft in progress, so that I can get some feedback from early reviewers. It is not yet ready for learning.
In this chapter you will learn how to pay an invoice using `lightning-cli pay ` command. As we did in previous chapter we already have an invoice to pay.
Check ln invoice:
`lntb1m1p03ft7lpp5zve4dsgwgdxekqqq39vhgcnv6gfa2g2ktqy9lf0aph60d0388xmqdqqcqzpgsp545a9fphd8m5ayplcu8m5845cr4m0zcnyxddwv4g3zm32yprkfd4q9qy9qsq3s4y6cmyvh0qw9qm0sf80llxyyjy9xwrjds7lpkqhzv247jsm6q5me8t9e6ftquma664gz5u4a2rvs0yf4f0mlwtwfs6as5uj5djzhcqpnqlcj
`
This invoice starts with prefix ln+tb+1m that indicates milli, so you should multi by 0.001. That means we'll pay an invoice by 100000 satoshis.
### Understanding your invoice
If you want to decode your lightning invoice you should use `lightning-cli decodepay ` command that receives a string and checks and parses as specified by the [BOLT 11 specification](https://github.com/lightningnetwork/lightning-rfc/blob/master/11-payment-encoding.md).
On success it returns an object with the following fields:
* currency: Currency.
* timestamp: the UNIX-style timestamp of the invoice.
* expiry: the number of seconds this is valid after timestamp.
* payee: the public key of the recipient.
* payment_hash: the payment hash of the request.
* signature: the DER-encoded signature.
* description: Description.
```
c$lightning-cli --network=testnet decodepay lntb1m1p03ft7lpp5zve4dsgwgdxekqqq39vhgcnv6gfa2g2ktqy9lf0aph60d0388xmqdqqcqzpgsp545a9fphd8m5ayplcu8m5845cr4m0zcnyxddwv4g3zm32yprkfd4q9qy9qsq3s4y6cmyvh0qw9qm0sf80llxyyjy9xwrjds7lpkqhzv247jsm6q5me8t9e6ftquma664gz5u4a2rvs0yf4f0mlwtwfs6as5uj5djzhcqpnqlcj
{
"currency": "tb",
"created_at": 1595191263,
"expiry": 3600,
"payee": "0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84",
"msatoshi": 100000000,
"amount_msat": "100000000msat",
"description": "First LN Payment - Learning Bitcoin and Lightning from the Command line.",
"min_final_cltv_expiry": 40,
"payment_secret": "ad3a5486ed3ee9d207f8e1f743d6981d76f16264335ae6551116e2a204764b6a",
"features": "028200",
"payment_hash": "133356c10e434d9b0000895974626cd213d5215658085fa5fd0df4f6be2739b6",
"signature": "30450221008c2a4d636465de07141b7c1277ffe621244299c39361ef86c0b898aafa50de8102204de4eb2e7495839beeb5540a9caf543641e44d52fdfdcb7261aec29c951b215f"
}
```
Check payee value is the same as identity_pubkey value seen previous chapter.
**"identity_pubkey": "0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84",**
### Check your balance
As we did in previous chapter we have established an channel with a total capacity of 280.000 sats. This will be channel used to pay the invoice.
```
c$ lightning-cli --network=testnet listfunds
{
"outputs": [
{
"txid": "9843c037f54a4660b297a9f2454e11d26d8659f084a284a5740bb15cb1d97aa6",
"output": 0,
"value": 19238,
"amount_msat": "19238000msat",
"scriptpubkey": "0014aa572371f29310cd677d039cdcd054156c1a9545",
"address": "tb1q4ftjxu0jjvgv6emaqwwde5z5z4kp49299gmdpd",
"status": "confirmed",
"blockheight": 1780768,
"reserved": false
}
],
"channels": [
{
"peer_id": "0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84",
"connected": true,
"state": "CHANNELD_AWAITING_LOCKIN",
"channel_sat": 280000,
"our_amount_msat": "280000000msat",
"channel_total_sat": **280000**,
"amount_msat": "280000000msat",
"funding_txid": "9843c037f54a4660b297a9f2454e11d26d8659f084a284a5740bb15cb1d97aa6",
"funding_output": 1
}
]
}
```
### Paying your invoice
You should use `lightning-cli pay ` command to pay the invoice. The pay RPC command attempts to find a route to the given destination, and send the funds asked in amount value.
Notice amount is expressed in milli-satoshi.
```
c$lightning-cli --network=testnet pay
lntb1m1p03ft7lpp5zve4dsgwgdxekqqq39vhgcnv6gfa2g2ktqy9lf0aph60d0388xmqdqqcqzpgsp545a9fphd8m5ayplcu8m5845cr4m0zcnyxddwv4g3zm32yprkfd4q9qy9qsq3s4y6cmyvh0qw9qm0sf80llxyyjy9xwrjds7lpkqhzv247jsm6q5me8t9e6ftquma664gz5u4a2rvs0yf4f0mlwtwfs6as5uj5djzhcqpnqlcj
{
"id": 1,
"payment_hash": "133356c10e434d9b0000895974626cd213d5215658085fa5fd0df4f6be2739b6",
"destination": "0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84",
"msatoshi": 100000000,
"amount_msat": "100000000msat",
"msatoshi_sent": 100000000,
"amount_sent_msat": "100000000msat",
"created_at": 1595191379,
"status": "complete",
"payment_preimage": "8b7549ffd4e648374669d47992c1ab44086501d5dd85d7e3d15766d70e9196e3",
"bolt11": "lntb1m1p03ft7lpp5zve4dsgwgdxekqqq39vhgcnv6gfa2g2ktqy9lf0aph60d0388xmqdqqcqzpgsp545a9fphd8m5ayplcu8m5845cr4m0zcnyxddwv4g3zm32yprkfd4q9qy9qsq3s4y6cmyvh0qw9qm0sf80llxyyjy9xwrjds7lpkqhzv247jsm6q5me8t9e6ftquma664gz5u4a2rvs0yf4f0mlwtwfs6as5uj5djzhcqpnqlcj"
}
```
### Check your balance
We've performed payment successfully and gets decreased channel balance on our side. Now it has 180000 as available balance.
```
c$ lightning-cli --network=testnet listfunds
{
"outputs": [
{
"txid": "9843c037f54a4660b297a9f2454e11d26d8659f084a284a5740bb15cb1d97aa6",
"output": 0,
"value": 19238,
"amount_msat": "19238000msat",
"scriptpubkey": "0014aa572371f29310cd677d039cdcd054156c1a9545",
"address": "tb1q4ftjxu0jjvgv6emaqwwde5z5z4kp49299gmdpd",
"status": "confirmed",
"blockheight": 1780768,
"reserved": false
}
],
"channels": [
{
"peer_id": "0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84",
"connected": true,
"state": "CHANNELD_NORMAL",
"short_channel_id": "1780768x12x1",
"channel_sat": 180000,
"our_amount_msat": "180000000msat",
"channel_total_sat": 280000,
"amount_msat": "280000000msat",
"funding_txid": "9843c037f54a4660b297a9f2454e11d26d8659f084a284a5740bb15cb1d97aa6",
"funding_output": 1
}
]
}
```
## Summary: Paying a Invoice
We've created an invoice by 100.000 satoshis using a second machine and we've payed it using our main Lightning network node c-lightning. The channel was created with an initial amount of 280000 satoshis. This is called Total capacity channel. Later we've payed invoice we proved local balance was reduced remaining at 180.000 satoshis.
## What's Next?
Continue "Understanding Your Lightning Setup" with [§19.3: Closing a Channel](19_3_Closing_a_Channel.md).

239
19_3_Closing_a_Channel.md Normal file
View File

@ -0,0 +1,239 @@
# 19.3: Closing a Channel
> :information_source: **NOTE:** This is a draft in progress, so that I can get some feedback from early reviewers. It is not yet ready for learning.
In this chapter you'll be able to close a channel and learn what it means and how to do it using `lightning-cli close` command-line interface. The close RPC command attempts to close the channel cooperatively with the peer, or unilaterally after unilateraltimeout argument expires measured in seconds and the output will be sent to the address controlled by your c-lightning wallet if you don't specify one.
Close a channel means you and your counterparty will send their agreed-upon channel balance to the blockchain whereby you must pay transaction fees and must wait for the transaction to be mined.
### Listing your channels.
You can use the `lightning-cli listfunds` command to see your channels. This RPC command displays all funds available, either in unspent outputs (UTXOs) in the internal wallet or funds locked in currently open channels.
```
c$ lightning-cli --network=testnet listfunds
{
"outputs": [
{
"txid": "9843c037f54a4660b297a9f2454e11d26d8659f084a284a5740bb15cb1d97aa6",
"output": 0,
"value": 19238,
"amount_msat": "19238000msat",
"scriptpubkey": "0014aa572371f29310cd677d039cdcd054156c1a9545",
"address": "tb1q4ftjxu0jjvgv6emaqwwde5z5z4kp49299gmdpd",
"status": "confirmed",
"blockheight": 1780768,
"reserved": false
}
],
"channels": [
{
"peer_id": "0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84",
"connected": false,
"state": "CHANNELD_NORMAL",
"short_channel_id": "1780768x12x1",
"channel_sat": 180000,
"our_amount_msat": "180000000msat",
"channel_total_sat": 280000,
"amount_msat": "280000000msat",
"funding_txid": "9843c037f54a4660b297a9f2454e11d26d8659f084a284a5740bb15cb1d97aa6",
"funding_output": 1
}
]
}
```
Each channel has an identifier expressed in the short_channel_id field. Each value in short_channel_id means
"1780768x12x1"
* Created on 1780768 block.
* transaction index (12).
* output index (1).
## Closing a channel
You should use `lightning-cli close` command to close the channel. This RPC command attempts to close the channel cooperatively with the peer, or unilaterally after unilateraltimeout expires, and the to-local output will be sent to the address specified in destination.
### Types of Closing Channels.
Each participant of the channel is able to create as many Lightning payments to their counterparty as their funds they have. Most of the time there will be no disagreements between the participants, so there will only be two onchain transactions, one opening and the other closing the channel. However, there may be other scenarios in which you are not online, you do not agree with the last state of the channel or someone tries to steal funds from the other party.
#### Cooperative Close
In this case both channel participants agree to close the channel and settle the final state to the blockchain. Both participants must be online and it's performed by broadcasting an unconditional spend of the funding transaction with an output to each peer.
#### Force Close
In this case when only one participant is online or if the participants disagree on the last state of the channel, so one peer can perform an unilateral close of the channel without the cooperation of the other node. It's performed by broadcasting a commitment transaction that commits to a previous channel state which both parts have agreed upon.
This commitment transaction contains the channel state divided in two parts: the balance of each participant and all the pending payments (HTLCs).
To perform this kind of close you need to specify an argument called unilateraltimeout. If this value is not zero, the close command will unilaterally close the channel when that number of seconds is reached like this:
```
c$ lightning-cli --network=testnet close $NODEIDREMOTE 60
{
"tx": "0200000001a1091f727e6041cc93fead2ea46b8402133f53e6ab89ab106b49638c11f27cba00000000006a40aa8001df85010000000000160014d22818913daf3b4f86e0bcb302a5a812d1ef6b91c6772d20",
"txid": "02cc4c647eb3e06f37fcbde39871ebae4333b7581954ea86b27b85ced6a5c4f7",
"type": "unilateral"
}
```
### Node Information
Now we'll show you how to get information about your channel using `lightning-cli listchannels` command. The listchannels RPC command returns data on channels that are known to the node. Because channels may be bidirectional, up to 2 objects will be returned for each channel (one for each direction). To query information about own channels we'll use jq tool showed in previous chapters.
First we'll get our own node id public_key in NODEID variable.
```
c$ NODEID=$(lightning-cli --network=testnet getinfo | jq .id)
c$ echo $NODEID
"03fce2a20393a65b9d6cab5425f4cd33ddc621ade458efd69d652917e2b5eaf59c"
c$
```
Later we'll use select to show only data containing public_key id as source or destination.
```
c$ lightning-cli listchannels | jq '.channels[] | select(.source == '$NODEID' or .destination == '$NODEID')'
{
"source": "03fce2a20393a65b9d6cab5425f4cd33ddc621ade458efd69d652917e2b5eaf59c",
"destination": "0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84",
"short_channel_id": "1780768x12x1",
"public": true,
"satoshis": 280000,
"amount_msat": "280000000msat",
"message_flags": 1,
"channel_flags": 2,
"active": true,
"last_update": 1595508075,
"base_fee_millisatoshi": 1000,
"fee_per_millionth": 1,
"delay": 40,
"htlc_minimum_msat": "1000msat",
"htlc_maximum_msat": "280000000msat",
"features": ""
}
```
### Closing a channel
Finally you should use `lightning-cli close` command to close the channel. The close RPC command attempts to close the channel cooperatively with the peer, if you want to close it unilaterally set unilateraltimeout argument with number of seconds command will wait. If you set to 0 and the peer is online command can negotiate a mutual close. For this example we use an mutual close.
Now we'll get remote node id public key in a variable:
```
c$ $NODEIDREMOTE=lightning-cli listchannels | jq '.channels[] | select(.source == '$NODEID')' | jq .destination
c$ echo $NODEIDREMOTE
0302d48972ba7eef8b40696102ad114090fd4c146e381f18c7932a2a1d73566f84
c$
```
Now we use NODEIDREMOTE variable to close channel:
```
c$lightning-cli --network=testnet close $NODEIDREMOTE 0
{
"tx": "0200000001a67ad9b15cb10b74a584a284f059866dd2114e45f2a997b260464af537c043980100000000ffffffff02a08601000000000016001404e34b25e1310c9b90c7a53a6eba88f4eefe8efb69be020000000000160014865353eaccaa94aa4f90d3a0acdf3903c06c12c400000000",
"txid": "b4c0a1993dd113081eff5369a22d6afe1af9f0d07b29a590e8772ac7f712736a",
"type": "mutual"
}
```
The closing transaction onchain is [b4c0a1993dd113081eff5369a22d6afe1af9f0d07b29a590e8772ac7f712736a](https://blockstream.info/testnet/tx/b4c0a1993dd113081eff5369a22d6afe1af9f0d07b29a590e8772ac7f712736a).
This transaction has two outputs, one for remote node and other for local c-lightning wallet. Output on index 0 corresponds to remote node with a value of 100000. Output on index 1 correspond to local node with a value of 179817.
```
c$ bitcoin-cli -testnet getrawtransaction b4c0a1993dd113081eff5369a22d6afe1af9f0d07b29a590e8772ac7f712736a 1
{
"txid": "b4c0a1993dd113081eff5369a22d6afe1af9f0d07b29a590e8772ac7f712736a",
"hash": "9433409227ca3d7a6999cdcc2856272314aef96f0e869a04711eda4969bbd21f",
"version": 2,
"size": 334,
"vsize": 169,
"weight": 673,
"locktime": 0,
"vin": [
{
"txid": "9843c037f54a4660b297a9f2454e11d26d8659f084a284a5740bb15cb1d97aa6",
"vout": 1,
"scriptSig": {
"asm": "",
"hex": ""
},
"txinwitness": [
"",
"3045022100ef40a71fc4d4d0e197cd3d503961da90b71cedab25f6f30740b3640664efb617022061f68aaffccf739824668d07519c8cb59ec30117d87beff2ef217e31cb5e628801",
"304402201a28274f64ec78fecba74ebc2b13582564ab155f83593c65ca1667bb92c42de10220489e7c3adc5be8bac2c5771482e5571abd3f602cb40ece2cfea3b768eb5341ea01",
"52210364d9b2e600d837aad224702c5f30c0ab73ac499cb67f43899cbf83f6358d422c21036695eadb796fe140434aad02c7da76395a44f62747770bf381fa4a3c52ff279452ae"
],
"sequence": 4294967295
}
],
"vout": [
{
"value": 0.00100000,
"n": 0,
"scriptPubKey": {
"asm": "0 04e34b25e1310c9b90c7a53a6eba88f4eefe8efb",
"hex": "001404e34b25e1310c9b90c7a53a6eba88f4eefe8efb",
"reqSigs": 1,
"type": "witness_v0_keyhash",
"addresses": [
"tb1qqn35kf0pxyxfhyx855axaw5g7nh0arhmxyv3zk"
]
}
},
{
"value": 0.00179817,
"n": 1,
"scriptPubKey": {
"asm": "0 865353eaccaa94aa4f90d3a0acdf3903c06c12c4",
"hex": "0014865353eaccaa94aa4f90d3a0acdf3903c06c12c4",
"reqSigs": 1,
"type": "witness_v0_keyhash",
"addresses": [
"tb1qsef486kv42225nus6ws2eheeq0qxcykycqsymn"
]
}
}
],
"hex": "02000000000101a67ad9b15cb10b74a584a284f059866dd2114e45f2a997b260464af537c043980100000000ffffffff02a08601000000000016001404e34b25e1310c9b90c7a53a6eba88f4eefe8efb69be020000000000160014865353eaccaa94aa4f90d3a0acdf3903c06c12c40400483045022100ef40a71fc4d4d0e197cd3d503961da90b71cedab25f6f30740b3640664efb617022061f68aaffccf739824668d07519c8cb59ec30117d87beff2ef217e31cb5e62880147304402201a28274f64ec78fecba74ebc2b13582564ab155f83593c65ca1667bb92c42de10220489e7c3adc5be8bac2c5771482e5571abd3f602cb40ece2cfea3b768eb5341ea014752210364d9b2e600d837aad224702c5f30c0ab73ac499cb67f43899cbf83f6358d422c21036695eadb796fe140434aad02c7da76395a44f62747770bf381fa4a3c52ff279452ae00000000"
}
```
Listing funds onchain or offchain we get an output with a value of 179817 that results of 280000 minus 183 per fee in 279817. We have to substract 100000 paid on the invoice of the previous chapter to finally receives 179817 satoshis.
```
c$lightning-cli --network=testnet listfunds
{
"outputs": [
{
"txid": "9843c037f54a4660b297a9f2454e11d26d8659f084a284a5740bb15cb1d97aa6",
"output": 0,
"value": 19238,
"amount_msat": "19238000msat",
"scriptpubkey": "0014aa572371f29310cd677d039cdcd054156c1a9545",
"address": "tb1q4ftjxu0jjvgv6emaqwwde5z5z4kp49299gmdpd",
"status": "confirmed",
"blockheight": 1780768,
"reserved": false
},
{
"txid": "b4c0a1993dd113081eff5369a22d6afe1af9f0d07b29a590e8772ac7f712736a",
"output": 1,
"value": 179817,
"amount_msat": "179817000msat",
"scriptpubkey": "0014865353eaccaa94aa4f90d3a0acdf3903c06c12c4",
"address": "tb1qsef486kv42225nus6ws2eheeq0qxcykycqsymn",
"status": "confirmed",
"blockheight": 1781830,
"reserved": false
}
}
```
## Summary: Closing a channel
When you close a channel you perform an onchain transaction ending your financial relationship with remote node. To close a channel you must take into account its status and the type of closure you want to execute and decide some arguments to do it.
## What's Next?
Continue "Understanding Your Lightning Setup" with [§19.4: Lightning Network Review](19_4_Lightning_Network_Review.md).

View File

@ -0,0 +1,38 @@
## Lightning Network Review
In this brief review we add some important features of C-lightning and we list the most widely used implementations in the lightning network Today, although there are more. All implementations follow the Basis of Lightning Technology (BOLT) documents describe a layer-2 protocol for off-chain bitcoin transfers. The specifications are currently a work-in-progress and currently being drafted.
| Name | Description | BitcoinStandup | Language | Repository |
| ------------- | ------------- | :---: | ------------- | ------------- |
| C-lighting | Blockstream | X | C | [Download](https://github.com/ElementsProject/lightning) |
| LND | Lightning Labs | X | Go | [Download](https://github.com/lightningnetwork/lnd) |
| Eclair | ACINQ | - | Scala | [Download](https://github.com/ACINQ/eclair) |
### Plugins
c-lightning is a lightweight, highly customizable and standard compliant implementation of the Lightning Network protocol. The way c-lightning extend the functionality is using Plugins, that are a powerful and easy way to do it. Mainly they are subprocesses that are initiated by lightningd daemon and can interact with lightningd in a different ways:
* Command line option that allows plugins to register their own command line options that are exposed through lightningd.
* JSON-RPC command passthrough allows plugins to add their own commands to the JSON-RPC interface.
* Event stream subscriptions provide plugins with a push-based notification mechanism about events from the lightningd.
* Hooks are a primitive option that allows plugins to be notified about events in lightningd daemon and modify its behavior or pass custom behaviors.
A plugin may be written in any language, and communicates with lightningd through the plugins stdin and stdout. JSON-RPCv2 is used as protocol on top of the two streams, with the plugin acting as server and lightningd acting as client.
Here is a updated list of [plugins](https://github.com/lightningd/plugins) available.
### Backup
As we mentioned on Closing a channel chapter your node needs to be online all the time otherwise your counterparty could send a previous channel status and steals your funds. However, there is another scenario in which funds can be lost, and that is when a hardware failure occurs that prevents the node from establishing a cooperative closure with the counterparty. This will probably imply that if you do not have an exact copy of the state of the channel before the failure, you will have an invalid state that could cause the other node to assume it as an attempted fraud and use the penalty transaction. In this case all funds will be lost. To avoid this undesirable situation exists a solution based on the high availability of postgresQL database [here](https://github.com/gabridome/docs/blob/master/c-lightning_with_postgresql_reliability.md). We haven't tested this solution.
### Mobile wallets.
Today we know about two mobile lightning wallets that support c-lightning implementation. For iOS devices FullyNoded which is an open source iOS Bitcoin wallet that connects via Tor V3 authenticated service to your own full node. FullyNoded functionality is currently under active development and in early beta testing phase.
SparkWallet is a minimalistic wallet GUI for c-lightning, accessible over the web or through mobile and desktop apps for Android.
* [FullyNoded](https://github.com/Fonta1n3/FullyNoded/blob/master/Docs/Lightning.md) in TestFlight
* [SparkWallet](https://github.com/shesek/spark-wallet)