Commit Graph

2885 Commits

Author SHA1 Message Date
Rusty Russell 0135d563a0 pytest: write test to ensure renepay the correct channel's fee/cltv info.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-31 16:13:21 +09:30
Rusty Russell b88583e346 db: migrate old runes table to fix up id fields.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-31 05:33:15 +09:30
Rusty Russell 2de304314a runes: insert rune with correct id field.
"id" is a magic name, so it was being populated by sqlite3
automatically, starting at 0.  Fortunately, we only fetched by id in
one place: to indicate the `stored` flag when asked about an explicit
rune in `showrunes`.

Reported-by: @ShahanaFarooqui
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Fixed: JSON-RPC: `showrunes` on a specific rune would always say `stored`: false.
2023-08-31 05:33:15 +09:30
Rusty Russell 7429b1e7e1 pytest: test to show that we got db ids incorrect.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-31 05:33:15 +09:30
Rusty Russell 138d178dff pytest: fix plugin_connected_hook_chaining flake.
The code to workaround the intermittant error didn't work,
and we finally hit it again:

```
        # If reject happens fast enough, connect fails with "disconnected
        # during connection"
        try:
            l3.connect(l1)
        except RpcError as err:
>           assert "disconnected during connection" in err.error
E           assert 'disconnected during connection' in {'code': 402, 'message': 'disconnected during connection'}
E            +  where {'code': 402, 'message': 'disconnected during connection'} = RpcError("RPC call failed: method: connect, payload: {'id': '0266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c03518', 'host': '127.0.0.1', 'port': 41865}, error: {'code': 402, 'message': 'disconnected during connection'}").error
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-21 21:14:01 +09:30
Rusty Russell dec8ad3b8d pytest: fix autoclean test flake
```
        l3.rpc.setconfig('autoclean-cycle', 10)
    
        # First it expires.
>       wait_for(lambda: only_one(l3.rpc.listinvoices('inv1')['invoices'])['status'] == 'expired')

```

If we're slow enough, the invoice is cleaned before we see it expire!
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-21 21:14:01 +09:30
Rusty Russell b5d1708900 plugins/sql: make testing-only sqlfilename option `dev-sqlfilename`.
dev options don't need to be documented, and this is only for debugging
the plugin itself.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-18 20:29:34 +09:30
Rusty Russell d3c7d48acb pay: don't discard high-htlc_min channels when searching for routehint starts.
As side-effect, getroute(0) is special too.

Reported-by: MiddleW4y in Discord
Fixes: #6577
Changelog-Fixed: `pay` will still use an invoice routehint if path to it doesn't take 1-msat payments.
2023-08-18 14:55:32 +09:30
Rusty Russell 2c3f8b8a04 pytest: test that we can pay via routehints even if a 1000-min-htlc channel is in path.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-18 14:55:32 +09:30
Rusty Russell f4e2d9a0ae lightningd: clean up properly if we fail to exec plugin.
Reported-by: @niftynei
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Fixed: Plugins: we clean up properly if a plugin fails to start, and we don't kill all processes if it's from `plugin startdir`.
2023-08-18 13:18:49 +09:30
Rusty Russell 04ddb4af8d pytest: test that failing to start a plugin due to failure to exec does not put it in plugins list.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-18 13:18:49 +09:30
Rusty Russell bc36a4580c pytest: test (failing) for not crashing if plugin fails to exec via `plugin startdir`
It hits the new assert(): before that (tested!) it actually kills everything and logs you out.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-18 13:18:49 +09:30
Dusty Daemon c67f1f92a8
splice: prevent splice going to onchaind & race prevention
Don’t send the funding spend to onchaind if we detect it in inflights (aka. a splice). While we already prevented onchaind_funding_spent from being called directly, the call to wallet_channeltxs_add meant onchaind_funding_spent would be called *anyway* on restart. This is now fixed.

Additionally there was a potential for a race problem depending on the firing order of the channel depth and and funding spent events.

Instead of requiring these events fire in a specific order, we make a special “memory only” inflight object to prevent the race regardless of firing order.

Changelog-Fixed: Splice: bugfix for restart related race condition interacting with adversarial close detection.
2023-08-16 12:28:53 +09:30
Alex Myers 553369896b pytest: add no argument cli test 2023-08-16 12:25:25 +09:30
Rusty Russell 6a16a6fe25 closingd: fix case where we we can pass under min-relay-fee for mutual close.
In spec commit 498f104fd399488c77f449d05cb21c0b604636a2 (August 2021),
Bastien Teinturier removed the requirement that the mutual close fee be
less than or equal the final commitment tx.

We adopted that change in v0.10.2, but we made sure to never offer a fee
under the final commitment tx's fee, so we didn't break older nodes.

However, the closing tx can actually be larger than the final commitment tx!
The final commit tx has a 22-byte P2WKH output and a 34-byte P2WSH output;
the closing can have two 34-byte outputs, making it 4*8 = 32 Sipa heavier.
Previously this would only happen if both sides asked for P2WSH outputs,
but now it happens with P2TR, which we now do.

The result is that we create a tx which is below the finally commitment
tx fee, and may be below minrelayfee (as it was in regtest).

So it's time to remove that backwards-compatibility hack.

Changelog-Fixed: Protocol: We may propose mutual close transaction which has a slightly higher fee than the final commitment tx (depending on the outputs, e.g. two taproot outputs).
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Fixes: #6545
2023-08-12 13:17:46 +09:30
Rusty Russell a9c05d7d16 pytest: test for mutual close fail under very low feerates.
```
$ l1-cli close 445x1x1 
# Sending closing fee offer 183sat, with range 0sat-183sat
# Received closing fee offer 183sat, with range 0sat-1000000sat
{
   "tx": "0200000000010153ce29f4df20875492760ec51092d01ade3da99ffd72c3ff47b02e8f78a5845a0100000000ffffffff02b882010000000000225120847b3d31b036c0b4fad77fd41805f375f4fc9507d52f2a19d858b43975a633b0d1be0d000000000022512017912fd7fc767d03e02461bd932556d78291ea226db5efec84d84a5c753a650a0400473044022005b184a595ec0b650dffb3168d003b13ae0d98d456d879ec7fac7012f3dbad6202202f5a9620a59fb3cb9269be3b2a941f18fe1b7e3037c259125c56d3ec86c8e91a014730440220559f1c2a578e35a975466bb6f2319d313cd79070add77c51b6f6aeb25f7eae9802204749e84e7f8a777c66896a38588f6046a28653a493c34c79a0080580a0f389ec01475221024ff290301210ddffa14db591eb629d864bb4b4583586f5bffaaebc4ca8d5edef2102e0de3f54ca6cf38cb527b326242bf418a4a0a50485c97999074e69e127216fd052ae00000000",
   "txid": "216ed9adf8df623770e219f52b31350de60cd1b236d6f043664d9eb5bc462ad4",
   "type": "mutual"
}
rusty@rusty-Framework:~/devel/cvs/lightning (master)$ bt-cli getrawmempool
[
]
```

Logs show:

```
2023-08-11T02:20:13.947Z DEBUG   plugin-bcli: sendrawtx exit 26 (bitcoin-cli -regtest -datadir=/home/rusty/.bitcoin sendrawtransaction 0200000000010153ce29f4df20875492760ec51092d01ade3da99ffd72c3ff47b02e8f78a5845a0100000000ffffffff02b882010000000000225120847b3d31b036c0b4fad77fd41805f375f4fc9507d52f2a19d858b43975a633b0d1be0d000000000022512017912fd7fc767d03e02461bd932556d78291ea226db5efec84d84a5c753a650a0400473044022005b184a595ec0b650dffb3168d003b13ae0d98d456d879ec7fac7012f3dbad6202202f5a9620a59fb3cb9269be3b2a941f18fe1b7e3037c259125c56d3ec86c8e91a014730440220559f1c2a578e35a975466bb6f2319d313cd79070add77c51b6f6aeb25f7eae9802204749e84e7f8a777c66896a38588f6046a28653a493c34c79a0080580a0f389ec01475221024ff290301210ddffa14db591eb629d864bb4b4583586f5bffaaebc4ca8d5edef2102e0de3f54ca6cf38cb527b326242bf418a4a0a50485c97999074e69e127216fd052ae00000000) error code: -26\nerror message:\nmin relay fee not met, 183 < 192

