sui_adapter_latest/static_programmable_transactions/execution/
values.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::static_programmable_transactions::{env::Env, typing::ast::Type};
5use move_binary_format::errors::PartialVMError;
6use move_core_types::{account_address::AccountAddress, runtime_value::MoveTypeLayout, u256::U256};
7use move_vm_types::{
8    values::{
9        self, Locals as VMLocals, Struct, VMValueCast, Value as VMValue, VectorSpecialization,
10    },
11    views::ValueView,
12};
13use sui_types::{
14    base_types::{ObjectID, SequenceNumber},
15    digests::TransactionDigest,
16    error::ExecutionError,
17    move_package::{UpgradeCap, UpgradeReceipt, UpgradeTicket},
18};
19pub enum InputValue<'a> {
20    Bytes(&'a ByteValue),
21    Loaded(Local<'a>),
22}
23
24pub enum ByteValue {
25    Pure(Vec<u8>),
26    Receiving {
27        id: ObjectID,
28        version: SequenceNumber,
29    },
30}
31
32/// A memory location that can be borrowed or moved from
33pub struct Local<'a>(&'a mut Locals, u16);
34
35/// A set of memory locations that can be borrowed or moved from. Used for inputs and results
36pub struct Locals(VMLocals);
37
38#[derive(Debug)]
39pub struct Value(VMValue);
40
41impl Locals {
42    pub fn new<Items>(values: Items) -> Result<Self, ExecutionError>
43    where
44        Items: IntoIterator<Item = Option<Value>>,
45        Items::IntoIter: ExactSizeIterator,
46    {
47        let values = values.into_iter();
48        let n = values.len();
49        assert_invariant!(n <= u16::MAX as usize, "Locals size exceeds u16::MAX");
50        let mut locals = VMLocals::new(n);
51        for (i, value_opt) in values.enumerate() {
52            let Some(value) = value_opt else {
53                // If the value is None, we leave the local invalid
54                continue;
55            };
56            locals
57                .store_loc(i, value.0, /* violation check */ true)
58                .map_err(iv("store loc"))?;
59        }
60        Ok(Self(locals))
61    }
62
63    pub fn new_invalid(n: usize) -> Result<Self, ExecutionError> {
64        assert_invariant!(n <= u16::MAX as usize, "Locals size exceeds u16::MAX");
65        Ok(Self(VMLocals::new(n)))
66    }
67
68    pub fn local(&mut self, index: u16) -> Result<Local<'_>, ExecutionError> {
69        Ok(Local(self, index))
70    }
71}
72
73impl Local<'_> {
74    /// Does the local contain a value?
75    pub fn is_invalid(&self) -> Result<bool, ExecutionError> {
76        self.0
77            .0
78            .is_invalid(self.1 as usize)
79            .map_err(iv("out of bounds"))
80    }
81
82    pub fn store(&mut self, value: Value) -> Result<(), ExecutionError> {
83        self.0
84            .0
85            .store_loc(self.1 as usize, value.0, /* violation check */ true)
86            .map_err(iv("store loc"))
87    }
88
89    /// Move the value out of the local
90    pub fn move_(&mut self) -> Result<Value, ExecutionError> {
91        assert_invariant!(!self.is_invalid()?, "cannot move invalid local");
92        Ok(Value(
93            self.0
94                .0
95                .move_loc(self.1 as usize, /* violation check */ true)
96                .map_err(iv("move loc"))?,
97        ))
98    }
99
100    /// Copy the value out in the local
101    pub fn copy(&self) -> Result<Value, ExecutionError> {
102        assert_invariant!(!self.is_invalid()?, "cannot copy invalid local");
103        Ok(Value(
104            self.0.0.copy_loc(self.1 as usize).map_err(iv("copy loc"))?,
105        ))
106    }
107
108    /// Borrow the local, creating a reference to the value
109    pub fn borrow(&self) -> Result<Value, ExecutionError> {
110        assert_invariant!(!self.is_invalid()?, "cannot borrow invalid local");
111        Ok(Value(
112            self.0
113                .0
114                .borrow_loc(self.1 as usize)
115                .map_err(iv("borrow loc"))?,
116        ))
117    }
118
119    pub fn move_if_valid(&mut self) -> Result<Option<Value>, ExecutionError> {
120        if self.is_invalid()? {
121            Ok(None)
122        } else {
123            Ok(Some(self.move_()?))
124        }
125    }
126}
127
128impl Value {
129    pub fn copy(&self) -> Result<Self, ExecutionError> {
130        Ok(Value(self.0.copy_value().map_err(iv("copy"))?))
131    }
132
133    /// Read the value, giving an invariant violation if the value is not a reference
134    pub fn read_ref(self) -> Result<Self, ExecutionError> {
135        let value: values::Reference = self.0.cast().map_err(iv("cast"))?;
136        Ok(Self(value.read_ref().map_err(iv("read ref"))?))
137    }
138
139    /// This function will invariant violation on an invalid cast
140    pub fn cast<V>(self) -> Result<V, ExecutionError>
141    where
142        VMValue: VMValueCast<V>,
143    {
144        self.0.cast().map_err(iv("cast"))
145    }
146
147    pub fn deserialize(env: &Env, bytes: &[u8], ty: Type) -> Result<Value, ExecutionError> {
148        let layout = env.runtime_layout(&ty)?;
149        let Some(value) = VMValue::simple_deserialize(bytes, &layout) else {
150            // we already checked the layout of pure bytes during typing
151            // and objects should already be valid
152            invariant_violation!("unable to deserialize value to type {ty:?}")
153        };
154        Ok(Value(value))
155    }
156
157    pub fn typed_serialize(&self, layout: &MoveTypeLayout) -> Option<Vec<u8>> {
158        self.0.typed_serialize(layout)
159    }
160
161    /// Used for getting access to the inner VMValue for tracing purposes.
162    pub(super) fn inner_for_tracing(&self) -> &VMValue {
163        &self.0
164    }
165}
166
167impl From<VMValue> for Value {
168    fn from(value: VMValue) -> Self {
169        Value(value)
170    }
171}
172
173impl From<Value> for VMValue {
174    fn from(value: Value) -> Self {
175        value.0
176    }
177}
178
179impl VMValueCast<Value> for VMValue {
180    fn cast(self) -> Result<Value, PartialVMError> {
181        Ok(self.into())
182    }
183}
184
185impl ValueView for Value {
186    fn visit(&self, visitor: &mut impl move_vm_types::views::ValueVisitor) {
187        self.0.visit(visitor)
188    }
189}
190
191//**************************************************************************************************
192// Value Construction
193//**************************************************************************************************
194
195impl Value {
196    pub fn id(address: AccountAddress) -> Self {
197        // ID { address }
198        Self(VMValue::struct_(Struct::pack([VMValue::address(address)])))
199    }
200
201    pub fn uid(address: AccountAddress) -> Self {
202        // UID { ID { address } }
203        Self(VMValue::struct_(Struct::pack([Self::id(address).0])))
204    }
205
206    pub fn receiving(id: ObjectID, version: SequenceNumber) -> Self {
207        Self(VMValue::struct_(Struct::pack([
208            Self::id(id.into()).0,
209            VMValue::u64(version.into()),
210        ])))
211    }
212
213    pub fn balance(amount: u64) -> Self {
214        // Balance { amount }
215        Self(VMValue::struct_(Struct::pack([VMValue::u64(amount)])))
216    }
217
218    /// The uid _must_ be registered by the object runtime before being called
219    pub fn coin(id: ObjectID, amount: u64) -> Self {
220        Self(VMValue::struct_(Struct::pack([
221            Self::uid(id.into()).0,
222            Self::balance(amount).0,
223        ])))
224    }
225
226    /// Constructs a `sui::funds_accumulator::Withdrawal` value
227    pub fn funds_accumulator_withdrawal(owner: AccountAddress, limit: U256) -> Self {
228        // public struct Withdrawal has drop {
229        //     owner: address,
230        //     limit: u256,
231        // }
232        Self(VMValue::struct_(Struct::pack([
233            VMValue::address(owner),
234            VMValue::u256(limit),
235        ])))
236    }
237
238    pub fn vec_pack(ty: Type, values: Vec<Self>) -> Result<Self, ExecutionError> {
239        let specialization: VectorSpecialization = ty
240            .try_into()
241            .map_err(|e| make_invariant_violation!("Unable to specialize vector: {e}"))?;
242        let vec = values::Vector::pack(specialization, values.into_iter().map(|v| v.0))
243            .map_err(iv("pack"))?;
244        Ok(Self(vec))
245    }
246
247    /// Should be called once at the start of a transaction to populate the location with the
248    /// transaction context.
249    pub fn new_tx_context(digest: TransactionDigest) -> Result<Self, ExecutionError> {
250        // public struct TxContext has drop {
251        //     sender: address,
252        //     tx_hash: vector<u8>,
253        //     epoch: u64,
254        //     epoch_timestamp_ms: u64,
255        //     ids_created: u64,
256        // }
257        Ok(Self(VMValue::struct_(Struct::pack([
258            VMValue::address(AccountAddress::ZERO),
259            VMValue::vector_u8(digest.inner().iter().copied()),
260            VMValue::u64(0),
261            VMValue::u64(0),
262            VMValue::u64(0),
263        ]))))
264    }
265
266    pub fn one_time_witness() -> Result<Self, ExecutionError> {
267        // public struct <ONE_TIME_WITNESS> has drop{
268        //     _dummy: bool,
269        // }
270        Ok(Self(VMValue::struct_(Struct::pack([VMValue::bool(true)]))))
271    }
272}
273
274//**************************************************************************************************
275// Coin Functions
276//**************************************************************************************************
277
278impl Value {
279    pub fn unpack_coin(self) -> Result<(ObjectID, u64), ExecutionError> {
280        let [id, balance] = unpack(self.0)?;
281        // unpack UID
282        let [id] = unpack(id)?;
283        // unpack ID
284        let [id] = unpack(id)?;
285        let id: AccountAddress = id.cast().map_err(iv("cast"))?;
286        // unpack Balance
287        let [balance] = unpack(balance)?;
288        let balance: u64 = balance.cast().map_err(iv("cast"))?;
289        Ok((ObjectID::from(id), balance))
290    }
291
292    pub fn coin_ref_value(self) -> Result<u64, ExecutionError> {
293        let balance_value_ref = borrow_coin_ref_balance_value(self.0)?;
294        let balance_value_ref: values::Reference = balance_value_ref.cast().map_err(iv("cast"))?;
295        let balance_value = balance_value_ref.read_ref().map_err(iv("read ref"))?;
296        balance_value.cast().map_err(iv("cast"))
297    }
298
299    /// The coin value MUST be checked before calling this function, if `amount` is greater than
300    /// the value of the coin, it will return an invariant violation.
301    pub fn coin_ref_subtract_balance(self, amount: u64) -> Result<(), ExecutionError> {
302        coin_ref_modify_balance(self.0, |balance| {
303            let Some(new_balance) = balance.checked_sub(amount) else {
304                invariant_violation!("coin balance {balance} is less than {amount}")
305            };
306            Ok(new_balance)
307        })
308    }
309
310    /// The coin max value MUST be checked before calling this function, if `amount` plus the current
311    /// balance is greater than `u64::MAX`, it will return an invariant violation.
312    pub fn coin_ref_add_balance(self, amount: u64) -> Result<(), ExecutionError> {
313        coin_ref_modify_balance(self.0, |balance| {
314            let Some(new_balance) = balance.checked_add(amount) else {
315                invariant_violation!("coin balance {balance} + {amount} is greater than u64::MAX")
316            };
317            Ok(new_balance)
318        })
319    }
320}
321
322fn coin_ref_modify_balance(
323    coin_ref: VMValue,
324    modify: impl FnOnce(u64) -> Result<u64, ExecutionError>,
325) -> Result<(), ExecutionError> {
326    let balance_value_ref = borrow_coin_ref_balance_value(coin_ref)?;
327    let reference: values::Reference = balance_value_ref
328        .copy_value()
329        .map_err(iv("copy"))?
330        .cast()
331        .map_err(iv("cast"))?;
332    let balance: u64 = reference
333        .read_ref()
334        .map_err(iv("read ref"))?
335        .cast()
336        .map_err(iv("cast"))?;
337    let new_balance = modify(balance)?;
338    let reference: values::Reference = balance_value_ref.cast().map_err(iv("cast"))?;
339    reference
340        .write_ref(VMValue::u64(new_balance))
341        .map_err(iv("write ref"))
342}
343
344fn borrow_coin_ref_balance_value(coin_ref: VMValue) -> Result<VMValue, ExecutionError> {
345    let coin_ref: values::StructRef = coin_ref.cast().map_err(iv("cast"))?;
346    let balance = coin_ref.borrow_field(1).map_err(iv("borrow field"))?;
347    let balance: values::StructRef = balance.cast().map_err(iv("cast"))?;
348    balance.borrow_field(0).map_err(iv("borrow field"))
349}
350
351//**************************************************************************************************
352// Upgrades
353//**************************************************************************************************
354
355impl Value {
356    pub fn upgrade_cap(cap: UpgradeCap) -> Self {
357        // public struct UpgradeCap has key, store {
358        //     id: UID,
359        //     package: ID,
360        //     version: u64,
361        //     policy: u8,
362        // }
363        let UpgradeCap {
364            id,
365            package,
366            version,
367            policy,
368        } = cap;
369        Self(VMValue::struct_(Struct::pack([
370            Self::uid(id.id.bytes.into()).0,
371            Self::id(package.bytes.into()).0,
372            VMValue::u64(version),
373            VMValue::u8(policy),
374        ])))
375    }
376
377    pub fn upgrade_receipt(receipt: UpgradeReceipt) -> Self {
378        // public struct UpgradeReceipt {
379        //     cap: ID,
380        //     package: ID,
381        // }
382        let UpgradeReceipt { cap, package } = receipt;
383        Self(VMValue::struct_(Struct::pack([
384            Self::id(cap.bytes.into()).0,
385            Self::id(package.bytes.into()).0,
386        ])))
387    }
388
389    pub fn into_upgrade_ticket(self) -> Result<UpgradeTicket, ExecutionError> {
390        //  public struct UpgradeTicket {
391        //     cap: ID,
392        //     package: ID,
393        //     policy: u8,
394        //     digest: vector<u8>,
395        // }
396        // unpack UpgradeTicket
397        let [cap, package, policy, digest] = unpack(self.0)?;
398        // unpack cap ID
399        let [cap] = unpack(cap)?;
400        let cap: AccountAddress = cap.cast().map_err(iv("cast"))?;
401        // unpack package ID
402        let [package] = unpack(package)?;
403        let package: AccountAddress = package.cast().map_err(iv("cast"))?;
404        // unpack policy
405        let policy: u8 = policy.cast().map_err(iv("cast"))?;
406        // unpack digest
407        let digest: Vec<u8> = digest.cast().map_err(iv("cast"))?;
408        Ok(UpgradeTicket {
409            cap: sui_types::id::ID::new(cap.into()),
410            package: sui_types::id::ID::new(package.into()),
411            policy,
412            digest,
413        })
414    }
415}
416
417fn unpack<const N: usize>(value: VMValue) -> Result<[VMValue; N], ExecutionError> {
418    let value: values::Struct = value.cast().map_err(iv("cast"))?;
419    let unpacked = value.unpack().map_err(iv("unpack"))?.collect::<Vec<_>>();
420    assert_invariant!(unpacked.len() == N, "Expected {N} fields, got {unpacked:?}");
421    Ok(unpacked.try_into().unwrap())
422}
423
424const fn iv(case: &str) -> impl FnOnce(PartialVMError) -> ExecutionError + use<'_> {
425    move |e| make_invariant_violation!("unexpected {case} failure {e:?}")
426}