Commit Graph

1394 Commits

Author SHA1 Message Date
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
Rusty Russell f078e54e98 lightningd: remove various deprecated JSON fields.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Removed: JSON-RPC: removed `listtransactions` `outputs` `satoshis` field (deprecated v0.10.1)
Changelog-Removed: JSON-RPC: removed `listpeers` `channels` deprecated fields (deprecated v0.10.1)
Changelog-Removed: JSON-RPC: removed `listpeers` `channels` `closer` now omitted, rather than `null` (deprecated v0.10.1)
2022-05-18 10:15:36 +09:30
Rusty Russell d18817a525 wallet: don't get so upset on orphaned HTLC.
User grubman on IRC reported a crash due to new HTLC checks:

```
2022-04-05T01:15:17.707Z **BROKEN** wallet: Missing preimage for orphaned HTLC; replacing with zeros
...
2022-04-05T01:15:44.950Z **BROKEN** lightningd: check_already_failed:Both failed and succeeded?
2022-04-05T01:15:45.020Z **BROKEN** lightningd: FATAL SIGNAL 6 (version v0.11.0rc1-modded)
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: common/daemon.c:38 (send_backtrace) 0xaaaab8f7f8bb
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: common/daemon.c:46 (crashdump) 0xaaaab8f7f91b
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: (null):0 ((null)) 0xffffa4a315bf
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: (null):0 ((null)) 0xffffa45c6cd8
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: (null):0 ((null)) 0xffffa45b3a27
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: lightningd/log.c:821 (fatal_vfmt) 0xaaaab8f3e1b7
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: lightningd/log.c:829 (fatal) 0xaaaab8f3e24b
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: lightningd/htlc_end.c:87 (corrupt) 0xaaaab8f325d3
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: lightningd/htlc_end.c:175 (htlc_out_check) 0xaaaab8f32ee3
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: lightningd/peer_htlcs.c:1471 (check_already_failed) 0xaaaab8f53ea7
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: lightningd/peer_htlcs.c:1575 (onchain_failed_our_htlc) 0xaaaab8f54aab
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: lightningd/onchain_control.c:411 (handle_missing_htlc_output) 0xaaaab8f4037b
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: lightningd/onchain_control.c:544 (onchain_msg) 0xaaaab8f409bf
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: lightningd/subd.c:556 (sd_msg_read) 0xaaaab8f5f8ef
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: ccan/ccan/io/io.c:59 (next_plan) 0xaaaab8fda197
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: ccan/ccan/io/io.c:407 (do_plan) 0xaaaab8fda76f
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: ccan/ccan/io/io.c:417 (io_ready) 0xaaaab8fda82f
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: ccan/ccan/io/poll.c:453 (io_loop) 0xaaaab8fdc77f
2022-04-05T01:15:45.020Z **BROKEN** lightningd: backtrace: lightningd/io_loop_with_timers.c:22 (io_loop_with_timers) 0xaaaab8f37857
2022-04-05T01:15:45.021Z **BROKEN** lightningd: backtrace: lightningd/lightningd.c:1181 (main) 0xaaaab8f3bcff
2022-04-05T01:15:45.021Z **BROKEN** lightningd: backtrace: (null):0 ((null)) 0xffffa45b3d4f
2022-04-05T01:15:45.021Z **BROKEN** lightningd: backtrace: (null):0 ((null)) 0xaaaab8f1ed33
```

Since no HTLCs are likely to still be pending since v0.6.1, we can remove that compat
code.  Indeed, this happens on my node: we've not loaded the incoming HTLC because
it's resolved.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-04-05 15:39:38 +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 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 7e789be0ea doc: update BOLTs to latest master.
Just typo fixes and the like.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-04-02 09:40:18 +10:30
Rusty Russell 3b536400f9 specs: update CSV files.
Regenerate from current BOLTS via `make extract-bolt-csv`

1. The remote_addr field was added manually into peer_wire.csv: this
   needs to be a patch otherwise it vanishes on regen.
2. We never brought into the channel_disabled fields, because it was
   too much hassle (we never actually generate this!).  Do it now.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-04-02 09:40:18 +10:30
Rusty Russell 2f7f7ec255 lightningd: add "style" to listforwards.
Suggested-by: @t-bast
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: `listforwards` has new entry `style`, currently "legacy" or "tlv".
2022-03-31 19:38:05 +10:30
Rusty Russell 5cb4705eb4 unit tests: don't crash if !HAVE_SQLITE3.
Fixes: #4928
Reported-by: @whitslack
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-30 14:20:56 +10:30
Rusty Russell aad4495f56 delinvoice: allow desconly arg to only remove the description.
Means that field is now optional in JSON output.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: `delinvoice` has a new parameter `desconly` to remove description.
2022-03-29 10:04:16 +10:30
Rusty Russell 7147fea2ff common: add const to accepted_extra_tlvs arg.
It was tlv_fields_valid that wanted a non-const: now that's gone, we
can make this correctly const.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-25 13:55:44 +10:30
Rusty Russell 4e8239fcfe lightningd: don't tell connectd to discard peer unless no subds left.
Otherwise it waits for subds to exit, but they don't.  Plus, the others
may still be talking!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-23 13:20:12 +10:30
Rusty Russell ba1242af3e lightningd: add find_channel_by_scid
More efficient to search a known peer than the whole set.

Also, move find_channel_by_id() from channel_control.c into channel.c
where we'd expect it.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-23 13:20:12 +10:30
Rusty Russell b3438e9bba lightningd: associate connect commands with peer, not channel.
Sure, we want to connect (usually) because of an active channel, but
it's not specific to the channel itself.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-23 13:20:12 +10:30
Rusty Russell 7de7b7be61 lightningd: use channel_id when a peer is activated.
Rather than intuiting whether this is a new channel / active channel,
use the channel_id.  This simplifies things and makes them explicit,
and prepares for multiple live channels per peer.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-23 13:20:12 +10:30
Rusty Russell fe9f391a93 connectd: tell lightningd the channel_id when we give it the active peer.
Now we always have it (either extracted from an unsolicited message,
or told to us by lightningd when it tells us it wants to talk), we can
always send it.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-23 13:20:12 +10:30
Rusty Russell 57263a3eb2 lightningd: handle reestablish directly from connectd.
We don't need to hand it to channeld: it will read it!  We simply
need to tell it to expect it.

Similarly, openingd/dualopend will never see it, so remove that logic.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-23 13:20:12 +10:30
Rusty Russell 2424b7dea8 connectd: hold peer until we're interested.
Either because lightningd tells us it wants to talk, or because the peer
says something about a channel.

We also introduce a behavior change: we disconnect after a failed open.
We might want to modify this later, but we it's a side-effect of openingd
not holding onto idle connections.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-23 13:20:12 +10:30
Rusty Russell deecedb033 connectd: tell lightningd when disconnect is complete.
This avoids races in our tests where we assume it's sync (and is kind
of nicer).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-23 13:20:12 +10:30
Rusty Russell 16e9ba0361 connectd: fix confusing names.
The message from lightningd simply acknowleges that we are allowed to
discard the peer (because no subdaemons are talking to it anymore).
This difference becomes more stark once connectd holds on to idle
peers.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-23 13:20:12 +10:30
Rusty Russell 999c734bb5 setchannel: add minhtlc
Suggested by @m-schmook, I realized that if we append it later I'll
never get it right: I expect parameters min and max, not max and min!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: Protocol: you can now alter the `htlc_minimum_msat` and `htlc_maximum_msat` your node advertizes.
2022-03-22 18:45:41 +10:30
Rusty Russell 4fdcee9a11 channeld: generalize specific_feerates mesage into config_channel.
1. Add the htlc_max param.
2. Allow parameters to be unset, meaning "don't change".

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-22 18:45:41 +10:30
Rusty Russell 6fdcc86f9d lightningd: store htlc_maximum_msat for channel in the db.
We currently don't allow setting it, but it's been requested.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-22 18:45:41 +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
Ken Sedgwick 36466af3eb hsmd: Add fields to hsmd_sign_{,remote_}commitment_tx for validating signers 2022-03-16 12:06:21 +10:30
Michael Schmoock 67fdc6f8ad gossipd: send updated node_annoucement remote_addr
This is the cheapest algo I came up with that simply checks that the
same `remote_addr` has been report by two different peers. Can be
improved in many ways:

 - Check by connecting to a radonm peers in the network
 - Check for more than two confirmations or a certain fraction
 - ...

Changelog-Added: Send updated node_annoucement when two peers report the same remote_addr.
2022-03-11 16:42:45 +10:30
Ken Sedgwick 3abe22213c hsmd: Augment call to hsmd_sign_withdrawal_tx with wallet index metadata 2022-03-10 10:22:29 +10:30
Rusty Russell d7ffb712e5 dualopend: restore memleak calls.
And implement a timeout (20 seconds) just in case it's not listening.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-10 09:40:09 +10:30
Rusty Russell 00bb6f07d7 lightningd: simplify memleak code.
Instead of doing this weird chaining, just call them all at once and
use a reference counter.

