Commit Graph

500 Commits

Author SHA1 Message Date
Rusty Russell
6a84fc2d47 pytest: don't ask for p2tr addresses on liquid.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-10-26 12:37:58 +10:30
Sangbida Chaudhuri
310405761a schema: update schema to remove bip86 and add mnemonic to expose secret
This schema change updates newaddr to remove bip86 which was previously added, since don't want to make unnecessary schema changes this is being removed.

The generated files for the exposesecret schema change are also being added
2025-10-26 12:37:58 +10:30
Sangbida Chaudhuri
22b17daab9 tests: Update test assertions and comments for unified derivation approach 2025-10-26 12:37:58 +10:30
Rusty Russell
9987b6f93a lightningd: try harder to ensure uniqueness in --dev-save-plugin-io names.
Incorporate a time: this covers the restart case as well.  And make it time_mono(),
which doesn't get overridden when we override normal wall time.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-10-24 11:30:17 +10:30
Rusty Russell
eb0d042693 common: add brace hack for jsonrpc_async_parse.
This is a trick from bcli: we ask bitcoind for the block, and it hands
us a 2MB hex blob (which we read in multiple parts).  Our parser wades
through it all, but a quick search for '}' makes it much faster.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-10-24 11:28:57 +10:30
Rusty Russell
c88c8eacd0 lightningd: use jsonrpc_io for reading JSON commands.
This is more efficient if we have lots of incoming commands, too.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-10-24 11:28:57 +10:30
Rusty Russell
01e83b7637 lightningd: handle unparsable onion from first hop when using injectonionmessage.
In this case we have a failmsg, so we should use that.  Otherwise we can have
both failmsg and failonion NULL in the call to injectonion_fail, which is not
valid.

```
DEBUG   022d223620a359a47ff7f7ac447c85c46c923da53389221a0054c11c1e3ca31d59-chan#1: Removing out HTLC 1 state RCVD_REMOVE_ACK_REVOCATION WIRE_INVALID_ONION_HMAC
**BROKEN** lightningd: FATAL SIGNAL 11 (version v25.09-135-g19a3bbc-modded)
**BROKEN** lightningd: backtrace: common/daemon.c:41 (send_backtrace) 0x6220e8fe0080
**BROKEN** lightningd: backtrace: common/daemon.c:78 (crashdump) 0x6220e8fe00cf
**BROKEN** lightningd: backtrace: ./signal/../sysdeps/unix/sysv/linux/x86_64/libc_sigaction.c:0 ((null)) 0x73614bc4532f
**BROKEN** lightningd: backtrace: lightningd/pay.c:1701 (injectonion_fail) 0x6220e8f951c0
**BROKEN** lightningd: backtrace: lightningd/pay.c:330 (tell_waiters_failed) 0x6220e8f943be
**BROKEN** lightningd: backtrace: lightningd/pay.c:656 (payment_failed) 0x6220e8f98db1
**BROKEN** lightningd: backtrace: lightningd/peer_htlcs.c:313 (fail_out_htlc) 0x6220e8fa1d04
**BROKEN** lightningd: backtrace: lightningd/peer_htlcs.c:1988 (remove_htlc_out) 0x6220e8fa271b
**BROKEN** lightningd: backtrace: lightningd/peer_htlcs.c:2086 (update_out_htlc) 0x6220e8fa2904
**BROKEN** lightningd: backtrace: lightningd/peer_htlcs.c:2095 (changed_htlc) 0x6220e8fa2c24
**BROKEN** lightningd: backtrace: lightningd/peer_htlcs.c:2608 (peer_got_revoke) 0x6220e8fa6e5a
**BROKEN** lightningd: backtrace: lightningd/channel_control.c:1555 (channel_msg) 0x6220e8f62725
**BROKEN** lightningd: backtrace: lightningd/subd.c:560 (sd_msg_read) 0x6220e8fb2eed
**BROKEN** lightningd: backtrace: ccan/ccan/io/io.c:60 (next_plan) 0x6220e90a3335
**BROKEN** lightningd: backtrace: ccan/ccan/io/io.c:422 (do_plan) 0x6220e90a3806
**BROKEN** lightningd: backtrace: ccan/ccan/io/io.c:439 (io_ready) 0x6220e90a38c3
**BROKEN** lightningd: backtrace: ccan/ccan/io/poll.c:455 (io_loop) 0x6220e90a524f
**BROKEN** lightningd: backtrace: lightningd/io_loop_with_timers.c:22 (io_loop_with_timers) 0x6220e8f7d1c7
**BROKEN** lightningd: backtrace: lightningd/lightningd.c:1496 (main) 0x6220e8f82db2
**BROKEN** lightningd: backtrace: ../sysdeps/nptl/libc_start_call_main.h:58 (__libc_start_call_main) 0x73614bc2a1c9
**BROKEN** lightningd: backtrace: ../csu/libc-start.c:360 (__libc_start_main_impl) 0x73614bc2a28a
**BROKEN** lightningd: backtrace: (null):0 ((null)) 0x6220e8f53b64
**BROKEN** lightningd: backtrace: (null):0 ((null)) 0xffffffffffffffff
```

