sui_adapter_latest/static_programmable_transactions/execution/
values.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
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::collections::BTreeMap;

use crate::static_programmable_transactions::{env::Env, typing::ast::Type};
use move_binary_format::errors::PartialVMError;
use move_core_types::account_address::AccountAddress;
use move_vm_types::{
    values::{
        self, Locals as VMLocals, Struct, VMValueCast, Value as VMValue, VectorSpecialization,
    },
    views::ValueView,
};
use sui_types::{
    base_types::{ObjectID, SequenceNumber},
    digests::TransactionDigest,
    error::ExecutionError,
    move_package::{UpgradeCap, UpgradeReceipt, UpgradeTicket},
    object::Owner,
};
pub enum InputValue<'a> {
    Bytes(&'a ByteValue),
    Loaded(Local<'a>),
}

pub enum InitialInput {
    Bytes(ByteValue),
    Object(InputObjectMetadata, Value),
}

pub enum ByteValue {
    Pure(Vec<u8>),
    Receiving {
        id: ObjectID,
        version: SequenceNumber,
    },
}

#[derive(Clone, Debug)]
pub struct InputObjectMetadata {
    pub id: ObjectID,
    pub is_mutable_input: bool,
    pub owner: Owner,
    pub version: SequenceNumber,
    pub type_: Type,
}

pub struct InputObjectValue {
    pub object_metadata: InputObjectMetadata,
    pub value: Option<Value>,
}

pub struct Inputs {
    metadata: BTreeMap<u16, InputObjectMetadata>,
    byte_values: BTreeMap<u16, ByteValue>,
    locals: Locals,
}

/// A memory location that can be borrowed or moved from
pub struct Local<'a>(&'a mut Locals, u16);

/// A set of memory locations that can be borrowed or moved from. Used for inputs and results
pub struct Locals(VMLocals);

#[derive(Debug)]
pub struct Value(VMValue);

impl Inputs {
    pub fn new<Items>(values: Items) -> Result<Self, ExecutionError>
    where
        Items: IntoIterator<Item = InitialInput>,
        Items::IntoIter: ExactSizeIterator,
    {
        let values = values.into_iter();
        let n = values.len();
        assert_invariant!(n <= u16::MAX as usize, "Locals size exceeds u16::MAX");
        let mut locals = VMLocals::new(n);
        let mut metadata = BTreeMap::new();
        let mut byte_values = BTreeMap::new();
        for (i, value) in values.enumerate() {
            match value {
                InitialInput::Bytes(byte_value) => {
                    byte_values.insert(i as u16, byte_value);
                }
                InitialInput::Object(object_metadata, value) => {
                    metadata.insert(i as u16, object_metadata);
                    locals
                        .store_loc(i, value.0, /* violation check */ true)
                        .map_err(iv("store loc"))?;
                }
            }
        }
        Ok(Self {
            metadata,
            byte_values,
            locals: Locals(locals),
        })
    }

    /// Is the input a non-fixed byte value?
    /// Once it is fixed, it will be a loaded value and this will return false
    pub fn is_bytes(&self, index: u16) -> bool {
        self.byte_values.contains_key(&index)
    }

    /// Retrieve an input, either a loaded value or a byte value
    pub fn get(&mut self, index: u16) -> Result<InputValue, ExecutionError> {
        Ok(match self.byte_values.get(&index) {
            Some(byte_value) => InputValue::Bytes(byte_value),
            None => InputValue::Loaded(self.locals.local(index)?),
        })
    }

    /// Fix a byte value to a loaded value
    pub fn fix(&mut self, index: u16, value: Value) -> Result<(), ExecutionError> {
        let byte_value = self.byte_values.remove(&index);
        assert_invariant!(
            byte_value.is_some(),
            "Cannot fix a value that is not a byte value"
        );
        self.locals
            .0
            .store_loc(index as usize, value.0, /* violation check */ true)
            .map_err(iv("store loc"))?;
        Ok(())
    }