Indeed, tx weight is 192!
```

Reported-by: @ShahanaFarooqui
2023-08-12 13:17:46 +09:30
Rusty Russell efc0264ba2 renepay: add command notifications
These show that we should clean up our notes.  Here's the result from test_hardmpp:

# we have computed a set of 1 flows with probability 0.328, fees 0msat and delay 23
# No MPP, so added 0msat shadow fee
# Shadow route on flow 0/1 added 0 block delay. now 5
# sendpay flow groupid=1, partid=1, delivering=1800000000msat, probability=0.328
# Update chan knowledge scid=103x2x0, dir=0: [0msat,1799999999msat]
# onion error WIRE_TEMPORARY_CHANNEL_FAILURE from node #1 103x2x0: failed: WIRE_TEMPORARY_CHANNEL_FAILURE (reply from remote)
# we have computed a set of 2 flows with probability 0.115, fees 0msat and delay 23
# Shadow route on flow 0/2 added 0 block delay. now 5
# Shadow route on flow 1/2 added 0 block delay. now 5
# sendpay flow groupid=1, partid=3, delivering=500000000msat, probability=0.475
# sendpay flow groupid=1, partid=2, delivering=1300000000msat, probability=0.242
# Update chan knowledge scid=103x2x0, dir=0: [0msat,1299999999msat]
# onion error WIRE_TEMPORARY_CHANNEL_FAILURE from node #1 103x2x0: failed: WIRE_TEMPORARY_CHANNEL_FAILURE (reply from remote)
# we have computed a set of 2 flows with probability 0.084, fees 0msat and delay 23
# Shadow route on flow 0/2 added 0 block delay. now 5
# Shadow route on flow 1/2 added 0 block delay. now 5
# sendpay flow groupid=1, partid=5, delivering=260000000msat, probability=0.467
# sendpay flow groupid=1, partid=4, delivering=1040000000msat, probability=0.179
# Update chan knowledge scid=103x2x0, dir=0: [0msat,1039999999msat]
# onion error WIRE_TEMPORARY_CHANNEL_FAILURE from node #1 103x2x0: failed: WIRE_TEMPORARY_CHANNEL_FAILURE (reply from remote)
# we have computed a set of 2 flows with probability 0.052, fees 0msat and delay 23
# Shadow route on flow 0/2 added 0 block delay. now 5
# Shadow route on flow 1/2 added 0 block delay. now 5
# sendpay flow groupid=1, partid=7, delivering=120000000msat, probability=0.494
# sendpay flow groupid=1, partid=6, delivering=920000000msat, probability=0.105

Ideally it would look something like:

# Computed 1 flows, probability=0.328:
#  Flow 1: 103x2x0 1800000000msat fee=0msat probability=0.328 shadow=+0msat/0blocks
#  Flow 1: FAIL: TEMPORARY_CHANNEL_FAILURE for 103x2x0.
# Computed 2 flows, probability=0.115:
#  Flow 2: XXX->XXX 1300000000msat fee=XXX, probability=0.475 shadow=+0msat/0blocks
#  Flow 3: XXX->XXX 500000000msat fee=XXX, probability=0.475 shadow=+0msat/0blocks
#  Flow 2: FAIL: TEMPORARY_CHANNEL_FAILURE from node #1 103x2x0
# Computed 2 flows (3 total), probability=0.084, fee=0msat, delay=23
...
#  Flow 4: SUCCESS, 2 in progress should succeed soon.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-12 09:41:24 +09:30
Rusty Russell d7b3bdd420 renepay: drive *all* progress from termination of struct pay_flow.
The main function here is payment_reconsider:
* Each payment has a list of pay_flow.
* This is populated in try_paying(), calling add_payflows & sendpay_new_flows.
* When we get a notification, we resolve a pay_flow using one of the pay_flow_failedxxx
  or pay_flow_succeeded functions.
* They call payment_reconsider() which cleans up finished flows decides what to do:
  often calling try_paying again.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-12 09:41:24 +09:30
Rusty Russell 01a29d8453 renepay: fix up handling of errors from final node.
Treat it just like "PAY_TRY_OTHER_ROUTE", except it is from the final node:
this means we correctly process that it "succeeded".

Add a test: this crashes sometimes, but it's cleaned up soon...

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-12 09:41:24 +09:30
Alex Myers d8d2032ba5 gossipd: load pending spam node announcements without forgetting previous node announcements
Fixes: #6531
2023-08-12 09:29:16 +09:30
Alex Myers 53dd6cd44a pytest: test gossip_store loading of spam node announcement before channel update 2023-08-12 09:29:16 +09:30
Dusty Daemon c50e93d9fb splice: Move splice to experimental feature bit
This was recommended by @t-bast: if the final spec commits to something
compatible, we can simply advertize and accept both features, but if it
does change in incompatible ways we won't cause problems for nodes
who implement the official spec.

(I split this, so first, we remove the OPT_SPLICE entirely, to make
sure we caught them all. --RR)

Suggested-by: @t-bast
Changelog-None
2023-08-10 15:52:53 +09:30
Rusty Russell dabd6c6b70 pytest: run splicing test on every run.
EXPERIMENTAL_SPLICING=1 turns it on for *all* tests, to make sure we don't
accidentally break those.  But we can (and should!) run the splice test
under every possible CI scenario.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-08 14:31:47 +09:30
Rusty Russell 54bcb10227 lightningd: fix bolt11 parsing in preapproveinvocie, sendonion, listsendpays and renepay
Since bolt11_decode now insists that any `lightning:` prefix be removed, we need
to make sure to use param_invstring not param_string for all bolt11 parameters:

```
2023-08-07T05:55:32.515Z **BROKEN** lightningd: FATAL SIGNAL 6 (version v23.08rc1-21-g0bf5ee6)
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: common/daemon.c:38 (send_backtrace) 0x55dd94934154
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: common/daemon.c:75 (crashdump) 0x55dd949342e6
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: ./signal/../sysdeps/unix/sysv/linux/x86_64/libc_sigaction.c:0 ((null)) 0x7f5cf5a3bcef
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: ./nptl/pthread_kill.c:44 (__pthread_kill_implementation) 0x7f5cf5a9226b
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: ./nptl/pthread_kill.c:78 (__pthread_kill_internal) 0x7f5cf5a9226b
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: ./nptl/pthread_kill.c:89 (__GI___pthread_kill) 0x7f5cf5a9226b
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: ../sysdeps/posix/raise.c:26 (__GI_raise) 0x7f5cf5a3bc45
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: ./stdlib/abort.c:79 (__GI_abort) 0x7f5cf5a227fb
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: ./assert/assert.c:92 (__assert_fail_base) 0x7f5cf5a2271a
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: ./assert/assert.c:101 (__GI___assert_fail) 0x7f5cf5a33595
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: common/bolt11.c:734 (bolt11_decode_nosig) 0x55dd94929967
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: common/bolt11.c:953 (bolt11_decode) 0x55dd9492a44f
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: lightningd/pay.c:1730 (json_listsendpays) 0x55dd948d7d72
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: lightningd/jsonrpc.c:658 (command_exec) 0x55dd948b525b
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: lightningd/jsonrpc.c:786 (rpc_command_hook_final) 0x55dd948b5876
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: lightningd/plugin_hook.c:285 (plugin_hook_call_) 0x55dd948f6446
2023-08-07T05:55:32.515Z **BROKEN** lightningd: backtrace: lightningd/jsonrpc.c:874 (plugin_hook_call_rpc_command) 0x55dd948b5c77
2023-08-07T05:55:32.516Z **BROKEN** lightningd: backtrace: lightningd/jsonrpc.c:984 (parse_request) 0x55dd948b6234
2023-08-07T05:55:32.516Z **BROKEN** lightningd: backtrace: lightningd/jsonrpc.c:1090 (read_json) 0x55dd948b670f
2023-08-07T05:55:32.516Z **BROKEN** lightningd: backtrace: ccan/ccan/io/io.c:59 (next_plan) 0x55dd94ac9bf4
2023-08-07T05:55:32.516Z **BROKEN** lightningd: backtrace: ccan/ccan/io/io.c:407 (do_plan) 0x55dd94aca823
2023-08-07T05:55:32.516Z **BROKEN** lightningd: backtrace: ccan/ccan/io/io.c:417 (io_ready) 0x55dd94aca865
2023-08-07T05:55:32.516Z **BROKEN** lightningd: backtrace: ccan/ccan/io/poll.c:453 (io_loop) 0x55dd94accbff
2023-08-07T05:55:32.516Z **BROKEN** lightningd: backtrace: lightningd/io_loop_with_timers.c:22 (io_loop_with_timers) 0x55dd948b33c4
2023-08-07T05:55:32.516Z **BROKEN** lightningd: backtrace: lightningd/lightningd.c:1332 (main) 0x55dd948ba429
2023-08-07T05:55:32.516Z **BROKEN** lightningd: backtrace: ../sysdeps/nptl/libc_start_call_main.h:58 (__libc_start_call_main) 0x7f5cf5a2350f
2023-08-07T05:55:32.516Z **BROKEN** lightningd: backtrace: ../csu/libc-start.c:381 (__libc_start_main_impl) 0x7f5cf5a235c8
2023-08-07T05:55:32.516Z **BROKEN** lightningd: backtrace: (null):0 ((null)) 0x55dd94881e74
2023-08-07T05:55:32.516Z **BROKEN** lightningd: backtrace: (null):0 ((null)) 0xffffffffffffffff
```

Fixes: #6524
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-None: broken in master since last release.
2023-08-07 18:46:48 +09:30
Rusty Russell 7a88900476 pytest: test for listsendpays and lightning: prefix crash.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-07 18:46:48 +09:30
Rusty Russell 91ea85be36 lightningd: close connection when HTLC addition times out.
I noticed this while debugging an issue with ACINQ, that we got upset,
but didn't trigger a reconnect cycle.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Fixed: Protocol: We now close connection with a peer if adding an HTLC times out (which may be a TCP connectivity issue).
2023-08-07 18:45:29 +09:30
Rusty Russell d4ed1c7f6f pytest: test that we close connection if adding an HTLC times out.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-07 18:45:29 +09:30
Rusty Russell f556be5d82 renepay: allow it to die gracefully without crashing lightningd.
Suggested-by: @Lagrang3
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-07 17:13:29 +09:30
Rusty Russell 34b6731b82 lightningd: don't return to a default filter level if there are no per-file filters.
In this case, the user's default was info, but they specifically asked for debug
from one plugin.  Since there were no per-file filters, it set filtering to the
default level, info, and rejected it.  Since it's been explicitly filtered in,
we need to pass it at this point.

Reported-by: @wtogami
Fixes: #6503
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-06 14:37:49 +09:30
Rusty Russell be2cbe784f pytest: test for filtering bug.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-06 14:37:49 +09:30
Dusty Daemon fb179f2d5e
splicing: Remove dependency on experimental_dual_fund
Splicing should work automatically on v1 or v2 channels so this requirement isn’t needed.

Changelog-None
[ Squashed fixup into a single commit --RR ]
2023-08-06 12:19:42 +09:30
Rusty Russell 0f6687ec7b codex32: use "cl" instead of "ms" as our HRP.
This was strongly recommended by Russell O'Connor: the "ms" implies that
it's a BIP-32 master secret, and this is CLN specific.

If we changed the hrp to "cln" it would be better, but apparently that
means we no longer fit in a "standard billfold metal wallet" (and
our code assumes a 2-byte prefix anyway).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-02 16:12:32 +09:30
Rusty Russell 5900742b3a hsmtool: remove threshold arg.
It really has to be 0, since it's the complete secret.  And we didn't handle
it well, (`a` would be treated as 0, for example!).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-02 08:42:50 +09:30
Rusty Russell 4dcd712d6e hsmtool: tighten checks for validity on getcodexsecret
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-02 08:42:50 +09:30
Rusty Russell e981a4f14a lightningd: pass signed tx through to close callback.
Thread the signed tx through so close's JSON return contains that,
rather than the unsigned channel->last_tx.

We have to split the "get cmd_id" from "resolve the close commands" though;
and of course, as before, we don't actually print the txids of multiple
transactions even though we may have multi in flight due to splice!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Fixed: JSON-RPC: `close` returns a `tx` field with witness data populated (i.e. signed).
Fixes: #6440
2023-08-02 07:09:28 +09:30
Rusty Russell 673d81adde pytest: test for bad 'tx' result from close.
We print it without the witness!

Reported-by: https://github.com/wtogami
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-08-02 07:09:28 +09:30
Dusty Daemon 4628e3ace8 channeld: Code to implement splicing
Update the lightningd <-> channeld interface with lots of new commands to needed to facilitate spicing.

Implement the channeld splicing protocol leveraging the interactivetx protocol.

Implement lightningd’s channel_control to support channeld in its splicing efforts.

Changelog-Added: Added the features to enable splicing & resizing of active channels.
2023-07-31 21:00:22 +09:30
Aditya Sharma 6a734d8b4d tests/test_misc.py: Add a subprocess to make sure getcodexsecret fetches out the hsm_secret in bip93 format. 2023-07-31 20:57:40 +09:30
Rusty Russell 2c2592fe36 lightningd: fix crash on startup expirations.
The wait code assumes ld->wallet is populated, but it's not.  Start the
expiration cycle later.

```
0x7f271a18d08f ??? /build/glibc-SzIz7B/glibc-2.31/signal/../sysdeps/unix/sysv/linux/x86_64/sigaction.c:0
0x5581a27dc082 wait_index_increment lightningd/wait.c:112
0x5581a27e331a invoice_index_inc wallet/invoices.c:738
0x5581a27e3dfe invoice_index_update_status wallet/invoices.c:775
0x5581a27e3ea3 trigger_expiration wallet/invoices.c:185
0x5581a27e3f47 invoices_new wallet/invoices.c:134
0x5581a27e8a2c wallet_new wallet/wallet.c:121
0x5581a27b08b5 main lightningd/lightningd.c:1082
```

Fixes: #6457
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-31 20:42:31 +09:30
Rusty Russell 4b173eec3b pytest: add test for expiration-on-startup crash.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-31 20:42:31 +09:30
Rusty Russell 4a1d4f4f46 pytest: correctly annotate invoice tests needing sqlite3.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-31 20:42:31 +09:30
Rusty Russell 97af40c545 pytest: fix the invoice typo migration if you ran and created both.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-31 13:25:22 +09:30
Rusty Russell 81b30c9483 pytest: test for grubles' screwed node.
If you actually ran your node with the botched "last_invoice_created_index" typo migration
(fortunately, not release, just master) you can get a db with both the real "last_invoices_created_index" and the bad "last_invoice_created_index" entries.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-31 13:25:22 +09:30
Lagrang3 e5695b3c23 renepay: add test
Signed-off-by: Lagrang3 <eduardo.quintana@pm.me>
2023-07-31 12:58:56 +09:30
Lagrang3 3024afe524 renepay: more cleanups
- adopt "const <type> *"convention
- remove use_shadow option for some pyln tests
- show prob. information of flows into paynotes
- show prob. of success of entire payment flow in paynotes
- minflow: We were not releasing the memory of flow arrays when replacing
  them with a new canditate.
- use memleak_scan_obj in memleak_check
- replace u64 with size_t

Signed-off-by: Lagrang3 <eduardo.quintana@pm.me>
2023-07-31 12:58:56 +09:30
Lagrang3 79486c1e3b renepay: fixups after comments
- remove internal gheap checks
- add check for arc_t.chanidx overflow
- remove outdated comments
- check the delta flow bounds before augmenting along a path
- get_flow_paths uses a dynamic tal array instead of a list.
- fix a unit test that depended on the order of returned flows
- fix bug: lightnind doesn't like if I reuse the partid of a failed
  flow, therefore use a higher partid than any of the previous attempts.
- plugin_err instead of LOG_BROKEN if sendpay fails and we cannot get a
  an error code.
- fix wrong comments.
- remove the background timer.
- This is a bugfix. Previous to this the MCF network was built using the
knowledge of the min and max liquidity but it didn't take into account
pending HTLCs.
- Also remove the min_prob_success option but hardcode a 90% value.

Removing some options that are not relevant to the user, they're kept
for developer mode only:
- base_fee_penalty
- min_prob_success
- prob_cost_factor
- remove heap.h, not used

Signed-off-by: Lagrang3 <eduardo.quintana@pm.me>
2023-07-31 12:58:56 +09:30
Rusty Russell b8ca193606 renepay: an experimental payment plugin
Signed-off-by: Lagrang3 <eduardo.quintana@pm.me>
Changelog-Added: Plugins: `renepay`: an experimental pay plugin implementing Pickhardt payments (`renepay` and `renepaystatus`).
2023-07-31 12:58:56 +09:30
adi2011 82c11529ab tests: Added test_recover to test --recover flag. 2023-07-31 11:29:59 +09:30
niftynei 9b8909e507 dual-fund: keep track of aborted requests, seamlessly restart daemon
Clean restart of daemon after a tx-abort is a nice way to work around
the 'persistent' disconnect that we t-bast noticed.

Changelog-Fixed: `dualopend`: Fix behavior for tx-aborts. No longer hangs, appropriately continues re-init of RBF requests without reconnction msg exchange.
2023-07-30 15:20:04 +09:30
niftynei c807db4b7f dual-fund tests: add tests for reported incompat with Eclair
Bug Report:
- initiate a channel open eclair -> cln
- wait for the transaction to be published
- eclair initiates rbf, and cancels it by sending tx_abort before exchanging commit_sig
- at that point everything looks good, cln echoes the tx_abort and stays connected
- eclair initiates another RBF attempt and sends tx_init_rbf: for some unknown reason,
  cln answers with channel_reestablish (??) followed by an error saying
  "Bad reestablish message: WIRE_TX_INIT_RBF"

Diagnosis:
  CLN is doing a reconnect after a tx-abort is sent.

Extra Test:
  Realized that if we abort, we won't correctly advanced to NORMAL if
  blocks are mined while we're in hanging state. CLN should advance
  after block containing channel open is mined.

Reported-By: @t-bast
2023-07-30 15:20:04 +09:30
Rusty Russell e39fe41ff0 pytest: fix flake in penalty tests
Make sure we've completely processed htlc, so we will definitely consider it an old spend.  If we're too fast, l2 might consider it a legitimate unilateral close:

```
        # Make sure both sides got revoke_and_ack for final.
        l1.daemon.wait_for_log('peer_in WIRE_REVOKE_AND_ACK')
        l2.daemon.wait_for_log('peer_in WIRE_REVOKE_AND_ACK')
    
        # Now we really mess things up!
        bitcoind.rpc.sendrawtransaction(tx)
        bitcoind.generate_block(1)
    
        l2.daemon.wait_for_log(' to ONCHAIN')
        # FIXME: l1 should try to stumble along!
    
        # l2 should spend all of the outputs (except to-us).
        # Could happen in any order, depending on commitment tx.
        needle = l2.daemon.logsearch_start
        ((_, txid1, blocks1), (_, txid2, blocks2)) = \
