1 #include "config.h"
2 #include <assert.h>
3 #include <bitcoin/chainparams.h>
4 #include <bitcoin/psbt.h>
5 #include <bitcoin/script.h>
6 #include <ccan/str/hex/hex.h>
7 #include <ccan/tal/str/str.h>
8 #include <common/type_to_string.h>
9 #include <wally_psbt.h>
10 #include <wire/wire.h>
11 #include <bitcoin/tx.h>
12
13 #define SEGREGATED_WITNESS_FLAG 0x1
14
new_tx_output(const tal_t * ctx,struct amount_sat amount,const u8 * script)15 struct bitcoin_tx_output *new_tx_output(const tal_t *ctx,
16 struct amount_sat amount,
17 const u8 *script)
18 {
19 struct bitcoin_tx_output *output = tal(ctx, struct bitcoin_tx_output);
20 output->amount = amount;
21 output->script = tal_dup_arr(output, u8, script, tal_count(script), 0);
22 return output;
23 }
24
wally_tx_output(const tal_t * ctx,const u8 * script,struct amount_sat amount)25 struct wally_tx_output *wally_tx_output(const tal_t *ctx,
26 const u8 *script,
27 struct amount_sat amount)
28 {
29 u64 satoshis = amount.satoshis; /* Raw: wally API */
30 struct wally_tx_output *output;
31 int ret;
32
33 tal_wally_start();
34 if (chainparams->is_elements) {
35 u8 value[9];
36 ret = wally_tx_confidential_value_from_satoshi(satoshis, value,
37 sizeof(value));
38 assert(ret == WALLY_OK);
39 ret = wally_tx_elements_output_init_alloc(
40 script, tal_bytelen(script), chainparams->fee_asset_tag, 33,
41 value, sizeof(value), NULL, 0, NULL, 0, NULL, 0, &output);
42 if (ret != WALLY_OK) {
43 output = NULL;
44 goto done;
45 }
46
47 /* Cheat a bit by also setting the numeric satoshi value,
48 * otherwise we end up converting a number of times */
49 output->satoshi = satoshis;
50 } else {
51 ret = wally_tx_output_init_alloc(satoshis, script,
52 tal_bytelen(script), &output);
53 if (ret != WALLY_OK) {
54 output = NULL;
55 goto done;
56 }
57 }
58
59 done:
60 tal_wally_end(tal_steal(ctx, output));
61 return output;
62 }
63
bitcoin_tx_add_output(struct bitcoin_tx * tx,const u8 * script,u8 * wscript,struct amount_sat amount)64 int bitcoin_tx_add_output(struct bitcoin_tx *tx, const u8 *script,
65 u8 *wscript, struct amount_sat amount)
66 {
67 size_t i = tx->wtx->num_outputs;
68 struct wally_tx_output *output;
69 struct wally_psbt_output *psbt_out;
70 int ret;
71 const struct chainparams *chainparams = tx->chainparams;
72 assert(i < tx->wtx->outputs_allocation_len);
73
74 assert(tx->wtx != NULL);
75 assert(chainparams);
76
77 output = wally_tx_output(NULL, script, amount);
78 assert(output);
79 tal_wally_start();
80 ret = wally_tx_add_output(tx->wtx, output);
81 assert(ret == WALLY_OK);
82 tal_wally_end(tx->wtx);
83
84 psbt_out = psbt_add_output(tx->psbt, output, i);
85 if (wscript) {
86 tal_wally_start();
87 ret = wally_psbt_output_set_witness_script(psbt_out,
88 wscript,
89 tal_bytelen(wscript));
90 assert(ret == WALLY_OK);
91 tal_wally_end(tx->psbt);
92 }
93
94 wally_tx_output_free(output);
95 bitcoin_tx_output_set_amount(tx, i, amount);
96
97 return i;
98 }
99
bitcoin_tx_add_multi_outputs(struct bitcoin_tx * tx,struct bitcoin_tx_output ** outputs)100 int bitcoin_tx_add_multi_outputs(struct bitcoin_tx *tx,
101 struct bitcoin_tx_output **outputs)
102 {
103 for (size_t j = 0; j < tal_count(outputs); j++)
104 bitcoin_tx_add_output(tx, outputs[j]->script,
105 NULL, outputs[j]->amount);
106
107 return tx->wtx->num_outputs;
108 }
109
elements_wtx_output_is_fee(const struct wally_tx * tx,int outnum)110 bool elements_wtx_output_is_fee(const struct wally_tx *tx, int outnum)
111 {
112 assert(outnum < tx->num_outputs);
113 return chainparams->is_elements &&
114 tx->outputs[outnum].script_len == 0;
115 }
116
elements_tx_output_is_fee(const struct bitcoin_tx * tx,int outnum)117 bool elements_tx_output_is_fee(const struct bitcoin_tx *tx, int outnum)
118 {
119 return elements_wtx_output_is_fee(tx->wtx, outnum);
120 }
121
bitcoin_tx_compute_fee_w_inputs(const struct bitcoin_tx * tx,struct amount_sat input_val)122 struct amount_sat bitcoin_tx_compute_fee_w_inputs(const struct bitcoin_tx *tx,
123 struct amount_sat input_val)
124 {
125 struct amount_asset asset;
126 bool ok;
127
128 for (size_t i = 0; i < tx->wtx->num_outputs; i++) {
129 asset = bitcoin_tx_output_get_amount(tx, i);
130 if (elements_tx_output_is_fee(tx, i) ||
131 !amount_asset_is_main(&asset))
132 continue;
133
134 ok = amount_sat_sub(&input_val, input_val,
135 amount_asset_to_sat(&asset));
136 if (!ok)
137 return AMOUNT_SAT(0);
138
139 }
140 return input_val;
141 }
142
143 /**
144 * Compute how much fee we are actually sending with this transaction.
145 */
bitcoin_tx_compute_fee(const struct bitcoin_tx * tx)146 struct amount_sat bitcoin_tx_compute_fee(const struct bitcoin_tx *tx)
147 {
148 struct amount_sat input_total = AMOUNT_SAT(0), input_amt;
149 bool ok;
150
151 for (size_t i = 0; i < tx->psbt->num_inputs; i++) {
152 input_amt = psbt_input_get_amount(tx->psbt, i);
153 ok = amount_sat_add(&input_total, input_total, input_amt);
154 assert(ok);
155 }
156
157 return bitcoin_tx_compute_fee_w_inputs(tx, input_total);
158 }
159
160 /*
161 * Add an explicit fee output if necessary.
162 *
163 * An explicit fee output is only necessary if we are using an elements
164 * transaction, and we have a non-zero fee. This method may be called multiple
165 * times.
166 *
167 * Returns the position of the fee output, or -1 in the case of non-elements
168 * transactions.
169 */
elements_tx_add_fee_output(struct bitcoin_tx * tx)170 static int elements_tx_add_fee_output(struct bitcoin_tx *tx)
171 {
172 struct amount_sat fee = bitcoin_tx_compute_fee(tx);
173 int pos;
174
175 /* If we aren't using elements, we don't add explicit fee outputs */
176 if (!chainparams->is_elements || amount_sat_eq(fee, AMOUNT_SAT(0)))
177 return -1;
178
179 /* Try to find any existing fee output */
180 for (pos = 0; pos < tx->wtx->num_outputs; pos++) {
181 if (elements_tx_output_is_fee(tx, pos))
182 break;
183 }
184
185 if (pos == tx->wtx->num_outputs)
186 return bitcoin_tx_add_output(tx, NULL, NULL, fee);
187 else {
188 bitcoin_tx_output_set_amount(tx, pos, fee);
189 return pos;
190 }
191 }
192
bitcoin_tx_set_locktime(struct bitcoin_tx * tx,u32 locktime)193 void bitcoin_tx_set_locktime(struct bitcoin_tx *tx, u32 locktime)
194 {
195 tx->wtx->locktime = locktime;
196 tx->psbt->tx->locktime = locktime;
197 }
198
bitcoin_tx_add_input(struct bitcoin_tx * tx,const struct bitcoin_outpoint * outpoint,u32 sequence,const u8 * scriptSig,struct amount_sat amount,const u8 * scriptPubkey,const u8 * input_wscript)199 int bitcoin_tx_add_input(struct bitcoin_tx *tx,
200 const struct bitcoin_outpoint *outpoint,
201 u32 sequence, const u8 *scriptSig,
202 struct amount_sat amount, const u8 *scriptPubkey,
203 const u8 *input_wscript)
204 {
205 int wally_err;
206 int input_num = tx->wtx->num_inputs;
207
208 psbt_append_input(tx->psbt, outpoint,
209 sequence, scriptSig,
210 input_wscript, NULL);
211
212 if (input_wscript) {
213 scriptPubkey = scriptpubkey_p2wsh(tx->psbt, input_wscript);
214 }
215
216 assert(scriptPubkey);
217 psbt_input_set_wit_utxo(tx->psbt, input_num,
218 scriptPubkey, amount);
219
220 tal_wally_start();
221 wally_err = wally_tx_add_input(tx->wtx,
222 &tx->psbt->tx->inputs[input_num]);
223 assert(wally_err == WALLY_OK);
224
225 /* scriptsig isn't actually stored in psbt input, so add that now */
226 wally_tx_set_input_script(tx->wtx, input_num,
227 scriptSig, tal_bytelen(scriptSig));
228 tal_wally_end(tx->wtx);
229
230 if (is_elements(chainparams)) {
231 struct amount_asset asset;
232 /* FIXME: persist asset tags */
233 asset = amount_sat_to_asset(&amount,
234 chainparams->fee_asset_tag);
235 /* FIXME: persist nonces */
236 psbt_elements_input_set_asset(tx->psbt, input_num, &asset);
237 }
238 return input_num;
239 }
240
bitcoin_tx_check(const struct bitcoin_tx * tx)241 bool bitcoin_tx_check(const struct bitcoin_tx *tx)
242 {
243 u8 *newtx;
244 size_t written;
245 int flags = WALLY_TX_FLAG_USE_WITNESS;
246
247 if (wally_tx_get_length(tx->wtx, flags, &written) != WALLY_OK)
248 return false;
249
250 newtx = tal_arr(tmpctx, u8, written);
251 if (wally_tx_to_bytes(tx->wtx, flags, newtx, written, &written) !=
252 WALLY_OK)
253 return false;
254
255 if (written != tal_bytelen(newtx))
256 return false;
257
258 tal_free(newtx);
259 return true;
260 }
261
bitcoin_tx_output_set_amount(struct bitcoin_tx * tx,int outnum,struct amount_sat amount)262 void bitcoin_tx_output_set_amount(struct bitcoin_tx *tx, int outnum,
263 struct amount_sat amount)
264 {
265 u64 satoshis = amount.satoshis; /* Raw: low-level helper */
266 struct wally_tx_output *output = &tx->wtx->outputs[outnum];
267 assert(outnum < tx->wtx->num_outputs);
268 if (chainparams->is_elements) {
269 int ret = wally_tx_confidential_value_from_satoshi(
270 satoshis, output->value, output->value_len);
271 assert(ret == WALLY_OK);
272 } else {
273 output->satoshi = satoshis;
274
275 /* update the global tx for the psbt also */
276 output = &tx->psbt->tx->outputs[outnum];
277 output->satoshi = satoshis;
278 }
279 }
280
wally_tx_output_get_script(const tal_t * ctx,const struct wally_tx_output * output)281 const u8 *wally_tx_output_get_script(const tal_t *ctx,
282 const struct wally_tx_output *output)
283 {
284 if (output->script == NULL) {
285 /* This can happen for coinbase transactions and pegin
286 * transactions */
287 return NULL;
288 }
289
290 return tal_dup_arr(ctx, u8, output->script, output->script_len, 0);
291 }
292
bitcoin_tx_output_get_script(const tal_t * ctx,const struct bitcoin_tx * tx,int outnum)293 const u8 *bitcoin_tx_output_get_script(const tal_t *ctx,
294 const struct bitcoin_tx *tx, int outnum)
295 {
296 const struct wally_tx_output *output;
297 assert(outnum < tx->wtx->num_outputs);
298 output = &tx->wtx->outputs[outnum];
299
300 return wally_tx_output_get_script(ctx, output);
301 }
302
bitcoin_tx_output_get_witscript(const tal_t * ctx,const struct bitcoin_tx * tx,int outnum)303 u8 *bitcoin_tx_output_get_witscript(const tal_t *ctx, const struct bitcoin_tx *tx,
304 int outnum)
305 {
306 struct wally_psbt_output *out;
307
308 assert(outnum < tx->psbt->num_outputs);
309 out = &tx->psbt->outputs[outnum];
310
311 if (out->witness_script_len == 0)
312 return NULL;
313
314 return tal_dup_arr(ctx, u8, out->witness_script, out->witness_script_len, 0);
315 }
316
bitcoin_tx_output_get_amount(const struct bitcoin_tx * tx,int outnum)317 struct amount_asset bitcoin_tx_output_get_amount(const struct bitcoin_tx *tx,
318 int outnum)
319 {
320 assert(tx->chainparams);
321 assert(outnum < tx->wtx->num_outputs);
322 return wally_tx_output_get_amount(&tx->wtx->outputs[outnum]);
323 }
324
bitcoin_tx_output_get_amount_sat(const struct bitcoin_tx * tx,int outnum,struct amount_sat * amount)325 void bitcoin_tx_output_get_amount_sat(const struct bitcoin_tx *tx, int outnum,
326 struct amount_sat *amount)
327 {
328 struct amount_asset asset_amt;
329 asset_amt = bitcoin_tx_output_get_amount(tx, outnum);
330 assert(amount_asset_is_main(&asset_amt));
331 *amount = amount_asset_to_sat(&asset_amt);
332 }
333
bitcoin_tx_input_set_witness(struct bitcoin_tx * tx,int innum,u8 ** witness)334 void bitcoin_tx_input_set_witness(struct bitcoin_tx *tx, int innum,
335 u8 **witness)
336 {
337 struct wally_tx_witness_stack *stack = NULL;
338 size_t stack_size = tal_count(witness);
339
340 tal_wally_start();
341 /* Free any lingering witness */
342 if (witness) {
343 wally_tx_witness_stack_init_alloc(stack_size, &stack);
344 for (size_t i = 0; i < stack_size; i++)
345 wally_tx_witness_stack_add(stack, witness[i],
346 tal_bytelen(witness[i]));
347 }
348 tal_wally_end(tmpctx);
349
350 tal_wally_start();
351 wally_tx_set_input_witness(tx->wtx, innum, stack);
352 tal_wally_end(tx->wtx);
353
354 /* Also add to the psbt */
355 tal_wally_start();
356 wally_psbt_input_set_final_witness(&tx->psbt->inputs[innum], stack);
357 tal_wally_end(tx->psbt);
358
359 if (taken(witness))
360 tal_free(witness);
361 }
362
bitcoin_tx_input_set_script(struct bitcoin_tx * tx,int innum,u8 * script)363 void bitcoin_tx_input_set_script(struct bitcoin_tx *tx, int innum, u8 *script)
364 {
365 struct wally_psbt_input *in;
366
367 tal_wally_start();
368 wally_tx_set_input_script(tx->wtx, innum, script, tal_bytelen(script));
369 tal_wally_end(tx->wtx);
370
371 /* Also add to the psbt */
372 assert(innum < tx->psbt->num_inputs);
373 in = &tx->psbt->inputs[innum];
374 tal_wally_start();
375 wally_psbt_input_set_final_scriptsig(in, script, tal_bytelen(script));
376 tal_wally_end(tx->psbt);
377 }
378
bitcoin_tx_input_get_witness(const tal_t * ctx,const struct bitcoin_tx * tx,int innum,int witnum)379 const u8 *bitcoin_tx_input_get_witness(const tal_t *ctx,
380 const struct bitcoin_tx *tx, int innum,
381 int witnum)
382 {
383 const u8 *witness_item;
384 struct wally_tx_witness_item *item;
385 assert(innum < tx->wtx->num_inputs);
386 assert(witnum < tx->wtx->inputs[innum].witness->num_items);
387 item = &tx->wtx->inputs[innum].witness->items[witnum];
388 witness_item =
389 tal_dup_arr(ctx, u8, item->witness, item->witness_len, 0);
390 return witness_item;
391 }
392
393 /* FIXME: remove */
bitcoin_tx_input_get_txid(const struct bitcoin_tx * tx,int innum,struct bitcoin_txid * out)394 void bitcoin_tx_input_get_txid(const struct bitcoin_tx *tx, int innum,
395 struct bitcoin_txid *out)
396 {
397 assert(innum < tx->wtx->num_inputs);
398 wally_tx_input_get_txid(&tx->wtx->inputs[innum], out);
399 }
400
bitcoin_tx_input_get_outpoint(const struct bitcoin_tx * tx,int innum,struct bitcoin_outpoint * outpoint)401 void bitcoin_tx_input_get_outpoint(const struct bitcoin_tx *tx,
402 int innum,
403 struct bitcoin_outpoint *outpoint)
404 {
405 assert(innum < tx->wtx->num_inputs);
406 wally_tx_input_get_outpoint(&tx->wtx->inputs[innum], outpoint);
407 }
408
bitcoin_tx_input_set_outpoint(struct bitcoin_tx * tx,int innum,const struct bitcoin_outpoint * outpoint)409 void bitcoin_tx_input_set_outpoint(struct bitcoin_tx *tx, int innum,
410 const struct bitcoin_outpoint *outpoint)
411 {
412 struct wally_tx_input *in;
413 assert(innum < tx->wtx->num_inputs);
414
415 in = &tx->wtx->inputs[innum];
416 BUILD_ASSERT(sizeof(struct bitcoin_txid) == sizeof(in->txhash));
417 memcpy(in->txhash, &outpoint->txid, sizeof(struct bitcoin_txid));
418 in->index = outpoint->n;
419 }
420
421 /* FIXME: remove */
wally_tx_input_get_txid(const struct wally_tx_input * in,struct bitcoin_txid * txid)422 void wally_tx_input_get_txid(const struct wally_tx_input *in,
423 struct bitcoin_txid *txid)
424 {
425 BUILD_ASSERT(sizeof(struct bitcoin_txid) == sizeof(in->txhash));
426 memcpy(txid, in->txhash, sizeof(struct bitcoin_txid));
427 }
428
wally_tx_input_get_outpoint(const struct wally_tx_input * in,struct bitcoin_outpoint * outpoint)429 void wally_tx_input_get_outpoint(const struct wally_tx_input *in,
430 struct bitcoin_outpoint *outpoint)
431 {
432 BUILD_ASSERT(sizeof(struct bitcoin_txid) == sizeof(in->txhash));
433 memcpy(&outpoint->txid, in->txhash, sizeof(struct bitcoin_txid));
434 outpoint->n = in->index;
435 }
436
437 /* BIP144:
438 * If the witness is empty, the old serialization format should be used. */
uses_witness(const struct wally_tx * wtx)439 static bool uses_witness(const struct wally_tx *wtx)
440 {
441 size_t i;
442
443 for (i = 0; i < wtx->num_inputs; i++) {
444 if (wtx->inputs[i].witness)
445 return true;
446 }
447 return false;
448 }
449
linearize_tx(const tal_t * ctx,const struct bitcoin_tx * tx)450 u8 *linearize_tx(const tal_t *ctx, const struct bitcoin_tx *tx)
451 {
452 return linearize_wtx(ctx, tx->wtx);
453 }
454
linearize_wtx(const tal_t * ctx,const struct wally_tx * wtx)455 u8 *linearize_wtx(const tal_t *ctx, const struct wally_tx *wtx)
456 {
457 u8 *arr;
458 u32 flag = 0;
459 size_t len, written;
460 int res;
461
462 if (uses_witness(wtx))
463 flag |= WALLY_TX_FLAG_USE_WITNESS;
464
465 res = wally_tx_get_length(wtx, flag, &len);
466 assert(res == WALLY_OK);
467 arr = tal_arr(ctx, u8, len);
468 res = wally_tx_to_bytes(wtx, flag, arr, len, &written);
469 assert(len == written);
470
471 return arr;
472 }
473
wally_tx_weight(const struct wally_tx * wtx)474 size_t wally_tx_weight(const struct wally_tx *wtx)
475 {
476 size_t weight;
477 int ret = wally_tx_get_weight(wtx, &weight);
478 assert(ret == WALLY_OK);
479 return weight;
480 }
481
bitcoin_tx_weight(const struct bitcoin_tx * tx)482 size_t bitcoin_tx_weight(const struct bitcoin_tx *tx)
483 {
484 return wally_tx_weight(tx->wtx);
485 }
486
wally_txid(const struct wally_tx * wtx,struct bitcoin_txid * txid)487 void wally_txid(const struct wally_tx *wtx, struct bitcoin_txid *txid)
488 {
489 u8 *arr;
490 size_t len, written;
491 int res;
492
493 /* Never use BIP141 form for txid */
494 res = wally_tx_get_length(wtx, 0, &len);
495 assert(res == WALLY_OK);
496 arr = tal_arr(NULL, u8, len);
497 res = wally_tx_to_bytes(wtx, 0, arr, len, &written);
498 assert(len == written);
499
500 sha256_double(&txid->shad, arr, len);
501 tal_free(arr);
502 }
503
504 /* We used to have beautiful, optimal code which fed the tx parts directly
505 * into sha256_update(). But that was before libwally; but now we don't have
506 * to maintain our own transaction code, so there's that. */
bitcoin_txid(const struct bitcoin_tx * tx,struct bitcoin_txid * txid)507 void bitcoin_txid(const struct bitcoin_tx *tx, struct bitcoin_txid *txid)
508 {
509 wally_txid(tx->wtx, txid);
510 }
511
512 /* Use the bitcoin_tx destructor to also free the wally_tx */
bitcoin_tx_destroy(struct bitcoin_tx * tx)513 static void bitcoin_tx_destroy(struct bitcoin_tx *tx)
514 {
515 wally_tx_free(tx->wtx);
516 }
517
bitcoin_tx(const tal_t * ctx,const struct chainparams * chainparams,varint_t input_count,varint_t output_count,u32 nlocktime)518 struct bitcoin_tx *bitcoin_tx(const tal_t *ctx,
519 const struct chainparams *chainparams,
520 varint_t input_count, varint_t output_count,
521 u32 nlocktime)
522 {
523 struct bitcoin_tx *tx = tal(ctx, struct bitcoin_tx);
524 assert(chainparams);
525
526 /* If we are constructing an elements transaction we need to
527 * explicitly add the fee as an extra output. So allocate one more
528 * than the outputs we need internally. */
529 if (chainparams->is_elements)
530 output_count += 1;
531
532 tal_wally_start();
533 wally_tx_init_alloc(WALLY_TX_VERSION_2, nlocktime, input_count, output_count,
534 &tx->wtx);
535 tal_add_destructor(tx, bitcoin_tx_destroy);
536 tal_wally_end(tal_steal(tx, tx->wtx));
537
538 tx->chainparams = chainparams;
539 tx->psbt = new_psbt(tx, tx->wtx);
540
541 return tx;
542 }
543
bitcoin_tx_finalize(struct bitcoin_tx * tx)544 void bitcoin_tx_finalize(struct bitcoin_tx *tx)
545 {
546 elements_tx_add_fee_output(tx);
547 assert(bitcoin_tx_check(tx));
548 }
549
bitcoin_tx_with_psbt(const tal_t * ctx,struct wally_psbt * psbt STEALS)550 struct bitcoin_tx *bitcoin_tx_with_psbt(const tal_t *ctx, struct wally_psbt *psbt STEALS)
551 {
552 struct bitcoin_tx *tx = bitcoin_tx(ctx, chainparams,
553 psbt->tx->num_inputs,
554 psbt->tx->num_outputs,
555 psbt->tx->locktime);
556 wally_tx_free(tx->wtx);
557
558 psbt_finalize(psbt);
559 tx->wtx = psbt_final_tx(tx, psbt);
560 if (!tx->wtx) {
561 tal_wally_start();
562 if (wally_tx_clone_alloc(psbt->tx, 0, &tx->wtx) != WALLY_OK)
563 tx->wtx = NULL;
564 tal_wally_end(tal_steal(tx, tx->wtx));
565 if (!tx->wtx)
566 return tal_free(tx);
567 }
568
569 tal_free(tx->psbt);
570 tx->psbt = tal_steal(tx, psbt);
571
572 return tx;
573 }
574
pull_wtx(const tal_t * ctx,const u8 ** cursor,size_t * max)575 static struct wally_tx *pull_wtx(const tal_t *ctx,
576 const u8 **cursor,
577 size_t *max)
578 {
579 int flags = WALLY_TX_FLAG_USE_WITNESS;
580 struct wally_tx *wtx;
581
582 if (chainparams->is_elements)
583 flags |= WALLY_TX_FLAG_USE_ELEMENTS;
584
585 tal_wally_start();
586 if (wally_tx_from_bytes(*cursor, *max, flags, &wtx) != WALLY_OK) {
587 fromwire_fail(cursor, max);
588 wtx = tal_free(wtx);
589 }
590 tal_wally_end(tal_steal(ctx, wtx));
591
592 if (wtx) {
593 size_t wsize;
594 wally_tx_get_length(wtx, flags, &wsize);
595 *cursor += wsize;
596 *max -= wsize;
597 }
598
599 return wtx;
600 }
601
pull_bitcoin_tx(const tal_t * ctx,const u8 ** cursor,size_t * max)602 struct bitcoin_tx *pull_bitcoin_tx(const tal_t *ctx, const u8 **cursor,
603 size_t *max)
604 {
605 struct bitcoin_tx *tx = tal(ctx, struct bitcoin_tx);
606 tx->wtx = pull_wtx(tx, cursor, max);
607 if (!tx->wtx)
608 return tal_free(tx);
609
610 tal_add_destructor(tx, bitcoin_tx_destroy);
611 tx->chainparams = chainparams;
612 tx->psbt = new_psbt(tx, tx->wtx);
613 if (!tx->psbt)
614 return tal_free(tx);
615
616 return tx;
617 }
618
bitcoin_tx_from_hex(const tal_t * ctx,const char * hex,size_t hexlen)619 struct bitcoin_tx *bitcoin_tx_from_hex(const tal_t *ctx, const char *hex,
620 size_t hexlen)
621 {
622 const char *end;
623 u8 *linear_tx;
624 const u8 *p;
625 struct bitcoin_tx *tx;
626 size_t len;
627
628 end = memchr(hex, '\n', hexlen);
629 if (!end)
630 end = hex + hexlen;
631
632 len = hex_data_size(end - hex);
633 p = linear_tx = tal_arr(ctx, u8, len);
634 if (!hex_decode(hex, end - hex, linear_tx, len))
635 goto fail;
636
637 tx = pull_bitcoin_tx(ctx, &p, &len);
638 if (!tx)
639 goto fail;
640
641 if (len)
642 goto fail_free_tx;
643
644 tal_free(linear_tx);
645
646 return tx;
647
648 fail_free_tx:
649 tal_free(tx);
650 fail:
651 tal_free(linear_tx);
652 return NULL;
653 }
654
655 /* <sigh>. Bitcoind represents hashes as little-endian for RPC. */
reverse_bytes(u8 * arr,size_t len)656 static void reverse_bytes(u8 *arr, size_t len)
657 {
658 unsigned int i;
659
660 for (i = 0; i < len / 2; i++) {
661 unsigned char tmp = arr[i];
662 arr[i] = arr[len - 1 - i];
663 arr[len - 1 - i] = tmp;
664 }
665 }
666
bitcoin_txid_from_hex(const char * hexstr,size_t hexstr_len,struct bitcoin_txid * txid)667 bool bitcoin_txid_from_hex(const char *hexstr, size_t hexstr_len,
668 struct bitcoin_txid *txid)
669 {
670 if (!hex_decode(hexstr, hexstr_len, txid, sizeof(*txid)))
671 return false;
672 reverse_bytes(txid->shad.sha.u.u8, sizeof(txid->shad.sha.u.u8));
673 return true;
674 }
675
bitcoin_txid_to_hex(const struct bitcoin_txid * txid,char * hexstr,size_t hexstr_len)676 bool bitcoin_txid_to_hex(const struct bitcoin_txid *txid,
677 char *hexstr, size_t hexstr_len)
678 {
679 struct sha256_double rev = txid->shad;
680 reverse_bytes(rev.sha.u.u8, sizeof(rev.sha.u.u8));
681 return hex_encode(&rev, sizeof(rev), hexstr, hexstr_len);
682 }
683
fmt_bitcoin_tx(const tal_t * ctx,const struct bitcoin_tx * tx)684 static char *fmt_bitcoin_tx(const tal_t *ctx, const struct bitcoin_tx *tx)
685 {
686 u8 *lin = linearize_tx(ctx, tx);
687 char *s = tal_hex(ctx, lin);
688 tal_free(lin);
689 return s;
690 }
691
fmt_bitcoin_txid(const tal_t * ctx,const struct bitcoin_txid * txid)692 static char *fmt_bitcoin_txid(const tal_t *ctx, const struct bitcoin_txid *txid)
693 {
694 char *hexstr = tal_arr(ctx, char, hex_str_size(sizeof(*txid)));
695
696 bitcoin_txid_to_hex(txid, hexstr, hex_str_size(sizeof(*txid)));
697 return hexstr;
698 }
699
fmt_bitcoin_outpoint(const tal_t * ctx,const struct bitcoin_outpoint * outpoint)700 static char *fmt_bitcoin_outpoint(const tal_t *ctx,
701 const struct bitcoin_outpoint *outpoint)
702 {
703 return tal_fmt(ctx, "%s:%u",
704 fmt_bitcoin_txid(tmpctx, &outpoint->txid),
705 outpoint->n);
706 }
707
fmt_wally_tx(const tal_t * ctx,const struct wally_tx * tx)708 static char *fmt_wally_tx(const tal_t *ctx, const struct wally_tx *tx)
709 {
710 u8 *lin = linearize_wtx(ctx, tx);
711 char *s = tal_hex(ctx, lin);
712 tal_free(lin);
713 return s;
714 }
715
716 REGISTER_TYPE_TO_STRING(bitcoin_tx, fmt_bitcoin_tx);
717 REGISTER_TYPE_TO_STRING(bitcoin_txid, fmt_bitcoin_txid);
718 REGISTER_TYPE_TO_STRING(bitcoin_outpoint, fmt_bitcoin_outpoint);
719 REGISTER_TYPE_TO_STRING(wally_tx, fmt_wally_tx);
720
fromwire_bitcoin_txid(const u8 ** cursor,size_t * max,struct bitcoin_txid * txid)721 void fromwire_bitcoin_txid(const u8 **cursor, size_t *max,
722 struct bitcoin_txid *txid)
723 {
724 fromwire_sha256_double(cursor, max, &txid->shad);
725 }
726
fromwire_bitcoin_tx(const tal_t * ctx,const u8 ** cursor,size_t * max)727 struct bitcoin_tx *fromwire_bitcoin_tx(const tal_t *ctx,
728 const u8 **cursor, size_t *max)
729 {
730 struct bitcoin_tx *tx;
731
732 u32 len = fromwire_u32(cursor, max);
733 size_t start = *max;
734 tx = pull_bitcoin_tx(ctx, cursor, max);
735 if (!tx)
736 return fromwire_fail(cursor, max);
737 // Check that we consumed len bytes
738 if (start - *max != len)
739 return fromwire_fail(cursor, max);
740
741 /* pull_bitcoin_tx sets the psbt */
742 tal_free(tx->psbt);
743 tx->psbt = fromwire_wally_psbt(tx, cursor, max);
744 if (!tx->psbt)
745 return fromwire_fail(cursor, max);
746
747 return tx;
748 }
749
fromwire_wally_tx(const tal_t * ctx,const u8 ** cursor,size_t * max)750 struct wally_tx *fromwire_wally_tx(const tal_t *ctx,
751 const u8 **cursor, size_t *max)
752 {
753 struct wally_tx *wtx;
754 wtx = pull_wtx(ctx, cursor, max);
755 if (!wtx)
756 return fromwire_fail(cursor, max);
757 return wtx;
758 }
759
towire_bitcoin_txid(u8 ** pptr,const struct bitcoin_txid * txid)760 void towire_bitcoin_txid(u8 **pptr, const struct bitcoin_txid *txid)
761 {
762 towire_sha256_double(pptr, &txid->shad);
763 }
764
towire_bitcoin_outpoint(u8 ** pptr,const struct bitcoin_outpoint * outp)765 void towire_bitcoin_outpoint(u8 **pptr, const struct bitcoin_outpoint *outp)
766 {
767 towire_bitcoin_txid(pptr, &outp->txid);
768 towire_u32(pptr, outp->n);
769 }
770
fromwire_bitcoin_outpoint(const u8 ** cursor,size_t * max,struct bitcoin_outpoint * outp)771 void fromwire_bitcoin_outpoint(const u8 **cursor, size_t *max,
772 struct bitcoin_outpoint *outp)
773 {
774 fromwire_bitcoin_txid(cursor, max, &outp->txid);
775 outp->n = fromwire_u32(cursor, max);
776 }
777
towire_bitcoin_tx(u8 ** pptr,const struct bitcoin_tx * tx)778 void towire_bitcoin_tx(u8 **pptr, const struct bitcoin_tx *tx)
779 {
780 u8 *lin = linearize_tx(tmpctx, tx);
781 towire_u32(pptr, tal_count(lin));
782 towire_u8_array(pptr, lin, tal_count(lin));
783
784 towire_wally_psbt(pptr, tx->psbt);
785 }
786
towire_wally_tx(u8 ** pptr,const struct wally_tx * wtx)787 void towire_wally_tx(u8 **pptr, const struct wally_tx *wtx)
788 {
789 u8 *lin = linearize_wtx(tmpctx, wtx);
790 towire_u8_array(pptr, lin, tal_count(lin));
791 }
792
fromwire_bitcoin_tx_output(const tal_t * ctx,const u8 ** cursor,size_t * max)793 struct bitcoin_tx_output *fromwire_bitcoin_tx_output(const tal_t *ctx,
794 const u8 **cursor, size_t *max)
795 {
796 struct bitcoin_tx_output *output = tal(ctx, struct bitcoin_tx_output);
797 output->amount = fromwire_amount_sat(cursor, max);
798 u16 script_len = fromwire_u16(cursor, max);
799 output->script = fromwire_tal_arrn(output, cursor, max, script_len);
800 if (!*cursor)
801 return tal_free(output);
802 return output;
803 }
804
towire_bitcoin_tx_output(u8 ** pptr,const struct bitcoin_tx_output * output)805 void towire_bitcoin_tx_output(u8 **pptr, const struct bitcoin_tx_output *output)
806 {
807 towire_amount_sat(pptr, output->amount);
808 towire_u16(pptr, tal_count(output->script));
809 towire_u8_array(pptr, output->script, tal_count(output->script));
810 }
811
wally_tx_input_spends(const struct wally_tx_input * input,const struct bitcoin_outpoint * outpoint)812 bool wally_tx_input_spends(const struct wally_tx_input *input,
813 const struct bitcoin_outpoint *outpoint)
814 {
815 /* Useful, as tx_part can have some NULL inputs */
816 if (!input)
817 return false;
818 BUILD_ASSERT(sizeof(outpoint->txid) == sizeof(input->txhash));
819 if (memcmp(&outpoint->txid, input->txhash, sizeof(outpoint->txid)) != 0)
820 return false;
821 return input->index == outpoint->n;
822 }
823
824 /* FIXME(cdecker) Make the caller pass in a reference to amount_asset, and
825 * return false if unintelligible/encrypted. (WARN UNUSED). */
826 struct amount_asset
wally_tx_output_get_amount(const struct wally_tx_output * output)827 wally_tx_output_get_amount(const struct wally_tx_output *output)
828 {
829 struct amount_asset amount;
830 be64 raw;
831
832 if (chainparams->is_elements) {
833 assert(output->asset_len == sizeof(amount.asset));
834 memcpy(&amount.asset, output->asset, sizeof(amount.asset));
835 /* We currently only support explicit value
836 * asset tags, others are confidential, so
837 * don't even try to assign a value to it. */
838 if (output->asset[0] == 0x01) {
839 memcpy(&raw, output->value + 1, sizeof(raw));
840 amount.value = be64_to_cpu(raw);
841 } else {
842 amount.value = 0;
843 }
844 } else {
845 /* Do not assign amount.asset, we should never touch it in
846 * non-elements scenarios. */
847 amount.value = output->satoshi;
848 }
849
850 return amount;
851 }
852
853 /* Various weights of transaction parts. */
bitcoin_tx_core_weight(size_t num_inputs,size_t num_outputs)854 size_t bitcoin_tx_core_weight(size_t num_inputs, size_t num_outputs)
855 {
856 size_t weight;
857
858 /* version, input count, output count, locktime */
859 weight = (4 + varint_size(num_inputs) + varint_size(num_outputs) + 4)
860 * 4;
861
862 /* Add segwit fields: marker + flag */
863 weight += 1 + 1;
864
865 /* A couple of things need to change for elements: */
866 if (chainparams->is_elements) {
867 /* Each transaction has surjection and rangeproof (both empty
868 * for us as long as we use unblinded L-BTC transactions). */
869 weight += 2 * 4;
870
871 /* An elements transaction has 1 additional output for fees */
872 weight += bitcoin_tx_output_weight(0);
873 }
874 return weight;
875 }
876
bitcoin_tx_output_weight(size_t outscript_len)877 size_t bitcoin_tx_output_weight(size_t outscript_len)
878 {
879 size_t weight;
880
881 /* amount, len, scriptpubkey */
882 weight = (8 + varint_size(outscript_len) + outscript_len) * 4;
883
884 if (chainparams->is_elements) {
885 /* Each output additionally has an asset_tag (1 + 32), value
886 * is prefixed by a version (1 byte), an empty nonce (1
887 * byte), two empty proofs (2 bytes). */
888 weight += (32 + 1 + 1 + 1) * 4;
889 }
890
891 return weight;
892 }
893
894 /* We grind signatures to get them down to 71 bytes */
bitcoin_tx_input_sig_weight(void)895 size_t bitcoin_tx_input_sig_weight(void)
896 {
897 return 1 + 71;
898 }
899
900 /* Input weight */
bitcoin_tx_input_weight(bool p2sh,size_t witness_weight)901 size_t bitcoin_tx_input_weight(bool p2sh, size_t witness_weight)
902 {
903 size_t weight = witness_weight;
904
905 /* Input weight: txid + index + sequence */
906 weight += (32 + 4 + 4) * 4;
907
908 /* We always encode the length of the script, even if empty */
909 weight += 1 * 4;
910
911 /* P2SH variants include push of <0 <20-byte-key-hash>> */
912 if (p2sh)
913 weight += 23 * 4;
914
915 /* Elements inputs have 6 bytes of blank proofs attached. */
916 if (chainparams->is_elements)
917 weight += 6;
918
919 return weight;
920 }
921
bitcoin_tx_simple_input_witness_weight(void)922 size_t bitcoin_tx_simple_input_witness_weight(void)
923 {
924 /* Account for witness (1 byte count + sig + key) */
925 return 1 + (bitcoin_tx_input_sig_weight() + 1 + 33);
926 }
927
928 /* We only do segwit inputs, and we assume witness is sig + key */
bitcoin_tx_simple_input_weight(bool p2sh)929 size_t bitcoin_tx_simple_input_weight(bool p2sh)
930 {
931 return bitcoin_tx_input_weight(p2sh,
932 bitcoin_tx_simple_input_witness_weight());
933 }
934
change_amount(struct amount_sat excess,u32 feerate_perkw,size_t total_weight)935 struct amount_sat change_amount(struct amount_sat excess, u32 feerate_perkw,
936 size_t total_weight)
937 {
938 size_t outweight;
939 struct amount_sat change_fee;
940
941 /* Must be able to pay for its own additional weight */
942 outweight = bitcoin_tx_output_weight(BITCOIN_SCRIPTPUBKEY_P2WPKH_LEN);
943
944 /* Rounding can cause off by one errors, so we do this */
945 if (!amount_sat_sub(&change_fee,
946 amount_tx_fee(feerate_perkw, outweight + total_weight),
947 amount_tx_fee(feerate_perkw, total_weight)))
948 return AMOUNT_SAT(0);
949
950 if (!amount_sat_sub(&excess, excess, change_fee))
951 return AMOUNT_SAT(0);
952
953 /* Must be non-dust */
954 if (!amount_sat_greater_eq(excess, chainparams->dust_limit))
955 return AMOUNT_SAT(0);
956
957 return excess;
958 }
959