-
Notifications
You must be signed in to change notification settings - Fork 59
/
mod.rs
836 lines (739 loc) · 27.5 KB
/
mod.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
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
// Copyright (c) RoochNetwork
// Copyright (c) The Diem Core Contributors
// Copyright (c) The Move Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::natives::helpers;
/// A native Table implementation for save any type of value.
/// Refactor from https://github.com/rooch-network/move/blob/c7d8c2b0cdd06dbd90e0ab306932356620b5648a/language/extensions/move-table-extension/src/lib.rs#L4
use better_any::{Tid, TidAble};
use move_binary_format::errors::{PartialVMError, PartialVMResult};
use move_core_types::{
account_address::AccountAddress,
effects::Op,
gas_algebra::{InternalGas, InternalGasPerByte, NumBytes},
language_storage::TypeTag,
value::MoveTypeLayout,
vm_status::StatusCode,
};
use move_vm_runtime::{
native_functions,
native_functions::{NativeContext, NativeFunction, NativeFunctionTable},
};
use move_vm_types::{
loaded_data::runtime_types::Type,
natives::function::NativeResult,
pop_arg,
values::{GlobalValue, Struct, Value},
};
use moveos_types::{
object::{ObjectID, TableInfo},
state::TableTypeInfo,
state_resolver::StateResolver,
};
use parking_lot::RwLock;
use smallvec::smallvec;
use std::{
collections::{btree_map::Entry, BTreeMap, BTreeSet, VecDeque},
sync::Arc,
};
/// The native table context extension. This needs to be attached to the NativeContextExtensions
/// value which is passed into session functions, so its accessible from natives of this
/// extension.
#[derive(Tid)]
pub struct NativeTableContext<'a> {
resolver: &'a dyn StateResolver,
//tx_hash: [u8; 32],
table_data: Arc<RwLock<TableData>>,
}
/// Ensure the error codes in this file is consistent with the error code in raw_table.move
const E_ALREADY_EXISTS: u64 = 1;
const E_NOT_FOUND: u64 = 2;
const E_DUPLICATE_OPERATION: u64 = 3;
// ===========================================================================================
// Private Data Structures and Constants
/// A structure representing mutable data of the NativeTableContext. This is in a RefCell
/// of the overall context so we can mutate while still accessing the overall context.
#[derive(Default)]
pub struct TableData {
new_tables: BTreeMap<ObjectID, TableTypeInfo>,
removed_tables: BTreeSet<ObjectID>,
tables: BTreeMap<ObjectID, Table>,
}
/// A structure representing runtime table value.
pub struct TableRuntimeValue {
/// This is the Layout and TypeTag of the value stored in Box<V>
/// If the value is GlobalValue::None, the Layout and TypeTag are not known
value_layout_and_type: Option<(MoveTypeLayout, TypeTag)>,
/// This is the Box<V> value in MoveVM memory
/// It can be GlobalValue::None
box_value: GlobalValue,
}
impl TableRuntimeValue {
pub fn new(value_layout: MoveTypeLayout, value_type: TypeTag, box_value: GlobalValue) -> Self {
debug_assert!(box_value.exists().unwrap());
Self {
value_layout_and_type: Some((value_layout, value_type)),
box_value,
}
}
pub fn none() -> Self {
Self {
value_layout_and_type: None,
box_value: GlobalValue::none(),
}
}
pub fn exists(&self) -> PartialVMResult<bool> {
Ok(self.value_layout_and_type.is_some() && self.box_value.exists()?)
}
pub fn move_to(
&mut self,
val: Value,
value_layout: MoveTypeLayout,
value_type: TypeTag,
) -> Result<(), (PartialVMError, Value)> {
//TODO extract the type check logic into a helper function
if let Some((_exist_value_layout, exist_value_type)) = &self.value_layout_and_type {
if *exist_value_type != value_type {
return Err((
PartialVMError::new(StatusCode::TYPE_MISMATCH).with_message(format!(
"Cannot move value of type {} to value of type {}",
value_type, exist_value_type
)),
val,
));
}
} else {
self.value_layout_and_type = Some((value_layout, value_type));
}
self.box_value.move_to(val)?;
Ok(())
}
pub fn borrow_global(&self, expect_value_type: TypeTag) -> PartialVMResult<Value> {
let value = self.box_value.borrow_global()?;
match &self.value_layout_and_type {
Some((_exist_value_layout, exist_value_type)) => {
if *exist_value_type != expect_value_type {
return Err(PartialVMError::new(StatusCode::TYPE_MISMATCH).with_message(
format!(
"Cannot borrow value of type {} as type {}",
exist_value_type, expect_value_type
),
));
}
}
None => {
//TODO ensure and test this case
unreachable!("Cannot borrow value of unknown type")
//return Err(PartialVMError::new(StatusCode::MISSING_DATA).with_message(format!("Cannot borrow value of unknown type as type {}", expect_value_type)));
}
}
Ok(value)
}
pub fn move_from(&mut self, expect_value_type: TypeTag) -> PartialVMResult<Value> {
let value = self.box_value.move_from()?;
match &self.value_layout_and_type {
Some((_exist_value_layout, exist_value_type)) => {
if *exist_value_type != expect_value_type {
return Err(PartialVMError::new(StatusCode::TYPE_MISMATCH).with_message(
format!(
"Cannot move value of type {} as type {}",
exist_value_type, expect_value_type
),
));
}
}
None => {
unreachable!("Cannot move value of unknown type")
}
}
Ok(value)
}
pub fn into_effect(self) -> Option<(MoveTypeLayout, TypeTag, Op<Value>)> {
let op_opt = self.box_value.into_effect();
match (op_opt, self.value_layout_and_type) {
(Some(op), Some((value_layout, value_type))) => Some((value_layout, value_type, op)),
(None, None) => None,
(None, Some(_)) => {
// The box_value is loaded, but do not change, so no effect
None
}
(Some(_op), None) => {
unreachable!("Cannot have op without value_layout_and_type")
}
}
}
}
/// A structure representing a single table.
pub struct Table {
handle: ObjectID,
key_layout: MoveTypeLayout,
content: BTreeMap<Vec<u8>, TableRuntimeValue>,
size_increment: i64,
}
// =========================================================================================
// Implementation of Native Table Context
impl<'a> NativeTableContext<'a> {
/// Create a new instance of a native table context. This must be passed in via an
/// extension into VM session functions.
pub fn new(resolver: &'a dyn StateResolver, table_data: Arc<RwLock<TableData>>) -> Self {
Self {
resolver,
table_data,
}
}
}
impl TableData {
/// Gets or creates a new table in the TableData. This initializes information about
/// the table, like the type layout for keys and values.
fn get_or_create_table(
&mut self,
context: &NativeContext,
handle: ObjectID,
key_ty: &Type,
) -> PartialVMResult<&mut Table> {
Ok(match self.tables.entry(handle) {
Entry::Vacant(e) => {
let key_layout = type_to_type_layout(context, key_ty)?;
let table = Table {
handle,
key_layout,
content: Default::default(),
size_increment: 0,
};
if log::log_enabled!(log::Level::Trace) {
let key_type = type_to_type_tag(context, key_ty)?;
log::trace!("[RawTable] creating table {} with key {}", handle, key_type);
}
e.insert(table)
}
Entry::Occupied(e) => e.into_mut(),
})
}
pub fn get_or_create_table_with_key_layout(
&mut self,
handle: ObjectID,
key_layout: MoveTypeLayout,
) -> PartialVMResult<&mut Table> {
Ok(match self.tables.entry(handle) {
Entry::Vacant(e) => {
let table = Table {
handle,
key_layout,
content: Default::default(),
size_increment: 0,
};
e.insert(table)
}
Entry::Occupied(e) => e.into_mut(),
})
}
pub fn borrow_table(&self, handle: &ObjectID) -> PartialVMResult<&Table> {
self.tables
.get(handle)
.ok_or_else(|| PartialVMError::new(StatusCode::STORAGE_ERROR))
}
pub fn exist_table(&self, handle: &ObjectID) -> bool {
self.tables.contains_key(handle)
}
/// into inner
pub fn into_inner(
self,
) -> (
BTreeMap<ObjectID, TableTypeInfo>,
BTreeSet<ObjectID>,
BTreeMap<ObjectID, Table>,
) {
let TableData {
new_tables,
removed_tables,
tables,
} = self;
(new_tables, removed_tables, tables)
}
}
impl Table {
fn get_or_create_global_value(
&mut self,
native_context: &NativeContext,
table_context: &NativeTableContext,
key: Vec<u8>,
) -> PartialVMResult<(&mut TableRuntimeValue, Option<Option<NumBytes>>)> {
Ok(match self.content.entry(key) {
Entry::Vacant(entry) => {
let (tv, loaded) = match table_context
.resolver
.resolve_table_item(&self.handle, entry.key())
.map_err(|err| {
partial_extension_error(format!("remote table resolver failure: {}", err))
})? {
Some(value_box) => {
let value_layout = get_type_layout(native_context, &value_box.value_type)?;
let val = deserialize_and_box(&value_layout, &value_box.value)?;
(
TableRuntimeValue::new(
value_layout,
value_box.value_type,
GlobalValue::cached(val)?,
),
Some(NumBytes::new(value_box.value.len() as u64)),
)
}
None => (TableRuntimeValue::none(), None),
};
(entry.insert(tv), Some(loaded))
}
Entry::Occupied(entry) => (entry.into_mut(), None),
})
}
pub fn get_or_create_global_value_with_layout_fn(
&mut self,
resolver: &dyn StateResolver,
key: Vec<u8>,
f: impl FnOnce(&TypeTag) -> PartialVMResult<MoveTypeLayout>,
) -> PartialVMResult<(&mut TableRuntimeValue, Option<Option<NumBytes>>)> {
Ok(match self.content.entry(key) {
Entry::Vacant(entry) => {
let (tv, loaded) = match resolver
.resolve_table_item(&self.handle, entry.key())
.map_err(|err| {
partial_extension_error(format!("remote table resolver failure: {}", err))
})? {
Some(value_box) => {
let value_layout = f(&value_box.value_type)?;
let val = deserialize_and_box(&value_layout, &value_box.value)?;
(
TableRuntimeValue::new(
value_layout,
value_box.value_type,
GlobalValue::cached(val)?,
),
Some(NumBytes::new(value_box.value.len() as u64)),
)
}
None => (TableRuntimeValue::none(), None),
};
(entry.insert(tv), Some(loaded))
}
Entry::Occupied(entry) => (entry.into_mut(), None),
})
}
pub fn get_global_value(&self, key: &Vec<u8>) -> Option<&TableRuntimeValue> {
self.content.get(key)
}
pub fn contains_key(&self, key: &Vec<u8>) -> bool {
self.content.contains_key(key)
}
pub fn into_inner(
self,
) -> (
ObjectID,
MoveTypeLayout,
BTreeMap<Vec<u8>, TableRuntimeValue>,
i64,
) {
let Table {
handle,
key_layout,
content,
size_increment,
} = self;
(handle, key_layout, content, size_increment)
}
pub fn key_layout(&self) -> &MoveTypeLayout {
&self.key_layout
}
}
// =========================================================================================
// Native Function Implementations
/// Returns all natives for tables.
pub fn table_natives(table_addr: AccountAddress, gas_params: GasParameters) -> NativeFunctionTable {
let natives: [(&str, &str, NativeFunction); 7] = [
(
"raw_table",
"add_box",
make_native_add_box(gas_params.common.clone(), gas_params.add_box),
),
(
"raw_table",
"borrow_box",
make_native_borrow_box(gas_params.common.clone(), gas_params.borrow_box.clone()),
),
(
"raw_table",
"borrow_box_mut",
make_native_borrow_box(gas_params.common.clone(), gas_params.borrow_box),
),
(
"raw_table",
"remove_box",
make_native_remove_box(gas_params.common.clone(), gas_params.remove_box),
),
(
"raw_table",
"contains_box",
make_native_contains_box(gas_params.common, gas_params.contains_box),
),
(
"raw_table",
"drop_unchecked_box",
make_native_drop_unchecked_box(gas_params.drop_unchecked_box),
),
(
"raw_table",
"box_length",
make_native_box_length(gas_params.box_length),
),
];
native_functions::make_table_from_iter(table_addr, natives)
}
#[derive(Debug, Clone)]
pub struct CommonGasParameters {
pub load_base: InternalGas,
pub load_per_byte: InternalGasPerByte,
pub load_failure: InternalGas,
}
impl CommonGasParameters {
fn calculate_load_cost(&self, loaded: Option<Option<NumBytes>>) -> InternalGas {
self.load_base
+ match loaded {
Some(Some(num_bytes)) => self.load_per_byte * num_bytes,
Some(None) => self.load_failure,
None => 0.into(),
}
}
}
#[derive(Debug, Clone)]
pub struct AddBoxGasParameters {
pub base: InternalGas,
pub per_byte_serialized: InternalGasPerByte,
}
fn native_add_box(
common_gas_params: &CommonGasParameters,
gas_params: &AddBoxGasParameters,
context: &mut NativeContext,
ty_args: Vec<Type>,
mut args: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
//0 K Type
//1 V Type
//2 Box<V> Type
assert_eq!(ty_args.len(), 3);
assert_eq!(args.len(), 3);
let table_context = context.extensions().get::<NativeTableContext>();
let mut table_data = table_context.table_data.write();
let val = args.pop_back().unwrap();
let key = args.pop_back().unwrap();
let handle = get_table_handle(&mut args)?;
let mut cost = gas_params.base;
let table = table_data.get_or_create_table(context, handle, &ty_args[0])?;
let key_bytes = serialize(&table.key_layout, &key)?;
cost += gas_params.per_byte_serialized * NumBytes::new(key_bytes.len() as u64);
let (tv, loaded) = table.get_or_create_global_value(context, table_context, key_bytes)?;
cost += common_gas_params.calculate_load_cost(loaded);
let value_layout = type_to_type_layout(context, &ty_args[1])?;
let value_type = type_to_type_tag(context, &ty_args[1])?;
match tv.move_to(val, value_layout, value_type) {
Ok(_) => {
table.size_increment += 1;
Ok(NativeResult::ok(cost, smallvec![]))
}
Err(_) => Ok(NativeResult::err(
cost,
moveos_types::move_std::error::already_exists(E_ALREADY_EXISTS),
)),
}
}
pub fn make_native_add_box(
common_gas_params: CommonGasParameters,
gas_params: AddBoxGasParameters,
) -> NativeFunction {
Arc::new(
move |context, ty_args, args| -> PartialVMResult<NativeResult> {
native_add_box(&common_gas_params, &gas_params, context, ty_args, args)
},
)
}
#[derive(Debug, Clone)]
pub struct BorrowBoxGasParameters {
pub base: InternalGas,
pub per_byte_serialized: InternalGasPerByte,
}
fn native_borrow_box(
common_gas_params: &CommonGasParameters,
gas_params: &BorrowBoxGasParameters,
context: &mut NativeContext,
ty_args: Vec<Type>,
mut args: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
assert_eq!(ty_args.len(), 3);
assert_eq!(args.len(), 2);
let table_context = context.extensions().get::<NativeTableContext>();
let mut table_data = table_context.table_data.write();
let key = args.pop_back().unwrap();
let handle = get_table_handle(&mut args)?;
let table = table_data.get_or_create_table(context, handle, &ty_args[0])?;
let mut cost = gas_params.base;
let key_bytes = serialize(&table.key_layout, &key)?;
cost += gas_params.per_byte_serialized * NumBytes::new(key_bytes.len() as u64);
let (tv, loaded) = table.get_or_create_global_value(context, table_context, key_bytes)?;
cost += common_gas_params.calculate_load_cost(loaded);
let value_type = type_to_type_tag(context, &ty_args[1])?;
match tv.borrow_global(value_type) {
Ok(ref_val) => Ok(NativeResult::ok(cost, smallvec![ref_val])),
Err(_) => Ok(NativeResult::err(
cost,
moveos_types::move_std::error::not_found(E_NOT_FOUND),
)),
}
}
pub fn make_native_borrow_box(
common_gas_params: CommonGasParameters,
gas_params: BorrowBoxGasParameters,
) -> NativeFunction {
Arc::new(
move |context, ty_args, args| -> PartialVMResult<NativeResult> {
native_borrow_box(&common_gas_params, &gas_params, context, ty_args, args)
},
)
}
#[derive(Debug, Clone)]
pub struct ContainsBoxGasParameters {
pub base: InternalGas,
pub per_byte_serialized: InternalGasPerByte,
}
fn native_contains_box(
common_gas_params: &CommonGasParameters,
gas_params: &ContainsBoxGasParameters,
context: &mut NativeContext,
ty_args: Vec<Type>,
mut args: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
assert_eq!(ty_args.len(), 1);
assert_eq!(args.len(), 2);
let table_context = context.extensions().get::<NativeTableContext>();
let mut table_data = table_context.table_data.write();
let key = args.pop_back().unwrap();
let handle = get_table_handle(&mut args)?;
let table = table_data.get_or_create_table(context, handle, &ty_args[0])?;
let mut cost = gas_params.base;
if log::log_enabled!(log::Level::Trace) {
log::trace!(
"[RawTable] contains: table_handle: {}, key_type: {}",
&&table.handle,
type_to_type_tag(context, &ty_args[0])?
);
}
let key_bytes = serialize(&table.key_layout, &key)?;
cost += gas_params.per_byte_serialized * NumBytes::new(key_bytes.len() as u64);
let (tv, loaded) = table.get_or_create_global_value(context, table_context, key_bytes)?;
cost += common_gas_params.calculate_load_cost(loaded);
let exists = Value::bool(tv.exists()?);
Ok(NativeResult::ok(cost, smallvec![exists]))
}
pub fn make_native_contains_box(
common_gas_params: CommonGasParameters,
gas_params: ContainsBoxGasParameters,
) -> NativeFunction {
Arc::new(
move |context, ty_args, args| -> PartialVMResult<NativeResult> {
native_contains_box(&common_gas_params, &gas_params, context, ty_args, args)
},
)
}
#[derive(Debug, Clone)]
pub struct RemoveGasParameters {
pub base: InternalGas,
pub per_byte_serialized: InternalGasPerByte,
}
fn native_remove_box(
common_gas_params: &CommonGasParameters,
gas_params: &RemoveGasParameters,
context: &mut NativeContext,
ty_args: Vec<Type>,
mut args: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
assert_eq!(ty_args.len(), 3);
assert_eq!(args.len(), 2);
let table_context = context.extensions().get::<NativeTableContext>();
let mut table_data = table_context.table_data.write();
let key = args.pop_back().unwrap();
let handle = get_table_handle(&mut args)?;
let table = table_data.get_or_create_table(context, handle, &ty_args[0])?;
let mut cost = gas_params.base;
let key_bytes = serialize(&table.key_layout, &key)?;
cost += gas_params.per_byte_serialized * NumBytes::new(key_bytes.len() as u64);
let (tv, loaded) = table.get_or_create_global_value(context, table_context, key_bytes)?;
cost += common_gas_params.calculate_load_cost(loaded);
let value_type = type_to_type_tag(context, &ty_args[1])?;
match tv.move_from(value_type) {
Ok(val) => {
table.size_increment -= 1;
Ok(NativeResult::ok(cost, smallvec![val]))
}
Err(_) => Ok(NativeResult::err(
cost,
moveos_types::move_std::error::not_found(E_NOT_FOUND),
)),
}
}
pub fn make_native_remove_box(
common_gas_params: CommonGasParameters,
gas_params: RemoveGasParameters,
) -> NativeFunction {
Arc::new(
move |context, ty_args, args| -> PartialVMResult<NativeResult> {
native_remove_box(&common_gas_params, &gas_params, context, ty_args, args)
},
)
}
#[derive(Debug, Clone)]
pub struct BoxLengthGasParameters {
pub base: InternalGas,
}
fn native_box_length(
gas_params: &BoxLengthGasParameters,
context: &mut NativeContext,
_ty_args: Vec<Type>,
mut args: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
assert_eq!(args.len(), 1);
let table_context = context.extensions().get::<NativeTableContext>();
let table_data = table_context.table_data.write();
let handle = get_table_handle(&mut args)?;
let remote_table_size = table_context
.resolver
.resolve_object_state(&handle)
.map_err(|err| partial_extension_error(format!("remote table resolver failure: {}", err)))?
.map(|state| state.as_object::<TableInfo>())
.transpose()
.map_err(|err| partial_extension_error(format!("remote table resolver failure: {}", err)))?
.map_or_else(|| 0u64, |obj| obj.value.size);
let size_increment = if table_data.exist_table(&handle) {
table_data.borrow_table(&handle).unwrap().size_increment
} else {
0i64
};
let updated_table_size = (remote_table_size as i64) + size_increment;
debug_assert!(updated_table_size >= 0);
let length = Value::u64(updated_table_size as u64);
let cost = gas_params.base;
Ok(NativeResult::ok(cost, smallvec![length]))
}
pub fn make_native_box_length(gas_params: BoxLengthGasParameters) -> NativeFunction {
Arc::new(
move |context, ty_args, args| -> PartialVMResult<NativeResult> {
native_box_length(&gas_params, context, ty_args, args)
},
)
}
#[derive(Debug, Clone)]
pub struct DropUncheckedBoxGasParameters {
pub base: InternalGas,
}
fn native_drop_unchecked_box(
gas_params: &DropUncheckedBoxGasParameters,
context: &mut NativeContext,
_ty_args: Vec<Type>,
mut args: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
assert_eq!(args.len(), 1);
let table_context = context.extensions().get::<NativeTableContext>();
let mut table_data = table_context.table_data.write();
let handle = get_table_handle(&mut args)?;
if table_data.removed_tables.insert(handle) {
Ok(NativeResult::ok(gas_params.base, smallvec![]))
} else {
Ok(NativeResult::err(
gas_params.base,
moveos_types::move_std::error::not_found(E_DUPLICATE_OPERATION),
))
}
}
pub fn make_native_drop_unchecked_box(gas_params: DropUncheckedBoxGasParameters) -> NativeFunction {
Arc::new(
move |context, ty_args, args| -> PartialVMResult<NativeResult> {
native_drop_unchecked_box(&gas_params, context, ty_args, args)
},
)
}
#[derive(Debug, Clone)]
pub struct GasParameters {
pub common: CommonGasParameters,
pub add_box: AddBoxGasParameters,
pub borrow_box: BorrowBoxGasParameters,
pub contains_box: ContainsBoxGasParameters,
pub remove_box: RemoveGasParameters,
pub drop_unchecked_box: DropUncheckedBoxGasParameters,
pub box_length: BoxLengthGasParameters,
}
impl GasParameters {
pub fn zeros() -> Self {
Self {
common: CommonGasParameters {
load_base: 0.into(),
load_per_byte: 0.into(),
load_failure: 0.into(),
},
add_box: AddBoxGasParameters {
base: 0.into(),
per_byte_serialized: 0.into(),
},
borrow_box: BorrowBoxGasParameters {
base: 0.into(),
per_byte_serialized: 0.into(),
},
contains_box: ContainsBoxGasParameters {
base: 0.into(),
per_byte_serialized: 0.into(),
},
remove_box: RemoveGasParameters {
base: 0.into(),
per_byte_serialized: 0.into(),
},
drop_unchecked_box: DropUncheckedBoxGasParameters { base: 0.into() },
box_length: BoxLengthGasParameters { base: 0.into() },
}
}
}
// =========================================================================================
// Helpers
// The handle type in Move is `&ObjectID`. This function extracts the address from `ObjectID`.
fn get_table_handle(args: &mut VecDeque<Value>) -> PartialVMResult<ObjectID> {
let handle = pop_arg!(args, Struct);
helpers::get_object_id_from_struct(handle)
}
pub fn serialize(layout: &MoveTypeLayout, val: &Value) -> PartialVMResult<Vec<u8>> {
val.simple_serialize(layout).ok_or_else(|| {
partial_extension_error(format!(
"cannot serialize table key or value, layout:{:?}, val:{:?}",
layout, val
))
})
}
// Deserialize a value and box it to `moveos_std::raw_table::Box<V>`.
fn deserialize_and_box(layout: &MoveTypeLayout, bytes: &[u8]) -> PartialVMResult<Value> {
let value = Value::simple_deserialize(bytes, layout).ok_or_else(|| {
partial_extension_error(format!(
"cannot deserialize table key or value, layout:{:?}, bytes:{:?}",
layout,
hex::encode(bytes)
))
})?;
Ok(Value::struct_(Struct::pack(vec![value])))
}
fn partial_extension_error(msg: impl ToString) -> PartialVMError {
PartialVMError::new(StatusCode::VM_EXTENSION_ERROR).with_message(msg.to_string())
}
fn type_to_type_layout(context: &NativeContext, ty: &Type) -> PartialVMResult<MoveTypeLayout> {
context
.type_to_type_layout(ty)?
.ok_or_else(|| partial_extension_error("cannot determine type layout"))
}
fn type_to_type_tag(context: &NativeContext, ty: &Type) -> PartialVMResult<TypeTag> {
context.type_to_type_tag(ty)
}
fn get_type_layout(context: &NativeContext, type_tag: &TypeTag) -> PartialVMResult<MoveTypeLayout> {
context
.get_type_layout(type_tag)
.map_err(|e| e.to_partial())
}