bitcoin/blockdata/
script.rs

1// Rust Bitcoin Library
2// Written in 2014 by
3//     Andrew Poelstra <apoelstra@wpsoftware.net>
4//
5// To the extent possible under law, the author(s) have dedicated all
6// copyright and related and neighboring rights to this software to
7// the public domain worldwide. This software is distributed without
8// any warranty.
9//
10// You should have received a copy of the CC0 Public Domain Dedication
11// along with this software.
12// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
13//
14
15//! Script
16//!
17//! Scripts define Bitcoin's digital signature scheme: a signature is formed
18//! from a script (the second half of which is defined by a coin to be spent,
19//! and the first half provided by the spending transaction), and is valid
20//! iff the script leaves `TRUE` on the stack after being evaluated.
21//! Bitcoin's script is a stack-based assembly language similar in spirit to
22//! Forth.
23//!
24//! This module provides the structures and functions needed to support scripts.
25//!
26
27use std::default::Default;
28use std::{error, fmt, io, str};
29
30#[cfg(feature = "serde")] use serde;
31
32use hash_types::{PubkeyHash, WPubkeyHash, ScriptHash, WScriptHash};
33use blockdata::opcodes;
34use consensus::{encode, Decodable, Encodable};
35use hashes::{Hash, hex};
36#[cfg(feature="bitcoinconsensus")] use bitcoinconsensus;
37#[cfg(feature="bitcoinconsensus")] use std::convert;
38use secp256k1::Secp256k1;
39#[cfg(feature="bitcoinconsensus")] use OutPoint;
40
41use util::key::PublicKey;
42
43#[derive(Clone, Default, PartialOrd, Ord, PartialEq, Eq, Hash)]
44/// A Bitcoin script
45pub struct Script(Box<[u8]>);
46
47impl fmt::Debug for Script {
48    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
49        f.write_str("Script(")?;
50        self.fmt_asm(f)?;
51        f.write_str(")")
52    }
53}
54
55impl fmt::Display for Script {
56    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
57        fmt::Debug::fmt(self, f)
58    }
59}
60
61impl fmt::LowerHex for Script {
62    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63        for &ch in self.0.iter() {
64            write!(f, "{:02x}", ch)?;
65        }
66        Ok(())
67    }
68}
69
70impl fmt::UpperHex for Script {
71    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
72        for &ch in self.0.iter() {
73            write!(f, "{:02X}", ch)?;
74        }
75        Ok(())
76    }
77}
78
79impl hex::FromHex for Script {
80    fn from_byte_iter<I>(iter: I) -> Result<Self, hex::Error>
81        where I: Iterator<Item=Result<u8, hex::Error>> +
82            ExactSizeIterator +
83            DoubleEndedIterator,
84    {
85        Vec::from_byte_iter(iter).map(|v| Script(Box::<[u8]>::from(v)))
86    }
87}
88impl str::FromStr for Script {
89    type Err = hex::Error;
90    fn from_str(s: &str) -> Result<Self, hex::Error> {
91        hex::FromHex::from_hex(s)
92    }
93}
94
95#[derive(PartialEq, Eq, Debug, Clone)]
96/// An object which can be used to construct a script piece by piece
97pub struct Builder(Vec<u8>, Option<opcodes::All>);
98display_from_debug!(Builder);
99
100/// Ways that a script might fail. Not everything is split up as
101/// much as it could be; patches welcome if more detailed errors
102/// would help you.
103#[derive(PartialEq, Eq, Debug, Clone)]
104pub enum Error {
105    /// Something did a non-minimal push; for more information see
106    /// `https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#Push_operators`
107    NonMinimalPush,
108    /// Some opcode expected a parameter, but it was missing or truncated
109    EarlyEndOfScript,
110    /// Tried to read an array off the stack as a number when it was more than 4 bytes
111    NumericOverflow,
112    #[cfg(feature="bitcoinconsensus")]
113    /// Error validating the script with bitcoinconsensus library
114    BitcoinConsensus(bitcoinconsensus::Error),
115    #[cfg(feature="bitcoinconsensus")]
116    /// Can not find the spent output
117    UnknownSpentOutput(OutPoint),
118    #[cfg(feature="bitcoinconsensus")]
119    /// Can not serialize the spending transaction
120    SerializationError
121}
122
123impl fmt::Display for Error {
124    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
125        let str = match *self {
126            Error::NonMinimalPush => "non-minimal datapush",
127            Error::EarlyEndOfScript => "unexpected end of script",
128            Error::NumericOverflow => "numeric overflow (number on stack larger than 4 bytes)",
129            #[cfg(feature="bitcoinconsensus")]
130            Error::BitcoinConsensus(ref _n) => "bitcoinconsensus verification failed",
131            #[cfg(feature="bitcoinconsensus")]
132            Error::UnknownSpentOutput(ref _point) => "unknown spent output Transaction::verify()",
133            #[cfg(feature="bitcoinconsensus")]
134            Error::SerializationError => "can not serialize the spending transaction in Transaction::verify()",
135        };
136        f.write_str(str)
137    }
138}
139
140impl error::Error for Error {}
141
142#[cfg(feature="bitcoinconsensus")]
143#[doc(hidden)]
144impl convert::From<bitcoinconsensus::Error> for Error {
145    fn from(err: bitcoinconsensus::Error) -> Error {
146        match err {
147            _ => Error::BitcoinConsensus(err)
148        }
149    }
150}
151/// Helper to encode an integer in script format
152fn build_scriptint(n: i64) -> Vec<u8> {
153    if n == 0 { return vec![] }
154
155    let neg = n < 0;
156
157    let mut abs = if neg { -n } else { n } as usize;
158    let mut v = vec![];
159    while abs > 0xFF {
160        v.push((abs & 0xFF) as u8);
161        abs >>= 8;
162    }
163    // If the number's value causes the sign bit to be set, we need an extra
164    // byte to get the correct value and correct sign bit
165    if abs & 0x80 != 0 {
166        v.push(abs as u8);
167        v.push(if neg { 0x80u8 } else { 0u8 });
168    }
169    // Otherwise we just set the sign bit ourselves
170    else {
171        abs |= if neg { 0x80 } else { 0 };
172        v.push(abs as u8);
173    }
174    v
175}
176
177/// Helper to decode an integer in script format
178/// Notice that this fails on overflow: the result is the same as in
179/// bitcoind, that only 4-byte signed-magnitude values may be read as
180/// numbers. They can be added or subtracted (and a long time ago,
181/// multiplied and divided), and this may result in numbers which
182/// can't be written out in 4 bytes or less. This is ok! The number
183/// just can't be read as a number again.
184/// This is a bit crazy and subtle, but it makes sense: you can load
185/// 32-bit numbers and do anything with them, which back when mult/div
186/// was allowed, could result in up to a 64-bit number. We don't want
187/// overflow since that's surprising --- and we don't want numbers that
188/// don't fit in 64 bits (for efficiency on modern processors) so we
189/// simply say, anything in excess of 32 bits is no longer a number.
190/// This is basically a ranged type implementation.
191pub fn read_scriptint(v: &[u8]) -> Result<i64, Error> {
192    let len = v.len();
193    if len == 0 { return Ok(0); }
194    if len > 4 { return Err(Error::NumericOverflow); }
195
196    let (mut ret, sh) = v.iter()
197                         .fold((0, 0), |(acc, sh), n| (acc + ((*n as i64) << sh), sh + 8));
198    if v[len - 1] & 0x80 != 0 {
199        ret &= (1 << (sh - 1)) - 1;
200        ret = -ret;
201    }
202    Ok(ret)
203}
204
205/// This is like "`read_scriptint` then map 0 to false and everything
206/// else as true", except that the overflow rules don't apply.
207#[inline]
208pub fn read_scriptbool(v: &[u8]) -> bool {
209    !(v.is_empty() ||
210        ((v[v.len() - 1] == 0 || v[v.len() - 1] == 0x80) &&
211         v.iter().rev().skip(1).all(|&w| w == 0)))
212}
213
214/// Read a script-encoded unsigned integer
215pub fn read_uint(data: &[u8], size: usize) -> Result<usize, Error> {
216    if data.len() < size {
217        Err(Error::EarlyEndOfScript)
218    } else {
219        let mut ret = 0;
220        for (i, item) in data.iter().take(size).enumerate() {
221            ret += (*item as usize) << (i * 8);
222        }
223        Ok(ret)
224    }
225}
226
227impl Script {
228    /// Creates a new empty script
229    pub fn new() -> Script { Script(vec![].into_boxed_slice()) }
230
231    /// Generates P2PK-type of scriptPubkey
232    pub fn new_p2pk(secp: &Secp256k1, pubkey: &PublicKey) -> Script {
233        Builder::new()
234            .push_key(secp, pubkey)
235            .push_opcode(opcodes::all::OP_CHECKSIG)
236            .into_script()
237    }
238
239    /// Generates P2PKH-type of scriptPubkey
240    pub fn new_p2pkh(pubkey_hash: &PubkeyHash) -> Script {
241        Builder::new()
242            .push_opcode(opcodes::all::OP_DUP)
243            .push_opcode(opcodes::all::OP_HASH160)
244            .push_slice(&pubkey_hash[..])
245            .push_opcode(opcodes::all::OP_EQUALVERIFY)
246            .push_opcode(opcodes::all::OP_CHECKSIG)
247            .into_script()
248    }
249
250    /// Generates P2SH-type of scriptPubkey with a given hash of the redeem script
251    pub fn new_p2sh(script_hash: &ScriptHash) -> Script {
252        Builder::new()
253            .push_opcode(opcodes::all::OP_HASH160)
254            .push_slice(&script_hash[..])
255            .push_opcode(opcodes::all::OP_EQUAL)
256            .into_script()
257    }
258
259    /// Generates P2WPKH-type of scriptPubkey
260    pub fn new_v0_wpkh(pubkey_hash: &WPubkeyHash) -> Script {
261        Script::new_witness_program(::bech32::u5::try_from_u8(0).unwrap(), &pubkey_hash.to_vec())
262    }
263
264    /// Generates P2WSH-type of scriptPubkey with a given hash of the redeem script
265    pub fn new_v0_wsh(script_hash: &WScriptHash) -> Script {
266        Script::new_witness_program(::bech32::u5::try_from_u8(0).unwrap(), &script_hash.to_vec())
267    }
268
269    /// Generates P2WSH-type of scriptPubkey with a given hash of the redeem script
270    pub fn new_witness_program(ver: ::bech32::u5, program: &[u8]) -> Script {
271        let mut verop = ver.to_u8();
272        assert!(verop <= 16, "incorrect witness version provided: {}", verop);
273        if verop > 0 {
274            verop = 0x50 + verop;
275        }
276        Builder::new()
277            .push_opcode(verop.into())
278            .push_slice(&program)
279            .into_script()
280    }
281
282    /// Generates OP_RETURN-type of scriptPubkey for a given data
283    pub fn new_op_return(data: &[u8]) -> Script {
284        Builder::new()
285            .push_opcode(opcodes::all::OP_RETURN)
286            .push_slice(data)
287            .into_script()
288    }
289
290    /// Returns 160-bit hash of the script
291    pub fn script_hash(&self) -> ScriptHash {
292        ScriptHash::hash(&self.as_bytes())
293    }
294
295    /// Returns 256-bit hash of the script for P2WSH outputs
296    pub fn wscript_hash(&self) -> WScriptHash {
297        WScriptHash::hash(&self.as_bytes())
298    }
299
300    /// The length in bytes of the script
301    pub fn len(&self) -> usize { self.0.len() }
302
303    /// Whether the script is the empty script
304    pub fn is_empty(&self) -> bool { self.0.is_empty() }
305
306    /// Returns the script data
307    pub fn as_bytes(&self) -> &[u8] { &*self.0 }
308
309    /// Returns a copy of the script data
310    pub fn to_bytes(&self) -> Vec<u8> { self.0.clone().into_vec() }
311
312    /// Convert the script into a byte vector
313    pub fn into_bytes(self) -> Vec<u8> { self.0.into_vec() }
314
315    /// Compute the P2SH output corresponding to this redeem script
316    pub fn to_p2sh(&self) -> Script {
317        Script::new_p2sh(&self.script_hash())
318    }
319
320    /// Compute the P2WSH output corresponding to this witnessScript (aka the "witness redeem
321    /// script")
322    pub fn to_v0_p2wsh(&self) -> Script {
323        Script::new_v0_wsh(&self.wscript_hash())
324    }
325
326    /// Checks whether a script pubkey is a p2sh output
327    #[inline]
328    pub fn is_p2sh(&self) -> bool {
329        self.0.len() == 23 &&
330        self.0[0] == opcodes::all::OP_HASH160.into_u8() &&
331        self.0[1] == opcodes::all::OP_PUSHBYTES_20.into_u8() &&
332        self.0[22] == opcodes::all::OP_EQUAL.into_u8()
333    }
334
335    /// Checks whether a script pubkey is a p2pkh output
336    #[inline]
337    pub fn is_p2pkh(&self) -> bool {
338        self.0.len() == 25 &&
339        self.0[0] == opcodes::all::OP_DUP.into_u8() &&
340        self.0[1] == opcodes::all::OP_HASH160.into_u8() &&
341        self.0[2] == opcodes::all::OP_PUSHBYTES_20.into_u8() &&
342        self.0[23] == opcodes::all::OP_EQUALVERIFY.into_u8() &&
343        self.0[24] == opcodes::all::OP_CHECKSIG.into_u8()
344    }
345
346    /// Checks whether a script pubkey is a p2pk output
347    #[inline]
348    pub fn is_p2pk(&self) -> bool {
349        (self.0.len() == 67 &&
350            self.0[0] == opcodes::all::OP_PUSHBYTES_65.into_u8() &&
351            self.0[66] == opcodes::all::OP_CHECKSIG.into_u8())
352     || (self.0.len() == 35 &&
353            self.0[0] == opcodes::all::OP_PUSHBYTES_33.into_u8() &&
354            self.0[34] == opcodes::all::OP_CHECKSIG.into_u8())
355    }
356
357    /// Checks whether a script pubkey is a Segregated Witness (segwit) program.
358    #[inline]
359    pub fn is_witness_program(&self) -> bool {
360        // A scriptPubKey (or redeemScript as defined in BIP16/P2SH) that consists of a 1-byte
361        // push opcode (for 0 to 16) followed by a data push between 2 and 40 bytes gets a new
362        // special meaning. The value of the first push is called the "version byte". The following
363        // byte vector pushed is called the "witness program".
364        let min_vernum: u8 = opcodes::all::OP_PUSHNUM_1.into_u8();
365        let max_vernum: u8 = opcodes::all::OP_PUSHNUM_16.into_u8();
366        self.0.len() >= 4
367            && self.0.len() <= 42
368            // Version 0 or PUSHNUM_1-PUSHNUM_16
369            && (self.0[0] == 0 || self.0[0] >= min_vernum && self.0[0] <= max_vernum)
370            // Second byte push opcode 2-40 bytes
371            && self.0[1] >= opcodes::all::OP_PUSHBYTES_2.into_u8()
372            && self.0[1] <= opcodes::all::OP_PUSHBYTES_40.into_u8()
373            // Check that the rest of the script has the correct size
374            && self.0.len() - 2 == self.0[1] as usize
375    }
376
377    /// Checks whether a script pubkey is a p2wsh output
378    #[inline]
379    pub fn is_v0_p2wsh(&self) -> bool {
380        self.0.len() == 34 &&
381        self.0[0] == opcodes::all::OP_PUSHBYTES_0.into_u8() &&
382        self.0[1] == opcodes::all::OP_PUSHBYTES_32.into_u8()
383    }
384
385    /// Checks whether a script pubkey is a p2wpkh output
386    #[inline]
387    pub fn is_v0_p2wpkh(&self) -> bool {
388        self.0.len() == 22 &&
389            self.0[0] == opcodes::all::OP_PUSHBYTES_0.into_u8() &&
390            self.0[1] == opcodes::all::OP_PUSHBYTES_20.into_u8()
391    }
392
393    /// Check if this is an OP_RETURN output
394    pub fn is_op_return (&self) -> bool {
395        !self.0.is_empty() && (opcodes::All::from(self.0[0]) == opcodes::all::OP_RETURN)
396    }
397
398    /// Whether a script can be proven to have no satisfying input
399    pub fn is_provably_unspendable(&self) -> bool {
400        !self.0.is_empty() && (opcodes::All::from(self.0[0]).classify() == opcodes::Class::ReturnOp ||
401                               opcodes::All::from(self.0[0]).classify() == opcodes::Class::IllegalOp)
402    }
403
404    /// Iterate over the script in the form of `Instruction`s, which are an enum covering
405    /// opcodes, datapushes and errors. At most one error will be returned and then the
406    /// iterator will end. To instead iterate over the script as sequence of bytes, treat
407    /// it as a slice using `script[..]` or convert it to a vector using `into_bytes()`.
408    ///
409    /// To force minimal pushes, use [instructions_minimal].
410    pub fn instructions(&self) -> Instructions {
411        Instructions {
412            data: &self.0[..],
413            enforce_minimal: false,
414        }
415    }
416
417    /// Iterate over the script in the form of `Instruction`s while enforcing
418    /// minimal pushes.
419    pub fn instructions_minimal(&self) -> Instructions {
420        Instructions {
421            data: &self.0[..],
422            enforce_minimal: true,
423        }
424    }
425
426    #[cfg(feature="bitcoinconsensus")]
427    /// verify spend of an input script
428    /// # Parameters
429    ///  * index - the input index in spending which is spending this transaction
430    ///  * amount - the amount this script guards
431    ///  * spending - the transaction that attempts to spend the output holding this script
432    pub fn verify (&self, index: usize, amount: u64, spending: &[u8]) -> Result<(), Error> {
433        Ok(bitcoinconsensus::verify (&self.0[..], amount, spending, index)?)
434    }
435
436    /// Write the assembly decoding of the script to the formatter.
437    pub fn fmt_asm(&self, f: &mut dyn fmt::Write) -> fmt::Result {
438        let mut index = 0;
439        while index < self.0.len() {
440            let opcode = opcodes::All::from(self.0[index]);
441            index += 1;
442
443            let data_len = if let opcodes::Class::PushBytes(n) = opcode.classify() {
444                n as usize
445            } else {
446                match opcode {
447                    opcodes::all::OP_PUSHDATA1 => {
448                        if self.0.len() < index + 1 {
449                            f.write_str("<unexpected end>")?;
450                            break;
451                        }
452                        match read_uint(&self.0[index..], 1) {
453                            Ok(n) => { index += 1; n as usize }
454                            Err(_) => { f.write_str("<bad length>")?; break; }
455                        }
456                    }
457                    opcodes::all::OP_PUSHDATA2 => {
458                        if self.0.len() < index + 2 {
459                            f.write_str("<unexpected end>")?;
460                            break;
461                        }
462                        match read_uint(&self.0[index..], 2) {
463                            Ok(n) => { index += 2; n as usize }
464                            Err(_) => { f.write_str("<bad length>")?; break; }
465                        }
466                    }
467                    opcodes::all::OP_PUSHDATA4 => {
468                        if self.0.len() < index + 4 {
469                            f.write_str("<unexpected end>")?;
470                            break;
471                        }
472                        match read_uint(&self.0[index..], 4) {
473                            Ok(n) => { index += 4; n as usize }
474                            Err(_) => { f.write_str("<bad length>")?; break; }
475                        }
476                    }
477                    _ => 0
478                }
479            };
480
481            if index > 1 { f.write_str(" ")?; }
482            // Write the opcode
483            if opcode == opcodes::all::OP_PUSHBYTES_0 {
484                f.write_str("OP_0")?;
485            } else {
486                write!(f, "{:?}", opcode)?;
487            }
488            // Write any pushdata
489            if data_len > 0 {
490                f.write_str(" ")?;
491                if index + data_len <= self.0.len() {
492                    for ch in &self.0[index..index + data_len] {
493                            write!(f, "{:02x}", ch)?;
494                    }
495                    index += data_len;
496                } else {
497                    f.write_str("<push past end>")?;
498                    break;
499                }
500            }
501        }
502        Ok(())
503    }
504
505    /// Get the assembly decoding of the script.
506    pub fn asm(&self) -> String {
507        let mut buf = String::new();
508        self.fmt_asm(&mut buf).unwrap();
509        buf
510    }
511}
512
513/// Creates a new script from an existing vector
514impl From<Vec<u8>> for Script {
515    fn from(v: Vec<u8>) -> Script { Script(v.into_boxed_slice()) }
516}
517
518impl_index_newtype!(Script, u8);
519
520/// A "parsed opcode" which allows iterating over a Script in a more sensible way
521#[derive(Debug, PartialEq, Eq, Clone)]
522pub enum Instruction<'a> {
523    /// Push a bunch of data
524    PushBytes(&'a [u8]),
525    /// Some non-push opcode
526    Op(opcodes::All),
527}
528
529/// Iterator over a script returning parsed opcodes
530pub struct Instructions<'a> {
531    data: &'a [u8],
532    enforce_minimal: bool,
533}
534
535impl<'a> Iterator for Instructions<'a> {
536    type Item = Result<Instruction<'a>, Error>;
537
538    fn next(&mut self) -> Option<Result<Instruction<'a>, Error>> {
539        if self.data.is_empty() {
540            return None;
541        }
542
543        match opcodes::All::from(self.data[0]).classify() {
544            opcodes::Class::PushBytes(n) => {
545                let n = n as usize;
546                if self.data.len() < n + 1 {
547                    self.data = &[];  // Kill iterator so that it does not return an infinite stream of errors
548                    return Some(Err(Error::EarlyEndOfScript));
549                }
550                if self.enforce_minimal {
551                    if n == 1 && (self.data[1] == 0x81 || (self.data[1] > 0 && self.data[1] <= 16)) {
552                        self.data = &[];
553                        return Some(Err(Error::NonMinimalPush));
554                    }
555                }
556                let ret = Some(Ok(Instruction::PushBytes(&self.data[1..n+1])));
557                self.data = &self.data[n + 1..];
558                ret
559            }
560            opcodes::Class::Ordinary(opcodes::Ordinary::OP_PUSHDATA1) => {
561                if self.data.len() < 2 {
562                    self.data = &[];
563                    return Some(Err(Error::EarlyEndOfScript));
564                }
565                let n = match read_uint(&self.data[1..], 1) {
566                    Ok(n) => n,
567                    Err(e) => {
568                        self.data = &[];
569                        return Some(Err(e));
570                    }
571                };
572                if self.data.len() < n + 2 {
573                    self.data = &[];
574                    return Some(Err(Error::EarlyEndOfScript));
575                }
576                if self.enforce_minimal && n < 76 {
577                    self.data = &[];
578                    return Some(Err(Error::NonMinimalPush));
579                }
580                let ret = Some(Ok(Instruction::PushBytes(&self.data[2..n+2])));
581                self.data = &self.data[n + 2..];
582                ret
583            }
584            opcodes::Class::Ordinary(opcodes::Ordinary::OP_PUSHDATA2) => {
585                if self.data.len() < 3 {
586                    self.data = &[];
587                    return Some(Err(Error::EarlyEndOfScript));
588                }
589                let n = match read_uint(&self.data[1..], 2) {
590                    Ok(n) => n,
591                    Err(e) => {
592                        self.data = &[];
593                        return Some(Err(e));
594                    }
595                };
596                if self.enforce_minimal && n < 0x100 {
597                    self.data = &[];
598                    return Some(Err(Error::NonMinimalPush));
599                }
600                if self.data.len() < n + 3 {
601                    self.data = &[];
602                    return Some(Err(Error::EarlyEndOfScript));
603                }
604                let ret = Some(Ok(Instruction::PushBytes(&self.data[3..n + 3])));
605                self.data = &self.data[n + 3..];
606                ret
607            }
608            opcodes::Class::Ordinary(opcodes::Ordinary::OP_PUSHDATA4) => {
609                if self.data.len() < 5 {
610                    self.data = &[];
611                    return Some(Err(Error::EarlyEndOfScript));
612                }
613                let n = match read_uint(&self.data[1..], 4) {
614                    Ok(n) => n,
615                    Err(e) => {
616                        self.data = &[];
617                        return Some(Err(e));
618                    }
619                };
620                if self.enforce_minimal && n < 0x10000 {
621                    self.data = &[];
622                    return Some(Err(Error::NonMinimalPush));
623                }
624                if self.data.len() < n + 5 {
625                    self.data = &[];
626                    return Some(Err(Error::EarlyEndOfScript));
627                }
628                let ret = Some(Ok(Instruction::PushBytes(&self.data[5..n + 5])));
629                self.data = &self.data[n + 5..];
630                ret
631            }
632            // Everything else we can push right through
633            _ => {
634                let ret = Some(Ok(Instruction::Op(opcodes::All::from(self.data[0]))));
635                self.data = &self.data[1..];
636                ret
637            }
638        }
639    }
640}
641
642impl Builder {
643    /// Creates a new empty script
644    pub fn new() -> Self {
645        Builder(vec![], None)
646    }
647
648    /// The length in bytes of the script
649    pub fn len(&self) -> usize { self.0.len() }
650
651    /// Whether the script is the empty script
652    pub fn is_empty(&self) -> bool { self.0.is_empty() }
653
654    /// Adds instructions to push an integer onto the stack. Integers are
655    /// encoded as little-endian signed-magnitude numbers, but there are
656    /// dedicated opcodes to push some small integers.
657    pub fn push_int(self, data: i64) -> Builder {
658        // We can special-case -1, 1-16
659        if data == -1 || (data >= 1 && data <= 16) {
660            let opcode = opcodes::All::from(
661                (data - 1 + opcodes::OP_TRUE.into_u8() as i64) as u8
662            );
663            self.push_opcode(opcode)
664        }
665        // We can also special-case zero
666        else if data == 0 {
667            self.push_opcode(opcodes::OP_FALSE)
668        }
669        // Otherwise encode it as data
670        else { self.push_scriptint(data) }
671    }
672
673    /// Adds instructions to push an integer onto the stack, using the explicit
674    /// encoding regardless of the availability of dedicated opcodes.
675    pub fn push_scriptint(self, data: i64) -> Builder {
676        self.push_slice(&build_scriptint(data))
677    }
678
679    /// Adds instructions to push some arbitrary data onto the stack
680    pub fn push_slice(mut self, data: &[u8]) -> Builder {
681        // Start with a PUSH opcode
682        match data.len() as u64 {
683            n if n < opcodes::Ordinary::OP_PUSHDATA1 as u64 => { self.0.push(n as u8); },
684            n if n < 0x100 => {
685                self.0.push(opcodes::Ordinary::OP_PUSHDATA1.into_u8());
686                self.0.push(n as u8);
687            },
688            n if n < 0x10000 => {
689                self.0.push(opcodes::Ordinary::OP_PUSHDATA2.into_u8());
690                self.0.push((n % 0x100) as u8);
691                self.0.push((n / 0x100) as u8);
692            },
693            n if n < 0x100000000 => {
694                self.0.push(opcodes::Ordinary::OP_PUSHDATA4.into_u8());
695                self.0.push((n % 0x100) as u8);
696                self.0.push(((n / 0x100) % 0x100) as u8);
697                self.0.push(((n / 0x10000) % 0x100) as u8);
698                self.0.push((n / 0x1000000) as u8);
699            }
700            _ => panic!("tried to put a 4bn+ sized object into a script!")
701        }
702        // Then push the raw bytes
703        self.0.extend(data.iter().cloned());
704        self.1 = None;
705        self
706    }
707
708    /// Pushes a public key
709    pub fn push_key(self, secp: &Secp256k1, key: &PublicKey) -> Builder {
710        if key.compressed {
711            self.push_slice(&key.key.serialize_vec(secp, true)[..])
712        } else {
713            self.push_slice(&key.key.serialize_vec(secp, false)[..])
714        }
715    }
716
717    /// Adds a single opcode to the script
718    pub fn push_opcode(mut self, data: opcodes::All) -> Builder {
719        self.0.push(data.into_u8());
720        self.1 = Some(data);
721        self
722    }
723
724    /// Adds an `OP_VERIFY` to the script, unless the most-recently-added
725    /// opcode has an alternate `VERIFY` form, in which case that opcode
726    /// is replaced. e.g. `OP_CHECKSIG` will become `OP_CHECKSIGVERIFY`.
727    pub fn push_verify(mut self) -> Builder {
728        match self.1 {
729            Some(opcodes::all::OP_EQUAL) => {
730                self.0.pop();
731                self.push_opcode(opcodes::all::OP_EQUALVERIFY)
732            },
733            Some(opcodes::all::OP_NUMEQUAL) => {
734                self.0.pop();
735                self.push_opcode(opcodes::all::OP_NUMEQUALVERIFY)
736            },
737            Some(opcodes::all::OP_CHECKSIG) => {
738                self.0.pop();
739                self.push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
740            },
741            Some(opcodes::all::OP_CHECKMULTISIG) => {
742                self.0.pop();
743                self.push_opcode(opcodes::all::OP_CHECKMULTISIGVERIFY)
744            },
745            _ => self.push_opcode(opcodes::all::OP_VERIFY),
746        }
747    }
748
749    /// Converts the `Builder` into an unmodifiable `Script`
750    pub fn into_script(self) -> Script {
751        Script(self.0.into_boxed_slice())
752    }
753}
754
755/// Adds an individual opcode to the script
756impl Default for Builder {
757    fn default() -> Builder { Builder::new() }
758}
759
760/// Creates a new script from an existing vector
761impl From<Vec<u8>> for Builder {
762    fn from(v: Vec<u8>) -> Builder {
763        let script = Script(v.into_boxed_slice());
764        let last_op = match script.instructions().last() {
765            Some(Ok(Instruction::Op(op))) => Some(op),
766            _ => None,
767        };
768        Builder(script.into_bytes(), last_op)
769    }
770}
771
772impl_index_newtype!(Builder, u8);
773
774#[cfg(feature = "serde")]
775impl<'de> serde::Deserialize<'de> for Script {
776    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
777    where
778        D: serde::Deserializer<'de>,
779    {
780        use std::fmt::Formatter;
781        use hashes::hex::FromHex;
782
783        struct Visitor;
784        impl<'de> serde::de::Visitor<'de> for Visitor {
785            type Value = Script;
786
787            fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
788                formatter.write_str("a script")
789            }
790
791            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
792            where
793                E: serde::de::Error,
794            {
795                let v = Vec::from_hex(v).map_err(E::custom)?;
796                Ok(Script::from(v))
797            }
798
799            fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
800            where
801                E: serde::de::Error,
802            {
803                self.visit_str(v)
804            }
805
806            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
807            where
808                E: serde::de::Error,
809            {
810                self.visit_str(&v)
811            }
812        }
813
814        deserializer.deserialize_str(Visitor)
815    }
816}
817
818#[cfg(feature = "serde")]
819impl serde::Serialize for Script {
820    /// User-facing serialization for `Script`.
821    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
822    where
823        S: serde::Serializer,
824    {
825        serializer.serialize_str(&format!("{:x}", self))
826    }
827}
828
829// Network serialization
830impl Encodable for Script {
831    #[inline]
832    fn consensus_encode<S: io::Write>(
833        &self,
834        s: S,
835    ) -> Result<usize, io::Error> {
836        self.0.consensus_encode(s)
837    }
838}
839
840impl Decodable for Script {
841    #[inline]
842    fn consensus_decode<D: io::Read>(d: D) -> Result<Self, encode::Error> {
843        Ok(Script(Decodable::consensus_decode(d)?))
844    }
845}
846
847#[cfg(test)]
848mod test {
849    use std::str::FromStr;
850
851    use super::*;
852    use super::build_scriptint;
853
854    use hashes::hex::{FromHex, ToHex};
855    use consensus::encode::{deserialize, serialize};
856    use blockdata::opcodes;
857    use util::key::PublicKey;
858    use util::psbt::serialize::Serialize;
859
860    #[test]
861    fn script() {
862        let mut comp = vec![];
863        let mut script = Builder::new();
864        assert_eq!(&script[..], &comp[..]);
865
866        // small ints
867        script = script.push_int(1);  comp.push(81u8); assert_eq!(&script[..], &comp[..]);
868        script = script.push_int(0);  comp.push(0u8);  assert_eq!(&script[..], &comp[..]);
869        script = script.push_int(4);  comp.push(84u8); assert_eq!(&script[..], &comp[..]);
870        script = script.push_int(-1); comp.push(79u8); assert_eq!(&script[..], &comp[..]);
871        // forced scriptint
872        script = script.push_scriptint(4); comp.extend([1u8, 4].iter().cloned()); assert_eq!(&script[..], &comp[..]);
873        // big ints
874        script = script.push_int(17); comp.extend([1u8, 17].iter().cloned()); assert_eq!(&script[..], &comp[..]);
875        script = script.push_int(10000); comp.extend([2u8, 16, 39].iter().cloned()); assert_eq!(&script[..], &comp[..]);
876        // notice the sign bit set here, hence the extra zero/128 at the end
877        script = script.push_int(10000000); comp.extend([4u8, 128, 150, 152, 0].iter().cloned()); assert_eq!(&script[..], &comp[..]);
878        script = script.push_int(-10000000); comp.extend([4u8, 128, 150, 152, 128].iter().cloned()); assert_eq!(&script[..], &comp[..]);
879
880        // data
881        script = script.push_slice("NRA4VR".as_bytes()); comp.extend([6u8, 78, 82, 65, 52, 86, 82].iter().cloned()); assert_eq!(&script[..], &comp[..]);
882
883        let secp = Secp256k1::new();
884
885        // keys
886        let keystr = "21032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af";
887        let key = PublicKey::from_str(&keystr[2..]).unwrap();
888        script = script.push_key(&secp, &key); comp.extend(Vec::from_hex(keystr).unwrap().iter().cloned()); assert_eq!(&script[..], &comp[..]);
889        let keystr = "41042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133";
890        let key = PublicKey::from_str(&keystr[2..]).unwrap();
891        script = script.push_key(&secp, &key); comp.extend(Vec::from_hex(keystr).unwrap().iter().cloned()); assert_eq!(&script[..], &comp[..]);
892
893        // opcodes
894        script = script.push_opcode(opcodes::all::OP_CHECKSIG); comp.push(0xACu8); assert_eq!(&script[..], &comp[..]);
895        script = script.push_opcode(opcodes::all::OP_CHECKSIG); comp.push(0xACu8); assert_eq!(&script[..], &comp[..]);
896    }
897
898    #[test]
899    fn script_builder() {
900        // from txid 3bb5e6434c11fb93f64574af5d116736510717f2c595eb45b52c28e31622dfff which was in my mempool when I wrote the test
901        let script = Builder::new().push_opcode(opcodes::all::OP_DUP)
902                                   .push_opcode(opcodes::all::OP_HASH160)
903                                   .push_slice(&Vec::from_hex("16e1ae70ff0fa102905d4af297f6912bda6cce19").unwrap())
904                                   .push_opcode(opcodes::all::OP_EQUALVERIFY)
905                                   .push_opcode(opcodes::all::OP_CHECKSIG)
906                                   .into_script();
907        assert_eq!(&format!("{:x}", script), "76a91416e1ae70ff0fa102905d4af297f6912bda6cce1988ac");
908    }
909
910    #[test]
911    fn script_generators() {
912        let secp = Secp256k1::new();
913
914        let pubkey = PublicKey::from_str("0234e6a79c5359c613762d537e0e19d86c77c1666d8c9ab050f23acd198e97f93e").unwrap();
915        assert!(Script::new_p2pk(&secp, &pubkey).is_p2pk());
916
917        let pubkey_hash = PubkeyHash::hash(&pubkey.serialize());
918        assert!(Script::new_p2pkh(&pubkey_hash).is_p2pkh());
919
920        let wpubkey_hash = WPubkeyHash::hash(&pubkey.serialize());
921        assert!(Script::new_v0_wpkh(&wpubkey_hash).is_v0_p2wpkh());
922
923        let script = Builder::new().push_opcode(opcodes::all::OP_NUMEQUAL)
924                                   .push_verify()
925                                   .into_script();
926        let script_hash = ScriptHash::hash(&script.serialize());
927        let p2sh = Script::new_p2sh(&script_hash);
928        assert!(p2sh.is_p2sh());
929        assert_eq!(script.to_p2sh(), p2sh);
930
931        let wscript_hash = WScriptHash::hash(&script.serialize());
932        let p2wsh = Script::new_v0_wsh(&wscript_hash);
933        assert!(p2wsh.is_v0_p2wsh());
934        assert_eq!(script.to_v0_p2wsh(), p2wsh);
935
936        // Test data are taken from the second output of
937        // 2ccb3a1f745eb4eefcf29391460250adda5fab78aaddb902d25d3cd97d9d8e61 transaction
938        let data = Vec::<u8>::from_hex("aa21a9ed20280f53f2d21663cac89e6bd2ad19edbabb048cda08e73ed19e9268d0afea2a").unwrap();
939        let op_return = Script::new_op_return(&data);
940        assert!(op_return.is_op_return());
941        assert_eq!(op_return.to_hex(), "6a24aa21a9ed20280f53f2d21663cac89e6bd2ad19edbabb048cda08e73ed19e9268d0afea2a");
942    }
943
944    #[test]
945    fn script_builder_verify() {
946        let simple = Builder::new()
947            .push_verify()
948            .into_script();
949        assert_eq!(format!("{:x}", simple), "69");
950        let simple2 = Builder::from(vec![])
951            .push_verify()
952            .into_script();
953        assert_eq!(format!("{:x}", simple2), "69");
954
955        let nonverify = Builder::new()
956            .push_verify()
957            .push_verify()
958            .into_script();
959        assert_eq!(format!("{:x}", nonverify), "6969");
960        let nonverify2 = Builder::from(vec![0x69])
961            .push_verify()
962            .into_script();
963        assert_eq!(format!("{:x}", nonverify2), "6969");
964
965        let equal = Builder::new()
966            .push_opcode(opcodes::all::OP_EQUAL)
967            .push_verify()
968            .into_script();
969        assert_eq!(format!("{:x}", equal), "88");
970        let equal2 = Builder::from(vec![0x87])
971            .push_verify()
972            .into_script();
973        assert_eq!(format!("{:x}", equal2), "88");
974
975        let numequal = Builder::new()
976            .push_opcode(opcodes::all::OP_NUMEQUAL)
977            .push_verify()
978            .into_script();
979        assert_eq!(format!("{:x}", numequal), "9d");
980        let numequal2 = Builder::from(vec![0x9c])
981            .push_verify()
982            .into_script();
983        assert_eq!(format!("{:x}", numequal2), "9d");
984
985        let checksig = Builder::new()
986            .push_opcode(opcodes::all::OP_CHECKSIG)
987            .push_verify()
988            .into_script();
989        assert_eq!(format!("{:x}", checksig), "ad");
990        let checksig2 = Builder::from(vec![0xac])
991            .push_verify()
992            .into_script();
993        assert_eq!(format!("{:x}", checksig2), "ad");
994
995        let checkmultisig = Builder::new()
996            .push_opcode(opcodes::all::OP_CHECKMULTISIG)
997            .push_verify()
998            .into_script();
999        assert_eq!(format!("{:x}", checkmultisig), "af");
1000        let checkmultisig2 = Builder::from(vec![0xae])
1001            .push_verify()
1002            .into_script();
1003        assert_eq!(format!("{:x}", checkmultisig2), "af");
1004
1005        let trick_slice = Builder::new()
1006            .push_slice(&[0xae]) // OP_CHECKMULTISIG
1007            .push_verify()
1008            .into_script();
1009        assert_eq!(format!("{:x}", trick_slice), "01ae69");
1010        let trick_slice2 = Builder::from(vec![0x01, 0xae])
1011            .push_verify()
1012            .into_script();
1013        assert_eq!(format!("{:x}", trick_slice2), "01ae69");
1014   }
1015
1016    #[test]
1017    fn script_serialize() {
1018        let hex_script = Vec::from_hex("6c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52").unwrap();
1019        let script: Result<Script, _> = deserialize(&hex_script);
1020        assert!(script.is_ok());
1021        assert_eq!(serialize(&script.unwrap()), hex_script);
1022    }
1023
1024    #[test]
1025    fn scriptint_round_trip() {
1026        assert_eq!(build_scriptint(-1), vec![0x81]);
1027        assert_eq!(build_scriptint(255), vec![255, 0]);
1028        assert_eq!(build_scriptint(256), vec![0, 1]);
1029        assert_eq!(build_scriptint(257), vec![1, 1]);
1030        assert_eq!(build_scriptint(511), vec![255, 1]);
1031        for &i in [10, 100, 255, 256, 1000, 10000, 25000, 200000, 5000000, 1000000000,
1032                             (1 << 31) - 1, -((1 << 31) - 1)].iter() {
1033            assert_eq!(Ok(i), read_scriptint(&build_scriptint(i)));
1034            assert_eq!(Ok(-i), read_scriptint(&build_scriptint(-i)));
1035        }
1036        assert!(read_scriptint(&build_scriptint(1 << 31)).is_err());
1037        assert!(read_scriptint(&build_scriptint(-(1 << 31))).is_err());
1038    }
1039
1040    #[test]
1041    fn script_hashes() {
1042        let script = hex_script!("410446ef0102d1ec5240f0d061a4246c1bdef63fc3dbab7733052fbbf0ecd8f41fc26bf049ebb4f9527f374280259e7cfa99c48b0e3f39c51347a19a5819651503a5ac");
1043        assert_eq!(script.script_hash().to_hex(), "8292bcfbef1884f73c813dfe9c82fd7e814291ea");
1044        assert_eq!(script.wscript_hash().to_hex(), "3e1525eb183ad4f9b3c5fa3175bdca2a52e947b135bbb90383bf9f6408e2c324");
1045    }
1046
1047    #[test]
1048    fn provably_unspendable_test() {
1049        // p2pk
1050        assert_eq!(hex_script!("410446ef0102d1ec5240f0d061a4246c1bdef63fc3dbab7733052fbbf0ecd8f41fc26bf049ebb4f9527f374280259e7cfa99c48b0e3f39c51347a19a5819651503a5ac").is_provably_unspendable(), false);
1051        assert_eq!(hex_script!("4104ea1feff861b51fe3f5f8a3b12d0f4712db80e919548a80839fc47c6a21e66d957e9c5d8cd108c7a2d2324bad71f9904ac0ae7336507d785b17a2c115e427a32fac").is_provably_unspendable(), false);
1052        // p2pkhash
1053        assert_eq!(hex_script!("76a914ee61d57ab51b9d212335b1dba62794ac20d2bcf988ac").is_provably_unspendable(), false);
1054        assert_eq!(hex_script!("6aa9149eb21980dc9d413d8eac27314938b9da920ee53e87").is_provably_unspendable(), true);
1055    }
1056
1057    #[test]
1058    fn op_return_test() {
1059        assert_eq!(hex_script!("6aa9149eb21980dc9d413d8eac27314938b9da920ee53e87").is_op_return(), true);
1060        assert_eq!(hex_script!("76a914ee61d57ab51b9d212335b1dba62794ac20d2bcf988ac").is_op_return(), false);
1061        assert_eq!(hex_script!("").is_op_return(), false);
1062    }
1063
1064    #[test]
1065    #[cfg(feature = "serde")]
1066    fn script_json_serialize() {
1067        use serde_json;
1068
1069        let original = hex_script!("827651a0698faaa9a8a7a687");
1070        let json = serde_json::to_value(&original).unwrap();
1071        assert_eq!(json, serde_json::Value::String("827651a0698faaa9a8a7a687".to_owned()));
1072        let des = serde_json::from_value(json).unwrap();
1073        assert_eq!(original, des);
1074    }
1075
1076    #[test]
1077    fn script_asm() {
1078        assert_eq!(hex_script!("6363636363686868686800").asm(),
1079                   "OP_IF OP_IF OP_IF OP_IF OP_IF OP_ENDIF OP_ENDIF OP_ENDIF OP_ENDIF OP_ENDIF OP_0");
1080        assert_eq!(hex_script!("6363636363686868686800").asm(),
1081                   "OP_IF OP_IF OP_IF OP_IF OP_IF OP_ENDIF OP_ENDIF OP_ENDIF OP_ENDIF OP_ENDIF OP_0");
1082        assert_eq!(hex_script!("2102715e91d37d239dea832f1460e91e368115d8ca6cc23a7da966795abad9e3b699ac").asm(),
1083                   "OP_PUSHBYTES_33 02715e91d37d239dea832f1460e91e368115d8ca6cc23a7da966795abad9e3b699 OP_CHECKSIG");
1084        // Elements Alpha peg-out transaction with some signatures removed for brevity. Mainly to test PUSHDATA1
1085        assert_eq!(hex_script!("0047304402202457e78cc1b7f50d0543863c27de75d07982bde8359b9e3316adec0aec165f2f02200203fd331c4e4a4a02f48cf1c291e2c0d6b2f7078a784b5b3649fca41f8794d401004cf1552103244e602b46755f24327142a0517288cebd159eccb6ccf41ea6edf1f601e9af952103bbbacc302d19d29dbfa62d23f37944ae19853cf260c745c2bea739c95328fcb721039227e83246bd51140fe93538b2301c9048be82ef2fb3c7fc5d78426ed6f609ad210229bf310c379b90033e2ecb07f77ecf9b8d59acb623ab7be25a0caed539e2e6472103703e2ed676936f10b3ce9149fa2d4a32060fb86fa9a70a4efe3f21d7ab90611921031e9b7c6022400a6bb0424bbcde14cff6c016b91ee3803926f3440abf5c146d05210334667f975f55a8455d515a2ef1c94fdfa3315f12319a14515d2a13d82831f62f57ae").asm(),
1086                   "OP_0 OP_PUSHBYTES_71 304402202457e78cc1b7f50d0543863c27de75d07982bde8359b9e3316adec0aec165f2f02200203fd331c4e4a4a02f48cf1c291e2c0d6b2f7078a784b5b3649fca41f8794d401 OP_0 OP_PUSHDATA1 552103244e602b46755f24327142a0517288cebd159eccb6ccf41ea6edf1f601e9af952103bbbacc302d19d29dbfa62d23f37944ae19853cf260c745c2bea739c95328fcb721039227e83246bd51140fe93538b2301c9048be82ef2fb3c7fc5d78426ed6f609ad210229bf310c379b90033e2ecb07f77ecf9b8d59acb623ab7be25a0caed539e2e6472103703e2ed676936f10b3ce9149fa2d4a32060fb86fa9a70a4efe3f21d7ab90611921031e9b7c6022400a6bb0424bbcde14cff6c016b91ee3803926f3440abf5c146d05210334667f975f55a8455d515a2ef1c94fdfa3315f12319a14515d2a13d82831f62f57ae");
1087    }
1088
1089    #[test]
1090    fn script_p2sh_p2p2k_template() {
1091        // random outputs I picked out of the mempool
1092        assert!(hex_script!("76a91402306a7c23f3e8010de41e9e591348bb83f11daa88ac").is_p2pkh());
1093        assert!(!hex_script!("76a91402306a7c23f3e8010de41e9e591348bb83f11daa88ac").is_p2sh());
1094        assert!(!hex_script!("76a91402306a7c23f3e8010de41e9e591348bb83f11daa88ad").is_p2pkh());
1095        assert!(!hex_script!("").is_p2pkh());
1096        assert!(hex_script!("a914acc91e6fef5c7f24e5c8b3f11a664aa8f1352ffd87").is_p2sh());
1097        assert!(!hex_script!("a914acc91e6fef5c7f24e5c8b3f11a664aa8f1352ffd87").is_p2pkh());
1098        assert!(!hex_script!("a314acc91e6fef5c7f24e5c8b3f11a664aa8f1352ffd87").is_p2sh());
1099    }
1100
1101    #[test]
1102    fn script_p2pk() {
1103        assert!(hex_script!("21021aeaf2f8638a129a3156fbe7e5ef635226b0bafd495ff03afe2c843d7e3a4b51ac").is_p2pk());
1104        assert!(hex_script!("410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac").is_p2pk());
1105    }
1106
1107    #[test]
1108    fn p2sh_p2wsh_conversion() {
1109        // Test vectors taken from Core tests/data/script_tests.json
1110        // bare p2wsh
1111        let redeem_script = hex_script!("410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8ac");
1112        let expected_witout = hex_script!("0020b95237b48faaa69eb078e1170be3b5cbb3fddf16d0a991e14ad274f7b33a4f64");
1113        assert!(redeem_script.to_v0_p2wsh().is_v0_p2wsh());
1114        assert_eq!(redeem_script.to_v0_p2wsh(), expected_witout);
1115
1116        // p2sh
1117        let redeem_script = hex_script!("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8");
1118        let expected_p2shout = hex_script!("a91491b24bf9f5288532960ac687abb035127b1d28a587");
1119        assert!(redeem_script.to_p2sh().is_p2sh());
1120        assert_eq!(redeem_script.to_p2sh(), expected_p2shout);
1121
1122        // p2sh-p2wsh
1123        let redeem_script = hex_script!("410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8ac");
1124        let expected_witout = hex_script!("0020b95237b48faaa69eb078e1170be3b5cbb3fddf16d0a991e14ad274f7b33a4f64");
1125        let expected_out = hex_script!("a914f386c2ba255cc56d20cfa6ea8b062f8b5994551887");
1126        assert!(redeem_script.to_p2sh().is_p2sh());
1127        assert!(redeem_script.to_p2sh().to_v0_p2wsh().is_v0_p2wsh());
1128        assert_eq!(redeem_script.to_v0_p2wsh(), expected_witout);
1129        assert_eq!(redeem_script.to_v0_p2wsh().to_p2sh(), expected_out);
1130    }
1131
1132    #[test]
1133    fn test_iterator() {
1134        let zero = hex_script!("00");
1135        let zeropush = hex_script!("0100");
1136
1137        let nonminimal = hex_script!("4c0169b2");      // PUSHDATA1 for no reason
1138        let minimal = hex_script!("0169b2");           // minimal
1139        let nonminimal_alt = hex_script!("026900b2");  // non-minimal number but minimal push (should be OK)
1140
1141        let v_zero: Result<Vec<Instruction>, Error> = zero.instructions_minimal().collect();
1142        let v_zeropush: Result<Vec<Instruction>, Error> = zeropush.instructions_minimal().collect();
1143
1144        let v_min: Result<Vec<Instruction>, Error> = minimal.instructions_minimal().collect();
1145        let v_nonmin: Result<Vec<Instruction>, Error> = nonminimal.instructions_minimal().collect();
1146        let v_nonmin_alt: Result<Vec<Instruction>, Error> = nonminimal_alt.instructions_minimal().collect();
1147        let slop_v_min: Result<Vec<Instruction>, Error> = minimal.instructions().collect();
1148        let slop_v_nonmin: Result<Vec<Instruction>, Error> = nonminimal.instructions().collect();
1149        let slop_v_nonmin_alt: Result<Vec<Instruction>, Error> = nonminimal_alt.instructions().collect();
1150
1151        assert_eq!(
1152            v_zero.unwrap(),
1153            vec![
1154                Instruction::PushBytes(&[]),
1155            ]
1156        );
1157        assert_eq!(
1158            v_zeropush.unwrap(),
1159            vec![
1160                Instruction::PushBytes(&[0]),
1161            ]
1162        );
1163
1164        assert_eq!(
1165            v_min.clone().unwrap(),
1166            vec![
1167                Instruction::PushBytes(&[105]),
1168                Instruction::Op(opcodes::OP_NOP3),
1169            ]
1170        );
1171
1172        assert_eq!(
1173            v_nonmin.err().unwrap(),
1174            Error::NonMinimalPush
1175        );
1176
1177        assert_eq!(
1178            v_nonmin_alt.clone().unwrap(),
1179            vec![
1180                Instruction::PushBytes(&[105, 0]),
1181                Instruction::Op(opcodes::OP_NOP3),
1182            ]
1183        );
1184
1185        assert_eq!(v_min.clone().unwrap(), slop_v_min.unwrap());
1186        assert_eq!(v_min.unwrap(), slop_v_nonmin.unwrap());
1187        assert_eq!(v_nonmin_alt.unwrap(), slop_v_nonmin_alt.unwrap());
1188    }
1189
1190	#[test]
1191    fn script_ord() {
1192        let script_1 = Builder::new().push_slice(&[1,2,3,4]).into_script();
1193        let script_2 = Builder::new().push_int(10).into_script();
1194        let script_3 = Builder::new().push_int(15).into_script();
1195        let script_4 = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
1196
1197        assert!(script_1 < script_2);
1198        assert!(script_2 < script_3);
1199        assert!(script_3 < script_4);
1200
1201        assert!(script_1 <= script_1);
1202        assert!(script_1 >= script_1);
1203
1204        assert!(script_4 > script_3);
1205        assert!(script_3 > script_2);
1206        assert!(script_2 > script_1);
1207    }
1208
1209	#[test]
1210	#[cfg(feature="bitcoinconsensus")]
1211	fn test_bitcoinconsensus () {
1212		// a random segwit transaction from the blockchain using native segwit
1213		let spent = Builder::from(Vec::from_hex("0020701a8d401c84fb13e6baf169d59684e17abd9fa216c8cc5b9fc63d622ff8c58d").unwrap()).into_script();
1214		let spending = Vec::from_hex("010000000001011f97548fbbe7a0db7588a66e18d803d0089315aa7d4cc28360b6ec50ef36718a0100000000ffffffff02df1776000000000017a9146c002a686959067f4866b8fb493ad7970290ab728757d29f0000000000220020701a8d401c84fb13e6baf169d59684e17abd9fa216c8cc5b9fc63d622ff8c58d04004730440220565d170eed95ff95027a69b313758450ba84a01224e1f7f130dda46e94d13f8602207bdd20e307f062594022f12ed5017bbf4a055a06aea91c10110a0e3bb23117fc014730440220647d2dc5b15f60bc37dc42618a370b2a1490293f9e5c8464f53ec4fe1dfe067302203598773895b4b16d37485cbe21b337f4e4b650739880098c592553add7dd4355016952210375e00eb72e29da82b89367947f29ef34afb75e8654f6ea368e0acdfd92976b7c2103a1b26313f430c4b15bb1fdce663207659d8cac749a0e53d70eff01874496feff2103c96d495bfdd5ba4145e3e046fee45e84a8a48ad05bd8dbb395c011a32cf9f88053ae00000000").unwrap();
1215		spent.verify(0, 18393430, spending.as_slice()).unwrap();
1216	}
1217}
1218