1 #include "internal.h"
2 
3 #include "ccan/ccan/build_assert/build_assert.h"
4 
5 #include <include/wally_crypto.h>
6 #include <include/wally_transaction.h>
7 
8 #include <limits.h>
9 #include <stdbool.h>
10 #include "transaction_int.h"
11 #include "transaction_shared.h"
12 #include "script_int.h"
13 
14 #define WALLY_TX_ALL_FLAGS \
15     (WALLY_TX_FLAG_USE_WITNESS | WALLY_TX_FLAG_USE_ELEMENTS | \
16      WALLY_TX_FLAG_ALLOW_PARTIAL | WALLY_TX_FLAG_PRE_BIP144)
17 
18 /* We use the maximum DER sig length (plus a byte for the sighash) so that
19  * we overestimate the size by a byte or two per tx sig. This allows using
20  * e.g. the minimum fee rate/bump rate without core rejecting it for low fees.
21  */
22 static const unsigned char DUMMY_SIG[EC_SIGNATURE_DER_MAX_LEN + 1]; /* +1 for sighash */
23 
24 /* Mask for the actual sighash bits */
25 #define SIGHASH_MASK 0x1f
26 
27 /* Bytes of stack space to use to avoid allocations for tx serializing */
28 #define TX_STACK_SIZE 2048
29 
30 #define TX_COPY_ELSE_CLEAR(dst, src, siz) \
31     if (src) \
32         memcpy(dst, src, siz); \
33     else \
34         wally_clear(dst, siz);
35 
36 #define MAX_INVALID_SATOSHI ((uint64_t) -1)
37 
38 /* Extra options when serializing for hashing */
39 struct tx_serialize_opts
40 {
41     uint32_t sighash;                /* 8 bit sighash value for sig */
42     uint32_t tx_sighash;             /* 32 bit sighash value for tx */
43     size_t index;                    /* index of input we are signing */
44     const unsigned char *script;     /* scriptPubkey spent by the input we are signing */
45     size_t script_len;               /* length of 'script' in bytes */
46     uint64_t satoshi;                /* Amount of the input we are signing */
47     bool bip143;                     /* Serialize for BIP143 hash */
48     const unsigned char *value;      /* Confidential value of the input we are signing */
49     size_t value_len;                /* length of 'value' in bytes */
50 };
51 
52 static const unsigned char EMPTY_OUTPUT[9] = {
53     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00
54 };
55 
56 #define WALLY_SATOSHI_MAX ((uint64_t)WALLY_BTC_MAX * WALLY_SATOSHI_PER_BTC)
57 
58 /* LCOV_EXCL_START */
59 /* Check assumptions we expect to hold true */
assert_tx_assumptions(void)60 static void assert_tx_assumptions(void)
61 {
62     BUILD_ASSERT(WALLY_TXHASH_LEN == SHA256_LEN);
63     BUILD_ASSERT(sizeof(DUMMY_SIG) == EC_SIGNATURE_DER_MAX_LEN + 1);
64     BUILD_ASSERT(sizeof(DUMMY_SIG) - 1 == EC_SIGNATURE_DER_MAX_LOW_R_LEN + 1);
65 }
66 /* LCOV_EXCL_STOP */
67 
is_valid_witness_stack(const struct wally_tx_witness_stack * stack)68 static bool is_valid_witness_stack(const struct wally_tx_witness_stack *stack)
69 {
70     return stack &&
71            BYTES_VALID(stack->items, stack->items_allocation_len) &&
72            (stack->items != NULL || stack->num_items == 0);
73 }
74 
is_valid_tx(const struct wally_tx * tx)75 static bool is_valid_tx(const struct wally_tx *tx)
76 {
77     /* Note: The last two conditions are redundant, but having them here
78      *       ensures accurate static analysis from tools like clang.
79      */
80     return tx &&
81            BYTES_VALID(tx->inputs, tx->inputs_allocation_len) &&
82            BYTES_VALID(tx->outputs, tx->outputs_allocation_len) &&
83            (tx->num_inputs == 0 || tx->inputs != NULL) &&
84            (tx->num_outputs == 0 || tx->outputs != NULL);
85 }
86 
is_valid_tx_input(const struct wally_tx_input * input)87 static bool is_valid_tx_input(const struct wally_tx_input *input)
88 {
89     return input &&
90            BYTES_VALID(input->script, input->script_len) &&
91            (!input->witness || is_valid_witness_stack(input->witness))
92 #ifdef BUILD_ELEMENTS
93            && (!input->pegin_witness || is_valid_witness_stack(input->pegin_witness))
94 #endif
95     ;
96 }
97 
is_valid_tx_output(const struct wally_tx_output * output)98 static bool is_valid_tx_output(const struct wally_tx_output *output)
99 {
100     return output &&
101            BYTES_VALID(output->script, output->script_len) &&
102            output->satoshi <= WALLY_SATOSHI_MAX;
103 }
104 
is_valid_elements_tx_input(const struct wally_tx_input * input)105 static bool is_valid_elements_tx_input(const struct wally_tx_input *input)
106 {
107     return is_valid_tx_input(input) && (input->features & WALLY_TX_IS_ELEMENTS);
108 }
109 
is_valid_elements_tx_input_pegin(const struct wally_tx_input * input)110 static bool is_valid_elements_tx_input_pegin(const struct wally_tx_input *input)
111 {
112     return is_valid_elements_tx_input(input) && (input->features & WALLY_TX_IS_PEGIN);
113 }
114 
is_null_bytes(const unsigned char * bytes,size_t bytes_len)115 static bool is_null_bytes(const unsigned char *bytes, size_t bytes_len)
116 {
117     size_t i;
118     for (i = 0; i < bytes_len; ++i)
119         if (bytes[i])
120             return false;
121     return true;
122 }
123 
is_coinbase_bytes(const unsigned char * bytes,size_t bytes_len,uint32_t index)124 static bool is_coinbase_bytes(const unsigned char *bytes, size_t bytes_len, uint32_t index)
125 {
126     return index == 0xffffffff && is_null_bytes(bytes, bytes_len);
127 }
128 
is_valid_coinbase_input(const struct wally_tx_input * input)129 static bool is_valid_coinbase_input(const struct wally_tx_input *input)
130 {
131     return input && is_coinbase_bytes(input->txhash, sizeof(input->txhash), input->index);
132 }
133 
is_valid_elements_tx_output(const struct wally_tx_output * output)134 static bool is_valid_elements_tx_output(const struct wally_tx_output *output)
135 {
136     return output &&
137            BYTES_VALID(output->script, output->script_len) &&
138            (output->features & WALLY_TX_IS_ELEMENTS);
139 }
140 
is_valid_elements_tx(const struct wally_tx * tx)141 static bool is_valid_elements_tx(const struct wally_tx *tx)
142 {
143     size_t i;
144 
145     if (!tx->num_inputs && !tx->num_outputs)
146         return false; /* No inputs & no outputs, treat as non-elements tx */
147 
148     for (i = 0; i < tx->num_inputs; ++i)
149         if (!is_valid_elements_tx_input(tx->inputs + i))
150             return false;
151 
152     for (i = 0; i < tx->num_outputs; ++i)
153         if (!is_valid_elements_tx_output(tx->outputs + i))
154             return false;
155 
156     return true;
157 }
158 
clone_bytes(unsigned char ** dst,const unsigned char * src,size_t len)159 bool clone_bytes(unsigned char **dst, const unsigned char *src, size_t len)
160 {
161     if (!len) {
162         *dst = NULL;
163         return true;
164     }
165     *dst = wally_malloc(len);
166     if (*dst)
167         memcpy(*dst, src, len);
168     return *dst != NULL;
169 }
170 
realloc_array(const void * src,size_t old_n,size_t new_n,size_t size)171 void *realloc_array(const void *src, size_t old_n, size_t new_n, size_t size)
172 {
173     unsigned char *p = wally_malloc(new_n * size);
174     if (!p)
175         return NULL;
176     if (src)
177         memcpy(p, src, old_n * size);
178     wally_clear(p + old_n * size, (new_n - old_n) * size);
179     return p;
180 }
181 
replace_bytes(const unsigned char * bytes,size_t bytes_len,unsigned char ** bytes_out,size_t * bytes_len_out)182 int replace_bytes(const unsigned char *bytes, size_t bytes_len,
183                   unsigned char **bytes_out, size_t *bytes_len_out)
184 {
185     unsigned char *new_bytes = NULL;
186 
187     if (BYTES_INVALID(bytes, bytes_len) || BYTES_INVALID(*bytes_out, *bytes_len_out))
188         return WALLY_EINVAL;
189 
190     /* TODO: Avoid reallocation if new bytes is smaller than the existing one */
191     if (!clone_bytes(&new_bytes, bytes, bytes_len))
192         return WALLY_ENOMEM;
193 
194     clear_and_free(*bytes_out, *bytes_len_out);
195     *bytes_out = new_bytes;
196     *bytes_len_out = bytes_len;
197     return WALLY_OK;
198 }
199 
200 
wally_tx_witness_stack_clone_alloc(const struct wally_tx_witness_stack * stack,struct wally_tx_witness_stack ** output)201 int wally_tx_witness_stack_clone_alloc(const struct wally_tx_witness_stack *stack,
202                                        struct wally_tx_witness_stack **output)
203 {
204     struct wally_tx_witness_stack *result;
205     size_t i;
206     int ret;
207 
208     TX_CHECK_OUTPUT;
209     if (!stack)
210         return WALLY_EINVAL;
211 
212     ret = wally_tx_witness_stack_init_alloc(stack->items_allocation_len, &result);
213     for (i = 0; ret == WALLY_OK && i < stack->num_items; ++i) {
214         ret = wally_tx_witness_stack_set(result, i,
215                                          stack->items[i].witness,
216                                          stack->items[i].witness_len);
217     }
218     if (ret == WALLY_OK)
219         *output = result;
220     else
221         wally_tx_witness_stack_free(result);
222     return ret;
223 }
224 
wally_tx_witness_stack_init_alloc(size_t allocation_len,struct wally_tx_witness_stack ** output)225 int wally_tx_witness_stack_init_alloc(size_t allocation_len,
226                                       struct wally_tx_witness_stack **output)
227 {
228     struct wally_tx_witness_stack *result;
229 
230     TX_CHECK_OUTPUT;
231     TX_OUTPUT_ALLOC(struct wally_tx_witness_stack);
232 
233     if (allocation_len) {
234         result->items = wally_calloc(allocation_len * sizeof(*result->items));
235         if (!result->items) {
236             wally_free(result);
237             *output = NULL;
238             return WALLY_ENOMEM;
239         }
240     }
241     result->items_allocation_len = allocation_len;
242     result->num_items = 0;
243     return WALLY_OK;
244 }
245 
tx_witness_stack_free(struct wally_tx_witness_stack * stack,bool free_parent)246 static int tx_witness_stack_free(struct wally_tx_witness_stack *stack,
247                                  bool free_parent)
248 {
249     size_t i;
250 
251     if (stack) {
252         if (stack->items) {
253             for (i = 0; i < stack->num_items; ++i) {
254                 if (stack->items[i].witness)
255                     clear_and_free(stack->items[i].witness,
256                                    stack->items[i].witness_len);
257             }
258             clear_and_free(stack->items, stack->num_items * sizeof(*stack->items));
259         }
260         wally_clear(stack, sizeof(*stack));
261         if (free_parent)
262             wally_free(stack);
263     }
264     return WALLY_OK;
265 }
266 
wally_tx_witness_stack_free(struct wally_tx_witness_stack * stack)267 int wally_tx_witness_stack_free(struct wally_tx_witness_stack *stack)
268 {
269     return tx_witness_stack_free(stack, true);
270 }
271 
wally_tx_witness_stack_add(struct wally_tx_witness_stack * stack,const unsigned char * witness,size_t witness_len)272 int wally_tx_witness_stack_add(
273     struct wally_tx_witness_stack *stack,
274     const unsigned char *witness, size_t witness_len)
275 {
276     if (!stack)
277         return WALLY_EINVAL;
278     return wally_tx_witness_stack_set(stack, stack->num_items,
279                                       witness, witness_len);
280 }
281 
wally_tx_witness_stack_add_dummy(struct wally_tx_witness_stack * stack,uint32_t flags)282 int wally_tx_witness_stack_add_dummy(
283     struct wally_tx_witness_stack *stack, uint32_t flags)
284 {
285     if (!stack)
286         return WALLY_EINVAL;
287     return wally_tx_witness_stack_set_dummy(stack, stack->num_items, flags);
288 }
289 
290 
wally_tx_witness_stack_set(struct wally_tx_witness_stack * stack,size_t index,const unsigned char * witness,size_t witness_len)291 int wally_tx_witness_stack_set(struct wally_tx_witness_stack *stack, size_t index,
292                                const unsigned char *witness, size_t witness_len)
293 {
294     unsigned char *new_witness = NULL;
295 
296     if (!is_valid_witness_stack(stack) || (!witness && witness_len))
297         return WALLY_EINVAL;
298 
299     if (!clone_bytes(&new_witness, witness, witness_len))
300         return WALLY_ENOMEM;
301 
302     if (index >= stack->num_items) {
303         if (index >= stack->items_allocation_len) {
304             /* Expand the witness array */
305             struct wally_tx_witness_item *p;
306             p = realloc_array(stack->items, stack->items_allocation_len,
307                               index + 1, sizeof(*stack->items));
308             if (!p) {
309                 clear_and_free(new_witness, witness_len);
310                 return WALLY_ENOMEM;
311             }
312             clear_and_free(stack->items, stack->num_items * sizeof(*stack->items));
313             stack->items = p;
314             stack->items_allocation_len = index + 1;
315         }
316         stack->num_items = index + 1;
317     }
318     clear_and_free(stack->items[index].witness, stack->items[index].witness_len);
319     stack->items[index].witness = new_witness;
320     stack->items[index].witness_len = witness_len;
321     return WALLY_OK;
322 }
323 
wally_tx_witness_stack_set_dummy(struct wally_tx_witness_stack * stack,size_t index,uint32_t flags)324 int wally_tx_witness_stack_set_dummy(struct wally_tx_witness_stack *stack,
325                                      size_t index, uint32_t flags)
326 {
327     const unsigned char *p = NULL;
328     size_t len = 0;
329 
330     if (flags == WALLY_TX_DUMMY_SIG) {
331         p = DUMMY_SIG;
332         len = sizeof(DUMMY_SIG);
333     } else if (flags == WALLY_TX_DUMMY_SIG_LOW_R) {
334         p = DUMMY_SIG;
335         len = sizeof(DUMMY_SIG) - 1; /* Low-R signatures are always at least 1 byte shorter */
336     } else if (flags != WALLY_TX_DUMMY_NULL)
337         return WALLY_EINVAL;
338     return wally_tx_witness_stack_set(stack, index, p, len);
339 }
340 
clone_input_to(struct wally_tx_input * dst,const struct wally_tx_input * src)341 static bool clone_input_to(
342     struct wally_tx_input *dst,
343     const struct wally_tx_input *src)
344 {
345     unsigned char *new_script = NULL;
346 #ifdef BUILD_ELEMENTS
347     unsigned char *new_issuance_amount = NULL, *new_inflation_keys = NULL,
348                   *new_issuance_amount_rangeproof = NULL, *new_inflation_keys_rangeproof = NULL;
349     struct wally_tx_witness_stack *new_pegin_witness = NULL;
350 #endif
351     struct wally_tx_witness_stack *new_witness = NULL;
352 
353     if (src->witness)
354         wally_tx_witness_stack_clone_alloc(src->witness, &new_witness);
355 
356 #ifdef BUILD_ELEMENTS
357     if (src->pegin_witness)
358         wally_tx_witness_stack_clone_alloc(src->pegin_witness, &new_pegin_witness);
359 #endif
360 
361     if (!clone_bytes(&new_script, src->script, src->script_len) ||
362 #ifdef BUILD_ELEMENTS
363         !clone_bytes(&new_issuance_amount, src->issuance_amount, src->issuance_amount_len) ||
364         !clone_bytes(&new_inflation_keys, src->inflation_keys, src->inflation_keys_len) ||
365         !clone_bytes(&new_issuance_amount_rangeproof, src->issuance_amount_rangeproof, src->issuance_amount_rangeproof_len) ||
366         !clone_bytes(&new_inflation_keys_rangeproof, src->inflation_keys_rangeproof, src->inflation_keys_rangeproof_len) ||
367 #endif
368         (src->witness && !new_witness)) {
369         clear_and_free(new_script, src->script_len);
370 #ifdef BUILD_ELEMENTS
371         clear_and_free(new_issuance_amount, src->issuance_amount_len);
372         clear_and_free(new_inflation_keys, src->inflation_keys_len);
373         clear_and_free(new_issuance_amount_rangeproof, src->issuance_amount_rangeproof_len);
374         clear_and_free(new_inflation_keys_rangeproof, src->inflation_keys_rangeproof_len);
375         wally_tx_witness_stack_free(new_pegin_witness);
376 #endif
377         wally_tx_witness_stack_free(new_witness);
378         return false;
379     }
380 
381     memcpy(dst, src, sizeof(*src));
382     dst->script = new_script;
383 #ifdef BUILD_ELEMENTS
384     dst->issuance_amount = new_issuance_amount;
385     dst->inflation_keys = new_inflation_keys;
386     dst->issuance_amount_rangeproof = new_issuance_amount_rangeproof;
387     dst->inflation_keys_rangeproof = new_inflation_keys_rangeproof;
388     dst->pegin_witness = new_pegin_witness;
389 #endif
390     dst->witness = new_witness;
391     return true;
392 }
393 
tx_elements_input_issuance_proof_init(struct wally_tx_input * input,const unsigned char * issuance_amount_rangeproof,size_t issuance_amount_rangeproof_len,const unsigned char * inflation_keys_rangeproof,size_t inflation_keys_rangeproof_len)394 static int tx_elements_input_issuance_proof_init(
395     struct wally_tx_input *input,
396     const unsigned char *issuance_amount_rangeproof,
397     size_t issuance_amount_rangeproof_len,
398     const unsigned char *inflation_keys_rangeproof,
399     size_t inflation_keys_rangeproof_len)
400 {
401 #ifdef BUILD_ELEMENTS
402     unsigned char *new_issuance_amount_rangeproof = NULL, *new_inflation_keys_rangeproof = NULL;
403 #endif
404     (void) input;
405 
406     if (BYTES_INVALID(issuance_amount_rangeproof, issuance_amount_rangeproof_len) ||
407         BYTES_INVALID(inflation_keys_rangeproof, inflation_keys_rangeproof_len))
408         return WALLY_EINVAL;
409 
410 #ifdef BUILD_ELEMENTS
411     if (!clone_bytes(&new_issuance_amount_rangeproof, issuance_amount_rangeproof, issuance_amount_rangeproof_len) ||
412         !clone_bytes(&new_inflation_keys_rangeproof, inflation_keys_rangeproof, inflation_keys_rangeproof_len)) {
413         clear_and_free(new_issuance_amount_rangeproof, issuance_amount_rangeproof_len);
414         clear_and_free(new_inflation_keys_rangeproof, inflation_keys_rangeproof_len);
415         return WALLY_ENOMEM;
416     }
417 
418     input->issuance_amount_rangeproof = new_issuance_amount_rangeproof;
419     input->issuance_amount_rangeproof_len = issuance_amount_rangeproof_len;
420     input->inflation_keys_rangeproof = new_inflation_keys_rangeproof;
421     input->inflation_keys_rangeproof_len = inflation_keys_rangeproof_len;
422 #endif
423     return WALLY_OK;
424 }
425 
tx_elements_input_issuance_init(struct wally_tx_input * input,const unsigned char * nonce,size_t nonce_len,const unsigned char * entropy,size_t entropy_len,const unsigned char * issuance_amount,size_t issuance_amount_len,const unsigned char * inflation_keys,size_t inflation_keys_len,const unsigned char * issuance_amount_rangeproof,size_t issuance_amount_rangeproof_len,const unsigned char * inflation_keys_rangeproof,size_t inflation_keys_rangeproof_len,bool is_elements)426 static int tx_elements_input_issuance_init(
427     struct wally_tx_input *input,
428     const unsigned char *nonce,
429     size_t nonce_len,
430     const unsigned char *entropy,
431     size_t entropy_len,
432     const unsigned char *issuance_amount,
433     size_t issuance_amount_len,
434     const unsigned char *inflation_keys,
435     size_t inflation_keys_len,
436     const unsigned char *issuance_amount_rangeproof,
437     size_t issuance_amount_rangeproof_len,
438     const unsigned char *inflation_keys_rangeproof,
439     size_t inflation_keys_rangeproof_len,
440     bool is_elements)
441 {
442 #ifdef BUILD_ELEMENTS
443     int ret;
444     unsigned char *new_issuance_amount = NULL, *new_inflation_keys = NULL;
445 #endif
446 
447     if (!input ||
448         BYTES_INVALID_N(nonce, nonce_len, WALLY_TX_ASSET_TAG_LEN) ||
449         BYTES_INVALID_N(entropy, entropy_len, WALLY_TX_ASSET_TAG_LEN) ||
450         BYTES_INVALID(issuance_amount, issuance_amount_len) ||
451         BYTES_INVALID(inflation_keys, inflation_keys_len) ||
452         BYTES_INVALID(issuance_amount_rangeproof, issuance_amount_rangeproof_len) ||
453         BYTES_INVALID(inflation_keys_rangeproof, inflation_keys_rangeproof_len))
454         return WALLY_EINVAL;
455 
456 #ifdef BUILD_ELEMENTS
457     if (!clone_bytes(&new_issuance_amount, issuance_amount, issuance_amount_len) ||
458         !clone_bytes(&new_inflation_keys, inflation_keys, inflation_keys_len))
459         ret = WALLY_ENOMEM;
460     else
461         ret = tx_elements_input_issuance_proof_init(input,
462                                                     issuance_amount_rangeproof,
463                                                     issuance_amount_rangeproof_len,
464                                                     inflation_keys_rangeproof,
465                                                     inflation_keys_rangeproof_len);
466 
467     if (ret != WALLY_OK) {
468         clear_and_free(new_issuance_amount, issuance_amount_len);
469         clear_and_free(new_inflation_keys, inflation_keys_len);
470         return ret;
471     }
472 
473     TX_COPY_ELSE_CLEAR(input->blinding_nonce, nonce, sizeof(input->blinding_nonce));
474     TX_COPY_ELSE_CLEAR(input->entropy, entropy, sizeof(input->entropy));
475     input->issuance_amount = new_issuance_amount;
476     input->issuance_amount_len = issuance_amount_len;
477     input->inflation_keys = new_inflation_keys;
478     input->inflation_keys_len = inflation_keys_len;
479 #endif
480 
481     if (is_elements) {
482         input->features |= WALLY_TX_IS_ELEMENTS;
483         if (nonce || entropy)
484             input->features |= WALLY_TX_IS_ISSUANCE;
485     }
486 
487     return WALLY_OK;
488 }
489 
wally_tx_elements_input_issuance_set(struct wally_tx_input * input,const unsigned char * nonce,size_t nonce_len,const unsigned char * entropy,size_t entropy_len,const unsigned char * issuance_amount,size_t issuance_amount_len,const unsigned char * inflation_keys,size_t inflation_keys_len,const unsigned char * issuance_amount_rangeproof,size_t issuance_amount_rangeproof_len,const unsigned char * inflation_keys_rangeproof,size_t inflation_keys_rangeproof_len)490 int wally_tx_elements_input_issuance_set(
491     struct wally_tx_input *input,
492     const unsigned char *nonce,
493     size_t nonce_len,
494     const unsigned char *entropy,
495     size_t entropy_len,
496     const unsigned char *issuance_amount,
497     size_t issuance_amount_len,
498     const unsigned char *inflation_keys,
499     size_t inflation_keys_len,
500     const unsigned char *issuance_amount_rangeproof,
501     size_t issuance_amount_rangeproof_len,
502     const unsigned char *inflation_keys_rangeproof,
503     size_t inflation_keys_rangeproof_len)
504 {
505 #ifdef BUILD_ELEMENTS
506     unsigned char *input_issuance_amount = input->issuance_amount;
507     size_t input_issuance_amount_len = input->issuance_amount_len;
508     unsigned char *input_inflation_keys = input->inflation_keys;
509     size_t input_inflation_keys_len = input->inflation_keys_len;
510     unsigned char *input_issuance_amount_rangeproof = input->issuance_amount_rangeproof;
511     size_t input_issuance_amount_rangeproof_len = input->issuance_amount_rangeproof_len;
512     unsigned char *input_inflation_keys_rangeproof = input->inflation_keys_rangeproof;
513     size_t input_inflation_keys_rangeproof_len = input->inflation_keys_rangeproof_len;
514 #endif /* BUILD_ELEMENTS */
515     int ret = tx_elements_input_issuance_init(input,
516                                               nonce,
517                                               nonce_len,
518                                               entropy,
519                                               entropy_len,
520                                               issuance_amount,
521                                               issuance_amount_len,
522                                               inflation_keys,
523                                               inflation_keys_len,
524                                               issuance_amount_rangeproof,
525                                               issuance_amount_rangeproof_len,
526                                               inflation_keys_rangeproof,
527                                               inflation_keys_rangeproof_len,
528                                               true);
529 #ifdef BUILD_ELEMENTS
530     if (ret == WALLY_OK) {
531         clear_and_free(input_issuance_amount, input_issuance_amount_len);
532         clear_and_free(input_inflation_keys, input_inflation_keys_len);
533         clear_and_free(input_issuance_amount_rangeproof, input_issuance_amount_rangeproof_len);
534         clear_and_free(input_inflation_keys_rangeproof, input_inflation_keys_rangeproof_len);
535     }
536 #endif /* BUILD_ELEMENTS */
537     return ret;
538 }
539 
wally_tx_elements_input_issuance_free(struct wally_tx_input * input)540 int wally_tx_elements_input_issuance_free(
541     struct wally_tx_input *input)
542 {
543     (void) input;
544 #ifdef BUILD_ELEMENTS
545     if (input) {
546         input->features &= ~(WALLY_TX_IS_ELEMENTS | WALLY_TX_IS_ISSUANCE);
547         wally_clear(input->blinding_nonce, sizeof(input->blinding_nonce));
548         wally_clear(input->entropy, sizeof(input->entropy));
549 
550 #define FREE_PTR_AND_LEN(name) clear_and_free(input->name, input->name ## _len); \
551     input->name = NULL; input->name ## _len = 0
552 
553         FREE_PTR_AND_LEN(issuance_amount);
554         FREE_PTR_AND_LEN(inflation_keys);
555         FREE_PTR_AND_LEN(issuance_amount_rangeproof);
556         FREE_PTR_AND_LEN(inflation_keys_rangeproof);
557 #undef FREE_PTR_AND_LEN
558 
559         tx_witness_stack_free(input->pegin_witness, true);
560         input->pegin_witness = NULL;
561     }
562 #endif /* BUILD_ELEMENTS */
563     return WALLY_OK;
564 }
565 
tx_elements_input_init(const unsigned char * txhash,size_t txhash_len,uint32_t utxo_index,uint32_t sequence,const unsigned char * script,size_t script_len,const struct wally_tx_witness_stack * witness,const unsigned char * nonce,size_t nonce_len,const unsigned char * entropy,size_t entropy_len,const unsigned char * issuance_amount,size_t issuance_amount_len,const unsigned char * inflation_keys,size_t inflation_keys_len,const unsigned char * issuance_amount_rangeproof,size_t issuance_amount_rangeproof_len,const unsigned char * inflation_keys_rangeproof,size_t inflation_keys_rangeproof_len,const struct wally_tx_witness_stack * pegin_witness,struct wally_tx_input * output,bool is_elements)566 static int tx_elements_input_init(
567     const unsigned char *txhash, size_t txhash_len,
568     uint32_t utxo_index, uint32_t sequence,
569     const unsigned char *script, size_t script_len,
570     const struct wally_tx_witness_stack *witness,
571     const unsigned char *nonce, size_t nonce_len,
572     const unsigned char *entropy, size_t entropy_len,
573     const unsigned char *issuance_amount, size_t issuance_amount_len,
574     const unsigned char *inflation_keys, size_t inflation_keys_len,
575     const unsigned char *issuance_amount_rangeproof, size_t issuance_amount_rangeproof_len,
576     const unsigned char *inflation_keys_rangeproof, size_t inflation_keys_rangeproof_len,
577     const struct wally_tx_witness_stack *pegin_witness,
578     struct wally_tx_input *output, bool is_elements)
579 {
580     struct wally_tx_witness_stack *new_witness = NULL;
581     struct wally_tx_witness_stack *new_pegin_witness = NULL;
582     unsigned char *new_script = NULL;
583     int ret = WALLY_OK, old_features;
584 
585     if (!txhash || txhash_len != WALLY_TXHASH_LEN ||
586         BYTES_INVALID(script, script_len) || !output)
587         return WALLY_EINVAL;
588 
589     old_features = output->features;
590 
591     if (witness)
592         ret = wally_tx_witness_stack_clone_alloc(witness, &new_witness);
593     if (ret == WALLY_OK && pegin_witness)
594         ret = wally_tx_witness_stack_clone_alloc(pegin_witness, &new_pegin_witness);
595     if (ret == WALLY_OK && !clone_bytes(&new_script, script, script_len))
596         ret = WALLY_ENOMEM;
597     if (ret == WALLY_OK) {
598         output->features = 0;
599         ret = tx_elements_input_issuance_init(output,
600                                               nonce,
601                                               nonce_len,
602                                               entropy,
603                                               entropy_len,
604                                               issuance_amount,
605                                               issuance_amount_len,
606                                               inflation_keys,
607                                               inflation_keys_len,
608                                               issuance_amount_rangeproof,
609                                               issuance_amount_rangeproof_len,
610                                               inflation_keys_rangeproof,
611                                               inflation_keys_rangeproof_len,
612                                               is_elements);
613     }
614 
615     if (ret != WALLY_OK) {
616         wally_tx_witness_stack_free(new_witness);
617         wally_tx_witness_stack_free(new_pegin_witness);
618         clear_and_free(new_script, script_len);
619         output->features = old_features;
620     } else {
621         const bool is_coinbase = is_coinbase_bytes(txhash, WALLY_TXHASH_LEN, utxo_index);
622         memcpy(output->txhash, txhash, WALLY_TXHASH_LEN);
623         if (is_elements && !is_coinbase)
624             output->index = utxo_index & WALLY_TX_INDEX_MASK;
625         else
626             output->index = utxo_index;
627         if (is_elements && !is_coinbase && (utxo_index & WALLY_TX_PEGIN_FLAG))
628             output->features |= WALLY_TX_IS_PEGIN;
629         if (is_coinbase)
630             output->features |= WALLY_TX_IS_COINBASE;
631         output->sequence = sequence;
632         output->script = new_script;
633         output->script_len = script_len;
634         output->witness = new_witness;
635 #ifdef BUILD_ELEMENTS
636         output->pegin_witness = new_pegin_witness;
637 #endif /* BUILD_ELEMENTS */
638     }
639     return ret;
640 }
641 
wally_tx_elements_input_init(const unsigned char * txhash,size_t txhash_len,uint32_t utxo_index,uint32_t sequence,const unsigned char * script,size_t script_len,const struct wally_tx_witness_stack * witness,const unsigned char * nonce,size_t nonce_len,const unsigned char * entropy,size_t entropy_len,const unsigned char * issuance_amount,size_t issuance_amount_len,const unsigned char * inflation_keys,uint64_t inflation_keys_len,const unsigned char * issuance_amount_rangeproof,size_t issuance_amount_rangeproof_len,const unsigned char * inflation_keys_rangeproof,size_t inflation_keys_rangeproof_len,const struct wally_tx_witness_stack * pegin_witness,struct wally_tx_input * output)642 int wally_tx_elements_input_init(
643     const unsigned char *txhash, size_t txhash_len,
644     uint32_t utxo_index, uint32_t sequence,
645     const unsigned char *script, size_t script_len,
646     const struct wally_tx_witness_stack *witness,
647     const unsigned char *nonce, size_t nonce_len,
648     const unsigned char *entropy, size_t entropy_len,
649     const unsigned char *issuance_amount, size_t issuance_amount_len,
650     const unsigned char *inflation_keys, uint64_t inflation_keys_len,
651     const unsigned char *issuance_amount_rangeproof, size_t issuance_amount_rangeproof_len,
652     const unsigned char *inflation_keys_rangeproof, size_t inflation_keys_rangeproof_len,
653     const struct wally_tx_witness_stack *pegin_witness,
654     struct wally_tx_input *output)
655 {
656     return tx_elements_input_init(
657         txhash, txhash_len,
658         utxo_index, sequence,
659         script, script_len,
660         witness, nonce, nonce_len,
661         entropy, entropy_len,
662         issuance_amount, issuance_amount_len,
663         inflation_keys, inflation_keys_len,
664         issuance_amount_rangeproof, issuance_amount_rangeproof_len,
665         inflation_keys_rangeproof, inflation_keys_rangeproof_len,
666         pegin_witness, output, true);
667 }
668 
wally_tx_input_init(const unsigned char * txhash,size_t txhash_len,uint32_t utxo_index,uint32_t sequence,const unsigned char * script,size_t script_len,const struct wally_tx_witness_stack * witness,struct wally_tx_input * output)669 int wally_tx_input_init(const unsigned char *txhash, size_t txhash_len,
670                         uint32_t utxo_index, uint32_t sequence,
671                         const unsigned char *script, size_t script_len,
672                         const struct wally_tx_witness_stack *witness,
673                         struct wally_tx_input *output)
674 {
675     return tx_elements_input_init(txhash, txhash_len,
676                                   utxo_index, sequence,
677                                   script, script_len,
678                                   witness, NULL, 0, NULL, 0,
679                                   NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL,
680                                   output, false);
681 }
682 
wally_tx_elements_input_init_alloc(const unsigned char * txhash,size_t txhash_len,uint32_t utxo_index,uint32_t sequence,const unsigned char * script,size_t script_len,const struct wally_tx_witness_stack * witness,const unsigned char * nonce,size_t nonce_len,const unsigned char * entropy,size_t entropy_len,const unsigned char * issuance_amount,size_t issuance_amount_len,const unsigned char * inflation_keys,size_t inflation_keys_len,const unsigned char * issuance_amount_rangeproof,size_t issuance_amount_rangeproof_len,const unsigned char * inflation_keys_rangeproof,size_t inflation_keys_rangeproof_len,const struct wally_tx_witness_stack * pegin_witness,struct wally_tx_input ** output)683 int wally_tx_elements_input_init_alloc(
684     const unsigned char *txhash, size_t txhash_len,
685     uint32_t utxo_index, uint32_t sequence,
686     const unsigned char *script, size_t script_len,
687     const struct wally_tx_witness_stack *witness,
688     const unsigned char *nonce, size_t nonce_len,
689     const unsigned char *entropy, size_t entropy_len,
690     const unsigned char *issuance_amount, size_t issuance_amount_len,
691     const unsigned char *inflation_keys, size_t inflation_keys_len,
692     const unsigned char *issuance_amount_rangeproof, size_t issuance_amount_rangeproof_len,
693     const unsigned char *inflation_keys_rangeproof, size_t inflation_keys_rangeproof_len,
694     const struct wally_tx_witness_stack *pegin_witness,
695     struct wally_tx_input **output)
696 {
697     struct wally_tx_input *result;
698     int ret;
699 
700     TX_CHECK_OUTPUT;
701     TX_OUTPUT_ALLOC(struct wally_tx_input);
702 
703     ret = tx_elements_input_init(txhash, txhash_len, utxo_index, sequence,
704                                  script, script_len, witness,
705                                  nonce, nonce_len, entropy, entropy_len,
706                                  issuance_amount, issuance_amount_len,
707                                  inflation_keys, inflation_keys_len,
708                                  issuance_amount_rangeproof,
709                                  issuance_amount_rangeproof_len,
710                                  inflation_keys_rangeproof,
711                                  inflation_keys_rangeproof_len, pegin_witness,
712                                  result, true);
713 
714     if (ret != WALLY_OK) {
715         clear_and_free(result, sizeof(*result));
716         *output = NULL;
717     }
718     return ret;
719 }
720 
wally_tx_input_init_alloc(const unsigned char * txhash,size_t txhash_len,uint32_t utxo_index,uint32_t sequence,const unsigned char * script,size_t script_len,const struct wally_tx_witness_stack * witness,struct wally_tx_input ** output)721 int wally_tx_input_init_alloc(const unsigned char *txhash, size_t txhash_len,
722                               uint32_t utxo_index, uint32_t sequence,
723                               const unsigned char *script, size_t script_len,
724                               const struct wally_tx_witness_stack *witness,
725                               struct wally_tx_input **output)
726 {
727     struct wally_tx_input *result;
728     int ret;
729 
730     TX_CHECK_OUTPUT;
731     TX_OUTPUT_ALLOC(struct wally_tx_input);
732 
733     ret = wally_tx_input_init(txhash, txhash_len, utxo_index, sequence,
734                               script, script_len, witness, result);
735 
736     if (ret != WALLY_OK) {
737         clear_and_free(result, sizeof(*result));
738         *output = NULL;
739     }
740     return ret;
741 }
742 
tx_input_free(struct wally_tx_input * input,bool free_parent)743 static int tx_input_free(struct wally_tx_input *input, bool free_parent)
744 {
745     if (input) {
746         clear_and_free(input->script, input->script_len);
747         tx_witness_stack_free(input->witness, true);
748         wally_tx_elements_input_issuance_free(input);
749         wally_clear(input, sizeof(*input));
750         if (free_parent)
751             wally_free(input);
752     }
753     return WALLY_OK;
754 }
755 
wally_tx_input_free(struct wally_tx_input * input)756 int wally_tx_input_free(struct wally_tx_input *input)
757 {
758     return tx_input_free(input, true);
759 }
760 
wally_tx_output_clone(const struct wally_tx_output * src,struct wally_tx_output * output)761 int wally_tx_output_clone(const struct wally_tx_output *src,
762                           struct wally_tx_output *output)
763 {
764     unsigned char *new_script = NULL;
765 #ifdef BUILD_ELEMENTS
766     unsigned char *new_asset = NULL, *new_value = NULL, *new_nonce = NULL,
767                   *new_surjectionproof = NULL, *new_rangeproof = NULL;
768 #endif
769     if (!src || !output)
770         return WALLY_EINVAL;
771 
772 #ifdef BUILD_ELEMENTS
773     if (!clone_bytes(&new_asset, src->asset, src->asset_len) ||
774         !clone_bytes(&new_value, src->value, src->value_len) ||
775         !clone_bytes(&new_nonce, src->nonce, src->nonce_len) ||
776         !clone_bytes(&new_surjectionproof, src->surjectionproof, src->surjectionproof_len) ||
777         !clone_bytes(&new_rangeproof, src->rangeproof, src->rangeproof_len) ||
778         !clone_bytes(&new_script, src->script, src->script_len)) {
779 #else
780     if (!clone_bytes(&new_script, src->script, src->script_len)) {
781 #endif
782         clear_and_free(new_script, src->script_len);
783 #ifdef BUILD_ELEMENTS
784         clear_and_free(new_asset, src->asset_len);
785         clear_and_free(new_value, src->value_len);
786         clear_and_free(new_nonce, src->nonce_len);
787         clear_and_free(new_surjectionproof,  src->surjectionproof_len);
788         clear_and_free(new_rangeproof, src->rangeproof_len);
789 #endif
790         return WALLY_ENOMEM;
791     }
792 
793     memcpy(output, src, sizeof(*src));
794     output->script = new_script;
795 #ifdef BUILD_ELEMENTS
796     output->asset = new_asset;
797     output->value = new_value;
798     output->nonce = new_nonce;
799     output->surjectionproof = new_surjectionproof;
800     output->rangeproof = new_rangeproof;
801 #endif
802     return WALLY_OK;
803 }
804 
805 int wally_tx_output_clone_alloc(const struct wally_tx_output *src,
806                                 struct wally_tx_output **output)
807 {
808     struct wally_tx_output *result;
809     int ret;
810 
811     TX_CHECK_OUTPUT;
812     TX_OUTPUT_ALLOC(struct wally_tx_output);
813 
814     ret = wally_tx_output_clone(src, result);
815     if (ret != WALLY_OK) {
816         wally_free(result);
817         *output = NULL;
818     }
819     return ret;
820 }
821 
822 static int tx_elements_output_proof_init(
823     struct wally_tx_output *output,
824     const unsigned char *surjectionproof,
825     size_t surjectionproof_len,
826     const unsigned char *rangeproof,
827     size_t rangeproof_len)
828 {
829 #ifdef BUILD_ELEMENTS
830     unsigned char *new_surjectionproof = NULL, *new_rangeproof = NULL;
831 #endif
832     (void) output;
833 
834     if (BYTES_INVALID(surjectionproof, surjectionproof_len) ||
835         BYTES_INVALID(rangeproof, rangeproof_len))
836         return WALLY_EINVAL;
837 
838 #ifdef BUILD_ELEMENTS
839     if (!clone_bytes(&new_surjectionproof, surjectionproof, surjectionproof_len) ||
840         !clone_bytes(&new_rangeproof, rangeproof, rangeproof_len)) {
841         clear_and_free(new_surjectionproof,  surjectionproof_len);
842         clear_and_free(new_rangeproof, rangeproof_len);
843         return WALLY_ENOMEM;
844     }
845 
846     output->surjectionproof = new_surjectionproof;
847     output->surjectionproof_len = surjectionproof_len;
848     output->rangeproof = new_rangeproof;
849     output->rangeproof_len = rangeproof_len;
850 #endif
851     return WALLY_OK;
852 }
853 
854 static int tx_elements_output_commitment_init(
855     struct wally_tx_output *output,
856     const unsigned char *asset,
857     size_t asset_len,
858     const unsigned char *value,
859     size_t value_len,
860     const unsigned char *nonce,
861     size_t nonce_len,
862     const unsigned char *surjectionproof,
863     size_t surjectionproof_len,
864     const unsigned char *rangeproof,
865     size_t rangeproof_len,
866     bool is_elements)
867 {
868 #ifdef BUILD_ELEMENTS
869     int ret;
870     unsigned char *new_asset = NULL, *new_value = NULL, *new_nonce = NULL;
871 #endif
872 
873     if (!output ||
874         BYTES_INVALID_N(asset, asset_len, WALLY_TX_ASSET_CT_ASSET_LEN) ||
875         ((value != NULL) != (value_len == WALLY_TX_ASSET_CT_VALUE_LEN ||
876                              value_len == WALLY_TX_ASSET_CT_VALUE_UNBLIND_LEN)) ||
877         BYTES_INVALID_N(nonce, nonce_len, WALLY_TX_ASSET_CT_NONCE_LEN) ||
878         BYTES_INVALID(surjectionproof, surjectionproof_len) ||
879         BYTES_INVALID(rangeproof, rangeproof_len))
880         return WALLY_EINVAL;
881 
882 #ifdef BUILD_ELEMENTS
883     if (!clone_bytes(&new_asset, asset, asset_len) ||
884         !clone_bytes(&new_value, value, value_len) ||
885         !clone_bytes(&new_nonce, nonce, nonce_len))
886         ret = WALLY_ENOMEM;
887     else
888         ret = tx_elements_output_proof_init(output,
889                                             surjectionproof,
890                                             surjectionproof_len,
891                                             rangeproof,
892                                             rangeproof_len);
893     if (ret != WALLY_OK) {
894         clear_and_free(new_asset, asset_len);
895         clear_and_free(new_value, value_len);
896         clear_and_free(new_nonce, nonce_len);
897         return ret;
898     }
899 
900     output->asset = new_asset;
901     output->asset_len = asset_len;
902     output->value = new_value;
903     output->value_len = value_len;
904     output->nonce = new_nonce;
905     output->nonce_len = nonce_len;
906 #endif /* BUILD_ELEMENTS */
907 
908     if (is_elements)
909         output->features |= WALLY_TX_IS_ELEMENTS;
910 
911     return WALLY_OK;
912 }
913 
914 int wally_tx_elements_output_commitment_set(
915     struct wally_tx_output *output,
916     const unsigned char *asset,
917     size_t asset_len,
918     const unsigned char *value,
919     size_t value_len,
920     const unsigned char *nonce,
921     size_t nonce_len,
922     const unsigned char *surjectionproof,
923     size_t surjectionproof_len,
924     const unsigned char *rangeproof,
925     size_t rangeproof_len)
926 {
927 #ifdef BUILD_ELEMENTS
928     unsigned char *output_asset = output->asset;
929     size_t output_asset_len = output->asset_len;
930     unsigned char *output_value = output->value;
931     size_t output_value_len = output->value_len;
932     unsigned char *output_nonce = output->nonce;
933     size_t output_nonce_len = output->nonce_len;
934     unsigned char *output_surjectionproof = output->surjectionproof;
935     size_t output_surjectionproof_len = output->surjectionproof_len;
936     unsigned char *output_rangeproof = output->rangeproof;
937     size_t output_rangeproof_len = output->rangeproof_len;
938 #endif /* BUILD_ELEMENTS */
939     int ret = tx_elements_output_commitment_init(output, asset, asset_len,
940                                                  value, value_len,
941                                                  nonce, nonce_len,
942                                                  surjectionproof, surjectionproof_len,
943                                                  rangeproof, rangeproof_len, true);
944     if (ret == WALLY_OK) {
945 #ifdef BUILD_ELEMENTS
946         clear_and_free(output_asset, output_asset_len);
947         clear_and_free(output_value, output_value_len);
948         clear_and_free(output_nonce, output_nonce_len);
949         clear_and_free(output_surjectionproof, output_surjectionproof_len);
950         clear_and_free(output_rangeproof, output_rangeproof_len);
951 #endif /* BUILD_ELEMENTS */
952     }
953     return ret;
954 }
955 
956 int wally_tx_elements_output_commitment_free(
957     struct wally_tx_output *output)
958 {
959     (void) output;
960 #ifdef BUILD_ELEMENTS
961     if (output) {
962         output->features &= ~WALLY_TX_IS_ELEMENTS;
963         clear_and_free(output->asset, output->asset_len);
964         clear_and_free(output->value, output->value_len);
965         clear_and_free(output->nonce, output->nonce_len);
966         clear_and_free(output->surjectionproof, output->surjectionproof_len);
967         clear_and_free(output->rangeproof, output->rangeproof_len);
968     }
969 #endif /* BUILD_ELEMENTS */
970     return WALLY_OK;
971 }
972 
973 static int tx_elements_output_init(
974     uint64_t satoshi,
975     const unsigned char *script,
976     size_t script_len,
977     const unsigned char *asset,
978     size_t asset_len,
979     const unsigned char *value,
980     size_t value_len,
981     const unsigned char *nonce,
982     size_t nonce_len,
983     const unsigned char *surjectionproof,
984     size_t surjectionproof_len,
985     const unsigned char *rangeproof,
986     size_t rangeproof_len,
987     struct wally_tx_output *output,
988     bool is_elements)
989 {
990     int ret, old_features;
991     unsigned char *new_script = NULL;
992 
993     if (BYTES_INVALID(script, script_len) || !output ||
994         (satoshi > WALLY_SATOSHI_MAX && !is_elements))
995         return WALLY_EINVAL;
996 
997     if (!clone_bytes(&new_script, script, script_len))
998         return WALLY_ENOMEM;
999 
1000     old_features = output->features;
1001     output->features = 0;
1002     if ((ret = tx_elements_output_commitment_init(output, asset, asset_len,
1003                                                   value, value_len,
1004                                                   nonce, nonce_len,
1005                                                   surjectionproof, surjectionproof_len,
1006                                                   rangeproof, rangeproof_len,
1007                                                   is_elements)) != WALLY_OK) {
1008         output->features = old_features;
1009         clear_and_free(new_script, script_len);
1010         return ret;
1011     }
1012 
1013     output->script = new_script;
1014     output->script_len = script_len;
1015     output->satoshi = satoshi;
1016     return WALLY_OK;
1017 }
1018 
1019 int wally_tx_elements_output_init(
1020     const unsigned char *script,
1021     size_t script_len,
1022     const unsigned char *asset,
1023     size_t asset_len,
1024     const unsigned char *value,
1025     size_t value_len,
1026     const unsigned char *nonce,
1027     size_t nonce_len,
1028     const unsigned char *surjectionproof,
1029     size_t surjectionproof_len,
1030     const unsigned char *rangeproof,
1031     size_t rangeproof_len,
1032     struct wally_tx_output *output)
1033 {
1034     return tx_elements_output_init(MAX_INVALID_SATOSHI, script, script_len,
1035                                    asset, asset_len, value, value_len,
1036                                    nonce, nonce_len,
1037                                    surjectionproof, surjectionproof_len,
1038                                    rangeproof, rangeproof_len, output, true);
1039 }
1040 
1041 int wally_tx_elements_output_init_alloc(
1042     const unsigned char *script,
1043     size_t script_len,
1044     const unsigned char *asset,
1045     size_t asset_len,
1046     const unsigned char *value,
1047     size_t value_len,
1048     const unsigned char *nonce,
1049     size_t nonce_len,
1050     const unsigned char *surjectionproof,
1051     size_t surjectionproof_len,
1052     const unsigned char *rangeproof,
1053     size_t rangeproof_len,
1054     struct wally_tx_output **output)
1055 {
1056     struct wally_tx_output *result;
1057     int ret;
1058 
1059     TX_CHECK_OUTPUT;
1060     TX_OUTPUT_ALLOC(struct wally_tx_output);
1061 
1062     ret = tx_elements_output_init(-1, script, script_len,
1063                                   asset, asset_len,
1064                                   value, value_len,
1065                                   nonce, nonce_len,
1066                                   surjectionproof,
1067                                   surjectionproof_len,
1068                                   rangeproof, rangeproof_len,
1069                                   result, true);
1070     if (ret != WALLY_OK) {
1071         clear_and_free(result, sizeof(*result));
1072         *output = NULL;
1073     }
1074     return ret;
1075 }
1076 
1077 int wally_tx_output_init(uint64_t satoshi,
1078                          const unsigned char *script, size_t script_len,
1079                          struct wally_tx_output *output)
1080 {
1081     return tx_elements_output_init(satoshi, script, script_len,
1082                                    NULL, 0, NULL, 0, NULL, 0,
1083                                    NULL, 0, NULL, 0, output, false);
1084 }
1085 
1086 int wally_tx_output_init_alloc(uint64_t satoshi,
1087                                const unsigned char *script, size_t script_len,
1088                                struct wally_tx_output **output)
1089 {
1090     struct wally_tx_output *result;
1091     int ret;
1092 
1093     TX_CHECK_OUTPUT;
1094     TX_OUTPUT_ALLOC(struct wally_tx_output);
1095 
1096     ret = wally_tx_output_init(satoshi, script, script_len, result);
1097 
1098     if (ret != WALLY_OK) {
1099         clear_and_free(result, sizeof(*result));
1100         *output = NULL;
1101     }
1102     return ret;
1103 }
1104 
1105 static int tx_output_free(struct wally_tx_output *output, bool free_parent)
1106 {
1107     if (output) {
1108         clear_and_free(output->script, output->script_len);
1109         wally_tx_elements_output_commitment_free(output);
1110         wally_clear(output, sizeof(*output));
1111         if (free_parent)
1112             wally_free(output);
1113     }
1114     return WALLY_OK;
1115 }
1116 
1117 int wally_tx_output_free(struct wally_tx_output *output)
1118 {
1119     return tx_output_free(output, true);
1120 }
1121 
1122 int wally_tx_init_alloc(uint32_t version, uint32_t locktime,
1123                         size_t inputs_allocation_len,
1124                         size_t outputs_allocation_len,
1125                         struct wally_tx **output)
1126 {
1127     struct wally_tx_input *new_inputs = NULL;
1128     struct wally_tx_output *new_outputs = NULL;
1129     struct wally_tx *result;
1130 
1131     TX_CHECK_OUTPUT;
1132     TX_OUTPUT_ALLOC(struct wally_tx);
1133 
1134     if (inputs_allocation_len)
1135         new_inputs = wally_malloc(inputs_allocation_len * sizeof(struct wally_tx_input));
1136     if (outputs_allocation_len)
1137         new_outputs = wally_malloc(outputs_allocation_len * sizeof(struct wally_tx_output));
1138     if ((inputs_allocation_len && !new_inputs) ||
1139         (outputs_allocation_len && !new_outputs)) {
1140         wally_free(new_inputs);
1141         wally_free(new_outputs);
1142         wally_free(result);
1143         *output = NULL;
1144         return WALLY_ENOMEM;
1145     }
1146 
1147     result->version = version;
1148     result->locktime = locktime;
1149     result->inputs = new_inputs;
1150     result->num_inputs = 0;
1151     result->inputs_allocation_len = inputs_allocation_len;
1152     result->outputs = new_outputs;
1153     result->num_outputs = 0;
1154     result->outputs_allocation_len = outputs_allocation_len;
1155     return WALLY_OK;
1156 }
1157 
1158 static int tx_free(struct wally_tx *tx, bool free_parent)
1159 {
1160     size_t i;
1161     if (tx) {
1162         for (i = 0; i < tx->num_inputs; ++i)
1163             tx_input_free(&tx->inputs[i], false);
1164         clear_and_free(tx->inputs, tx->inputs_allocation_len * sizeof(*tx->inputs));
1165         for (i = 0; i < tx->num_outputs; ++i)
1166             tx_output_free(&tx->outputs[i], false);
1167         clear_and_free(tx->outputs, tx->outputs_allocation_len * sizeof(*tx->outputs));
1168         wally_clear(tx, sizeof(*tx));
1169         if (free_parent)
1170             wally_free(tx);
1171     }
1172     return WALLY_OK;
1173 }
1174 
1175 int wally_tx_free(struct wally_tx *tx)
1176 {
1177     return tx_free(tx, true);
1178 }
1179 
1180 int wally_tx_add_input_at(struct wally_tx *tx, uint32_t index,
1181                           const struct wally_tx_input *input)
1182 {
1183     if (!is_valid_tx(tx) || index > tx->num_inputs || !is_valid_tx_input(input))
1184         return WALLY_EINVAL;
1185 
1186     if (tx->num_inputs >= tx->inputs_allocation_len) {
1187         /* Expand the inputs array */
1188         struct wally_tx_input *p;
1189         p = realloc_array(tx->inputs, tx->inputs_allocation_len,
1190                           tx->num_inputs + 1, sizeof(*tx->inputs));
1191         if (!p)
1192             return WALLY_ENOMEM;
1193 
1194         clear_and_free(tx->inputs, tx->num_inputs * sizeof(*tx->inputs));
1195         tx->inputs = p;
1196         tx->inputs_allocation_len += 1;
1197     }
1198 
1199     memmove(tx->inputs + index + 1, tx->inputs + index,
1200             (tx->num_inputs - index) * sizeof(*input));
1201 
1202     if (!clone_input_to(tx->inputs + index, input)) {
1203         memmove(tx->inputs + index, tx->inputs + index + 1,
1204                 (tx->num_inputs - index) * sizeof(*input)); /* Undo */
1205         return WALLY_ENOMEM;
1206     }
1207 
1208     tx->num_inputs += 1;
1209     return WALLY_OK;
1210 }
1211 
1212 int wally_tx_add_input(struct wally_tx *tx, const struct wally_tx_input *input)
1213 {
1214     return tx ? wally_tx_add_input_at(tx, tx->num_inputs, input) : WALLY_EINVAL;
1215 }
1216 
1217 static int tx_add_elements_raw_input_at(
1218     struct wally_tx *tx, uint32_t index,
1219     const unsigned char *txhash, size_t txhash_len,
1220     uint32_t utxo_index, uint32_t sequence,
1221     const unsigned char *script, size_t script_len,
1222     const struct wally_tx_witness_stack *witness,
1223     const unsigned char *nonce, size_t nonce_len,
1224     const unsigned char *entropy, size_t entropy_len,
1225     const unsigned char *issuance_amount, size_t issuance_amount_len,
1226     const unsigned char *inflation_keys, size_t inflation_keys_len,
1227     const unsigned char *issuance_amount_rangeproof, size_t issuance_amount_rangeproof_len,
1228     const unsigned char *inflation_keys_rangeproof, size_t inflation_keys_rangeproof_len,
1229     const struct wally_tx_witness_stack *pegin_witness,
1230     uint32_t flags, bool is_elements)
1231 {
1232     /* Add an input without allocating a temporary wally_tx_input */
1233     struct wally_tx_input input = {
1234         { 0 }, utxo_index, sequence,
1235         (unsigned char *)script, script_len,
1236         (struct wally_tx_witness_stack *) witness,
1237         is_elements ? WALLY_TX_IS_ELEMENTS : 0,
1238 #ifdef BUILD_ELEMENTS
1239         { 0 }, { 0 }, (unsigned char *) issuance_amount,
1240         issuance_amount_len,
1241         (unsigned char *) inflation_keys,
1242         inflation_keys_len,
1243         (unsigned char *) issuance_amount_rangeproof,
1244         issuance_amount_rangeproof_len,
1245         (unsigned char *) inflation_keys_rangeproof,
1246         inflation_keys_rangeproof_len,
1247         (struct wally_tx_witness_stack *) pegin_witness
1248 #endif /* BUILD_ELEMENTS */
1249     };
1250     bool is_coinbase;
1251     int ret;
1252 #ifndef BUILD_ELEMENTS
1253     (void)pegin_witness;
1254 #endif
1255 
1256     if (flags)
1257         return WALLY_EINVAL; /* TODO: Allow creation of p2pkh/p2sh using flags */
1258 
1259     if (!txhash || txhash_len != WALLY_TXHASH_LEN ||
1260         BYTES_INVALID_N(nonce, nonce_len, WALLY_TX_ASSET_TAG_LEN) ||
1261         BYTES_INVALID_N(entropy, entropy_len, WALLY_TX_ASSET_TAG_LEN) ||
1262         BYTES_INVALID(issuance_amount, issuance_amount_len) ||
1263         BYTES_INVALID(inflation_keys, inflation_keys_len) ||
1264         BYTES_INVALID(issuance_amount_rangeproof, issuance_amount_rangeproof_len) ||
1265         BYTES_INVALID(inflation_keys_rangeproof, inflation_keys_rangeproof_len))
1266         return WALLY_EINVAL;
1267 
1268     is_coinbase = is_coinbase_bytes(txhash, txhash_len, utxo_index);
1269     if (is_elements && !is_coinbase)
1270         input.index = utxo_index & WALLY_TX_INDEX_MASK;
1271     else
1272         input.index = utxo_index;
1273     if (is_coinbase)
1274         input.features |= WALLY_TX_IS_COINBASE;
1275     else if (is_elements) {
1276         if (utxo_index & WALLY_TX_ISSUANCE_FLAG)
1277             input.features |= WALLY_TX_IS_ISSUANCE;
1278         if (utxo_index & WALLY_TX_PEGIN_FLAG)
1279             input.features |= WALLY_TX_IS_PEGIN;
1280     }
1281 
1282     memcpy(input.txhash, txhash, WALLY_TXHASH_LEN);
1283 #ifdef BUILD_ELEMENTS
1284     if (nonce)
1285         memcpy(input.blinding_nonce, nonce, WALLY_TX_ASSET_TAG_LEN);
1286     if (entropy)
1287         memcpy(input.entropy, entropy, WALLY_TX_ASSET_TAG_LEN);
1288 #endif /* BUILD_ELEMENTS */
1289     ret = wally_tx_add_input_at(tx, index, &input);
1290     wally_clear(&input, sizeof(input));
1291     return ret;
1292 }
1293 
1294 int wally_tx_add_elements_raw_input(
1295     struct wally_tx *tx,
1296     const unsigned char *txhash, size_t txhash_len,
1297     uint32_t utxo_index, uint32_t sequence,
1298     const unsigned char *script, size_t script_len,
1299     const struct wally_tx_witness_stack *witness,
1300     const unsigned char *nonce, size_t nonce_len,
1301     const unsigned char *entropy, size_t entropy_len,
1302     const unsigned char *issuance_amount, size_t issuance_amount_len,
1303     const unsigned char *inflation_keys, size_t inflation_keys_len,
1304     const unsigned char *issuance_amount_rangeproof, size_t issuance_amount_rangeproof_len,
1305     const unsigned char *inflation_keys_rangeproof, size_t inflation_keys_rangeproof_len,
1306     const struct wally_tx_witness_stack *pegin_witness, uint32_t flags)
1307 {
1308     if (!tx)
1309         return WALLY_EINVAL;
1310     return tx_add_elements_raw_input_at(
1311         tx, tx->num_inputs, txhash, txhash_len,
1312         utxo_index, sequence, script,
1313         script_len, witness,
1314         nonce, nonce_len, entropy, entropy_len,
1315         issuance_amount, issuance_amount_len,
1316         inflation_keys, inflation_keys_len,
1317         issuance_amount_rangeproof, issuance_amount_rangeproof_len,
1318         inflation_keys_rangeproof, inflation_keys_rangeproof_len,
1319         pegin_witness, flags, true);
1320 }
1321 
1322 int wally_tx_add_elements_raw_input_at(
1323     struct wally_tx *tx, uint32_t index,
1324     const unsigned char *txhash, size_t txhash_len,
1325     uint32_t utxo_index, uint32_t sequence,
1326     const unsigned char *script, size_t script_len,
1327     const struct wally_tx_witness_stack *witness,
1328     const unsigned char *nonce, size_t nonce_len,
1329     const unsigned char *entropy, size_t entropy_len,
1330     const unsigned char *issuance_amount, size_t issuance_amount_len,
1331     const unsigned char *inflation_keys, size_t inflation_keys_len,
1332     const unsigned char *issuance_amount_rangeproof, size_t issuance_amount_rangeproof_len,
1333     const unsigned char *inflation_keys_rangeproof, size_t inflation_keys_rangeproof_len,
1334     const struct wally_tx_witness_stack *pegin_witness, uint32_t flags)
1335 {
1336     return tx_add_elements_raw_input_at(
1337         tx, index, txhash, txhash_len,
1338         utxo_index, sequence, script,
1339         script_len, witness,
1340         nonce, nonce_len, entropy, entropy_len,
1341         issuance_amount, issuance_amount_len,
1342         inflation_keys, inflation_keys_len,
1343         issuance_amount_rangeproof, issuance_amount_rangeproof_len,
1344         inflation_keys_rangeproof, inflation_keys_rangeproof_len,
1345         pegin_witness, flags, true);
1346 }
1347 
1348 
1349 int wally_tx_add_raw_input(struct wally_tx *tx,
1350                            const unsigned char *txhash, size_t txhash_len,
1351                            uint32_t utxo_index, uint32_t sequence,
1352                            const unsigned char *script, size_t script_len,
1353                            const struct wally_tx_witness_stack *witness,
1354                            uint32_t flags)
1355 {
1356     if (!tx)
1357         return WALLY_EINVAL;
1358     return tx_add_elements_raw_input_at(tx, tx->num_inputs, txhash, txhash_len,
1359                                         utxo_index, sequence, script,
1360                                         script_len, witness,
1361                                         NULL, 0, NULL, 0, NULL, 0, NULL, 0,
1362                                         NULL, 0, NULL, 0, NULL, flags, false);
1363 }
1364 
1365 int wally_tx_add_raw_input_at(struct wally_tx *tx, uint32_t index,
1366                               const unsigned char *txhash, size_t txhash_len,
1367                               uint32_t utxo_index, uint32_t sequence,
1368                               const unsigned char *script, size_t script_len,
1369                               const struct wally_tx_witness_stack *witness,
1370                               uint32_t flags)
1371 {
1372     return tx_add_elements_raw_input_at(tx, index, txhash, txhash_len,
1373                                         utxo_index, sequence, script,
1374                                         script_len, witness,
1375                                         NULL, 0, NULL, 0, NULL, 0, NULL, 0,
1376                                         NULL, 0, NULL, 0, NULL, flags, false);
1377 }
1378 
1379 int wally_tx_remove_input(struct wally_tx *tx, size_t index)
1380 {
1381     struct wally_tx_input *input;
1382 
1383     if (!is_valid_tx(tx) || index >= tx->num_inputs)
1384         return WALLY_EINVAL;
1385 
1386     input = tx->inputs + index;
1387     tx_input_free(input, false);
1388     if (index != tx->num_inputs - 1)
1389         memmove(input, input + 1,
1390                 (tx->num_inputs - index - 1) * sizeof(*input));
1391     wally_clear(tx->inputs + tx->num_inputs - 1, sizeof(*input));
1392 
1393     tx->num_inputs -= 1;
1394     return WALLY_OK;
1395 }
1396 
1397 int wally_tx_add_output_at(struct wally_tx *tx, uint32_t index,
1398                            const struct wally_tx_output *output)
1399 {
1400     uint64_t total;
1401     int ret;
1402     const bool is_elements = output->features & WALLY_TX_IS_ELEMENTS;
1403 
1404     if (!is_valid_tx(tx) || index > tx->num_outputs)
1405         return WALLY_EINVAL;
1406 
1407     if (!is_elements) {
1408         if (!is_valid_tx_output(output) ||
1409             wally_tx_get_total_output_satoshi(tx, &total) != WALLY_OK ||
1410             total + output->satoshi < total || total + output->satoshi > WALLY_SATOSHI_MAX)
1411             return WALLY_EINVAL;
1412     } else if (!is_valid_elements_tx_output(output))
1413         return WALLY_EINVAL;
1414 
1415     if (tx->num_outputs >= tx->outputs_allocation_len) {
1416         /* Expand the outputs array */
1417         struct wally_tx_output *p;
1418         p = realloc_array(tx->outputs, tx->outputs_allocation_len,
1419                           tx->num_outputs + 1, sizeof(*tx->outputs));
1420         if (!p)
1421             return WALLY_ENOMEM;
1422 
1423         clear_and_free(tx->outputs, tx->num_outputs * sizeof(*tx->outputs));
1424         tx->outputs = p;
1425         tx->outputs_allocation_len += 1;
1426     }
1427 
1428     memmove(tx->outputs + index + 1, tx->outputs + index,
1429             (tx->num_outputs - index) * sizeof(*output));
1430 
1431     if ((ret = wally_tx_output_clone(output, tx->outputs + index)) != WALLY_OK) {
1432         memmove(tx->outputs + index, tx->outputs + index + 1,
1433                 (tx->num_outputs - index) * sizeof(*output)); /* Undo */
1434         return ret;
1435     }
1436 
1437     tx->num_outputs += 1;
1438     return WALLY_OK;
1439 }
1440 
1441 int wally_tx_add_output(struct wally_tx *tx, const struct wally_tx_output *output)
1442 {
1443     return tx ? wally_tx_add_output_at(tx, tx->num_outputs, output) : WALLY_EINVAL;
1444 }
1445 
1446 static int tx_add_elements_raw_output_at(
1447     struct wally_tx *tx, uint32_t index, uint64_t satoshi,
1448     const unsigned char *script, size_t script_len,
1449     const unsigned char *asset, size_t asset_len,
1450     const unsigned char *value, size_t value_len,
1451     const unsigned char *nonce, size_t nonce_len,
1452     const unsigned char *surjectionproof, size_t surjectionproof_len,
1453     const unsigned char *rangeproof, size_t rangeproof_len,
1454     uint32_t flags, bool is_elements)
1455 {
1456     /* Add an output without allocating a temporary wally_tx_output */
1457     struct wally_tx_output output = {
1458         satoshi, (unsigned char *)script, script_len,
1459         is_elements ? WALLY_TX_IS_ELEMENTS : 0,
1460 #ifdef BUILD_ELEMENTS
1461         (unsigned char *)asset, asset_len, (unsigned char *)value, value_len,
1462         (unsigned char *)nonce, nonce_len, (unsigned char *)surjectionproof, surjectionproof_len,
1463         (unsigned char *)rangeproof, rangeproof_len,
1464 #endif /* BUILD_ELEMENTS */
1465     };
1466     int ret;
1467 
1468     if (flags)
1469         return WALLY_EINVAL;
1470 
1471     if (BYTES_INVALID_N(asset, asset_len, WALLY_TX_ASSET_CT_ASSET_LEN) ||
1472         ((value != NULL) != (value_len == WALLY_TX_ASSET_CT_VALUE_LEN ||
1473                              value_len == WALLY_TX_ASSET_CT_VALUE_UNBLIND_LEN)) ||
1474         BYTES_INVALID_N(nonce, nonce_len, WALLY_TX_ASSET_CT_NONCE_LEN) ||
1475         BYTES_INVALID(surjectionproof, surjectionproof_len) ||
1476         BYTES_INVALID(rangeproof, rangeproof_len))
1477         return WALLY_EINVAL;
1478 
1479     ret = wally_tx_add_output_at(tx, index, &output);
1480     wally_clear(&output, sizeof(output));
1481     return ret;
1482 }
1483 
1484 int wally_tx_add_elements_raw_output(
1485     struct wally_tx *tx,
1486     const unsigned char *script, size_t script_len,
1487     const unsigned char *asset, size_t asset_len,
1488     const unsigned char *value, size_t value_len,
1489     const unsigned char *nonce, size_t nonce_len,
1490     const unsigned char *surjectionproof, size_t surjectionproof_len,
1491     const unsigned char *rangeproof, size_t rangeproof_len,
1492     uint32_t flags)
1493 {
1494     if (!tx)
1495         return WALLY_EINVAL;
1496     return tx_add_elements_raw_output_at(tx, tx->num_outputs, -1,
1497                                          script, script_len,
1498                                          asset, asset_len,
1499                                          value, value_len,
1500                                          nonce, nonce_len,
1501                                          surjectionproof, surjectionproof_len,
1502                                          rangeproof, rangeproof_len,
1503                                          flags, true);
1504 }
1505 
1506 int wally_tx_add_elements_raw_output_at(
1507     struct wally_tx *tx, uint32_t index,
1508     const unsigned char *script, size_t script_len,
1509     const unsigned char *asset, size_t asset_len,
1510     const unsigned char *value, size_t value_len,
1511     const unsigned char *nonce, size_t nonce_len,
1512     const unsigned char *surjectionproof, size_t surjectionproof_len,
1513     const unsigned char *rangeproof, size_t rangeproof_len,
1514     uint32_t flags)
1515 {
1516     return tx_add_elements_raw_output_at(tx, index, -1,
1517                                          script, script_len,
1518                                          asset, asset_len,
1519                                          value, value_len,
1520                                          nonce, nonce_len,
1521                                          surjectionproof, surjectionproof_len,
1522                                          rangeproof, rangeproof_len,
1523                                          flags, true);
1524 }
1525 
1526 int wally_tx_add_raw_output(struct wally_tx *tx, uint64_t satoshi,
1527                             const unsigned char *script, size_t script_len,
1528                             uint32_t flags)
1529 {
1530     if (!tx)
1531         return WALLY_EINVAL;
1532     return tx_add_elements_raw_output_at(tx, tx->num_outputs, satoshi,
1533                                          script, script_len,
1534                                          NULL, 0, NULL, 0, NULL, 0,
1535                                          NULL, 0, NULL, 0, flags, false);
1536 }
1537 
1538 int wally_tx_add_raw_output_at(struct wally_tx *tx, uint32_t index,
1539                                uint64_t satoshi,
1540                                const unsigned char *script, size_t script_len,
1541                                uint32_t flags)
1542 {
1543     return tx_add_elements_raw_output_at(tx, index, satoshi,
1544                                          script, script_len,
1545                                          NULL, 0, NULL, 0, NULL, 0,
1546                                          NULL, 0, NULL, 0, flags, false);
1547 }
1548 
1549 int wally_tx_remove_output(struct wally_tx *tx, size_t index)
1550 {
1551     struct wally_tx_output *output;
1552 
1553     if (!is_valid_tx(tx) || index >= tx->num_outputs)
1554         return WALLY_EINVAL;
1555 
1556     output = tx->outputs + index;
1557     tx_output_free(output, false);
1558     if (index != tx->num_outputs - 1)
1559         memmove(output, output + 1,
1560                 (tx->num_outputs - index - 1) * sizeof(*output));
1561     wally_clear(tx->outputs + tx->num_outputs - 1, sizeof(*output));
1562 
1563     tx->num_outputs -= 1;
1564     return WALLY_OK;
1565 }
1566 
1567 int wally_tx_get_witness_count(const struct wally_tx *tx, size_t *written)
1568 {
1569     size_t i;
1570 
1571     if (written)
1572         *written = 0;
1573 
1574     if (!is_valid_tx(tx) || !written)
1575         return WALLY_EINVAL;
1576 
1577     for (i = 0; i < tx->num_inputs; ++i) {
1578         if (tx->inputs[i].witness)
1579             *written += 1;
1580 #ifdef BUILD_ELEMENTS
1581         /* TODO: check the count in the presence of a mix of NULL and non-NULL witnesses */
1582         if (tx->inputs[i].issuance_amount_rangeproof_len)
1583             *written += 1;
1584         if (tx->inputs[i].inflation_keys_rangeproof_len)
1585             *written += 1;
1586         if (tx->inputs[i].pegin_witness)
1587             *written += 1;
1588 #endif
1589     }
1590 
1591 #ifdef BUILD_ELEMENTS
1592     /* TODO: check the count in the presence of a mix of NULL and non-NULL witnesses */
1593     for (i = 0; i < tx->num_outputs; ++i) {
1594         if (tx->outputs[i].surjectionproof_len)
1595             *written += 1;
1596         if (tx->outputs[i].rangeproof_len)
1597             *written += 1;
1598     }
1599 #endif
1600 
1601     return WALLY_OK;
1602 }
1603 
1604 /* We compute the size of the witness separately so we can compute vsize
1605  * without iterating the transaction twice with different flags.
1606  */
1607 static int tx_get_lengths(const struct wally_tx *tx,
1608                           const struct tx_serialize_opts *opts, uint32_t flags,
1609                           size_t *base_size, size_t *witness_size,
1610                           size_t *witness_count, bool is_elements)
1611 {
1612     size_t n, i, j;
1613     const bool anyonecanpay = opts && opts->sighash & WALLY_SIGHASH_ANYONECANPAY;
1614     const bool sh_rangeproof = opts && opts->sighash & WALLY_SIGHASH_RANGEPROOF;
1615     const bool sh_none = opts && (opts->sighash & SIGHASH_MASK) == WALLY_SIGHASH_NONE;
1616     const bool sh_single = opts && (opts->sighash & SIGHASH_MASK) == WALLY_SIGHASH_SINGLE;
1617 
1618     *witness_count = 0;
1619 
1620     if (!is_valid_tx(tx))
1621         return WALLY_EINVAL;
1622 
1623     if (opts) {
1624         if (flags & WALLY_TX_FLAG_USE_WITNESS)
1625             return WALLY_ERROR; /* Segwit tx hashing uses bip143 opts member */
1626 
1627         if (opts->bip143) {
1628             *base_size = sizeof(uint32_t) + /* version */
1629                          SHA256_LEN + /* hash prevouts */
1630                          SHA256_LEN + /* hash sequence */
1631                          WALLY_TXHASH_LEN + sizeof(uint32_t) + /* outpoint + index */
1632                          varbuff_get_length(opts->script_len) + /* script */
1633                          (is_elements ? confidential_value_length_from_bytes(opts->value) + SHA256_LEN :
1634                           sizeof(uint64_t)) + /* amount */
1635                          sizeof(uint32_t) + /* input sequence */
1636                          SHA256_LEN + /* hash outputs */
1637                          ((is_elements && sh_rangeproof) ? SHA256_LEN : 0) + /* rangeproof */
1638                          sizeof(uint32_t) + /* nlocktime */
1639                          sizeof(uint32_t); /* tx sighash */
1640 #ifdef BUILD_ELEMENTS
1641             if (tx->inputs[opts->index].features & WALLY_TX_IS_ISSUANCE)
1642                 *base_size += 2 * WALLY_TX_ASSET_TAG_LEN +
1643                               confidential_value_length_from_bytes(tx->inputs[opts->index].issuance_amount) +
1644                               confidential_value_length_from_bytes(tx->inputs[opts->index].inflation_keys);
1645 #endif
1646             *witness_size = 0;
1647             return WALLY_OK;
1648         }
1649     }
1650 
1651     if ((flags & ~WALLY_TX_ALL_FLAGS) ||
1652         ((flags & WALLY_TX_FLAG_USE_WITNESS) &&
1653          wally_tx_get_witness_count(tx, witness_count) != WALLY_OK))
1654         return WALLY_EINVAL;
1655 
1656     if (!*witness_count)
1657         flags &= ~WALLY_TX_FLAG_USE_WITNESS;
1658 
1659     n = sizeof(tx->version) +
1660         varint_get_length(anyonecanpay ? 1 : tx->num_inputs) +
1661         (sh_none ? 1 : varint_get_length(sh_single ? opts->index + 1 : tx->num_outputs)) +
1662         sizeof(tx->locktime) +
1663         (opts ? sizeof(leint32_t) : 0); /* Include trailing tx_sighash */
1664 
1665     if (!opts && is_elements)
1666         n += sizeof(uint8_t); /* witness flag */
1667     for (i = 0; i < tx->num_inputs; ++i) {
1668         const struct wally_tx_input *input = tx->inputs + i;
1669         if (anyonecanpay && i != opts->index)
1670             continue; /* anyonecanpay only signs the given index */
1671 
1672         n += sizeof(input->txhash) +
1673              sizeof(input->index) +
1674              sizeof(input->sequence);
1675 
1676 #ifdef BUILD_ELEMENTS
1677         if (input->features & WALLY_TX_IS_ISSUANCE) {
1678             n += sizeof(input->blinding_nonce) +
1679                  sizeof(input->entropy) +
1680                  confidential_value_length_from_bytes(input->issuance_amount) +
1681                  confidential_value_length_from_bytes(input->inflation_keys);
1682         }
1683 #endif
1684 
1685         if (opts) {
1686             if (i == opts->index)
1687                 n += varbuff_get_length(opts->script_len);
1688             else
1689                 ++n;
1690         } else
1691             n += varbuff_get_length(input->script_len);
1692 
1693     }
1694 
1695     if (!sh_none) {
1696         size_t num_outputs = sh_single ? opts->index + 1 : tx->num_outputs;
1697 
1698         for (i = 0; i < num_outputs; ++i) {
1699             const struct wally_tx_output *output = tx->outputs + i;
1700             if (sh_single && i != opts->index)
1701                 n += sizeof(EMPTY_OUTPUT);
1702             else {
1703                 if (is_elements && (output->features & WALLY_TX_IS_ELEMENTS)) {
1704 #ifdef BUILD_ELEMENTS
1705                     n += confidential_asset_length_from_bytes(output->asset) +
1706                          confidential_value_length_from_bytes(output->value) +
1707                          confidential_nonce_length_from_bytes(output->nonce);
1708 #endif
1709                 } else
1710                     n += sizeof(output->satoshi);
1711                 n += varbuff_get_length(output->script_len);
1712 
1713 #ifdef BUILD_ELEMENTS
1714                 if (is_elements && sh_rangeproof) {
1715                     n += varbuff_get_length(output->rangeproof_len) +
1716                          varbuff_get_length(output->surjectionproof_len);
1717                 }
1718 #endif /* BUILD_ELEMENTS */
1719             }
1720         }
1721     }
1722 
1723     *base_size = n;
1724 
1725     n = 0;
1726     if (flags & WALLY_TX_FLAG_USE_WITNESS) {
1727         if (is_elements) {
1728 #ifdef BUILD_ELEMENTS
1729             for (i = 0; i < tx->num_inputs; ++i) {
1730                 const struct wally_tx_input *input = tx->inputs + i;
1731                 size_t num_items;
1732                 n += varbuff_get_length(input->issuance_amount_rangeproof_len);
1733                 n += varbuff_get_length(input->inflation_keys_rangeproof_len);
1734                 num_items = input->witness ? input->witness->num_items : 0;
1735                 n += varint_get_length(num_items);
1736                 for (j = 0; j < num_items; ++j) {
1737                     const struct wally_tx_witness_item *stack;
1738                     stack = input->witness->items + j;
1739                     n += varbuff_get_length(stack->witness_len);
1740                 }
1741                 num_items = input->pegin_witness ? input->pegin_witness->num_items : 0;
1742                 n += varint_get_length(num_items);
1743                 for (j = 0; j < num_items; ++j) {
1744                     const struct wally_tx_witness_item *stack;
1745                     stack = input->pegin_witness->items + j;
1746                     n += varbuff_get_length(stack->witness_len);
1747                 }
1748             }
1749 
1750             for (i = 0; i < tx->num_outputs; ++i) {
1751                 const struct wally_tx_output *output = tx->outputs + i;
1752                 n += varbuff_get_length(output->surjectionproof_len);
1753                 n += varbuff_get_length(output->rangeproof_len);
1754             }
1755 #endif /* BUILD_ELEMENTS */
1756         } else {
1757             n = 2; /* For marker and flag bytes 0x00 0x01 */
1758 
1759             for (i = 0; i < tx->num_inputs; ++i) {
1760                 const struct wally_tx_input *input = tx->inputs + i;
1761                 size_t num_items = input->witness ? input->witness->num_items : 0;
1762                 n += varint_get_length(num_items);
1763                 for (j = 0; j < num_items; ++j) {
1764                     const struct wally_tx_witness_item *stack;
1765                     stack = input->witness->items + j;
1766                     n += varbuff_get_length(stack->witness_len);
1767                 }
1768             }
1769         }
1770     }
1771 
1772     *witness_size = n;
1773     return WALLY_OK;
1774 }
1775 
1776 static int tx_get_length(const struct wally_tx *tx,
1777                          const struct tx_serialize_opts *opts, uint32_t flags,
1778                          size_t *written, bool is_elements)
1779 {
1780     size_t base_size, witness_size, witness_count;
1781 
1782     if (written)
1783         *written = 0;
1784 
1785     if (!written ||
1786         tx_get_lengths(tx, opts, flags, &base_size, &witness_size,
1787                        &witness_count, is_elements) != WALLY_OK)
1788         return WALLY_EINVAL;
1789 
1790     if (witness_count && (flags & WALLY_TX_FLAG_USE_WITNESS))
1791         *written = base_size + witness_size;
1792     else
1793         *written = base_size;
1794 
1795     return WALLY_OK;
1796 }
1797 
1798 int wally_tx_get_length(const struct wally_tx *tx, uint32_t flags,
1799                         size_t *written)
1800 {
1801     size_t is_elements = 0;
1802 #ifdef BUILD_ELEMENTS
1803     if (wally_tx_is_elements(tx, &is_elements) != WALLY_OK)
1804         return WALLY_EINVAL;
1805 #endif
1806 
1807     return tx_get_length(tx, NULL, flags, written, is_elements != 0);
1808 }
1809 
1810 int wally_tx_get_weight(const struct wally_tx *tx, size_t *written)
1811 {
1812     size_t base_size, witness_size, witness_count;
1813     size_t is_elements = 0;
1814 
1815     if (written)
1816         *written = 0;
1817 
1818 #ifdef BUILD_ELEMENTS
1819     if (wally_tx_is_elements(tx, &is_elements) != WALLY_OK)
1820         return WALLY_EINVAL;
1821 #endif
1822 
1823     if (!written ||
1824         tx_get_lengths(tx, NULL, WALLY_TX_FLAG_USE_WITNESS, &base_size,
1825                        &witness_size, &witness_count, is_elements != 0) != WALLY_OK)
1826         return WALLY_EINVAL;
1827 
1828     if (witness_count)
1829         *written = base_size * 4 + witness_size;
1830     else
1831         *written = base_size * 4;
1832 
1833     return WALLY_OK;
1834 }
1835 
1836 int wally_tx_vsize_from_weight(size_t weight, size_t *written)
1837 {
1838     *written = (weight + 3) / 4; /* ceil(weight/4) */
1839     return WALLY_OK;
1840 }
1841 
1842 int wally_tx_get_vsize(const struct wally_tx *tx, size_t *written)
1843 {
1844     int ret = wally_tx_get_weight(tx, written);
1845     if (ret == WALLY_OK)
1846         ret = wally_tx_vsize_from_weight(*written, written);
1847     return ret;
1848 }
1849 
1850 static inline int tx_to_bip143_bytes(const struct wally_tx *tx,
1851                                      const struct tx_serialize_opts *opts,
1852                                      uint32_t flags,
1853                                      unsigned char *bytes_out, size_t len,
1854                                      size_t *written)
1855 {
1856     unsigned char buff[TX_STACK_SIZE / 2], *buff_p = buff;
1857     size_t i, inputs_size, outputs_size, rangeproof_size = 0, issuances_size = 0, buff_len = sizeof(buff);
1858     size_t is_elements = 0;
1859     const bool anyonecanpay = opts->sighash & WALLY_SIGHASH_ANYONECANPAY;
1860 #ifdef BUILD_ELEMENTS
1861     const bool sh_rangeproof = opts->sighash & WALLY_SIGHASH_RANGEPROOF;
1862 #endif
1863     const bool sh_none = (opts->sighash & SIGHASH_MASK) == WALLY_SIGHASH_NONE;
1864     const bool sh_single = (opts->sighash & SIGHASH_MASK) == WALLY_SIGHASH_SINGLE;
1865     unsigned char *p = bytes_out, *output_p;
1866     int ret = WALLY_OK;
1867 
1868     (void)flags;
1869     (void)len;
1870 
1871 #ifdef BUILD_ELEMENTS
1872     if ((ret = wally_tx_is_elements(tx, &is_elements)) != WALLY_OK)
1873         return ret;
1874 #endif
1875 
1876     /* Note we assume tx_to_bytes has already validated all inputs */
1877     p += uint32_to_le_bytes(tx->version, p);
1878 
1879     inputs_size = tx->num_inputs * (WALLY_TXHASH_LEN + sizeof(uint32_t));
1880     if (sh_none || (sh_single && opts->index >= tx->num_outputs))
1881         outputs_size = 0;
1882     else if (sh_single) {
1883         if (!is_elements)
1884             outputs_size = sizeof(uint64_t) +
1885                            varbuff_get_length(tx->outputs[opts->index].script_len);
1886 #ifdef BUILD_ELEMENTS
1887         else {
1888             outputs_size = confidential_asset_length_from_bytes(tx->outputs[opts->index].asset) +
1889                            confidential_value_length_from_bytes(tx->outputs[opts->index].value) +
1890                            confidential_nonce_length_from_bytes(tx->outputs[opts->index].nonce) +
1891                            varbuff_get_length(tx->outputs[opts->index].script_len);
1892 
1893             if (sh_rangeproof) {
1894                 rangeproof_size = varbuff_get_length(tx->outputs[opts->index].rangeproof_len) +
1895                                   varbuff_get_length(tx->outputs[opts->index].surjectionproof_len);
1896             }
1897         }
1898 #else
1899         else
1900             return WALLY_EINVAL;
1901 #endif
1902     } else {
1903         outputs_size = 0;
1904         for (i = 0; i < tx->num_outputs; ++i) {
1905             if (!is_elements)
1906                 outputs_size += sizeof(uint64_t);
1907 #ifdef BUILD_ELEMENTS
1908             else {
1909                 outputs_size += confidential_asset_length_from_bytes(tx->outputs[i].asset) +
1910                                 confidential_value_length_from_bytes(tx->outputs[i].value) +
1911                                 confidential_nonce_length_from_bytes(tx->outputs[i].nonce);
1912 
1913                 if (sh_rangeproof) {
1914                     rangeproof_size += varbuff_get_length(tx->outputs[i].rangeproof_len) +
1915                                        varbuff_get_length(tx->outputs[i].surjectionproof_len);
1916                 }
1917             }
1918 #else
1919             else
1920                 return WALLY_EINVAL;
1921 #endif
1922             outputs_size += varbuff_get_length(tx->outputs[i].script_len);
1923         }
1924     }
1925 
1926 #ifdef BUILD_ELEMENTS
1927     if (is_elements && !anyonecanpay) {
1928         for (i = 0; i < tx->num_inputs; ++i) {
1929             if (tx->inputs[i].features & WALLY_TX_IS_ISSUANCE)
1930                 issuances_size +=
1931                     2 * WALLY_TX_ASSET_TAG_LEN +
1932                     confidential_value_length_from_bytes(tx->inputs[i].issuance_amount) +
1933                     confidential_value_length_from_bytes(tx->inputs[i].inflation_keys);
1934             else
1935                 issuances_size += 1;
1936         }
1937     }
1938 #endif
1939 
1940     if (inputs_size > buff_len || outputs_size > buff_len ||
1941         rangeproof_size > buff_len || issuances_size > buff_len) {
1942         buff_len = inputs_size > outputs_size ? inputs_size : outputs_size;
1943         buff_len = buff_len > rangeproof_size ? buff_len : rangeproof_size;
1944         buff_len = buff_len > issuances_size ? buff_len : issuances_size;
1945         buff_p = wally_malloc(buff_len);
1946         if (buff_p == NULL)
1947             return WALLY_ENOMEM;
1948     }
1949 
1950     /* Inputs */
1951     if (anyonecanpay)
1952         memset(p, 0, SHA256_LEN);
1953     else {
1954         for (i = 0; i < tx->num_inputs; ++i) {
1955             unsigned char *tmp_p = buff_p + i * (WALLY_TXHASH_LEN + sizeof(uint32_t));
1956             memcpy(tmp_p, tx->inputs[i].txhash, WALLY_TXHASH_LEN);
1957             uint32_to_le_bytes(tx->inputs[i].index, tmp_p + WALLY_TXHASH_LEN);
1958         }
1959 
1960         if ((ret = wally_sha256d(buff_p, inputs_size, p, SHA256_LEN)) != WALLY_OK)
1961             goto error;
1962     }
1963     p += SHA256_LEN;
1964 
1965     /* Sequences */
1966     if (anyonecanpay || sh_single || sh_none)
1967         memset(p, 0, SHA256_LEN);
1968     else {
1969         for (i = 0; i < tx->num_inputs; ++i)
1970             uint32_to_le_bytes(tx->inputs[i].sequence, buff_p + i * sizeof(uint32_t));
1971 
1972         ret = wally_sha256d(buff_p, tx->num_inputs * sizeof(uint32_t), p, SHA256_LEN);
1973         if (ret != WALLY_OK)
1974             goto error;
1975     }
1976     p += SHA256_LEN;
1977 
1978 #ifdef BUILD_ELEMENTS
1979     if (is_elements) {
1980         /* Issuance */
1981         if (anyonecanpay)
1982             memset(p, 0, SHA256_LEN);
1983         else {
1984             unsigned char *tmp_p = buff_p;
1985             for (i = 0; i < tx->num_inputs; ++i) {
1986                 if (tx->inputs[i].features & WALLY_TX_IS_ISSUANCE) {
1987                     memcpy(tmp_p, tx->inputs[i].blinding_nonce, WALLY_TX_ASSET_TAG_LEN);
1988                     tmp_p += WALLY_TX_ASSET_TAG_LEN;
1989                     memcpy(tmp_p, tx->inputs[i].entropy, WALLY_TX_ASSET_TAG_LEN);
1990                     tmp_p += WALLY_TX_ASSET_TAG_LEN;
1991                     tmp_p += confidential_value_to_bytes(tx->inputs[i].issuance_amount,
1992                                                          tx->inputs[i].issuance_amount_len, tmp_p);
1993                     tmp_p += confidential_value_to_bytes(tx->inputs[i].inflation_keys,
1994                                                          tx->inputs[i].inflation_keys_len, tmp_p);
1995                 }
1996                 else
1997                     *tmp_p++ = 0;
1998             }
1999 
2000             if ((ret = wally_sha256d(buff_p, issuances_size, p, SHA256_LEN)) != WALLY_OK)
2001                 goto error;
2002         }
2003         p += SHA256_LEN;
2004     }
2005 #endif /* BUILD_ELEMENTS */
2006 
2007     /* Input details */
2008     memcpy(p, tx->inputs[opts->index].txhash, WALLY_TXHASH_LEN);
2009     p += WALLY_TXHASH_LEN;
2010     p += uint32_to_le_bytes(tx->inputs[opts->index].index, p);
2011     p += varbuff_to_bytes(opts->script, opts->script_len, p);
2012     if (!is_elements)
2013         p += uint64_to_le_bytes(opts->satoshi, p);
2014 #ifdef BUILD_ELEMENTS
2015     else
2016         p += confidential_value_to_bytes(opts->value, opts->value_len, p);
2017 #endif
2018     p += uint32_to_le_bytes(tx->inputs[opts->index].sequence, p);
2019 
2020 #ifdef BUILD_ELEMENTS
2021     if (is_elements && (tx->inputs[opts->index].features & WALLY_TX_IS_ISSUANCE)) {
2022         memcpy(p, tx->inputs[opts->index].blinding_nonce, WALLY_TX_ASSET_TAG_LEN);
2023         p += WALLY_TX_ASSET_TAG_LEN;
2024         memcpy(p, tx->inputs[opts->index].entropy, WALLY_TX_ASSET_TAG_LEN);
2025         p += WALLY_TX_ASSET_TAG_LEN;
2026         p += confidential_value_to_bytes(tx->inputs[opts->index].issuance_amount,
2027                                          tx->inputs[opts->index].issuance_amount_len, p);
2028         p += confidential_value_to_bytes(tx->inputs[opts->index].inflation_keys,
2029                                          tx->inputs[opts->index].inflation_keys_len, p);
2030     }
2031 #endif
2032 
2033     /* Outputs */
2034     if (sh_none || (sh_single && opts->index >= tx->num_outputs))
2035         memset(p, 0, SHA256_LEN);
2036     else {
2037         output_p = buff_p;
2038         for (i = 0; i < tx->num_outputs; ++i) {
2039             if (sh_single && i != opts->index)
2040                 continue;
2041             if (!is_elements)
2042                 output_p += uint64_to_le_bytes(tx->outputs[i].satoshi, output_p);
2043 #ifdef BUILD_ELEMENTS
2044             else {
2045                 output_p += confidential_value_to_bytes(tx->outputs[i].asset, tx->outputs[i].asset_len,
2046                                                         output_p);
2047                 output_p += confidential_value_to_bytes(tx->outputs[i].value, tx->outputs[i].value_len,
2048                                                         output_p);
2049                 output_p += confidential_value_to_bytes(tx->outputs[i].nonce, tx->outputs[i].nonce_len,
2050                                                         output_p);
2051             }
2052 #endif
2053             output_p += varbuff_to_bytes(tx->outputs[i].script,
2054                                          tx->outputs[i].script_len, output_p);
2055         }
2056 
2057         ret = wally_sha256d(buff_p, outputs_size, p, SHA256_LEN);
2058         if (ret != WALLY_OK)
2059             goto error;
2060     }
2061     p += SHA256_LEN;
2062 
2063     /* rangeproof */
2064 #ifdef BUILD_ELEMENTS
2065     if (is_elements && sh_rangeproof) {
2066         if (sh_none || (sh_single && opts->index >= tx->num_outputs))
2067             memset(p, 0, SHA256_LEN);
2068         else {
2069             output_p = buff_p;
2070             for (i = 0; i < tx->num_outputs; ++i) {
2071                 if (sh_single && i != opts->index)
2072                     continue;
2073                 output_p += varbuff_to_bytes(tx->outputs[i].rangeproof,
2074                                              tx->outputs[i].rangeproof_len, output_p);
2075                 output_p += varbuff_to_bytes(tx->outputs[i].surjectionproof,
2076                                              tx->outputs[i].surjectionproof_len, output_p);
2077             }
2078             ret = wally_sha256d(buff_p, rangeproof_size, p, SHA256_LEN);
2079             if (ret != WALLY_OK)
2080                 goto error;
2081         }
2082         p += SHA256_LEN;
2083     }
2084 #endif
2085 
2086     /* nlocktime and sighash*/
2087     p += uint32_to_le_bytes(tx->locktime, p);
2088     p += uint32_to_le_bytes(opts->tx_sighash, p);
2089 
2090     *written = p - bytes_out;
2091 
2092 error:
2093     if (buff_p != buff)
2094         clear_and_free(buff_p, buff_len);
2095     else
2096         wally_clear(buff, sizeof(buff));
2097     return ret;
2098 }
2099 
2100 static int tx_to_bytes(const struct wally_tx *tx,
2101                        const struct tx_serialize_opts *opts,
2102                        uint32_t flags,
2103                        unsigned char *bytes_out, size_t len,
2104                        size_t *written,
2105                        bool is_elements)
2106 {
2107     size_t n, i, j, witness_count;
2108     const bool anyonecanpay = opts && opts->sighash & WALLY_SIGHASH_ANYONECANPAY;
2109 #ifdef BUILD_ELEMENTS
2110     const bool sh_rangeproof = opts && opts->sighash & WALLY_SIGHASH_RANGEPROOF;
2111 #endif
2112     const bool sh_none = opts && (opts->sighash & SIGHASH_MASK) == WALLY_SIGHASH_NONE;
2113     const bool sh_single = opts && (opts->sighash & SIGHASH_MASK) == WALLY_SIGHASH_SINGLE;
2114     unsigned char *p = bytes_out;
2115 
2116     if (written)
2117         *written = 0;
2118 
2119     if (!is_valid_tx(tx) ||
2120         (flags & ~WALLY_TX_ALL_FLAGS) || !bytes_out || !written ||
2121         tx_get_length(tx, opts, flags, &n, is_elements) != WALLY_OK)
2122         return WALLY_EINVAL;
2123 
2124     if (opts && (flags & WALLY_TX_FLAG_USE_WITNESS))
2125         return WALLY_ERROR; /* Segwit tx hashing is handled elsewhere */
2126 
2127     if (!(flags & WALLY_TX_FLAG_ALLOW_PARTIAL)) {
2128         /* 0-input/output txs can be only be written with this flag */
2129         if (!tx->num_inputs || !tx->num_outputs)
2130             return WALLY_EINVAL;
2131     }
2132 
2133     if (!tx->num_inputs) {
2134         /* 0-input txs can only be written in the pre-BIP144 format,
2135          * since otherwise the resulting tx is ambiguous.
2136          * Used in PSBTs while building the tx for example.
2137          */
2138         if (!(flags & WALLY_TX_FLAG_PRE_BIP144))
2139             return WALLY_EINVAL;
2140         flags &= ~WALLY_TX_FLAG_USE_WITNESS;
2141     }
2142 
2143     if (n > len) {
2144         *written = n;
2145         return WALLY_OK;
2146     }
2147 
2148     if (opts && opts->bip143)
2149         return tx_to_bip143_bytes(tx, opts, flags, bytes_out, len, written);
2150 
2151     if (flags & WALLY_TX_FLAG_USE_WITNESS) {
2152         if (wally_tx_get_witness_count(tx, &witness_count) != WALLY_OK)
2153             return WALLY_EINVAL;
2154         if (!witness_count)
2155             flags &= ~WALLY_TX_FLAG_USE_WITNESS;
2156     }
2157 
2158     p += uint32_to_le_bytes(tx->version, p);
2159     if (is_elements) {
2160         if (!opts)
2161             *p++ = flags & WALLY_TX_FLAG_USE_WITNESS ? 1 : 0;
2162     } else {
2163         if (flags & WALLY_TX_FLAG_USE_WITNESS) {
2164             *p++ = 0; /* Write BIP 144 marker */
2165             *p++ = 1; /* Write BIP 144 flag */
2166         }
2167     }
2168     if (anyonecanpay)
2169         *p++ = 1;
2170     else
2171         p += varint_to_bytes(tx->num_inputs, p);
2172 
2173     for (i = 0; i < tx->num_inputs; ++i) {
2174         const struct wally_tx_input *input = tx->inputs + i;
2175         if (anyonecanpay && i != opts->index)
2176             continue; /* anyonecanpay only signs the given index */
2177 
2178         memcpy(p, input->txhash, sizeof(input->txhash));
2179         p += sizeof(input->txhash);
2180         if (!opts && (input->features & WALLY_TX_IS_ISSUANCE))
2181             p += uint32_to_le_bytes(input->index | WALLY_TX_ISSUANCE_FLAG, p);
2182         else if (!opts && (input->features & WALLY_TX_IS_PEGIN))
2183             p += uint32_to_le_bytes(input->index | WALLY_TX_PEGIN_FLAG, p);
2184         else
2185             p += uint32_to_le_bytes(input->index, p);
2186         if (opts) {
2187             if (i == opts->index)
2188                 p += varbuff_to_bytes(opts->script, opts->script_len, p);
2189             else
2190                 *p++ = 0; /* Blank scripts for non-signing inputs */
2191         } else
2192             p += varbuff_to_bytes(input->script, input->script_len, p);
2193 
2194         if ((sh_none || sh_single) && i != opts->index)
2195             p += uint32_to_le_bytes(0, p);
2196         else
2197             p += uint32_to_le_bytes(input->sequence, p);
2198         if (input->features & WALLY_TX_IS_ISSUANCE) {
2199             if (!is_elements)
2200                 return WALLY_EINVAL;
2201 #ifdef BUILD_ELEMENTS
2202             memcpy(p, input->blinding_nonce, WALLY_TX_ASSET_TAG_LEN);
2203             p += WALLY_TX_ASSET_TAG_LEN;
2204             memcpy(p, input->entropy, WALLY_TX_ASSET_TAG_LEN);
2205             p += WALLY_TX_ASSET_TAG_LEN;
2206             p += confidential_value_to_bytes(input->issuance_amount, input->issuance_amount_len, p);
2207             p += confidential_value_to_bytes(input->inflation_keys, input->inflation_keys_len, p);
2208 #endif
2209         }
2210     }
2211 
2212     if (sh_none)
2213         *p++ = 0;
2214     else {
2215         size_t num_outputs = sh_single ? opts->index + 1 : tx->num_outputs;
2216         p += varint_to_bytes(num_outputs, p);
2217 
2218         for (i = 0; i < num_outputs; ++i) {
2219             const struct wally_tx_output *output = tx->outputs + i;
2220             if (sh_single && i != opts->index) {
2221                 memcpy(p, EMPTY_OUTPUT, sizeof(EMPTY_OUTPUT));
2222                 p += sizeof(EMPTY_OUTPUT);
2223             } else {
2224                 if (output->features & WALLY_TX_IS_ELEMENTS) {
2225                     if (!is_elements)
2226                         return WALLY_EINVAL;
2227 #ifdef BUILD_ELEMENTS
2228                     p += confidential_value_to_bytes(output->asset, output->asset_len, p);
2229                     p += confidential_value_to_bytes(output->value, output->value_len, p);
2230                     p += confidential_value_to_bytes(output->nonce, output->nonce_len, p);
2231 #endif
2232                 } else {
2233                     p += uint64_to_le_bytes(output->satoshi, p);
2234                 }
2235                 p += varbuff_to_bytes(output->script, output->script_len, p);
2236 
2237 #ifdef BUILD_ELEMENTS
2238                 if (is_elements && sh_rangeproof) {
2239                     p += varbuff_to_bytes(output->rangeproof,
2240                                           output->rangeproof_len, p);
2241                     p += varbuff_to_bytes(output->surjectionproof,
2242                                           output->surjectionproof_len, p);
2243                 }
2244 #endif
2245             }
2246         }
2247     }
2248 
2249     if (!is_elements && (flags & WALLY_TX_FLAG_USE_WITNESS)) {
2250         for (i = 0; i < tx->num_inputs; ++i) {
2251             const struct wally_tx_input *input = tx->inputs + i;
2252             size_t num_items = input->witness ? input->witness->num_items : 0;
2253             p += varint_to_bytes(num_items, p);
2254             for (j = 0; j < num_items; ++j) {
2255                 const struct wally_tx_witness_item *stack;
2256                 stack = input->witness->items + j;
2257                 p += varbuff_to_bytes(stack->witness, stack->witness_len, p);
2258             }
2259         }
2260     }
2261 
2262     p += uint32_to_le_bytes(tx->locktime, p);
2263     if (opts)
2264         uint32_to_le_bytes(opts->tx_sighash, p);
2265 
2266 #ifdef BUILD_ELEMENTS
2267     if (is_elements && (flags & WALLY_TX_FLAG_USE_WITNESS)) {
2268         for (i = 0; i < tx->num_inputs; ++i) {
2269             const struct wally_tx_input *input = tx->inputs + i;
2270             size_t num_items;
2271             p += varbuff_to_bytes(input->issuance_amount_rangeproof, input->issuance_amount_rangeproof_len, p);
2272             p += varbuff_to_bytes(input->inflation_keys_rangeproof, input->inflation_keys_rangeproof_len, p);
2273             num_items = input->witness ? input->witness->num_items : 0;
2274             p += varint_to_bytes(num_items, p);
2275             for (j = 0; j < num_items; ++j) {
2276                 const struct wally_tx_witness_item *stack;
2277                 stack = input->witness->items + j;
2278                 p += varbuff_to_bytes(stack->witness, stack->witness_len, p);
2279             }
2280             num_items = input->pegin_witness ? input->pegin_witness->num_items : 0;
2281             p += varint_to_bytes(num_items, p);
2282             for (j = 0; j < num_items; ++j) {
2283                 const struct wally_tx_witness_item *stack;
2284                 stack = input->pegin_witness->items + j;
2285                 p += varbuff_to_bytes(stack->witness, stack->witness_len, p);
2286             }
2287         }
2288         for (i = 0; i < tx->num_outputs; ++i) {
2289             const struct wally_tx_output *output = tx->outputs + i;
2290             p += varbuff_to_bytes(output->surjectionproof, output->surjectionproof_len, p);
2291             p += varbuff_to_bytes(output->rangeproof, output->rangeproof_len, p);
2292         }
2293     }
2294 #endif
2295     *written = n;
2296     return WALLY_OK;
2297 }
2298 
2299 int wally_tx_to_bytes(const struct wally_tx *tx, uint32_t flags,
2300                       unsigned char *bytes_out, size_t len,
2301                       size_t *written)
2302 {
2303     size_t is_elements = 0;
2304 
2305 #ifdef BUILD_ELEMENTS
2306     if (wally_tx_is_elements(tx, &is_elements) != WALLY_OK)
2307         return WALLY_EINVAL;
2308 #endif
2309     return tx_to_bytes(tx, NULL, flags, bytes_out, len, written, is_elements);
2310 }
2311 
2312 /* Common implementation for hex conversion and txid calculation */
2313 static int tx_to_hex_or_txid(const struct wally_tx *tx, uint32_t flags,
2314                              char **output,
2315                              unsigned char *bytes_out, size_t len,
2316                              bool is_elements)
2317 {
2318     unsigned char buff[TX_STACK_SIZE], *buff_p = buff;
2319     size_t n, written;
2320     int ret;
2321 
2322     if (output)
2323         *output = NULL;
2324 
2325     if ((output && (bytes_out || len)) ||
2326         (!output && (!bytes_out || len != WALLY_TXHASH_LEN)))
2327         return WALLY_EINVAL;
2328 
2329     ret = tx_to_bytes(tx, NULL, flags, buff_p, sizeof(buff), &n, is_elements);
2330     if (ret == WALLY_OK) {
2331         if (n > sizeof(buff)) {
2332             if ((buff_p = wally_malloc(n)) == NULL)
2333                 return WALLY_ENOMEM;
2334             ret = tx_to_bytes(tx, NULL, flags, buff_p, n, &written, is_elements);
2335             if (n != written)
2336                 ret = WALLY_ERROR; /* Length calculated incorrectly */
2337         }
2338         if (ret == WALLY_OK) {
2339             if (output)
2340                 ret = wally_hex_from_bytes(buff_p, n, output);
2341             else
2342                 ret = wally_sha256d(buff_p, n, bytes_out, len);
2343         }
2344         wally_clear(buff_p, n);
2345         if (buff_p != buff)
2346             wally_free(buff_p);
2347     }
2348     return ret;
2349 }
2350 
2351 int wally_tx_to_hex(const struct wally_tx *tx, uint32_t flags,
2352                     char **output)
2353 {
2354     size_t is_elements = 0;
2355 
2356 #ifdef BUILD_ELEMENTS
2357     if (wally_tx_is_elements(tx, &is_elements) != WALLY_OK)
2358         return WALLY_EINVAL;
2359 #endif
2360     return tx_to_hex_or_txid(tx, flags, output, NULL, 0, is_elements);
2361 }
2362 
2363 int wally_tx_get_txid(const struct wally_tx *tx, unsigned char *bytes_out, size_t len)
2364 {
2365     uint32_t flags = WALLY_TX_FLAG_ALLOW_PARTIAL;
2366     size_t is_elements = 0;
2367 
2368 #ifdef BUILD_ELEMENTS
2369     if (wally_tx_is_elements(tx, &is_elements) != WALLY_OK)
2370         return WALLY_EINVAL;
2371 #endif
2372     if (!is_elements)
2373         flags |= WALLY_TX_FLAG_PRE_BIP144;
2374     return tx_to_hex_or_txid(tx, flags, NULL, bytes_out, len, is_elements);
2375 }
2376 
2377 static int analyze_tx(const unsigned char *bytes, size_t bytes_len,
2378                       uint32_t flags, size_t *num_inputs, size_t *num_outputs,
2379                       bool *expect_witnesses)
2380 {
2381     const unsigned char *p = bytes, *end = bytes + bytes_len;
2382     uint64_t v, num_witnesses;
2383     size_t i, j;
2384     struct wally_tx tmp_tx;
2385     const bool is_elements = flags & WALLY_TX_FLAG_USE_ELEMENTS;
2386 
2387     if (num_inputs)
2388         *num_inputs = 0;
2389     if (num_outputs)
2390         *num_outputs = 0;
2391     if (expect_witnesses)
2392         *expect_witnesses = false;
2393 
2394     if (!bytes || bytes_len < sizeof(uint32_t) + 2 || (flags & ~WALLY_TX_ALL_FLAGS) ||
2395         !num_inputs || !num_outputs || !expect_witnesses)
2396         return WALLY_EINVAL;
2397 
2398     p += uint32_from_le_bytes(p, &tmp_tx.version);
2399 
2400     if (is_elements) {
2401         if (flags & WALLY_TX_FLAG_PRE_BIP144)
2402             return WALLY_EINVAL; /* No pre-BIP 144 serialisation for elements */
2403         *expect_witnesses = *p++ != 0;
2404     } else {
2405         if (!(flags & WALLY_TX_FLAG_PRE_BIP144) && *p == 0) {
2406             /* BIP 144 extended serialization */
2407             if (p[1] != 0x1)
2408                 return WALLY_EINVAL; /* Invalid witness flag */
2409             p += 2;
2410             *expect_witnesses = true;
2411         }
2412     }
2413 
2414 #define ensure_n(n) if (p > end || p + (n) > end) return WALLY_EINVAL
2415 
2416 #define ensure_varint(dst) ensure_n(varint_length_from_bytes(p)); \
2417     p += varint_from_bytes(p, (dst))
2418 
2419 #define ensure_varbuff(dst) ensure_varint((dst)); \
2420     ensure_n(*dst)
2421 
2422 #define ensure_commitment(dst, explicit_siz, prefix_a, prefix_b) \
2423     switch (*dst) { \
2424     case 0: \
2425         ensure_n(sizeof(uint8_t)); \
2426         p++; \
2427         break; \
2428     case 1: \
2429         ensure_n(explicit_siz); \
2430         p += explicit_siz; \
2431         break; \
2432     case prefix_a: \
2433     case prefix_b: \
2434         ensure_n(WALLY_TX_ASSET_CT_LEN); \
2435         p += WALLY_TX_ASSET_CT_LEN; \
2436         break; \
2437     default: \
2438         return WALLY_EINVAL; \
2439     }
2440 
2441 #define ensure_committed_value(dst) \
2442     ensure_commitment(dst, WALLY_TX_ASSET_CT_VALUE_UNBLIND_LEN, WALLY_TX_ASSET_CT_VALUE_PREFIX_A, WALLY_TX_ASSET_CT_VALUE_PREFIX_B)
2443 
2444 #define ensure_committed_asset(dst) \
2445     ensure_commitment(dst, WALLY_TX_ASSET_CT_ASSET_LEN, WALLY_TX_ASSET_CT_ASSET_PREFIX_A, WALLY_TX_ASSET_CT_ASSET_PREFIX_B)
2446 
2447 #define ensure_committed_nonce(dst) \
2448     ensure_commitment(dst, WALLY_TX_ASSET_CT_NONCE_LEN, WALLY_TX_ASSET_CT_NONCE_PREFIX_A, WALLY_TX_ASSET_CT_NONCE_PREFIX_B)
2449 
2450     ensure_varint(&v);
2451     *num_inputs = v;
2452 
2453     for (i = 0; i < *num_inputs; ++i) {
2454         bool expect_issuance;
2455         uint32_t utxo_index;
2456         ensure_n(WALLY_TXHASH_LEN + sizeof(uint32_t));
2457         uint32_from_le_bytes(p + WALLY_TXHASH_LEN, &utxo_index);
2458         expect_issuance = is_elements && (utxo_index & WALLY_TX_ISSUANCE_FLAG) && !is_coinbase_bytes(p, WALLY_TXHASH_LEN, utxo_index);
2459         p += WALLY_TXHASH_LEN + sizeof(uint32_t);
2460         ensure_varbuff(&v);
2461         /* FIXME: Analyze script types if required */
2462         p += v;
2463         ensure_n(sizeof(uint32_t));
2464         p += sizeof(uint32_t);
2465         if (expect_issuance) {
2466             ensure_n(2 * WALLY_TX_ASSET_TAG_LEN);
2467             p += 2 * WALLY_TX_ASSET_TAG_LEN;
2468             ensure_committed_value(p); /* issuance amount */
2469             ensure_committed_value(p); /* inflation keys */
2470         }
2471     }
2472 
2473     ensure_varint(&v);
2474     *num_outputs = v;
2475 
2476     for (i = 0; i < *num_outputs; ++i) {
2477         if (is_elements) {
2478             ensure_committed_asset(p);
2479             ensure_committed_value(p);
2480             ensure_committed_nonce(p);
2481         } else {
2482             ensure_n(sizeof(uint64_t));
2483             p += sizeof(uint64_t);
2484         }
2485         ensure_varbuff(&v);
2486         /* FIXME: Analyze script types if required */
2487         p += v;
2488     }
2489 
2490     if (*expect_witnesses && !is_elements) {
2491         for (i = 0; i < *num_inputs; ++i) {
2492             ensure_varint(&num_witnesses);
2493             for (j = 0; j < num_witnesses; ++j) {
2494                 ensure_varbuff(&v);
2495                 p += v;
2496             }
2497         }
2498     }
2499 
2500     ensure_n(sizeof(uint32_t)); /* Locktime */
2501 
2502     if (*expect_witnesses && is_elements) {
2503         p += sizeof(uint32_t);
2504         for (i = 0; i < *num_inputs; ++i) {
2505             ensure_varbuff(&v); /* issuance amount rangeproof */
2506             p += v;
2507             ensure_varbuff(&v); /* inflation keys rangeproof */
2508             p += v;
2509             ensure_varint(&num_witnesses); /* scriptWitness */
2510             for (j = 0; j < num_witnesses; ++j) {
2511                 ensure_varbuff(&v);
2512                 p += v;
2513             }
2514             ensure_varint(&num_witnesses); /* peginWitness */
2515             for (j = 0; j < num_witnesses; ++j) {
2516                 ensure_varbuff(&v);
2517                 p += v;
2518             }
2519         }
2520 
2521         for (i = 0; i < *num_outputs; ++i) {
2522             ensure_varbuff(&v); /* surjection proof */
2523             p += v;
2524             ensure_varbuff(&v); /* range proof */
2525             p += v;
2526         }
2527     }
2528 
2529 #undef ensure_n
2530 #undef ensure_varint
2531 #undef ensure_varbuff
2532 #undef ensure_commitment
2533 #undef ensure_committed_value
2534 #undef ensure_committed_asset
2535 #undef ensure_committed_nonce
2536     return WALLY_OK;
2537 }
2538 
2539 static int witness_stack_from_bytes(const unsigned char *bytes, struct wally_tx_witness_stack **witness, uint64_t *offset)
2540 {
2541     int ret = WALLY_OK;
2542     size_t i;
2543     uint64_t num_witnesses;
2544     const unsigned char *p = bytes;
2545     p += varint_from_bytes(p, &num_witnesses);
2546     if (num_witnesses) {
2547         ret = wally_tx_witness_stack_init_alloc(num_witnesses, witness);
2548         if (ret != WALLY_OK)
2549             goto cleanup;
2550 
2551         for (i = 0; i < num_witnesses; ++i) {
2552             uint64_t witness_len;
2553             p += varint_from_bytes(p, &witness_len);
2554             ret = wally_tx_witness_stack_set(*witness, i, p, witness_len);
2555             if (ret != WALLY_OK)
2556                 goto cleanup;
2557             p += witness_len;
2558         }
2559     }
2560 
2561     *offset = p - bytes;
2562 
2563 cleanup:
2564     return ret;
2565 }
2566 
2567 static int tx_from_bytes(const unsigned char *bytes, size_t bytes_len,
2568                          uint32_t flags, struct wally_tx **output)
2569 {
2570     const unsigned char *p = bytes;
2571     const bool is_elements = flags & WALLY_TX_FLAG_USE_ELEMENTS;
2572     bool expect_witnesses;
2573     size_t i, j, num_inputs, num_outputs;
2574     uint64_t tmp, num_witnesses;
2575     int ret;
2576     struct wally_tx *result;
2577 
2578     TX_CHECK_OUTPUT;
2579 
2580     if (analyze_tx(bytes, bytes_len, flags, &num_inputs, &num_outputs,
2581                    &expect_witnesses) != WALLY_OK)
2582         return WALLY_EINVAL;
2583 
2584     ret = wally_tx_init_alloc(0, 0, num_inputs, num_outputs, output);
2585     if (ret != WALLY_OK)
2586         return ret;
2587     result = (struct wally_tx *)*output;
2588 
2589     p += uint32_from_le_bytes(p, &result->version);
2590     if (is_elements)
2591         p++; /* Skip witness flag */
2592     else if (expect_witnesses)
2593         p += 2; /* Skip flag bytes */
2594     p += varint_from_bytes(p, &tmp);
2595 
2596     for (i = 0; i < num_inputs; ++i) {
2597         const unsigned char *txhash = p, *script, *nonce = NULL, *entropy = NULL;
2598         const unsigned char *issuance_amount = NULL, *inflation_keys = NULL;
2599         uint32_t index, sequence;
2600         uint64_t script_len, issuance_amount_len = 0, inflation_keys_len = 0;
2601         p += WALLY_TXHASH_LEN;
2602         p += uint32_from_le_bytes(p, &index);
2603         p += varint_from_bytes(p, &script_len);
2604         script = p;
2605         p += script_len;
2606         p += uint32_from_le_bytes(p, &sequence);
2607         if (is_elements && !!(index & WALLY_TX_ISSUANCE_FLAG) && !is_coinbase_bytes(txhash, WALLY_TXHASH_LEN, index)) {
2608             nonce = p;
2609             p += WALLY_TX_ASSET_TAG_LEN;
2610             entropy = p;
2611             p += WALLY_TX_ASSET_TAG_LEN;
2612             issuance_amount = p;
2613             p += confidential_value_varint_from_bytes(p, &issuance_amount_len);
2614             inflation_keys = p;
2615             p += confidential_value_varint_from_bytes(p, &inflation_keys_len);
2616         }
2617         ret = tx_elements_input_init(txhash, WALLY_TXHASH_LEN, index, sequence,
2618                                      script_len ? script : NULL, script_len, NULL,
2619                                      nonce, nonce ? WALLY_TX_ASSET_TAG_LEN : 0,
2620                                      entropy, entropy ? WALLY_TX_ASSET_TAG_LEN : 0,
2621                                      issuance_amount_len ? issuance_amount : NULL, issuance_amount_len,
2622                                      inflation_keys_len ? inflation_keys : NULL, inflation_keys_len,
2623                                      NULL, 0, NULL, 0, NULL, &result->inputs[i], is_elements);
2624         if (ret != WALLY_OK)
2625             goto fail;
2626         result->num_inputs += 1;
2627     }
2628 
2629     p += varint_from_bytes(p, &tmp);
2630     for (i = 0; i < num_outputs; ++i) {
2631         const unsigned char *script, *asset = NULL, *value = NULL, *nonce = NULL;
2632         uint64_t satoshi = -1, script_len, asset_len = 0, value_len = 0, nonce_len = 0;
2633         if (is_elements) {
2634             asset = p;
2635             p += confidential_asset_varint_from_bytes(p, &asset_len);
2636             value = p;
2637             p += confidential_value_varint_from_bytes(p, &value_len);
2638             nonce = p;
2639             p += confidential_nonce_varint_from_bytes(p, &nonce_len);
2640         } else
2641             p += uint64_from_le_bytes(p, &satoshi);
2642         p += varint_from_bytes(p, &script_len);
2643         script = p;
2644         p += script_len;
2645         ret = tx_elements_output_init(satoshi, script_len ? script : NULL, script_len,
2646                                       asset_len ? asset : NULL, asset_len,
2647                                       value_len ? value : NULL, value_len,
2648                                       nonce_len ? nonce : NULL, nonce_len,
2649                                       NULL, 0, NULL, 0,
2650                                       &result->outputs[i], is_elements);
2651         if (ret != WALLY_OK)
2652             goto fail;
2653         result->num_outputs += 1;
2654     }
2655 
2656     if (expect_witnesses && !is_elements) {
2657         for (i = 0; i < num_inputs; ++i) {
2658             p += varint_from_bytes(p, &num_witnesses);
2659             if (!num_witnesses)
2660                 continue;
2661             ret = wally_tx_witness_stack_init_alloc(num_witnesses,
2662                                                     &result->inputs[i].witness);
2663             if (ret != WALLY_OK)
2664                 goto fail;
2665 
2666             for (j = 0; j < num_witnesses; ++j) {
2667                 uint64_t witness_len;
2668                 p += varint_from_bytes(p, &witness_len);
2669                 ret = wally_tx_witness_stack_set(result->inputs[i].witness, j,
2670                                                  p, witness_len);
2671                 if (ret != WALLY_OK)
2672                     goto fail;
2673                 p += witness_len;
2674             }
2675         }
2676     }
2677 
2678     uint32_from_le_bytes(p, &result->locktime);
2679 
2680 #ifdef BUILD_ELEMENTS
2681 
2682 #define proof_from_bytes(dst, len) \
2683     p += varint_from_bytes(p, (len)); \
2684     (dst) = p; \
2685     p += *(len)
2686 
2687     if (expect_witnesses && is_elements) {
2688         p += sizeof(uint32_t);
2689         for (i = 0; i < num_inputs; ++i) {
2690             const unsigned char *issuance_amount_rangeproof, *inflation_keys_rangeproof;
2691             uint64_t issuance_amount_rangeproof_len, inflation_keys_rangeproof_len, offset;
2692             proof_from_bytes(issuance_amount_rangeproof, &issuance_amount_rangeproof_len);
2693             proof_from_bytes(inflation_keys_rangeproof, &inflation_keys_rangeproof_len);
2694             ret = tx_elements_input_issuance_proof_init(result->inputs + i,
2695                                                         issuance_amount_rangeproof_len ? issuance_amount_rangeproof : NULL,
2696                                                         issuance_amount_rangeproof_len,
2697                                                         inflation_keys_rangeproof_len ? inflation_keys_rangeproof : NULL,
2698                                                         inflation_keys_rangeproof_len);
2699             if (ret != WALLY_OK)
2700                 goto fail;
2701             ret = witness_stack_from_bytes(p, &result->inputs[i].witness, &offset);
2702             if (ret != WALLY_OK)
2703                 goto fail;
2704             p += offset;
2705             ret = witness_stack_from_bytes(p, &result->inputs[i].pegin_witness, &offset);
2706             if (ret != WALLY_OK)
2707                 goto fail;
2708             p += offset;
2709         }
2710 
2711         for (i = 0; i < num_outputs; ++i) {
2712             const unsigned char *surjectionproof, *rangeproof;
2713             uint64_t surjectionproof_len, rangeproof_len;
2714             proof_from_bytes(surjectionproof, &surjectionproof_len);
2715             proof_from_bytes(rangeproof, &rangeproof_len);
2716             ret = tx_elements_output_proof_init(result->outputs + i,
2717                                                 surjectionproof_len ? surjectionproof : NULL,
2718                                                 surjectionproof_len,
2719                                                 rangeproof_len ? rangeproof : NULL,
2720                                                 rangeproof_len);
2721             if (ret != WALLY_OK)
2722                 goto fail;
2723         }
2724     }
2725 
2726 #undef proof_from_bytes
2727 
2728 #endif /* BUILD_ELEMENTS */
2729     return WALLY_OK;
2730 fail:
2731     tx_free(result, true);
2732     *output = NULL;
2733     return ret;
2734 }
2735 
2736 int wally_tx_from_bytes(const unsigned char *bytes, size_t bytes_len,
2737                         uint32_t flags, struct wally_tx **output)
2738 {
2739     return tx_from_bytes(bytes, bytes_len, flags, output);
2740 }
2741 
2742 int wally_tx_from_hex(const char *hex, uint32_t flags,
2743                       struct wally_tx **output)
2744 {
2745     unsigned char buff[TX_STACK_SIZE], *buff_p = buff;
2746     size_t hex_len = hex ? strlen(hex) : 0, bin_len;
2747     size_t written;
2748     int ret;
2749 
2750     if (!hex || hex_len & 0x1 || !output)
2751         return WALLY_EINVAL;
2752 
2753     bin_len = hex_len / 2;
2754 
2755     if (bin_len > sizeof(buff)) {
2756         if ((buff_p = wally_malloc(bin_len)) == NULL)
2757             return WALLY_ENOMEM;
2758     }
2759     ret = wally_hex_to_bytes(hex, buff_p, bin_len, &written);
2760     if (ret == WALLY_OK)
2761         ret = tx_from_bytes(buff_p, bin_len, flags, output);
2762 
2763     if (buff_p != buff)
2764         clear_and_free(buff_p, bin_len);
2765     else
2766         wally_clear(buff, bin_len);
2767 
2768     return ret;
2769 }
2770 
2771 int wally_tx_is_elements(const struct wally_tx *tx, size_t *written)
2772 {
2773     if (!tx || !written)
2774         return WALLY_EINVAL;
2775 
2776     *written = is_valid_elements_tx(tx);
2777 
2778     return WALLY_OK;
2779 }
2780 
2781 int wally_tx_elements_input_is_pegin(const struct wally_tx_input *input,
2782                                      size_t *written)
2783 {
2784     if (!input || !written)
2785         return WALLY_EINVAL;
2786 
2787     *written = is_valid_elements_tx_input_pegin(input);
2788 
2789     return WALLY_OK;
2790 }
2791 
2792 int wally_tx_is_coinbase(const struct wally_tx *tx, size_t *written)
2793 {
2794     if (!tx || !written)
2795         return WALLY_EINVAL;
2796 
2797     *written = tx->num_inputs == 1 && is_valid_coinbase_input(tx->inputs);
2798 
2799     return WALLY_OK;
2800 }
2801 
2802 static int tx_get_signature_hash(const struct wally_tx *tx,
2803                                  size_t index,
2804                                  const unsigned char *script, size_t script_len,
2805                                  const unsigned char *extra, size_t extra_len,
2806                                  uint32_t extra_offset, uint64_t satoshi,
2807                                  const unsigned char *value,
2808                                  size_t value_len,
2809                                  uint32_t sighash, uint32_t tx_sighash, uint32_t flags,
2810                                  unsigned char *bytes_out, size_t len)
2811 {
2812     unsigned char buff[TX_STACK_SIZE], *buff_p = buff;
2813     size_t n, n2;
2814     size_t is_elements = 0;
2815     int ret;
2816     const struct tx_serialize_opts opts = {
2817         sighash, tx_sighash, index, script, script_len, satoshi,
2818         (flags & WALLY_TX_FLAG_USE_WITNESS) ? true : false,
2819         value, value_len
2820     };
2821 
2822     if (!is_valid_tx(tx) || BYTES_INVALID(script, script_len) ||
2823         BYTES_INVALID(extra, extra_len) ||
2824         satoshi > WALLY_SATOSHI_MAX || (sighash & 0xffffff00) ||
2825         (flags & ~WALLY_TX_ALL_FLAGS) || !bytes_out || len < SHA256_LEN)
2826         return WALLY_EINVAL;
2827 
2828     if (extra || extra_len || extra_offset)
2829         return WALLY_ERROR; /* FIXME: Not implemented yet */
2830 
2831     if (index >= tx->num_inputs ||
2832         (index >= tx->num_outputs && (sighash & SIGHASH_MASK) == WALLY_SIGHASH_SINGLE)) {
2833         if (!(flags & WALLY_TX_FLAG_USE_WITNESS)) {
2834             memset(bytes_out, 0, SHA256_LEN);
2835             bytes_out[0] = 0x1;
2836             return WALLY_OK;
2837         }
2838     }
2839 
2840 #ifdef BUILD_ELEMENTS
2841     if ((ret = wally_tx_is_elements(tx, &is_elements)) != WALLY_OK)
2842         goto fail;
2843 #endif
2844 
2845     if ((ret = tx_get_length(tx, &opts, 0, &n, is_elements != 0)) != WALLY_OK)
2846         goto fail;
2847 
2848     if (n > sizeof(buff) && (buff_p = wally_malloc(n)) == NULL) {
2849         ret = WALLY_ENOMEM;
2850         goto fail;
2851     }
2852 
2853     if ((ret = tx_to_bytes(tx, &opts, 0, buff_p, n, &n2, is_elements != 0)) != WALLY_OK)
2854         goto fail;
2855 
2856     if (n != n2)
2857         ret = WALLY_ERROR; /* tx_get_length/tx_to_bytes mismatch, should not happen! */
2858     else
2859         ret = wally_sha256d(buff_p, n2, bytes_out, len);
2860 
2861 fail:
2862     if (buff_p != buff)
2863         clear_and_free(buff_p, n);
2864     else
2865         wally_clear(buff, sizeof(buff));
2866     return ret;
2867 }
2868 
2869 int wally_tx_get_signature_hash(const struct wally_tx *tx,
2870                                 size_t index,
2871                                 const unsigned char *script, size_t script_len,
2872                                 const unsigned char *extra, size_t extra_len,
2873                                 uint32_t extra_offset, uint64_t satoshi,
2874                                 uint32_t sighash, uint32_t tx_sighash, uint32_t flags,
2875                                 unsigned char *bytes_out, size_t len)
2876 {
2877     return tx_get_signature_hash(tx, index, script, script_len,
2878                                  extra, extra_len, extra_offset, satoshi,
2879                                  NULL, 0, sighash, tx_sighash, flags, bytes_out, len);
2880 }
2881 
2882 int wally_tx_get_btc_signature_hash(const struct wally_tx *tx, size_t index,
2883                                     const unsigned char *script, size_t script_len,
2884                                     uint64_t satoshi, uint32_t sighash, uint32_t flags,
2885                                     unsigned char *bytes_out, size_t len)
2886 {
2887     return wally_tx_get_signature_hash(tx, index, script, script_len,
2888                                        NULL, 0, 0, satoshi, sighash, sighash,
2889                                        flags, bytes_out, len);
2890 }
2891 
2892 int wally_tx_get_elements_signature_hash(const struct wally_tx *tx,
2893                                          size_t index,
2894                                          const unsigned char *script, size_t script_len,
2895                                          const unsigned char *value, size_t value_len,
2896                                          uint32_t sighash, uint32_t flags,
2897                                          unsigned char *bytes_out, size_t len)
2898 {
2899     return tx_get_signature_hash(tx, index, script, script_len,
2900                                  NULL, 0, 0, 0, value, value_len,
2901                                  sighash, sighash, flags, bytes_out, len);
2902 }
2903 
2904 int wally_tx_confidential_value_from_satoshi(uint64_t satoshi,
2905                                              unsigned char *bytes_out,
2906                                              size_t len)
2907 {
2908     if (!bytes_out || len != WALLY_TX_ASSET_CT_VALUE_UNBLIND_LEN)
2909         return WALLY_EINVAL;
2910 
2911     *bytes_out = 0x1;
2912     uint64_to_be_bytes(satoshi, &bytes_out[1]);
2913 
2914     return WALLY_OK;
2915 }
2916 
2917 int wally_tx_confidential_value_to_satoshi(const unsigned char *value,
2918                                            size_t value_len,
2919                                            uint64_t *value_out)
2920 {
2921     if (!value || value_len != WALLY_TX_ASSET_CT_VALUE_UNBLIND_LEN || !value_out || value[0] != 0x1)
2922         return WALLY_EINVAL;
2923 
2924     uint64_from_be_bytes(&value[1], value_out);
2925 
2926     return WALLY_OK;
2927 }
2928 
2929 int wally_tx_elements_issuance_generate_entropy(const unsigned char *txhash,
2930                                                 size_t txhash_len,
2931                                                 uint32_t index,
2932                                                 const unsigned char *contract_hash,
2933                                                 size_t contract_hash_len,
2934                                                 unsigned char *bytes_out,
2935                                                 size_t len)
2936 {
2937     unsigned char buff[2 * SHA256_LEN];
2938     unsigned char buff_2[WALLY_TXHASH_LEN + sizeof(uint32_t)];
2939     int ret;
2940 
2941     if (!txhash || txhash_len != WALLY_TXHASH_LEN ||
2942         !contract_hash || contract_hash_len != SHA256_LEN ||
2943         !bytes_out || len != SHA256_LEN)
2944         return WALLY_EINVAL;
2945 
2946     memcpy(buff_2, txhash, txhash_len);
2947     uint32_to_le_bytes(index, buff_2 + txhash_len);
2948 
2949     ret = wally_sha256d(buff_2, sizeof(buff_2), buff, SHA256_LEN);
2950     if (ret == WALLY_OK) {
2951         memcpy(buff + SHA256_LEN, contract_hash, contract_hash_len);
2952         ret = wally_sha256_midstate(buff, sizeof(buff), bytes_out, len);
2953     }
2954 
2955     wally_clear_2(buff, sizeof(buff), buff_2, sizeof(buff_2));
2956     return ret;
2957 }
2958 
2959 static int tx_elements_token_from_bytes(const unsigned char *entropy,
2960                                         size_t entropy_len,
2961                                         const unsigned char *bytes,
2962                                         size_t bytes_len,
2963                                         unsigned char *bytes_out,
2964                                         size_t len)
2965 {
2966     unsigned char buff[2 * SHA256_LEN];
2967     int ret;
2968 
2969     if (!entropy || entropy_len != SHA256_LEN ||
2970         !bytes_len || bytes_len != SHA256_LEN ||
2971         !bytes_out || len != SHA256_LEN)
2972         return WALLY_EINVAL;
2973 
2974     memcpy(buff, entropy, entropy_len);
2975     memcpy(buff + SHA256_LEN, bytes, bytes_len);
2976 
2977     ret = wally_sha256_midstate(buff, sizeof(buff), bytes_out, len);
2978     wally_clear(buff, sizeof(buff));
2979 
2980     return ret;
2981 }
2982 
2983 int wally_tx_elements_issuance_calculate_asset(const unsigned char *entropy,
2984                                                size_t entropy_len,
2985                                                unsigned char *bytes_out,
2986                                                size_t len)
2987 {
2988     unsigned char buff[SHA256_LEN] = { 0 };
2989     return tx_elements_token_from_bytes(entropy, entropy_len,
2990                                         buff, sizeof(buff),
2991                                         bytes_out, len);
2992 }
2993 
2994 int wally_tx_elements_issuance_calculate_reissuance_token(const unsigned char *entropy,
2995                                                           size_t entropy_len,
2996                                                           uint32_t flags,
2997                                                           unsigned char *bytes_out,
2998                                                           size_t len)
2999 {
3000     unsigned char buff[SHA256_LEN] = { 0 };
3001 
3002     if ((flags & ~WALLY_TX_FLAG_BLINDED_INITIAL_ISSUANCE))
3003         return WALLY_EINVAL;
3004 
3005     /* 32-byte '1' constant for unblinded and '2' for confidential */
3006     buff[0] = flags + 1;
3007     return tx_elements_token_from_bytes(entropy, entropy_len,
3008                                         buff, sizeof(buff),
3009                                         bytes_out, len);
3010 }
3011 
3012 int wally_tx_get_total_output_satoshi(const struct wally_tx *tx, uint64_t *value_out)
3013 {
3014     size_t i;
3015     if (value_out)
3016         *value_out = 0;
3017 
3018     if (!is_valid_tx(tx) || !value_out)
3019         return WALLY_EINVAL;
3020 
3021     for (i = 0; i < tx->num_outputs; ++i) {
3022         uint64_t v = *value_out + tx->outputs[i].satoshi;
3023 
3024         if (tx->outputs[i].satoshi > WALLY_SATOSHI_MAX ||
3025             v < *value_out || v > WALLY_SATOSHI_MAX) {
3026             /* Overflow or too many satoshi in outputs */
3027             *value_out = 0;
3028             return WALLY_EINVAL;
3029         }
3030         *value_out = v;
3031     }
3032 
3033     return WALLY_OK;
3034 }
3035 
3036 static struct wally_tx_input *tx_get_input(const struct wally_tx *tx, size_t index)
3037 {
3038     return is_valid_tx(tx) && index < tx->num_inputs ? &tx->inputs[index] : NULL;
3039 }
3040 
3041 #define TX_SET_B(typ, name) \
3042     int wally_tx_set_ ## typ ## _ ## name(const struct wally_tx *tx, size_t index, \
3043                                           const unsigned char *name, size_t name ## _len) { \
3044         return wally_tx_ ## typ ## _set_ ## name(tx_get_ ## typ(tx, index), name, name ## _len); \
3045     }
3046 
3047 #if defined (SWIG_JAVA_BUILD) || defined (SWIG_PYTHON_BUILD) || defined (SWIG_JAVASCRIPT_BUILD)
3048 
3049 /* Getters for wally_tx_input/wally_tx_output/wally_tx values */
3050 
3051 static int tx_getb_impl(const void *input,
3052                         const unsigned char *src, size_t src_len,
3053                         unsigned char *bytes_out, size_t len, size_t *written)
3054 {
3055     if (written)
3056         *written = 0;
3057     if (!input || !bytes_out || len < src_len || !written)
3058         return WALLY_EINVAL;
3059     memcpy(bytes_out, src, src_len);
3060     *written = src_len;
3061     return WALLY_OK;
3062 }
3063 
3064 #define GET_TX_B_FIXED(typ, name, siz, n) \
3065     int wally_ ## typ ## _get_ ## name(const struct wally_ ## typ *input, \
3066                                        unsigned char *bytes_out, size_t len) { \
3067         size_t written; \
3068         if (!input || len != n) \
3069             return WALLY_EINVAL; \
3070         return tx_getb_impl(input, input->name, siz, bytes_out, len, &written); \
3071     }
3072 
3073 
3074 GET_TX_B_FIXED(tx_input, txhash, WALLY_TXHASH_LEN, WALLY_TXHASH_LEN)
3075 #ifdef BUILD_ELEMENTS
3076 GET_TX_B_FIXED(tx_input, blinding_nonce, SHA256_LEN, SHA256_LEN)
3077 GET_TX_B_FIXED(tx_input, entropy, SHA256_LEN, SHA256_LEN)
3078 #endif /* BUILD_ELEMENTS */
3079 
3080 
3081 #define GET_TX_B(typ, name, siz) \
3082     int wally_ ## typ ## _get_ ## name(const struct wally_ ## typ *input, \
3083                                        unsigned char *bytes_out, size_t len, size_t * written) { \
3084         if (!input) \
3085             return WALLY_EINVAL; \
3086         return tx_getb_impl(input, input->name, siz, bytes_out, len, written); \
3087     }
3088 
3089 #define GET_TX_I(typ, name, outtyp) \
3090     int wally_ ## typ ## _get_ ## name(const struct wally_ ## typ *input, outtyp * written) { \
3091         if (written) *written = 0; \
3092         if (!input || !written) return WALLY_EINVAL; \
3093         *written = input->name; \
3094         return WALLY_OK; \
3095     }
3096 
3097 
3098 GET_TX_B(tx_input, script, input->script_len)
3099 static bool get_witness_preamble(const struct wally_tx_input *input,
3100                                  size_t index, size_t *written)
3101 {
3102     if (written)
3103         *written = 0;
3104     if (!is_valid_tx_input(input) || !written ||
3105         !is_valid_witness_stack(input->witness) ||
3106         index >= input->witness->num_items)
3107         return false;
3108     return true;
3109 }
3110 
3111 int wally_tx_input_get_witness(const struct wally_tx_input *input, size_t index,
3112                                unsigned char *bytes_out, size_t len, size_t *written)
3113 {
3114     if (!bytes_out || !get_witness_preamble(input, index, written) ||
3115         len < input->witness->items[index].witness_len)
3116         return WALLY_EINVAL;
3117     memcpy(bytes_out, input->witness->items[index].witness,
3118            input->witness->items[index].witness_len);
3119     *written = input->witness->items[index].witness_len;
3120     return WALLY_OK;
3121 }
3122 
3123 GET_TX_I(tx_input, index, size_t)
3124 GET_TX_I(tx_input, sequence, size_t)
3125 GET_TX_I(tx_input, script_len, size_t)
3126 
3127 int wally_tx_input_get_witness_len(const struct wally_tx_input *input,
3128                                    size_t index, size_t *written)
3129 {
3130     if (!get_witness_preamble(input, index, written))
3131         return WALLY_EINVAL;
3132     *written = input->witness->items[index].witness_len;
3133     return WALLY_OK;
3134 }
3135 #ifdef BUILD_ELEMENTS
3136 GET_TX_B(tx_input, issuance_amount, input->issuance_amount_len)
3137 GET_TX_I(tx_input, issuance_amount_len, size_t)
3138 GET_TX_B(tx_input, inflation_keys, input->inflation_keys_len)
3139 GET_TX_I(tx_input, inflation_keys_len, size_t)
3140 GET_TX_B(tx_input, issuance_amount_rangeproof, input->issuance_amount_rangeproof_len)
3141 GET_TX_I(tx_input, issuance_amount_rangeproof_len, size_t)
3142 GET_TX_B(tx_input, inflation_keys_rangeproof, input->inflation_keys_rangeproof_len)
3143 GET_TX_I(tx_input, inflation_keys_rangeproof_len, size_t)
3144 #endif /* BUILD_ELEMENTS */
3145 
3146 GET_TX_B(tx_output, script, input->script_len)
3147 GET_TX_I(tx_output, satoshi, uint64_t)
3148 GET_TX_I(tx_output, script_len, size_t)
3149 
3150 #ifdef BUILD_ELEMENTS
3151 GET_TX_B_FIXED(tx_output, asset, input->asset_len, WALLY_TX_ASSET_CT_ASSET_LEN)
3152 GET_TX_I(tx_output, asset_len, size_t)
3153 GET_TX_B(tx_output, value, input->value_len)
3154 GET_TX_I(tx_output, value_len, size_t)
3155 GET_TX_B_FIXED(tx_output, nonce, input->nonce_len, WALLY_TX_ASSET_CT_NONCE_LEN)
3156 GET_TX_I(tx_output, nonce_len, size_t)
3157 GET_TX_B(tx_output, surjectionproof, input->surjectionproof_len)
3158 GET_TX_I(tx_output, surjectionproof_len, size_t)
3159 GET_TX_B(tx_output, rangeproof, input->rangeproof_len)
3160 GET_TX_I(tx_output, rangeproof_len, size_t)
3161 #endif /* BUILD_ELEMENTS */
3162 
3163 GET_TX_I(tx, version, size_t)
3164 GET_TX_I(tx, locktime, size_t)
3165 GET_TX_I(tx, num_inputs, size_t)
3166 GET_TX_I(tx, num_outputs, size_t)
3167 
3168 #ifdef BUILD_ELEMENTS
3169 static int tx_setb_impl(const unsigned char *bytes, size_t bytes_len,
3170                         unsigned char **bytes_out, size_t *bytes_out_len)
3171 {
3172     /* TODO: Avoid reallocation if smaller than the existing one */
3173     unsigned char *new_bytes = NULL;
3174     if (!clone_bytes(&new_bytes, bytes, bytes_len))
3175         return WALLY_ENOMEM;
3176 
3177     clear_and_free(*bytes_out, *bytes_out_len);
3178     *bytes_out = new_bytes;
3179     *bytes_out_len = bytes_len;
3180     return WALLY_OK;
3181 }
3182 
3183 #define SET_TX_B(typ, name, siz) \
3184     int wally_ ## typ ## _set_ ## name(struct wally_ ## typ *output, \
3185                                        const unsigned char *bytes, size_t siz) { \
3186         if (!is_valid_elements_ ## typ(output) || BYTES_INVALID(bytes, siz)) \
3187             return WALLY_EINVAL; \
3188         return tx_setb_impl(bytes, siz, &output->name, &output->name ## _len); \
3189     }
3190 
3191 #define SET_TX_B_FIXED(typ, name, siz, n) \
3192     int wally_ ## typ ## _set_ ## name(struct wally_ ## typ *output, \
3193                                        const unsigned char *bytes, size_t siz) { \
3194         if (!is_valid_elements_ ## typ(output) || (siz && siz != n) || BYTES_INVALID(bytes, siz)) \
3195             return WALLY_EINVAL; \
3196         return tx_setb_impl(bytes, siz, &output->name, &output->name ## _len); \
3197     }
3198 #endif /* BUILD_ELEMENTS */
3199 
3200 int wally_tx_input_set_index(struct wally_tx_input *input, uint32_t index)
3201 {
3202     if (!is_valid_tx_input(input))
3203         return WALLY_EINVAL;
3204     input->index = index;
3205     return WALLY_OK;
3206 }
3207 
3208 int wally_tx_input_set_sequence(struct wally_tx_input *input, uint32_t sequence)
3209 {
3210     if (!is_valid_tx_input(input))
3211         return WALLY_EINVAL;
3212     input->sequence = sequence;
3213     return WALLY_OK;
3214 }
3215 
3216 int wally_tx_input_set_txhash(struct wally_tx_input *input,
3217                               const unsigned char *txhash, size_t len)
3218 {
3219     if (!is_valid_tx_input(input) || !txhash || (len != WALLY_TXHASH_LEN))
3220         return WALLY_EINVAL;
3221     memcpy(input->txhash, txhash, WALLY_TXHASH_LEN);
3222     return WALLY_OK;
3223 }
3224 
3225 int wally_tx_output_set_script(struct wally_tx_output *output,
3226                                const unsigned char *script, size_t script_len)
3227 {
3228     if (!is_valid_tx_output(output))
3229         return WALLY_EINVAL;
3230     return replace_bytes(script, script_len, &output->script, &output->script_len);
3231 }
3232 
3233 int wally_tx_output_set_satoshi(struct wally_tx_output *output, uint64_t satoshi)
3234 {
3235     if (!is_valid_tx_output(output) || satoshi > WALLY_SATOSHI_MAX)
3236         return WALLY_EINVAL;
3237     output->satoshi = satoshi;
3238     return WALLY_OK;
3239 }
3240 
3241 #ifdef BUILD_ELEMENTS
3242 #define SET_TX_ARRAY(typ, name, siz) \
3243     int wally_ ## typ ## _set_ ## name(struct wally_ ## typ *input, \
3244                                        const unsigned char *name, size_t name ## _len) { \
3245         if (!is_valid_elements_ ## typ(input) || !name || name ## _len != siz) \
3246             return WALLY_EINVAL; \
3247         memcpy(input->name, name, siz); \
3248         return WALLY_OK; \
3249     }
3250 
3251 SET_TX_ARRAY(tx_input, blinding_nonce, SHA256_LEN)
3252 SET_TX_ARRAY(tx_input, entropy, SHA256_LEN)
3253 SET_TX_B(tx_input, inflation_keys, siz)
3254 SET_TX_B(tx_input, inflation_keys_rangeproof, siz)
3255 SET_TX_B(tx_input, issuance_amount, siz)
3256 SET_TX_B(tx_input, issuance_amount_rangeproof, siz)
3257 
3258 SET_TX_B_FIXED(tx_output, asset, siz, WALLY_TX_ASSET_CT_ASSET_LEN)
3259 int wally_tx_output_set_value(struct wally_tx_output *output, const unsigned char *value, size_t value_len)
3260 {
3261     if (!is_valid_elements_tx_output(output) ||
3262         ((value != NULL) != (value_len == WALLY_TX_ASSET_CT_VALUE_LEN ||
3263                              value_len == WALLY_TX_ASSET_CT_VALUE_UNBLIND_LEN)))
3264         return WALLY_EINVAL;
3265     return tx_setb_impl(value, value_len, &output->value, &output->value_len);
3266 }
3267 SET_TX_B_FIXED(tx_output, nonce, siz, WALLY_TX_ASSET_CT_NONCE_LEN)
3268 SET_TX_B(tx_output, surjectionproof, siz)
3269 SET_TX_B(tx_output, rangeproof, siz)
3270 #endif
3271 
3272 static struct wally_tx_output *tx_get_output(const struct wally_tx *tx, size_t index)
3273 {
3274     return is_valid_tx(tx) && index < tx->num_outputs ? &tx->outputs[index] : NULL;
3275 }
3276 
3277 #define TX_GET_B(typ, name) \
3278     int wally_tx_get_ ## typ ## _ ## name(const struct wally_tx *tx, size_t index, unsigned char *bytes_out, size_t len, size_t *written) { \
3279         return wally_tx_ ## typ ## _get_ ## name(tx_get_ ## typ(tx, index), bytes_out, len, written); \
3280     }
3281 
3282 #define TX_GET_B_FIXED(typ, name) \
3283     int wally_tx_get_ ## typ ## _ ## name(const struct wally_tx *tx, size_t index, unsigned char *bytes_out, size_t len) { \
3284         return wally_tx_ ## typ ## _get_ ## name(tx_get_ ## typ(tx, index), bytes_out, len); \
3285     }
3286 
3287 #define TX_GET_I(typ, name) \
3288     int wally_tx_get_ ## typ ## _ ## name(const struct wally_tx *tx, size_t index, size_t *written) { \
3289         return wally_tx_ ## typ ## _get_ ## name(tx_get_ ## typ(tx, index), written); \
3290     }
3291 
3292 TX_GET_B(input, script)
3293 TX_GET_I(input, script_len)
3294 TX_GET_B_FIXED(input, txhash)
3295 TX_GET_I(input, index)
3296 TX_GET_I(input, sequence)
3297 
3298 int wally_tx_get_input_witness(const struct wally_tx *tx, size_t index, size_t wit_index, unsigned char *bytes_out, size_t len, size_t *written)
3299 {
3300     return wally_tx_input_get_witness(tx_get_input(tx, index), wit_index, bytes_out, len, written);
3301 }
3302 
3303 int wally_tx_get_input_witness_len(const struct wally_tx *tx, size_t index, size_t wit_index, size_t *written)
3304 {
3305     return wally_tx_input_get_witness_len(tx_get_input(tx, index), wit_index, written);
3306 }
3307 
3308 #ifdef BUILD_ELEMENTS
3309 TX_GET_B_FIXED(input, blinding_nonce)
3310 TX_GET_B_FIXED(input, entropy)
3311 TX_GET_B(input, inflation_keys)
3312 TX_GET_B(input, inflation_keys_rangeproof)
3313 TX_GET_B(input, issuance_amount)
3314 TX_GET_B(input, issuance_amount_rangeproof)
3315 TX_GET_I(input, inflation_keys_len)
3316 TX_GET_I(input, inflation_keys_rangeproof_len)
3317 TX_GET_I(input, issuance_amount_len)
3318 TX_GET_I(input, issuance_amount_rangeproof_len)
3319 #endif /* BUILD_ELEMENTS */
3320 TX_GET_B(output, script)
3321 TX_GET_I(output, script_len)
3322 
3323 int wally_tx_get_output_satoshi(const struct wally_tx *tx, size_t index, uint64_t *value_out)
3324 {
3325     return wally_tx_output_get_satoshi(tx_get_output(tx, index), value_out);
3326 }
3327 
3328 #ifdef BUILD_ELEMENTS
3329 TX_GET_B_FIXED(output, asset)
3330 TX_GET_B(output, value)
3331 TX_GET_B_FIXED(output, nonce)
3332 TX_GET_B(output, surjectionproof)
3333 TX_GET_B(output, rangeproof)
3334 TX_GET_I(output, asset_len)
3335 TX_GET_I(output, value_len)
3336 TX_GET_I(output, nonce_len)
3337 TX_GET_I(output, surjectionproof_len)
3338 TX_GET_I(output, rangeproof_len)
3339 #endif /* BUILD_ELEMENTS */
3340 
3341 TX_SET_B(input, txhash)
3342 
3343 int wally_tx_set_input_index(const struct wally_tx *tx, size_t index, uint32_t index_in)
3344 {
3345     return wally_tx_input_set_index(tx_get_input(tx, index), index_in);
3346 }
3347 
3348 int wally_tx_set_input_sequence(const struct wally_tx *tx, size_t index, uint32_t sequence)
3349 {
3350     return wally_tx_input_set_sequence(tx_get_input(tx, index), sequence);
3351 }
3352 
3353 TX_SET_B(output, script)
3354 
3355 int wally_tx_set_output_satoshi(const struct wally_tx *tx, size_t index, uint64_t satoshi)
3356 {
3357     uint64_t current, total;
3358 
3359     if (wally_tx_get_output_satoshi(tx, index, &current) != WALLY_OK ||
3360         wally_tx_get_total_output_satoshi(tx, &total) != WALLY_OK)
3361         return WALLY_EINVAL;
3362     total -= current;
3363     if (total + satoshi < total || total + satoshi > WALLY_SATOSHI_MAX)
3364         return WALLY_EINVAL;
3365     return wally_tx_output_set_satoshi(tx_get_output(tx, index), satoshi);
3366 }
3367 
3368 #ifdef BUILD_ELEMENTS
3369 TX_SET_B(input, blinding_nonce)
3370 TX_SET_B(input, entropy)
3371 TX_SET_B(input, inflation_keys)
3372 TX_SET_B(input, inflation_keys_rangeproof)
3373 TX_SET_B(input, issuance_amount)
3374 TX_SET_B(input, issuance_amount_rangeproof)
3375 
3376 TX_SET_B(output, asset)
3377 TX_SET_B(output, value)
3378 TX_SET_B(output, nonce)
3379 TX_SET_B(output, surjectionproof)
3380 TX_SET_B(output, rangeproof)
3381 #endif
3382 #endif /* SWIG_JAVA_BUILD/SWIG_PYTHON_BUILD */
3383 
3384 int wally_tx_input_set_witness(struct wally_tx_input *input,
3385                                const struct wally_tx_witness_stack *stack)
3386 {
3387     struct wally_tx_witness_stack *new_witness = NULL;
3388 
3389     if (!is_valid_tx_input(input) || (stack && !is_valid_witness_stack(stack)))
3390         return WALLY_EINVAL;
3391 
3392     if (stack &&
3393         wally_tx_witness_stack_clone_alloc(stack, &new_witness) != WALLY_OK)
3394         return WALLY_ENOMEM;
3395 
3396     tx_witness_stack_free(input->witness, true);
3397     input->witness = new_witness;
3398     return WALLY_OK;
3399 }
3400 
3401 int wally_tx_set_input_witness(const struct wally_tx *tx, size_t index,
3402                                const struct wally_tx_witness_stack *stack)
3403 {
3404     return wally_tx_input_set_witness(tx_get_input(tx, index), stack);
3405 }
3406 
3407 
3408 int wally_tx_input_set_script(struct wally_tx_input *input,
3409                               const unsigned char *script, size_t script_len)
3410 {
3411     if (!is_valid_tx_input(input))
3412         return WALLY_EINVAL;
3413     return replace_bytes(script, script_len, &input->script, &input->script_len);
3414 }
3415 
3416 TX_SET_B(input, script)
3417 
3418 int wally_tx_clone_alloc(const struct wally_tx *tx, uint32_t flags, struct wally_tx **output)
3419 {
3420     size_t i;
3421     struct wally_tx *result = NULL;
3422     int ret;
3423 
3424     TX_CHECK_OUTPUT;
3425 
3426     if (!is_valid_tx(tx) || flags != 0)
3427         return WALLY_EINVAL;
3428 
3429     ret = wally_tx_init_alloc(tx->version, tx->locktime, tx->num_inputs, tx->num_outputs, &result);
3430 
3431     for (i = 0; ret == WALLY_OK && i < tx->num_inputs; ++i)
3432         ret = wally_tx_add_input(result, &tx->inputs[i]);
3433 
3434     for (i = 0; ret == WALLY_OK && i < tx->num_outputs; ++i)
3435         ret = wally_tx_add_output(result, &tx->outputs[i]);
3436 
3437     if (ret == WALLY_OK)
3438         *output = result;
3439     else
3440         wally_tx_free(result);
3441 
3442     return ret;
3443 }
3444