1 #include <bitcoin/script.h>
2 #include <ccan/crypto/hkdf_sha256/hkdf_sha256.h>
3 #include <ccan/tal/str/str.h>
4 #include <common/bolt12_merkle.h>
5 #include <common/hash_u5.h>
6 #include <common/key_derive.h>
7 #include <common/lease_rates.h>
8 #include <common/type_to_string.h>
9 #include <hsmd/capabilities.h>
10 #include <hsmd/libhsmd.h>
11 #include <inttypes.h>
12 #include <secp256k1_ecdh.h>
13 #include <secp256k1_schnorrsig.h>
14 #include <sodium/utils.h>
15 #include <wally_psbt.h>
16 
17 #if DEVELOPER
18 /* If they specify --dev-force-privkey it ends up in here. */
19 struct privkey *dev_force_privkey;
20 /* If they specify --dev-force-bip32-seed it ends up in here. */
21 struct secret *dev_force_bip32_seed;
22 #endif
23 
24 /*~ Nobody will ever find it here!  hsm_secret is our root secret, the bip32
25  * tree and bolt12 payer_id keys are derived from that, and cached here. */
26 struct {
27 	struct secret hsm_secret;
28 	struct ext_key bip32;
29 	secp256k1_keypair bolt12;
30 } secretstuff;
31 
32 /* Have we initialized the secretstuff? */
33 bool initialized = false;
34 
hsmd_client_new_main(const tal_t * ctx,u64 capabilities,void * extra)35 struct hsmd_client *hsmd_client_new_main(const tal_t *ctx, u64 capabilities,
36 					 void *extra)
37 {
38 	struct hsmd_client *c = tal(ctx, struct hsmd_client);
39 	c->dbid = 0;
40 	c->capabilities = capabilities;
41 	c->extra = extra;
42 	return c;
43 }
44 
hsmd_client_new_peer(const tal_t * ctx,u64 capabilities,u64 dbid,const struct node_id * peer_id,void * extra)45 struct hsmd_client *hsmd_client_new_peer(const tal_t *ctx, u64 capabilities,
46 					 u64 dbid,
47 					 const struct node_id *peer_id,
48 					 void *extra)
49 {
50 	struct hsmd_client *c = tal(ctx, struct hsmd_client);
51 	c->dbid = dbid;
52 	c->capabilities = capabilities;
53 	c->id = *peer_id;
54 	c->extra = extra;
55 	return c;
56 }
57 
58 /*~ This routine checks that a client is allowed to call the handler. */
hsmd_check_client_capabilities(struct hsmd_client * client,enum hsmd_wire t)59 bool hsmd_check_client_capabilities(struct hsmd_client *client,
60 				    enum hsmd_wire t)
61 {
62 	/*~ Here's a useful trick: enums in C are not real types, they're
63 	 * semantic sugar sprinkled over an int, bascally (in fact, older
64 	 * versions of gcc used to convert the values ints in the parser!).
65 	 *
66 	 * But GCC will do one thing for us: if we have a switch statement
67 	 * with a controlling expression which is an enum, it will warn us
68 	 * if a declared enum value is *not* handled in the switch, eg:
69 	 *     enumeration value ‘FOOBAR’ not handled in switch [-Werror=switch]
70 	 *
71 	 * This only works if there's no 'default' label, which is sometimes
72 	 * hard, as we *can* have non-enum values in our enum.  But the tradeoff
73 	 * is worth it so the compiler tells us everywhere we have to fix when
74 	 * we add a new enum identifier!
75 	 */
76 	switch (t) {
77 	case WIRE_HSMD_ECDH_REQ:
78 		return (client->capabilities & HSM_CAP_ECDH) != 0;
79 
80 	case WIRE_HSMD_CANNOUNCEMENT_SIG_REQ:
81 	case WIRE_HSMD_CUPDATE_SIG_REQ:
82 	case WIRE_HSMD_NODE_ANNOUNCEMENT_SIG_REQ:
83 		return (client->capabilities & HSM_CAP_SIGN_GOSSIP) != 0;
84 
85 	case WIRE_HSMD_SIGN_DELAYED_PAYMENT_TO_US:
86 	case WIRE_HSMD_SIGN_REMOTE_HTLC_TO_US:
87 	case WIRE_HSMD_SIGN_PENALTY_TO_US:
88 	case WIRE_HSMD_SIGN_LOCAL_HTLC_TX:
89 		return (client->capabilities & HSM_CAP_SIGN_ONCHAIN_TX) != 0;
90 
91 	case WIRE_HSMD_GET_PER_COMMITMENT_POINT:
92 	case WIRE_HSMD_CHECK_FUTURE_SECRET:
93 		return (client->capabilities & HSM_CAP_COMMITMENT_POINT) != 0;
94 
95 	case WIRE_HSMD_SIGN_REMOTE_COMMITMENT_TX:
96 	case WIRE_HSMD_SIGN_REMOTE_HTLC_TX:
97 		return (client->capabilities & HSM_CAP_SIGN_REMOTE_TX) != 0;
98 
99 	case WIRE_HSMD_SIGN_MUTUAL_CLOSE_TX:
100 		return (client->capabilities & HSM_CAP_SIGN_CLOSING_TX) != 0;
101 
102 	case WIRE_HSMD_SIGN_OPTION_WILL_FUND_OFFER:
103 		return (client->capabilities & HSM_CAP_SIGN_WILL_FUND_OFFER) != 0;
104 
105 	case WIRE_HSMD_INIT:
106 	case WIRE_HSMD_CLIENT_HSMFD:
107 	case WIRE_HSMD_SIGN_WITHDRAWAL:
108 	case WIRE_HSMD_SIGN_INVOICE:
109 	case WIRE_HSMD_SIGN_COMMITMENT_TX:
110 	case WIRE_HSMD_GET_CHANNEL_BASEPOINTS:
111 	case WIRE_HSMD_DEV_MEMLEAK:
112 	case WIRE_HSMD_SIGN_MESSAGE:
113 	case WIRE_HSMD_GET_OUTPUT_SCRIPTPUBKEY:
114 	case WIRE_HSMD_SIGN_BOLT12:
115 		return (client->capabilities & HSM_CAP_MASTER) != 0;
116 
117 	/*~ These are messages sent by the HSM so we should never receive them. */
118 	/* FIXME: Since we autogenerate these, we should really generate separate
119 	 * enums for replies to avoid this kind of clutter! */
120 	case WIRE_HSMD_ECDH_RESP:
121 	case WIRE_HSMD_CANNOUNCEMENT_SIG_REPLY:
122 	case WIRE_HSMD_CUPDATE_SIG_REPLY:
123 	case WIRE_HSMD_CLIENT_HSMFD_REPLY:
124 	case WIRE_HSMD_NODE_ANNOUNCEMENT_SIG_REPLY:
125 	case WIRE_HSMD_SIGN_WITHDRAWAL_REPLY:
126 	case WIRE_HSMD_SIGN_INVOICE_REPLY:
127 	case WIRE_HSMD_INIT_REPLY:
128 	case WIRE_HSMSTATUS_CLIENT_BAD_REQUEST:
129 	case WIRE_HSMD_SIGN_COMMITMENT_TX_REPLY:
130 	case WIRE_HSMD_SIGN_TX_REPLY:
131 	case WIRE_HSMD_SIGN_OPTION_WILL_FUND_OFFER_REPLY:
132 	case WIRE_HSMD_GET_PER_COMMITMENT_POINT_REPLY:
133 	case WIRE_HSMD_CHECK_FUTURE_SECRET_REPLY:
134 	case WIRE_HSMD_GET_CHANNEL_BASEPOINTS_REPLY:
135 	case WIRE_HSMD_DEV_MEMLEAK_REPLY:
136 	case WIRE_HSMD_SIGN_MESSAGE_REPLY:
137 	case WIRE_HSMD_GET_OUTPUT_SCRIPTPUBKEY_REPLY:
138 	case WIRE_HSMD_SIGN_BOLT12_REPLY:
139 		break;
140 	}
141 	return false;
142 }
143 
144 /*~ ccan/compiler.h defines PRINTF_FMT as the gcc compiler hint so it will
145  * check that fmt and other trailing arguments really are the correct type.
146  */
147 /* This function is used to format an error message before passing it
148  * to the library user specified hsmd_status_bad_request */
149 static u8 *hsmd_status_bad_request_fmt(struct hsmd_client *client,
150 				       const u8 *msg, const char *fmt, ...)
151     PRINTF_FMT(3, 4);
152 
hsmd_status_bad_request_fmt(struct hsmd_client * client,const u8 * msg,const char * fmt,...)153 static u8 *hsmd_status_bad_request_fmt(struct hsmd_client *client,
154 				       const u8 *msg, const char *fmt, ...)
155 {
156 	va_list ap;
157 	char *str;
158 
159 	va_start(ap, fmt);
160 	str = tal_fmt(tmpctx, fmt, ap);
161 	va_end(ap);
162 	return hsmd_status_bad_request(client, msg, str);
163 }
164 
165 /* Convenience wrapper for when we simply can't parse. */
hsmd_status_malformed_request(struct hsmd_client * c,const u8 * msg_in)166 static u8 *hsmd_status_malformed_request(struct hsmd_client *c, const u8 *msg_in)
167 {
168 	return hsmd_status_bad_request(c, msg_in, "could not parse request");
169 }
170 
171 /*~ This returns the secret and/or public key for this node. */
node_key(struct privkey * node_privkey,struct pubkey * node_id)172 static void node_key(struct privkey *node_privkey, struct pubkey *node_id)
173 {
174 	u32 salt = 0;
175 	struct privkey unused_s;
176 	struct pubkey unused_k;
177 
178 	/* If caller specifies NULL, they don't want the results. */
179 	if (node_privkey == NULL)
180 		node_privkey = &unused_s;
181 	if (node_id == NULL)
182 		node_id = &unused_k;
183 
184 	/*~ So, there is apparently a 1 in 2^127 chance that a random value is
185 	 * not a valid private key, so this never actually loops. */
186 	do {
187 		/*~ ccan/crypto/hkdf_sha256 implements RFC5869 "Hardened Key
188 		 * Derivation Functions".  That means that if a derived key
189 		 * leaks somehow, the other keys are not compromised. */
190 		hkdf_sha256(node_privkey, sizeof(*node_privkey),
191 			    &salt, sizeof(salt),
192 			    &secretstuff.hsm_secret,
193 			    sizeof(secretstuff.hsm_secret),
194 			    "nodeid", 6);
195 		salt++;
196 	} while (!secp256k1_ec_pubkey_create(secp256k1_ctx, &node_id->pubkey,
197 					     node_privkey->secret.data));
198 
199 #if DEVELOPER
200 	/* In DEVELOPER mode, we can override with --dev-force-privkey */
201 	if (dev_force_privkey) {
202 		*node_privkey = *dev_force_privkey;
203 		if (!secp256k1_ec_pubkey_create(secp256k1_ctx, &node_id->pubkey,
204 						node_privkey->secret.data))
205 			hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
206 				      "Failed to derive pubkey for dev_force_privkey");
207 	}
208 #endif
209 }
210 
211 /*~ This returns the secret and/or public x-only key for this node. */
node_schnorrkey(secp256k1_keypair * node_keypair,struct point32 * node_id32)212 static void node_schnorrkey(secp256k1_keypair *node_keypair,
213 			    struct point32 *node_id32)
214 {
215 	secp256k1_keypair unused_kp;
216 	struct privkey node_privkey;
217 
218 	if (!node_keypair)
219 		node_keypair = &unused_kp;
220 
221 	node_key(&node_privkey, NULL);
222 	if (secp256k1_keypair_create(secp256k1_ctx, node_keypair,
223 				     node_privkey.secret.data) != 1)
224 		hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
225 				   "Failed to derive keypair");
226 
227 	if (node_id32) {
228 		if (secp256k1_keypair_xonly_pub(secp256k1_ctx,
229 						&node_id32->pubkey,
230 						NULL, node_keypair) != 1)
231 			hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
232 					   "Failed to derive xonly pub");
233 	}
234 }
235 
236 /*~ This secret is the basis for all per-channel secrets: the per-channel seeds
237  * will be generated by mixing in the dbid and the peer node_id. */
hsm_channel_secret_base(struct secret * channel_seed_base)238 static void hsm_channel_secret_base(struct secret *channel_seed_base)
239 {
240 	hkdf_sha256(channel_seed_base, sizeof(struct secret), NULL, 0,
241 		    &secretstuff.hsm_secret, sizeof(secretstuff.hsm_secret),
242 		    /*~ Initially, we didn't support multiple channels per
243 		     * peer at all: a channel had to be completely forgotten
244 		     * before another could exist.  That was slightly relaxed,
245 		     * but the phrase "peer seed" is wired into the seed
246 		     * generation here, so we need to keep it that way for
247 		     * existing clients, rather than using "channel seed". */
248 		    "peer seed", strlen("peer seed"));
249 }
250 
251 /*~ This gets the seed for this particular channel. */
get_channel_seed(const struct node_id * peer_id,u64 dbid,struct secret * channel_seed)252 static void get_channel_seed(const struct node_id *peer_id, u64 dbid,
253 			     struct secret *channel_seed)
254 {
255 	struct secret channel_base;
256 	u8 input[sizeof(peer_id->k) + sizeof(dbid)];
257 	/*~ Again, "per-peer" should be "per-channel", but Hysterical Raisins */
258 	const char *info = "per-peer seed";
259 
260 	/*~ We use the DER encoding of the pubkey, because it's platform
261 	 * independent.  Since the dbid is unique, however, it's completely
262 	 * unnecessary, but again, existing users can't be broken. */
263 	/* FIXME: lnd has a nicer BIP32 method for deriving secrets which we
264 	 * should migrate to. */
265 	hsm_channel_secret_base(&channel_base);
266 	memcpy(input, peer_id->k, sizeof(peer_id->k));
267 	BUILD_ASSERT(sizeof(peer_id->k) == PUBKEY_CMPR_LEN);
268 	/*~ For all that talk about platform-independence, note that this
269 	 * field is endian-dependent!  But let's face it, little-endian won.
270 	 * In related news, we don't support EBCDIC or middle-endian. */
271 	memcpy(input + PUBKEY_CMPR_LEN, &dbid, sizeof(dbid));
272 
273 	hkdf_sha256(channel_seed, sizeof(*channel_seed),
274 		    input, sizeof(input),
275 		    &channel_base, sizeof(channel_base),
276 		    info, strlen(info));
277 }
278 
279 /*~ For almost every wallet tx we use the BIP32 seed, but not for onchain
280  * unilateral closes from a peer: they (may) have an output to us using a
281  * public key based on the channel basepoints.  It's a bit spammy to spend
282  * those immediately just to make the wallet simpler, and we didn't appreciate
283  * the problem when we designed the protocol for commitment transaction keys.
284  *
285  * So we store just enough about the channel it came from (which may be
286  * long-gone) to regenerate the keys here.  That has the added advantage that
287  * the secrets themselves stay within the HSM. */
hsm_unilateral_close_privkey(struct privkey * dst,struct unilateral_close_info * info)288 static void hsm_unilateral_close_privkey(struct privkey *dst,
289 					 struct unilateral_close_info *info)
290 {
291 	struct secret channel_seed;
292 	struct basepoints basepoints;
293 	struct secrets secrets;
294 
295 	get_channel_seed(&info->peer_id, info->channel_id, &channel_seed);
296 	derive_basepoints(&channel_seed, NULL, &basepoints, &secrets, NULL);
297 
298 	/* BOLT #3:
299 	 *
300 	 * If `option_static_remotekey` or `option_anchors` is
301 	 * negotiated, the `remotepubkey` is simply the remote node's
302 	 * `payment_basepoint`, otherwise it is calculated as above using the
303 	 * remote node's `payment_basepoint`.
304 	 */
305 	/* In our UTXO representation, this is indicated by a NULL
306 	 * commitment_point. */
307 	if (!info->commitment_point)
308 		dst->secret = secrets.payment_basepoint_secret;
309 	else if (!derive_simple_privkey(&secrets.payment_basepoint_secret,
310 					&basepoints.payment,
311 					info->commitment_point,
312 					dst)) {
313 		hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
314 				   "Deriving unilateral_close_privkey");
315 	}
316 }
317 
318 /*~ Get the keys for this given BIP32 index: if privkey is NULL, we
319  * don't fill it in. */
bitcoin_key(struct privkey * privkey,struct pubkey * pubkey,u32 index)320 static void bitcoin_key(struct privkey *privkey, struct pubkey *pubkey,
321 			u32 index)
322 {
323 	struct ext_key ext;
324 	struct privkey unused_priv;
325 
326 	if (privkey == NULL)
327 		privkey = &unused_priv;
328 
329 	if (index >= BIP32_INITIAL_HARDENED_CHILD)
330 		hsmd_status_failed(STATUS_FAIL_MASTER_IO, "Index %u too great",
331 				   index);
332 
333 	/*~ This uses libwally, which doesn't dovetail directly with
334 	 * libsecp256k1 even though it, too, uses it internally. */
335 	if (bip32_key_from_parent(&secretstuff.bip32, index,
336 				  BIP32_FLAG_KEY_PRIVATE, &ext) != WALLY_OK)
337 		hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
338 				   "BIP32 of %u failed", index);
339 
340 	/* libwally says: The private key with prefix byte 0; remove it
341 	 * for libsecp256k1. */
342 	memcpy(privkey->secret.data, ext.priv_key+1, 32);
343 	if (!secp256k1_ec_pubkey_create(secp256k1_ctx, &pubkey->pubkey,
344 					privkey->secret.data))
345 		hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
346 				   "BIP32 pubkey %u create failed", index);
347 }
348 
349 /* This gets the bitcoin private key needed to spend from our wallet */
hsm_key_for_utxo(struct privkey * privkey,struct pubkey * pubkey,const struct utxo * utxo)350 static void hsm_key_for_utxo(struct privkey *privkey, struct pubkey *pubkey,
351 			     const struct utxo *utxo)
352 {
353 	if (utxo->close_info != NULL) {
354 		/* This is a their_unilateral_close/to-us output, so
355 		 * we need to derive the secret the long way */
356 		hsmd_status_debug("Unilateral close output, deriving secrets");
357 		hsm_unilateral_close_privkey(privkey, utxo->close_info);
358 		pubkey_from_privkey(privkey, pubkey);
359 		hsmd_status_debug("Derived public key %s from unilateral close",
360 			     type_to_string(tmpctx, struct pubkey, pubkey));
361 	} else {
362 		/* Simple case: just get derive via HD-derivation */
363 		bitcoin_key(privkey, pubkey, utxo->keyindex);
364 	}
365 }
366 
367 /* Find our inputs by the pubkey associated with the inputs, and
368  * add a partial sig for each */
sign_our_inputs(struct utxo ** utxos,struct wally_psbt * psbt)369 static void sign_our_inputs(struct utxo **utxos, struct wally_psbt *psbt)
370 {
371 	for (size_t i = 0; i < tal_count(utxos); i++) {
372 		struct utxo *utxo = utxos[i];
373 		for (size_t j = 0; j < psbt->num_inputs; j++) {
374 			struct privkey privkey;
375 			struct pubkey pubkey;
376 
377 			if (!wally_tx_input_spends(&psbt->tx->inputs[j],
378 						   &utxo->outpoint))
379 				continue;
380 
381 			hsm_key_for_utxo(&privkey, &pubkey, utxo);
382 
383 			/* This line is basically the entire reason we have
384 			 * to iterate through to match the psbt input
385 			 * to the UTXO -- otherwise we would just
386 			 * call wally_psbt_sign for every utxo privkey
387 			 * and be done with it. We can't do that though
388 			 * because any UTXO that's derived from channel_info
389 			 * requires the HSM to find the pubkey, and we
390 			 * skip doing that until now as a bit of a reduction
391 			 * of complexity in the calling code */
392 			psbt_input_add_pubkey(psbt, j, &pubkey);
393 
394 			/* It's actually a P2WSH in this case. */
395 			if (utxo->close_info && utxo->close_info->option_anchor_outputs) {
396 				const u8 *wscript
397 					= anchor_to_remote_redeem(tmpctx,
398 								  &pubkey,
399 								  utxo->close_info->csv);
400 				psbt_input_set_witscript(psbt, j, wscript);
401 				psbt_input_set_wit_utxo(psbt, j,
402 							scriptpubkey_p2wsh(psbt, wscript),
403 							utxo->amount);
404 			}
405 			tal_wally_start();
406 			if (wally_psbt_sign(psbt, privkey.secret.data,
407 					    sizeof(privkey.secret.data),
408 					    EC_FLAG_GRIND_R) != WALLY_OK)
409 				hsmd_status_broken(
410 				    "Received wally_err attempting to "
411 				    "sign utxo with key %s. PSBT: %s",
412 				    type_to_string(tmpctx, struct pubkey,
413 						   &pubkey),
414 				    type_to_string(tmpctx, struct wally_psbt,
415 						   psbt));
416 			tal_wally_end(psbt);
417 		}
418 	}
419 }
420 
421 /*~ This covers several cases where onchaind is creating a transaction which
422  * sends funds to our internal wallet. */
423 /* FIXME: Derive output address for this client, and check it here! */
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)424 static u8 *handle_sign_to_us_tx(struct hsmd_client *c, const u8 *msg_in,
425 				struct bitcoin_tx *tx,
426 				const struct privkey *privkey,
427 				const u8 *wscript,
428 				enum sighash_type sighash_type)
429 {
430 	struct bitcoin_signature sig;
431 	struct pubkey pubkey;
432 
433 	if (!pubkey_from_privkey(privkey, &pubkey))
434 		return hsmd_status_bad_request(c, msg_in,
435 					       "bad pubkey_from_privkey");
436 
437 	if (tx->wtx->num_inputs != 1)
438 		return hsmd_status_bad_request(c, msg_in, "bad txinput count");
439 
440 	sign_tx_input(tx, 0, NULL, wscript, privkey, &pubkey, sighash_type, &sig);
441 
442 	return towire_hsmd_sign_tx_reply(NULL, &sig);
443 }
444 
445 /*~ lightningd asks us to sign a message.  I tweeted the spec
446  * in https://twitter.com/rusty_twit/status/1182102005914800128:
447  *
448  * @roasbeef & @bitconner point out that #lnd algo is:
449  *    zbase32(SigRec(SHA256(SHA256("Lightning Signed Message:" + msg)))).
450  * zbase32 from https://philzimmermann.com/docs/human-oriented-base-32-encoding.txt
451  * and SigRec has first byte 31 + recovery id, followed by 64 byte sig.  #specinatweet
452  */
handle_sign_message(struct hsmd_client * c,const u8 * msg_in)453 static u8 *handle_sign_message(struct hsmd_client *c, const u8 *msg_in)
454 {
455 	u8 *msg;
456 	struct sha256_ctx sctx = SHA256_INIT;
457 	struct sha256_double shad;
458 	secp256k1_ecdsa_recoverable_signature rsig;
459 	struct privkey node_pkey;
460 
461 	if (!fromwire_hsmd_sign_message(tmpctx, msg_in, &msg))
462 		return hsmd_status_malformed_request(c, msg_in);
463 
464 	/* Prefixing by a known string means we'll never be convinced
465 	 * to sign some gossip message, etc. */
466 	sha256_update(&sctx, "Lightning Signed Message:",
467 		      strlen("Lightning Signed Message:"));
468 	sha256_update(&sctx, msg, tal_count(msg));
469 	sha256_double_done(&sctx, &shad);
470 
471 	node_key(&node_pkey, NULL);
472 	/*~ By no small coincidence, this libsecp routine uses the exact
473 	 * recovery signature format mandated by BOLT 11. */
474 	if (!secp256k1_ecdsa_sign_recoverable(secp256k1_ctx, &rsig,
475                                               shad.sha.u.u8,
476                                               node_pkey.secret.data,
477                                               NULL, NULL)) {
478 		return hsmd_status_bad_request(c, msg_in, "Failed to sign message");
479 	}
480 
481 	return towire_hsmd_sign_message_reply(NULL, &rsig);
482 }
483 
484 /*~ lightningd asks us to sign a liquidity ad offer */
handle_sign_option_will_fund_offer(struct hsmd_client * c,const u8 * msg_in)485 static u8 *handle_sign_option_will_fund_offer(struct hsmd_client *c,
486 					      const u8 *msg_in)
487 {
488 	struct pubkey funding_pubkey;
489 	u32 lease_expiry, channel_fee_base_max_msat;
490 	u16 channel_fee_max_ppt;
491 	struct sha256 sha;
492 	secp256k1_ecdsa_signature sig;
493 	struct privkey node_pkey;
494 
495 	if (!fromwire_hsmd_sign_option_will_fund_offer(msg_in,
496 						       &funding_pubkey,
497 						       &lease_expiry,
498 						       &channel_fee_base_max_msat,
499 						       &channel_fee_max_ppt))
500 		return hsmd_status_malformed_request(c, msg_in);
501 
502 	lease_rates_get_commitment(&funding_pubkey, lease_expiry,
503 				   channel_fee_base_max_msat,
504 				   channel_fee_max_ppt,
505 				   &sha);
506 
507 	node_key(&node_pkey, NULL);
508 
509 	if (!secp256k1_ecdsa_sign(secp256k1_ctx, &sig,
510 				  sha.u.u8,
511 				  node_pkey.secret.data,
512 				  NULL, NULL))
513 		return hsmd_status_bad_request(c, msg_in,
514 					       "Failed to sign message");
515 
516 	return towire_hsmd_sign_option_will_fund_offer_reply(NULL, &sig);
517 }
518 
519 /*~ lightningd asks us to sign a bolt12 (e.g. offer). */
handle_sign_bolt12(struct hsmd_client * c,const u8 * msg_in)520 static u8 *handle_sign_bolt12(struct hsmd_client *c, const u8 *msg_in)
521 {
522 	char *messagename, *fieldname;
523 	struct sha256 merkle, sha;
524 	struct bip340sig sig;
525 	secp256k1_keypair kp;
526 	u8 *publictweak;
527 
528 	if (!fromwire_hsmd_sign_bolt12(tmpctx, msg_in,
529 				       &messagename, &fieldname, &merkle,
530 				       &publictweak))
531 		return hsmd_status_malformed_request(c, msg_in);
532 
533 	sighash_from_merkle(messagename, fieldname, &merkle, &sha);
534 
535 	if (!publictweak) {
536 		node_schnorrkey(&kp, NULL);
537 	} else {
538 		/* If we're tweaking key, we use bolt12 key */
539 		struct point32 bolt12;
540 		struct sha256 tweak;
541 
542 		if (secp256k1_keypair_xonly_pub(secp256k1_ctx,
543 						&bolt12.pubkey, NULL,
544 						&secretstuff.bolt12) != 1)
545 			hsmd_status_failed(
546 			    STATUS_FAIL_INTERNAL_ERROR,
547 			    "Could not derive bolt12 public key.");
548 		payer_key_tweak(&bolt12, publictweak, tal_bytelen(publictweak),
549 				&tweak);
550 
551 		kp = secretstuff.bolt12;
552 
553 		if (secp256k1_keypair_xonly_tweak_add(secp256k1_ctx,
554 						      &kp,
555 						      tweak.u.u8) != 1) {
556 			return hsmd_status_bad_request_fmt(
557 			    c, msg_in, "Failed to get tweak key");
558 		}
559 	}
560 
561 	if (!secp256k1_schnorrsig_sign(secp256k1_ctx, sig.u8,
562 				       sha.u.u8,
563 				       &kp,
564 				       NULL, NULL)) {
565 		return hsmd_status_bad_request_fmt(c, msg_in,
566 						   "Failed to sign bolt12");
567 	}
568 
569 	return towire_hsmd_sign_bolt12_reply(NULL, &sig);
570 }
571 
572 /*~ Lightning invoices, defined by BOLT 11, are signed.  This has been
573  * surprisingly controversial; it means a node needs to be online to create
574  * invoices.  However, it seems clear to me that in a world without
575  * intermedaries you need proof that you have received an offer (the
576  * signature), as well as proof that you've paid it (the preimage). */
handle_sign_invoice(struct hsmd_client * c,const u8 * msg_in)577 static u8 *handle_sign_invoice(struct hsmd_client *c, const u8 *msg_in)
578 {
579 	/*~ We make up a 'u5' type to represent BOLT11's 5-bits-per-byte
580 	 * format: it's only for human consumption, as typedefs are almost
581 	 * entirely transparent to the C compiler. */
582 	u5 *u5bytes;
583 	u8 *hrpu8;
584 	char *hrp;
585 	struct sha256 sha;
586         secp256k1_ecdsa_recoverable_signature rsig;
587 	struct hash_u5 hu5;
588 	struct privkey node_pkey;
589 
590 	if (!fromwire_hsmd_sign_invoice(tmpctx, msg_in, &u5bytes, &hrpu8))
591 		return hsmd_status_malformed_request(c, msg_in);
592 
593 	/* BOLT #11:
594 	 *
595 	 * A writer... MUST set `signature` to a valid 512-bit
596 	 * secp256k1 signature of the SHA2 256-bit hash of the
597 	 * human-readable part, represented as UTF-8 bytes,
598 	 * concatenated with the data part (excluding the signature)
599 	 * with 0 bits appended to pad the data to the next byte
600 	 * boundary, with a trailing byte containing the recovery ID
601 	 * (0, 1, 2, or 3).
602 	 */
603 
604 	/* FIXME: Check invoice! */
605 
606 	/*~ tal_dup_arr() does what you'd expect: allocate an array by copying
607 	 * another; the cast is needed because the hrp is a 'char' array, not
608 	 * a 'u8' (unsigned char) as it's the "human readable" part.
609 	 *
610 	 * The final arg of tal_dup_arr() is how many extra bytes to allocate:
611 	 * it's so often zero that I've thought about dropping the argument, but
612 	 * in cases like this (adding a NUL terminator) it's perfect. */
613 	hrp = tal_dup_arr(tmpctx, char, (char *)hrpu8, tal_count(hrpu8), 1);
614 	hrp[tal_count(hrpu8)] = '\0';
615 
616 	hash_u5_init(&hu5, hrp);
617 	hash_u5(&hu5, u5bytes, tal_count(u5bytes));
618 	hash_u5_done(&hu5, &sha);
619 
620 	node_key(&node_pkey, NULL);
621 	/*~ By no small coincidence, this libsecp routine uses the exact
622 	 * recovery signature format mandated by BOLT 11. */
623 	if (!secp256k1_ecdsa_sign_recoverable(secp256k1_ctx, &rsig,
624                                               (const u8 *)&sha,
625                                               node_pkey.secret.data,
626                                               NULL, NULL)) {
627 		return hsmd_status_bad_request_fmt(c, msg_in,
628 						   "Failed to sign invoice");
629 	}
630 
631 	return towire_hsmd_sign_invoice_reply(NULL, &rsig);
632 }
633 
634 /*~ This gets the basepoints for a channel; it's not private information really
635  * (we tell the peer this to establish a channel, as it sets up the keys used
636  * for each transaction).
637  *
638  * Note that this is asked by lightningd, so it tells us what channels it wants.
639  */
handle_get_channel_basepoints(struct hsmd_client * c,const u8 * msg_in)640 static u8 *handle_get_channel_basepoints(struct hsmd_client *c,
641 					 const u8 *msg_in)
642 {
643 	struct node_id peer_id;
644 	u64 dbid;
645 	struct secret seed;
646 	struct basepoints basepoints;
647 	struct pubkey funding_pubkey;
648 
649 	if (!fromwire_hsmd_get_channel_basepoints(msg_in, &peer_id, &dbid))
650 		return hsmd_status_malformed_request(c, msg_in);
651 
652 	get_channel_seed(&peer_id, dbid, &seed);
653 	derive_basepoints(&seed, &funding_pubkey, &basepoints, NULL, NULL);
654 
655 	return towire_hsmd_get_channel_basepoints_reply(NULL, &basepoints,
656 							&funding_pubkey);
657 }
658 
659 /*~ The client has asked us to extract the shared secret from an EC Diffie
660  * Hellman token.  This doesn't leak any information, but requires the private
661  * key, so the hsmd performs it.  It's used to set up an encryption key for the
662  * connection handshaking (BOLT #8) and for the onion wrapping (BOLT #4). */
handle_ecdh(struct hsmd_client * c,const u8 * msg_in)663 static u8 *handle_ecdh(struct hsmd_client *c, const u8 *msg_in)
664 {
665 	struct privkey privkey;
666 	struct pubkey point;
667 	struct secret ss;
668 
669 	if (!fromwire_hsmd_ecdh_req(msg_in, &point))
670 		return hsmd_status_malformed_request(c, msg_in);
671 
672 	/*~ We simply use the secp256k1_ecdh function: if privkey.secret.data is invalid,
673 	 * we kill them for bad randomness (~1 in 2^127 if privkey.secret.data is random) */
674 	node_key(&privkey, NULL);
675 	if (secp256k1_ecdh(secp256k1_ctx, ss.data, &point.pubkey,
676 			   privkey.secret.data, NULL, NULL) != 1) {
677 		return hsmd_status_bad_request_fmt(c, msg_in,
678 						   "secp256k1_ecdh fail");
679 	}
680 
681 	/*~ In the normal case, we return the shared secret, and then read
682 	 * the next msg. */
683 	return towire_hsmd_ecdh_resp(NULL, &ss);
684 }
685 
686 /*~ This is used when the remote peer claims to have knowledge of future
687  * commitment states (option_data_loss_protect in the spec) which means we've
688  * been restored from backup or something, and may have already revealed
689  * secrets.  We carefully check that this is true, here. */
handle_check_future_secret(struct hsmd_client * c,const u8 * msg_in)690 static u8 *handle_check_future_secret(struct hsmd_client *c, const u8 *msg_in)
691 {
692 	struct secret channel_seed;
693 	struct sha256 shaseed;
694 	u64 n;
695 	struct secret secret, suggested;
696 
697 	if (!fromwire_hsmd_check_future_secret(msg_in, &n, &suggested))
698 		return hsmd_status_malformed_request(c, msg_in);
699 
700 	get_channel_seed(&c->id, c->dbid, &channel_seed);
701 	if (!derive_shaseed(&channel_seed, &shaseed))
702 		return hsmd_status_bad_request_fmt(c, msg_in,
703 						   "bad derive_shaseed");
704 
705 	if (!per_commit_secret(&shaseed, &secret, n))
706 		return hsmd_status_bad_request_fmt(
707 		    c, msg_in, "bad commit secret #%" PRIu64, n);
708 
709 	/*~ Note the special secret_eq_consttime: we generate foo_eq for many
710 	 * types using ccan/structeq, but not 'struct secret' because any
711 	 * comparison risks leaking information about the secret if it is
712 	 * timing dependent. */
713 	return towire_hsmd_check_future_secret_reply(
714 	    NULL, secret_eq_consttime(&secret, &suggested));
715 }
716 
handle_get_output_scriptpubkey(struct hsmd_client * c,const u8 * msg_in)717 static u8 *handle_get_output_scriptpubkey(struct hsmd_client *c,
718 					  const u8 *msg_in)
719 {
720 	struct pubkey pubkey;
721 	struct privkey privkey;
722 	struct unilateral_close_info info;
723 	u8 *scriptPubkey;
724 
725 	info.commitment_point = NULL;
726 	if (!fromwire_hsmd_get_output_scriptpubkey(tmpctx, msg_in,
727 						  &info.channel_id,
728 						  &info.peer_id,
729 						  &info.commitment_point))
730 		return hsmd_status_malformed_request(c, msg_in);
731 
732 	hsm_unilateral_close_privkey(&privkey, &info);
733 	pubkey_from_privkey(&privkey, &pubkey);
734 	scriptPubkey = scriptpubkey_p2wpkh(tmpctx, &pubkey);
735 
736 	return towire_hsmd_get_output_scriptpubkey_reply(NULL,
737 								       scriptPubkey);
738 }
739 
740 /*~ The specific routine to sign the channel_announcement message.  This is
741  * defined in BOLT #7, and requires *two* signatures: one from this node's key
742  * (to prove it's from us), and one from the bitcoin key used to create the
743  * funding transaction (to prove we own the output). */
handle_cannouncement_sig(struct hsmd_client * c,const u8 * msg_in)744 static u8 *handle_cannouncement_sig(struct hsmd_client *c, const u8 *msg_in)
745 {
746 	/*~ Our autogeneration code doesn't define field offsets, so we just
747 	 * copy this from the spec itself.
748 	 *
749 	 * Note that 'check-source' will actually find and check this quote
750 	 * against the spec (if available); whitespace is ignored and
751 	 * "..." means some content is skipped, but it works remarkably well to
752 	 * track spec changes. */
753 
754 	/* BOLT #7:
755 	 *
756 	 * - MUST compute the double-SHA256 hash `h` of the message, beginning
757 	 *   at offset 256, up to the end of the message.
758 	 *     - Note: the hash skips the 4 signatures but hashes the rest of the
759 	 *       message, including any future fields appended to the end.
760 	 */
761 	/* First type bytes are the msg type */
762 	size_t offset = 2 + 256;
763 	struct privkey node_pkey;
764 	secp256k1_ecdsa_signature node_sig, bitcoin_sig;
765 	struct sha256_double hash;
766 	u8 *reply;
767 	u8 *ca;
768 	struct pubkey funding_pubkey;
769 	struct privkey funding_privkey;
770 	struct secret channel_seed;
771 
772 	/*~ You'll find FIXMEs like this scattered through the code.
773 	 * Sometimes they suggest simple improvements which someone like
774 	 * yourself should go ahead an implement.  Sometimes they're deceptive
775 	 * quagmires which will cause you nothing but grief.  You decide! */
776 
777 	/*~ Christian uses TODO(cdecker) or FIXME(cdecker), but I'm sure he won't
778 	 * mind if you fix this for him! */
779 
780 	/* FIXME: We should cache these. */
781 	get_channel_seed(&c->id, c->dbid, &channel_seed);
782 	derive_funding_key(&channel_seed, &funding_pubkey, &funding_privkey);
783 
784 	/*~ fromwire_ routines which need to do allocation take a tal context
785 	 * as their first field; tmpctx is good here since we won't need it
786 	 * after this function. */
787 	if (!fromwire_hsmd_cannouncement_sig_req(tmpctx, msg_in, &ca))
788 		return hsmd_status_malformed_request(c, msg_in);
789 
790 	if (tal_count(ca) < offset)
791 		return hsmd_status_bad_request_fmt(
792 		    c, msg_in, "bad cannounce length %zu", tal_count(ca));
793 
794 	if (fromwire_peektype(ca) != WIRE_CHANNEL_ANNOUNCEMENT)
795 		return hsmd_status_bad_request_fmt(
796 		    c, msg_in, "Invalid channel announcement");
797 
798 	node_key(&node_pkey, NULL);
799 	sha256_double(&hash, ca + offset, tal_count(ca) - offset);
800 
801 	sign_hash(&node_pkey, &hash, &node_sig);
802 	sign_hash(&funding_privkey, &hash, &bitcoin_sig);
803 
804 	reply = towire_hsmd_cannouncement_sig_reply(NULL, &node_sig,
805 						   &bitcoin_sig);
806 	return reply;
807 }
808 
809 /*~ It's optional for nodes to send node_announcement, but it lets us set our
810  * favourite color and cool alias!  Plus other minor details like how to
811  * connect to us. */
handle_sign_node_announcement(struct hsmd_client * c,const u8 * msg_in)812 static u8 *handle_sign_node_announcement(struct hsmd_client *c,
813 					 const u8 *msg_in)
814 {
815 	/* BOLT #7:
816 	 *
817 	 * The origin node:
818 	 *...
819 	 * - MUST set `signature` to the signature of the double-SHA256 of the
820 	 *   entire remaining packet after `signature` (using the key given by
821 	 *   `node_id`).
822 	 */
823 	/* 2 bytes msg type + 64 bytes signature */
824 	size_t offset = 66;
825 	struct sha256_double hash;
826 	struct privkey node_pkey;
827 	secp256k1_ecdsa_signature sig;
828 	u8 *reply;
829 	u8 *ann;
830 
831 	if (!fromwire_hsmd_node_announcement_sig_req(tmpctx, msg_in, &ann))
832 		return hsmd_status_malformed_request(c, msg_in);
833 
834 	if (tal_count(ann) < offset)
835 		return hsmd_status_bad_request(c, msg_in,
836 					       "Node announcement too short");
837 
838 	if (fromwire_peektype(ann) != WIRE_NODE_ANNOUNCEMENT)
839 		return hsmd_status_bad_request(c, msg_in,
840 					       "Invalid announcement");
841 
842 	node_key(&node_pkey, NULL);
843 	sha256_double(&hash, ann + offset, tal_count(ann) - offset);
844 
845 	sign_hash(&node_pkey, &hash, &sig);
846 
847 	reply = towire_hsmd_node_announcement_sig_reply(NULL, &sig);
848 	return reply;
849 }
850 
851 /*~ The specific routine to sign the channel_update message. */
handle_channel_update_sig(struct hsmd_client * c,const u8 * msg_in)852 static u8 *handle_channel_update_sig(struct hsmd_client *c, const u8 *msg_in)
853 {
854 	/* BOLT #7:
855 	 *
856 	 * - MUST set `signature` to the signature of the double-SHA256 of the
857 	 *   entire remaining packet after `signature`, using its own
858 	 *   `node_id`.
859 	 */
860 	/* 2 bytes msg type + 64 bytes signature */
861 	size_t offset = 66;
862 	struct privkey node_pkey;
863 	struct sha256_double hash;
864 	secp256k1_ecdsa_signature sig;
865 	struct short_channel_id scid;
866 	u32 timestamp, fee_base_msat, fee_proportional_mill;
867 	struct amount_msat htlc_minimum, htlc_maximum;
868 	u8 message_flags, channel_flags;
869 	u16 cltv_expiry_delta;
870 	struct bitcoin_blkid chain_hash;
871 	u8 *cu;
872 
873 	if (!fromwire_hsmd_cupdate_sig_req(tmpctx, msg_in, &cu))
874 		return hsmd_status_malformed_request(c, msg_in);
875 
876 	if (!fromwire_channel_update_option_channel_htlc_max(cu, &sig,
877 			&chain_hash, &scid, &timestamp, &message_flags,
878 			&channel_flags, &cltv_expiry_delta,
879 			&htlc_minimum, &fee_base_msat,
880 			&fee_proportional_mill, &htlc_maximum)) {
881 		return hsmd_status_bad_request(c, msg_in,
882 					       "Bad inner channel_update");
883 	}
884 	if (tal_count(cu) < offset)
885 		return hsmd_status_bad_request(
886 		    c, msg_in, "inner channel_update too short");
887 
888 	node_key(&node_pkey, NULL);
889 	sha256_double(&hash, cu + offset, tal_count(cu) - offset);
890 
891 	sign_hash(&node_pkey, &hash, &sig);
892 
893 	cu = towire_channel_update_option_channel_htlc_max(tmpctx, &sig, &chain_hash,
894 				   &scid, timestamp, message_flags, channel_flags,
895 				   cltv_expiry_delta, htlc_minimum,
896 				   fee_base_msat, fee_proportional_mill,
897 				   htlc_maximum);
898 	return towire_hsmd_cupdate_sig_reply(NULL, cu);
899 }
900 
901 /*~ This get the Nth a per-commitment point, and for N > 2, returns the
902  * grandparent per-commitment secret.  This pattern is because after
903  * negotiating commitment N-1, we send them the next per-commitment point,
904  * and reveal the previous per-commitment secret as a promise not to spend
905  * the previous commitment transaction. */
handle_get_per_commitment_point(struct hsmd_client * c,const u8 * msg_in)906 static u8 *handle_get_per_commitment_point(struct hsmd_client *c, const u8 *msg_in)
907 {
908 	struct secret channel_seed;
909 	struct sha256 shaseed;
910 	struct pubkey per_commitment_point;
911 	u64 n;
912 	struct secret *old_secret;
913 
914 	if (!fromwire_hsmd_get_per_commitment_point(msg_in, &n))
915 		return hsmd_status_malformed_request(c, msg_in);
916 
917 	get_channel_seed(&c->id, c->dbid, &channel_seed);
918 	if (!derive_shaseed(&channel_seed, &shaseed))
919 		return hsmd_status_bad_request(c, msg_in, "bad derive_shaseed");
920 
921 	if (!per_commit_point(&shaseed, &per_commitment_point, n))
922 		return hsmd_status_bad_request_fmt(
923 		    c, msg_in, "bad per_commit_point %" PRIu64, n);
924 
925 	if (n >= 2) {
926 		old_secret = tal(tmpctx, struct secret);
927 		if (!per_commit_secret(&shaseed, old_secret, n - 2)) {
928 			return hsmd_status_bad_request_fmt(
929 			    c, msg_in, "Cannot derive secret %" PRIu64, n - 2);
930 		}
931 	} else
932 		old_secret = NULL;
933 
934 	/*~ hsm_client_wire.csv marks the secret field here optional, so it only
935 	 * gets included if the parameter is non-NULL.  We violate 80 columns
936 	 * pretty badly here, but it's a recommendation not a religion. */
937 	return towire_hsmd_get_per_commitment_point_reply(
938 	    NULL, &per_commitment_point, old_secret);
939 }
940 
941 /*~ lightningd asks us to sign a withdrawal; same as above but in theory
942  * we can do more to check the previous case is valid. */
handle_sign_withdrawal_tx(struct hsmd_client * c,const u8 * msg_in)943 static u8 *handle_sign_withdrawal_tx(struct hsmd_client *c, const u8 *msg_in)
944 {
945 	struct utxo **utxos;
946 	struct wally_psbt *psbt;
947 
948 	if (!fromwire_hsmd_sign_withdrawal(tmpctx, msg_in,
949 					  &utxos, &psbt))
950 		return hsmd_status_malformed_request(c, msg_in);
951 
952 	sign_our_inputs(utxos, psbt);
953 
954 	return towire_hsmd_sign_withdrawal_reply(NULL, psbt);
955 }
956 
957 /* This is used by closingd to sign off on a mutual close tx. */
handle_sign_mutual_close_tx(struct hsmd_client * c,const u8 * msg_in)958 static u8 *handle_sign_mutual_close_tx(struct hsmd_client *c, const u8 *msg_in)
959 {
960 	struct secret channel_seed;
961 	struct bitcoin_tx *tx;
962 	struct pubkey remote_funding_pubkey, local_funding_pubkey;
963 	struct bitcoin_signature sig;
964 	struct secrets secrets;
965 	const u8 *funding_wscript;
966 
967 	if (!fromwire_hsmd_sign_mutual_close_tx(tmpctx, msg_in,
968 					       &tx,
969 					       &remote_funding_pubkey))
970 		return hsmd_status_malformed_request(c, msg_in);
971 
972 	tx->chainparams = c->chainparams;
973 	/* FIXME: We should know dust level, decent fee range and
974 	 * balances, and final_keyindex, and thus be able to check tx
975 	 * outputs! */
976 	get_channel_seed(&c->id, c->dbid, &channel_seed);
977 	derive_basepoints(&channel_seed,
978 			  &local_funding_pubkey, NULL, &secrets, NULL);
979 
980 	funding_wscript = bitcoin_redeem_2of2(tmpctx,
981 					      &local_funding_pubkey,
982 					      &remote_funding_pubkey);
983 	sign_tx_input(tx, 0, NULL, funding_wscript,
984 		      &secrets.funding_privkey,
985 		      &local_funding_pubkey,
986 		      SIGHASH_ALL, &sig);
987 
988 	return towire_hsmd_sign_tx_reply(NULL, &sig);
989 }
990 
991 /*~ This is used when a commitment transaction is onchain, and has an HTLC
992  * output paying to them, which has timed out; this signs that transaction,
993  * which lightningd will broadcast to collect the funds. */
handle_sign_local_htlc_tx(struct hsmd_client * c,const u8 * msg_in)994 static u8 *handle_sign_local_htlc_tx(struct hsmd_client *c, const u8 *msg_in)
995 {
996 	u64 commit_num;
997 	struct secret channel_seed, htlc_basepoint_secret;
998 	struct sha256 shaseed;
999 	struct pubkey per_commitment_point, htlc_basepoint;
1000 	struct bitcoin_tx *tx;
1001 	u8 *wscript;
1002 	struct bitcoin_signature sig;
1003 	struct privkey htlc_privkey;
1004 	struct pubkey htlc_pubkey;
1005 	bool option_anchor_outputs;
1006 
1007 	if (!fromwire_hsmd_sign_local_htlc_tx(tmpctx, msg_in,
1008 					     &commit_num, &tx, &wscript,
1009 					     &option_anchor_outputs))
1010 		return hsmd_status_malformed_request(c, msg_in);
1011 
1012 	tx->chainparams = c->chainparams;
1013 	get_channel_seed(&c->id, c->dbid, &channel_seed);
1014 
1015 	if (!derive_shaseed(&channel_seed, &shaseed))
1016 		return hsmd_status_bad_request_fmt(c, msg_in,
1017 						   "bad derive_shaseed");
1018 
1019 	if (!per_commit_point(&shaseed, &per_commitment_point, commit_num))
1020 		return hsmd_status_bad_request_fmt(
1021 		    c, msg_in, "bad per_commitment_point %" PRIu64, commit_num);
1022 
1023 	if (!derive_htlc_basepoint(&channel_seed,
1024 				   &htlc_basepoint,
1025 				   &htlc_basepoint_secret))
1026 		return hsmd_status_bad_request_fmt(
1027 		    c, msg_in, "Failed deriving htlc basepoint");
1028 
1029 	if (!derive_simple_privkey(&htlc_basepoint_secret,
1030 				   &htlc_basepoint,
1031 				   &per_commitment_point,
1032 				   &htlc_privkey))
1033 		return hsmd_status_bad_request_fmt(
1034 		    c, msg_in, "Failed deriving htlc privkey");
1035 
1036 	if (!pubkey_from_privkey(&htlc_privkey, &htlc_pubkey))
1037 		return hsmd_status_bad_request_fmt(c, msg_in,
1038 						   "bad pubkey_from_privkey");
1039 
1040 	if (tx->wtx->num_inputs != 1)
1041 		return hsmd_status_bad_request_fmt(c, msg_in,
1042 						   "bad txinput count");
1043 
1044 	/* FIXME: Check that output script is correct! */
1045 
1046 	/* BOLT #3:
1047 	 * ## HTLC-Timeout and HTLC-Success Transactions
1048 	 *...
1049 	 * * if `option_anchors` applies to this commitment transaction,
1050 	 *   `SIGHASH_SINGLE|SIGHASH_ANYONECANPAY` is used.
1051 	 */
1052 	sign_tx_input(tx, 0, NULL, wscript, &htlc_privkey, &htlc_pubkey,
1053 		      option_anchor_outputs
1054 		      ? (SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)
1055 		      : SIGHASH_ALL,
1056 		      &sig);
1057 
1058 	return towire_hsmd_sign_tx_reply(NULL, &sig);
1059 }
1060 
1061 /*~ This is used by channeld to create signatures for the remote peer's
1062  * HTLC transactions. */
handle_sign_remote_htlc_tx(struct hsmd_client * c,const u8 * msg_in)1063 static u8 *handle_sign_remote_htlc_tx(struct hsmd_client *c, const u8 *msg_in)
1064 {
1065 	struct secret channel_seed;
1066 	struct bitcoin_tx *tx;
1067 	struct bitcoin_signature sig;
1068 	struct secrets secrets;
1069 	struct basepoints basepoints;
1070 	struct pubkey remote_per_commit_point;
1071 	u8 *wscript;
1072 	struct privkey htlc_privkey;
1073 	struct pubkey htlc_pubkey;
1074 	bool option_anchor_outputs;
1075 
1076 	if (!fromwire_hsmd_sign_remote_htlc_tx(tmpctx, msg_in,
1077 					      &tx, &wscript,
1078 					      &remote_per_commit_point,
1079 					      &option_anchor_outputs))
1080 		return hsmd_status_malformed_request(c, msg_in);
1081 
1082 	tx->chainparams = c->chainparams;
1083 	get_channel_seed(&c->id, c->dbid, &channel_seed);
1084 	derive_basepoints(&channel_seed, NULL, &basepoints, &secrets, NULL);
1085 
1086 	if (!derive_simple_privkey(&secrets.htlc_basepoint_secret,
1087 				   &basepoints.htlc,
1088 				   &remote_per_commit_point,
1089 				   &htlc_privkey))
1090 		return hsmd_status_bad_request_fmt(
1091 		    c, msg_in, "Failed deriving htlc privkey");
1092 
1093 	if (!derive_simple_key(&basepoints.htlc,
1094 			       &remote_per_commit_point,
1095 			       &htlc_pubkey))
1096 		return hsmd_status_bad_request_fmt(
1097 		    c, msg_in, "Failed deriving htlc pubkey");
1098 
1099 	/* BOLT #3:
1100 	 * ## HTLC-Timeout and HTLC-Success Transactions
1101 	 *...
1102 	 * * if `option_anchors` applies to this commitment transaction,
1103 	 *   `SIGHASH_SINGLE|SIGHASH_ANYONECANPAY` is used.
1104 	 */
1105 	sign_tx_input(tx, 0, NULL, wscript, &htlc_privkey, &htlc_pubkey,
1106 		      option_anchor_outputs
1107 		      ? (SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)
1108 		      : SIGHASH_ALL, &sig);
1109 
1110 	return towire_hsmd_sign_tx_reply(NULL, &sig);
1111 }
1112 
1113 /*~ This is used by channeld to create signatures for the remote peer's
1114  * commitment transaction.  It's functionally identical to signing our own,
1115  * but we expect to do this repeatedly as commitment transactions are
1116  * updated.
1117  *
1118  * The HSM almost certainly *should* do more checks before signing!
1119  */
1120 /* FIXME: make sure it meets some criteria? */
handle_sign_remote_commitment_tx(struct hsmd_client * c,const u8 * msg_in)1121 static u8 *handle_sign_remote_commitment_tx(struct hsmd_client *c, const u8 *msg_in)
1122 {
1123 	struct pubkey remote_funding_pubkey, local_funding_pubkey;
1124 	struct secret channel_seed;
1125 	struct bitcoin_tx *tx;
1126 	struct bitcoin_signature sig;
1127 	struct secrets secrets;
1128 	const u8 *funding_wscript;
1129 	struct pubkey remote_per_commit;
1130 	bool option_static_remotekey;
1131 
1132 	if (!fromwire_hsmd_sign_remote_commitment_tx(tmpctx, msg_in,
1133 						    &tx,
1134 						    &remote_funding_pubkey,
1135 						    &remote_per_commit,
1136 						    &option_static_remotekey))
1137 		return hsmd_status_malformed_request(c, msg_in);
1138 	tx->chainparams = c->chainparams;
1139 
1140 	/* Basic sanity checks. */
1141 	if (tx->wtx->num_inputs != 1)
1142 		return hsmd_status_bad_request_fmt(c, msg_in,
1143 						   "tx must have 1 input");
1144 
1145 	if (tx->wtx->num_outputs == 0)
1146 		return hsmd_status_bad_request_fmt(c, msg_in,
1147 						   "tx must have > 0 outputs");
1148 
1149 	get_channel_seed(&c->id, c->dbid, &channel_seed);
1150 	derive_basepoints(&channel_seed,
1151 			  &local_funding_pubkey, NULL, &secrets, NULL);
1152 
1153 	funding_wscript = bitcoin_redeem_2of2(tmpctx,
1154 					      &local_funding_pubkey,
1155 					      &remote_funding_pubkey);
1156 	sign_tx_input(tx, 0, NULL, funding_wscript,
1157 		      &secrets.funding_privkey,
1158 		      &local_funding_pubkey,
1159 		      SIGHASH_ALL,
1160 		      &sig);
1161 
1162 	return towire_hsmd_sign_tx_reply(NULL, &sig);
1163 }
1164 
1165 /*~ This is used when the remote peer's commitment transaction is revoked;
1166  * we can use the revocation secret to spend the outputs.  For simplicity,
1167  * we do them one at a time, though. */
handle_sign_penalty_to_us(struct hsmd_client * c,const u8 * msg_in)1168 static u8 *handle_sign_penalty_to_us(struct hsmd_client *c, const u8 *msg_in)
1169 {
1170 	struct secret channel_seed, revocation_secret, revocation_basepoint_secret;
1171 	struct pubkey revocation_basepoint;
1172 	struct bitcoin_tx *tx;
1173 	struct pubkey point;
1174 	struct privkey privkey;
1175 	u8 *wscript;
1176 
1177 	if (!fromwire_hsmd_sign_penalty_to_us(tmpctx, msg_in,
1178 					     &revocation_secret,
1179 					     &tx, &wscript))
1180 		return hsmd_status_malformed_request(c, msg_in);
1181 	tx->chainparams = c->chainparams;
1182 
1183 	if (!pubkey_from_secret(&revocation_secret, &point))
1184 		return hsmd_status_bad_request_fmt(c, msg_in,
1185 						   "Failed deriving pubkey");
1186 
1187 	get_channel_seed(&c->id, c->dbid, &channel_seed);
1188 	if (!derive_revocation_basepoint(&channel_seed,
1189 					 &revocation_basepoint,
1190 					 &revocation_basepoint_secret))
1191 		return hsmd_status_bad_request_fmt(
1192 		    c, msg_in, "Failed deriving revocation basepoint");
1193 
1194 	if (!derive_revocation_privkey(&revocation_basepoint_secret,
1195 				       &revocation_secret,
1196 				       &revocation_basepoint,
1197 				       &point,
1198 				       &privkey))
1199 		return hsmd_status_bad_request_fmt(
1200 		    c, msg_in, "Failed deriving revocation privkey");
1201 
1202 	return handle_sign_to_us_tx(c, msg_in, tx, &privkey, wscript,
1203 				    SIGHASH_ALL);
1204 }
1205 
1206 /*~ This is another lightningd-only interface; signing a commit transaction.
1207  * This is dangerous, since if we sign a revoked commitment tx we'll lose
1208  * funds, thus it's only available to lightningd.
1209  *
1210  *
1211  * Oh look, another FIXME! */
1212 /* FIXME: Ensure HSM never does this twice for same dbid! */
handle_sign_commitment_tx(struct hsmd_client * c,const u8 * msg_in)1213 static u8 *handle_sign_commitment_tx(struct hsmd_client *c, const u8 *msg_in)
1214 {
1215 	struct pubkey remote_funding_pubkey, local_funding_pubkey;
1216 	struct node_id peer_id;
1217 	u64 dbid;
1218 	struct secret channel_seed;
1219 	struct bitcoin_tx *tx;
1220 	struct bitcoin_signature sig;
1221 	struct secrets secrets;
1222 	const u8 *funding_wscript;
1223 
1224 	if (!fromwire_hsmd_sign_commitment_tx(tmpctx, msg_in,
1225 					     &peer_id, &dbid,
1226 					     &tx,
1227 					     &remote_funding_pubkey))
1228 		return hsmd_status_malformed_request(c, msg_in);
1229 
1230 	tx->chainparams = c->chainparams;
1231 
1232 	/* Basic sanity checks. */
1233 	if (tx->wtx->num_inputs != 1)
1234 		return hsmd_status_bad_request(c, msg_in,
1235 					       "tx must have 1 input");
1236 
1237 	if (tx->wtx->num_outputs == 0)
1238 		return hsmd_status_bad_request_fmt(c, msg_in,
1239 						   "tx must have > 0 outputs");
1240 
1241 	get_channel_seed(&peer_id, dbid, &channel_seed);
1242 	derive_basepoints(&channel_seed,
1243 			  &local_funding_pubkey, NULL, &secrets, NULL);
1244 
1245 	/*~ Bitcoin signatures cover the (part of) the script they're
1246 	 * executing; the rules are a bit complex in general, but for
1247 	 * Segregated Witness it's simply the current script. */
1248 	funding_wscript = bitcoin_redeem_2of2(tmpctx,
1249 					      &local_funding_pubkey,
1250 					      &remote_funding_pubkey);
1251 	sign_tx_input(tx, 0, NULL, funding_wscript,
1252 		      &secrets.funding_privkey,
1253 		      &local_funding_pubkey,
1254 		      SIGHASH_ALL,
1255 		      &sig);
1256 
1257 	return towire_hsmd_sign_commitment_tx_reply(NULL, &sig);
1258 }
1259 
1260 /*~ This is used when a commitment transaction is onchain, and has an HTLC
1261  * output paying to us (because we have the preimage); this signs that
1262  * transaction, which lightningd will broadcast to collect the funds. */
handle_sign_remote_htlc_to_us(struct hsmd_client * c,const u8 * msg_in)1263 static u8 *handle_sign_remote_htlc_to_us(struct hsmd_client *c,
1264 					 const u8 *msg_in)
1265 {
1266 	struct secret channel_seed, htlc_basepoint_secret;
1267 	struct pubkey htlc_basepoint;
1268 	struct bitcoin_tx *tx;
1269 	struct pubkey remote_per_commitment_point;
1270 	struct privkey privkey;
1271 	u8 *wscript;
1272 	bool option_anchor_outputs;
1273 
1274 	if (!fromwire_hsmd_sign_remote_htlc_to_us(
1275 		tmpctx, msg_in, &remote_per_commitment_point, &tx, &wscript,
1276 		&option_anchor_outputs))
1277 		return hsmd_status_malformed_request(c, msg_in);
1278 
1279 	tx->chainparams = c->chainparams;
1280 	get_channel_seed(&c->id, c->dbid, &channel_seed);
1281 
1282 	if (!derive_htlc_basepoint(&channel_seed, &htlc_basepoint,
1283 				   &htlc_basepoint_secret))
1284 		return hsmd_status_bad_request(c, msg_in,
1285 					       "Failed derive_htlc_basepoint");
1286 
1287 	if (!derive_simple_privkey(&htlc_basepoint_secret,
1288 				   &htlc_basepoint,
1289 				   &remote_per_commitment_point,
1290 				   &privkey))
1291 		return hsmd_status_bad_request(c, msg_in,
1292 					       "Failed deriving htlc privkey");
1293 
1294 	/* BOLT #3:
1295 	 * ## HTLC-Timeout and HTLC-Success Transactions
1296 	 *...
1297 	 * * if `option_anchors` applies to this commitment transaction,
1298 	 *   `SIGHASH_SINGLE|SIGHASH_ANYONECANPAY` is used.
1299 	 */
1300 	return handle_sign_to_us_tx(
1301 	    c, msg_in, tx, &privkey, wscript,
1302 	    option_anchor_outputs ? (SIGHASH_SINGLE | SIGHASH_ANYONECANPAY)
1303 				  : SIGHASH_ALL);
1304 }
1305 
1306 /*~ When we send a commitment transaction onchain (unilateral close), there's
1307  * a delay before we can spend it.  onchaind does an explicit transaction to
1308  * transfer it to the wallet so that doesn't need to remember how to spend
1309  * this complex transaction. */
handle_sign_delayed_payment_to_us(struct hsmd_client * c,const u8 * msg_in)1310 static u8 *handle_sign_delayed_payment_to_us(struct hsmd_client *c,
1311 					     const u8 *msg_in)
1312 {
1313 	u64 commit_num;
1314 	struct secret channel_seed, basepoint_secret;
1315 	struct pubkey basepoint;
1316 	struct bitcoin_tx *tx;
1317 	struct sha256 shaseed;
1318 	struct pubkey per_commitment_point;
1319 	struct privkey privkey;
1320 	u8 *wscript;
1321 
1322 	/*~ We don't derive the wscript ourselves, but perhaps we should? */
1323 	if (!fromwire_hsmd_sign_delayed_payment_to_us(tmpctx, msg_in,
1324 						     &commit_num,
1325 						     &tx, &wscript))
1326 		return hsmd_status_malformed_request(c, msg_in);
1327 	tx->chainparams = c->chainparams;
1328 	get_channel_seed(&c->id, c->dbid, &channel_seed);
1329 
1330 	/*~ ccan/crypto/shachain how we efficiently derive 2^48 ordered
1331 	 * preimages from a single seed; the twist is that as the preimages
1332 	 * are revealed, you can generate the previous ones yourself, needing
1333 	 * to only keep log(N) of them at any time. */
1334 	if (!derive_shaseed(&channel_seed, &shaseed))
1335 		return hsmd_status_bad_request(c, msg_in, "bad derive_shaseed");
1336 
1337 	/*~ BOLT #3 describes exactly how this is used to generate the Nth
1338 	 * per-commitment point. */
1339 	if (!per_commit_point(&shaseed, &per_commitment_point, commit_num))
1340 		return hsmd_status_bad_request_fmt(
1341 		    c, msg_in, "bad per_commitment_point %" PRIu64, commit_num);
1342 
1343 	/*~ ... which is combined with the basepoint to generate then N'th key.
1344 	 */
1345 	if (!derive_delayed_payment_basepoint(&channel_seed,
1346 					      &basepoint,
1347 					      &basepoint_secret))
1348 		return hsmd_status_bad_request(c, msg_in,
1349 					       "failed deriving basepoint");
1350 
1351 	if (!derive_simple_privkey(&basepoint_secret,
1352 				   &basepoint,
1353 				   &per_commitment_point,
1354 				   &privkey))
1355 		return hsmd_status_bad_request(c, msg_in,
1356 					       "failed deriving privkey");
1357 
1358 	return handle_sign_to_us_tx(c, msg_in, tx, &privkey, wscript,
1359 				    SIGHASH_ALL);
1360 }
1361 
hsmd_handle_client_message(const tal_t * ctx,struct hsmd_client * client,const u8 * msg)1362 u8 *hsmd_handle_client_message(const tal_t *ctx, struct hsmd_client *client,
1363 			       const u8 *msg)
1364 {
1365 	enum hsmd_wire t = fromwire_peektype(msg);
1366 
1367 	hsmd_status_debug("Client: Received message %d from client", t);
1368 
1369 	/* Before we do anything else, is this client allowed to do
1370 	 * what he asks for? */
1371 	if (!hsmd_check_client_capabilities(client, t))
1372 		return hsmd_status_bad_request_fmt(
1373 		    client, msg, "does not have capability to run %d", t);
1374 
1375 	/* If we aren't initialized yet we better get an init message
1376 	 * first. Otherwise we don't load the secret and every
1377 	 * signature we produce is just going to be junk. */
1378 	if (!initialized && t != WIRE_HSMD_INIT)
1379 		hsmd_status_failed(STATUS_FAIL_MASTER_IO,
1380 			      "hsmd was not initialized correctly, expected "
1381 			      "message type %d, got %d",
1382 			      WIRE_HSMD_INIT, t);
1383 
1384 	/* Now actually go and do what the client asked for */
1385 	switch (t) {
1386 	case WIRE_HSMD_INIT:
1387 	case WIRE_HSMD_CLIENT_HSMFD:
1388 		/* Not implemented yet. Should not have been passed here yet. */
1389 		return hsmd_status_bad_request_fmt(
1390 		    client, msg,
1391 		    "Message of type %s should be handled externally to "
1392 		    "libhsmd",
1393 		    hsmd_wire_name(t));
1394 
1395 	case WIRE_HSMD_GET_OUTPUT_SCRIPTPUBKEY:
1396 		return handle_get_output_scriptpubkey(client, msg);
1397 	case WIRE_HSMD_CHECK_FUTURE_SECRET:
1398 		return handle_check_future_secret(client, msg);
1399 	case WIRE_HSMD_ECDH_REQ:
1400 		return handle_ecdh(client, msg);
1401 	case WIRE_HSMD_SIGN_INVOICE:
1402 		return handle_sign_invoice(client, msg);
1403 	case WIRE_HSMD_SIGN_OPTION_WILL_FUND_OFFER:
1404 		return handle_sign_option_will_fund_offer(client, msg);
1405 	case WIRE_HSMD_SIGN_BOLT12:
1406 		return handle_sign_bolt12(client, msg);
1407 	case WIRE_HSMD_SIGN_MESSAGE:
1408 		return handle_sign_message(client, msg);
1409 	case WIRE_HSMD_GET_CHANNEL_BASEPOINTS:
1410 		return handle_get_channel_basepoints(client, msg);
1411 	case WIRE_HSMD_CANNOUNCEMENT_SIG_REQ:
1412 		return handle_cannouncement_sig(client, msg);
1413 	case WIRE_HSMD_NODE_ANNOUNCEMENT_SIG_REQ:
1414 		return handle_sign_node_announcement(client, msg);
1415 	case WIRE_HSMD_CUPDATE_SIG_REQ:
1416 		return handle_channel_update_sig(client, msg);
1417 	case WIRE_HSMD_GET_PER_COMMITMENT_POINT:
1418 		return handle_get_per_commitment_point(client, msg);
1419 	case WIRE_HSMD_SIGN_WITHDRAWAL:
1420 		return handle_sign_withdrawal_tx(client, msg);
1421 	case WIRE_HSMD_SIGN_MUTUAL_CLOSE_TX:
1422 		return handle_sign_mutual_close_tx(client, msg);
1423 	case WIRE_HSMD_SIGN_LOCAL_HTLC_TX:
1424 		return handle_sign_local_htlc_tx(client, msg);
1425 	case WIRE_HSMD_SIGN_REMOTE_HTLC_TX:
1426 		return handle_sign_remote_htlc_tx(client, msg);
1427 	case WIRE_HSMD_SIGN_REMOTE_COMMITMENT_TX:
1428 		return handle_sign_remote_commitment_tx(client, msg);
1429 	case WIRE_HSMD_SIGN_PENALTY_TO_US:
1430 		return handle_sign_penalty_to_us(client, msg);
1431 	case WIRE_HSMD_SIGN_COMMITMENT_TX:
1432 		return handle_sign_commitment_tx(client, msg);
1433 	case WIRE_HSMD_SIGN_REMOTE_HTLC_TO_US:
1434 		return handle_sign_remote_htlc_to_us(client, msg);
1435 	case WIRE_HSMD_SIGN_DELAYED_PAYMENT_TO_US:
1436 		return handle_sign_delayed_payment_to_us(client, msg);
1437 
1438 	case WIRE_HSMD_DEV_MEMLEAK:
1439 	case WIRE_HSMD_ECDH_RESP:
1440 	case WIRE_HSMD_CANNOUNCEMENT_SIG_REPLY:
1441 	case WIRE_HSMD_CUPDATE_SIG_REPLY:
1442 	case WIRE_HSMD_CLIENT_HSMFD_REPLY:
1443 	case WIRE_HSMD_NODE_ANNOUNCEMENT_SIG_REPLY:
1444 	case WIRE_HSMD_SIGN_WITHDRAWAL_REPLY:
1445 	case WIRE_HSMD_SIGN_INVOICE_REPLY:
1446 	case WIRE_HSMD_INIT_REPLY:
1447 	case WIRE_HSMSTATUS_CLIENT_BAD_REQUEST:
1448 	case WIRE_HSMD_SIGN_COMMITMENT_TX_REPLY:
1449 	case WIRE_HSMD_SIGN_TX_REPLY:
1450 	case WIRE_HSMD_SIGN_OPTION_WILL_FUND_OFFER_REPLY:
1451 	case WIRE_HSMD_GET_PER_COMMITMENT_POINT_REPLY:
1452 	case WIRE_HSMD_CHECK_FUTURE_SECRET_REPLY:
1453 	case WIRE_HSMD_GET_CHANNEL_BASEPOINTS_REPLY:
1454 	case WIRE_HSMD_DEV_MEMLEAK_REPLY:
1455 	case WIRE_HSMD_SIGN_MESSAGE_REPLY:
1456 	case WIRE_HSMD_GET_OUTPUT_SCRIPTPUBKEY_REPLY:
1457 	case WIRE_HSMD_SIGN_BOLT12_REPLY:
1458 		break;
1459 	}
1460 	return hsmd_status_bad_request(client, msg, "Unknown request");
1461 }
1462 
hsmd_init(struct secret hsm_secret,struct bip32_key_version bip32_key_version)1463 u8 *hsmd_init(struct secret hsm_secret,
1464 	      struct bip32_key_version bip32_key_version)
1465 {
1466 	u8 bip32_seed[BIP32_ENTROPY_LEN_256];
1467 	struct pubkey key;
1468 	struct point32 bolt12;
1469 	u32 salt = 0;
1470 	struct ext_key master_extkey, child_extkey;
1471 	struct node_id node_id;
1472 	struct secret onion_reply_secret;
1473 
1474 	/*~ Don't swap this. */
1475 	sodium_mlock(secretstuff.hsm_secret.data,
1476 		     sizeof(secretstuff.hsm_secret.data));
1477 	memcpy(secretstuff.hsm_secret.data, hsm_secret.data, sizeof(hsm_secret.data));
1478 
1479 	assert(bip32_key_version.bip32_pubkey_version == BIP32_VER_MAIN_PUBLIC
1480 			|| bip32_key_version.bip32_pubkey_version == BIP32_VER_TEST_PUBLIC);
1481 
1482 	assert(bip32_key_version.bip32_privkey_version == BIP32_VER_MAIN_PRIVATE
1483 			|| bip32_key_version.bip32_privkey_version == BIP32_VER_TEST_PRIVATE);
1484 
1485 	/* Fill in the BIP32 tree for bitcoin addresses. */
1486 	/* In libwally-core, the version BIP32_VER_TEST_PRIVATE is for testnet/regtest,
1487 	 * and BIP32_VER_MAIN_PRIVATE is for mainnet. For litecoin, we also set it like
1488 	 * bitcoin else.*/
1489 	do {
1490 		hkdf_sha256(bip32_seed, sizeof(bip32_seed),
1491 			    &salt, sizeof(salt),
1492 			    &secretstuff.hsm_secret,
1493 			    sizeof(secretstuff.hsm_secret),
1494 			    "bip32 seed", strlen("bip32 seed"));
1495 		salt++;
1496 	} while (bip32_key_from_seed(bip32_seed, sizeof(bip32_seed),
1497 				     bip32_key_version.bip32_privkey_version,
1498 				     0, &master_extkey) != WALLY_OK);
1499 
1500 #if DEVELOPER
1501 	/* In DEVELOPER mode, we can override with --dev-force-bip32-seed */
1502 	if (dev_force_bip32_seed) {
1503 		if (bip32_key_from_seed(dev_force_bip32_seed->data,
1504 					sizeof(dev_force_bip32_seed->data),
1505 					bip32_key_version.bip32_privkey_version,
1506 					0, &master_extkey) != WALLY_OK)
1507 			hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
1508 					   "Can't derive bip32 master key");
1509 	}
1510 #endif /* DEVELOPER */
1511 
1512 	/* BIP 32:
1513 	 *
1514 	 * The default wallet layout
1515 	 *
1516 	 * An HDW is organized as several 'accounts'. Accounts are numbered,
1517 	 * the default account ("") being number 0. Clients are not required
1518 	 * to support more than one account - if not, they only use the
1519 	 * default account.
1520 	 *
1521 	 * Each account is composed of two keypair chains: an internal and an
1522 	 * external one. The external keychain is used to generate new public
1523 	 * addresses, while the internal keychain is used for all other
1524 	 * operations (change addresses, generation addresses, ..., anything
1525 	 * that doesn't need to be communicated). Clients that do not support
1526 	 * separate keychains for these should use the external one for
1527 	 * everything.
1528 	 *
1529 	 *  - m/iH/0/k corresponds to the k'th keypair of the external chain of
1530 	 * account number i of the HDW derived from master m.
1531 	 */
1532 	/* Hence child 0, then child 0 again to get extkey to derive from. */
1533 	if (bip32_key_from_parent(&master_extkey, 0, BIP32_FLAG_KEY_PRIVATE,
1534 				  &child_extkey) != WALLY_OK)
1535 		/*~ status_failed() is a helper which exits and sends lightningd
1536 		 * a message about what happened.  For hsmd, that's fatal to
1537 		 * lightningd. */
1538 		hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
1539 				   "Can't derive child bip32 key");
1540 
1541 	if (bip32_key_from_parent(&child_extkey, 0, BIP32_FLAG_KEY_PRIVATE,
1542 				  &secretstuff.bip32) != WALLY_OK)
1543 		hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
1544 				   "Can't derive private bip32 key");
1545 
1546 	/* BIP 33:
1547 	 *
1548 	 * We propose the first level of BIP32 tree structure to be used as
1549 	 * "purpose". This purpose determines the further structure beneath
1550 	 * this node.
1551 	 *
1552 	 *  m / purpose' / *
1553 	 *
1554 	 * Apostrophe indicates that BIP32 hardened derivation is used.
1555 	 *
1556 	 * We encourage different schemes to apply for assigning a separate
1557 	 * BIP number and use the same number for purpose field, so addresses
1558 	 * won't be generated from overlapping BIP32 spaces.
1559 	 *
1560 	 * Example: Scheme described in BIP44 should use 44' (or 0x8000002C)
1561 	 * as purpose.
1562 	 */
1563 	/* Clearly, we should use 9735, the unicode point for lightning! */
1564 	if (bip32_key_from_parent(&master_extkey,
1565 				  BIP32_INITIAL_HARDENED_CHILD|9735,
1566 				  BIP32_FLAG_KEY_PRIVATE,
1567 				  &child_extkey) != WALLY_OK)
1568 		hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
1569 				   "Can't derive bolt12 bip32 key");
1570 
1571 	/* libwally says: The private key with prefix byte 0; remove it
1572 	 * for libsecp256k1. */
1573 	if (secp256k1_keypair_create(secp256k1_ctx, &secretstuff.bolt12,
1574 				     child_extkey.priv_key+1) != 1)
1575 		hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
1576 				   "Can't derive bolt12 keypair");
1577 
1578 	/* Now we can consider ourselves initialized, and we won't get
1579 	 * upset if we get a non-init message. */
1580 	initialized = true;
1581 
1582 	/*~ We tell lightning our node id and (public) bip32 seed. */
1583 	node_key(NULL, &key);
1584 	node_id_from_pubkey(&node_id, &key);
1585 
1586 	/* We also give it the base key for bolt12 payerids */
1587 	if (secp256k1_keypair_xonly_pub(secp256k1_ctx, &bolt12.pubkey, NULL,
1588 					&secretstuff.bolt12) != 1)
1589 		hsmd_status_failed(STATUS_FAIL_INTERNAL_ERROR,
1590 				   "Could derive bolt12 public key.");
1591 
1592 	/*~ We derive a secret for onion_message's self_id so we can tell
1593 	 * if it used a path we created (i.e. do not leak our public id!) */
1594 	hkdf_sha256(&onion_reply_secret, sizeof(onion_reply_secret),
1595 		    NULL, 0,
1596 		    &secretstuff.hsm_secret,
1597 		    sizeof(secretstuff.hsm_secret),
1598 		    "onion reply secret", strlen("onion reply secret"));
1599 
1600 	/*~ Note: marshalling a bip32 tree only marshals the public side,
1601 	 * not the secrets!  So we're not actually handing them out here!
1602 	 */
1603 	return take(towire_hsmd_init_reply(
1604 	    NULL, &node_id, &secretstuff.bip32,
1605 	    &bolt12, &onion_reply_secret));
1606 }
1607