Skip to content

Commit

Permalink
chore: cargo clippy --fix (#12)
Browse files Browse the repository at this point in the history
* It's mostly removing redundant "&" and "&mut".
* Also removes number of "vec!" usages, replacing Vec with array.
* Removing ".clone()" for Copy types (PublicKey).
* Removed redundant closures.
* Replaced .or(...).unwrap() with .unwrap_or(...), which I then replaced
  with .unwrap_or_else(...).
* Manually applied `matches!` macro in a few places.
* Ran `cargo fmt --all` on the result.

Signed-off-by: Thorbjørn Lindeijer <[email protected]>
  • Loading branch information
bjorn authored Nov 2, 2023
1 parent 692f17e commit 3bd76de
Show file tree
Hide file tree
Showing 39 changed files with 375 additions and 396 deletions.
8 changes: 4 additions & 4 deletions src/amount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ impl FromStr for Amount {
type Err = Error;

fn from_str(s: &str) -> Result<Amount> {
let mut inner = Decimal::from_str(&s)?;
let mut inner = Decimal::from_str(s)?;
// Check we don't lose precision
let scale = inner.scale();
if scale > STELLAR_SCALE {
Expand Down Expand Up @@ -266,15 +266,15 @@ impl TryFrom<Stroops> for Amount {
}

impl XDRSerialize for Price {
fn write_xdr(&self, mut out: &mut Vec<u8>) -> Result<u64> {
fn write_xdr(&self, out: &mut Vec<u8>) -> Result<u64> {
let xdr_price = self.to_xdr()?;
xdr_price.write_xdr(&mut out).map_err(Error::XdrError)
xdr_price.write_xdr(out).map_err(Error::XdrError)
}
}

impl XDRDeserialize for Price {
fn from_xdr_bytes(buffer: &[u8]) -> Result<(Self, u64)> {
let (xdr_price, bytes_read) = xdr::Price::read_xdr(&buffer).map_err(Error::XdrError)?;
let (xdr_price, bytes_read) = xdr::Price::read_xdr(buffer).map_err(Error::XdrError)?;
let res = Price::from_xdr(&xdr_price)?;
Ok((res, bytes_read))
}
Expand Down
34 changes: 14 additions & 20 deletions src/asset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,7 @@ impl Asset {

/// Returns true if the asset is a Native. Returns false otherwise.
pub fn is_native(&self) -> bool {
match *self {
Asset::Native => true,
_ => false,
}
matches!(*self, Asset::Native)
}

/// If the asset is a Credit, returns its value. Returns None otherwise
Expand Down Expand Up @@ -136,9 +133,9 @@ impl CreditAsset {
/// Code must be shorter than 12 characters.
pub fn new(code: String, issuer: PublicKey) -> Result<CreditAsset> {
let code_len = code.len();
if code_len >= 1 && code_len <= 4 {
if (1..=4).contains(&code_len) {
Ok(CreditAsset::AlphaNum4 { code, issuer })
} else if code_len >= 5 && code_len <= 12 {
} else if (5..=12).contains(&code_len) {
Ok(CreditAsset::AlphaNum12 { code, issuer })
} else {
Err(Error::InvalidAssetCode)
Expand All @@ -148,16 +145,16 @@ impl CreditAsset {
/// Returns the asset code.
pub fn code(&self) -> &str {
match self {
CreditAsset::AlphaNum4 { code, issuer: _ } => &code,
CreditAsset::AlphaNum12 { code, issuer: _ } => &code,
CreditAsset::AlphaNum4 { code, issuer: _ } => code,
CreditAsset::AlphaNum12 { code, issuer: _ } => code,
}
}

/// Returns the asset issuer.
pub fn issuer(&self) -> &PublicKey {
match self {
CreditAsset::AlphaNum4 { code: _, issuer } => &issuer,
CreditAsset::AlphaNum12 { code: _, issuer } => &issuer,
CreditAsset::AlphaNum4 { code: _, issuer } => issuer,
CreditAsset::AlphaNum12 { code: _, issuer } => issuer,
}
}

Expand Down Expand Up @@ -197,10 +194,7 @@ impl TrustLineAsset {

/// Returns true if the asset is a Native. Returns false otherwise.
pub fn is_native(&self) -> bool {
match *self {
Self::Native => true,
_ => false,
}
matches!(*self, Self::Native)
}

/// Returns true if the asset is a Credit. Returns false otherwise.
Expand Down Expand Up @@ -299,31 +293,31 @@ impl TrustLineAsset {
}

impl XDRSerialize for TrustLineAsset {
fn write_xdr(&self, mut out: &mut Vec<u8>) -> Result<u64> {
fn write_xdr(&self, out: &mut Vec<u8>) -> Result<u64> {
let xdr_asset = self.to_xdr()?;
xdr_asset.write_xdr(&mut out).map_err(Error::XdrError)
xdr_asset.write_xdr(out).map_err(Error::XdrError)
}
}

impl XDRDeserialize for TrustLineAsset {
fn from_xdr_bytes(buffer: &[u8]) -> Result<(Self, u64)> {
let (xdr_asset, bytes_read) =
xdr::TrustLineAsset::read_xdr(&buffer).map_err(Error::XdrError)?;
xdr::TrustLineAsset::read_xdr(buffer).map_err(Error::XdrError)?;
let res = TrustLineAsset::from_xdr(&xdr_asset)?;
Ok((res, bytes_read))
}
}

impl XDRSerialize for Asset {
fn write_xdr(&self, mut out: &mut Vec<u8>) -> Result<u64> {
fn write_xdr(&self, out: &mut Vec<u8>) -> Result<u64> {
let xdr_asset = self.to_xdr()?;
xdr_asset.write_xdr(&mut out).map_err(Error::XdrError)
xdr_asset.write_xdr(out).map_err(Error::XdrError)
}
}

impl XDRDeserialize for Asset {
fn from_xdr_bytes(buffer: &[u8]) -> Result<(Self, u64)> {
let (xdr_asset, bytes_read) = xdr::Asset::read_xdr(&buffer).map_err(Error::XdrError)?;
let (xdr_asset, bytes_read) = xdr::Asset::read_xdr(buffer).map_err(Error::XdrError)?;
let res = Asset::from_xdr(&xdr_asset)?;
Ok((res, bytes_read))
}
Expand Down
12 changes: 6 additions & 6 deletions src/claim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,32 +209,32 @@ impl ClaimPredicate {
}

impl XDRSerialize for Claimant {
fn write_xdr(&self, mut out: &mut Vec<u8>) -> Result<u64> {
fn write_xdr(&self, out: &mut Vec<u8>) -> Result<u64> {
let xdr = self.to_xdr()?;
xdr.write_xdr(&mut out).map_err(Error::XdrError)
xdr.write_xdr(out).map_err(Error::XdrError)
}
}

impl XDRDeserialize for Claimant {
fn from_xdr_bytes(buffer: &[u8]) -> Result<(Self, u64)> {
let (xdr_claimant, bytes_read) =
xdr::Claimant::read_xdr(&buffer).map_err(Error::XdrError)?;
xdr::Claimant::read_xdr(buffer).map_err(Error::XdrError)?;
let res = Claimant::from_xdr(&xdr_claimant)?;
Ok((res, bytes_read))
}
}

impl XDRSerialize for ClaimPredicate {
fn write_xdr(&self, mut out: &mut Vec<u8>) -> Result<u64> {
fn write_xdr(&self, out: &mut Vec<u8>) -> Result<u64> {
let xdr = self.to_xdr()?;
xdr.write_xdr(&mut out).map_err(Error::XdrError)
xdr.write_xdr(out).map_err(Error::XdrError)
}
}

impl XDRDeserialize for ClaimPredicate {
fn from_xdr_bytes(buffer: &[u8]) -> Result<(Self, u64)> {
let (xdr_claim, bytes_read) =
xdr::ClaimPredicate::read_xdr(&buffer).map_err(Error::XdrError)?;
xdr::ClaimPredicate::read_xdr(buffer).map_err(Error::XdrError)?;
let res = ClaimPredicate::from_xdr(&xdr_claim)?;
Ok((res, bytes_read))
}
Expand Down
4 changes: 2 additions & 2 deletions src/crypto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub use sodium_oxide::*;

/// Compute sha256 hash of `m`.
pub fn hash(m: &[u8]) -> Vec<u8> {
sha2::Sha256::digest(&m).to_vec()
sha2::Sha256::digest(m).to_vec()
}

#[derive(Debug, Clone, PartialEq)]
Expand Down Expand Up @@ -92,6 +92,6 @@ where

/// Return the signature hint, that is the last 4 bytes of the public key.
pub fn signature_hint(&self) -> SignatureHint {
SignatureHint::from_public_key(&self.verifier.verify_key.as_ref())
SignatureHint::from_public_key(self.verifier.verify_key.as_ref())
}
}
10 changes: 5 additions & 5 deletions src/crypto/public_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub struct PublicKey(pub [u8; 32]);
impl PublicKey {
/// Create from `account_id`, e.g. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`.
pub fn from_account_id(account_id: &str) -> Result<PublicKey> {
let bytes = strkey::decode_account_id(&account_id)?;
let bytes = strkey::decode_account_id(account_id)?;
Self::from_slice(&bytes)
}

Expand All @@ -33,7 +33,7 @@ impl PublicKey {
}

pub fn to_muxed_account(&self, id: u64) -> MuxedAccount {
self.clone().into_muxed_account(id)
(*self).into_muxed_account(id)
}

pub fn to_xdr_uint256(&self) -> Result<xdr::Uint256> {
Expand Down Expand Up @@ -90,13 +90,13 @@ impl MuxedEd25519PublicKey {
}

pub fn from_account_id(account_id: &str) -> Result<MuxedEd25519PublicKey> {
let (bytes, id) = strkey::decode_muxed_account(&account_id)?;
let (bytes, id) = strkey::decode_muxed_account(account_id)?;
Self::from_slice(&bytes, id)
}

/// Create from raw byte and id.
pub fn from_slice(data: &[u8], id: u64) -> Result<MuxedEd25519PublicKey> {
let key = PublicKey::from_slice(&data)?;
let key = PublicKey::from_slice(data)?;
Ok(MuxedEd25519PublicKey { key, id })
}

Expand All @@ -106,7 +106,7 @@ impl MuxedEd25519PublicKey {
}

pub fn account_id(&self) -> String {
strkey::encode_muxed_account(&self.key.as_bytes(), self.id)
strkey::encode_muxed_account(self.key.as_bytes(), self.id)
}

pub fn to_xdr(&self) -> Result<xdr::MuxedAccount> {
Expand Down
19 changes: 9 additions & 10 deletions src/crypto/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ impl DecoratedSignature {
/// Creates a new `DecoratedSignature` from the pre image.
pub fn new_from_preimage(preimage: &[u8]) -> Result<DecoratedSignature> {
let hint = SignatureHint::from_slice(&preimage[preimage.len() - 4..])?;
let signature = Signature::from_bytes(&preimage).map_err(|_| Error::InvalidSignature)?;
let signature = Signature::from_bytes(preimage).map_err(|_| Error::InvalidSignature)?;
Ok(DecoratedSignature::new(hint, signature))
}

Expand Down Expand Up @@ -172,7 +172,7 @@ impl SignerKey {
tx: &TransactionEnvelope,
network: &Network,
) -> Result<SignerKey> {
let preauthtx = PreAuthTxHash::new_from_transaction_envelope(&tx, &network)?;
let preauthtx = PreAuthTxHash::new_from_transaction_envelope(tx, network)?;
Ok(SignerKey::new_from_pre_authorized_transaction(preauthtx))
}

Expand Down Expand Up @@ -334,7 +334,7 @@ impl PreAuthTxHash {
tx: &TransactionEnvelope,
network: &Network,
) -> Result<PreAuthTxHash> {
let hash = tx.hash(&network)?;
let hash = tx.hash(network)?;
PreAuthTxHash::new(hash)
}

Expand Down Expand Up @@ -369,31 +369,30 @@ impl HashX {
}

impl XDRSerialize for SignerKey {
fn write_xdr(&self, mut out: &mut Vec<u8>) -> Result<u64> {
fn write_xdr(&self, out: &mut Vec<u8>) -> Result<u64> {
let xdr_signer = self.to_xdr()?;
xdr_signer.write_xdr(&mut out).map_err(Error::XdrError)
xdr_signer.write_xdr(out).map_err(Error::XdrError)
}
}

impl XDRDeserialize for SignerKey {
fn from_xdr_bytes(buffer: &[u8]) -> Result<(Self, u64)> {
let (xdr_signer, bytes_read) =
xdr::SignerKey::read_xdr(&buffer).map_err(Error::XdrError)?;
let (xdr_signer, bytes_read) = xdr::SignerKey::read_xdr(buffer).map_err(Error::XdrError)?;
let res = SignerKey::from_xdr(&xdr_signer)?;
Ok((res, bytes_read))
}
}

impl XDRSerialize for Signer {
fn write_xdr(&self, mut out: &mut Vec<u8>) -> Result<u64> {
fn write_xdr(&self, out: &mut Vec<u8>) -> Result<u64> {
let xdr_signer = self.to_xdr()?;
xdr_signer.write_xdr(&mut out).map_err(Error::XdrError)
xdr_signer.write_xdr(out).map_err(Error::XdrError)
}
}

impl XDRDeserialize for Signer {
fn from_xdr_bytes(buffer: &[u8]) -> Result<(Self, u64)> {
let (xdr_signer, bytes_read) = xdr::Signer::read_xdr(&buffer).map_err(Error::XdrError)?;
let (xdr_signer, bytes_read) = xdr::Signer::read_xdr(buffer).map_err(Error::XdrError)?;
let res = Signer::from_xdr(&xdr_signer)?;
Ok((res, bytes_read))
}
Expand Down
24 changes: 12 additions & 12 deletions src/crypto/sodium_oxide/keypair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ impl AsRef<KeyPair<SecretKey, sodium::PublicKey>> for SodiumKeyPair {
impl SodiumKeyPair {
/// Create the key pair from the secret seed, e.g. `SDAKFNYEIAORZKKCYRILFQKLLOCNPL5SWJ3YY5NM3ZH6GJSZGXHZEPQS`.
pub fn from_secret_seed(data: &str) -> Result<SodiumKeyPair> {
let bytes = strkey::decode_secret_seed(&data)?;
let bytes = strkey::decode_secret_seed(data)?;
Self::from_seed_bytes(&bytes)
}

Expand All @@ -63,7 +63,7 @@ impl SodiumKeyPair {

/// Crete a key pair from raw bytes.
pub fn from_seed_bytes(data: &[u8]) -> Result<SodiumKeyPair> {
let the_seed = sodium::Seed::from_slice(&data).ok_or(Error::InvalidSeed)?;
let the_seed = sodium::Seed::from_slice(data).ok_or(Error::InvalidSeed)?;
let (public, sk) = sodium::keypair_from_seed(&the_seed);
let secret = SecretKey {
key: sk,
Expand Down Expand Up @@ -94,15 +94,15 @@ impl SodiumKeyPair {
}

pub fn verify(&self, sig: &Signature, msg: &[u8]) -> bool {
self.0.verify(msg, &sig).map_or(false, |_| true)
self.0.verify(msg, sig).map_or(false, |_| true)
}
}

impl std::str::FromStr for SodiumKeyPair {
type Err = crate::error::Error;

fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
let sk = SodiumKeyPair::from_secret_seed(&s)?;
let sk = SodiumKeyPair::from_secret_seed(s)?;
Ok(sk)
}
}
Expand Down Expand Up @@ -159,8 +159,8 @@ mod tests {
];

for &(secret, address) in keypairs.iter() {
let keypair = SodiumKeyPair::from_secret_seed(&secret).unwrap();
let keypair2 = SodiumKeyPair::from_str(&secret).unwrap();
let keypair = SodiumKeyPair::from_secret_seed(secret).unwrap();
let keypair2 = SodiumKeyPair::from_str(secret).unwrap();
assert_eq!(&keypair2.secret_key().secret_seed(), secret);
let account_id = keypair.public_key().account_id();
assert_eq!(&account_id, address);
Expand All @@ -183,26 +183,26 @@ mod tests {
#[test]
fn test_sign_and_verify() {
let the_secret = "SD7X7LEHBNMUIKQGKPARG5TDJNBHKC346OUARHGZL5ITC6IJPXHILY36";
let kp = SodiumKeyPair::from_secret_seed(&the_secret).unwrap();
let kp = SodiumKeyPair::from_secret_seed(the_secret).unwrap();
let message = "test post please ignore".as_bytes();
let sign = kp.sign(&message);
let expected_sign = vec![
let sign = kp.sign(message);
let expected_sign = [
0x19, 0xDB, 0xFD, 0xAF, 0x0A, 0xA8, 0x4D, 0xF9, 0xA7, 0xFF, 0x6F, 0xE3, 0xC1, 0x0E,
0xBC, 0x1F, 0xE2, 0x14, 0xC5, 0x10, 0xB9, 0x5D, 0xB0, 0xD6, 0x33, 0xBE, 0xD9, 0x3D,
0xF9, 0x25, 0x6B, 0xA9, 0x92, 0xEF, 0x7D, 0x94, 0xB2, 0xA6, 0xE4, 0x54, 0xDE, 0x8F,
0x21, 0x9, 0x28, 0xCA, 0x96, 0x11, 0x39, 0x03, 0x29, 0xC8, 0x40, 0xC8, 0xE5, 0x64,
0xE7, 0xA0, 0x72, 0x16, 0x02, 0x7A, 0xB4, 0xA,
];
assert_eq!(sign.to_bytes(), expected_sign[..]);
assert!(kp.verify(&sign, &message));
assert!(kp.verify(&sign, message));
}

#[test]
fn test_sign_decorated() {
let the_secret = "SD7X7LEHBNMUIKQGKPARG5TDJNBHKC346OUARHGZL5ITC6IJPXHILY36";
let kp = SodiumKeyPair::from_secret_seed(&the_secret).unwrap();
let kp = SodiumKeyPair::from_secret_seed(the_secret).unwrap();
let message = "test post please ignore".as_bytes();
let sign = kp.as_ref().sign_decorated(&message);
let sign = kp.as_ref().sign_decorated(message);
assert_eq!(sign.hint().to_vec(), vec![0x0B, 0xFA, 0xD1, 0x34]);
}
}
Loading

0 comments on commit 3bd76de

Please sign in to comment.