-
Notifications
You must be signed in to change notification settings - Fork 906
/
libhsmd.c
1780 lines (1547 loc) · 60.7 KB
/
libhsmd.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/crypto/hkdf_sha256/hkdf_sha256.h>
#include <ccan/tal/str/str.h>
#include <common/bolt12_merkle.h>
#include <common/hash_u5.h>
#include <common/key_derive.h>
#include <common/lease_rates.h>
#include <common/type_to_string.h>
#include <hsmd/capabilities.h>
#include <hsmd/libhsmd.h>
#include <inttypes.h>
#include <secp256k1_ecdh.h>
#include <secp256k1_schnorrsig.h>
#include <sodium/utils.h>
#include <wally_psbt.h>
#if DEVELOPER
/* If they specify --dev-force-privkey it ends up in here. */
struct privkey *dev_force_privkey;
/* If they specify --dev-force-bip32-seed it ends up in here. */
struct secret *dev_force_bip32_seed;
#endif
/*~ Nobody will ever find it here! hsm_secret is our root secret, the bip32
* tree, bolt12 payer_id keys and derived_secret are derived from that, and
* cached here. */
struct {
struct secret hsm_secret;
struct ext_key bip32;
struct secret bolt12;
struct secret derived_secret;
} secretstuff;
/* Have we initialized the secretstuff? */
bool initialized = false;
struct hsmd_client *hsmd_client_new_main(const tal_t *ctx, u64 capabilities,
void *extra)
{
struct hsmd_client *c = tal(ctx, struct hsmd_client);
c->dbid = 0;
c->capabilities = capabilities;
c->extra = extra;
return c;
}
struct hsmd_client *hsmd_client_new_peer(const tal_t *ctx, u64 capabilities,
u64 dbid,
const struct node_id *peer_id,
void *extra)
{
struct hsmd_client *c = tal(ctx, struct hsmd_client);
c->dbid = dbid;
c->capabilities = capabilities;
c->id = *peer_id;
c->extra = extra;
return c;
}
/*~ This routine checks that a client is allowed to call the handler. */
bool hsmd_check_client_capabilities(struct hsmd_client *client,
enum hsmd_wire t)
{
/*~ Here's a useful trick: enums in C are not real types, they're
* semantic sugar sprinkled over an int, bascally (in fact, older
* versions of gcc used to convert the values ints in the parser!).
*
* But GCC will do one thing for us: if we have a switch statement
* with a controlling expression which is an enum, it will warn us
* if a declared enum value is *not* handled in the switch, eg:
* enumeration value ‘FOOBAR’ not handled in switch [-Werror=switch]
*
* This only works if there's no 'default' label, which is sometimes
* hard, as we *can* have non-enum values in our enum. But the tradeoff
* is worth it so the compiler tells us everywhere we have to fix when
* we add a new enum identifier!
*/
switch (t) {
case WIRE_HSMD_ECDH_REQ:
return (client->capabilities & HSM_CAP_ECDH) != 0;
case WIRE_HSMD_CANNOUNCEMENT_SIG_REQ:
case WIRE_HSMD_CUPDATE_SIG_REQ:
case WIRE_HSMD_NODE_ANNOUNCEMENT_SIG_REQ:
return (client->capabilities & HSM_CAP_SIGN_GOSSIP) != 0;
case WIRE_HSMD_SIGN_DELAYED_PAYMENT_TO_US:
case WIRE_HSMD_SIGN_REMOTE_HTLC_TO_US:
case WIRE_HSMD_SIGN_PENALTY_TO_US:
case WIRE_HSMD_SIGN_LOCAL_HTLC_TX:
return (client->capabilities & HSM_CAP_SIGN_ONCHAIN_TX) != 0;
case WIRE_HSMD_GET_PER_COMMITMENT_POINT:
case WIRE_HSMD_CHECK_FUTURE_SECRET:
case WIRE_HSMD_READY_CHANNEL:
return (client->capabilities & HSM_CAP_COMMITMENT_POINT) != 0;
case WIRE_HSMD_SIGN_REMOTE_COMMITMENT_TX:
case WIRE_HSMD_SIGN_REMOTE_HTLC_TX:
case WIRE_HSMD_VALIDATE_COMMITMENT_TX:
case WIRE_HSMD_VALIDATE_REVOCATION:
return (client->capabilities & HSM_CAP_SIGN_REMOTE_TX) != 0;
case WIRE_HSMD_SIGN_MUTUAL_CLOSE_TX:
return (client->capabilities & HSM_CAP_SIGN_CLOSING_TX) != 0;
case WIRE_HSMD_SIGN_OPTION_WILL_FUND_OFFER:
return (client->capabilities & HSM_CAP_SIGN_WILL_FUND_OFFER) != 0;
case WIRE_HSMD_INIT:
case WIRE_HSMD_NEW_CHANNEL:
case WIRE_HSMD_CLIENT_HSMFD:
case WIRE_HSMD_SIGN_WITHDRAWAL:
case WIRE_HSMD_SIGN_INVOICE:
case WIRE_HSMD_SIGN_COMMITMENT_TX:
case WIRE_HSMD_GET_CHANNEL_BASEPOINTS:
case WIRE_HSMD_DEV_MEMLEAK:
case WIRE_HSMD_SIGN_MESSAGE:
case WIRE_HSMD_GET_OUTPUT_SCRIPTPUBKEY:
case WIRE_HSMD_SIGN_BOLT12:
case WIRE_HSMD_DERIVE_SECRET:
return (client->capabilities & HSM_CAP_MASTER) != 0;
/*~ These are messages sent by the HSM so we should never receive them. */
/* FIXME: Since we autogenerate these, we should really generate separate
* enums for replies to avoid this kind of clutter! */
case WIRE_HSMD_ECDH_RESP:
case WIRE_HSMD_CANNOUNCEMENT_SIG_REPLY:
case WIRE_HSMD_CUPDATE_SIG_REPLY:
case WIRE_HSMD_CLIENT_HSMFD_REPLY:
case WIRE_HSMD_NEW_CHANNEL_REPLY:
case WIRE_HSMD_READY_CHANNEL_REPLY:
case WIRE_HSMD_NODE_ANNOUNCEMENT_SIG_REPLY:
case WIRE_HSMD_SIGN_WITHDRAWAL_REPLY:
case WIRE_HSMD_SIGN_INVOICE_REPLY:
case WIRE_HSMD_INIT_REPLY_V1:
case WIRE_HSMD_INIT_REPLY_V2:
case WIRE_HSMSTATUS_CLIENT_BAD_REQUEST:
case WIRE_HSMD_SIGN_COMMITMENT_TX_REPLY:
case WIRE_HSMD_VALIDATE_COMMITMENT_TX_REPLY:
case WIRE_HSMD_VALIDATE_REVOCATION_REPLY:
case WIRE_HSMD_SIGN_TX_REPLY:
case WIRE_HSMD_SIGN_OPTION_WILL_FUND_OFFER_REPLY:
case WIRE_HSMD_GET_PER_COMMITMENT_POINT_REPLY:
case WIRE_HSMD_CHECK_FUTURE_SECRET_REPLY:
case WIRE_HSMD_GET_CHANNEL_BASEPOINTS_REPLY:
case WIRE_HSMD_DEV_MEMLEAK_REPLY:
case WIRE_HSMD_SIGN_MESSAGE_REPLY:
case WIRE_HSMD_GET_OUTPUT_SCRIPTPUBKEY_REPLY:
case WIRE_HSMD_SIGN_BOLT12_REPLY:
case WIRE_HSMD_DERIVE_SECRET_REPLY:
break;
}
return false;
}
/*~ ccan/compiler.h defines PRINTF_FMT as the gcc compiler hint so it will
* check that fmt and other trailing arguments really are the correct type.
*/
/* This function is used to format an error message before passing it
* to the library user specified hsmd_status_bad_request */
static u8 *hsmd_status_bad_request_fmt(struct hsmd_client *client,
const u8 *msg, const char *fmt, ...)
PRINTF_FMT(3, 4);
static u8 *hsmd_status_bad_request_fmt(struct hsmd_client *client,
const u8 *msg, const char *fmt, ...)
{
va_list ap;
char *str;
va_start(ap, fmt);
str = tal_fmt(tmpctx, fmt, ap);
va_end(ap);
return hsmd_status_bad_request(client, msg, str);
}
/* Convenience wrapper for when we simply can't parse. */
static u8 *hsmd_status_malformed_request(struct hsmd_client *c, const u8 *msg_in)
{
return hsmd_status_bad_request(c, msg_in, "could not parse request");
}
/*~ This returns the secret and/or public key for this node. */
static void node_key(struct privkey *node_privkey, struct pubkey *node_id)
{
u32 salt = 0;
struct privkey unused_s;
struct pubkey unused_k;
/* If caller specifies NULL, they don't want the results. */
if (node_privkey == NULL)
node_privkey = &unused_s;
if (node_id == NULL)
node_id = &unused_k;
/*~ So, there is apparently a 1 in 2^127 chance that a random value is
* not a valid private key, so this never actually loops. */
do {
/*~ ccan/crypto/hkdf_sha256 implements RFC5869 "Hardened Key
* Derivation Functions". That means that if a derived key
* leaks somehow, the other keys are not compromised. */
hkdf_sha256(node_privkey, sizeof(*node_privkey),
&salt, sizeof(salt),
&secretstuff.hsm_secret,
sizeof(secretstuff.hsm_secret),
"nodeid", 6);
salt++;
} while (!secp256k1_ec_pubkey_create(secp256k1_ctx, &node_id->pubkey,
node_privkey->secret.data));
#if DEVELOPER
/* In DEVELOPER mode, we can override with --dev-force-privkey */
if (dev_force_privkey) {
*node_privkey = *dev_force_privkey;
if (!secp256k1_ec_pubkey_create(secp256k1_ctx, &node_id->pubkey,
node_privkey->secret.data))
hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Failed to derive pubkey for dev_force_privkey");
}
#endif
}
/*~ This returns the secret key for this node. */
static void node_schnorrkey(secp256k1_keypair *node_keypair)
{
struct privkey node_privkey;
node_key(&node_privkey, NULL);
if (secp256k1_keypair_create(secp256k1_ctx, node_keypair,
node_privkey.secret.data) != 1)
hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Failed to derive keypair");
}
/*~ This secret is the basis for all per-channel secrets: the per-channel seeds
* will be generated by mixing in the dbid and the peer node_id. */
static void hsm_channel_secret_base(struct secret *channel_seed_base)
{
hkdf_sha256(channel_seed_base, sizeof(struct secret), NULL, 0,
&secretstuff.hsm_secret, sizeof(secretstuff.hsm_secret),
/*~ Initially, we didn't support multiple channels per
* peer at all: a channel had to be completely forgotten
* before another could exist. That was slightly relaxed,
* but the phrase "peer seed" is wired into the seed
* generation here, so we need to keep it that way for
* existing clients, rather than using "channel seed". */
"peer seed", strlen("peer seed"));
}
/* This will derive pseudorandom secret Key from a derived key */
static u8 *handle_derive_secret(struct hsmd_client *c, const u8 *msg_in)
{
u8 *info;
struct secret secret;
if (!fromwire_hsmd_derive_secret(tmpctx, msg_in, &info))
return hsmd_status_malformed_request(c, msg_in);
hkdf_sha256(&secret, sizeof(struct secret), NULL, 0,
&secretstuff.derived_secret, sizeof(secretstuff.derived_secret),
info, tal_bytelen(info));
return towire_hsmd_derive_secret_reply(NULL, &secret);
}
/*~ This gets the seed for this particular channel. */
static void get_channel_seed(const struct node_id *peer_id, u64 dbid,
struct secret *channel_seed)
{
struct secret channel_base;
u8 input[sizeof(peer_id->k) + sizeof(dbid)];
/*~ Again, "per-peer" should be "per-channel", but Hysterical Raisins */
const char *info = "per-peer seed";
/*~ We use the DER encoding of the pubkey, because it's platform
* independent. Since the dbid is unique, however, it's completely
* unnecessary, but again, existing users can't be broken. */
/* FIXME: lnd has a nicer BIP32 method for deriving secrets which we
* should migrate to. */
hsm_channel_secret_base(&channel_base);
memcpy(input, peer_id->k, sizeof(peer_id->k));
BUILD_ASSERT(sizeof(peer_id->k) == PUBKEY_CMPR_LEN);
/*~ For all that talk about platform-independence, note that this
* field is endian-dependent! But let's face it, little-endian won.
* In related news, we don't support EBCDIC or middle-endian. */
memcpy(input + PUBKEY_CMPR_LEN, &dbid, sizeof(dbid));
hkdf_sha256(channel_seed, sizeof(*channel_seed),
input, sizeof(input),
&channel_base, sizeof(channel_base),
info, strlen(info));
}
/* ~This stub implementation is overriden by fully validating signers
* that need to manage per-channel state. */
static u8 *handle_new_channel(struct hsmd_client *c, const u8 *msg_in)
{
struct node_id peer_id;
u64 dbid;
if (!fromwire_hsmd_new_channel(msg_in, &peer_id, &dbid))
return hsmd_status_malformed_request(c, msg_in);
/* Stub implementation */
return towire_hsmd_new_channel_reply(NULL);
}
static bool mem_is_zero(const void *mem, size_t len)
{
size_t i;
for (i = 0; i < len; ++i)
if (((const unsigned char *)mem)[i])
return false;
return true;
}
/* ~This stub implementation is overriden by fully validating signers
* that need the unchanging channel parameters. */
static u8 *handle_ready_channel(struct hsmd_client *c, const u8 *msg_in)
{
bool is_outbound;
struct amount_sat channel_value;
struct amount_msat push_value;
struct bitcoin_txid funding_txid;
u16 funding_txout;
u16 local_to_self_delay;
u8 *local_shutdown_script;
u32 *local_shutdown_wallet_index;
struct basepoints remote_basepoints;
struct pubkey remote_funding_pubkey;
u16 remote_to_self_delay;
u8 *remote_shutdown_script;
struct amount_msat value_msat;
struct channel_type *channel_type;
if (!fromwire_hsmd_ready_channel(tmpctx, msg_in, &is_outbound,
&channel_value, &push_value, &funding_txid,
&funding_txout, &local_to_self_delay,
&local_shutdown_script,
&local_shutdown_wallet_index,
&remote_basepoints,
&remote_funding_pubkey,
&remote_to_self_delay,
&remote_shutdown_script,
&channel_type))
return hsmd_status_malformed_request(c, msg_in);
/* Stub implementation */
/* Fail fast if any values are uninitialized or obviously wrong. */
assert(amount_sat_greater(channel_value, AMOUNT_SAT(0)));
assert(amount_sat_to_msat(&value_msat, channel_value));
assert(amount_msat_less_eq(push_value, value_msat));
assert(!mem_is_zero(&funding_txid, sizeof(funding_txid)));
assert(local_to_self_delay > 0);
assert(remote_to_self_delay > 0);
return towire_hsmd_ready_channel_reply(NULL);
}
/*~ For almost every wallet tx we use the BIP32 seed, but not for onchain
* unilateral closes from a peer: they (may) have an output to us using a
* public key based on the channel basepoints. It's a bit spammy to spend
* those immediately just to make the wallet simpler, and we didn't appreciate
* the problem when we designed the protocol for commitment transaction keys.
*
* So we store just enough about the channel it came from (which may be
* long-gone) to regenerate the keys here. That has the added advantage that
* the secrets themselves stay within the HSM. */
static void hsm_unilateral_close_privkey(struct privkey *dst,
struct unilateral_close_info *info)
{
struct secret channel_seed;
struct basepoints basepoints;
struct secrets secrets;
get_channel_seed(&info->peer_id, info->channel_id, &channel_seed);
derive_basepoints(&channel_seed, NULL, &basepoints, &secrets, NULL);
/* BOLT #3:
*
* If `option_static_remotekey` or `option_anchors` is
* negotiated, the `remotepubkey` is simply the remote node's
* `payment_basepoint`, otherwise it is calculated as above using the
* remote node's `payment_basepoint`.
*/
/* In our UTXO representation, this is indicated by a NULL
* commitment_point. */
if (!info->commitment_point)
dst->secret = secrets.payment_basepoint_secret;
else if (!derive_simple_privkey(&secrets.payment_basepoint_secret,
&basepoints.payment,
info->commitment_point,
dst)) {
hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Deriving unilateral_close_privkey");
}
}
/*~ Get the keys for this given BIP32 index: if privkey is NULL, we
* don't fill it in. */
static void bitcoin_key(struct privkey *privkey, struct pubkey *pubkey,
u32 index)
{
struct ext_key ext;
struct privkey unused_priv;
if (privkey == NULL)
privkey = &unused_priv;
if (index >= BIP32_INITIAL_HARDENED_CHILD)
hsmd_status_failed(STATUS_FAIL_MASTER_IO, "Index %u too great",
index);
/*~ This uses libwally, which doesn't dovetail directly with
* libsecp256k1 even though it, too, uses it internally. */
if (bip32_key_from_parent(&secretstuff.bip32, index,
BIP32_FLAG_KEY_PRIVATE, &ext) != WALLY_OK)
hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
"BIP32 of %u failed", index);
/* libwally says: The private key with prefix byte 0; remove it
* for libsecp256k1. */
memcpy(privkey->secret.data, ext.priv_key+1, 32);
if (!secp256k1_ec_pubkey_create(secp256k1_ctx, &pubkey->pubkey,
privkey->secret.data))
hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
"BIP32 pubkey %u create failed", index);
}
/* This gets the bitcoin private key needed to spend from our wallet */
static void hsm_key_for_utxo(struct privkey *privkey, struct pubkey *pubkey,
const struct utxo *utxo)
{
if (utxo->close_info != NULL) {
/* This is a their_unilateral_close/to-us output, so
* we need to derive the secret the long way */
hsmd_status_debug("Unilateral close output, deriving secrets");
hsm_unilateral_close_privkey(privkey, utxo->close_info);
pubkey_from_privkey(privkey, pubkey);
hsmd_status_debug("Derived public key %s from unilateral close",
type_to_string(tmpctx, struct pubkey, pubkey));
} else {
/* Simple case: just get derive via HD-derivation */
bitcoin_key(privkey, pubkey, utxo->keyindex);
}
}
/* Find our inputs by the pubkey associated with the inputs, and
* add a partial sig for each */
static void sign_our_inputs(struct utxo **utxos, struct wally_psbt *psbt)
{
for (size_t i = 0; i < tal_count(utxos); i++) {
struct utxo *utxo = utxos[i];
for (size_t j = 0; j < psbt->num_inputs; j++) {
struct privkey privkey;
struct pubkey pubkey;
if (!wally_tx_input_spends(&psbt->tx->inputs[j],
&utxo->outpoint))
continue;
hsm_key_for_utxo(&privkey, &pubkey, utxo);
/* This line is basically the entire reason we have
* to iterate through to match the psbt input
* to the UTXO -- otherwise we would just
* call wally_psbt_sign for every utxo privkey
* and be done with it. We can't do that though
* because any UTXO that's derived from channel_info
* requires the HSM to find the pubkey, and we
* skip doing that until now as a bit of a reduction
* of complexity in the calling code */
psbt_input_add_pubkey(psbt, j, &pubkey);
/* It's actually a P2WSH in this case. */
if (utxo->close_info && utxo->close_info->option_anchor_outputs) {
const u8 *wscript
= anchor_to_remote_redeem(tmpctx,
&pubkey,
utxo->close_info->csv);
psbt_input_set_witscript(psbt, j, wscript);
psbt_input_set_wit_utxo(psbt, j,
scriptpubkey_p2wsh(psbt, wscript),
utxo->amount);
}
tal_wally_start();
if (wally_psbt_sign(psbt, privkey.secret.data,
sizeof(privkey.secret.data),
EC_FLAG_GRIND_R) != WALLY_OK) {
tal_wally_end(psbt);
hsmd_status_broken(
"Received wally_err attempting to "
"sign utxo with key %s. PSBT: %s",
type_to_string(tmpctx, struct pubkey,
&pubkey),
type_to_string(tmpctx, struct wally_psbt,
psbt));
}
tal_wally_end(psbt);
}
}
}
/*~ This covers several cases where onchaind is creating a transaction which
* sends funds to our internal wallet. */
/* FIXME: Derive output address for this client, and check it here! */
static u8 *handle_sign_to_us_tx(struct hsmd_client *c, const u8 *msg_in,
struct bitcoin_tx *tx,
const struct privkey *privkey,
const u8 *wscript,
enum sighash_type sighash_type)
{
struct bitcoin_signature sig;
struct pubkey pubkey;
if (!pubkey_from_privkey(privkey, &pubkey))
return hsmd_status_bad_request(c, msg_in,
"bad pubkey_from_privkey");
if (tx->wtx->num_inputs != 1)
return hsmd_status_bad_request(c, msg_in, "bad txinput count");
sign_tx_input(tx, 0, NULL, wscript, privkey, &pubkey, sighash_type, &sig);
return towire_hsmd_sign_tx_reply(NULL, &sig);
}
/*~ lightningd asks us to sign a message. I tweeted the spec
* in https://twitter.com/rusty_twit/status/1182102005914800128:
*
* @roasbeef & @bitconner point out that #lnd algo is:
* zbase32(SigRec(SHA256(SHA256("Lightning Signed Message:" + msg)))).
* zbase32 from https://philzimmermann.com/docs/human-oriented-base-32-encoding.txt
* and SigRec has first byte 31 + recovery id, followed by 64 byte sig. #specinatweet
*/
static u8 *handle_sign_message(struct hsmd_client *c, const u8 *msg_in)
{
u8 *msg;
struct sha256_ctx sctx = SHA256_INIT;
struct sha256_double shad;
secp256k1_ecdsa_recoverable_signature rsig;
struct privkey node_pkey;
if (!fromwire_hsmd_sign_message(tmpctx, msg_in, &msg))
return hsmd_status_malformed_request(c, msg_in);
/* Prefixing by a known string means we'll never be convinced
* to sign some gossip message, etc. */
sha256_update(&sctx, "Lightning Signed Message:",
strlen("Lightning Signed Message:"));
sha256_update(&sctx, msg, tal_count(msg));
sha256_double_done(&sctx, &shad);
node_key(&node_pkey, NULL);
/*~ By no small coincidence, this libsecp routine uses the exact
* recovery signature format mandated by BOLT 11. */
if (!secp256k1_ecdsa_sign_recoverable(secp256k1_ctx, &rsig,
shad.sha.u.u8,
node_pkey.secret.data,
NULL, NULL)) {
return hsmd_status_bad_request(c, msg_in, "Failed to sign message");
}
return towire_hsmd_sign_message_reply(NULL, &rsig);
}
/*~ lightningd asks us to sign a liquidity ad offer */
static u8 *handle_sign_option_will_fund_offer(struct hsmd_client *c,
const u8 *msg_in)
{
struct pubkey funding_pubkey;
u32 lease_expiry, channel_fee_base_max_msat;
u16 channel_fee_max_ppt;
struct sha256 sha;
secp256k1_ecdsa_signature sig;
struct privkey node_pkey;
if (!fromwire_hsmd_sign_option_will_fund_offer(msg_in,
&funding_pubkey,
&lease_expiry,
&channel_fee_base_max_msat,
&channel_fee_max_ppt))
return hsmd_status_malformed_request(c, msg_in);
lease_rates_get_commitment(&funding_pubkey, lease_expiry,
channel_fee_base_max_msat,
channel_fee_max_ppt,
&sha);
node_key(&node_pkey, NULL);
if (!secp256k1_ecdsa_sign(secp256k1_ctx, &sig,
sha.u.u8,
node_pkey.secret.data,
NULL, NULL))
return hsmd_status_bad_request(c, msg_in,
"Failed to sign message");
return towire_hsmd_sign_option_will_fund_offer_reply(NULL, &sig);
}
/*~ lightningd asks us to sign a bolt12 (e.g. offer). */
static u8 *handle_sign_bolt12(struct hsmd_client *c, const u8 *msg_in)
{
char *messagename, *fieldname;
struct sha256 merkle, sha;
struct bip340sig sig;
secp256k1_keypair kp;
u8 *publictweak;
if (!fromwire_hsmd_sign_bolt12(tmpctx, msg_in,
&messagename, &fieldname, &merkle,
&publictweak))
return hsmd_status_malformed_request(c, msg_in);
sighash_from_merkle(messagename, fieldname, &merkle, &sha);
if (!publictweak) {
node_schnorrkey(&kp);
} else {
/* If we're tweaking key, we use bolt12 key */
struct privkey tweakedkey;
struct pubkey bolt12;
struct sha256 tweak;
if (secp256k1_ec_pubkey_create(secp256k1_ctx, &bolt12.pubkey,
secretstuff.bolt12.data) != 1)
hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Could derive bolt12 public key.");
payer_key_tweak(&bolt12, publictweak, tal_bytelen(publictweak),
&tweak);
tweakedkey.secret = secretstuff.bolt12;
if (secp256k1_ec_seckey_tweak_add(secp256k1_ctx,
tweakedkey.secret.data,
tweak.u.u8) != 1)
hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Could tweak bolt12 key.");
if (secp256k1_keypair_create(secp256k1_ctx, &kp,
tweakedkey.secret.data) != 1)
hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Failed to derive bolt12 keypair");
}
if (!secp256k1_schnorrsig_sign32(secp256k1_ctx, sig.u8,
sha.u.u8,
&kp,
NULL)) {
return hsmd_status_bad_request_fmt(c, msg_in,
"Failed to sign bolt12");
}
return towire_hsmd_sign_bolt12_reply(NULL, &sig);
}
/*~ Lightning invoices, defined by BOLT 11, are signed. This has been
* surprisingly controversial; it means a node needs to be online to create
* invoices. However, it seems clear to me that in a world without
* intermedaries you need proof that you have received an offer (the
* signature), as well as proof that you've paid it (the preimage). */
static u8 *handle_sign_invoice(struct hsmd_client *c, const u8 *msg_in)
{
/*~ We make up a 'u5' type to represent BOLT11's 5-bits-per-byte
* format: it's only for human consumption, as typedefs are almost
* entirely transparent to the C compiler. */
u5 *u5bytes;
u8 *hrpu8;
char *hrp;
struct sha256 sha;
secp256k1_ecdsa_recoverable_signature rsig;
struct hash_u5 hu5;
struct privkey node_pkey;
if (!fromwire_hsmd_sign_invoice(tmpctx, msg_in, &u5bytes, &hrpu8))
return hsmd_status_malformed_request(c, msg_in);
/* BOLT #11:
*
* A writer... MUST set `signature` to a valid 512-bit
* secp256k1 signature of the SHA2 256-bit hash of the
* human-readable part, represented as UTF-8 bytes,
* concatenated with the data part (excluding the signature)
* with 0 bits appended to pad the data to the next byte
* boundary, with a trailing byte containing the recovery ID
* (0, 1, 2, or 3).
*/
/* FIXME: Check invoice! */
/*~ tal_dup_arr() does what you'd expect: allocate an array by copying
* another; the cast is needed because the hrp is a 'char' array, not
* a 'u8' (unsigned char) as it's the "human readable" part.
*
* The final arg of tal_dup_arr() is how many extra bytes to allocate:
* it's so often zero that I've thought about dropping the argument, but
* in cases like this (adding a NUL terminator) it's perfect. */
hrp = tal_dup_arr(tmpctx, char, (char *)hrpu8, tal_count(hrpu8), 1);
hrp[tal_count(hrpu8)] = '\0';
hash_u5_init(&hu5, hrp);
hash_u5(&hu5, u5bytes, tal_count(u5bytes));
hash_u5_done(&hu5, &sha);
node_key(&node_pkey, NULL);
/*~ By no small coincidence, this libsecp routine uses the exact
* recovery signature format mandated by BOLT 11. */
if (!secp256k1_ecdsa_sign_recoverable(secp256k1_ctx, &rsig,
(const u8 *)&sha,
node_pkey.secret.data,
NULL, NULL)) {
return hsmd_status_bad_request_fmt(c, msg_in,
"Failed to sign invoice");
}
return towire_hsmd_sign_invoice_reply(NULL, &rsig);
}
/*~ This gets the basepoints for a channel; it's not private information really
* (we tell the peer this to establish a channel, as it sets up the keys used
* for each transaction).
*
* Note that this is asked by lightningd, so it tells us what channels it wants.
*/
static u8 *handle_get_channel_basepoints(struct hsmd_client *c,
const u8 *msg_in)
{
struct node_id peer_id;
u64 dbid;
struct secret seed;
struct basepoints basepoints;
struct pubkey funding_pubkey;
if (!fromwire_hsmd_get_channel_basepoints(msg_in, &peer_id, &dbid))
return hsmd_status_malformed_request(c, msg_in);
get_channel_seed(&peer_id, dbid, &seed);
derive_basepoints(&seed, &funding_pubkey, &basepoints, NULL, NULL);
return towire_hsmd_get_channel_basepoints_reply(NULL, &basepoints,
&funding_pubkey);
}
/*~ The client has asked us to extract the shared secret from an EC Diffie
* Hellman token. This doesn't leak any information, but requires the private
* key, so the hsmd performs it. It's used to set up an encryption key for the
* connection handshaking (BOLT #8) and for the onion wrapping (BOLT #4). */
static u8 *handle_ecdh(struct hsmd_client *c, const u8 *msg_in)
{
struct privkey privkey;
struct pubkey point;
struct secret ss;
if (!fromwire_hsmd_ecdh_req(msg_in, &point))
return hsmd_status_malformed_request(c, msg_in);
/*~ We simply use the secp256k1_ecdh function: if privkey.secret.data is invalid,
* we kill them for bad randomness (~1 in 2^127 if privkey.secret.data is random) */
node_key(&privkey, NULL);
if (secp256k1_ecdh(secp256k1_ctx, ss.data, &point.pubkey,
privkey.secret.data, NULL, NULL) != 1) {
return hsmd_status_bad_request_fmt(c, msg_in,
"secp256k1_ecdh fail");
}
/*~ In the normal case, we return the shared secret, and then read
* the next msg. */
return towire_hsmd_ecdh_resp(NULL, &ss);
}
/*~ This is used when the remote peer claims to have knowledge of future
* commitment states (option_data_loss_protect in the spec) which means we've
* been restored from backup or something, and may have already revealed
* secrets. We carefully check that this is true, here. */
static u8 *handle_check_future_secret(struct hsmd_client *c, const u8 *msg_in)
{
struct secret channel_seed;
struct sha256 shaseed;
u64 n;
struct secret secret, suggested;
if (!fromwire_hsmd_check_future_secret(msg_in, &n, &suggested))
return hsmd_status_malformed_request(c, msg_in);
get_channel_seed(&c->id, c->dbid, &channel_seed);
if (!derive_shaseed(&channel_seed, &shaseed))
return hsmd_status_bad_request_fmt(c, msg_in,
"bad derive_shaseed");
if (!per_commit_secret(&shaseed, &secret, n))
return hsmd_status_bad_request_fmt(
c, msg_in, "bad commit secret #%" PRIu64, n);
/*~ Note the special secret_eq_consttime: we generate foo_eq for many
* types using ccan/structeq, but not 'struct secret' because any
* comparison risks leaking information about the secret if it is
* timing dependent. */
return towire_hsmd_check_future_secret_reply(
NULL, secret_eq_consttime(&secret, &suggested));
}
static u8 *handle_get_output_scriptpubkey(struct hsmd_client *c,
const u8 *msg_in)
{
struct pubkey pubkey;
struct privkey privkey;
struct unilateral_close_info info;
u8 *scriptPubkey;
info.commitment_point = NULL;
if (!fromwire_hsmd_get_output_scriptpubkey(tmpctx, msg_in,
&info.channel_id,
&info.peer_id,
&info.commitment_point))
return hsmd_status_malformed_request(c, msg_in);
hsm_unilateral_close_privkey(&privkey, &info);
pubkey_from_privkey(&privkey, &pubkey);
scriptPubkey = scriptpubkey_p2wpkh(tmpctx, &pubkey);
return towire_hsmd_get_output_scriptpubkey_reply(NULL,
scriptPubkey);
}
/*~ The specific routine to sign the channel_announcement message. This is
* defined in BOLT #7, and requires *two* signatures: one from this node's key
* (to prove it's from us), and one from the bitcoin key used to create the
* funding transaction (to prove we own the output). */
static u8 *handle_cannouncement_sig(struct hsmd_client *c, const u8 *msg_in)
{
/*~ Our autogeneration code doesn't define field offsets, so we just
* copy this from the spec itself.
*
* Note that 'check-source' will actually find and check this quote
* against the spec (if available); whitespace is ignored and
* "..." means some content is skipped, but it works remarkably well to
* track spec changes. */
/* BOLT #7:
*
* - MUST compute the double-SHA256 hash `h` of the message, beginning
* at offset 256, up to the end of the message.
* - Note: the hash skips the 4 signatures but hashes the rest of the
* message, including any future fields appended to the end.
*/
/* First type bytes are the msg type */
size_t offset = 2 + 256;
struct privkey node_pkey;
secp256k1_ecdsa_signature node_sig, bitcoin_sig;
struct sha256_double hash;
u8 *reply;
u8 *ca;
struct pubkey funding_pubkey;
struct privkey funding_privkey;
struct secret channel_seed;
/*~ You'll find FIXMEs like this scattered through the code.
* Sometimes they suggest simple improvements which someone like
* yourself should go ahead an implement. Sometimes they're deceptive
* quagmires which will cause you nothing but grief. You decide! */
/*~ Christian uses TODO(cdecker) or FIXME(cdecker), but I'm sure he won't
* mind if you fix this for him! */
/* FIXME: We should cache these. */
get_channel_seed(&c->id, c->dbid, &channel_seed);
derive_funding_key(&channel_seed, &funding_pubkey, &funding_privkey);
/*~ fromwire_ routines which need to do allocation take a tal context
* as their first field; tmpctx is good here since we won't need it
* after this function. */
if (!fromwire_hsmd_cannouncement_sig_req(tmpctx, msg_in, &ca))
return hsmd_status_malformed_request(c, msg_in);
if (tal_count(ca) < offset)
return hsmd_status_bad_request_fmt(
c, msg_in, "bad cannounce length %zu", tal_count(ca));
if (fromwire_peektype(ca) != WIRE_CHANNEL_ANNOUNCEMENT)
return hsmd_status_bad_request_fmt(
c, msg_in, "Invalid channel announcement");
node_key(&node_pkey, NULL);
sha256_double(&hash, ca + offset, tal_count(ca) - offset);
sign_hash(&node_pkey, &hash, &node_sig);
sign_hash(&funding_privkey, &hash, &bitcoin_sig);
reply = towire_hsmd_cannouncement_sig_reply(NULL, &node_sig,
&bitcoin_sig);
return reply;
}
/*~ It's optional for nodes to send node_announcement, but it lets us set our
* favourite color and cool alias! Plus other minor details like how to
* connect to us. */
static u8 *handle_sign_node_announcement(struct hsmd_client *c,
const u8 *msg_in)
{
/* BOLT #7:
*
* The origin node:
*...
* - MUST set `signature` to the signature of the double-SHA256 of the
* entire remaining packet after `signature` (using the key given by
* `node_id`).
*/
/* 2 bytes msg type + 64 bytes signature */
size_t offset = 66;
struct sha256_double hash;
struct privkey node_pkey;
secp256k1_ecdsa_signature sig;
u8 *reply;
u8 *ann;
if (!fromwire_hsmd_node_announcement_sig_req(tmpctx, msg_in, &ann))
return hsmd_status_malformed_request(c, msg_in);
if (tal_count(ann) < offset)
return hsmd_status_bad_request(c, msg_in,
"Node announcement too short");
if (fromwire_peektype(ann) != WIRE_NODE_ANNOUNCEMENT)
return hsmd_status_bad_request(c, msg_in,
"Invalid announcement");
node_key(&node_pkey, NULL);
sha256_double(&hash, ann + offset, tal_count(ann) - offset);
sign_hash(&node_pkey, &hash, &sig);
reply = towire_hsmd_node_announcement_sig_reply(NULL, &sig);
return reply;
}
/*~ The specific routine to sign the channel_update message. */
static u8 *handle_channel_update_sig(struct hsmd_client *c, const u8 *msg_in)
{
/* BOLT #7:
*
* - MUST set `signature` to the signature of the double-SHA256 of the
* entire remaining packet after `signature`, using its own
* `node_id`.
*/
/* 2 bytes msg type + 64 bytes signature */
size_t offset = 66;
struct privkey node_pkey;
struct sha256_double hash;
secp256k1_ecdsa_signature sig;
struct short_channel_id scid;
u32 timestamp, fee_base_msat, fee_proportional_mill;
struct amount_msat htlc_minimum, htlc_maximum;
u8 message_flags, channel_flags;
u16 cltv_expiry_delta;
struct bitcoin_blkid chain_hash;
u8 *cu;
if (!fromwire_hsmd_cupdate_sig_req(tmpctx, msg_in, &cu))
return hsmd_status_malformed_request(c, msg_in);
if (!fromwire_channel_update(cu, &sig,
&chain_hash, &scid, ×tamp, &message_flags,
&channel_flags, &cltv_expiry_delta,
&htlc_minimum, &fee_base_msat,
&fee_proportional_mill, &htlc_maximum)) {
return hsmd_status_bad_request(c, msg_in,
"Bad inner channel_update");
}
if (tal_count(cu) < offset)
return hsmd_status_bad_request(
c, msg_in, "inner channel_update too short");
node_key(&node_pkey, NULL);
sha256_double(&hash, cu + offset, tal_count(cu) - offset);
sign_hash(&node_pkey, &hash, &sig);
cu = towire_channel_update(tmpctx, &sig, &chain_hash,
&scid, timestamp, message_flags, channel_flags,
cltv_expiry_delta, htlc_minimum,
fee_base_msat, fee_proportional_mill,
htlc_maximum);
return towire_hsmd_cupdate_sig_reply(NULL, cu);
}
/*~ This get the Nth a per-commitment point, and for N > 2, returns the
* grandparent per-commitment secret. This pattern is because after
* negotiating commitment N-1, we send them the next per-commitment point,
* and reveal the previous per-commitment secret as a promise not to spend
* the previous commitment transaction. */
static u8 *handle_get_per_commitment_point(struct hsmd_client *c, const u8 *msg_in)
{
struct secret channel_seed;
struct sha256 shaseed;
struct pubkey per_commitment_point;