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
//! Functions for interacting with the current runtime.

use alloc::{collections::BTreeSet, vec, vec::Vec};
use core::mem::MaybeUninit;

use casper_types::{
    account::AccountHash,
    api_error,
    bytesrepr::{self, FromBytes},
    contracts::{ContractVersion, NamedKeys},
    system::CallStackElement,
    ApiError, BlockTime, CLTyped, CLValue, ContractHash, ContractPackageHash, Key, Phase,
    RuntimeArgs, URef, BLAKE2B_DIGEST_LENGTH, BLOCKTIME_SERIALIZED_LENGTH, PHASE_SERIALIZED_LENGTH,
};

use crate::{contract_api, ext_ffi, unwrap_or_revert::UnwrapOrRevert};

/// Number of random bytes returned from the `random_bytes()` function.
const RANDOM_BYTES_COUNT: usize = 32;

/// Returns the given [`CLValue`] to the host, terminating the currently running module.
///
/// Note this function is only relevant to contracts stored on chain which are invoked via
/// [`call_contract`] and can thus return a value to their caller.  The return value of a directly
/// deployed contract is never used.
pub fn ret(value: CLValue) -> ! {
    let (ptr, size, _bytes) = contract_api::to_ptr(value);
    unsafe {
        ext_ffi::casper_ret(ptr, size);
    }
}

/// Stops execution of a contract and reverts execution effects with a given [`ApiError`].
///
/// The provided `ApiError` is returned in the form of a numeric exit code to the caller via the
/// deploy response.
pub fn revert<T: Into<ApiError>>(error: T) -> ! {
    unsafe {
        ext_ffi::casper_revert(error.into().into());
    }
}

/// Calls the given stored contract, passing the given arguments to it.
///
/// If the stored contract calls [`ret`], then that value is returned from `call_contract`.  If the
/// stored contract calls [`revert`], then execution stops and `call_contract` doesn't return.
/// Otherwise `call_contract` returns `()`.
pub fn call_contract<T: CLTyped + FromBytes>(
    contract_hash: ContractHash,
    entry_point_name: &str,
    runtime_args: RuntimeArgs,
) -> T {
    let (contract_hash_ptr, contract_hash_size, _bytes1) = contract_api::to_ptr(contract_hash);
    let (entry_point_name_ptr, entry_point_name_size, _bytes2) =
        contract_api::to_ptr(entry_point_name);
    let (runtime_args_ptr, runtime_args_size, _bytes2) = contract_api::to_ptr(runtime_args);

    let bytes_written = {
        let mut bytes_written = MaybeUninit::uninit();
        let ret = unsafe {
            ext_ffi::casper_call_contract(
                contract_hash_ptr,
                contract_hash_size,
                entry_point_name_ptr,
                entry_point_name_size,
                runtime_args_ptr,
                runtime_args_size,
                bytes_written.as_mut_ptr(),
            )
        };
        api_error::result_from(ret).unwrap_or_revert();
        unsafe { bytes_written.assume_init() }
    };
    deserialize_contract_result(bytes_written)
}

/// Invokes the specified `entry_point_name` of stored logic at a specific `contract_package_hash`
/// address, for the most current version of a contract package by default or a specific
/// `contract_version` if one is provided, and passing the provided `runtime_args` to it
///
/// If the stored contract calls [`ret`], then that value is returned from
/// `call_versioned_contract`.  If the stored contract calls [`revert`], then execution stops and
/// `call_versioned_contract` doesn't return. Otherwise `call_versioned_contract` returns `()`.
pub fn call_versioned_contract<T: CLTyped + FromBytes>(
    contract_package_hash: ContractPackageHash,
    contract_version: Option<ContractVersion>,
    entry_point_name: &str,
    runtime_args: RuntimeArgs,
) -> T {
    let (contract_package_hash_ptr, contract_package_hash_size, _bytes) =
        contract_api::to_ptr(contract_package_hash);
    let (contract_version_ptr, contract_version_size, _bytes) =
        contract_api::to_ptr(contract_version);
    let (entry_point_name_ptr, entry_point_name_size, _bytes) =
        contract_api::to_ptr(entry_point_name);
    let (runtime_args_ptr, runtime_args_size, _bytes) = contract_api::to_ptr(runtime_args);

    let bytes_written = {
        let mut bytes_written = MaybeUninit::uninit();
        let ret = unsafe {
            ext_ffi::casper_call_versioned_contract(
                contract_package_hash_ptr,
                contract_package_hash_size,
                contract_version_ptr,
                contract_version_size,
                entry_point_name_ptr,
                entry_point_name_size,
                runtime_args_ptr,
                runtime_args_size,
                bytes_written.as_mut_ptr(),
            )
        };
        api_error::result_from(ret).unwrap_or_revert();
        unsafe { bytes_written.assume_init() }
    };
    deserialize_contract_result(bytes_written)
}

