#![cfg(feature = "full")]
pub use crate::message::{AddressLoader, SimpleAddressLoader};
use {
super::SanitizedVersionedTransaction,
crate::{
hash::Hash,
message::{
legacy,
v0::{self, LoadedAddresses},
LegacyMessage, SanitizedMessage, VersionedMessage,
},
precompiles::verify_if_precompile,
pubkey::Pubkey,
sanitize::Sanitize,
signature::Signature,
simple_vote_transaction_checker::is_simple_vote_transaction,
solana_sdk::feature_set,
transaction::{Result, Transaction, TransactionError, VersionedTransaction},
},
solana_program::message::SanitizedVersionedMessage,
};
pub const MAX_TX_ACCOUNT_LOCKS: usize = 128;
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SanitizedTransaction {
message: SanitizedMessage,
message_hash: Hash,
is_simple_vote_tx: bool,
signatures: Vec<Signature>,
}
#[derive(Debug, Clone, Default, Eq, PartialEq)]
pub struct TransactionAccountLocks<'a> {
pub readonly: Vec<&'a Pubkey>,
pub writable: Vec<&'a Pubkey>,
}
pub enum MessageHash {
Precomputed(Hash),
Compute,
}
impl From<Hash> for MessageHash {
fn from(hash: Hash) -> Self {
Self::Precomputed(hash)
}
}
impl SanitizedTransaction {
pub fn try_new(
tx: SanitizedVersionedTransaction,
message_hash: Hash,
is_simple_vote_tx: bool,
address_loader: impl AddressLoader,
) -> Result<Self> {
let signatures = tx.signatures;
let SanitizedVersionedMessage { message } = tx.message;
let message = match message {
VersionedMessage::Legacy(message) => {
SanitizedMessage::Legacy(LegacyMessage::new(message))
}
VersionedMessage::V0(message) => {
let loaded_addresses =
address_loader.load_addresses(&message.address_table_lookups)?;
SanitizedMessage::V0(v0::LoadedMessage::new(message, loaded_addresses))
}
};
Ok(Self {
message,
message_hash,
is_simple_vote_tx,
signatures,
})
}
pub fn try_create(
tx: VersionedTransaction,
message_hash: impl Into<MessageHash>,
is_simple_vote_tx: Option<bool>,
address_loader: impl AddressLoader,
) -> Result<Self> {
let sanitized_versioned_tx = SanitizedVersionedTransaction::try_from(tx)?;
let is_simple_vote_tx = is_simple_vote_tx
.unwrap_or_else(|| is_simple_vote_transaction(&sanitized_versioned_tx));
let message_hash = match message_hash.into() {
MessageHash::Compute => sanitized_versioned_tx.message.message.hash(),
MessageHash::Precomputed(hash) => hash,
};
Self::try_new(
sanitized_versioned_tx,
message_hash,
is_simple_vote_tx,
address_loader,
)
}
pub fn try_from_legacy_transaction(tx: Transaction) -> Result<Self> {
tx.sanitize()?;
Ok(Self {
message_hash: tx.message.hash(),
message: SanitizedMessage::Legacy(LegacyMessage::new(tx.message)),
is_simple_vote_tx: false,
signatures: tx.signatures,
})
}
pub fn from_transaction_for_tests(tx: Transaction) -> Self {
Self::try_from_legacy_transaction(tx).unwrap()
}
pub fn signature(&self) -> &Signature {
&self.signatures[0]
}
pub fn signatures(&self) -> &[Signature] {
&self.signatures
}
pub fn message(&self) -> &SanitizedMessage {
&self.message
}
pub fn message_hash(&self) -> &Hash {
&self.message_hash
}
pub fn is_simple_vote_transaction(&self) -> bool {
self.is_simple_vote_tx
}
pub fn to_versioned_transaction(&self) -> VersionedTransaction {
let signatures = self.signatures.clone();
match &self.message {
SanitizedMessage::V0(sanitized_msg) => VersionedTransaction {
signatures,
message: VersionedMessage::V0(v0::Message::clone(&sanitized_msg.message)),
},
SanitizedMessage::Legacy(legacy_message) => VersionedTransaction {
signatures,
message: VersionedMessage::Legacy(legacy::Message::clone(&legacy_message.message)),
},
}
}
pub fn get_account_locks(
&self,
tx_account_lock_limit: usize,
) -> Result<TransactionAccountLocks> {
Self::validate_account_locks(self.message(), tx_account_lock_limit)?;
Ok(self.get_account_locks_unchecked())
}
pub fn get_account_locks_unchecked(&self) -> TransactionAccountLocks {
let message = &self.message;
let account_keys = message.account_keys();
let num_readonly_accounts = message.num_readonly_accounts();
let num_writable_accounts = account_keys.len().saturating_sub(num_readonly_accounts);
let mut account_locks = TransactionAccountLocks {
writable: Vec::with_capacity(num_writable_accounts),
readonly: Vec::with_capacity(num_readonly_accounts),
};
for (i, key) in account_keys.iter().enumerate() {
if message.is_writable(i) {
account_locks.writable.push(key);
} else {
account_locks.readonly.push(key);
}
}
account_locks
}
pub fn get_loaded_addresses(&self) -> LoadedAddresses {
match &self.message {
SanitizedMessage::Legacy(_) => LoadedAddresses::default(),
SanitizedMessage::V0(message) => LoadedAddresses::clone(&message.loaded_addresses),
}
}
pub fn get_durable_nonce(&self) -> Option<&Pubkey> {
self.message.get_durable_nonce()
}
fn message_data(&self) -> Vec<u8> {
match &self.message {
SanitizedMessage::Legacy(legacy_message) => legacy_message.message.serialize(),
SanitizedMessage::V0(loaded_msg) => loaded_msg.message.serialize(),
}
}
pub fn verify(&self) -> Result<()> {
let message_bytes = self.message_data();
if self
.signatures
.iter()
.zip(self.message.account_keys().iter())
.map(|(signature, pubkey)| signature.verify(pubkey.as_ref(), &message_bytes))
.any(|verified| !verified)
{
Err(TransactionError::SignatureFailure)
} else {
Ok(())
}
}
pub fn verify_precompiles(&self, feature_set: &feature_set::FeatureSet) -> Result<()> {
for (program_id, instruction) in self.message.program_instructions_iter() {
verify_if_precompile(
program_id,
instruction,
self.message().instructions(),
feature_set,
)
.map_err(|_| TransactionError::InvalidAccountIndex)?;
}
Ok(())
}
pub fn validate_account_locks(
message: &SanitizedMessage,
tx_account_lock_limit: usize,
) -> Result<()> {
if message.has_duplicates() {
Err(TransactionError::AccountLoadedTwice)
} else if message.account_keys().len() > tx_account_lock_limit {
Err(TransactionError::TooManyAccountLocks)
} else {
Ok(())
}
}
}
#[cfg(test)]
#[allow(clippy::arithmetic_side_effects)]
mod tests {
use {
super::*,
crate::signer::{keypair::Keypair, Signer},
solana_program::vote::{self, state::Vote},
};
#[test]
fn test_try_create_simple_vote_tx() {
let bank_hash = Hash::default();
let block_hash = Hash::default();
let vote_keypair = Keypair::new();
let node_keypair = Keypair::new();
let auth_keypair = Keypair::new();
let votes = Vote::new(vec![1, 2, 3], bank_hash);
let vote_ix =
vote::instruction::vote(&vote_keypair.pubkey(), &auth_keypair.pubkey(), votes);
let mut vote_tx = Transaction::new_with_payer(&[vote_ix], Some(&node_keypair.pubkey()));
vote_tx.partial_sign(&[&node_keypair], block_hash);
vote_tx.partial_sign(&[&auth_keypair], block_hash);
{
let vote_transaction = SanitizedTransaction::try_create(
VersionedTransaction::from(vote_tx.clone()),
MessageHash::Compute,
None,
SimpleAddressLoader::Disabled,
)
.unwrap();
assert!(vote_transaction.is_simple_vote_transaction());
}
{
let vote_transaction = SanitizedTransaction::try_create(
VersionedTransaction::from(vote_tx.clone()),
MessageHash::Compute,
Some(false),
SimpleAddressLoader::Disabled,
)
.unwrap();
assert!(!vote_transaction.is_simple_vote_transaction());
}
vote_tx.signatures.push(Signature::default());
vote_tx.message.header.num_required_signatures = 3;
{
let vote_transaction = SanitizedTransaction::try_create(
VersionedTransaction::from(vote_tx.clone()),
MessageHash::Compute,
None,
SimpleAddressLoader::Disabled,
)
.unwrap();
assert!(!vote_transaction.is_simple_vote_transaction());
}
{
let vote_transaction = SanitizedTransaction::try_create(
VersionedTransaction::from(vote_tx),
MessageHash::Compute,
Some(true),
SimpleAddressLoader::Disabled,
)
.unwrap();
assert!(vote_transaction.is_simple_vote_transaction());
}
}
}