md-codec 0.34.0

Reference implementation of the Mnemonic Descriptor (MD) format for engravable BIP 388 wallet policy backups
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
//! v0.32 AST → `miniscript::Descriptor<DescriptorPublicKey>` converter.
//!
//! Replaces the v0.14-era hand-rolled 5-shape allow-list with a generic
//! converter that builds a miniscript `Descriptor` from any
//! BIP-388-parseable md1 wire AST. Address derivation
//! ([`crate::Descriptor::derive_address`]) delegates to this module then
//! to `miniscript::Descriptor::address`.
//!
//! Feature-gated behind `derive` (default-on).

use crate::canonicalize::{ExpandedKey, expand_per_at_n};
use crate::derive::xpub_from_tlv_bytes;
use crate::encode::Descriptor;
use crate::error::Error;
use crate::origin_path::OriginPath;
use crate::tag::Tag;
use crate::tree::{Body, Node};
use crate::use_site_path::UseSitePath;

use bitcoin::bip32::{ChildNumber, DerivationPath, Fingerprint};
use miniscript::descriptor::{
    DescriptorPublicKey, DescriptorXKey, SinglePub, SinglePubKey, Wildcard,
};
use miniscript::miniscript::limits::{MAX_PUBKEYS_IN_CHECKSIGADD, MAX_PUBKEYS_PER_MULTISIG};
use miniscript::{
    AbsLockTime, Legacy, Miniscript, RelLockTime, ScriptContext, Segwitv0, Tap, Terminal, Threshold,
};
use std::str::FromStr;
use std::sync::Arc;

/// BIP-341 NUMS H-point x-only coordinate. Used as the internal key when
/// `Body::Tr { is_nums: true, .. }`.
const NUMS_H_POINT_X_ONLY_HEX: &str =
    "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0";

/// Convert an md1 [`Descriptor`] AST to a
/// `miniscript::Descriptor<DescriptorPublicKey>` for `chain` (the
/// multipath alt selector). The trailing wildcard `/*` remains for
/// `miniscript::Descriptor::at_derivation_index` to resolve.
///
/// `chain` is resolved in-place during key construction (multipath alt
/// substituted into each `DescriptorXKey.derivation_path`); the resulting
/// `Descriptor` is single-path.
///
/// # Errors
///
/// - [`Error::MissingPubkey`] / [`Error::InvalidXpubBytes`] /
///   [`Error::MissingExplicitOrigin`] propagated from
///   [`expand_per_at_n`].
/// - [`Error::AddressDerivationFailed`] wrapping any miniscript-layer
///   failure (type check, context error, unsupported fragment) or arity
///   mismatch raised by the converter.
pub fn to_miniscript_descriptor(
    d: &Descriptor,
    chain: u32,
) -> Result<miniscript::Descriptor<DescriptorPublicKey>, Error> {
    let expanded = expand_per_at_n(d)?;
    let mut keys: Vec<DescriptorPublicKey> = Vec::with_capacity(expanded.len());
    for e in &expanded {
        keys.push(build_descriptor_public_key(e, &d.use_site_path, chain)?);
    }
    node_to_descriptor(&d.tree, &keys)
}

/// Build a `DescriptorPublicKey::XPub` for one expanded `@N`, with the
/// chain alt substituted into `derivation_path` in-place.
fn build_descriptor_public_key(
    e: &ExpandedKey,
    use_site: &UseSitePath,
    chain: u32,
) -> Result<DescriptorPublicKey, Error> {
    let xpub_bytes = e.xpub.ok_or(Error::MissingPubkey { idx: e.idx })?;
    let xkey = xpub_from_tlv_bytes(e.idx, &xpub_bytes)?;

    let origin = e.fingerprint.map(|fp| {
        (
            Fingerprint::from(fp),
            origin_path_to_derivation(&e.origin_path),
        )
    });

    // Derivation path is the use-site multipath alt (without the trailing
    // wildcard, which is handled via `Wildcard::Unhardened`).
    let derivation_path = use_site_to_derivation_path(use_site, chain)?;

    Ok(DescriptorPublicKey::XPub(DescriptorXKey {
        origin,
        xkey,
        derivation_path,
        wildcard: Wildcard::Unhardened,
    }))
}