fn deserialize_contract_result<T: CLTyped + FromBytes>(bytes_written: usize) -> T {
    let serialized_result = if bytes_written == 0 {
        // If no bytes were written, the host buffer hasn't been set and hence shouldn't be read.
        vec![]
    } else {
        // NOTE: this is a copy of the contents of `read_host_buffer()`.  Calling that directly from
        // here causes several contracts to fail with a Wasmi `Unreachable` error.
        let bytes_non_null_ptr = contract_api::alloc_bytes(bytes_written);
        let mut dest: Vec<u8> = unsafe {
            Vec::from_raw_parts(bytes_non_null_ptr.as_ptr(), bytes_written, bytes_written)
        };
        read_host_buffer_into(&mut dest).unwrap_or_revert();
        dest
    };

    bytesrepr::deserialize(serialized_result).unwrap_or_revert()
}

/// Returns size in bytes of a given named argument passed to the host for the current module
/// invocation.
///
/// This will return either Some with the size of argument if present, or None if given argument is
/// not passed.
fn get_named_arg_size(name: &str) -> Option<usize> {
    let mut arg_size: usize = 0;
    let ret = unsafe {
        ext_ffi::casper_get_named_arg_size(
            name.as_bytes().as_ptr(),
            name.len(),
            &mut arg_size as *mut usize,
        )
    };
    match api_error::result_from(ret) {
        Ok(_) => Some(arg_size),
        Err(ApiError::MissingArgument) => None,
        Err(e) => revert(e),
    }
}

/// Returns given named argument passed to the host for the current module invocation.
///
/// Note that this is only relevant to contracts stored on-chain since a contract deployed directly
/// is not invoked with any arguments.
pub fn get_named_arg<T: FromBytes>(name: &str) -> T {
    let arg_size = get_named_arg_size(name).unwrap_or_revert_with(ApiError::MissingArgument);
    let arg_bytes = if arg_size > 0 {
        let res = {
            let data_non_null_ptr = contract_api::alloc_bytes(arg_size);
            let ret = unsafe {
                ext_ffi::casper_get_named_arg(
                    name.as_bytes().as_ptr(),
                    name.len(),
                    data_non_null_ptr.as_ptr(),
                    arg_size,
                )
            };
            let data =
                unsafe { Vec::from_raw_parts(data_non_null_ptr.as_ptr(), arg_size, arg_size) };
            api_error::result_from(ret).map(|_| data)
        };
        // Assumed to be safe as `get_named_arg_size` checks the argument already
        res.unwrap_or_revert()
    } else {
        // Avoids allocation with 0 bytes and a call to get_named_arg
        Vec::new()
    };
    bytesrepr::deserialize(arg_bytes).unwrap_or_revert_with(ApiError::InvalidArgument)
}

/// Returns the caller of the current context, i.e. the [`AccountHash`] of the account which made
/// the deploy request.
pub fn get_caller() -> AccountHash {
    let output_size = {
        let mut output_size = MaybeUninit::uninit();
        let ret = unsafe { ext_ffi::casper_get_caller(output_size.as_mut_ptr()) };
        api_error::result_from(ret).unwrap_or_revert();
        unsafe { output_size.assume_init() }
    };
    let buf = read_host_buffer(output_size).unwrap_or_revert();
    bytesrepr::deserialize(buf).unwrap_or_revert()
}

