ab_system_contract_simple_wallet_base/
lib.rs

1//! A simple wallet contract base contract to be used by other contracts
2//!
3//! It includes the core logic, making contracts using it much more compact. The implementation is
4//! based on [`schnorrkel`] crate and its SR25519 signature scheme.
5//!
6//! It abstracts away its inner types in the public API to allow it to evolve over time.
7//!
8//! The general workflow is:
9//! * [`SimpleWalletBase::initialize`] is used for wallet initialization
10//! * [`SimpleWalletBase::authorize`] is used for authorization
11//! * [`SimpleWalletBase::execute`] is used for executing method calls contained in the payload,
12//!   followed by [`SimpleWalletBase::increase_nonce`]
13//! * [`SimpleWalletBase::change_public_key`] is used for change public key to a different one
14
15#![feature(
16    maybe_uninit_as_bytes,
17    maybe_uninit_slice,
18    non_null_from_ref,
19    ptr_as_ref_unchecked,
20    slice_as_array,
21    try_blocks,
22    unchecked_shifts
23)]
24#![no_std]
25
26pub mod payload;
27pub mod seal;
28pub mod utils;
29
30use crate::payload::{TransactionMethodContext, TransactionPayloadDecoder};
31use crate::seal::hash_and_verify;
32use ab_contracts_common::env::{Env, MethodContext};
33use ab_contracts_common::{ContractError, MAX_TOTAL_METHOD_ARGS};
34use ab_contracts_io_type::trivial_type::TrivialType;
35use ab_contracts_macros::contract;
36use ab_contracts_standards::tx_handler::{TxHandlerPayload, TxHandlerSeal, TxHandlerSlots};
37use ab_transaction::TransactionHeader;
38use core::mem::MaybeUninit;
39use core::ptr;
40use schnorrkel::PublicKey;
41
42/// Context for transaction signatures, see [`SigningContext`].
43///
44/// [`SigningContext`]: schnorrkel::context::SigningContext
45///
46/// This constant is helpful for frontend/hardware wallet implementations.
47pub const SIGNING_CONTEXT: &[u8] = b"system-simple-wallet";
48/// Size of the buffer in pointers that is used for `ExternalArgs` pointers.
49///
50/// This constant is helpful for transaction generation to check whether a created transaction
51/// doesn't exceed this limit.
52///
53/// `#[slot]` argument using one pointer, `#[input]` two pointers and `#[output]` three pointers
54/// each.
55pub const EXTERNAL_ARGS_BUFFER_SIZE: usize = 3 * MAX_TOTAL_METHOD_ARGS as usize;
56/// Size of the buffer in `u128` elements that is used as a stack for storing outputs.
57///
58/// This constant is helpful for transaction generation to check whether a created transaction
59/// doesn't exceed this limit.
60///
61/// This defines how big the total size of `#[output]` arguments and return values could be in all
62/// methods of the payload together.
63///
64/// Overflow will result in an error.
65pub const OUTPUT_BUFFER_SIZE: usize = 32 * 1024 / size_of::<u128>();
66/// Size of the buffer in entries that is used to store buffer offsets.
67///
68/// This constant is helpful for transaction generation to check whether a created transaction
69/// doesn't exceed this limit.
70///
71/// This defines how many `#[output]` arguments and return values could exist in all methods of the
72/// payload together.
73///
74/// Overflow will result in an error.
75pub const OUTPUT_BUFFER_OFFSETS_SIZE: usize = 16;
76
77/// Transaction seal.
78///
79/// Contains signature and nonce, this is necessary to produce a correctly sealed transaction.
80#[derive(Debug, Copy, Clone, TrivialType)]
81#[repr(C)]
82pub struct Seal {
83    pub signature: [u8; 64],
84    pub nonce: u64,
85}
86
87/// State of the wallet.
88///
89/// Shouldn't be necessary to use directly.
90#[derive(Debug, Copy, Clone, Eq, PartialEq, TrivialType)]
91#[repr(C)]
92pub struct WalletState {
93    pub public_key: [u8; 32],
94    pub nonce: u64,
95}
96
97/// A simple wallet contract base contract to be used by other contracts.
98///
99/// See the module description for details.
100#[derive(Debug, Copy, Clone, TrivialType)]
101#[repr(C)]
102pub struct SimpleWalletBase;
103
104#[contract]
105impl SimpleWalletBase {
106    /// Returns initial state with a provided public key
107    #[view]
108    pub fn initialize(#[input] &public_key: &[u8; 32]) -> Result<WalletState, ContractError> {
109        // TODO: Storing some lower-level representation of the public key might reduce the cost of
110        //  verification in `Self::authorize()` method
111        // Ensure public key is valid
112        PublicKey::from_bytes(&public_key).map_err(|_error| ContractError::BadInput)?;
113
114        Ok(WalletState {
115            public_key,
116            nonce: 0,
117        })
118    }
119
120    /// Reads state of `owner` and returns `Ok(())` if authorization succeeds
121    #[view]
122    pub fn authorize(
123        #[input] state: &WalletState,
124        #[input] header: &TransactionHeader,
125        #[input] read_slots: &TxHandlerSlots,
126        #[input] write_slots: &TxHandlerSlots,
127        #[input] payload: &TxHandlerPayload,
128        #[input] seal: &TxHandlerSeal,
129    ) -> Result<(), ContractError> {
130        let Some(seal) = seal.read_trivial_type::<Seal>() else {
131            return Err(ContractError::BadInput);
132        };
133
134        let expected_nonce = state.nonce;
135        // Check if max nonce value was already reached
136        if expected_nonce.checked_add(1).is_none() {
137            return Err(ContractError::Forbidden);
138        };
139
140        let public_key = PublicKey::from_bytes(state.public_key.as_ref())
141            .expect("Guaranteed by constructor; qed");
142        hash_and_verify(
143            &public_key,
144            expected_nonce,
145            header,
146            read_slots.get_initialized(),
147            write_slots.get_initialized(),
148            payload.get_initialized(),
149            &seal,
150        )
151    }
152
153    /// Executes provided transactions in the payload.
154    ///
155    /// IMPORTANT:
156    /// * *must only be called with trusted input*, for example, successful signature verification
157    ///   in [`SimpleWalletBase::authorize()`] implies transaction was seen and verified by the user
158    /// * *remember to also [`SimpleWalletBase::increase_nonce()`] afterward* unless there is a very
159    ///   good reason not to (like when wallet was replaced with another implementation containing a
160    ///   different state)
161    ///
162    /// The caller must set themselves as a context or else error will be returned.
163    #[update]
164    pub fn execute(
165        #[env] env: &mut Env<'_>,
166        #[input] header: &TransactionHeader,
167        #[input] read_slots: &TxHandlerSlots,
168        #[input] write_slots: &TxHandlerSlots,
169        #[input] payload: &TxHandlerPayload,
170        #[input] seal: &TxHandlerSeal,
171    ) -> Result<(), ContractError> {
172        let _ = header;
173        let _ = read_slots;
174        let _ = write_slots;
175        let _ = seal;
176
177        // Only allow direct calls by context owner
178        if env.caller() != env.context() {
179            return Err(ContractError::Forbidden);
180        }
181
182        let mut external_args_buffer = [ptr::null_mut(); EXTERNAL_ARGS_BUFFER_SIZE];
183        let mut output_buffer = [MaybeUninit::uninit(); OUTPUT_BUFFER_SIZE];
184        let mut output_buffer_offsets = [MaybeUninit::uninit(); OUTPUT_BUFFER_OFFSETS_SIZE];
185
186        let mut payload_decoder = TransactionPayloadDecoder::new(
187            payload.get_initialized(),
188            &mut external_args_buffer,
189            &mut output_buffer,
190            &mut output_buffer_offsets,
191            |method_context| match method_context {
192                TransactionMethodContext::Null => MethodContext::Reset,
193                TransactionMethodContext::Wallet => MethodContext::Keep,
194            },
195        );
196
197        while let Some(prepared_method) = payload_decoder
198            .decode_next_method()
199            .map_err(|_error| ContractError::BadInput)?
200        {
201            env.call_prepared(prepared_method)?;
202        }
203
204        Ok(())
205    }
206
207    /// Returns state with increased nonce
208    #[view]
209    pub fn increase_nonce(#[input] state: &WalletState) -> Result<WalletState, ContractError> {
210        let nonce = state.nonce.checked_add(1).ok_or(ContractError::Forbidden)?;
211
212        Ok(WalletState {
213            public_key: state.public_key,
214            nonce,
215        })
216    }
217
218    /// Returns a new state with a changed public key
219    #[view]
220    pub fn change_public_key(
221        #[input] state: &WalletState,
222        #[input] &public_key: &[u8; 32],
223    ) -> Result<WalletState, ContractError> {
224        // Ensure public key is valid
225        PublicKey::from_bytes(&public_key).map_err(|_error| ContractError::BadInput)?;
226
227        Ok(WalletState {
228            public_key,
229            nonce: state.nonce,
230        })
231    }
232}