Commit Graph

1267 Commits

Author SHA1 Message Date
Rusty Russell 01a47720c3 plugins/libplugin-pay: hack in blinded path support.
We simply take the first one, and route to the start of that.  Then we
append the blinded path to the onion construction.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-11-09 15:08:03 +01:00
Rusty Russell cb1156cd32 libplugin: support filters.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-11-09 20:25:58 +10:30
Rusty Russell f0731d2ca1 common/json_stream: support filtering don't print fields not allowed.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-11-09 20:25:58 +10:30
Rusty Russell 508a170598 common/json_filter: routine to turn "filter" JSON into a filter.
Since the "struct command" is different from plugins and lightningd, we
need an accessor for this to work (the plugin one is a dummy for now!).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-11-09 20:25:58 +10:30
Rusty Russell 3c75770586 common/json_filter: routines for json filtering.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-11-09 20:25:58 +10:30
Christian Decker 2605e117c9 pytest: Add test for optional options in cln-plugin
Changelog-Added: cln-plugin: Options are no longer required to have a default value
2022-11-03 11:28:22 +01:00
Justin Moon f111d6772d Plugin config options with no defaults 2022-11-03 11:28:22 +01:00
Rusty Russell 5cf86a1a2e common: update to latest onion message spec.
Mainly, field name changes.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-EXPERIMENTAL: Protocol: Support for forwarding blinded payments (as per latest draft)
2022-10-26 11:29:06 +10:30
Rusty Russell 426886ff9b lightningd: return invalid_onon_blinding for any blinded payment error.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-10-26 11:29:06 +10:30
Rusty Russell c0ae2394d8 common/blindedpath: generalize construction routines.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-10-26 11:29:06 +10:30
Rusty Russell 662c6931f3 Remove point32.
The x-only dream is dead.  Remove all trace.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-10-26 11:29:06 +10:30
Rusty Russell 1cdf21678e offers: print out more details, fix up schema for decode of blinded paths.
We need to print out first_node_id, and "node_id" is now called
"blinded_node_id" in the spec.

And the schema didn't include the payment fields in the blinded path
for invoices (which broke as soon as we actually tested one!).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-10-26 11:29:06 +10:30
Rusty Russell e30ea91908 BOLTs: update to more recent bolt12 spec.
It's 2b7ad577d7a790b302bd1aa044b22c809c76e49d, which reverts the
point32 changes.

It also restores send_invoice in `invoice`, which we had removed
from spec and put into the recurrence patch.