Reported-by: @michael1011
Changelog-Fixed: lightningd: potential crash when we receive a malformed onion complain from our first peer when using sendonion / injectpaymentonion.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-10-13 14:13:57 +10:30
Rusty Russell
5c71ba2210 pytest: test for malformed reply from first hop when using injectpaymentonion.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-10-13 14:13:57 +10:30
Rusty Russell
cb2849d03f wallet: don't delete old htlcs when we forget a channel, do it on startup.
For old channels, this can take a while, and it stops everything.  But
we are only doing this to save space; it's not a *functional* necessity.

A quick and dirty test with 50,000 htlcs shows the htlc deletion took
450msec.  I tried adding an index, and changing it to set hstate to
HTLC_STATE_INVALID instead of deleting entries, but it still took about 350ms.

Whereas the "COUNT(*)" only took 1.7msec, so it's worth keeping.

Reported-by: @michael1011
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Changed: lightningd: we defer deletion of old htlcs on channel close, to avoid pausing for a long time (we clean them on startup)
Fixes: https://github.com/ElementsProject/lightning/issues/7962
2025-10-02 10:19:55 +09:30
Matt Whitlock
4d47cc681d tests: do not leak file descriptors
Changelog-None
2025-09-15 11:19:17 +09:30
Rusty Russell
12e2f58e69 pytest: restore bookkeeper to recover tests.
Now handles when we remove the db.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-08-19 13:37:50 +09:30
Rusty Russell
fd657e8483 ]bkpr: save accounts in the datastore instead of database.
Note that the test where we remove the database causes the bookkeeper
plugin to assert, since we have removed part (but not all!) of its data
by removing the datastore.

Once the transition to the datastore is complete, this can be restored.

Note that we destroy the request before receiving a response, which causes
a message in the trace span which was confusing our test.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-08-19 13:37:50 +09:30
Rusty Russell
e43a4a96e7 pyln-testing: check plugin notifications against any extant notification schemas.
Note that we need a workaround for deprecated APIs where "channel_state_changed" output "null" which violated the schema.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-08-18 10:01:07 +09:30
Rusty Russell
7893c878b1 pytest: use _ not - in plugin options to zeroconf-selective.py.
This allows us to specify:

	l2.rpc.plugin_start(plugin_path, zeroconf_allow=l1.info['id'])

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-08-13 14:20:28 +09:30
Rusty Russell
4e94a6cb2b lightningd: make option_channel_type compulsory.
As per BOLT recommendation https://github.com/lightning/bolts/pull/1232, this means
we will insist on this being available.