>           l2.wait_for_onchaind_txs(('OUR_PENALTY_TX',
                                      'THEIR_REVOKED_UNILATERAL/DELAYED_CHEAT_OUTPUT_TO_THEM'),
                                     ('OUR_PENALTY_TX',
                                      'THEIR_REVOKED_UNILATERAL/OUR_HTLC'))

tests/test_closing.py:687: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
contrib/pyln-testing/pyln/testing/utils.py:1264: in wait_for_onchaind_txs
    r = self.daemon.wait_for_log('Telling lightningd about {} to resolve {}'
contrib/pyln-testing/pyln/testing/utils.py:346: in wait_for_log
    return self.wait_for_logs([regex], timeout)
```

You can see l2 here:

```
lightningd-2 2023-07-27T03:34:24.533Z DEBUG   0266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c03518-onchaind-chan#1: Their unilateral tx, old commit point
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-28 09:44:58 +09:30
Rusty Russell f15e2506ca pytest: fix flake in test_gossip_store_compact_on_load.
We can have almost arbitrary re-transmissions of private updates, looking at the decode: in this case, instead of the expected:

```
  DELETED: private channel_announcement (scid23)
  DELETED: private channel_update (scid23/0)
  DELETED: private channel_update (scid23/1)
delete channel (scid23)
channel_announcement (scid23)
channel_amount
  DELETED: channel_update (scid23/0)
  DELETED: channel_update (scid23/1)
node_announcement
node_announcement
channel_update (scid23)
private channel_announcement (scid12)
  DELETED: private channel_update (scid12/0)
  DELETED: private channel_update (scid12/1)
channel_update (scid23)
private_channel_update (scid12)
private_channel_update (scid12)
```

We had:

```
  DELETED: private channel_announcement
  DELETED: private channel_update
  DELETED: private channel_update
  DELETED: private channel_update
  DELETED: private channel_update
channel_announcement
channel_amount
  DELETED: channel_update
  DELETED: channel_update
node_announcement
node_announcement
channel_update
private channel_announcement
  DELETED: private channel_update
  DELETED: private channel_update
channel_update
private channel_update
private channel_update
```

Which means we deleted 9, and hence failed:

```
    @pytest.mark.developer("gossip without DEVELOPER=1 is slow")
    def test_gossip_store_compact_on_load(node_factory, bitcoind):
        l2 = setup_gossip_store_test(node_factory, bitcoind)
    
        gs_path = os.path.join(l2.daemon.lightning_dir, TEST_NETWORK, 'gossip_store')
        gs = subprocess.run(['devtools/dump-gossipstore', '--print-deleted', gs_path],
                            check=True, timeout=TIMEOUT, stdout=subprocess.PIPE)
        print(gs.stdout.decode())
    
        l2.restart()
    
>       wait_for(lambda: l2.daemon.is_in_log(r'gossip_store_compact_offline: [5-8] deleted, 9 copied'))

tests/test_gossip.py:1776: 
```
2023-07-28 09:44:58 +09:30
Rusty Russell 435a4623ad wallet: fix migration of existing invoices's id variable.
Rusty can't type.  Rusty can't test.  Bad Rusty.  Bad.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-27 15:54:08 +09:30
Rusty Russell 909bed6a30 pytest: add test for db crash on conflicting invoice.id
```
2023-07-26T14:26:37.504Z BROKEN lightningd: Error executing statement: wallet/invoices.c:282: INSERT INTO invoices ( id, payment_hash, payment_key, state , msatoshi, label, expiry_time , pay_index, msatoshi_received , paid_timestamp, bolt11, description, features, local_offer_id) VALUES ( ?, ?, ?, ? , ?, ?, ? , NULL, NULL , NULL, ?, ?, ?, ?);: UNIQUE constraint failed: invoices.id
```

Reported-by: https://github.com/hMsats
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-27 15:54:08 +09:30
Alex Myers 7915a9d678 pytest: add reckless local install test 2023-07-27 06:53:49 +09:30
Alex Myers 8704a4b499 reckless: add installation capability for additional sources
Abstracts search and directory traversal. Adds support for installing
from a local git repository, a local directory, or a web hosted git repo
without relying on an api.

Changelog-Changed: Reckless can now install directly from local sources.
2023-07-27 06:53:49 +09:30
Rusty Russell 978c1699ea lightningd: fail incoming HTLCs if peer would close channel.
This cause of cascading failure was pointed out by @t-bast: if fees spike and
you don't timeout an outgoing onchain HTLC, you should nonetheless fail the incoming htlc
because otherwise the incoming peer will close on you.

Of course, there's a risk of losing funds, but this only happens if you weren't going to get the HTLC spend in time anyway.  And it would also catch any other reason that the downstream onchain goes wrong, containing the damage.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Reported-by: @t-bast
Changelog-Fixed: Protocol: We will close incoming HTLCs early if the outgoing HTLC is stuck onchain long enough, to avoid cascating failure.
2023-07-26 06:58:38 +09:30
Rusty Russell fd445aa467 pytest: test that we proactively close incoming HTLCs to avoid them closing on us.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-26 06:58:38 +09:30
Vincenzo Palazzo f4fd12cc15 channeld: Verify the signature sent by the counterparty
This commit addresses an issue to enhance the resilience of core
lightning when receiving node announcements.

According to BOLT 7 (The announcement_signatures Message),
if the node_signature OR the bitcoin_signature is NOT correct,
it is recommended to either send a warning and close the connection or send an error and fail the channel.

In this commit, we take a strict approach. If any error is detected, we
send an error and fail the open channel operation.
This is because the announcement_signatures operation is optional,
and we assume that it must be correct.

lnprototest at commit dea47c29b5541dbfe7fe53cc2598330e897fa4f4 report
the following error now.

```
2023-07-06T21:03:20.930Z DEBUG   hsmd: Shutting down

ERROR    root:helpers.py:170 Traceback (most recent call last):
  File "/home/vincent/Github/lightning/external/lnprototest/tests/helpers.py", line 167, in run_runner
    runner.run(test)
  File "/home/vincent/Github/lightning/external/lnprototest/lnprototest/runner.py", line 99, in run
    all_done = sequence.action(self)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/home/vincent/Github/lightning/external/lnprototest/lnprototest/structure.py", line 55, in action
    all_done &= e.action(runner)
                ^^^^^^^^^^^^^^^^
  File "/home/vincent/Github/lightning/external/lnprototest/lnprototest/event.py", line 365, in action
    raise EventError(self, "{}: message was {}".format(err, msg.to_str()))
lnprototest.errors.EventError: `Expected msgtype-warning, got msgtype-error: message was error channel_id=a37362839b13f61cfe82d35bd397b1264c389b245847cfb6111b38892546dc77 data=4661696c656420746f20766572696679206e6f64655f7369676e61747572652e` on event [{"event": "ExpectMsg", "file": "test_bolt2-01-close_channel.py", "pos": "157"},]
============================================================================================================================================================== short test summary info ===============================================================================================================================================================
FAILED tests/test_bolt2-01-close_channel.py::test_close_channel_shutdown_msg_normal_case_receiver_side - AssertionError: `Expected msgtype-shutdown, got msgtype-error: message was error channel_id=a37362839b13f61cfe82d35bd397b1264c389b245847cfb6111b38892546dc77 data=4661696c656420746f20766572696679206e6f64655f7369676e61747572652e` on event [{"event": "ExpectMsg", "file": "test_bolt2-01-close_channel.py", "pos": "75"},]
FAILED tests/test_bolt2-01-close_channel.py::test_close_channel_shutdown_msg_wrong_script_pubkey_receiver_side - AssertionError: `Expected msgtype-warning, got msgtype-error: message was error channel_id=a37362839b13f61cfe82d35bd397b1264c389b245847cfb6111b38892546dc77 data=4661696c656420746f20766572696679206e6f64655f7369676e61747572652e` on event [{"event": "ExpectMsg", "file": "test_bolt2-01-close_channel.py", "pos": "157"},]

```

Changelog-Fixes: channeld: Verify the signature sent in announcement_signatures by the counterparty
Reported-by: lnprototest
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2023-07-26 06:57:15 +09:30
Rusty Russell 620135335d libplugin/pay: allow shortcut for self-pay.
This is the simplest solution, not the best, but there's significant risk in try to remove the "we have a path" assumption in the code pay code.

Includes removing a `tal_steal` which was incorrect: the buffer has the same lifetime as the plugin, so if we steal it then things get messy when we free the  struct payment.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: Plugins: `pay` will now pay your own invoices if you try.
2023-07-26 06:55:48 +09:30
Rusty Russell 18760db66d lightningd: sendpay implement zero-length path == self-pay.
Previously, the "payment" and "invoice" paths were completely separate, but this now calls both.  It bypasses htlc_sets (and thus, cannot do MPP), and bypasses the hook too: the former is tied closely to HTLCs, and the hook is also very htlc-centric.

Includes finishing unfinished sentence in sendpay man page, as a bonus.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: Plugins: `sendpay` now allows self-payment of invoices, by specifying an empty route.
2023-07-26 06:55:48 +09:30
Rusty Russell 07e00d50c6 invoice: return error string from invoice_check_payment.
Clean these up: they were debug logs, but we want to pass this information
back for self-payments.

Also fixes "Attept" typo which altered tests!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-26 06:55:48 +09:30
Rusty Russell adee07125a pytest: test self-payments using sendpay.
We want to allow this, so write a test.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-26 06:55:48 +09:30
Rusty Russell 11b5f31034 lightningd: clean up commando rune_counter from datastore on migration.
Pointed out by @ShahanaFarooqui, we leave a single unused entry in the datastore,
so we should clean that up too.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-25 14:47:12 +09:30
Rusty Russell 925f9fcce5 lightningd: migrate (and delete) old commando blacklists.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-25 14:47:12 +09:30
Rusty Russell dccbccf8f2 lightningd: migrate (and delete) old commando runes.
If they have invalid runes, we bail, but if they have runes which used
a different master secret (old commando.py allowed you to override
secret), we just complain and delete them.

Note that this requires more mocks in wallet/test/run-db.c...

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-25 14:47:12 +09:30
Rusty Russell a219c99691 commando: pass through commands to lightningd.
The in-core commands are much more helpful with details on why runes failed, too!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-25 14:47:12 +09:30
Rusty Russell 38075a95d4 commando: use CLN's checkrune() instead of our own for for rune validation.
This means (temporarily) that blacklisting won't work (fix later), and
means that old-style (commando.py) master-secret-override doesn't work.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Removed: Plugins: `commando` no longer allows datastore ['commando', 'secret'] to override master secret (re-issue runes if you were using that!).
2023-07-25 14:47:12 +09:30
Rusty Russell cd16690af8 commando: always active.
We used to activate on the first rune creation, but we're no longer in charge
of runes, so we can't make that call.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-25 14:47:12 +09:30
Rusty Russell 8d64e6e277 pytest: use native l1 commando secret.
We're going to remove the ability to override the master secret, so fix
up our tests.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-25 14:47:12 +09:30
Shahana Farooqui 49fdc0df99 runes: Renamed `listrunes` to `showrunes` 2023-07-25 11:07:43 +09:30
Rusty Russell d25a8ca0fd lightningd: expose created_index and updated_index fields.
If you miss a wait event, you can catch up by doing listinvoices and
getting the max of these fields.  It's also a good debugging clue.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-23 13:48:37 +09:30
Rusty Russell 284262d006 listinvoices: add limit param.
Changelog-Added: JSON-RPC: `listinvoices` has `limit` parameter for listing control.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-23 13:48:37 +09:30
Rusty Russell 16c133746b listinvoices: add index and start params.
Now we have defined ordering, we can add a start param.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: `listinvoices` has `index` and `start` parameters for listing control.
2023-07-23 13:48:37 +09:30
Rusty Russell bbf4f312a4 invoice: include invoice label to wait subsystem when it's paid.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-23 13:48:37 +09:30
Rusty Russell 6782c2fef5 lightningd: trigger changed wait when delinvoice desconly used.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-23 13:48:37 +09:30
Rusty Russell cbdfc75bde invoices: pass through info to delete function, call invoice_index_deleted.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-23 13:48:37 +09:30
Rusty Russell 5a76eaab06 wallet: hook up updated_index for invoices.
We do expirations inside the loop, so we can set updated_index
and trigger the callback.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-23 13:48:37 +09:30
Rusty Russell 7b69e7e1fe wallet: hook up created_index for invoices.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-23 13:48:37 +09:30
Rusty Russell 7372b518ef pytest: test for setchannel's new ignorefeelimits.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-22 13:11:08 +09:30
Rusty Russell 8910529e6a lightningd: expose ignore_fee_limits field in listpeerchannels.
Changelog-Added: JSON-RPC: `listpeerchannels` has a new field `ignore_fee_limits`
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-22 13:11:08 +09:30
Rusty Russell 063a883303 pytest: make tor-requiring tests clearly distinguishable
This way you can run pytest with '-k no _tor_'.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-22 11:08:04 +09:30
Rusty Russell 0d34f4916e pytest: fix timeout in test_sql
The logs show we're not waiting for the right transaction, so be explicit.

```
        # Check that channels gets refreshed!
        scid = l1.get_channel_scid(l2)
        l1.rpc.setchannel(scid, feebase=123)
        wait_for(lambda: l3.rpc.sql("SELECT short_channel_id FROM channels WHERE base_fee_millisatoshi = 123;")['rows'] == [[scid]])
        l3.daemon.wait_for_log("Refreshing channels...")
        l3.daemon.wait_for_log("Refreshing channel: {}".format(scid))
    
        # This has to wait for the hold_invoice plugin to let go!
        l1.rpc.close(l2.info['id'])
        bitcoind.generate_block(13, wait_for_mempool=1)
>       wait_for(lambda: len(l3.rpc.listchannels()['channels']) == 2)

tests/test_plugin.py:4143: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

success = <function test_sql.<locals>.<lambda> at 0x7fde3b9cd3a0>, timeout = 180

    def wait_for(success, timeout=TIMEOUT):
        start_time = time.time()
        interval = 0.25
        while not success():
            time_left = start_time + timeout - time.time()
            if time_left <= 0:
>               raise ValueError("Timeout while waiting for {}".format(success))
E               ValueError: Timeout while waiting for <function test_sql.<locals>.<lambda> at 0x7fde3b9cd3a0>
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-22 08:52:55 +09:30
Rusty Russell 6a7a0ea7d0 pytest: fix flake handling intest_restorefrompeer.
We tried to fix this flake before, but now it actually happened again it shows that
b5845afd43 wasn't correct.

```
        # If this happens fast enough, connect fails with "disconnected
        # during connection"
        try:
            l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
        except RpcError as err:
>           assert "disconnected during connection" in err.error
E           assert 'disconnected during connection' in {'code': 402, 'message': 'disconnected during connection'}
E            +  where {'code': 402, 'message': 'disconnected during connection'} = RpcError("RPC call failed: method: connect, payload: {'id': '022d223620a359a47ff7f7ac447c85c46c923da53389221a0054c11c1e3ca31d59', 'host': 'localhost', 'port': 41849}, error: {'code': 402, 'message': 'disconnected during connection'}").error

tests/test_misc.py:2728: AssertionError
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-22 08:52:55 +09:30
Rusty Russell 2e28226e18 pytest: fix timeout in test_channel_lease_unilat_closes
Sometimes syncing 4032 blocks can take too long:

```
        # This can timeout, so do it in easy stages.
        for i in range(16):
            bitcoind.generate_block(4032 // 16)
>       sync_blockheight(bitcoind, [l2, l3])

tests/test_closing.py:996: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
contrib/pyln-testing/pyln/testing/utils.py:135: in sync_blockheight
    wait_for(lambda: n.rpc.getinfo()['blockheight'] == height)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

success = <function sync_blockheight.<locals>.<lambda> at 0x7ffb00227670>
timeout = 180

    def wait_for(success, timeout=TIMEOUT):
        start_time = time.time()
        interval = 0.25
        while not success():
            time_left = start_time + timeout - time.time()
            if time_left <= 0:
>               raise ValueError("Timeout while waiting for {}".format(success))
E               ValueError: Timeout while waiting for <function sync_blockheight.<locals>.<lambda> at 0x7ffb00227670>
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-22 08:52:55 +09:30
Rusty Russell e91f8ddb51 pytest: fix test_anchor_min_emergency "bad gossip" messages.
l1 shuts down too fast, channeld doesn't get to tell gossipd about the channel,
and l2 sends (private) update_channel and we complain:

```
lightningd-2 2023-07-20T03:42:37.744Z DEBUG   gossipd: received private channel announcement from channeld for 103x1x0
lightningd-2 2023-07-20T03:42:37.791Z DEBUG   022d223620a359a47ff7f7ac447c85c46c923da53389221a0054c11c1e3ca31d59-hsmd: Got WIRE_HSMD_CUPDATE_SIG_REQ
lightningd-2 2023-07-20T03:42:37.796Z DEBUG   hsmd: Client: Received message 3 from client
lightningd-1 2023-07-20T03:42:37.857Z DEBUG   022d223620a359a47ff7f7ac447c85c46c923da53389221a0054c11c1e3ca31d59-gossipd: Bad gossip order: WIRE_CHANNEL_UPDATE before announcement 103x1x0/0
lightningd-1 2023-07-20T03:42:37.864Z DEBUG   022d223620a359a47ff7f7ac447c85c46c923da53389221a0054c11c1e3ca31d59-gossipd: Bad gossip order: WIRE_CHANNEL_UPDATE before announcement 103x1x0/0
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-22 08:52:55 +09:30
Rusty Russell 745d3f6226 pytest: fix race in test_gossip_not_dying
Writing to the gossip_store file is not explicitly synchronized, so it
seems that connectd has not caught up with the dying flags we've set.

Simply wait for a second.  Hacky, but should work.

```
    def test_gossip_not_dying(node_factory, bitcoind):
        l1 = node_factory.get_node()
        l2, l3 = node_factory.line_graph(2, wait_for_announce=True)
    
        l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
        # Wait until it sees all the updates, node announcments.
        wait_for(lambda: len([n for n in l1.rpc.listnodes()['nodes'] if 'alias' in n])
                 + len(l1.rpc.listchannels()['channels']) == 4)
    
        def get_gossip(node):
            out = subprocess.run(['devtools/gossipwith',
                                  '--initial-sync',
                                  '--timeout-after=2',
                                  '{}@localhost:{}'.format(node.info['id'], node.port)],
                                 check=True,
                                 timeout=TIMEOUT, stdout=subprocess.PIPE).stdout
    
            msgs = []
            while len(out):
                l, t = struct.unpack('>HH', out[0:4])
                msg = out[2:2 + l]
                out = out[2 + l:]
    
                # Ignore pings, timestamp_filter
                if t == 265 or t == 18:
                    continue
                # channel_announcement node_announcement or channel_update
                assert t == 256 or t == 257 or t == 258
                msgs.append(msg)
    
            return msgs
    
        assert len(get_gossip(l1)) == 5
    
        # Close l2->l3, mine block.
        l2.rpc.close(l3.info['id'])
        bitcoind.generate_block(1, wait_for_mempool=1)
    
        l1.daemon.wait_for_log("closing soon due to the funding outpoint being spent")
    
        # We won't gossip the dead channel any more (but we still propagate node_announcement)
>       assert len(get_gossip(l1)) == 2
E       assert 4 == 2
E        +  where 4 = len([b'\x01\x01L\xc2\xbe\x08\xbb\xa8~\x8f\x80R\x9e`J\x1cS\x18|\x12\n\xe5_6\xb0\xa6S\x9fU\xae\x19\x9c\x1fXB\xab\x81N\x13\xdc\x8e}\xb9\xb0\xb6\xe6\x14h\xd4:\x90\xce\xc3\xad\x9ezR`~\xba@\xc9\x91e\x89\xab\x00\x07\x88\xa0\x00\n\x02i\xa2d\xb8\xa9`\x02-"6 \xa3Y\xa4\x7f\xf7\xf7\xacD|\x85\xc4l\x92=\xa53\x89"\x1a\x00T\xc1\x1c\x1e<\xa3\x1dY\x02-"SILENTARTIST-27fc801-modded\x00\x00\x00\x00\x00\x00\x00', b'\x01\x01M\x00\x86\x8e4\xc8\x90p\n\x98\xf7\xce4\x1e\xd9\xd6-6\xfb(\xf0\xe4\xb7\x90\x7f\x89\xb9\xfa\x00\x82\x1b\xeb\x1fY\x93\x1e\xe0c\xb2\x0e<\xe6\x06x\xb7\xe54};\xfbd\xa0\x01S\xcf\xe8{\xf8\x8f/\xa7\xc0\xe2h\x00\x07\x88\xa0\x00\n\x02i\xa2d\xb8\xa9`\x03]+\x11\x92\xdf\xba\x13N\x10\xe5@\x87]6n\xbc\x8b\xc3S\xd5\xaavk\x80\xc0\x90\xb3\x9c:]\x88]\x03]+HOPPINGFIRE-27fc801-modded\x00\x00\x00\x00\x00\x00\x00\x00', b'\x01\x02~\xe0\x13\xb4\x84Gz\xcf(\xd4w\xa7\x9bZ\x1a\xe82\xd1\xe1\x1bLm\xc8\n\xcd\xd4\xfb\x88\xf8\xc6\xdbt\\v\x89~\xd1.e\xc8\xa8o\x9c`\xd5\xa8\x97\x11l\xf2g\xcb\xa8\xcf\r\x869\xd3\xb5\xd5\x9a\xa0my\x9f\x87\xebX\x0b\x9e_\x11\xdc!\x1e\x9f\xb6j\xbb6\x99\x99\x90D\xf8\xfe\x14h\x01\x16#\x936B\x86\xc6\x00\x00g\x00\x00\x01\x00\x00d\xb8\xa9d\x01\x02\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\n\x00\x00\x00\x00;\x023\x80', b"\x01\x0284\xf1a\x86z\x8e\xf2\xe5'\xf7\xfe1\x8d\x96R\x0c\xe7\x1fj#\xaf\xbd/\xba\x10e\xd1\xccQ-\xcf/>\xa5g\xc6\xd8\x9cO \xe7~\xb3\xda\xe0\\vg\xfb\x02&T\x93\xa0\xd4\x95\x8e\xd5L\x12\x9a\xf7\xe6\x9f\x87\xebX\x0b\x9e_\x11\xdc!\x1e\x9f\xb6j\xbb6\x99\x99\x90D\xf8\xfe\x14h\x01\x16#\x936B\x86\xc6\x00\x00g\x00\x00\x01\x00\x00d\xb8\xa9d\x01\x03\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\n\x00\x00\x00\x00;\x023\x80"])
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-22 08:52:55 +09:30
Rusty Russell 77d08d13a2 pytest: test for runes, based on commando tests.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-21 16:44:22 +09:30
Christian Decker c3a983375c pytest: Remove tests that rely on presplit behavior
These tests make assumptions about the presplitter behavior which
we'll remove in the next commit. We remove them here so we don't cause
temporary breaks in the git history.
2023-07-21 07:13:48 +09:30
Rusty Russell 55d6a13ffc gossipd: aggressively advertize *both* sides of channel_update.
While one side was not produced by us, we have a vested interest in propagating it.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: Protocol: When we send our own gossip when a peer connects, also send any incoming channel_updates.
2023-07-21 07:13:11 +09:30
Rusty Russell 7409a93d17 gossipd: when we dump our own gossip, include our node_announcement.
@endothermicdev and I found this while investigating a "nobody sees my node_announcement" bug report.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Fixes: #6410
Reported-by: benjaminchodroff on discord
Changelog-Fixed: Protocol: When we send our own gossip when a peer connects, send our node_announcement too (regression in v23.05)
2023-07-21 07:13:11 +09:30
Rusty Russell ef4db6648d pytest: test for force-broadcasting our own gossip.
We do this as suggested by the spec: send our own gossip even if they didn't ask for it.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-21 07:13:11 +09:30
Rusty Russell 656517f643 connectd: don't gossip dying channels.
Fixes: #6368
Changelog-Fixed: Protocol: we no longer gossip about recently-closed channels (Eclair gets upset with this).
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-20 11:47:32 +09:30
Rusty Russell 26bb791298 pytest: test for whether we gossip spent channels.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-20 11:47:32 +09:30
Rusty Russell e5d0d6958c lightningd: fix up log filtering for generic daemons (e.g. connectd).
Without this, only per-peer daemons were filtered correctly.  For generic
daemons, we need to filter with the actual nodeid they use (if any).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Fixed: config: `log-level` filters now apply correctly to messages from `connectd`.
2023-07-19 19:13:57 +09:30
Rusty Russell 4a7b1b457e lightningd: extend log-level to support filter per-file.
Fixes: #5392
Changelog-Added: config: `log-level` can be specified on a per-logfile basis.
2023-07-19 19:13:57 +09:30
Rusty Russell e0c1c8ec81 lightningd: clean up logging initializations.
Rather than initializating the "print_level" field on first use, we can
do it in logging_options_parsed(), now we have a linked list of them.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-19 19:13:57 +09:30
Shahana Farooqui a4835cf266 commando: changed listrunes schema for `restrictions` `english` key
Changelog: None
2023-07-19 05:40:30 +09:30
Rusty Russell 5151020224 pytest: fix flake in test_feerates
```
2023-07-14T05:32:54.3688763Z         # Set ECONOMICAL/6 feerate, for unilateral_close and htlc_resolution
2023-07-14T05:32:54.3689123Z         l1.set_feerates((15000, 11000, 0, 0), True)
2023-07-14T05:32:54.3689484Z         feerates = l1.rpc.feerates('perkw')
2023-07-14T05:32:54.3689919Z >       assert feerates['perkw']['unilateral_close'] == 11000
2023-07-14T05:32:54.3690226Z E       assert 15000 == 11000
2023-07-14T05:32:54.3690391Z
2023-07-14T05:32:54.3690514Z tests/test_misc.py:1572: AssertionError
```

