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;
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 serialize(&self) -> Option<Vec<u8>> {
158        self.0.serialize()
159    }
160}
161
162impl From<VMValue> for Value {
163    fn from(value: VMValue) -> Self {
164        Value(value)
165    }
166}
167
168impl From<Value> for VMValue {
169    fn from(value: Value) -> Self {
170        value.0
171    }
172}
173
174impl VMValueCast<Value> for VMValue {
175    fn cast(self) -> Result<Value, PartialVMError> {
176        Ok(self.into())
177    }
178}
179
180impl ValueView for Value {
181    fn visit(&self, visitor: &mut impl move_vm_types::views::ValueVisitor) {
182        self.0.visit(visitor)
183    }
184}
185
186//**************************************************************************************************
187// Value Construction
188//**************************************************************************************************
189
190impl Value {
191    pub fn id(address: AccountAddress) -> Self {
192        // ID { address }
193        Self(VMValue::struct_(Struct::pack([VMValue::address(address)])))
194    }
195
196    pub fn uid(address: AccountAddress) -> Self {
197        // UID { ID { address } }
198        Self(VMValue::struct_(Struct::pack([Self::id(address).0])))
199    }
200
201    pub fn receiving(id: ObjectID, version: SequenceNumber) -> Self {
202        Self(VMValue::struct_(Struct::pack([
203            Self::id(id.into()).0,
204            VMValue::u64(version.into()),
205        ])))
206    }
207
208    pub fn balance(amount: u64) -> Self {
209        // Balance { amount }
210        Self(VMValue::struct_(Struct::pack([VMValue::u64(amount)])))
211    }
212
213    /// The uid _must_ be registered by the object runtime before being called
214    pub fn coin(id: ObjectID, amount: u64) -> Self {
215        Self(VMValue::struct_(Struct::pack([
216            Self::uid(id.into()).0,
217            Self::balance(amount).0,
218        ])))
219    }
220
221    pub fn vec_pack(ty: Type, values: Vec<Self>) -> Result<Self, ExecutionError> {
222        let specialization: VectorSpecialization = ty
223            .try_into()
224            .map_err(|e| make_invariant_violation!("Unable to specialize vector: {e}"))?;
225        let vec = values::Vector::pack(specialization, values.into_iter().map(|v| v.0))
226            .map_err(iv("pack"))?;
227        Ok(Self(vec))
228    }
229
230    /// Should be called once at the start of a transaction to populate the location with the
231    /// transaction context.
232    pub fn new_tx_context(digest: TransactionDigest) -> Result<Self, ExecutionError> {
233        // public struct TxContext has drop {
234        //     sender: address,
235        //     tx_hash: vector<u8>,
236        //     epoch: u64,
237        //     epoch_timestamp_ms: u64,
238        //     ids_created: u64,
239        // }
240        Ok(Self(VMValue::struct_(Struct::pack([
241            VMValue::address(AccountAddress::ZERO),
242            VMValue::vector_u8(digest.inner().iter().copied()),
243            VMValue::u64(0),
244            VMValue::u64(0),
245            VMValue::u64(0),
246        ]))))
247    }
248
249    pub fn one_time_witness() -> Result<Self, ExecutionError> {
250        // public struct <ONE_TIME_WITNESS> has drop{
251        //     _dummy: bool,
252        // }
253        Ok(Self(VMValue::struct_(Struct::pack([VMValue::bool(true)]))))
254    }
255}
256
257//**************************************************************************************************
258// Coin Functions
259//**************************************************************************************************
260
261impl Value {
262    pub fn unpack_coin(self) -> Result<(ObjectID, u64), ExecutionError> {
263        let [id, balance] = unpack(self.0)?;
264        // unpack UID
265        let [id] = unpack(id)?;
266        // unpack ID
267        let [id] = unpack(id)?;
268        let id: AccountAddress = id.cast().map_err(iv("cast"))?;
269        // unpack Balance
270        let [balance] = unpack(balance)?;
271        let balance: u64 = balance.cast().map_err(iv("cast"))?;
272        Ok((ObjectID::from(id), balance))
273    }
274
275    pub fn coin_ref_value(self) -> Result<u64, ExecutionError> {
276        let balance_value_ref = borrow_coin_ref_balance_value(self.0)?;
277        let balance_value_ref: values::Reference = balance_value_ref.cast().map_err(iv("cast"))?;
278        let balance_value = balance_value_ref.read_ref().map_err(iv("read ref"))?;
279        balance_value.cast().map_err(iv("cast"))
280    }
281
282    /// The coin value MUST be checked before calling this function, if `amount` is greater than
283    /// the value of the coin, it will return an invariant violation.
284    pub fn coin_ref_subtract_balance(self, amount: u64) -> Result<(), ExecutionError> {
285        coin_ref_modify_balance(self.0, |balance| {
286            let Some(new_balance) = balance.checked_sub(amount) else {
287                invariant_violation!("coin balance {balance} is less than {amount}")
288            };
289            Ok(new_balance)
290        })
291    }
292
293    /// The coin max value MUST be checked before calling this function, if `amount` plus the current
294    /// balance is greater than `u64::MAX`, it will return an invariant violation.
295    pub fn coin_ref_add_balance(self, amount: u64) -> Result<(), ExecutionError> {
296        coin_ref_modify_balance(self.0, |balance| {
297            let Some(new_balance) = balance.checked_add(amount) else {
298                invariant_violation!("coin balance {balance} + {amount} is greater than u64::MAX")
299            };
300            Ok(new_balance)
301        })
302    }
303}
304
305fn coin_ref_modify_balance(
306    coin_ref: VMValue,
307    modify: impl FnOnce(u64) -> Result<u64, ExecutionError>,
308) -> Result<(), ExecutionError> {
309    let balance_value_ref = borrow_coin_ref_balance_value(coin_ref)?;
310    let reference: values::Reference = balance_value_ref
311        .copy_value()
312        .map_err(iv("copy"))?
313        .cast()
314        .map_err(iv("cast"))?;
315    let balance: u64 = reference
316        .read_ref()
317        .map_err(iv("read ref"))?
318        .cast()
319        .map_err(iv("cast"))?;
320    let new_balance = modify(balance)?;
321    let reference: values::Reference = balance_value_ref.cast().map_err(iv("cast"))?;
322    reference
323        .write_ref(VMValue::u64(new_balance))
324        .map_err(iv("write ref"))
325}
326
327fn borrow_coin_ref_balance_value(coin_ref: VMValue) -> Result<VMValue, ExecutionError> {
328    let coin_ref: values::StructRef = coin_ref.cast().map_err(iv("cast"))?;
329    let balance = coin_ref.borrow_field(1).map_err(iv("borrow field"))?;
330    let balance: values::StructRef = balance.cast().map_err(iv("cast"))?;
331    balance.borrow_field(0).map_err(iv("borrow field"))
332}
333
334//**************************************************************************************************
335// Upgrades
336//**************************************************************************************************
337
338impl Value {
339    pub fn upgrade_cap(cap: UpgradeCap) -> Self {
340        // public struct UpgradeCap has key, store {
341        //     id: UID,
342        //     package: ID,
343        //     version: u64,
344        //     policy: u8,
345        // }
346        let UpgradeCap {
347            id,
348            package,
349            version,
350            policy,
351        } = cap;
352        Self(VMValue::struct_(Struct::pack([
353            Self::uid(id.id.bytes.into()).0,
354            Self::id(package.bytes.into()).0,
355            VMValue::u64(version),
356            VMValue::u8(policy),
357        ])))
358    }
359
360    pub fn upgrade_receipt(receipt: UpgradeReceipt) -> Self {
361        // public struct UpgradeReceipt {
362        //     cap: ID,
363        //     package: ID,
364        // }
365        let UpgradeReceipt { cap, package } = receipt;
366        Self(VMValue::struct_(Struct::pack([
367            Self::id(cap.bytes.into()).0,
368            Self::id(package.bytes.into()).0,
369        ])))
370    }
371
372    pub fn into_upgrade_ticket(self) -> Result<UpgradeTicket, ExecutionError> {
373        //  public struct UpgradeTicket {
374        //     cap: ID,
375        //     package: ID,
376        //     policy: u8,
377        //     digest: vector<u8>,
378        // }
379        // unpack UpgradeTicket
380        let [cap, package, policy, digest] = unpack(self.0)?;
381        // unpack cap ID
382        let [cap] = unpack(cap)?;
383        let cap: AccountAddress = cap.cast().map_err(iv("cast"))?;
384        // unpack package ID
385        let [package] = unpack(package)?;
386        let package: AccountAddress = package.cast().map_err(iv("cast"))?;
387        // unpack policy
388        let policy: u8 = policy.cast().map_err(iv("cast"))?;
389        // unpack digest
390        let digest: Vec<u8> = digest.cast().map_err(iv("cast"))?;
391        Ok(UpgradeTicket {
392            cap: sui_types::id::ID::new(cap.into()),
393            package: sui_types::id::ID::new(package.into()),
394            policy,
395            digest,
396        })
397    }
398}
399
400fn unpack<const N: usize>(value: VMValue) -> Result<[VMValue; N], ExecutionError> {
401    let value: values::Struct = value.cast().map_err(iv("cast"))?;
402    let unpacked = value.unpack().map_err(iv("unpack"))?.collect::<Vec<_>>();
403    assert_invariant!(unpacked.len() == N, "Expected {N} fields, got {unpacked:?}");
404    Ok(unpacked.try_into().unwrap())
405}
406
407const fn iv(case: &str) -> impl FnOnce(PartialVMError) -> ExecutionError + use<'_> {
408    move |e| make_invariant_violation!("unexpected {case} failure {e:?}")
409}