Commit Graph

270 Commits

Author SHA1 Message Date
niftynei 864f2f3e21 channel_id: save to database, dont derive from funding_txid
v2 channel open uses a different method to derive the channel_id, so now
we save it to the database so that we dont have to remember how to
derive it for each.

includes a migration for existing channels
2020-09-09 19:54:20 +09:30
Rusty Russell 3a2191fcfe wallet: db_bind_talarr and db_column_talarr helpers.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-09-02 09:46:37 +09:30
Rusty Russell 1702c7a69a hsmd: convert to new wire generation style.
Note that other directories were explicitly depending on the generated
file, instead of relying on their (already existing) dependency on 
$(LIGHTNINGD_HSM_CLIENT_OBJS), so we remove that.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-08-25 12:53:13 +09:30
Rusty Russell 95294e25ea wallet: do valgrind checks when binding db statements.
Otherwise valgrind gets upset when we *run* the statements: better
to get a backtrace when we bind, so we can tell which field it is!

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-08-21 11:25:51 +09:30
Rusty Russell f762f7e247 db: remove assertion on validity of node_ids read from db.
We've never hit this, we do check them on insert, and it's slowing
down some operations unnecessarily.

$ time lightning-cli -R --network=regtest --lightning-dir /tmp/ltests-k8jhvtty/test_pay_stress_1/lightning-1/ listpays > /dev/null

Before:
	real	0m1.781s
	user	0m0.127s
	sys	0m0.013s

After:
	real	0m1.545s
	user	0m0.124s
	sys	0m0.024s

Also, the raw listsendpays drops from 0.983s to 0.676s.

