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
use crate::{ckb_constants::*, error::SysError};
#[cfg(target_arch = "riscv64")]
use core::arch::asm;
use core::ffi::CStr;

#[cfg(target_arch = "riscv64")]
unsafe fn syscall(
    mut a0: u64,
    a1: u64,
    a2: u64,
    a3: u64,
    a4: u64,
    a5: u64,
    a6: u64,
    a7: u64,
) -> u64 {
    asm!(
      "ecall",
      inout("a0") a0,
      in("a1") a1,
      in("a2") a2,
      in("a3") a3,
      in("a4") a4,
      in("a5") a5,
      in("a6") a6,
      in("a7") a7
    );
    a0
}

#[cfg(not(target_arch = "riscv64"))]
unsafe fn syscall(
    _a0: u64,
    _a1: u64,
    _a2: u64,
    _a3: u64,
    _a4: u64,
    _a5: u64,
    _a6: u64,
    _a7: u64,
) -> u64 {
    u64::MAX
}

/// Exit, this script will be terminated after the exit syscall.
/// exit code `0` represents verification is success, others represent error code.
pub fn exit(code: i8) -> ! {
    unsafe { syscall(code as u64, 0, 0, 0, 0, 0, 0, SYS_EXIT) };
    loop {}
}

/// Load data
/// Return data length or syscall error
fn syscall_load(
    buf_ptr: *mut u8,
    len: usize,
    offset: usize,
    a3: u64,
    a4: u64,
    a5: u64,
    a6: u64,
    syscall_num: u64,
) -> Result<usize, SysError> {
    let mut actual_data_len = len;
    let len_ptr: *mut usize = &mut actual_data_len;
    let ret = unsafe {
        syscall(
            buf_ptr as u64,
            len_ptr as u64,
            offset as u64,
            a3,
            a4,
            a5,
            a6,
            syscall_num,
        )
    };
    SysError::build_syscall_result(ret, len, actual_data_len)
}

/// Load transaction hash
///
/// Return the loaded data length or a syscall error
///
/// # Arguments
///
/// * `buf` - a writable buf used to receive the data
/// * `offset` - offset
///
/// # Example
///
/// ```
/// let mut tx_hash = [0u8; 32];
/// let len = load_tx_hash(&mut tx_hash, 0).unwrap();
/// assert_eq!(len, tx_hash.len());
/// ```
pub fn load_tx_hash(buf: &mut [u8], offset: usize) -> Result<usize, SysError> {
    syscall_load(
        buf.as_mut_ptr(),
        buf.len(),
        offset,
        0,
        0,
        0,
        0,
        SYS_LOAD_TX_HASH,
    )
}

/// Load script hash
///
/// Return the loaded data length or a syscall error
///
/// # Arguments
///
/// * `buf` - a writable buf used to receive the data
/// * `offset` - offset
///
/// # Example
///
/// ```
/// let mut script_hash = [0u8; 32];
/// let len = load_script_hash(&mut script_hash, 0).unwrap();
/// assert_eq!(len, script_hash.len());
/// ```
pub fn load_script_hash(buf: &mut [u8], offset: usize) -> Result<usize, SysError> {
    syscall_load(
        buf.as_mut_ptr(),
        buf.len(),
        offset,
        0,
        0,
        0,
        0,
        SYS_LOAD_SCRIPT_HASH,
    )
}

/// Load cell
///
/// Return the loaded data length or a syscall error
///
/// # Arguments
///
/// * `buf` - a writable buf used to receive the data
/// * `offset` - offset
/// * `index` - index of cell
/// * `source` - source of cell
pub fn load_cell(
    buf: &mut [u8],
    offset: usize,
    index: usize,
    source: Source,
) -> Result<usize, SysError> {
    syscall_load(
        buf.as_mut_ptr(),
        buf.len(),
        offset,
        index as u64,
        source as u64,
        0,
        0,
        SYS_LOAD_CELL,
    )
}

