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
mod alloc_util;
pub mod pointers;

use self::alloc_util::*;
use self::pointers::*;
use crate::bytesrepr::{deserialize, FromBytes, ToBytes};
use crate::ext_ffi;
use crate::key::{Key, UREF_SIZE};
use crate::value::{Contract, Value};
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;
use core::convert::{TryFrom, TryInto};

/// Read value under the key in the global state
pub fn read<T>(u_ptr: UPointer<T>) -> T
where
    T: TryFrom<Value>,
{
    let key: Key = u_ptr.into();
    let value = read_untyped(&key);
    value
        .try_into()
        .map_err(|_| "T could not be derived from Value")
        .unwrap()
}

fn read_untyped(key: &Key) -> Value {
    // Note: _bytes is necessary to keep the Vec<u8> in scope. If _bytes is
    //      dropped then key_ptr becomes invalid.

    let (key_ptr, key_size, _bytes) = to_ptr(key);
    let value_size = unsafe { ext_ffi::read_value(key_ptr, key_size) };
    let value_ptr = alloc_bytes(value_size);
    let value_bytes = unsafe {
        ext_ffi::get_read(value_ptr);
        Vec::from_raw_parts(value_ptr, value_size, value_size)
    };
    deserialize(&value_bytes).unwrap()
}

/// Write the value under the key in the global state
pub fn write<T>(u_ptr: UPointer<T>, t: T)
where
    Value: From<T>,
{
    let key = u_ptr.into();
    let value = t.into();
    write_untyped(&key, &value)
}

fn write_untyped(key: &Key, value: &Value) {
    let (key_ptr, key_size, _bytes) = to_ptr(key);
    let (value_ptr, value_size, _bytes2) = to_ptr(value);
    unsafe {
        ext_ffi::write(key_ptr, key_size, value_ptr, value_size);
    }
}

/// Add the given value to the one currently under the key in the global state
pub fn add<T>(u_ptr: UPointer<T>, t: T)
where
    Value: From<T>,
{
    let key = u_ptr.into();
    let value = t.into();
    add_untyped(&key, &value)
}

fn add_untyped(key: &Key, value: &Value) {
    let (key_ptr, key_size, _bytes) = to_ptr(key);
    let (value_ptr, value_size, _bytes2) = to_ptr(value);
    unsafe {
        // Could panic if the value under the key cannot be added to
        // the given value in memory
        ext_ffi::add(key_ptr, key_size, value_ptr, value_size);
    }
}

/// Returns a new unforgable pointer, where value is initialized to `init`
pub fn new_uref<T>(init: T) -> UPointer<T>
where
    Value: From<T>,
{
    let key_ptr = alloc_bytes(UREF_SIZE);
    let bytes = unsafe {
        ext_ffi::new_uref(key_ptr);
        Vec::from_raw_parts(key_ptr, UREF_SIZE, UREF_SIZE)
    };
    let key: Key = deserialize(&bytes).unwrap();
    if let Key::URef(id) = key {
        let value: Value = init.into();
        write_untyped(&key, &value);
        UPointer::new(id)
    } else {
        panic!("URef FFI did not return a URef!");
    }
}

fn fn_bytes_by_name(name: &str) -> Vec<u8> {
    let (name_ptr, name_size, _bytes) = str_ref_to_ptr(name);
    let fn_size = unsafe { ext_ffi::serialize_function(name_ptr, name_size) };
    let fn_ptr = alloc_bytes(fn_size);
    unsafe {
        ext_ffi::get_function(fn_ptr);
        Vec::from_raw_parts(fn_ptr, fn_size, fn_size)
    }
}

/// Returns the serialized bytes of a function which is exported in the current module.
/// Note that the function is wrapped up in a new module and re-exported under the name
/// "call". `fn_bytes_by_name` is meant to be used when storing a contract on-chain at
/// an unforgable reference.
pub fn fn_by_name(name: &str, known_urefs: BTreeMap<String, Key>) -> Contract {
    let bytes = fn_bytes_by_name(name);
    Contract::new(bytes, known_urefs)
}