/// Returns the current [`BlockTime`].
pub fn get_blocktime() -> BlockTime {
    let dest_non_null_ptr = contract_api::alloc_bytes(BLOCKTIME_SERIALIZED_LENGTH);
    let bytes = unsafe {
        ext_ffi::casper_get_blocktime(dest_non_null_ptr.as_ptr());
        Vec::from_raw_parts(
            dest_non_null_ptr.as_ptr(),
            BLOCKTIME_SERIALIZED_LENGTH,
            BLOCKTIME_SERIALIZED_LENGTH,
        )
    };
    bytesrepr::deserialize(bytes).unwrap_or_revert()
}

/// Returns the current [`Phase`].
pub fn get_phase() -> Phase {
    let dest_non_null_ptr = contract_api::alloc_bytes(PHASE_SERIALIZED_LENGTH);
    unsafe { ext_ffi::casper_get_phase(dest_non_null_ptr.as_ptr()) };
    let bytes = unsafe {
        Vec::from_raw_parts(
            dest_non_null_ptr.as_ptr(),
            PHASE_SERIALIZED_LENGTH,
            PHASE_SERIALIZED_LENGTH,
        )
    };
    bytesrepr::deserialize(bytes).unwrap_or_revert()
}

/// Returns the requested named [`Key`] from the current context.
///
/// The current context is either the caller's account or a stored contract depending on whether the
/// currently-executing module is a direct call or a sub-call respectively.
pub fn get_key(name: &str) -> Option<Key> {
    let (name_ptr, name_size, _bytes) = contract_api::to_ptr(name);
    let mut key_bytes = vec![0u8; Key::max_serialized_length()];
    let mut total_bytes: usize = 0;
    let ret = unsafe {
        ext_ffi::casper_get_key(
            name_ptr,
            name_size,
            key_bytes.as_mut_ptr(),
            key_bytes.len(),
            &mut total_bytes as *mut usize,
        )
    };
    match api_error::result_from(ret) {
        Ok(_) => {}
        Err(ApiError::MissingKey) => return None,
        Err(e) => revert(e),
    }
    key_bytes.truncate(total_bytes);
    let key: Key = bytesrepr::deserialize(key_bytes).unwrap_or_revert();
    Some(key)
}

/// Returns `true` if `name` exists in the current context's named keys.
///
/// The current context is either the caller's account or a stored contract depending on whether the
/// currently-executing module is a direct call or a sub-call respectively.
pub fn has_key(name: &str) -> bool {
    let (name_ptr, name_size, _bytes) = contract_api::to_ptr(name);
    let result = unsafe { ext_ffi::casper_has_key(name_ptr, name_size) };
    result == 0
}

/// Stores the given [`Key`] under `name` in the current context's named keys.
///
/// The current context is either the caller's account or a stored contract depending on whether the
/// currently-executing module is a direct call or a sub-call respectively.
pub fn put_key(name: &str, key: Key) {
    let (name_ptr, name_size, _bytes) = contract_api::to_ptr(name);
    let (key_ptr, key_size, _bytes2) = contract_api::to_ptr(key);
    unsafe { ext_ffi::casper_put_key(name_ptr, name_size, key_ptr, key_size) };
}

/// Removes the [`Key`] stored under `name` in the current context's named keys.
///
/// The current context is either the caller's account or a stored contract depending on whether the
/// currently-executing module is a direct call or a sub-call respectively.
pub fn remove_key(name: &str) {
    let (name_ptr, name_size, _bytes) = contract_api::to_ptr(name);
    unsafe { ext_ffi::casper_remove_key(name_ptr, name_size) }
}

/// Returns the set of [`AccountHash`] from the calling account's context `authorization_keys`.
pub fn list_authorization_keys() -> BTreeSet<AccountHash> {
    let (total_authorization_keys, result_size) = {
        let mut authorization_keys = MaybeUninit::uninit();
        let mut result_size = MaybeUninit::uninit();
        let ret = unsafe {
            ext_ffi::casper_load_authorization_keys(
                authorization_keys.as_mut_ptr(),
                result_size.as_mut_ptr(),
            )
        };
        api_error::result_from(ret).unwrap_or_revert();
        let total_authorization_keys = unsafe { authorization_keys.assume_init() };
        let result_size = unsafe { result_size.assume_init() };
        (total_authorization_keys, result_size)
    };

    if total_authorization_keys == 0 {
        return BTreeSet::new();
    }

    let bytes = read_host_buffer(result_size).unwrap_or_revert();
    bytesrepr::deserialize(bytes).unwrap_or_revert()
}