    /// Collect object data and the value, if it was not moved
    pub fn into_objects(self) -> Result<Vec<(InputObjectMetadata, Option<Value>)>, ExecutionError> {
        let Self {
            metadata,
            byte_values: _,
            mut locals,
        } = self;

        metadata
            .into_iter()
            .map(|(i, object_metadata)| {
                let mut local = locals.local(i)?;
                let value = if local.is_invalid()? {
                    // Object was moved, nothing to take
                    None
                } else {
                    // Object was not moved, take the value
                    Some(local.move_()?)
                };
                Ok((object_metadata, value))
            })
            .collect()
    }
}

impl Locals {
    pub fn new<Items>(values: Items) -> Result<Self, ExecutionError>
    where
        Items: IntoIterator<Item = Value>,
        Items::IntoIter: ExactSizeIterator,
    {
        let values = values.into_iter();
        let n = values.len();
        assert_invariant!(n <= u16::MAX as usize, "Locals size exceeds u16::MAX");
        let mut locals = VMLocals::new(n);
        for (i, value) in values.enumerate() {
            locals
                .store_loc(i, value.0, /* violation check */ true)
                .map_err(iv("store loc"))?;
        }
        Ok(Self(locals))
    }

    pub fn local(&mut self, index: u16) -> Result<Local, ExecutionError> {
        Ok(Local(self, index))
    }
}

impl Local<'_> {
    /// Does the local contain a value?
    pub fn is_invalid(&self) -> Result<bool, ExecutionError> {
        self.0
            .0
            .is_invalid(self.1 as usize)
            .map_err(iv("out of bounds"))
    }

    /// Move the value out of the local
    pub fn move_(&mut self) -> Result<Value, ExecutionError> {
        assert_invariant!(!self.is_invalid()?, "cannot move invalid local");
        Ok(Value(
            self.0
                .0
                .move_loc(self.1 as usize, /* violation check */ true)
                .map_err(iv("move loc"))?,
        ))
    }

    /// Copy the value out in the local
    pub fn copy(&self) -> Result<Value, ExecutionError> {
        assert_invariant!(!self.is_invalid()?, "cannot copy invalid local");
        Ok(Value(
            self.0.0.copy_loc(self.1 as usize).map_err(iv("copy loc"))?,
        ))
    }

    /// Borrow the local, creating a reference to the value
    pub fn borrow(&self) -> Result<Value, ExecutionError> {
        assert_invariant!(!self.is_invalid()?, "cannot borrow invalid local");
        Ok(Value(
            self.0
                .0
                .borrow_loc(self.1 as usize)
                .map_err(iv("borrow loc"))?,
        ))
    }
}

impl Value {
    pub fn copy(&self) -> Result<Self, ExecutionError> {
        Ok(Value(self.0.copy_value().map_err(iv("copy"))?))
    }

    /// Read the value, giving an invariant violation if the value is not a reference
    pub fn read_ref(self) -> Result<Self, ExecutionError> {
        let value: values::Reference = self.0.cast().map_err(iv("cast"))?;
        Ok(Self(value.read_ref().map_err(iv("read ref"))?))
    }

    /// This function will invariant violation on an invalid cast
    pub fn cast<V>(self) -> Result<V, ExecutionError>
    where
        VMValue: VMValueCast<V>,
    {
        self.0.cast().map_err(iv("cast"))
    }

    pub fn deserialize(env: &Env, bytes: &[u8], ty: Type) -> Result<Value, ExecutionError> {
        let layout = env.runtime_layout(&ty)?;
        let Some(value) = VMValue::simple_deserialize(bytes, &layout) else {
            // we already checked the layout of pure bytes during typing
            // and objects should already be valid
            invariant_violation!("unable to deserialize value to type {ty:?}")
        };
        Ok(Value(value))
    }

    pub fn serialize(&self) -> Option<Vec<u8>> {
        self.0.serialize()
    }
}

impl From<VMValue> for Value {
    fn from(value: VMValue) -> Self {
        Value(value)
    }
}

impl From<Value> for VMValue {
    fn from(value: Value) -> Self {
        value.0
    }
}

impl VMValueCast<Value> for VMValue {
    fn cast(self) -> Result<Value, PartialVMError> {
        Ok(self.into())
    }
}

impl ValueView for Value {
    fn visit(&self, visitor: &mut impl move_vm_types::views::ValueVisitor) {
        self.0.visit(visitor)
    }
}