/// Load input
///
/// Return the loaded data length or a syscall error
///
/// # Arguments
///
/// * `buf` - a writable buf used to receive the data
/// * `offset` - offset
/// * `index` - index of cell
/// * `source` - source of cell
pub fn load_input(
    buf: &mut [u8],
    offset: usize,
    index: usize,
    source: Source,
) -> Result<usize, SysError> {
    syscall_load(
        buf.as_mut_ptr(),
        buf.len(),
        offset,
        index as u64,
        source as u64,
        0,
        0,
        SYS_LOAD_INPUT,
    )
}

/// Load header
///
/// Return the loaded data length or a syscall error
///
/// # Arguments
///
/// * `buf` - a writable buf used to receive the data
/// * `offset` - offset
/// * `index` - index of cell or header
/// * `source` - source
pub fn load_header(
    buf: &mut [u8],
    offset: usize,
    index: usize,
    source: Source,
) -> Result<usize, SysError> {
    syscall_load(
        buf.as_mut_ptr(),
        buf.len(),
        offset,
        index as u64,
        source as u64,
        0,
        0,
        SYS_LOAD_HEADER,
    )
}

/// Load witness
///
/// Return the loaded data length or a syscall error
///
/// # Arguments
///
/// * `buf` - a writable buf used to receive the data
/// * `offset` - offset
/// * `index` - index of cell
/// * `source` - source
pub fn load_witness(
    buf: &mut [u8],
    offset: usize,
    index: usize,
    source: Source,
) -> Result<usize, SysError> {
    syscall_load(
        buf.as_mut_ptr(),
        buf.len(),
        offset,
        index as u64,
        source as u64,
        0,
        0,
        SYS_LOAD_WITNESS,
    )
}

/// Load transaction
///
/// Return the loaded data length or a syscall error
///
/// # Arguments
///
/// * `buf` - a writable buf used to receive the data
/// * `offset` - offset
pub fn load_transaction(buf: &mut [u8], offset: usize) -> Result<usize, SysError> {
    syscall_load(
        buf.as_mut_ptr(),
        buf.len(),
        offset,
        0,
        0,
        0,
        0,
        SYS_LOAD_TRANSACTION,
    )
}

/// Load cell by field
///
/// Return the loaded data length or a syscall error
///
/// # Arguments
///
/// * `buf` - a writable buf used to receive the data
/// * `offset` - offset
/// * `index` - index of cell
/// * `source` - source of cell
/// * `field` - field of cell
///
/// # Example
///
/// ```
/// let mut buf = [0u8; size_of::<u64>()];
/// let len = load_cell_by_field(&mut buf, 0, 0, Source::GroupInput, CellField::Capacity).unwrap();
/// assert_eq!(len, buf.len());
/// ```
pub fn load_cell_by_field(
    buf: &mut [u8],
    offset: usize,
    index: usize,
    source: Source,
    field: CellField,
) -> Result<usize, SysError> {
    syscall_load(
        buf.as_mut_ptr(),
        buf.len(),
        offset,
        index as u64,
        source as u64,
        field as u64,
        0,
        SYS_LOAD_CELL_BY_FIELD,
    )
}

/// Load header by field
///
/// Return the loaded data length or a syscall error
///
/// # Arguments
///
/// * `buf` - a writable buf used to receive the data
/// * `offset` - offset
/// * `index` - index
/// * `source` - source
/// * `field` - field
///
/// # Example
///
/// ```
/// let mut buf = [0u8; 8];
/// let len = load_header_by_field(&mut buf, 0, index, source, HeaderField::EpochNumber)?;
/// debug_assert_eq!(len, buf.len());
/// ```
pub fn load_header_by_field(
    buf: &mut [u8],
    offset: usize,
    index: usize,
    source: Source,
    field: HeaderField,
) -> Result<usize, SysError> {
    syscall_load(
        buf.as_mut_ptr(),
        buf.len(),
        offset,
        index as u64,
        source as u64,
        field as u64,
        0,
        SYS_LOAD_HEADER_BY_FIELD,
    )
}

