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
use crate::tx_verifier::OutputsDataVerifier;
use ckb_chain_spec::consensus::{ConsensusBuilder, TYPE_ID_CODE_HASH};
use ckb_error::Error as CKBError;
use ckb_script::{TransactionScriptsVerifier, TxVerifyEnv};
use ckb_traits::{CellDataProvider, HeaderProvider};
use ckb_types::{
bytes::Bytes,
core::{
cell::{CellMeta, CellMetaBuilder, ResolvedTransaction},
hardfork::HardForkSwitch,
Capacity, Cycle, DepType, EpochExt, EpochNumberWithFraction, HeaderView, ScriptHashType,
TransactionInfo, TransactionView,
},
packed::{Byte32, CellDep, CellOutput, OutPoint, Script},
prelude::*,
};
use linked_hash_set::LinkedHashSet;
use rand::{thread_rng, Rng};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
pub fn random_hash() -> Byte32 {
let mut rng = thread_rng();
let mut buf = [0u8; 32];
rng.fill(&mut buf);
buf.pack()
}
pub fn random_out_point() -> OutPoint {
OutPoint::new_builder().tx_hash(random_hash()).build()
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Message {
pub id: Byte32,
pub message: String,
}
#[derive(Default)]
pub struct Context {
pub cells: HashMap<OutPoint, (CellOutput, Bytes)>,
pub transaction_infos: HashMap<OutPoint, TransactionInfo>,
pub headers: HashMap<Byte32, HeaderView>,
pub epoches: HashMap<Byte32, EpochExt>,
pub cells_by_data_hash: HashMap<Byte32, OutPoint>,
capture_debug: bool,
captured_messages: Arc<Mutex<Vec<Message>>>,
}
impl Context {
#[deprecated(since = "0.1.1", note = "Please use the deploy_cell function instead")]
pub fn deploy_contract(&mut self, data: Bytes) -> OutPoint {
self.deploy_cell(data)
}
pub fn deploy_cell(&mut self, data: Bytes) -> OutPoint {
let data_hash = CellOutput::calc_data_hash(&data);
if let Some(out_point) = self.cells_by_data_hash.get(&data_hash) {
return out_point.to_owned();
}
let mut rng = thread_rng();
let tx_hash = {
let mut buf = [0u8; 32];
rng.fill(&mut buf);
buf.pack()
};
let out_point = OutPoint::new(tx_hash.clone(), 0);
let cell = CellOutput::new_builder()
.capacity(Capacity::bytes(data.len()).expect("script capacity").pack())
.build();
self.cells.insert(out_point.clone(), (cell, data.into()));
self.cells_by_data_hash.insert(data_hash, out_point.clone());
out_point
}
pub fn insert_header(&mut self, header: HeaderView) {
self.headers.insert(header.hash(), header);
}
pub fn link_cell_with_block(
&mut self,
out_point: OutPoint,
block_hash: Byte32,
tx_index: usize,
) {
let header = self
.headers
.get(&block_hash)
.expect("can't find the header");
self.transaction_infos.insert(
out_point,
TransactionInfo::new(header.number(), header.epoch(), block_hash, tx_index),
);
}
#[deprecated(
since = "0.1.1",
note = "Please use the get_cell_by_data_hash function instead"
)]
pub fn get_contract_out_point(&self, data_hash: &Byte32) -> Option<OutPoint> {
self.get_cell_by_data_hash(data_hash)
}
pub fn get_cell_by_data_hash(&self, data_hash: &Byte32) -> Option<OutPoint> {
self.cells_by_data_hash.get(data_hash).cloned()
}
pub fn create_cell(&mut self, cell: CellOutput, data: Bytes) -> OutPoint {
let out_point = random_out_point();
self.create_cell_with_out_point(out_point.clone(), cell, data);
out_point
}
pub fn create_cell_with_out_point(
&mut self,
out_point: OutPoint,
cell: CellOutput,
data: Bytes,
) {
self.cells.insert(out_point, (cell, data));
}
#[deprecated(
since = "0.1.1",
note = "Please use the create_cell_with_out_point function instead"
)]
pub fn insert_cell(&mut self, out_point: OutPoint, cell: CellOutput, data: Bytes) {
self.create_cell_with_out_point(out_point, cell, data)
}
pub fn get_cell(&self, out_point: &OutPoint) -> Option<(CellOutput, Bytes)> {
self.cells.get(out_point).cloned()
}
pub fn build_script(&mut self, out_point: &OutPoint, args: Bytes) -> Option<Script> {
let (_, contract_data) = self.cells.get(out_point)?;
let data_hash = CellOutput::calc_data_hash(contract_data);
Some(
Script::new_builder()
.code_hash(data_hash)
.hash_type(ScriptHashType::Data.into())
.args(args.pack())
.build(),
)
}
fn find_cell_dep_for_script(&self, script: &Script) -> CellDep {
if script.hash_type() != ScriptHashType::Data.into() {
panic!("do not support hash_type {} yet", script.hash_type());
}
let out_point = self
.get_cell_by_data_hash(&script.code_hash())
.expect("find contract out point");
CellDep::new_builder()
.out_point(out_point)
.dep_type(DepType::Code.into())
.build()
}
pub fn complete_tx(&mut self, tx: TransactionView) -> TransactionView {
let mut cell_deps: LinkedHashSet<CellDep> = LinkedHashSet::new();
for cell_dep in tx.cell_deps_iter() {
cell_deps.insert(cell_dep);
}
for i in tx.input_pts_iter() {
if let Some((cell, _data)) = self.cells.get(&i) {
let dep = self.find_cell_dep_for_script(&cell.lock());
cell_deps.insert(dep);
if let Some(script) = cell.type_().to_opt() {
if script.code_hash() != TYPE_ID_CODE_HASH.pack()
|| script.hash_type() != ScriptHashType::Type.into()
{
let dep = self.find_cell_dep_for_script(&script);
cell_deps.insert(dep);
}
}
}
}
for (cell, _data) in tx.outputs_with_data_iter() {
if let Some(script) = cell.type_().to_opt() {
if script.code_hash() != TYPE_ID_CODE_HASH.pack()
|| script.hash_type() != ScriptHashType::Type.into()
{
let dep = self.find_cell_dep_for_script(&script);
cell_deps.insert(dep);
}
}
}
tx.as_advanced_builder()
.set_cell_deps(Vec::new())
.cell_deps(cell_deps.into_iter().collect::<Vec<_>>().pack())
.build()
}
fn build_resolved_tx(&self, tx: &TransactionView) -> ResolvedTransaction {
let input_cells = tx
.inputs()
.into_iter()
.map(|input| {
let previous_out_point = input.previous_output();
let (input_output, input_data) = self.cells.get(&previous_out_point).unwrap();
let tx_info_opt = self.transaction_infos.get(&previous_out_point);
let mut b = CellMetaBuilder::from_cell_output(
input_output.to_owned(),
input_data.to_vec().into(),
)
.out_point(previous_out_point);
if let Some(tx_info) = tx_info_opt {
b = b.transaction_info(tx_info.to_owned());
}
b.build()
})
.collect();
let resolved_cell_deps = tx
.cell_deps()
.into_iter()
.map(|deps_out_point| {
let (dep_output, dep_data) = self.cells.get(&deps_out_point.out_point()).unwrap();
let tx_info_opt = self.transaction_infos.get(&deps_out_point.out_point());
let mut b = CellMetaBuilder::from_cell_output(
dep_output.to_owned(),
dep_data.to_vec().into(),
)
.out_point(deps_out_point.out_point());
if let Some(tx_info) = tx_info_opt {
b = b.transaction_info(tx_info.to_owned());
}
b.build()
})
.collect();
ResolvedTransaction {
transaction: tx.clone(),
resolved_cell_deps,
resolved_inputs: input_cells,
resolved_dep_groups: vec![],
}
}
fn verify_tx_consensus(&self, tx: &TransactionView) -> Result<(), CKBError> {
OutputsDataVerifier::new(tx).verify()?;
Ok(())
}
pub fn capture_debug(&self) -> bool {
self.capture_debug
}
pub fn set_capture_debug(&mut self, capture_debug: bool) {
self.capture_debug = capture_debug;
}
pub fn captured_messages(&self) -> Vec<Message> {
self.captured_messages.lock().unwrap().clone()
}
pub fn verify_tx(&self, tx: &TransactionView, max_cycles: u64) -> Result<Cycle, CKBError> {
let consensus = {
let hardfork_switch = HardForkSwitch::new_without_any_enabled()
.as_builder()
.rfc_0232(200)
.build()
.unwrap();
ConsensusBuilder::default()
.hardfork_switch(hardfork_switch)
.build()
};
let tx_env = {
let epoch = EpochNumberWithFraction::new(300, 0, 1);
let header = HeaderView::new_advanced_builder()
.epoch(epoch.pack())
.build();
TxVerifyEnv::new_commit(&header)
};
self.verify_tx_consensus(tx)?;
let resolved_tx = self.build_resolved_tx(tx);
let mut verifier = TransactionScriptsVerifier::new(&resolved_tx, &consensus, self, &tx_env);
if self.capture_debug {
let captured_messages = self.captured_messages.clone();
verifier.set_debug_printer(move |id, message| {
let msg = Message {
id: id.clone(),
message: message.to_string(),
};
captured_messages.lock().unwrap().push(msg);
});
} else {
verifier.set_debug_printer(|_id, msg| {
println!("[contract debug] {}", msg);
});
}
verifier.verify(max_cycles)
}
}
impl CellDataProvider for Context {
fn load_cell_data(&self, cell: &CellMeta) -> Option<Bytes> {
cell.mem_cell_data
.as_ref()
.map(|data| Bytes::from(data.to_vec()))
.or_else(|| self.get_cell_data(&cell.out_point))
}
fn get_cell_data(&self, out_point: &OutPoint) -> Option<Bytes> {
self.cells
.get(out_point)
.map(|(_, data)| Bytes::from(data.to_vec()))
}
fn get_cell_data_hash(&self, out_point: &OutPoint) -> Option<Byte32> {
self.cells
.get(out_point)
.map(|(_, data)| CellOutput::calc_data_hash(&data))
}
}
impl HeaderProvider for Context {
fn get_header(&self, block_hash: &Byte32) -> Option<HeaderView> {
self.headers.get(block_hash).cloned()
}
}