1 #include "config.h"
2 #include <assert.h>
3 #include <bitcoin/chainparams.h>
4 #include <bitcoin/psbt.h>
5 #include <bitcoin/pubkey.h>
6 #include <bitcoin/script.h>
7 #include <ccan/ccan/array_size/array_size.h>
8 #include <ccan/ccan/mem/mem.h>
9 #include <ccan/tal/str/str.h>
10 #include <common/type_to_string.h>
11 #include <wally_psbt.h>
12 #include <wire/wire.h>
13 
14 
psbt_destroy(struct wally_psbt * psbt)15 void psbt_destroy(struct wally_psbt *psbt)
16 {
17 	wally_psbt_free(psbt);
18 }
19 
init_psbt(const tal_t * ctx,size_t num_inputs,size_t num_outputs)20 static struct wally_psbt *init_psbt(const tal_t *ctx, size_t num_inputs, size_t num_outputs)
21 {
22 	int wally_err;
23 	struct wally_psbt *psbt;
24 
25 	tal_wally_start();
26 	if (is_elements(chainparams))
27 		wally_err = wally_psbt_elements_init_alloc(0, num_inputs, num_outputs, 0, &psbt);
28 	else
29 		wally_err = wally_psbt_init_alloc(0, num_inputs, num_outputs, 0, &psbt);
30 	assert(wally_err == WALLY_OK);
31 	tal_add_destructor(psbt, psbt_destroy);
32 	tal_wally_end(tal_steal(ctx, psbt));
33 
34 	return psbt;
35 }
36 
create_psbt(const tal_t * ctx,size_t num_inputs,size_t num_outputs,u32 locktime)37 struct wally_psbt *create_psbt(const tal_t *ctx, size_t num_inputs, size_t num_outputs, u32 locktime)
38 {
39 	int wally_err;
40 	struct wally_tx *wtx;
41 	struct wally_psbt *psbt;
42 
43 	tal_wally_start();
44 	if (wally_tx_init_alloc(WALLY_TX_VERSION_2, locktime, num_inputs, num_outputs, &wtx) != WALLY_OK)
45 		abort();
46 	/* wtx is freed below */
47 	tal_wally_end(NULL);
48 
49 	psbt = init_psbt(ctx, num_inputs, num_outputs);
50 
51 	tal_wally_start();
52 	wally_err = wally_psbt_set_global_tx(psbt, wtx);
53 	assert(wally_err == WALLY_OK);
54 	tal_wally_end(psbt);
55 
56 	wally_tx_free(wtx);
57 	return psbt;
58 }
59 
clone_psbt(const tal_t * ctx,struct wally_psbt * psbt)60 struct wally_psbt *clone_psbt(const tal_t *ctx, struct wally_psbt *psbt)
61 {
62 	struct wally_psbt *clone;
63 	tal_wally_start();
64 	if (wally_psbt_clone_alloc(psbt, 0, &clone) != WALLY_OK)
65 		abort();
66 	tal_wally_end(tal_steal(ctx, clone));
67 	return clone;
68 }
69 
new_psbt(const tal_t * ctx,const struct wally_tx * wtx)70 struct wally_psbt *new_psbt(const tal_t *ctx, const struct wally_tx *wtx)
71 {
72 	struct wally_psbt *psbt;
73 	int wally_err;
74 
75 	psbt = init_psbt(ctx, wtx->num_inputs, wtx->num_outputs);
76 
77 	tal_wally_start();
78 	/* Set directly: avoids psbt checks for non-NULL scripts/witnesses */
79 	wally_err = wally_tx_clone_alloc(wtx, 0, &psbt->tx);
80 	assert(wally_err == WALLY_OK);
81 	/* Inputs/outs are pre-allocated above, 'add' them as empty dummies */
82 	psbt->num_inputs = wtx->num_inputs;
83 	psbt->num_outputs = wtx->num_outputs;
84 
85 	for (size_t i = 0; i < wtx->num_inputs; i++) {
86 		/* add these scripts + witnesses to the psbt */
87 		if (wtx->inputs[i].script) {
88 			wally_err =
89 				wally_psbt_input_set_final_scriptsig(&psbt->inputs[i],
90 								     wtx->inputs[i].script,
91 								     wtx->inputs[i].script_len);
92 			assert(wally_err == WALLY_OK);
93 		}
94 		if (wtx->inputs[i].witness) {
95 			wally_err =
96 				wally_psbt_input_set_final_witness(&psbt->inputs[i],
97 								   wtx->inputs[i].witness);
98 			assert(wally_err == WALLY_OK);
99 		}
100 	}
101 
102 	tal_wally_end(psbt);
103 	return psbt;
104 }
105 
psbt_is_finalized(const struct wally_psbt * psbt)106 bool psbt_is_finalized(const struct wally_psbt *psbt)
107 {
108 	size_t is_finalized;
109 	int wally_err = wally_psbt_is_finalized(psbt, &is_finalized);
110 	assert(wally_err == WALLY_OK);
111 	return is_finalized ? true : false;
112 }
113 
psbt_add_input(struct wally_psbt * psbt,struct wally_tx_input * input,size_t insert_at)114 struct wally_psbt_input *psbt_add_input(struct wally_psbt *psbt,
115 					struct wally_tx_input *input,
116 				       	size_t insert_at)
117 {
118 	const u32 flags = WALLY_PSBT_FLAG_NON_FINAL; /* Skip script/witness */
119 	int wally_err;
120 
121 	tal_wally_start();
122 	wally_err = wally_psbt_add_input_at(psbt, insert_at, flags, input);
123 	assert(wally_err == WALLY_OK);
124 	tal_wally_end(psbt);
125 	return &psbt->inputs[insert_at];
126 }
127 
psbt_append_input(struct wally_psbt * psbt,const struct bitcoin_outpoint * outpoint,u32 sequence,const u8 * scriptSig,const u8 * input_wscript,const u8 * redeemscript)128 struct wally_psbt_input *psbt_append_input(struct wally_psbt *psbt,
129 					   const struct bitcoin_outpoint *outpoint,
130 					   u32 sequence,
131 					   const u8 *scriptSig,
132 					   const u8 *input_wscript,
133 					   const u8 *redeemscript)
134 {
135 	struct wally_tx_input *tx_in;
136 	size_t input_num = psbt->num_inputs;
137 	const u32 flags = WALLY_PSBT_FLAG_NON_FINAL; /* Skip script/witness */
138 	int wally_err;
139 
140 	tal_wally_start();
141 	if (chainparams->is_elements) {
142 		if (wally_tx_elements_input_init_alloc(outpoint->txid.shad.sha.u.u8,
143 						       sizeof(outpoint->txid.shad.sha.u.u8),
144 						       outpoint->n,
145 						       sequence, NULL, 0,
146 						       NULL,
147 						       NULL, 0,
148 						       NULL, 0, NULL, 0,
149 						       NULL, 0, NULL, 0,
150 						       NULL, 0, NULL,
151 						       &tx_in) != WALLY_OK)
152 			abort();
153 	} else {
154 		if (wally_tx_input_init_alloc(outpoint->txid.shad.sha.u.u8,
155 					      sizeof(outpoint->txid.shad.sha.u.u8),
156 					      outpoint->n,
157 					      sequence, NULL, 0, NULL,
158 					      &tx_in) != WALLY_OK)
159 			abort();
160 	}
161 
162 	wally_err = wally_psbt_add_input_at(psbt, input_num, flags, tx_in);
163 	assert(wally_err == WALLY_OK);
164 	wally_tx_input_free(tx_in);
165 	tal_wally_end(psbt);
166 
167 	if (input_wscript) {
168 		/* Add the prev output's data into the PSBT struct */
169 		psbt_input_set_witscript(psbt, input_num, input_wscript);
170 	}
171 
172 	if (redeemscript) {
173 		tal_wally_start();
174 		wally_err = wally_psbt_input_set_redeem_script(&psbt->inputs[input_num],
175 							       redeemscript,
176 							       tal_bytelen(redeemscript));
177 		assert(wally_err == WALLY_OK);
178 		tal_wally_end(psbt);
179 	}
180 
181 	return &psbt->inputs[input_num];
182 }
183 
psbt_rm_input(struct wally_psbt * psbt,size_t remove_at)184 void psbt_rm_input(struct wally_psbt *psbt,
185 		   size_t remove_at)
186 {
187 	int wally_err = wally_psbt_remove_input(psbt, remove_at);
188 	assert(wally_err == WALLY_OK);
189 }
190 
psbt_add_output(struct wally_psbt * psbt,struct wally_tx_output * output,size_t insert_at)191 struct wally_psbt_output *psbt_add_output(struct wally_psbt *psbt,
192 					  struct wally_tx_output *output,
193 					  size_t insert_at)
194 {
195 	int wally_err;
196 
197 	tal_wally_start();
198 	wally_err = wally_psbt_add_output_at(psbt, insert_at, 0, output);
199 	assert(wally_err == WALLY_OK);
200 	tal_wally_end(psbt);
201 	return &psbt->outputs[insert_at];
202 }
203 
psbt_append_output(struct wally_psbt * psbt,const u8 * script,struct amount_sat amount)204 struct wally_psbt_output *psbt_append_output(struct wally_psbt *psbt,
205 					     const u8 *script,
206 					     struct amount_sat amount)
207 {
208 	struct wally_psbt_output *out;
209 	struct wally_tx_output *tx_out = wally_tx_output(NULL, script, amount);
210 
211 	out = psbt_add_output(psbt, tx_out, psbt->tx->num_outputs);
212 	wally_tx_output_free(tx_out);
213 	return out;
214 }
psbt_insert_output(struct wally_psbt * psbt,const u8 * script,struct amount_sat amount,size_t insert_at)215 struct wally_psbt_output *psbt_insert_output(struct wally_psbt *psbt,
216 					     const u8 *script,
217 					     struct amount_sat amount,
218 					     size_t insert_at)
219 {
220 	struct wally_psbt_output *out;
221 	struct wally_tx_output *tx_out = wally_tx_output(NULL, script, amount);
222 
223 	out = psbt_add_output(psbt, tx_out, insert_at);
224 	wally_tx_output_free(tx_out);
225 	return out;
226 }
227 
psbt_rm_output(struct wally_psbt * psbt,size_t remove_at)228 void psbt_rm_output(struct wally_psbt *psbt,
229 		    size_t remove_at)
230 {
231 	int wally_err = wally_psbt_remove_output(psbt, remove_at);
232 	assert(wally_err == WALLY_OK);
233 }
234 
psbt_input_add_pubkey(struct wally_psbt * psbt,size_t in,const struct pubkey * pubkey)235 void psbt_input_add_pubkey(struct wally_psbt *psbt, size_t in,
236 			   const struct pubkey *pubkey)
237 {
238 	int wally_err;
239 	u32 empty_path[1] = {0};
240 	unsigned char fingerprint[4];
241 	struct ripemd160 hash;
242 	u8 pk_der[PUBKEY_CMPR_LEN];
243 
244 	assert(in < psbt->num_inputs);
245 
246 	/* Find the key identifier fingerprint:
247 	 * the first 32 bits of the identifier, where the identifier
248 	 * is the hash160 of the ECDSA serialized public key
249 	 * https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#key-identifiers
250 	 * */
251 	pubkey_to_hash160(pubkey, &hash);
252 	memcpy(fingerprint, hash.u.u8, sizeof(fingerprint));
253 
254 	/* we serialize the compressed version of the key, wally likes this */
255 	pubkey_to_der(pk_der, pubkey);
256 
257 	tal_wally_start();
258 	wally_err = wally_psbt_input_add_keypath_item(&psbt->inputs[in],
259 						      pk_der, sizeof(pk_der),
260 						      fingerprint, sizeof(fingerprint),
261 						      empty_path, ARRAY_SIZE(empty_path));
262 	assert(wally_err == WALLY_OK);
263 	tal_wally_end(psbt);
264 }
265 
psbt_input_set_signature(struct wally_psbt * psbt,size_t in,const struct pubkey * pubkey,const struct bitcoin_signature * sig)266 bool psbt_input_set_signature(struct wally_psbt *psbt, size_t in,
267 			      const struct pubkey *pubkey,
268 			      const struct bitcoin_signature *sig)
269 {
270 	u8 pk_der[PUBKEY_CMPR_LEN];
271 	bool ok;
272 
273 	assert(in < psbt->num_inputs);
274 
275 	/* we serialize the compressed version of the key, wally likes this */
276 	pubkey_to_der(pk_der, pubkey);
277 	tal_wally_start();
278 	wally_psbt_input_set_sighash(&psbt->inputs[in], sig->sighash_type);
279 	ok = wally_psbt_input_add_signature(&psbt->inputs[in],
280 					    pk_der, sizeof(pk_der),
281 					    sig->s.data,
282 					    sizeof(sig->s.data)) == WALLY_OK;
283 	tal_wally_end(psbt);
284 	return ok;
285 }
286 
psbt_input_set_wit_utxo(struct wally_psbt * psbt,size_t in,const u8 * scriptPubkey,struct amount_sat amt)287 void psbt_input_set_wit_utxo(struct wally_psbt *psbt, size_t in,
288 			     const u8 *scriptPubkey, struct amount_sat amt)
289 {
290 	struct wally_tx_output *tx_out;
291 	int wally_err;
292 
293 	assert(in < psbt->num_inputs);
294 	assert(tal_bytelen(scriptPubkey) > 0);
295 	tal_wally_start();
296 	if (is_elements(chainparams)) {
297 		u8 value[9];
298 		wally_err =
299 			wally_tx_confidential_value_from_satoshi(amt.satoshis, /* Raw: wally API */
300 								 value,
301 								 sizeof(value));
302 		assert(wally_err == WALLY_OK);
303 		wally_err =
304 			wally_tx_elements_output_init_alloc(scriptPubkey,
305 						      tal_bytelen(scriptPubkey),
306 						      chainparams->fee_asset_tag,
307 						      ELEMENTS_ASSET_LEN,
308 						      value, sizeof(value),
309 						      NULL, 0, NULL, 0,
310 						      NULL, 0, &tx_out);
311 
312 	} else
313 		wally_err = wally_tx_output_init_alloc(amt.satoshis, /* Raw: type conv */
314 						 scriptPubkey,
315 						 tal_bytelen(scriptPubkey),
316 						 &tx_out);
317 	assert(wally_err == WALLY_OK);
318 	wally_err = wally_psbt_input_set_witness_utxo(&psbt->inputs[in], tx_out);
319 	wally_tx_output_free(tx_out);
320 	assert(wally_err == WALLY_OK);
321 	tal_wally_end(psbt);
322 }
323 
psbt_input_set_utxo(struct wally_psbt * psbt,size_t in,const struct wally_tx * prev_tx)324 void psbt_input_set_utxo(struct wally_psbt *psbt, size_t in,
325 			 const struct wally_tx *prev_tx)
326 {
327 	int wally_err;
328 	tal_wally_start();
329 	wally_err = wally_psbt_input_set_utxo(&psbt->inputs[in],
330 					      prev_tx);
331 	tal_wally_end(psbt);
332 	assert(wally_err == WALLY_OK);
333 }
334 
psbt_input_set_witscript(struct wally_psbt * psbt,size_t in,const u8 * wscript)335 void psbt_input_set_witscript(struct wally_psbt *psbt, size_t in, const u8 *wscript)
336 {
337 	int wally_err;
338 
339 	tal_wally_start();
340 	wally_err = wally_psbt_input_set_witness_script(&psbt->inputs[in],
341 							wscript,
342 							tal_bytelen(wscript));
343 	assert(wally_err == WALLY_OK);
344 	tal_wally_end(psbt);
345 }
346 
psbt_elements_input_set_asset(struct wally_psbt * psbt,size_t in,struct amount_asset * asset)347 void psbt_elements_input_set_asset(struct wally_psbt *psbt, size_t in,
348 				   struct amount_asset *asset)
349 {
350 	tal_wally_start();
351 
352 	if (asset->value > 0)
353 		if (wally_psbt_input_set_value(&psbt->inputs[in],
354 					       asset->value) != WALLY_OK)
355 			abort();
356 
357 	/* PSET expects an asset tag without the prefix */
358 	if (wally_psbt_input_set_asset(&psbt->inputs[in],
359 				       asset->asset + 1,
360 				       ELEMENTS_ASSET_LEN - 1) != WALLY_OK)
361 		abort();
362 	tal_wally_end(psbt);
363 }
364 
psbt_elements_normalize_fees(struct wally_psbt * psbt)365 void psbt_elements_normalize_fees(struct wally_psbt *psbt)
366 {
367 	struct amount_asset asset;
368 	size_t fee_output_idx = psbt->num_outputs;
369 
370 	if (!is_elements(chainparams))
371 		return;
372 
373 	/* Elements requires that every input value is accounted for,
374 	 * including the fees */
375 	struct amount_sat total_in = AMOUNT_SAT(0), val;
376 	for (size_t i = 0; i < psbt->num_inputs; i++) {
377 		val = psbt_input_get_amount(psbt, i);
378 		if (!amount_sat_add(&total_in, total_in, val))
379 			return;
380 	}
381 	for (size_t i = 0; i < psbt->num_outputs; i++) {
382 		asset = wally_tx_output_get_amount(&psbt->tx->outputs[i]);
383 		if (elements_wtx_output_is_fee(psbt->tx, i)) {
384 			if (fee_output_idx == psbt->num_outputs) {
385 				fee_output_idx = i;
386 				continue;
387 			}
388 			/* We already have at least one fee output,
389 			 * remove this one */
390 			psbt_rm_output(psbt, i--);
391 			continue;
392 		}
393 		if (!amount_asset_is_main(&asset))
394 			continue;
395 
396 		if (!amount_sat_sub(&total_in, total_in,
397 				    amount_asset_to_sat(&asset)))
398 			return;
399 	}
400 
401 	if (amount_sat_eq(total_in, AMOUNT_SAT(0)))
402 		return;
403 
404 	/* We need to add a fee output */
405 	if (fee_output_idx == psbt->num_outputs) {
406 		psbt_append_output(psbt, NULL, total_in);
407 	} else {
408 		u64 sats = total_in.satoshis; /* Raw: wally API */
409 		struct wally_tx_output *out = &psbt->tx->outputs[fee_output_idx];
410 		if (wally_tx_confidential_value_from_satoshi(
411 			sats, out->value, out->value_len) != WALLY_OK)
412 			return;
413 	}
414 }
415 
psbt_has_input(const struct wally_psbt * psbt,const struct bitcoin_outpoint * outpoint)416 bool psbt_has_input(const struct wally_psbt *psbt,
417 		    const struct bitcoin_outpoint *outpoint)
418 {
419 	for (size_t i = 0; i < psbt->num_inputs; i++) {
420 		struct bitcoin_txid in_txid;
421 		struct wally_tx_input *in = &psbt->tx->inputs[i];
422 
423 		if (outpoint->n != in->index)
424 			continue;
425 
426 		wally_tx_input_get_txid(in, &in_txid);
427 		if (bitcoin_txid_eq(&outpoint->txid, &in_txid))
428 			return true;
429 	}
430 	return false;
431 }
432 
psbt_input_set_redeemscript(struct wally_psbt * psbt,size_t in,const u8 * redeemscript)433 bool psbt_input_set_redeemscript(struct wally_psbt *psbt, size_t in,
434 				 const u8 *redeemscript)
435 {
436 	int wally_err;
437 	assert(psbt->num_inputs > in);
438 	wally_err = wally_psbt_input_set_redeem_script(&psbt->inputs[in],
439 						       redeemscript,
440 						       tal_bytelen(redeemscript));
441 	return wally_err == WALLY_OK;
442 }
443 
psbt_input_get_amount(const struct wally_psbt * psbt,size_t in)444 struct amount_sat psbt_input_get_amount(const struct wally_psbt *psbt,
445 					size_t in)
446 {
447 	struct amount_sat val;
448 	assert(in < psbt->num_inputs);
449 	if (psbt->inputs[in].witness_utxo) {
450 		struct amount_asset amt_asset =
451 			wally_tx_output_get_amount(psbt->inputs[in].witness_utxo);
452 		assert(amount_asset_is_main(&amt_asset));
453 		val = amount_asset_to_sat(&amt_asset);
454 	} else if (psbt->inputs[in].utxo) {
455 		int idx = psbt->tx->inputs[in].index;
456 		struct wally_tx *prev_tx = psbt->inputs[in].utxo;
457 		val = amount_sat(prev_tx->outputs[idx].satoshi);
458 	} else
459 		abort();
460 
461 	return val;
462 }
463 
psbt_output_get_amount(const struct wally_psbt * psbt,size_t out)464 struct amount_sat psbt_output_get_amount(const struct wally_psbt *psbt,
465 					 size_t out)
466 {
467 	struct amount_asset asset;
468 	assert(out < psbt->num_outputs);
469 	asset = wally_tx_output_get_amount(&psbt->tx->outputs[out]);
470 	assert(amount_asset_is_main(&asset));
471 	return amount_asset_to_sat(&asset);
472 }
473 
add(u8 ** key,const void * mem,size_t len)474 static void add(u8 **key, const void *mem, size_t len)
475 {
476 	size_t oldlen = tal_count(*key);
477 	tal_resize(key, oldlen + len);
478 	memcpy(*key + oldlen, memcheck(mem, len), len);
479 }
480 
add_type(u8 ** key,const u8 num)481 static void add_type(u8 **key, const u8 num)
482 {
483 	add(key, &num, 1);
484 }
485 
add_varint(u8 ** key,size_t val)486 static void add_varint(u8 **key, size_t val)
487 {
488 	u8 vt[VARINT_MAX_LEN];
489 	size_t vtlen;
490 	vtlen = varint_put(vt, val);
491 	add(key, vt, vtlen);
492 }
493 
494 #define LIGHTNING_PROPRIETARY_PREFIX "lightning"
495 
psbt_make_key(const tal_t * ctx,u8 key_subtype,const u8 * key_data)496 u8 *psbt_make_key(const tal_t *ctx, u8 key_subtype, const u8 *key_data)
497 {
498 	/**
499 	 * BIP174:
500 	 * Type: Proprietary Use Type <tt>PSBT_GLOBAL_PROPRIETARY = 0xFC</tt>
501 	 ** Key: Variable length identifier prefix, followed
502 	 *       by a subtype, followed by the key data itself.
503 	 *** <tt>{0xFC}|<prefix>|{subtype}|{key data}</tt>
504 	 ** Value: Any value data as defined by the proprietary type user.
505 	 *** <tt><data></tt>
506 	 */
507 	u8 *key = tal_arr(ctx, u8, 0);
508 	add_type(&key, PSBT_PROPRIETARY_TYPE);
509 	add_varint(&key, strlen(LIGHTNING_PROPRIETARY_PREFIX));
510 	add(&key, LIGHTNING_PROPRIETARY_PREFIX,
511 	    strlen(LIGHTNING_PROPRIETARY_PREFIX));
512 	add_type(&key, key_subtype);
513 	if (key_data)
514 		add(&key, key_data, tal_bytelen(key_data));
515 	return key;
516 }
517 
wally_map_set_unknown(const tal_t * ctx,struct wally_map * map,const u8 * key,const void * value,size_t value_len)518 static bool wally_map_set_unknown(const tal_t *ctx,
519 				  struct wally_map *map,
520 				  const u8 *key,
521 				  const void *value,
522 				  size_t value_len)
523 {
524 	size_t exists_at;
525 	struct wally_map_item *item;
526 
527 	assert(value_len != 0);
528 	if (wally_map_find(map, key, tal_bytelen(key), &exists_at) != WALLY_OK)
529 		return false;
530 
531 	/* If not exists, add */
532 	if (exists_at == 0) {
533 		bool ok;
534 		tal_wally_start();
535 		ok = wally_map_add(map, key, tal_bytelen(key),
536 			      (unsigned char *) memcheck(value, value_len), value_len)
537 			== WALLY_OK;
538 		tal_wally_end(ctx);
539 		return ok;
540 	}
541 
542 	/* Already in map, update entry */
543 	item = &map->items[exists_at - 1];
544 	tal_resize(&item->value, value_len);
545 	memcpy(item->value, memcheck(value, value_len), value_len);
546 	item->value_len = value_len;
547 
548 	return true;
549 }
550 
psbt_input_set_unknown(const tal_t * ctx,struct wally_psbt_input * in,const u8 * key,const void * value,size_t value_len)551 void psbt_input_set_unknown(const tal_t *ctx,
552 			    struct wally_psbt_input *in,
553 			    const u8 *key,
554 			    const void *value,
555 			    size_t value_len)
556 {
557 	if (!wally_map_set_unknown(ctx, &in->unknowns, key, value, value_len))
558 		abort();
559 }
560 
psbt_get_unknown(const struct wally_map * map,const u8 * key,size_t * val_len)561 void *psbt_get_unknown(const struct wally_map *map,
562 		       const u8 *key,
563 		       size_t *val_len)
564 {
565 	size_t index;
566 
567 	if (wally_map_find(map, key, tal_bytelen(key), &index) != WALLY_OK)
568 		return NULL;
569 
570 	/* Zero: item not found. */
571 	if (index == 0)
572 		return NULL;
573 
574 	/* ++: item is at this index minus 1 */
575 	*val_len = map->items[index - 1].value_len;
576 	return map->items[index - 1].value;
577 }
578 
psbt_get_lightning(const struct wally_map * map,const u8 proprietary_type,size_t * val_len)579 void *psbt_get_lightning(const struct wally_map *map,
580 			 const u8 proprietary_type,
581 			 size_t *val_len)
582 {
583 	void *res;
584 	u8 *key = psbt_make_key(NULL, proprietary_type, NULL);
585 	res = psbt_get_unknown(map, key, val_len);
586 	tal_free(key);
587 	return res;
588 }
589 
590 
psbt_output_set_unknown(const tal_t * ctx,struct wally_psbt_output * out,const u8 * key,const void * value,size_t value_len)591 void psbt_output_set_unknown(const tal_t *ctx,
592 			     struct wally_psbt_output *out,
593 			     const u8 *key,
594 			     const void *value,
595 			     size_t value_len)
596 {
597 	if (!wally_map_set_unknown(ctx, &out->unknowns, key, value, value_len))
598 		abort();
599 }
600 
601 /* Use the destructor to free the wally_tx */
wally_tx_destroy(struct wally_tx * wtx)602 static void wally_tx_destroy(struct wally_tx *wtx)
603 {
604 	wally_tx_free(wtx);
605 }
606 
psbt_finalize(struct wally_psbt * psbt)607 bool psbt_finalize(struct wally_psbt *psbt)
608 {
609 	bool ok;
610 
611 	tal_wally_start();
612 
613 	/* Wally doesn't know how to finalize P2WSH; this happens with
614 	 * option_anchor_outputs, and finalizing is trivial. */
615 	/* FIXME: miniscript! miniscript! miniscript! */
616 	for (size_t i = 0; i < psbt->num_inputs; i++) {
617 		struct wally_psbt_input *input = &psbt->inputs[i];
618 		struct wally_tx_witness_stack *stack;
619 
620 		if (!is_anchor_witness_script(input->witness_script,
621 					      input->witness_script_len))
622 			continue;
623 
624 		if (input->signatures.num_items != 1)
625 			continue;
626 
627 		/* BOLT #3:
628 		 * #### `to_remote` Output
629 		 *
630 		 * If `option_anchor_outputs` applies to the commitment
631 		 * transaction, the `to_remote` output is encumbered by a one
632 		 * block csv lock.
633 		 *
634 		 *    <remote_pubkey> OP_CHECKSIGVERIFY 1 OP_CHECKSEQUENCEVERIFY
635 		 *
636 		 * The output is spent by an input with `nSequence`
637 		 * field set to `1` and witness:
638 		 *
639 		 *    <remote_sig>
640 		 */
641 		wally_tx_witness_stack_init_alloc(2, &stack);
642 		wally_tx_witness_stack_add(stack,
643 					   input->signatures.items[0].value,
644 					   input->signatures.items[0].value_len);
645 		wally_tx_witness_stack_add(stack,
646 					   input->witness_script,
647 					   input->witness_script_len);
648 		input->final_witness = stack;
649 	}
650 
651 	ok = (wally_psbt_finalize(psbt) == WALLY_OK);
652 	tal_wally_end(psbt);
653 
654 	return ok && psbt_is_finalized(psbt);
655 }
656 
psbt_final_tx(const tal_t * ctx,const struct wally_psbt * psbt)657 struct wally_tx *psbt_final_tx(const tal_t *ctx, const struct wally_psbt *psbt)
658 {
659 	struct wally_tx *wtx;
660 
661 	if (!psbt_is_finalized(psbt))
662 		return NULL;
663 
664 	tal_wally_start();
665 	if (wally_psbt_extract(psbt, &wtx) == WALLY_OK)
666 		tal_add_destructor(wtx, wally_tx_destroy);
667 	else
668 		wtx = NULL;
669 
670 	tal_wally_end(tal_steal(ctx, wtx));
671 	return wtx;
672 }
673 
psbt_from_b64(const tal_t * ctx,const char * b64,size_t b64len)674 struct wally_psbt *psbt_from_b64(const tal_t *ctx,
675 				 const char *b64,
676 				 size_t b64len)
677 {
678 	struct wally_psbt *psbt;
679 	char *str = tal_strndup(tmpctx, b64, b64len);
680 
681 	tal_wally_start();
682 	if (wally_psbt_from_base64(str, &psbt) == WALLY_OK)
683 		tal_add_destructor(psbt, psbt_destroy);
684 	else
685 		psbt = NULL;
686 	tal_wally_end(tal_steal(ctx, psbt));
687 
688 	return psbt;
689 }
690 
psbt_to_b64(const tal_t * ctx,const struct wally_psbt * psbt)691 char *psbt_to_b64(const tal_t *ctx, const struct wally_psbt *psbt)
692 {
693 	char *serialized_psbt;
694 	int ret;
695 
696 	tal_wally_start();
697 	ret = wally_psbt_to_base64(psbt, 0, &serialized_psbt);
698 	assert(ret == WALLY_OK);
699 	tal_wally_end(tal_steal(ctx, serialized_psbt));
700 
701 	return serialized_psbt;
702 }
703 REGISTER_TYPE_TO_STRING(wally_psbt, psbt_to_b64);
704 
psbt_get_bytes(const tal_t * ctx,const struct wally_psbt * psbt,size_t * bytes_written)705 const u8 *psbt_get_bytes(const tal_t *ctx, const struct wally_psbt *psbt,
706 			 size_t *bytes_written)
707 {
708 	size_t len = 0;
709 	u8 *bytes;
710 
711 	if (!psbt) {
712 		*bytes_written = 0;
713 		return NULL;
714 	}
715 
716 	wally_psbt_get_length(psbt, 0, &len);
717 	bytes = tal_arr(ctx, u8, len);
718 
719 	if (wally_psbt_to_bytes(psbt, 0, bytes, len, bytes_written) != WALLY_OK ||
720 	    *bytes_written != len) {
721 		/* something went wrong. bad libwally ?? */
722 		abort();
723 	}
724 	return bytes;
725 }
726 
psbt_from_bytes(const tal_t * ctx,const u8 * bytes,size_t byte_len)727 struct wally_psbt *psbt_from_bytes(const tal_t *ctx, const u8 *bytes,
728 				   size_t byte_len)
729 {
730 	struct wally_psbt *psbt;
731 
732 	tal_wally_start();
733 	if (wally_psbt_from_bytes(bytes, byte_len, &psbt) == WALLY_OK)
734 		tal_add_destructor(psbt, psbt_destroy);
735 	else
736 		psbt = NULL;
737 	tal_wally_end(tal_steal(ctx, psbt));
738 
739 	return psbt;
740 }
741 
towire_wally_psbt(u8 ** pptr,const struct wally_psbt * psbt)742 void towire_wally_psbt(u8 **pptr, const struct wally_psbt *psbt)
743 {
744 	/* Let's include the PSBT bytes */
745 	size_t bytes_written;
746 	const u8 *pbt_bytes = psbt_get_bytes(NULL, psbt, &bytes_written);
747 	towire_u32(pptr, bytes_written);
748 	towire_u8_array(pptr, pbt_bytes, bytes_written);
749 	tal_free(pbt_bytes);
750 }
751 
fromwire_wally_psbt(const tal_t * ctx,const u8 ** cursor,size_t * max)752 struct wally_psbt *fromwire_wally_psbt(const tal_t *ctx,
753 				       const u8 **cursor, size_t *max)
754 {
755 	struct wally_psbt *psbt;
756 	u32 psbt_byte_len;
757 	const u8 *psbt_buf;
758 
759 	psbt_byte_len = fromwire_u32(cursor, max);
760 	psbt_buf = fromwire(cursor, max, NULL, psbt_byte_len);
761 	if (!psbt_buf || psbt_byte_len == 0)
762 		return NULL;
763 
764 	psbt = psbt_from_bytes(ctx, psbt_buf, psbt_byte_len);
765 	if (!psbt)
766 		return fromwire_fail(cursor, max);
767 
768 #if DEVELOPER
769 	/* Re-marshall for sanity check! */
770 	u8 *tmpbuf = tal_arr(NULL, u8, psbt_byte_len);
771 	size_t written;
772 	if (wally_psbt_to_bytes(psbt, 0, tmpbuf, psbt_byte_len, &written) != WALLY_OK) {
773 		tal_free(tmpbuf);
774 		tal_free(psbt);
775 		return fromwire_fail(cursor, max);
776 	}
777 	tal_free(tmpbuf);
778 #endif
779 
780 	return psbt;
781 }
782 
783 /* This only works on a non-final psbt because we're ALL SEGWIT! */
psbt_txid(const tal_t * ctx,const struct wally_psbt * psbt,struct bitcoin_txid * txid,struct wally_tx ** wtx)784 void psbt_txid(const tal_t *ctx,
785 	       const struct wally_psbt *psbt, struct bitcoin_txid *txid,
786 	       struct wally_tx **wtx)
787 {
788 	struct wally_tx *tx;
789 
790 	/* You can *almost* take txid of global tx.  But @niftynei thought
791 	 * about this far more than me and pointed out that P2SH
792 	 * inputs would not be represented, so here we go. */
793 	tal_wally_start();
794 	wally_tx_clone_alloc(psbt->tx, 0, &tx);
795 
796 	for (size_t i = 0; i < tx->num_inputs; i++) {
797 		if (psbt->inputs[i].final_scriptsig) {
798 			wally_tx_set_input_script(tx, i,
799 						  psbt->inputs[i].final_scriptsig,
800 						  psbt->inputs[i].final_scriptsig_len);
801 		} else if (psbt->inputs[i].redeem_script) {
802 			u8 *script;
803 
804 			/* P2SH requires push of the redeemscript, from libwally src */
805 			script = tal_arr(tmpctx, u8, 0);
806 			script_push_bytes(&script,
807 					  psbt->inputs[i].redeem_script,
808 					  psbt->inputs[i].redeem_script_len);
809 			wally_tx_set_input_script(tx, i, script, tal_bytelen(script));
810 		}
811 	}
812 	tal_wally_end(tal_steal(ctx, tx));
813 
814 	wally_txid(tx, txid);
815 	if (wtx)
816 		*wtx = tx;
817 	else
818 		wally_tx_free(tx);
819 }
820 
psbt_compute_fee(const struct wally_psbt * psbt)821 struct amount_sat psbt_compute_fee(const struct wally_psbt *psbt)
822 {
823 	struct amount_sat fee, input_amt;
824 	struct amount_asset asset;
825 	bool ok;
826 
827 	fee = AMOUNT_SAT(0);
828 	for (size_t i = 0; i < psbt->num_inputs; i++) {
829 		input_amt = psbt_input_get_amount(psbt, i);
830 		ok = amount_sat_add(&fee, fee, input_amt);
831 		assert(ok);
832 	}
833 
834 	for (size_t i = 0; i < psbt->num_outputs; i++) {
835 		asset = wally_tx_output_get_amount(&psbt->tx->outputs[i]);
836 		if (!amount_asset_is_main(&asset)
837 		    || elements_wtx_output_is_fee(psbt->tx, i))
838 			continue;
839 
840 		ok = amount_sat_sub(&fee, fee, amount_asset_to_sat(&asset));
841 		if (!ok)
842 			return AMOUNT_SAT(0);
843 	}
844 
845 	return fee;
846 }
847