/// Gets the serialized bytes of an exported function (see `fn_by_name`), then
/// computes gets the address from the host to produce a key where the contract is then
/// stored in the global state. This key is returned.
pub fn store_function(name: &str, known_urefs: BTreeMap<String, Key>) -> ContractPointer {
    let bytes = fn_bytes_by_name(name);
    let fn_hash = {
        let mut tmp = [0u8; 32];
        unsafe {
            ext_ffi::function_address(tmp.as_mut_ptr());
        }
        tmp
    };
    let key = Key::Hash(fn_hash);
    let value = Value::Contract(Contract::new(bytes, known_urefs));
    write_untyped(&key, &value);
    ContractPointer::Hash(fn_hash)
}

/// Return the i-th argument passed to the host for the current module
/// invokation. Note that this is only relevent to contracts stored on-chain
/// since a contract deployed directly is not invoked with any arguments.
pub fn get_arg<T: FromBytes>(i: u32) -> T {
    let arg_size = unsafe { ext_ffi::load_arg(i) };
    let dest_ptr = alloc_bytes(arg_size);
    let arg_bytes = unsafe {
        ext_ffi::get_arg(dest_ptr);
        Vec::from_raw_parts(dest_ptr, arg_size, arg_size)
    };
    // TODO: better error handling (i.e. pass the `Result` on)
    deserialize(&arg_bytes).unwrap()
}

/// Return the unforgable reference known by the current module under the given name.
/// This either comes from the known_urefs of the account or contract,
/// depending on whether the current module is a sub-call or not.
pub fn get_uref(name: &str) -> Key {
    let (name_ptr, name_size, _bytes) = str_ref_to_ptr(name);
    let dest_ptr = alloc_bytes(UREF_SIZE);
    let uref_bytes = unsafe {
        ext_ffi::get_uref(name_ptr, name_size, dest_ptr);
        Vec::from_raw_parts(dest_ptr, UREF_SIZE, UREF_SIZE)
    };
    // TODO: better error handling (i.e. pass the `Result` on)
    deserialize(&uref_bytes).unwrap()
}

/// Check if the given name corresponds to a known unforgable reference
pub fn has_uref(name: &str) -> bool {
    let (name_ptr, name_size, _bytes) = str_ref_to_ptr(name);
    let result = unsafe { ext_ffi::has_uref_name(name_ptr, name_size) };
    result == 0
}

/// Add the given key to the known_urefs map under the given name
pub fn add_uref(name: &str, key: &Key) {
    let (name_ptr, name_size, _bytes) = str_ref_to_ptr(name);
    let (key_ptr, key_size, _bytes2) = to_ptr(key);
    unsafe { ext_ffi::add_uref(name_ptr, name_size, key_ptr, key_size) };
}

/// Return `t` to the host, terminating the currently running module.
/// Note this function is only relevent to contracts stored on chain which
/// return a value to their caller. The return value of a directly deployed
/// contract is never looked at.
#[allow(clippy::ptr_arg)]
pub fn ret<T: ToBytes>(t: &T, extra_urefs: &Vec<Key>) -> ! {
    let (ptr, size, _bytes) = to_ptr(t);
    let (urefs_ptr, urefs_size, _bytes2) = to_ptr(extra_urefs);
    unsafe {
        ext_ffi::ret(ptr, size, urefs_ptr, urefs_size);
    }
}

/// Call the given contract, passing the given (serialized) arguments to
/// the host in order to have them available to the called contract during its
/// execution. The value returned from the contract call (see `ret` above) is
/// returned from this function.
#[allow(clippy::ptr_arg)]
pub fn call_contract<T: FromBytes>(
    c_ptr: ContractPointer,
    args: &Vec<Vec<u8>>,
    extra_urefs: &Vec<Key>,
) -> T {
    let contract_key: Key = c_ptr.into();
    let (key_ptr, key_size, _bytes1) = to_ptr(&contract_key);
    let (args_ptr, args_size, _bytes2) = to_ptr(args);
    let (urefs_ptr, urefs_size, _bytes3) = to_ptr(extra_urefs);
    let res_size = unsafe {
        ext_ffi::call_contract(
            key_ptr, key_size, args_ptr, args_size, urefs_ptr, urefs_size,
        )
    };
    let res_ptr = alloc_bytes(res_size);
    let res_bytes = unsafe {
        ext_ffi::get_call_result(res_ptr);
        Vec::from_raw_parts(res_ptr, res_size, res_size)
    };
    deserialize(&res_bytes).unwrap()
}