/// Returns the named keys of the current context.
///
/// The current context is either the caller's account or a stored contract depending on whether the
/// currently-executing module is a direct call or a sub-call respectively.
pub fn list_named_keys() -> NamedKeys {
    let (total_keys, result_size) = {
        let mut total_keys = MaybeUninit::uninit();
        let mut result_size = 0;
        let ret = unsafe {
            ext_ffi::casper_load_named_keys(total_keys.as_mut_ptr(), &mut result_size as *mut usize)
        };
        api_error::result_from(ret).unwrap_or_revert();
        let total_keys = unsafe { total_keys.assume_init() };
        (total_keys, result_size)
    };
    if total_keys == 0 {
        return NamedKeys::new();
    }
    let bytes = read_host_buffer(result_size).unwrap_or_revert();
    bytesrepr::deserialize(bytes).unwrap_or_revert()
}

/// Validates uref against named keys.
pub fn is_valid_uref(uref: URef) -> bool {
    let (uref_ptr, uref_size, _bytes) = contract_api::to_ptr(uref);
    let result = unsafe { ext_ffi::casper_is_valid_uref(uref_ptr, uref_size) };
    result != 0
}

/// Returns a 32-byte BLAKE2b digest
pub fn blake2b<T: AsRef<[u8]>>(input: T) -> [u8; BLAKE2B_DIGEST_LENGTH] {
    let mut ret = [0; BLAKE2B_DIGEST_LENGTH];
    let result = unsafe {
        ext_ffi::casper_blake2b(
            input.as_ref().as_ptr(),
            input.as_ref().len(),
            ret.as_mut_ptr(),
            BLAKE2B_DIGEST_LENGTH,
        )
    };
    api_error::result_from(result).unwrap_or_revert();
    ret
}

/// Returns 32 pseudo random bytes.
pub fn random_bytes() -> [u8; RANDOM_BYTES_COUNT] {
    let mut ret = [0; RANDOM_BYTES_COUNT];
    let result = unsafe { ext_ffi::casper_random_bytes(ret.as_mut_ptr(), RANDOM_BYTES_COUNT) };
    api_error::result_from(result).unwrap_or_revert();
    ret
}

fn read_host_buffer_into(dest: &mut [u8]) -> Result<usize, ApiError> {
    let mut bytes_written = MaybeUninit::uninit();
    let ret = unsafe {
        ext_ffi::casper_read_host_buffer(dest.as_mut_ptr(), dest.len(), bytes_written.as_mut_ptr())
    };
    // NOTE: When rewriting below expression as `result_from(ret).map(|_| unsafe { ... })`, and the
    // caller ignores the return value, execution of the contract becomes unstable and ultimately
    // leads to `Unreachable` error.
    api_error::result_from(ret)?;
    Ok(unsafe { bytes_written.assume_init() })
}

pub(crate) fn read_host_buffer(size: usize) -> Result<Vec<u8>, ApiError> {
    let mut dest: Vec<u8> = if size == 0 {
        Vec::new()
    } else {
        let bytes_non_null_ptr = contract_api::alloc_bytes(size);
        unsafe { Vec::from_raw_parts(bytes_non_null_ptr.as_ptr(), size, size) }
    };
    read_host_buffer_into(&mut dest)?;
    Ok(dest)
}

/// Returns the call stack.
pub fn get_call_stack() -> Vec<CallStackElement> {
    let (call_stack_len, result_size) = {
        let mut call_stack_len: usize = 0;
        let mut result_size: usize = 0;
        let ret = unsafe {
            ext_ffi::casper_load_call_stack(
                &mut call_stack_len as *mut usize,
                &mut result_size as *mut usize,
            )
        };
        api_error::result_from(ret).unwrap_or_revert();
        (call_stack_len, result_size)
    };
    if call_stack_len == 0 {
        return Vec::new();
    }
    let bytes = read_host_buffer(result_size).unwrap_or_revert();
    bytesrepr::deserialize(bytes).unwrap_or_revert()
}

#[cfg(feature = "test-support")]
/// Prints a debug message
pub fn print(text: &str) {
    let (text_ptr, text_size, _bytes) = contract_api::to_ptr(text);
    unsafe { ext_ffi::casper_print(text_ptr, text_size) }
}