(With -O3 -flto, listsendpays is 0.416s, listpays 0.971s).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-08-21 09:52:33 +09:30
Rusty Russell 754765c139 utxo: keep flag to recognize to-remote option_anchor_outputs closes.
We need to remember this in the db (it's a P2WSH for option_anchor_outputs),
and we need to set nSequence to 1 to spend it.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-08-14 11:51:14 +09:30
Rusty Russell b093856d0c db: add option_anchor_outputs entry to channel table.
This is the same way we handle option_static_remotekey, which
is also sticky (if negotiated at opening time, it always applies).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-08-14 11:51:14 +09:30
Rusty Russell cf25ca11b8 sendpsbt: annotate transactions in wallet.
This is what txsend does, only we have a psbt so we have
to change the db interface to take a wally_tx.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2020-08-13 12:37:02 -05:00
Jon Griffiths 95d3d65c62 wally: update to the latest wally version
Includes:
psbt: Use renamed functions for new wally version
psbt: Set the transaction directly to avoid script workarounds
psbt: Use low-S grinding when computing signatures
tx: Use wally_tx_clone from libwally now that its exported

Signed-off-by: Jon Griffiths <jon_p_griffiths@yahoo.com>
2020-08-07 10:28:01 +09:30
niftynei 90b393ca1a hsmd/db: backfill pubkey information so that psbts signing works
the way we use PSBTs to sign things requires that we have the
scriptpubkey available on the utxo so we can populate the witness-utxo
field with it.

this causes problems if we don't already have the scriptpubkey cached in
the database, as in *some* cases we require a round trip to the HSM to
populate them

to get over this hump, we backfill any and all missing scriptpubkey
information for the utxo's that we hold in our wallet.

this will allow us to clean up the NULL handling of missing
scriptpubkeys.
2020-07-29 13:13:46 +02:00
niftynei 65c2bac2f3 hsmd/wallet: pass the bip32_key down into migrations
we're about to add a migration that requires access to the bip32_key
in order to calculate missing scriptpubkeys.

prior to this patch, we don't have access to the bip32 key in the db
migration, as it's set on the wallet but after the db migrations are
run.

here we patch it through so that every migration can access it
2020-07-29 13:13:46 +02:00
niftynei 7ebdc14397 utxos: add a 'reserved_til' marker for utxos
Allow a utxo to be reserved until explicitly unreserved or until a timer
runs out. Currently unused.

We explicitly do not unreserve these at startup.
2020-07-15 18:49:02 +09:30
niftynei f5f85b389d elements,pset: populate elements specific data for PSBTs
PSETs have a bit different requirements. The witness_utxo needs
the asset tag + values, and these should also be added to the PSET
struct separately as well. To do this, we create a new 'init' method for
elements inputs, which takes care of the elements specific things.
2020-07-13 11:37:24 +09:30
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
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 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
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 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 667a763659 db: Add a table to track the penalty_bases for revocations 2020-05-07 15:05:39 +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
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 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 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
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
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 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
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
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
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
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
Christian Decker 964156dc2d db: Add transaction_annotations table 2019-10-07 20:03:24 -05:00
Rusty Russell 14b55d03d5 db: use correct backend for retrieving text fields.
Otherwise we don't have a nul terminator:

ep 22 02:25:42 lntxbot lightningd[804]: 2019/09/22 02:25:42 plugin-jqmethods Initialized jqmethods plugin.
Sep 22 02:30:01 lntxbot lightningd[804]: lightningd: FATAL SIGNAL 11 (version v0.7.2.1-255-g7686068)
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b03a0c6be send_backtrace
Sep 22 02:30:01 lntxbot lightningd[804]:         common/daemon.c:40
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b03a0c751 crashdump
Sep 22 02:30:01 lntxbot lightningd[804]:         common/daemon.c:53
Sep 22 02:30:01 lntxbot lightningd[804]: 0x7f1654d30f1f ???                                                                                                                                                                            Sep 22 02:30:01 lntxbot lightningd[804]:         ???:0
Sep 22 02:30:01 lntxbot lightningd[804]: 0x7f1654dad578 ???
Sep 22 02:30:01 lntxbot lightningd[804]:         ???:0
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b03a48b70 memcpy
Sep 22 02:30:01 lntxbot lightningd[804]:         /usr/include/x86_64-linux-gnu/bits/string_fortified.h:34
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b03a48b70 tal_dup_
Sep 22 02:30:01 lntxbot lightningd[804]:         ccan/ccan/tal/tal.c:796
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b03a46e81 tal_strdup_
Sep 22 02:30:01 lntxbot lightningd[804]:         ccan/ccan/tal/str/str.c:18
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b03a2e680 wallet_stmt2payment
Sep 22 02:30:01 lntxbot lightningd[804]:         wallet/wallet.c:2167
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b03a32711 wallet_payment_list
Sep 22 02:30:01 lntxbot lightningd[804]:         wallet/wallet.c:2446
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b039fb0d2 json_listsendpays
Sep 22 02:30:01 lntxbot lightningd[804]:         lightningd/pay.c:989
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b039f0d6f parse_request
Sep 22 02:30:01 lntxbot lightningd[804]:         lightningd/jsonrpc.c:650
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b039f1039 read_json
Sep 22 02:30:01 lntxbot lightningd[804]:         lightningd/jsonrpc.c:748
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b03a3ddee next_plan
Sep 22 02:30:01 lntxbot lightningd[804]:         ccan/ccan/io/io.c:59
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b03a3e2dd do_plan
Sep 22 02:30:01 lntxbot lightningd[804]:         ccan/ccan/io/io.c:407
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b03a3e30a io_ready
Sep 22 02:30:01 lntxbot lightningd[804]:         ccan/ccan/io/io.c:417
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b03a3fae2 io_loop
Sep 22 02:30:01 lntxbot lightningd[804]:         ccan/ccan/io/poll.c:445
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b039ee96c io_loop_with_timers
Sep 22 02:30:01 lntxbot lightningd[804]:         lightningd/io_loop_with_timers.c:24
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b039f2796 main
Sep 22 02:30:01 lntxbot lightningd[804]:         lightningd/lightningd.c:835
Sep 22 02:30:01 lntxbot lightningd[804]: 0x7f1654d13b96 ???
Sep 22 02:30:01 lntxbot lightningd[804]:         ???:0
Sep 22 02:30:01 lntxbot lightningd[804]: 0x561b039e1919 ???
Sep 22 02:30:01 lntxbot lightningd[804]:         ???:0
Sep 22 02:30:01 lntxbot lightningd[804]: 0xffffffffffffffff ???
Sep 22 02:30:01 lntxbot lightningd[804]:         ???:0

Reported-by: @fiatjaf
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-09-23 02:05:53 +00:00
Christian Decker d901304120 db: Change table field types to be more specific
sqlite3 was forgiving, postgres isn't, so let's make sure we use the strictest
field type possible, relaxing when rewriting.

The commit consists just of the following mapping

 - INTEGER -> BIGSERIAL if it is the primary key
 - INTEGER -> BIGINT if it is an amount or a reference to a primary key

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-22 02:03:43 +00:00
Christian Decker 416af636f0 db: Check execution when accessing the result of a statement
This was already done in `db_step` but `db_count_changes` and
`db_last_insert_id` also rely on the statement being executed. Furthermore we
now check that the statement was executed before freeing it, so it can't
happen that we dispose of a statement we meant to execute but forgot.

The combination of these could be used to replace the pending_statement
tracking based on lists, since we now make sure to execute all statements and
we use the memleak checker to make sure we don't keep a statement in memory.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-22 02:03:43 +00:00
Christian Decker 07f8d9046a db: Change migrations to use types of the correct cardinality
sqlite3 doesn't really do any validation whatsoever, and there is no
difference between 64bit and 32bit numbers. Posgtres on the other hand gets
very upset if the size doesn't match.

This commit swaps out handwavy types with the ones that should be there :-)

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-22 02:03:43 +00:00
Christian Decker 6b26ce5764 db: Split the vars table to have type-specific columns
This was weird right from the start, so we just split the table into integers
and blobs, so each column has a well-defined format. It is also required for
postgres not to cry about explicit casts in the `paramTypes` array.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-22 02:03:43 +00:00
Christian Decker 074af11e43 db: Select driver by dsn prefix
We were doing exact matches before, but prefix is sufficient.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-22 02:03:43 +00:00
Christian Decker ad89699888 db: Allow some internal queries to fail
The first ever query to check if the version DB exists may fail. We allow
this, but we need to restart the DB transaction since postgres fails the
current transaction and rolls back any changes.