I originally had implemented compatibility, but other changes
which followed this are far too widespread.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-EXPERIMENTAL: offers: complete rework of spec from other teams (yay!) breaks previous compatibility (boo!)
2022-10-26 11:29:06 +10:30
Rusty Russell eac8401f84 Makefile: separate bolt12 wireobjects
Most things don't want them, so don't link it into everything by default.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-10-26 11:29:06 +10:30
Rusty Russell 82d98e4b96 gossmap: move gossmap_guess_node_id to pay plugin.
This removes a point32 dependency.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-10-26 11:29:06 +10:30
Rusty Russell bed905a394 lightningd: use 33 byte pubkeys internally.
We still use 32 bytes on the wire, but internally don't use x-only.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-10-26 11:29:06 +10:30
niftynei e00857827f funder: cleanup datastore on state-change/channel failure
Let's not leave old state hanging around! Note that this fires
for pretty much every/any channel (even if we're not the opener).
2022-10-20 13:42:41 +02:00
niftynei efd096dc96 funder: filter prev-outs such that we only use still unspent ones
If for some reason a utxo we used previously is no longer 'unspent',
we shouldn't use it for the next transaction.
2022-10-20 13:42:41 +02:00
niftynei 38e2428f12 funder: use utxopsbt to build psbt for RBFs
We use the saved previous outputs (plus maybe some new ones?) to build a
psbt for an RBF request.

RBFs utxo reuse is now working so we can unfail the test (and update
it to reflect that the lease sticks around through an RBF cycle).

Changelog-Fixed: Plugins: `funder` now honors lease requests across RBFs
2022-10-20 13:42:41 +02:00
niftynei 45acc20a8d funder: use previous outputs in count towards available funding
Still need to use them to build the PSBT for the rbf however.
2022-10-20 13:42:41 +02:00
niftynei 7733c2b0f4 funder: pull out previous input list from datastore on RBF
It'd be nice to know which utxos we used previously, so we can rebuild a
transaction using them!
2022-10-20 13:42:41 +02:00
niftynei a5e9035e2e funder: save utxos of signed txs to datastore
We're going to need to know what utxos we used if we RBF this channel;
so we serialize our inputs and save them to the datastore under the channel_id.
2022-10-20 13:42:41 +02:00
niftynei dc9e79c445 funder: rm quote that makes nifty cringe every time she sees it 2022-10-20 13:42:41 +02:00
niftynei 85039d4f4e df: pass lease data back to funder for rbfs
let's let RBFs know about our lease info!
2022-10-20 13:42:41 +02:00
niftynei 8d864d2299 funder: we always pass in channel_max, no need to special case it
Parse the channel_max along with everything else.
2022-10-20 13:42:41 +02:00
Rusty Russell e855ac2f9e keysend: just strip even unknown fields.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Fixed: Plugins: `keysend` now removes unknown even (technically illegal!) fields, to try to accept more payments.
2022-10-04 17:48:08 +02:00
Rusty Russell 2fbe0f59f1 plugins/fetchinvoice: remove obsolete string-based API.
Generate the payload in the callers.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-29 16:10:57 +09:30
Rusty Russell 41ef85318d onionmessages: remove obsolete onion message parsing.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-29 16:10:57 +09:30
Rusty Russell 8771c86379 common/onion: expunge all trace of different onion styles.
In particular, remove special routines to pull length: it's there,
take it and check it yourself.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-28 13:40:57 +02:00
Rusty Russell 68f15f17bb delforward: allow deletion of "unknown in_htlc_id" and fix autoclean to use it.
Note the caveats: we will delete *all* of them at once!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-27 14:42:03 +09:30
Christian Decker e1fc88ff70 cln-plugin: Prep the logging payload in a let
I wanted to debug why we weren't getting some log messages, and this
makes that a bit easier in future.
2022-09-25 15:13:12 +02:00
Christian Decker 064a5a6940 cln-plugin: Add log filtering support
We filter based on the environment variable `CLN_PLUGIN_LOG`,
defaulting to `info` as that is not as noisy as `debug` or `trace`, at
least libraries will not spam us too heavily.

Changelog-Added cln-plugin: The logs level from cln-plugins can be configured by the `CLN_PLUGIN_LOG` environment variable.
2022-09-25 15:13:12 +02:00
Christian Decker 8898511cf6 cln-plugin: Defer binding the plugin state until after configuring
We had a bit of a chicken-and-egg problem, where we instantiated the
`state` to be managed by the `Plugin` during the very first step when
creating the `Builder`, but then the state might depend on the
configuration we only get later. This would force developers to add
placeholders in the form of `Option` into the state, when really
they'd never be none after configuring.

This defers the binding until after we get the configuration and
cleans up the semantics:

 - `Builder`: declare options, hooks, etc
 - `ConfiguredPlugin`: we have exchanged the handshake with
   `lightningd`, now we can construct the `state` accordingly
 - `Plugin`: Running instance of the plugin

Changelog-Changed: cln-plugin: Moved the state binding to the plugin until after the configuration step
2022-09-25 15:13:12 +02:00
Rusty Russell bb49e1bea5 common: assume htlc_maximum_msat, don't check bit any more.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-24 15:22:27 +09:30
Rusty Russell 253b25522b BOLT: update to version which requires option_channel_htlc_max.
We will now simply reject old-style ones as invalid.  Turns out the
only trace we could find is a channel between two nodes unconnected to
the rest of the network.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Changed: Protocol: We now require all channel_update messages include htlc_maximum_msat (as per latest BOLTs)
2022-09-24 15:22:27 +09:30
Rusty Russell 6338758018 gossmap: make API more robust against future changes.
Many changes to gossmap (including the pending ones!) don't actually
concern readers, as long as they obey certain rules:

1. Ignore unknown messages.
2. Treat all 16 upper bits of length as flags, ignore unknown ones.

So now we split the version byte into MAJOR and MINOR, and you can
ignore MINOR changes.

We don't expose the internal version (for creating the map)
programmatically: you should really hardcode what major version you
understand!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-24 15:22:27 +09:30
Rusty Russell f52ff07558 lightningd: allow delpay to delete a specific payment.
This is actually what the autoclean plugin wants, especially since
you can't otherwise delete a payment which has failed then succeeded.

But insist on neither or both being specified, at least for now.

Changelog-Added: JSON-RPC: `delpay` takes optional `groupid` and `partid` parameters to specify exactly what payment to delete.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-22 15:19:46 +02:00
Rusty Russell fa7d732ba6 lightningd: allow a connection to specify db batching.
Previous commit was a hack which *always* batched where possible, this
is a more sophisticated opt-in varaint, with a timeout sanity check.

Final performance for cleaning up 1M pays/forwards/invoices:

```
$ time l1-cli autoclean-once succeededpays 1
{
   "autoclean": {
      "succeededpays": {
         "cleaned": 1000000,
         "uncleaned": 26895
      }
   }
}

real	6m9.828s
user	0m0.003s
sys	0m0.001s
$ time l2-cli autoclean-once succeededforwards 1
{
   "autoclean": {
      "succeededforwards": {
         "cleaned": 1000000,
         "uncleaned": 40
      }
   }
}

real	3m20.789s
user	0m0.004s
sys	0m0.001s
$ time l3-cli autoclean-once paidinvoices 1
{
   "autoclean": {
      "paidinvoices": {
         "cleaned": 1000000,
         "uncleaned": 0
      }
   }
}

real	6m47.941s
user	0m0.001s
sys	0m0.000s
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: `batching` command to allow database transactions to cross multiple back-to-back JSON commands.
2022-09-22 15:19:46 +02:00
Rusty Russell 8b7a8265e7 libplugin: avoid memmove if we have many outputs to lightningd.
Use linked list, not an array.

```
+   97.89%     0.01%  autoclean  autoclean             [.] next_plan
-   97.08%     0.01%  autoclean  autoclean             [.] json_stream_output_write
   - 97.06% json_stream_output_write
      - 84.29% ld_stream_complete
         - 83.87% tal_arr_remove_
            + 83.71% __memcpy_avx_unaligned_erms (inlined)
      + 12.76% rpc_stream_complete
+   96.59%     0.03%  autoclean  autoclean             [.] tal_arr_remove_
+   96.48%     0.00%  autoclean  libc.so.6             [.] __memcpy_avx_unaligned_erms (inlined)
+   94.98%    94.98%  autoclean  libc.so.6             [.] __memmove_avx_unaligned_erms
+   84.29%     0.01%  autoclean  autoclean             [.] ld_stream_complete
+   12.76%     0.00%  autoclean  autoclean             [.] rpc_stream_complete
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-22 15:19:46 +02:00
Rusty Russell 4d8c321517 libplugin: optimize parsing lightningd rpc responses.
autoclean was using 98% of its time in memmove; we should simply keep
an offset, and memmove when it's empty.  And also, only memmove the
used region, not the entire buffer!

Running on product of giantnodes.py:

	$ time l1-cli autoclean-once failedpays 1
	{
	   "autoclean": {
	      "failedpays": {
	         "cleaned": 26895,
	         "uncleaned": 1000000
	      }
	   }
	}

Before:
	real	20m46.579s
	user	0m0.000s
	sys	0m0.001s
	
After:
	real	2m10.568s
	user	0m0.001s
	sys	0m0.000s

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-22 15:19:46 +02:00
Rusty Russell 540a6e4b99 autoclean: remove per-delete debugging messages.
They slow down benchmarking, which is kind of unfair!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-22 15:19:46 +02:00
Rusty Russell 13e10877de autoclean: add autoclean-once command.
Changelog-Added: Plugins: `autoclean-once` command for a single cleanup.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-22 15:19:46 +02:00
Rusty Russell 399288db3f autoclean: use config variables, not commands.
It's more natural: we will eventually support dynamic config variables,
so this will be quite nice.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: Plugins: `autoclean` can now delete old forwards, payments, and invoices automatically.
2022-09-22 15:19:46 +02:00
Rusty Russell a15f1be5f8 autoclean: clean up listforwards as well.
And take the opportunity to rename l0 and l1 in the tests to the
more natural l1 l2 (since we add l3).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-22 15:19:46 +02:00
Rusty Russell 4cab396cc8 autoclean: handle cleaning of old payments (not just invoices).
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-22 15:19:46 +02:00
Rusty Russell 660c9af1d9 autoclean: allow cleaning of paid invoices too.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-22 15:19:46 +02:00
Rusty Russell 7da51892e8 autoclean: save stats on how much we cleaned.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-22 15:19:46 +02:00
Rusty Russell 17858c9490 lightningd: deprecated "delexpiredinvoice", put functionality in autoclean plugin.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Deprecated: JSON-RPC: `delexpiredinvoice`: use `autoclean-once`.
2022-09-22 15:19:46 +02:00
Rusty Russell bd76a196f5 autoclean: new interface
In preparation for more things being autocleaned.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-22 15:19:46 +02:00
Rusty Russell 41a52929f7 libplugin: handle JSON reply after command freed.
This can happen, and in fact does below in our test_autoclean_once
test where we update the datastore, and return from the cmd.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-22 15:19:46 +02:00
Rusty Russell df4b477e88 keysend: allow extratlvs parameter, even in non-experimental mode.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: `keysend` now has `extratlvs` option in non-EXPERIMENTAL builds.
2022-09-22 17:19:11 +09:30
Rusty Russell ce0f544073 keysend: try to find description in TLV.
"Who needs specs?"  FFS...

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: Protocol: `keysend` will now attach the longest valid text field in the onion to the invoice (so you can have Sphinx.chat users spam you!)
2022-09-22 17:19:11 +09:30
antongalitch 41502be60a Fix a small typo 2022-09-22 10:00:35 +09:30
Christian Decker 759fcb64a8 pay: If the channel_hint matches our allocation allow it
It means we consume the channel completely to the best of our
knowledge, so let that through.

Changelog-Fixed: pay: Squeezed out the last `msat` from our local view of the network
2022-09-21 11:25:47 +02:00
Christian Decker 2def843dce pay: Allow using a channel on equality of estimated capacity
In the case of the local channel we set the estimation to the exact
value spendable, which is important when we want to drain a channel,
because there we actually want to get the last msat.
2022-09-21 11:25:47 +02:00
Christian Decker 5c1de8029a openingd: Add `reserve` to `fundchannel` and `multifundchannel`
Changelog-Added: JSON-RPC: `fundchannel`, `multifundchannel` and `fundchannel_start` now accept a `reserve` parameter to indicate the absolute reserve to impose on the peer.
2022-09-21 11:25:47 +02:00
Rusty Russell 5b58eda748 libplugin: mark the cmd notleak() whenever command_still_pending() called.
This is what we do in lightningd, which makes memleak much more forgiving:
you can hang temporaries off cmd without getting reports of leaks (also
when send_outreq called).

We remove all the notleak() calls in plugins which worked around this!
And avoid multiple notleak labels, since both send_outreq() and
command_still_pending() can be called multiple times.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-19 11:34:42 +09:30
Rusty Russell 701dd3dcef memleak: remove exclusions from memleak_start()
Add memleak_ignore_children() so callers can do exclusions themselves.

Having two exclusions was always such a hack!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-19 11:34:42 +09:30
Rusty Russell 3380f559f9 memleak: simplify API.
Mainly renaming.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-19 11:34:42 +09:30
Rusty Russell 2da5244e83 jsonrpc: make error codes an enum.
This allows GDB to print values, but also allows us to use them in
'case' statements.  This wasn't allowed before because they're not
constant terms.

This also made it clear there's a clash between two error codes,
so move one.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Changed: JSON-RPC: Error code from bcli plugin changed from 400 to 500.
2022-09-19 10:18:55 +09:30
Rusty Russell 42c9aa1a5f libplugin: forget pending requests if associated command freed.
This is usually fine, but without this, commando (another branch!) has
a race:

1. A command has multiple parts.
2. We start sending them out.
3. We get a response, which completes the cmd.
4. We go to send the next one out, but it's been freed.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-16 12:31:45 +09:30
Rusty Russell bf54d6dcf5 libplugin: use proper JSON id for rpc_scan().
And fold start_json_request() and start_json_rpc() into the core
function since it's the only caller.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-16 12:31:45 +09:30
Rusty Russell d360075d22 libplugin: use string ids correctly.
Build them from the command which caused them, and take plugin name
as basename with extension stripped.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-16 12:31:45 +09:30
Rusty Russell ce0b765c96 cln-rpc: allow id to be any token.
Suggested-by: @cdecker
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-16 12:31:45 +09:30
Rusty Russell db89a34135 libplugin: allow lightningd to give us non-numeric ids.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-16 12:31:45 +09:30
Rusty Russell 5d25934865 plugins/Makefile: regenerate plugins list when config changes.
In particular, if rust is enabled/disabled.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-16 12:31:45 +09:30
Otto Sabart 0a856778bc plugins/bcli: load RPC password from stdin instead of an argument
Changelog-Fixed: bcli: don't expose bitcoin RPC password on commandline
2022-09-15 13:24:37 +09:30
Rusty Russell a6d4756d08 commando: make rune alternatives a JSON array.
This avoids having to escape | or &, though we still allow that for
the deprecation period.

To detect deprecated usage, we insist that alternatives are *always*
an array (which could be loosened later), but that also means that
restrictions must *always* be an array for now.

Before:

```
# invoice, description either A or B
lightning-cli commando-rune '["method=invoice","pnamedescription=A|pnamedescription=B"]'
# invoice, description literally 'A|B'
lightning-cli commando-rune '["method=invoice","pnamedescription=A\\|B"]'
```

After:

```
# invoice, description either A or B
lightning-cli commando-rune '[["method=invoice"],["pnamedescription=A", "pnamedescription=B"]]'
# invoice, description literally 'A|B'
lightning-cli commando-rune '[["method=invoice"],["pnamedescription=A|B"]]'
```

Changelog-Deprecated: JSON-RPC: `commando-rune` restrictions is always an array, each element an array of alternatives.  Replaces a string with `|`-separators, so no escaping necessary except for `\\`.
2022-09-14 17:46:43 +02:00
Rusty Russell d57d87ea3a commando: unmangle JSON.
JSON needs to escape \, since it can't be in front of anything unexpected,
so no \|.  So we need to return \\ to \, and in theory handle \n etc.

Changelog-Fixed: JSON-RPC: `commando-rune` now handles \\ escapes properly.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-14 17:46:43 +02:00
Christian Decker f64d755e43 pay: Aggregate `completed_at` in `listpays` and `pay`
The completion of a successful payment is defined as the first
completion of a successful part, hence we just collect the minimum
completion time of successes.

Changelog-Added: JSON-RPC: `pay` and `listpays` now lists the completion time.
2022-09-14 13:14:10 +02:00
niftynei c143914ebf bkpr: migration to delete any duplicate lease_fee entries
Clean up for #5557.

If you've got duplicate 'lease_fee' entries, we delete them!
2022-09-14 15:59:37 +09:30
Rusty Russell b3b5b74069 libplugin: allow NULL calllbacks for jsonrpc_set_datastore.
You often don't care about the reply, so this is quite convenient.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-12 14:00:41 +02:00
Rusty Russell 6cf3d47505 offers: remove backwards-compatiblity invoice_request signatures.
We changed the field name in v0.11.0, so this breaks compat with
v0.10.2.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-12 09:34:52 +09:30
Rusty Russell 136d0c8005 offers: update to remove "vendor" and "timestamp" fields.
Changelog-EXPERIMENTAL: remove "vendor" (use "issuer") and "timestamp" (use "created_at") fields (deprecated v0.10.2).
2022-09-12 09:34:52 +09:30
Rusty Russell 318650a627 listchannels: don't show "htlc_maximum_msat" if channel_update didn't set it.
It was deprecated in v0.10.1, but only one channel on the network
doesn't set it now anyway, and we'll be ignoring that soon.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-12 09:34:52 +09:30
Rusty Russell bcabb3825f Makefile: Revert ba7d4a8f6b (make-schema: don't include tools/fromschema.py in SHASUMS)
1. If the tool changes, you need to regenerate since the output may
   change.

2. This didn't just filter that out, ignored all but the first
   dependency, which made bisecting the bookkeeper plugin a nightmare:
   it didn't regenerate the .po file, causing random crashes.

If we want this, try $(filter-out tools/fromschema.py) instead.  But I
don't think we want that.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-09-08 00:36:51 +03:00
niftynei ea414320a3 build, shadows: fix broken build (no shadows)
Merged a commit that broke everything with shadows, which turned out to
be the bookkeeper code.
2022-08-31 21:40:41 +03:00
Rusty Russell 6fe570820e Remove general shadowed variables.
We shadow local variables in several places: generally, these changes
make the code clearer.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-08-31 12:18:28 +03:00
niftynei 1a25651182 bkpr-recorder: fatal if there's an error with a database statement
We were silently failing when NULLS FIRST wasn't found on older boxes
(running sqlite3 < v3.30.1)
2022-08-16 12:32:08 -05:00
niftynei 256044081f bkpr: remove duplicate log stmt 2022-08-10 10:30:45 -05:00
niftynei 23cd58402a bkpr: create accounts for zero sat channels
we weren't making records for 'missed' accounts that had a zero balance
at snapshot time (if peer opens channel and is unused)

Fixes: #5502
Reported-By: https://github.com/niftynei/cln-logmaid
2022-08-10 10:30:45 -05:00
niftynei 3fcf60ab7c bkpr: track channel rebalances, display in listincome
Track rebalances, and report income events for them.

Previously `listincome` would report:
	- invoice event, debit, outgoing channel
	- invoice_fee event, debit, outgoing channel
	- invoice event, credit, inbound channel

Now reports:
	- rebalance_fee, debit, outgoing channel
	(same value as invoice_fee above)

Note: only applies on channel events; if a rebalance falls to chain
we'll use the older style of accounting.

Changelog-None
2022-08-09 11:57:18 +09:30
Christian Decker da0b651803 pay: Use safe list traversal when completing suspended payments
When traversing the list we call `command_finished` which modifies the
list we are traversing. This ensures we don't end up advancing in the
list iteration.

Reported-by: Rusty Russell <@rustyrussell>
2022-08-08 11:52:29 -05:00
Christian Decker 65a449e2c3 pay: Remove use-after-free bug
Technically this is a use-after-free since `command_finished` frees
the `cmd` which is also the parent of `p`, so reset it early. All
paths lead to `command_finished` so setting it early is ok.

Reported-by: Rusty Russell <@rustyrussell>
2022-08-08 11:52:29 -05:00
Christian Decker 093933b14d pay: Do not replay results against payments that were not suspended
Suspended payments now have the same groupid as the actual attempt,
this allows us to identify pay calls that were suspended due to us and
terminate only those.

Changelog-Fixed pay: Fixed a crash when `pay` was called multiple times while an attempt was already in progress.
2022-08-08 11:52:29 -05:00
Christian Decker aca9c7d49c pay: Annotate suspended payments with the groupid they mirror
This should prevent us from accidentally completing a payment twice,
when replaying the result of an actual attempt against pay call that
was suspended due to it still being pending.
2022-08-08 11:52:29 -05:00
Christian Decker 2632cddfe4 pay: Fix a memory leak when retrying getroute 2022-08-04 11:14:45 -05:00
niftynei dfa325dc4d bkpr: make unit tests not fail if !HAVE_SQLITE3
We rely on sqlite3 being present to run unit tests for some bookkeeper
tests; here we effectively disable these tests if not available

Fixes report in #4928
Reported-By: @whitslack
2022-08-02 11:52:57 +09:30
Rusty Russell 2971b2af79 bkpr: insert obscure 60s pop references.
The initial snapshots on an already-running lightningd are expected to
be unbalanced, but this shouldn't cause users to long for the green,
green grass of home.

This controls the Art of Noise.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-08-01 09:01:08 -07:00
niftynei 3445882ee4 bkpr: use long-uint not size_t for time_t
Reported-By: @endothermicdev
2022-07-31 21:53:05 +09:30
niftynei 4e503f7d0a bkpr/listpeeers: add lease_fees back to funds; separate out in listpeers
First, how we record "our_funds" and then apply pushes vs lease_fees
(for liquidity ad buys/sales) was exactly opposite.

For pushes we were reporting the total funded into the channel, with the
push representing how much we'd later moved to the peer.

For lease_fees we were rerporting the total in the channel, with the
push representing how much was already moved to the peer.

We fix this (from a view perspective) by re-adding lease fees to what's
reported in the channel funding totals. Since this is now new behavior
(for leased channel values), we added new fields so we can take the old
field names thru a deprecation cycle.

We also make it possible to differentiate btw a push and a lease_fee
(before they were all the same), by adding to new fields to `listpeers`:
`fee_paid_msat` and `fee_rcvd_msat`.

This allows us to avoid math in the bookkeeper, instead we just pick
the numbers out directly and record them.

Fixes #5472

Changelog-Added: JSON-RPC: `listpeers` now has a few new fields for `funding` (`remote_funds_msat`, `local_funds_msat`, `fee_paid_msat`, `fee_rcvd_msat`).
Changelog-Deprecated: JSON-RPC: `listpeers`.`funded` fields `local_msat` and `remote_msat` are now deprecated.
2022-07-31 21:53:05 +09:30
William Casarin 10d66c25c4 commando-rune: show warning when creating runes with no restrictions
Changelog-Added: Show warning when creating runes with no restrictions
Signed-off-by: William Casarin <jb55@jb55.com>
2022-07-29 08:46:14 -07:00
niftynei 6e9af1ef3e bkpr: cleanup csv_safe_str 2022-07-28 12:08:18 +09:30
niftynei c83c1521ce memleak: throw away things when we're done with them
memleak was complaining about dangling refs; they were all allocated off
of `cmd` but not technically unreachabe from any in-context memory.

Instead we move things over to tmpctx to clean up (in the paths where
we're going to move the objects out of reach via intermediate RPC call)

ALSO: cleans up unused param in `lookup_invoice_desc`

lightningd-1 2022-07-23T19:17:11.192Z **BROKEN** plugin-bookkeeper: MEMLEAK: 0x1511f68
lightningd-1 2022-07-23T19:17:11.194Z **BROKEN** plugin-bookkeeper:   label=plugins/bkpr/recorder.c:1048:struct account
lightningd-1 2022-07-23T19:17:11.194Z **BROKEN** plugin-bookkeeper:   backtrace:
lightningd-1 2022-07-23T19:17:11.194Z **BROKEN** plugin-bookkeeper:     ccan/ccan/tal/tal.c:442 (tal_alloc_)
lightningd-1 2022-07-23T19:17:11.194Z **BROKEN** plugin-bookkeeper:     plugins/bkpr/recorder.c:1048 (stmt2account)
lightningd-1 2022-07-23T19:17:11.194Z **BROKEN** plugin-bookkeeper:     plugins/bkpr/recorder.c:1109 (find_account)
lightningd-1 2022-07-23T19:17:11.196Z **BROKEN** plugin-bookkeeper:     plugins/bkpr/bookkeeper.c:1606 (parse_and_log_channel_move)
lightningd-1 2022-07-23T19:17:11.197Z **BROKEN** plugin-bookkeeper:     plugins/bkpr/bookkeeper.c:1713 (json_coin_moved)
lightningd-1 2022-07-23T19:17:11.198Z **BROKEN** plugin-bookkeeper:     plugins/libplugin.c:1421 (ld_command_handle)
lightningd-1 2022-07-23T19:17:11.198Z **BROKEN** plugin-bookkeeper:     plugins/libplugin.c:1491 (ld_read_json_one)
lightningd-1 2022-07-23T19:17:11.199Z **BROKEN** plugin-bookkeeper:     plugins/libplugin.c:1511 (ld_read_json)
lightningd-1 2022-07-23T19:17:11.199Z **BROKEN** plugin-bookkeeper:     ccan/ccan/io/io.c:59 (next_plan)
lightningd-1 2022-07-23T19:17:11.199Z **BROKEN** plugin-bookkeeper:     ccan/ccan/io/io.c:407 (do_plan)
lightningd-1 2022-07-23T19:17:11.199Z **BROKEN** plugin-bookkeeper:     ccan/ccan/io/io.c:417 (io_ready)
lightningd-1 2022-07-23T19:17:11.199Z **BROKEN** plugin-bookkeeper:     ccan/ccan/io/poll.c:453 (io_loop)
lightningd-1 2022-07-23T19:17:11.199Z **BROKEN** plugin-bookkeeper:     plugins/libplugin.c:1708 (plugin_main)
lightningd-1 2022-07-23T19:17:11.199Z **BROKEN** plugin-bookkeeper:     plugins/bkpr/bookkeeper.c:1812 (main)
lightningd-1 2022-07-23T19:17:11.200Z **BROKEN** plugin-bookkeeper:     ../csu/libc-start.c:308 (__libc_start_main)
lightningd-1 2022-07-23T19:17:11.200Z **BROKEN** plugin-bookkeeper:   parents:
lightningd-1 2022-07-23T19:17:11.200Z **BROKEN** plugin-bookkeeper:     plugins/libplugin.c:1378:struct command
lightningd-1 2022-07-23T19:17:11.200Z **BROKEN** plugin-bookkeeper: MEMLEAK: 0x15305b8
lightningd-1 2022-07-23T19:17:11.200Z **BROKEN** plugin-bookkeeper:   label=plugins/bkpr/bookkeeper.c:1643:enum mvt_tag[]
lightningd-1 2022-07-23T19:17:11.200Z **BROKEN** plugin-bookkeeper:   backtrace:
lightningd-1 2022-07-23T19:17:11.200Z **BROKEN** plugin-bookkeeper:     ccan/ccan/tal/tal.c:442 (tal_alloc_)
lightningd-1 2022-07-23T19:17:11.201Z **BROKEN** plugin-bookkeeper:     ccan/ccan/tal/tal.c:471 (tal_alloc_arr_)
lightningd-1 2022-07-23T19:17:11.201Z **BROKEN** plugin-bookkeeper:     plugins/bkpr/bookkeeper.c:1643 (parse_tags)
lightningd-1 2022-07-23T19:17:11.201Z **BROKEN** plugin-bookkeeper:     plugins/bkpr/bookkeeper.c:1686 (json_coin_moved)
lightningd-1 2022-07-23T19:17:11.201Z **BROKEN** plugin-bookkeeper:     plugins/libplugin.c:1421 (ld_command_handle)
lightningd-1 2022-07-23T19:17:11.201Z **BROKEN** plugin-bookkeeper:     plugins/libplugin.c:1491 (ld_read_json_one)
lightningd-1 2022-07-23T19:17:11.201Z **BROKEN** plugin-bookkeeper:     plugins/libplugin.c:1511 (ld_read_json)
lightningd-1 2022-07-23T19:17:11.201Z **BROKEN** plugin-bookkeeper:     ccan/ccan/io/io.c:59 (next_plan)
lightningd-1 2022-07-23T19:17:11.201Z **BROKEN** plugin-bookkeeper:     ccan/ccan/io/io.c:407 (do_plan)
lightningd-1 2022-07-23T19:17:11.202Z **BROKEN** plugin-bookkeeper:     ccan/ccan/io/io.c:417 (io_ready)
lightningd-1 2022-07-23T19:17:11.202Z **BROKEN** plugin-bookkeeper:     ccan/ccan/io/poll.c:453 (io_loop)
lightningd-1 2022-07-23T19:17:11.202Z **BROKEN** plugin-bookkeeper:     plugins/libplugin.c:1708 (plugin_main)
lightningd-1 2022-07-23T19:17:11.203Z **BROKEN** plugin-bookkeeper:     plugins/bkpr/bookkeeper.c:1812 (main)
lightningd-1 2022-07-23T19:17:11.204Z **BROKEN** plugin-bookkeeper:     ../csu/libc-start.c:308 (__libc_start_main)
lightningd-1 2022-07-23T19:17:11.204Z **BROKEN** plugin-bookkeeper:   parents:
lightningd-1 2022-07-23T19:17:11.204Z **BROKEN** plugin-bookkeeper:     plugins/libplugin.c:1378:struct command
lightningd-1 2022-07-23T19:17:11.204Z **BROKEN** plugin-bookkeeper: MEMLEAK: 0x1508da8
lightningd-1 2022-07-23T19:17:11.204Z **BROKEN** plugin-bookkeeper:   label=plugins/bkpr/bookkeeper.c:1568:struct channel_event
lightningd-1 2022-07-23T19:17:11.204Z **BROKEN** plugin-bookkeeper:   backtrace:
lightningd-1 2022-07-23T19:17:11.204Z **BROKEN** plugin-bookkeeper:     ccan/ccan/tal/tal.c:442 (tal_alloc_)
lightningd-1 2022-07-23T19:17:11.204Z **BROKEN** plugin-bookkeeper:     plugins/bkpr/bookkeeper.c:1568 (parse_and_log_channel_move)
lightningd-1 2022-07-23T19:17:11.204Z **BROKEN** plugin-bookkeeper:     plugins/bkpr/bookkeeper.c:1713 (json_coin_moved)
lightningd-1 2022-07-23T19:17:11.205Z **BROKEN** plugin-bookkeeper:     plugins/libplugin.c:1421 (ld_command_handle)
lightningd-1 2022-07-23T19:17:11.205Z **BROKEN** plugin-bookkeeper:     plugins/libplugin.c:1491 (ld_read_json_one)
lightningd-1 2022-07-23T19:17:11.205Z **BROKEN** plugin-bookkeeper:     plugins/libplugin.c:1511 (ld_read_json)
lightningd-1 2022-07-23T19:17:11.205Z **BROKEN** plugin-bookkeeper:     ccan/ccan/io/io.c:59 (next_plan)
lightningd-1 2022-07-23T19:17:11.205Z **BROKEN** plugin-bookkeeper:     ccan/ccan/io/io.c:407 (do_plan)
lightningd-1 2022-07-23T19:17:11.205Z **BROKEN** plugin-bookkeeper:     ccan/ccan/io/io.c:417 (io_ready)
lightningd-1 2022-07-23T19:17:11.205Z **BROKEN** plugin-bookkeeper:     ccan/ccan/io/poll.c:453 (io_loop)
lightningd-1 2022-07-23T19:17:11.205Z **BROKEN** plugin-bookkeeper:     plugins/libplugin.c:1708 (plugin_main)
lightningd-1 2022-07-23T19:17:11.205Z **BROKEN** plugin-bookkeeper:     plugins/bkpr/bookkeeper.c:1812 (main)
lightningd-1 2022-07-23T19:17:11.206Z **BROKEN** plugin-bookkeeper:     ../csu/libc-start.c:308 (__libc_start_main)
lightningd-1 2022-07-23T19:17:11.206Z **BROKEN** plugin-bookkeeper:   parents:
lightningd-1 2022-07-23T19:17:11.206Z **BROKEN** plugin-bookkeeper:     plugins/libplugin.c:1378:struct command
2022-07-28 12:08:18 +09:30
niftynei 2f72bbbbc5 nit: send_outreq returns &pending, no need to call sep command 2022-07-28 12:08:18 +09:30
niftynei e048292fdf bkpr-zeroconf: Zeroconfs will emit 'channel_proposed' event
Keep the accounts as an 'append only' log, instead we move the marker
for the 'channel_open' forward when a 'channel_open' comes out.

We also neatly hide the 'channel_proposed' events in 'inspect' if
there's a 'channel_open' for that same event.

If you call inspect before the 'channel_open' is confirmed, you'll see
the tag as 'channel_proposed', afterwards it shows up as
'channel_open'. However the event log rolls forward -- listaccountevents
will show the correct history of the proposal then open confirming (plus
any routing that happened before the channel confirmed).
2022-07-28 12:08:18 +09:30
niftynei 30aa1d79fb bkpr: for zerconfs, we still wanna know you're opening a channel
We need a record of the channel account before you start sending
payments through it. Normally we don't start allowing payments to be
sent until after the channel has locked in but zeroconf does away with
this assumption.

Instead we push out a "channel_proposed" event, which should only show
up for zeroconfs.
2022-07-28 12:08:18 +09:30
Rusty Russell 305a238810 plugins/Makefile: put bitcoin/chainparams.o in PLUGIN_COMMON_OBJS since everyone needs it.
This was originally done as part of the bookkeeper introduction, but it deserves its
own patch (and that one didn't remove the bitcoin/chainparams.o from the individual
requirements lines).

Suggested-by: @niftynei
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-28 12:08:18 +09:30
niftynei 71c03bc082 bkpr: Add an option to set the database to something else (postgres)
`lightningd` has an option --wallet that lets you supply a database dsn
string to connect to a sqlite3/postgres database that's hosted/stored
elsewhere.

This adds the `--bookkeeper-db` option which does the same, except for
the bookkeeping data for a node!

Note that the default is to go in the `lightning-dir` in a database
called `accounts.sqlite3`
2022-07-28 12:08:18 +09:30
niftynei e5d3ce3b1f bkpr incomestmt: properly escape things for the CSVs
First off, when we pull data out of JSON, unescape it so we don't end up
with extraneous escapes in our bookkeeping data. I promise, it's worth
it.

Then, when we print descriptions out to the csvs, we gotta wrap
everything in quotes... but also we have to change all the double-quotes
to singles so that adding the quotes doesn't do anything untoward.

We also just pass it thru json_escape to get rid of linebreaks etc.

Note that in the tests we do a byte comparison instead of converting the
CSV dumps to strings because python will escape the strings on
conversion...
2022-07-28 12:08:18 +09:30
niftynei 5146baa00b bkpr csvs: koinly + cointracker only accept fees on the same line
So we print out invoice fees on the same line for those CSVs! This means
we have to do a little bit of gymnastics (but not too bad):
	- we save the fee amount onto the income event now so we can use
it later
	- we ignore every "invoice_fee" event for the koinly/cointracker

Note that since we're not skipping income events in the loops we also
move the newline character to the start of every `_entry` function so
skipped records dont incur empth lines.

Changelog-Added: bkpr: print out invoice fees on the same line for `koinly` and `cointracker` csv types
2022-07-28 12:08:18 +09:30
niftynei 352b419755 bkpr: save invoice description data to the database and display it
It'll be really nice to be able to read description data about an
invoice, if we've got it!
2022-07-28 12:08:18 +09:30
niftynei 2d22bab879 bkpr: fetch originating account, if exists, and make sure is populated
It's possible we'll get an "external" event for an account/channel and
then try to do close checks on it and it'll bomb out because we didn't
go look up the originating account to make sure that that had open info

Now, we make sure and do that when we hear about an originating account
2022-07-28 12:08:18 +09:30
niftynei 55e15c5f10 bkpr: correctly pass in command for `jsonrpc_request_start`
We weren't passing the command, which meant that it wasn't getting
populated correctly.

We do that now, it fixes some crashes
2022-07-28 12:08:18 +09:30
niftynei 67ce0ee3b2 bkpr: prevent crash when updating same account all at once
If two events for the same (unlogged) account come in and get run
through the "lookup peer" code, we should anticipate that.

We do two things here:
	- one, if it's a duplicate "event" to create the channel open
	  we check for that and just exit early
	- two, we were using a copy of the account that was
	  fetched/pulled from before the RPC ran, so instead we
	  just re-pull the most up to date account info for the
	  close checks.

This fixes the crash I was getting in re-running these things
2022-07-28 12:08:18 +09:30
niftynei 38eb95ffee bkpr: more logging 2022-07-28 12:08:18 +09:30
niftynei 9346158290 bkpr: new method, "is_external_account"
Utility method to figure out if an account is "external"
2022-07-28 12:08:18 +09:30
niftynei 97204d6e0a bkpr: duplicate the name, dont steal it 2022-07-28 12:08:18 +09:30
niftynei 0617690981 coin_mvt/bkpr: add "stealable" tag to stealable outputs
If we expect further events for an onchain output (because we can steal
it away from the 'external'/rightful owner), we mark them.

This prevents us from marking a channel as 'onchain-resolved' before
all events that we're interested in have actually hit the chain.

Case that this matters:
Peer publishes a (cheating) unilateral close and a timeout htlc (which
we can steal).
We then steal the timeout htlc.

W/o the stealable flag, we'd have marked the channel as resolved when
the peer published the timeout htlc, which is incorrect as we're still
waiting for the resolution of that timeout htlc (b/c we *can* steal it).
2022-07-28 12:08:18 +09:30
niftynei c1cef773ca bkpr: make sure there's always at least on difference in blockheights
We can't divide by zero, so make sure it's always 1 (with a small loss
of precision for other cases, ce la vie)
2022-07-28 12:08:18 +09:30
niftynei 0c2b43b6b2 bkpr: add more data to listaccountevents printout 2022-07-28 12:08:18 +09:30
niftynei d72033882f bkpr: check for channel resolution for any "originated" event
We were failing to mark channels as resolved b/c we weren't using later
events to external (but originated from this account) events as signals
to run the channel resolution check.

This fixes that, and adds a test.
2022-07-28 12:08:18 +09:30
niftynei cf8b30d2e8 bkpr: print more info in bkpr-listbalances 2022-07-28 12:08:18 +09:30
niftynei 3dcfd2d0e4 bkpr: account name is required for bkpr-inspect 2022-07-28 12:08:18 +09:30
niftynei 563910e667 bkpr: add docs, change names to 'bkpr-*'
Adds schema definitions and manpages for bkpr- commands; also renames
the commands to all start with 'bkpr-', so they're easier to identify/
make runes about.
2022-07-28 12:08:18 +09:30
niftynei e2ef44c043 bkpr: add 'msat' suffix to all msat denominated fields
Makes our json schema parsing work as expected.
2022-07-28 12:08:18 +09:30
niftynei 2b3ef37590 bkpr: don't use a minus in a sql stmt
Avoid rounding errors in sql by doing it in code.
2022-07-28 12:08:18 +09:30
niftynei a45da63280 bkpr: pass the node_id over for channel_opens, add to account
it's nice to know what node your channel was opened with. in theory we
could use listpeers to merge the data after the fact, except that
channels disappear after they've been closed for a bit. it's better to
just save the info.

we print it out in `listbalances`, as that's a great place account level
information
2022-07-28 12:08:18 +09:30
niftynei a3d82d5a01 bkpr: exclude non-wallet events in the balance snapshot
Anchor outputs are ignored by the clightning wallet, but we keep track
of them in the bookkeeper. This causes problems when we do the balance
checks on restart w/ the balance_snapshot -- it results in us printing
out a journal_entry to 'get rid of' the anchors that the clightning node
doesnt know about.

Instead, we mark some outputs as 'ignored' and exclude these from our
account balance sums when we're comparing to the clightning snapshot.
2022-07-28 12:08:18 +09:30
niftynei fec8186413 bkpr: get rid of crash in `listincome`
Our consolidate fees had a crash bug (and was pretty convoluted). This
makes it less convoluted and resolves the crash.

The only kinda meh thing is that we have to look up the most recent
timestamp data for the onchain fee entry separately, because of the way
SQL sums work.
2022-07-28 12:08:18 +09:30
niftynei 10e58a3788 nit,bkpr: add a note about what the tag was to this printout
Makes it much easier to debug when something goes wrong!
2022-07-28 12:08:18 +09:30
niftynei e7ed196f87 bkpr: separate the invoice_fees from the invoice paid
For income events, break out the amount paid in routing fees vs the
total amount of the *invoice* that is paid.

Also printout these fees, when available, on listaccountevents
2022-07-28 12:08:18 +09:30
niftynei 91ebddeb78 bkpr: actually fill in the current blockheight for `channelsapy`
I had hardcoded something for the tests, but really we want this to be
dynamically fetched from lightningd via `getinfo`.

This does the trick!
2022-07-28 12:08:18 +09:30
niftynei ee47715a1b bkpr: command to calculate some APYs/stats on channel routing fees
Computes some stats from the net routed fees etc

```
{
   "channel_apys": [
      {
         "account": "7de277250f8003c35378c1eb20aacf8fa6a69dd4bb22077266329a9ad812cd5d",
         "routed_out": "2000msat",
         "routed_in": "125100101msat",
         "lease_fee_paid": "0msat",
         "lease_fee_earned": "670000msat",
         "pushed_out": "0msat",
         "pushed_in": "0msat",
         "our_start_balance": "100670000msat",
         "channel_start_balance": "1100670000msat",
         "fees_out": "0msat",
         "fees_in": "10100101msat",
         "utilization_out": "0.0002%",
         "utilization_out_initial": "0.0020%",
         "utilization_in": "11.3658%",
         "utilization_in_initial": "12.5100%",
         "apy_out": "0.0000%",
         "apy_out_initial": "0.0000%",
         "apy_in": "3203.3924%",
         "apy_in_initial": "3525.8779%",
         "apy_total": "3203.3924%",
         "apy_total_initial": "3203.3924%",
         "apy_lease": "8.7014%"
      },
      {
         "account": "b71937a02eb7694d946c311297ca2da454057c5c3e97ac67500739cc2afbc0c5",
         "routed_out": "110000000msat",
         "routed_in": "0msat",
         "lease_fee_paid": "670000msat",
         "lease_fee_earned": "0msat",
         "pushed_out": "0msat",
         "pushed_in": "0msat",
         "our_start_balance": "4000000000msat",
         "channel_start_balance": "4100670000msat",
         "fees_out": "10100101msat",
         "fees_in": "0msat",
         "utilization_out": "2.6825%",
         "utilization_out_initial": "2.7500%",
         "utilization_in": "0.0000%",
         "utilization_in_initial": "0.0000%",
         "apy_out": "2579.4892%",
         "apy_out_initial": "2644.4084%",
         "apy_in": "0.0000%",
         "apy_in_initial": "0.0000%",
         "apy_total": "2579.4892%",
         "apy_total_initial": "2579.4892%"
      },
      {
         "account": "net",
         "routed_out": "110002000msat",
         "routed_in": "125100101msat",
         "lease_fee_paid": "670000msat",
         "lease_fee_earned": "670000msat",
         "pushed_out": "0msat",
         "pushed_in": "0msat",
         "our_start_balance": "4100670000msat",
         "channel_start_balance": "5201340000msat",
         "fees_out": "10100101msat",
         "fees_in": "10100101msat",
         "utilization_out": "2.1149%",
         "utilization_out_initial": "2.6825%",
         "utilization_in": "2.4052%",
         "utilization_in_initial": "11.3658%",
         "apy_out": "677.8788%",
         "apy_out_initial": "859.8297%",
         "apy_in": "677.8788%",
         "apy_in_initial": "3203.3924%",
         "apy_total": "1355.7575%",
         "apy_total_initial": "1355.7575%",
         "apy_lease": "0.2122%"
      }
   ]
}
```
2022-07-28 12:08:18 +09:30
niftynei c05900c676 bkpr: add option --bookkeeper-dir
Allow setting custom directory for bookkeeper's database
and default directory for any csv file creation
2022-07-28 12:08:18 +09:30
niftynei 12b5c06219 bkpr: add 'start_time' and 'end_time' to `listincome`
Add ability to filter results by timestamp.

Note that "start_time" is everything *after* that timestamp; and
"end_time" is everything *up to and including* that timestamp.
2022-07-28 12:08:18 +09:30
niftynei a0b34066e0 bkpr: add `dumpincomecsv` command
Prints out the `listincome` events as a CSV formatted file

Current csv_format options:

- koinly
- cointracker
- harmony (https://github.com/harmony-csv/harmony)
- quickbooks*

*Quickbooks expects values in 'USD', whereas we print values out
in <currency> (will be noted in the Description field). This won't work
how you'd expect -> you might need to do some conversion etc before
uploading it.

All amounts emitted as 'btc' w/ *11* decimals.
2022-07-28 12:08:18 +09:30
niftynei a7b7ea5d49 bkpr: add a 'consolidate-fees' flag to the income stmt
Defaults to true. This is actually what you want to see -- the fees for
an account's txid collapsed into a single entry.
2022-07-28 12:08:18 +09:30
niftynei 83c6cf25d2 bkpr: 'to_miner' spends are considered terminal
This is a rare case where we RBF the output of a penalty until it no
longer has an output value we can reclaim. We ignore the txid for these
events when closing a channel.
2022-07-28 12:08:18 +09:30
niftynei 1dd52ba003 bkpr: mark external deposits (withdraws) via blockheight when confirmed
We issue events for external deposits (withdrawals) before the tx is
confirmed in a block. To avoid double counting these, we don't count
them as confirmed/included until after they're confirmed. We do this
by keeping the blockheight as zero until the withdraw for the input for
them comes through.

Note that since we don't have any way to note when RBF'd withdraws
aren't eligible for block inclusion anymore, we don't really have a good
heuristic to trim them. Which is fine, they *will* show up in account
events however.
2022-07-28 12:08:18 +09:30
niftynei 593f1e7365 bkpr: add a 'listincome' event
list the income/expense events for a node.
2022-07-28 12:08:18 +09:30
niftynei 595c52f611 bkpr: add timestamp filters to event lists 2022-07-28 12:08:18 +09:30
niftynei 462fa20c17 bkpr: move json_to functions to respective type files 2022-07-28 12:08:18 +09:30
niftynei 5f41d9247e bkpr: properly account for onchain fees for channel closes
onchain fees are weird at channel close because:

- you may be missing an trimmed htlc (which went to fees)
- the balance from close may have been rounded (msats cant land on
chain)
- the close might have been a past state and you've actually
  ended up with more money onchain than you had in the channel. wut

This commit accounts for all of this appropriately, with some tests.

channel_close.debit should equal onchain_fee.credit (for that txid)
plus sum(chain_event.credit [wallet/channel_acct]).

In the penalty case, channel_close.debit becomes channel_close.debit +
penalty_adj.debit, i.e.

	channel-close.debit + (penalty_adj.debit) =
		onchain_fee.credit
	      + sum(chain_event.credit [wallet/channel_acct])
2022-07-28 12:08:18 +09:30
niftynei 8f869ade3c bkpr: use chain_closed count to do mark account closed
More robust than inspecting the returned utxo treeset -- if the tree is
complete but missing outputs we'll get the wrong result
2022-07-28 12:08:18 +09:30
niftynei 7d5a0988db bkpr: save closed_count for account, when known
When the closing channel event tells you how many outputs to expect,
save it to the account so we can verify the account is fully closed/onchain.
2022-07-28 12:08:18 +09:30
niftynei 7b6956e4f9 bkpr: annotate an account with the block at which it's been resolved
Due to the way that onchain channel closes work, there is often a delay
between when the funding output is spent and the channel is considered
'closed'.

Once *every* downstream utxo of a channel has landed on chain, we
annotate the account with the resolving blockheight.

This gives us some insight into whether or not the chain fees etc of a
channel are going to update further and allows for a natural marker to
prune data (at a later date)
2022-07-28 12:08:18 +09:30
niftynei b33bd05524 bkpr: add an 'inspect' command to the bookkeeper
Pass in an account id, get out a utxo chain of the channel open and
close (and any other related htlc txs etc).

Note that this prints all wallet deposits that occurred in any of the
tx's that touched this channel.

This is fine and expected for any tx that's not the open; when
considerig the tx open event, the wallet deposit that's present is
typically the change. If there were other channels opened in the same tx
then the change won't match up exactly...
2022-07-28 12:08:18 +09:30
niftynei fea33221d4 bkpr: once we get channel_opens, we might need to update the fee records
Also note that we might have ignored/missed fees for the channel
closed's spending txid, so we attempt to update those as well.

Backfilling for missed events is a beast.
2022-07-28 12:08:18 +09:30
niftynei 8827423556 bkpr: account for pushed amounts and record the output_value
We need the total output_value, and we can figure this out if we look at
the remote amount also.

We also need to account for the pushed/leased amount, as for leased
channels this really messes with onchain fee calculations.

We copy basically the events that lightningd emits for leased channels:
an open event with the 'lease fee' (pushed?) amount credited to the side
that made the lease/push; then an in-channel event to effectively push
the pushed/leased amount over to the peer it was paid to.

We run the journal entry info after this, so the journal snapshot will
take the pushed amount into account when figuring out what the further
missed in-channel payments were (if any)
2022-07-28 12:08:18 +09:30
niftynei 2385d8d613 bkpr: listbalances, rename 'account_id' => 'account' 2022-07-28 12:08:18 +09:30
niftynei f767e41755 bkpr: listbalances, skip the external account
it's essentialy meaningless
2022-07-28 12:08:18 +09:30
niftynei 791c1a7526 bkpr: cleanup wallet fee entries if decide they belong to a channel
Because we update the onchain_fee table every time a new event comes in,
it's possible (and in fact happens) that we get a wallet
withdraw/deposit event and then the channel open output event.

What we'd expect in this case is that the fees for the tx were credited
to the channel's account, not the wallet. But since we got the two
in/out events first, the fees were accumulated there first.

Our existing logic will add the channel's fees correctly, but we weren't
zeroing out the wallet's balance once it'd been determined that they
were 'ineligble' so to speak, for being included in the fees that round.
2022-07-28 12:08:18 +09:30
niftynei 08d8de8e45 bkpr: don't try to add fees if this tx didn't touch any accts
Dividing by zero causes problems.
2022-07-28 12:08:18 +09:30
niftynei 8c3347d129 bkpr: dont count fees for channel closes if we're not the opener
The opener pays fees on close, so if we're not the opener we should
ignore any fees on the closing tx.
2022-07-28 12:08:18 +09:30
niftynei ee8c04a63a bkpr: update tests for wallet/external onchain fees
Working as intended; had a bool switched etc
2022-07-28 12:08:18 +09:30
niftynei 2a3875204a bkpr: parse the 'originating_account' field, save to event
It's useful to know which account an 'external' event impacted, so we
save this data now
2022-07-28 12:08:18 +09:30
niftynei 307ea93592 bkpr: invert channel + chain event printouts
We now add chain events for starting channel balances, so print these
out with chain first then channel events.

Makes it less confusing for channel lease fee events.
2022-07-28 12:08:18 +09:30
niftynei 8089f246c1 bkpr: use tags not str for tag originations 2022-07-28 12:08:18 +09:30
niftynei a1d72cef06 bkpr: add a new command `listaccountevents`
Prints all the events for the requested account. If no account
requested, prints out all the events. Ordered by timestamp.

Changelog-Added: bookkeeper: new command `listaccountevents`
2022-07-28 12:08:18 +09:30
niftynei 8039fde5ab bkpr: if we're missing info about an account, add in journal entry
There's two situations where we're missing info.

One is we get a 'channel_closed' event (but there's no 'channel_open')

The other is a balance_snapshot arrives with information about accounts
that doesn't match what's already on disk. (For some of these cases, we
may be missing 'channel_open' events..)

In the easy case (no channel_open missing), we just figure out what the
2022-07-28 12:08:18 +09:30
niftynei ccffac8208 bkpr: put the account name on the event
When we print events out, we need to know the account name. This makes
our lookup a lot easier, since we just pull it out from the database
every time we query for these.
2022-07-28 12:08:18 +09:30
niftynei d943e5e85c bkpr: use pointer for payment_id for channel events
sometimes these are null!
2022-07-28 12:08:18 +09:30
niftynei 8ec35b7eb1 bkpr: turns out these fields are optional
pushes and channel leases don't provide fees or payment_id info
2022-07-28 12:08:18 +09:30
niftynei 899d54edd0 bkpr: have onchain_fee records be write-only, don't update in place
One really rough thing about how we did onchain fees is that the records update
every time a new event comes in.

The better way to do this is to create new entries for every adjustment,
so that reconciliation between printouts isn't a misery.

We add a timestamp and `update_count` to these records, so you can
roughly order them now (and have a good idea of the last time an event
that updated an onchain_fee occurred).
2022-07-28 12:08:18 +09:30
niftynei 29c6884468 bkpr: add journal entry for offset account balances; report listbalances
When the node starts up, it records missing/updated account balances
to the 'channel' events... which is kinda fucked for wallet + external
events now that i think about it but these are all treated the same
anyway so it's fine.

This is the magic piece that lets your bookkeeping data startup ok on an
already running/established node.
2022-07-28 12:08:18 +09:30
niftynei b7d85f1d0b bkpr: wire up our chain fee accting to chain event reception
When we get a chain event, check to see if this updates any onchain fee
records that we have.
2022-07-28 12:08:18 +09:30
Rusty Russell 721ceb7519 patch db-fatal-plugin_err.patch 2022-07-28 12:08:18 +09:30
niftynei 351dc17e46 bkpr: add bookkeeper to PLUGINS list
This makes it start up automatically
2022-07-28 12:08:18 +09:30
niftynei dc113d0a3f bkpr: create onchain fee records for events
clightning doesn't give us any info about onchain fees (how could it?
it only knows about utxo object levels, and doesn't keep track of
how/when those are all related)

Instead, we keep running totals of the onchain fees for utxos. This
implements the master method for accounting for them, plus includes
tests to account for channel opens (across two accounts) as well as a
htlc-tx channel close.

Missing: we don't currently emit an event from cln for `withdraw`
initiated removal of funds, so the accounting for wallet -> external
funds is a bit janky. We don't account for the fees on these
transactions since we don't have the resulting 'external' event to
register them against!
2022-07-28 12:08:18 +09:30
niftynei c12cd99039 bkpr: tests for db crud 2022-07-28 12:08:18 +09:30
niftynei b08ccfec1e bookkeeper: initial crud (no tests) 2022-07-28 12:08:18 +09:30
niftynei cd95d91ed5 bkpr-tests: first test of plugin bkpr database
First test of bookkeeper database, for just the migrations.
2022-07-28 12:08:18 +09:30
niftynei fb951dbbd6 bkpr: first attempt at database code for accounting
A database scheme and first attempt at drivers for the bookkeeper
database.

Also moves bookkeeper plugin into its own subdirectory
2022-07-28 12:08:18 +09:30
niftynei 1a3bfc479f bookkeep: first commit, stub of new plugin
Will manage bookkeeping for cln
2022-07-28 12:08:18 +09:30
niftynei 79a76a96f7 v2open: dont rely on ordering of interprocess messages
Originally I (incorrectly?) assumed that since TX_COMMITMENT_SIGNED
always came before TX_SIGNATURES, we would always receive a response
from openchannel_update (w/ commitment_secured = true) before getting
notification of receipt of the peer's signatures.

But it's observable in the logs of hung tests that this in fact is a
wrong assumption -- the notification for the tx_sigs arrives at our
spender plugin before the callback from our openchannel_update RPC.

This mis-ordering causes a hang.

Luckily we're pretty much setup to handle this race already w/ states
etc, minus actually calling the method advance the plot in case we're
ready.

2022-07-26T05:37:59.4529095Z lightningd-1 2022-07-26T05:10:07.395Z DEBUG   035d2b1192dfba134e10e540875d366ebc8bc353d5aa766b80c090b39c3a5d885d-dualopend-chan#2: peer_in WIRE_COMMITMENT_SIGNED
2022-07-26T05:37:59.4530452Z lightningd-1 2022-07-26T05:10:07.396Z DEBUG   035d2b1192dfba134e10e540875d366ebc8bc353d5aa766b80c090b39c3a5d885d-hsmd: Got WIRE_HSMD_VALIDATE_COMMITMENT_TX
2022-07-26T05:37:59.4530719Z lightningd-1 2022-07-26T05:10:07.396Z DEBUG   hsmd: Client: Received message 35 from client
2022-07-26T05:37:59.4531386Z lightningd-1 2022-07-26T05:10:07.396Z DEBUG   035d2b1192dfba134e10e540875d366ebc8bc353d5aa766b80c090b39c3a5d885d-dualopend-chan#2: billboard: channel open: commitment received, sending to lightningd to save
2022-07-26T05:37:59.4531856Z lightningd-1 2022-07-26T05:10:07.398Z DEBUG   035d2b1192dfba134e10e540875d366ebc8bc353d5aa766b80c090b39c3a5d885d-dualopend-chan#2: peer_in WIRE_TX_SIGNATURES
>>> 2022-07-26T05:37:59.4532553Z lightningd-1 2022-07-26T05:10:07.400Z DEBUG   plugin-spenderp: mfc 60:`openchannel_peer_sigs` notice received for channel 9d145e763f08ee6f715ba7677f869cbb9580c7406f4d0b0ff3a0987efe501e13 <<<< THIS ONE WAS ASSUMED TO COME AFTER openchannel_update (next line)
2022-07-26T05:37:59.4533048Z lightningd-1 2022-07-26T05:10:07.400Z DEBUG   plugin-spenderp: mfc 60, dest 0: openchannel_update 035d2b1192dfba134e10e540875d366ebc8bc353d5aa766b80c090b39c3a5d885d returned.
2022-07-26T05:37:59.4554292Z lightningd-1 2022-07-26T05:10:07.400Z DEBUG   plugin-spenderp: mfc 60: parallel `openchannel_update`.
2022-07-26T05:37:59.4555485Z lightningd-1 2022-07-26T05:10:07.400Z DEBUG   plugin-spenderp: mfc 60: funding tx 50425e20dbf0ca6fe112a8811b8048edb5bfa8d2922079668c5f353b859b45cb
2022-07-26T05:37:59.4557934Z lightningd-1 2022-07-26T05:10:07.508Z DEBUG   0266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c03518-hsmd: Got WIRE_HSMD_CUPDATE_SIG_REQ
2022-07-26T05:37:59.4558244Z lightningd-1 2022-07-26T05:10:07.508Z DEBUG   hsmd: Client: Received message 3 from client
2022-07-26T05:37:59.4558738Z lightningd-3 2022-07-26T05:11:03.234Z DEBUG   0266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c03518-gossipd: seeker: startup peer finished
2022-07-26T05:37:59.4559209Z lightningd-3 2022-07-26T05:11:03.234Z DEBUG   0266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c03518-gossipd: seeker: state = PROBING_SCIDS Seeking scids 1 - 105

(The last 2 log messages (from a different node) are >1min after the last
log line from lightning-1, because lightning-1 hung)

Hacked lightningd up to test this (such that notification always sent
before the RPC response, works as intended w/ patch)
2022-07-27 19:31:04 +09:30
niftynei d3ba017672 valgrind: rm ref to cmd when cmd is free'd
We were cmd was getting free'd but holding on to reference of the
thing was causing problems.

==523280== Invalid read of size 8
==523280==    at 0x1B3E14: del_notifier_property (tal.c:326)
==523280==    by 0x1B3E14: tal_del_notifier_ (tal.c:569)
==523280==    by 0x1123E7: handle_rpc_reply (libplugin.c:671)
==523280==    by 0x1123E7: rpc_read_response_one (libplugin.c:866)
==523280==    by 0x1123E7: rpc_conn_read_response (libplugin.c:886)
==523280==    by 0x1A7B53: next_plan (io.c:59)
==523280==    by 0x1A7B53: do_plan (io.c:407)
==523280==    by 0x1A7B53: io_ready (io.c:417)
==523280==    by 0x1A9BDB: io_loop (poll.c:453)
==523280==    by 0x1141D0: plugin_main (libplugin.c:1708)
==523280==    by 0x10D7E4: main (commando.c:937)
==523280==  Address 0x52de928 is 8 bytes inside a block of size 40 free'd
==523280==    at 0x483F0C3: free (vg_replace_malloc.c:872)
==523280==    by 0x1B2CDD: del_tree (tal.c:419)
==523280==    by 0x1B37BB: tal_free (tal.c:486)
==523280==    by 0x1B37BB: tal_free (tal.c:474)
==523280==    by 0x110CB2: command_complete (libplugin.c:255)
==523280==    by 0x110CB2: command_done_err (libplugin.c:390)
==523280==    by 0x10F511: handle_reply (commando.c:560)
==523280==    by 0x10F511: handle_custommsg (commando.c:609)
==523280==    by 0x113877: ld_command_handle (libplugin.c:1441)
==523280==    by 0x113877: ld_read_json_one (libplugin.c:1491)
==523280==    by 0x113877: ld_read_json (libplugin.c:1511)
==523280==    by 0x1A7B53: next_plan (io.c:59)
==523280==    by 0x1A7B53: do_plan (io.c:407)
==523280==    by 0x1A7B53: io_ready (io.c:417)
==523280==    by 0x1A9BDB: io_loop (poll.c:453)
==523280==    by 0x1141D0: plugin_main (libplugin.c:1708)
==523280==    by 0x10D7E4: main (commando.c:937)
==523280==  Block was alloc'd at
==523280==    at 0x483C855: malloc (vg_replace_malloc.c:381)
==523280==    by 0x1B3BBD: allocate (tal.c:250)
==523280==    by 0x1B3BBD: add_notifier_property (tal.c:303)
==523280==    by 0x1B3BBD: tal_add_destructor2_ (tal.c:529)
==523280==    by 0x110725: jsonrpc_request_start_ (libplugin.c:181)
==523280==    by 0x10E0EA: send_more_cmd (commando.c:643)
==523280==    by 0x11243C: handle_rpc_reply (libplugin.c:696)
==523280==    by 0x11243C: rpc_read_response_one (libplugin.c:866)
==523280==    by 0x11243C: rpc_conn_read_response (libplugin.c:886)
==523280==    by 0x1A7B53: next_plan (io.c:59)
==523280==    by 0x1A7B53: do_plan (io.c:407)
==523280==    by 0x1A7B53: io_ready (io.c:417)
==523280==    by 0x1A9BDB: io_loop (poll.c:453)
==523280==    by 0x1141D0: plugin_main (libplugin.c:1708)
==523280==    by 0x10D7E4: main (commando.c:937)
==523280==
{
   <insert_a_suppression_name_here>
2022-07-26 15:11:30 -07:00
Rusty Russell 9aa9a8236f commando: free incmd as soon as we use it.
Otherwise we left it in the cache, causing "New cmd replacing old"
messages.
2022-07-26 09:33:40 -07:00
Rusty Russell da4e33cd0d decode: fix crash when decoding invalid rune.
If rune contains invalid UTF-8, offers (which implements decode) would
produce JSON with invalid UTF-8, which causes lightningd to complain
and kill it, and then die because it's an important plugin.

So don't decode invalid UTF-8!

Reported-by: @jb55
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-25 15:14:01 -07:00
niftynei bb4da47131 msat: cleanup msat outputs for apis
Don't use the _str() option for msat outputs, use the built-in helpers
which are deprecation aware.

Fixes #5447

Reported-By: @fiatjaf
2022-07-23 16:22:38 +09:30
Rusty Russell c10e385612 commando: add stress test, fix memleak report.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-21 15:37:05 -05:00
Rusty Russell 05a666e424 commando: limit to 16 partially-received incoming commands at a time.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-21 15:37:05 -05:00
Rusty Russell aaf743e438 commando: fix crash when rune is completely bogus.
The error routine returns a string literal in this case, which we can't take().

Reported-by: @jb55
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-21 15:37:05 -05:00
Rusty Russell 43e5ef3cc4 libplugin: don't call callbacks if cmd completed before response.
This can particularly happen with commando:

```
 commando: FATAL SIGNAL 11 (version 06b36d3)
0x55609e953d51 send_backtrace
	common/daemon.c:33
0x55609e953dfb crashdump
	common/daemon.c:46
0x7f665e3b908f ???
	/build/glibc-SzIz7B/glibc-2.31/signal/../sysdeps/unix/sysv/linux/x86_64/sigaction.c:0
0x55609e9387a3 send_more_cmd
	plugins/commando.c:632
0x55609e93b270 handle_rpc_reply
	plugins/libplugin.c:669
0x55609e93bd50 rpc_read_response_one
	plugins/libplugin.c:842
0x55609e93be86 rpc_conn_read_response
	plugins/libplugin.c:862
0x55609e9f4f68 next_plan
	ccan/ccan/io/io.c:59
0x55609e9f5b70 do_plan
	ccan/ccan/io/io.c:407
0x55609e9f5bb2 io_ready
	ccan/ccan/io/io.c:417
0x55609e9f7ea5 io_loop
	ccan/ccan/io/poll.c:453
0x55609e93eb20 plugin_main
	plugins/libplugin.c:1676
0x55609e9397ab main
	plugins/commando.c:922
0x7f665e39a082 __libc_start_main
	../csu/libc-start.c:308
0x55609e93677d ???
	???:0
0xffffffffffffffff ???
	???:0
```

Reported-by: @adi2011
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-21 15:37:05 -05:00
Christian Decker aa82a96034 cln-plugin: Fix plugin dependencies 2022-07-21 14:19:06 +09:30
Christian Decker e586a61228 cln-plugin: Add metadata required by crates.io 2022-07-21 14:19:06 +09:30
Christian Decker 1efa5c37be cln-plugin: Notify waiting tasks if the lightningd connection closes
This is usually a signal that lightningd is shutting down, so notify
any instance that is waiting on `plugin.join()`.

Changelog-Fixed: cln-plugin: Fixed an issue where plugins would hang indefinitely despite `lightningd` closing the connection
2022-07-21 14:19:06 +09:30
adi2011 5abed486d0 Add rune and commando to gitignore.
Changelog-None: Small fix
2022-07-19 15:29:26 +09:30
Rusty Russell a3c4908f4a lightningd: don't explicitly tell connectd to disconnect, have it do it on sending error/warning.
Connectd already does this when we *receive* an error or warning, but
now do it on send.  This causes some slight behavior change: we don't
disconnect when we close a channel, for example (our behaviour here
has been inconsistent across versions, depending on the code).

When connectd is told to disconnect, it now does so immediately, and
doesn't wait for subds to drain etc.  That simplifies the manual
disconnect case, which now cleans up as it would from any other
disconnection when connectd says it's disconnected.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-18 20:50:04 -05:00
Rusty Russell aec307f7ba multifundchannel: fix race where we restart fundchannel.
Disconnecting a peer after openingd fails is not instantaneous:
we abort the open, so openingd sends out a WIRE_ERROR which makes
connectd close the connection.

As a result this test fails often.  The simplest fix is to wait for a
second in multifundchannel before retrying, which is also robust
against behaviour changes if we decide *not* to disconnect in future.

Also make sure that addrhint ownership is correct, since this can
lead to a use-after-free if we filter dests.

```
tests/test_connection.py::test_multifunding_best_effort FAILED                                                    [100%]

======================================================= FAILURES ========================================================
_____________________________________________ test_multifunding_best_effort _____________________________________________

node_factory = <pyln.testing.utils.NodeFactory object at 0x7f6c0c95c1c0>
bitcoind = <pyln.testing.utils.BitcoinD object at 0x7f6c0c92a880>

    @pytest.mark.openchannel('v1')
    @pytest.mark.developer("disconnect=... needs DEVELOPER=1")
    def test_multifunding_best_effort(node_factory, bitcoind):
        '''
        Check that best_effort flag works.
        '''
        disconnects = ["-WIRE_INIT",
                       "-WIRE_ACCEPT_CHANNEL",
                       "-WIRE_FUNDING_SIGNED"]
        l1 = node_factory.get_node()
        l2 = node_factory.get_node()
        l3 = node_factory.get_node(disconnect=disconnects)
        l4 = node_factory.get_node()
    
        l1.fundwallet(2000000)
    
        destinations = [{"id": '{}@localhost:{}'.format(l2.info['id'], l2.port),
                         "amount": 50000},
                        {"id": '{}@localhost:{}'.format(l3.info['id'], l3.port),
                         "amount": 50000},
                        {"id": '{}@localhost:{}'.format(l4.info['id'], l4.port),
                         "amount": 50000}]
    
        for i, d in enumerate(disconnects):
            # Should succeed due to best-effort flag.
>           l1.rpc.multifundchannel(destinations, minchannels=2)

tests/test_connection.py:2070: 
...
>           raise RpcError(method, payload, resp['error'])
E           pyln.client.lightning.RpcError: RPC call failed: method: multifundchannel, payload: {'destinations': [{'id': '022d223620a359a47ff7f7ac447c85c46c923da53389221a0054c11c1e3ca31d59@localhost:41023', 'amount': 50000}, {'id': '035d2b1192dfba134e10e540875d366ebc8bc353d5aa766b80c090b39c3a5d885d@localhost:41977', 'amount': 50000}, {'id': '0382ce59ebf18be7d84677c2e35f23294b9992ceca95491fcf8a56c6cb2d9de199@localhost:34943', 'amount': 50000}], 'minchannels': 2}, error: {'code': 305, 'message': 'Peer not connected at start', 'data': {'id': '0382ce59ebf18be7d84677c2e35f23294b9992ceca95491fcf8a56c6cb2d9de199', 'method': 'fundchannel_start'}}
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-18 20:50:04 -05:00
Rusty Russell 8c48eda8c7 decode: support decoding runes.
This is a bit weird since it lives in the offers plugin, but it works
well.  This should make runes much more approachable for people!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-17 08:51:02 +09:30
Rusty Russell 468dff1723 commando: add rate for maximum successful rune use per minute.
I'm assuming that nobody wants a rate slower than 1 per minute; we can
introduce 'drate' if we want a per-day kind of limit.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-17 08:51:02 +09:30
Rusty Russell 4ab09f7cfb commando: add support for parameters by array, parameter count.
Awkward to filter, but they're really practical for many commands.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-17 08:51:02 +09:30
Rusty Russell 8688daf937 commando: require runes for operation.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-17 08:51:02 +09:30
Rusty Russell ae4856df70 commando: don't look at messages *at all* unless they've created a rune.
This means we can leave commando on by default, without an explicit config flag.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-17 08:51:02 +09:30
Rusty Russell 419cb60b1b commando: add commando-rune command.
Can both mint new runes, and add one or more restrictions to existing ones.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-17 08:51:02 +09:30
Rusty Russell 0d94530f13 commando: runes infrastructure.
We support the old commando.py plugin, which stores a random secret,
as well as a more modern approach which uses makesecret.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-17 08:51:02 +09:30
Rusty Russell b49703e279 commando: correctly reflect error data field.
Some JSON error include "data", and we should reflect that.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-17 08:51:02 +09:30
Rusty Russell 49df89556b commando: support commands larger than 64k.
This is needed for invoice, which can be asked to commit to giant descriptions
(though that's antisocial!).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-17 08:51:02 +09:30
Rusty Russell 3fe246c2e7 plugins/commando: basic commando plugin (no runes yet).
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au
Changelog-Added: Plugins: `commando` a new builtin plugin to send/recv peer commands over the lightning network, using runes.
2022-07-17 08:51:02 +09:30
Rusty Russell 3eccf16f98 libplugin: datastore helpers.
Plugins are supposed to store their data in the datastore, and commando does so:
let's make it easier for them by providing convenience APIs.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-17 08:51:02 +09:30
Rusty Russell d3e64c3970 libplugin: jsonrpc_request_whole_object_start() for more custom request handling.
commando wants to see the whole reply object, and also not to assume params is
an object.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-17 08:51:02 +09:30
Rusty Russell d0a55a62b3 common/json_stream: make json_add_jsonstr take a length.
This is useful when have have a jsmntok_t.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-17 08:51:02 +09:30
Rusty Russell 3e672b784d Makefile: use a library archive for CCAN
The linker discards whole files in an archive if it doesn't need them,
so saves a bit of space (and time).  Also allows us to add more niche
things to CCAN (e.g. runes support!) without bloating all the binaries.

We also had many places which depended on $(CCAN_FILES), but that was
already a dependent of $(ALL_PROGRAMS) and $(ALL_TEST_PROGRAMS).

Before:

```
$ size lightningd/lightning*d
   text	   data	    bss	    dec	    hex	filename
2247683	   8696	  39008	2295387	 23065b	lightningd/lightning_channeld
2086607	   7432	  38880	2132919	 208bb7	lightningd/lightning_closingd
2227916	   8056	  39200	2275172	 22b764	lightningd/lightning_connectd
3369236	 119288	  39240	3527764	 35d454	lightningd/lightningd
2183551	   8352	  38880	2230783	 2209ff	lightningd/lightning_dualopend
2196389	   8024	  39136	2243549	 223bdd	lightningd/lightning_gossipd
2086216	   7488	  39264	2132968	 208be8	lightningd/lightning_hsmd
2134396	   8136	  39424	2181956	 214b44	lightningd/lightning_onchaind
2133391	   8352	  38880	2180623	 21460f	lightningd/lightning_openingd
1512168	   2136	  34384	1548688	 17a190	lightningd/lightning_websocketd
```

After:
```
text	   data	    bss	    dec	    hex	filename
2192065	   8488	  38912	2239465	 222be9	lightningd/lightning_channeld
2030957	   7224	  38816	2076997	 1fb145	lightningd/lightning_closingd
2179571	   7968	  39104	2226643	 21f9d3	lightningd/lightning_connectd
3354296	 119288	  39208	3512792	 3599d8	lightningd/lightningd
2127933	   8144	  38816	2174893	 212fad	lightningd/lightning_dualopend
2141699	   7856	  39072	2188627	 216553	lightningd/lightning_gossipd
2024482	   7288	   5240	2037010	 1f1512	lightningd/lightning_hsmd
2072074	   7920	   5400	2085394	 1fd212	lightningd/lightning_onchaind
2077773	   8144	  38816	2124733	 206bbd	lightningd/lightning_openingd
1408958	   1752	    344	1411054	 1587ee	lightningd/lightning_websocketd
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-17 08:51:02 +09:30
Simon Vrouwe ad3cbed7c2 plugin: autoclean fix double free when re-enable, remove xfail mark from test_
Fixes a crash when enabling after a disable with cycle_seconds=0.
2022-07-16 14:19:05 +09:30
Rusty Russell dbae5ae569 common/json_stream.c: provide explicit json_add_primitive_fmt and json_add_str_fmt routines.
Rather than a generic "add member", provide two routines: one which
doesn't quote, and one which does.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-15 12:24:00 -05:00
Rusty Russell 401f1debc5 common: clean up json routine locations.
We have them split over common/param.c, common/json.c,
common/json_helpers.c, common/json_tok.c and common/json_stream.c.

Change that to:
* common/json_parse (all the json_to_xxx routines)
* common/json_parse_simple (simplest the json parsing routines, for cli too)
* common/json_stream (all the json_add_xxx routines)
* common/json_param (all the param and param_xxx routines)

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-15 12:24:00 -05:00
Rusty Russell f12f0d6929 common: remove json_tok.
Make local copies for tests, and fundchannel plugin (which just passes
params through).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-15 12:24:00 -05:00
Rusty Russell a9b992ff4a plugins/spender/multifundchannel: remove json_tok.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-15 12:24:00 -05:00
Rusty Russell 0236d4e4da common/json_stream: remove useless attempt at oom handling.
We tell membuf to use tal, and tal never returns NULL, so this
code can never be triggered.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-15 12:24:00 -05:00
Rusty Russell c34a0a22ad makesecret: change info_hex arg to simply "hex" to match datastore command.
And fix schema: it wasn't tested as there was no test-by-parameter-name.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-07-15 22:17:58 +09:30
adi2011 1450f1758c Plugin: Add new plugin for SCB, Updated makefile and gitignore as well 2022-07-14 12:24:48 -05:00
niftynei 95ec897ac0 dual-fund: Fail if you try to buy a liquidity ad w/o dualfunding on
Fixes #5271

In-Collaboration-With: Base58 'n Coding Seminar Participants

Changelog-Changed: `fundchannel` now errors if you try to buy a liquidity ad but dont' have `experimental-dual-fund` enabled
2022-07-13 12:29:50 -05:00
Justin Moon 42783aaa92 cln_plugin: Configure "dynamic" field in "getmanifest" message 2022-07-11 11:05:50 +02:00
Christian Decker 7930e34da3 pay: Populate the channel hints with either the scid or the alias
We'll use one of the two, and we reuse the `scid` field, since we
don't really care that much which one it is.
2022-07-04 22:14:06 +02:00
Christian Decker 0ce68b26c6 jsonrpc: Include the direction also if we have an alias
The direction only depends on the ordering between node_ids, not the
short_channel_id, so we can include it and it won't change. This was
causing some trouble loading the `channel_hints` in the `pay` plugin.
2022-07-04 22:14:06 +02:00
Christian Decker a4e6b58fa4 ld: Consider local aliases when forwarding 2022-07-04 22:14:06 +02:00
Christian Decker 1ae3dba529 invoice: Consider aliases too when selecting routehints 2022-07-04 22:14:06 +02:00
Christian Decker 185cd81be4 jsonrpc: Add `mindepth` argument to fundchannel and multifundchannel
This will eventually enable us to specify 0 for zeroconf channels.

Changelog-Added: JSON-RPC: Added `mindepth` argument to specify the number of confirmations we require for `fundchannel` and `multifundchannel`
2022-07-04 22:14:06 +02:00
Christian Decker e6442d798e cln-plugin: Make the proxy-related configuration Option<>
These are only populated if a proxy was specified, see
lightningd/plugin.c:1855, so we were getting upset when we expected
them and they weren't set.
2022-06-22 12:07:55 +02:00
Justin Moon 5ec424bc86 cln-plugin: Configuration struct
Represents the "configuration" part of the "init" message during
plugin initialization.

Changelog-Added: cln_plugin: persist cln configuration from init msg
2022-06-22 12:07:55 +02:00
Justin Moon 318b6e803e cln-plugin: Add unittest for parsing "init" message 2022-06-22 12:07:55 +02:00
Justin Moon 14483901cd cln-plugin: Save "configuration" from "init" method 2022-06-22 12:07:55 +02:00
Rusty Russell 5531de99de lease_rates: prepare for msats fields as raw numbers.
We would otherwise multiply them by 1000.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-06-21 06:52:35 +09:30
Rusty Russell 6461815dd9 plugins/funder: fix parameter parsing.
This code was buggy: handing "1000" as a parameter to
min_their_funding_msat, don't turn that into "1000sat"!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-06-21 06:52:35 +09:30
Rusty Russell 6139319b60 funder: prepare for msats fields as raw numbers.
We would otherwise multiply them by 1000.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-06-21 06:52:35 +09:30
Rusty Russell 993f44f289 libplugin: don't be so strict on msat fields.
Let the parsing handle if they're the wrong type (soon they'll be u64).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-06-21 06:52:35 +09:30
Rusty Russell 98c264de66 fundchannel, txprepare, multiwithdraw: don't assume "excess_msat" will have "msat" appended.
After next patch, it's a raw u64, and this code broke.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-06-21 06:52:35 +09:30
Rusty Russell 01411d70be common: enforce that msat fields are called "xxx_msat".
Now we've fixed them all, make sure no new ones slip in!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-06-21 06:52:35 +09:30
Rusty Russell fccb11a641 fetchinvoice: amount_msat not msat.
The name in the spec is `msat`, but I don't want to make an API exception.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: `fetchinvoice` `changes` `amount_msat`
Changelog-Deprecated: JSON-RPC: `fetchinvoice` `changes` `msat` (use `amount_msat`)
2022-06-21 06:52:35 +09:30
Rusty Russell f117225436 pay: use amount_msat for amount report inside attempts.
Nobody really parses this though, fortunately.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: `pay` `attempts` `amount_msat` field.
Changelog-Deprecated: JSON-RPC: `pay` `attempts` `amount` field (use `amount_msat`).
2022-06-21 06:52:35 +09:30
Rusty Russell cd7e784d6f lightningd: change `msatoshi` args to `amount_msat`.
This is consistent with our output changes, and increases consistency.
It also keeps future sanity checks happy, that we only use JSON msat
helpers with '_msat' fields.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Changed: JSON-RPC: `invoice`, `sendonion`, `sendpay`, `pay`, `keysend`, `fetchinvoice`, `sendinvoice`: `msatoshi` argument is now called `amount_msat` to match other fields.
Changelog-Deprecated: JSON-RPC: `invoice`, `sendonion`, `sendpay`, `pay`, `keysend`, `fetchinvoice`, `sendinvoice` `msatoshi` (use `amount_msat`)
2022-06-21 06:52:35 +09:30
Rusty Russell 36a2491a89 json: fix up msat amounts in non-_msat fields.
We had json_add_amount_msat_only(), which was designed to be used to
print out msat fields, if we had sats.

However, we misused it, so split it into the three different cases:
1. json_add_amount_sat_msat: We are using it correctly, with a field called
   xxx_msat.
2. json_add_amount_sats_deprecated: We were using it wrong, so deprecate
   the old field and create a new one which does end in _msat.
3. json_add_sats: we were using it to hand sats as a JSON parameter to an
   interface, where "XXXsat".

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Deprecated: Plugins: `rbf_channel` and `openchannel2` hooks `their_funding` (use `their_funding_msat`)
Changelog-Deprecated: Plugins: `openchannel2` hook `dust_limit_satoshis` (use `dust_limit_msat`)
Changelog-Deprecated: Plugins: `openchannel` hook `funding_satoshis` (use `funding_msat`)
Changelog-Deprecated: Plugins: `openchannel` hook `dust_limit_satoshis` (use `dust_limit_msat`)
Changelog-Deprecated: Plugins: `openchannel` hook `channel_reserve_satoshis` (use `channel_reserve_msat`)
Changelog-Deprecated: Plugins: `channel_opened` notification `amount` (use `funding_msat`)
Changelog-Deprecated: JSON-RPC: `listtransactions` `msat` (use `amount_msat`)
Changelog-Deprecated: Plugins: `htlc_accepted` `forward_amount` (use `forward_msat`)
2022-06-21 06:52:35 +09:30
Jon Griffiths 572942c783 psbt: use DER encoded + sighash byte for PSBT_IN_PARTIAL_SIG items
Per BIP-0171, the signature map is of pubkey to "The signature as would
be pushed to the stack from a scriptSig or witness".

Fixes 5298

Changelog-Fixed: PSBT: Fix signature encoding to comply with BIP-0171.

Signed-off-by: Jon Griffiths <jon_p_griffiths@yahoo.com>
2022-06-09 18:28:35 +02:00
Christian Decker f1d0325620 topo: Fix issue considering the wrong direction for capacity limits
Changelog-Fixed: topology: Under some circumstances we were considering the limits on the wrong direction for a channel
2022-05-25 14:47:05 +09:30
Rusty Russell 355025239d Make sure DEFAULT_TARGETS includes rust testing examples.
Otherwise tests fail:

```
    def test_plugin_start(node_factory):
        """Start a minimal plugin and ensure it is well-behaved
        """
        bin_path = Path.cwd() / "target" / "debug" / "examples" / "cln-plugin-startup"
>       l1 = node_factory.get_node(options={"plugin": str(bin_path), 'test-option': 31337})
...
error starting plugin '/home/runner/work/lightning/lightning/target/debug/examples/cln-plugin-startup': opening pipe: No such file or directory
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-04-13 05:25:00 +09:30
Rusty Russell c598d4df74 Makefile: make sure ALL_PROGRAMS doesn't include cln-grpc plugin.
$(ALL_PROGRAMS) are assumed to be C programs for now.

Add $(C_PLUGINS) as a new variable.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-04-13 05:25:00 +09:30
Rusty Russell e4ed15dc33 plugins: fix cln-grpc to work as a builtin when we're run in-tree.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-04-13 05:25:00 +09:30
Rusty Russell 436706384c plugins: add grpc-plugin to PLUGINS, so it gets started and installed.
Fixes: #5162
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-04-13 05:25:00 +09:30
Michael Dance f067e8c909 Changed external/libwally-core to test_build_fix
Combined with the following commit which is required to
update against changed libsecp256k1 APIs:

Updated deprecated function calls
2022-04-12 15:17:52 +09:30
Christian Decker b359a24772 cln-plugin: Handle --help invocations better
We now have ternary outcomes for `Builder.configure()` and
`Builder.start()`:

 - Ok(Some(p)) means we were configured correctly, and can continue
   with our work normally
 - Ok(None) means that `lightningd` was invoked with `--help`, we
   weren't configured (which is not an error since the `lightningd` just
   implicitly told us to shut down) and user code should clean up and
   exit as well
 - Err(e) something went wrong, user code may report an error and exit.
2022-04-11 15:20:32 +09:30
Christian Decker 8717c4e5a2 cln-grpc: Add midstate between configuration and replying to init
This is a bit special, in that it allows us to configure the plugin,
but then still abort startup by sending `init` with the `disable` flag
set.
2022-04-10 14:16:35 +09:30
Christian Decker 9826402c99 cln-grpc: Do not exit if grpc-port is not set
Exiting doesn't mesh well with builtin plugins, so just sit there and
do nothing

Changelog-None
2022-04-10 14:16:35 +09:30
Christian Decker 767da45037 cln-grpc: Do not log an error when called with `--help`
Changelog-None
2022-04-08 11:30:10 +09:30
Rusty Russell 836c1b805b doc: update c-lightning to Core Lightning almost everywhere.
Mostly comments and docs: some places are actually paths, which
I have avoided changing.  We may migrate them slowly, particularly
when they're user-visible.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-04-07 06:53:26 +09:30
Rusty Russell f51a3d8ef7 plugins/pay: always include `bolt11` (and `description`) in listpays.
We were setting it on the root, but that doesn't get handed to
sendpay.  Our schema doesn't *require* bolt11, either, so this was
missed (there could be a *bolt12* instead).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Fixed: JSON-RPC: `listpays` always includes `bolt11` or `bolt12` field.
2022-04-04 20:26:04 +09:30
Rusty Russell e47786da04 pay/sendpay: also store description in case bolt11 uses description_hash.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-04-04 20:26:04 +09:30
Rusty Russell d5c736fe86 pay: require description if bolt11 only has hash.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: `pay` has `description` parameter, will be required if bolt11 only has a hash.
Changelog-Deprecated: JSON-RPC: `pay` for a bolt11 which uses a `description_hash`, without setting `description`.
2022-04-04 20:26:04 +09:30
Rusty Russell 6c54e0e7e7 pay: add absolute "maxfee" parameter.
This is what LND does, and it's better for upper layers than trying to
twist our maxfeepercent / exemptfee heuristics to suit.

(I don't remember who complained about this, sorry!)

I'm doing this now because I want to add YA parameter next!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: `pay` has new parameter `maxfee` for setting absolute fee (instead of using `maxfeepercent` and/or `exemptfee`)
2022-04-04 20:26:04 +09:30
Rusty Russell 92028ebaee plugins/pay: remove legacypay.
I think the new pay command has proven itself in the last 18 months!

Also various pay tests took "compat" then didn't use it, so clean them
up.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Removed: JSON-RPC: `legacypay` (`pay` replaced it in 0.9.0).
2022-04-04 20:26:04 +09:30
Rusty Russell bf4d9e30d2 fundpsbt: deprecate reserve=true/false usage.
Make it always a number; this makes the JSON request specification
simpler.  We allowed a number since v0.10.1.

(reserve=True is the default anyway, so usually it can be omitted:
reserve=False becomes reserve=0).

Changelog-Deprecated: JSON-RPC: `fundpsbt`/`utxopsbt` `reserve` must be a number, not bool (for `true` use 72/don't specify, for `false` use 0).  Numbers have been allowed since v0.10.1.
2022-04-02 09:46:01 +10:30
Rusty Russell 1c685ce3e8 plugins/pay: send payment_metadata if provided in invoice.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: Protocol: `pay` (and decode, etc) supports bolt11 payment_metadata a-la https://github.com/lightning/bolts/pull/912
2022-04-02 09:40:18 +10:30
Rusty Russell 5cdb16a93c plugins/pay: don't crash on malformed time.
See: https://github.com/ElementsProject/lightning/issues/4991

We seem to correctly set end_time everywhere, so this looks like
a use-after-free somehow?  But this will fix the crash right here :(

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-31 09:05:53 +10:30
Christian Decker 09ee28cb51 cln-grpc: Do not start unless a `grpc-port` is specified
For now we don't want to autostart.

Suggested-by: Rusty Russell <@rustyrussell>
2022-03-30 12:15:55 +10:30
Christian Decker bf7ad86ef2 cln-grpc: Rename the grpc plugin and binary
Suggested-by: Rusty Russell <@rustyrussell>
Changelog-Added: plugins: `cln-grpc` first class GRPC interface for remotely controlling nodes over mTLS authentication
2022-03-30 12:15:55 +10:30
Christian Decker dd66c85fcb grpc-plugin: Make the grpc port to listen on configurable
Changelog-Added: cln-grpc-plugin: The plugin can be configured to listen on a specific port using the `grpc-port` option
2022-03-30 12:15:55 +10:30
Christian Decker 647ed6a8c8 cln: Add grpc port as configurable option 2022-03-30 12:15:55 +10:30
Christian Decker 27e468d2ae grpc-plugin: Generate mTLS certificates and use them in grpc 2022-03-30 12:15:55 +10:30
Christian Decker a17edeb839 cln-grpc-plugin: Add basic grpc-plugin 2022-03-30 12:15:55 +10:30
Christian Decker b4c7ba2d8f cln-grpc-plugin: Add scaffolding for the cln-grpc-plugin 2022-03-30 12:15:55 +10:30
Rusty Russell 20392ae526 connectd: restore obs2 onion support.
I removed these prematurely: we *haven't* had a release since
introducing them!

This consists of reverting d15d629b8b
"plugins/fetchinvoice: remove obsolete string-based API." and
plugins/fetchinvoice: remove obsolete string-based
API. "onion_messages: remove obs2 support."

Some minor changes due to updated fromwire_tlv API since they
were removed, but not much.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-EXPERIMENTAL: REVERT: Removed backwards compat with onion messages from v0.10.1.
2022-03-29 10:55:12 +10:30
Rusty Russell 93caef3584 common/tlvstream: allow fromwire_tlv to accept *any* unknown type.
This is used for keysend if EXPERIMENTAL_FEATURES is set.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-25 13:55:44 +10:30
Rusty Russell 83ee68ab06 common/tlvstream: put TLV checking back in the generic function.
Callers were supposed to call "tlv_fields_valid" after fromwire_tlv,
but few did.  Make this the default, and call the underlying function
directly where we want to be more flexible (one place).

This loses the ability to allow misordered fields, or to pass through
*any* even fields.  We restore that for special cases in the next
patch.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-25 13:55:44 +10:30
Rusty Russell a770f51d0e tools/generate_wire.py: make functions allocate the TLV.
Requiring the caller to allocate them is ugly, and differs from
other types.

This means we need a context arg if we don't have one already.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-25 13:55:44 +10:30
Rusty Russell d15d629b8b plugins/fetchinvoice: remove obsolete string-based API.
Generate the payload in the callers.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-25 13:55:44 +10:30
Rusty Russell fa0c29f959 tools/generate_wire.py: tlvs should start with tlv_
No more "towire_offer", but "towire_tlv_offer".

This means we double-up on the unfortunately-named `tlv_payload` inside
the onion, but we should rename that in the spec when we remove
old payloads.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-25 13:55:44 +10:30
Rusty Russell f447e39d2d offers: neater response on malformed invoice.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-25 13:55:44 +10:30
Rusty Russell 7829f2eb06 onion_messages: remove obs2 support.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-EXPERIMENTAL: Removed backwards compat with onion messages from v0.10.1.
2022-03-25 13:55:44 +10:30
Rusty Russell 65f5bb2638 pytest: test for compat code.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-25 13:55:44 +10:30
Rusty Russell 726b6878d1 offers: import latest variant from draft.
In particular, this changes the name of a field in invoice_request:
`payer_signature` becomes simply `signature`.  So we allow both for
now, and send the old one unless deprecated_apis is disabled.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-25 13:55:44 +10:30
Rusty Russell f95c9522fd plugins/bcli: fix false memleak detection.
Well, it is leaking a bool for the command duration, but that's probably OK.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-24 13:19:10 +10:30
Rusty Russell 915a591873 spender: free up vars to avoid transient false leak reports.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-23 13:20:12 +10:30
Rusty Russell dbc77bcbc4 pay: fix leak detect on shadow route.
Short term leak, but leak-detect is right: it's dumb code!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>

```
plugin-pay: MEMLEAK: 0x2505318
plugin-pay:   label=common/utils.c:134:char[]
plugin-pay:   backtrace:
plugin-pay:     ccan/ccan/tal/tal.c:442 (tal_alloc_)
plugin-pay:     ccan/ccan/tal/tal.c:471 (tal_alloc_arr_)
plugin-pay:     common/utils.c:134 (tal_hexstr)
plugin-pay:     common/node_id.c:48 (node_id_to_hexstr)
plugin-pay:     common/node_id.c:50 (fmt_node_id_)
plugin-pay:     common/type_to_string.c:32 (type_to_string_)
plugin-pay:     plugins/libplugin-pay.c:2970 (shadow_route_extend)
plugin-pay:     plugins/libplugin-pay.c:3113 (shadow_route_listchannels)
plugin-pay:     plugins/libplugin.c:563 (handle_rpc_reply)
plugin-pay:     plugins/libplugin.c:731 (rpc_read_response_one)
plugin-pay:     plugins/libplugin.c:751 (rpc_conn_read_response)
plugin-pay:     ccan/ccan/io/io.c:59 (next_plan)
plugin-pay:     ccan/ccan/io/io.c:407 (do_plan)
plugin-pay:     ccan/ccan/io/io.c:417 (io_ready)
plugin-pay:     ccan/ccan/io/poll.c:453 (io_loop)
plugin-pay:     plugins/libplugin.c:1565 (plugin_main)
plugin-pay:     plugins/pay.c:2569 (main)
plugin-pay:   parents:
plugin-pay:     plugins/libplugin.c:155:struct out_req
```
2022-03-22 18:45:41 +10:30
Rusty Russell f29890ed66 lightningd: check htlc_maximum_msat of channels for routehints.
We still use the channel hint here (as it's the only option), we just
warn about lack of capacity.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-22 18:45:41 +10:30
Rusty Russell 65be18d355 memleak: handle libwally allocations better.
Things allocated by libwally all get the tal_name "wally_tal",
which cost me a few hours trying to find a leak.

In the case where we're making one of the allocations the parent
of the others (e.g. a wally_psbt), we can do better: supply a name
for the tal_wally_end().

So I add a new tal_wally_end_onto() which does the standard
tal_steal() trick, and also changes the (typechecked!) name.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-21 10:19:50 +10:30
Rusty Russell 43a833e405 lightningd: remove support for legacy onion format.
As per proposal in https://github.com/lightning/bolts/pull/962

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Removed: protocol: support for legacy onion format removed, since everyone supports the new one.
2022-03-18 09:20:11 +10:30
Christian Decker 6706384c50 cln-plugin: Ensure we cleanly shut down when we lose the master conn 2022-03-10 10:21:41 +10:30
Christian Decker 1bd2b8c9f7 cln-plugin: Make notification handlers asynchronous 2022-03-10 10:21:41 +10:30
Christian Decker af4eed3787 cln-plugin: Make hooks asynchronous 2022-03-10 10:21:41 +10:30
Christian Decker a7ef38732f cln-plugin: Make rpcmethod handlers async 2022-03-10 10:21:41 +10:30
Christian Decker 60e773239c cln-plugin: Add notification subscriptions and hooks to the plugins
For now hooks are treated identically to rpcmethods, with the
exception of not being returned in the `getmanifest` call. Later on we
can add typed handlers as well.
2022-03-10 10:21:41 +10:30
Christian Decker 8c6af21169 cln-plugin: Add support for synchronous RPC methods
Changelog-Experimental: cln-plugin: Added support for non-async RPC method passthrough (async support coming soon)
2022-03-10 10:21:41 +10:30
Christian Decker 22618a2f94 cln-plugin: Rework the plugin library using a Builder 2022-03-10 10:21:41 +10:30
Christian Decker fbcb4c33ad cln-plugin: Populate the options when we get an `init` call 2022-03-10 10:21:41 +10:30
Christian Decker 249fa8675a cln-plugin: Add options to the `getmanifest` call 2022-03-10 10:21:41 +10:30
Christian Decker fe21b89b56 pytest: Add a test for the cln-plugin logging integration 2022-03-10 10:21:41 +10:30
Christian Decker f5e1829117 cln-plugin: Implement logging facade adapter for cln plugins
We wrap emitted messages into a JSON-RPC notification envelope and
write them to stdout. We use an indirection over an mpsc channel in
order to avoid deadlocks if we emit logs while holding the writer lock
on stdout.
2022-03-10 10:21:41 +10:30
Christian Decker 9ae1f33992 cln-plugin: Get started with the plugin interface 2022-03-10 10:21:41 +10:30
niftynei 7add7ca199 json: reverse parse a coin_mvt tag back into an enum 2022-03-05 15:12:12 +10:30
Rusty Russell cd37753849 plugins/bcli: neaten to fix spurious leak report.
```
plugin-bcli: MEMLEAK: 0x1d2a118
plugin-bcli:   label=plugins/bcli.c:636:const char *[]
plugin-bcli:   backtrace:
plugin-bcli:     ccan/ccan/tal/tal.c:442 (tal_alloc_)
plugin-bcli:     ccan/ccan/tal/tal.c:471 (tal_alloc_arr_)
plugin-bcli:     plugins/bcli.c:636 (estimatefees_next)
plugin-bcli:     plugins/bcli.c:684 (estimatefees)
plugin-bcli:     plugins/libplugin.c:1307 (ld_command_handle)
plugin-bcli:     plugins/libplugin.c:1348 (ld_read_json_one)
plugin-bcli:     plugins/libplugin.c:1368 (ld_read_json)
plugin-bcli:     ccan/ccan/io/io.c:59 (next_plan)
plugin-bcli:     ccan/ccan/io/io.c:407 (do_plan)
plugin-bcli:     ccan/ccan/io/io.c:417 (io_ready)
plugin-bcli:     ccan/ccan/io/poll.c:453 (io_loop)
plugin-bcli:     plugins/libplugin.c:1565 (plugin_main)
plugin-bcli:     plugins/bcli.c:965 (main)
plugin-bcli:   parents:
plugin-bcli:     plugins/libplugin.c:1235:struct command
```

It's neater to convert start_bitcoin_cli() to take varargs, and handle take:
the above "leak" is because we don't keep a pointer to the params[] array
which we use to pass to start_bitcoin_cli().

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-03 10:23:11 +00:00
Simon Vrouwe 2d06c38997 plugin-funder: fix typos in option lease-fee-base-msat and funder-fuzz-percent
Changelog-Experimental: option `--lease-fee-base-msat` renamed to `--lease-fee-base-sat`

Changelog-Experimental: option `--lease-fee-base-msat` deprecated and will be removed next release
2022-03-01 09:38:40 +10:30
Rusty Russell 7081413e20 plugins/funder: actually free the pending_opens.
It's a small leak, but real.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-02-27 07:44:26 +10:30
Rusty Russell d5064ff56c libplugin: make memleak see current requests.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-02-27 07:44:26 +10:30
Rusty Russell c5b424b6ce plugins/pay: make memleak happy.
1. Tell memleak about our linked-list of current payments.
2. Don't remove them from list until we actually free them (in destructor, naturally).
3. Decode invoices into tmpctx (we steal / copy what we want anyway).
4. Free params after we've used them.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-02-27 07:44:26 +10:30
Rusty Russell 246b724dbe libplugin-pay: fix spurious leak reports.
1. The dijkstra can be temporary, doesn't need to last as long as pay cmd.
2. We fail multiple times in several places, so don't leak old failreason.
3. Make payments findable by our memleak detector.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-02-27 07:44:26 +10:30
Rusty Russell b3338a174e plugins/keysend: prevent leak detecting getting upset.
1. We don't keep a pointer to payments (unlike pay, which keeps a
   linked list), so mark it notleak.
2. plugin->our_features is overloaded for "features we want to set" (used by keysend)
   and then "features we have".  Create a new field, which is cleaner.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-02-27 07:44:26 +10:30
Rusty Russell a901402e66 plugins/pay: fix unnecessary code.
1. p is a child of cmd, so it's freed by command_failed.
2. cltv_budget is set a few lines up to the same thing already.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-02-27 07:44:26 +10:30
Michael Schmoock 38e2abf68a peer_exchange: set, read and log remote_addr
Changelog-Added: Protocol: set remote_addr on init tlvs
2022-02-22 05:45:47 +10:30
niftynei 4dafeede5c coin moves: notify when we make deposits to external accounts
The blockheight is zero though, since these aren't included in a block
yet.

We also don't issue an 'external' deposit event if we can tell that the
address you're sending to actually belongs to our wallet (we'll issue a
deposit event when it gets included in a block)
2022-01-26 13:34:45 +10:30
Rusty Russell 967ffbfbcb global: use tal_dup_or_null().
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-12-30 14:36:55 +10:30
Rusty Russell 35e3c1866e common: generalize extract_channel_id().
connectd is going to end up using this do demux; make it fast and complete.

Fixing this reveals a problem in openingd: it now extracts the channel_id
from funding_signed (which is where we transition off the temporary), and
gets upset.  So fix that.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-12-30 09:50:40 +10:30
Christian Decker a98ccac777 pay: Disable channels that are not in normal state
Since we have the exact state of the channels from the `listpeers`
response we can filter out the ones that are not yet normal or not
anymore. This is more of a safety net, given that the `gossip_store`
should contain local disables, but better not be racy :-)

Changelog-None
2021-12-14 15:07:45 +10:30
ZmnSCPxj jxPCSnmZ d088288daa bitcoin/chainparams.h: Split BIP173 name into onchain and Lightning HRPs.
Fixes: #4937
2021-12-14 11:21:35 +10:30
Denis Ahrens 522ee5c595 fix 'listincoming' field incoming_capacity_msat.
incoming_capacity_msat field showed the value as microsat.

Changelog-Fixed: JSON-RPC: listincoming showed incoming_capacity_msat field 1000 times actual value.
2021-12-14 11:19:51 +10:30
Rusty Russell 484222b0a1 daemons: remove unused functions or make static.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-12-06 10:05:39 +10:30
Rusty Russell 4ffda340d3 check: make sure all files outside contrib/ include "config.h" first.
And turn "" includes into full-path (which makes it easier to put
config.h first, and finds some cases check-includes.sh missed
previously).

config.h sets _GNU_SOURCE which really needs to be done before any
'#includes': we mainly got away with it with glibc, but other platforms
like Alpine may have stricter requirements.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-12-06 10:05:39 +10:30
Matt Whitlock 1f79aad830 common/utils: introduce tmpdir_mkstemp; use it
Various unit tests were creating temporary files unconditionally in /tmp
and were not cleaning up after themselves. Introduce a new variant of
mkstemp(3p) that respects the TMPDIR environment variable, and use it in
the offending unit tests. This allows each test run to use a dedicated
TMPDIR that can be cleaned up after the run.

Changelog-None

Signed-off-by: Matt Whitlock <c-lightning@mattwhitlock.name>
2021-12-06 09:20:27 +10:30
Andrew Toth fa6f01d5b1 Add route exclusion payment modifier and pay rpc exclude arg
Changelog-Added: Add `exclude` option for `pay` command to manually exclude channels or nodes when finding a route.
2021-12-04 21:37:42 +10:30
Andrew Toth 384c359c79 refactor: move exclude parsing to json_tok 2021-12-04 21:37:42 +10:30
Rusty Russell 296437c655 bolt12: remove deprecated `chains` fields
We also move recurrence fields into a separate spec patch.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-12-01 05:44:28 +10:30
Rusty Russell 163d3a16f4 doc: clean up offers bolt quotes
As of 2b923a0367c5f9154fcec706e3302cc4658dd889.

Recurrence quotes need to be marked separately, since they're no longer
in offers main bolt.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-12-01 05:44:28 +10:30
Rusty Russell 5361107c9c gossipd: handle receipt of modern onion message.
And wire it through to the hook; update the plugins to recognize
modern vs obs2 onions.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-12-01 05:44:28 +10:30
Rusty Russell e7b263304e lightningd: Send updated onion spec messages.
It's very similar to the previous, but there are a few changes:

1. The enctlv fields are numbered differently.
2. The message itself is a different number.

The onionmsg_path type is the same, however, so we keep that constant
at least.

The result is a lot of cut & paste, but we will delete the old one
next release.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-12-01 05:44:28 +10:30
Rusty Russell 5cf2c2fbd7 lightningd: return both obsolete and modern blindedpaths from "blindedpath" RPC.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-12-01 05:44:28 +10:30
Rusty Russell b3af5f5a2c spec: import latest onionmessage spec, based on routeblinding.
This is from 6e99c5feaf60cb797507d181fe583224309318e9

We renamed the enctlv field to encrypted_recipient_data in the spec, and the
new onion_message is message 513.  We don't handle it until the next patch.

Two renames:
1. blinding_seed -> blinding_point.
2. enctlv -> encrypted_recipient_data.

We don't do a compat cycle for our JSON APIs for these experimental
features only used by our own plugins, we just rename.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-12-01 05:44:28 +10:30
Rusty Russell 1ec6346f3d common: rename current onion message structures to obs2_.
Yes, we changed the spec again.  Hopefully for the last time!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-12-01 05:44:28 +10:30
Rusty Russell b74848f6f6 common: remove support for pre v0.10.2 onionmessages.
Temporarily disable sendpay_blinding test which uses obsolete onionmsg;
there's still some debate on the PR about how blinded HTLCs will work.

Changelog-EXPERIMENTAL: onionmessage: removed support for v0.10.1 onion messages.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-12-01 05:44:28 +10:30
Rusty Russell 166ee4bac8 plugins/Makefile: improve header dependencies.
Not all plugins depended on their headers.  Keep it simple: all
plugins depend on all plugin headers.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-12-01 05:44:28 +10:30
Simon Vrouwe e08528b7b5 libplugin-pay: fix valgrind error
for the case rpc "listpeers" returns an error, such as in shutdown
2021-11-30 13:34:44 +10:30
Rusty Russell 6c9b752751 memleak: make notleak use the tal name instead of a boutique struct.
This lets us mark it directly.

Get rid of long-unused "notleaks" member of struct lightningd too.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-27 10:38:13 +10:30
Rusty Russell 57328fe59e tests: use common_setup/common_shutdown to avoid leaks.
It also does more checks (like taken() checks).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-17 10:51:48 +10:30
Rusty Russell cd36436179 paystatus: remove doubled amount_msat.
It's always been there:

```
{
   "pay": [
      {
         "bolt11": "...",
         "amount_msat": "1000msat",
         "amount_msat": "1000msat",
         "destination": "03...",
         "attempts": [
            {
               "strategy": "Initial attempt",
               "start_time": "2021-11-06T04:20:20.135Z",
               "age_in_seconds": 229032,
               "end_time": "2021-11-06T04:20:27.792Z",
               "state": "completed",
               "success": {
                  "id": 31994,
                  "payment_preimage": "..."
               }
            }
         ]
      }
   ]
}
```

Reported-by: denis2342 on IRC
Changelog-Fixed: JSON-RPC: `paystatus` entries no longer have two identical `amount_msat` entries.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-17 10:50:33 +10:30
Vincenzo Palazzo e0745358d1 Fix typo in the error message.
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2021-10-30 11:12:21 +02:00
Rene Pickhardt 0ba1bc30fe pay: Use log probability based bias in channel selection
Changelog-Changed: pay: The route selection will now use the log-propability-based channel selection to increase success rate and reduce time to completion
2021-10-22 16:04:37 +02:00
Rusty Russell 233d339061 libplugin-pay: bias towards larger channels.
We bias by channel linearly by capacity, scaled by median fee.
This means that we effectively double the fee if we would use the
entire capacity, and only increase it by 50% if we would only use
1/2 the capacity.

This should drive us towards larger channels.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Changed: Plugins: `pay` now biases towards larger channels, improving success probability.
2021-10-22 16:04:37 +02:00
Rusty Russell 0b3c79b3c2 common/dijkstra: hand channel direction to path_score callback.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-10-22 16:04:37 +02:00
Rusty Russell 67220ca31d offers: fix overzealous BROKEN log.
sendonionmessage can fail when sending a reply, either because
the reply had a bad first peer, or because it went offline.  The
latter happens in CI, which is how I found this.

Also fixed typo "onio" -> "onion".

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-10-14 10:09:03 +10:30
Christian Decker cd7d87f98e pay: listpays groups by payment_hash and groupid
Fixes #4482
Fixes #4481

Changelog-Added: pay: Payment attempts are now grouped by the pay command that initiated them
Changelog-Fixed: pay: `listpays` returns payments orderd by their creation date
Changelog-Fixed: pay: `listpays` no longer groups attempts from multiple attempts to pay an invoice
2021-10-13 13:41:18 +10:30
Christian Decker 49cddaff3d pay: Stash and forward results for duplicate `pay` calls 2021-10-13 13:41:18 +10:30
Christian Decker 917bea6764 pay: Mark completed payments as such by nullifying `cmd`
We want to avoid returning duplicate results when cross-completing, so
mark them as completed when we return a result.
2021-10-13 13:41:18 +10:30
Christian Decker 99f6faaabb libplugin: Add callbacks for successful and failed payments
We're about to suspend duplicate calls to `pay` and this will help us
notify them if the original payment completes.
2021-10-13 13:41:18 +10:30
Christian Decker a4fb5bceb0 pay: Make `pay` idempotent 2021-10-13 13:41:18 +10:30
Christian Decker 5f260840ab jsonrpc: Add `groupid` to `waitsendpay` 2021-10-13 13:41:18 +10:30
Christian Decker f384385f8e pay: Call `listsendpays` to find prior attempts and abort if needed
So far we've always been deferring the deletion, retry and early abort
logic to `sendonion` and `sendpay` which do not have the context to
decide if a call is legitimate or not (they were mostly based on
heuristics). By calling `listsendpays` for the invoice's
`payment_hash` we can identify what our `groupid` should be, but more
importantly we can also abort if another payment is pending or a prior
attempt has already succeeded.
2021-10-13 13:41:18 +10:30
Christian Decker db84b984e5 pay: Add `groupid` to the payment struct 2021-10-13 13:41:18 +10:30
Rusty Russell c92ce59892 BOLT 12: switch invoice_request/invoice to singular `chain` field.
We keep the now-removed chains field, and in deprecated mode, we set it.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-EXPERIMENTAL: bolt12: `chains` in invoice_request and invoice is deprecated, `chain` is used instead.
2021-10-08 13:47:30 +02:00
Rusty Russell 45bf7a3974 bolt12: update to latest spec.
Main changes are:
1. Uses point32 instead of pubkey32.
2. Uses issuer instead of vendor.
3. Uses byte instead of u8.
4. blinded_path num_hops is now a byte, not u16 (we don't use that yet!).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-EXPERIMENTAL: bolt12: `vendor` is deprecated: the field is now called `issuer`.
2021-10-08 13:47:30 +02:00
Rusty Russell 8f582e770c BOLT12: use point32 instead of pubkey32.
That's the modern BOLT12 term.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-10-08 13:47:30 +02:00
ZmnSCPxj jxPCSnmZ d4690358d9 plugins/libplugin.c: Allow freeing notification `struct command *`.
We always allocate a new `struct command` when we get a full JSON
object from stdin:

b2df01dc73/plugins/libplugin.c (L1229-L1233)

If it happens to be a notification, we pass the `struct command` to
the handler, and not free it ourselves:

b2df01dc73/plugins/libplugin.c (L1270-L1275)

There are only nine points in `plugins/libplugin.c` where we `tal_free`
anything, and only one of them frees a `struct command`:

b2df01dc73/plugins/libplugin.c (L224-L234)

The above function `command_complete` is not appropriate for
notification handlers; the above function sends out a response
to our stdout, which a notification handler should not do.

However, as-is, it does mean that notification handling leaks
`struct command` objects, which can be problematic if we ever
have future built-in plugins which are significantly more
dependent on notifications.

This commit changes notification handlers to return
`struct command_result *`, because possibly in the future
notification handlers may want to perform `send_outreq`, so we
might as well use our standard convention for callbacks, and
to encourage future developers to check how to properly
terminate notification handlers (and free up the
`struct command`).

We also now provide a `notification_handled` function which a
notification handler must eventually call, as well as a
`notification_handler_pending` which is just a snowclone of
`command_still_pending`.
2021-10-08 14:40:04 +10:30
Rusty Russell 368fc07d05 offers: send a modern onion reply in response to a modern request.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Experimental: Protocol: Updated onion_message support to match updated draft specification (with backwards compat for old version)
2021-10-04 11:58:31 +02:00
Rusty Russell af7e0a1183 offers: save replytok properly.
We carefully copied the buffer, but the tok is inside an array.  We get away
with it for now, but with coming changes it gets freed.  We need to copy
the token and all the tokens within it.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-10-04 11:58:31 +02:00
Rusty Russell a71f2475d5 fetchinvoice: handle modern onion_message reply.
This comes in via the onion_message_ourpath hook, and we identify the
path by checking the node alias it came to (vs the obsolete version
which used the blinding).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-10-04 11:58:31 +02:00
Rusty Russell 8dd038c106 fetchinvoice: send modern as well as obsolete messages.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-10-04 11:58:31 +02:00
Vincenzo Palazzo 9d5c992fc8 plugin: Adding status to the pay plugin
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>

Rebase

Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2021-09-22 16:23:24 +09:30
Christian Decker 910e79ddb5 bcli: Accept "already in chain" errors as success 2021-09-22 09:08:48 +09:30
Christian Decker e6d5df7918 jsonrpc: Simplify the state decision of `listpays`
It was really different from the way we decide the overall state of a
`pay` command's output. Now we use a more similar state decision,
based on collecting all states and checking them at the end to
determine the outcome.
2021-09-22 09:08:48 +09:30
Christian Decker 6ad8a8a3c9 pay: Fix wrong result being returned by pay
We were checking against the wrong enum value, resulting in an
erroneous `pending` state as a final result.

Changelog-Fixed: pay: `pay` would sometimes misreport a final state of `pending` instead of `failed`
2021-09-22 09:08:48 +09:30
Rusty Russell 2112f4fd8e fetchinvoice: include send in path, use pubkeys.
We had sent->path be a list of node_ids, but it makes more sense as
pubkeys so we can avoid conversion.  Also, I find it easier to think
about (especially creating backwards paths) if we include *ourselves*
as the first element in the path.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-22 06:44:26 +09:30
Rusty Russell 37ddf2e829 lightningd: rename sendonionmessage to sendobsonionmessage.
sendonionmessage is going to be the new one, and do much *less*.

As this is an internal experimental-only API, no deprecation cycle
required.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-22 06:44:26 +09:30
Rusty Russell 6aa520bb9b lightningd: remove sendonionmesage parity hack.
offers contain an x-only pubkey: to route to them to need to know the
02 vs 03 prefix.  If they're in the gossmap it's easy, but if they're
a directly-connected peer it's harder.  We used to have
sendonionmessage tweak the key if it found a peer with the matching
key, but this was always a hack.

It turns out that we try to connect to the node anyway, which is
a noop if it's already connected.  So try connecting to the other
parity if the first one fails.

Also, this registers when we fail to connect, and returns an error
rather than waiting for timeout.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-22 06:44:26 +09:30
Rusty Russell 24536c5561 common/autodata: use instead of ccan/autodata
This means it needs to be linked ~everywhere.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-21 18:04:43 +02:00
Jan Sarenik 284ad2bade Fix for Alpine Linux ond OpenBSD
After recent header files clean-up it was not possible to
build c-lightning 7401b2682. This patch fixes it both for
Alpine Linux and OpenBSD.

Proposed-by: nathanael <nathanael@dalliard.ch>

Changelog-None
2021-09-20 14:44:27 +02:00
Rusty Russell 7401b26824 cleanup: remove unneeded includes in C files.
Before:
 Ten builds, laptop -j5, no ccache:

```
real	0m36.686000-38.956000(38.608+/-0.65)s
user	2m32.864000-42.253000(40.7545+/-2.7)s
sys	0m16.618000-18.316000(17.8531+/-0.48)s
```

 Ten builds, laptop -j5, ccache (warm):

```
real	0m8.212000-8.577000(8.39989+/-0.13)s
user	0m12.731000-13.212000(12.9751+/-0.17)s
sys	0m3.697000-3.902000(3.83722+/-0.064)s
```

After:
 Ten builds, laptop -j5, no ccache: 8% faster

```
real	0m33.802000-35.773000(35.468+/-0.54)s
user	2m19.073000-27.754000(26.2542+/-2.3)s
sys	0m15.784000-17.173000(16.7165+/-0.37)s
```

 Ten builds, laptop -j5, ccache (warm): 1% faster

```
real	0m8.200000-8.485000(8.30138+/-0.097)s
user	0m12.485000-13.100000(12.7344+/-0.19)s
sys	0m3.702000-3.889000(3.78787+/-0.056)s
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-17 09:43:22 +09:30
Rusty Russell ea30c34d82 cleanup: remove unneeded includes in header files.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-17 09:43:22 +09:30
Rusty Russell cb22015b2a common/channel_type: wrapper for generated 'struct channel_type'.
We make it a first-class citizen internally, even though we won't use
it over the wire (at least, non-experimental builds).  This scheme
follows the latest draft, in which features are flagged compulsory.

We also add several helper functions.

Since uses the *even* bits (as per latest spec), not the *odd* bits,
we have some other fixups.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-13 15:53:23 +02:00
Rusty Russell 31f439760f libplugin: make leaks log at LOG_BROKEN so they break CI.
Now we've fixed them, this makes sure CI notices if new leaks appear.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-08 19:11:47 +02:00
Rusty Russell 14002915a1 plugins/libplugin: mark timers as not-a-leak.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-08 19:11:47 +02:00
Rusty Russell 4f4c49c88a libplugin: fix leak of struct command when we don't read it all at once.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Fixed: Plugins: C plugins would could leak memory on every command (esp. seen when hammering topology's listchannels).
2021-09-08 19:11:47 +02:00
Rusty Russell 127539a993 plugins/topology: use memleak annotation instead of global_gossmap hammer.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-08 19:11:47 +02:00
Rusty Russell 68470c8f22 plugins/txprepare: annotate unreleased_txs list against false memleaks.
And fix utx leak in the withdraw case.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-08 19:11:47 +02:00