-
Notifications
You must be signed in to change notification settings - Fork 913
/
Copy pathwallet.c
2064 lines (1786 loc) · 59.3 KB
/
wallet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "invoices.h"
#include "wallet.h"
#include <bitcoin/script.h>
#include <ccan/structeq/structeq.h>
#include <ccan/tal/str/str.h>
#include <common/key_derive.h>
#include <common/wireaddr.h>
#include <inttypes.h>
#include <lightningd/invoice.h>
#include <lightningd/lightningd.h>
#include <lightningd/log.h>
#include <lightningd/peer_control.h>
#include <lightningd/peer_htlcs.h>
#define SQLITE_MAX_UINT 0x7FFFFFFFFFFFFFFF
#define DIRECTION_INCOMING 0
#define DIRECTION_OUTGOING 1
/* How many blocks must a UTXO entry be buried under to be considered old enough
* to prune? */
#define UTXO_PRUNE_DEPTH 144
static void outpointfilters_init(struct wallet *w)
{
sqlite3_stmt *stmt;
struct utxo **utxos = wallet_get_utxos(NULL, w, output_state_any);
struct bitcoin_txid txid;
u32 outnum;
w->owned_outpoints = outpointfilter_new(w);
for (size_t i = 0; i < tal_count(utxos); i++)
outpointfilter_add(w->owned_outpoints, &utxos[i]->txid, utxos[i]->outnum);
tal_free(utxos);
w->utxoset_outpoints = outpointfilter_new(w);
stmt = db_prepare(w->db, "SELECT txid, outnum FROM utxoset WHERE spendheight is NULL");
while (sqlite3_step(stmt) == SQLITE_ROW) {
sqlite3_column_sha256_double(stmt, 0, &txid.shad);
outnum = sqlite3_column_int(stmt, 1);
outpointfilter_add(w->utxoset_outpoints, &txid, outnum);
}
sqlite3_finalize(stmt);
}
struct wallet *wallet_new(struct lightningd *ld,
struct log *log, struct timers *timers)
{
struct wallet *wallet = tal(ld, struct wallet);
wallet->ld = ld;
wallet->db = db_setup(wallet, log);
wallet->log = log;
wallet->bip32_base = NULL;
wallet->invoices = invoices_new(wallet, wallet->db, log, timers);
list_head_init(&wallet->unstored_payments);
db_begin_transaction(wallet->db);
outpointfilters_init(wallet);
db_commit_transaction(wallet->db);
return wallet;
}
/* We actually use the db constraints to uniquify, so OK if this fails. */
bool wallet_add_utxo(struct wallet *w, struct utxo *utxo,
enum wallet_output_type type)
{
sqlite3_stmt *stmt;
stmt = db_prepare(w->db, "INSERT INTO outputs ("
"prev_out_tx, "
"prev_out_index, "
"value, "
"type, "
"status, "
"keyindex, "
"channel_id, "
"peer_id, "
"commitment_point, "
"confirmation_height, "
"spend_height) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
sqlite3_bind_blob(stmt, 1, &utxo->txid, sizeof(utxo->txid), SQLITE_TRANSIENT);
sqlite3_bind_int(stmt, 2, utxo->outnum);
sqlite3_bind_int64(stmt, 3, utxo->amount);
sqlite3_bind_int(stmt, 4, type);
sqlite3_bind_int(stmt, 5, output_state_available);
sqlite3_bind_int(stmt, 6, utxo->keyindex);
if (utxo->close_info) {
sqlite3_bind_int64(stmt, 7, utxo->close_info->channel_id);
sqlite3_bind_pubkey(stmt, 8, &utxo->close_info->peer_id);
sqlite3_bind_pubkey(stmt, 9, &utxo->close_info->commitment_point);
} else {
sqlite3_bind_null(stmt, 7);
sqlite3_bind_null(stmt, 8);
sqlite3_bind_null(stmt, 9);
}
if (utxo->blockheight) {
sqlite3_bind_int(stmt, 10, *utxo->blockheight);
} else
sqlite3_bind_null(stmt, 10);
if (utxo->spendheight)
sqlite3_bind_int(stmt, 11, *utxo->spendheight);
else
sqlite3_bind_null(stmt, 11);
/* May fail if we already know about the tx, e.g., because
* it's change or some internal tx. */
return db_exec_prepared_mayfail(w->db, stmt);
}
/**
* wallet_stmt2output - Extract data from stmt and fill an UTXO
*
* Returns true on success.
*/
static bool wallet_stmt2output(sqlite3_stmt *stmt, struct utxo *utxo)
{
int *blockheight, *spendheight;
sqlite3_column_sha256_double(stmt, 0, &utxo->txid.shad);
utxo->outnum = sqlite3_column_int(stmt, 1);
utxo->amount = sqlite3_column_int64(stmt, 2);
utxo->is_p2sh = sqlite3_column_int(stmt, 3) == p2sh_wpkh;
utxo->status = sqlite3_column_int(stmt, 4);
utxo->keyindex = sqlite3_column_int(stmt, 5);
if (sqlite3_column_type(stmt, 6) != SQLITE_NULL) {
utxo->close_info = tal(utxo, struct unilateral_close_info);
utxo->close_info->channel_id = sqlite3_column_int64(stmt, 6);
sqlite3_column_pubkey(stmt, 7, &utxo->close_info->peer_id);
sqlite3_column_pubkey(stmt, 8, &utxo->close_info->commitment_point);
} else {
utxo->close_info = NULL;
}
utxo->blockheight = NULL;
utxo->spendheight = NULL;
if (sqlite3_column_type(stmt, 9) != SQLITE_NULL) {
blockheight = tal(utxo, int);
*blockheight = sqlite3_column_int(stmt, 9);
utxo->blockheight = blockheight;
}
if (sqlite3_column_type(stmt, 10) != SQLITE_NULL) {
spendheight = tal(utxo, int);
*spendheight = sqlite3_column_int(stmt, 10);
utxo->spendheight = spendheight;
}
return true;
}
bool wallet_update_output_status(struct wallet *w,
const struct bitcoin_txid *txid,
const u32 outnum, enum output_status oldstatus,
enum output_status newstatus)
{
sqlite3_stmt *stmt;
if (oldstatus != output_state_any) {
stmt = db_prepare(
w->db, "UPDATE outputs SET status=? WHERE status=? AND prev_out_tx=? AND prev_out_index=?");
sqlite3_bind_int(stmt, 1, newstatus);
sqlite3_bind_int(stmt, 2, oldstatus);
sqlite3_bind_blob(stmt, 3, txid, sizeof(*txid), SQLITE_TRANSIENT);
sqlite3_bind_int(stmt, 4, outnum);
} else {
stmt = db_prepare(
w->db, "UPDATE outputs SET status=? WHERE prev_out_tx=? AND prev_out_index=?");
sqlite3_bind_int(stmt, 1, newstatus);
sqlite3_bind_blob(stmt, 2, txid, sizeof(*txid), SQLITE_TRANSIENT);
sqlite3_bind_int(stmt, 3, outnum);
}
db_exec_prepared(w->db, stmt);
return sqlite3_changes(w->db->sql) > 0;
}
struct utxo **wallet_get_utxos(const tal_t *ctx, struct wallet *w, const enum output_status state)
{
struct utxo **results;
int i;
sqlite3_stmt *stmt = db_prepare(
w->db, "SELECT prev_out_tx, prev_out_index, value, type, status, keyindex, "
"channel_id, peer_id, commitment_point, confirmation_height, spend_height "
"FROM outputs WHERE status=?1 OR ?1=255");
sqlite3_bind_int(stmt, 1, state);
results = tal_arr(ctx, struct utxo*, 0);
for (i=0; sqlite3_step(stmt) == SQLITE_ROW; i++) {
tal_resize(&results, i+1);
results[i] = tal(results, struct utxo);
wallet_stmt2output(stmt, results[i]);
}
sqlite3_finalize(stmt);
return results;
}
/**
* unreserve_utxo - Mark a reserved UTXO as available again
*/
static void unreserve_utxo(struct wallet *w, const struct utxo *unres)
{
if (!wallet_update_output_status(w, &unres->txid, unres->outnum,
output_state_reserved,
output_state_available)) {
fatal("Unable to unreserve output");
}
}
/**
* destroy_utxos - Destructor for an array of pointers to utxo
*/
static void destroy_utxos(const struct utxo **utxos, struct wallet *w)
{
for (size_t i = 0; i < tal_count(utxos); i++)
unreserve_utxo(w, utxos[i]);
}
void wallet_confirm_utxos(struct wallet *w, const struct utxo **utxos)
{
tal_del_destructor2(utxos, destroy_utxos, w);
for (size_t i = 0; i < tal_count(utxos); i++) {
if (!wallet_update_output_status(
w, &utxos[i]->txid, utxos[i]->outnum,
output_state_reserved, output_state_spent)) {
fatal("Unable to mark output as spent");
}
}
}
static const struct utxo **wallet_select(const tal_t *ctx, struct wallet *w,
const u64 value,
const u32 feerate_per_kw,
size_t outscriptlen,
bool may_have_change,
u64 *satoshi_in,
u64 *fee_estimate)
{
size_t i = 0;
struct utxo **available;
u64 weight;
const struct utxo **utxos = tal_arr(ctx, const struct utxo *, 0);
tal_add_destructor2(utxos, destroy_utxos, w);
/* version, input count, output count, locktime */
weight = (4 + 1 + 1 + 4) * 4;
/* The main output: amount, len, scriptpubkey */
weight += (8 + 1 + outscriptlen) * 4;
/* Change output will be P2WPKH */
if (may_have_change)
weight += (8 + 1 + BITCOIN_SCRIPTPUBKEY_P2WPKH_LEN) * 4;
*fee_estimate = 0;
*satoshi_in = 0;
available = wallet_get_utxos(ctx, w, output_state_available);
for (i = 0; i < tal_count(available); i++) {
size_t input_weight;
tal_resize(&utxos, i + 1);
utxos[i] = tal_steal(utxos, available[i]);
if (!wallet_update_output_status(
w, &available[i]->txid, available[i]->outnum,
output_state_available, output_state_reserved))
fatal("Unable to reserve output");
/* Input weight: txid + index + sequence */
input_weight = (32 + 4 + 4) * 4;
/* We always encode the length of the script, even if empty */
input_weight += 1 * 4;
/* P2SH variants include push of <0 <20-byte-key-hash>> */
if (utxos[i]->is_p2sh)
input_weight += 23 * 4;
/* Account for witness (1 byte count + sig + key) */
input_weight += 1 + (1 + 73 + 1 + 33);
weight += input_weight;
*fee_estimate = weight * feerate_per_kw / 1000;
*satoshi_in += utxos[i]->amount;
if (*satoshi_in >= *fee_estimate + value)
break;
}
tal_free(available);
return utxos;
}
const struct utxo **wallet_select_coins(const tal_t *ctx, struct wallet *w,
const u64 value,
const u32 feerate_per_kw,
size_t outscriptlen,
u64 *fee_estimate, u64 *changesatoshi)
{
u64 satoshi_in;
const struct utxo **utxo;
utxo = wallet_select(ctx, w, value, feerate_per_kw,
outscriptlen, true,
&satoshi_in, fee_estimate);
/* Couldn't afford it? */
if (satoshi_in < *fee_estimate + value)
return tal_free(utxo);
*changesatoshi = satoshi_in - value - *fee_estimate;
return utxo;
}
const struct utxo **wallet_select_all(const tal_t *ctx, struct wallet *w,
const u32 feerate_per_kw,
size_t outscriptlen,
u64 *value,
u64 *fee_estimate)
{
u64 satoshi_in;
const struct utxo **utxo;
/* Huge value, but won't overflow on addition */
utxo = wallet_select(ctx, w, (1ULL << 56), feerate_per_kw,
outscriptlen, false,
&satoshi_in, fee_estimate);
/* Can't afford fees? */
if (*fee_estimate > satoshi_in)
return tal_free(utxo);
*value = satoshi_in - *fee_estimate;
return utxo;
}
bool wallet_can_spend(struct wallet *w, const u8 *script,
u32 *index, bool *output_is_p2sh)
{
struct ext_key ext;
u64 bip32_max_index = db_get_intvar(w->db, "bip32_max_index", 0);
u32 i;
/* If not one of these, can't be for us. */
if (is_p2sh(script, NULL))
*output_is_p2sh = true;
else if (is_p2wpkh(script, NULL))
*output_is_p2sh = false;
else
return false;
for (i = 0; i <= bip32_max_index; i++) {
u8 *s;
if (bip32_key_from_parent(w->bip32_base, i,
BIP32_FLAG_KEY_PUBLIC, &ext)
!= WALLY_OK) {
abort();
}
s = scriptpubkey_p2wpkh_derkey(w, ext.pub_key);
if (*output_is_p2sh) {
u8 *p2sh = scriptpubkey_p2sh(w, s);
tal_free(s);
s = p2sh;
}
if (scripteq(s, script)) {
tal_free(s);
*index = i;
return true;
}
tal_free(s);
}
return false;
}
s64 wallet_get_newindex(struct lightningd *ld)
{
u64 newidx = db_get_intvar(ld->wallet->db, "bip32_max_index", 0) + 1;
if (newidx == BIP32_INITIAL_HARDENED_CHILD)
return -1;
db_set_intvar(ld->wallet->db, "bip32_max_index", newidx);
return newidx;
}
static void wallet_shachain_init(struct wallet *wallet,
struct wallet_shachain *chain)
{
sqlite3_stmt *stmt;
assert(chain->id == 0);
/* Create shachain */
shachain_init(&chain->chain);
stmt = db_prepare(wallet->db, "INSERT INTO shachains (min_index, num_valid) VALUES (?, 0);");
sqlite3_bind_int64(stmt, 1, chain->chain.min_index);
db_exec_prepared(wallet->db, stmt);
chain->id = sqlite3_last_insert_rowid(wallet->db->sql);
}
/* TODO(cdecker) Stolen from shachain, move to some appropriate location */
static unsigned int count_trailing_zeroes(uint64_t index)
{
#if HAVE_BUILTIN_CTZLL
return index ? (unsigned int)__builtin_ctzll(index) : SHACHAIN_BITS;
#else
unsigned int i;
for (i = 0; i < SHACHAIN_BITS; i++) {
if (index & (1ULL << i))
break;
}
return i;
#endif
}
bool wallet_shachain_add_hash(struct wallet *wallet,
struct wallet_shachain *chain,
uint64_t index,
const struct sha256 *hash)
{
sqlite3_stmt *stmt;
u32 pos = count_trailing_zeroes(index);
assert(index < SQLITE_MAX_UINT);
if (!shachain_add_hash(&chain->chain, index, hash)) {
return false;
}
stmt = db_prepare(wallet->db, "UPDATE shachains SET num_valid=?, min_index=? WHERE id=?");
sqlite3_bind_int(stmt, 1, chain->chain.num_valid);
sqlite3_bind_int64(stmt, 2, index);
sqlite3_bind_int64(stmt, 3, chain->id);
db_exec_prepared(wallet->db, stmt);
stmt = db_prepare(
wallet->db,
"REPLACE INTO shachain_known (shachain_id, pos, idx, hash) VALUES (?, ?, ?, ?);");
sqlite3_bind_int64(stmt, 1, chain->id);
sqlite3_bind_int(stmt, 2, pos);
sqlite3_bind_int64(stmt, 3, index);
sqlite3_bind_blob(stmt, 4, hash, sizeof(*hash), SQLITE_TRANSIENT);
db_exec_prepared(wallet->db, stmt);
return true;
}
bool wallet_shachain_load(struct wallet *wallet, u64 id,
struct wallet_shachain *chain)
{
int err;
sqlite3_stmt *stmt;
chain->id = id;
shachain_init(&chain->chain);
/* Load shachain metadata */
stmt = db_prepare(wallet->db, "SELECT min_index, num_valid FROM shachains WHERE id=?");
sqlite3_bind_int64(stmt, 1, id);
err = sqlite3_step(stmt);
if (err != SQLITE_ROW) {
sqlite3_finalize(stmt);
return false;
}
chain->chain.min_index = sqlite3_column_int64(stmt, 0);
chain->chain.num_valid = sqlite3_column_int64(stmt, 1);
sqlite3_finalize(stmt);
/* Load shachain known entries */
stmt = db_prepare(wallet->db, "SELECT idx, hash, pos FROM shachain_known WHERE shachain_id=?");
sqlite3_bind_int64(stmt, 1, id);
while (sqlite3_step(stmt) == SQLITE_ROW) {
int pos = sqlite3_column_int(stmt, 2);
chain->chain.known[pos].index = sqlite3_column_int64(stmt, 0);
memcpy(&chain->chain.known[pos].hash, sqlite3_column_blob(stmt, 1), sqlite3_column_bytes(stmt, 1));
}
sqlite3_finalize(stmt);
return true;
}
static struct peer *wallet_peer_load(struct wallet *w, const u64 dbid)
{
const unsigned char *addrstr;
struct peer *peer;
struct pubkey id;
struct wireaddr *addrp, addr;
sqlite3_stmt *stmt =
db_query(__func__, w->db,
"SELECT id, node_id, address FROM peers WHERE id=%"PRIu64";", dbid);
if (!stmt || sqlite3_step(stmt) != SQLITE_ROW) {
sqlite3_finalize(stmt);
return NULL;
}
if (!sqlite3_column_pubkey(stmt, 1, &id)) {
sqlite3_finalize(stmt);
return NULL;
}
addrstr = sqlite3_column_text(stmt, 2);
if (addrstr) {
addrp = &addr;
if (!parse_wireaddr((const char*)addrstr, addrp, DEFAULT_PORT, NULL)) {
sqlite3_finalize(stmt);
return NULL;
}
} else
addrp = NULL;
peer = new_peer(w->ld, sqlite3_column_int64(stmt, 0),
&id, addrp);
sqlite3_finalize(stmt);
return peer;
}
bool wallet_peer_by_nodeid(struct wallet *w, const struct pubkey *nodeid,
struct peer *peer)
{
bool ok;
const unsigned char *addrstr;
sqlite3_stmt *stmt = db_prepare(w->db, "SELECT id, node_id, address FROM peers WHERE node_id=?;");
sqlite3_bind_pubkey(stmt, 1, nodeid);
ok = stmt != NULL && sqlite3_step(stmt) == SQLITE_ROW;
if (ok) {
peer->dbid = sqlite3_column_int64(stmt, 0);
ok &= sqlite3_column_pubkey(stmt, 1, &peer->id);
addrstr = sqlite3_column_text(stmt, 2);
if (addrstr)
parse_wireaddr((const char*)addrstr, &peer->addr, DEFAULT_PORT, NULL);
} else {
/* Make sure we mark this as a new peer */
peer->dbid = 0;
}
sqlite3_finalize(stmt);
return ok;
}
static secp256k1_ecdsa_signature *
wallet_htlc_sigs_load(const tal_t *ctx, struct wallet *w, u64 channelid)
{
sqlite3_stmt *stmt = db_prepare(w->db, "SELECT signature FROM htlc_sigs WHERE channelid = ?");
secp256k1_ecdsa_signature *htlc_sigs = tal_arr(ctx, secp256k1_ecdsa_signature, 0);
sqlite3_bind_int64(stmt, 1, channelid);
size_t n = 0;
while (stmt && sqlite3_step(stmt) == SQLITE_ROW) {
tal_resize(&htlc_sigs, n+1);
sqlite3_column_signature(stmt, 0, &htlc_sigs[n]);
n++;
}
sqlite3_finalize(stmt);
log_debug(w->log, "Loaded %zu HTLC signatures from DB", n);
return htlc_sigs;
}
/**
* wallet_stmt2channel - Helper to populate a wallet_channel from a sqlite3_stmt
*/
static struct channel *wallet_stmt2channel(const tal_t *ctx, struct wallet *w, sqlite3_stmt *stmt)
{
bool ok = true;
struct channel_info channel_info;
struct short_channel_id *scid;
struct channel *chan;
u64 peer_dbid;
struct peer *peer;
struct wallet_shachain wshachain;
struct channel_config our_config;
struct bitcoin_txid funding_txid;
secp256k1_ecdsa_signature last_sig;
u8 *remote_shutdown_scriptpubkey;
struct changed_htlc *last_sent_commit;
s64 final_key_idx;
peer_dbid = sqlite3_column_int64(stmt, 1);
peer = find_peer_by_dbid(w->ld, peer_dbid);
if (!peer) {
peer = wallet_peer_load(w, peer_dbid);
if (!peer) {
return NULL;
}
}
if (sqlite3_column_type(stmt, 2) != SQLITE_NULL) {
scid = tal(tmpctx, struct short_channel_id);
sqlite3_column_short_channel_id(stmt, 2, scid);
} else {
scid = NULL;
}
ok &= wallet_shachain_load(w, sqlite3_column_int64(stmt, 27),
&wshachain);
remote_shutdown_scriptpubkey = sqlite3_column_arr(tmpctx, stmt, 28, u8);
/* Do we have a last_sent_commit, if yes, populate */
if (sqlite3_column_type(stmt, 30) != SQLITE_NULL) {
last_sent_commit = tal(tmpctx, struct changed_htlc);
last_sent_commit->newstate = sqlite3_column_int64(stmt, 30);
last_sent_commit->id = sqlite3_column_int64(stmt, 31);
} else {
last_sent_commit = NULL;
}
ok &= wallet_channel_config_load(w, sqlite3_column_int64(stmt, 3),
&our_config);
ok &= sqlite3_column_sha256_double(stmt, 12, &funding_txid.shad);
ok &= sqlite3_column_signature(stmt, 33, &last_sig);
/* Populate channel_info */
ok &= sqlite3_column_pubkey(stmt, 18, &channel_info.remote_fundingkey);
ok &= sqlite3_column_pubkey(stmt, 19, &channel_info.theirbase.revocation);
ok &= sqlite3_column_pubkey(stmt, 20, &channel_info.theirbase.payment);
ok &= sqlite3_column_pubkey(stmt, 21, &channel_info.theirbase.htlc);
ok &= sqlite3_column_pubkey(stmt, 22, &channel_info.theirbase.delayed_payment);
ok &= sqlite3_column_pubkey(stmt, 23, &channel_info.remote_per_commit);
ok &= sqlite3_column_pubkey(stmt, 24, &channel_info.old_remote_per_commit);
channel_info.feerate_per_kw[LOCAL] = sqlite3_column_int(stmt, 25);
channel_info.feerate_per_kw[REMOTE] = sqlite3_column_int(stmt, 26);
wallet_channel_config_load(w, sqlite3_column_int64(stmt, 4),
&channel_info.their_config);
if (!ok) {
return NULL;
}
final_key_idx = sqlite3_column_int64(stmt, 29);
if (final_key_idx < 0) {
log_broken(w->log, "%s: Final key < 0", __func__);
return NULL;
}
chan = new_channel(peer, sqlite3_column_int64(stmt, 0),
&wshachain,
sqlite3_column_int(stmt, 5),
sqlite3_column_int(stmt, 6),
NULL, /* Set up fresh log */
"Loaded from database",
sqlite3_column_int(stmt, 7),
&our_config,
sqlite3_column_int(stmt, 8),
sqlite3_column_int64(stmt, 9),
sqlite3_column_int64(stmt, 10),
sqlite3_column_int64(stmt, 11),
&funding_txid,
sqlite3_column_int(stmt, 13),
sqlite3_column_int64(stmt, 14),
sqlite3_column_int64(stmt, 16),
sqlite3_column_int(stmt, 15) != 0,
scid,
sqlite3_column_int64(stmt, 17),
sqlite3_column_tx(tmpctx, stmt, 32),
&last_sig,
wallet_htlc_sigs_load(tmpctx, w,
sqlite3_column_int64(stmt, 0)),
&channel_info,
remote_shutdown_scriptpubkey,
final_key_idx,
sqlite3_column_int(stmt, 34) != 0,
last_sent_commit,
sqlite3_column_int64(stmt, 35));
return chan;
}
/* List of fields to retrieve from the channels DB table, in the order
* that wallet_stmt2channel understands and will parse correctly */
static const char *channel_fields =
"id, peer_id, short_channel_id, channel_config_local, "
"channel_config_remote, state, funder, channel_flags, "
"minimum_depth, "
"next_index_local, next_index_remote, "
"next_htlc_id, funding_tx_id, funding_tx_outnum, funding_satoshi, "
"funding_locked_remote, push_msatoshi, msatoshi_local, "
"fundingkey_remote, revocation_basepoint_remote, "
"payment_basepoint_remote, htlc_basepoint_remote, "
"delayed_payment_basepoint_remote, per_commit_remote, "
"old_per_commit_remote, local_feerate_per_kw, remote_feerate_per_kw, shachain_remote_id, "
"shutdown_scriptpubkey_remote, shutdown_keyidx_local, "
"last_sent_commit_state, last_sent_commit_id, "
"last_tx, last_sig, last_was_revoke, first_blocknum";
bool wallet_channels_load_active(const tal_t *ctx, struct wallet *w)
{
bool ok = true;
sqlite3_stmt *stmt;
/* We load all channels */
stmt = db_query(
__func__, w->db, "SELECT %s FROM channels;",
channel_fields);
w->max_channel_dbid = 0;
int count = 0;
while (ok && stmt && sqlite3_step(stmt) == SQLITE_ROW) {
struct channel *c = wallet_stmt2channel(ctx, w, stmt);
if (!c) {
ok = false;
break;
}
if (c->dbid > w->max_channel_dbid)
w->max_channel_dbid = c->dbid;
count++;
}
log_debug(w->log, "Loaded %d channels from DB", count);
sqlite3_finalize(stmt);
return ok;
}
#ifdef COMPAT_V052
/* Upgrade of db (or initial create): do we have anything to scan for? */
static bool wallet_ever_used(struct wallet *w)
{
sqlite3_stmt *stmt;
bool channel_utxos;
/* If we ever handed out an address. */
if (db_get_intvar(w->db, "bip32_max_index", 0) != 0)
return true;
/* Or if they do a unilateral close, the output to us provides a UTXO. */
stmt = db_query(__func__, w->db,
"SELECT COUNT(*) FROM outputs WHERE commitment_point IS NOT NULL;");
int ret = sqlite3_step(stmt);
assert(ret == SQLITE_ROW);
channel_utxos = (sqlite3_column_int(stmt, 0) != 0);
sqlite3_finalize(stmt);
return channel_utxos;
}
#endif
/* We want the earlier of either:
* 1. The first channel we're still watching (it might have closed),
* 2. The last block we scanned for UTXO (might have new incoming payments)
*
* chaintopology actually subtracts another 100 blocks to make sure we
* catch chain forks.
*/
u32 wallet_first_blocknum(struct wallet *w, u32 first_possible)
{
int err;
u32 first_channel, first_utxo;
sqlite3_stmt *stmt =
db_query(__func__, w->db,
"SELECT MIN(first_blocknum) FROM channels;");
/* If we ever opened a channel, this will give us the first block. */
err = sqlite3_step(stmt);
if (err == SQLITE_ROW && sqlite3_column_type(stmt, 0) != SQLITE_NULL)
first_channel = sqlite3_column_int(stmt, 0);
else
first_channel = UINT32_MAX;
sqlite3_finalize(stmt);
#ifdef COMPAT_V052
/* This field was missing in older databases. */
first_utxo = db_get_intvar(w->db, "last_processed_block", 0);
if (first_utxo == 0) {
/* Don't know? New db, or upgraded. */
if (wallet_ever_used(w))
/* Be conservative */
first_utxo = first_possible;
else
first_utxo = UINT32_MAX;
}
#else
first_utxo = db_get_intvar(w->db, "last_processed_block", UINT32_MAX);
#endif
if (first_utxo < first_channel)
return first_utxo;
else
return first_channel;
}
static void wallet_channel_config_insert(struct wallet *w,
struct channel_config *cc)
{
sqlite3_stmt *stmt;
assert(cc->id == 0);
stmt = db_prepare(w->db, "INSERT INTO channel_configs DEFAULT VALUES;");
db_exec_prepared(w->db, stmt);
cc->id = sqlite3_last_insert_rowid(w->db->sql);
}
static void wallet_channel_config_save(struct wallet *w,
const struct channel_config *cc)
{
sqlite3_stmt *stmt;
assert(cc->id != 0);
stmt = db_prepare(w->db, "UPDATE channel_configs SET"
" dust_limit_satoshis=?,"
" max_htlc_value_in_flight_msat=?,"
" channel_reserve_satoshis=?,"
" htlc_minimum_msat=?,"
" to_self_delay=?,"
" max_accepted_htlcs=?"
" WHERE id=?;");
sqlite3_bind_int64(stmt, 1, cc->dust_limit_satoshis);
sqlite3_bind_int64(stmt, 2, cc->max_htlc_value_in_flight_msat);
sqlite3_bind_int64(stmt, 3, cc->channel_reserve_satoshis);
sqlite3_bind_int64(stmt, 4, cc->htlc_minimum_msat);
sqlite3_bind_int(stmt, 5, cc->to_self_delay);
sqlite3_bind_int(stmt, 6, cc->max_accepted_htlcs);
sqlite3_bind_int64(stmt, 7, cc->id);
db_exec_prepared(w->db, stmt);
}
bool wallet_channel_config_load(struct wallet *w, const u64 id,
struct channel_config *cc)
{
bool ok = true;
int col = 1;
const char *query =
"SELECT id, dust_limit_satoshis, max_htlc_value_in_flight_msat, "
"channel_reserve_satoshis, htlc_minimum_msat, to_self_delay, "
"max_accepted_htlcs FROM channel_configs WHERE id=%" PRIu64 ";";
sqlite3_stmt *stmt = db_query(__func__, w->db, query, id);
if (!stmt || sqlite3_step(stmt) != SQLITE_ROW) {
sqlite3_finalize(stmt);
return false;
}
cc->id = id;
cc->dust_limit_satoshis = sqlite3_column_int64(stmt, col++);
cc->max_htlc_value_in_flight_msat = sqlite3_column_int64(stmt, col++);
cc->channel_reserve_satoshis = sqlite3_column_int64(stmt, col++);
cc->htlc_minimum_msat = sqlite3_column_int64(stmt, col++);
cc->to_self_delay = sqlite3_column_int(stmt, col++);
cc->max_accepted_htlcs = sqlite3_column_int(stmt, col++);
assert(col == 7);
sqlite3_finalize(stmt);
return ok;
}
u64 wallet_get_channel_dbid(struct wallet *wallet)
{
return ++wallet->max_channel_dbid;
}
void wallet_channel_save(struct wallet *w, struct channel *chan)
{
sqlite3_stmt *stmt;
assert(chan->first_blocknum);
wallet_channel_config_save(w, &chan->our_config);
stmt = db_prepare(w->db, "UPDATE channels SET"
" shachain_remote_id=?,"
" short_channel_id=?,"
" state=?,"
" funder=?,"
" channel_flags=?,"
" minimum_depth=?,"
" next_index_local=?,"
" next_index_remote=?,"
" next_htlc_id=?,"
" funding_tx_id=?,"
" funding_tx_outnum=?,"
" funding_satoshi=?,"
" funding_locked_remote=?,"
" push_msatoshi=?,"
" msatoshi_local=?,"
" shutdown_scriptpubkey_remote=?,"
" shutdown_keyidx_local=?,"
" channel_config_local=?,"
" last_tx=?, last_sig=?,"
" last_was_revoke=?"
" WHERE id=?");
sqlite3_bind_int64(stmt, 1, chan->their_shachain.id);
if (chan->scid)
sqlite3_bind_short_channel_id(stmt, 2, chan->scid);
sqlite3_bind_int(stmt, 3, chan->state);
sqlite3_bind_int(stmt, 4, chan->funder);
sqlite3_bind_int(stmt, 5, chan->channel_flags);
sqlite3_bind_int(stmt, 6, chan->minimum_depth);
sqlite3_bind_int64(stmt, 7, chan->next_index[LOCAL]);
sqlite3_bind_int64(stmt, 8, chan->next_index[REMOTE]);
sqlite3_bind_int64(stmt, 9, chan->next_htlc_id);
sqlite3_bind_sha256_double(stmt, 10, &chan->funding_txid.shad);
sqlite3_bind_int(stmt, 11, chan->funding_outnum);
sqlite3_bind_int64(stmt, 12, chan->funding_satoshi);
sqlite3_bind_int(stmt, 13, chan->remote_funding_locked);
sqlite3_bind_int64(stmt, 14, chan->push_msat);
sqlite3_bind_int64(stmt, 15, chan->our_msatoshi);
if (chan->remote_shutdown_scriptpubkey)
sqlite3_bind_blob(stmt, 16, chan->remote_shutdown_scriptpubkey,
tal_len(chan->remote_shutdown_scriptpubkey),
SQLITE_TRANSIENT);
sqlite3_bind_int64(stmt, 17, chan->final_key_idx);
sqlite3_bind_int64(stmt, 18, chan->our_config.id);
sqlite3_bind_tx(stmt, 19, chan->last_tx);
sqlite3_bind_signature(stmt, 20, &chan->last_sig);
sqlite3_bind_int(stmt, 21, chan->last_was_revoke);
sqlite3_bind_int64(stmt, 22, chan->dbid);
db_exec_prepared(w->db, stmt);
wallet_channel_config_save(w, &chan->channel_info.their_config);
stmt = db_prepare(w->db, "UPDATE channels SET"
" fundingkey_remote=?,"
" revocation_basepoint_remote=?,"
" payment_basepoint_remote=?,"
" htlc_basepoint_remote=?,"
" delayed_payment_basepoint_remote=?,"
" per_commit_remote=?,"
" old_per_commit_remote=?,"
" local_feerate_per_kw=?,"
" remote_feerate_per_kw=?,"
" channel_config_remote=?"
" WHERE id=?");
sqlite3_bind_pubkey(stmt, 1, &chan->channel_info.remote_fundingkey);
sqlite3_bind_pubkey(stmt, 2, &chan->channel_info.theirbase.revocation);
sqlite3_bind_pubkey(stmt, 3, &chan->channel_info.theirbase.payment);
sqlite3_bind_pubkey(stmt, 4, &chan->channel_info.theirbase.htlc);
sqlite3_bind_pubkey(stmt, 5, &chan->channel_info.theirbase.delayed_payment);
sqlite3_bind_pubkey(stmt, 6, &chan->channel_info.remote_per_commit);
sqlite3_bind_pubkey(stmt, 7, &chan->channel_info.old_remote_per_commit);
sqlite3_bind_int(stmt, 8, chan->channel_info.feerate_per_kw[LOCAL]);
sqlite3_bind_int(stmt, 9, chan->channel_info.feerate_per_kw[REMOTE]);
sqlite3_bind_int64(stmt, 10, chan->channel_info.their_config.id);
sqlite3_bind_int64(stmt, 11, chan->dbid);
db_exec_prepared(w->db, stmt);
/* If we have a last_sent_commit, store it */
if (chan->last_sent_commit) {
stmt = db_prepare(w->db,
"UPDATE channels SET"
" last_sent_commit_state=?,"
" last_sent_commit_id=?"
" WHERE id=?");
sqlite3_bind_int(stmt, 1, chan->last_sent_commit->newstate);
sqlite3_bind_int64(stmt, 2, chan->last_sent_commit->id);
sqlite3_bind_int64(stmt, 3, chan->dbid);
db_exec_prepared(w->db, stmt);
}
}
void wallet_channel_insert(struct wallet *w, struct channel *chan)
{
sqlite3_stmt *stmt;
if (chan->peer->dbid == 0) {
/* Need to create the peer first */
stmt = db_prepare(w->db, "INSERT INTO peers (node_id, address) VALUES (?, ?);");
sqlite3_bind_pubkey(stmt, 1, &chan->peer->id);
if (chan->peer->addr.type == ADDR_TYPE_PADDING)
sqlite3_bind_null(stmt, 2);
else
sqlite3_bind_text(stmt, 2,
type_to_string(tmpctx, struct wireaddr, &chan->peer->addr),
-1, SQLITE_TRANSIENT);
db_exec_prepared(w->db, stmt);
chan->peer->dbid = sqlite3_last_insert_rowid(w->db->sql);
}
/* Insert a stub, that we update, unifies INSERT and UPDATE paths */
stmt = db_prepare(w->db, "INSERT INTO channels ("
"peer_id, first_blocknum, id) VALUES (?, ?, ?);");
sqlite3_bind_int64(stmt, 1, chan->peer->dbid);
sqlite3_bind_int(stmt, 2, chan->first_blocknum);
sqlite3_bind_int(stmt, 3, chan->dbid);
db_exec_prepared(w->db, stmt);
wallet_channel_config_insert(w, &chan->our_config);
wallet_channel_config_insert(w, &chan->channel_info.their_config);
wallet_shachain_init(w, &chan->their_shachain);
/* Now save path as normal */
wallet_channel_save(w, chan);
}
void wallet_channel_delete(struct wallet *w, u64 wallet_id)
{
sqlite3_stmt *stmt;
stmt = db_prepare(w->db,
"DELETE FROM channels WHERE id=?");
sqlite3_bind_int64(stmt, 1, wallet_id);
db_exec_prepared(w->db, stmt);
}