To make it simpler, we return the subd_req so we can hang a destructor
off it which decrements after the request is complete.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-03-10 09:40:09 +10:30
niftynei ea36c3a938 db: collapse the db_queries files into the generated ones
There's no reason to have these be independent of the generated files,
all the data contained within them is 'formulaic'
2022-03-05 15:03:34 +10:30
niftynei 453ef7f0ce db: mark that column is unused/ignored
2022-01-25T23:41:45.2994844Z ----------------------------- Captured stderr call -----------------------------
2022-01-25T23:41:45.2995230Z lightningd: Never accessed column 1 in query SELECT 1  FROM offers WHERE offer_id = ?;
2022-03-05 15:03:34 +10:30
niftynei ce12d2b8a9 database: pull out database code into a new module
We're going to reuse the database controllers for the accounting plugin
2022-03-05 15:03:34 +10:30
niftynei 03c950bae8 db: decouple `fatal` reliance, have as impl defined function
`fatal` is defined in lightningd and has logfile dependencies etc.

Make it more generic by allowing declaration in the use file (wallet.c)
2022-03-05 15:03:34 +10:30
niftynei b0829fc52a lightningd/Make: cleanup lightningd+wallet headers
There is no "wallet_lib_headers" variable in wallet/Makefile

Likewise, there were two "lightningd_headers", a couple of unused
variables and some other nonsene in lightningd/Makefile
2022-03-05 15:03:34 +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
Rusty Russell 727b486d49 connectd: don't received useless peer fd if we're told to send final msg.
We don't need the connection to ourselves, just to free it.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-02-08 11:15:52 +10:30
Rusty Russell 3c5d27e3e9 subdaemons: remove gossipd fd from per-peer daemons.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-02-08 11:15:52 +10:30
Rusty Russell 1c71c9849b connectd: handle custom messages.
This is neater than what we had before, and slightly more general.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Changed: JSON_RPC: `sendcustommsg` now works with any connected peer, even when shutting down a channel.
2022-02-08 11:15:52 +10:30
Rusty Russell 5065bd6fc2 lightningd: use our cached channel_update for errors instead of asking gossipd.
We also no longer strip the type off: everyone handles both forms, and
Eclair doesn't strip (and it's easier!).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-02-08 11:15:52 +10:30
Sebastian Falbesoner 8309a049eb db: enable SQLite extended result codes
With this change, we get more fine-grained error messages if something
goes wrong in the course of communicating with the SQLite database. To
pick some random examples, the error codes SQLITE_IOERR_NOMEM,
SQLITE_IOERR_CORRUPTFS or SQLITE_IOERR_FSYNC are way more specific
than just a plain SQLITE_IOERR, and the corresponding error messages
generated by sqlite3_errstr() will hence give a better hint to the
user (or also to the developers, if an error report is sent) what the
cause for a failure is.

Changelog-None
2022-02-07 13:59:10 +10:30
niftynei 36ca175ec7 wallet: was erroring out, saving to null field
Add missing field to first write
2022-02-07 13:02:09 +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 39c93ee6e5 connectd: get addresses from lightningd, not gossipd.
It's weird to have connectd ask gossipd, when lightningd can just do it
and hand all the addresses together.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-01-20 15:24:06 +10:30
Rusty Russell 741f44725a patch lightningd-peer-fds.patch 2022-01-20 15:24:06 +10:30
Rusty Russell 6115ed02e8 subdaemons: don't stream gossip_store at all.
We now let gossipd do it.

This also means there's nothing left in 'struct per_peer_state' to
send across the wire (the fds are sent separately), so that gets
removed from wire messages too.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2022-01-20 15:24:06 +10:30
Rusty Russell 425a7af512 common/coin_mvt: clean up API a little.
1. tal_strndup(.., str, strlen(str)) == tal_strdup()
2. tal_strdup also takes(), so document that.
3. Avoid passing 'struct sha256' on the stack: use ptr.
4. Generally, structures shouldn't keep pointers to things they don't own.
   In this case, mvt->node_id.
5. Make payment_hash a pointer, since NULL is more natural than an all-zero
   hash.

And add NON_NULL_ARGS() to the functions; it's cumbersome, but make it
fairly clear what params are optional.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-12-30 14:36:55 +10:30
Rusty Russell 90b669857e lightningd: handle channel cleanups more explicitly.
1. Freeing an unconfirmed channel already releases the subd, so don't
   do that explicitly.
2. Use channel->owner to transfer ownership where possible, using
   channel_set_owner() which handles all the cases.

This simplifies the code and makes it more readable, IMHO.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-12-30 09:50:40 +10:30
niftynei 8225a9decf coin_mvt: log events for pushes/lease_fees for leased channels
We need to stash/save the amount of the lease fees on a leased channel,
we do this by re-using the 'push' amount field on channel (which is
technically correct, since we're essentially pushing the fee amount to
the peer).

Also updates a bit of how the pushes are accounted for (pushed to now
has an event; their channel will open at zero but then they'll
immediately register a push event).

Leases fees are treated exactly the same as pushes, except labeled
differently.

Required adding a 'lease_fee' field to the inflights so we keep track of
the fee for the lease until the open happens.
2021-12-28 04:42:42 +10:30
niftynei bddd3694fa coin_mvt: record fees for an outbound htlc
If we initialized the payment, the fees are the entire fee-chain
(final hop amount - starting hop amount)

If it's a payment we routed, the fees are the diff between the
inbound htlc and the outbound (net gain by this routing)

Added to database so data persists nicely.
2021-12-28 04:42:42 +10:30
niftynei 8098a4cd21 onchaind: remove 'is_replay' logic
we used this originally to suppress duplicate issuance of coin-move
events; we're assuming that any plugin expects duplicate events though
(and knows how to de-dupe them), so we no longer need this logic.
2021-12-28 04:42:42 +10:30
niftynei d2c4d4aec2 coin_mvts: rewrite how onchain events are recorded, update tests
The old model of coin movements attempted to compute fees etc and log
amounts, not utxos. This is not as robust, as multi-party opens and dual
funded channels make it hard to account for fees etc correctly.

Instead, we move towards a 'utxo' view of the onchain events. Every
event is either the creation or 'destruction' of a utxo. For cases where
the value of the utxo is not (fully) debited/credited to our account, we
also record the output_value. E.g. channel closings spend a utxo who's
entire value we may not own.

Since we're now tracking UTXOs onchain, we can now do more complex
assertions about the onchain footprint of them. The integration tests
have been updated to now use more 'chain aware' assertions about the
ending state.
2021-12-28 04:42:42 +10:30
Ken Sedgwick bb574be839 hsmd: Add hsmd_new_channel 2021-12-14 11:24:52 +10:30
Ken Sedgwick e8f43ef6ca wallet: make wallet_can_spend non-static because needed 2021-12-14 11:24:52 +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
Simon Vrouwe f936fa926f plugins: simplify shutdown loop, simply close the db
The only thing that needs ld->wallet after this is destroy_invoices_waiter (off jsonrpc)
Could not find any other destructors (destroy_*) that need wallet or db access after this.
Any db access would now segfault.
2021-12-14 09:33:10 +10:30
Andrew Toth 78fb78478b make: remove generated files when running clean 2021-12-06 10:06:25 +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
ZmnSCPxj jxPCSnmZ 3433ff5e15 wallet/db.c, wallet/wallet.c: Add a partial index to speed up startup.
Closes: #4901

Tested by `EXPLAIN QUERY PLAN` on sqlite3; #4901 shows the result from
@whitslack doing a similar partial index on PostgreSQL on his ~1000 chan
node.

ChangeLog-Added: db: Speed up loading of pending HTLCs during startup by using a partial index.
2021-12-02 11:54:57 +01:00
Simon Vrouwe 63bd569bf6 lightningd: cleanup, freeing jsonrpc in shutdown cannot trigger db write's anymore
since PR #3867 utxos are unreserved by height, destroy_utxos and
related functions are not used anymore so clean them up also

