mod borrowed;
mod builder;
mod instruction;
mod owned;
mod push_bytes;
mod tag;
#[cfg(test)]
mod tests;
mod witness_program;
use core::cmp::Ordering;
use core::fmt;
#[cfg(feature = "serde")]
use core::marker::PhantomData;
#[cfg(feature = "hex")]
use internals::hex::DisplayHex;
use internals::script::{self, PushDataLenLen};
use crate::prelude::rc::Rc;
#[cfg(target_has_atomic = "ptr")]
use crate::prelude::sync::Arc;
use crate::prelude::{Borrow, BorrowMut, Box, Cow, ToOwned, Vec};
#[rustfmt::skip] #[doc(inline)]
pub use self::{
builder::Builder,
borrowed::{Script, ScriptEncoder},
instruction::{Instruction, InstructionIndices, Instructions},
owned::{ScriptBuf, ScriptBufDecoder, ScriptBufDecoderError},
push_bytes::{PushBytes, PushBytesBuf, PushBytesError, ScriptIntError},
tag::{Tag, RedeemScriptTag, ScriptPubKeyTag, ScriptSigTag, WitnessScriptTag},
witness_program::{
validate_witness_program, ParsedWitnessProgram, WitnessProgramClass, WitnessProgramError,
P2A_PROGRAM, WITNESS_PROGRAM_MAX_SIZE, WITNESS_PROGRAM_MIN_SIZE,
},
};
#[doc(inline)]
pub use crate::hash_types::{
RedeemScriptSizeError, ScriptHash, WScriptHash, WitnessScriptSizeError,
};
pub type RedeemScriptBuf = ScriptBuf<RedeemScriptTag>;
pub type RedeemScript = Script<RedeemScriptTag>;
pub type ScriptPubKey = Script<ScriptPubKeyTag>;
pub type ScriptSig = Script<ScriptSigTag>;
pub type ScriptPubKeyBuf = ScriptBuf<ScriptPubKeyTag>;
pub type ScriptPubKeyBufDecoder = ScriptBufDecoder<ScriptPubKeyTag>;
pub type ScriptSigBuf = ScriptBuf<ScriptSigTag>;
pub type ScriptSigBufDecoder = ScriptBufDecoder<ScriptSigTag>;
pub type WitnessScriptBuf = ScriptBuf<WitnessScriptTag>;
pub type WitnessScript = Script<WitnessScriptTag>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
NonMinimalPush,
EarlyEndOfScript,
NumericOverflow,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NonMinimalPush => f.write_str("non-minimal datapush"),
Self::EarlyEndOfScript => f.write_str("unexpected end of script"),
Self::NumericOverflow => {
f.write_str("numeric overflow (number on stack larger than 4 bytes)")
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {}
pub const MAX_REDEEM_SCRIPT_SIZE: usize = 520;
pub const MAX_WITNESS_SCRIPT_SIZE: usize = 10_000;
pub const SCRIPTNUM_STANDARD_MAX_LEN: usize = 4;
pub const SCRIPTNUM_CLTV_MAX_LEN: usize = 5;
pub trait ScriptHashableTag: sealed::Sealed {}
impl ScriptHashableTag for RedeemScriptTag {}
impl ScriptHashableTag for ScriptPubKeyTag {}
mod sealed {
pub trait Sealed {}
impl Sealed for super::RedeemScriptTag {}
impl Sealed for super::ScriptPubKeyTag {}
}
impl<T: ScriptHashableTag> TryFrom<ScriptBuf<T>> for ScriptHash {
type Error = RedeemScriptSizeError;
#[inline]
fn try_from(redeem_script: ScriptBuf<T>) -> Result<Self, Self::Error> {
Self::from_script(&redeem_script)
}
}
impl<T: ScriptHashableTag> TryFrom<&ScriptBuf<T>> for ScriptHash {
type Error = RedeemScriptSizeError;
#[inline]
fn try_from(redeem_script: &ScriptBuf<T>) -> Result<Self, Self::Error> {
Self::from_script(redeem_script)
}
}
impl<T: ScriptHashableTag> TryFrom<&Script<T>> for ScriptHash {
type Error = RedeemScriptSizeError;
#[inline]
fn try_from(redeem_script: &Script<T>) -> Result<Self, Self::Error> {
Self::from_script(redeem_script)
}
}
impl TryFrom<WitnessScriptBuf> for WScriptHash {
type Error = WitnessScriptSizeError;
#[inline]
fn try_from(witness_script: WitnessScriptBuf) -> Result<Self, Self::Error> {
Self::from_script(&witness_script)
}
}
impl TryFrom<&WitnessScriptBuf> for WScriptHash {
type Error = WitnessScriptSizeError;
#[inline]
fn try_from(witness_script: &WitnessScriptBuf) -> Result<Self, Self::Error> {
Self::from_script(witness_script)
}
}
impl TryFrom<&WitnessScript> for WScriptHash {
type Error = WitnessScriptSizeError;
#[inline]
fn try_from(witness_script: &WitnessScript) -> Result<Self, Self::Error> {
Self::from_script(witness_script)
}
}
pub fn write_scriptint(out: &mut [u8; 8], n: i64) -> usize {
let encoded = encode_scriptnum(n);
assert!(encoded.len() <= out.len(), "encoded script integer exceeds output buffer");
out[..encoded.len()].copy_from_slice(&encoded);
encoded.len()
}
pub fn encode_scriptnum(n: i64) -> Vec<u8> {
if n == 0 {
return Vec::new();
}
let mut encoded = Vec::new();
let neg = n < 0;
let mut abs = n.unsigned_abs();
while abs > 0 {
encoded.push((abs & 0xff) as u8);
abs >>= 8;
}
if let Some(last) = encoded.last_mut() {
if *last & 0x80 != 0 {
encoded.push(if neg { 0x80 } else { 0 });
} else if neg {
*last |= 0x80;
}
}
encoded
}
pub fn read_scriptint_non_minimal(v: &[u8]) -> Result<i32, ScriptIntError> {
let ret = read_scriptnum(v, false, SCRIPTNUM_STANDARD_MAX_LEN)?;
Ok(i32::try_from(ret).expect("4 bytes or less fits in i32"))
}
pub fn read_scriptnum(
v: &[u8],
require_minimal: bool,
max_len: usize,
) -> Result<i64, ScriptIntError> {
if v.is_empty() {
return Ok(0);
}
if v.len() > max_len {
return Err(ScriptIntError::NumericOverflow);
}
if require_minimal && !is_minimally_encoded_scriptnum(v, max_len) {
return Err(ScriptIntError::NonMinimal);
}
let mut ret = 0i64;
let mut sh = 0;
for byte in v {
ret += i64::from(*byte) << sh;
sh += 8;
}
if v[v.len() - 1] & 0x80 != 0 {
ret &= (1 << (sh - 1)) - 1;
ret = -ret;
}
Ok(ret)
}
pub fn is_minimally_encoded_scriptnum(v: &[u8], max_len: usize) -> bool {
if v.len() > max_len {
return false;
}
if v.is_empty() {
return true;
}
let last = v[v.len() - 1];
if last.trailing_zeros() >= 7 {
if v.len() == 1 {
return false;
}
if v[v.len() - 2] & 0x80 == 0 {
return false;
}
}
true
}
#[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,
}
}
impl<T> From<ScriptBuf<T>> for Box<Script<T>> {
#[inline]
fn from(v: ScriptBuf<T>) -> Self {
v.into_boxed_script()
}
}
impl<T> From<ScriptBuf<T>> for Cow<'_, Script<T>> {
#[inline]
fn from(value: ScriptBuf<T>) -> Self {
Cow::Owned(value)
}
}
impl<'a, T> From<Cow<'a, Script<T>>> for ScriptBuf<T> {
#[inline]
fn from(value: Cow<'a, Script<T>>) -> Self {
match value {
Cow::Owned(owned) => owned,
Cow::Borrowed(borrowed) => borrowed.into(),
}
}
}
impl<'a, T> From<Cow<'a, Script<T>>> for Box<Script<T>> {
#[inline]
fn from(value: Cow<'a, Script<T>>) -> Self {
match value {
Cow::Owned(owned) => owned.into(),
Cow::Borrowed(borrowed) => borrowed.into(),
}
}
}
impl<'a, T> From<&'a Script<T>> for Box<Script<T>> {
#[inline]
fn from(value: &'a Script<T>) -> Self {
value.to_owned().into()
}
}
impl<'a, T> From<&'a Script<T>> for ScriptBuf<T> {
#[inline]
fn from(value: &'a Script<T>) -> Self {
value.to_owned()
}
}
impl<'a, T> From<&'a Script<T>> for Cow<'a, Script<T>> {
#[inline]
fn from(value: &'a Script<T>) -> Self {
Cow::Borrowed(value)
}
}
#[cfg(target_has_atomic = "ptr")]
impl<'a, T> From<&'a Script<T>> for Arc<Script<T>> {
#[inline]
fn from(value: &'a Script<T>) -> Self {
Script::from_arc_bytes(Arc::from(value.as_bytes()))
}
}
impl<'a, T> From<&'a Script<T>> for Rc<Script<T>> {
#[inline]
fn from(value: &'a Script<T>) -> Self {
Script::from_rc_bytes(Rc::from(value.as_bytes()))
}
}
impl<T> From<Vec<u8>> for ScriptBuf<T> {
#[inline]
fn from(v: Vec<u8>) -> Self {
Self::from_bytes(v)
}
}
impl<T> From<ScriptBuf<T>> for Vec<u8> {
#[inline]
fn from(v: ScriptBuf<T>) -> Self {
v.into_bytes()
}
}
impl<T> AsRef<Self> for Script<T> {
#[inline]
fn as_ref(&self) -> &Self {
self
}
}
impl<T> AsRef<Script<T>> for ScriptBuf<T> {
#[inline]
fn as_ref(&self) -> &Script<T> {
self
}
}
impl<T> AsRef<[u8]> for Script<T> {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl<T> AsRef<[u8]> for ScriptBuf<T> {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl<T> AsMut<Self> for Script<T> {
#[inline]
fn as_mut(&mut self) -> &mut Self {
self
}
}
impl<T> AsMut<Script<T>> for ScriptBuf<T> {
#[inline]
fn as_mut(&mut self) -> &mut Script<T> {
self
}
}
impl<T> AsMut<[u8]> for Script<T> {
#[inline]
fn as_mut(&mut self) -> &mut [u8] {
self.as_mut_bytes()
}
}
impl<T> AsMut<[u8]> for ScriptBuf<T> {
#[inline]
fn as_mut(&mut self) -> &mut [u8] {
self.as_mut_bytes()
}
}
impl<T> fmt::Debug for Script<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("Script(")?;
fmt::Display::fmt(self, f)?;
f.write_str(")")
}
}
impl<T> fmt::Debug for ScriptBuf<T> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.as_script(), f)
}
}
impl<T> fmt::Display for Script<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
macro_rules! read_push_data_len {
($iter:expr, $size:path, $formatter:expr) => {
match script::read_push_data_len($iter, $size) {
Ok(n) => n,
Err(_) => {
$formatter.write_str("<unexpected end>")?;
break;
}
}
};
}
let mut iter = self.as_bytes().iter();
let mut at_least_one = false;
while let Some(byte) = iter.next().copied() {
use crate::opcodes::{OP_PUSHDATA1, OP_PUSHDATA2, OP_PUSHDATA4};
let data_len = if byte <= 75 {
usize::from(byte)
} else {
match byte {
OP_PUSHDATA1 => {
read_push_data_len!(&mut iter, PushDataLenLen::One, f)
}
OP_PUSHDATA2 => {
read_push_data_len!(&mut iter, PushDataLenLen::Two, f)
}
OP_PUSHDATA4 => {
read_push_data_len!(&mut iter, PushDataLenLen::Four, f)
}
_ => 0,
}
};
if at_least_one {
f.write_str(" ")?;
} else {
at_least_one = true;
}
crate::opcodes::fmt_opcode(byte, f)?;
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(())
}
}
impl<T> fmt::Display for ScriptBuf<T> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.as_script(), f)
}
}
#[cfg(feature = "hex")]
impl<T> fmt::LowerHex for Script<T> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(&self.as_bytes().as_hex(), f)
}
}
#[cfg(feature = "hex")]
impl<T> fmt::LowerHex for ScriptBuf<T> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(self.as_script(), f)
}
}
#[cfg(feature = "hex")]
impl<T> fmt::UpperHex for Script<T> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::UpperHex::fmt(&self.as_bytes().as_hex(), f)
}
}
#[cfg(feature = "hex")]
impl<T> fmt::UpperHex for ScriptBuf<T> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::UpperHex::fmt(self.as_script(), f)
}
}
impl<T> Borrow<Script<T>> for ScriptBuf<T> {
#[inline]
fn borrow(&self) -> &Script<T> {
self
}
}
impl<T> BorrowMut<Script<T>> for ScriptBuf<T> {
#[inline]
fn borrow_mut(&mut self) -> &mut Script<T> {
self
}
}
impl<T: PartialEq> PartialEq<ScriptBuf<T>> for Script<T> {
#[inline]
fn eq(&self, other: &ScriptBuf<T>) -> bool {
self.eq(other.as_script())
}
}
impl<T: PartialEq> PartialEq<Script<T>> for ScriptBuf<T> {
#[inline]
fn eq(&self, other: &Script<T>) -> bool {
self.as_script().eq(other)
}
}
impl<T: PartialOrd> PartialOrd<Script<T>> for ScriptBuf<T> {
#[inline]
fn partial_cmp(&self, other: &Script<T>) -> Option<Ordering> {
self.as_script().partial_cmp(other)
}
}
impl<T: PartialOrd> PartialOrd<ScriptBuf<T>> for Script<T> {
#[inline]
fn partial_cmp(&self, other: &ScriptBuf<T>) -> Option<Ordering> {
self.partial_cmp(other.as_script())
}
}
#[cfg(feature = "serde")]
impl<T> serde::Serialize for Script<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if serializer.is_human_readable() {
serializer.collect_str(&format_args!("{:x}", self))
} else {
serializer.serialize_bytes(self.as_bytes())
}
}
}
#[cfg(feature = "serde")]
impl<'de, T> serde::Deserialize<'de> for &'de Script<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct Visitor<T>(PhantomData<T>);
impl<'de, T: 'de> serde::de::Visitor<'de> for Visitor<T> {
type Value = &'de Script<T>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("borrowed bytes")
}
fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(Script::from_bytes(v))
}
}
if deserializer.is_human_readable() {
use crate::serde::de::Error;
return Err(D::Error::custom(
"deserialization of `&Script` from human-readable formats is not possible",
));
}
deserializer.deserialize_bytes(Visitor(PhantomData))
}
}
#[cfg(feature = "serde")]
impl<T> serde::Serialize for ScriptBuf<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
(**self).serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de, T> serde::Deserialize<'de> for ScriptBuf<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use core::fmt::Formatter;
if deserializer.is_human_readable() {
struct Visitor<T>(PhantomData<T>);
impl<T> serde::de::Visitor<'_> for Visitor<T> {
type Value = ScriptBuf<T>;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("a script hex")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
let v = hex::decode_to_vec(v).map_err(E::custom)?;
Ok(ScriptBuf::from(v))
}
}
deserializer.deserialize_str(Visitor(PhantomData))
} else {
struct BytesVisitor<T>(PhantomData<T>);
impl<T> serde::de::Visitor<'_> for BytesVisitor<T> {
type Value = ScriptBuf<T>;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("a script Vec<u8>")
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(ScriptBuf::from(v.to_vec()))
}
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(ScriptBuf::from(v))
}
}
deserializer.deserialize_byte_buf(BytesVisitor(PhantomData))
}
}
}