The rough checks in set_feerates don't actually ensure that we've digested
the changes, so copy the check from elsewhere that makes sure
feerates['estimates'] has indeed been updated.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-16 12:57:27 +09:30
Rusty Russell 1ddf4bac2c pytest: fix flake in tests/test_closing.py::test_penalty_rbf_normal[True]
We assume that RBFs will happen in order (txid1, txid2) but that doesn't always happen.

```
        for depth in range(2, 10):
            bitcoind.generate_block(1)
            # l2 should RBF, twice even, one for the l1 main output,
            # one for the l1 HTLC output.
            # Don't assume a specific order!
            start = l2.daemon.logsearch_start
>           txid1 = get_rbf_txid(l2, txid1)

tests/test_closing.py:1671: 
...
                            print("({} was previously in logs!)".format(r))
>                   raise TimeoutError('Unable to find "{}" in logs.'.format(exs))
E                   TimeoutError: Unable to find "[re.compile('RBF onchain .*1fe38fe22852baaedccc3a9fd9d897e46bae5b7ca31daf23e0aa456fb235475e')]" in logs.

contrib/pyln-testing/pyln/testing/utils.py:328: TimeoutError
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-16 12:57:27 +09:30
Rusty Russell 8de3b89aac pytest: test for bad estimatefees results.
See: #6183
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-16 12:57:27 +09:30
Vincenzo Palazzo 5f6642a6ff fix(jsonrpc): trim the lightning: prefix from invoice
Previously, our code checked for the presence of the `lightning:`
prefix while decoding a bolt11 string. Although this prefix is valid
and accepted by the core lightning pay command, it was causing issues
with how we managed invoices. Specifically, we were skipping the prefix
when creating a copy of the invoice string and storing the raw invoice
(including the prefix) in the database, which caused inconsistencies
in the user experience.

To address this issue, we need to strip the `lightning:` prefix before
calling each core lightning command. In addition, we should
modify the invstring inside the db with the canonical one.

This commit fixes the issue by stripping the `lightning:` prefix
from the `listsendpays` function, which will improve the
user experience and ensure consistency in our invoice management (see
next commit).

Reported-by: @johngribbin
Link: ElementsProject#6207
Fixes: debbdc0
Changelog-Fixes: trim the `lightning:` prefix from invoice everywhere.
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2023-07-14 15:04:26 +09:30
Rusty Russell ad592d8b0d plugins: fix shutdown notification to contain object.
We fixed the others.  There are no fields, but this keeps it consistent.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: `shutdown` notification contains `shutdown` object (notification consistency)
2023-07-13 18:59:37 +09:30
Rusty Russell 4d507065f3 libplugin: support wildcard subscriptions.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-13 18:59:37 +09:30
Rusty Russell 279b3aa7e8 pyln: add ability to subscribe to all notifications.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-13 18:59:37 +09:30
Greg Sanders 4b70736d13 Support p2tr deposit addresses
Changelog-Added: JSON-RPC: newaddr: p2tr option to create taproot addresses.
Changelog-Changed: Wallet: we now use taproot change addresses.
2023-07-11 11:41:15 +09:30
Vincenzo Palazzo 011f3c1e14 lightnind: cleanup not necessary logs
This is just housekeeping that allows up
to do not spam the logs of people with not
useful information.

Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2023-07-11 09:24:31 +09:30
Rusty Russell 29bf5151f1 pytest: fix flake in test_closing_anchorspend_htlc_tx_rbf
Turns out we resubmit two txs (the commitment tx, and the anchor spend), but only wait
for one of them: if we mine a block before the anchor spend, it doesn't go in:

```
    @unittest.skipIf(TEST_NETWORK != 'regtest', 'elementsd anchors unsupported')
    @pytest.mark.developer("needs dev_disconnect")
    def test_closing_anchorspend_htlc_tx_rbf(node_factory, bitcoind):