This just commits (and fails) and starts a new transaction so the rest of the
migration can continue.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-22 02:03:43 +00:00
Christian Decker db6abda3a4 db: Adjust some db migrations to be compatible with postgres
Needed to change a couple of migrations. The changes are mostly innocuous:

 - changing BLOB to TEXT for short_channel_ids which is the correct type
   anyway, and sqlite3 treats them the same anyway.
 - Use `int` for version since the byte representation is checked by postgres.
 - Change anything that is INT, but will be bound to u64 to BIGINT (again
   postgres checks these more carefully than sqlite3).

Two migrations were replaced with dummy values, since they are buried deep
enough, and I found no portable way of expressing `strftime()` and `INSERT OR
IGNORE`.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-22 02:03:43 +00:00
Christian Decker 640e64cb73 db: Switch statement lookup to use the original query instead
Using a generated identifier with filename and line proved to be brittle since
compilers assign the __LINE__ macro differently on multi-line macro
invocations.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-22 02:03:43 +00:00
Christian Decker 3df8ccd3e0 db: Reorder migrations to reflect their relationship
This is dangerous but needed since postgres is not as forgiving about
unsatisfied foreign key constraints even while in a DB transaction.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-22 02:03:43 +00:00
Christian Decker e2f7c86271 db: Move remainder of the sqlite3 into the apropriate file
We used to do some of the setup work in db.c, which is now free of any
sqlite3-specific code. In addition we also switch over to fully qualified DSNs
to specify the location of the wallet.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-22 02:03:43 +00:00
Rusty Russell 11ee089d4b db: store option_static_remotekey for each channel.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-09-10 16:18:25 -05:00
Rusty Russell acf3952acc JSON: remove handling of pre-Adelaide (B:T:N) short_channel_ids.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-09-06 14:19:14 +02:00
Rusty Russell 91dcd1d55a db: convert pre-Adelaide short_channel_ids.
We're about to remove them.

Includes fix to sqlite3_bind_short_channel_id to not assume `id` is a
tal object.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-09-06 14:19:14 +02:00
Christian Decker 58f448904c db: Extract db config lookup into its own function
Signed-off-by: Christian Decker <decker.christian@gmail.com>
Suggested-by: Rusty Russell <@rustyrussell>
2019-09-05 23:41:05 +00:00
Christian Decker c6b6958ae6 db: Remove sqlite3 from db.c and db.h
Now that all the users are migrated to the abstraction layer we can remove the
legacy implementation.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker a29bedb5b8 db: Switch to indirect db close
Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker 742bcdb2bc db: Move statement expansion into the driver
It's better to let the driver decide when and how to expand. It can then
report the expanded statement back to the dispatch through the
`db_changes_add` function.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker b6d583c26a db: Move tracking of pending statements into the `struct db`
We now have a much stronger consistency check from the combination of
transaction wrapping, tal memory leak detection. Tramsaction wrapping ensures
that each statement is executed before the transaction is committed. The
commit is also driven by the `io_loop`, which means that it is no longer
possible for us to have statements outside of transactions and transactions
are guaranteed to commit at the round's end.

