Skip to main content

sui_move_natives_latest/
dynamic_field.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::{
5    NativesCostTable, abstract_size, charge_cache_or_load_gas, get_extension, get_extension_mut,
6    get_nested_struct_field, get_object_id,
7    object_runtime::{
8        ObjectRuntime,
9        object_store::{CacheInfo, ObjectResult},
10    },
11};
12use move_binary_format::errors::PartialVMResult;
13use move_binary_format::{partial_vm_error, safe_assert, safe_assert_eq, safe_unwrap};
14use move_core_types::{
15    account_address::AccountAddress,
16    gas_algebra::InternalGas,
17    language_storage::{StructTag, TypeTag},
18    vm_status::StatusCode,
19};
20use move_vm_runtime::native_charge_gas_early_exit;
21use move_vm_runtime::natives::functions::NativeContext;
22use move_vm_runtime::{
23    execution::{
24        Type,
25        values::{StructRef, Value},
26    },
27    natives::functions::NativeResult,
28    pop_arg,
29    shared::views::{SizeConfig, ValueView},
30};
31use smallvec::smallvec;
32use std::collections::VecDeque;
33use sui_types::{base_types::MoveObjectType, dynamic_field::derive_dynamic_field_id};
34use tracing::instrument;
35
36const E_KEY_DOES_NOT_EXIST: u64 = 1;
37const E_FIELD_TYPE_MISMATCH: u64 = 2;
38const E_BCS_SERIALIZATION_FAILURE: u64 = 3;
39
40// Used for pre-existing values
41const PRE_EXISTING_ABSTRACT_SIZE: u64 = 2;
42// Used for borrowing pre-existing values
43const BORROW_ABSTRACT_SIZE: u64 = 8;
44
45macro_rules! get_or_fetch_object {
46    ($context:ident, $ty_args:ident, $parent:ident, $child_id:ident, $ty_cost_per_byte:expr) => {{
47        let child_ty = safe_unwrap!($ty_args.pop());
48        native_charge_gas_early_exit!(
49            $context,
50            $ty_cost_per_byte.saturating_mul(u64::from(child_ty.size()?))
51        );
52
53        safe_assert!($ty_args.is_empty());
54        let (tag, layout, annotated_layout) = match crate::get_tag_and_layouts($context, &child_ty)?
55        {
56            Some(res) => res,
57            None => {
58                return Ok(NativeResult::err(
59                    $context.gas_used(),
60                    E_BCS_SERIALIZATION_FAILURE,
61                ));
62            }
63        };
64
65        let object_runtime: &mut ObjectRuntime = $crate::get_extension_mut!($context)?;
66        object_runtime.get_or_fetch_child_object(
67            $parent,
68            $child_id,
69            &layout,
70            &annotated_layout,
71            MoveObjectType::from(tag),
72        )?
73    }};
74}
75
76#[derive(Clone)]
77pub struct DynamicFieldHashTypeAndKeyCostParams {
78    pub dynamic_field_hash_type_and_key_cost_base: InternalGas,
79    pub dynamic_field_hash_type_and_key_type_cost_per_byte: InternalGas,
80    pub dynamic_field_hash_type_and_key_value_cost_per_byte: InternalGas,
81    pub dynamic_field_hash_type_and_key_type_tag_cost_per_byte: InternalGas,
82}
83
84/***************************************************************************************************
85 * native fun hash_type_and_key
86 * Implementation of the Move native function `hash_type_and_key<K: copy + drop + store>(parent: address, k: K): address`
87 *   gas cost: dynamic_field_hash_type_and_key_cost_base                            | covers various fixed costs in the oper
88 *              + dynamic_field_hash_type_and_key_type_cost_per_byte * size_of(K)   | covers cost of operating on the type `K`
89 *              + dynamic_field_hash_type_and_key_value_cost_per_byte * size_of(k)  | covers cost of operating on the value `k`
90 *              + dynamic_field_hash_type_and_key_type_tag_cost_per_byte * size_of(type_tag(k))    | covers cost of operating on the type tag of `K`
91 **************************************************************************************************/
92#[instrument(level = "trace", skip_all)]
93pub fn hash_type_and_key(
94    context: &mut NativeContext,
95    mut ty_args: Vec<Type>,
96    mut args: VecDeque<Value>,
97) -> PartialVMResult<NativeResult> {
98    safe_assert_eq!(ty_args.len(), 1);
99    safe_assert_eq!(args.len(), 2);
100
101    let dynamic_field_hash_type_and_key_cost_params = get_extension!(context, NativesCostTable)?
102        .dynamic_field_hash_type_and_key_cost_params
103        .clone();
104
105    // Charge base fee
106    native_charge_gas_early_exit!(
107        context,
108        dynamic_field_hash_type_and_key_cost_params.dynamic_field_hash_type_and_key_cost_base
109    );
110
111    let k_ty = safe_unwrap!(ty_args.pop());
112    let k: Value = safe_unwrap!(args.pop_back());
113    let parent = pop_arg!(args, AccountAddress);
114
115    // Get size info for costing for derivations, serializations, etc
116    let k_ty_size = u64::from(k_ty.size()?);
117    let k_value_size = u64::from(abstract_size(
118        get_extension!(context, ObjectRuntime)?.protocol_config,
119        &k,
120    )?);
121    native_charge_gas_early_exit!(
122        context,
123        dynamic_field_hash_type_and_key_cost_params
124            .dynamic_field_hash_type_and_key_type_cost_per_byte
125            .saturating_mul(k_ty_size)
126            + dynamic_field_hash_type_and_key_cost_params
127                .dynamic_field_hash_type_and_key_value_cost_per_byte
128                .saturating_mul(k_value_size)
129    );
130
131    let k_tag = context.type_to_type_tag(&k_ty)?;
132    let k_tag_size = u64::from(k_tag.abstract_size_for_gas_metering());
133
134    native_charge_gas_early_exit!(
135        context,
136        dynamic_field_hash_type_and_key_cost_params
137            .dynamic_field_hash_type_and_key_type_tag_cost_per_byte
138            .saturating_mul(k_tag_size)
139    );
140
141    let k_layout = match context.type_to_type_layout(&k_ty) {
142        Ok(Some(layout)) => layout,
143        Err(err) if err.major_status() == StatusCode::OUT_OF_GAS => return Err(err),
144        _ => {
145            return Ok(NativeResult::err(
146                context.gas_used(),
147                E_BCS_SERIALIZATION_FAILURE,
148            ));
149        }
150    };
151    let cost = context.gas_used();
152    let Some(k_bytes) = k.typed_serialize(&k_layout) else {
153        return Ok(NativeResult::err(cost, E_BCS_SERIALIZATION_FAILURE));
154    };
155    let Ok(id) = derive_dynamic_field_id(parent, &k_tag, &k_bytes) else {
156        return Ok(NativeResult::err(cost, E_BCS_SERIALIZATION_FAILURE));
157    };
158
159    Ok(NativeResult::ok(cost, smallvec![Value::address(id.into())]))
160}
161
162#[derive(Clone)]
163pub struct DynamicFieldAddChildObjectCostParams {
164    pub dynamic_field_add_child_object_cost_base: InternalGas,
165    pub dynamic_field_add_child_object_type_cost_per_byte: InternalGas,
166    pub dynamic_field_add_child_object_value_cost_per_byte: InternalGas,
167    pub dynamic_field_add_child_object_struct_tag_cost_per_byte: InternalGas,
168}
169
170/***************************************************************************************************
171 * native fun add_child_object
172 * throws `E_KEY_ALREADY_EXISTS` if a child already exists with that ID
173 * Implementation of the Move native function `add_child_object<Child: key>(parent: address, child: Child)`
174 *   gas cost: dynamic_field_add_child_object_cost_base                    | covers various fixed costs in the oper
175 *              + dynamic_field_add_child_object_type_cost_per_byte * size_of(Child)        | covers cost of operating on the type `Child`
176 *              + dynamic_field_add_child_object_value_cost_per_byte * size_of(child)       | covers cost of operating on the value `child`
177 *              + dynamic_field_add_child_object_struct_tag_cost_per_byte * size_of(struct)tag(Child))  | covers cost of operating on the struct tag of `Child`
178 **************************************************************************************************/
179#[instrument(level = "trace", skip_all)]
180pub fn add_child_object(
181    context: &mut NativeContext,
182    mut ty_args: Vec<Type>,
183    mut args: VecDeque<Value>,
184) -> PartialVMResult<NativeResult> {
185    safe_assert_eq!(ty_args.len(), 1);
186    safe_assert_eq!(args.len(), 2);
187
188    let dynamic_field_add_child_object_cost_params = get_extension!(context, NativesCostTable)?
189        .dynamic_field_add_child_object_cost_params
190        .clone();
191
192    // Charge base fee
193    native_charge_gas_early_exit!(
194        context,
195        dynamic_field_add_child_object_cost_params.dynamic_field_add_child_object_cost_base
196    );
197
198    let child = safe_unwrap!(args.pop_back());
199    let parent = pop_arg!(args, AccountAddress).into();
200    safe_assert!(args.is_empty());
201
202    // The value already exists, the size of the value is irrelevant
203    let child_value_size = PRE_EXISTING_ABSTRACT_SIZE;
204    // ID extraction step
205    native_charge_gas_early_exit!(
206        context,
207        dynamic_field_add_child_object_cost_params
208            .dynamic_field_add_child_object_value_cost_per_byte
209            .saturating_mul(child_value_size)
210    );
211
212    // TODO remove this copy_value, which will require VM changes
213    let child_id = safe_unwrap!(
214        get_object_id(child.copy_value()).and_then(|v| v.value_as::<AccountAddress>())
215    )
216    .into();
217    let child_ty = safe_unwrap!(ty_args.pop());
218    let child_type_size = u64::from(child_ty.size()?);
219
220    native_charge_gas_early_exit!(
221        context,
222        dynamic_field_add_child_object_cost_params
223            .dynamic_field_add_child_object_type_cost_per_byte
224            .saturating_mul(child_type_size)
225    );
226
227    safe_assert!(ty_args.is_empty());
228    let tag = match context.type_to_type_tag(&child_ty)? {
229        TypeTag::Struct(s) => *s,
230        _ => {
231            return Err(partial_vm_error!(
232                UNKNOWN_INVARIANT_VIOLATION_ERROR,
233                "Sui verifier guarantees this is a struct"
234            ));
235        }
236    };
237
238    let struct_tag_size = u64::from(tag.abstract_size_for_gas_metering());
239    native_charge_gas_early_exit!(
240        context,
241        dynamic_field_add_child_object_cost_params
242            .dynamic_field_add_child_object_struct_tag_cost_per_byte
243            .saturating_mul(struct_tag_size)
244    );
245
246    context.type_to_type_layout(&child_ty)?;
247
248    let object_runtime: &mut ObjectRuntime = get_extension_mut!(context)?;
249    object_runtime.add_child_object(parent, child_id, MoveObjectType::from(tag), child)?;
250    Ok(NativeResult::ok(context.gas_used(), smallvec![]))
251}
252
253#[derive(Clone)]
254pub struct DynamicFieldBorrowChildObjectCostParams {
255    pub dynamic_field_borrow_child_object_cost_base: InternalGas,
256    pub dynamic_field_borrow_child_object_child_ref_cost_per_byte: InternalGas,
257    pub dynamic_field_borrow_child_object_type_cost_per_byte: InternalGas,
258}
259
260/***************************************************************************************************
261 * native fun borrow_child_object
262 * throws `E_KEY_DOES_NOT_EXIST` if a child does not exist with that ID at that type
263 * or throws `E_FIELD_TYPE_MISMATCH` if the type does not match (as the runtime does not distinguish different reference types)
264 * Implementation of the Move native function `borrow_child_object_mut<Child: key>(parent: &mut UID, id: address): &mut Child`
265 *   gas cost: dynamic_field_borrow_child_object_cost_base                    | covers various fixed costs in the oper
266 *              + dynamic_field_borrow_child_object_child_ref_cost_per_byte  * size_of(&Child)  | covers cost of fetching and returning `&Child`
267 *              + dynamic_field_borrow_child_object_type_cost_per_byte  * size_of(Child)        | covers cost of operating on type `Child`
268 **************************************************************************************************/
269#[instrument(level = "trace", skip_all)]
270pub fn borrow_child_object(
271    context: &mut NativeContext,
272    mut ty_args: Vec<Type>,
273    mut args: VecDeque<Value>,
274) -> PartialVMResult<NativeResult> {
275    safe_assert_eq!(ty_args.len(), 1);
276    safe_assert_eq!(args.len(), 2);
277
278    let dynamic_field_borrow_child_object_cost_params = get_extension!(context, NativesCostTable)?
279        .dynamic_field_borrow_child_object_cost_params
280        .clone();
281    native_charge_gas_early_exit!(
282        context,
283        dynamic_field_borrow_child_object_cost_params.dynamic_field_borrow_child_object_cost_base
284    );
285
286    let child_id = pop_arg!(args, AccountAddress).into();
287
288    let parent_uid = safe_unwrap!(pop_arg!(args, StructRef).read_ref());
289    // UID { id: ID { bytes: address } }
290    let parent = safe_unwrap!(
291        get_nested_struct_field(parent_uid, &[0, 0]).and_then(|v| v.value_as::<AccountAddress>())
292    )
293    .into();
294
295    safe_assert!(args.is_empty());
296    let global_value_result = get_or_fetch_object!(
297        context,
298        ty_args,
299        parent,
300        child_id,
301        dynamic_field_borrow_child_object_cost_params
302            .dynamic_field_borrow_child_object_type_cost_per_byte
303    );
304    let (cache_info, global_value) = match global_value_result {
305        ObjectResult::MismatchedType => {
306            return Ok(NativeResult::err(context.gas_used(), E_FIELD_TYPE_MISMATCH));
307        }
308        ObjectResult::Loaded(gv) => gv,
309    };
310    if !global_value.exists()? {
311        return Ok(NativeResult::err(context.gas_used(), E_KEY_DOES_NOT_EXIST));
312    }
313    let child_ref = global_value.borrow_global().map_err(|err| {
314        if err.major_status() == StatusCode::MISSING_DATA {
315            partial_vm_error!(
316                UNKNOWN_INVARIANT_VIOLATION_ERROR,
317                "borrow_global returned MISSING_DATA after exists() was true"
318            )
319        } else {
320            err
321        }
322    })?;
323
324    charge_cache_or_load_gas!(context, cache_info);
325    let child_ref_size = match cache_info {
326        CacheInfo::CachedValue => {
327            // The value already existed
328            BORROW_ABSTRACT_SIZE.into()
329        }
330        // The Move value had to be created. We traverse references to get the full size of the
331        // borrowed value
332        CacheInfo::CachedObject | CacheInfo::Loaded(_) => {
333            child_ref.abstract_memory_size(&SizeConfig {
334                include_vector_size: true,
335                traverse_references: true,
336            })?
337        }
338    };
339
340    native_charge_gas_early_exit!(
341        context,
342        dynamic_field_borrow_child_object_cost_params
343            .dynamic_field_borrow_child_object_child_ref_cost_per_byte
344            .saturating_mul(u64::from(child_ref_size))
345    );
346
347    Ok(NativeResult::ok(context.gas_used(), smallvec![child_ref]))
348}
349
350#[derive(Clone)]
351pub struct DynamicFieldRemoveChildObjectCostParams {
352    pub dynamic_field_remove_child_object_cost_base: InternalGas,
353    pub dynamic_field_remove_child_object_child_cost_per_byte: InternalGas,
354    pub dynamic_field_remove_child_object_type_cost_per_byte: InternalGas,
355}
356/***************************************************************************************************
357 * native fun remove_child_object
358 * throws `E_KEY_DOES_NOT_EXIST` if a child does not exist with that ID at that type
359 * or throws `E_FIELD_TYPE_MISMATCH` if the type does not match
360 * Implementation of the Move native function `remove_child_object<Child: key>(parent: address, id: address): Child`
361 *   gas cost: dynamic_field_remove_child_object_cost_base                    | covers various fixed costs in the oper
362 *              + dynamic_field_remove_child_object_type_cost_per_byte * size_of(Child)      | covers cost of operating on type `Child`
363 *              + dynamic_field_remove_child_object_child_cost_per_byte  * size_of(child)     | covers cost of fetching and returning value of type `Child`
364 **************************************************************************************************/
365#[instrument(level = "trace", skip_all)]
366pub fn remove_child_object(
367    context: &mut NativeContext,
368    mut ty_args: Vec<Type>,
369    mut args: VecDeque<Value>,
370) -> PartialVMResult<NativeResult> {
371    safe_assert_eq!(ty_args.len(), 1);
372    safe_assert_eq!(args.len(), 2);
373
374    let dynamic_field_remove_child_object_cost_params = get_extension!(context, NativesCostTable)?
375        .dynamic_field_remove_child_object_cost_params
376        .clone();
377    native_charge_gas_early_exit!(
378        context,
379        dynamic_field_remove_child_object_cost_params.dynamic_field_remove_child_object_cost_base
380    );
381
382    let child_id = pop_arg!(args, AccountAddress).into();
383    let parent = pop_arg!(args, AccountAddress).into();
384    safe_assert!(args.is_empty());
385    let global_value_result = get_or_fetch_object!(
386        context,
387        ty_args,
388        parent,
389        child_id,
390        dynamic_field_remove_child_object_cost_params
391            .dynamic_field_remove_child_object_type_cost_per_byte
392    );
393    let (cache_info, global_value) = match global_value_result {
394        ObjectResult::MismatchedType => {
395            return Ok(NativeResult::err(context.gas_used(), E_FIELD_TYPE_MISMATCH));
396        }
397        ObjectResult::Loaded(gv) => gv,
398    };
399
400    if !global_value.exists()? {
401        return Ok(NativeResult::err(context.gas_used(), E_KEY_DOES_NOT_EXIST));
402    }
403    let child = global_value.move_from().map_err(|err| {
404        if err.major_status() == StatusCode::MISSING_DATA {
405            partial_vm_error!(
406                UNKNOWN_INVARIANT_VIOLATION_ERROR,
407                "move_from returned MISSING_DATA after exists() was true"
408            )
409        } else {
410            err
411        }
412    })?;
413
414    charge_cache_or_load_gas!(context, cache_info);
415
416    let child_size = match cache_info {
417        CacheInfo::CachedValue => {
418            // The value already existed
419            PRE_EXISTING_ABSTRACT_SIZE.into()
420        }
421        // The Move value had to be created. The value isn't a reference so traverse_references
422        // doesn't matter
423        CacheInfo::CachedObject | CacheInfo::Loaded(_) => {
424            child.abstract_memory_size(&SizeConfig {
425                include_vector_size: true,
426                traverse_references: false,
427            })?
428        }
429    };
430    native_charge_gas_early_exit!(
431        context,
432        dynamic_field_remove_child_object_cost_params
433            .dynamic_field_remove_child_object_child_cost_per_byte
434            .saturating_mul(u64::from(child_size))
435    );
436
437    Ok(NativeResult::ok(context.gas_used(), smallvec![child]))
438}
439
440#[derive(Clone)]
441pub struct DynamicFieldHasChildObjectCostParams {
442    // All inputs are constant same size. No need for special costing as this is a lookup
443    pub dynamic_field_has_child_object_cost_base: InternalGas,
444}
445/***************************************************************************************************
446 * native fun has_child_object
447 * Implementation of the Move native function `has_child_object(parent: address, id: address): bool`
448 *   gas cost: dynamic_field_has_child_object_cost_base                    | covers various fixed costs in the oper
449 **************************************************************************************************/
450#[instrument(level = "trace", skip_all)]
451pub fn has_child_object(
452    context: &mut NativeContext,
453    ty_args: Vec<Type>,
454    mut args: VecDeque<Value>,
455) -> PartialVMResult<NativeResult> {
456    safe_assert!(ty_args.is_empty());
457    safe_assert_eq!(args.len(), 2);
458
459    let dynamic_field_has_child_object_cost_params = get_extension!(context, NativesCostTable)?
460        .dynamic_field_has_child_object_cost_params
461        .clone();
462    native_charge_gas_early_exit!(
463        context,
464        dynamic_field_has_child_object_cost_params.dynamic_field_has_child_object_cost_base
465    );
466
467    let child_id = pop_arg!(args, AccountAddress).into();
468    let parent = pop_arg!(args, AccountAddress).into();
469    let object_runtime: &mut ObjectRuntime = get_extension_mut!(context)?;
470    let (cache_info, has_child) = object_runtime.child_object_exists(parent, child_id)?;
471    charge_cache_or_load_gas!(context, cache_info);
472    Ok(NativeResult::ok(
473        context.gas_used(),
474        smallvec![Value::bool(has_child)],
475    ))
476}
477
478#[derive(Clone)]
479pub struct DynamicFieldHasChildObjectWithTyCostParams {
480    pub dynamic_field_has_child_object_with_ty_cost_base: InternalGas,
481    pub dynamic_field_has_child_object_with_ty_type_cost_per_byte: InternalGas,
482    pub dynamic_field_has_child_object_with_ty_type_tag_cost_per_byte: InternalGas,
483}
484/***************************************************************************************************
485 * native fun has_child_object_with_ty
486 * Implementation of the Move native function `has_child_object_with_ty<Child: key>(parent: address, id: address): bool`
487 *   gas cost: dynamic_field_has_child_object_with_ty_cost_base               | covers various fixed costs in the oper
488 *              + dynamic_field_has_child_object_with_ty_type_cost_per_byte * size_of(Child)        | covers cost of operating on type `Child`
489 *              + dynamic_field_has_child_object_with_ty_type_tag_cost_per_byte * size_of(Child)    | covers cost of fetching and returning value of type tag for `Child`
490 **************************************************************************************************/
491#[instrument(level = "trace", skip_all)]
492pub fn has_child_object_with_ty(
493    context: &mut NativeContext,
494    mut ty_args: Vec<Type>,
495    mut args: VecDeque<Value>,
496) -> PartialVMResult<NativeResult> {
497    safe_assert_eq!(ty_args.len(), 1);
498    safe_assert_eq!(args.len(), 2);
499
500    let dynamic_field_has_child_object_with_ty_cost_params =
501        get_extension!(context, NativesCostTable)?
502            .dynamic_field_has_child_object_with_ty_cost_params
503            .clone();
504    native_charge_gas_early_exit!(
505        context,
506        dynamic_field_has_child_object_with_ty_cost_params
507            .dynamic_field_has_child_object_with_ty_cost_base
508    );
509
510    let child_id = pop_arg!(args, AccountAddress).into();
511    let parent = pop_arg!(args, AccountAddress).into();
512    safe_assert!(args.is_empty());
513    let ty = safe_unwrap!(ty_args.pop());
514
515    native_charge_gas_early_exit!(
516        context,
517        dynamic_field_has_child_object_with_ty_cost_params
518            .dynamic_field_has_child_object_with_ty_type_cost_per_byte
519            .saturating_mul(u64::from(ty.size()?))
520    );
521
522    let tag: StructTag = match context.type_to_type_tag(&ty)? {
523        TypeTag::Struct(s) => *s,
524        _ => {
525            return Err(partial_vm_error!(
526                UNKNOWN_INVARIANT_VIOLATION_ERROR,
527                "Sui verifier guarantees this is a struct"
528            ));
529        }
530    };
531
532    native_charge_gas_early_exit!(
533        context,
534        dynamic_field_has_child_object_with_ty_cost_params
535            .dynamic_field_has_child_object_with_ty_type_tag_cost_per_byte
536            .saturating_mul(u64::from(tag.abstract_size_for_gas_metering()))
537    );
538
539    let object_runtime: &mut ObjectRuntime = get_extension_mut!(context)?;
540    let (cache_info, has_child) = object_runtime.child_object_exists_and_has_type(
541        parent,
542        child_id,
543        &MoveObjectType::from(tag),
544    )?;
545    charge_cache_or_load_gas!(context, cache_info);
546    Ok(NativeResult::ok(
547        context.gas_used(),
548        smallvec![Value::bool(has_child)],
549    ))
550}