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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
// Miniscript
// Written in 2019 by
//     Sanket Kanjular and Andrew Poelstra
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//

use bitcoin;
use bitcoin::hashes::{hash160, sha256, Hash};

use super::{stack, Error, Stack};
use miniscript::context::NoChecks;
use {Miniscript, MiniscriptKey};

/// Attempts to parse a slice as a Bitcoin public key, checking compressedness
/// if asked to, but otherwise dropping it
fn pk_from_slice(slice: &[u8], require_compressed: bool) -> Result<bitcoin::PublicKey, Error> {
    if let Ok(pk) = bitcoin::PublicKey::from_slice(slice) {
        if require_compressed && !pk.compressed {
            Err(Error::UncompressedPubkey)
        } else {
            Ok(pk)
        }
    } else {
        Err(Error::PubkeyParseError)
    }
}

fn pk_from_stackelem<'a>(
    elem: &stack::Element<'a>,
    require_compressed: bool,
) -> Result<bitcoin::PublicKey, Error> {
    let slice = if let stack::Element::Push(slice) = *elem {
        slice
    } else {
        return Err(Error::PubkeyParseError);
    };
    pk_from_slice(slice, require_compressed)
}

fn script_from_stackelem<'a>(
    elem: &stack::Element<'a>,
) -> Result<Miniscript<bitcoin::PublicKey, NoChecks>, Error> {
    match *elem {
        stack::Element::Push(sl) => {
            Miniscript::parse_insane(&bitcoin::Script::from(sl.to_owned())).map_err(Error::from)
        }
        stack::Element::Satisfied => Miniscript::from_ast(::Terminal::True).map_err(Error::from),
        stack::Element::Dissatisfied => {
            Miniscript::from_ast(::Terminal::False).map_err(Error::from)
        }
    }
}

/// Helper type to indicate the origin of the bare pubkey that the interpereter uses
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum PubkeyType {
    Pk,
    Pkh,
    Wpkh,
    ShWpkh,
}

/// Helper type to indicate the origin of the bare miniscript that the interpereter uses
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum ScriptType {
    Bare,
    Sh,
    Wsh,
    ShWsh,
}

/// Structure representing a script under evaluation as a Miniscript
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Inner {
    /// The script being evaluated is a simple public key check (pay-to-pk,
    /// pay-to-pkhash or pay-to-witness-pkhash)
    PublicKey(bitcoin::PublicKey, PubkeyType),
    /// The script being evaluated is an actual script
    Script(Miniscript<bitcoin::PublicKey, NoChecks>, ScriptType),
}

