forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wallet.c
5125 lines (4498 loc) · 143 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 "config.h"
#include <bitcoin/script.h>
#include <ccan/array_size/array_size.h>
#include <ccan/cast/cast.h>
#include <ccan/mem/mem.h>
#include <ccan/tal/str/str.h>
#include <common/blockheight_states.h>
#include <common/fee_states.h>
#include <common/onionreply.h>
#include <common/type_to_string.h>
#include <db/bindings.h>
#include <db/common.h>
#include <db/exec.h>
#include <db/utils.h>
#include <lightningd/chaintopology.h>
#include <lightningd/channel.h>
#include <lightningd/coin_mvts.h>
#include <lightningd/notification.h>
#include <lightningd/peer_control.h>
#include <onchaind/onchaind_wiregen.h>
#include <wallet/invoices.h>
#include <wallet/txfilter.h>
#include <wallet/wallet.h>
#include <wally_bip32.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
/* 12 hours is usually enough reservation time */
#define RESERVATION_INC (6 * 12)
/* Possible channel state */
enum channel_state_bucket {
IN_OFFERED = 0,
IN_FULLFILLED = 1,
OUT_OFFERED = 2,
OUT_FULLFILLED = 3,
};
/* channel state identifier */
struct channel_state_param {
const char *dir_key;
const char *type_key;
const enum channel_state_bucket state;
};
/* Implement db_fatal, as a wrapper around fatal.
* We use a ifndef block so that it can get be
* implemented in a test file first, if necessary */
#ifndef DB_FATAL
#define DB_FATAL
void db_fatal(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fatal_vfmt(fmt, ap);
va_end(ap);
}
#endif /* DB_FATAL */
static void outpointfilters_init(struct wallet *w)
{
struct db_stmt *stmt;
struct utxo **utxos = wallet_get_utxos(NULL, w, OUTPUT_STATE_ANY);
struct bitcoin_outpoint outpoint;
w->owned_outpoints = outpointfilter_new(w);
for (size_t i = 0; i < tal_count(utxos); i++)
outpointfilter_add(w->owned_outpoints, &utxos[i]->outpoint);
tal_free(utxos);
w->utxoset_outpoints = outpointfilter_new(w);
stmt = db_prepare_v2(
w->db,
SQL("SELECT txid, outnum FROM utxoset WHERE spendheight is NULL"));
db_query_prepared(stmt);
while (db_step(stmt)) {
db_col_txid(stmt, "txid", &outpoint.txid);
outpoint.n = db_col_int(stmt, "outnum");
outpointfilter_add(w->utxoset_outpoints, &outpoint);
}
tal_free(stmt);
}
struct wallet *wallet_new(struct lightningd *ld, struct timers *timers,
struct ext_key *bip32_base STEALS)
{
struct wallet *wallet = tal(ld, struct wallet);
wallet->ld = ld;
wallet->log = new_log(wallet, ld->log_book, NULL, "wallet");
wallet->bip32_base = tal_steal(wallet, bip32_base);
wallet->keyscan_gap = 50;
list_head_init(&wallet->unstored_payments);
wallet->db = db_setup(wallet, ld, wallet->bip32_base);
db_begin_transaction(wallet->db);
wallet->invoices = invoices_new(wallet, wallet->db, timers);
outpointfilters_init(wallet);
db_commit_transaction(wallet->db);
return wallet;
}
/**
* wallet_add_utxo - Register an UTXO which we (partially) own
*
* Add an UTXO to the set of outputs we care about.
*
* This can fail if we've already seen UTXO.
*/
static bool wallet_add_utxo(struct wallet *w, struct utxo *utxo,
enum wallet_output_type type)
{
struct db_stmt *stmt;
stmt = db_prepare_v2(w->db, SQL("SELECT * from outputs WHERE "
"prev_out_tx=? AND prev_out_index=?"));
db_bind_txid(stmt, 0, &utxo->outpoint.txid);
db_bind_int(stmt, 1, utxo->outpoint.n);
db_query_prepared(stmt);
/* If we get a result, that means a clash. */
if (db_step(stmt)) {
db_col_ignore(stmt, "*");
tal_free(stmt);
return false;
}
tal_free(stmt);
stmt = db_prepare_v2(
w->db, SQL("INSERT INTO outputs ("
" prev_out_tx"
", prev_out_index"
", value"
", type"
", status"
", keyindex"
", channel_id"
", peer_id"
", commitment_point"
", option_anchor_outputs"
", confirmation_height"
", spend_height"
", scriptpubkey"
") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"));
db_bind_txid(stmt, 0, &utxo->outpoint.txid);
db_bind_int(stmt, 1, utxo->outpoint.n);
db_bind_amount_sat(stmt, 2, &utxo->amount);
db_bind_int(stmt, 3, wallet_output_type_in_db(type));
db_bind_int(stmt, 4, OUTPUT_STATE_AVAILABLE);
db_bind_int(stmt, 5, utxo->keyindex);
if (utxo->close_info) {
db_bind_u64(stmt, 6, utxo->close_info->channel_id);
db_bind_node_id(stmt, 7, &utxo->close_info->peer_id);
if (utxo->close_info->commitment_point)
db_bind_pubkey(stmt, 8, utxo->close_info->commitment_point);
else
db_bind_null(stmt, 8);
db_bind_int(stmt, 9, utxo->close_info->option_anchor_outputs);
} else {
db_bind_null(stmt, 6);
db_bind_null(stmt, 7);
db_bind_null(stmt, 8);
db_bind_null(stmt, 9);
}
if (utxo->blockheight) {
db_bind_int(stmt, 10, *utxo->blockheight);
} else
db_bind_null(stmt, 10);
if (utxo->spendheight)
db_bind_int(stmt, 11, *utxo->spendheight);
else
db_bind_null(stmt, 11);
db_bind_blob(stmt, 12, utxo->scriptPubkey,
tal_bytelen(utxo->scriptPubkey));
db_exec_prepared_v2(take(stmt));
return true;
}
/**
* wallet_stmt2output - Extract data from stmt and fill an UTXO
*/
static struct utxo *wallet_stmt2output(const tal_t *ctx, struct db_stmt *stmt)
{
struct utxo *utxo = tal(ctx, struct utxo);
u32 *blockheight, *spendheight;
db_col_txid(stmt, "prev_out_tx", &utxo->outpoint.txid);
utxo->outpoint.n = db_col_int(stmt, "prev_out_index");
db_col_amount_sat(stmt, "value", &utxo->amount);
utxo->is_p2sh = db_col_int(stmt, "type") == p2sh_wpkh;
utxo->status = db_col_int(stmt, "status");
utxo->keyindex = db_col_int(stmt, "keyindex");
if (!db_col_is_null(stmt, "channel_id")) {
utxo->close_info = tal(utxo, struct unilateral_close_info);
utxo->close_info->channel_id = db_col_u64(stmt, "channel_id");
db_col_node_id(stmt, "peer_id", &utxo->close_info->peer_id);
if (!db_col_is_null(stmt, "commitment_point")) {
utxo->close_info->commitment_point
= tal(utxo->close_info, struct pubkey);
db_col_pubkey(stmt, "commitment_point",
utxo->close_info->commitment_point);
} else
utxo->close_info->commitment_point = NULL;
utxo->close_info->option_anchor_outputs
= db_col_int(stmt, "option_anchor_outputs");
utxo->close_info->csv = db_col_int(stmt, "csv_lock");
} else {
utxo->close_info = NULL;
db_col_ignore(stmt, "peer_id");
db_col_ignore(stmt, "commitment_point");
db_col_ignore(stmt, "option_anchor_outputs");
db_col_ignore(stmt, "csv_lock");
}
utxo->scriptPubkey = db_col_arr(utxo, stmt, "scriptpubkey", u8);
utxo->blockheight = NULL;
utxo->spendheight = NULL;
if (!db_col_is_null(stmt, "confirmation_height")) {
blockheight = tal(utxo, u32);
*blockheight = db_col_int(stmt, "confirmation_height");
utxo->blockheight = blockheight;
}
if (!db_col_is_null(stmt, "spend_height")) {
spendheight = tal(utxo, u32);
*spendheight = db_col_int(stmt, "spend_height");
utxo->spendheight = spendheight;
}
/* This column can be null if 0.9.1 db or below. */
utxo->reserved_til = db_col_int_or_default(stmt, "reserved_til", 0);
return utxo;
}
bool wallet_update_output_status(struct wallet *w,
const struct bitcoin_outpoint *outpoint,
enum output_status oldstatus,
enum output_status newstatus)
{
struct db_stmt *stmt;
size_t changes;
if (oldstatus != OUTPUT_STATE_ANY) {
stmt = db_prepare_v2(
w->db, SQL("UPDATE outputs SET status=? WHERE status=? AND "
"prev_out_tx=? AND prev_out_index=?"));
db_bind_int(stmt, 0, output_status_in_db(newstatus));
db_bind_int(stmt, 1, output_status_in_db(oldstatus));
db_bind_txid(stmt, 2, &outpoint->txid);
db_bind_int(stmt, 3, outpoint->n);
} else {
stmt = db_prepare_v2(w->db,
SQL("UPDATE outputs SET status=? WHERE "
"prev_out_tx=? AND prev_out_index=?"));
db_bind_int(stmt, 0, output_status_in_db(newstatus));
db_bind_txid(stmt, 1, &outpoint->txid);
db_bind_int(stmt, 2, outpoint->n);
}
db_exec_prepared_v2(stmt);
changes = db_count_changes(stmt);
tal_free(stmt);
return changes > 0;
}
struct utxo **wallet_get_utxos(const tal_t *ctx, struct wallet *w, const enum output_status state)
{
struct utxo **results;
int i;
struct db_stmt *stmt;
if (state == OUTPUT_STATE_ANY) {
stmt = db_prepare_v2(w->db, SQL("SELECT"
" prev_out_tx"
", prev_out_index"
", value"
", type"
", status"
", keyindex"
", channel_id"
", peer_id"
", commitment_point"
", option_anchor_outputs"
", confirmation_height"
", spend_height"
", scriptpubkey "
", reserved_til "
", csv_lock "
"FROM outputs"));
} else {
stmt = db_prepare_v2(w->db, SQL("SELECT"
" prev_out_tx"
", prev_out_index"
", value"
", type"
", status"
", keyindex"
", channel_id"
", peer_id"
", commitment_point"
", option_anchor_outputs"
", confirmation_height"
", spend_height"
", scriptpubkey "
", reserved_til "
", csv_lock "
"FROM outputs "
"WHERE status= ? "));
db_bind_int(stmt, 0, output_status_in_db(state));
}
db_query_prepared(stmt);
results = tal_arr(ctx, struct utxo*, 0);
for (i=0; db_step(stmt); i++) {
struct utxo *u = wallet_stmt2output(results, stmt);
tal_arr_expand(&results, u);
}
tal_free(stmt);
return results;
}
struct utxo **wallet_get_unconfirmed_closeinfo_utxos(const tal_t *ctx,
struct wallet *w)
{
struct db_stmt *stmt;
struct utxo **results;
int i;
stmt = db_prepare_v2(w->db, SQL("SELECT"
" prev_out_tx"
", prev_out_index"
", value"
", type"
", status"
", keyindex"
", channel_id"
", peer_id"
", commitment_point"
", option_anchor_outputs"
", confirmation_height"
", spend_height"
", scriptpubkey"
", reserved_til"
", csv_lock"
" FROM outputs"
" WHERE channel_id IS NOT NULL AND "
"confirmation_height IS NULL"));
db_query_prepared(stmt);
results = tal_arr(ctx, struct utxo *, 0);
for (i = 0; db_step(stmt); i++) {
struct utxo *u = wallet_stmt2output(results, stmt);
tal_arr_expand(&results, u);
}
tal_free(stmt);
return results;
}
struct utxo *wallet_utxo_get(const tal_t *ctx, struct wallet *w,
const struct bitcoin_outpoint *outpoint)
{
struct db_stmt *stmt;
struct utxo *utxo;
stmt = db_prepare_v2(w->db, SQL("SELECT"
" prev_out_tx"
", prev_out_index"
", value"
", type"
", status"
", keyindex"
", channel_id"
", peer_id"
", commitment_point"
", option_anchor_outputs"
", confirmation_height"
", spend_height"
", scriptpubkey"
", reserved_til"
", csv_lock"
" FROM outputs"
" WHERE prev_out_tx = ?"
" AND prev_out_index = ?"));
db_bind_txid(stmt, 0, &outpoint->txid);
db_bind_int(stmt, 1, outpoint->n);
db_query_prepared(stmt);
if (!db_step(stmt)) {
tal_free(stmt);
return NULL;
}
utxo = wallet_stmt2output(ctx, stmt);
tal_free(stmt);
return utxo;
}
static void db_set_utxo(struct db *db, const struct utxo *utxo)
{
struct db_stmt *stmt;
if (utxo->status == OUTPUT_STATE_RESERVED)
assert(utxo->reserved_til);
else
assert(!utxo->reserved_til);
stmt = db_prepare_v2(
db, SQL("UPDATE outputs SET status=?, reserved_til=? "
"WHERE prev_out_tx=? AND prev_out_index=?"));
db_bind_int(stmt, 0, output_status_in_db(utxo->status));
db_bind_int(stmt, 1, utxo->reserved_til);
db_bind_txid(stmt, 2, &utxo->outpoint.txid);
db_bind_int(stmt, 3, utxo->outpoint.n);
db_exec_prepared_v2(take(stmt));
}
bool wallet_reserve_utxo(struct wallet *w, struct utxo *utxo,
u32 current_height,
u32 reserve)
{
switch (utxo->status) {
case OUTPUT_STATE_SPENT:
return false;
case OUTPUT_STATE_AVAILABLE:
case OUTPUT_STATE_RESERVED:
break;
case OUTPUT_STATE_ANY:
abort();
}
/* We simple increase existing reservations, which DTRT if we unreserve */
if (utxo->reserved_til >= current_height)
utxo->reserved_til += reserve;
else
utxo->reserved_til = current_height + reserve;
utxo->status = OUTPUT_STATE_RESERVED;
db_set_utxo(w->db, utxo);
return true;
}
void wallet_unreserve_utxo(struct wallet *w, struct utxo *utxo,
u32 current_height,
u32 unreserve)
{
if (utxo->status != OUTPUT_STATE_RESERVED)
fatal("UTXO %s is not reserved",
type_to_string(tmpctx, struct bitcoin_outpoint,
&utxo->outpoint));
if (utxo->reserved_til <= current_height + unreserve) {
utxo->status = OUTPUT_STATE_AVAILABLE;
utxo->reserved_til = 0;
} else
utxo->reserved_til -= unreserve;
db_set_utxo(w->db, utxo);
}
static bool excluded(const struct utxo **excludes,
const struct utxo *utxo)
{
for (size_t i = 0; i < tal_count(excludes); i++) {
if (bitcoin_outpoint_eq(&excludes[i]->outpoint, &utxo->outpoint))
return true;
}
return false;
}
static bool deep_enough(u32 maxheight, const struct utxo *utxo,
u32 current_blockheight)
{
if (utxo->close_info
&& utxo->close_info->option_anchor_outputs) {
/* All option_anchor_output close_infos
* have a csv of at least 1 */
if (!utxo->blockheight)
return false;
u32 csv_free = *utxo->blockheight + utxo->close_info->csv - 1;
assert(csv_free >= *utxo->blockheight);
if (csv_free > current_blockheight)
return false;
}
/* If we require confirmations check that we have a
* confirmation height and that it is below the required
* maxheight (current_height - minconf) */
if (maxheight == 0)
return true;
if (!utxo->blockheight)
return false;
return *utxo->blockheight <= maxheight;
}
/* FIXME: Make this wallet_find_utxos, and branch and bound and I've
* left that to @niftynei to do, who actually read the paper! */
struct utxo *wallet_find_utxo(const tal_t *ctx, struct wallet *w,
unsigned current_blockheight,
struct amount_sat *amount_hint,
unsigned feerate_per_kw,
u32 maxheight,
const struct utxo **excludes)
{
struct db_stmt *stmt;
struct utxo *utxo;
stmt = db_prepare_v2(w->db, SQL("SELECT"
" prev_out_tx"
", prev_out_index"
", value"
", type"
", status"
", keyindex"
", channel_id"
", peer_id"
", commitment_point"
", option_anchor_outputs"
", confirmation_height"
", spend_height"
", scriptpubkey "
", reserved_til"
", csv_lock"
" FROM outputs"
" WHERE status = ?"
" OR (status = ? AND reserved_til <= ?)"
"ORDER BY RANDOM();"));
db_bind_int(stmt, 0, output_status_in_db(OUTPUT_STATE_AVAILABLE));
db_bind_int(stmt, 1, output_status_in_db(OUTPUT_STATE_RESERVED));
db_bind_u64(stmt, 2, current_blockheight);
/* FIXME: Use feerate + estimate of input cost to establish
* range for amount_hint */
db_query_prepared(stmt);
utxo = NULL;
while (!utxo && db_step(stmt)) {
utxo = wallet_stmt2output(ctx, stmt);
if (excluded(excludes, utxo)
|| !deep_enough(maxheight, utxo, current_blockheight))
utxo = tal_free(utxo);
}
tal_free(stmt);
return utxo;
}
bool wallet_add_onchaind_utxo(struct wallet *w,
const struct bitcoin_outpoint *outpoint,
const u8 *scriptpubkey,
u32 blockheight,
struct amount_sat amount,
const struct channel *channel,
/* NULL if option_static_remotekey */
const struct pubkey *commitment_point,
u32 csv_lock)
{
struct db_stmt *stmt;
stmt = db_prepare_v2(w->db, SQL("SELECT * from outputs WHERE "
"prev_out_tx=? AND prev_out_index=?"));
db_bind_txid(stmt, 0, &outpoint->txid);
db_bind_int(stmt, 1, outpoint->n);
db_query_prepared(stmt);
/* If we get a result, that means a clash. */
if (db_step(stmt)) {
db_col_ignore(stmt, "*");
tal_free(stmt);
return false;
}
tal_free(stmt);
stmt = db_prepare_v2(
w->db, SQL("INSERT INTO outputs ("
" prev_out_tx"
", prev_out_index"
", value"
", type"
", status"
", keyindex"
", channel_id"
", peer_id"
", commitment_point"
", option_anchor_outputs"
", confirmation_height"
", spend_height"
", scriptpubkey"
", csv_lock"
") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"));
db_bind_txid(stmt, 0, &outpoint->txid);
db_bind_int(stmt, 1, outpoint->n);
db_bind_amount_sat(stmt, 2, &amount);
db_bind_int(stmt, 3, wallet_output_type_in_db(p2wpkh));
db_bind_int(stmt, 4, OUTPUT_STATE_AVAILABLE);
db_bind_int(stmt, 5, 0);
db_bind_u64(stmt, 6, channel->dbid);
db_bind_node_id(stmt, 7, &channel->peer->id);
if (commitment_point)
db_bind_pubkey(stmt, 8, commitment_point);
else
db_bind_null(stmt, 8);
db_bind_int(stmt, 9, channel_has(channel, OPT_ANCHOR_OUTPUTS));
db_bind_int(stmt, 10, blockheight);
/* spendheight */
db_bind_null(stmt, 11);
db_bind_blob(stmt, 12, scriptpubkey, tal_bytelen(scriptpubkey));
db_bind_int(stmt, 13, csv_lock);
db_exec_prepared_v2(take(stmt));
return true;
}
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 + w->keyscan_gap; 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)) {
/* If we found a used key in the keyscan_gap we should
* remember that. */
if (i > bip32_max_index)
db_set_intvar(w->db, "bip32_max_index", i);
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)
{
struct db_stmt *stmt;
assert(chain->id == 0);
/* Create shachain */
shachain_init(&chain->chain);
stmt = db_prepare_v2(
wallet->db,
SQL("INSERT INTO shachains (min_index, num_valid) VALUES (?, 0);"));
db_bind_u64(stmt, 0, chain->chain.min_index);
db_exec_prepared_v2(stmt);
chain->id = db_last_insert_id_v2(stmt);
tal_free(stmt);
}
/* 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 secret *hash)
{
struct db_stmt *stmt;
u32 pos = count_trailing_zeroes(index);
struct sha256 s;
bool updated;
BUILD_ASSERT(sizeof(s) == sizeof(*hash));
memcpy(&s, hash, sizeof(s));
assert(index < SQLITE_MAX_UINT);
if (!shachain_add_hash(&chain->chain, index, &s)) {
return false;
}
stmt = db_prepare_v2(
wallet->db,
SQL("UPDATE shachains SET num_valid=?, min_index=? WHERE id=?"));
db_bind_int(stmt, 0, chain->chain.num_valid);
db_bind_u64(stmt, 1, index);
db_bind_u64(stmt, 2, chain->id);
db_exec_prepared_v2(take(stmt));
stmt = db_prepare_v2(wallet->db,
SQL("UPDATE shachain_known SET idx=?, hash=? "
"WHERE shachain_id=? AND pos=?"));
db_bind_u64(stmt, 0, index);
db_bind_secret(stmt, 1, hash);
db_bind_u64(stmt, 2, chain->id);
db_bind_int(stmt, 3, pos);
db_exec_prepared_v2(stmt);
updated = db_count_changes(stmt) == 1;
tal_free(stmt);
if (!updated) {
stmt = db_prepare_v2(
wallet->db, SQL("INSERT INTO shachain_known (shachain_id, "
"pos, idx, hash) VALUES (?, ?, ?, ?);"));
db_bind_u64(stmt, 0, chain->id);
db_bind_int(stmt, 1, pos);
db_bind_u64(stmt, 2, index);
db_bind_secret(stmt, 3, hash);
db_exec_prepared_v2(take(stmt));
}
return true;
}
static bool wallet_shachain_load(struct wallet *wallet, u64 id,
struct wallet_shachain *chain)
{
struct db_stmt *stmt;
chain->id = id;
shachain_init(&chain->chain);
/* Load shachain metadata */
stmt = db_prepare_v2(
wallet->db,
SQL("SELECT min_index, num_valid FROM shachains WHERE id=?"));
db_bind_u64(stmt, 0, id);
db_query_prepared(stmt);
if (!db_step(stmt)) {
tal_free(stmt);
return false;
}
chain->chain.min_index = db_col_u64(stmt, "min_index");
chain->chain.num_valid = db_col_u64(stmt, "num_valid");
tal_free(stmt);
/* Load shachain known entries */
stmt = db_prepare_v2(wallet->db,
SQL("SELECT idx, hash, pos FROM shachain_known "
"WHERE shachain_id=?"));
db_bind_u64(stmt, 0, id);
db_query_prepared(stmt);
while (db_step(stmt)) {
int pos = db_col_int(stmt, "pos");
chain->chain.known[pos].index = db_col_u64(stmt, "idx");
db_col_sha256(stmt, "hash", &chain->chain.known[pos].hash);
}
tal_free(stmt);
return true;
}
static struct peer *wallet_peer_load(struct wallet *w, const u64 dbid)
{
const char *addrstr;
struct peer *peer = NULL;
struct node_id id;
struct wireaddr_internal addr;
struct db_stmt *stmt;
stmt = db_prepare_v2(
w->db, SQL("SELECT id, node_id, address FROM peers WHERE id=?;"));
db_bind_u64(stmt, 0, dbid);
db_query_prepared(stmt);
if (!db_step(stmt))
goto done;
if (db_col_is_null(stmt, "node_id")) {
db_col_ignore(stmt, "address");
db_col_ignore(stmt, "id");
goto done;
}
db_col_node_id(stmt, "node_id", &id);
/* This can happen for peers last seen on Torv2! */
addrstr = db_col_strdup(tmpctx, stmt, "address");
if (!parse_wireaddr_internal(addrstr, &addr, chainparams_get_ln_port(chainparams),
false, false, true, true, NULL)) {
log_unusual(w->log, "Unparsable peer address %s: replacing",
addrstr);
parse_wireaddr_internal("127.0.0.1:1", &addr, chainparams_get_ln_port(chainparams),
false, false, true, true, NULL);
}
/* FIXME: save incoming in db! */
peer = new_peer(w->ld, db_col_u64(stmt, "id"), &id, &addr, false);
done:
tal_free(stmt);
return peer;
}
static struct bitcoin_signature *
wallet_htlc_sigs_load(const tal_t *ctx, struct wallet *w, u64 channelid,
bool option_anchor_outputs)
{
struct db_stmt *stmt;
struct bitcoin_signature *htlc_sigs = tal_arr(ctx, struct bitcoin_signature, 0);
stmt = db_prepare_v2(
w->db, SQL("SELECT signature FROM htlc_sigs WHERE channelid = ?"));
db_bind_u64(stmt, 0, channelid);
db_query_prepared(stmt);
while (db_step(stmt)) {
struct bitcoin_signature sig;
db_col_signature(stmt, "signature", &sig.s);
/* BOLT #3:
* ## HTLC-Timeout and HTLC-Success Transactions
*...
* * if `option_anchors` applies to this commitment
* transaction, `SIGHASH_SINGLE|SIGHASH_ANYONECANPAY` is
* used as described in [BOLT #5]
*/
if (option_anchor_outputs)
sig.sighash_type = SIGHASH_SINGLE|SIGHASH_ANYONECANPAY;
else
sig.sighash_type = SIGHASH_ALL;
tal_arr_expand(&htlc_sigs, sig);
}
tal_free(stmt);
log_debug(w->log, "Loaded %zu HTLC signatures from DB",
tal_count(htlc_sigs));
return htlc_sigs;
}
bool wallet_remote_ann_sigs_load(const tal_t *ctx, struct wallet *w, u64 id,
secp256k1_ecdsa_signature **remote_ann_node_sig,
secp256k1_ecdsa_signature **remote_ann_bitcoin_sig)
{
struct db_stmt *stmt;
bool res;
stmt = db_prepare_v2(
w->db, SQL("SELECT remote_ann_node_sig, remote_ann_bitcoin_sig"
" FROM channels WHERE id = ?"));
db_bind_u64(stmt, 0, id);
db_query_prepared(stmt);
res = db_step(stmt);
/* This must succeed, since we know the channel exists */
assert(res);
/* if only one sig exists, forget the sig and hope peer send new ones*/
if (db_col_is_null(stmt, "remote_ann_node_sig")
|| db_col_is_null(stmt, "remote_ann_bitcoin_sig")) {
db_col_ignore(stmt, "remote_ann_bitcoin_sig");
*remote_ann_node_sig = *remote_ann_bitcoin_sig = NULL;
tal_free(stmt);
return true;
}
/* the case left over is both sigs exist */
*remote_ann_node_sig = tal(ctx, secp256k1_ecdsa_signature);
*remote_ann_bitcoin_sig = tal(ctx, secp256k1_ecdsa_signature);
if (!db_col_signature(stmt, "remote_ann_node_sig", *remote_ann_node_sig))
goto fail;
if (!db_col_signature(stmt, "remote_ann_bitcoin_sig", *remote_ann_bitcoin_sig))
goto fail;
tal_free(stmt);
return true;
fail:
*remote_ann_node_sig = tal_free(*remote_ann_node_sig);
*remote_ann_bitcoin_sig = tal_free(*remote_ann_bitcoin_sig);
tal_free(stmt);
return false;
}
static struct fee_states *wallet_channel_fee_states_load(struct wallet *w,
const u64 id,
enum side opener)
{
struct fee_states *fee_states;
struct db_stmt *stmt;
stmt = db_prepare_v2(w->db, SQL("SELECT hstate, feerate_per_kw FROM channel_feerates WHERE channel_id = ?"));
db_bind_u64(stmt, 0, id);
db_query_prepared(stmt);
/* Start with blank slate. */
fee_states = new_fee_states(w, opener, NULL);
while (db_step(stmt)) {
enum htlc_state hstate = htlc_state_in_db(db_col_int(stmt, "hstate"));
u32 feerate = db_col_int(stmt, "feerate_per_kw");
if (fee_states->feerate[hstate] != NULL) {
log_broken(w->log,
"duplicate channel_feerates for %s id %"PRIu64,
htlc_state_name(hstate), id);
fee_states = tal_free(fee_states);
break;
}
fee_states->feerate[hstate] = tal_dup(fee_states, u32, &feerate);
}
tal_free(stmt);
if (fee_states && !fee_states_valid(fee_states, opener)) {
log_broken(w->log,
"invalid channel_feerates for id %"PRIu64, id);
fee_states = tal_free(fee_states);
}
return fee_states;
}
static struct height_states *wallet_channel_height_states_load(struct wallet *w,
const u64 id,
enum side opener)
{
struct height_states *states;
struct db_stmt *stmt;
stmt = db_prepare_v2(w->db, SQL("SELECT hstate, blockheight FROM channel_blockheights WHERE channel_id = ?"));
db_bind_u64(stmt, 0, id);
db_query_prepared(stmt);
/* Start with blank slate. */
states = new_height_states(w, opener, NULL);
while (db_step(stmt)) {
enum htlc_state hstate = htlc_state_in_db(db_col_int(stmt, "hstate"));
u32 blockheight = db_col_int(stmt, "blockheight");
if (states->height[hstate] != NULL) {
log_broken(w->log,
"duplicate channel_blockheights for %s id %"PRIu64,
htlc_state_name(hstate), id);
states = tal_free(states);
break;
}
states->height[hstate] = tal_dup(states, u32, &blockheight);
}
tal_free(stmt);