/// Translate an `OriginPath` into a `bip32::DerivationPath`.
fn origin_path_to_derivation(p: &OriginPath) -> DerivationPath {
    let children: Vec<ChildNumber> = p
        .components
        .iter()
        .map(|c| {
            if c.hardened {
                ChildNumber::from_hardened_idx(c.value)
                    .unwrap_or(ChildNumber::Hardened { index: c.value })
            } else {
                ChildNumber::from_normal_idx(c.value)
                    .unwrap_or(ChildNumber::Normal { index: c.value })
            }
        })
        .collect();
    DerivationPath::from(children)
}

/// Build the per-key `derivation_path` from the use-site multipath: a
/// single `ChildNumber` for `multipath[chain]`, or empty when no
/// multipath. The trailing `/*` wildcard is encoded via the `wildcard`
/// field, not the path.
fn use_site_to_derivation_path(u: &UseSitePath, chain: u32) -> Result<DerivationPath, Error> {
    let mut comps: Vec<ChildNumber> = Vec::new();
    if let Some(alts) = &u.multipath {
        let alt = alts
            .get(chain as usize)
            .ok_or(Error::ChainIndexOutOfRange {
                chain,
                alt_count: alts.len(),
            })?;
        if alt.hardened {
            return Err(Error::HardenedPublicDerivation);
        }
        comps.push(ChildNumber::Normal { index: alt.value });
    }
    Ok(DerivationPath::from(comps))
}

/// Map an md1 top-level tree node onto a `miniscript::Descriptor`.
fn node_to_descriptor(
    node: &Node,
    keys: &[DescriptorPublicKey],
) -> Result<miniscript::Descriptor<DescriptorPublicKey>, Error> {
    match (&node.tag, &node.body) {
        (Tag::Pkh, Body::KeyArg { index }) => {
            let pk = lookup_key(keys, *index)?;
            miniscript::Descriptor::new_pkh(pk).map_err(|e| failed(e.to_string()))
        }
        (Tag::Wpkh, Body::KeyArg { index }) => {
            let pk = lookup_key(keys, *index)?;
            miniscript::Descriptor::new_wpkh(pk).map_err(|e| failed(e.to_string()))
        }
        (Tag::Sh, Body::Children(children)) if children.len() == 1 => {
            sh_inner_to_descriptor(&children[0], keys)
        }
        (Tag::Wsh, Body::Children(children)) if children.len() == 1 => {
            wsh_inner_to_descriptor(&children[0], keys)
        }
        (
            Tag::Tr,
            Body::Tr {
                is_nums,
                key_index,
                tree,
            },
        ) => {
            let internal_key = if *is_nums {
                build_nums_internal_key()?
            } else {
                lookup_key(keys, *key_index)?
            };
            let script_tree = if let Some(t) = tree {
                Some(tree_to_taptree(t, keys)?)
            } else {
                None
            };
            miniscript::Descriptor::new_tr(internal_key, script_tree)
                .map_err(|e| failed(e.to_string()))
        }
        _ => Err(failed(format!(
            "unsupported top-level tag {:?} with body shape",
            node.tag
        ))),
    }
}

/// Build the NUMS-point `DescriptorPublicKey` (BIP-341 H-point as a
/// single x-only descriptor key, no origin/path).
fn build_nums_internal_key() -> Result<DescriptorPublicKey, Error> {
    let x_only = bitcoin::secp256k1::XOnlyPublicKey::from_str(NUMS_H_POINT_X_ONLY_HEX)
        .map_err(|e| failed(format!("NUMS x-only parse: {e}")))?;
    Ok(DescriptorPublicKey::Single(SinglePub {
        origin: None,
        key: SinglePubKey::XOnly(x_only),
    }))
}