/// Load input by field
///
/// Return the loaded data length or a syscall error
///
/// # Arguments
///
/// * `buf` - a writable buf used to receive the data
/// * `offset` - offset
/// * `index` - index
/// * `source` - source
/// * `field` - field
///
/// # Example
///
/// ```
/// let mut buf = [0u8; 8];
/// let len = load_input_by_field(&mut buf, 0, index, source, InputField::Since)?;
/// debug_assert_eq!(len, buf.len());
/// ```
pub fn load_input_by_field(
    buf: &mut [u8],
    offset: usize,
    index: usize,
    source: Source,
    field: InputField,
) -> Result<usize, SysError> {
    syscall_load(
        buf.as_mut_ptr(),
        buf.len(),
        offset,
        index as u64,
        source as u64,
        field as u64,
        0,
        SYS_LOAD_INPUT_BY_FIELD,
    )
}

/// Load cell data, read cell data
///
/// Return the loaded data length or a syscall error
///
/// # Arguments
///
/// * `buf` - a writable buf used to receive the data
/// * `offset` - offset
/// * `index` - index
/// * `source` - source
pub fn load_cell_data(
    buf: &mut [u8],
    offset: usize,
    index: usize,
    source: Source,
) -> Result<usize, SysError> {
    syscall_load(
        buf.as_mut_ptr(),
        buf.len(),
        offset,
        index as u64,
        source as u64,
        0,
        0,
        SYS_LOAD_CELL_DATA,
    )
}

/// Load script
///
/// Return the loaded data length or a syscall error
///
/// # Arguments
///
/// * `buf` - a writable buf used to receive the data
/// * `offset` - offset
pub fn load_script(buf: &mut [u8], offset: usize) -> Result<usize, SysError> {
    syscall_load(
        buf.as_mut_ptr(),
        buf.len(),
        offset,
        0,
        0,
        0,
        0,
        SYS_LOAD_SCRIPT,
    )
}

/// Output debug message
///
/// You should use the macro version syscall: `debug!`
///
/// # Arguments
///
/// * `s` - string to output
pub fn debug(mut s: alloc::string::String) {
    s.push('\0');
    let c_str = s.into_bytes();
    unsafe {
        syscall(c_str.as_ptr() as u64, 0, 0, 0, 0, 0, 0, SYS_DEBUG);
    }
}

/// Load cell data, read cell data
///
/// Return the loaded data length or a syscall error
///
/// # Arguments
///
/// * `buf_ptr` - a writable pointer used to receive the data
/// * `len` - length that the `buf_ptr` can receives.
/// * `offset` - offset
/// * `index` - index
/// * `source` - source
pub fn load_cell_data_raw(
    buf_ptr: *mut u8,
    len: usize,
    offset: usize,
    index: usize,
    source: Source,
) -> Result<usize, SysError> {
    syscall_load(
        buf_ptr,
        len,
        offset,
        index as u64,
        source as u64,
        0,
        0,
        SYS_LOAD_CELL_DATA,
    )
}

/// Load cell code, read cell data as executable code
///
/// Return the loaded data length or a syscall error
///
/// # Arguments
///
/// * `buf_ptr` - a writable pointer used to receive the data
/// * `len` - length that the `buf_ptr` can receives.
/// * `content_offset` - offset
/// * `content_size` - read length
/// * `index` - index
/// * `source` - source
pub fn load_cell_code(
    buf_ptr: *mut u8,
    len: usize,
    content_offset: usize,
    content_size: usize,
    index: usize,
    source: Source,
) -> Result<usize, SysError> {
    let ret = unsafe {
        syscall(
            buf_ptr as u64,
            len as u64,
            content_offset as u64,
            content_size as u64,
            index as u64,
            source as u64,
            0,
            SYS_LOAD_CELL_DATA_AS_CODE,
        )
    };
    SysError::build_syscall_result(ret, len, len)
}

/// *VM version* syscall returns current running VM version, so far 2 values will be returned:
///   - Error for Lina CKB-VM version
///   - 1 for the new hardfork CKB-VM version.
///
/// This syscall consumes 500 cycles.
pub fn vm_version() -> Result<u64, SysError> {
    let ret = unsafe { syscall(0, 0, 0, 0, 0, 0, 0, SYS_VM_VERSION) };
    match ret {
        1 | 2 => Ok(ret),
        _ => Err(SysError::Unknown(ret)),
    }
}

/// *Current Cycles* returns current cycle consumption just before executing this syscall.
///  This syscall consumes 500 cycles.
pub fn current_cycles() -> u64 {
    unsafe { syscall(0, 0, 0, 0, 0, 0, 0, SYS_CURRENT_CYCLES) }
}