However free(ld->jsonrpc) still needs to happen before free(ld) because its
destructors need list_head pointers from ld
2021-11-30 13:34:44 +10:30
Simon Vrouwe 5f69674faa lightningd: shutdown plugins after subdaemons and assert no write access to db
because:
    - shutdown_subdaemons can trigger db write, comments in that function say so at least
    - resurrecting the main event loop with subdaemons still running is counter productive
      in shutting down activity (such as htlc's, hook_calls etc.)
    - custom behavior injected by plugins via hooks should be consistent, see test
      in previous commmit

    IDEA:

    in shutdown_plugins, when starting new io_loop:

    - A plugin that is still running can return a jsonrpc_request response, this triggers
      response_cb, which cannot be handled because subdaemons are gone -> so any response_cb should be blocked/aborted

    - jsonrpc is still there, so users (such as plugins) can make new jsonrpc_request's which
      cannot be handled because subdaemons are gone -> so new rpc_request should also be blocked

    - But we do want to send/receive notifications and log messages (handled in jsonrpc as jsonrpc_notification)
      as these do not trigger subdaemon calls or db_write's
      Log messages and notifications do not have "id" field, where jsonrpc_request *do* have an "id" field

    PLAN (hypothesis):
    - hack into plugin_read_json_one OR plugin_response_handle to filter-out json with
      an "id" field, this should
      block/abandon any jsonrpc_request responses (and new jsonrpc_requests for plugins?)

  Q. Can internal (so not via plugin) jsonrpc_requests called in the main io_loop return/revive in
     the shutdown io_loop?
  A. No. All code under lightningd/ returning command_still_pending depends on either a subdaemon, timer or
     plugin. In shutdown loop the subdaemons are dead, timer struct cleared and plugins will be taken
     care of (in next commits).

 fixup: we can only io_break the main io_loop once
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 efeb1bc65b wallet: fix sqlite3 column renaming since db backup merge.
Because db->conn is a void *, changing it (from a direct pointer to
a pointer to a pair of pointers) did not break compile if one place hadn't
been update.

The result was a confusing failure: sqlite3 complaining about API misuse,
since the db->conn pointer was not a valid db handle any more.

This is one case where avoiding a void * is hard: we might not even
have the postgresql types, since it might not be installed.  But a union
would have been superior here.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-18 12:53:17 +10:30
ZmnSCPxj jxPCSnmZ a294683675 wallet/db_sqlite3.c: Support direct replication of SQLITE3 backends.
ChangeLog-Added: With the `sqlite3://` scheme for `--wallet` option, you can now specify a second file path for real-time database backup by separating it from the main file path with a `:` character.
2021-11-17 12:10:07 +10:30
Rusty Russell 6c34e522dd wallet: db column manipulation helpers.
Removing columns and renaming them is easy in Postgres, hard in
sqlite3.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-17 10:51:48 +10:30
Rusty Russell fcf3d0ce6c db: turn generated queries array into a simple hash table.
Since we have that functionality, let's use it.  Also, make table
const.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-17 10:51:48 +10:30
Rusty Russell 53c9d9853d wallet: remove db_column_ functions.
Keep some as internal helpers only.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-17 10:51:48 +10:30
Rusty Russell 2e6df89274 wallet: remove redundant field counters, ignored fields.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-17 10:51:48 +10:30
Rusty Russell c462ccae1a wallet: have db track what columns are accessed in DEVELOPER mode.
And add db_col_ignore helper for cases where it's deliberate.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-17 10:51:48 +10:30
Rusty Russell 663c8c6c02 wallet: convert db internal routines to db_col_
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-17 10:51:48 +10:30
Rusty Russell b8a240bd15 wallet: convert wallet.c to db_col_ APIs
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-17 10:51:48 +10:30
Rusty Russell c2a4285a7c wallet: use db_col_ accessors in wallet/invoices.c
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-17 10:51:48 +10:30
Rusty Russell befab73070 db: improve db_col_* APIs.
1. db_col_text becomes db_col_strdup, which is what is usually wanted.
2. db_col_short_channel_id becomes db_col_short_channel_id_str, to emphasize
   that it stores in string form.  Modern versions should store u64.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-17 10:51:48 +10:30
Rusty Russell 5b482eb04b db: db_col_ variants for accessing SELECT statements by name.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-17 10:51:48 +10:30
Rusty Russell 787fbb1228 db: create simple hashtable of fields in SELECT.
This simplistically maps names to numbers, eg:

	SELECT foo, bar FROM tbl;

'foo' -> 0
'bar' -> 1

If a statement is too complex for our simple parsing, we treat it as a
single field (which currently it always is).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-17 10:51:48 +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
Christian Decker 344579b233 wallet: Re-sync the payments.id sequence with postgresql
Fixes #4883
Fixes #4879
Changelog-None: Unreleased bug being fixed.
2021-10-31 13:11:34 +01:00
ZmnSCPxj jxPCSnmZ d330e6e5b4 wallet/db_postgres.c: Fix obvious typo in error message.
ChangeLog-None
2021-10-28 15:51:25 +02:00
niftynei 42e40c1ced htlcs: add flag to 'fail immediately'
If we're over the dust limit, we fail it immediatey *after* commiting
it, but we need a way to signal this throughout the lifecycle, so we add
it to htlc_in struct and persist it through to the database.

If it's supposed to be failed, we fail after the commit cycle is
completed.
2021-10-23 12:59:13 +02:00
niftynei 1fe829c546 lightningd: new option for htlc dust limit
To reduce the surface area of amount of a channel balance that can be
eaten up as htlc dust, we introduce a new config
'--max-dust-htlc-exposure-msat', which sets the max amount that any
channel's balance can be added as dust

Changelog-Added: config: new option --max-dust-htlc-exposure-msat, which limits the total amount of sats to be allowed as dust on a channel
2021-10-23 12:59:13 +02:00
ZmnSCPxj jxPCSnmZ ab026fb4de wallet/db_sqlite3.c: Increase busy timeout to 60 seconds.
Closes: #4860

ChangeLog-Added: With `sqlite3` db backend we now use a 60-second busy timer, to allow backup processes like `litestream` to operate safely.
2021-10-17 23:58:39 +00:00
Rusty Russell c012a71dec CI: suppress postgres vaccuuming.
```
[gw1] [ 98%] PASSED tests/test_wallet.py::test_hsmtool_dump_descriptors 
tests/test_wallet.py::test_fundchannel_listtransaction 
[gw0] [ 98%] PASSED tests/test_plugin.py::test_channel_opened_notification 
tests/test_wallet.py::test_hsmtool_generatehsm 
[gw0] [ 98%] PASSED tests/test_wallet.py::test_hsmtool_generatehsm 
tests/test_wallet.py::test_withdraw_nlocktime_fuzz 
[gw1] [ 98%] ERROR tests/test_wallet.py::test_fundchannel_listtransaction 
tests/test_wallet.py::test_fundchannel_listtransaction 
tests/test_wallet.py::test_withdraw_nlocktime_fuzz 
tests/test_wallet.py::test_fundchannel_listtransaction 
[gw0] [ 99%] ERROR tests/test_wallet.py::test_withdraw_nlocktime_fuzz 
tests/test_wallet.py::test_multiwithdraw_simple 
[gw1] [ 99%] ERROR tests/test_wallet.py::test_fundchannel_listtransaction 
tests/test_wallet.py::test_withdraw_nlocktime 
tests/test_wallet.py::test_multiwithdraw_simple 
tests/test_wallet.py::test_withdraw_nlocktime 
tests/test_wallet.py::test_multiwithdraw_simple 
tests/test_wallet.py::test_withdraw_nlocktime 
[gw0] [ 99%] ERROR tests/test_wallet.py::test_multiwithdraw_simple 
tests/test_wallet.py::test_repro_4258 
[gw1] [ 99%] ERROR tests/test_wallet.py::test_withdraw_nlocktime
...
2021-10-12 06:36:09.203 UTC [224552] STATEMENT:  SELECT version FROM version LIMIT 1
2021-10-12 06:36:09.566 UTC [224523] PANIC:  could not write to file "pg_wal/xlogtemp.224523": No space left on device
2021-10-12 06:36:09.566 UTC [224523] STATEMENT:  VACUUM FULL;
Error vacuuming db: BEGIN command failed: PANIC:  could not write to file "pg_wal/xlogtemp.224523": No space left on device
server closed the connection unexpectedly
	This probably means the server terminated abnormally
	before or while processing the request.
```
2021-10-15 12:09:36 +02:00
Rusty Russell da03985996 wallet: only hand onchaind the HTLCs it needs to know.
This will make closing long-lived channels more efficient, and it's
just nicer.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-10-15 12:09:36 +02:00
Rusty Russell c503232cde common: use bitcoin_outpoint.
I started pulling this thread, and the entire codebase got unravelled.

Oh well, it's done now!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-10-15 12:09:36 +02:00
Rusty Russell 2bb13bacc2 db: vacuum after a db upgrade.
This is particularly useful after our recent field deletion:

before: 362,573,824 bytes
after: 124,190,720 bytes

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Changed: db: removal of old HTLC information and vacuuming shrinks large lightningd.sqlite3 by a factor of 2-3.
2021-10-15 12:09:36 +02:00
Rusty Russell f986549cea db: clear our unneeded htlc fields in old terminated HTLCs.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-10-15 12:09:36 +02:00
Rusty Russell 433e61fcb9 wallet: remove unnecessary data from channel_htlcs when htlc is dead.
In particular, the onion and errors can be large, but now we'll never
need to retransmit them.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-10-15 12:09:36 +02:00
Rusty Russell 8a85bf6880 lightningd: populate min/max commit fields in db.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-10-15 12:09:36 +02:00
Rusty Russell 36b66871a2 db: add min/max commitnum fields to channel_htlcs.
And initialize max to current height max when htlcs are already dead.
Turns out (thanks CI!) that MAX() of multiple columns is GREATEST() in
Postgres.  That's clearer (MAX is used elsewhere for single columns),
so translate on the sqlite3 side.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-10-15 12:09:36 +02:00
Rusty Russell bdaec48400 wallet: wrap htlc_state enum in db function.
All enums in the db should be wrapped this way on reading/writing them.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-10-15 12:09:36 +02:00
Christian Decker 5f260840ab jsonrpc: Add `groupid` to `waitsendpay` 2021-10-13 13:41:18 +10:30
Christian Decker 817b1b361e db: Add `groupid` to HTLCs 2021-10-13 13:41:18 +10:30
Christian Decker 0bb0d8a707 wallet: Add function to retrieve the latest groupid for a payment
When doing things like `waitsendpay` without specifying the `groupid`
we likely want to use the latest `groupid` we created, since that's
the one in flight. This adds a function to quickly retrieve that.
2021-10-13 13:41:18 +10:30
Christian Decker ba4be0313b db: Add groupid to the payments table 2021-10-13 13:41:18 +10:30
Christian Decker c963e6b03f db: Don't switch between text and blob fields
The database will yell at you if you try.
2021-10-10 11:05:01 +10:30
Christian Decker b9c602c7e4 db: Fix a syntax error with the optional parameters
SQL doesn't really allow `a OR 1` as a clause since `1` is not a
boolean expression. Moving it into `a OR 1=1` however is valid again.
2021-10-10 11:05:01 +10:30
Rusty Russell 79e09b92ef Makefile: remove generated files.
By popular merge-hell demand.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Changed: Build: Python is now required to build, as generated files are no longer checked into the repository.
2021-09-22 15:25:14 +02:00
Rusty Russell 3dbf3b057a Makefile: remove NO_PYTHON flag in anticipation of making it compulsory.
And note the EXPERIMENTAL_DUAL_FUND env var in HACKING.md.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-22 15:25:14 +02:00
Vincenzo Palazzo eb103c15df review 2/2: Use generic query to make the code more readable.
Suggested by @cdecker

P.S: Also this include an API refactoring from my previous solution, also this it is suggested by @cdecker.

Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2021-09-22 16:23:24 +09:30
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
Vincenzo Palazzo 62ef403d20 doc: Update doc with the new parameter supported
Changelog-Added: Support to listpays the status parameter to filter the payments by status.

Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2021-09-22 16:23:24 +09:30
Vincenzo Palazzo ee8c7252a3 wallet db: Support the query on database with status and payment hash.
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2021-09-22 16:23:24 +09:30
Vincenzo Palazzo fd33aed4b5 rpc: Integrate the status flow in the listsendpays command
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2021-09-22 16:23:24 +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
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 789b330338 lightningd/closing_control.c: move json_close here from peer_control.c
They share some code, but not much: command_find_channel is made
non-static.  Rest is move-only.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-15 18:23:30 +02:00
Rusty Russell 183fe107e8 lightningd: use channel_type, pass to-and-from channeld.
Instead of explicit option_static_remotekey and option_anchor_outputs flags.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-13 15:53:23 +02:00
Rusty Russell 6ee8c40b29 closing: add option to set closing range.
This affects the range we offer even without quick-close, but it's
more critical for quick-close.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSONRPC: `close` now takes a `feerange` parameter to set min/max fee rates for mutual close.
2021-09-09 12:04:48 +09:30
Rusty Russell 79d7e83f51 --experimental-quick-close to enable quick-close negotiation
Based on a commit by @niftynei, but:
- Separated quickclose logic from main loop.
- I made it indep of anchor_outputs, use and option instead.
- Disable if they've specified how to negotiate.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-09 12:04:48 +09:30
Rusty Russell fb4edc2938 Makefile: update bolt version to include option_anchors_zero_fee_htlc_tx.
This touches a lot of text, mainly to change "if `option_anchor_outputs`"
to "if `option_anchors`"

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-09 12:04:48 +09:30
Rusty Russell d6192c2cb0 db: simple index addition to speed listpeers.
Fixes: #4718
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-09-04 13:41:35 +02:00
Rusty Russell 5bf2b5c0ba wallet: set a timeout if the db is busy.
This is recommended for litestream, which allows for easy async backup,
and harmless otherwise.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Changed: db: we now set a busy timeout to safely allow others to access sqlite3 db (e.g. litestream)
2021-08-26 12:44:02 +09:30
Rusty Russell fe86c117d9 datastore: turn keys into arrays
After some discussion with @shesek, and my own usage, we agreed that
a more comprehensive interface, which explicitly supports grouping,
is desirable.

Thus keys are now arrays, with the semantic that a key is either a
parent or has a value, never both.

For convenience in the JSON schema, we always return them as arrays,
though we accept simple strings as arguments.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-08-25 10:06:31 +02:00
Rusty Russell 533571a655 datastore: add generation, simple atomicity.
We add a generation counter, and allow update or del conditional
on a given generation.

Formalizes error codes, too, since we have more now.

Suggested-by: @shesek
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-08-25 10:06:31 +02:00
Rusty Russell 432508e65e datastore: allow replace/append.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-08-25 10:06:31 +02:00
Rusty Russell 2fb8735f04 wallet: add datastore access routines.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-08-25 10:06:31 +02:00
Rusty Russell df17387e05 wallet: add datastore for plugins to use.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-08-25 10:06:31 +02:00
Sebastian Falbesoner 48473eb3e9 wallet-test: fix segfault due to uninitialized block
The variable `block` (instace of `struct block`) is
allocated on the stack without being initialized, i.e. its
member `prev` points to nowhere. This causes a segmentation
fault on my machine on the binding of "prev_hash" on running
`wallet_block_add`, as the following core-dump analysis
shows:

    $ egdb ./wallet/test/run-wallet ./run-wallet.core
    [...]
    Core was generated by `run-wallet'.
    Program terminated with signal SIGSEGV, Segmentation fault.
    ---Type <return> to continue, or q <return> to quit---
    #0  0x000008f67a04b660 in memcpy (dst0=<optimized out>, src0=0x100007f8c, length=32) at /usr/src/lib/libc/string/memcpy.c:97
    97                      TLOOP1(*dst++ = *src++);
    (gdb) bt
    #0  0x000008f67a04b660 in memcpy (dst0=<optimized out>, src0=0x100007f8c, length=32) at /usr/src/lib/libc/string/memcpy.c:97
    #1  0x000008f73e838f60 in sqlite3VdbeMemSetStr () from /usr/local/lib/libsqlite3.so.37.12
    #2  0x000008f73e83cb11 in bindText () from /usr/local/lib/libsqlite3.so.37.12
    #3  0x000008f44bc91345 in db_sqlite3_query (stmt=0x8f6845bf028) at wallet/db_sqlite3.c:77
    #4  0x000008f44bc91122 in db_sqlite3_exec (stmt=0x8f6845bf028) at wallet/db_sqlite3.c:110
    #5  0x000008f44bcbb3b2 in db_exec_prepared_v2 (stmt=0x8f6845bf028) at ./wallet/db.c:2055
    #6  0x000008f44bcc6890 in wallet_block_add (w=0x8f688b5bba8, b=0x7f7ffffca788) at ./wallet/wallet.c:3556
    #7  0x000008f44bce2607 in test_wallet_outputs (ld=0x8f6a35a7828, ctx=0x8f6a35c0268) at wallet/test/run-wallet.c:1104
    #8  0x000008f44bcddec0 in main (argc=1, argv=0x7f7ffffcaaf8) at wallet/test/run-wallet.c:1930

Fix by explicitely setting the whole structure to zero.

[ Rebuilt generated files, too --RR ]
2021-08-23 19:46:04 +09:30
niftynei 4514d2a180 wallet-test: print better error message on failure 2021-08-17 13:20:00 +09:30
niftynei 773aa26321 utxos: more comprehensive fix for csv check
we only 'need' to check the CSV for 'option_anchor_outputs' (and even
then, really only ones with csv's greater than 1 but...)

Reported-In: #4697
2021-08-17 13:20:00 +09:30
Rusty Russell 66af5f8a28 chaintopology: tell gossipd that channels no longer exist on reorg.
This actually caused the flake in test_funding_reorg_private, where
l1 and l2 might not mark the original channel disabled.  In fact, they
should *remove* it as it gets reorged out.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-08-14 12:07:38 +09:30
Antoine Poinsot 8157e378f4 wallet: correct CSV check in `deep_enough`
Return false if the timelock didn't mature yet, not the other way
around.

Also, the check shouldn't be strict: if the CSV is 1 it is valid
at utxo->blockheight + 1.

Signed-off-by: Antoine Poinsot <darosior@protonmail.com>
2021-08-09 13:57:36 -05:00
Rusty Russell 44c469d52b disableoffer: fix disabling of already-used offers.
Turns out we didn't actually test this at all, and next commit does :(

    offer_status_in_db: 4 is invalid
    lightningd: FATAL SIGNAL 6 (version v0.10.0-459-g48fbd45-modded)
    0x5608cd360855 send_backtrace
	common/daemon.c:39
    0x5608cd3608ff crashdump
	common/daemon.c:52
    0x7f9af1dae20f ???
	???:0
    0x7f9af1dae18b ???
	???:0
    0x7f9af1d8d858 ???
	???:0
    0x5608cd30a47e fatal
	lightningd/log.c:819
    0x5608cd3430c5 offer_status_in_db
	wallet/wallet.h:1424
    0x5608cd34f1f3 wallet_offer_disable
	wallet/wallet.c:4494
    0x5608cd33ae2e json_disableoffer
	lightningd/offer.c:256
    0x5608cd3038fc command_exec
	lightningd/jsonrpc.c:643

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-07-21 13:27:27 -04:00
niftynei 03ccebc296 utxo: don't add outputs that aren't currently eligible to be spent
If an output's CSV lock hasn't been surpassed yet, don't try to
include it in a transaction
2021-07-20 13:28:38 -04:00
niftynei 86f7a179a9 channel utxo: persist the 'csv' lock value to database
Channel leases modify the CSV height that an output is eligible for
being spent at,  persist this to the database
2021-07-20 13:28:38 -04:00
niftynei 67b8a22aa7 channel: wire blockheight updates from channeld in to database 2021-07-20 13:28:38 -04:00
niftynei 265f960cfe liquidity-ads: persist channel blockheight states to disk
Adds new tables to database, backfills, basically copies the fee_rates
state machine for channeld.
2021-07-20 13:28:38 -04:00
niftynei a396c341cf lease_rates: persist channel's lease info 2021-07-20 13:28:38 -04:00
niftynei 04b6ad06cb change fees: more accurate rounding for change amount
We were getting off-by-one for the total amount that the change is for,
since it rounds the fee *down*, independent of the total weight of the
entire tx.

We fix this by using the diff btw the fee of the total weight (w/ and
w/o the change output)
2021-07-19 16:13:24 -04:00
Rusty Russell 33a40ca73b listinvoice: populate local_offer_id when iterating whole db.
And add the local_offer_id to the schemas too.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-EXPERIMENTAL: JSONRPC: `listoffers` now shows `local_offer_id` when listing all offers.
2021-07-03 12:13:45 +09:30
Christian Decker edf4b416c2 htlc: Wire extra TLV types into the HTLC onion decoding 2021-06-26 10:55:13 +09:30
Rusty Russell 9929d6383a channeld: add a message to read if we only want to reestablish.
This supports reestablish on a closed channel: we tell channeld to
respond to the reestablish message appropriately, then close the
channel.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-06-25 13:23:28 +09:30
Rusty Russell 9f8a6e2314 lightningd: always pass closing connections through channeld.
It handles all the cases of retransmission, and in the normal case
retransmits shutdown and immediately returns for us to run closingd.

This is actually far simpler and reduces code duplication.

[ Includes fixup to stop warn_unused_result from Christian ]

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Fixed: Protocol: We could get stuck on signature exchange if we needed to retransmit the final revoke_and_ack.
2021-06-25 13:23:28 +09:30
Rusty Russell 0a99b8c64c listtransactions: don't create a msat field called "satoshis".
That's a terrible, terrible idea.  (Documentation comes in later patch
which has the schema).

Also, blockheight is a u32, so simplify.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Deprecated: JSON-RPC: `listtransactions` `outputs` `satoshis` field (use `msat` instead).
2021-06-25 09:49:33 +09:30
Rusty Russell 064ad486e3 close: check that destination is going to be accepted.
Prior to this, sending a v1 address (or, in fact, any random crap!)
would cause the unsupporting node to unilaterally close.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-06-11 13:54:20 +09:30
Christian Decker a503032bab lightning: Add status field to htlc_in 2021-06-05 17:47:32 +09:30
Rusty Russell 220b6129bf wallet: save thresholds for option_static_remotekey.
Since we will soon be able to activate it on existing channels,
we need to mark the threshold.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-06-04 16:13:08 +09:30
Rusty Russell bf0320a53e openingd/dualopend: remove send_msg functionality.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-06-03 16:16:34 +09:30
Rusty Russell e2f225e4cd lightningd: use connectd to send the final error message, not openingd/dualopend
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-06-03 16:16:34 +09:30
Nalin Bhardwaj a88a6e604c wallet: sort listsendpays by ID
Changelog-Changed: JSON: `listsendpays` output is now ordered by `id`.
2021-06-01 11:14:38 -05:00
Vincenzo Palazzo 0ed7c0d083 Suggested code cleanup by TODO comment
This commit introduces the code cleanup suggested by the TODO comment in the code.

Basically, it moves the code from the if-else statement to a switch statement without the default case. I used the basic idea of the code used in PR #4507.

Changelog-Changed: None.

Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2021-05-31 11:52:07 +09:30
Rusty Russell bca8427317 Makefile: allow postfixes to SHA256STAMP.
For markdown, there's no simple comment prefix: we need a postfix too.
We also need to use "" since we want to use ' in some of the Makefiles
in future when V=1.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-05-27 20:28:49 +09:30
Rusty Russell efe29c9db8 sendpsbt, fundpsbt, utxopsbt, reserveinputs, unreserveinputs: allow custom number of blocks to reserve.
Not an API break: reserve=true|false still works for fundpsbt and utxopsbt,
but we also allow a raw number in there.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-05-26 15:08:01 +09:30
Rusty Russell f24dc9173d wallet: add "reserved_to_block" field to listfunds.
We already have this field in reserveinputs and unreserveinputs.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: `listfunds` has a new `reserved_to_block` field.
2021-05-26 15:08:01 +09:30
Antoine Poinsot fe8074c8c3 Refuse to parse v2 onion addresses without deprecated_apis
Tor v2 hidden services have been deprecated for a while:
https://blog.torproject.org/v2-deprecation-timeline .

This prevents user from being able to set them in the configuration
and to connect to them while still letting us be able to parse them
for gossip.

Changelog-Deprecated: lightningd: v2 Tor addresses.  Use v3.  See https://blog.torproject.org/v2-deprecation-timeline.

Signed-off-by: Antoine Poinsot <darosior@protonmail.com>
2021-05-24 20:22:45 +09:30
niftynei d04c373283 rbf: when a channel is open, remove all the inflights
The channel's open has been mined, we don't need to keep all of these around
now.
2021-05-24 12:17:48 +09:30
niftynei 062bc12813 rbf: update the channel's funding_txid to match what's mined
If the peer is offline when we see the funding txid, we don't actually
update the channel's info. Here, we move it up to where the scid is set,
so that we always update the channel's funding_txid to the correct
(mined) information.
2021-05-24 12:17:48 +09:30
niftynei 4247ec3a05 inflights: save the whole psbt to the database
Otherwise we're missing info when we go to broadcast these and can't
properly sign the transaction to close it.

Found-by: @jasan
2021-05-24 12:17:48 +09:30
niftynei 82fa3fa2ef df-rbf: order inflights by funding_feerate
When we re-populate from disk, we need to know what order to recreate the
inflights list in.

Fixes #4511
2021-05-24 12:17:48 +09:30
niftynei 9a1041ee97 fundpsbt: dont add utxos that are a net-loss
if the utxo can't pay for its own fees, dont put it in the tx

Changelog-Changed: JSONRPC: fundpsbt will not include UTXOs that aren't economic (can't pay for their own fees), unless 'all'
2021-05-23 08:19:50 +09:30
Rusty Russell 25b5e1e099 update-mocks: make sure we cover all test programs.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-05-22 17:53:04 +09:30
Rusty Russell cc6f1fd120 update-mocks: don't try to regenerate files.
If you do update-mocks in a dirty tree, the recursive make that it
uses will try to rebuild things!  Suppress that.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-05-22 17:53:04 +09:30
fiatjaf 0d68febd8d reorganize .gitignore entries across subdirs. 2021-05-18 09:43:50 +09:30
niftynei 71a4a2e31c df: rework closing logic
Trying to put all the disconnect logic into the same path was a dumb
idea. If you asked to reconnect but passed in an 'unsaved' channel, we
would not call the 'reconnect' code.

Instead, we make a differentiation between "unsaved" channels
(ones that we haven't received commitment tx for) and handle the
disconnect for these separate from where we want to do a reconnect.
2021-05-12 11:25:41 +09:30
Rusty Russell 9c3cf5aff9 newaddr: don't include "address" field.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Removed: JSON-RPC: `newaddr` no longer includes `address` field (deprecated in 0.7.1)
2021-04-07 14:34:39 +09:30
Rusty Russell 9dbac21d3b doc: remove suffix for included-in-master BOLTs.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-04-07 14:34:39 +09:30
Rusty Russell 006300ab96 lightningd: set "direction" correctly for connect which is already connected.
This means remembering the connection direction.  We also use the address to try
to reconnect, which we shouldn't bother with if they connect to us.

For peers from the database, we currently always save the addr: we shouldn't really
do this if they connected to us, since it's not useful for reconnecting (we don't
show the addr in JSON reply to listpeers unless we're connected, so it's only an
internal issue).  This is left for future work.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-03-26 13:22:33 +10:30
Rusty Russell b0d6996ed6 lightningd: get connection direction from connectd.
This matters: if we connected, the address is probably usable for future connections.
But if they connected, the port is probably not (but the IP address may be).

Changelog-Added: JSON-RPC: `connect` returns "direction" ("in": they iniatated, or "out": we initiated)
Changelog-Added: plugins: `peer_connected` hook and `connect` notifications have "direction" field.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-03-26 13:22:33 +10:30
niftynei fba1191f06 df: actually save the peer's sigs transmission to disk
Otherwise we have no idea whether or not they actually sent their sigs
or not.
2021-03-17 10:25:18 +10:30
Rusty Russell 6c9d9ee9a2 connect: return address we actually connected to.
Otherwise, we might find an address other than the one given and
the user might think that address worked.

Fixes: #4185
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: `connect` returns `address` it actually connected to
2021-03-17 08:38:08 +10:30
Rusty Russell b62706aa01 close: accept wrong_funding outpoint arg if we negotiated the feature.
Changelog-Added: lightningd: experimental-shutdown-wrong-funding to allow remote nodes to close incorrectly opened channels.
Changelog-Added: JSON-RPC: close has a new `wrong_funding` option to try to close out unused channels where we messed up the funding tx.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-03-16 13:08:40 +10:30
Rusty Russell 820fbcd65a channeld: code to send wrong_funding if lightningd says to.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-03-16 13:08:40 +10:30
Rusty Russell 80c2f28373 channeld: accept the 'wrong_funding' shutdown TLV.
If it passes checks, lightningd puts it in the database.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-03-16 13:08:40 +10:30
Rusty Russell cce280400c wallet: out "wrong_funding" information in the db for persistence.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-03-16 13:08:40 +10:30
niftynei bec96a6c5b df: add openchannel_abort command
Allows us to clean up an in-progress open that we won't be completing

Changelog-Added: EXPERIMENTAL JSON-RPC: Permit user-initiated aborting of in-progress opens. Only valid for not-yet-committed opens and RBF-attempts
2021-03-15 14:08:44 +10:30
Christian Decker 1ed08746d3 wallet: Do not generate basepoints in the hsmd
We now load them from the DB, and don't need the keys to be present at
startup.
2021-03-09 14:58:29 +10:30
Christian Decker 039751b875 wallet: Load local basepoints from the database alongside the hsmd 2021-03-09 14:58:29 +10:30
Christian Decker ae7d722ec5 wallet: Store local channel basepoints when a new channel is created 2021-03-09 14:58:29 +10:30
Christian Decker 4887a5a18f db: Add migration for the local basepoints and the funding pubkey 2021-03-09 14:58:29 +10:30
Christian Decker bc42e8df13 db: Add the migration_context to hold info required by migrations 2021-03-09 14:58:29 +10:30
Christian Decker 2f6e33a7cd wallet: Add migration to cache local basepoints from the HSMd 2021-03-09 14:58:29 +10:30
niftynei 07153bff6a df: cleanup error handling on lightningd side
Make existing methods understand how unsaved channels work, re-work
errors so that we handle everything appropriately
2021-03-06 15:03:56 +10:30
niftynei a23277af57 listpeers: include info on channels that are in-process
Channels that we're in negotiation for, but don't have a commitment
transaction saved for yet.
2021-03-06 15:03:56 +10:30
niftynei ff069ff924 rbf: consolidate failure paths, use "warnings"
We move over to the new "warning" paradigm, instead of using
an "rbf_fail" message.

Every failure is either a warning or an error; on warnings we
hang up and reconnect later, effectively resetting the state.
2021-03-06 15:03:56 +10:30
Rusty Russell 4dcd4ca155 listpeers: add latest feerate and actual last fee amount.
Users have no idea what they would pay for unilateral closes.
At least this gives them a clue!

Reported-by: @az0re on IRC.

Changelog-Added: JSON-RPC: `listpeers` now shows latest feerate and unilaral close fee.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-03-05 13:12:41 +10:30
niftynei da81d4bced channel: skip unsaved channels
Now that "peer->channels" contains `unsaved` channels, skip overthem
where appropriate
2021-03-03 16:19:04 -06:00
niftynei 538fd670ce df: add helper for creating an "unsaved" channel
Channel that's not saved to database yet
2021-03-03 16:19:04 -06:00
niftynei 4baa10ef68 channel: remove `psbt` and `remote_tx_sigs`
We just added this, but we've migrated them to the "inflight" struct
instead, as they actually pertain to an single inflight open attempt
2021-03-03 12:28:22 +10:30
niftynei 36f3b13279 inflight: add a 'channel-inflight' concept, in-progress channel stuffs
"inflights" are all potential channel funding transactions that we
currently have commitment transactions for.
2021-03-03 12:28:22 +10:30
Karol Hosiawa c1e958d2b9 Added index to forwarded_payments.state to speedup lookups using this column 2021-03-03 09:19:20 +10:30
Karol Hosiawa 8a8f81175d Added in_channel,out_channel,state params to listforwards 2021-03-03 09:19:20 +10:30
Christian Decker ebb1b19c65 plugin: Fix the custommsg hook not to include the internal prefix
We were always prefixing the `message` field with the internal type
prefix 0x0407, followed by the length prefix. Neither is needed since
the type being constant is of no interest to the plugin and the length
being implicit due to the JSON-encoding.

Reported-by: Ilya Evdokimov
Changelog-Fixed: plugin: The `custommsg` hook no longer includes the internal type prefix and length prefix in its `payload`
Changelog-Deprecated: plugin: The `message` field on the `custommsg` hook is deprecated in favor of the `payload` field, which skips the internal prefix.
2021-03-02 14:41:16 +10:30
Rusty Russell 874ca99c32 offers: make 'used' flag more useful.
We used to only set it for single-use offers (where it's required),
but it's still interesting for multi-use offers, so let's keep it
there.

We also put this field in the documentation.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-02-25 14:44:03 +10:30
Christian Decker c8f7cfe224 gen: Commit derived files for PR #4378 2021-02-25 11:06:22 +10:30
Christian Decker 6252930c82 db: Set the failonion to the default value on creation
This ensures that after the migration in the previous commit we never
insert a new htlc with a null value.

Fixes: #4363

Reported-by: Zoltán Gálli <@gallizoltan>
Changelog-Fixed: db: Fixed an access to a NULL-field in the `channel_htlcs` table and resulting warning.
2021-02-25 11:06:22 +10:30
Christian Decker 2c1411a70b db: Set the failonion on channel_htlcs if is is not set 2021-02-25 11:06:22 +10:30
Christian Decker 8818645316 Regenerate derived files 2021-02-11 09:48:55 +01:00
Christian Decker 87d3818c63 wallet: Fix a potential memory leak when loading state changes
The leak exists if we `tal_free` the result array onto another parent,
but the `ctx` we allocated on is still valid. This leads to a
temporary gap in the ownership tree which is then reported as the
following error:

```text
- Node /tmp/ltests-ufn3ox3p/test_htlc_out_timeout_1/lightning-1/ has memory leaks: [
   {
       "backtrace": [
           "ccan/ccan/tal/tal.c:442 (tal_alloc_)",
           "ccan/ccan/tal/tal.c:471 (tal_alloc_arr_)",
           "ccan/ccan/tal/tal.c:799 (tal_dup_)",
           "ccan/ccan/tal/str/str.c:18 (tal_strdup_)",
           "wallet/wallet.c:1652 (wallet_state_change_get)",
           "lightningd/peer_control.c:869 (json_]add_channel)",
           "lightningd/peer_control.c:1319 (json_add_peer)",
           "lightningd/peer_control.c:1348 (json_listpeers)",
           "lightningd/jsonrpc.c:643 (command_exec)",
           "lightningd/jsonrpc.c:753 (rpc_command_hook_callback)",
           "lightningd/plugin_hook.c:288 (plugin_hook_call_)",
           "lightningd/jsonrpc.c:808 (plugin_hook_call_rpc_command)",
           "lightningd/jsonrpc.c:888 (parse_request)",
           "lightningd/jsonrpc.c:979 (read_json)",
           "ccan/ccan/io/io.c:59 (next_plan)",
           "ccan/ccan/io/io.c:435 (io_do_always)",
           "ccan/ccan/io/poll.c:300 (handle_always)",
           "ccan/ccan/io/poll.c:377 (io_loop)",
           "lightningd/io_loop_with_timers.c:24 (io_loop_with_timers)",
           "lightningd/lightningd.c:1016 (main)"
       ],
       "label": "wallet/wallet.c:1652:char[]",
       "parents": [
           "common/json_stream.c:29:struct json_stream",
           "ccan/ccan/io/io.c:91:struct io_conn",
           "lightningd/lightningd.c:116:struct lightningd"
       ],
       "value": "0x556b0856ab68"
   },
```

Changelog-None
2021-02-11 09:48:55 +01:00
niftynei 0d4bb06dad reservations: add weight of fee-output to weight calculation
have the estimated fee include all the weight, even fee outputs
2021-02-04 13:25:34 -06:00
niftynei ea95ad9c12 fund/utxopsbt: flag 'excess_as_change' to add a change output for excess
In the case where you want a PSBT and also want the output to be added
as a change address, use `excess_as_change` = true.

Generates a change address to use. If you want to pay the excess
elsewhere, you will have to add separately.

Changelog-Added: JSON-RPC: Add new parameter `excess_as_change` to fundpsbt+utxopsbt
2021-02-04 13:25:34 -06:00
Rusty Russell 6b11cc8b8c common: disallow NULL channel_id to peer_failed_err.
No more sending "all-channel" errors; in particular, gossipd now only
sends warnings (which make us hang up), not errors, and peer_connected
rejections are warnings (and disconnect), not errors.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Changed: Plugins: `peer_connected` rejections now send a warning, not an error, to the peer.
2021-02-04 12:02:52 +10:30
niftynei 8591f11188 wallet nit: consolidate stmt free into one line 2021-01-25 10:05:17 +10:30
niftynei 6778ea5d05 wallet: cleanup fee_states alloc on error 2021-01-25 10:05:17 +10:30
ZmnSCPxj jxPCSnmZ 4dfbee47f7 wallet/db.c: Speed up deletion of single peers.
ChangeLog-Fixed: Database: Speed up deletion of peer especially when there is a long history with that peer.
2021-01-19 09:56:12 +01:00
niftynei 9fdf1ea32a df: reinitialize dual-funding
Prior to this, all reconnect logic lived in channeld. If you
disconnected before we finished building a funding transaction, that was
no big deal. Now, however, we're waiting for the funding to lock in in
dualopend, instead of handing straight to channeld to wait.

So we need a way to restart dualopend.
2021-01-10 13:44:04 +01:00
niftynei fd2e16f8bc db: add flag to database for recving remote's sigs
We need to know if they've sent us their sigs message yet. Ideally, we'd
be able to check the 'finalness' of the PSBT, however if the peer
doesn't have any inputs to the channel this doesn't work.
2021-01-10 13:44:04 +01:00
niftynei 90d936bb60 df: handle shutdown (before lockedin) in dualopend
A channel can be closed before it locks in. This lets dualopend handle
shutdown messages from the peer before the channel is locked in.
2021-01-10 13:44:04 +01:00
niftynei e0e929ed14 peer_control: remove PSBT from peer_start_channeld
Since we're moving all of the PSBT signing to dualopend, we no longer
need a PSBT to be passed to channeld
2021-01-10 13:44:04 +01:00
Christian Decker 8e908ff652 Revert "wallet: Remove in-memory utxoset filter"
This reverts commit c239a7161b.

The goal of c239a716 was to reduce the memory footprint of our
internal UTXO set tracking, and testing against the sqlite3 backend
showed no performance impact. We have since found that the added
roundtrips to the DB server with postgres was having a considerable
performance impact, and backups would also bloat due to the increased
number of queries.

Undoing this change skips the noop updates that were causing this
regression.

Changelog-Fixed: db: Fixed a performance regression during block sync, resulting in many more queries against the DB than necessary.
2021-01-08 12:08:32 +10:30
Karol Hosiawa a2c208e121 Added spent option to listfunds
Changelog-Added: JSON-RPC: The `listfunds` method now includes spent outputs if the `spent` parameter is set to true.
2020-12-22 13:00:02 +01:00
Rusty Russell 723c16072a cleanups: feedback from Christian Decker review.
1. Hoist 7200 constant into the bolt12 heade2.
2. Make preimage the last createinvoice arg, so we could make it optional.
3. Check the validity of the preimage in createinvoice.
4. Always output used flag in listoffers.
5. Rename wallet offer iterators to offer_id iterators.
6. Fix paramter typos.
7. Rename `local_offer_id` parameter to `localofferid`.
8. Add reference constraints on local_offer_id db fields.
9. Remove cut/paste comment.
10. Clarify source of fatal() messages in wallet.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-12-15 12:05:02 +01:00
Rusty Russell a33e39b7e8 pay, wallet: rename internal `bolt11` vars to `invstring`.
And handle bolt12 strings if EXPERIMENTAL_FEATURES.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-12-15 12:05:02 +01:00
Rusty Russell 4c4288e3e5 invoice: handle bolt12 strings if EXPERIMENTAL_FEATURES.
The database still calls them `bolt11`, but we treat them depending on
prefix.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-12-15 12:05:02 +01:00
Rusty Russell fab0842d31 lightningd: createinvoice low-level invoice creation command.
This takes an unsigned bolt11 (or bolt12 if EXPERIMENTAL_FEATURES) string
and signs it and puts it in the database.

The invoice command could now be moved out to a plugin, in fact.

Changelog-Added: JSON-RPC: `createinvoice` new low-level invoice creation API.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-12-15 12:05:02 +01:00
Rusty Russell 3f4683e3f8 sendpay: optional argument to link local offer.
This is for offers which have `send_invoice`: we need to associate the
payment with the original offer, in (the usual) case where it is a single
use offer.  We mark it used when it's paid, to avoid a race.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-12-15 12:05:02 +01:00
Rusty Russell 963f6b5d67 invoice: add an optional local_offer_id.
This allows us to mark an offer used when an invoice derived from it
is paid, and importantly, avoid any other invoices for the offer being
paid.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-12-15 12:05:02 +01:00
Rusty Russell 381b0f456c db: offer table.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-12-15 12:05:02 +01:00
Rusty Russell 32c7c133f4 common/sphinx: make onionpacket.routinginfo a dynamic member.
Still asserts that it's the standard size, but makes it a dynamic
member.  For simpliciy, changes the parse_onionpacket API (it must be
a tal object now, so we might as well allocate it here to catch all
the callers).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-12-11 15:51:24 +01:00
Rusty Russell 25b0dbe7e8 wallet: remove debugging fprintf.
Left over from e81d78ec4c.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-12-10 20:32:18 +10:30
Rusty Russell 1a3c0a0c0d invoice: fix potential race where invoice is paid/expired while we're calling hook.
There's actually a (very unlikely) race here: we would previously have
crashed with an assertion in invoices_resolve.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-12-02 16:50:12 +10:30
niftynei e81d78ec4c fundpsbt/utxopsbt: new `min_witness_weight` param
Needed for v2 of channel opens, where the minimum weight is 110; a
'simple utxo' (sig + key) weighs in at 107, so we a need a way to
establish a floor for this case.

Changelog-Added: JSON-RPC: fundpsbt/utxopsbt have new param, `min_witness_utxo`, which sets a floor for the weight calculation of an added input
2020-12-02 14:19:08 +10:30
Rusty Russell ca2bd98082 unittest: use common_setup / common_shutdown almost everywhere.
Avoids much cut & paste.  Some tests don't need any of it, but most
want at least some of this infrastructure.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-12-02 12:55:09 +10:30
Michael Schmoock 6cc96c07dc feat: adds state_changes to listpeers output
Changelog-Added: RCP: Added 'state_changes' history to listpeers channels
2020-11-06 14:47:04 -06:00
Michael Schmoock 88c1dc56e8 db: adds a state_change history to database 2020-11-06 14:47:04 -06:00
Michael Schmoock 68ce25c92d feat: adds timestamp to state_change notification 2020-11-06 14:47:04 -06:00
Michael Schmoock b7c18517df rpc: adds opener and closer to listpeers channels
Changelog-Added: RPC: Added 'opener' and 'closer' to listpeers channels
2020-11-06 14:47:04 -06:00
Michael Schmoock 083a856c31 db: persist channel closer and state change cause 2020-11-06 14:47:04 -06:00
Michael Schmoock 8a8dabaa58 feat: adds state change cause and message
This adds a `state_change` 'cause' to a channel.
A 'cause' is some initial 'reason' a channel was created or closed by:

  /* Anything other than the reasons below. Should not happen. */
  REASON_UNKNOWN,
  /* Unconscious internal reasons, e.g. dev fail of a channel. */
  REASON_LOCAL,
  /* The operator or a plugin opened or closed a channel by intention. */
  REASON_USER,
  /* The remote closed or funded a channel with us by intention. */
  REASON_REMOTE,
  /* E.g. We need to close a channel because of bad signatures and such. */
  REASON_PROTOCOL,
  /* A channel was closed onchain, while we were offline. */
  /* Note: This is very likely a conscious remote decision. */
  REASON_ONCHAIN

If a 'cause' is known and a subsequent state change is made with
`REASON_UNKNOWN` the preceding cause will be used as reason, since a lot
(all `REASON_UNKNOWN`) state changes are a subsequent consequences of a prior
cause: local, user, remote, protocol or onchain.

Changelog-Added: Plugins: Channel closure resaon/cause to channel_state_changed notification
2020-11-06 14:47:04 -06:00
Christian Decker d487ec5c9b wallet: Remove orphan statements.po file 2020-10-29 11:11:48 +10:30
Rusty Russell 497e71ca13 Makefile: fix bashism in NO_PYTHON
== is a bash extension; in shell it's a single =:

```
/bin/sh: 1: [: unexpected operator
sql-rewrite wallet/db_postgres_sqlgen.c
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-10-26 21:28:36 -05:00
Rusty Russell 1e5789d421 close: add notification for slow closes.
For compatibility, we only do this if `allow-deprecated-apis` is false
for now.  Otherwise scripts parsing should use `grep -v '^# '` or
start using `-N none`.

Changelog-Added: JSON-RPC: `close` now sends notifications for slow closes (if `allow-deprecated-apis`=false)
Changelog-Deprecated: cli: scripts should filter out '^# ' or use `-N none`, as commands will start returning notifications soon
Fixes: #3925
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-10-23 13:53:16 +10:30
Rusty Russell a8177e9013 Makefile: make check-includes check all the non-generated files.
Note that check-whitespace and check-bolt already do this, so we
can eliminate redundant lines in common/Makefile and bitcoin/Makefile.

We also include the plugin headers in ALL_C_HEADERS so they get
checked.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-10-22 12:14:34 +10:30
niftynei a7d4b8780e elementsd: disable dual-funding test; don't add non-witness utxo
Elementsd needs to be updated to v0.20.0 in order for this to work as
expected
2020-10-20 12:50:31 +10:30
niftynei 818f152618 channel: save funding_psbt to database
Only populated until we receive the peer's funding_locked
2020-10-20 12:50:31 +10:30
niftynei b2ec5a9f45 peer_channeld: pass over PSBT, remove second message
We need the PSBT to create the finalized tx from once the peer's
tx_signatures are received. Since we're passing the PSBT, we no longer
need the secondary message to be passed, as it was derived from the
PSBT.

Also removes now unused witness serialization code
2020-10-20 12:50:31 +10:30
niftynei d0702e05dd psbt: add the full transaction for the utxo in a psbt
We need this for dual funding, since the interactive tx construction
protocol requires the full tx to send places. We add it to all PSBTs (if
we have it), here
2020-10-20 12:50:31 +10:30
niftynei 3c98bec693 db: add helper for db_col_psbt
We had db_bind_psbt; this is the missing symmetric response to that
2020-10-20 12:50:31 +10:30
niftynei e2a6fd7112 common: pull up `param_psbt`
Usable other places, not just in wallet
2020-10-20 12:50:31 +10:30
Michael Schmoock db19f19eb3 chore: adds env NO_PYTHON check to Makefiles
This adds an environment variable $NO_PYTHON check to Makefiles so that:
 - It checks and runs into an defined error instead of some python hickup:
   `ModuleNotFoundError: No module named 'mako'`
 - makes it possible to manually export this environment variable NO_PYTHON=1
   to run the same testcase that travis is running on job 1 which causes
   so much pain ;)

Changelog-None
2020-10-19 13:17:03 +02:00
Christian Decker 77ca07e91d db: Fix statement expansion bugs found through dblog mode 2020-10-10 11:34:43 +10:30
Michael Schmoock 011590b20e fix: broken SQL statement in wallet db_set_utxo
I discovered this accidentally when using the `tests/plugins/dblog.py`
plugin on another testcase: tests/test_connection.py::test_fail_unconfirmed

There the plugin/hook crashes because it can't execute the statement:
```json
{
  "jsonrpc": "2.0",
  "id": 34,
  "error": {
    "code": -32600,
    "message": "Error while processing db_write: unrecognized token: \"174WHERE\"",
    "traceback": "Traceback (most recent call last):\n  File \"/home/will/projects/lightning.git/contrib/pyln-client/pyln/client/plugin.py\", line 535, in _dispatch_request\n    result = self._exec_func(method.func, request)\n  File \"/home/will/projects/lightning.git/contrib/pyln-client/pyln/client/plugin.py\", line 520, in _exec_func\n    return func(*ba.args, **ba.kwargs)\n  File \"/home/will/projects/lightning.git/tests/plugins/dblog.py\", line 45, in db_write\n    plugin.conn.execute(c)\nsqlite3.OperationalError: unrecognized token: \"174WHERE\"\n"
  }
}
```

Changelog-Fixed: plugin: Regression with SQL statement expansion that could result in invalid statements being passed to the `db_write` hook.
2020-10-10 11:34:43 +10:30
Rusty Russell 7260d9ea3d plugins: generate list of plugins more atomically, respect V=1 and --quiet.
I got a corrupt file, which looked like multiple concurrent attempts
to build it.  So instead, build it in one command, but also use
VERBOSE so we print correctly with V=1 (and --quiet).

Also move into plugins/ where it logically belongs.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-09-24 13:19:59 +02:00
Rusty Russell 488b32b003 build: run update-mocks.
Some declarations are redundant now.  Removing them does nothing, but
it makes other PRs cleaner.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-09-24 13:19:59 +02:00
Rusty Russell d5cb0d85b5 utils: use a cleaner pattern to capture wally allocations.
We force use of tal_wally_start/tal_wally_end around every wally
allocation, and with "end" make the caller choose where to reparent
everything.

This is particularly powerful where we allocate a tx or a psbt: we
want that tx or psbt to be the parent of the other allocations, so
this way we can reparent the tx or psbt, then reparent everything
else onto it.

Implementing psbt_finalize (which uses a behavior flag antipattern)
was tricky, so I ended up splitting that into 'psbt_finalize' and
'psbt_final_tx', which I think also makes the callers clearer.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-09-23 14:45:53 +02:00
Christian Decker 1d9e7cf079 db: Add support for key-value pair DSNs in postgresql
These are simple space-separated key-value pair sets of options instead of the
URI style DSNs, but they are also much more flexible allowing the user to
specify client SSL certificates, server certificates, compression and
encryption levels, and much more (see [1] for more information)

[1]: https://www.postgresql.org/docs/9.1/libpq-connect.html

Changelog-Added: db: Added support for key-value DSNs for postgresql, allowing for a wider variety of configurations and environments.
2020-09-23 20:20:40 +09:30
Rusty Russell 58f6e316cc lightningd: separate fee_states out of struct channel_info.
It was always kind of weird in there anyway.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-09-23 15:51:13 +09:30
Rusty Russell 77b62d9e42 bitcoin/psbt: psbt_finalize needs a tal ctx.
Since it returns a wally_tx.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-09-23 13:52:49 +09:30
Christian Decker de7b41695f db: Fix size mismatch on postgres in a migration
Changelog-Fixed: db: Fixed a broken migration on postgres DBs that had really old channels.
2020-09-23 10:48:31 +09:30
Matt Whitlock eab14768a8 update SHA256STAMPs using sorted dependencies 2020-09-17 10:23:40 +09:30
Vincenzo Palazzo f62d7bbe45 Added additional fix to code formatting and English spelling.
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2020-09-10 17:27:51 +09:30
Vincenzo Palazzo 9fbeb9bcdc delpay: code style changes and fixed docs
Changelog-Added: JSON-RPC: delpay a new method to delete the payment completed or failed.

Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2020-09-10 17:27:51 +09:30
niftynei 273f0991b0 elements: include the value + asset tag for 'PSET's
Not strictly necessary as technically this info is included in the
witness_utxo, but nice to have
2020-09-10 12:31:36 +09:30
Michael Schmoock d86855d1f7 feat: adds channel_state_changed notification
This notification will be raised whenever a channel state changes.
The payload includes the channel and peer identifiers and the
old and the new state.

Example payload:

```
{
    "channel_state_changed": {
        "peer_id": "03bc9337c7a28bb784d67742ebedd30a93bacdf7e4ca16436ef3798000242b2251",
        "channel_id": "a2d0851832f0e30a0cf778a826d72f077ca86b69f72677e0267f23f63a0599b4",
        "short_channel_id" : "561820x1020x1",
        "old_state": "CHANNELD_NORMAL",
        "new_state": "AWAITING_UNILATERAL"
    }
}
```

Changelog-Added: Plugins: channel_state_changed notification
2020-09-10 10:24:06 +09:30
niftynei c50f377a85 psbt: pull out changeset logic into common, update API
Greatly simplify the changeset API. Instead of 'diff' we simply generate
the changes.

Also pulls up the 'next message' method, as at some point the
interactive tx protocol will be used for other things as well
(splices/closes etc)

Suggested-By: @rustyrussell
2020-09-09 19:54:20 +09:30
niftynei 5cd06227d7 build: exclude dualopend from non-experimental builds 2020-09-09 19:54:20 +09:30
niftynei 303263d381 psbt: clean up interface for setting metadata on PSBT inputs
it's just neater if it's not all wrapped up together, simplifies the
interface a smidge
2020-09-09 19:54:20 +09:30
niftynei 8d429ecd06 df: add needed info to any PSBT we produce
dual funding needs the max-witness-len and utxo fields set for every
input. we should add them when we create a 'fundpsbt', so that every
psbt that c-lightning generates is dual-funding ready
2020-09-09 19:54:20 +09:30