-
Notifications
You must be signed in to change notification settings - Fork 622
/
script.rs
1514 lines (1338 loc) · 61.3 KB
/
script.rs
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Rust Bitcoin Library
// Written in 2014 by
// Andrew Poelstra <apoelstra@wpsoftware.net>
//
// 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/>.
//
//! Bitcoin scripts.
//!
//! Scripts define Bitcoin's digital signature scheme: a signature is formed
//! from a script (the second half of which is defined by a coin to be spent,
//! and the first half provided by the spending transaction), and is valid iff
//! the script leaves `TRUE` on the stack after being evaluated. Bitcoin's
//! script is a stack-based assembly language similar in spirit to Forth.
//!
//! This module provides the structures and functions needed to support scripts.
//!
use prelude::*;
use io;
use core::{fmt, default::Default};
use core::ops::Index;
#[cfg(feature = "serde")] use serde;
use hash_types::{PubkeyHash, WPubkeyHash, ScriptHash, WScriptHash};
use blockdata::opcodes;
use consensus::{encode, Decodable, Encodable};
use hashes::{Hash, hex};
use policy::DUST_RELAY_TX_FEE;
#[cfg(feature="bitcoinconsensus")] use bitcoinconsensus;
#[cfg(feature="bitcoinconsensus")] use core::convert::From;
use OutPoint;
use util::key::PublicKey;
use util::address::WitnessVersion;
use util::taproot::{LeafVersion, TapBranchHash, TapLeafHash};
use secp256k1::{Secp256k1, Verification, XOnlyPublicKey};
use schnorr::{TapTweak, TweakedPublicKey, UntweakedPublicKey};
/// A Bitcoin script.
#[derive(Clone, Default, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Script(Box<[u8]>);
impl<I> Index<I> for Script
where
[u8]: Index<I>,
{
type Output = <[u8] as Index<I>>::Output;
#[inline]
fn index(&self, index: I) -> &Self::Output {
&self.0[index]
}
}
impl AsRef<[u8]> for Script {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl fmt::Debug for Script {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("Script(")?;
self.fmt_asm(f)?;
f.write_str(")")
}
}
impl fmt::Display for Script {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl fmt::LowerHex for Script {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for &ch in self.0.iter() {
write!(f, "{:02x}", ch)?;
}
Ok(())
}
}
impl fmt::UpperHex for Script {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for &ch in self.0.iter() {
write!(f, "{:02X}", ch)?;
}
Ok(())
}
}
impl hex::FromHex for Script {
fn from_byte_iter<I>(iter: I) -> Result<Self, hex::Error>
where
I: Iterator<Item=Result<u8, hex::Error>> + ExactSizeIterator + DoubleEndedIterator,
{
Vec::from_byte_iter(iter).map(|v| Script(Box::<[u8]>::from(v)))
}
}
impl ::core::str::FromStr for Script {
type Err = hex::Error;
fn from_str(s: &str) -> Result<Self, hex::Error> {
hex::FromHex::from_hex(s)
}
}
/// An object which can be used to construct a script piece by piece.
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct Builder(Vec<u8>, Option<opcodes::All>);
display_from_debug!(Builder);
impl<I> Index<I> for Builder
where
Vec<u8>: Index<I>,
{
type Output = <Vec<u8> as Index<I>>::Output;
#[inline]
fn index(&self, index: I) -> &Self::Output {
&self.0[index]
}
}
/// Ways that a script might fail. Not everything is split up as
/// much as it could be; patches welcome if more detailed errors
/// would help you.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
pub enum Error {
/// Something did a non-minimal push; for more information see
/// `https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#Push_operators`
NonMinimalPush,
/// Some opcode expected a parameter, but it was missing or truncated
EarlyEndOfScript,
/// Tried to read an array off the stack as a number when it was more than 4 bytes
NumericOverflow,
/// Error validating the script with bitcoinconsensus library
BitcoinConsensus(BitcoinConsensusError),
/// Can not find the spent output
UnknownSpentOutput(OutPoint),
/// Can not serialize the spending transaction
SerializationError
}
/// A [`bitcoinconsensus::Error`] alias. Exists to enable the compiler to ensure `bitcoinconsensus`
/// feature gating is correct.
#[cfg(feature = "bitcoinconsensus")]
#[cfg_attr(docsrs, doc(cfg(feature = "bitcoinconsensus")))]
pub type BitcoinConsensusError = bitcoinconsensus::Error;
/// Dummy error type used when `bitcoinconsensus` feature is not enabled.
#[cfg(not(feature = "bitcoinconsensus"))]
#[cfg_attr(docsrs, doc(cfg(not(feature = "bitcoinconsensus"))))]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
pub struct BitcoinConsensusError {
_uninhabited: Uninhabited,
}
#[cfg(not(feature = "bitcoinconsensus"))]
#[cfg_attr(docsrs, doc(cfg(not(feature = "bitcoinconsensus"))))]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
enum Uninhabited {}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = match *self {
Error::NonMinimalPush => "non-minimal datapush",
Error::EarlyEndOfScript => "unexpected end of script",
Error::NumericOverflow => "numeric overflow (number on stack larger than 4 bytes)",
Error::BitcoinConsensus(ref _n) => "bitcoinconsensus verification failed",
Error::UnknownSpentOutput(ref _point) => "unknown spent output Transaction::verify()",
Error::SerializationError => "can not serialize the spending transaction in Transaction::verify()",
};
f.write_str(str)
}
}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl ::std::error::Error for Error {}
// Our internal error proves that we only return these two cases from `read_uint_iter`.
// Since it's private we don't bother with trait impls besides From.
enum UintError {
EarlyEndOfScript,
NumericOverflow,
}
impl From<UintError> for Error {
fn from(error: UintError) -> Self {
match error {
UintError::EarlyEndOfScript => Error::EarlyEndOfScript,
UintError::NumericOverflow => Error::NumericOverflow,
}
}
}
#[cfg(feature = "bitcoinconsensus")]
#[doc(hidden)]
impl From<bitcoinconsensus::Error> for Error {
fn from(err: bitcoinconsensus::Error) -> Error {
Error::BitcoinConsensus(err)
}
}
/// Helper to encode an integer in script format
fn build_scriptint(n: i64) -> Vec<u8> {
if n == 0 { return vec![] }
let neg = n < 0;
let mut abs = if neg { -n } else { n } as usize;
let mut v = vec![];
while abs > 0xFF {
v.push((abs & 0xFF) as u8);
abs >>= 8;
}
// If the number's value causes the sign bit to be set, we need an extra
// byte to get the correct value and correct sign bit
if abs & 0x80 != 0 {
v.push(abs as u8);
v.push(if neg { 0x80u8 } else { 0u8 });
}
// Otherwise we just set the sign bit ourselves
else {
abs |= if neg { 0x80 } else { 0 };
v.push(abs as u8);
}
v
}
/// Helper to decode an integer in script format
/// Notice that this fails on overflow: the result is the same as in
/// bitcoind, that only 4-byte signed-magnitude values may be read as
/// numbers. They can be added or subtracted (and a long time ago,
/// multiplied and divided), and this may result in numbers which
/// can't be written out in 4 bytes or less. This is ok! The number
/// just can't be read as a number again.
/// This is a bit crazy and subtle, but it makes sense: you can load
/// 32-bit numbers and do anything with them, which back when mult/div
/// was allowed, could result in up to a 64-bit number. We don't want
/// overflow since that's surprising --- and we don't want numbers that
/// don't fit in 64 bits (for efficiency on modern processors) so we
/// simply say, anything in excess of 32 bits is no longer a number.
/// This is basically a ranged type implementation.
pub fn read_scriptint(v: &[u8]) -> Result<i64, Error> {
let len = v.len();
if len == 0 { return Ok(0); }
if len > 4 { return Err(Error::NumericOverflow); }
let (mut ret, sh) = v.iter()
.fold((0, 0), |(acc, sh), n| (acc + ((*n as i64) << sh), sh + 8));
if v[len - 1] & 0x80 != 0 {
ret &= (1 << (sh - 1)) - 1;
ret = -ret;
}
Ok(ret)
}
/// This is like "`read_scriptint` then map 0 to false and everything
/// else as true", except that the overflow rules don't apply.
#[inline]
pub fn read_scriptbool(v: &[u8]) -> bool {
match v.split_last() {
Some((last, rest)) => !((last & !0x80 == 0x00) && rest.iter().all(|&b| b == 0)),
None => false,
}
}
/// Read a script-encoded unsigned integer
///
/// ## Errors
///
/// This function returns an error in these cases:
///
/// * `data` is shorter than `size` => `EarlyEndOfScript`
/// * `size` is greater than `u16::max_value / 8` (8191) => `NumericOverflow`
/// * The number being read overflows `usize` => `NumericOverflow`
///
/// Note that this does **not** return an error for `size` between `core::size_of::<usize>()`
/// and `u16::max_value / 8` if there's no overflow.
pub fn read_uint(data: &[u8], size: usize) -> Result<usize, Error> {
read_uint_iter(&mut data.iter(), size).map_err(Into::into)
}
// We internally use implementation based on iterator so that it automatically advances as needed
// Errors are same as above, just different type.
fn read_uint_iter(data: &mut ::core::slice::Iter<'_, u8>, size: usize) -> Result<usize, UintError> {
if data.len() < size {
Err(UintError::EarlyEndOfScript)
} else if size > usize::from(u16::max_value() / 8) {
// Casting to u32 would overflow
Err(UintError::NumericOverflow)
} else {
let mut ret = 0;
for (i, item) in data.take(size).enumerate() {
ret = usize::from(*item)
// Casting is safe because we checked above to not repeat the same check in a loop
.checked_shl((i * 8) as u32)
.ok_or(UintError::NumericOverflow)?
.checked_add(ret)
.ok_or(UintError::NumericOverflow)?;
}
Ok(ret)
}
}
impl Script {
/// Creates a new empty script.
pub fn new() -> Script { Script(vec![].into_boxed_slice()) }
/// Generates P2PK-type of scriptPubkey.
pub fn new_p2pk(pubkey: &PublicKey) -> Script {
Builder::new()
.push_key(pubkey)
.push_opcode(opcodes::all::OP_CHECKSIG)
.into_script()
}
/// Generates P2PKH-type of scriptPubkey.
pub fn new_p2pkh(pubkey_hash: &PubkeyHash) -> Script {
Builder::new()
.push_opcode(opcodes::all::OP_DUP)
.push_opcode(opcodes::all::OP_HASH160)
.push_slice(&pubkey_hash[..])
.push_opcode(opcodes::all::OP_EQUALVERIFY)
.push_opcode(opcodes::all::OP_CHECKSIG)
.into_script()
}
/// Generates P2SH-type of scriptPubkey with a given hash of the redeem script.
pub fn new_p2sh(script_hash: &ScriptHash) -> Script {
Builder::new()
.push_opcode(opcodes::all::OP_HASH160)
.push_slice(&script_hash[..])
.push_opcode(opcodes::all::OP_EQUAL)
.into_script()
}
/// Generates P2WPKH-type of scriptPubkey.
#[deprecated(since = "0.28.0", note = "use Script::new_v0_p2wpkh method instead")]
pub fn new_v0_wpkh(pubkey_hash: &WPubkeyHash) -> Script {
Script::new_v0_p2wpkh(pubkey_hash)
}
/// Generates P2WPKH-type of scriptPubkey.
pub fn new_v0_p2wpkh(pubkey_hash: &WPubkeyHash) -> Script {
Script::new_witness_program(WitnessVersion::V0, &pubkey_hash[..])
}
/// Generates P2WSH-type of scriptPubkey with a given hash of the redeem script.
#[deprecated(since = "0.28.0", note = "use Script::new_v0_p2wsh method instead")]
pub fn new_v0_wsh(script_hash: &WScriptHash) -> Script {
Script::new_v0_p2wsh(script_hash)
}
/// Generates P2WSH-type of scriptPubkey with a given hash of the redeem script.
pub fn new_v0_p2wsh(script_hash: &WScriptHash) -> Script {
Script::new_witness_program(WitnessVersion::V0, &script_hash[..])
}
/// Generates P2TR for script spending path using an internal public key and some optional
/// script tree merkle root.
pub fn new_v1_p2tr<C: Verification>(secp: &Secp256k1<C>, internal_key: UntweakedPublicKey, merkle_root: Option<TapBranchHash>) -> Script {
let (output_key, _) = internal_key.tap_tweak(secp, merkle_root);
Script::new_witness_program(WitnessVersion::V1, &output_key.serialize())
}
/// Generates P2TR for key spending path for a known [`TweakedPublicKey`].
pub fn new_v1_p2tr_tweaked(output_key: TweakedPublicKey) -> Script {
Script::new_witness_program(WitnessVersion::V1, &output_key.serialize())
}
/// Generates P2WSH-type of scriptPubkey with a given hash of the redeem script.
pub fn new_witness_program(version: WitnessVersion, program: &[u8]) -> Script {
Builder::new()
.push_opcode(version.into())
.push_slice(program)
.into_script()
}
/// Generates OP_RETURN-type of scriptPubkey for the given data.
pub fn new_op_return(data: &[u8]) -> Script {
Builder::new()
.push_opcode(opcodes::all::OP_RETURN)
.push_slice(data)
.into_script()
}
/// Returns 160-bit hash of the script.
pub fn script_hash(&self) -> ScriptHash {
ScriptHash::hash(self.as_bytes())
}
/// Returns 256-bit hash of the script for P2WSH outputs.
pub fn wscript_hash(&self) -> WScriptHash {
WScriptHash::hash(self.as_bytes())
}
/// Returns the length in bytes of the script.
pub fn len(&self) -> usize { self.0.len() }
/// Returns whether the script is the empty script.
pub fn is_empty(&self) -> bool { self.0.is_empty() }
/// Returns the script data as a byte slice.
pub fn as_bytes(&self) -> &[u8] { &*self.0 }
/// Returns a copy of the script data.
pub fn to_bytes(&self) -> Vec<u8> { self.0.clone().into_vec() }
/// Converts the script into a byte vector.
pub fn into_bytes(self) -> Vec<u8> { self.0.into_vec() }
/// Computes the P2SH output corresponding to this redeem script.
pub fn to_p2sh(&self) -> Script {
Script::new_p2sh(&self.script_hash())
}
/// Computes the P2WSH output corresponding to this witnessScript (aka the "witness redeem
/// script").
pub fn to_v0_p2wsh(&self) -> Script {
Script::new_v0_p2wsh(&self.wscript_hash())
}
/// Computes P2TR output with a given internal key and a single script spending path equal to
/// the current script, assuming that the script is a Tapscript.
#[inline]
pub fn to_v1_p2tr<C: Verification>(&self, secp: &Secp256k1<C>, internal_key: UntweakedPublicKey) -> Script {
let leaf_hash = TapLeafHash::from_script(&self, LeafVersion::TapScript);
let merkle_root = TapBranchHash::from_inner(leaf_hash.into_inner());
Script::new_v1_p2tr(&secp, internal_key, Some(merkle_root))
}
/// Returns witness version of the script, if any, assuming the script is a `scriptPubkey`.
#[inline]
pub fn witness_version(&self) -> Option<WitnessVersion> {
self.0.get(0).and_then(|opcode| WitnessVersion::from_opcode(opcodes::All::from(*opcode)).ok())
}
/// Checks whether a script pubkey is a P2SH output.
#[inline]
pub fn is_p2sh(&self) -> bool {
self.0.len() == 23
&& self.0[0] == opcodes::all::OP_HASH160.into_u8()
&& self.0[1] == opcodes::all::OP_PUSHBYTES_20.into_u8()
&& self.0[22] == opcodes::all::OP_EQUAL.into_u8()
}
/// Checks whether a script pubkey is a P2PKH output.
#[inline]
pub fn is_p2pkh(&self) -> bool {
self.0.len() == 25
&& self.0[0] == opcodes::all::OP_DUP.into_u8()
&& self.0[1] == opcodes::all::OP_HASH160.into_u8()
&& self.0[2] == opcodes::all::OP_PUSHBYTES_20.into_u8()
&& self.0[23] == opcodes::all::OP_EQUALVERIFY.into_u8()
&& self.0[24] == opcodes::all::OP_CHECKSIG.into_u8()
}
/// Checks whether a script pubkey is a P2PK output.
#[inline]
pub fn is_p2pk(&self) -> bool {
match self.len() {
67 => {
self.0[0] == opcodes::all::OP_PUSHBYTES_65.into_u8()
&& self.0[66] == opcodes::all::OP_CHECKSIG.into_u8()
}
35 => {
self.0[0] == opcodes::all::OP_PUSHBYTES_33.into_u8()
&& self.0[34] == opcodes::all::OP_CHECKSIG.into_u8()
}
_ => false
}
}
/// Checks whether a script pubkey is a Segregated Witness (segwit) program.
#[inline]
pub fn is_witness_program(&self) -> bool {
// A scriptPubKey (or redeemScript as defined in BIP16/P2SH) that consists of a 1-byte
// push opcode (for 0 to 16) followed by a data push between 2 and 40 bytes gets a new
// special meaning. The value of the first push is called the "version byte". The following
// byte vector pushed is called the "witness program".
let script_len = self.0.len();
if script_len < 4 || script_len > 42 {
return false
}
let ver_opcode = opcodes::All::from(self.0[0]); // Version 0 or PUSHNUM_1-PUSHNUM_16
let push_opbyte = self.0[1]; // Second byte push opcode 2-40 bytes
WitnessVersion::from_opcode(ver_opcode).is_ok()
&& push_opbyte >= opcodes::all::OP_PUSHBYTES_2.into_u8()
&& push_opbyte <= opcodes::all::OP_PUSHBYTES_40.into_u8()
// Check that the rest of the script has the correct size
&& script_len - 2 == push_opbyte as usize
}
/// Checks whether a script pubkey is a P2WSH output.
#[inline]
pub fn is_v0_p2wsh(&self) -> bool {
self.0.len() == 34
&& self.witness_version() == Some(WitnessVersion::V0)
&& self.0[1] == opcodes::all::OP_PUSHBYTES_32.into_u8()
}
/// Checks whether a script pubkey is a P2WPKH output.
#[inline]
pub fn is_v0_p2wpkh(&self) -> bool {
self.0.len() == 22
&& self.witness_version() == Some(WitnessVersion::V0)
&& self.0[1] == opcodes::all::OP_PUSHBYTES_20.into_u8()
}
/// Checks whether a script pubkey is a P2TR output.
#[inline]
pub fn is_v1_p2tr(&self) -> bool {
self.0.len() == 34
&& self.witness_version() == Some(WitnessVersion::V1)
&& self.0[1] == opcodes::all::OP_PUSHBYTES_32.into_u8()
}
/// Check if this is an OP_RETURN output.
pub fn is_op_return (&self) -> bool {
match self.0.first() {
Some(b) => *b == opcodes::all::OP_RETURN.into_u8(),
None => false
}
}
/// Checks whether a script can be proven to have no satisfying input.
pub fn is_provably_unspendable(&self) -> bool {
use blockdata::opcodes::Class::{ReturnOp, IllegalOp};
match self.0.first() {
Some(b) => {
let first = opcodes::All::from(*b);
let class = first.classify(opcodes::ClassifyContext::Legacy);
class == ReturnOp || class == IllegalOp
},
None => false,
}
}
/// Returns the minimum value an output with this script should have in order to be
/// broadcastable on today's Bitcoin network.
pub fn dust_value(&self) -> ::Amount {
// This must never be lower than Bitcoin Core's GetDustThreshold() (as of v0.21) as it may
// otherwise allow users to create transactions which likely can never be broadcast/confirmed.
let sats = DUST_RELAY_TX_FEE as u64 / 1000 * // The default dust relay fee is 3000 satoshi/kB (i.e. 3 sat/vByte)
if self.is_op_return() {
0
} else if self.is_witness_program() {
32 + 4 + 1 + (107 / 4) + 4 + // The spend cost copied from Core
8 + // The serialized size of the TxOut's amount field
self.consensus_encode(&mut sink()).expect("sinks don't error") as u64 // The serialized size of this script_pubkey
} else {
32 + 4 + 1 + 107 + 4 + // The spend cost copied from Core
8 + // The serialized size of the TxOut's amount field
self.consensus_encode(&mut sink()).expect("sinks don't error") as u64 // The serialized size of this script_pubkey
};
::Amount::from_sat(sats)
}
/// Iterates over the script in the form of `Instruction`s, which are an enum covering opcodes,
/// datapushes and errors.
///
/// At most one error will be returned and then the iterator will end. To instead iterate over
/// the script as sequence of bytes, treat it as a slice using `script[..]` or convert it to a
/// vector using `into_bytes()`.
///
/// To force minimal pushes, use [`Self::instructions_minimal`].
pub fn instructions(&self) -> Instructions {
Instructions {
data: &self.0[..],
enforce_minimal: false,
}
}
/// Iterates over the script in the form of `Instruction`s while enforcing minimal pushes.
pub fn instructions_minimal(&self) -> Instructions {
Instructions {
data: &self.0[..],
enforce_minimal: true,
}
}
/// Shorthand for [`Self::verify_with_flags`] with flag [bitcoinconsensus::VERIFY_ALL].
#[cfg(feature="bitcoinconsensus")]
#[cfg_attr(docsrs, doc(cfg(feature = "bitcoinconsensus")))]
pub fn verify (&self, index: usize, amount: ::Amount, spending: &[u8]) -> Result<(), Error> {
self.verify_with_flags(index, amount, spending, ::bitcoinconsensus::VERIFY_ALL)
}
/// Verifies spend of an input script.
///
/// # Parameters
/// * `index` - The input index in spending which is spending this transaction.
/// * `amount` - The amount this script guards.
/// * `spending` - The transaction that attempts to spend the output holding this script.
/// * `flags` - Verification flags, see [`bitcoinconsensus::VERIFY_ALL`] and similar.
#[cfg(feature="bitcoinconsensus")]
#[cfg_attr(docsrs, doc(cfg(feature = "bitcoinconsensus")))]
pub fn verify_with_flags<F: Into<u32>>(&self, index: usize, amount: ::Amount, spending: &[u8], flags: F) -> Result<(), Error> {
Ok(bitcoinconsensus::verify_with_flags (&self.0[..], amount.as_sat(), spending, index, flags.into())?)
}
/// Writes the assembly decoding of the script bytes to the formatter.
pub fn bytes_to_asm_fmt(script: &[u8], f: &mut dyn fmt::Write) -> fmt::Result {
// This has to be a macro because it needs to break the loop
macro_rules! read_push_data_len {
($iter:expr, $len:expr, $formatter:expr) => {
match read_uint_iter($iter, $len) {
Ok(n) => {
n
},
Err(UintError::EarlyEndOfScript) => {
$formatter.write_str("<unexpected end>")?;
break;
}
// We got the data in a slice which implies it being shorter than `usize::max_value()`
// So if we got overflow, we can confidently say the number is higher than length of
// the slice even though we don't know the exact number. This implies attempt to push
// past end.
Err(UintError::NumericOverflow) => {
$formatter.write_str("<push past end>")?;
break;
}
}
}
}
let mut iter = script.iter();
// Was at least one opcode emitted?
let mut at_least_one = false;
// `iter` needs to be borrowed in `read_push_data_len`, so we have to use `while let` instead
// of `for`.
while let Some(byte) = iter.next() {
let opcode = opcodes::All::from(*byte);
let data_len = if let opcodes::Class::PushBytes(n) = opcode.classify(opcodes::ClassifyContext::Legacy) {
n as usize
} else {
match opcode {
opcodes::all::OP_PUSHDATA1 => {
// side effects: may write and break from the loop
read_push_data_len!(&mut iter, 1, f)
}
opcodes::all::OP_PUSHDATA2 => {
// side effects: may write and break from the loop
read_push_data_len!(&mut iter, 2, f)
}
opcodes::all::OP_PUSHDATA4 => {
// side effects: may write and break from the loop
read_push_data_len!(&mut iter, 4, f)
}
_ => 0
}
};
if at_least_one {
f.write_str(" ")?;
} else {
at_least_one = true;
}
// Write the opcode
if opcode == opcodes::all::OP_PUSHBYTES_0 {
f.write_str("OP_0")?;
} else {
write!(f, "{:?}", opcode)?;
}
// Write any pushdata
if data_len > 0 {
f.write_str(" ")?;
if data_len <= iter.len() {
for ch in iter.by_ref().take(data_len) {
write!(f, "{:02x}", ch)?;
}
} else {
f.write_str("<push past end>")?;
break;
}
}
}
Ok(())
}
/// Writes the assembly decoding of the script to the formatter.
pub fn fmt_asm(&self, f: &mut dyn fmt::Write) -> fmt::Result {
Script::bytes_to_asm_fmt(self.as_ref(), f)
}
/// Creates an assembly decoding of the script in the given byte slice.
pub fn bytes_to_asm(script: &[u8]) -> String {
let mut buf = String::new();
Script::bytes_to_asm_fmt(script, &mut buf).unwrap();
buf
}
/// Returns the assembly decoding of the script.
pub fn asm(&self) -> String {
Script::bytes_to_asm(self.as_ref())
}
}
/// Creates a new script from an existing vector.
impl From<Vec<u8>> for Script {
fn from(v: Vec<u8>) -> Script { Script(v.into_boxed_slice()) }
}
/// A "parsed opcode" which allows iterating over a [`Script`] in a more sensible way.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Instruction<'a> {
/// Push a bunch of data.
PushBytes(&'a [u8]),
/// Some non-push opcode.
Op(opcodes::All),
}
/// Iterator over a script returning parsed opcodes.
pub struct Instructions<'a> {
data: &'a [u8],
enforce_minimal: bool,
}
impl<'a> Iterator for Instructions<'a> {
type Item = Result<Instruction<'a>, Error>;
fn next(&mut self) -> Option<Result<Instruction<'a>, Error>> {
if self.data.is_empty() {
return None;
}
// classify parameter does not really matter here since we are only using
// it for pushes and nums
match opcodes::All::from(self.data[0]).classify(opcodes::ClassifyContext::Legacy) {
opcodes::Class::PushBytes(n) => {
let n = n as usize;
if self.data.len() < n + 1 {
self.data = &[]; // Kill iterator so that it does not return an infinite stream of errors
return Some(Err(Error::EarlyEndOfScript));
}
if self.enforce_minimal {
if n == 1 && (self.data[1] == 0x81 || (self.data[1] > 0 && self.data[1] <= 16)) {
self.data = &[];
return Some(Err(Error::NonMinimalPush));
}
}
let ret = Some(Ok(Instruction::PushBytes(&self.data[1..n+1])));
self.data = &self.data[n + 1..];
ret
}
opcodes::Class::Ordinary(opcodes::Ordinary::OP_PUSHDATA1) => {
if self.data.len() < 2 {
self.data = &[];
return Some(Err(Error::EarlyEndOfScript));
}
let n = match read_uint(&self.data[1..], 1) {
Ok(n) => n,
Err(e) => {
self.data = &[];
return Some(Err(e));
}
};
if self.data.len() < n + 2 {
self.data = &[];
return Some(Err(Error::EarlyEndOfScript));
}
if self.enforce_minimal && n < 76 {
self.data = &[];
return Some(Err(Error::NonMinimalPush));
}
let ret = Some(Ok(Instruction::PushBytes(&self.data[2..n+2])));
self.data = &self.data[n + 2..];
ret
}
opcodes::Class::Ordinary(opcodes::Ordinary::OP_PUSHDATA2) => {
if self.data.len() < 3 {
self.data = &[];
return Some(Err(Error::EarlyEndOfScript));
}
let n = match read_uint(&self.data[1..], 2) {
Ok(n) => n,
Err(e) => {
self.data = &[];
return Some(Err(e));
}
};
if self.enforce_minimal && n < 0x100 {
self.data = &[];
return Some(Err(Error::NonMinimalPush));
}
if self.data.len() < n + 3 {
self.data = &[];
return Some(Err(Error::EarlyEndOfScript));
}
let ret = Some(Ok(Instruction::PushBytes(&self.data[3..n + 3])));
self.data = &self.data[n + 3..];
ret
}
opcodes::Class::Ordinary(opcodes::Ordinary::OP_PUSHDATA4) => {
if self.data.len() < 5 {
self.data = &[];
return Some(Err(Error::EarlyEndOfScript));
}
let n = match read_uint(&self.data[1..], 4) {
Ok(n) => n,
Err(e) => {
self.data = &[];
return Some(Err(e));
}
};
if self.enforce_minimal && n < 0x10000 {
self.data = &[];
return Some(Err(Error::NonMinimalPush));
}
if self.data.len() < n + 5 {
self.data = &[];
return Some(Err(Error::EarlyEndOfScript));
}
let ret = Some(Ok(Instruction::PushBytes(&self.data[5..n + 5])));
self.data = &self.data[n + 5..];
ret
}
// Everything else we can push right through
_ => {
let ret = Some(Ok(Instruction::Op(opcodes::All::from(self.data[0]))));
self.data = &self.data[1..];
ret
}
}
}
}
impl<'a> ::core::iter::FusedIterator for Instructions<'a> {}
impl Builder {
/// Creates a new empty script.
pub fn new() -> Self {
Builder(vec![], None)
}
/// Returns the length in bytes of the script.
pub fn len(&self) -> usize { self.0.len() }
/// Checks whether the script is the empty script.
pub fn is_empty(&self) -> bool { self.0.is_empty() }
/// Adds instructions to push an integer onto the stack. Integers are
/// encoded as little-endian signed-magnitude numbers, but there are
/// dedicated opcodes to push some small integers.
pub fn push_int(self, data: i64) -> Builder {
// We can special-case -1, 1-16
if data == -1 || (data >= 1 && data <= 16) {
let opcode = opcodes::All::from(
(data - 1 + opcodes::OP_TRUE.into_u8() as i64) as u8
);
self.push_opcode(opcode)
}
// We can also special-case zero
else if data == 0 {
self.push_opcode(opcodes::OP_FALSE)
}
// Otherwise encode it as data
else { self.push_scriptint(data) }
}
/// Adds instructions to push an integer onto the stack, using the explicit
/// encoding regardless of the availability of dedicated opcodes.
pub fn push_scriptint(self, data: i64) -> Builder {
self.push_slice(&build_scriptint(data))
}
/// Adds instructions to push some arbitrary data onto the stack.
pub fn push_slice(mut self, data: &[u8]) -> Builder {
// Start with a PUSH opcode
match data.len() as u64 {
n if n < opcodes::Ordinary::OP_PUSHDATA1 as u64 => { self.0.push(n as u8); },
n if n < 0x100 => {
self.0.push(opcodes::Ordinary::OP_PUSHDATA1.into_u8());
self.0.push(n as u8);
},
n if n < 0x10000 => {
self.0.push(opcodes::Ordinary::OP_PUSHDATA2.into_u8());
self.0.push((n % 0x100) as u8);
self.0.push((n / 0x100) as u8);
},
n if n < 0x100000000 => {
self.0.push(opcodes::Ordinary::OP_PUSHDATA4.into_u8());
self.0.push((n % 0x100) as u8);
self.0.push(((n / 0x100) % 0x100) as u8);
self.0.push(((n / 0x10000) % 0x100) as u8);
self.0.push((n / 0x1000000) as u8);
}
_ => panic!("tried to put a 4bn+ sized object into a script!")
}
// Then push the raw bytes
self.0.extend(data.iter().cloned());
self.1 = None;
self
}
/// Adds instructions to push a public key onto the stack.
pub fn push_key(self, key: &PublicKey) -> Builder {
if key.compressed {
self.push_slice(&key.inner.serialize()[..])
} else {
self.push_slice(&key.inner.serialize_uncompressed()[..])
}
}
/// Adds instructions to push an XOnly public key onto the stack.
pub fn push_x_only_key(self, x_only_key: &XOnlyPublicKey) -> Builder {
self.push_slice(&x_only_key.serialize())
}
/// Adds a single opcode to the script.
pub fn push_opcode(mut self, data: opcodes::All) -> Builder {
self.0.push(data.into_u8());
self.1 = Some(data);
self
}
/// Adds an `OP_VERIFY` to the script, unless the most-recently-added
/// opcode has an alternate `VERIFY` form, in which case that opcode
/// is replaced e.g., `OP_CHECKSIG` will become `OP_CHECKSIGVERIFY`.
pub fn push_verify(mut self) -> Builder {
match self.1 {
Some(opcodes::all::OP_EQUAL) => {
self.0.pop();
self.push_opcode(opcodes::all::OP_EQUALVERIFY)
},
Some(opcodes::all::OP_NUMEQUAL) => {
self.0.pop();
self.push_opcode(opcodes::all::OP_NUMEQUALVERIFY)
},
Some(opcodes::all::OP_CHECKSIG) => {
self.0.pop();
self.push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
},
Some(opcodes::all::OP_CHECKMULTISIG) => {
self.0.pop();
self.push_opcode(opcodes::all::OP_CHECKMULTISIGVERIFY)
},
_ => self.push_opcode(opcodes::all::OP_VERIFY),
}
}
/// Converts the `Builder` into an unmodifiable `Script`.
pub fn into_script(self) -> Script {
Script(self.0.into_boxed_slice())
}
}
impl Default for Builder {
fn default() -> Builder { Builder::new() }
}
/// Creates a new builder from an existing vector.
impl From<Vec<u8>> for Builder {
fn from(v: Vec<u8>) -> Builder {
let script = Script(v.into_boxed_slice());
let last_op = match script.instructions().last() {
Some(Ok(Instruction::Op(op))) => Some(op),
_ => None,
};
Builder(script.into_bytes(), last_op)
}
}
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de> serde::Deserialize<'de> for Script {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use core::fmt::Formatter;
use hashes::hex::FromHex;
if deserializer.is_human_readable() {
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = Script;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("a script hex")
}