...
        l1.daemon.wait_for_log('Peer permanent failure in CHANNELD_NORMAL: Offered HTLC 0 SENT_ADD_ACK_REVOCATION cltv 116 hit deadline')
        l1.daemon.wait_for_log('Creating anchor spend for CPFP')
    
        wait_for(lambda: len(bitcoind.rpc.getrawmempool()) == 2)
    
        # But we don't mine it!  And fees go up again!
        l1.set_feerates((3000, 3000, 3000, 3000))
        bitcoind.generate_block(1, needfeerate=5000)
    
        l1.daemon.wait_for_log('RBF anchor spend')
        l1.daemon.wait_for_log('sendrawtx exit 0')
    
        # And now we'll get it in (there's some rounding, so feerate a bit lower!)
        bitcoind.generate_block(1, needfeerate=2990)
    
>       wait_for(lambda: 'ONCHAIN:Tracking our own unilateral close' in only_one(l1.rpc.listpeerchannels()['channels'])['status'])
```
2023-07-10 13:37:22 +02:00
Rusty Russell 4b9537730b pytest: fix flake in test_routing_gossip.
If we mine too fast, gossip can reach a node which considers it too far in the guture.  Break it up.

```
    @pytest.mark.developer("Too slow without --dev-fast-gossip")
    def test_routing_gossip(node_factory, bitcoind):
        nodes = node_factory.get_nodes(5)
    
        for i in range(len(nodes) - 1):
            src, dst = nodes[i], nodes[i + 1]
            src.rpc.connect(dst.info['id'], 'localhost', dst.port)
            src.openchannel(dst, CHANNEL_SIZE, confirm=False, wait_for_announce=False)
    
        # openchannel calls fundwallet which mines a block; so first channel
        # is 4 deep, last is unconfirmed.
    
        # Allow announce messages.
        mine_funding_to_announce(bitcoind, nodes, num_blocks=6, wait_for_mempool=1)
    
        # Deep check that all channels are in there
        comb = []
        for i in range(len(nodes) - 1):
            comb.append((nodes[i].info['id'], nodes[i + 1].info['id']))
            comb.append((nodes[i + 1].info['id'], nodes[i].info['id']))
    
        def check_gossip(n):
            seen = []
            channels = n.rpc.listchannels()['channels']
            for c in channels:
                seen.append((c['source'], c['destination']))
            missing = set(comb) - set(seen)
            logging.debug("Node {id} is missing channels {chans}".format(
                id=n.info['id'],
                chans=missing)
            )
            return len(missing) == 0
    
        for n in nodes:
