Skip to main content

sui_move_natives_latest/
config.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::{
5    NativesCostTable, abstract_size, get_extension, get_extension_mut,
6    object_runtime::ObjectRuntime,
7};
8use move_binary_format::errors::PartialVMResult;
9use move_binary_format::partial_vm_error;
10use move_binary_format::{safe_assert_eq, safe_unwrap};
11use move_core_types::{
12    account_address::AccountAddress, gas_algebra::InternalGas, language_storage::StructTag,
13    runtime_value as R,
14};
15use move_vm_runtime::execution::values::{Struct, Vector};
16use move_vm_runtime::native_charge_gas_early_exit;
17use move_vm_runtime::natives::functions::NativeContext;
18use move_vm_runtime::{
19    execution::{Type, values::Value},
20    natives::functions::NativeResult,
21    pop_arg,
22};
23use smallvec::smallvec;
24use std::collections::VecDeque;
25use sui_types::{TypeTag, base_types::MoveObjectType};
26use tracing::{error, instrument};
27
28const E_BCS_SERIALIZATION_FAILURE: u64 = 2;
29
30#[derive(Clone)]
31pub struct ConfigReadSettingImplCostParams {
32    pub config_read_setting_impl_cost_base: Option<InternalGas>,
33    pub config_read_setting_impl_cost_per_byte: Option<InternalGas>,
34}
35
36#[instrument(level = "trace", skip_all)]
37pub fn read_setting_impl(
38    context: &mut NativeContext,
39    mut ty_args: Vec<Type>,
40    mut args: VecDeque<Value>,
41) -> PartialVMResult<NativeResult> {
42    safe_assert_eq!(ty_args.len(), 4);
43    safe_assert_eq!(args.len(), 3);
44
45    let ConfigReadSettingImplCostParams {
46        config_read_setting_impl_cost_base,
47        config_read_setting_impl_cost_per_byte,
48    } = get_extension!(context, NativesCostTable)?
49        .config_read_setting_impl_cost_params
50        .clone();
51
52    let config_read_setting_impl_cost_base =
53        config_read_setting_impl_cost_base.ok_or_else(|| {
54            partial_vm_error!(UNKNOWN_INVARIANT_VIOLATION_ERROR, "gas cost is not set")
55        })?;
56    let config_read_setting_impl_cost_per_byte = config_read_setting_impl_cost_per_byte
57        .ok_or_else(|| {
58            partial_vm_error!(UNKNOWN_INVARIANT_VIOLATION_ERROR, "gas cost is not set")
59        })?;
60    // Charge base fee
61    native_charge_gas_early_exit!(context, config_read_setting_impl_cost_base);
62
63    let value_ty = safe_unwrap!(ty_args.pop());
64    let setting_data_value_ty = safe_unwrap!(ty_args.pop());
65    let setting_value_ty = safe_unwrap!(ty_args.pop());
66    let field_setting_ty = safe_unwrap!(ty_args.pop());
67
68    let current_epoch = pop_arg!(args, u64);
69    let name_df_addr = pop_arg!(args, AccountAddress);
70    let config_addr = pop_arg!(args, AccountAddress);
71
72    let field_setting_tag: StructTag = match context.type_to_type_tag(&field_setting_ty)? {
73        TypeTag::Struct(s) => *s,
74        _ => {
75            return Err(partial_vm_error!(
76                UNKNOWN_INVARIANT_VIOLATION_ERROR,
77                "Sui verifier guarantees this is a struct"
78            ));
79        }
80    };
81    let Some(field_setting_layout) = context.type_to_type_layout(&field_setting_ty)? else {
82        return Ok(NativeResult::err(
83            context.gas_used(),
84            E_BCS_SERIALIZATION_FAILURE,
85        ));
86    };
87    let object_runtime: &mut ObjectRuntime = get_extension_mut!(context)?;
88
89    let read_value_opt = consistent_value_before_current_epoch(
90        object_runtime,
91        field_setting_tag,
92        &field_setting_layout,
93        &setting_value_ty,
94        &setting_data_value_ty,
95        &value_ty,
96        config_addr,
97        name_df_addr,
98        current_epoch,
99    )?;
100
101    let size = abstract_size(object_runtime.protocol_config, &read_value_opt)?;
102
103    native_charge_gas_early_exit!(
104        context,
105        config_read_setting_impl_cost_per_byte.saturating_mul(u64::from(size))
106    );
107
108    Ok(NativeResult::ok(
109        context.gas_used(),
110        smallvec![read_value_opt],
111    ))
112}
113
114fn consistent_value_before_current_epoch(
115    object_runtime: &mut ObjectRuntime,
116    field_setting_tag: StructTag,
117    field_setting_layout: &R::MoveTypeLayout,
118    _setting_value_ty: &Type,
119    setting_data_value_ty: &Type,
120    value_ty: &Type,
121    config_addr: AccountAddress,
122    name_df_addr: AccountAddress,
123    current_epoch: u64,
124) -> PartialVMResult<Value> {
125    let field_setting_obj_ty = MoveObjectType::from(field_setting_tag);
126    let Some(field) = object_runtime.config_setting_unsequenced_read(
127        config_addr.into(),
128        name_df_addr.into(),
129        field_setting_layout,
130        &field_setting_obj_ty,
131    ) else {
132        return option_none(value_ty);
133    };
134
135    let [_id, _name, setting]: [Value; 3] = unpack_struct(field)?;
136    let [data_opt]: [Value; 1] = unpack_struct(setting)?;
137    let data = match unpack_option(data_opt, setting_data_value_ty)? {
138        None => {
139            error!(
140                "
141                SettingData is none.
142                config_addr: {config_addr},
143                name_df_addr: {name_df_addr},
144                field_setting_obj_ty: {field_setting_obj_ty:?}",
145            );
146            return option_none(value_ty);
147        }
148        Some(data) => data,
149    };
150    let [newer_value_epoch, newer_value, older_value_opt]: [Value; 3] = unpack_struct(data)?;
151    let newer_value_epoch: u64 = newer_value_epoch.value_as()?;
152    debug_assert!(
153        unpack_option(newer_value.copy_value(), value_ty)?.is_some()
154            || unpack_option(older_value_opt.copy_value(), value_ty)?.is_some()
155    );
156    Ok(if current_epoch > newer_value_epoch {
157        newer_value
158    } else {
159        older_value_opt
160    })
161}
162
163fn unpack_struct<const N: usize>(s: Value) -> PartialVMResult<[Value; N]> {
164    let s: Struct = s.value_as()?;
165    s.unpack().collect::<Vec<_>>().try_into().map_err(|e| {
166        partial_vm_error!(
167            UNKNOWN_INVARIANT_VIOLATION_ERROR,
168            "struct expected to have {N} fields: {e:?}"
169        )
170    })
171}
172
173fn unpack_option(option: Value, type_param: &Type) -> PartialVMResult<Option<Value>> {
174    let [vec_value]: [Value; 1] = unpack_struct(option)?;
175    let vec: Vector = vec_value.value_as()?;
176    Ok(if vec.elem_len()? == 0 {
177        None
178    } else {
179        let [elem]: [Value; 1] = vec.unpack(type_param, 1)?.try_into().map_err(|e| {
180            partial_vm_error!(
181                UNKNOWN_INVARIANT_VIOLATION_ERROR,
182                "vector expected to have one element: {e:?}"
183            )
184        })?;
185        Some(elem)
186    })
187}
188
189fn option_none(type_param: &Type) -> PartialVMResult<Value> {
190    Ok(Value::struct_(Struct::pack(vec![Vector::empty(
191        type_param.try_into()?,
192    )?])))
193}