// The `Script` returned by this method is always generated/cloned ... when
// rust-bitcoin is updated to use a copy-on-write internal representation we
// should revisit this and return references to the actual txdata wherever
// possible
/// Parses an `Inner` and appropriate `Stack` from completed transaction data,
/// as well as the script that should be used as a scriptCode in a sighash
pub fn from_txdata<'txin>(
    spk: &bitcoin::Script,
    script_sig: &'txin bitcoin::Script,
    witness: &'txin [Vec<u8>],
) -> Result<(Inner, Stack<'txin>, bitcoin::Script), Error> {
    let mut ssig_stack: Stack = script_sig
        .instructions_minimal()
        .map(stack::Element::from_instruction)
        .collect::<Result<Vec<stack::Element>, Error>>()?
        .into();
    let mut wit_stack: Stack = witness
        .iter()
        .map(stack::Element::from)
        .collect::<Vec<stack::Element>>()
        .into();

    // ** pay to pubkey **
    if spk.is_p2pk() {
        if !wit_stack.is_empty() {
            Err(Error::NonEmptyWitness)
        } else {
            Ok((
                Inner::PublicKey(
                    pk_from_slice(&spk[1..spk.len() - 1], false)?,
                    PubkeyType::Pk,
                ),
                ssig_stack,
                spk.clone(),
            ))
        }
    // ** pay to pubkeyhash **
    } else if spk.is_p2pkh() {
        if !wit_stack.is_empty() {
            Err(Error::NonEmptyWitness)
        } else {
            match ssig_stack.pop() {
                Some(elem) => {
                    let pk = pk_from_stackelem(&elem, false)?;
                    if *spk == bitcoin::Script::new_p2pkh(&pk.to_pubkeyhash().into()) {
                        Ok((
                            Inner::PublicKey(pk, PubkeyType::Pkh),
                            ssig_stack,
                            spk.clone(),
                        ))
                    } else {
                        Err(Error::IncorrectPubkeyHash)
                    }
                }
                None => Err(Error::UnexpectedStackEnd),
            }
        }
    // ** pay to witness pubkeyhash **
    } else if spk.is_v0_p2wpkh() {
        if !ssig_stack.is_empty() {
            Err(Error::NonEmptyScriptSig)
        } else {
            match wit_stack.pop() {
                Some(elem) => {
                    let pk = pk_from_stackelem(&elem, true)?;
                    if *spk == bitcoin::Script::new_v0_wpkh(&pk.to_pubkeyhash().into()) {
                        Ok((
                            Inner::PublicKey(pk, PubkeyType::Wpkh),
                            wit_stack,
                            bitcoin::Script::new_p2pkh(&pk.to_pubkeyhash().into()), // bip143, why..
                        ))
                    } else {
                        Err(Error::IncorrectWPubkeyHash)
                    }
                }
                None => Err(Error::UnexpectedStackEnd),
            }
        }
    // ** pay to witness scripthash **
    } else if spk.is_v0_p2wsh() {
        if !ssig_stack.is_empty() {
            Err(Error::NonEmptyScriptSig)
        } else {
            match wit_stack.pop() {
                Some(elem) => {
                    let miniscript = script_from_stackelem(&elem)?;
                    let script = miniscript.encode();
                    let scripthash = sha256::Hash::hash(&script[..]);
                    if *spk == bitcoin::Script::new_v0_wsh(&scripthash.into()) {
                        Ok((
                            Inner::Script(miniscript, ScriptType::Wsh),
                            wit_stack,
                            script,
                        ))
                    } else {
                        Err(Error::IncorrectWScriptHash)
                    }
                }
                None => Err(Error::UnexpectedStackEnd),
            }
        }
    // ** pay to scripthash **
    } else if spk.is_p2sh() {
        match ssig_stack.pop() {
            Some(elem) => {
                if let stack::Element::Push(slice) = elem {
                    let scripthash = hash160::Hash::hash(slice);
                    if *spk != bitcoin::Script::new_p2sh(&scripthash.into()) {
                        return Err(Error::IncorrectScriptHash);
                    }
                    // ** p2sh-wrapped wpkh **
                    if slice.len() == 22 && slice[0] == 0 && slice[1] == 20 {
                        return match wit_stack.pop() {
                            Some(elem) => {
                                if !ssig_stack.is_empty() {
                                    Err(Error::NonEmptyScriptSig)
                                } else {
                                    let pk = pk_from_stackelem(&elem, true)?;
                                    if slice
                                        == &bitcoin::Script::new_v0_wpkh(&pk.to_pubkeyhash().into())
                                            [..]
                                    {
                                        Ok((
                                            Inner::PublicKey(pk, PubkeyType::ShWpkh),
                                            wit_stack,
                                            bitcoin::Script::new_p2pkh(&pk.to_pubkeyhash().into()), // bip143, why..
                                        ))
                                    } else {
                                        Err(Error::IncorrectWScriptHash)
                                    }
                                }
                            }
                            None => Err(Error::UnexpectedStackEnd),
                        };
                    // ** p2sh-wrapped wsh **
                    } else if slice.len() == 34 && slice[0] == 0 && slice[1] == 32 {
                        return match wit_stack.pop() {
                            Some(elem) => {
                                if !ssig_stack.is_empty() {
                                    Err(Error::NonEmptyScriptSig)
                                } else {
                                    let miniscript = script_from_stackelem(&elem)?;
                                    let script = miniscript.encode();
                                    let scripthash = sha256::Hash::hash(&script[..]);
                                    if slice == &bitcoin::Script::new_v0_wsh(&scripthash.into())[..]
                                    {
                                        Ok((
                                            Inner::Script(miniscript, ScriptType::ShWsh),
                                            wit_stack,
                                            script,
                                        ))
                                    } else {
                                        Err(Error::IncorrectWScriptHash)
                                    }
                                }
                            }
                            None => Err(Error::UnexpectedStackEnd),
                        };
                    }
                }
                // normal p2sh
                let miniscript = script_from_stackelem(&elem)?;
                let script = miniscript.encode();
                if wit_stack.is_empty() {
                    let scripthash = hash160::Hash::hash(&script[..]);
                    if *spk == bitcoin::Script::new_p2sh(&scripthash.into()) {
                        Ok((
                            Inner::Script(miniscript, ScriptType::Sh),
                            ssig_stack,
                            script,
                        ))
                    } else {
                        Err(Error::IncorrectScriptHash)
                    }
                } else {
                    Err(Error::NonEmptyWitness)
                }
            }
            None => Err(Error::UnexpectedStackEnd),
        }
    // ** bare script **
    } else {
        if wit_stack.is_empty() {
            let miniscript = Miniscript::parse_insane(spk)?;
            Ok((
                Inner::Script(miniscript, ScriptType::Bare),
                ssig_stack,
                spk.clone(),
            ))
        } else {
            Err(Error::NonEmptyWitness)
        }
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use bitcoin::blockdata::script;
    use bitcoin::hashes::hex::FromHex;
    use bitcoin::hashes::{hash160, sha256, Hash};
    use bitcoin::{self, Script};
    use std::str::FromStr;

    struct KeyTestData {
        pk_spk: bitcoin::Script,
        pk_sig: bitcoin::Script,
        pkh_spk: bitcoin::Script,
        pkh_sig: bitcoin::Script,
        pkh_sig_justkey: bitcoin::Script,
        wpkh_spk: bitcoin::Script,
        wpkh_stack: Vec<Vec<u8>>,
        wpkh_stack_justkey: Vec<Vec<u8>>,
        sh_wpkh_spk: bitcoin::Script,
        sh_wpkh_sig: bitcoin::Script,
        sh_wpkh_stack: Vec<Vec<u8>>,
        sh_wpkh_stack_justkey: Vec<Vec<u8>>,
    }

    impl KeyTestData {
        fn from_key(key: bitcoin::PublicKey) -> KeyTestData {
            // what a funny looking signature..
            let dummy_sig = Vec::from_hex(
                "\
                302e02153b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63\
                    02153b78ce563f89a0ed9414f5aa28ad0d96d6795f9c65\
            ",
            )
            .unwrap();

            let pkhash = key.to_pubkeyhash().into();
            let wpkhash = key.to_pubkeyhash().into();
            let wpkh_spk = bitcoin::Script::new_v0_wpkh(&wpkhash);
            let wpkh_scripthash = hash160::Hash::hash(&wpkh_spk[..]).into();

            KeyTestData {
                pk_spk: bitcoin::Script::new_p2pk(&key),
                pkh_spk: bitcoin::Script::new_p2pkh(&pkhash),
                pk_sig: script::Builder::new().push_slice(&dummy_sig).into_script(),
                pkh_sig: script::Builder::new()
                    .push_slice(&dummy_sig)
                    .push_key(&key)
                    .into_script(),
                pkh_sig_justkey: script::Builder::new().push_key(&key).into_script(),
                wpkh_spk: wpkh_spk.clone(),
                wpkh_stack: vec![dummy_sig.clone(), key.to_bytes()],
                wpkh_stack_justkey: vec![key.to_bytes()],
                sh_wpkh_spk: bitcoin::Script::new_p2sh(&wpkh_scripthash),
                sh_wpkh_sig: script::Builder::new()
                    .push_slice(&wpkh_spk[..])
                    .into_script(),
                sh_wpkh_stack: vec![dummy_sig, key.to_bytes()],
                sh_wpkh_stack_justkey: vec![key.to_bytes()],
            }
        }
    }

    struct FixedTestData {
        pk_comp: bitcoin::PublicKey,
        pk_uncomp: bitcoin::PublicKey,
    }

    fn fixed_test_data() -> FixedTestData {
        FixedTestData {
            pk_comp: bitcoin::PublicKey::from_str(
                "\
                025edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143\
            ",
            )
            .unwrap(),
            pk_uncomp: bitcoin::PublicKey::from_str(
                "\
                045edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143\
                  efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868\
            ",
            )
            .unwrap(),
        }
    }

    #[test]
    fn pubkey_pk() {
        let fixed = fixed_test_data();
        let comp = KeyTestData::from_key(fixed.pk_comp);
        let uncomp = KeyTestData::from_key(fixed.pk_uncomp);
        let blank_script = bitcoin::Script::new();

        // Compressed pk, empty scriptsig
        let (inner, stack, script_code) =
            from_txdata(&comp.pk_spk, &blank_script, &[]).expect("parse txdata");
        assert_eq!(inner, Inner::PublicKey(fixed.pk_comp, PubkeyType::Pk));
        assert_eq!(stack, Stack::from(vec![]));
        assert_eq!(script_code, comp.pk_spk);

        // Uncompressed pk, empty scriptsig
        let (inner, stack, script_code) =
            from_txdata(&uncomp.pk_spk, &blank_script, &[]).expect("parse txdata");
        assert_eq!(inner, Inner::PublicKey(fixed.pk_uncomp, PubkeyType::Pk));
        assert_eq!(stack, Stack::from(vec![]));
        assert_eq!(script_code, uncomp.pk_spk);

        // Compressed pk, correct scriptsig
        let (inner, stack, script_code) =
            from_txdata(&comp.pk_spk, &comp.pk_sig, &[]).expect("parse txdata");
        assert_eq!(inner, Inner::PublicKey(fixed.pk_comp, PubkeyType::Pk));
        assert_eq!(stack, Stack::from(vec![comp.pk_sig[1..].into()]));
        assert_eq!(script_code, comp.pk_spk);

        // Uncompressed pk, correct scriptsig
        let (inner, stack, script_code) =
            from_txdata(&uncomp.pk_spk, &uncomp.pk_sig, &[]).expect("parse txdata");
        assert_eq!(inner, Inner::PublicKey(fixed.pk_uncomp, PubkeyType::Pk));
        assert_eq!(stack, Stack::from(vec![uncomp.pk_sig[1..].into()]));
        assert_eq!(script_code, uncomp.pk_spk);

        // Scriptpubkey has invalid key
        let mut spk = comp.pk_spk.to_bytes();
        spk[1] = 5;
        let spk = bitcoin::Script::from(spk);
        let err = from_txdata(&spk, &bitcoin::Script::new(), &[]).unwrap_err();
        assert_eq!(err.to_string(), "could not parse pubkey");

        // Scriptpubkey has invalid script
        let mut spk = comp.pk_spk.to_bytes();
        spk[0] = 100;
        let spk = bitcoin::Script::from(spk);
        let err = from_txdata(&spk, &bitcoin::Script::new(), &[]).unwrap_err();
        assert_eq!(&err.to_string()[0..12], "parse error:");

        // Witness is nonempty
        let err = from_txdata(&comp.pk_spk, &comp.pk_sig, &[vec![]]).unwrap_err();
        assert_eq!(err.to_string(), "legacy spend had nonempty witness");
    }

    #[test]
    fn pubkey_pkh() {
        let fixed = fixed_test_data();
        let comp = KeyTestData::from_key(fixed.pk_comp);
        let uncomp = KeyTestData::from_key(fixed.pk_uncomp);

        // pkh, empty scriptsig; this time it errors out
        let err = from_txdata(&comp.pkh_spk, &bitcoin::Script::new(), &[]).unwrap_err();
        assert_eq!(err.to_string(), "unexpected end of stack");

        // pkh, wrong pubkey
        let err = from_txdata(&comp.pkh_spk, &uncomp.pkh_sig_justkey, &[]).unwrap_err();
        assert_eq!(err.to_string(), "public key did not match scriptpubkey");

        // pkh, right pubkey, no signature
        let (inner, stack, script_code) =
            from_txdata(&comp.pkh_spk, &comp.pkh_sig_justkey, &[]).expect("parse txdata");
        assert_eq!(inner, Inner::PublicKey(fixed.pk_comp, PubkeyType::Pkh));
        assert_eq!(stack, Stack::from(vec![]));
        assert_eq!(script_code, comp.pkh_spk);

        let (inner, stack, script_code) =
            from_txdata(&uncomp.pkh_spk, &uncomp.pkh_sig_justkey, &[]).expect("parse txdata");
        assert_eq!(inner, Inner::PublicKey(fixed.pk_uncomp, PubkeyType::Pkh));
        assert_eq!(stack, Stack::from(vec![]));
        assert_eq!(script_code, uncomp.pkh_spk);

        // pkh, right pubkey, signature
        let (inner, stack, script_code) =
            from_txdata(&comp.pkh_spk, &comp.pkh_sig_justkey, &[]).expect("parse txdata");
        assert_eq!(inner, Inner::PublicKey(fixed.pk_comp, PubkeyType::Pkh));
        assert_eq!(stack, Stack::from(vec![]));
        assert_eq!(script_code, comp.pkh_spk);

        let (inner, stack, script_code) =
            from_txdata(&uncomp.pkh_spk, &uncomp.pkh_sig_justkey, &[]).expect("parse txdata");
        assert_eq!(inner, Inner::PublicKey(fixed.pk_uncomp, PubkeyType::Pkh));
        assert_eq!(stack, Stack::from(vec![]));
        assert_eq!(script_code, uncomp.pkh_spk);

        // Witness is nonempty
        let err = from_txdata(&comp.pkh_spk, &comp.pkh_sig, &[vec![]]).unwrap_err();
        assert_eq!(err.to_string(), "legacy spend had nonempty witness");
    }

    #[test]
    fn pubkey_wpkh() {
        let fixed = fixed_test_data();
        let comp = KeyTestData::from_key(fixed.pk_comp);
        let uncomp = KeyTestData::from_key(fixed.pk_uncomp);
        let blank_script = bitcoin::Script::new();

        // wpkh, empty witness; this time it errors out
        let err = from_txdata(&comp.wpkh_spk, &blank_script, &[]).unwrap_err();
        assert_eq!(err.to_string(), "unexpected end of stack");

        // wpkh, uncompressed pubkey
        let err =
            from_txdata(&comp.wpkh_spk, &blank_script, &uncomp.wpkh_stack_justkey).unwrap_err();
        assert_eq!(
            err.to_string(),
            "uncompressed pubkey in non-legacy descriptor"
        );

        // wpkh, wrong pubkey
        let err =
            from_txdata(&uncomp.wpkh_spk, &blank_script, &comp.wpkh_stack_justkey).unwrap_err();
        assert_eq!(
            err.to_string(),
            "public key did not match scriptpubkey (segwit v0)"
        );

        // wpkh, right pubkey, no signature
        let (inner, stack, script_code) =
            from_txdata(&comp.wpkh_spk, &blank_script, &comp.wpkh_stack_justkey)
                .expect("parse txdata");
        assert_eq!(inner, Inner::PublicKey(fixed.pk_comp, PubkeyType::Wpkh));
        assert_eq!(stack, Stack::from(vec![]));
        assert_eq!(script_code, comp.pkh_spk);

        // wpkh, right pubkey, signature
        let (inner, stack, script_code) =
            from_txdata(&comp.wpkh_spk, &blank_script, &comp.wpkh_stack).expect("parse txdata");
        assert_eq!(inner, Inner::PublicKey(fixed.pk_comp, PubkeyType::Wpkh));
        assert_eq!(stack, Stack::from(vec![comp.wpkh_stack[0][..].into()]));
        assert_eq!(script_code, comp.pkh_spk);

        // Scriptsig is nonempty
        let err = from_txdata(&comp.wpkh_spk, &comp.pk_sig, &comp.wpkh_stack_justkey).unwrap_err();
        assert_eq!(err.to_string(), "segwit spend had nonempty scriptsig");
    }

    #[test]
    fn pubkey_sh_wpkh() {
        let fixed = fixed_test_data();
        let comp = KeyTestData::from_key(fixed.pk_comp);
        let uncomp = KeyTestData::from_key(fixed.pk_uncomp);
        let blank_script = bitcoin::Script::new();

        // sh_wpkh, missing witness or scriptsig
        let err = from_txdata(&comp.sh_wpkh_spk, &blank_script, &[]).unwrap_err();
        assert_eq!(err.to_string(), "unexpected end of stack");
        let err = from_txdata(&comp.sh_wpkh_spk, &comp.sh_wpkh_sig, &[]).unwrap_err();
        assert_eq!(err.to_string(), "unexpected end of stack");
        let err = from_txdata(&comp.sh_wpkh_spk, &blank_script, &comp.sh_wpkh_stack).unwrap_err();
        assert_eq!(err.to_string(), "unexpected end of stack");

        // sh_wpkh, uncompressed pubkey
        let err = from_txdata(
            &uncomp.sh_wpkh_spk,
            &uncomp.sh_wpkh_sig,
            &uncomp.sh_wpkh_stack_justkey,
        )
        .unwrap_err();
        assert_eq!(
            err.to_string(),
            "uncompressed pubkey in non-legacy descriptor"
        );

        // sh_wpkh, wrong redeem script for scriptpubkey
        let err = from_txdata(
            &uncomp.sh_wpkh_spk,
            &comp.sh_wpkh_sig,
            &comp.sh_wpkh_stack_justkey,
        )
        .unwrap_err();
        assert_eq!(err.to_string(), "redeem script did not match scriptpubkey",);

        // sh_wpkh, wrong redeem script for witness script
        let err = from_txdata(
            &uncomp.sh_wpkh_spk,
            &uncomp.sh_wpkh_sig,
            &comp.sh_wpkh_stack_justkey,
        )
        .unwrap_err();
        assert_eq!(err.to_string(), "witness script did not match scriptpubkey",);

        // sh_wpkh, right pubkey, no signature
        let (inner, stack, script_code) = from_txdata(
            &comp.sh_wpkh_spk,
            &comp.sh_wpkh_sig,
            &comp.sh_wpkh_stack_justkey,
        )
        .expect("parse txdata");
        assert_eq!(inner, Inner::PublicKey(fixed.pk_comp, PubkeyType::ShWpkh));
        assert_eq!(stack, Stack::from(vec![]));
        assert_eq!(script_code, comp.pkh_spk);

        // sh_wpkh, right pubkey, signature
        let (inner, stack, script_code) =
            from_txdata(&comp.sh_wpkh_spk, &comp.sh_wpkh_sig, &comp.sh_wpkh_stack)
                .expect("parse txdata");
        assert_eq!(inner, Inner::PublicKey(fixed.pk_comp, PubkeyType::ShWpkh));
        assert_eq!(stack, Stack::from(vec![comp.sh_wpkh_stack[0][..].into()]));
        assert_eq!(script_code, comp.pkh_spk);
    }

    #[test]
    fn script_bare() {
        let preimage = b"12345678----____12345678----____";
        let hash = hash160::Hash::hash(&preimage[..]);
        let miniscript: ::Miniscript<bitcoin::PublicKey, NoChecks> =
            ::Miniscript::from_str_insane(&format!("hash160({})", hash)).unwrap();

        let spk = miniscript.encode();
        let blank_script = bitcoin::Script::new();

        // bare script has no validity requirements beyond being a sane script
        let (inner, stack, script_code) =
            from_txdata(&spk, &blank_script, &[]).expect("parse txdata");
        assert_eq!(inner, Inner::Script(miniscript, ScriptType::Bare));
        assert_eq!(stack, Stack::from(vec![]));
        assert_eq!(script_code, spk);

        let err = from_txdata(&blank_script, &blank_script, &[]).unwrap_err();
        assert_eq!(&err.to_string()[0..12], "parse error:");

        // nonempty witness
        let err = from_txdata(&spk, &blank_script, &[vec![]]).unwrap_err();
        assert_eq!(&err.to_string(), "legacy spend had nonempty witness");
    }

    #[test]
    fn script_sh() {
        let preimage = b"12345678----____12345678----____";
        let hash = hash160::Hash::hash(&preimage[..]);
        let miniscript: ::Miniscript<bitcoin::PublicKey, NoChecks> =
            ::Miniscript::from_str_insane(&format!("hash160({})", hash)).unwrap();

        let redeem_script = miniscript.encode();
        let rs_hash = hash160::Hash::hash(&redeem_script[..]).into();

        let spk = Script::new_p2sh(&rs_hash);
        let script_sig = script::Builder::new()
            .push_slice(&redeem_script[..])
            .into_script();
        let blank_script = bitcoin::Script::new();

        // sh without scriptsig
        let err = from_txdata(&spk, &blank_script, &[]).unwrap_err();
        assert_eq!(&err.to_string(), "unexpected end of stack");

        // with incorrect scriptsig
        let err = from_txdata(&spk, &spk, &[]).unwrap_err();
        assert_eq!(&err.to_string(), "expected push in script");

        // with correct scriptsig
        let (inner, stack, script_code) =
            from_txdata(&spk, &script_sig, &[]).expect("parse txdata");
        assert_eq!(inner, Inner::Script(miniscript, ScriptType::Sh));
        assert_eq!(stack, Stack::from(vec![]));
        assert_eq!(script_code, redeem_script);

        // nonempty witness
        let err = from_txdata(&spk, &script_sig, &[vec![]]).unwrap_err();
        assert_eq!(&err.to_string(), "legacy spend had nonempty witness");
    }

    #[test]
    fn script_wsh() {
        let preimage = b"12345678----____12345678----____";
        let hash = hash160::Hash::hash(&preimage[..]);
        let miniscript: ::Miniscript<bitcoin::PublicKey, NoChecks> =
            ::Miniscript::from_str_insane(&format!("hash160({})", hash)).unwrap();

        let witness_script = miniscript.encode();
        let wit_hash = sha256::Hash::hash(&witness_script[..]).into();
        let wit_stack = vec![witness_script.to_bytes()];

        let spk = Script::new_v0_wsh(&wit_hash);
        let blank_script = bitcoin::Script::new();

        // wsh without witness
        let err = from_txdata(&spk, &blank_script, &[]).unwrap_err();
        assert_eq!(&err.to_string(), "unexpected end of stack");

        // with incorrect witness
        let err = from_txdata(&spk, &blank_script, &[spk.to_bytes()]).unwrap_err();
        assert_eq!(&err.to_string()[0..12], "parse error:");

        // with correct witness
        let (inner, stack, script_code) =
            from_txdata(&spk, &blank_script, &wit_stack).expect("parse txdata");
        assert_eq!(inner, Inner::Script(miniscript, ScriptType::Wsh));
        assert_eq!(stack, Stack::from(vec![]));
        assert_eq!(script_code, witness_script);

        // nonempty script_sig
        let script_sig = script::Builder::new()
            .push_slice(&witness_script[..])
            .into_script();
        let err = from_txdata(&spk, &script_sig, &wit_stack).unwrap_err();
        assert_eq!(&err.to_string(), "segwit spend had nonempty scriptsig");
    }

    #[test]
    fn script_sh_wsh() {
        let preimage = b"12345678----____12345678----____";
        let hash = hash160::Hash::hash(&preimage[..]);
        let miniscript: ::Miniscript<bitcoin::PublicKey, NoChecks> =
            ::Miniscript::from_str_insane(&format!("hash160({})", hash)).unwrap();

        let witness_script = miniscript.encode();
        let wit_hash = sha256::Hash::hash(&witness_script[..]).into();
        let wit_stack = vec![witness_script.to_bytes()];

        let redeem_script = Script::new_v0_wsh(&wit_hash);
        let script_sig = script::Builder::new()
            .push_slice(&redeem_script[..])
            .into_script();
        let blank_script = bitcoin::Script::new();

        let rs_hash = hash160::Hash::hash(&redeem_script[..]).into();
        let spk = Script::new_p2sh(&rs_hash);

        // shwsh without witness or scriptsig
        let err = from_txdata(&spk, &blank_script, &[]).unwrap_err();
        assert_eq!(&err.to_string(), "unexpected end of stack");
        let err = from_txdata(&spk, &script_sig, &[]).unwrap_err();
        assert_eq!(&err.to_string(), "unexpected end of stack");
        let err = from_txdata(&spk, &blank_script, &wit_stack).unwrap_err();
        assert_eq!(&err.to_string(), "unexpected end of stack");

        // with incorrect witness
        let err = from_txdata(&spk, &script_sig, &[spk.to_bytes()]).unwrap_err();
        assert_eq!(&err.to_string()[0..12], "parse error:");

        // with incorrect scriptsig
        let err = from_txdata(&spk, &redeem_script, &wit_stack).unwrap_err();
        assert_eq!(&err.to_string(), "redeem script did not match scriptpubkey");

        // with correct witness
        let (inner, stack, script_code) =
            from_txdata(&spk, &script_sig, &wit_stack).expect("parse txdata");
        assert_eq!(inner, Inner::Script(miniscript, ScriptType::ShWsh));
        assert_eq!(stack, Stack::from(vec![]));
        assert_eq!(script_code, witness_script);
    }
}