/// Descriptor-level `wsh(...)` inner: choose between
/// `Descriptor::new_wsh_sortedmulti` and `Descriptor::new_wsh(<Miniscript>)`.
fn wsh_inner_to_descriptor(
    inner: &Node,
    keys: &[DescriptorPublicKey],
) -> Result<miniscript::Descriptor<DescriptorPublicKey>, Error> {
    if let (Tag::SortedMulti, Body::MultiKeys { k, indices }) = (&inner.tag, &inner.body) {
        let thresh = build_multi_threshold::<{ MAX_PUBKEYS_PER_MULTISIG }>(
            *k,
            indices,
            keys,
            "wsh-sortedmulti",
        )?;
        return miniscript::Descriptor::new_wsh_sortedmulti(thresh)
            .map_err(|e| failed(e.to_string()));
    }
    let ms = node_to_miniscript::<Segwitv0>(inner, keys)?;
    miniscript::Descriptor::new_wsh(ms).map_err(|e| failed(e.to_string()))
}

/// Descriptor-level `sh(...)` inner: dispatch between `sh(wsh(...))`,
/// `sh(wpkh(...))`, `sh(sortedmulti(...))`, and `sh(<miniscript>)`
/// (Legacy context).
fn sh_inner_to_descriptor(
    inner: &Node,
    keys: &[DescriptorPublicKey],
) -> Result<miniscript::Descriptor<DescriptorPublicKey>, Error> {
    match (&inner.tag, &inner.body) {
        (Tag::Wsh, Body::Children(grand)) if grand.len() == 1 => {
            let grandchild = &grand[0];
            if let (Tag::SortedMulti, Body::MultiKeys { k, indices }) =
                (&grandchild.tag, &grandchild.body)
            {
                let thresh = build_multi_threshold::<{ MAX_PUBKEYS_PER_MULTISIG }>(
                    *k,
                    indices,
                    keys,
                    "sh-wsh-sortedmulti",
                )?;
                return miniscript::Descriptor::new_sh_wsh_sortedmulti(thresh)
                    .map_err(|e| failed(e.to_string()));
            }
            let ms = node_to_miniscript::<Segwitv0>(grandchild, keys)?;
            miniscript::Descriptor::new_sh_wsh(ms).map_err(|e| failed(e.to_string()))
        }
        (Tag::Wpkh, Body::KeyArg { index }) => {
            let pk = lookup_key(keys, *index)?;
            miniscript::Descriptor::new_sh_wpkh(pk).map_err(|e| failed(e.to_string()))
        }
        (Tag::SortedMulti, Body::MultiKeys { k, indices }) => {
            let thresh = build_multi_threshold::<{ MAX_PUBKEYS_PER_MULTISIG }>(
                *k,
                indices,
                keys,
                "sh-sortedmulti",
            )?;
            miniscript::Descriptor::new_sh_sortedmulti(thresh).map_err(|e| failed(e.to_string()))
        }
        _ => {
            let ms = node_to_miniscript::<Legacy>(inner, keys)?;
            miniscript::Descriptor::new_sh(ms).map_err(|e| failed(e.to_string()))
        }
    }
}

/// Recurse into a tap-script-tree node. Returns a `miniscript::TapTree`.
fn tree_to_taptree(
    node: &Node,
    keys: &[DescriptorPublicKey],
) -> Result<miniscript::descriptor::TapTree<DescriptorPublicKey>, Error> {
    if let (Tag::TapTree, Body::Children(children)) = (&node.tag, &node.body) {
        if children.len() != 2 {
            return Err(failed(format!(
                "Tag::TapTree expected 2 children, got {}",
                children.len()
            )));
        }
        let l = tree_to_taptree(&children[0], keys)?;
        let r = tree_to_taptree(&children[1], keys)?;
        return miniscript::descriptor::TapTree::combine(l, r)
            .map_err(|e| failed(format!("TapTree depth: {e}")));
    }
    // Single bare leaf — including the v0.30 single-leaf wire optimization
    // where `Body::Tr { tree: Some(<bare PkK Node>) }` skips the `Tag::TapTree`
    // wrap.
    let ms = node_to_miniscript::<Tap>(node, keys)?;
    Ok(miniscript::descriptor::TapTree::leaf(Arc::new(ms)))
}

