ab_system_contract_simple_wallet_base/payload/builder.rs
1//! Transaction payload creation utilities
2
3#[cfg(test)]
4mod tests;
5
6use crate::MAX_OUTPUTS;
7use crate::payload::decoder_core::{output_ref, slot_output_ref, writes_output};
8use crate::payload::{
9 DeclaredOutput, FfiDataSizeCapacityRo, OutputState, TransactionInput, TransactionMethodContext,
10 TransactionOutput, TransactionOutputKind, TransactionPayloadDecoderError, TransactionSlot,
11};
12use ab_aligned_buffer::OwnedAlignedBuffer;
13use ab_aligned_buffer::alignment::Align16;
14use ab_contracts_common::MAX_TOTAL_METHOD_ARGS;
15use ab_contracts_common::metadata::decode::{
16 ArgumentKind, MetadataDecodingError, MethodKind, MethodMetadataDecoder, MethodMetadataItem,
17 MethodsContainerKind,
18};
19use ab_contracts_common::method::{ExternalArgs, MethodFingerprint};
20use ab_core_primitives::address::Address;
21use ab_io_type::alignment::Alignment;
22use ab_io_type::metadata::IoTypeDetails;
23use ab_io_type::trivial_type::TrivialType;
24use core::ffi::c_void;
25use core::mem::MaybeUninit;
26use core::ptr::NonNull;
27use core::{hint, slice};
28
29const {
30 // Make sure bit flags for all arguments will fit into a single u8 below
31 assert!(MAX_TOTAL_METHOD_ARGS as u32 == u8::BITS);
32}
33
34/// Read from an external arguments pointer and move it forward.
35///
36/// # Safety
37/// `external_args` must have enough capacity for the read value, the current offset must have the
38/// correct alignment for the type being read, and the bytes at the current offset must be a valid
39/// `T`.
40#[inline(always)]
41#[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
42unsafe fn read_external_args<T>(external_args: &mut NonNull<c_void>) -> T {
43 // SAFETY: Guaranteed by this function's contract
44 unsafe {
45 let value = external_args.cast::<T>().read();
46 *external_args = external_args.byte_add(size_of::<T>());
47 value
48 }
49}
50
51/// Errors for [`TransactionPayloadBuilder`]
52#[derive(Debug, thiserror::Error)]
53pub enum TransactionPayloadBuilderError<'a> {
54 /// Metadata decoding error
55 #[error("Metadata decoding error: {0}")]
56 MetadataDecodingError(MetadataDecodingError<'a>),
57 /// Too many arguments
58 #[error("Too many arguments")]
59 TooManyArguments(u8),
60 /// An output index of [`MAX_OUTPUTS`] or more, which tags can't hold
61 #[error("Invalid output index: {0}")]
62 InvalidOutputIndex(u8),
63 /// The payload doesn't fit into the maximum size given to [`TransactionPayloadBuilder::new()`]
64 #[error("The payload is too large")]
65 PayloadTooLarge,
66 /// More than [`MAX_OUTPUTS`] outputs declared
67 #[error("Too many outputs")]
68 TooManyOutputs,
69 /// [`MethodCallReferences::outputs`] doesn't have exactly one entry for each output of the
70 /// method
71 #[error("The method has {expected} outputs, but {actual} output indices are given")]
72 NumberOfOutputsMismatch { expected: u8, actual: usize },
73 /// [`MethodCallReferences::slots`] has more entries than the method has slots
74 #[error("The method has {num_slots} slots, but {num_references} slot references are given")]
75 TooManySlotReferences {
76 num_slots: u8,
77 num_references: usize,
78 },
79 /// [`MethodCallReferences::inputs`] has more entries than the method has inputs
80 #[error("The method has {num_inputs} inputs, but {num_references} input references are given")]
81 TooManyInputReferences {
82 num_inputs: u8,
83 num_references: usize,
84 },
85 /// No method call writes the declared output with this index, see
86 /// [`TransactionPayloadBuilder::into_aligned_bytes()`]
87 #[error("No method call writes the output with output index {0}")]
88 UnusedOutput(u8),
89 /// The method call breaks a rule of the payload format, with the error that
90 /// [`TransactionPayloadDecoder`] returns for such a payload, see
91 /// [`TransactionPayloadBuilder::with_method_call()`]
92 ///
93 /// [`TransactionPayloadDecoder`]: crate::payload::decoder::TransactionPayloadDecoder
94 #[error("The method call breaks a rule of the payload format: {0}")]
95 PayloadRule(TransactionPayloadDecoderError),
96}
97
98/// Declared output that no method call wrote yet, with capacity `0`
99const UNWRITTEN_OUTPUT: DeclaredOutput = DeclaredOutput {
100 offset: 0,
101 capacity: 0,
102 size: 0,
103 state: OutputState::NotWritten,
104};
105
106/// References of a method call to declared outputs, by position among the method's arguments of
107/// each kind, see [`TransactionPayloadBuilder::with_method_call()`]
108#[derive(Debug, Default, Copy, Clone)]
109pub struct MethodCallReferences<'a> {
110 /// Output index for each `#[slot]`, whose value the slot gets instead of an explicit address.
111 /// `None` or no entry for an explicit address.
112 pub slots: &'a [Option<u8>],
113 /// Output index for each `#[input]`, whose value the input gets instead of a value in the
114 /// payload. `None` or no entry for a value in the payload.
115 pub inputs: &'a [Option<u8>],
116 /// Output index for each `#[output]` and the return value (last), which they write. Exactly
117 /// one entry for each output of the method.
118 pub outputs: &'a [u8],
119}
120
121/// Builder for payload to be used with [`TxHandler`] (primarily for [`SimpleWallet`]).
122///
123/// The number of outputs that the payload declares is given to [`Self::new()`]. Method calls,
124/// added with [`Self::with_method_call()`], write these outputs and refer to them by output index,
125/// and the builder computes the capacity of every declared output from the method calls that write
126/// it.
127///
128/// Methods in the payload are decoded and called with [`TransactionPayloadCaller`], and can be
129/// described without calling them with [`TransactionPayloadDecoder`].
130///
131/// [`TxHandler`]: ab_contracts_standards::tx_handler::TxHandler
132/// [`SimpleWallet`]: crate::SimpleWalletBase
133/// [`TransactionPayloadCaller`]: crate::payload::caller::TransactionPayloadCaller
134/// [`TransactionPayloadDecoder`]: crate::payload::decoder::TransactionPayloadDecoder
135#[derive(Debug)]
136pub struct TransactionPayloadBuilder {
137 /// Starts with the header, which declares the outputs, with a capacity for each of them that
138 /// method calls raise, see [`Self::into_aligned_bytes()`]
139 payload: OwnedAlignedBuffer,
140 /// Entries before `num_outputs` are the outputs that the payload declares, with their
141 /// capacities and what the method calls added so far wrote into them last, as decoders see
142 /// them after those method calls
143 declared_outputs: [DeclaredOutput; MAX_OUTPUTS],
144 /// Number of outputs that the payload declares, at most [`MAX_OUTPUTS`]
145 num_outputs: u8,
146}
147
148impl Clone for TransactionPayloadBuilder {
149 fn clone(&self) -> Self {
150 let Self {
151 payload,
152 declared_outputs,
153 num_outputs,
154 } = self;
155
156 // The capacity of the payload is its maximum size, which `OwnedAlignedBuffer::clone()`
157 // doesn't keep
158 let mut cloned_payload = OwnedAlignedBuffer::with_capacity(payload.capacity());
159 cloned_payload.copy_from_slice(payload);
160
161 Self {
162 payload: cloned_payload,
163 declared_outputs: *declared_outputs,
164 num_outputs: *num_outputs,
165 }
166 }
167}
168
169impl TransactionPayloadBuilder {
170 /// Create a new instance for a payload of up to `max_size` bytes that declares `num_outputs`
171 /// outputs.
172 ///
173 /// Memory for the whole payload is allocated here and never reallocated, a method call that
174 /// doesn't fit returns [`TransactionPayloadBuilderError::PayloadTooLarge`]. The payload is
175 /// padded to a multiple of [`Alignment::MAX`], so `max_size` is rounded down to a multiple of
176 /// it, after it is limited to [`OwnedAlignedBuffer::MAX_CAPACITY`].
177 ///
178 /// `#[output]` arguments and return values of method calls write the declared outputs, and
179 /// slots and inputs of later method calls can refer to what was written last, by output index
180 /// from `0` to `num_outputs - 1`, see [`MethodCallReferences`]. The header of the payload has
181 /// room for the capacity of every declared output, which starts at `0`, and every method call
182 /// that writes an output raises its capacity to what the method needs, so capacities don't
183 /// have to be known upfront. The memory of every declared output is aligned for every output
184 /// type. [`SimpleWalletBase::execute()`] only calls the methods of a payload whose declared
185 /// outputs fit into [`OUTPUT_BUFFER_SIZE`] together, see [`TransactionPayloadDecoder`].
186 ///
187 /// The header is written right away, so a payload without method calls is the header.
188 ///
189 /// Returns an error if `num_outputs` is larger than [`MAX_OUTPUTS`] or the header doesn't fit
190 /// into `max_size`.
191 ///
192 /// [`SimpleWalletBase::execute()`]: crate::SimpleWalletBase::execute
193 /// [`OUTPUT_BUFFER_SIZE`]: crate::OUTPUT_BUFFER_SIZE
194 /// [`TransactionPayloadDecoder`]: crate::payload::decoder::TransactionPayloadDecoder
195 // TODO: Not annotated with `no_panic`, since allocating the payload can panic
196 pub fn new(
197 max_size: u32,
198 num_outputs: u8,
199 ) -> Result<Self, TransactionPayloadBuilderError<'static>> {
200 if usize::from(num_outputs) > MAX_OUTPUTS {
201 return Err(TransactionPayloadBuilderError::TooManyOutputs);
202 }
203
204 // A larger buffer can't be allocated
205 #[cfg_attr(
206 target_pointer_width = "64",
207 expect(
208 clippy::unnecessary_min_or_max,
209 reason = "`MAX_CAPACITY` is `u32::MAX` where `usize` is 64-bit"
210 )
211 )]
212 let max_size = max_size.min(OwnedAlignedBuffer::<Align16>::MAX_CAPACITY);
213 let mut builder = Self {
214 payload: OwnedAlignedBuffer::with_capacity(
215 max_size / u32::from(Alignment::MAX.get()) * u32::from(Alignment::MAX.get()),
216 ),
217 declared_outputs: [UNWRITTEN_OUTPUT; MAX_OUTPUTS],
218 num_outputs,
219 };
220 builder.push_payload_byte(num_outputs)?;
221 // Method calls that write an output raise its capacity
222 for _ in 0..num_outputs {
223 builder.extend_payload_with_alignment(&0u32.to_le_bytes(), Alignment::of::<u32>())?;
224 }
225
226 Ok(builder)
227 }
228
229 /// Add method call to the payload.
230 ///
231 /// The wallet will call this method in addition order.
232 ///
233 /// `references` refer to outputs that the payload declares (see [`Self::new()`]): the output
234 /// index for each `#[slot]` and `#[input]` that gets the value that an earlier method call
235 /// wrote last into that output instead of the value in `external_args`, and the output index
236 /// that each `#[output]` and the return value write. See [`TransactionInput`] for more details.
237 /// The capacity of every output that the method call writes is raised to the recommended
238 /// capacity of the `#[output]` or the size of the return value if it is smaller.
239 ///
240 /// Every output index must be below [`MAX_OUTPUTS`]
241 /// ([`TransactionPayloadBuilderError::InvalidOutputIndex`]). The method call is also checked
242 /// against the rules of the payload format about outputs, mostly with the code that decoders
243 /// use, so that [`TransactionPayloadDecoder`] accepts the payload, and a broken rule is
244 /// returned as [`TransactionPayloadBuilderError::PayloadRule`] with the error that the
245 /// decoder returns for it, in the order in which the decoder checks the rules:
246 /// * a slot or an input only refers to a declared output that an earlier method call wrote
247 /// ([`TransactionPayloadDecoderError::OutputIndexNotFound`]) and that this method call
248 /// doesn't write ([`TransactionPayloadDecoderError::OutputReferencedBySameMethod`])
249 /// * a slot only refers to a return value with the size of an address
250 /// ([`TransactionPayloadDecoderError::InvalidSlotOutputIndexSize`]); an `#[output]` used as a
251 /// slot gets its size when its method is called, so [`TransactionPayloadCaller`] checks it
252 /// * the method call only writes declared outputs
253 /// ([`TransactionPayloadDecoderError::OutputIndexNotFound`]), each at most once
254 /// ([`TransactionPayloadDecoderError::OutputUsedTwice`])
255 ///
256 /// The other rules about outputs hold by construction: the return value is the last output,
257 /// and every output gets a capacity that is enough for every method call that writes it.
258 ///
259 /// Outputs are given to the method empty, with size `0`, whatever an earlier method call wrote
260 /// into them, so methods called from transactions must accept empty outputs, like
261 /// [`MaybeData`] and [`VariableElements`]. A method with an `#[output]` of a [`TrivialType`]
262 /// can't be called directly from a transaction, since its value has to be initialized first,
263 /// for example by a separate method. Initializing values is domain-specific, so the payload
264 /// format doesn't do it. Executors that check arguments against the method's metadata reject
265 /// such calls, while the native executor trusts transactions, so with it such a call violates
266 /// the requirements of the called method.
267 ///
268 /// The return value is given the size of its type, since executors write the whole value, so
269 /// later method calls can refer to it as an input or a slot. The state returned by an `#[init]`
270 /// method is the exception: executors store it as the state of the contract instead of writing
271 /// it to the caller, so it is encoded as an `#[output]` that needs no capacity, like the state
272 /// in the last `#[output]` of `#[init]` without a return value, and later method calls
273 /// referring to it get it empty.
274 ///
275 /// On error, the builder is left unchanged, so other method calls can still be added.
276 ///
277 /// [`TransactionPayloadDecoder`]: crate::payload::decoder::TransactionPayloadDecoder
278 /// [`TransactionPayloadCaller`]: crate::payload::caller::TransactionPayloadCaller
279 /// [`MaybeData`]: ab_io_type::maybe_data::MaybeData
280 /// [`VariableElements`]: ab_io_type::variable_elements::VariableElements
281 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
282 pub fn with_method_call<Args>(
283 &mut self,
284 contract: &Address,
285 external_args: &Args,
286 method_context: TransactionMethodContext,
287 references: MethodCallReferences<'_>,
288 ) -> Result<(), TransactionPayloadBuilderError<'static>>
289 where
290 Args: ExternalArgs,
291 {
292 let external_args = NonNull::from_ref(external_args).cast::<*const c_void>();
293
294 // SAFETY: Called with statically valid data
295 unsafe {
296 self.with_method_call_untyped(
297 contract,
298 external_args,
299 Args::METADATA,
300 &Args::FINGERPRINT,
301 method_context,
302 references,
303 )
304 }
305 }
306
307 /// Other than unsafe API, this method is identical to [`Self::with_method_call()`].
308 ///
309 /// # Safety
310 /// `external_args` must correspond to `method_metadata` and `method_fingerprint`. Outputs are
311 /// never read from `external_args`. The pointers of slots and inputs that refer to declared
312 /// outputs in `references` are never dereferenced, so they may dangle, but they must not be
313 /// null, since external arguments hold every pointer as [`NonNull`].
314 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
315 pub unsafe fn with_method_call_untyped<'a>(
316 &mut self,
317 contract: &Address,
318 external_args: NonNull<*const c_void>,
319 method_metadata: &'a [u8],
320 method_fingerprint: &MethodFingerprint,
321 method_context: TransactionMethodContext,
322 references: MethodCallReferences<'_>,
323 ) -> Result<(), TransactionPayloadBuilderError<'a>> {
324 let payload_len = self.payload.len();
325 // SAFETY: Guaranteed by this function's contract
326 let result = unsafe {
327 self.add_method_call_untyped(
328 contract,
329 external_args,
330 method_metadata,
331 method_fingerprint,
332 method_context,
333 references,
334 )
335 };
336 if result.is_err() {
337 // Remove the part of a method call that didn't fit, declared outputs weren't changed
338 // SAFETY: The payload only grows, so its first `payload_len` bytes are still
339 // initialized
340 unsafe {
341 self.payload.set_len(payload_len);
342 }
343 }
344
345 result
346 }
347
348 /// Add the method call to the payload, see [`Self::with_method_call_untyped()`].
349 ///
350 /// Errors other than [`TransactionPayloadBuilderError::PayloadTooLarge`] are returned before
351 /// anything is changed. After that error, part of the method call might have been added to
352 /// the payload, while declared outputs are only changed after the whole method call was added.
353 ///
354 /// # Safety
355 /// The same as for [`Self::with_method_call_untyped()`].
356 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
357 unsafe fn add_method_call_untyped<'a>(
358 &mut self,
359 contract: &Address,
360 external_args: NonNull<*const c_void>,
361 mut method_metadata: &'a [u8],
362 method_fingerprint: &MethodFingerprint,
363 method_context: TransactionMethodContext,
364 references: MethodCallReferences<'_>,
365 ) -> Result<(), TransactionPayloadBuilderError<'a>> {
366 let external_args = &mut external_args.cast::<c_void>();
367 let MethodCallReferences {
368 slots: slot_output_indices,
369 inputs: input_output_indices,
370 outputs: output_indices,
371 } = references;
372
373 let (metadata_decoder, method_metadata_item) =
374 MethodMetadataDecoder::new(&mut method_metadata, MethodsContainerKind::Unknown)
375 .decode_next()
376 .map_err(TransactionPayloadBuilderError::MetadataDecodingError)?;
377 let mut metadata_decoder = metadata_decoder.without_auto_drain();
378
379 #[expect(
380 clippy::rest_pattern_accessible_field,
381 reason = "Do not need other fields"
382 )]
383 let MethodMetadataItem {
384 method_kind,
385 num_arguments,
386 ..
387 } = method_metadata_item;
388 let number_of_arguments = num_arguments.saturating_add(u8::from(method_kind.has_self()));
389
390 if number_of_arguments > MAX_TOTAL_METHOD_ARGS {
391 return Err(TransactionPayloadBuilderError::TooManyArguments(
392 number_of_arguments,
393 ));
394 }
395
396 let mut num_slot_arguments = 0u8;
397 let mut num_input_arguments = 0u8;
398 let mut num_output_arguments = 0u8;
399 // Offset of the return value among outputs and its size if executors write it to the
400 // caller
401 let mut return_value_offset = None;
402 let mut return_value_size = None;
403
404 let mut input_output_type_details =
405 [MaybeUninit::<IoTypeDetails>::uninit(); MAX_TOTAL_METHOD_ARGS as usize];
406 // Collect information about all arguments, so that everything except whether the method
407 // call fits is checked before the payload is changed
408 while let Some(item) = metadata_decoder
409 .decode_next()
410 .transpose()
411 .map_err(TransactionPayloadBuilderError::MetadataDecodingError)?
412 {
413 match item.argument_kind {
414 ArgumentKind::EnvRo
415 | ArgumentKind::EnvRw
416 | ArgumentKind::TmpRo
417 | ArgumentKind::TmpRw => {
418 // Not represented in external args
419 }
420 ArgumentKind::SlotRo | ArgumentKind::SlotRw => {
421 num_slot_arguments += 1;
422 }
423 ArgumentKind::Input => {
424 // SAFETY: The counters only count arguments decoded before this one, so they
425 // and their sum are below `num_arguments`, the number of items that the
426 // metadata decoder returns (see `MethodMetadataItem::num_arguments`). The check
427 // of the number of arguments above limits `num_arguments` to
428 // `MAX_TOTAL_METHOD_ARGS`.
429 unsafe {
430 hint::assert_unchecked(num_input_arguments < MAX_TOTAL_METHOD_ARGS);
431 }
432 input_output_type_details[usize::from(num_input_arguments)]
433 .write(item.type_details.unwrap_or(IoTypeDetails::bytes(0)));
434 num_input_arguments += 1;
435 }
436 ArgumentKind::Output | ArgumentKind::Return => {
437 // The state of `#[init]` has no type details, so it needs no capacity
438 let type_details = item.type_details.unwrap_or(IoTypeDetails::bytes(0));
439 // The return value is the last argument (see
440 // `ArgumentsMetadataDecoder::decode_next()`), so it is also the last output. In
441 // `#[init]` it is the state, which executors store instead of writing it to the
442 // caller, so it is encoded as an output then, like the state in the last
443 // `#[output]` of `#[init]` without a return value.
444 if matches!(item.argument_kind, ArgumentKind::Return)
445 && !matches!(method_kind, MethodKind::Init)
446 {
447 return_value_offset = Some(usize::from(num_output_arguments));
448 // The size of the return value is the size of its type, which is its
449 // recommended capacity
450 return_value_size = Some(type_details.recommended_capacity);
451 }
452 // SAFETY: Same as for inputs above
453 unsafe {
454 hint::assert_unchecked(
455 num_input_arguments + num_output_arguments < MAX_TOTAL_METHOD_ARGS,
456 );
457 }
458 // After all inputs, which come before outputs
459 input_output_type_details
460 [usize::from(num_input_arguments + num_output_arguments)]
461 .write(type_details);
462 num_output_arguments += 1;
463 }
464 }
465 }
466 // SAFETY: As for the writes above, the counters and their sum are at most `num_arguments`,
467 // so they stay within the `MAX_TOTAL_METHOD_ARGS` elements of the array. The metadata
468 // decoder returns all inputs before outputs (see
469 // `ArgumentsMetadataDecoder::decode_next()`), so the first `num_input_arguments` elements
470 // were initialized above with inputs and the next `num_output_arguments` ones with
471 // outputs.
472 let (input_type_details, output_type_details) = unsafe {
473 let (input_type_details, output_type_details) =
474 input_output_type_details.split_at_unchecked(usize::from(num_input_arguments));
475 let output_type_details =
476 output_type_details.get_unchecked(..usize::from(num_output_arguments));
477
478 (
479 input_type_details.assume_init_ref(),
480 output_type_details.assume_init_ref(),
481 )
482 };
483
484 if slot_output_indices.len() > usize::from(num_slot_arguments) {
485 return Err(TransactionPayloadBuilderError::TooManySlotReferences {
486 num_slots: num_slot_arguments,
487 num_references: slot_output_indices.len(),
488 });
489 }
490 if input_output_indices.len() > usize::from(num_input_arguments) {
491 return Err(TransactionPayloadBuilderError::TooManyInputReferences {
492 num_inputs: num_input_arguments,
493 num_references: input_output_indices.len(),
494 });
495 }
496 if output_indices.len() != usize::from(num_output_arguments) {
497 return Err(TransactionPayloadBuilderError::NumberOfOutputsMismatch {
498 expected: num_output_arguments,
499 actual: output_indices.len(),
500 });
501 }
502
503 // `TransactionSlot` for each slot, an explicit address unless it refers to a declared
504 // output
505 let mut slot_tags =
506 [TransactionSlot::new_address().into_u8(); MAX_TOTAL_METHOD_ARGS as usize];
507 for (&slot_output_index, slot_tag) in slot_output_indices.iter().zip(&mut slot_tags) {
508 if let Some(output_index) = slot_output_index {
509 *slot_tag = TransactionSlot::new_output_index(output_index)
510 .ok_or(TransactionPayloadBuilderError::InvalidOutputIndex(
511 output_index,
512 ))?
513 .into_u8();
514 }
515 }
516 // `TransactionInput` for each input
517 let mut input_tags = [0; MAX_TOTAL_METHOD_ARGS as usize];
518 for ((input_offset, type_details), input_tag) in
519 input_type_details.iter().enumerate().zip(&mut input_tags)
520 {
521 let input = if let Some(&Some(output_index)) = input_output_indices.get(input_offset) {
522 // Only the output index is written, so the alignment of the input isn't used
523 TransactionInput::new_output_index(output_index).ok_or(
524 TransactionPayloadBuilderError::InvalidOutputIndex(output_index),
525 )?
526 } else {
527 TransactionInput::new_value(type_details.alignment)
528 };
529 *input_tag = input.into_u8();
530 }
531 // `TransactionOutput` for each output, the return value last
532 let mut output_tags = [0; MAX_TOTAL_METHOD_ARGS as usize];
533 for ((output_offset, &output_index), output_tag) in
534 output_indices.iter().enumerate().zip(&mut output_tags)
535 {
536 let output = if return_value_offset == Some(output_offset) {
537 TransactionOutput::new_return_value(output_index)
538 } else {
539 TransactionOutput::new_output(output_index)
540 }
541 .ok_or(TransactionPayloadBuilderError::InvalidOutputIndex(
542 output_index,
543 ))?;
544 *output_tag = output.into_u8();
545 }
546 // SAFETY: `num_output_arguments` is at most `MAX_TOTAL_METHOD_ARGS`, as for the details of
547 // outputs above, and the loop above wrote a tag for each of the as many output indices
548 let output_tags = unsafe { output_tags.get_unchecked(..usize::from(num_output_arguments)) };
549
550 // The rules of the payload format about outputs, checked in the same order as decoders do,
551 // with `declared_outputs` in the state that decoders have after the earlier method calls
552 for &output_index in slot_output_indices.iter().flatten() {
553 slot_output_ref(self.declared_outputs(), output_index, output_tags)
554 .map_err(TransactionPayloadBuilderError::PayloadRule)?;
555 }
556 for &output_index in input_output_indices.iter().flatten() {
557 output_ref(self.declared_outputs(), output_index, output_tags)
558 .map_err(TransactionPayloadBuilderError::PayloadRule)?;
559 }
560 // Every output writes a declared output, each at most once, as
561 // `PayloadDecoderCore::write_outputs()` checks. Its other rules hold by construction: the
562 // tags are valid, and the return value is the last output.
563 let mut remaining_output_tags = output_tags;
564 while let Some((&output_tag, later_output_tags)) = remaining_output_tags.split_first() {
565 remaining_output_tags = later_output_tags;
566
567 let output_index = TransactionOutput::tag_output_index(output_tag);
568 if output_index >= self.num_outputs {
569 return Err(TransactionPayloadBuilderError::PayloadRule(
570 TransactionPayloadDecoderError::OutputIndexNotFound(output_index),
571 ));
572 }
573 if writes_output(later_output_tags, output_index) {
574 return Err(TransactionPayloadBuilderError::PayloadRule(
575 TransactionPayloadDecoderError::OutputUsedTwice(output_index),
576 ));
577 }
578 }
579
580 self.extend_payload_with_alignment(contract.as_bytes(), Alignment::of::<Address>())?;
581 self.extend_payload_with_alignment(
582 method_fingerprint.as_bytes(),
583 Alignment::of::<MethodFingerprint>(),
584 )?;
585 self.push_payload_byte(method_context as u8)?;
586
587 // Store number of slots and `TransactionSlot` for each slot
588 self.push_payload_byte(num_slot_arguments)?;
589 for &slot_tag in slot_tags.iter().take(usize::from(num_slot_arguments)) {
590 self.push_payload_byte(slot_tag)?;
591 }
592
593 // Store number of inputs and `TransactionInput` for each input
594 self.push_payload_byte(num_input_arguments)?;
595 for &input_tag in input_tags.iter().take(usize::from(num_input_arguments)) {
596 self.push_payload_byte(input_tag)?;
597 }
598
599 // Store number of outputs and `TransactionOutput` for each output
600 self.push_payload_byte(num_output_arguments)?;
601 for &output_tag in output_tags {
602 self.push_payload_byte(output_tag)?;
603 }
604
605 for slot_offset in 0..usize::from(num_slot_arguments) {
606 // SAFETY: Method description requires the layout to correspond to metadata, where all
607 // slots come before inputs and outputs (see `ArgumentsMetadataDecoder::decode_next()`),
608 // and the pointer to be non-null even when it dangles
609 let address = unsafe { read_external_args::<NonNull<Address>>(external_args) };
610
611 if slot_output_indices
612 .get(slot_offset)
613 .copied()
614 .flatten()
615 .is_none()
616 {
617 // SAFETY: Method description requires the layout to correspond to metadata, and
618 // the slot doesn't refer to a declared output, so it points to an address
619 let address = unsafe { address.as_ref() };
620 self.extend_payload_with_alignment(address.as_bytes(), Alignment::of::<Address>())?;
621 }
622 }
623
624 for (input_offset, type_details) in input_type_details.iter().enumerate() {
625 // SAFETY: Method description requires the layout to correspond to metadata, where the
626 // inputs come right after the slots (see `ArgumentsMetadataDecoder::decode_next()`),
627 // and the pointer to be non-null even when it dangles
628 let FfiDataSizeCapacityRo {
629 data_ptr,
630 size,
631 capacity: _,
632 } = unsafe { read_external_args(external_args) };
633
634 if input_output_indices
635 .get(input_offset)
636 .copied()
637 .flatten()
638 .is_none()
639 {
640 // SAFETY: Method description requires the layout to correspond to metadata, and
641 // the input doesn't refer to a declared output, so it points to `size` bytes
642 let data =
643 unsafe { slice::from_raw_parts(data_ptr.as_ptr().cast_const(), size as usize) };
644 self.extend_payload_with_alignment(&size.to_le_bytes(), Alignment::of::<u32>())?;
645 self.extend_payload_with_alignment(data, type_details.alignment)?;
646 }
647 }
648
649 if let Some(size) = return_value_size {
650 self.extend_payload_with_alignment(&size.to_le_bytes(), Alignment::of::<u32>())?;
651 }
652
653 // Only after the whole method call was added, so that declared outputs don't change if it
654 // doesn't fit. An `#[output]` needs its recommended capacity, and the recommended capacity
655 // of a return value is its size.
656 for (&output_tag, type_details) in output_tags.iter().zip(output_type_details) {
657 // SAFETY: The tag was made from a `TransactionOutput` above, and every output index was
658 // checked above to refer to a declared output
659 unsafe {
660 let output = TransactionOutput::from_u8(output_tag).unwrap_unchecked();
661 self.write_output(output, type_details.recommended_capacity);
662 }
663 }
664
665 Ok(())
666 }
667
668 /// Returns 16-byte aligned bytes, padded to a multiple of `u128` size.
669 ///
670 /// The contents is a header with the declared outputs, followed by a concatenated sequence of
671 /// method calls with their arguments. All data structures are correctly aligned in the
672 /// returned byte buffer with `0` used as padding when necessary.
673 /// [`OwnedAlignedBuffer::as_u128_slice()`] returns the whole payload as `u128`s. Every payload
674 /// starts with the header, also without declared outputs and method calls.
675 ///
676 /// The capacity of every declared output is the largest that a method call writing it needs:
677 /// the recommended capacity of an `#[output]`, the size of a return value, or `0` for the state
678 /// returned by an `#[init]` method.
679 ///
680 /// Returns [`TransactionPayloadBuilderError::UnusedOutput`] with the first declared output that
681 /// no method call writes, since its memory would never be used, which most likely means that a
682 /// method call refers to the wrong output index. [`TransactionPayloadDecoder`] and
683 /// [`TransactionPayloadCaller`] accept such a payload.
684 ///
685 /// The header:
686 /// * Number of declared outputs: `u8`
687 /// * For each declared output:
688 /// * Its capacity as little-endian `u32`
689 ///
690 /// Each method is serialized in the following way:
691 /// * Contract to call: [`Address`]
692 /// * Fingerprint of the method to call: [`MethodFingerprint`]
693 /// * Method context: [`TransactionMethodContext`]
694 /// * Number of `#[slot]` arguments: `u8`
695 /// * For each `#[slot]` argument:
696 /// * [`TransactionSlot`] as `u8`
697 /// * Number of `#[input]` arguments: `u8`
698 /// * For each `#[input]` argument:
699 /// * [`TransactionInput`] as `u8`
700 /// * Number of `#[output]` arguments, including the return value: `u8`
701 /// * For each `#[output]` argument, followed by the return value if there is one:
702 /// * [`TransactionOutput`] as `u8`
703 /// * For each [`TransactionSlot`], whose type is [`TransactionSlotType::Address`]:
704 /// * [`Address`]
705 /// * For each [`TransactionInput`], whose type is [`TransactionInputType::Value`]:
706 /// * Input size as little-endian `u32` followed by the input itself
707 /// * If the last [`TransactionOutput`] is a return value:
708 /// * Its size as little-endian `u32`
709 ///
710 /// [`TransactionPayloadDecoder`]: crate::payload::decoder::TransactionPayloadDecoder
711 /// [`TransactionPayloadCaller`]: crate::payload::caller::TransactionPayloadCaller
712 /// [`TransactionSlotType::Address`]: crate::payload::TransactionSlotType::Address
713 /// [`TransactionInputType::Value`]: crate::payload::TransactionInputType::Value
714 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
715 pub fn into_aligned_bytes(
716 mut self,
717 ) -> Result<OwnedAlignedBuffer, TransactionPayloadBuilderError<'static>> {
718 for (output_index, declared_output) in (0..=u8::MAX).zip(self.declared_outputs()) {
719 if declared_output.state == OutputState::NotWritten {
720 return Err(TransactionPayloadBuilderError::UnusedOutput(output_index));
721 }
722 }
723
724 // Always fits, since the capacity is a multiple of `Alignment::MAX`, see `Self::new()`
725 self.ensure_alignment(Alignment::MAX)?;
726
727 Ok(self.payload)
728 }
729
730 /// Record that a method call writes `output`, which needs `capacity` bytes, and raise the
731 /// capacity of its declared output in the header to that if it is smaller.
732 ///
733 /// # Safety
734 /// The output index of `output` must refer to a declared output.
735 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
736 unsafe fn write_output(&mut self, output: TransactionOutput, capacity: u32) {
737 let output_index = usize::from(output.output_index());
738 // Capacities follow the number of declared outputs and 3 bytes of padding
739 let offset = size_of::<u32>() * (1 + output_index);
740 // SAFETY: The output is declared (function contract), and `Self::new()` declares at most
741 // `MAX_OUTPUTS` outputs. `Self::new()` wrote a capacity for every declared output into the
742 // header, and the payload only grows after that.
743 unsafe {
744 hint::assert_unchecked(
745 output_index < MAX_OUTPUTS
746 && offset + size_of::<u32>() <= self.payload.len() as usize,
747 );
748 }
749
750 let declared_output = self
751 .declared_outputs
752 .get_mut(output_index)
753 .expect("Below `MAX_OUTPUTS`, as asserted above; qed");
754 declared_output.capacity = declared_output.capacity.max(capacity);
755 let kind = output.kind();
756 let size = match kind {
757 TransactionOutputKind::Output => 0,
758 // The capacity that a return value needs is its size
759 TransactionOutputKind::ReturnValue => capacity,
760 };
761 declared_output.set_written(kind, size);
762
763 let declared_capacity = self.payload.as_mut_slice()[offset..]
764 .first_chunk_mut::<{ size_of::<u32>() }>()
765 .expect("The header has a capacity for every declared output; qed");
766 *declared_capacity = declared_output.capacity.to_le_bytes();
767 }
768
769 /// Outputs that the payload declares
770 #[inline(always)]
771 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
772 fn declared_outputs(&self) -> &[DeclaredOutput] {
773 // SAFETY: `Self::new()` sets `num_outputs` to at most `MAX_OUTPUTS`, the length of
774 // `declared_outputs`, and it never changes after that
775 unsafe {
776 self.declared_outputs
777 .get_unchecked(..usize::from(self.num_outputs))
778 }
779 }
780
781 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
782 fn extend_payload_with_alignment(
783 &mut self,
784 bytes: &[u8],
785 alignment: Alignment,
786 ) -> Result<(), TransactionPayloadBuilderError<'static>> {
787 self.ensure_alignment(alignment)?;
788 self.extend_payload(bytes)
789 }
790
791 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
792 fn ensure_alignment(
793 &mut self,
794 alignment: Alignment,
795 ) -> Result<(), TransactionPayloadBuilderError<'static>> {
796 let alignment = usize::from(alignment.get());
797
798 let unaligned_by = self.payload.len() as usize % alignment;
799 if unaligned_by > 0 {
800 let padding_bytes = alignment - unaligned_by;
801 // Byte by byte rather than as a slice of zeroes, which the compiler can't prove to be
802 // in bounds
803 for _ in 0..padding_bytes {
804 self.push_payload_byte(0)?;
805 }
806 }
807
808 Ok(())
809 }
810
811 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
812 fn push_payload_byte(
813 &mut self,
814 byte: u8,
815 ) -> Result<(), TransactionPayloadBuilderError<'static>> {
816 self.extend_payload(&[byte])
817 }
818
819 /// Append `bytes` to the payload if they fit into its capacity, it is never reallocated
820 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
821 fn extend_payload(
822 &mut self,
823 bytes: &[u8],
824 ) -> Result<(), TransactionPayloadBuilderError<'static>> {
825 // The checks in `OwnedAlignedBuffer::append()` that decide whether it reallocates, so the
826 // compiler can prove that it never does
827 let fits = u32::try_from(bytes.len())
828 .ok()
829 .and_then(|len| self.payload.len().checked_add(len))
830 .is_some_and(|new_len| new_len <= self.payload.capacity());
831 if !fits {
832 return Err(TransactionPayloadBuilderError::PayloadTooLarge);
833 }
834
835 self.payload
836 .append(bytes)
837 .map_err(|_error| TransactionPayloadBuilderError::PayloadTooLarge)
838 }
839}