From 307fc10abb2a89944745ee85da0ff601ae65d2e0 Mon Sep 17 00:00:00 2001 From: Matthias Seitz Date: Fri, 14 Jul 2023 02:09:26 +0200 Subject: [PATCH] chore: add some txs helpers (#3767) --- crates/primitives/src/transaction/mod.rs | 25 ++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/primitives/src/transaction/mod.rs b/crates/primitives/src/transaction/mod.rs index 055402c302..796baf2986 100644 --- a/crates/primitives/src/transaction/mod.rs +++ b/crates/primitives/src/transaction/mod.rs @@ -780,6 +780,8 @@ impl Decodable for TransactionKind { } /// Signed transaction without its Hash. Used type for inserting into the DB. +/// +/// This can by converted to [`TransactionSigned`] by calling [`TransactionSignedNoHash::hash`]. #[derive_arbitrary(compact)] #[derive(Debug, Clone, PartialEq, Eq, Hash, AsRef, Deref, Default, Serialize, Deserialize)] pub struct TransactionSignedNoHash { @@ -800,6 +802,14 @@ impl TransactionSignedNoHash { keccak256(&buf) } + /// Recover signer from signature and hash. + /// + /// Returns `None` if the transaction's signature is invalid, see also [Self::recover_signer]. + pub fn recover_signer(&self) -> Option
{ + let signature_hash = self.signature_hash(); + self.signature.recover_signer(signature_hash) + } + /// Converts into a transaction type with its hash: [`TransactionSigned`]. pub fn with_hash(self) -> TransactionSigned { self.into() @@ -938,7 +948,7 @@ impl TransactionSigned { self.signature.recover_signer(signature_hash) } - /// Devour Self, recover signer and return [`TransactionSignedEcRecovered`] + /// Consumes the type, recover signer and return [`TransactionSignedEcRecovered`] /// /// Returns `None` if the transaction's signature is invalid, see also [Self::recover_signer]. pub fn into_ecrecovered(self) -> Option { @@ -946,12 +956,23 @@ impl TransactionSigned { Some(TransactionSignedEcRecovered { signed_transaction: self, signer }) } - /// try to recover signer and return [`TransactionSignedEcRecovered`] + /// Tries to recover signer and return [`TransactionSignedEcRecovered`] by cloning the type. pub fn try_ecrecovered(&self) -> Option { let signer = self.recover_signer()?; Some(TransactionSignedEcRecovered { signed_transaction: self.clone(), signer }) } + /// Tries to recover signer and return [`TransactionSignedEcRecovered`]. + /// + /// Returns `Err(Self)` if the transaction's signature is invalid, see also + /// [Self::recover_signer]. + pub fn try_into_ecrecovered(self) -> Result { + match self.recover_signer() { + None => Err(self), + Some(signer) => Ok(TransactionSignedEcRecovered { signed_transaction: self, signer }), + } + } + /// Returns the enveloped encoded transactions. /// /// See also [TransactionSigned::encode_enveloped]