|
| 1 | +//! Prevalidation of Aptos transactions. |
| 2 | +
|
| 3 | +use crate::{Error, Prevalidated}; |
| 4 | + |
| 5 | +use aptos_types::account_address::AccountAddress; |
| 6 | +use aptos_types::transaction::SignedTransaction as AptosTransaction; |
| 7 | +use movement_types::transaction::Transaction; |
| 8 | + |
| 9 | +use std::collections::HashSet; |
| 10 | + |
| 11 | +/// Prevalidates a Transaction as a correctly encoded and signed AptosTransaction, |
| 12 | +/// optionally vetted against a whitelist of sender addresses. |
| 13 | +pub struct Validator { |
| 14 | + whitelist: Option<HashSet<AccountAddress>>, |
| 15 | +} |
| 16 | + |
| 17 | +impl Validator { |
| 18 | + /// Creates a Validator with no whitelist. All well-formed signed transactions |
| 19 | + /// are validated. |
| 20 | + pub fn new() -> Self { |
| 21 | + Validator { whitelist: None } |
| 22 | + } |
| 23 | + |
| 24 | + /// Creates a Validator configured with a whitelist. Transactions are checked |
| 25 | + /// against the addresses in the whitelist, in addition to being well-formed |
| 26 | + /// and signed. |
| 27 | + pub fn with_whitelist<I>(whitelist: I) -> Self |
| 28 | + where |
| 29 | + I: IntoIterator<Item = AccountAddress>, |
| 30 | + { |
| 31 | + Validator { whitelist: Some(whitelist.into_iter().collect()) } |
| 32 | + } |
| 33 | + |
| 34 | + /// Returns `Ok` if the transaction is valid accordingly to this instance's |
| 35 | + /// configuration. `Err` is returned for validation errors. |
| 36 | + pub fn prevalidate( |
| 37 | + &self, |
| 38 | + transaction: Transaction, |
| 39 | + ) -> Result<Prevalidated<Transaction>, Error> { |
| 40 | + // Deserialize data as Aptos transaction, fail if invalid. |
| 41 | + let aptos_transaction: AptosTransaction = |
| 42 | + bcs::from_bytes(&transaction.data()).map_err(|e| { |
| 43 | + Error::Validation(format!("failed to deserialize Aptos transaction: {}", e)) |
| 44 | + })?; |
| 45 | + |
| 46 | + // Verify that the signature is valid |
| 47 | + aptos_transaction |
| 48 | + .verify_signature() |
| 49 | + .map_err(|e| Error::Validation(format!("signature verification failed: {}", e)))?; |
| 50 | + |
| 51 | + // Check the sender against the whitelist, if provided. |
| 52 | + if let Some(whitelist) = &self.whitelist { |
| 53 | + if !whitelist.contains(&aptos_transaction.sender()) { |
| 54 | + return Err(Error::Validation("transaction sender not in whitelist".into())); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + Ok(Prevalidated(transaction)) |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +#[cfg(test)] |
| 63 | +mod tests { |
| 64 | + use super::*; |
| 65 | + use aptos_crypto::{ed25519::Ed25519PrivateKey, Uniform as _}; |
| 66 | + use aptos_sdk::{ |
| 67 | + transaction_builder::TransactionFactory, |
| 68 | + types::{chain_id::ChainId, LocalAccount}, |
| 69 | + }; |
| 70 | + use aptos_types::account_config::aptos_test_root_address; |
| 71 | + use aptos_types::transaction::{RawTransaction, SignedTransaction}; |
| 72 | + use movement_types::transaction::Transaction; |
| 73 | + |
| 74 | + use rand::rngs::OsRng; |
| 75 | + |
| 76 | + fn create_test_transaction(account: &LocalAccount) -> Result<Transaction, anyhow::Error> { |
| 77 | + let tx_factory = TransactionFactory::new(ChainId::test()) |
| 78 | + .with_gas_unit_price(100) |
| 79 | + .with_max_gas_amount(100_000); |
| 80 | + |
| 81 | + let aptos_transaction = account |
| 82 | + .sign_with_transaction_builder(tx_factory.create_user_account(account.public_key())); |
| 83 | + |
| 84 | + let serialized_aptos_transaction = bcs::to_bytes(&aptos_transaction)?; |
| 85 | + |
| 86 | + Ok(Transaction::new(serialized_aptos_transaction, 0, aptos_transaction.sequence_number())) |
| 87 | + } |
| 88 | + |
| 89 | + fn create_test_transaction_with_invalid_signature( |
| 90 | + account: &LocalAccount, |
| 91 | + ) -> Result<Transaction, anyhow::Error> { |
| 92 | + // Create a raw transaction |
| 93 | + let factory = TransactionFactory::new(ChainId::test()); |
| 94 | + let raw_txn: RawTransaction = factory |
| 95 | + .transfer(aptos_test_root_address(), 1000) |
| 96 | + .sender(account.address()) |
| 97 | + .sequence_number(0) |
| 98 | + .build(); |
| 99 | + |
| 100 | + // Now generate a DIFFERENT key to sign (invalid signer) |
| 101 | + let bad_key = Ed25519PrivateKey::generate(&mut OsRng); |
| 102 | + |
| 103 | + // Manually create a SignedTransaction with the wrong signature |
| 104 | + let aptos_transaction = raw_txn.sign( |
| 105 | + &bad_key, |
| 106 | + account.public_key().clone(), // <- NOTE: still using the correct pubkey |
| 107 | + )?; |
| 108 | + let aptos_transaction: SignedTransaction = aptos_transaction.into_inner(); |
| 109 | + |
| 110 | + let serialized_aptos_transaction = bcs::to_bytes(&aptos_transaction)?; |
| 111 | + |
| 112 | + Ok(Transaction::new(serialized_aptos_transaction, 0, aptos_transaction.sequence_number())) |
| 113 | + } |
| 114 | + |
| 115 | + #[test] |
| 116 | + fn invalid_transaction() -> Result<(), anyhow::Error> { |
| 117 | + let tx = Transaction::new(vec![42; 42], 0, 0); |
| 118 | + |
| 119 | + let validator = Validator::new(); |
| 120 | + |
| 121 | + match validator.prevalidate(tx) { |
| 122 | + Err(Error::Validation(_)) => Ok(()), |
| 123 | + Err(e) => panic!("unexpected error: {e:?}"), |
| 124 | + Ok(_) => panic!("should not prevalidate an invalid payload"), |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + #[test] |
| 129 | + fn incorrectly_signed_transaction() -> Result<(), anyhow::Error> { |
| 130 | + let account = LocalAccount::generate(&mut OsRng); |
| 131 | + let tx = create_test_transaction_with_invalid_signature(&account)?; |
| 132 | + |
| 133 | + let validator = Validator::new(); |
| 134 | + |
| 135 | + match validator.prevalidate(tx) { |
| 136 | + Err(Error::Validation(_)) => Ok(()), |
| 137 | + Err(e) => panic!("unexpected error: {e:?}"), |
| 138 | + Ok(_) => panic!("should not prevalidate an invalid payload"), |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + #[test] |
| 143 | + fn valid_transaction_no_whitelist() -> Result<(), anyhow::Error> { |
| 144 | + let account = LocalAccount::generate(&mut OsRng); |
| 145 | + let tx = create_test_transaction(&account)?; |
| 146 | + let tx_hash = tx.id(); |
| 147 | + |
| 148 | + let validator = Validator::new(); |
| 149 | + let Prevalidated(tx) = validator.prevalidate(tx)?; |
| 150 | + |
| 151 | + assert_eq!(tx.id(), tx_hash); |
| 152 | + Ok(()) |
| 153 | + } |
| 154 | + |
| 155 | + #[test] |
| 156 | + fn valid_transaction_sender_whitelisted() -> Result<(), anyhow::Error> { |
| 157 | + let account = LocalAccount::generate(&mut OsRng); |
| 158 | + let tx = create_test_transaction(&account)?; |
| 159 | + let tx_hash = tx.id(); |
| 160 | + |
| 161 | + let validator = Validator::with_whitelist([account.address()]); |
| 162 | + let Prevalidated(tx) = validator.prevalidate(tx)?; |
| 163 | + |
| 164 | + assert_eq!(tx.id(), tx_hash); |
| 165 | + Ok(()) |
| 166 | + } |
| 167 | + |
| 168 | + #[test] |
| 169 | + fn valid_transaction_sender_not_in_whitelist() -> Result<(), anyhow::Error> { |
| 170 | + let mut rng = OsRng; |
| 171 | + let account = LocalAccount::generate(&mut rng); |
| 172 | + let tx = create_test_transaction(&account)?; |
| 173 | + let whitelisted_account = LocalAccount::generate(&mut rng); |
| 174 | + |
| 175 | + let validator = Validator::with_whitelist([whitelisted_account.address()]); |
| 176 | + |
| 177 | + match validator.prevalidate(tx) { |
| 178 | + Err(Error::Validation(_)) => Ok(()), |
| 179 | + Err(e) => panic!("unexpected error: {e:?}"), |
| 180 | + Ok(_) => panic!("should not prevalidate an invalid payload"), |
| 181 | + } |
| 182 | + } |
| 183 | +} |
0 commit comments