/// Convert a miniscript-leaf md1 node into a `Miniscript<Pk, Ctx>`.
fn node_to_miniscript<Ctx>(
    node: &Node,
    keys: &[DescriptorPublicKey],
) -> Result<Miniscript<DescriptorPublicKey, Ctx>, Error>
where
    Ctx: ScriptContext,
{
    let term: Terminal<DescriptorPublicKey, Ctx> = match (&node.tag, &node.body) {
        (Tag::PkK, Body::KeyArg { index }) => {
            // Phase E: bare PkK always emits as Check(pk_k(...)) since
            // miniscript leaves require a `K` (check'd-key) at any
            // satisfied position. md1 wire normalises by stripping the
            // outer `c:` wrapper; re-apply here.
            let pk = lookup_key(keys, *index)?;
            let inner = Miniscript::from_ast(Terminal::PkK(pk)).map_err(into_failed)?;
            Terminal::Check(Arc::new(inner))
        }
        (Tag::PkH, Body::KeyArg { index }) => {
            let pk = lookup_key(keys, *index)?;
            let inner = Miniscript::from_ast(Terminal::PkH(pk)).map_err(into_failed)?;
            Terminal::Check(Arc::new(inner))
        }
        (Tag::Check, Body::Children(children)) => {
            arity_eq(node.tag, children.len(), 1)?;
            Terminal::Check(Arc::new(node_to_miniscript::<Ctx>(&children[0], keys)?))
        }
        (Tag::Verify, Body::Children(children)) => {
            arity_eq(node.tag, children.len(), 1)?;
            Terminal::Verify(Arc::new(node_to_miniscript::<Ctx>(&children[0], keys)?))
        }
        (Tag::Swap, Body::Children(children)) => {
            arity_eq(node.tag, children.len(), 1)?;
            Terminal::Swap(Arc::new(node_to_miniscript::<Ctx>(&children[0], keys)?))
        }
        (Tag::Alt, Body::Children(children)) => {
            arity_eq(node.tag, children.len(), 1)?;
            Terminal::Alt(Arc::new(node_to_miniscript::<Ctx>(&children[0], keys)?))
        }
        (Tag::DupIf, Body::Children(children)) => {
            arity_eq(node.tag, children.len(), 1)?;
            Terminal::DupIf(Arc::new(node_to_miniscript::<Ctx>(&children[0], keys)?))
        }
        (Tag::NonZero, Body::Children(children)) => {
            arity_eq(node.tag, children.len(), 1)?;
            Terminal::NonZero(Arc::new(node_to_miniscript::<Ctx>(&children[0], keys)?))
        }
        (Tag::ZeroNotEqual, Body::Children(children)) => {
            arity_eq(node.tag, children.len(), 1)?;
            Terminal::ZeroNotEqual(Arc::new(node_to_miniscript::<Ctx>(&children[0], keys)?))
        }
        (Tag::AndV, Body::Children(children)) => {
            arity_eq(node.tag, children.len(), 2)?;
            let l = node_to_miniscript::<Ctx>(&children[0], keys)?;
            let r = node_to_miniscript::<Ctx>(&children[1], keys)?;
            Terminal::AndV(Arc::new(l), Arc::new(r))
        }
        (Tag::AndB, Body::Children(children)) => {
            arity_eq(node.tag, children.len(), 2)?;
            let l = node_to_miniscript::<Ctx>(&children[0], keys)?;
            let r = node_to_miniscript::<Ctx>(&children[1], keys)?;
            Terminal::AndB(Arc::new(l), Arc::new(r))
        }
        (Tag::AndOr, Body::Children(children)) => {
            arity_eq(node.tag, children.len(), 3)?;
            let a = node_to_miniscript::<Ctx>(&children[0], keys)?;
            let b = node_to_miniscript::<Ctx>(&children[1], keys)?;
            let c = node_to_miniscript::<Ctx>(&children[2], keys)?;
            Terminal::AndOr(Arc::new(a), Arc::new(b), Arc::new(c))
        }
        (Tag::OrB, Body::Children(children)) => {
            arity_eq(node.tag, children.len(), 2)?;
            let l = node_to_miniscript::<Ctx>(&children[0], keys)?;
            let r = node_to_miniscript::<Ctx>(&children[1], keys)?;
            Terminal::OrB(Arc::new(l), Arc::new(r))
        }
        (Tag::OrC, Body::Children(children)) => {
            arity_eq(node.tag, children.len(), 2)?;
            let l = node_to_miniscript::<Ctx>(&children[0], keys)?;
            let r = node_to_miniscript::<Ctx>(&children[1], keys)?;
            Terminal::OrC(Arc::new(l), Arc::new(r))
        }
        (Tag::OrD, Body::Children(children)) => {
            arity_eq(node.tag, children.len(), 2)?;
            let l = node_to_miniscript::<Ctx>(&children[0], keys)?;
            let r = node_to_miniscript::<Ctx>(&children[1], keys)?;
            Terminal::OrD(Arc::new(l), Arc::new(r))
        }
        (Tag::OrI, Body::Children(children)) => {
            arity_eq(node.tag, children.len(), 2)?;
            let l = node_to_miniscript::<Ctx>(&children[0], keys)?;
            let r = node_to_miniscript::<Ctx>(&children[1], keys)?;
            Terminal::OrI(Arc::new(l), Arc::new(r))
        }
        (Tag::Thresh, Body::Variable { k, children }) => {
            let mut subs: Vec<Arc<Miniscript<DescriptorPublicKey, Ctx>>> =
                Vec::with_capacity(children.len());
            for c in children {
                subs.push(Arc::new(node_to_miniscript::<Ctx>(c, keys)?));
            }
            let thresh =
                Threshold::<_, 0>::new(*k as usize, subs).map_err(|e| failed(e.to_string()))?;
            Terminal::Thresh(thresh)
        }
        (Tag::Multi, Body::MultiKeys { k, indices }) => {
            // `Terminal::Multi` is `Ctx`-generic at the variant level;
            // rust-miniscript's `Miniscript::from_ast` enforces context-
            // appropriateness (rejects Multi inside Tap, MultiA inside
            // Segwitv0) via `check_global_consensus_validity`.
            let thresh =
                build_multi_threshold::<{ MAX_PUBKEYS_PER_MULTISIG }>(*k, indices, keys, "multi")?;
            Terminal::Multi(thresh)
        }
        (Tag::MultiA, Body::MultiKeys { k, indices }) => {
            let thresh = build_multi_threshold::<{ MAX_PUBKEYS_IN_CHECKSIGADD }>(
                *k, indices, keys, "multi_a",
            )?;
            Terminal::MultiA(thresh)
        }
        (Tag::SortedMulti, Body::MultiKeys { .. }) => {
            return Err(failed(
                "Tag::SortedMulti must be the sole child of wsh/sh; cannot appear as a miniscript leaf"
                    .to_string(),
            ));
        }
        (Tag::SortedMultiA, Body::MultiKeys { .. }) => {
            return Err(failed(
                "Tag::SortedMultiA must be a tap-leaf root child; rust-miniscript v13 has no Terminal::SortedMultiA fragment"
                    .to_string(),
            ));
        }
        (Tag::After, Body::Timelock(v)) => {
            let lt = AbsLockTime::from_consensus(*v).map_err(|e| failed(e.to_string()))?;
            Terminal::After(lt)
        }
        (Tag::Older, Body::Timelock(v)) => {
            let lt = RelLockTime::from_consensus(*v).map_err(|e| failed(e.to_string()))?;
            Terminal::Older(lt)
        }
        (Tag::Sha256, Body::Hash256Body(h)) => {
            let hash = sha256_from_bytes(h)?;
            Terminal::Sha256(hash)
        }
        (Tag::Hash256, Body::Hash256Body(h)) => {
            let hash = hash256_from_bytes(h)?;
            Terminal::Hash256(hash)
        }
        (Tag::Ripemd160, Body::Hash160Body(h)) => {
            let hash = ripemd160_from_bytes(h)?;
            Terminal::Ripemd160(hash)
        }
        (Tag::Hash160, Body::Hash160Body(h)) => {
            let hash = hash160_from_bytes(h)?;
            Terminal::Hash160(hash)
        }
        (Tag::RawPkH, Body::Hash160Body(_)) => {
            return Err(failed(
                "Tag::RawPkH is not constructible through miniscript's public API".to_string(),
            ));
        }
        (Tag::False, Body::Empty) => Terminal::False,
        (Tag::True, Body::Empty) => Terminal::True,
        (Tag::TapTree, _) => {
            return Err(failed(
                "Tag::TapTree is a tap-tree internal node, not a miniscript leaf".to_string(),
            ));
        }
        (Tag::Tr, _) | (Tag::Wsh, _) | (Tag::Sh, _) | (Tag::Wpkh, _) | (Tag::Pkh, _) => {
            return Err(failed(format!(
                "top-level wrapper {:?} cannot appear inside a miniscript context",
                node.tag
            )));
        }
        _ => {
            return Err(failed(format!(
                "tag {:?} unsupported with body shape",
                node.tag
            )));
        }
    };
    Miniscript::from_ast(term).map_err(into_failed)
}