For CLN, we added this in 0.12.0 (2022-08-23), though there were fixes as late as 24.02. Either way that's well outside our support window.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Closes: https://github.com/ElementsProject/lightning/issues/8152
Changelog-Changed: Protocol: We now insist that peers support `option_channel_type` (in CLN since 0.12.0 in late 2022, similar for other implementations).
2025-08-13 14:20:28 +09:30
Rusty Russell
6a94683db4 hsmd: don't assert that our own locktime is > 0.
By policy, our stub hsmd accepts everything: openingd is supposed to
sort this out (or use VLS for a real HSM implementation!).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Fixed: Config: the node no longer crashes if you set `watchtime-blocks` to 0 (which is fine for testing: don't do this on mainnet!).
2025-08-07 14:55:30 +09:30
Rusty Russell
e6b14da968 pytest: test for watchtime-blocks=0
It's not really advisable, but it's legal, though our HSMD refuses to
sign off on operations.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-08-07 14:55:30 +09:30
Rusty Russell
b7e20b327c lightningd: enable peer storage by default,
Now we've make it only on existing channels, and not have to call
listdatastore every time, that means we can safely turn it on by
default.

Changelog-Added: Protocol: we now offer peer storage to any peers who create a channel.
Changelog-Deprecated: Config: `--experimental-peer-storage` (it's now the default).
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-05-16 23:39:35 +09:30
Rusty Russell
adf7663fef chanbackup: only store backups for peers with current/previous channels.
This seems fair.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-05-16 23:39:35 +09:30
Rusty Russell
833b8d11d3 pytest: fix test_bitcoind_fail_first to accept multi-line broken messages.
This will still pass once we split the lines in the next commit.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-05-14 17:12:47 +09:30
Lagrang3
50cdf05a4a add signmessagewithkey RPC
signmessagewithkey: allows to sign a message with a key associated with
one bitcoin address in our wallet.

Changelog-Added: add a new rpc command signmessagewithkey to sign input messages with keys from our wallet.

Signed-off-by: Lagrang3 <lagrang3@protonmail.com>
2025-05-13 13:19:03 +09:30
ShahanaFarooqui
49bcc94f3b tests: Fix test_emergencyrecover to check for ChannelReestablish
Make sure we are sending bogus channel reestablish after recovering from
emergency.recover file and peer storage backup.

Key Changes:
 - Add wait_for_log() with appropriate debug statements
2025-05-13 09:48:42 +09:30
Rusty Russell
0824d12849 bcli: don't try asking non-full nodes for blocks.
Suggested-by: @NicolasDorier
Closes: https://github.com/ElementsProject/lightning/issues/8078
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Changed: Protocol: we no longer try asking for blocks from bitcoind's peers if they don't store blocks.
2025-05-12 10:38:25 +09:30
Rusty Russell
628d002c59 pytest: fix flake in test_listforwards_and_listhtlcs
We need to make sure the close tx is generated where we expect, so the following code
doesn't wait foreverL

```
2025-05-08T04:31:31.1071194Z >       assert l2.rpc.wait('htlcs', 'deleted', 3)['deleted'] == 5
2025-05-08T04:31:31.1071518Z 
2025-05-08T04:31:31.1071645Z tests/test_misc.py:3398: 
...
2025-05-08T04:31:31.1079841Z E       Failed: Timeout >1800.0s
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-05-11 11:25:40 +09:30
Rusty Russell
1d5cb4b49c bitcoin: fix out-by-one-error in bitcoin_tx_input_weight.
We need one byte for the number of witness elements.  Some callers added it themselves,
but it's always needed.  So document and fix the callers.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-05-06 12:27:53 +09:30
Rusty Russell
a8f75cca28 common: fix utxo_spend_weight to understand how cheap P2TR is.
We previously treated it as a P2WPKH, which is wrong.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Fixed: wallet: fees are much closer to target feerate when doing txprepare/fundchannel.
2025-05-06 12:27:53 +09:30
Rusty Russell
7a276bbe09 common/utxo: use a real type for the UTXO, not a boolean is_p2sh.
To actually evaluate spend cost, we need to know whether it's taproot or not.
Using an enum (rather than making callers examine the script) means we can
ensure all cases are handled.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-05-06 12:27:53 +09:30
Rusty Russell
f054600723 pytest: fix flake in test_setconfig_access.
We were supposed to put the sqlite db in a different directory, but
the test was wrong!  So occasionally we would crash with:

```
Failed to commit DB transaction: Failed to commit a transaction: disk I/O error
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-05-02 13:25:11 -07:00
Rusty Russell
6bf36915fd lightningd: support index/start/end pagination for listhtlcs.
Changelog-Added: JSON-RPC: `listhtlcs` supports `index`, `start` and `end` parameters for pagination support.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-04-29 09:38:20 +09:30
Rusty Russell
7ba6263c48 lightningd: add created_index and updated_index to listhtlcs.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON-RPC: `listhtlcs` has `created_index` and `updated_index` fields.
2025-04-29 09:38:20 +09:30
Rusty Russell
07c495e7fb lightningd: keep indexes updated for channel_htlcs table (aka listhtlcs).
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-04-29 09:38:20 +09:30
Rusty Russell
db104aae92 lightningd: improve wait API by making details fields per-subsystem.
It makes the schema simpler, and indeed, expressable by GRPC.

Changelog-Added: JSON-RPC: `wait` now has separate `invoices`, `forwards` and `sendpays` objects for each subsystem.
Changelog-Deprecated: JSON-RPC: `wait` reply `details` object: use subsytem specific object instead.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-04-29 09:38:20 +09:30
Rusty Russell
e951155002 trace: fix parent handling (and test it!).
Testing parenting handling revealed several issues:

1. By calling "trace_span_start" when CLN_TRACEPARENT is set produces a bogus
   entry, for which the span_id is overwritten so we never end it.
2. We don't need to close the remote parent when we close the first child: in
   fact, this causes the remaining traces to be detached from the parent!
3. Suspension should return current to the parent, not to NULL.

Now the traces balance as we expect.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-04-23 13:45:18 +09:30
Rusty Russell
924f28adcb pytest: add test hooks so we can test tracing.
Suggested-by: Christian Decker
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-04-23 13:45:18 +09:30
Rusty Russell
139d21173b pytest: fix test_recover_plugin flake
It can try to reconnect while we're explicitly connecting:

```
2025-04-15T03:40:53.9184103Z >       l2.rpc.connect(l1.info['id'], 'localhost', l1.port)
2025-04-15T03:40:53.9184311Z 
2025-04-15T03:40:53.9184401Z tests/test_misc.py:3078:
...
2025-04-15T03:40:53.9206302Z >           raise RpcError(method, payload, resp['error'])
2025-04-15T03:40:53.9207225Z E           pyln.client.lightning.RpcError: RPC call failed: method: connect, payload: {'id': '0266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c03518', 'host': 'localhost', 'port': 45219}, error: {'code': 402, 'message': 'disconnected during connection'}
```

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-04-16 08:02:14 +09:30
Rusty Russell
2050f9afd9 pytest: fix flake in test_setconfig_access.
We play with directory permissions, but sqlites needs that, and sometimes (due to a timer, perhaps?)
it gets really upset about it:

```
lightningd-1 2025-03-16T23:29:58.506Z INFO    lightningd: Server started with public key 0266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c03518, alias JUNIORBEAM-f91eb11-modded (color #0266e4) and lightningd f91eb11-modded
lightningd-1 2025-03-16T23:29:58.617Z DEBUG   lightningd: Adding block 101: 55af171ade598f8c4f9a494eaaffe6b9f5ea64c7b0f3b273694148adf7ad7385
lightningd-1 2025-03-16T23:29:58.752Z TRACE   lightningd: Calling rpc_command hook of plugin cln-xpay
lightningd-1 2025-03-16T23:29:58.764Z TRACE   lightningd: Plugin cln-xpay returned from rpc_command hook call
lightningd-1 2025-03-16T23:29:58.784Z TRACE   lightningd: Calling rpc_command hook of plugin cln-xpay
lightningd-1 2025-03-16T23:29:58.840Z TRACE   lightningd: Plugin cln-xpay returned from rpc_command hook call
lightningd-1 2025-03-16T23:29:58.854Z TRACE   lightningd: Calling rpc_command hook of plugin cln-xpay
lightningd-1 2025-03-16T23:29:58.865Z DEBUG   gossipd: REPLY WIRE_GOSSIPD_NEW_BLOCKHEIGHT_REPLY with 0 fds
lightningd-1 2025-03-16T23:29:58.901Z **BROKEN** lightningd: Error executing statement: db/exec.c:108: UPDATE vars SET intval = intval + 1 WHERE name = 'data_version' AND intval = ?: attempt to write a readonly database
lightningd-1 2025-03-16T23:29:58.916Z **BROKEN** lightningd: Error executing statement: db/exec.c:108: UPDATE vars SET intval = intval + 1 WHERE name = 'data_version' AND intval = ?: attempt to write a readonly database
lightningd-1 2025-03-16T23:29:58.941Z **BROKEN** lightningd: FATAL SIGNAL 6 (version f91eb11-modded)
{'github_repository': 'ElementsProject/lightning', 'github_sha': 'f91eb118388dc1455c67d16079168fd0267ba248', 'github_ref': 'refs/pull/8112/merge', 'github_ref_name': 'HEAD', 'github_run_id': 13888173501, 'github_head_ref': 'flake-memleak', 'github_run_number': 12573, 'github_base_ref': 'master', 'github_run_attempt': '1', 'testname': 'test_setconfig_access', 'start_time': 1742167762, 'end_time': 1742167800, 'outcome': 'fail'}
----------------------------- Captured stderr call -----------------------------
Error executing statement: db/exec.c:108: UPDATE vars SET intval = intval + 1 WHERE name = 'data_version' AND intval = ?: attempt to write a readonly database
lightningd: FATAL SIGNAL 6 (version f91eb11-modded)
Log dumped in /tmp/lightning-crash.log.20250316232958
Lost connection to the RPC socket.Lost connection to the RPC socket.
=========================== short test summary info ============================
FAILED tests/test_misc.py::test_setconfig_access - AssertionError: Regex pattern did not match.
 Regex: 'Cannot write to config file /tmp/ltests-22a5dz1j/test_setconfig_access_1/lightning-1/regtest/config'
 Input: "RPC call failed: method: check, payload: {'command_to_check': 'setconfig', 'config': 'min-capacity-sat', 'val': 1000000}, error: Connection to RPC server lost."
ERROR tests/test_misc.py::test_setconfig_access - ValueError:
Node errors:
 - lightningd-1: had BROKEN messages
 - lightningd-1: Node exited with return code -6
```

So we move the db file for sqlite.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-03-24 13:59:58 +10:30
Rusty Russell
67c91a7e5c BOLTs: Update to version with peer storage merged.
Unfortunately a spec typo means the data fields are missing (PR pending),
so we still patch those in.

The message "your_peer_storage" got renamed to "peer_storage_retrieval",
and the option "want_peer_backup_storage" was removed.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-EXPERIMENTAL: `experimental-peer-storage` now only advertizes feature 43, not 41.
2025-03-18 14:30:58 +10:30
Rusty Russell
10f333b041 devtools/bolt12-cli: fix interpretation of blindedpay, amounts.
The old blindedpay fields would have an entry per hop, but that was changed
to a single per-path entry.  The devtools hadn't caught up.

Similarly, it didn't like descriptionless offer fields in invreqs and invoices.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-02-26 14:26:47 -06:00
Rusty Russell
4fdbd8ba98 lightningd: catch edits of config files *before* we're committed.
Another report, that we crash if it's edited.  We should check that too!

Reported-by: daywalker90
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-02-24 19:38:37 +10:30
Rusty Russell
5e79cd4608 lightningd: check for writability before allowing setconfig.
If we actually can't write it, we crash (to avoid an inconsistent
state), so sanity check FIRST.

Fixes: https://github.com/ElementsProject/lightning/issues/7964
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-02-24 19:38:37 +10:30
Rusty Russell
989cf17982 setconfig: put vars in separate "config.setconfig" file.
This is neater than appending to some random file: we only do that once
if there's no "include" line to include a ".setconfig" file.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-02-24 19:38:37 +10:30
Rusty Russell
da2fb198c4 setconfig: make source for setconfig "setconfig transient".
Previously it would be the value of the previous config setting.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-02-24 19:38:37 +10:30
Rusty Russell
5a80223f3e setconfig: add transient option.
Changelog-Added: JSON-RPC: `setconfig` now has a `transient` flag which means it won't rewrite your config file.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-02-24 19:38:37 +10:30
Aditya Sharma
2dcbc701e4 tests: Added test_emergencyrecoverpenaltytxn
This test would make sure that the node would publish a penalty txn when channel partner
cheats.
2025-02-22 11:51:54 -06:00
Aditya Sharma
b44ed32408 test_misc.py: Add test_emergencyrecover_old_format_handling
Key Changes:
 - Added encrypted_data which contains emergency.recover in the legacy format
 - Added assert to make sure we watch the funding txn
2025-02-22 11:51:54 -06:00
Rusty Russell
6d142dfad2 pytest: add multiline help test.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-02-20 14:37:28 +10:30
Rusty Russell
d18f564324 pytest: stop using deprecated commando_rune commands.
These are about to start logging warnings, so use modern versions for tests
which aren't explicitly about testing obsolete ones.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2025-02-13 21:15:45 -06:00
Rusty Russell
98679aa6cf pytest: fix flake in test_restorefrompeer.
Just because we've seen the block doesn't mean onchaind has finished
starting up.

```
 _____________________________ test_restorefrompeer _____________________________
[gw0] linux -- Python 3.10.15 /home/runner/.cache/pypoetry/virtualenvs/cln-meta-project-AqJ9wMix-py3.10/bin/python

node_factory = <pyln.testing.utils.NodeFactory object at 0x7fb8f3887f70>
bitcoind = <pyln.testing.utils.BitcoinD object at 0x7fb8f3886f50>

    @unittest.skipIf(os.getenv('TEST_DB_PROVIDER', 'sqlite3') != 'sqlite3', "deletes database, which is assumed sqlite3")
    def test_restorefrompeer(node_factory, bitcoind):
        """
        Test restorefrompeer
        """
        l1, l2 = node_factory.get_nodes(2, [{'broken_log': 'ERROR: Unknown commitment #.*, recovering our funds!',
                                             'experimental-peer-storage': None,
                                             'may_reconnect': True,
                                             'allow_bad_gossip': True},
                                            {'experimental-peer-storage': None,
                                             'may_reconnect': True}])
    
        l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
    
        c12, _ = l1.fundchannel(l2, 10**5)
        assert l1.daemon.is_in_log('Peer storage sent!')
        assert l2.daemon.is_in_log('Peer storage sent!')
    
        l1.stop()
        os.unlink(os.path.join(l1.daemon.lightning_dir, TEST_NETWORK, "lightningd.sqlite3"))
    
        l1.start()
        assert l1.daemon.is_in_log('Server started with public key')
    
        # 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['message']
    
        l1.daemon.wait_for_log('peer_in WIRE_YOUR_PEER_STORAGE')
    
        assert l1.rpc.restorefrompeer()['stubs'][0] == _['channel_id']
    
        l1.daemon.wait_for_log('peer_out WIRE_ERROR')
        l2.daemon.wait_for_log('State changed from CHANNELD_NORMAL to AWAITING_UNILATERAL')
    
        bitcoind.generate_block(5, wait_for_mempool=1)
        sync_blockheight(bitcoind, [l1, l2])
    
        l1.daemon.wait_for_log(r'All outputs resolved.*')
        wait_for(lambda: l1.rpc.listfunds()["channels"][0]["state"] == "ONCHAIN")
    
        # Check if funds are recovered.
        assert l1.rpc.listfunds()["channels"][0]["state"] == "ONCHAIN"
>       assert l2.rpc.listfunds()["channels"][0]["state"] == "ONCHAIN"
E       AssertionError: assert 'FUNDING_SPEND_SEEN' == 'ONCHAIN'
E         - ONCHAIN
E         + FUNDING_SPEND_SEEN

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

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2024-12-20 15:36:07 +10:30
Rusty Russell
1a5916cb81 pytest: try to fix flake in test_lightningd_still_loading
I can't reproduce this, but CI did (with Elements):

```
[gw3] linux -- Python 3.8.18 /home/runner/.cache/pypoetry/virtualenvs/cln-meta-project-AqJ9wMix-py3.8/bin/python

node_factory = <pyln.testing.utils.NodeFactory object at 0x7fd0e20f57f0>
bitcoind = <pyln.testing.utils.ElementsD object at 0x7fd0e307dbe0>
executor = <concurrent.futures.thread.ThreadPoolExecutor object at 0x7fd0e307da30>

    @pytest.mark.openchannel('v1')
    @pytest.mark.openchannel('v2')
    def test_lightningd_still_loading(node_factory, bitcoind, executor):
        """Test that we recognize we haven't got all blocks from bitcoind"""
    
        mock_release = Event()
    
        # This is slow enough that we're going to notice.
        def mock_getblock(r):
            conf_file = os.path.join(bitcoind.bitcoin_dir, 'bitcoin.conf')
            brpc = RawProxy(btc_conf_file=conf_file)
            if r['params'][0] == slow_blockid:
                mock_release.wait(TIMEOUT)
            return {
                "result": brpc._call(r['method'], *r['params']),
                "error": None,
                "id": r['id']
            }
    
        # Start it, establish channel, get extra funds.
        l1, l2, l3 = node_factory.get_nodes(3, opts=[{'may_reconnect': True,
                                                      'wait_for_bitcoind_sync': False},
                                                     {'may_reconnect': True,
                                                      'wait_for_bitcoind_sync': False},
                                                     {}])
        node_factory.join_nodes([l1, l2])
    
        # Balance l1<->l2 channel
        l1.pay(l2, 10**9 // 2)
    
        l1.stop()
    
        # Now make sure l2 is behind.
        bitcoind.generate_block(2)
        # Make sure l2/l3 are synced
        sync_blockheight(bitcoind, [l2, l3])
    
        # Make it slow grabbing the final block.
        slow_blockid = bitcoind.rpc.getblockhash(bitcoind.rpc.getblockcount())
        l1.daemon.rpcproxy.mock_rpc('getblock', mock_getblock)
    
        l1.start(wait_for_bitcoind_sync=False)
    
        # It will warn about being out-of-sync.
        assert 'warning_bitcoind_sync' not in l1.rpc.getinfo()
        assert 'warning_lightningd_sync' in l1.rpc.getinfo()
    
        # Make sure it's connected to l2 (otherwise we get TEMPORARY_CHANNEL_FAILURE)
        wait_for(lambda: only_one(l1.rpc.listpeers(l2.info['id'])['peers'])['connected'])
    
        # Payments will succced.
        l1.pay(l2, 1000)
>       assert l1.daemon.is_in_log(r"Sending HTLC while still syncing with bitcoin network \(104 vs 105\)")
E       AssertionError: assert None
E        +  where None = <bound method TailableProc.is_in_log of <pyln.testing.utils.LightningD object at 0x7fd0e20f9fa0>>('Sending HTLC while still syncing with bitcoin network \\(104 vs 105\\)')
E        +    where <bound method TailableProc.is_in_log of <pyln.testing.utils.LightningD object at 0x7fd0e20f9fa0>> = <pyln.testing.utils.LightningD object at 0x7fd0e20f9fa0>.is_in_log
E        +      where <pyln.testing.utils.LightningD object at 0x7fd0e20f9fa0> = <fixtures.LightningNode object at 0x7fd0e20f59d0>.daemon
```

What was in logs was:

```
lightningd-1 2024-11-18T05:33:50.634Z DEBUG   022d223620a359a47ff7f7ac447c85c46c923da53389221a0054c11c1e3ca31d59-chan#1: Sending HTLC while still syncing with bitcoin network (103 vs 105)
```

Implying that l1 was an extra block behind.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2024-11-19 17:51:18 +10:30
Rusty Russell
229fc3f2b4 xpay: make the xpay layer persistent.
As the first user of a persistent layer, this tripped tests which
assumed the datastore would be empty!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2024-11-18 11:03:26 +10:30