forked from BitVM/BitVM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
232 lines (213 loc) · 6.39 KB
/
lib.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
#[allow(dead_code)]
// Re-export what is needed to write treepp scripts
pub mod treepp {
pub use crate::execute_script;
pub use bitcoin_script::{define_pushable, script};
define_pushable!();
pub use bitcoin::ScriptBuf as Script;
}
use core::fmt;
use bitcoin::{hashes::Hash, hex::DisplayHex, Opcode, TapLeafHash, Transaction};
use bitcoin_scriptexec::{Exec, ExecCtx, ExecError, ExecStats, Options, Stack, TxTemplate};
pub mod bigint;
pub mod bn254;
pub mod bridge;
pub mod fflonk;
pub mod groth16;
pub mod hash;
pub mod pseudo;
pub mod signatures;
pub mod u32;
pub mod u4;
/// A wrapper for the stack types to print them better.
pub struct FmtStack(Stack);
impl fmt::Display for FmtStack {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut iter = self.0.iter_str().enumerate().peekable();
write!(f, "\n0:\t\t ")?;
while let Some((index, item)) = iter.next() {
write!(f, "0x{:8}", item.as_hex())?;
if iter.peek().is_some() {
if (index + 1) % f.width().unwrap() == 0 {
write!(f, "\n{}:\t\t", index + 1)?;
}
write!(f, " ")?;
}
}
Ok(())
}
}
impl FmtStack {
pub fn len(&self) -> usize { self.0.len() }
pub fn get(&self, index: usize) -> Vec<u8> { self.0.get(index) }
}
impl fmt::Debug for FmtStack {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)?;
Ok(())
}
}
#[derive(Debug)]
pub struct ExecuteInfo {
pub success: bool,
pub error: Option<ExecError>,
pub final_stack: FmtStack,
pub remaining_script: String,
pub last_opcode: Option<Opcode>,
pub stats: ExecStats,
}
impl fmt::Display for ExecuteInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.success {
writeln!(f, "Script execution successful.")?;
} else {
writeln!(f, "Script execution failed!")?;
}
if let Some(ref error) = self.error {
writeln!(f, "Error: {:?}", error)?;
}
if !self.remaining_script.is_empty() {
writeln!(f, "Remaining Script: {}", self.remaining_script)?;
}
if self.final_stack.len() > 0 {
match f.width() {
None => writeln!(f, "Final Stack: {:4}", self.final_stack)?,
Some(width) => {
writeln!(f, "Final Stack: {:width$}", self.final_stack, width = width)?
}
}
}
if let Some(ref opcode) = self.last_opcode {
writeln!(f, "Last Opcode: {:?}", opcode)?;
}
writeln!(f, "Stats: {:?}", self.stats)?;
Ok(())
}
}
pub fn execute_script(script: bitcoin::ScriptBuf) -> ExecuteInfo {
let mut exec = Exec::new(
ExecCtx::Tapscript,
Options::default(),
TxTemplate {
tx: Transaction {
version: bitcoin::transaction::Version::TWO,
lock_time: bitcoin::locktime::absolute::LockTime::ZERO,
input: vec![],
output: vec![],
},
prevouts: vec![],
input_idx: 0,
taproot_annex_scriptleaf: Some((TapLeafHash::all_zeros(), None)),
},
script,
vec![],
)
.expect("error creating exec");
loop {
if exec.exec_next().is_err() {
break;
}
}
let res = exec.result().unwrap();
ExecuteInfo {
success: res.success,
error: res.error.clone(),
last_opcode: res.opcode,
final_stack: FmtStack(exec.stack().clone()),
remaining_script: exec.remaining_script().to_asm_string(),
stats: exec.stats().clone(),
}
}
// Execute a script on stack without `MAX_STACK_SIZE` limit.
// This function is only used for script test, not for production.
//
// NOTE: Only for test purposes.
pub fn execute_script_without_stack_limit(script: bitcoin::ScriptBuf) -> ExecuteInfo {
// Get the default options for the script exec.
let mut opts = Options::default();
// Do not enforce the stack limit.
opts.enforce_stack_limit = false;
let mut exec = Exec::new(
ExecCtx::Tapscript,
opts,
TxTemplate {
tx: Transaction {
version: bitcoin::transaction::Version::TWO,
lock_time: bitcoin::locktime::absolute::LockTime::ZERO,
input: vec![],
output: vec![],
},
prevouts: vec![],
input_idx: 0,
taproot_annex_scriptleaf: Some((TapLeafHash::all_zeros(), None)),
},
script,
vec![],
)
.expect("error creating exec");
loop {
if exec.exec_next().is_err() {
break;
}
}
let res = exec.result().unwrap();
ExecuteInfo {
success: res.success,
error: res.error.clone(),
last_opcode: res.opcode,
final_stack: FmtStack(exec.stack().clone()),
remaining_script: exec.remaining_script().to_asm_string(),
stats: exec.stats().clone(),
}
}
#[cfg(test)]
mod test {
use crate::bn254;
use crate::bn254::fp254impl::Fp254Impl;
use super::execute_script_without_stack_limit;
use super::treepp::*;
#[test]
fn test_script_debug() {
let script = script! {
OP_TRUE
DEBUG
OP_TRUE
OP_VERIFY
};
let exec_result = execute_script(script);
assert!(!exec_result.success);
}
#[test]
fn test_script_execute() {
let script = script! {
for i in 0..36 {
{ 0x0babe123 + i }
}
};
let exec_result = execute_script(script);
// The width decides how many stack elements are printed per row
println!(
"{:width$}",
exec_result,
width = bn254::fq::Fq::N_LIMBS as usize
);
println!("{:4}", exec_result);
println!("{}", exec_result);
assert!(!exec_result.success);
assert_eq!(exec_result.error, None);
}
#[test]
fn test_execute_script_without_stack_limit() {
let script = script! {
for i in 0..1001 {
OP_1
}
for i in 0..1001 {
OP_DROP
}
OP_1
};
let exec_result = execute_script_without_stack_limit(script);
assert!(exec_result.success);
}
}