//**************************************************************************************************
// Value Construction
//**************************************************************************************************

impl Value {
    pub fn id(address: AccountAddress) -> Self {
        // ID { address }
        Self(VMValue::struct_(Struct::pack([VMValue::address(address)])))
    }

    pub fn uid(address: AccountAddress) -> Self {
        // UID { ID { address } }
        Self(VMValue::struct_(Struct::pack([Self::id(address).0])))
    }

    pub fn receiving(id: ObjectID, version: SequenceNumber) -> Self {
        Self(VMValue::struct_(Struct::pack([
            Self::id(id.into()).0,
            VMValue::u64(version.into()),
        ])))
    }

    pub fn balance(amount: u64) -> Self {
        // Balance { amount }
        Self(VMValue::struct_(Struct::pack([VMValue::u64(amount)])))
    }

    /// The uid _must_ be registered by the object runtime before being called
    pub fn coin(id: ObjectID, amount: u64) -> Self {
        Self(VMValue::struct_(Struct::pack([
            Self::uid(id.into()).0,
            Self::balance(amount).0,
        ])))
    }

    pub fn vec_pack(ty: Type, values: Vec<Self>) -> Result<Self, ExecutionError> {
        let specialization: VectorSpecialization = ty
            .try_into()
            .map_err(|e| make_invariant_violation!("Unable to specialize vector: {e}"))?;
        let vec = values::Vector::pack(specialization, values.into_iter().map(|v| v.0))
            .map_err(iv("pack"))?;
        Ok(Self(vec))
    }

    pub fn tx_context(digest: TransactionDigest) -> Result<Self, ExecutionError> {
        // public struct TxContext has drop {
        //     sender: address,
        //     tx_hash: vector<u8>,
        //     epoch: u64,
        //     epoch_timestamp_ms: u64,
        //     ids_created: u64,
        // }
        Ok(Self(VMValue::struct_(Struct::pack([
            VMValue::address(AccountAddress::ZERO),
            VMValue::vector_u8(digest.inner().iter().copied()),
            VMValue::u64(0),
            VMValue::u64(0),
            VMValue::u64(0),
        ]))))
    }

    pub fn one_time_witness() -> Result<Self, ExecutionError> {
        // public struct <ONE_TIME_WITNESS> has drop{
        //     _dummy: bool,
        // }
        Ok(Self(VMValue::struct_(Struct::pack([VMValue::bool(true)]))))
    }
}

//**************************************************************************************************
// Coin Functions
//**************************************************************************************************

impl Value {
    pub fn unpack_coin(self) -> Result<(ObjectID, u64), ExecutionError> {
        let [id, balance] = unpack(self.0)?;
        // unpack UID
        let [id] = unpack(id)?;
        // unpack ID
        let [id] = unpack(id)?;
        let id: AccountAddress = id.cast().map_err(iv("cast"))?;
        // unpack Balance
        let [balance] = unpack(balance)?;
        let balance: u64 = balance.cast().map_err(iv("cast"))?;
        Ok((ObjectID::from(id), balance))
    }

    pub fn coin_ref_value(self) -> Result<u64, ExecutionError> {
        let balance_value_ref = borrow_coin_ref_balance_value(self.0)?;
        let balance_value_ref: values::Reference = balance_value_ref.cast().map_err(iv("cast"))?;
        let balance_value = balance_value_ref.read_ref().map_err(iv("read ref"))?;
        balance_value.cast().map_err(iv("cast"))
    }

    /// The coin value MUST be checked before calling this function, if `amount` is greater than
    /// the value of the coin, it will return an invariant violation.
    pub fn coin_ref_subtract_balance(self, amount: u64) -> Result<(), ExecutionError> {
        coin_ref_modify_balance(self.0, |balance| {
            let Some(new_balance) = balance.checked_sub(amount) else {
                invariant_violation!("coin balance {balance} is less than {amount}")
            };
            Ok(new_balance)
        })
    }

    /// The coin max value MUST be checked before calling this function, if `amount` plus the current
    /// balance is greater than `u64::MAX`, it will return an invariant violation.
    pub fn coin_ref_add_balance(self, amount: u64) -> Result<(), ExecutionError> {
        coin_ref_modify_balance(self.0, |balance| {
            let Some(new_balance) = balance.checked_add(amount) else {
                invariant_violation!("coin balance {balance} + {amount} is greater than u64::MAX")
            };
            Ok(new_balance)
        })
    }
}

