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_coin.is_none()
247 && env.protocol_config.gasless_transaction_drop_safety()
248 {
249 None
250 } else {
251 Some(Value)
252 };
253 Ok(Self {
254 tx_context: Some(Value),
255 gas_coin,
256 objects,
257 withdrawals,
258 pure,
259 receiving,
260 results: Vec::with_capacity(ast.commands.len()),
261 })
262 }
263
264 fn location(&mut self, l: T::Location) -> Result<&mut Option<Value>, ExecutionError> {
265 Ok(match l {
266 T::Location::TxContext => &mut self.tx_context,
267 T::Location::GasCoin => &mut self.gas_coin,
268 T::Location::ObjectInput(i) => self.objects.safe_get_mut(i as usize)?,
269 T::Location::WithdrawalInput(i) => self.withdrawals.safe_get_mut(i as usize)?,
270 T::Location::PureInput(i) => self.pure.safe_get_mut(i as usize)?,
271 T::Location::ReceivingInput(i) => self.receiving.safe_get_mut(i as usize)?,
272 T::Location::Result(i, j) => self
273 .results
274 .safe_get_mut(i as usize)?
275 .safe_get_mut(j as usize)?,
276 })
277 }
278 }
279
280 pub fn transaction<Mode: ExecutionMode>(
283 env: &Env,
284 ast: &T::Transaction,
285 ) -> Result<(), ExecutionError> {
286 let mut context = Context::new(env, ast)?;
287 let commands = &ast.commands;
288 for c in commands {
289 let result =
290 command(&mut context, c).map_err(|e| e.with_command_index(c.idx as usize))?;
291 assert_invariant!(
292 result.len() == c.value.result_type.len(),
293 "result length mismatch"
294 );
295 assert_invariant!(
297 result.len() == c.value.drop_values.len(),
298 "drop values length mismatch"
299 );
300 let result_values = result
301 .into_iter()
302 .zip(c.value.drop_values.iter().copied())
303 .map(|(v, drop)| {
304 if !drop {
305 Some(v)
306 } else {
307 consume_value(v);
308 None
309 }
310 })
311 .collect();
312 context.results.push(result_values);
313 }
314
315 let Context {
316 tx_context,
317 gas_coin,
318 objects,
319 withdrawals,
320 pure,
321 receiving,
322 results,
323 } = context;
324 consume_value_opt(gas_coin);
325 consume_value_opts(objects);
327 consume_value_opts(withdrawals);
328 consume_value_opts(pure);
329 consume_value_opts(receiving);
330 assert_invariant!(results.len() == commands.len(), "result length mismatch");
331 for (i, (result, c)) in results.into_iter().zip(&ast.commands).enumerate() {
332 let tys = &c.value.result_type;
333 assert_invariant!(result.len() == tys.len(), "result length mismatch");
334 for (j, (vopt, ty)) in result.into_iter().zip(tys).enumerate() {
335 drop_value_opt::<Mode>((i, j), vopt, ty)?;
336 }
337 }
338 assert_invariant!(tx_context.is_some(), "tx_context should never be moved");
339 Ok(())
340 }
341
342 fn command(
343 context: &mut Context,
344 sp!(_, c): &T::Command,
345 ) -> Result<Vec<Value>, ExecutionError> {
346 let result_tys = &c.result_type;
347 Ok(match &c.command {
348 T::Command__::MoveCall(mc) => {
349 let T::MoveCall {
350 function,
351 arguments: args,
352 } = &**mc;
353 let return_ = &function.signature.return_;
354 let arg_values = arguments(context, args)?;
355 consume_values(arg_values);
356 (0..return_.len()).map(|_| Value).collect()
357 }
358 T::Command__::TransferObjects(objects, recipient) => {
359 let object_values = arguments(context, objects)?;
360 let recipient_value = argument(context, recipient)?;
361 consume_values(object_values);
362 consume_value(recipient_value);
363 vec![]
364 }
365 T::Command__::SplitCoins(_, coin, amounts) => {
366 let coin_value = argument(context, coin)?;
367 let amount_values = arguments(context, amounts)?;
368 consume_values(amount_values);
369 consume_value(coin_value);
370 (0..amounts.len()).map(|_| Value).collect()
371 }
372 T::Command__::MergeCoins(_, target, coins) => {
373 let target_value = argument(context, target)?;
374 let coin_values = arguments(context, coins)?;
375 consume_values(coin_values);
376 consume_value(target_value);
377 vec![]
378 }
379 T::Command__::MakeMoveVec(_, xs) => {
380 let vs = arguments(context, xs)?;
381 consume_values(vs);
382 vec![Value]
383 }
384 T::Command__::Publish(_, _, _) => result_tys.iter().map(|_| Value).collect(),
385 T::Command__::Upgrade(_, _, _, x, _) => {
386 let v = argument(context, x)?;
387 consume_value(v);
388 vec![Value]
389 }
390 })
391 }
392
393 fn consume_values(_: Vec<Value>) {}
394
395 fn consume_value(_: Value) {}
396
397 fn consume_value_opts(_: Vec<Option<Value>>) {}
398
399 fn consume_value_opt(_: Option<Value>) {}
400
401 fn drop_value_opt<Mode: ExecutionMode>(
402 idx: (usize, usize),
403 value: Option<Value>,
404 ty: &Type,
405 ) -> Result<(), ExecutionError> {
406 match value {
407 Some(v) => drop_value::<Mode>(idx, v, ty),
408 None => Ok(()),
409 }
410 }
411
412 fn drop_value<Mode: ExecutionMode>(
413 (i, j): (usize, usize),
414 value: Value,
415 ty: &Type,
416 ) -> Result<(), ExecutionError> {
417 let abilities = ty.abilities();
418 if !abilities.has_drop() && !Mode::allow_arbitrary_values() {
419 let msg = if abilities.has_copy() {
420 "The value has copy, but not drop. \
421 Its last usage must be by-value so it can be taken."
422 } else {
423 "Unused value without drop"
424 };
425 return Err(ExecutionError::new_with_source(
426 ExecutionErrorKind::UnusedValueWithoutDrop {
427 result_idx: checked_as!(i, u16)?,
428 secondary_idx: checked_as!(j, u16)?,
429 },
430 msg,
431 ));
432 }
433 consume_value(value);
434 Ok(())
435 }
436
437 fn arguments(context: &mut Context, xs: &[T::Argument]) -> Result<Vec<Value>, ExecutionError> {
438 xs.iter().map(|x| argument(context, x)).collect()
439 }
440
441 fn argument(context: &mut Context, sp!(_, x): &T::Argument) -> Result<Value, ExecutionError> {
442 match &x.0 {
443 T::Argument__::Use(T::Usage::Move(location)) => move_value(context, *location),
444 T::Argument__::Use(T::Usage::Copy { location, .. }) => copy_value(context, *location),
445 T::Argument__::Borrow(_, location) => borrow_location(context, *location),
446 T::Argument__::Read(usage) => read_ref(context, usage),
447 T::Argument__::Freeze(usage) => freeze_ref(context, usage),
448 }
449 }
450
451 fn move_value(context: &mut Context, l: T::Location) -> Result<Value, ExecutionError> {
452 let Some(value) = context.location(l)?.take() else {
453 invariant_violation!("memory safety should have failed")
454 };
455 Ok(value)
456 }
457
458 fn copy_value(context: &mut Context, l: T::Location) -> Result<Value, ExecutionError> {
459 assert_invariant!(
460 context.location(l)?.is_some(),
461 "memory safety should have failed"
462 );
463 Ok(Value)
464 }
465
466 fn borrow_location(context: &mut Context, l: T::Location) -> Result<Value, ExecutionError> {
467 assert_invariant!(
468 context.location(l)?.is_some(),
469 "memory safety should have failed"
470 );
471 Ok(Value)
472 }
473
474 fn read_ref(context: &mut Context, u: &T::Usage) -> Result<Value, ExecutionError> {
475 let value = match u {
476 T::Usage::Move(l) => move_value(context, *l)?,
477 T::Usage::Copy { location, .. } => copy_value(context, *location)?,
478 };
479 consume_value(value);
480 Ok(Value)
481 }
482
483 fn freeze_ref(context: &mut Context, u: &T::Usage) -> Result<Value, ExecutionError> {
484 let value = match u {
485 T::Usage::Move(l) => move_value(context, *l)?,
486 T::Usage::Copy { location, .. } => copy_value(context, *location)?,
487 };
488 consume_value(value);
489 Ok(Value)
490 }
491}