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
use crate::ScriptError;
use ckb_error::Error;
use ckb_types::{
core::{Cycle, ScriptHashType},
packed::Script,
};
use ckb_vm::{
machine::{VERSION0, VERSION1},
memory::{FLAG_EXECUTABLE, FLAG_FREEZED},
snapshot::{make_snapshot, Snapshot},
CoreMachine as _, Memory, SupportMachine, ISA_B, ISA_IMC, ISA_MOP, RISCV_PAGESIZE,
};
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use std::fmt;
#[cfg(has_asm)]
use ckb_vm::machine::asm::{AsmCoreMachine, AsmMachine};
#[cfg(not(has_asm))]
use ckb_vm::{DefaultCoreMachine, SparseMemory, TraceMachine, WXorXMemory};
pub type VmIsa = u8;
pub type VmVersion = u32;
#[cfg(has_asm)]
pub(crate) type CoreMachineType = AsmCoreMachine;
#[cfg(not(has_asm))]
pub(crate) type CoreMachineType = DefaultCoreMachine<u64, WXorXMemory<SparseMemory<u64>>>;
#[cfg(has_asm)]
pub type CoreMachine = Box<AsmCoreMachine>;
#[cfg(not(has_asm))]
pub type CoreMachine = DefaultCoreMachine<u64, WXorXMemory<SparseMemory<u64>>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ScriptVersion {
V0 = 0,
V1 = 1,
}
impl ScriptVersion {
pub const fn latest() -> Self {
Self::V1
}
pub fn vm_isa(self) -> VmIsa {
match self {
Self::V0 => ISA_IMC,
Self::V1 => ISA_IMC | ISA_B | ISA_MOP,
}
}
pub fn vm_version(self) -> VmVersion {
match self {
Self::V0 => VERSION0,
Self::V1 => VERSION1,
}
}
pub fn data_hash_type(self) -> ScriptHashType {
match self {
Self::V0 => ScriptHashType::Data,
Self::V1 => ScriptHashType::Data1,
}
}
pub fn init_core_machine_without_limit(self) -> CoreMachine {
self.init_core_machine(u64::MAX)
}
pub fn init_core_machine(self, max_cycles: Cycle) -> CoreMachine {
let isa = self.vm_isa();
let version = self.vm_version();
CoreMachineType::new(isa, version, max_cycles)
}
}
#[cfg(has_asm)]
pub(crate) type Machine<'a> = AsmMachine<'a>;
#[cfg(not(has_asm))]
pub(crate) type Machine<'a> = TraceMachine<'a, CoreMachine>;
pub struct ResumableMachine<'a> {
pub(crate) machine: Machine<'a>,
pub(crate) program_loaded: bool,
}
impl<'a> ResumableMachine<'a> {
pub(crate) fn new(machine: Machine<'a>, program_loaded: bool) -> Self {
ResumableMachine {
machine,
program_loaded,
}
}
pub(crate) fn cycles(&self) -> Cycle {
self.machine.machine.cycles()
}
#[cfg(test)]
pub(crate) fn set_cycles(&mut self, cycles: Cycle) {
self.machine.machine.set_cycles(cycles)
}
pub(crate) fn set_max_cycles(&mut self, cycles: Cycle) {
set_vm_max_cycles(&mut self.machine, cycles)
}
pub fn program_loaded(&self) -> bool {
self.program_loaded
}
}
#[cfg(has_asm)]
pub(crate) fn set_vm_max_cycles(vm: &mut Machine<'_>, cycles: Cycle) {
vm.set_max_cycles(cycles)
}
#[cfg(not(has_asm))]
pub(crate) fn set_vm_max_cycles(vm: &mut Machine<'_>, cycles: Cycle) {
vm.machine.inner_mut().set_max_cycles(cycles)
}
pub struct ScriptGroup {
pub script: Script,
pub group_type: ScriptGroupType,
pub input_indices: Vec<usize>,
pub output_indices: Vec<usize>,
}
impl ScriptGroup {
pub fn new(script: &Script, group_type: ScriptGroupType) -> Self {
Self {
group_type,
script: script.to_owned(),
input_indices: vec![],
output_indices: vec![],
}
}
pub fn from_lock_script(script: &Script) -> Self {
Self::new(script, ScriptGroupType::Lock)
}
pub fn from_type_script(script: &Script) -> Self {
Self::new(script, ScriptGroupType::Type)
}
}
#[derive(Copy, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ScriptGroupType {
Lock,
Type,
}
impl fmt::Display for ScriptGroupType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ScriptGroupType::Lock => write!(f, "Lock"),
ScriptGroupType::Type => write!(f, "Type"),
}
}
}
pub struct TransactionSnapshot {
pub current: usize,
pub snap: Option<(Snapshot, Cycle)>,
pub current_cycles: Cycle,
pub limit_cycles: Cycle,
}
pub struct TransactionState<'a> {
pub current: usize,
pub vm: Option<ResumableMachine<'a>>,
pub current_cycles: Cycle,
pub limit_cycles: Cycle,
pub enable_backup_page_flags: bool,
pub flags_tracing: Vec<(u64, u64)>,
}
impl TransactionState<'_> {
pub fn next_limit_cycles(&self, step_cycles: Cycle, max_cycles: Cycle) -> (Cycle, bool) {
let remain = max_cycles - self.current_cycles;
let next_limit = self.limit_cycles + step_cycles;
if next_limit < remain {
(next_limit, false)
} else {
(remain, true)
}
}
}
impl TransactionSnapshot {
pub fn next_limit_cycles(&self, step_cycles: Cycle, max_cycles: Cycle) -> (Cycle, bool) {
let remain = max_cycles - self.current_cycles;
let next_limit = self.limit_cycles + step_cycles;
if next_limit < remain {
(next_limit, false)
} else {
(remain, true)
}
}
}
impl TryFrom<TransactionState<'_>> for TransactionSnapshot {
type Error = Error;
fn try_from(state: TransactionState<'_>) -> Result<Self, Self::Error> {
let TransactionState {
current,
vm,
current_cycles,
limit_cycles,
enable_backup_page_flags,
flags_tracing,
} = state;
let (snap, current_cycles) = if let Some(mut vm) = vm {
if vm.program_loaded {
let vm_cycles = vm.cycles();
if !enable_backup_page_flags {
for (addr, memory_size) in flags_tracing {
let mut current_addr = addr;
while current_addr < addr + memory_size {
let page = current_addr / RISCV_PAGESIZE as u64;
vm.machine
.machine
.memory_mut()
.clear_flag(page, FLAG_EXECUTABLE | FLAG_FREEZED)
.map_err(|e| {
ScriptError::VMInternalError(format!("{:?}", e))
.unknown_source()
})?;
current_addr += RISCV_PAGESIZE as u64;
}
}
}
(
Some((
make_snapshot(&mut vm.machine.machine).map_err(|e| {
ScriptError::VMInternalError(format!("{:?}", e)).unknown_source()
})?,
vm_cycles,
)),
current_cycles,
)
} else {
(None, current_cycles)
}
} else {
(None, current_cycles)
};
Ok(TransactionSnapshot {
current,
snap,
current_cycles,
limit_cycles,
})
}
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum VerifyResult<'a> {
Completed(Cycle),
Suspended(TransactionState<'a>),
}
impl std::fmt::Debug for TransactionSnapshot {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("TransactionSnapshot")
.field("current", &self.current)
.field("current_cycles", &self.current_cycles)
.field("limit_cycles", &self.limit_cycles)
.finish()
}
}
impl std::fmt::Debug for TransactionState<'_> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("TransactionState")
.field("current", &self.current)
.field("current_cycles", &self.current_cycles)
.field("limit_cycles", &self.limit_cycles)
.finish()
}
}