fn coin_ref_modify_balance(
    coin_ref: VMValue,
    modify: impl FnOnce(u64) -> Result<u64, ExecutionError>,
) -> Result<(), ExecutionError> {
    let balance_value_ref = borrow_coin_ref_balance_value(coin_ref)?;
    let reference: values::Reference = balance_value_ref
        .copy_value()
        .map_err(iv("copy"))?
        .cast()
        .map_err(iv("cast"))?;
    let balance: u64 = reference
        .read_ref()
        .map_err(iv("read ref"))?
        .cast()
        .map_err(iv("cast"))?;
    let new_balance = modify(balance)?;
    let reference: values::Reference = balance_value_ref.cast().map_err(iv("cast"))?;
    reference
        .write_ref(VMValue::u64(new_balance))
        .map_err(iv("write ref"))
}

fn borrow_coin_ref_balance_value(coin_ref: VMValue) -> Result<VMValue, ExecutionError> {
    let coin_ref: values::StructRef = coin_ref.cast().map_err(iv("cast"))?;
    let balance = coin_ref.borrow_field(1).map_err(iv("borrow field"))?;
    let balance: values::StructRef = balance.cast().map_err(iv("cast"))?;
    balance.borrow_field(0).map_err(iv("borrow field"))
}

//**************************************************************************************************
// Upgrades
//**************************************************************************************************

impl Value {
    pub fn upgrade_cap(cap: UpgradeCap) -> Self {
        // public struct UpgradeCap has key, store {
        //     id: UID,
        //     package: ID,
        //     version: u64,
        //     policy: u8,
        // }
        let UpgradeCap {
            id,
            package,
            version,
            policy,
        } = cap;
        Self(VMValue::struct_(Struct::pack([
            Self::uid(id.id.bytes.into()).0,
            Self::id(package.bytes.into()).0,
            VMValue::u64(version),
            VMValue::u8(policy),
        ])))
    }

    pub fn upgrade_receipt(receipt: UpgradeReceipt) -> Self {
        // public struct UpgradeReceipt {
        //     cap: ID,
        //     package: ID,
        // }
        let UpgradeReceipt { cap, package } = receipt;
        Self(VMValue::struct_(Struct::pack([
            Self::id(cap.bytes.into()).0,
            Self::id(package.bytes.into()).0,
        ])))
    }

    pub fn into_upgrade_ticket(self) -> Result<UpgradeTicket, ExecutionError> {
        //  public struct UpgradeTicket {
        //     cap: ID,
        //     package: ID,
        //     policy: u8,
        //     digest: vector<u8>,
        // }
        // unpack UpgradeTicket
        let [cap, package, policy, digest] = unpack(self.0)?;
        // unpack cap ID
        let [cap] = unpack(cap)?;
        let cap: AccountAddress = cap.cast().map_err(iv("cast"))?;
        // unpack package ID
        let [package] = unpack(package)?;
        let package: AccountAddress = package.cast().map_err(iv("cast"))?;
        // unpack policy
        let policy: u8 = policy.cast().map_err(iv("cast"))?;
        // unpack digest
        let digest: Vec<u8> = digest.cast().map_err(iv("cast"))?;
        Ok(UpgradeTicket {
            cap: sui_types::id::ID::new(cap.into()),
            package: sui_types::id::ID::new(package.into()),
            policy,
            digest,
        })
    }
}

fn unpack<const N: usize>(value: VMValue) -> Result<[VMValue; N], ExecutionError> {
    let value: values::Struct = value.cast().map_err(iv("cast"))?;
    let unpacked = value.unpack().map_err(iv("unpack"))?.collect::<Vec<_>>();
    assert_invariant!(unpacked.len() == N, "Expected {N} fields, got {unpacked:?}");
    Ok(unpacked.try_into().unwrap())
}

const fn iv(case: &str) -> impl FnOnce(PartialVMError) -> ExecutionError + use<'_> {
    move |e| make_invariant_violation!("unexpected {case} failure {e:?}")
}