>           wait_for(lambda: check_gossip(n))

tests/test_gossip.py:721: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

success = <function test_routing_gossip.<locals>.<lambda> at 0x7f3200534ef0>
timeout = 180

    def wait_for(success, timeout=TIMEOUT):
        start_time = time.time()
        interval = 0.25
        while not success():
            time_left = start_time + timeout - time.time()
            if time_left <= 0:
>               raise ValueError("Timeout while waiting for {}".format(success))
E               ValueError: Timeout while waiting for <function test_routing_gossip.<locals>.<lambda> at 0x7f3200534ef0>
2023-07-10 13:37:22 +02:00
Matt Morehouse a264e10564 fuzz: initial sha256 seeds
Corpus generated from 100+ CPU hours of fuzzing and then minimized.
2023-07-10 14:56:50 +09:30
Matt Morehouse 8547912708 fuzz: initial ripemd160 seeds
Corpus generated from 100+ CPU hours of fuzzing and then minimized.
2023-07-10 14:56:50 +09:30
Matt Morehouse f0f043c742 fuzz: add sha256 target
The target fuzzes CCAN's implementation of sha256 and compares the hash
results against OpenSSL's implementation.
2023-07-10 14:56:50 +09:30
Matt Morehouse 8d7885abc1 fuzz: add ripemd160 target
The target fuzzes CCAN's implementation of ripemd160 and compares the
hash results against OpenSSL's implementation.
2023-07-10 14:56:50 +09:30
Rusty Russell 99b885c84c plugins: update for new deprecation API where all fields are nicely wrapped.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-10 14:51:11 +09:30
Shahana Farooqui 4e5e38f4b0 tests: notification response fixes
tests: notification response fixes
2023-07-10 14:51:11 +09:30
Christian Decker 6583f0dead pyln: Create a dedicated pyln-grpc-proto package
Having the grpc bindings in the pyln-testing package was always a bit
strange, however it came with additional issues. Due to the way that
protos are handled by protobuf, any name clash, independently of where
we import the protos, would cause an import error. This usually
happens in diamond-pattern dependencies, and so pull out the generated
files into their own package that everyone else can rely on.

Changelog-None
2023-07-10 13:47:38 +09:30
Rusty Russell 212c4dba76 pytest: fix flake in test_onchain_middleman_simple with anchors.
Greg Sanders helped debug this:

```
        # Payment should succeed.
>       l1.bitcoin.generate_block(1, wait_for_mempool=txid1)

tests/test_closing.py:2145: 
...
>               raise ValueError("Timeout while waiting for {}".format(success))
E               ValueError: Timeout while waiting for <function BitcoinD.generate_block.<locals>.<lambda> at 0x7f7cd7271560>
```

The lgos show the HTLC tx doesn't go through because it double-spent an input but didn't spend enough:

```
2023-07-06T03:05:54.3424456Z lightningd-2 2023-07-06T02:57:37.490Z DEBUG   plugin-bcli: sendrawtx exit 26 (bitcoin-cli -regtest -datadir=/tmp/ltests-yihsd7f4/test_onchain_middleman_simple_1/lightning-2/ -rpcport=39033 -rpcuser=... -stdinrpcpass sendrawtransaction 0200000000010220f632933db174def3b4bd879ad892e28f4422ee6e844bda27c4e5bdbc754fda030000000001000000975e48aeaced953f7c2b85f20e85b5c241258cb9dbd2ba13de3038daba6316330100000000fdffffff02a1860100000000002200202df545ea882889846c52fc5e111ac07ce07e0c09418ac15743a6f6284c2a4fa739391e000000000016001461ed06c0632af284ec9e192e97758fc04692c8290500473044022064446978d7f15d923237d44d7701e4a09a2d03ebb0a7e2c42e22c67435ad2fcc02201c51002fb72920978c79872e427acd90a13423e841b4198717c1771e7355ba4683473044022059ed9e2c536a71fac3cd63c7349c64a4445f0f936270295518a8aa03607d1e9d022064d318669a7602f585c84fe80aa95487816920c2a8ac26836601fbb369068ff38320478171dbde0e1c243e5c1ae23bcce446ab361197ca10d57c1d8f030cc9ff52158c76a914f5fb7361abefe39af0c3ab31d5be71096deeb4198763ac6721034bbdd4e5a933a3a83f6c3d22714cf23c452cb0c5ac8e429eea14992262787e687c8201208763a9147a3d3592e3d93a525beed57acce3eb70ba1b514288527c21039a62150fd6808d6c68aabd1e9d144c93e84a8f54f4e0f9ec5b3c37eee0a051c752ae6775017eb175ac6851b275680247304402200fde6a943a2f7f0287af2f5c5872326a4b8ad7020a098c4e05c28d2c2a0f2018022053a1263f982b98bb8dfcbb3a66641fe9f298e7ab432a78d21a2e79190d74753f012102397b0449a60d9d35634401bceaf3beb6118fc229b8552bd7122f735808b28aee00000000) error code: -26\nerror message:\ninsufficient fee, rejecting replacement 76f438f176d8f9beabb286f53c81aa7dcb4948d12f034f51753f4dd9071d6a74; new feerate 0.00029576 BTC/kvB <= old feerate 0.00054659 BTC/kvB
```

This is because sometimes we reuse the same UTXO for the anchor push spend as we do for the HTLC.  That would be fine, except that we can have bitcoind mine the commitment tx and not the anchor push, and then we fail to replace it.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-07-09 16:49:48 +09:30
Rusty Russell e6d23b5677 pytest: test for emergency minimum fund violations.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-29 11:28:47 -04:00
Rusty Russell 2f0e13e793 multifundchannel: use `excess_as_change` flag to simplify logic.
This was added to fundpsbt/utxopsbt in v0.10, but the spender plugin
didn't take advantage of it, instead calculating its own change amount
and output.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-29 11:28:47 -04:00
Rusty Russell 7894d7136f pytest: adapt all the anchor-iff-EXPERIMENTAL tests to --experimental-anchors.
We use parameterization here.  The old `anchor_expected()` was for
non-zero-fee anchors, and have bitrotted so there are some other
changes as well.

Unfortunately, all the anchor accounting seems to be broken, but I
cannot understand these tests at all.  I had to simply disable them
for now.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-29 11:28:47 -04:00
Rusty Russell f64188f925 pytest: make dual-funding tests using option_anchors_zero_fee_htlc_tx.
They used to force option_anchor_outputs, so switch them.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-29 11:28:47 -04:00
Rusty Russell 825173f1b4 pytest: test CPFP using anchors.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-29 11:28:47 -04:00
Rusty Russell af6d7c0779 global: thread zero fee option everywhere.
In most cases, it's the same as option_anchor_outputs, but for
fees it's different.  This transformation is the simplest:
pass it as a pair, and test it explicitly.

In future we could rationalize some paths, but this was nice
and mechanical.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-29 11:28:47 -04:00
Rusty Russell 96e198f751 openingd: use a lower feerate for first commitment tx for anchors.
We need to know both, because in theory we could negotiate a
non-anchor channel even if they support it.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-29 11:28:47 -04:00
Rusty Russell e45bf14300 lightningd: use lowball feerate for commit_tx on anchor channels.
Since we can CPFP, we don't have to track the feerate as closely.  But
it still needs to get in the mempool, so we use 10 sat/byte, or the
100 block estimate if that is higher.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: `feerates` has new fields `unilateral_anchor_close` to show the feerate used for anchor channels (currently experimental), and `unilateral_close_nonanchor_satoshis`.
Changelog-Changed: JSON-RPC: `feerates` `unilateral_close_satoshis` now assumes anchor channels if enabled (currently experimental).
2023-06-29 11:28:47 -04:00
Rusty Russell d895ef4fee pytest: test for commitment feerate.
Interesting we didn't actually test that the feerate we use is
actually delivered.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-29 11:28:47 -04:00
Rusty Russell b5845afd43 pytest: fix another flake in test_restorefrompeer.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-23 14:36:23 +09:30
Rusty Russell 71adeccfbf pytest: fix reconnect flake in test_plugin_connected_hook_chaining
```
         l1.rpc.reject(l3.info['id'])
     
         l2.connect(l1)
         l1.daemon.wait_for_logs([
             f"peer_connected_logger_a {l2id}",
             f"{l2id} is allowed",
             f"peer_connected_logger_b {l2id}"
         ])
         assert len(l1.rpc.listpeers(l2id)['peers']) == 1
     
 >       l3.connect(l1)
 tests/test_plugin.py:468: 
... 
 >           raise RpcError(method, payload, resp['error'])
 E           pyln.client.lightning.RpcError: RPC call failed: method: connect, payload: {'id': '0266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c03518', 'host': '127.0.0.1', 'port': 42391}, error: {'code': 402, 'message': 'disconnected during connection'}
 
 contrib/pyln-client/pyln/client/lightning.py:422: RpcError
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-23 14:36:23 +09:30
Matt Morehouse 8991f27497 fuzz: initial fuzz-cryptomsg seeds
Corpus generated by 300+ CPU hours of fuzzing and then minimized.
2023-06-23 13:12:42 +09:30
Matt Morehouse 1d94d2cd5d fuzz: test message encryption and decryption
Add a fuzz test for BOLT 8 message encryption and decryption. The fuzz
test is based on the unit test at common/test/run-cryptomsg.c and uses a
static initial state with fuzzer-generated messages to encrypt or
decrypt.
2023-06-23 13:12:42 +09:30
Matt Morehouse 8d9f033954 fuzz: initial handshake target seeds
Corpora generated for fuzz-connectd-handshake-act{1,2,3} from 300+ CPU
hours of fuzzing and then minimized.
2023-06-22 13:40:45 +09:30
Matt Morehouse 0e2173f1fd fuzz: add handshake act 3 target
The fuzz target uses static keys with a fuzzer-generated Act 3 packet.
2023-06-22 13:40:45 +09:30
Matt Morehouse a203db00ca fuzz: add handshake act 2 target
The fuzz target uses static keys with a fuzzer-generated Act 2 packet.
2023-06-22 13:40:45 +09:30
Matt Morehouse 4bb216a611 fuzz: add handshake act 1 target
The fuzz target uses static keys with a fuzzer-generated Act 1 packet.
2023-06-22 13:40:45 +09:30
Matt Morehouse 2b629b2509 fuzz: add connectd_handshake.h
This header will be used by multiple fuzz targets to fuzz Acts 1, 2, and
3 of the BOLT 8 handshake.

We could make this header into a full library, but considering its
narrow use let's try not to over-engineer things.
2023-06-22 13:40:45 +09:30
Rusty Russell ca9a6b15b5 pay: don't require description for hashdesc invoices (i.e. undeprecate).
Since we didn't hash the descriptions properly (see previous commit), we
cannot immediately deprecate omitting the descriptions (since you'd
have to omit them for backwards compat!).

And move the "must have description or hash" test into bolt11.c core.
Changelog-Deprecated: `pay` has *undeprecated* paying a description-hash invoice without providing the description.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-22 13:23:21 +09:30
Rusty Russell 92ff0fd8c0 pay, decodepay: handle descriptions with " inside them where we use hashed descriptions.
This means we need to push off requring this for another full deprecation cycle!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Fixed: JSON-RPC: `pay` and `decodepay` with description now correctly handle JSON escapes (e.g " inside description)
2023-06-22 13:23:21 +09:30
Rusty Russell 6287f3e3b1 pytest: test_pay flake fix.
This is almost certainly because the HTLCs are not fully settled, so wait for that:

```
2023-06-20T11:37:56.2332158Z         assert apys_2[0]['our_start_balance_msat'] == Millisatoshi(0)
2023-06-20T11:37:56.2332443Z >       assert apys_1[0]['routed_out_msat'] == apys_2[0]['routed_in_msat']
2023-06-20T11:37:56.2332571Z E       assert 1892216msat == 2810170msat
2023-06-20T11:37:56.2332580Z 
2023-06-20T11:37:56.2332717Z tests/test_pay.py:81: AssertionError
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-21 13:28:49 +09:30
Rusty Russell 35011337eb pytest: fix unexpected reconnection check in test_setconfig()
If we reconnect before the channel is completely closed, we might get
a "reconnected" message, so mine a block after and make sure it's
processed.

