1use crate::{
5 execution_mode::ExecutionMode,
6 static_programmable_transactions::{env::Env, typing::ast as T},
7};
8use sui_types::error::ExecutionError;
9
10pub fn refine_and_verify<Mode: ExecutionMode>(
14 env: &Env,
15 ast: &mut T::Transaction,
16) -> Result<(), ExecutionError> {
17 refine::transaction(env, ast)?;
18 verify::transaction::<Mode>(env, ast)?;
19 Ok(())
20}
21
22mod refine {
23 use sui_types::{
24 coin::{COIN_MODULE_NAME, SEND_FUNDS_FUNC_NAME},
25 error::ExecutionError,
26 };
27
28 use crate::{
29 sp,
30 static_programmable_transactions::{
31 env::Env,
32 spanned::sp,
33 typing::{
34 ast::{self as T, Type},
35 translate::coin_inner_type,
36 },
37 },
38 };
39 use std::collections::BTreeSet;
40
41 struct Context {
42 used: BTreeSet<T::Location>,
44 moved: BTreeSet<T::Location>,
48 }
49
50 impl Context {
51 fn new() -> Self {
52 Self {
53 used: BTreeSet::new(),
54 moved: BTreeSet::new(),
55 }
56 }
57 }
58
59 pub fn transaction(env: &Env, ast: &mut T::Transaction) -> Result<(), ExecutionError> {
62 let mut context = Context::new();
63 for c in ast.commands.iter_mut().rev() {
64 command(&mut context, c);
65 }
66 return_unused_withdrawal_conversions(env, ast, &context.moved)
67 }
68
69 fn command(context: &mut Context, sp!(_, c): &mut T::Command) {
70 match &mut c.command {
71 T::Command__::MoveCall(mc) => arguments(context, &mut mc.arguments),
72 T::Command__::TransferObjects(objects, recipient) => {
73 argument(context, recipient);
74 arguments(context, objects);
75 }
76 T::Command__::SplitCoins(_, coin, amounts) => {
77 arguments(context, amounts);
78 argument(context, coin);
79 }
80 T::Command__::MergeCoins(_, target, coins) => {
81 arguments(context, coins);
82 argument(context, target);
83 }
84 T::Command__::MakeMoveVec(_, xs) => arguments(context, xs),
85 T::Command__::Publish(_, _, _) => (),
86 T::Command__::Upgrade(_, _, _, x, _) => argument(context, x),
87 }
88 }
89
90 fn arguments(context: &mut Context, args: &mut [T::Argument]) {
91 for arg in args.iter_mut().rev() {
92 argument(context, arg)
93 }
94 }
95
96 fn argument(context: &mut Context, arg: &mut T::Argument) {
97 let usage = match &mut arg.value.0 {
98 T::Argument__::Use(u) | T::Argument__::Read(u) | T::Argument__::Freeze(u) => u,
99 T::Argument__::Borrow(_, loc) => {
100 context.used.insert(*loc);
102 return;
103 }
104 };
105 match &usage {
106 T::Usage::Move(loc) => {
107 context.used.insert(*loc);
109 context.moved.insert(*loc);
110 }
111 T::Usage::Copy { location, borrowed } => {
112 let location = *location;
114 let last_usage = context.used.insert(location);
115 if last_usage && !borrowed.get().unwrap() {
116 *usage = T::Usage::Move(location);
118 context.moved.insert(location);
119 }
120 }
121 }
122 }
123
124 fn return_unused_withdrawal_conversions(
127 env: &Env,
128 ast: &mut T::Transaction,
129 moved_locations: &BTreeSet<T::Location>,
130 ) -> Result<(), ExecutionError> {
131 assert_invariant!(
133 ast.withdrawal_compatibility_conversions.is_empty()
134 || env.protocol_config.enable_accumulators(),
135 "Withdrawal conversions should be empty if accumulators are not enabled"
136 );
137 for conversion_info in
138 ast.withdrawal_compatibility_conversions
139 .values()
140 .filter(|conversion| {
141 let conversion_location = T::Location::Result(conversion.conversion_result, 0);
144 !moved_locations.contains(&conversion_location)
145 })
146 {
147 let Some(cur_command) = ast.commands.len().checked_sub(1) else {
148 invariant_violation!("cannot be zero commands with a conversion")
149 };
150 let cur_command = checked_as!(cur_command, u16)?;
151 let T::WithdrawalCompatibilityConversion {
152 owner,
153 conversion_result,
154 } = *conversion_info;
155 let Some(conversion_command) = ast.commands.get(conversion_result as usize) else {
156 invariant_violation!("conversion result should be a valid command index")
157 };
158 assert_invariant!(
159 conversion_command.value.result_type.len() == 1,
160 "conversion should have one result"
161 );
162 let T::Location::PureInput(owner_pure_idx) = owner else {
163 invariant_violation!("owner should be a pure input")
164 };
165 assert_invariant!(
166 ast.pure.len() > owner_pure_idx as usize,
167 "owner pure input index out of bounds"
168 );
169 assert_invariant!(
170 ast.pure.get(owner_pure_idx as usize).unwrap().ty == T::Type::Address,
171 "owner pure input should be an address"
172 );
173 let Some(conversion_ty) = conversion_command.value.result_type.first() else {
174 invariant_violation!("conversion should have a result type")
175 };
176 let Some(inner_ty) = coin_inner_type(conversion_ty) else {
177 invariant_violation!("conversion result should be a coin type")
178 };
179 let move_result_ = T::Argument__::new_move(T::Location::Result(conversion_result, 0));
180 let move_result = sp(cur_command, (move_result_, conversion_ty.clone()));
181 let owner_ty = Type::Address;
182 let owner_arg_ = T::Argument__::new_move(owner);
183 let owner_arg = sp(cur_command, (owner_arg_, owner_ty));
184 let return_command__ = T::Command__::MoveCall(Box::new(T::MoveCall {
185 function: env.load_framework_function(
186 COIN_MODULE_NAME,
187 SEND_FUNDS_FUNC_NAME,
188 vec![inner_ty.clone()],
189 )?,
190 arguments: vec![move_result, owner_arg],
191 }));
192 let return_command = sp(
193 cur_command,
194 T::Command_ {
195 command: return_command__,
196 result_type: vec![],
197 drop_values: vec![],
198 consumed_shared_objects: vec![],
199 },
200 );
201 ast.commands.push(return_command);
202 }
203 Ok(())
204 }
205}
206
207mod verify {
208 use crate::{
209 execution_mode::ExecutionMode,
210 sp,
211 static_programmable_transactions::{
212 env::Env,
213 typing::ast::{self as T, Type},
214 },
215 };
216 use sui_types::error::{ExecutionError, SafeIndex};
217 use sui_types::execution_status::ExecutionErrorKind;
218
219 #[must_use]
220 struct Value;
221
222 struct Context {
223 tx_context: Option<Value>,
224 gas_coin: Option<Value>,
225 objects: Vec<Option<Value>>,
226 withdrawals: Vec<Option<Value>>,
227 pure: Vec<Option<Value>>,
228 receiving: Vec<Option<Value>>,
229 results: Vec<Vec<Option<Value>>>,
230 }
231
232 impl Context {
233 fn new(_env: &Env, ast: &T::Transaction) -> Result<Self, ExecutionError> {
234 let objects = ast.objects.iter().map(|_| Some(Value)).collect::<Vec<_>>();
235 let withdrawals = ast
236 .withdrawals
237 .iter()
238 .map(|_| Some(Value))
239 .collect::<Vec<_>>();
240 let pure = ast.pure.iter().map(|_| Some(Value)).collect::<Vec<_>>();
241 let receiving = ast
242 .receiving
243 .iter()
244 .map(|_| Some(Value))
245 .collect::<Vec<_>>();
246 let gas_coin = if ast.gas_payment.is_none() {
247 None
248 } else {
249 Some(Value)
250 };
251 Ok(Self {
252 tx_context: Some(Value),
253 gas_coin,
254 objects,
255 withdrawals,
256 pure,
257 receiving,
258 results: Vec::with_capacity(ast.commands.len()),
259 })
260 }
261
262 fn location(&mut self, l: T::Location) -> Result<&mut Option<Value>, ExecutionError> {
263 Ok(match l {
264 T::Location::TxContext => &mut self.tx_context,
265 T::Location::GasCoin => &mut self.gas_coin,
266 T::Location::ObjectInput(i) => self.objects.safe_get_mut(i as usize)?,
267 T::Location::WithdrawalInput(i) => self.withdrawals.safe_get_mut(i as usize)?,
268 T::Location::PureInput(i) => self.pure.safe_get_mut(i as usize)?,
269 T::Location::ReceivingInput(i) => self.receiving.safe_get_mut(i as usize)?,
270 T::Location::Result(i, j) => self
271 .results
272 .safe_get_mut(i as usize)?
273 .safe_get_mut(j as usize)?,
274 })
275 }
276 }
277
278 pub fn transaction<Mode: ExecutionMode>(
281 env: &Env,
282 ast: &T::Transaction,
283 ) -> Result<(), ExecutionError> {
284 let mut context = Context::new(env, ast)?;
285 let commands = &ast.commands;
286 for c in commands {
287 let result =
288 command(&mut context, c).map_err(|e| e.with_command_index(c.idx as usize))?;
289 assert_invariant!(
290 result.len() == c.value.result_type.len(),
291 "result length mismatch"
292 );
293 assert_invariant!(
295 result.len() == c.value.drop_values.len(),
296 "drop values length mismatch"
297 );
298 let result_values = result
299 .into_iter()
300 .zip(c.value.drop_values.iter().copied())
301 .map(|(v, drop)| {
302 if !drop {
303 Some(v)
304 } else {
305 consume_value(v);
306 None
307 }
308 })
309 .collect();
310 context.results.push(result_values);
311 }
312
313 let Context {
314 tx_context,
315 gas_coin,
316 objects,
317 withdrawals,
318 pure,
319 receiving,
320 results,
321 } = context;
322 consume_value_opt(gas_coin);
323 consume_value_opts(objects);
325 consume_value_opts(withdrawals);
326 consume_value_opts(pure);
327 consume_value_opts(receiving);
328 assert_invariant!(results.len() == commands.len(), "result length mismatch");
329 for (i, (result, c)) in results.into_iter().zip(&ast.commands).enumerate() {
330 let tys = &c.value.result_type;
331 assert_invariant!(result.len() == tys.len(), "result length mismatch");
332 for (j, (vopt, ty)) in result.into_iter().zip(tys).enumerate() {
333 drop_value_opt::<Mode>((i, j), vopt, ty)?;
334 }
335 }
336 assert_invariant!(tx_context.is_some(), "tx_context should never be moved");
337 Ok(())
338 }
339
340 fn command(
341 context: &mut Context,
342 sp!(_, c): &T::Command,
343 ) -> Result<Vec<Value>, ExecutionError> {
344 let result_tys = &c.result_type;
345 Ok(match &c.command {
346 T::Command__::MoveCall(mc) => {
347 let T::MoveCall {
348 function,
349 arguments: args,
350 } = &**mc;
351 let return_ = &function.signature.return_;
352 let arg_values = arguments(context, args)?;
353 consume_values(arg_values);
354 (0..return_.len()).map(|_| Value).collect()
355 }
356 T::Command__::TransferObjects(objects, recipient) => {
357 let object_values = arguments(context, objects)?;
358 let recipient_value = argument(context, recipient)?;
359 consume_values(object_values);
360 consume_value(recipient_value);
361 vec![]
362 }
363 T::Command__::SplitCoins(_, coin, amounts) => {
364 let coin_value = argument(context, coin)?;
365 let amount_values = arguments(context, amounts)?;
366 consume_values(amount_values);
367 consume_value(coin_value);
368 (0..amounts.len()).map(|_| Value).collect()
369 }
370 T::Command__::MergeCoins(_, target, coins) => {
371 let target_value = argument(context, target)?;
372 let coin_values = arguments(context, coins)?;
373 consume_values(coin_values);
374 consume_value(target_value);
375 vec![]
376 }
377 T::Command__::MakeMoveVec(_, xs) => {
378 let vs = arguments(context, xs)?;
379 consume_values(vs);
380 vec![Value]
381 }
382 T::Command__::Publish(_, _, _) => result_tys.iter().map(|_| Value).collect(),
383 T::Command__::Upgrade(_, _, _, x, _) => {
384 let v = argument(context, x)?;
385 consume_value(v);
386 vec![Value]
387 }
388 })
389 }
390
391 fn consume_values(_: Vec<Value>) {}
392
393 fn consume_value(_: Value) {}
394
395 fn consume_value_opts(_: Vec<Option<Value>>) {}
396
397 fn consume_value_opt(_: Option<Value>) {}
398
399 fn drop_value_opt<Mode: ExecutionMode>(
400 idx: (usize, usize),
401 value: Option<Value>,
402 ty: &Type,
403 ) -> Result<(), ExecutionError> {
404 match value {
405 Some(v) => drop_value::<Mode>(idx, v, ty),
406 None => Ok(()),
407 }
408 }
409
410 fn drop_value<Mode: ExecutionMode>(
411 (i, j): (usize, usize),
412 value: Value,
413 ty: &Type,
414 ) -> Result<(), ExecutionError> {
415 let abilities = ty.abilities();
416 if !abilities.has_drop() && !Mode::allow_arbitrary_values() {
417 let msg = if abilities.has_copy() {
418 "The value has copy, but not drop. \
419 Its last usage must be by-value so it can be taken."
420 } else {
421 "Unused value without drop"
422 };
423 return Err(ExecutionError::new_with_source(
424 ExecutionErrorKind::UnusedValueWithoutDrop {
425 result_idx: checked_as!(i, u16)?,
426 secondary_idx: checked_as!(j, u16)?,
427 },
428 msg,
429 ));
430 }
431 consume_value(value);
432 Ok(())
433 }
434
435 fn arguments(context: &mut Context, xs: &[T::Argument]) -> Result<Vec<Value>, ExecutionError> {
436 xs.iter().map(|x| argument(context, x)).collect()
437 }
438
439 fn argument(context: &mut Context, sp!(_, x): &T::Argument) -> Result<Value, ExecutionError> {
440 match &x.0 {
441 T::Argument__::Use(T::Usage::Move(location)) => move_value(context, *location),
442 T::Argument__::Use(T::Usage::Copy { location, .. }) => copy_value(context, *location),
443 T::Argument__::Borrow(_, location) => borrow_location(context, *location),
444 T::Argument__::Read(usage) => read_ref(context, usage),
445 T::Argument__::Freeze(usage) => freeze_ref(context, usage),
446 }
447 }
448
449 fn move_value(context: &mut Context, l: T::Location) -> Result<Value, ExecutionError> {
450 let Some(value) = context.location(l)?.take() else {
451 invariant_violation!("memory safety should have failed")
452 };
453 Ok(value)
454 }
455
456 fn copy_value(context: &mut Context, l: T::Location) -> Result<Value, ExecutionError> {
457 assert_invariant!(
458 context.location(l)?.is_some(),
459 "memory safety should have failed"
460 );
461 Ok(Value)
462 }
463
464 fn borrow_location(context: &mut Context, l: T::Location) -> Result<Value, ExecutionError> {
465 assert_invariant!(
466 context.location(l)?.is_some(),
467 "memory safety should have failed"
468 );
469 Ok(Value)
470 }
471
472 fn read_ref(context: &mut Context, u: &T::Usage) -> Result<Value, ExecutionError> {
473 let value = match u {
474 T::Usage::Move(l) => move_value(context, *l)?,
475 T::Usage::Copy { location, .. } => copy_value(context, *location)?,
476 };
477 consume_value(value);
478 Ok(Value)
479 }
480
481 fn freeze_ref(context: &mut Context, u: &T::Usage) -> Result<Value, ExecutionError> {
482 let value = match u {
483 T::Usage::Move(l) => move_value(context, *l)?,
484 T::Usage::Copy { location, .. } => copy_value(context, *location)?,
485 };
486 consume_value(value);
487 Ok(Value)
488 }
489}