fn lookup_key(keys: &[DescriptorPublicKey], idx: u8) -> Result<DescriptorPublicKey, Error> {
    keys.get(idx as usize)
        .cloned()
        .ok_or_else(|| failed(format!("@{idx} out of range")))
}

fn build_multi_threshold<const MAX: usize>(
    k: u8,
    indices: &[u8],
    keys: &[DescriptorPublicKey],
    label: &str,
) -> Result<Threshold<DescriptorPublicKey, MAX>, Error> {
    let pks: Vec<DescriptorPublicKey> = indices
        .iter()
        .map(|i| lookup_key(keys, *i))
        .collect::<Result<_, _>>()?;
    Threshold::<DescriptorPublicKey, MAX>::new(k as usize, pks)
        .map_err(|e| failed(format!("{label} threshold: {e}")))
}

fn arity_eq(tag: Tag, got: usize, expected: usize) -> Result<(), Error> {
    if got != expected {
        return Err(failed(format!(
            "{tag:?} expected {expected} children, got {got}"
        )));
    }
    Ok(())
}

fn failed(detail: String) -> Error {
    Error::AddressDerivationFailed { detail }
}

fn into_failed(e: miniscript::Error) -> Error {
    failed(e.to_string())
}

// ─── Pk::Sha256 / Pk::Hash256 / Pk::Ripemd160 / Pk::Hash160 construction ─

fn sha256_from_bytes(h: &[u8; 32]) -> Result<bitcoin::hashes::sha256::Hash, Error> {
    use bitcoin::hashes::Hash;
    Ok(bitcoin::hashes::sha256::Hash::from_byte_array(*h))
}

fn hash256_from_bytes(h: &[u8; 32]) -> Result<miniscript::hash256::Hash, Error> {
    use bitcoin::hashes::Hash;
    Ok(miniscript::hash256::Hash::from_byte_array(*h))
}

fn ripemd160_from_bytes(h: &[u8; 20]) -> Result<bitcoin::hashes::ripemd160::Hash, Error> {
    use bitcoin::hashes::Hash;
    Ok(bitcoin::hashes::ripemd160::Hash::from_byte_array(*h))
}

fn hash160_from_bytes(h: &[u8; 20]) -> Result<bitcoin::hashes::hash160::Hash, Error> {
    use bitcoin::hashes::Hash;
    Ok(bitcoin::hashes::hash160::Hash::from_byte_array(*h))
}