```
2023-06-20T11:37:56.1302058Z         if errors.has_errors():
2023-06-20T11:37:56.1302648Z             # Format a nice list of everything that went wrong and raise an exception
2023-06-20T11:37:56.1303781Z             request.node.has_errors = True
2023-06-20T11:37:56.1304091Z >           raise ValueError(str(errors))
2023-06-20T11:37:56.1304370Z E           ValueError: 
2023-06-20T11:37:56.1304624Z E           Node errors:
2023-06-20T11:37:56.1305042Z E            - lightningd-2: had unexpected reconnections
2023-06-20T11:37:56.1305340Z E           Global errors:
```
...
```
2023-06-20T11:37:56.1960525Z lightningd-2 2023-06-20T11:21:28.638Z DEBUG   0266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c03518-chan#2: Peer has reconnected, state CLOSINGD_SIGEXCHANGE: connecting subd
```
2023-06-21 13:28:49 +09:30
Rusty Russell 263625872e autoclean: allow dynamic changes to autoclean-cycle.
Slightly less trivial: reset timer unless it's currently running callback.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-20 20:08:25 +09:30
Rusty Russell f8f8045a06 autoclean: various configuration options now dynamic.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Changed: Plugins: `autoclean` configuration variables now settable with `setconfig`.
2023-06-20 20:08:25 +09:30
Rusty Russell aa5c7e763f libplugin: make set callback for options take plugin ptr, check correct type.
I added a plugin arg and was surprised that compile didn't break.
This is because typesafe_cb et al are conditional casts: if the type
isn't as expected it has no effect, but we're passing plugin_option() through
varargs, so everything is accepted!

Add a noop inline to check type, and fix up the two cases where we
used `const char *` instead of `char *`.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-20 20:08:25 +09:30
Rusty Russell 703ffdf59b setconfig: comment out now-overridden lines.
Do it slightly intelligently, so if we had set previously using setconfig
we don't keep appending new ones, but replace it in-place.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-20 20:08:25 +09:30
Rusty Russell 6546be9757 lightningd: setconfig command.
Currently only implemented for min-capacity-sat.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: new command `setconfig` allows a limited number of configuration settings to be changed without restart.
2023-06-20 20:08:25 +09:30
Rusty Russell d09d0112f4 pytest: handle v fast disconnect during test_funding_external_wallet_corners()
We get "disconnected during connection" if we haven't finished processing
the connection when the peer sends error and hangs up.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-20 17:24:48 +09:30
Rusty Russell 2abcd8108e pytest: fix race in test_penalty_rbf_normal
We re-enable sendrawtransaction then mine a block to kick off RBF, but there's
a race where it can get a tx in that block, and then we timeout waiting for
both txs to get into the next block.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-20 17:24:48 +09:30
Greg Sanders e125640f43 Persist feature bits across restarts
[ Whitespace fix and remove gratuitous tal_free(peer->their_features) -- RR ]
2023-06-20 10:07:11 +09:30
Vincenzo Palazzo 85992e6e48 feat(bitcoind): pass the current known block height
When core lightning is asking the information about
the blockchain with `getchaininfo` command lightningd
know already the information about the min and max block height.

the problem is when we have a smarter Bitcoin backend that is able
to switch between different clients in some cases is helpful
give the information about current known height by lightningd and
pass it down to the plugin.

In this way, the plugin knows what is the correct known height from lightnind, and can
try to fix some problems if any exit.

This is particularly useful when you are syncing a new backend from scratch
like https://github.com/cloudhead/nakamoto and we avoid returning the
lower height from the known, and avoid the crash of core lightning.

With this information, the plugin can start to sync the chain and return
the answer back only when the chain is in sync with the current status of
lightningd.

Another reason to add this field and not wait the correct block in core
lightning itself is because Bitcoin Core is extremely slow to sync up,
so the question here is, how long should we wait? The time depends
on various factors.

With this approach of informing the plugin about the height, in some cases,
you can start the syncing but move the execution to another backend until
the previous one is ready.

The problem I want to solve is that I don't want to be left in the dark when
we run `getchaininfo`, and I want to have the opportunity to wait for
the blockchain sync or decide to dispatch the request elsewhere.

Changelog-Added: Pass the current known block height down to the getchaininfo call.
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2023-06-13 16:27:10 +02:00
Rusty Russell 55119e6ca0 pytest: mark test_commando_stress as slow.
It sometimes takes > 1800 seconds under valgrind.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-06 19:47:08 +09:30
Rusty Russell 33be5c8d80 commando: integer command parameters can be compared with < and >.
Previously any attempt would result in "is not an integer field"; we
now recognize valid JSON integers as integer fields.

Changelog-Fixed: Plugins: `commando` runes can now compare integer parameters using '<' and '>' as expected.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-06 19:47:08 +09:30
Rusty Russell 0f72542967 pytest: test for amount comparison.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-06 19:47:08 +09:30
Rusty Russell 3ac949d4c3 listconfigs: add `plugin` field if config is for a plugin.
I chose the full path name, not just the basename.

Suggested-by: @SimonVrouwe
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-03 10:50:29 +09:30
Rusty Russell 6275dd384c lightningd: deprecate listconfigs direct fields.
Changelog-Deprecated: JSON-RPC: `listconfigs` direct fields, use `configs` sub-object and `set`, `value_bool`, `value_str`, `value_int`, or `value_msat` fields.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-03 10:50:29 +09:30
Rusty Russell ea928bfca1 pytest: use modern listconfigs.
Use the configs object, as the others are about to be deprecated.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-03 10:50:29 +09:30
Rusty Russell 9cb2b2f13a listconfigs: show plugin options in 'configs' with normal options.
This integrates them with configvars properly: they almost "just work"
in listconfigs now, and we don't put them in a special sub-object
under their plugin.

Unfortunately, this means `listconfigs` now has a loose schema: any
plugin can add something to it.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Fixed: Plugins: reloaded plugins get passed any vars from configuration files.
Changelog-Deprecated: Config: boolean plugin options set to `1` or `0` (use `true` and `false` like non-plugin options).
2023-06-03 10:50:29 +09:30
Rusty Russell 1b252f349f config: replace accept-htlc-tlv-types with accept-htlc-tlv-type
We use multi-specifiable options elsewhere, this is just another.
Otherwise you can't add, you can only set them all.

Changelog-Added: Config: `accept-htlc-tlv-type` (replaces awkward-to-use `accept-htlc-tlv-types`)
Changelog-Deprecated: Config: `accept-htlc-tlv-types` (use `accept-htlc-tlv-type` multiple times)
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-03 10:50:29 +09:30
Rusty Russell b9270c564a lightningd: listconfigs update, using configvars code.
listconfigs is convenient, but it doesn't handle multi-options well: it
outputs an object with duplicate fields in this case (e.g. log-file), nor
is it extensible to show more than raw values.

However, listconfigs doesn't do what other list commands do (use a
sub-object "configs") so we can put the new values under that.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: `listconfigs` now has `configs` subobject with more information about each config option.
2023-06-03 10:50:29 +09:30
Rusty Russell edbaa944da lightningd: switch parsing to common/configvar
Now we wire in the code which gathers configvars and parses from there;
lightningd keeps the array of configuration variables for future use.

Note that lightning-cli also needs to read the config, but it has its
own options (including short ones!) and doesn't want to use this
configvar mechanism, so we have a different API for that now.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-03 10:50:29 +09:30
Rusty Russell ec8bba6b8a dev-allowdustreserve: make this a DEVELOPER option.
Otherwise, we should rename it?

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-03 10:50:29 +09:30
Rusty Russell f45c17450b ccan: update to latest ccan/opt
This adds:
1. ability to search for an option by name.
2. allowance to set our own bits when registering options.
3. show callbacks which can say "don't show", and variable length.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-03 10:50:29 +09:30
Rusty Russell fafeb65012 lightningd: deprecated experimental-websocket-port now we can use bind=ws:
Changelog-Deprecated: `experimental-websocket-port`: use `--bind=ws::<portnum>`.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-01 09:28:39 +09:30
Rusty Russell 7b843e8e58 lightningd: deprecate weird listening options.
These are only likely to confuse users, by silently changing behavior.

Changelog-Deprecated: Config: bind-addr=xxx.onion and addr=xxx.onion, use announce=xxx.onion (which was always equivalent).
Changelog-Deprecated: Config: addr=/socketpath, use listen=/socketpath (which was always equivalent).
2023-06-01 09:28:39 +09:30
Rusty Russell 21958879cf lightningd: deprecated --announce-addr-dns.
This obsoletes the use of --announce-addr-dns which I know Michael
didn't really like either.

Changelog-Deprecated: Config: `announce-addr-dns`; use `--bind-addr=dns:ADDR` for finer control.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-01 09:28:39 +09:30
Rusty Russell e66cf46a71 connectd: don't advertise websocket addresses.
I never really liked this hack: websockets are useful, advertizing
them not so much.

Note that we never actually documented that we would advertize these!

Changelog-EXPERIMENTAL: Protocol: Removed support for advertizing websocket addresses in gossip.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-06-01 09:28:39 +09:30
Rusty Russell cfa33ce362 lightningd: fix incorrect reuse of dualopend, leading to dev_queryfeerates race
CI hit this issue where it would get a tx_abort in fundchannel.  This
happens when the dualopend we use to query the feerates has not exited
yet (it waits for the tx_abort reply), and we mistakenly reuse it.

With multi-channel support, this is wrong: just run another one and it
all Just Works.

This means we need to rework our dual_open_control.c logic, since it
would previously create an unsaved channel then not clean up if
something went wrong.

Most people will never try to negotiate opening multiple channels to
the same peer at the same time (vs. having an established channel and
opening a new one), so this case is a bit weird.

```
         rates = l1.rpc.dev_queryrates(l2.info['id'], amount, amount)
     
         # l1 leases a channel from l2
         l1.rpc.fundchannel(l2.info['id'], amount, request_amt=amount,
                            feerate='{}perkw'.format(feerate),
 >                          compact_lease=rates['compact_lease'])
 
 tests/test_opening.py:1611: 
 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
 contrib/pyln-client/pyln/client/lightning.py:833: in fundchannel
     return self.call("fundchannel", payload)
 contrib/pyln-testing/pyln/testing/utils.py:721: in call
     res = LightningRpc.call(self, method, payload, cmdprefix, filter)

 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
 
 self = <pyln.testing.utils.PrettyPrintingLightningRpc object at 0x7f6cbcd97950>
 method = 'fundchannel'
 payload = {'amount': 500000, 'announce': True, 'compact_lease': '029a00640064000000644c4b40', 'feerate': '2000perkw', ...}
 cmdprefix = None, filter = None
 
     def call(self, method, payload=None, cmdprefix=None, filter=None):
         """Generic call API: you can set cmdprefix here, or set self.cmdprefix
...
         if not isinstance(resp, dict):
             raise ValueError("Malformed response, response is not a dictionary %s." % resp)
         elif "error" in resp:
 >           raise RpcError(method, payload, resp['error'])
 E           pyln.client.lightning.RpcError: RPC call failed: method: fundchannel, payload: {'id': '022d223620a359a47ff7f7ac447c85c46c923da53389221a0054c11c1e3ca31d59', 'amount': 500000, 'feerate': '2000perkw', 'announce': True, 'request_amt': 500000, 'compact_lease': '029a00640064000000644c4b40'}, error: {'code': -1, 'message': 'Abort requested', 'data': {'id': '022d223620a359a47ff7f7ac447c85c46c923da53389221a0054c11c1e3ca31d59', 'method': 'openchannel_init'}}
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-05-29 13:46:21 +09:30
Rusty Russell 1af9b9d0a8 pytest: slow down for bitcoind.
Failure under CI:

```
>       bitcoind.generate_block(1000)