By adding the tal-awareness we can also get a much better indication as to
whether we have un-freed statements flying around, which we can test at the
end of the round as well.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker 460299850f db: Add DB-specific db_last_insert_id
This is likely the last part we need to completely encapsulate the part of the
sqlite3 API that we were using. Like the `db_count_changes` call I decided to
pass in the `struct db_stmt` since really they refer to the statement that was
executed and not the db.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker dffd3d79bc db: Add type-safe column access functions
These are based on top of the basic column access functions, and act as a
small type-safe wrapper, that also does a bit of validation.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker a4e5371732 db: Add more type-safe bindings to the interface
Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker c68efdfcf4 db: Migrate to DB abstraction layer in db.c
Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker 716a3b11a5 sqlite3: Move begin transaction and commit into the driver
This has a slight side-effect of removing the actual begin and commit
statements from the `db_write` hooks, but they are mostly redundant anyway (no
harm in grouping pre-init statements into one transaction, and we know that
each post-init call is supposed to be wrapped anyway).

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker 492d77f213 db: Add setup and teardown function to DB
These are used to do one-time initializations and wait for pending statements
before closing.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker a2b5b1561e db: Add method to count changed rows of a db_stmt
I was hoping to get rid of these by using "ON CONFLICT" upserts, however
sqlite3 only started supporting them in version 3.24.0 which is newer than
some of our deployment targets.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker d0027b1036 db: Implement basic query capabilities
This is the first step towards being able to extract information from query
rows. Only the most basic types are exposed, the others will be built on top
of these primitives.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker 98963c58e4 db: Track whether a db_stmt has been executed
For some of the query methods in the next step we need to have an idea of
whether the stmt was executed (db_step function) so let's track that
explicitly.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker e65e4fcf4b wallet: Call db_stmt_free from the db_stmt destructor automatically
This is much more in line with the rest of our memory management.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker 093f5bfbec db: Switch to new DB asbtraction for DB migrations
These do not require the ability to iterate over the result, hence they can be
migrated already.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker 38601afd17 db: Implement skaffolding for the dispatch of DB-specific functions
These functions implement the lookup of the query, and the dispatch to the
DB-specific functions that do the actual heavy lifting.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker 455aa48da0 wallet: Move the struct db definition to db_common.h
All drivers will have to reach into it, so put it in a place that is reachable
from the drivers, along with all other definitions.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker e04772ec9c wallet: Move the db_fatal definition so we can use it in drivers
Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker acedcc593f wallet: Look up the db_config for the given driver in db_open
Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker e4ab98459c wallet: Add tooling to extract SQL queries and generate driver info
This is the counterpart of the annotations we did in the last few commits. It
extracts queries, passes them through a driver-specific query rewriter and
dumps them into a driver-specific query-list, along with some metadata to
facilitate processing later on. The generated query list is then registered as
a `db_config` and will be loaded by the driver upon instantiation.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker 803007ecdf db: Make the `db` struct private and provide accessors instead
We will soon generalize the DB, so directly reaching into the `struct db`
instance to talk to the sqlite3 connection is bad anyway. This increases
flexibility and allows us to tailor the actual implementation to the
underlying DB.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker 66a47d2761 wallet: Annotate migrations using the SQL macro
Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker 57f91246cf wallet: Change db_select_prepare to check for select instead
`db_select_prepare` was prepending the "SELECT" part in an attempt to limit
its use to read-only statements. This is leads to the queries in the code not
actually being well-formed, which we'll need in a later commit, and was also
resulting in extra allocations. This switches the behavior to just enforce a
"SELECT" prefix being present which allows us to have well-formed queries in
the code again and avoids the extra allocation.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Christian Decker f08fd9eaab wallet: Remove printf-like db_select variant
We need to have full DB queries that can be extracted at compile time later in
order to be able to rewrite them in other SQL dialects. In addition we had a
bit of unnecessary code-duplication in db_select and db_select_prepare. Now
the former uses the latter internally.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-09-05 23:41:05 +00:00
Rusty Russell 979fbeb3b0 lightningd: simplify --daemon.
Dumb programs which have a --daemon option call fork() early.  This is
terrible UX since startup errors get lost: the program exits with
"success" immediately then you discover via the logs that it didn't
start at all.

However, forking late introduced a heap of problems with changing
pids.  Instead, fork early but keep stderr and the parent around: if
we fail early on, the parent fails with us.  We release our parent
with an explicit action just before the main loop.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-08-04 21:29:03 +02:00
Rusty Russell 220449e1cd ccan: import ccan/json_out and ccan/json_escape.
These are generalized from our internal implementations.

The main difference is that 'struct json_escaped' is now 'struct
json_escape', so we replace that immediately.

