1 #include "internal.h"
2
3 #include <include/wally_elements.h>
4 #include <include/wally_script.h>
5 #include <include/wally_psbt.h>
6
7 #include <limits.h>
8 #include <stdbool.h>
9 #include "transaction_shared.h"
10 #include "psbt_int.h"
11 #include "script_int.h"
12 #include "script.h"
13 #include "pullpush.h"
14
15 /* TODO:
16 * - When setting utxo in an input via the psbt (in the SWIG
17 * case), check the txid matches the input (see is_matching_txid() call
18 * in the signing code).
19 * - When signing, validate the existing signatures and refuse to sign if
20 * any are incorrect. This prevents others pretending to sign and then
21 * gaining our signature without having provided theirs.
22 * - Signing of multisig inputs is not implemented.
23 * - Change detection is not implemented, something like:
24 * wally_psbt_is_related_output(psbt, index, ext_key, written) could
25 * identify whether the given output pays to and address from ext_key.
26 */
27
28 /* Constants for key types in serialized PSBTs */
29 #define PSBT_SEPARATOR 0x00
30
31 #define PSBT_GLOBAL_UNSIGNED_TX 0x00
32 #define PSBT_GLOBAL_VERSION 0xFB
33
34 #define PSBT_IN_NON_WITNESS_UTXO 0x00
35 #define PSBT_IN_WITNESS_UTXO 0x01
36 #define PSBT_IN_PARTIAL_SIG 0x02
37 #define PSBT_IN_SIGHASH_TYPE 0x03
38 #define PSBT_IN_REDEEM_SCRIPT 0x04
39 #define PSBT_IN_WITNESS_SCRIPT 0x05
40 #define PSBT_IN_BIP32_DERIVATION 0x06
41 #define PSBT_IN_FINAL_SCRIPTSIG 0x07
42 #define PSBT_IN_FINAL_SCRIPTWITNESS 0x08
43
44 #define PSBT_OUT_REDEEM_SCRIPT 0x00
45 #define PSBT_OUT_WITNESS_SCRIPT 0x01
46 #define PSBT_OUT_BIP32_DERIVATION 0x02
47
48 #ifdef BUILD_ELEMENTS
49 #define PSET_IN_VALUE 0x00
50 #define PSET_IN_VALUE_BLINDER 0x01
51 #define PSET_IN_ASSET 0x02
52 #define PSET_IN_ASSET_BLINDER 0x03
53 #define PSET_IN_PEG_IN_TX 0x04
54 #define PSET_IN_TXOUT_PROOF 0x05
55 #define PSET_IN_GENESIS_HASH 0x06
56 #define PSET_IN_CLAIM_SCRIPT 0x07
57
58 #define PSET_OUT_VALUE_COMMITMENT 0x00
59 #define PSET_OUT_VALUE_BLINDER 0x01
60 #define PSET_OUT_ASSET_COMMITMENT 0x02
61 #define PSET_OUT_ASSET_BLINDER 0x03
62 #define PSET_OUT_RANGE_PROOF 0x04
63 #define PSET_OUT_SURJECTION_PROOF 0x05
64 #define PSET_OUT_BLINDING_PUBKEY 0x06
65 #define PSET_OUT_NONCE_COMMITMENT 0x07
66 #endif /* BUILD ELEMENTS */
67
68 static const uint8_t PSBT_MAGIC[5] = {'p', 's', 'b', 't', 0xff};
69 static const uint8_t PSET_MAGIC[5] = {'p', 's', 'e', 't', 0xff};
70
71 #ifdef BUILD_ELEMENTS
72 static const uint8_t PSET_KEY_PREFIX[8] = {'e', 'l', 'e', 'm', 'e', 'n', 't', 's'};
73
is_elements_prefix(const unsigned char * key,size_t key_len)74 static bool is_elements_prefix(const unsigned char *key, size_t key_len) {
75 return key_len == sizeof(PSET_KEY_PREFIX) &&
76 memcmp(key, PSET_KEY_PREFIX, key_len) == 0;
77 }
78 #endif /* BUILD_ELEMENTS */
79
tx_clone_alloc(const struct wally_tx * src,struct wally_tx ** dst)80 static int tx_clone_alloc(const struct wally_tx *src, struct wally_tx **dst) {
81 return wally_tx_clone_alloc(src, 0, dst);
82 }
83
is_matching_txid(const struct wally_tx * tx,const unsigned char * txid,size_t txid_len)84 static bool is_matching_txid(const struct wally_tx *tx,
85 const unsigned char *txid, size_t txid_len)
86 {
87 unsigned char src_txid[WALLY_TXHASH_LEN];
88 bool ret;
89
90 if (!tx || !txid || txid_len != WALLY_TXHASH_LEN)
91 return false;
92
93 if (wally_tx_get_txid(tx, src_txid, sizeof(src_txid)) != WALLY_OK)
94 return false;
95
96 ret = memcmp(src_txid, txid, txid_len) == 0;
97 wally_clear(src_txid, sizeof(src_txid));
98 return ret;
99 }
100
array_grow(void ** src,size_t num_items,size_t * allocation_len,size_t item_size)101 static int array_grow(void **src, size_t num_items, size_t *allocation_len,
102 size_t item_size)
103 {
104 if (num_items == *allocation_len) {
105 /* Array is full, allocate more space */
106 const size_t n = (*allocation_len == 0 ? 1 : *allocation_len) * 2;
107 void *p = realloc_array(*src, *allocation_len, n, item_size);
108 if (!p)
109 return WALLY_ENOMEM;
110 /* Free and replace the old array with the new enlarged copy */
111 clear_and_free(*src, num_items * item_size);
112 *src = p;
113 *allocation_len = n;
114 }
115 return WALLY_OK;
116 }
117
wally_map_init(size_t allocation_len,struct wally_map * output)118 int wally_map_init(size_t allocation_len, struct wally_map *output)
119 {
120 if (!output)
121 return WALLY_EINVAL;
122
123 wally_clear(output, sizeof(*output));
124 if (allocation_len) {
125 output->items = wally_calloc(allocation_len * sizeof(*output->items));
126 if (!output->items)
127 return WALLY_ENOMEM;
128 }
129 output->items_allocation_len = allocation_len;
130 return WALLY_OK;
131 }
132
wally_map_init_alloc(size_t allocation_len,struct wally_map ** output)133 int wally_map_init_alloc(size_t allocation_len, struct wally_map **output)
134 {
135 struct wally_map *result;
136 int ret;
137
138 TX_CHECK_OUTPUT;
139 TX_OUTPUT_ALLOC(struct wally_map);
140
141 ret = wally_map_init(allocation_len, result);
142 if (ret != WALLY_OK) {
143 wally_free(result);
144 *output = NULL;
145 }
146 return ret;
147 }
148
wally_map_clear(struct wally_map * map_in)149 int wally_map_clear(struct wally_map *map_in)
150 {
151 size_t i;
152
153 if (!map_in)
154 return WALLY_EINVAL;
155 for (i = 0; i < map_in->num_items; ++i) {
156 clear_and_free(map_in->items[i].key, map_in->items[i].key_len);
157 clear_and_free(map_in->items[i].value, map_in->items[i].value_len);
158 }
159 clear_and_free(map_in->items, map_in->num_items * sizeof(*map_in->items));
160 wally_clear(map_in, sizeof(*map_in));
161 return WALLY_OK;
162 }
163
wally_map_free(struct wally_map * map_in)164 int wally_map_free(struct wally_map *map_in)
165 {
166 if (map_in) {
167 wally_map_clear(map_in);
168 wally_free(map_in);
169 }
170 return WALLY_OK;
171 }
172
wally_map_find(const struct wally_map * map_in,const unsigned char * key,size_t key_len,size_t * written)173 int wally_map_find(const struct wally_map *map_in,
174 const unsigned char *key, size_t key_len,
175 size_t *written)
176 {
177 size_t i;
178
179 if (written)
180 *written = 0;
181
182 if (!map_in || !key || BYTES_INVALID(key, key_len) || !written)
183 return WALLY_EINVAL;
184
185 for (i = 0; i < map_in->num_items; ++i) {
186 const struct wally_map_item *item = &map_in->items[i];
187
188 if (key_len == item->key_len && memcmp(key, item->key, key_len) == 0) {
189 *written = i + 1; /* Found */
190 break;
191 }
192 }
193 return WALLY_OK;
194 }
195
196 /* Note: If take_value is true and this errors, the caller must
197 * free `value`. By design this only happens with calls internal
198 * to this source file. */
map_add(struct wally_map * map_in,const unsigned char * key,size_t key_len,const unsigned char * value,size_t value_len,bool take_value,int (* check_fn)(const unsigned char * key,size_t key_len),bool ignore_dups)199 static int map_add(struct wally_map *map_in,
200 const unsigned char *key, size_t key_len,
201 const unsigned char *value, size_t value_len,
202 bool take_value,
203 int (*check_fn)(const unsigned char *key, size_t key_len),
204 bool ignore_dups)
205 {
206 size_t is_found;
207 int ret;
208
209 if (!map_in || !key || BYTES_INVALID(key, key_len) ||
210 (check_fn && check_fn(key, key_len) != WALLY_OK) ||
211 BYTES_INVALID(value, value_len))
212 return WALLY_EINVAL;
213
214 if ((ret = wally_map_find(map_in, key, key_len, &is_found)) != WALLY_OK)
215 return ret;
216
217 if (is_found) {
218 if (ignore_dups && take_value)
219 clear_and_free((unsigned char *)value, value_len);
220 return ignore_dups ? WALLY_OK : WALLY_EINVAL;
221 }
222
223 ret = array_grow((void *)&map_in->items, map_in->num_items,
224 &map_in->items_allocation_len, sizeof(struct wally_map_item));
225 if (ret == WALLY_OK) {
226 struct wally_map_item *new_item = map_in->items + map_in->num_items;
227
228 if (!clone_bytes(&new_item->key, key, key_len))
229 return WALLY_ENOMEM;
230 if (value) {
231 if (take_value)
232 new_item->value = (unsigned char *)value;
233 else if (!clone_bytes(&new_item->value, value, value_len)) {
234 clear_and_free(new_item->key, key_len);
235 new_item->key = NULL;
236 return WALLY_ENOMEM;
237 }
238 }
239 new_item->key_len = key_len;
240 new_item->value_len = value_len;
241 map_in->num_items++;
242 }
243 return ret;
244 }
245
wally_map_add(struct wally_map * map_in,const unsigned char * key,size_t key_len,const unsigned char * value,size_t value_len)246 int wally_map_add(struct wally_map *map_in,
247 const unsigned char *key, size_t key_len,
248 const unsigned char *value, size_t value_len)
249 {
250 return map_add(map_in, key, key_len, value, value_len, false, NULL, true);
251 }
252
wally_map_add_keypath_item(struct wally_map * map_in,const unsigned char * pub_key,size_t pub_key_len,const unsigned char * fingerprint,size_t fingerprint_len,const uint32_t * path,size_t path_len)253 int wally_map_add_keypath_item(struct wally_map *map_in,
254 const unsigned char *pub_key, size_t pub_key_len,
255 const unsigned char *fingerprint, size_t fingerprint_len,
256 const uint32_t *path, size_t path_len)
257 {
258 unsigned char *value;
259 size_t value_len, i;
260 int ret;
261
262 if (!map_in ||
263 (wally_ec_public_key_verify(pub_key, pub_key_len) != WALLY_OK) ||
264 !fingerprint || fingerprint_len != BIP32_KEY_FINGERPRINT_LEN ||
265 BYTES_INVALID(path, path_len))
266 return WALLY_EINVAL;
267
268 value_len = fingerprint_len + path_len * sizeof(uint32_t);
269 if (!(value = wally_malloc(value_len)))
270 return WALLY_ENOMEM;
271
272 memcpy(value, fingerprint, fingerprint_len);
273 for (i = 0; i < path_len; ++i) {
274 leint32_t tmp = cpu_to_le32(path[i]);
275 memcpy(value + fingerprint_len + i * sizeof(uint32_t),
276 &tmp, sizeof(tmp));
277 }
278
279 ret = map_add(map_in, pub_key, pub_key_len, value, value_len, true, NULL, true);
280 if (ret != WALLY_OK)
281 clear_and_free(value, value_len);
282 return ret;
283 }
284
map_item_compare(const void * lhs,const void * rhs)285 static int map_item_compare(const void *lhs, const void *rhs)
286 {
287 const struct wally_map_item *l = lhs, *r = rhs;
288 const size_t min_len = l->key_len < r->key_len ? l->key_len : r->key_len;
289 int cmp;
290
291 cmp = memcmp(l->key, r->key, min_len);
292 if (cmp == 0) {
293 /* Equal up to the min length, longest key is greater. If we have
294 * duplicate keys somehow, the resulting order is undefined */
295 cmp = l->key_len < r->key_len ? -1 : 1;
296 }
297 return cmp;
298 }
299
wally_map_sort(struct wally_map * map_in,uint32_t flags)300 int wally_map_sort(struct wally_map *map_in, uint32_t flags)
301 {
302 if (!map_in || flags)
303 return WALLY_EINVAL;
304
305 qsort(map_in->items, map_in->num_items, sizeof(struct wally_map_item), map_item_compare);
306 return WALLY_OK;
307 }
308
map_extend(struct wally_map * dst,const struct wally_map * src,int (* check_fn)(const unsigned char * key,size_t key_len))309 static int map_extend(struct wally_map *dst, const struct wally_map *src,
310 int (*check_fn)(const unsigned char *key, size_t key_len))
311 {
312 int ret = WALLY_OK;
313 size_t i;
314
315 if (src) {
316 for (i = 0; ret == WALLY_OK && i < src->num_items; ++i)
317 ret = map_add(dst, src->items[i].key, src->items[i].key_len,
318 src->items[i].value, src->items[i].value_len,
319 false, check_fn, true);
320 }
321 return ret;
322 }
323
map_assign(const struct wally_map * src,struct wally_map * dst,int (* check_fn)(const unsigned char * key,size_t key_len))324 static int map_assign(const struct wally_map *src, struct wally_map *dst,
325 int (*check_fn)(const unsigned char *key, size_t key_len))
326 {
327 struct wally_map result;
328 size_t i;
329 int ret = WALLY_OK;
330
331 if (!src)
332 ret = wally_map_init(0, &result);
333 else {
334 ret = wally_map_init(src->items_allocation_len, &result);
335 for (i = 0; ret == WALLY_OK && i < src->num_items; ++i)
336 ret = map_add(&result, src->items[i].key, src->items[i].key_len,
337 src->items[i].value, src->items[i].value_len,
338 false, check_fn, true);
339 }
340
341 if (ret != WALLY_OK)
342 wally_map_clear(&result);
343 else {
344 wally_map_clear(dst);
345 memcpy(dst, &result, sizeof(result));
346 }
347 return ret;
348 }
349
350 /* Set a struct member on a parent struct */
351 #define SET_STRUCT(PARENT, NAME, STRUCT_TYPE, CLONE_FN, FREE_FN) \
352 int PARENT ## _set_ ## NAME(struct PARENT *parent, const struct STRUCT_TYPE *p) { \
353 int ret = WALLY_OK; \
354 struct STRUCT_TYPE *new_p = NULL; \
355 if (!parent) return WALLY_EINVAL; \
356 if (p && (ret = CLONE_FN(p, &new_p)) != WALLY_OK) return ret; \
357 FREE_FN(parent->NAME); \
358 parent->NAME = new_p; \
359 return ret; \
360 }
361
362 /* Set a variable length bytes member on a parent struct */
363 #define SET_BYTES(PARENT, NAME) \
364 int PARENT ## _set_ ## NAME(struct PARENT *parent, const unsigned char *bytes, size_t len) { \
365 if (!parent) return WALLY_EINVAL; \
366 return replace_bytes(bytes, len, \
367 &parent->NAME, &parent->NAME ## _len); \
368 }
369
370 /* Set a fixed length bytes member on a parent struct */
371 #define SET_BYTES_N(PARENT, NAME, SIZE) \
372 int PARENT ## _set_ ## NAME(struct PARENT *parent, const unsigned char *bytes, size_t len) { \
373 if (!parent || BYTES_INVALID_N(bytes, len, SIZE)) return WALLY_EINVAL; \
374 return replace_bytes(bytes, len, \
375 &parent->NAME, &parent->NAME ## _len); \
376 }
377
378 /* Set/find in and add a vap value member on a parent struct */
379 #define SET_MAP(PARENT, NAME, CHECK_FN) \
380 int PARENT ## _set_ ## NAME ## s(struct PARENT *parent, const struct wally_map *map_in) { \
381 if (!parent) return WALLY_EINVAL; \
382 return map_assign(map_in, &parent->NAME ## s, CHECK_FN); \
383 } \
384 int PARENT ## _find_ ## NAME(struct PARENT *parent, \
385 const unsigned char *key, size_t key_len, \
386 size_t *written) { \
387 if (written) *written = 0; \
388 if (!parent) return WALLY_EINVAL; \
389 return wally_map_find(&parent->NAME ## s, key, key_len, written); \
390 } \
391 int PARENT ## _add_ ## NAME(struct PARENT *parent, \
392 const unsigned char *key, size_t key_len, \
393 const unsigned char *value, size_t value_len) { \
394 if (!parent) return WALLY_EINVAL; \
395 return wally_map_add(&parent->NAME ## s, key, key_len, value, value_len); \
396 }
397
398 /* Add a keypath to parent structs keyoaths member */
399 #define ADD_KEYPATH(PARENT) \
400 int PARENT ## _add_keypath_item(struct PARENT *parent, \
401 const unsigned char *pub_key, size_t pub_key_len, \
402 const unsigned char *fingerprint, size_t fingerprint_len, \
403 const uint32_t *child_path, size_t child_path_len) { \
404 if (!parent) return WALLY_EINVAL; \
405 return wally_map_add_keypath_item(&parent->keypaths, pub_key, pub_key_len, \
406 fingerprint, fingerprint_len, \
407 child_path, child_path_len); \
408 }
409
wally_psbt_input_is_finalized(const struct wally_psbt_input * input,size_t * written)410 int wally_psbt_input_is_finalized(const struct wally_psbt_input *input,
411 size_t *written)
412 {
413 if (written)
414 *written = 0;
415 if (!input || !written)
416 return WALLY_EINVAL;
417 *written = input->final_scriptsig || input->final_witness ? 1 : 0;
418 return WALLY_OK;
419 }
420
SET_STRUCT(wally_psbt_input,utxo,wally_tx,tx_clone_alloc,wally_tx_free)421 SET_STRUCT(wally_psbt_input, utxo, wally_tx,
422 tx_clone_alloc, wally_tx_free)
423 SET_STRUCT(wally_psbt_input, witness_utxo, wally_tx_output,
424 wally_tx_output_clone_alloc, wally_tx_output_free)
425 SET_BYTES(wally_psbt_input, redeem_script)
426 SET_BYTES(wally_psbt_input, witness_script)
427 SET_BYTES(wally_psbt_input, final_scriptsig)
428 SET_STRUCT(wally_psbt_input, final_witness, wally_tx_witness_stack,
429 wally_tx_witness_stack_clone_alloc, wally_tx_witness_stack_free)
430 SET_MAP(wally_psbt_input, keypath, wally_ec_public_key_verify)
431 ADD_KEYPATH(wally_psbt_input)
432 SET_MAP(wally_psbt_input, signature, wally_ec_public_key_verify)
433 SET_MAP(wally_psbt_input, unknown, NULL)
434
435 int wally_psbt_input_set_sighash(struct wally_psbt_input *input, uint32_t sighash)
436 {
437 if (!input)
438 return WALLY_EINVAL;
439 input->sighash = sighash;
440 return WALLY_OK;
441 }
442
443 #ifdef BUILD_ELEMENTS
wally_psbt_input_set_value(struct wally_psbt_input * input,uint64_t value)444 int wally_psbt_input_set_value(struct wally_psbt_input *input, uint64_t value)
445 {
446 if (!input)
447 return WALLY_EINVAL;
448 input->value = value;
449 input->has_value = 1u;
450 return WALLY_OK;
451 }
452
wally_psbt_input_clear_value(struct wally_psbt_input * input)453 int wally_psbt_input_clear_value(struct wally_psbt_input *input)
454 {
455 if (!input)
456 return WALLY_EINVAL;
457 input->value = 0;
458 input->has_value = 0;
459 return WALLY_OK;
460 }
461
SET_BYTES_N(wally_psbt_input,vbf,BLINDING_FACTOR_LEN)462 SET_BYTES_N(wally_psbt_input, vbf, BLINDING_FACTOR_LEN)
463 SET_BYTES_N(wally_psbt_input, asset, ASSET_TAG_LEN)
464 SET_BYTES_N(wally_psbt_input, abf, BLINDING_FACTOR_LEN)
465 SET_STRUCT(wally_psbt_input, pegin_tx, wally_tx,
466 tx_clone_alloc, wally_tx_free)
467 SET_BYTES(wally_psbt_input, txoutproof)
468 SET_BYTES_N(wally_psbt_input, genesis_blockhash, SHA256_LEN)
469 SET_BYTES(wally_psbt_input, claim_script)
470 #endif /* BUILD_ELEMENTS */
471
472 static int psbt_input_free(struct wally_psbt_input *input, bool free_parent)
473 {
474 if (input) {
475 wally_tx_free(input->utxo);
476 wally_tx_output_free(input->witness_utxo);
477 clear_and_free(input->redeem_script, input->redeem_script_len);
478 clear_and_free(input->witness_script, input->witness_script_len);
479 clear_and_free(input->final_scriptsig, input->final_scriptsig_len);
480 wally_tx_witness_stack_free(input->final_witness);
481 wally_map_clear(&input->keypaths);
482 wally_map_clear(&input->signatures);
483 wally_map_clear(&input->unknowns);
484
485 #ifdef BUILD_ELEMENTS
486 clear_and_free(input->vbf, input->vbf_len);
487 clear_and_free(input->asset, input->asset_len);
488 clear_and_free(input->abf, input->abf_len);
489 wally_tx_free(input->pegin_tx);
490 clear_and_free(input->txoutproof, input->txoutproof_len);
491 clear_and_free(input->genesis_blockhash, input->genesis_blockhash_len);
492 clear_and_free(input->claim_script, input->claim_script_len);
493 #endif /* BUILD_ELEMENTS */
494
495 wally_clear(input, sizeof(*input));
496 if (free_parent)
497 wally_free(input);
498 }
499 return WALLY_OK;
500 }
501
SET_BYTES(wally_psbt_output,redeem_script)502 SET_BYTES(wally_psbt_output, redeem_script)
503 SET_BYTES(wally_psbt_output, witness_script)
504 SET_MAP(wally_psbt_output, keypath, wally_ec_public_key_verify)
505 ADD_KEYPATH(wally_psbt_output)
506 SET_MAP(wally_psbt_output, unknown, NULL)
507
508 #ifdef BUILD_ELEMENTS
509 int wally_psbt_output_set_blinding_pubkey(struct wally_psbt_output *output,
510 const unsigned char *pub_key,
511 size_t pub_key_len)
512 {
513 int ret;
514 if (!output || BYTES_INVALID(pub_key, pub_key_len))
515 return WALLY_EINVAL;
516 if (pub_key &&
517 (ret = wally_ec_public_key_verify(pub_key, pub_key_len)) != WALLY_OK)
518 return ret;
519 return replace_bytes(pub_key, pub_key_len,
520 &output->blinding_pubkey, &output->blinding_pubkey_len);
521 }
522
SET_BYTES_N(wally_psbt_output,value_commitment,ASSET_COMMITMENT_LEN)523 SET_BYTES_N(wally_psbt_output, value_commitment, ASSET_COMMITMENT_LEN)
524 SET_BYTES_N(wally_psbt_output, vbf, BLINDING_FACTOR_LEN)
525 SET_BYTES_N(wally_psbt_output, asset_commitment, ASSET_COMMITMENT_LEN)
526 SET_BYTES_N(wally_psbt_output, abf, BLINDING_FACTOR_LEN)
527 SET_BYTES_N(wally_psbt_output, nonce, WALLY_TX_ASSET_CT_NONCE_LEN)
528 SET_BYTES(wally_psbt_output, rangeproof)
529 SET_BYTES(wally_psbt_output, surjectionproof)
530 #endif/* BUILD_ELEMENTS */
531
532 static int psbt_output_free(struct wally_psbt_output *output, bool free_parent)
533 {
534 if (output) {
535 clear_and_free(output->redeem_script, output->redeem_script_len);
536 clear_and_free(output->witness_script, output->witness_script_len);
537 wally_map_clear(&output->keypaths);
538 wally_map_clear(&output->unknowns);
539
540 #ifdef BUILD_ELEMENTS
541 clear_and_free(output->blinding_pubkey, output->blinding_pubkey_len);
542 clear_and_free(output->value_commitment, output->value_commitment_len);
543 clear_and_free(output->vbf, output->vbf_len);
544 clear_and_free(output->asset_commitment, output->asset_commitment_len);
545 clear_and_free(output->abf, output->abf_len);
546 clear_and_free(output->nonce, output->nonce_len);
547 clear_and_free(output->rangeproof, output->rangeproof_len);
548 clear_and_free(output->surjectionproof, output->surjectionproof_len);
549 #endif /* BUILD_ELEMENTS */
550
551 wally_clear(output, sizeof(*output));
552 if (free_parent)
553 wally_free(output);
554 }
555 return WALLY_OK;
556 }
557
wally_psbt_init_alloc(uint32_t version,size_t inputs_allocation_len,size_t outputs_allocation_len,size_t global_unknowns_allocation_len,struct wally_psbt ** output)558 int wally_psbt_init_alloc(uint32_t version, size_t inputs_allocation_len,
559 size_t outputs_allocation_len,
560 size_t global_unknowns_allocation_len,
561 struct wally_psbt **output)
562 {
563 struct wally_psbt *result;
564 int ret;
565
566 TX_CHECK_OUTPUT;
567 if (version)
568 return WALLY_EINVAL; /* Only version 0 is specified/supported */
569 TX_OUTPUT_ALLOC(struct wally_psbt);
570
571 if (inputs_allocation_len)
572 result->inputs = wally_calloc(inputs_allocation_len * sizeof(struct wally_psbt_input));
573 if (outputs_allocation_len)
574 result->outputs = wally_calloc(outputs_allocation_len * sizeof(struct wally_psbt_output));
575
576 ret = wally_map_init(global_unknowns_allocation_len, &result->unknowns);
577
578 if (ret != WALLY_OK ||
579 (inputs_allocation_len && !result->inputs) || (outputs_allocation_len && !result->outputs)) {
580 wally_psbt_free(result);
581 return ret != WALLY_OK ? ret : WALLY_ENOMEM;
582 }
583
584 result->version = version;
585 memcpy(result->magic, PSBT_MAGIC, sizeof(PSBT_MAGIC));
586 result->inputs_allocation_len = inputs_allocation_len;
587 result->outputs_allocation_len = outputs_allocation_len;
588 result->tx = NULL;
589 return WALLY_OK;
590 }
591
592 #ifdef BUILD_ELEMENTS
wally_psbt_elements_init_alloc(uint32_t version,size_t inputs_allocation_len,size_t outputs_allocation_len,size_t global_unknowns_allocation_len,struct wally_psbt ** output)593 int wally_psbt_elements_init_alloc(
594 uint32_t version,
595 size_t inputs_allocation_len,
596 size_t outputs_allocation_len,
597 size_t global_unknowns_allocation_len,
598 struct wally_psbt **output)
599 {
600 int ret = wally_psbt_init_alloc(version, inputs_allocation_len,
601 outputs_allocation_len,
602 global_unknowns_allocation_len, output);
603 if (ret == WALLY_OK)
604 memcpy((*output)->magic, PSET_MAGIC, sizeof(PSET_MAGIC));
605
606 return ret;
607 }
608 #endif /* BUILD_ELEMENTS */
609
wally_psbt_free(struct wally_psbt * psbt)610 int wally_psbt_free(struct wally_psbt *psbt)
611 {
612 size_t i;
613 if (psbt) {
614 wally_tx_free(psbt->tx);
615 for (i = 0; i < psbt->num_inputs; ++i)
616 psbt_input_free(&psbt->inputs[i], false);
617
618 wally_free(psbt->inputs);
619 for (i = 0; i < psbt->num_outputs; ++i)
620 psbt_output_free(&psbt->outputs[i], false);
621
622 wally_free(psbt->outputs);
623 wally_map_clear(&psbt->unknowns);
624 clear_and_free(psbt, sizeof(*psbt));
625 }
626 return WALLY_OK;
627 }
628
wally_psbt_get_global_tx_alloc(const struct wally_psbt * psbt,struct wally_tx ** output)629 int wally_psbt_get_global_tx_alloc(const struct wally_psbt *psbt, struct wally_tx **output)
630 {
631 TX_CHECK_OUTPUT;
632 if (!psbt)
633 return WALLY_EINVAL;
634 if (!psbt->tx)
635 return WALLY_OK; /* Return a NULL tx if not present */
636 return tx_clone_alloc(psbt->tx, output);
637 }
638
639 #define PSBT_GET(name) \
640 int wally_psbt_get_ ## name(const struct wally_psbt *psbt, size_t *written) { \
641 if (written) \
642 *written = 0; \
643 if (!psbt || !written) \
644 return WALLY_EINVAL; \
645 *written = psbt->name; \
646 return WALLY_OK; \
647 }
648
649 PSBT_GET(version)
PSBT_GET(num_inputs)650 PSBT_GET(num_inputs)
651 PSBT_GET(num_outputs)
652
653 int wally_psbt_is_finalized(const struct wally_psbt *psbt,
654 size_t *written)
655 {
656 size_t i;
657
658 if (written)
659 *written = 0;
660 if (!psbt || !written)
661 return WALLY_EINVAL;
662
663 for (i = 0; i < psbt->num_inputs; ++i) {
664 if (!psbt->inputs[i].final_scriptsig && !psbt->inputs[i].final_witness)
665 return WALLY_OK; /* Non fully finalized */
666 }
667 /* We are finalized if we have inputs since they are all finalized */
668 *written = psbt->num_inputs > 0 ? 1 : 0;
669 return WALLY_OK;
670 }
671
psbt_set_global_tx(struct wally_psbt * psbt,struct wally_tx * tx,bool do_clone)672 static int psbt_set_global_tx(struct wally_psbt *psbt, struct wally_tx *tx, bool do_clone)
673 {
674 struct wally_tx *new_tx = NULL;
675 struct wally_psbt_input *new_inputs = NULL;
676 struct wally_psbt_output *new_outputs = NULL;
677 size_t i;
678 int ret;
679
680 if (!psbt || psbt->tx || psbt->num_inputs || psbt->num_outputs || !tx)
681 return WALLY_EINVAL; /* PSBT must be completely empty */
682
683 for (i = 0; i < tx->num_inputs; ++i)
684 if (tx->inputs[i].script || tx->inputs[i].witness)
685 return WALLY_EINVAL; /* tx mustn't have scriptSigs or witnesses */
686
687 if (do_clone && (ret = tx_clone_alloc(tx, &new_tx)) != WALLY_OK)
688 return ret;
689
690 if (psbt->inputs_allocation_len < tx->num_inputs)
691 new_inputs = wally_calloc(tx->num_inputs * sizeof(struct wally_psbt_input));
692
693 if (psbt->outputs_allocation_len < tx->num_outputs)
694 new_outputs = wally_calloc(tx->num_outputs * sizeof(struct wally_psbt_output));
695
696 if ((psbt->inputs_allocation_len < tx->num_inputs && !new_inputs) ||
697 (psbt->outputs_allocation_len < tx->num_outputs && !new_outputs)) {
698 wally_free(new_inputs);
699 wally_free(new_outputs);
700 wally_tx_free(new_tx);
701 return WALLY_ENOMEM;
702 }
703
704 if (new_inputs) {
705 wally_free(psbt->inputs);
706 psbt->inputs = new_inputs;
707 psbt->inputs_allocation_len = tx->num_inputs;
708 }
709 if (new_outputs) {
710 wally_free(psbt->outputs);
711 psbt->outputs = new_outputs;
712 psbt->outputs_allocation_len = tx->num_outputs;
713 }
714 psbt->num_inputs = tx->num_inputs;
715 psbt->num_outputs = tx->num_outputs;
716 psbt->tx = do_clone ? new_tx : tx;
717 return WALLY_OK;
718 }
719
wally_psbt_set_global_tx(struct wally_psbt * psbt,const struct wally_tx * tx)720 int wally_psbt_set_global_tx(struct wally_psbt *psbt, const struct wally_tx *tx)
721 {
722 return psbt_set_global_tx(psbt, (struct wally_tx *)tx, true);
723 }
724
wally_psbt_add_input_at(struct wally_psbt * psbt,uint32_t index,uint32_t flags,const struct wally_tx_input * input)725 int wally_psbt_add_input_at(struct wally_psbt *psbt,
726 uint32_t index, uint32_t flags,
727 const struct wally_tx_input *input)
728 {
729 struct wally_tx_input tmp;
730 int ret;
731
732 if (!psbt || !psbt->tx || psbt->tx->num_inputs != psbt->num_inputs ||
733 (flags & ~WALLY_PSBT_FLAG_NON_FINAL) ||
734 index > psbt->num_inputs || !input)
735 return WALLY_EINVAL;
736
737 memcpy(&tmp, input, sizeof(tmp));
738 if (flags & WALLY_PSBT_FLAG_NON_FINAL) {
739 /* Clear scriptSig and witness before adding */
740 tmp.script = NULL;
741 tmp.script_len = 0;
742 tmp.witness = NULL;
743 }
744 ret = wally_tx_add_input_at(psbt->tx, index, &tmp);
745 wally_clear(&tmp, sizeof(tmp));
746
747 if (ret == WALLY_OK) {
748 if (psbt->num_inputs >= psbt->inputs_allocation_len) {
749 ret = array_grow((void *)&psbt->inputs, psbt->num_inputs,
750 &psbt->inputs_allocation_len,
751 sizeof(struct wally_psbt_input));
752 if (ret != WALLY_OK) {
753 wally_tx_remove_input(psbt->tx, index);
754 return ret;
755 }
756 }
757
758 memmove(psbt->inputs + index + 1, psbt->inputs + index,
759 (psbt->num_inputs - index) * sizeof(struct wally_psbt_input));
760 wally_clear(psbt->inputs + index, sizeof(struct wally_psbt_input));
761 psbt->num_inputs += 1;
762 }
763 return ret;
764 }
765
wally_psbt_remove_input(struct wally_psbt * psbt,uint32_t index)766 int wally_psbt_remove_input(struct wally_psbt *psbt, uint32_t index)
767 {
768 int ret;
769
770 if (!psbt || !psbt->tx || psbt->tx->num_inputs != psbt->num_inputs)
771 ret = WALLY_EINVAL;
772 else
773 ret = wally_tx_remove_input(psbt->tx, index);
774 if (ret == WALLY_OK) {
775 psbt_input_free(&psbt->inputs[index], false);
776 memmove(psbt->inputs + index, psbt->inputs + index + 1,
777 (psbt->num_inputs - index - 1) * sizeof(struct wally_psbt_input));
778 psbt->num_inputs -= 1;
779 }
780 return ret;
781 }
782
wally_psbt_add_output_at(struct wally_psbt * psbt,uint32_t index,uint32_t flags,const struct wally_tx_output * output)783 int wally_psbt_add_output_at(struct wally_psbt *psbt,
784 uint32_t index, uint32_t flags,
785 const struct wally_tx_output *output)
786 {
787 int ret;
788
789 if (!psbt || !psbt->tx || psbt->tx->num_outputs != psbt->num_outputs ||
790 flags || index > psbt->num_outputs || !output)
791 return WALLY_EINVAL;
792
793 ret = wally_tx_add_output_at(psbt->tx, index, output);
794
795 if (ret == WALLY_OK) {
796 if (psbt->num_outputs >= psbt->outputs_allocation_len) {
797 ret = array_grow((void *)&psbt->outputs, psbt->num_outputs,
798 &psbt->outputs_allocation_len,
799 sizeof(struct wally_psbt_output));
800 if (ret != WALLY_OK) {
801 wally_tx_remove_output(psbt->tx, index);
802 return ret;
803 }
804 }
805
806 memmove(psbt->outputs + index + 1, psbt->outputs + index,
807 (psbt->num_outputs - index) * sizeof(struct wally_psbt_output));
808 wally_clear(psbt->outputs + index, sizeof(struct wally_psbt_output));
809 psbt->num_outputs += 1;
810 }
811 return ret;
812 }
813
wally_psbt_remove_output(struct wally_psbt * psbt,uint32_t index)814 int wally_psbt_remove_output(struct wally_psbt *psbt, uint32_t index)
815 {
816 int ret;
817
818 if (!psbt || !psbt->tx || psbt->tx->num_outputs != psbt->num_outputs)
819 ret = WALLY_EINVAL;
820 else
821 ret = wally_tx_remove_output(psbt->tx, index);
822 if (ret == WALLY_OK) {
823 psbt_output_free(&psbt->outputs[index], false);
824 memmove(psbt->outputs + index, psbt->outputs + index + 1,
825 (psbt->num_outputs - index - 1) * sizeof(struct wally_psbt_output));
826 psbt->num_outputs -= 1;
827 }
828 return ret;
829 }
830
831
832 /* Stricter version of pull_subfield_end which insists there's nothing left. */
subfield_nomore_end(const unsigned char ** cursor,size_t * max,const unsigned char * subcursor,const size_t submax)833 static void subfield_nomore_end(const unsigned char **cursor, size_t *max,
834 const unsigned char *subcursor,
835 const size_t submax)
836 {
837 if (submax) {
838 pull_failed(cursor, max);
839 } else {
840 pull_subfield_end(cursor, max, subcursor, submax);
841 }
842 }
843
844 /* The remainder of the key is a public key, the value is a signature */
pull_map(const unsigned char ** cursor,size_t * max,const unsigned char * key,size_t key_len,struct wally_map * map_in,int (* check_fn)(const unsigned char * key,size_t key_len))845 static int pull_map(const unsigned char **cursor, size_t *max,
846 const unsigned char *key, size_t key_len,
847 struct wally_map *map_in,
848 int (*check_fn)(const unsigned char *key, size_t key_len))
849 {
850 const unsigned char *val;
851 size_t val_len;
852
853 pull_subfield_end(cursor, max, key, key_len);
854
855 val_len = pull_varlength(cursor, max);
856 val = pull_skip(cursor, max, val_len);
857
858 return map_add(map_in, key, key_len, val, val_len, false, check_fn, false);
859 }
860
861 /* Rewind cursor to prekey, and append unknown key/value to unknowns */
pull_unknown_key_value(const unsigned char ** cursor,size_t * max,const unsigned char * pre_key,struct wally_map * unknowns)862 static int pull_unknown_key_value(const unsigned char **cursor, size_t *max,
863 const unsigned char *pre_key,
864 struct wally_map *unknowns)
865 {
866 const unsigned char *key, *val;
867 size_t key_len, val_len;
868
869 /* If we've already failed, it's invalid */
870 if (!*cursor)
871 return WALLY_EINVAL;
872
873 /* We have to unwind a bit, to get entire key again. */
874 *max += (*cursor - pre_key);
875 *cursor = pre_key;
876
877 key_len = pull_varlength(cursor, max);
878 key = pull_skip(cursor, max, key_len);
879 val_len = pull_varlength(cursor, max);
880 val = pull_skip(cursor, max, val_len);
881
882 return map_add(unknowns, key, key_len, val, val_len, false, NULL, false);
883 }
884
885 #ifdef BUILD_ELEMENTS
push_elements_bytes_size(const struct wally_tx_output * out)886 static size_t push_elements_bytes_size(const struct wally_tx_output *out)
887 {
888 size_t size = 0;
889 size += out->asset_len == 0 ? 1 : out->asset_len;
890 size += out->value_len == 0 ? 1 : out->value_len;
891 size += out->nonce_len == 0 ? 1 : out->nonce_len;
892 size += out->script_len == 0 ? 1 : out->script_len + 1;
893 return size;
894 }
895
push_elements_bytes(unsigned char ** cursor,size_t * max,unsigned char * value,size_t val_len)896 static void push_elements_bytes(unsigned char **cursor, size_t *max,
897 unsigned char *value, size_t val_len)
898 {
899 unsigned char empty = 0;
900 push_bytes(cursor, max, value ? value : &empty, value ? val_len : sizeof(empty));
901 }
902
pull_elements_confidential(const unsigned char ** cursor,size_t * max,const unsigned char ** value,size_t * val_len,size_t prefixA,size_t prefixB,size_t prefixed_size,size_t explicit_size)903 static int pull_elements_confidential(const unsigned char **cursor, size_t *max,
904 const unsigned char **value, size_t *val_len,
905 size_t prefixA, size_t prefixB,
906 size_t prefixed_size, size_t explicit_size)
907 {
908 /* First byte is always the 'version' which tells you what the value is */
909 const uint8_t type = peek_u8(cursor, max);
910 size_t size;
911
912 if (type == 0) {
913 /* Empty, Pop off the type */
914 pull_u8(cursor, max);
915 *value = NULL;
916 *val_len = 0;
917 return WALLY_OK;
918 }
919
920 if (type == 1)
921 size = explicit_size;
922 else if (type == prefixA || type == prefixB)
923 size = prefixed_size;
924 else
925 return WALLY_EINVAL;
926
927 *value = pull_skip(cursor, max, size);
928 if (!*cursor)
929 return WALLY_EINVAL;
930 *val_len = size;
931 return WALLY_OK;
932 }
933
934 /* Either returns a 33-byte commitment to a confidential value, or
935 * a 64-bit explicit value. */
pull_confidential_value(const unsigned char ** cursor,size_t * max,const unsigned char ** value,size_t * val_len)936 static int pull_confidential_value(const unsigned char **cursor, size_t *max,
937 const unsigned char **value, size_t *val_len)
938
939 {
940 return pull_elements_confidential(cursor, max, value, val_len,
941 WALLY_TX_ASSET_CT_VALUE_PREFIX_A, WALLY_TX_ASSET_CT_VALUE_PREFIX_B,
942 WALLY_TX_ASSET_CT_VALUE_LEN, WALLY_TX_ASSET_CT_VALUE_UNBLIND_LEN);
943 }
944
pull_confidential_asset(const unsigned char ** cursor,size_t * max,const unsigned char ** asset,size_t * asset_len)945 static int pull_confidential_asset(const unsigned char **cursor, size_t *max,
946 const unsigned char **asset, size_t *asset_len)
947
948 {
949 return pull_elements_confidential(cursor, max, asset, asset_len,
950 WALLY_TX_ASSET_CT_ASSET_PREFIX_A, WALLY_TX_ASSET_CT_ASSET_PREFIX_B,
951 WALLY_TX_ASSET_CT_ASSET_LEN, WALLY_TX_ASSET_CT_ASSET_LEN);
952 }
953
pull_nonce(const unsigned char ** cursor,size_t * max,const unsigned char ** nonce,size_t * nonce_len)954 static int pull_nonce(const unsigned char **cursor, size_t *max,
955 const unsigned char **nonce, size_t *nonce_len)
956
957 {
958 return pull_elements_confidential(cursor, max, nonce, nonce_len,
959 WALLY_TX_ASSET_CT_NONCE_PREFIX_A, WALLY_TX_ASSET_CT_NONCE_PREFIX_B,
960 WALLY_TX_ASSET_CT_NONCE_LEN, WALLY_TX_ASSET_CT_NONCE_LEN);
961 }
962
963 #endif /* BUILD_ELEMENTS */
964
fetch_varlength_ptr(const unsigned char ** dst,size_t * len,const unsigned char ** cursor,size_t * max)965 static void fetch_varlength_ptr(const unsigned char **dst, size_t *len,
966 const unsigned char **cursor, size_t *max)
967 {
968 *len = pull_varlength(cursor, max);
969 *dst = pull_skip(cursor, max, *len);
970 }
971
972 /* Pull and set a variable length byte buffer */
973 #define PSBT_PULL_B(typ, name) \
974 if (result->name) \
975 return WALLY_EINVAL; /* Duplicate value */ \
976 subfield_nomore_end(cursor, max, key, key_len); \
977 fetch_varlength_ptr(&vl_p, &vl_len, cursor, max); \
978 if (!vl_len) \
979 result->name = wally_malloc(1); /* TODO: handle empty values more elegantly */ \
980 else if ((ret = wally_psbt_ ## typ ## _set_ ## name(result, vl_p, vl_len)) != WALLY_OK) \
981 return ret
982
pull_psbt_input(const unsigned char ** cursor,size_t * max,uint32_t flags,struct wally_psbt_input * result)983 static int pull_psbt_input(const unsigned char **cursor, size_t *max,
984 uint32_t flags, struct wally_psbt_input *result)
985 {
986 int ret;
987 size_t key_len, vl_len;
988 const unsigned char *pre_key, *vl_p;
989
990 /* Read key value pairs */
991 pre_key = *cursor;
992 while ((key_len = pull_varlength(cursor, max)) != 0) {
993 const unsigned char *key, *val;
994 size_t val_max;
995
996 /* Start parsing key */
997 pull_subfield_start(cursor, max, key_len, &key, &key_len);
998
999 /* Process based on type */
1000 switch (pull_varint(&key, &key_len)) {
1001 case PSBT_IN_NON_WITNESS_UTXO: {
1002 if (result->utxo)
1003 return WALLY_EINVAL; /* We already have a non witness utxo */
1004
1005 subfield_nomore_end(cursor, max, key, key_len);
1006
1007 /* Start parsing the value field. */
1008 pull_subfield_start(cursor, max, pull_varint(cursor, max),
1009 &val, &val_max);
1010 if ((ret = wally_tx_from_bytes(val, val_max, flags,
1011 &result->utxo)) != WALLY_OK)
1012 return ret;
1013
1014 pull_subfield_end(cursor, max, val, val_max);
1015 break;
1016 }
1017 case PSBT_IN_WITNESS_UTXO: {
1018 uint64_t amount, script_len;
1019 const unsigned char *script;
1020
1021 if (result->witness_utxo)
1022 return WALLY_EINVAL; /* Duplicate value */
1023
1024 subfield_nomore_end(cursor, max, key, key_len);
1025
1026 /* Start parsing the value field. */
1027 pull_subfield_start(cursor, max, pull_varint(cursor, max),
1028 &val, &val_max);
1029 #ifdef BUILD_ELEMENTS
1030 if (flags & WALLY_TX_FLAG_USE_ELEMENTS) {
1031 const unsigned char *asset, *value, *nonce;
1032 size_t asset_len, value_len, nonce_len;
1033 if ((ret = pull_confidential_asset(&val, &val_max, &asset, &asset_len)) != WALLY_OK)
1034 return ret;
1035 if ((ret = pull_confidential_value(&val, &val_max, &value, &value_len)) != WALLY_OK)
1036 return ret;
1037 if ((ret = pull_nonce(&val, &val_max, &nonce, &nonce_len)) != WALLY_OK)
1038 return ret;
1039
1040 script_len = pull_varint(&val, &val_max);
1041 script = pull_skip(&val, &val_max, script_len);
1042 if (!script || !script_len)
1043 return WALLY_EINVAL;
1044
1045 ret = wally_tx_elements_output_init_alloc(script, script_len,
1046 asset, asset_len,
1047 value, value_len,
1048 nonce, nonce_len,
1049 NULL, 0, NULL, 0,
1050 &result->witness_utxo);
1051 if (ret != WALLY_OK)
1052 return ret;
1053
1054 subfield_nomore_end(cursor, max, val, val_max);
1055 break;
1056 }
1057 #endif /* BUILD_ELEMENTS */
1058
1059 amount = pull_le64(&val, &val_max);
1060 script_len = pull_varint(&val, &val_max);
1061 script = pull_skip(&val, &val_max, script_len);
1062 if (!script || !script_len)
1063 return WALLY_EINVAL;
1064 ret = wally_tx_output_init_alloc(amount, script, script_len,
1065 &result->witness_utxo);
1066 if (ret != WALLY_OK)
1067 return ret;
1068
1069 subfield_nomore_end(cursor, max, val, val_max);
1070 break;
1071 }
1072 case PSBT_IN_PARTIAL_SIG: {
1073 ret = pull_map(cursor, max, key, key_len, &result->signatures,
1074 wally_ec_public_key_verify);
1075 if (ret != WALLY_OK)
1076 return ret;
1077 break;
1078 }
1079 case PSBT_IN_SIGHASH_TYPE: {
1080 if (result->sighash != 0)
1081 return WALLY_EINVAL; /* Duplicate value */
1082
1083 subfield_nomore_end(cursor, max, key, key_len);
1084
1085 /* Start parsing the value field. */
1086 pull_subfield_start(cursor, max,
1087 pull_varint(cursor, max),
1088 &val, &val_max);
1089 result->sighash = pull_le32(&val, &val_max);
1090 subfield_nomore_end(cursor, max, val, val_max);
1091 break;
1092 }
1093 case PSBT_IN_REDEEM_SCRIPT:
1094 PSBT_PULL_B(input, redeem_script);
1095 break;
1096 case PSBT_IN_WITNESS_SCRIPT:
1097 PSBT_PULL_B(input, witness_script);
1098 break;
1099 case PSBT_IN_BIP32_DERIVATION:
1100 if ((ret = pull_map(cursor, max, key, key_len, &result->keypaths,
1101 wally_ec_public_key_verify)) != WALLY_OK)
1102 return ret;
1103 break;
1104 case PSBT_IN_FINAL_SCRIPTSIG:
1105 PSBT_PULL_B(input, final_scriptsig);
1106 break;
1107 case PSBT_IN_FINAL_SCRIPTWITNESS: {
1108 uint64_t num_witnesses;
1109 size_t i;
1110 if (result->final_witness)
1111 return WALLY_EINVAL; /* Duplicate value */
1112 subfield_nomore_end(cursor, max, key, key_len);
1113
1114 /* Start parsing the value field. */
1115 pull_subfield_start(cursor, max,
1116 pull_varint(cursor, max),
1117 &val, &val_max);
1118 num_witnesses = pull_varint(&val, &val_max);
1119 ret = wally_tx_witness_stack_init_alloc(num_witnesses, &result->final_witness);
1120 if (ret != WALLY_OK)
1121 return ret;
1122
1123 for (i = 0; i < num_witnesses; ++i) {
1124 uint64_t witness_len = pull_varint(&val, &val_max);
1125 ret = wally_tx_witness_stack_set(result->final_witness, i,
1126 pull_skip(&val, &val_max, witness_len),
1127 witness_len);
1128 if (ret != WALLY_OK)
1129 return ret;
1130 }
1131 subfield_nomore_end(cursor, max, val, val_max);
1132 break;
1133 }
1134 #ifdef BUILD_ELEMENTS
1135 case PSBT_PROPRIETARY_TYPE: {
1136 const uint64_t id_len = pull_varlength(&key, &key_len);
1137
1138 if (!is_elements_prefix(key, id_len))
1139 goto unknown_type;
1140
1141 /* Skip the elements_id prefix */
1142 pull_skip(&key, &key_len, sizeof(PSET_KEY_PREFIX));
1143
1144 switch (pull_varint(&key, &key_len)) {
1145 case PSET_IN_VALUE: {
1146 if (result->has_value)
1147 return WALLY_EINVAL; /* Duplicate value */
1148
1149 subfield_nomore_end(cursor, max, key, key_len);
1150
1151 /* Start parsing the value field. */
1152 pull_subfield_start(cursor, max, pull_varint(cursor, max),
1153 &val, &val_max);
1154 result->value = pull_le64(&val, &val_max);
1155 subfield_nomore_end(cursor, max, val, val_max);
1156 result->has_value = true;
1157 break;
1158 }
1159 case PSET_IN_VALUE_BLINDER:
1160 PSBT_PULL_B(input, vbf);
1161 break;
1162 case PSET_IN_ASSET:
1163 PSBT_PULL_B(input, asset);
1164 break;
1165 case PSET_IN_ASSET_BLINDER:
1166 PSBT_PULL_B(input, abf);
1167 break;
1168 case PSET_IN_PEG_IN_TX: {
1169 if (result->pegin_tx)
1170 return WALLY_EINVAL; /* Duplicate value */
1171
1172 subfield_nomore_end(cursor, max, key, key_len);
1173
1174 /* Start parsing the value field. */
1175 pull_subfield_start(cursor, max,
1176 pull_varint(cursor, max),
1177 &val, &val_max);
1178
1179 ret = wally_tx_from_bytes(val, val_max, flags, &result->pegin_tx);
1180 if (ret != WALLY_OK)
1181 return ret;
1182
1183 pull_subfield_end(cursor, max, val, val_max);
1184 break;
1185 }
1186 case PSET_IN_TXOUT_PROOF:
1187 PSBT_PULL_B(input, txoutproof);
1188 break;
1189 case PSET_IN_GENESIS_HASH:
1190 PSBT_PULL_B(input, genesis_blockhash);
1191 break;
1192 case PSET_IN_CLAIM_SCRIPT:
1193 PSBT_PULL_B(input, claim_script);
1194 break;
1195 default:
1196 goto unknown_type;
1197 }
1198 break;
1199 }
1200 #endif /* BUILD_ELEMENTS */
1201 default: {
1202 unknown_type:
1203 /* Unknown case without elements or for unknown proprietary types */
1204 ret = pull_unknown_key_value(cursor, max, pre_key, &result->unknowns);
1205 if (ret != WALLY_OK)
1206 return ret;
1207 break;
1208 }
1209 }
1210 pre_key = *cursor;
1211 }
1212
1213 return WALLY_OK;
1214 }
1215
pull_psbt_output(const unsigned char ** cursor,size_t * max,struct wally_psbt_output * result)1216 static int pull_psbt_output(const unsigned char **cursor, size_t *max,
1217 struct wally_psbt_output *result)
1218 {
1219 int ret;
1220 size_t key_len, vl_len;
1221 const unsigned char *pre_key, *vl_p;
1222
1223 /* Read key value */
1224 pre_key = *cursor;
1225 while ((key_len = pull_varlength(cursor, max)) != 0) {
1226 const unsigned char *key;
1227
1228 /* Start parsing key */
1229 pull_subfield_start(cursor, max, key_len, &key, &key_len);
1230
1231 /* Process based on type */
1232 switch (pull_varint(&key, &key_len)) {
1233 case PSBT_OUT_REDEEM_SCRIPT:
1234 PSBT_PULL_B(output, redeem_script);
1235 break;
1236 case PSBT_OUT_WITNESS_SCRIPT:
1237 PSBT_PULL_B(output, witness_script);
1238 break;
1239 case PSBT_OUT_BIP32_DERIVATION:
1240 if ((ret = pull_map(cursor, max, key, key_len, &result->keypaths,
1241 wally_ec_public_key_verify)) != WALLY_OK)
1242 return ret;
1243 break;
1244 #ifdef BUILD_ELEMENTS
1245 case PSBT_PROPRIETARY_TYPE: {
1246 const uint64_t id_len = pull_varlength(&key, &key_len);
1247
1248 if (!is_elements_prefix(key, id_len))
1249 goto unknown_type;
1250
1251 /* Skip the elements_id prefix */
1252 pull_skip(&key, &key_len, sizeof(PSET_KEY_PREFIX));
1253
1254 switch (pull_varint(&key, &key_len)) {
1255 case PSET_OUT_VALUE_COMMITMENT:
1256 PSBT_PULL_B(output, value_commitment);
1257 break;
1258 case PSET_OUT_VALUE_BLINDER:
1259 PSBT_PULL_B(output, vbf);
1260 break;
1261 case PSET_OUT_ASSET_COMMITMENT:
1262 PSBT_PULL_B(output, asset_commitment);
1263 break;
1264 case PSET_OUT_ASSET_BLINDER:
1265 PSBT_PULL_B(output, abf);
1266 break;
1267 case PSET_OUT_RANGE_PROOF:
1268 PSBT_PULL_B(output, rangeproof);
1269 break;
1270 case PSET_OUT_SURJECTION_PROOF:
1271 PSBT_PULL_B(output, surjectionproof);
1272 break;
1273 case PSET_OUT_BLINDING_PUBKEY:
1274 PSBT_PULL_B(output, blinding_pubkey);
1275 break;
1276 case PSET_OUT_NONCE_COMMITMENT:
1277 PSBT_PULL_B(output, nonce);
1278 break;
1279 default:
1280 goto unknown_type;
1281 }
1282 break;
1283 }
1284 #endif /* BUILD_ELEMENTS */
1285 default: {
1286 unknown_type:
1287 /* Unknown case without elements or for unknown proprietary types */
1288 ret = pull_unknown_key_value(cursor, max, pre_key, &result->unknowns);
1289 if (ret != WALLY_OK)
1290 return ret;
1291 break;
1292 }
1293 }
1294 pre_key = *cursor;
1295 }
1296
1297 return WALLY_OK;
1298 }
1299
wally_psbt_from_bytes(const unsigned char * bytes,size_t len,struct wally_psbt ** output)1300 int wally_psbt_from_bytes(const unsigned char *bytes, size_t len,
1301 struct wally_psbt **output)
1302 {
1303 const unsigned char *magic, *pre_key;
1304 int ret;
1305 size_t i, key_len;
1306 struct wally_psbt *result = NULL;
1307 uint32_t flags = 0, pre144flag = WALLY_TX_FLAG_PRE_BIP144;
1308
1309 TX_CHECK_OUTPUT;
1310
1311 magic = pull_skip(&bytes, &len, sizeof(PSBT_MAGIC));
1312 if (!magic) {
1313 ret = WALLY_EINVAL; /* Not enough bytes */
1314 goto fail;
1315 }
1316 if (memcmp(magic, PSBT_MAGIC, sizeof(PSBT_MAGIC)) != 0 ) {
1317 #ifdef BUILD_ELEMENTS
1318 if (memcmp(magic, PSET_MAGIC, sizeof(PSET_MAGIC)) != 0) {
1319 ret = WALLY_EINVAL; /* Invalid Magic */
1320 goto fail;
1321 }
1322 flags |= WALLY_TX_FLAG_USE_ELEMENTS;
1323 pre144flag = 0;
1324 #else
1325 ret = WALLY_EINVAL; /* Invalid Magic */
1326 goto fail;
1327 #endif /* BUILD_ELEMENTS */
1328 }
1329
1330 /* Make the wally_psbt */
1331 if ((ret = wally_psbt_init_alloc(0, 0, 0, 8, &result)) != WALLY_OK)
1332 goto fail;
1333
1334 /* Set the magic */
1335 memcpy(result->magic, magic, sizeof(PSBT_MAGIC));
1336
1337 /* Read globals first */
1338 pre_key = bytes;
1339 while ((key_len = pull_varlength(&bytes, &len)) != 0) {
1340 const unsigned char *key, *val;
1341 size_t val_max;
1342
1343 /* Start parsing key */
1344 pull_subfield_start(&bytes, &len, key_len, &key, &key_len);
1345
1346 /* Process based on type */
1347 switch (pull_varint(&key, &key_len)) {
1348 case PSBT_GLOBAL_UNSIGNED_TX: {
1349 struct wally_tx *tx;
1350
1351 subfield_nomore_end(&bytes, &len, key, key_len);
1352
1353 /* Start parsing the value field. */
1354 pull_subfield_start(&bytes, &len,
1355 pull_varint(&bytes, &len),
1356 &val, &val_max);
1357 ret = wally_tx_from_bytes(val, val_max, flags | pre144flag, &tx);
1358 if (ret == WALLY_OK) {
1359 ret = psbt_set_global_tx(result, tx, false);
1360 if (ret != WALLY_OK)
1361 wally_tx_free(tx);
1362 }
1363 if (ret != WALLY_OK)
1364 goto fail;
1365 pull_subfield_end(&bytes, &len, val, val_max);
1366 break;
1367 }
1368 case PSBT_GLOBAL_VERSION: {
1369 if (result->version > 0) {
1370 ret = WALLY_EINVAL; /* Version already provided */
1371 goto fail;
1372 }
1373 subfield_nomore_end(&bytes, &len, key, key_len);
1374
1375 /* Start parsing the value field. */
1376 pull_subfield_start(&bytes, &len,
1377 pull_varint(&bytes, &len),
1378 &val, &val_max);
1379 result->version = pull_le32(&val, &val_max);
1380 subfield_nomore_end(&bytes, &len, val, val_max);
1381 if (result->version > WALLY_PSBT_HIGHEST_VERSION) {
1382 ret = WALLY_EINVAL; /* Unsupported version number */
1383 goto fail;
1384 }
1385 break;
1386 }
1387 /* Unknowns */
1388 default: {
1389 ret = pull_unknown_key_value(&bytes, &len, pre_key, &result->unknowns);
1390 if (ret != WALLY_OK)
1391 goto fail;
1392 break;
1393 }
1394 }
1395 pre_key = bytes;
1396 }
1397
1398 /* We don't technically need to test here, but it's a minor optimization */
1399 if (!bytes) {
1400 ret = WALLY_EINVAL; /* Missing global separator */
1401 goto fail;
1402 }
1403
1404 if (!result->tx) {
1405 ret = WALLY_EINVAL; /* No global tx */
1406 goto fail;
1407 }
1408
1409 /* Read inputs */
1410 for (i = 0; i < result->tx->num_inputs; ++i) {
1411 ret = pull_psbt_input(&bytes, &len, flags, &result->inputs[i]);
1412 if (ret != WALLY_OK)
1413 goto fail;
1414 }
1415
1416 /* Read outputs */
1417 for (i = 0; i < result->tx->num_outputs; ++i) {
1418 ret = pull_psbt_output(&bytes, &len, &result->outputs[i]);
1419 if (ret != WALLY_OK)
1420 goto fail;
1421 }
1422
1423 /* If we ran out of data anywhere, fail. */
1424 if (!bytes) {
1425 ret = WALLY_EINVAL;
1426 goto fail;
1427 }
1428
1429 *output = result;
1430 return WALLY_OK;
1431
1432 fail:
1433 wally_psbt_free(result);
1434 return ret;
1435 }
1436
wally_psbt_get_length(const struct wally_psbt * psbt,uint32_t flags,size_t * written)1437 int wally_psbt_get_length(const struct wally_psbt *psbt, uint32_t flags, size_t *written)
1438 {
1439 return wally_psbt_to_bytes(psbt, flags, NULL, 0, written);
1440 }
1441
1442 /* Literally a varbuff containing only type as a varint, then optional data */
push_psbt_key(unsigned char ** cursor,size_t * max,uint64_t type,const void * extra,size_t extra_len)1443 static void push_psbt_key(unsigned char **cursor, size_t *max,
1444 uint64_t type, const void *extra, size_t extra_len)
1445 {
1446 push_varint(cursor, max, varint_get_length(type) + extra_len);
1447 push_varint(cursor, max, type);
1448 push_bytes(cursor, max, extra, extra_len);
1449 }
1450
1451 #ifdef BUILD_ELEMENTS
1452 /* Common case of pushing elements proprietary type keys */
push_elements_key(unsigned char ** cursor,size_t * max,uint64_t type)1453 static void push_elements_key(unsigned char **cursor, size_t *max,
1454 uint64_t type)
1455 {
1456 push_varint(cursor, max, varint_get_length(PSBT_PROPRIETARY_TYPE)
1457 + varint_get_length(sizeof(PSET_KEY_PREFIX))
1458 + sizeof(PSET_KEY_PREFIX) + varint_get_length(type));
1459 push_varint(cursor, max, PSBT_PROPRIETARY_TYPE);
1460 push_varbuff(cursor, max, PSET_KEY_PREFIX, sizeof(PSET_KEY_PREFIX));
1461 push_varint(cursor, max, type);
1462 }
1463
push_elements_varbuff(unsigned char ** cursor,size_t * max,uint64_t type,const unsigned char * bytes,size_t bytes_len)1464 static void push_elements_varbuff(unsigned char **cursor, size_t *max,
1465 uint64_t type,
1466 const unsigned char *bytes, size_t bytes_len)
1467 {
1468 /* Note that due to dummy mallocs, bytes can be non-NULL while
1469 * bytes_len is 0. This represents a present-but-empty varbuff.
1470 */
1471 if (bytes) {
1472 push_elements_key(cursor, max, type);
1473 push_varbuff(cursor, max, bytes, bytes_len);
1474 }
1475 }
1476
1477 #endif /* BUILD_ELEMENTS */
1478
push_length_and_tx(unsigned char ** cursor,size_t * max,const struct wally_tx * tx,uint32_t flags)1479 static int push_length_and_tx(unsigned char **cursor, size_t *max,
1480 const struct wally_tx *tx, uint32_t flags)
1481 {
1482 int ret;
1483 size_t tx_len;
1484 unsigned char *p;
1485
1486 if ((ret = wally_tx_get_length(tx, flags, &tx_len)) != WALLY_OK)
1487 return ret;
1488
1489 push_varint(cursor, max, tx_len);
1490
1491 /* TODO: convert wally_tx to use push */
1492 if (!(p = push_bytes(cursor, max, NULL, tx_len)))
1493 return WALLY_OK; /* We catch this in caller. */
1494
1495 return wally_tx_to_bytes(tx, flags, p, tx_len, &tx_len);
1496 }
1497
push_witness_stack(unsigned char ** cursor,size_t * max,const struct wally_tx_witness_stack * witness)1498 static void push_witness_stack(unsigned char **cursor, size_t *max,
1499 const struct wally_tx_witness_stack *witness)
1500 {
1501 size_t i;
1502
1503 push_varint(cursor, max, witness->num_items);
1504 for (i = 0; i < witness->num_items; ++i) {
1505 push_varbuff(cursor, max, witness->items[i].witness,
1506 witness->items[i].witness_len);
1507 }
1508 }
1509
push_typed_map(unsigned char ** cursor,size_t * max,uint64_t type,const struct wally_map * map_in)1510 static void push_typed_map(unsigned char **cursor, size_t *max,
1511 uint64_t type, const struct wally_map *map_in)
1512 {
1513 size_t i;
1514 for (i = 0; i < map_in->num_items; ++i) {
1515 const struct wally_map_item *item = &map_in->items[i];
1516 push_psbt_key(cursor, max, type, item->key, item->key_len);
1517 push_varbuff(cursor, max, item->value, item->value_len);
1518 }
1519 }
1520
push_typed_varbuff(unsigned char ** cursor,size_t * max,uint64_t type,const unsigned char * bytes,size_t bytes_len)1521 static void push_typed_varbuff(unsigned char **cursor, size_t *max,
1522 uint64_t type,
1523 const unsigned char *bytes, size_t bytes_len)
1524 {
1525 if (bytes) {
1526 push_psbt_key(cursor, max, type, NULL, 0);
1527 push_varbuff(cursor, max, bytes, bytes_len);
1528 }
1529 }
1530
push_map(unsigned char ** cursor,size_t * max,const struct wally_map * map_in)1531 static void push_map(unsigned char **cursor, size_t *max,
1532 const struct wally_map *map_in)
1533 {
1534 size_t i;
1535 for (i = 0; i < map_in->num_items; ++i) {
1536 const struct wally_map_item *item = &map_in->items[i];
1537 push_varbuff(cursor, max, item->key, item->key_len);
1538 push_varbuff(cursor, max, item->value, item->value_len);
1539 }
1540 }
1541
push_psbt_input(unsigned char ** cursor,size_t * max,uint32_t flags,const struct wally_psbt_input * input)1542 static int push_psbt_input(unsigned char **cursor, size_t *max, uint32_t flags,
1543 const struct wally_psbt_input *input)
1544 {
1545 int ret;
1546
1547 (void)flags;
1548
1549 /* Non witness utxo */
1550 if (input->utxo) {
1551 push_psbt_key(cursor, max, PSBT_IN_NON_WITNESS_UTXO, NULL, 0);
1552 if ((ret = push_length_and_tx(cursor, max,
1553 input->utxo,
1554 WALLY_TX_FLAG_USE_WITNESS)) != WALLY_OK)
1555 return ret;
1556 }
1557
1558 /* Witness utxo */
1559 #ifdef BUILD_ELEMENTS
1560 if ((flags & WALLY_TX_FLAG_USE_ELEMENTS) && input->witness_utxo) {
1561 struct wally_tx_output *utxo = input->witness_utxo;
1562 const size_t buff_len = push_elements_bytes_size(utxo);
1563 size_t remaining = buff_len;
1564 unsigned char buff[1024], *buff_p = buff, *ptr;
1565
1566 if (buff_len > sizeof(buff) && !(buff_p = wally_malloc(buff_len)))
1567 return WALLY_ENOMEM;
1568 ptr = buff_p;
1569
1570 /* Push the asset, value, nonce, then scriptpubkey */
1571 push_psbt_key(cursor, max, PSBT_IN_WITNESS_UTXO, NULL, 0);
1572
1573 push_elements_bytes(&ptr, &remaining, utxo->asset, utxo->asset_len);
1574 push_elements_bytes(&ptr, &remaining, utxo->value, utxo->value_len);
1575 push_elements_bytes(&ptr, &remaining, utxo->nonce, utxo->nonce_len);
1576 push_varbuff(&ptr, &remaining, utxo->script, utxo->script_len);
1577
1578 if (!remaining)
1579 push_varbuff(cursor, max, buff_p, buff_len);
1580 if (buff_p != buff)
1581 clear_and_free(buff_p, buff_len);
1582 if (remaining)
1583 return WALLY_ERROR; /* Should not happen! */
1584 } else
1585 #endif /* BUILD_ELEMENTS */
1586 if (input->witness_utxo) {
1587 unsigned char wit_bytes[50], *w = wit_bytes; /* Witness outputs can be no larger than 50 bytes as specified in BIP 141 */
1588 size_t wit_max = sizeof(wit_bytes);
1589
1590 push_psbt_key(cursor, max, PSBT_IN_WITNESS_UTXO, NULL, 0);
1591
1592 push_le64(&w, &wit_max, input->witness_utxo->satoshi);
1593 push_varbuff(&w, &wit_max,
1594 input->witness_utxo->script,
1595 input->witness_utxo->script_len);
1596 if (!w)
1597 return WALLY_EINVAL;
1598
1599 push_varbuff(cursor, max, wit_bytes, w - wit_bytes);
1600 }
1601 /* Partial sigs */
1602 push_typed_map(cursor, max, PSBT_IN_PARTIAL_SIG, &input->signatures);
1603 /* Sighash type */
1604 if (input->sighash > 0) {
1605 push_psbt_key(cursor, max, PSBT_IN_SIGHASH_TYPE, NULL, 0);
1606 push_varint(cursor, max, sizeof(uint32_t));
1607 push_le32(cursor, max, input->sighash);
1608 }
1609 /* Redeem script */
1610 push_typed_varbuff(cursor, max, PSBT_IN_REDEEM_SCRIPT,
1611 input->redeem_script, input->redeem_script_len);
1612 /* Witness script */
1613 push_typed_varbuff(cursor, max, PSBT_IN_WITNESS_SCRIPT,
1614 input->witness_script, input->witness_script_len);
1615 /* Keypaths */
1616 push_typed_map(cursor, max, PSBT_IN_BIP32_DERIVATION, &input->keypaths);
1617 /* Final scriptSig */
1618 push_typed_varbuff(cursor, max, PSBT_IN_FINAL_SCRIPTSIG,
1619 input->final_scriptsig, input->final_scriptsig_len);
1620 /* Final scriptWitness */
1621 if (input->final_witness) {
1622 size_t wit_len = 0;
1623
1624 push_psbt_key(cursor, max, PSBT_IN_FINAL_SCRIPTWITNESS, NULL, 0);
1625
1626 /* First pass simply calculates length */
1627 push_witness_stack(NULL, &wit_len, input->final_witness);
1628
1629 push_varint(cursor, max, wit_len);
1630 push_witness_stack(cursor, max, input->final_witness);
1631 }
1632 #ifdef BUILD_ELEMENTS
1633 /* Confidential Assets blinding data */
1634 if (input->has_value) {
1635 push_elements_key(cursor, max, PSET_IN_VALUE);
1636 push_varint(cursor, max, sizeof(leint64_t));
1637 push_le64(cursor, max, input->value);
1638 }
1639 push_elements_varbuff(cursor, max, PSET_IN_VALUE_BLINDER,
1640 input->vbf, input->vbf_len);
1641 push_elements_varbuff(cursor, max, PSET_IN_ASSET,
1642 input->asset, input->asset_len);
1643 push_elements_varbuff(cursor, max, PSET_IN_ASSET_BLINDER,
1644 input->abf, input->abf_len);
1645 /* Peg ins */
1646 if (input->pegin_tx) {
1647 push_elements_key(cursor, max, PSET_IN_PEG_IN_TX);
1648 if ((ret = push_length_and_tx(cursor, max,
1649 input->pegin_tx,
1650 WALLY_TX_FLAG_USE_WITNESS)) != WALLY_OK)
1651 return ret;
1652 }
1653 push_elements_varbuff(cursor, max, PSET_IN_TXOUT_PROOF,
1654 input->txoutproof, input->txoutproof_len);
1655 push_elements_varbuff(cursor, max, PSET_IN_GENESIS_HASH,
1656 input->genesis_blockhash, input->genesis_blockhash_len);
1657 push_elements_varbuff(cursor, max, PSET_IN_CLAIM_SCRIPT,
1658 input->claim_script, input->claim_script_len);
1659 #endif /* BUILD_ELEMENTS */
1660 /* Unknowns */
1661 push_map(cursor, max, &input->unknowns);
1662 /* Separator */
1663 push_u8(cursor, max, PSBT_SEPARATOR);
1664 return WALLY_OK;
1665 }
1666
push_psbt_output(unsigned char ** cursor,size_t * max,const struct wally_psbt_output * output)1667 static int push_psbt_output(unsigned char **cursor, size_t *max,
1668 const struct wally_psbt_output *output)
1669 {
1670 /* Redeem script */
1671 push_typed_varbuff(cursor, max, PSBT_OUT_REDEEM_SCRIPT,
1672 output->redeem_script, output->redeem_script_len);
1673 /* Witness script */
1674 push_typed_varbuff(cursor, max, PSBT_OUT_WITNESS_SCRIPT,
1675 output->witness_script, output->witness_script_len);
1676 /* Keypaths */
1677 push_typed_map(cursor, max, PSBT_OUT_BIP32_DERIVATION, &output->keypaths);
1678
1679 #ifdef BUILD_ELEMENTS
1680 push_elements_varbuff(cursor, max, PSET_OUT_VALUE_COMMITMENT,
1681 output->value_commitment, output->value_commitment_len);
1682 push_elements_varbuff(cursor, max, PSET_OUT_VALUE_BLINDER,
1683 output->vbf, output->vbf_len);
1684 push_elements_varbuff(cursor, max, PSET_OUT_ASSET_COMMITMENT,
1685 output->asset_commitment, output->asset_commitment_len);
1686 push_elements_varbuff(cursor, max, PSET_OUT_ASSET_BLINDER,
1687 output->abf, output->abf_len);
1688 push_elements_varbuff(cursor, max, PSET_OUT_RANGE_PROOF,
1689 output->rangeproof, output->rangeproof_len);
1690 push_elements_varbuff(cursor, max, PSET_OUT_SURJECTION_PROOF,
1691 output->surjectionproof, output->surjectionproof_len);
1692 push_elements_varbuff(cursor, max, PSET_OUT_BLINDING_PUBKEY,
1693 output->blinding_pubkey, output->blinding_pubkey_len);
1694 push_elements_varbuff(cursor, max, PSET_OUT_NONCE_COMMITMENT,
1695 output->nonce, output->nonce_len);
1696 #endif /* BUILD_ELEMENTS */
1697 /* Unknowns */
1698 push_map(cursor, max, &output->unknowns);
1699 /* Separator */
1700 push_u8(cursor, max, PSBT_SEPARATOR);
1701 return WALLY_OK;
1702 }
1703
wally_psbt_to_bytes(const struct wally_psbt * psbt,uint32_t flags,unsigned char * bytes_out,size_t len,size_t * written)1704 int wally_psbt_to_bytes(const struct wally_psbt *psbt, uint32_t flags,
1705 unsigned char *bytes_out, size_t len,
1706 size_t *written)
1707 {
1708 unsigned char *cursor = bytes_out;
1709 size_t max = len, i, is_elements;
1710 uint32_t tx_flags;
1711 int ret;
1712
1713 if (written)
1714 *written = 0;
1715
1716 if (flags != 0 || !written)
1717 return WALLY_EINVAL;
1718
1719 if ((ret = wally_psbt_is_elements(psbt, &is_elements)) != WALLY_OK)
1720 return ret;
1721
1722 tx_flags = is_elements ? WALLY_TX_FLAG_USE_ELEMENTS : 0;
1723 push_bytes(&cursor, &max, psbt->magic, sizeof(psbt->magic));
1724
1725 /* Global tx */
1726 push_psbt_key(&cursor, &max, PSBT_GLOBAL_UNSIGNED_TX, NULL, 0);
1727 ret = push_length_and_tx(&cursor, &max, psbt->tx,
1728 WALLY_TX_FLAG_ALLOW_PARTIAL | WALLY_TX_FLAG_PRE_BIP144);
1729 if (ret != WALLY_OK)
1730 return ret;
1731
1732 /* version */
1733 if (psbt->version > 0) {
1734 push_psbt_key(&cursor, &max, PSBT_GLOBAL_VERSION, NULL, 0);
1735 push_varint(&cursor, &max, sizeof(uint32_t));
1736 push_le32(&cursor, &max, psbt->version);
1737 }
1738
1739 /* Unknowns */
1740 push_map(&cursor, &max, &psbt->unknowns);
1741
1742 /* Separator */
1743 push_u8(&cursor, &max, PSBT_SEPARATOR);
1744
1745 /* Push each input and output */
1746 for (i = 0; i < psbt->num_inputs; ++i) {
1747 const struct wally_psbt_input *input = &psbt->inputs[i];
1748 if ((ret = push_psbt_input(&cursor, &max, tx_flags, input)) != WALLY_OK)
1749 return ret;
1750 }
1751 for (i = 0; i < psbt->num_outputs; ++i) {
1752 const struct wally_psbt_output *output = &psbt->outputs[i];
1753 if ((ret = push_psbt_output(&cursor, &max, output)) != WALLY_OK)
1754 return ret;
1755 }
1756
1757 if (cursor == NULL) {
1758 /* Once cursor is NULL, max holds how many bytes we needed */
1759 *written = len + max;
1760 } else {
1761 *written = len - max;
1762 }
1763
1764 return WALLY_OK;
1765 }
1766
wally_psbt_from_base64(const char * base64,struct wally_psbt ** output)1767 int wally_psbt_from_base64(const char *base64, struct wally_psbt **output)
1768 {
1769 unsigned char *decoded;
1770 size_t max_len, written;
1771 int ret;
1772
1773 TX_CHECK_OUTPUT;
1774 if ((ret = wally_base64_get_maximum_length(base64, 0, &max_len)) != WALLY_OK)
1775 return ret;
1776
1777 /* Allocate the buffer to decode into */
1778 if ((decoded = wally_malloc(max_len)) == NULL)
1779 return WALLY_ENOMEM;
1780
1781 /* Decode the base64 psbt into binary */
1782 if ((ret = wally_base64_to_bytes(base64, 0, decoded, max_len, &written)) != WALLY_OK)
1783 goto done;
1784
1785 if (written <= sizeof(PSBT_MAGIC)) {
1786 ret = WALLY_EINVAL; /* Not enough bytes for the magic + any data */
1787 goto done;
1788 }
1789 if (written > max_len) {
1790 ret = WALLY_ERROR; /* Max len too small, should never happen! */
1791 goto done;
1792 }
1793
1794 /* decode the psbt */
1795 ret = wally_psbt_from_bytes(decoded, written, output);
1796
1797 done:
1798 clear_and_free(decoded, max_len);
1799 return ret;
1800 }
1801
wally_psbt_to_base64(const struct wally_psbt * psbt,uint32_t flags,char ** output)1802 int wally_psbt_to_base64(const struct wally_psbt *psbt, uint32_t flags, char **output)
1803 {
1804 unsigned char *buff;
1805 size_t len, written;
1806 int ret = WALLY_OK;
1807
1808 TX_CHECK_OUTPUT;
1809 if (!psbt)
1810 return WALLY_EINVAL;
1811
1812 if ((ret = wally_psbt_get_length(psbt, flags, &len)) != WALLY_OK)
1813 return ret;
1814
1815 if ((buff = wally_malloc(len)) == NULL)
1816 return WALLY_ENOMEM;
1817
1818 /* Get psbt bytes */
1819 if ((ret = wally_psbt_to_bytes(psbt, flags, buff, len, &written)) != WALLY_OK)
1820 goto done;
1821
1822 if (written != len) {
1823 ret = WALLY_ERROR; /* Length calculated incorrectly */
1824 goto done;
1825 }
1826
1827 /* Base64 encode */
1828 ret = wally_base64_from_bytes(buff, len, 0, output);
1829
1830 done:
1831 clear_and_free(buff, len);
1832 return ret;
1833 }
1834
1835 #define COMBINE_BYTES(typ, member) do { \
1836 if (!dst->member && src->member) { \
1837 if (src->member && !src->member ## _len) { \
1838 if ((dst->member = wally_malloc(1)) == NULL) ret = WALLY_ENOMEM; \
1839 } else \
1840 ret = wally_psbt_ ## typ ## _set_ ## member(dst, src->member, src->member ## _len); \
1841 if (ret != WALLY_OK) \
1842 return ret; \
1843 } } while (0)
1844
combine_txs(struct wally_tx ** dst,struct wally_tx * src)1845 static int combine_txs(struct wally_tx **dst, struct wally_tx *src)
1846 {
1847 if (!dst)
1848 return WALLY_EINVAL;
1849
1850 if (!*dst && src)
1851 return tx_clone_alloc(src, dst);
1852
1853 return WALLY_OK;
1854 }
1855
combine_inputs(struct wally_psbt_input * dst,const struct wally_psbt_input * src)1856 static int combine_inputs(struct wally_psbt_input *dst,
1857 const struct wally_psbt_input *src)
1858 {
1859 int ret;
1860
1861 if ((ret = combine_txs(&dst->utxo, src->utxo)) != WALLY_OK)
1862 return ret;
1863
1864 if (!dst->witness_utxo && src->witness_utxo) {
1865 ret = wally_tx_output_clone_alloc(src->witness_utxo, &dst->witness_utxo);
1866 if (ret != WALLY_OK)
1867 return ret;
1868 }
1869
1870 COMBINE_BYTES(input, redeem_script);
1871 COMBINE_BYTES(input, witness_script);
1872 COMBINE_BYTES(input, final_scriptsig);
1873
1874 if (!dst->final_witness && src->final_witness &&
1875 (ret = wally_psbt_input_set_final_witness(dst, src->final_witness)) != WALLY_OK)
1876 return ret;
1877 if ((ret = map_extend(&dst->keypaths, &src->keypaths, wally_ec_public_key_verify)) != WALLY_OK)
1878 return ret;
1879 if ((ret = map_extend(&dst->signatures, &src->signatures, wally_ec_public_key_verify)) != WALLY_OK)
1880 return ret;
1881 if ((ret = map_extend(&dst->unknowns, &src->unknowns, NULL)) != WALLY_OK)
1882 return ret;
1883 if (!dst->sighash && src->sighash)
1884 dst->sighash = src->sighash;
1885
1886 #ifdef BUILD_ELEMENTS
1887 if (!dst->has_value && src->has_value) {
1888 dst->value = src->value;
1889 dst->has_value = true;
1890 }
1891 COMBINE_BYTES(input, vbf);
1892 COMBINE_BYTES(input, asset);
1893 COMBINE_BYTES(input, abf);
1894 if ((ret = combine_txs(&dst->pegin_tx, src->pegin_tx)) != WALLY_OK)
1895 return ret;
1896 COMBINE_BYTES(input, txoutproof);
1897 COMBINE_BYTES(input, genesis_blockhash);
1898 COMBINE_BYTES(input, claim_script);
1899 #endif
1900 return WALLY_OK;
1901 }
1902
combine_outputs(struct wally_psbt_output * dst,const struct wally_psbt_output * src)1903 static int combine_outputs(struct wally_psbt_output *dst,
1904 const struct wally_psbt_output *src)
1905 {
1906 int ret;
1907
1908 if ((ret = map_extend(&dst->keypaths, &src->keypaths, wally_ec_public_key_verify)) != WALLY_OK)
1909 return ret;
1910 if ((ret = map_extend(&dst->unknowns, &src->unknowns, NULL)) != WALLY_OK)
1911 return ret;
1912
1913 COMBINE_BYTES(output, redeem_script);
1914 COMBINE_BYTES(output, witness_script);
1915
1916 #ifdef BUILD_ELEMENTS
1917 COMBINE_BYTES(output, blinding_pubkey);
1918 COMBINE_BYTES(output, value_commitment);
1919 COMBINE_BYTES(output, vbf);
1920 COMBINE_BYTES(output, asset_commitment);
1921 COMBINE_BYTES(output, abf);
1922 COMBINE_BYTES(output, nonce);
1923 COMBINE_BYTES(output, rangeproof);
1924 COMBINE_BYTES(output, surjectionproof);
1925 #endif
1926 return WALLY_OK;
1927 }
1928 #undef COMBINE_BYTES
1929
psbt_combine(struct wally_psbt * psbt,const struct wally_psbt * src)1930 static int psbt_combine(struct wally_psbt *psbt, const struct wally_psbt *src)
1931 {
1932 size_t i;
1933 int ret = WALLY_OK;
1934
1935 for (i = 0; ret == WALLY_OK && i < psbt->num_inputs; ++i)
1936 ret = combine_inputs(&psbt->inputs[i], &src->inputs[i]);
1937
1938 for (i = 0; ret == WALLY_OK && i < psbt->num_outputs; ++i)
1939 ret = combine_outputs(&psbt->outputs[i], &src->outputs[i]);
1940
1941 if (ret == WALLY_OK)
1942 ret = map_extend(&psbt->unknowns, &src->unknowns, NULL);
1943
1944 return ret;
1945 }
1946
wally_psbt_combine(struct wally_psbt * psbt,const struct wally_psbt * src)1947 int wally_psbt_combine(struct wally_psbt *psbt, const struct wally_psbt *src)
1948 {
1949 unsigned char txid[WALLY_TXHASH_LEN];
1950 int ret;
1951
1952 if (!psbt || !psbt->tx || !src || !src->tx)
1953 return WALLY_EINVAL;
1954
1955 ret = wally_tx_get_txid(src->tx, txid, sizeof(txid));
1956
1957 if (ret == WALLY_OK && !is_matching_txid(psbt->tx, txid, sizeof(txid)))
1958 ret = WALLY_EINVAL; /* Transactions don't match */
1959
1960 wally_clear(txid, sizeof(txid));
1961 return ret == WALLY_OK ? psbt_combine(psbt, src) : ret;
1962 }
1963
wally_psbt_clone_alloc(const struct wally_psbt * psbt,uint32_t flags,struct wally_psbt ** output)1964 int wally_psbt_clone_alloc(const struct wally_psbt *psbt, uint32_t flags,
1965 struct wally_psbt **output)
1966 {
1967 #ifdef BUILD_ELEMENTS
1968 size_t is_elements;
1969 #endif /* BUILD_ELEMENTS */
1970 int ret;
1971
1972 if (output)
1973 *output = NULL;
1974 if (!psbt || flags || !output)
1975 return WALLY_EINVAL;
1976
1977 #ifdef BUILD_ELEMENTS
1978 if ((ret = wally_psbt_is_elements(psbt, &is_elements)) != WALLY_OK)
1979 return ret;
1980
1981 if (is_elements)
1982 ret = wally_psbt_elements_init_alloc(psbt->version,
1983 psbt->inputs_allocation_len,
1984 psbt->outputs_allocation_len,
1985 psbt->unknowns.items_allocation_len,
1986 output);
1987 else
1988 #endif /* BUILD_ELEMENTS */
1989 ret = wally_psbt_init_alloc(psbt->version,
1990 psbt->inputs_allocation_len,
1991 psbt->outputs_allocation_len,
1992 psbt->unknowns.items_allocation_len,
1993 output);
1994 if (ret == WALLY_OK) {
1995 (*output)->num_inputs = psbt->num_inputs;
1996 (*output)->num_outputs = psbt->num_outputs;
1997 ret = psbt_combine(*output, psbt);
1998
1999 if (ret == WALLY_OK && psbt->tx)
2000 ret = tx_clone_alloc(psbt->tx, &(*output)->tx);
2001 if (ret != WALLY_OK) {
2002 wally_psbt_free(*output);
2003 *output = NULL;
2004 }
2005 }
2006 return ret;
2007 }
2008
psbt_input_sign(struct wally_psbt_input * input,const unsigned char * priv_key,size_t priv_key_len,const unsigned char * pub_key,size_t pub_key_len,const unsigned char * bytes,size_t bytes_len,uint32_t flags)2009 static int psbt_input_sign(struct wally_psbt_input *input,
2010 const unsigned char *priv_key, size_t priv_key_len,
2011 const unsigned char *pub_key, size_t pub_key_len,
2012 const unsigned char *bytes, size_t bytes_len,
2013 uint32_t flags)
2014 {
2015 unsigned char sig[EC_SIGNATURE_LEN], der[EC_SIGNATURE_DER_MAX_LEN + 1];
2016 size_t der_len;
2017 uint32_t sighash = input && input->sighash ? input->sighash : WALLY_SIGHASH_ALL;
2018 int ret;
2019
2020 if (!input || !priv_key || priv_key_len != EC_PRIVATE_KEY_LEN ||
2021 (wally_ec_public_key_verify(pub_key, pub_key_len) != WALLY_OK) ||
2022 !bytes || bytes_len != SHA256_LEN || (flags & ~EC_FLAGS_ALL) ||
2023 (sighash & 0xffffff00))
2024 return WALLY_EINVAL;
2025
2026 /* Only grinding flag is relevant */
2027 flags = EC_FLAG_ECDSA | (flags & EC_FLAG_GRIND_R);
2028 if ((ret = wally_ec_sig_from_bytes(priv_key, priv_key_len,
2029 bytes, SHA256_LEN, flags,
2030 sig, sizeof(sig))) != WALLY_OK)
2031 return ret;
2032
2033 if ((ret = wally_ec_sig_to_der(sig, sizeof(sig), der,
2034 sizeof(der), &der_len)) != WALLY_OK)
2035 return ret;
2036
2037 /* Convert sig to DER, add sighash byte and store in the input */
2038 der[der_len++] = sighash & 0xff;
2039 ret = wally_psbt_input_add_signature(input, pub_key, pub_key_len,
2040 der, der_len);
2041 wally_clear_2(sig, sizeof(sig), der, sizeof(der));
2042 return ret;
2043 }
2044
2045 /* Get the script to sign with */
input_get_scriptcode(const struct wally_psbt_input * input,uint32_t input_index,const unsigned char ** script,size_t * script_len)2046 static bool input_get_scriptcode(const struct wally_psbt_input *input,
2047 uint32_t input_index,
2048 const unsigned char **script,
2049 size_t *script_len)
2050 {
2051 const struct wally_tx_output *utxo = NULL;
2052 const struct wally_tx_output *out;
2053
2054 if (!input || !script || !script_len)
2055 return false;
2056
2057 *script = NULL;
2058 *script_len = 0;
2059
2060 if (input->utxo) {
2061 if (input_index >= input->utxo->num_outputs)
2062 return false; /* Invalid input index */
2063 utxo = &input->utxo->outputs[input_index];
2064 }
2065
2066 out = input->witness_utxo ? input->witness_utxo : utxo;
2067 if (!out)
2068 return false; /* No prevout to get the script from */
2069
2070 if (input->redeem_script) {
2071 unsigned char p2sh[WALLY_SCRIPTPUBKEY_P2SH_LEN];
2072 size_t p2sh_len;
2073
2074 if (wally_scriptpubkey_p2sh_from_bytes(input->redeem_script,
2075 input->redeem_script_len,
2076 WALLY_SCRIPT_HASH160,
2077 p2sh, sizeof(p2sh),
2078 &p2sh_len) != WALLY_OK)
2079 return false;
2080
2081 if (out->script_len != p2sh_len || memcmp(p2sh, out->script, p2sh_len))
2082 return false; /* Script mismatch */
2083
2084 *script = input->redeem_script;
2085 *script_len = input->redeem_script_len;
2086 return true;
2087 }
2088
2089 *script = out->script;
2090 *script_len = out->script_len;
2091 return true;
2092 }
2093
wally_psbt_sign(struct wally_psbt * psbt,const unsigned char * key,size_t key_len,uint32_t flags)2094 int wally_psbt_sign(struct wally_psbt *psbt,
2095 const unsigned char *key, size_t key_len, uint32_t flags)
2096 {
2097 unsigned char pubkey[EC_PUBLIC_KEY_LEN], full_pubkey[EC_PUBLIC_KEY_UNCOMPRESSED_LEN];
2098 const size_t pubkey_len = sizeof(pubkey), full_pubkey_len = sizeof(full_pubkey);
2099 unsigned char wpkh_sc[WALLY_SCRIPTPUBKEY_P2PKH_LEN];
2100 size_t is_elements, i;
2101 int ret;
2102
2103 if (!psbt || !psbt->tx || !key || key_len != EC_PRIVATE_KEY_LEN ||
2104 (flags & ~EC_FLAGS_ALL)) {
2105 return WALLY_EINVAL;
2106 }
2107
2108 if ((ret = wally_psbt_is_elements(psbt, &is_elements)) != WALLY_OK)
2109 return ret;
2110 #ifndef BUILD_ELEMENTS
2111 if (is_elements)
2112 return WALLY_EINVAL;
2113 #endif /* ndef BUILD_ELEMENTS */
2114
2115 /* Get the pubkey */
2116 ret = wally_ec_public_key_from_private_key(key, key_len,
2117 pubkey, pubkey_len);
2118 if (ret == WALLY_OK)
2119 ret = wally_ec_public_key_decompress(pubkey, pubkey_len,
2120 full_pubkey, full_pubkey_len);
2121 if (ret != WALLY_OK)
2122 return ret;
2123
2124 /* Go through each of the inputs */
2125 for (i = 0; i < psbt->num_inputs; ++i) {
2126 struct wally_psbt_input *input = &psbt->inputs[i];
2127 struct wally_tx_input *txin = &psbt->tx->inputs[i];
2128 unsigned char signature_hash[SHA256_LEN];
2129 const unsigned char *scriptcode;
2130 size_t keypath_index = 0, scriptcode_len;
2131 uint32_t sighash;
2132
2133 /* See if this input has a keypath matching the pubkey of the private key supplied */
2134 ret = wally_map_find(&input->keypaths, full_pubkey, full_pubkey_len, &keypath_index);
2135 if (ret == WALLY_OK && !keypath_index)
2136 ret = wally_map_find(&input->keypaths, pubkey, pubkey_len, &keypath_index);
2137 if (ret != WALLY_OK)
2138 continue;
2139
2140 if (!keypath_index)
2141 continue; /* Didn't find a keypath matching this pubkey: skip it */
2142 keypath_index -= 1; /* Use 0 based index below */
2143
2144 /* Make sure we don't already have a sig for this input */
2145 size_t is_found;
2146 ret = wally_map_find(&input->signatures, full_pubkey, full_pubkey_len, &is_found);
2147 if (ret == WALLY_OK && !is_found)
2148 ret = wally_map_find(&input->signatures, pubkey, pubkey_len, &is_found);
2149
2150 if (ret != WALLY_OK || is_found)
2151 continue; /* Already got a partial sig for this pubkey on this input */
2152
2153 /* From this point, any failure to sign returns an error, since we
2154 * have the key to sign this input we are expected to be able to */
2155
2156 if (!input_get_scriptcode(input, txin->index, &scriptcode, &scriptcode_len))
2157 return WALLY_EINVAL; /* Couldn't find the script to sign with */
2158
2159 sighash = input->sighash ? input->sighash : WALLY_SIGHASH_ALL;
2160
2161 if (input->witness_utxo) {
2162 size_t type;
2163
2164 ret = wally_scriptpubkey_get_type(scriptcode, scriptcode_len, &type);
2165 if (ret != WALLY_OK)
2166 return ret;
2167
2168 if (type == WALLY_SCRIPT_TYPE_P2WPKH) {
2169 ret = wally_scriptpubkey_p2pkh_from_bytes(&scriptcode[2],
2170 HASH160_LEN, 0,
2171 wpkh_sc, sizeof(wpkh_sc),
2172 &scriptcode_len);
2173 if (ret != WALLY_OK)
2174 return ret;
2175
2176 scriptcode = wpkh_sc;
2177 } else if (type == WALLY_SCRIPT_TYPE_P2WSH && input->witness_script) {
2178 unsigned char p2wsh[WALLY_SCRIPTPUBKEY_P2WSH_LEN];
2179 size_t written;
2180
2181 ret = wally_witness_program_from_bytes(input->witness_script,
2182 input->witness_script_len,
2183 WALLY_SCRIPT_SHA256,
2184 p2wsh, sizeof(p2wsh),
2185 &written);
2186 if (ret != WALLY_OK)
2187 return ret;
2188
2189 if (scriptcode_len != sizeof(p2wsh) ||
2190 memcmp(p2wsh, scriptcode, sizeof(p2wsh)))
2191 return WALLY_EINVAL;
2192
2193 scriptcode = input->witness_script;
2194 scriptcode_len = input->witness_script_len;
2195 } else
2196 return WALLY_EINVAL; /* Unknown scriptPubKey type/not enough info */
2197
2198 #ifdef BUILD_ELEMENTS
2199 if (is_elements)
2200 ret = wally_tx_get_elements_signature_hash(psbt->tx, i,
2201 scriptcode, scriptcode_len,
2202 input->witness_utxo->value,
2203 input->witness_utxo->value_len,
2204 sighash,
2205 WALLY_TX_FLAG_USE_WITNESS,
2206 signature_hash, SHA256_LEN);
2207 else
2208 #endif /* BUILD_ELEMENTS */
2209 ret = wally_tx_get_btc_signature_hash(psbt->tx, i,
2210 scriptcode, scriptcode_len,
2211 input->witness_utxo->satoshi,
2212 sighash,
2213 WALLY_TX_FLAG_USE_WITNESS,
2214 signature_hash, SHA256_LEN);
2215 if (ret != WALLY_OK)
2216 return ret;
2217 } else if (input->utxo) {
2218 if (!is_matching_txid(input->utxo,
2219 txin->txhash, sizeof(txin->txhash)))
2220 return WALLY_EINVAL; /* prevout doesn't match this input */
2221
2222 ret = wally_tx_get_btc_signature_hash(psbt->tx, i,
2223 scriptcode, scriptcode_len,
2224 0, sighash, 0,
2225 signature_hash, SHA256_LEN);
2226 if (ret != WALLY_OK)
2227 return ret;
2228 }
2229
2230 ret = psbt_input_sign(input, key, key_len,
2231 input->keypaths.items[keypath_index].key,
2232 input->keypaths.items[keypath_index].key_len,
2233 signature_hash, SHA256_LEN, flags);
2234 if (ret != WALLY_OK)
2235 return ret;
2236 }
2237
2238 return WALLY_OK;
2239 }
2240
finalize_p2pkh(struct wally_psbt_input * input)2241 static bool finalize_p2pkh(struct wally_psbt_input *input)
2242 {
2243 unsigned char script[WALLY_SCRIPTSIG_P2PKH_MAX_LEN];
2244 size_t script_len;
2245 const struct wally_map_item *sig;
2246
2247 if (input->signatures.num_items != 1)
2248 return false; /* Must be single key, single sig */
2249
2250 sig = &input->signatures.items[0];
2251
2252 if (wally_scriptsig_p2pkh_from_der(sig->key, sig->key_len,
2253 sig->value, sig->value_len,
2254 script, sizeof(script),
2255 &script_len) != WALLY_OK)
2256 return false;
2257
2258 if (!clone_bytes(&input->final_scriptsig, script, script_len))
2259 return false;
2260 input->final_scriptsig_len = script_len;
2261 return true;
2262 }
2263
finalize_p2sh_wrapped(struct wally_psbt_input * input)2264 static bool finalize_p2sh_wrapped(struct wally_psbt_input *input)
2265 {
2266 unsigned char *script;
2267 size_t script_len, push_len;
2268
2269 /* P2SH wrapped witness: add scriptSig pushing the redeemScript */
2270 script_len = script_get_push_size(input->redeem_script_len);
2271 if ((script = wally_malloc(script_len)) != NULL &&
2272 wally_script_push_from_bytes(input->redeem_script,
2273 input->redeem_script_len, 0,
2274 script, script_len,
2275 &push_len) == WALLY_OK) {
2276 input->final_scriptsig = script;
2277 input->final_scriptsig_len = push_len;
2278 return true;
2279 }
2280 /* Failed: clear caller-created witness stack before returning */
2281 wally_free(script);
2282 wally_tx_witness_stack_free(input->final_witness);
2283 input->final_witness = NULL;
2284 return false;
2285 }
2286
finalize_p2wpkh(struct wally_psbt_input * input)2287 static bool finalize_p2wpkh(struct wally_psbt_input *input)
2288 {
2289 const struct wally_map_item *sig;
2290
2291 if (input->signatures.num_items != 1)
2292 return false; /* Must be single key, single sig */
2293
2294 sig = &input->signatures.items[0];
2295
2296 if (wally_witness_p2wpkh_from_der(sig->key, sig->key_len,
2297 sig->value, sig->value_len,
2298 &input->final_witness) != WALLY_OK)
2299 return false;
2300
2301 return input->redeem_script ? finalize_p2sh_wrapped(input) : true;
2302 }
2303
finalize_multisig(struct wally_psbt_input * input,const unsigned char * out_script,size_t out_script_len,bool is_witness,bool is_p2sh)2304 static bool finalize_multisig(struct wally_psbt_input *input,
2305 const unsigned char *out_script, size_t out_script_len,
2306 bool is_witness, bool is_p2sh)
2307 {
2308 unsigned char sigs[EC_SIGNATURE_LEN * 15];
2309 uint32_t sighashes[15];
2310 const unsigned char *p = out_script, *end = p + out_script_len;
2311 size_t threshold, n_pubkeys, n_found = 0, i;
2312 bool ret = false;
2313
2314 if (!script_is_op_n(out_script[0], false, &threshold) ||
2315 input->signatures.num_items < threshold ||
2316 !script_is_op_n(out_script[out_script_len - 2], false, &n_pubkeys) ||
2317 n_pubkeys > 15)
2318 goto fail; /* Failed to parse or invalid script */
2319
2320 ++p; /* Skip the threshold */
2321
2322 /* Collect signatures corresponding to pubkeys in the multisig script */
2323 for (i = 0; i < n_pubkeys && p < end; ++i) {
2324 size_t opcode_size, found_pubkey_len;
2325 const unsigned char *found_pubkey;
2326 const struct wally_map_item *found_sig;
2327 size_t sig_index;
2328
2329 if (script_get_push_size_from_bytes(p, end - p,
2330 &found_pubkey_len) != WALLY_OK ||
2331 script_get_push_opcode_size_from_bytes(p, end - p,
2332 &opcode_size) != WALLY_OK)
2333 goto fail; /* Script is malformed, bail */
2334
2335 p += opcode_size;
2336 found_pubkey = p;
2337 p += found_pubkey_len; /* Move to next pubkey push */
2338
2339 /* Find the associated signature for this pubkey */
2340 if (wally_map_find(&input->signatures,
2341 found_pubkey, found_pubkey_len,
2342 &sig_index) != WALLY_OK || !sig_index)
2343 continue; /* Not found: try the next pubkey in the script */
2344
2345 found_sig = &input->signatures.items[sig_index - 1];
2346
2347 /* Sighash is appended to the DER signature */
2348 sighashes[n_found] = found_sig->value[found_sig->value_len - 1];
2349 /* Convert the DER signature to compact form */
2350 if (wally_ec_sig_from_der(found_sig->value, found_sig->value_len - 1,
2351 sigs + n_found * EC_SIGNATURE_LEN,
2352 EC_SIGNATURE_LEN) != WALLY_OK)
2353 continue; /* Failed to parse, try next pubkey */
2354
2355 if (++n_found == threshold)
2356 break; /* We have enough signatures, ignore any more */
2357 }
2358
2359 if (n_found != threshold)
2360 goto fail; /* Failed to find enough signatures */
2361
2362 if (is_witness) {
2363 if (wally_witness_multisig_from_bytes(out_script, out_script_len,
2364 sigs, n_found * EC_SIGNATURE_LEN,
2365 sighashes, n_found,
2366 0, &input->final_witness) != WALLY_OK)
2367 goto fail;
2368
2369 if (is_p2sh && !finalize_p2sh_wrapped(input))
2370 goto fail;
2371 } else {
2372 size_t max_len = n_found * (EC_SIGNATURE_DER_MAX_LEN + 2) + out_script_len;
2373 unsigned char *script = wally_malloc(max_len);
2374 size_t script_len;
2375
2376 if (!script ||
2377 wally_scriptsig_multisig_from_bytes(out_script, out_script_len,
2378 sigs, n_found * EC_SIGNATURE_LEN,
2379 sighashes, n_found, 0,
2380 script, max_len,
2381 &script_len) != WALLY_OK) {
2382 wally_free(script);
2383 goto fail;
2384 }
2385 input->final_scriptsig = script;
2386 input->final_scriptsig_len = script_len;
2387 }
2388 ret = true;
2389 fail:
2390 wally_clear_2(sigs, sizeof(sigs), sighashes, sizeof(sighashes));
2391 return ret;
2392 }
2393
wally_psbt_finalize(struct wally_psbt * psbt)2394 int wally_psbt_finalize(struct wally_psbt *psbt)
2395 {
2396 size_t i;
2397
2398 if (!psbt || !psbt->tx || psbt->tx->num_inputs != psbt->num_inputs)
2399 return WALLY_EINVAL;
2400
2401 for (i = 0; i < psbt->num_inputs; ++i) {
2402 struct wally_psbt_input *input = &psbt->inputs[i];
2403 const uint32_t utxo_index = psbt->tx->inputs[i].index;
2404
2405 /* Script for this input. originally set to the input's scriptPubKey, but in the case of a p2sh/p2wsh
2406 * input, it will be eventually be set to the unhashed script, if known */
2407 unsigned char *out_script = NULL;
2408 size_t out_script_len, type;
2409 bool is_witness = false, is_p2sh = false;
2410
2411 if (input->final_scriptsig || input->final_witness)
2412 continue; /* Already finalized */
2413
2414 /* Note that if we patch libwally to supply the non-witness utxo tx field (tx) for
2415 * witness inputs also, we'll need a different way to signal p2sh-p2wpkh scripts */
2416 if (input->witness_utxo && input->witness_utxo->script_len > 0) {
2417 out_script = input->witness_utxo->script;
2418 out_script_len = input->witness_utxo->script_len;
2419 is_witness = true;
2420 } else if (input->utxo && utxo_index < input->utxo->num_outputs) {
2421 struct wally_tx_output *out = &input->utxo->outputs[utxo_index];
2422 out_script = out->script;
2423 out_script_len = out->script_len;
2424 }
2425 if (input->redeem_script) {
2426 out_script = input->redeem_script;
2427 out_script_len = input->redeem_script_len;
2428 is_p2sh = true;
2429 }
2430 if (input->witness_script) {
2431 out_script = input->witness_script;
2432 out_script_len = input->witness_script_len;
2433 is_witness = true;
2434 }
2435
2436 if (!out_script)
2437 continue; /* We need an outscript to do anything */
2438
2439 if (wally_scriptpubkey_get_type(out_script, out_script_len, &type) != WALLY_OK)
2440 continue; /* Can't identify the type, skip */
2441
2442 switch(type) {
2443 case WALLY_SCRIPT_TYPE_P2PKH:
2444 if (!finalize_p2pkh(input))
2445 continue;
2446 break;
2447 case WALLY_SCRIPT_TYPE_P2WPKH:
2448 if (!finalize_p2wpkh(input))
2449 continue;
2450 break;
2451 case WALLY_SCRIPT_TYPE_MULTISIG:
2452 if (!finalize_multisig(input, out_script, out_script_len, is_witness, is_p2sh))
2453 continue;
2454 break;
2455 default:
2456 continue; /* Can't finalize this input, skip */
2457 }
2458
2459 /* Clear non-final things */
2460 clear_and_free(input->redeem_script, input->redeem_script_len);
2461 input->redeem_script_len = 0;
2462 input->redeem_script = NULL;
2463 clear_and_free(input->witness_script, input->witness_script_len);
2464 input->witness_script_len = 0;
2465 input->witness_script = NULL;
2466 wally_map_clear(&input->keypaths);
2467 wally_map_clear(&input->signatures);
2468 input->sighash = 0;
2469 }
2470 return WALLY_OK;
2471 }
2472
wally_psbt_extract(const struct wally_psbt * psbt,struct wally_tx ** output)2473 int wally_psbt_extract(const struct wally_psbt *psbt, struct wally_tx **output)
2474 {
2475 struct wally_tx *result = NULL;
2476 size_t i;
2477 int ret;
2478
2479 TX_CHECK_OUTPUT;
2480
2481 if (!psbt || !psbt->tx || !psbt->num_inputs || !psbt->num_outputs ||
2482 psbt->tx->num_inputs != psbt->num_inputs ||
2483 psbt->tx->num_outputs != psbt->num_outputs)
2484 return WALLY_EINVAL;
2485
2486 if ((ret = tx_clone_alloc(psbt->tx, &result)) != WALLY_OK)
2487 return ret;
2488
2489 for (i = 0; i < psbt->num_inputs; ++i) {
2490 const struct wally_psbt_input *input = &psbt->inputs[i];
2491 struct wally_tx_input *tx_input = &result->inputs[i];
2492
2493 if (!input->final_scriptsig && !input->final_witness) {
2494 ret = WALLY_EINVAL;
2495 break;
2496 }
2497
2498 if (input->final_scriptsig) {
2499 if (tx_input->script) {
2500 /* Our global tx shouldn't have a scriptSig */
2501 ret = WALLY_EINVAL;
2502 break;
2503 }
2504 if (!clone_bytes(&tx_input->script,
2505 input->final_scriptsig,
2506 input->final_scriptsig_len)) {
2507 ret = WALLY_ENOMEM;
2508 break;
2509 }
2510 tx_input->script_len = input->final_scriptsig_len;
2511 }
2512 if (input->final_witness) {
2513 if (tx_input->witness) {
2514 /* Our global tx shouldn't have a witness */
2515 ret = WALLY_EINVAL;
2516 break;
2517 }
2518 ret = wally_tx_witness_stack_clone_alloc(input->final_witness,
2519 &tx_input->witness);
2520 if (ret != WALLY_OK)
2521 break;
2522 }
2523 }
2524
2525 if (ret == WALLY_OK)
2526 *output = result;
2527 else
2528 wally_tx_free(result);
2529 return ret;
2530 }
2531
wally_psbt_is_elements(const struct wally_psbt * psbt,size_t * written)2532 int wally_psbt_is_elements(const struct wally_psbt *psbt, size_t *written)
2533 {
2534 if (!psbt || !written)
2535 return WALLY_EINVAL;
2536
2537 *written = memcmp(psbt->magic, PSET_MAGIC, sizeof(PSET_MAGIC)) ? 0 : 1;
2538 return WALLY_OK;
2539 }
2540
2541 #if defined(SWIG) || defined (SWIG_JAVA_BUILD) || defined (SWIG_PYTHON_BUILD) || defined (SWIG_JAVASCRIPT_BUILD)
2542
psbt_get_input(const struct wally_psbt * psbt,size_t index)2543 static struct wally_psbt_input *psbt_get_input(const struct wally_psbt *psbt, size_t index)
2544 {
2545 return psbt && index < psbt->num_inputs ? &psbt->inputs[index] : NULL;
2546 }
2547
psbt_get_output(const struct wally_psbt * psbt,size_t index)2548 static struct wally_psbt_output *psbt_get_output(const struct wally_psbt *psbt, size_t index)
2549 {
2550 return psbt && index < psbt->num_outputs ? &psbt->outputs[index] : NULL;
2551 }
2552
2553 /* Getters for maps in inputs/outputs */
2554 #define PSBT_GET_K(typ, name) \
2555 int wally_psbt_get_ ## typ ## _ ## name ## s_size(const struct wally_psbt *psbt, size_t index, \
2556 size_t *written) { \
2557 struct wally_psbt_ ## typ *p = psbt_get_ ## typ(psbt, index); \
2558 if (written) *written = 0; \
2559 if (!p || !written) return WALLY_EINVAL; \
2560 *written = p->name ## s ? p->name ## s->num_items : 0; \
2561 return WALLY_OK; \
2562 }
2563
2564 #define PSBT_GET_M(typ, name) \
2565 int wally_psbt_get_ ## typ ## _ ## name ## s_size(const struct wally_psbt *psbt, size_t index, \
2566 size_t *written) { \
2567 struct wally_psbt_ ## typ *p = psbt_get_ ## typ(psbt, index); \
2568 if (written) *written = 0; \
2569 if (!p || !written) return WALLY_EINVAL; \
2570 *written = p->name ## s.num_items; \
2571 return WALLY_OK; \
2572 } \
2573 int wally_psbt_find_ ## typ ## _ ## name(const struct wally_psbt *psbt, size_t index, \
2574 const unsigned char *key, size_t key_len, size_t *written) { \
2575 struct wally_psbt_ ## typ *p = psbt_get_ ## typ(psbt, index); \
2576 if (written) *written = 0; \
2577 if (!p || !key || !key_len || !written) return WALLY_EINVAL; \
2578 return wally_psbt_ ## typ ## _find_ ## name(p, key, key_len, written); \
2579 } \
2580 int wally_psbt_get_ ## typ ## _ ## name(const struct wally_psbt *psbt, size_t index, \
2581 size_t subindex, unsigned char *bytes_out, size_t len, size_t *written) { \
2582 struct wally_psbt_ ## typ *p = psbt_get_ ## typ(psbt, index); \
2583 if (written) *written = 0; \
2584 if (!p || !bytes_out || !len || !written || subindex >= p->name ## s.num_items) return WALLY_EINVAL; \
2585 *written = p->name ## s.items[subindex].value_len; \
2586 if (*written <= len) \
2587 memcpy(bytes_out, p->name ## s.items[subindex].value, *written); \
2588 return WALLY_OK; \
2589 } \
2590 int wally_psbt_get_ ## typ ## _ ## name ## _len(const struct wally_psbt *psbt, size_t index, \
2591 size_t subindex, size_t *written) { \
2592 struct wally_psbt_ ## typ *p = psbt_get_ ## typ(psbt, index); \
2593 if (written) *written = 0; \
2594 if (!p || !written || subindex >= p->name ## s.num_items) return WALLY_EINVAL; \
2595 *written = p->name ## s.items[subindex].value_len; \
2596 return WALLY_OK; \
2597 }
2598
2599
2600 /* Get a binary buffer value from an input/output */
2601 #define PSBT_GET_B(typ, name) \
2602 int wally_psbt_get_ ## typ ## _ ## name ## _len(const struct wally_psbt *psbt, size_t index, \
2603 size_t *written) { \
2604 struct wally_psbt_ ## typ *p = psbt_get_ ## typ(psbt, index); \
2605 if (written) *written = 0; \
2606 if (!p || !written) return WALLY_EINVAL; \
2607 *written = p->name ## _len; \
2608 return WALLY_OK; \
2609 } \
2610 int wally_psbt_get_ ## typ ## _ ## name(const struct wally_psbt *psbt, size_t index, \
2611 unsigned char *bytes_out, size_t len, size_t *written) { \
2612 struct wally_psbt_ ## typ *p = psbt_get_ ## typ(psbt, index); \
2613 if (written) *written = 0; \
2614 if (!p || !written) return WALLY_EINVAL; \
2615 *written = p->name ## _len; \
2616 if (p->name ## _len <= len) \
2617 memcpy(bytes_out, p->name, p->name ## _len); \
2618 return WALLY_OK; \
2619 }
2620
2621 /* Set a binary buffer value on an input/output */
2622 #define PSBT_SET_B(typ, name) \
2623 int wally_psbt_set_ ## typ ## _ ## name(struct wally_psbt *psbt, size_t index, \
2624 const unsigned char *name, size_t name ## _len) { \
2625 return wally_psbt_ ## typ ## _set_ ## name(psbt_get_ ## typ(psbt, index), name, name ## _len); \
2626 }
2627
2628 /* Get an integer value from an input/output */
2629 #define PSBT_GET_I(typ, name, inttyp) \
2630 int wally_psbt_get_ ## typ ## _ ## name(const struct wally_psbt *psbt, size_t index, \
2631 inttyp *written) { \
2632 struct wally_psbt_ ## typ *p = psbt_get_ ## typ(psbt, index); \
2633 if (written) *written = 0; \
2634 if (!p || !written) return WALLY_EINVAL; \
2635 *written = p->name; \
2636 return WALLY_OK; \
2637 }
2638
2639 /* Set an integer value on an input/output */
2640 #define PSBT_SET_I(typ, name, inttyp) \
2641 int wally_psbt_set_ ## typ ## _ ## name(struct wally_psbt *psbt, size_t index, \
2642 inttyp v) { \
2643 return wally_psbt_ ## typ ## _set_ ## name(psbt_get_ ## typ(psbt, index), v); \
2644 }
2645
2646 /* Get a struct from an input/output */
2647 #define PSBT_GET_S(typ, name, structtyp, clonefn) \
2648 int wally_psbt_get_ ## typ ## _ ## name ## _alloc(const struct wally_psbt *psbt, size_t index, \
2649 struct structtyp **output) { \
2650 struct wally_psbt_ ## typ *p = psbt_get_ ## typ(psbt, index); \
2651 if (output) *output = NULL; \
2652 if (!p || !output) return WALLY_EINVAL; \
2653 return clonefn(p->name, output); \
2654 }
2655
2656 /* Set a struct on an input/output */
2657 #define PSBT_SET_S(typ, name, structtyp) \
2658 int wally_psbt_set_ ## typ ## _ ## name(struct wally_psbt *psbt, size_t index, \
2659 const struct structtyp *p) { \
2660 return wally_psbt_ ## typ ## _set_ ## name(psbt_get_ ## typ(psbt, index), p); \
2661 }
2662
PSBT_GET_S(input,utxo,wally_tx,tx_clone_alloc)2663 PSBT_GET_S(input, utxo, wally_tx, tx_clone_alloc)
2664 PSBT_GET_S(input, witness_utxo, wally_tx_output, wally_tx_output_clone_alloc)
2665 PSBT_GET_B(input, redeem_script)
2666 PSBT_GET_B(input, witness_script)
2667 PSBT_GET_B(input, final_scriptsig)
2668 PSBT_GET_S(input, final_witness, wally_tx_witness_stack, wally_tx_witness_stack_clone_alloc)
2669 PSBT_GET_M(input, keypath)
2670 PSBT_GET_M(input, signature)
2671 PSBT_GET_M(input, unknown)
2672 PSBT_GET_I(input, sighash, size_t)
2673
2674 PSBT_SET_S(input, utxo, wally_tx)
2675 PSBT_SET_S(input, witness_utxo, wally_tx_output)
2676 PSBT_SET_B(input, redeem_script)
2677 PSBT_SET_B(input, witness_script)
2678 PSBT_SET_B(input, final_scriptsig)
2679 PSBT_SET_S(input, final_witness, wally_tx_witness_stack)
2680 PSBT_SET_S(input, keypaths, wally_map)
2681 PSBT_SET_S(input, signatures, wally_map)
2682 PSBT_SET_S(input, unknowns, wally_map)
2683 PSBT_SET_I(input, sighash, uint32_t)
2684
2685 #ifdef BUILD_ELEMENTS
2686 int wally_psbt_has_input_value(const struct wally_psbt *psbt, size_t index, size_t *written) {
2687 struct wally_psbt_input *p = psbt_get_input(psbt, index);
2688 if (written) *written = 0;
2689 if (!p || !written) return WALLY_EINVAL;
2690 *written = p->has_value ? 1 : 0;
2691 return WALLY_OK;
2692 }
PSBT_GET_I(input,value,uint64_t)2693 PSBT_GET_I(input, value, uint64_t)
2694 PSBT_GET_B(input, vbf)
2695 PSBT_GET_B(input, asset)
2696 PSBT_GET_B(input, abf)
2697 PSBT_GET_S(input, pegin_tx, wally_tx, tx_clone_alloc)
2698 PSBT_GET_B(input, txoutproof)
2699 PSBT_GET_B(input, genesis_blockhash)
2700 PSBT_GET_B(input, claim_script)
2701
2702 PSBT_SET_I(input, value, uint64_t)
2703 int wally_psbt_clear_input_value(struct wally_psbt *psbt, size_t index) {
2704 return wally_psbt_input_clear_value(psbt_get_input(psbt, index));
2705 }
2706 PSBT_SET_B(input, vbf)
2707 PSBT_SET_B(input, asset)
2708 PSBT_SET_B(input, abf)
2709 PSBT_SET_S(input, pegin_tx, wally_tx)
2710 PSBT_SET_B(input, txoutproof)
2711 PSBT_SET_B(input, genesis_blockhash)
2712 PSBT_SET_B(input, claim_script)
2713 #endif /* BUILD_ELEMENTS */
2714
2715 PSBT_GET_B(output, redeem_script)
2716 PSBT_GET_B(output, witness_script)
2717 PSBT_GET_M(output, keypath)
2718 PSBT_GET_M(output, unknown)
2719
2720 PSBT_SET_B(output, redeem_script)
2721 PSBT_SET_B(output, witness_script)
2722 PSBT_SET_S(output, keypaths, wally_map)
2723 PSBT_SET_S(output, unknowns, wally_map)
2724 #ifdef BUILD_ELEMENTS
2725 PSBT_GET_B(output, blinding_pubkey)
2726 PSBT_GET_B(output, value_commitment)
2727 PSBT_GET_B(output, vbf)
2728 PSBT_GET_B(output, asset_commitment)
2729 PSBT_GET_B(output, abf)
2730 PSBT_GET_B(output, nonce)
2731 PSBT_GET_B(output, rangeproof)
2732 PSBT_GET_B(output, surjectionproof)
2733
2734 PSBT_SET_B(output, blinding_pubkey)
2735 PSBT_SET_B(output, value_commitment)
2736 PSBT_SET_B(output, vbf)
2737 PSBT_SET_B(output, asset_commitment)
2738 PSBT_SET_B(output, abf)
2739 PSBT_SET_B(output, nonce)
2740 PSBT_SET_B(output, rangeproof)
2741 PSBT_SET_B(output, surjectionproof)
2742 #endif /* BUILD_ELEMENTS */
2743
2744 #endif /* SWIG/SWIG_JAVA_BUILD/SWIG_PYTHON_BUILD/SWIG_JAVASCRIPT_BUILD */
2745