darkfi/runtime/import/
util.rs

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
/* This file is part of DarkFi (https://dark.fi)
 *
 * Copyright (C) 2020-2024 Dyne.org foundation
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

use std::io::Cursor;

use darkfi_sdk::wasm;
use darkfi_serial::Decodable;
use log::{debug, error};
use wasmer::{FunctionEnvMut, WasmPtr};

use super::acl::acl_allow;
use crate::runtime::vm_runtime::{ContractSection, Env};

/// Host function for logging strings.
pub(crate) fn drk_log(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) {
    let (env, mut store) = ctx.data_and_store_mut();

    // Subtract used gas. Here we count the length of the string.
    env.subtract_gas(&mut store, len as u64);

    let memory_view = env.memory_view(&store);
    match ptr.read_utf8_string(&memory_view, len) {
        Ok(msg) => {
            let mut logs = env.logs.borrow_mut();
            logs.push(msg);
            std::mem::drop(logs);
        }
        Err(_) => {
            error!(
                target: "runtime::util::drk_log",
                "[WASM] [{}] drk_log(): Failed to read UTF-8 string from VM memory",
                env.contract_id,
            );
        }
    }
}

/// Writes data to the `contract_return_data` field of [`Env`].
/// The data will be read from `ptr` at a memory offset specified by `len`.
///
/// Returns `SUCCESS` on success, otherwise returns an error code corresponding
/// to a [`ContractError`].
///
/// Permissions: metadata, exec
pub(crate) fn set_return_data(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i64 {
    let (env, mut store) = ctx.data_and_store_mut();
    let cid = &env.contract_id;

    // Enforce function ACL
    if let Err(e) = acl_allow(env, &[ContractSection::Metadata, ContractSection::Exec]) {
        error!(
            target: "runtime::util::set_return_data",
            "[WASM] [{}] set_return_data(): Called in unauthorized section: {}", cid, e,
        );
        return darkfi_sdk::error::CALLER_ACCESS_DENIED
    }

    // Subtract used gas. Here we count the length read from the memory slice.
    env.subtract_gas(&mut store, len as u64);

    let memory_view = env.memory_view(&store);
    let Ok(slice) = ptr.slice(&memory_view, len) else { return darkfi_sdk::error::INTERNAL_ERROR };
    let Ok(return_data) = slice.read_to_vec() else { return darkfi_sdk::error::INTERNAL_ERROR };

    // This function should only ever be called once on the runtime.
    if env.contract_return_data.take().is_some() {
        return darkfi_sdk::error::SET_RETVAL_ERROR
    }
    env.contract_return_data.set(Some(return_data));

    wasm::entrypoint::SUCCESS
}

/// Retrieve an object from the object store specified by the index `idx`.
/// The object's data is written to `ptr`.
///
/// Returns `SUCCESS` on success and an error code otherwise.
///
/// Permissions: deploy, metadata, exec
pub(crate) fn get_object_bytes(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, idx: u32) -> i64 {
    // Get the slice, where we will read the size of the buffer
    let (env, mut store) = ctx.data_and_store_mut();
    let cid = env.contract_id;

    // Enforce function ACL
    if let Err(e) =
        acl_allow(env, &[ContractSection::Deploy, ContractSection::Metadata, ContractSection::Exec])
    {
        error!(
            target: "runtime::util::get_object_bytes()",
            "[WASM] [{}] get_object_bytes(): Called in unauthorized section: {}", cid, e,
        );
        return darkfi_sdk::error::CALLER_ACCESS_DENIED
    }

    // Get the object from env
    let objects = env.objects.borrow();
    if idx as usize >= objects.len() {
        error!(
            target: "runtime::util::get_object_bytes",
            "[WASM] [{}] get_object_bytes(): Tried to access object out of bounds", cid,
        );
        return darkfi_sdk::error::DATA_TOO_LARGE
    }
    let obj = objects[idx as usize].clone();
    drop(objects);

    if obj.len() > u32::MAX as usize {
        return darkfi_sdk::error::DATA_TOO_LARGE
    }

    // Subtract used gas. Here we count the bytes written to the memory slice
    env.subtract_gas(&mut store, obj.len() as u64);

    // Read N bytes from the object and write onto the ptr.
    let memory_view = env.memory_view(&store);
    let Ok(slice) = ptr.slice(&memory_view, obj.len() as u32) else {
        error!(
            target: "runtime::util::get_object_bytes",
            "[WASM] [{}] get_object_bytes(): Failed to make slice from ptr", cid,
        );
        return darkfi_sdk::error::INTERNAL_ERROR
    };

    // Put the result in the VM
    if let Err(e) = slice.write_slice(&obj) {
        error!(
            target: "runtime::util::get_object_bytes",
            "[WASM] [{}] get_object_bytes(): Failed to write to memory slice: {}", cid, e,
        );
        return darkfi_sdk::error::INTERNAL_ERROR
    };

    wasm::entrypoint::SUCCESS
}

/// Returns the size (number of bytes) of an object in the object store
/// specified by index `idx`.
///
/// Permissions: deploy, metadata, exec
pub(crate) fn get_object_size(mut ctx: FunctionEnvMut<Env>, idx: u32) -> i64 {
    // Get the slice, where we will read the size of the buffer
    let (env, mut store) = ctx.data_and_store_mut();
    let cid = env.contract_id;

    // Enforce function ACL
    if let Err(e) =
        acl_allow(env, &[ContractSection::Deploy, ContractSection::Metadata, ContractSection::Exec])
    {
        error!(
            target: "runtime::util::get_object_size()",
            "[WASM] [{}] get_object_size(): Called in unauthorized section: {}", cid, e,
        );
        return darkfi_sdk::error::CALLER_ACCESS_DENIED
    }

    // Get the object from env
    let objects = env.objects.borrow();
    if idx as usize >= objects.len() {
        error!(
            target: "runtime::util::get_object_size",
            "[WASM] [{}] get_object_size(): Tried to access object out of bounds", cid,
        );
        return darkfi_sdk::error::DATA_TOO_LARGE
    }

    let obj = &objects[idx as usize];
    let obj_len = obj.len();
    drop(objects);

    if obj_len > u32::MAX as usize {
        return darkfi_sdk::error::DATA_TOO_LARGE
    }

    // Subtract used gas. Here we count the size of the object.
    // TODO: This could probably be fixed-cost
    env.subtract_gas(&mut store, obj_len as u64);

    obj_len as i64
}

/// Will return current runtime configured verifying block height number
///
/// Permissions: deploy, metadata, exec
pub(crate) fn get_verifying_block_height(mut ctx: FunctionEnvMut<Env>) -> i64 {
    let (env, mut store) = ctx.data_and_store_mut();
    let cid = env.contract_id;

    if let Err(e) =
        acl_allow(env, &[ContractSection::Deploy, ContractSection::Metadata, ContractSection::Exec])
    {
        error!(
            target: "runtime::util::get_verifying_block_height",
            "[WASM] [{}] get_verifying_block_height(): Called in unauthorized section: {}", cid, e,
        );
        return darkfi_sdk::error::CALLER_ACCESS_DENIED
    }

    // Subtract used gas. Here we count the size of the object.
    // u32 is 4 bytes.
    env.subtract_gas(&mut store, 4);

    env.verifying_block_height as i64
}

/// Will return currently configured block time target, in seconds
///
/// Permissions: deploy, metadata, exec
pub(crate) fn get_block_target(mut ctx: FunctionEnvMut<Env>) -> i64 {
    let (env, mut store) = ctx.data_and_store_mut();
    let cid = env.contract_id;

    if let Err(e) =
        acl_allow(env, &[ContractSection::Deploy, ContractSection::Metadata, ContractSection::Exec])
    {
        error!(
            target: "runtime::util::get_block_target",
            "[WASM] [{}] get_block_target(): Called in unauthorized section: {}", cid, e,
        );
        return darkfi_sdk::error::CALLER_ACCESS_DENIED
    }

    // Subtract used gas. Here we count the size of the object.
    // u32 is 4 bytes.
    env.subtract_gas(&mut store, 4);

    env.block_target as i64
}

/// Will return current runtime configured transaction hash
///
/// Permissions: deploy, metadata, exec
pub(crate) fn get_tx_hash(mut ctx: FunctionEnvMut<Env>) -> i64 {
    let (env, mut store) = ctx.data_and_store_mut();
    let cid = env.contract_id;

    if let Err(e) =
        acl_allow(env, &[ContractSection::Deploy, ContractSection::Metadata, ContractSection::Exec])
    {
        error!(
            target: "runtime::util::get_tx_hash",
            "[WASM] [{}] get_tx_hash(): Called in unauthorized section: {}", cid, e,
        );
        return darkfi_sdk::error::CALLER_ACCESS_DENIED
    }

    // Subtract used gas. Here we count the size of the object.
    env.subtract_gas(&mut store, 32);

    // Return the length of the objects Vector.
    // This is the location of the data that was retrieved and pushed
    let mut objects = env.objects.borrow_mut();
    objects.push(env.tx_hash.inner().to_vec());
    (objects.len() - 1) as i64
}

/// Will return current runtime configured verifying block height number
///
/// Permissions: deploy, metadata, exec
pub(crate) fn get_call_index(mut ctx: FunctionEnvMut<Env>) -> i64 {
    let (env, mut store) = ctx.data_and_store_mut();
    let cid = env.contract_id;

    if let Err(e) =
        acl_allow(env, &[ContractSection::Deploy, ContractSection::Metadata, ContractSection::Exec])
    {
        error!(
            target: "runtime::util::get_call_index",
            "[WASM] [{}] get_call_index(): Called in unauthorized section: {}", cid, e,
        );
        return darkfi_sdk::error::CALLER_ACCESS_DENIED
    }

    // Subtract used gas. Here we count the size of the object.
    // u8 is 1 byte.
    env.subtract_gas(&mut store, 1);

    env.call_idx as i64
}

/// Will return current blockchain timestamp,
/// defined as the last block's timestamp.
///
/// Permissions: deploy, metadata, exec
pub(crate) fn get_blockchain_time(mut ctx: FunctionEnvMut<Env>) -> i64 {
    let (env, mut store) = ctx.data_and_store_mut();
    let cid = &env.contract_id;

    if let Err(e) =
        acl_allow(env, &[ContractSection::Deploy, ContractSection::Metadata, ContractSection::Exec])
    {
        error!(
            target: "runtime::util::get_blockchain_time",
            "[WASM] [{}] get_blockchain_time(): Called in unauthorized section: {}", cid, e,
        );
        return darkfi_sdk::error::CALLER_ACCESS_DENIED
    }

    // Grab current last block
    let timestamp = match env.blockchain.lock().unwrap().last_block_timestamp() {
        Ok(b) => b,
        Err(e) => {
            error!(
                target: "runtime::util::get_blockchain_time",
                "[WASM] [{}] get_blockchain_time(): Internal error getting from blocks tree: {}", cid, e,
            );
            return darkfi_sdk::error::DB_GET_FAILED
        }
    };

    // Subtract used gas. Here we count the size of the object.
    // u64 is 8 bytes.
    env.subtract_gas(&mut store, 8);

    // Create the return object
    let mut ret = Vec::with_capacity(8);
    ret.extend_from_slice(&timestamp.inner().to_be_bytes());

    // Copy Vec<u8> to the VM
    let mut objects = env.objects.borrow_mut();
    objects.push(ret.to_vec());
    if objects.len() > u32::MAX as usize {
        return darkfi_sdk::error::DATA_TOO_LARGE
    }

    (objects.len() - 1) as i64
}

/// Grabs last block from the `Blockchain` overlay and then copies its
/// height to the VM's object store.
///
/// On success, returns the index of the new object in the object store.
/// Otherwise, returns an error code.
///
/// Permissions: deploy, metadata, exec
pub(crate) fn get_last_block_height(mut ctx: FunctionEnvMut<Env>) -> i64 {
    let (env, mut store) = ctx.data_and_store_mut();
    let cid = &env.contract_id;

    // Enforce function ACL
    if let Err(e) =
        acl_allow(env, &[ContractSection::Deploy, ContractSection::Metadata, ContractSection::Exec])
    {
        error!(
            target: "runtime::util::get_last_block_height",
            "[WASM] [{}] get_last_block_height(): Called in unauthorized section: {}", cid, e,
        );
        return darkfi_sdk::error::CALLER_ACCESS_DENIED
    }

    // Grab current last block height
    let height = match env.blockchain.lock().unwrap().last_block_height() {
        Ok(b) => b,
        Err(e) => {
            error!(
                target: "runtime::util::get_last_block_height",
                "[WASM] [{}] get_last_block_height(): Internal error getting from blocks tree: {}", cid, e,
            );
            return darkfi_sdk::error::DB_GET_FAILED
        }
    };

    // Subtract used gas. Here we count the size of the object.
    // u64 is 8 bytes.
    env.subtract_gas(&mut store, 8);

    // Create the return object
    let mut ret = Vec::with_capacity(8);
    ret.extend_from_slice(&darkfi_serial::serialize(&height));

    // Copy Vec<u8> to the VM
    let mut objects = env.objects.borrow_mut();
    objects.push(ret.to_vec());
    if objects.len() > u32::MAX as usize {
        return darkfi_sdk::error::DATA_TOO_LARGE
    }

    (objects.len() - 1) as i64
}

/// Reads a transaction by hash from the transactions store.
///
/// This function can be called from the Exec or Metadata [`ContractSection`].
///
/// On success, returns the length of the transaction bytes vector in the environment.
/// Otherwise, returns an error code.
///
/// Permissions: deploy, metadata, exec
pub(crate) fn get_tx(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>) -> i64 {
    let (env, mut store) = ctx.data_and_store_mut();
    let cid = env.contract_id;

    if let Err(e) =
        acl_allow(env, &[ContractSection::Deploy, ContractSection::Metadata, ContractSection::Exec])
    {
        error!(
            target: "runtime::util::get_tx",
            "[WASM] [{}] get_tx(): Called in unauthorized section: {}", cid, e,
        );
        return darkfi_sdk::error::CALLER_ACCESS_DENIED
    }

    // Subtract used gas. Here we count the length of the looked-up hash.
    env.subtract_gas(&mut store, blake3::OUT_LEN as u64);

    // Ensure that it is possible to read memory
    let memory_view = env.memory_view(&store);
    let Ok(mem_slice) = ptr.slice(&memory_view, blake3::OUT_LEN as u32) else {
        error!(
            target: "runtime::util::get_tx",
            "[WASM] [{}] get_tx(): Failed to make slice from ptr", cid,
        );
        return darkfi_sdk::error::DB_GET_FAILED
    };

    let mut buf = vec![0_u8; blake3::OUT_LEN];
    if let Err(e) = mem_slice.read_slice(&mut buf) {
        error!(
            target: "runtime::util::get_tx",
            "[WASM] [{}] get_tx(): Failed to read from memory slice: {}", cid, e,
        );
        return darkfi_sdk::error::DB_GET_FAILED
    };

    let mut buf_reader = Cursor::new(buf);

    // Decode hash bytes for transaction that we wish to retrieve
    let hash: [u8; blake3::OUT_LEN] = match Decodable::decode(&mut buf_reader) {
        Ok(v) => v,
        Err(e) => {
            error!(
                target: "runtime::util::get_tx",
                "[WASM] [{}] get_tx(): Failed to decode hash from vec: {}", cid, e,
            );
            return darkfi_sdk::error::DB_GET_FAILED
        }
    };

    // Make sure there are no trailing bytes in the buffer. This means we've used all data that was
    // supplied.
    if buf_reader.position() != blake3::OUT_LEN as u64 {
        error!(
            target: "runtime::util::get_tx",
            "[WASM] [{}] get_tx(): Trailing bytes in argument stream", cid,
        );
        return darkfi_sdk::error::DB_GET_FAILED
    }

    // Retrieve transaction using the `hash`
    let ret = match env.blockchain.lock().unwrap().transactions.get_raw(&hash) {
        Ok(v) => v,
        Err(e) => {
            error!(
                target: "runtime::util::get_tx",
                "[WASM] [{}] get_tx(): Internal error getting from tree: {}", cid, e,
            );
            return darkfi_sdk::error::DB_GET_FAILED
        }
    };

    // Return special error if the data is empty
    let Some(return_data) = ret else {
        debug!(
            target: "runtime::util::get_tx",
            "[WASM] [{}] get_tx(): Return data is empty", cid,
        );
        return darkfi_sdk::error::DB_GET_EMPTY
    };

    if return_data.len() > u32::MAX as usize {
        return darkfi_sdk::error::DATA_TOO_LARGE
    }

    // Subtract used gas. Here we count the length of the data read from db.
    env.subtract_gas(&mut store, return_data.len() as u64);

    // Copy the data (Vec<u8>) to the VM by pushing it to the objects Vector.
    let mut objects = env.objects.borrow_mut();
    if objects.len() == u32::MAX as usize {
        return darkfi_sdk::error::DATA_TOO_LARGE
    }

    // Return the length of the objects Vector.
    // This is the location of the data that was retrieved and pushed
    objects.push(return_data.to_vec());
    (objects.len() - 1) as i64
}

/// Reads a transaction location by hash from the transactions store.
///
/// This function can be called from the Exec or Metadata [`ContractSection`].
///
/// On success, returns the length of the transaction location bytes vector in
/// the environment. Otherwise, returns an error code.
///
/// Permissions: deploy, metadata, exec
pub(crate) fn get_tx_location(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>) -> i64 {
    let (env, mut store) = ctx.data_and_store_mut();
    let cid = env.contract_id;

    if let Err(e) =
        acl_allow(env, &[ContractSection::Deploy, ContractSection::Metadata, ContractSection::Exec])
    {
        error!(
            target: "runtime::util::get_tx_location",
            "[WASM] [{}] get_tx_location(): Called in unauthorized section: {}", cid, e,
        );
        return darkfi_sdk::error::CALLER_ACCESS_DENIED
    }

    // Subtract used gas. Here we count the length of the looked-up hash.
    env.subtract_gas(&mut store, blake3::OUT_LEN as u64);

    // Ensure that it is possible to read memory
    let memory_view = env.memory_view(&store);
    let Ok(mem_slice) = ptr.slice(&memory_view, blake3::OUT_LEN as u32) else {
        error!(
            target: "runtime::util::get_tx_location",
            "[WASM] [{}] get_tx_location(): Failed to make slice from ptr", cid,
        );
        return darkfi_sdk::error::DB_GET_FAILED
    };

    let mut buf = vec![0_u8; blake3::OUT_LEN];
    if let Err(e) = mem_slice.read_slice(&mut buf) {
        error!(
            target: "runtime::util::get_tx_location",
            "[WASM] [{}] get_tx_location(): Failed to read from memory slice: {}", cid, e,
        );
        return darkfi_sdk::error::DB_GET_FAILED
    };

    let mut buf_reader = Cursor::new(buf);

    // Decode hash bytes for transaction that we wish to retrieve
    let hash: [u8; blake3::OUT_LEN] = match Decodable::decode(&mut buf_reader) {
        Ok(v) => v,
        Err(e) => {
            error!(
                target: "runtime::util::get_tx_location",
                "[WASM] [{}] get_tx_location(): Failed to decode hash from vec: {}", cid, e,
            );
            return darkfi_sdk::error::DB_GET_FAILED
        }
    };

    // Make sure there are no trailing bytes in the buffer. This means we've used all data that was
    // supplied.
    if buf_reader.position() != blake3::OUT_LEN as u64 {
        error!(
            target: "runtime::util::get_tx_location",
            "[WASM] [{}] get_tx_location(): Trailing bytes in argument stream", cid,
        );
        return darkfi_sdk::error::DB_GET_FAILED
    }

    // Retrieve transaction using the `hash`
    let ret = match env.blockchain.lock().unwrap().transactions.get_location_raw(&hash) {
        Ok(v) => v,
        Err(e) => {
            error!(
                target: "runtime::util::get_tx_location",
                "[WASM] [{}] get_tx_location(): Internal error getting from tree: {}", cid, e,
            );
            return darkfi_sdk::error::DB_GET_FAILED
        }
    };

    // Return special error if the data is empty
    let Some(return_data) = ret else {
        debug!(
            target: "runtime::util::get_tx_location",
            "[WASM] [{}] get_tx_location(): Return data is empty", cid,
        );
        return darkfi_sdk::error::DB_GET_EMPTY
    };

    if return_data.len() > u32::MAX as usize {
        return darkfi_sdk::error::DATA_TOO_LARGE
    }

    // Subtract used gas. Here we count the length of the data read from db.
    env.subtract_gas(&mut store, return_data.len() as u64);

    // Copy the data (Vec<u8>) to the VM by pushing it to the objects Vector.
    let mut objects = env.objects.borrow_mut();
    if objects.len() == u32::MAX as usize {
        return darkfi_sdk::error::DATA_TOO_LARGE
    }

    // Return the length of the objects Vector.
    // This is the location of the data that was retrieved and pushed
    objects.push(return_data.to_vec());
    (objects.len() - 1) as i64
}