/// Exec runs an executable file from specified cell data in the context of an
/// already existing machine, replacing the previous executable. The used cycles
/// does not change, but the code, registers and memory of the vm are replaced
/// by those of the new program. It's cycles consumption consists of two parts:
///
/// - Fixed 500 cycles
/// - Initial Loading Cycles (<https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0014-vm-cycle-limits/0014-vm-cycle-limits.md>)
///
/// The arguments used here are:
///
///   * `index`: an index value denoting the index of entries to read.
///   * `source`: a flag denoting the source of cells or witnesses to locate, possible values include:
///       + 1: input cells.
///       + `0x0100000000000001`: input cells with the same running script as current script
///       + 2: output cells.
///       + `0x0100000000000002`: output cells with the same running script as current script
///       + 3: dep cells.
///   * `place`: A value of 0 or 1:
///       + 0: read from cell data
///       + 1: read from witness
///   * `bounds`: high 32 bits means `offset`, low 32 bits means `length`. if `length` equals to zero, it read to end instead of reading 0 bytes.
///   * `argc`: argc contains the number of arguments passed to the program
///   * `argv`: argv is a one-dimensional array of strings
pub fn exec(
    index: usize,
    source: Source,
    place: usize,
    bounds: usize,
    // argc: i32,
    argv: &[&CStr],
) -> u64 {
    // https://www.gnu.org/software/libc/manual/html_node/Program-Arguments.html
    let argc = argv.len();
    let mut argv_ptr = alloc::vec![core::ptr::null(); argc + 1];
    for (idx, cstr) in argv.into_iter().enumerate() {
        argv_ptr[idx] = cstr.as_ptr();
    }
    unsafe {
        syscall(
            index as u64,
            source as u64,
            place as u64,
            bounds as u64,
            argc as u64,
            argv_ptr.as_ptr() as u64,
            0,
            SYS_EXEC,
        )
    }
}

#[cfg(feature = "ckb2023")]
#[repr(C)]
pub struct SpawnArgs {
    pub memory_limit: u64,
    pub exit_code: *mut i8,
    pub content: *mut u8,
    /// Before calling spawn, content_length should be the length of content;
    /// After calling spawn, content_length will be the real size of the returned data.
    pub content_length: *mut u64,
}

/// The Spawn and the latter two syscalls: Get Memory Limit and Set Content
/// together, implement a way to call another CKB Script in a CKB Script.
/// Note: available after ckb2023.
///
/// Returns success or a syscall error.
#[cfg(feature = "ckb2023")]
pub fn spawn(index: usize, source: Source, bounds: usize, argv: &[&CStr], spgs: &SpawnArgs) -> u64 {
    let argc = argv.len();
    let mut argv_ptr = alloc::vec![core::ptr::null(); argc + 1];
    for (idx, cstr) in argv.into_iter().enumerate() {
        argv_ptr[idx] = cstr.as_ptr();
    }
    unsafe {
        syscall(
            index as u64,
            source as u64,
            bounds as u64,
            argc as u64,
            argv_ptr.as_ptr() as u64,
            spgs as *const SpawnArgs as u64,
            0,
            SYS_SPAWN,
        )
    }
}

/// Get memory limit.
/// Note: available after ckb2023.
///
/// Returns a number between 1 and 8, representing 0.5 to 4M of memory.
#[cfg(feature = "ckb2023")]
pub fn get_memory_limit() -> u64 {
    unsafe { syscall(0, 0, 0, 0, 0, 0, 0, SYS_GET_MEMORY_LIMIT) }
}

/// Set content.
/// Note: available after ckb2023.
///
/// Return the actual written data length or a syscall error.
#[cfg(feature = "ckb2023")]
pub fn set_content(buf: &[u8]) -> Result<u64, SysError> {
    let mut len = buf.len() as u64;
    let len_ptr: *mut u64 = &mut len;
    unsafe {
        syscall(
            buf.as_ptr() as u64,
            len_ptr as u64,
            0,
            0,
            0,
            0,
            0,
            SYS_SET_CONTENT,
        )
    };
    Ok(len)
}