tests/test_closing.py:853: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
contrib/pyln-testing/pyln/testing/utils.py:496: in generate_block
    return self.rpc.generatetoaddress(numblocks, to_addr)
contrib/pyln-testing/pyln/testing/utils.py:374: in f
    res = proxy._call(name, *args)
../../../.cache/pypoetry/virtualenvs/cln-meta-project-AqJ9wMix-py3.7/lib/python3.7/site-packages/bitcoin/rpc.py:246: in _call
    response = self._get_response()
../../../.cache/pypoetry/virtualenvs/cln-meta-project-AqJ9wMix-py3.7/lib/python3.7/site-packages/bitcoin/rpc.py:276: in _get_response
    http_response = self.__conn.getresponse()
/opt/hostedtoolcache/Python/3.7.16/x64/lib/python3.7/http/client.py:1373: in getresponse
    response.begin()
/opt/hostedtoolcache/Python/3.7.16/x64/lib/python3.7/http/client.py:319: in begin
    version, status, reason = self._read_status()
/opt/hostedtoolcache/Python/3.7.16/x64/lib/python3.7/http/client.py:280: in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <socket.SocketIO object at 0x7fa21aa5d710>
b = <memory at 0x7fa21b771390>

    def readinto(self, b):
        """Read up to len(b) bytes into the writable buffer *b* and return
        the number of bytes read.  If the socket is non-blocking and no bytes
        are available, None is returned.
    
        If *b* is non-empty, a 0 return value indicates that the connection
        was shutdown at the other end.
        """
        self._checkClosed()
        self._checkReadable()
        if self._timeout_occurred:
            raise OSError("cannot read from timed out object")
        while True:
            try:
>               return self._sock.recv_into(b)
E               socket.timeout: timed out

/opt/hostedtoolcache/Python/3.7.16/x64/lib/python3.7/socket.py:589: timeout
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-05-29 13:46:21 +09:30
Rusty Russell 63e2619f9e pytest: fix up DF tests after onchaind broadcast rework.
07413c20b9 et al reworked how onchaind
does broadcasts, meaning tests needed to be updated to the new helpers
rather than searching logs themselves.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-05-29 13:46:21 +09:30
Rusty Russell 548b54e971 pytest: update test_v2_fail_second for listpeers changes.
Now should use listpeerchannels, since listpeers['channels'] is
deprecated.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-05-29 13:46:21 +09:30
Matt Morehouse 34d104b809 fuzz: new fuzz-bech32 seeds
Add new seeds generated after improving the fuzz-bech32 target.
2023-05-27 15:06:31 +09:30
Matt Morehouse ecdbab5813 fuzz: simplify fuzz-bech32.c
Use a short loop to eliminate redundant code.
2023-05-27 15:06:31 +09:30
Matt Morehouse 7db1e06fb5 fuzz: check decoded values
Decoded values should match the original values before encoding.
2023-05-27 15:06:31 +09:30
Matt Morehouse 255413377b fuzz: allow bech32_encode to succeed
We were passing a max_output_len that was too small, so every call to
bech32_encode was failing. Now we set max_output_len to the full size of
bech32_str.
2023-05-27 15:06:31 +09:30
Greg Sanders 90fefe0c3d test_withdraw_bech32m: test that expected outputs exist for bech32(m) withdrawals 2023-05-25 11:07:45 +09:30
Rusty Russell c11ae1aa34 pytest: remove EXPERIMENTAL_FEATURES as a consideration.
This currently means anchors tests are disabled, awaiting the
PR which implements zero-fee-htlc anchors to reenable them.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-05-23 09:34:08 +09:30
Rusty Russell b8aa3a579e listtransactions: remove annotations, which were only in EXPERIMENTAL_FEATURES.
I don't know if anyone was using them, they seem half-hearted.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-05-23 09:34:08 +09:30
Rusty Russell 4deb552fe9 build: don't generate experimental variants of wire files.
We no longer have any experimental-only wire definitions.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-05-23 09:34:08 +09:30
Rusty Russell ccf084156d channeld: use explicit --experimental-upgrade flag, not #ifdef EXPERIMENTAL_FEATURES
And no longer insist on opt_quiesce.

Changelog-EXPERIMENTAL: Config: `--experimental-upgrade-protocol` enables simple channel upgrades.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-05-23 09:34:08 +09:30
Rusty Russell 6c23349c72 channeld: allow stfu based on peer features, not EXPERIMENTAL_FEATURES.
Changelog-EXPERIMENTAL: Config: `--experimental-quiesce` enables queiescence, for testing.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-05-23 09:34:08 +09:30
Matt Morehouse f7602ea335 fuzz: new fuzz-bip32 seeds
Add new seeds generated after improving the fuzz-bip32 target.
2023-05-21 12:46:27 +02:00
Matt Morehouse 8265a94858 fuzz: correct buffer length for bip32_key_version
8 bytes are expected, not 4.

Because we were passing the wrong number of bytes, parsing was failing
every single time.
2023-05-21 12:46:27 +02:00
Matt Morehouse 7d662b6b68 fuzz: check key validity before serializing
We need to check that the key is valid for two reasons:
  1) towire_ext_key() aborts if the key is invalid
  2) fromwire_ext_key() doesn't check the parsed key for validity

Since bip32_key_get_fingerprint() fails if the key is invalid, we can
call it first to guarantee the key is valid before serializing.
2023-05-21 12:46:27 +02:00
Rusty Russell b746588356 pytest: fix tests/test_cln_rs.py to avoid race.
When we release too fast, the plugin crashes:

```
thread 'tokio-runtime-worker' panicked at 'called Result::unwrap() on an Err value: SendError(())', plugins/examples/cln-plugin-reentrant.rs:31:27
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace
```

This happens with CI under VALGRIND!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-05-19 14:17:44 +02:00
Christian Decker 708fb17fa2 pytest: Add helper to get a grpc stub and test decode 2023-05-05 09:24:07 -07:00
Christian Decker 90ede052ad pytest: Extend ListPeerChannels test to include ListClosedChannels 2023-05-05 11:54:41 +09:30
Christian Decker 318f35b243 pytest: Add a test for the grpc conversion of listpeerchannels
This is still a huge response, so we better make sure we can actually
convert it correctly.
2023-05-05 11:54:41 +09:30
Alex Myers 782c17996e pytest: ignore pip warning
Avoids failing the test with the pip warning:
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv

reported by: @ksedgwic
Changelog-None
2023-04-24 13:08:15 -07:00
Alex Myers 233f05e0e2 reckless: enable case-insensitive searching
Adds a test to validate case matching.
2023-04-15 10:33:07 -07:00
Christian Decker f69da84256 rs: Run hooks, methods and notification handlers in tokio tasks
Changelog-Changed: cln-plugin: Hooks, notifications and RPC methods now run asynchronously allowing for re-entrant handlers
2023-04-13 18:13:28 -07:00
Christian Decker db3707f957 pytest: Highlight the re-entrancy issue for cln-plugin events
This was pointed out by Daywalker [1]: we are synchronously processing
events from `lightningd` which means that if processing one of the
hooks or requests was slow or delayed, we would not get notifications,
hooks, or RPC requests, massively impacting the flexbility.

This highlights the issue with a failing test (it times out), and in
the next commit we will isolate event processing into their own task,
so to free the event loop from having to wait for an eventual
response.

[1] https://community.corelightning.org/c/developers/hold-invoice-plugin#comment_wrapper_16754493
2023-04-13 18:13:28 -07:00
Rusty Russell 8ef4b36a1f gossipd: send our own gossip aggressively when a new peer connects.
This was previously the role of connectd, but it's actually more
efficient for us to do it: connectd has to sweep through the entire
gossip_store, but we have datastructures for this already.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-04-13 08:48:50 -07:00
Rusty Russell ba7901bebd pytest: fix up test_gossip_ratelimit.
We were in fact feeding l1 its own gossip, which it doesn't ratelimit (this was
a bit fuzzy before, but definitely is the case now!).

So make this node actually l3, so we test what we expected to test.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-04-13 08:48:50 -07:00
Rusty Russell 58c624d067 pytest: fix test_penalty_htlc_tx_timeout accounting flake.
This test makes l2 save db, make a payment, then rollback.
*Sometimes* under CI (but not here) we don't shutdown fast enough
after the payment, so the moves.json from the coin_movements.py
records it.  Sure enough, the result is the node ends up with
a -10000msat balance.

Validated by putting a time.sleep(5) between:

```
    l2.rpc.pay(inv['bolt11'])

    import time
    time.sleep(5)
    # stop both nodes, roll back l2's database
```

The answer, of course, is to save and rollback *both* the db and
moves.json file.

Here's the error:
```
    def test_penalty_htlc_tx_timeout(node_factory, bitcoind, chainparams):
...    
        assert account_balance(l3, channel_id) == 0
>       assert account_balance(l2, channel_id) == 0

tests/test_closing.py:1527: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
tests/utils.py:184: in account_balance
    m_sum -= Millisatoshi(m['debit_msat'])
contrib/pyln-client/pyln/client/lightning.py:197: in __sub__
    return Millisatoshi(int(self) - int(other))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = -10000msat, v = -10000
...    
        if self.millisatoshis < 0:
>           raise ValueError("Millisatoshi must be >= 0")
E           ValueError: Millisatoshi must be >= 0

contrib/pyln-client/pyln/client/lightning.py:82: ValueError
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-04-13 09:03:13 +09:30
Rusty Russell 2e7ecb98f4 pytest: make sure we wait for all feerates to be gathered.
We need to wait until we're sure bcli has handed results to lightningd:

```
>       assert feerates['perkw']['mutual_close'] == 5000
E       assert 6250 == 5000

tests/test_misc.py:1617: AssertionError
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-04-13 09:03:13 +09:30
Rusty Russell 62d9ecb6d3 hsmtool: makerune command.
You still need to actually make a rune when lightningd starts, as
commando (for safety) won't work unless you actually generate a rune
(that it knows of!).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: hsmtool: `makerune` command to make a master rune for a node.
2023-04-11 11:19:13 -07:00
Christian Decker 6d76642f7e cln: Fix routehints conversion from cln-rpc and cln-grpc
Fixes #6143
Changelog-Fixed: clnrs: Fixed an issue converting routehints in keysend
2023-04-10 17:34:54 +09:30
Christian Decker b42984afe1 pytest: Reproduce #6143 2023-04-10 17:34:54 +09:30
Rusty Russell a000ee015a lightningd: do RBF again for all the txs.
Now we've set everything up, the replacement code is quite simple.

Some tests now have to deal with RBF though, and our rbf tests need work
since they look for the old onchaind messages.

In particular, when we can't afford the fee we want, we back off to
the next blockcount estimate, rather than spending all on fees
(necessarily).  So test_penalty_rbf_burn no longer applies.

Changelog-Changed: Protocol: spending unilateral close transactions now use dynamic fees based on deadlines (and RBF), instead of fixed fees.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-04-10 07:31:12 +09:30
Rusty Russell 3a3370f4c1 feerates: add `floor` field for the current minimum feerate bitcoind will accept
Changelog-Added: JSON-RPC: `feerates`: added `floor` field for current minimum feerate bitcoind will accept
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-04-10 07:31:12 +09:30
Rusty Russell 812a5a14c0 plugins/bcli: use the new feerate levels, and the floor.
Fixes: #4473
Changelog-Deprecated: Plugins: `estimatefees` returning feerates by name (e.g. "opening"); use `fee_floor` and `feerates`.
Changelog-Fixed: Plugins: `bcli` now tells us the minimal possible feerate, such as with mempool congestion, rather than assuming 1 sat/vbyte.
2023-04-10 07:31:12 +09:30
Rusty Russell 9e2d4240b1 lightningd: handle bcli plugins returning fee_floor and feerates parameters.
Changelog-Added: Plugins: `estimatefees` can return explicit `fee_floor` and `feerates` by block number.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2023-04-10 07:31:12 +09:30