The difference between lightningd's json-writing ringbuffer and the
more generic ccan/json_out is that the latter has a better API and
handles escaping transparently if something slips through (though
it does offer direct accessors so you can mess things up yourself!).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-06-12 02:00:15 +00:00
Christian Decker 1e2291c40c db: Add channel_id and type to the transactions table
Mainly used to differentiate channel-related transactions from on-chain wallet
transactions. Will be used to filter `listtransaction` results and bundle
transactions that belong to the same channel.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-06-08 02:58:27 +00:00
trueptolemy b41d529b28 DB: Store the remote channel announcement signatures into DB
1. Add the fields of remote channel announcement signatures into TABLE channels
2. Add the related function
2019-05-29 11:46:33 +02:00
ZmnSCPxj edfb1ace4a wallet/db.c: Be resilient against 32-bit time_t.
Fixes: #2621
2019-05-24 16:07:33 +02:00
trueptolemy 8a2312565c DB: add failcode field in forwarded_payments table 2019-05-03 11:45:57 +02:00
Rusty Russell 7ead29b695 db: add support for remote end specify option_upfront_shutdown_script.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-05-02 01:18:33 +00:00
Christian Decker 75de2e2f3c wallet: Record the received_time and resolved_time for HTLCs
Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-04-10 23:48:39 +00:00
Christian Decker 2ce9a1e10d wallet: Add `received_time` to `htlc_in` for forwarding times
We'd like to display the receive and resolution times in the forwardings
table. In order to remember the receive time we need to store it in the DB
along with the other information.

Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-04-10 23:48:39 +00:00
Christian Decker fcf133cd0a db: Add timestamp primitives so we can store them in the DB
Signed-off-by: Christian Decker <decker.christian@gmail.com>
2019-04-10 23:48:39 +00:00
Rusty Russell b4455d517c common/node_id: new type.
Node ids are pubkeys, but we only use them as pubkeys for routing and checking
gossip messages.  So we're packing and unpacking them constantly, and wasting
some space and time.

This introduces a new type, explicitly the SEC1 compressed encoding
(33 bytes).  We ensure its validity when we load from the db, or get it
from JSON.  We still use 'struct pubkey' for peer messages, which checks
validity.

Results from 5 runs, min-max(mean +/- stddev):
	store_load_msec,vsz_kb,store_rewrite_sec,listnodes_sec,listchannels_sec,routing_sec,peer_write_all_sec
	39475-39572(39518+/-36),2880732,41.150000-41.390000(41.298+/-0.085),2.260000-2.550000(2.336+/-0.11),44.390000-65.150000(58.648+/-7.5),32.740000-33.020000(32.89+/-0.093),44.130000-45.090000(44.566+/-0.32)

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-04-09 12:37:16 -07:00
Rusty Russell 837a095d68 pubkey: rename PUBKEY_DER_LEN to PUBKEY_CMPR_LEN.
Pubkeys are not not actually DER encoding, but Pieter Wuille corrected
me: it's SEC 1 documented encoding.

Results from 5 runs, min-max(mean +/- stddev):
	store_load_msec,vsz_kb,store_rewrite_sec,listnodes_sec,listchannels_sec,routing_sec,peer_write_all_sec
	38922-39297(39180.6+/-1.3e+02),2880728,41.040000-41.160000(41.106+/-0.05),2.270000-2.530000(2.338+/-0.097),44.570000-53.980000(49.696+/-3),32.840000-33.080000(32.95+/-0.095),43.060000-44.950000(43.696+/-0.72)

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-04-09 12:37:16 -07:00
lisa neigut ee1c82a7a7 db: fix memleak introduced with sqlite3_expanded_sql
wallet/test/run-wallet was failing the valgrind check; turns out
`sqlite3_expanded_sql` expects you to manage the memory of strings
it returns. from `sqlite3.h`:

** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
** is obtained from [sqlite3_malloc()] and must be free by the application
** by passing it to [sqlite3_free()].
2019-04-09 07:19:15 +00:00
Rusty Russell 03108e6501 db: fall back to deprecated sqlite3_trace() for db hook on old sqlite3.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-04-08 01:56:17 +00:00
Rusty Russell 7ccf3af51d pytest: test the db hook plugin.
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-04-08 01:56:17 +00:00
Rusty Russell f0200027b8 db: keep track of changes.
For the moment we just dump them to stderr, but later this will go to a hook.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-04-08 01:56:17 +00:00
Rusty Russell e1e26ca69d db: create explicit separate API for select statements.
I was tempted to create a new db_select_stmt wrapper type, but that means
a lot of boilerplate around binding, which expects to work with db_prepare
*and* db_select_prepare.

This lets us clearly differentiate between db queries (which don't need to
go to a plugin) and db changes (which do).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-04-08 01:56:17 +00:00
Rusty Russell 8c4ef7f059 db: avoid the only failing db_exec.
Replace with an explicit test for existence.  This simplifies our db interface.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2019-04-08 01:56:17 +00:00