Commit Graph

958 Commits

Author SHA1 Message Date
niftynei 0bd0de54fa psbt: have withdraw_tx use psbt's to create signed txs
this will allow us to add inputs that aren't ours to a tx that we sign
and finalize
2020-06-23 14:49:32 +02:00
niftynei 85dca84327 psbt-json: remove reliance on bitcoin_tx, use straight wally_psbt struct 2020-06-23 14:49:32 +02:00
niftynei c3ae44e296 psbt: don't crash if we can't add a partial sig
instead return a boolean indicating the success/failure of a sig set
2020-06-23 14:49:32 +02:00
lisa neigut 16656a85cf withdraw: refactor change output handling
We're not using the change_outnum for withdraw tx's (and the way
we were calculating it was broken as of the addition of 'multiple
outputs'). This removes the change output knowhow from withdraw_tx
entirely, and pushes the responsibility up to the caller to
include the change output in the output set if desired.

Consequently, we also remove the change output knowhow from hsmd.
2020-06-23 14:49:32 +02:00
niftynei 2900da6112 migrations: ignore channels that don't have a peer_id
We erase peer data after the last channel close transaction for that
peer is 100 blocks deep. We were failing to finish the migration because
the peer_id lookup on these was failing.

Now we ignore any channel with a null peer_id.

Fixes #3768
2020-06-17 14:30:41 +02:00
niftynei 431463b57a listfunds: also list reserved outputs
Currently 'listfunds' lies, a teensy eeinsy bit, in that it doesn't list
all of the funds in a wallet (it omits reserved wallet UTXOs). This
change makes the reserved outputs visible by listing them in the
'outputs' section along with a new field, 'reserved', which denotes the
UTXO's state

Changelog-Changed: JSON-RPC: `listfunds` 'outputs' now includes reserved outputs, designated as 'reserved' = true
2020-06-16 15:58:58 +02:00
niftynei bb589e0eaf psbt: database migration for converting last_tx to a psbt
We update the `last_tx` in `channels` to be psbt format, instead
of a linearized transaction.

We need the amount of the input populated, which we have since
this is the 'funding' amount. Ideally we'd also populate the funding
scriptPubkey, but to do that we'd need to access the HSM module to fetch
our local funding pubkey, which isn't initialized at the time that the
database migrations are run.

Since the only field the HSM uses currently when signing these is the
amount field, it's ok to just leave it out.

needs a test!
2020-06-11 13:13:13 +02:00
niftynei 8fa04a710a psbt: move `channels.last_tx` field to be a psbt
note: missing migration at the moment lol
2020-06-11 13:13:13 +02:00
niftynei 894a46e8e3 psbt: populate last commitment transaction's input info at db
when re-populating a channel's data from the database, since we don't
store the psbt data (with input scripts + amounts), we need to
re-populate it.

the right solution is to patch the psbt into the database; for now we
'monkey-patch' it in.
2020-06-11 13:13:13 +02:00
niftynei a04f0fe250 psbt: remove input_amounts from bitcoin tx
Instead we will stash them into the PSBT as a utxo/witness record (which
includes the amount)
2020-06-11 13:13:13 +02:00
niftynei 78d95b51aa nit: align spacing for SQL stmts 2020-05-29 16:20:23 -05:00
fiatjaf 96452eafb7 sort listinvoices and listsendpays by order of creation. 2020-05-29 15:30:59 +02:00
Antoine Poinsot 5dfd2436db wallet: show input txid in little endian for json_listtransactions
Changelog-Fixed: jsonrpc: `listtransactions` now displays all txids as little endian

Signed-off-by: Antoine Poinsot <darosior@protonmail.com>
2020-05-22 15:11:51 +02:00
lisa neigut 1fb9a078b6 txprepare: return psbt serialized version of tx as well
Changelog-Added: JSON-API: `txprepare` returns a psbt version of the created transaction
2020-05-21 18:45:07 +09:30
Antoine Poinsot f598caa60d config: don't ignore the --commit-fee option.
We did not take the value of --commit-fee into account : this removes
the unused option from lightningd and instead registers it in bcli,
where we set the actual feerate of commitment transactions. This also
corrects the documentation.

Changelog-Fixed: config: we now take the --commit-fee parameter into account.
Signed-off-by: Antoine Poinsot <darosior@protonmail.com>
2020-05-20 06:09:24 +09:30
niftynei fbe50e087a setup: create a common setup which will handle the wally-context
Since we now over-write the wally malloc/free functions, we need to do
so for tests as well. Here we pull up all of the common setup/teardown
logic into a separate place, and update the tests that use libwally to
use the new common_setup core

Changelog-None
2020-05-19 13:35:42 +09:30
Rusty Russell cfb320c972 wire: move remaining bitcoin functions out to bitcoin/ files.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-05-18 14:51:12 +02:00
Rusty Russell fda5f0b427 common/channel_id: move channel_id into its own file.
The definition was in wire/wire.h, and helper functions in fromwire.c!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-05-18 14:51:12 +02:00
lisa neigut 8acbbca05d coins: use the chain's BIP173 name instead of a 'unit of account'
Updates the unit of account to be the chain_id, which is the BIP173 name
of the chain that the coins moved on.

Suggested-By: @rustyrussell
2020-05-12 15:46:58 +09:30
lisa neigut de065580f6 coins: update API surface for creating coin movements
Canonicalize the signature for the 'tag-type' of coin moves by unique
constructor/method calls.

Suggested-By: @rustyrussell
2020-05-12 15:46:58 +09:30
lisa neigut aab9893661 coins: have `we_fulfilled` be fully 'ternary'
note that 'null' 'we_fulfilled's are going to be legacy from this
release forward.
2020-05-12 15:46:58 +09:30
lisa neigut 8537e77ac7 coins: re-write API interface for htlc notices
Wrap up more logic internally to the method call for htlcs. Also, don't
touch part id if we're not the 'origin'

Suggested-By: @rustyrussell
2020-05-12 15:46:58 +09:30
lisa neigut ffd9467f14 coin moves: persist the coin movement index counter to disk
Should make it easier to track when coin moves in the plugin are
disjoint from what c-lightning says it's broadcast already.
2020-05-12 15:46:58 +09:30
lisa neigut de86e29e16 coin moves: log all withdrawals when confirmed in a block
This moves the notification for our coin spends from when it's
successfully submited to the mempool to when they're confirmed in a
block.

We also add an 'informational' notice tagged as `spend_track` which
can be used to track which transaction a wallet output was spent in.
2020-05-12 15:46:58 +09:30
lisa neigut e9d26a46e0 coin moves: actually record the blockheight for all chain moves
Previously we were annotating every movement with the blockheight of
lightningd at notification time. Which is lossy in terms of info, and
won't be helpful for reorg reconciliation. Here we switch over to
logging chain moves iff they've been confirmed.

Next PR will fix this up for withdrawals, which are currently tagged
with a blockheight of zero, since we log on successful send.
2020-05-12 15:46:58 +09:30
lisa neigut 9caf20f636 coin moves: don't log coin moves in onchaind if we're replaying
On node start we replay onchaind's transactions from the database/from
our loaded htlc table.  To keep things tidy, we shouldn't notify the
ledger about these, so we wrap pretty much everything in a flag that
tells us whether or not this is a replay.

There's a very small corner case where dust transactions will get missed
if the node crashes after the htlc has been added to the database but
before we've successfully notified onchaind about it.

Notably, most of the obtrusive updates to onchaind wrappings are due to
the fact that we record dust (ignored outputs) before we receive
confirmation of its confirmation.
2020-05-12 15:46:58 +09:30
lisa neigut 5d58f125c5 coin moves: record withdrawals
For every withdrawal transaction emitted, we record each of the outputs
plus the fees paid for this transaction.
2020-05-12 15:46:58 +09:30
lisa neigut fc54bfc488 coin moves: record wallet deposits 2020-05-12 15:46:58 +09:30
lisa neigut ce8bdfcc45 coin_mvt: wire up notifications for in-channel htlcs
HTLCs trigger a coin movement only when their final form (state) is
reached. This prevents us from needing to concern ourselves with
retries, as well as being the absolutely most correct in terms of
answering the question 'when has the money irrevocably changed hands'.

All coin movements should pass this bar, for ultimate accounting
correctness
2020-05-12 15:46:58 +09:30
lisa neigut 434cad0c3b wallet-htlc: add 'we-filled' flag to saved htlc state
The current plan for coin movements involves tagging
origination/destination htlc's with a separate tag from 'routed' htlcs
(which pass through our node). In order to do this, we need a persistent flag on
incoming htlcs as to whether or not we are the final destination.
2020-05-12 15:46:58 +09:30
Christian Decker d1f8509060 watchtower: Call the commitment_revoked hook every time we update
Changelog-Added: plugin: Added a new `commitment_revocation` hook that provides the plugin with penalty transactions for all revoked transactions.
2020-05-07 15:05:39 +09:30
Christian Decker 38bad4cb39 channeld: Pass back the penalty_base when reporting a revocation 2020-05-07 15:05:39 +09:30
Christian Decker f9dab1e50a channeld: Pass penalty_base back to lightningd on each commit 2020-05-07 15:05:39 +09:30
Christian Decker 667a763659 db: Add a table to track the penalty_bases for revocations 2020-05-07 15:05:39 +09:30
Sebastian Falbesoner 3a881d9b41 db: unregister sqlite3 trace callback also in error case
For sqlite3 versions < 3.14 (i.e. HAVE_SQLITE3_EXPANDED_SQL is not set),
tracing is used to dump statements. The function db_sqlite3_exec()
registers a tracing callback in the beginning and unregisters it at the
end to "avoid it accessing the potentially stale pointer to stmt".
However, the unregistering so far only happened in the success case,
i.e. if the prepare or step calls failed, the callback was still set!

Running the test wallet/test/db-run with sqlite 3.11 leads to a
segmentation fault in the last call to db_commit_transaction():
the tested transaction contains an invalid statement and the (still
registered) trace callback is triggered then by sqlite3_exec() in
db_sqlite3_commit_tx(), leading to a segfault in db_changes_add()
(according to gdb), where it tries to access "stmt->query->readonly".

Changelog-None
2020-05-07 10:41:16 +09:30
lisa neigut 39d5117210 utxo: add scriptSig + scriptPubkey field
Allow the utxo object to bear the scriptSig and scriptPubKey
2020-05-07 08:43:00 +09:30
lisa neigut d8c9e70c0c wallet-df: save our_funds amount to channel record
We'll need it to represent to user in `listpeers`
2020-05-07 08:43:00 +09:30
Sebastian Falbesoner 8d4abc1104 db: fix error message in db_sqlite3_commit_tx()
This probably happened through copy-and-paste from
db_sqlite3_begin_tx().

Changelog-None
2020-05-06 08:42:51 +09:30
Rusty Russell f8cdb523dd plugin_hook_call: return indication whether we called the callback or not.
This will allow us to simplify the caller's command handling.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-05-05 13:45:17 +09:30
Rusty Russell 4eb1233ccb lightningd: don't report spurious temporary_node_failure on local failures.
I noticed the following in logs for tests/test_connection.py::test_feerate_stress:

```
DEBUG 022d223620a359a47ff7f7ac447c85c46c923da53389221a0054c11c1e3ca31d59-chan#1: Failing HTLC 18446744073709551615 due to peer death
DEBUG 022d223620a359a47ff7f7ac447c85c46c923da53389221a0054c11c1e3ca31d59-chan#1: local_routing_failure: 8194 (WIRE_TEMPORARY_NODE_FAILURE)
```

This is because it reports the (transient) node_failure error, because
our channel_failure message is incomplete.  Fix this wart up.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-05-04 18:56:33 +09:30
Sebastian Falbesoner 1dd606c9a1 wallet: fix typo in wallet_can_spend() comment 2020-05-04 10:22:59 +09:30
lisa neigut 0e20e3c5e7 df: rename 'funder' to 'opener'
Previously we've used the term 'funder' to refer to the peer
paying the fees for a transaction; v2 of openchannel will make
this no longer true. Instead we rename this to 'opener', or the
peer sending the 'open_channel' message, since this will be universally
true in a dual-funding world.
2020-05-04 10:22:26 +09:30
Christian Decker fb8661714e wallet: Add a gap limit when checking for incoming transactions
Changelog-Added: wallet: The wallet now has a gap limit that is used to check for incoming transactions when scanning the blockchain.
2020-04-20 07:48:32 +09:30
Rusty Russell deac09950a plugins: make chained hooks have two different callbacks.
One is called on every plugin return, and tells us whether to continue;
the other is only called if every plugin says ok.

This works for things like payload replacement, where we need to process
the results from each plugin, not just the final one!

We should probably turn everything into a chained callback next
release.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-04-16 09:40:39 +09:30
Rusty Russell 9aedb0c61f plugin: simplify hooks calling methods, and make lifetime requirements explicit.
They callback must take ownership of the payload (almost all do, but
now it's explicit).

And since the payload and cb_arg arguments to plugin_hook_call_() are
always identical, make them a single parameter.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-04-16 09:40:39 +09:30
Rusty Russell b29d1ed3ff channeld: support HTLCs with blinding (EXPERIMENTAL_FEATURES)
Note that it's channeld which calculates the shared secret, too.  This
minimizes the work that lightningd has to do, at cost of passing this
through.

We also don't yet save the blinding field(s) to the database.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-04-14 12:51:18 +09:30
Rusty Russell 539a73e1ec common/onion: EXPERIMENTAL handling of enctlv field to override next_short_channel_id.
This requires us to call ecdh() in the corner case where the blinding seed
is in the TLV itself (which is the case for the start of a blinded route).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-04-14 12:51:18 +09:30
Vasil Dimov 158d2212c2 closingd: configurable closing fee negotiation step
When negotiating the transaction fee for closing a channel [1], we used
to always pick the middle of the range between our proposal and the
peer's proposal.

Introduce a new option `fee_negotiation_step` to the close command, so
the peer who initiates the close can choose his back off step.

Partially resolves https://github.com/ElementsProject/lightning/issues/3270

[1] https://github.com/lightningnetwork/lightning-rfc/blob/master/02-peer-protocol.md#closing-negotiation-closing_signed

Changelog-Added: New optional parameter to the `close` command to control the closing transaction fee negotiation back off step
2020-04-07 13:52:48 +09:30
Vasil Dimov 3ce0552dd4 build: use locale-independent sort for mocks
Use `LC_ALL=C sort` instead of `sort` so that mocks get sorted in
the same way on all developers' environments.

Re-record the result of `make update-mocks`.

Changelog-None
2020-04-07 13:52:48 +09:30
Rusty Russell 41ebaffba3 lightningd: return `features` in connect response.
This is useful in general, but in particular it allows fundchannel to avoid YA
query to figure out if it can wumbo.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-Added: JSON: `connect` returns `features` of the connected peer on success.
2020-04-03 13:13:21 +10:30
darosior dce2e87928 chaintopology: better feerate targets differentiation
We kept track of an URGENT, a NORMAL, and a SLOW feerate. They were used
for opening (NORMAL), mutual (NORMAL), UNILATERAL (URGENT) transactions
as well as minimum and maximum estimations, and onchain resolution.

We now keep track of more fine-grained feerates:
- `opening` used for funding and also misc transactions
- `mutual_close` used for the mutual close transaction
- `unilateral_close` used for unilateral close (commitment transactions)
- `delayed_to_us` used for resolving our output from our unilateral close
- `htlc_resolution` used for resolving onchain HTLCs
- `penalty` used for resolving revoked transactions

We don't modify our requests to our Bitcoin backend, as the next commit
will batch them !

Changelog-deprecated: The "urgent", "slow", and "normal" field of the `feerates` command are now deprecated.
Changelog-added: The fields "opening", "mutual_close", "unilateral_close", "delayed_to_us", "htlc_resolution" and "penalty" have been added to the `feerates` command.
2020-03-30 20:17:18 +10:30
Christian Decker 453bfbc816 json-rpc: Fix test_txprepare if running with postgres
Postgres does not guarantee that the insertion order is the returned order,
which leads us to skip outputs that have already been stolen onto the selected
utxos set, but not added to it because it isn't confirmed. This may also
happen with sqlite3 though it's a lot rarer in that case.
2020-03-24 09:52:33 +10:30
Rusty Russell 24984ec680 common/sphinx: add realm flag so we can avoid legacy parsing.
For messages, we use the onion but payload lengths 0 and 1 aren't special.
Create a flag to disable that logic.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-03-17 18:47:52 +01:00
Christian Decker 959687bf6d onion: Pass the position and type of the failing TLV type out
We'll need this when returning an error to the sender.
2020-03-04 22:57:24 +01:00
Michael Schmoock 6c50185865 fix: cppcheck ignore two false positives on uninitvar 2020-03-04 14:04:51 +10:30
Rusty Russell f8a21f16c9 lightingd: do a local short_channel_id lookup for forwarding.
Even without optimization, it's faster to walk all the channels than
ping another daemon and wait for the response.

Changelog-Changed: Forwarding messages is now much faster (less inter-daemon traffic)
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-02-28 09:44:47 +10:30
Rusty Russell 247d249ea8 gossipd: provide helper to get a channels cupdate, create routine to use it.
The idea is that gossipd can give us the cupdate we need for an error, and
we wire things up so that we ask for it (async) just before we send the
error to the subdaemon.

I tried many other things, but they were all too high-risk.

1. We need to ask gossipd every time, since it produces these lazily
   (in particular, it doesn't actually generate an offline update unless
   the channel is used).
2. We can't do async calls in random places, since we'll end up with
   an HTLC in limbo.  What if another path tries to fail it at the same time?
3. This allows us to use a temporary_node_failure error, and upgrade it
   when gossipd replies.  This doesn't change any existing assumptions.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-02-28 09:44:47 +10:30
Rusty Russell 2aad3ffcf8 common: tal_dup_talarr() helper.
This is a common thing to do, so create a macro.

Unfortunately, it still needs the type arg, because the paramter may
be const, and the return cannot be, and C doesn't have a general
"(-const)" cast.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-02-27 14:16:16 +10:30
Rusty Russell c9e73dc4e0 lightningd: rename htlc_in field from failcode to badonion.
That's all it's used for now.

And remove unreferenced failoutchannel.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-02-25 11:12:12 +10:30
Rusty Russell 447730e70f wallet: only store BADONION codes in db for incoming htlcs: rest are all onionreplyies.
This completes the conversion; any in-flight HTLC failures get turned into temporary_node_failures.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-02-25 11:12:12 +10:30
Rusty Russell 72d55d3e3b lightningd: store raw msg rather than code for locally-failed outgoing HTLCs
At the moment, we store e.g. WIRE_TEMPORARY_CHANNEL_FAILURE, and then
lightningd has a large demux function which turns that into the correct
error message.

Such an enum demuxer is an anti-pattern.

Instead, store the message directly for output HTLCs; channeld now
sends us an error message rather than an error code.

For input HTLCs we will still need the failure code if the onion was
bad (since we need to prompt channeld to send a completely different
message than normal), though we can (and will!) eliminate its use in
non-BADONION failure cases.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-02-25 11:12:12 +10:30
Rusty Russell a150b09665 wallet: Add new htlc column "localfailmsg" for outgoing htlcs.
We're going to change our internal structure next, so this is preparation.
We populate existing errors with temporary node failures, for simplicity.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-02-25 11:12:12 +10:30
Rusty Russell ed839bfda0 channeld: get the onionreply back from lightningd for failed htlcs.
Instead of making it ourselves, lightningd does it.  Now we only have
two cases of failed htlcs: completely malformed (BADONION), and with
an already-wrapped onion reply to send.

This makes channeld's job much simpler.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-02-25 11:12:12 +10:30
Rusty Russell 7ab5c424b6 gossipd: provide (stripped) channel_update when resolving a channel.
I hadn't realized that lightningd asks gossipd every time we forward
a payment.  But I'm going to abuse it here to get the latest channel_update,
otherwise (as lightningd takes over error message generation) lightningd
needs to do an async request at various painful points.

So have gossipd tell us the lastest update (stripped so compatible with
the strange in-onion-error format).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-02-25 11:12:12 +10:30
Rusty Russell c7bbdd76d3 lightningd: handle fail_htlc_in with no known outgoing channel.
Turn it into temporary node failure: this only happens if we restart
with a failed htlc in, but it's clearer and more robust to handle it
generically.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-02-25 11:12:12 +10:30
Rusty Russell b84b4b4695 lightningd: rename htlc_in and htlc_out failuremsg fields to failonion.
This is clearer, especially when we also deal with raw not-yet-onion-wrapped
failure messages.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-02-25 11:12:12 +10:30
Rusty Russell d478dc0e59 wallet: fix null column access for pre-0.7.3 dbs.
Added in d901304120, this column is null in old dbs like mine:

2020-02-15T00:08:41.444Z **BROKEN** database: Accessing a null column 12 in query SELECT  id, channel_htlc_id, msatoshi, cltv_expiry, hstate, payment_hash, payment_key, routing_onion, failuremsg, malformed_onion, origin_htlc, shared_secret, received_time FROM channel_htlcs WHERE direction= ? AND channel_id= ? AND hstate != ?

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-02-18 10:22:58 +10:30
Rusty Russell fc4d01cd9d db: put scids in forwards even if we didn't actually send.
If the peer is not connected, or other error which means we don't
actually create an outgoing HTLC, we don't record the
short_channel_id.  This is unhelpful!

Pass the scid down to the wallet code, and explicitly hand the
scid and amount down to the notification code rather than handing it
the htlc_out (which it doesn't need).

Changelog-Changed: JSON API: `listforwards` now shows `out_channel` even if we couldn't forward.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-02-12 22:27:57 -06:00
darosior c79ab0f1b0 lightningd/bitcoind: use the Bitcoin plugin for getutxout 2020-02-12 11:45:07 +10:30
darosior 947f5ddde1 lightningd/bitcoind: use the Bitcoin plugin to send transactions
This restrains the informations we get about how the sending went to
an errmsg as we cant rely on bitcoin-cli specific output nor its exit code.
2020-02-12 11:45:07 +10:30
Vasil Dimov 18a40c0c5d build: re-record the result of `make update-mocks`
Changelog-None
2020-02-03 15:38:11 +00:00
darosior a589daa235 wallet: fuzz the nLockTime added to withdraw transactions 2020-02-03 00:45:27 +00:00
darosior 273029f244 wallet: set nLockTime to the tip for withdrawal transactions
This sets the nLockTime to the tip (and accordingly each input's nSequence to
0xfffffffe) for withdrawal transactions.

Even if the anti fee-sniping argument might not be valid until some time yet,
this makes our regular wallet transactions far less distinguishable from
bitcoind's ones since it now defaults to using native Segwit transactions
(like us). Moreover other wallets are likely to implement this (if they
haven't already).

Changelog-Added: wallet: withdrawal transactions now sets nlocktime to the current tip.
2020-02-03 00:45:27 +00:00
Vasil Dimov 55173a56b7 Use dedicated type for error codes
Before this patch we used `int` for error codes. The problem with
`int` is that we try to pass it to/from wire and the size of `int` is
not defined by the standard. So a sender with 4-byte `int` would write
4 bytes to the wire and a receiver with 2-byte `int` (for example) would
read just 2 bytes from the wire.

To resolve this:

* Introduce an error code type with a known size:
  `typedef s32 errcode_t`.

* Change all error code macros to constants of type `errcode_t`.
  Constants also play better with gdb - it would visualize the name of
  the constant instead of the numeric value.

* Change all functions that take error codes to take the new type
  `errcode_t` instead of `int`.

* Introduce towire / fromwire functions to send / receive the newly added
  type `errcode_t` and use it instead of `towire_int()`.

In addition:

* Remove the now unneeded `towire_int()`.

* Replace a hardcoded error code `-2` with a new constant
  `INVOICE_EXPIRED_DURING_WAIT` (903).

Changelog-Changed: The waitinvoice command would now return error code 903 to designate that the invoice expired during wait, instead of the previous -2
2020-01-31 06:02:47 +00:00
Christian Decker ccec64d63c peer: Add custommsg hook and wire it into channeld and openingd 2020-01-28 23:50:52 +01:00
Christian Decker 3c88d5c8c4 openingd: Implement sendcustommsg handling in openingd
Most of the work is done in `lightningd`, here we just need to queue the
message itself.
2020-01-28 23:50:52 +01:00
Christian Decker 3ad8438d91 json-rpc: Add sendcustommsg command
This command injects a custom message into the encrypted transport stream to
the peer, allowing users to build custom protocols on top of c-lightning
without requiring any changes to c-lightning itself.
2020-01-28 23:50:52 +01:00
Rusty Russell 262e4c840f sphinx: use struct secret for shared secret.
Generally I prefer structures over u8, since the size is enforced at
runtime; and in several places we were doing conversions as the code
using Sphinx does treat struct secret as type of the secret.

Note that passing an array is the same as passing the address, so
changing from 'u8 secret[32]' to 'struct secret secret' means various
'secret' parameters change to '&secret'.  Technically, '&secret' also
would have worked before, since '&' is a noop on array, but that's
always seemed a bit weird.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-01-24 10:01:44 +10:30
Rusty Russell 1099f6a5e1 common: use struct onionreply.
This makes it clear we're dealing with a message which is a wrapped error
reply (needing unwrap_onionreply), not an already-wrapped one.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-01-23 16:17:42 +10:30
Rusty Russell aa6aad0131 common: add struct onionreply
I really want a type which means "I am a wrapped onion reply" as separate
from "I am a normal wire msg".  Currently both user u8 *, and I got very
confused trying to figure out where each one was an unwrapped error msg,
or where it still needed (un)wrapping.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-01-23 16:17:42 +10:30
Rusty Russell ddce5573c7 channeld: use wirestring for failure strings.
I think this code predated wirestring.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-01-23 16:17:42 +10:30
Christian Decker 4be1868b8a pay: Invert ownership of wallet_payment
`wallet_payment_store` would free the `wallet_payment` instance which would
then cause us to reload it from the DB. Instead of doing the store->free->load
dance we now tell `wallet_payment_store` whether it should take ownership and
leave it alone if not.

Passing the payment around instead of referencing it through payment_hash and
partid is a nice side-effect.
2020-01-13 23:34:46 +01:00
Vasil Dimov 2ea91f834c Add the missing space between "if" and "("
Changelog-None
2020-01-06 12:57:59 +01:00
Christian Decker 3f3a48dae9 db: Turn the transaction counter into an optimistic lock
The optimistic lock prevents multiple instances of c-lightning making
concurrent modifications to the database. That would be unsafe as it messes up
the state in the DB. The optimistic lock is implemented by checking whether a
gated update on the previous value of the `data_version` actually results in
an update. If that's not the case the DB has been changed under our feet.

The lock provides linearizability of DB modifications: if a database is
changed under the feet of a running process that process will `abort()`, which
from a global point of view is as if it had crashed right after the last
successful commit. Any process that also changed the DB must've started
between the last successful commit and the unsuccessful one since otherwise
its counters would not have matched (which would also have aborted that
transaction). So this reduces all the possible timelines to an equivalent
where the first process died, and the second process recovered from the DB.

This is not that interesting for `sqlite3` where we are also protected via the
PID file, but when running on multiple hosts against the same DB, e.g., with
`postgres`, this protection becomes important.

Changelog-Added: DB: Optimistic logging prevents instances from running concurrently against the same database, providing linear consistency to changes.
2020-01-02 14:12:59 -06:00
Christian Decker 2c11c54dd2 db: Track the data_version in the database
This increments the `data_version` upon committing dirty transactions, reads
the last data_version upon startup, and tracks the number in memory in
parallel to the DB (see next commit for rationale).

Changelog-Changed: JSON-RPC: Added a `data_version` field to the `db_write` hook which returns a numeric transaction counter.
2020-01-02 14:12:59 -06:00
Christian Decker 4a4184be70 db: Add numeric data_version counter to count modifying transactions
This counter is incremented on each dirty transaction.
2020-01-02 14:12:59 -06:00
Christian Decker 09247d4f95 db: Add tracking of whether the current transaction is dirty 2020-01-02 14:12:59 -06:00
Christian Decker 097af493dd db: Move db_migrate transaction up one level
We are about to do some more operations before committing, so moving this up
allows us to reuse the same transaction.
2020-01-02 14:12:59 -06:00
Christian Decker 6020a0d587 db: Consolidate access to the changes in a db
We were passing them in separately, while we could just retrieve them from the
db instance instead.
2020-01-02 14:12:59 -06:00
lisa neigut 700b766ce1 wallet: remove edgecase around transaction checks
we don't populate the tx item when we're running a transaction check
from deep chain (prior to a chain replay)
2020-01-02 16:56:42 +01:00
Rusty Russell 72aa315b5e lightningd: save the fee_states into the database.
This is the final step: we pass the complete fee_states to and from
channeld.

Changelog-Fixed: "Bad commitment signature" closing channels when we sent back-to-back update_fee messages across multiple reconnects.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-12-12 22:15:48 +01:00
Rusty Russell 4270031d75 wallet: add per-channel feerate_state to the database.
The upgrade here is a bit tricky: we map the two values into the
feerate_state.  This is trivial if they're both the same, but if
they're different we don't know exactly what state they're in (this
being the source of the bug!).

So, we assume that the have received the update and not acked it,
as that would be the normal case.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-12-12 22:15:48 +01:00
Rusty Russell 8e3234e67a lightningd: sew in htlc set.
The invoice_try_pay code now takes a set, rather than a single htlc, but
it's basically the same thing.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-12-12 15:03:53 +01:00
Rusty Russell 12985331f7 htlcs: remove origin_htlc_id from htlc_out.
This is a transient field, so rework things so we don't leave it in
struct htlc_out.  Instead, load htlc_in first and connect htlc_out to
them as we go.

This also changes one place where we use it instead of the am_origin
flag.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-12-12 15:03:53 +01:00
Rusty Russell 345ca9b122 db: add partid field to htlc_out.
This is in preparation for partial payments.  For existing payments,
partid is 0 (to match the corresponding payment).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-12-12 15:03:53 +01:00
Rusty Russell 2d18c3a209 db: add partid, total_msat fields to payment entries.
This is in preparation for partial payments.  For existing payments,
partid is 0 (arbitrarity) and total_msat is msatoshi.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-12-12 15:03:53 +01:00
Christian Decker 9660549b0c changelog: Update changelog for the 0.7.4 release 2019-12-12 00:15:23 +01:00
Christian Decker ff5f7b194f sphinx: Return the error in parse_onionpacket
As suggested by @niftynei here: https://github.com/ElementsProject/lightning/pull/3260#discussion_r347543999

Suggested-by: Lisa Neigut <@niftynei>
Suggested-by: Rusty Russell <@rustyrussell>
Signed-off-by: Christian Decker <@cdecker>
2019-12-11 16:18:34 +01:00
Rusty Russell f7ebbb2ec5 common: make sphinx code ignorant of payload format.
Now "raw_payload" is always the complete string (including realm or length
bytes at the front).

This has several effects:
1. We can receive an decrypt an onion which is grossly malformed.
2. We can still hand this to the htlc_accepted hook.
3. We then fail it unless the htlc_accepted accepts it manually.
4. The createonion API now takes the raw payload, and does not know
   anything about "style".

The only caveat is that the sphinx code needs to know the payload
length: we have a call for that, which simply tells it to copy the
entire onion (and treat us as the final node) if it's invalid.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-12-09 14:33:31 +01:00
Christian Decker 69c17d2d31 wire: Let the TLV _is_valid function actually return validity
I got this one wrong myself, since the function name implied a boolean
result. So I changed it to take the optional err_index as argument.
2019-12-03 00:37:15 +00:00
Christian Decker 16b6c31010 json-rpc: Add the error onion if we stored it in the DB
If we can't decode the onion, because the onion got corrupted or we used
`sendonion` without specifying the `shared_secrets` used, the best we can do
is tell the caller instead.
2019-12-01 15:40:47 +01:00
Christian Decker 1cf3c12a81 cleanup: The failchannel is not tal-allocated when first assigned
This makes the copy on write redundant.
2019-12-01 15:40:47 +01:00
Christian Decker 27547ce8d4 pay: Allow `sendonion` callers to provide `shared_secrets`
This means that c-lightning can now internally decrypt an eventual error
message, and not force the caller to implement the decryption. The main
difficulty was that we now have a new state (channels and nodes not specified,
while shared_secrets are specified) which needed to be handled.
2019-12-01 15:40:47 +01:00
Christian Decker b8ce175fd2 pay: Handle payment failures resulting from sendonion correctly
We are breaking with a couple of assumptions, namely that we have the
`path_secrets` to decode the error onion. If this happens we just want it to
error out.
2019-12-01 15:40:47 +01:00
Christian Decker 41221b6ecb pay: Make wallet_payment->destination optional
If we use `sendonion` we don't actually know the destination, so we
make the destination a pointer which is NULL if we don't know.
2019-12-01 15:40:47 +01:00
Rusty Russell b9a03a08ef wallet/Makefile: fix dependency line.
The .o files need regen, not the .c files!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-11-28 11:50:13 +01:00
Rusty Russell e5247a68b6 lightningd: check payment secret on htlc receipt.
We don't set the secret to compulsory (yet!) but put code in for the
future.  Meanwhile, if there is a secret, check it is correct.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-11-24 23:33:17 +00:00
Rusty Russell 81c89aaef8 wallet: add invoice features into db.
In a future version, we will use features to insist that payers
provide the secret.  In transition, we may have old invoices which
didn't insist on that, so we need to know this on a per-invoice basis.

Not sure if I got the right syntax for adding an empty blob though!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-11-24 23:33:17 +00:00
Christian Decker e46f423ae9 sphinx: Cleanup route_step_decode_* functions
We have consolidated the two functions into a single `route_step_decode`
function, and made it static since we call it in the `process_onionpacket`
function. We remove the two exposed functions since they're no longer useful.
2019-11-22 04:40:25 +00:00
Christian Decker 2519f934aa tlv: Add validity check codegen for the tlv namespaces
Since the parser itself just parses and doesn't include validation anymore we
need to put that functionality somewhere. The validation consists of enforcing
that the types are in monotonically increasing order without duplicates and
that for the even types we know how to handle it.
2019-11-22 04:40:25 +00:00
Rusty Russell edbcb6fa15 lightningd: remove chainparams local parameter from wallet.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-11-20 20:41:53 +01:00
Michael Schmoock 68b9ded24a fix: listtx set txindex only if blockheight is known 2019-11-18 11:01:40 +01:00
Rusty Russell 0607f998d1 options: allow --log-level <level>:<prefix> for finegrained log control.
This allows finegrained logging control of particular subdaemons or
subsystems.

To do this, we defer setting the logging levels for each log object
until after early argument parsing (since e.g. "bitcoind" log object
is created early).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-changed: Options: log-level can now specify different levels for different subsystems.
2019-11-18 04:50:22 +00:00
Rusty Russell ef7a820ab1 log: make formatting more consistent.
1. Printed form is always "[<nodeid>-]<prefix>: <string>"
2. "jcon fd %i" becomes "jsonrpc #%i".
3. "jsonrpc" log is only used once, and is removed.
4. "database" log prefix is use for db accesses.
5. "lightningd(%i)" becomes simply "lightningd" without the pid.
6. The "lightningd_" prefix is stripped from subd log prefixes, and pid removed.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Changelog-changed: Logging: formatting made uniform: [NODEID-]SUBSYSTEM: MESSAGE
Changelog-removed: `lightning_` prefixes removed from subdaemon names, including in listpeers `owner` field.
2019-11-18 04:50:22 +00:00
Rusty Russell 86fb54a33b lightningd: remove per-peer log book.
We had a separate logbook for each peer, and copy log entries above
the printable log level into the master logbook.  This didn't always
work well, since we didn't dump it on crash for example.

Keep a single global logbook instead, and remove this infrastructure.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-11-18 04:50:22 +00:00
Rusty Russell e433d4ddc1 lightningd: have logging include an optional node_id for each entry.
A log can have a default node_id, which can be overridden on a per-entry
basis.  This changes the format of logging, so some tests need rework.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-11-18 04:50:22 +00:00
darosior f075b87137 bitcoind: remove the chainparams member
We now have a global constant, prefer to use it instead of having
two variables with the same utility.
2019-11-15 13:14:08 +01:00
Michael Schmoock fe4a25a780 wallet: fix skipping tx dups memory corruption
Changelog-Fixed: #3231 listtransactions crash
2019-11-15 03:53:56 +00:00
Michael Schmoock ed238758a2 wallet: fix accessing blockheight of unconfirmed transaction 2019-11-15 03:53:56 +00:00
Rusty Russell b7bbccd6fa common/sphinx: handle decoding of TLV payload.
We add routines to decode the expected fields from both legacy and tlv
hop formats.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-11-14 10:15:33 +01:00
lisa neigut 963a1da958 addr: handle P2SH/P2PKH in scriptpubkey encoding
Previously, returned null if a scriptpubkey was not Segwit; now
handles encoding to Base58 for other types.
2019-11-13 03:31:20 +00:00
Christian Decker 396e8224fa db: Add a migration to set received_time on forwards in rare cases
The case where this is needed is when the wallet had a forwarded payment
somewhere between commits 66a47d2 (which started tracking forwardings) and
d901304 (which added the `received_time` column). This just emulates the
behavior of sqlite3 for postgres as well.

Signed-off-by: Christian Decker <@cdecker>
2019-10-21 13:56:10 +02:00
Christian Decker 1ecad0cc53 db: Maybe a bit too pedantic?
Checking on whether we access a null field is ok, but should we crash right
away? Probably not. This reduces the access to a warning on sqlite3 and let's
it continue. We can look for occurences and fix them as they come up and then
re-arm the asserts once we addressed all cases.
2019-10-21 13:56:10 +02:00
Christian Decker 712595f0d2 db: Wire in the logs into the database so we can give feedback 2019-10-21 13:56:10 +02:00
Christian Decker ec8d774b29 db: Make column access way more pedantic
We should never access a nulled field, so add an assert to that effect.
2019-10-18 08:29:46 +02:00
Christian Decker 12f40f2227 db: Add _or_default variants for column accesses
We were implicitly relying on sqlite3 behavior that returns the zero-value for
nulled fields when accessing them. This adds the same behavior explicitly to
the DB abstraction in order to reduce `db_column_is_null` checks in the logic,
but still make it evident what is happening here.

Fixes https://github.com/fiatjaf/mcldsp/issues/1

Signed-off-by: Christian Decker <@cdecker>
2019-10-18 08:29:46 +02:00
Christian Decker 894627a287 db: Fix report and commit order for DB transactions
Reported-by: Simon Vrouwe <@SimonVrouwe>
Signed-off-by: Christian Decker <@cdecker>
2019-10-18 08:29:46 +02:00
Rusty Russell ca53c1b699 gossipd: push our own gossip messages harder.
I had a report of a 0.7.2 user whose node hadn't appeared on 1ml.  Their
node_announcement wasn't visible to my node, either.

I suspect this is a consequence of recent version reducing the amount of
gossip they send, as well as large nodes increasingly turning off gossip
altogether from some peers (as we do).  We should ignore timestamp filters
for our own channels: the easiest way to do this is to push them out
directly from gossipd (other messages are sent via the store).

We change channeld to wrap the local channel_announcements: previously
we just handed it to gossipd as for any other gossip message we received
from our peer.  Now gossipd knows to push it out, as it's local.

This interferes with the logic in tests/test_misc.py::test_htlc_send_timeout
which expects the node_announcement message last, so we generalize
that too.

[ Thanks to @trueptolmy for bugfix! ]
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-10-14 15:00:37 -05:00
Rusty Russell bd55f6d940
common/features: only support a single feature bitset.
This is mainly an internal-only change, especially since we don't
offer any globalfeatures.

However, LND (as of next release) will offer global features, and also
expect option_static_remotekey to be a *global* feature.  So we send
our (merged) feature bitset as both global and local in init, and fold
those bitsets together when we get an init msg.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-10-11 02:52:04 +00:00
lisa neigut 6e7cfcc76e walletrpc: explicitly note we discard utx on unsuccessful broadcast
If we can't broadcast the transaction, you're going to have to start
over regardless.  It's a tal child of cmd, which we free here.
2019-10-10 05:57:45 +00:00
lisa neigut af4ffe5fcd dev-forget-channel: accept passing in channel_id
This patch adds a channel_id parameter to allow for specifying
channels that are lacking a short_channel_id.

Useful in the case where a peer has 1) multiple channels (ONCHAIN etc)
and 2) a channel where the funding transaction hasn't been
broadcast/mined.
2019-10-10 05:57:45 +00:00
trueptolemy 019c052123 JSON-API: Allow `close` channel to specified address
Command format: close id [unilateraltimeout] [destination]

Close the channel with peer {id}, forcing a unilateral
close after {unilateraltimeout} seconds if non-zero, and
the to-local output will be sent to {destination}. If
{destination} isn't specified, the default is the address
of lightningd.

Also change the pylightning:
update the `close` API to support `destination` parameter
2019-10-09 21:04:16 -05:00
trueptolemy 71b606e050 lightningd: Add a new field `shutdown_scriptpubkey[NUM_SIDES]`
`shutdown_scriptpubkey[REMOTE]` is original remote_shutdown_scriptpubkey;
`shutdown_scriptpubkey[LOCAL]` is the script used for "to-local" output when `close`. Add the default is generated form `final_key_idx`;

Store `shutdown_scriptpubkey[LOCAL]` into wallet;
2019-10-09 21:04:16 -05:00
trueptolemy 75e946d256 json: Move `param_bitcoin_address` from wallet/walletrpc.c to lightningd/json.c
It's a useful helper, and it will be used to prase address in `close` command.
2019-10-09 21:04:16 -05:00
trueptolemy 7db3f1b8a6 json: Rename `json_tok_address_scriptpubkey` to `json_to_address_scriptpubkey`
Our json naming style is like `json_to_***`.
2019-10-09 16:51:42 -05:00
trueptolemy 36bc624928 Fix: fix the parameter prase of `txprepare`
The old prase process doesn't work!!
2019-10-09 16:51:42 -05:00
Rusty Russell 93865bb0f3 wallet: minor style fixes, and remove null JSON fields.
Our policy is generally to omit fields which aren't sensible.
Also, @niftynei points out the spacing in for loops.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-10-07 20:03:24 -05:00
Christian Decker 55af02b163 wallet: Fix a column access size mismatch when reading tx types 2019-10-07 20:03:24 -05:00
Christian Decker d840496e53 json-rpc: Make listtransaction non-experimental but hide annotations
We haven't tested the annotation for completeness yet, so let's not have
people start relying on them just yet.
2019-10-07 20:03:24 -05:00
Christian Decker 33bb4f7f58 json-rpc: Print details and annotations for listtransactions 2019-10-07 20:03:24 -05:00
Christian Decker d981b58234 wallet: Retrieve transaction annotations when listing transactions
This triple join should be efficient to read, and to process. We have a
one-to-many (tx-to-annotations), followed by a
one-to-one (annotation-to-channel) join, so we are limited to annotations x
transactions results.
2019-10-07 20:03:24 -05:00
Christian Decker ddae604f3d wallet: Move tx annotation for deposits into the wallet
We have split the iteration over the txs and the output in different
functions, so pushing the annotation down, while keeping the transaction
addition atop. This showcases the need to not have the txid reference the
transactions.id in the DB: we annotate in a function that doesn't have the tx
index context, but only add the TX after we have finished extracting.
2019-10-07 20:03:24 -05:00
Christian Decker 3d14c18074 wallet: Add primitives to annotate a transaction input and output
We'll slowly migrate from the tx annotations to the input and output we are
interested in.
2019-10-07 20:03:24 -05:00
Christian Decker 964156dc2d db: Add transaction_annotations table 2019-10-07 20:03:24 -05:00
Christian Decker 7283efa5b5 elements: Add amount_asset to support more than just plain satoshis
Currently the only source for amount_asset is the value getter on a tx output,
and we don't hand it too far around (mainly ignoring it if it isn't the
chain's main currency). Eventually we could bubble them up to the wallet, use
them to select outputs or actually support assets in the channels.

Since we don't hand them around too widely I thought it was ok for them to be
pass-by-value rather than having to allocate them and pass them around by
reference. They're just 41 bytes currently so the overhead should be ok.

Signed-off-by: Christian Decker <@cdecker>
2019-10-03 04:32:57 +00:00
Christian Decker d5f0c08a88 elements: Remove global is_elements variable in favor of chainparams
No need to keep duplicate globals.
2019-10-03 04:32:57 +00:00
Christian Decker f197e3da83 elements: Fix transaction size estimate when selecting coins
In elements we add an explicit fee output, if we don't consider it when
selecting coins, we end up underpaying the fees.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-10-03 04:32:57 +00:00
Christian Decker 17af57e504 elements: Compute correct weight in wallet_select for elements TXs
They are a bit larger, so account for that.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-10-03 04:32:57 +00:00
Christian Decker 639713b547 elements: Fix transaction handling for elements transactions
Skipping coinbase transactions and ensuring that the transaction is serialized
correctly when sending it onwards.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-10-03 04:32:57 +00:00
Saibato 0f9ba53581 Add enable-autotor-v2 config variable
With enable-autotor-v2 defined in cmdline the default behavior to create
v3 onions with the tor service call, is set to v2 onions.

Signed-off-by: Saibato <saibato.naga@pm.me>
2019-09-28 00:31:02 +02:00