Skip to content

Commit

Permalink
refactor: reorganize module imports and improve code formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
Charon-Fan committed Dec 11, 2024
1 parent 05d0669 commit eead8e5
Show file tree
Hide file tree
Showing 17 changed files with 670 additions and 550 deletions.
38 changes: 19 additions & 19 deletions rust/apps/monero/src/address.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::errors::{MoneroError, Result};
use crate::key::*;
use crate::structs::{AddressType, Network};
use crate::errors::{MoneroError, Result};
use crate::utils::{constants::PUBKEY_LEH, hash::keccak256};
use alloc::format;
use alloc::string::{String, ToString};
Expand Down Expand Up @@ -53,16 +53,18 @@ impl Address {
unknown_prefix => return Err(MoneroError::InvalidPrefix(unknown_prefix.to_string())),
};
let is_subaddress = prefix == "2A" || prefix == "3F" || prefix == "24";
let public_spend =
match PublicKey::from_bytes(&decoded[1..33]).map_err(|e| format!("decode error: {:?}", e)) {
Ok(public_spend) => public_spend,
_ => return Err(MoneroError::FormatError),
};
let public_spend = match PublicKey::from_bytes(&decoded[1..33])
.map_err(|e| format!("decode error: {:?}", e))
{
Ok(public_spend) => public_spend,
_ => return Err(MoneroError::FormatError),
};
let public_view = match PublicKey::from_bytes(&decoded[33..65])
.map_err(|e| format!("decode error: {:?}", e)) {
Ok(public_view) => public_view,
_ => return Err(MoneroError::FormatError),
};
.map_err(|e| format!("decode error: {:?}", e))
{
Ok(public_view) => public_view,
_ => return Err(MoneroError::FormatError),
};
Ok(Address {
network: net,
addr_type: if is_subaddress {
Expand Down Expand Up @@ -134,12 +136,7 @@ pub fn pub_keyring_to_address(
Err(e) => return Err(e),
};

match pub_keys_to_address(
net,
is_subaddress,
&pub_spend_key,
&pub_view_key,
) {
match pub_keys_to_address(net, is_subaddress, &pub_spend_key, &pub_view_key) {
Ok(address) => Ok(address),
Err(e) => Err(e),
}
Expand Down Expand Up @@ -202,7 +199,8 @@ pub fn generate_address(
AddressType::Standard,
public_spend_key.clone(),
private_view_key.get_public_key(),
).to_string());
)
.to_string());
}

let point = public_spend_key.point.decompress().unwrap();
Expand Down Expand Up @@ -288,7 +286,8 @@ mod tests {
let public_spend_key = keypair.spend.get_public_key();
let private_view_key = keypair.view;

let address = generate_address(&public_spend_key, &private_view_key, major, minor, true).unwrap();
let address =
generate_address(&public_spend_key, &private_view_key, major, minor, true).unwrap();

assert_eq!(
address,
Expand Down Expand Up @@ -322,7 +321,8 @@ mod tests {
"5a69bc37d807013f80e10959bc7855419f1b0b47258a64a6a8c440ffd223070f"
);

let sun_account = generate_address(&keypair.get_public_spend(), &keypair.view, 1, 0, true).unwrap();
let sun_account =
generate_address(&keypair.get_public_spend(), &keypair.view, 1, 0, true).unwrap();

assert_eq!(
sun_account,
Expand Down
2 changes: 1 addition & 1 deletion rust/apps/monero/src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use alloc::string::{String, ToString};
use keystore::errors::KeystoreError;
use thiserror::Error;
use thiserror;
use thiserror::Error;

#[derive(Error, Debug, PartialEq)]
pub enum MoneroError {
Expand Down
17 changes: 10 additions & 7 deletions rust/apps/monero/src/key.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::utils::{hash::hash_to_scalar, constants::PUBKEY_LEH};
use crate::errors::{MoneroError, Result};
use crate::utils::{constants::PUBKEY_LEH, hash::hash_to_scalar};
use alloc::format;
use alloc::string::{String, ToString};
use curve25519_dalek::edwards::{CompressedEdwardsY, EdwardsPoint};
Expand Down Expand Up @@ -45,16 +45,19 @@ impl PublicKey {
}

pub fn from_bytes(bytes: &[u8]) -> Result<PublicKey> {
let pub_key =
match CompressedEdwardsY::from_slice(bytes).map_err(|e| format!("decode error: {:?}", e)) {
Ok(point) => PublicKey { point },
_ => return Err(MoneroError::PublicKeyFromBytesError),
};
let pub_key = match CompressedEdwardsY::from_slice(bytes)
.map_err(|e| format!("decode error: {:?}", e))
{
Ok(point) => PublicKey { point },
_ => return Err(MoneroError::PublicKeyFromBytesError),
};
Ok(pub_key)
}

pub fn from_str(s: &str) -> Result<PublicKey> {
let bytes = hex::decode(s).map_err(|e| format!("decode error: {:?}", e)).unwrap();
let bytes = hex::decode(s)
.map_err(|e| format!("decode error: {:?}", e))
.unwrap();
PublicKey::from_bytes(&bytes)
}
}
Expand Down
94 changes: 56 additions & 38 deletions rust/apps/monero/src/key_images.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
use crate::errors::{MoneroError, Result};
use crate::key::{generate_key_image_from_priavte_key, KeyPair, PrivateKey, PublicKey};
use crate::outputs::{ExportedTransferDetail, ExportedTransferDetails};
use crate::utils::{
decrypt_data_with_pvk, encrypt_data_with_pvk, hash::{hash_to_scalar, keccak256},
constants::*, sign::generate_ring_signature, varinteger::*,
constants::*,
decrypt_data_with_pvk, encrypt_data_with_pvk,
hash::{hash_to_scalar, keccak256},
sign::generate_ring_signature,
varinteger::*,
};
use crate::outputs::{ExportedTransferDetails, ExportedTransferDetail};
use crate::errors::{MoneroError, Result};
use curve25519_dalek::EdwardsPoint;
use curve25519_dalek::edwards::CompressedEdwardsY;
use curve25519_dalek::scalar::Scalar;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use rand_core::SeedableRng;
use curve25519_dalek::edwards::CompressedEdwardsY;
use curve25519_dalek::scalar::Scalar;
use curve25519_dalek::EdwardsPoint;
use hex;
use rand_core::SeedableRng;
use rand_core::{CryptoRng, RngCore};

#[derive(Debug, Clone, Copy)]
Expand All @@ -24,7 +27,10 @@ impl Keyimage {
}

pub fn to_point(&self) -> EdwardsPoint {
CompressedEdwardsY::from_slice(&self.0).unwrap().decompress().unwrap()
CompressedEdwardsY::from_slice(&self.0)
.unwrap()
.decompress()
.unwrap()
}

pub fn to_bytes(&self) -> Vec<u8> {
Expand Down Expand Up @@ -87,22 +93,27 @@ impl From<&Vec<u8>> for KeyImages {
}
}


fn calc_output_key_offset(
keypair: &KeyPair,
tx_pubkey: &[u8; 32],
internal_output_index: u64,
major: u32,
minor: u32,
) -> Scalar {
let recv_derivation =
(keypair.view.scalar * PublicKey::from_bytes(tx_pubkey).unwrap().point.decompress().unwrap()).mul_by_cofactor();
let recv_derivation = (keypair.view.scalar
* PublicKey::from_bytes(tx_pubkey)
.unwrap()
.point
.decompress()
.unwrap())
.mul_by_cofactor();

let mut output_index_buf = vec![0; length(internal_output_index)];
encode(internal_output_index, &mut output_index_buf);
let scalar = output_index_buf.to_vec();

let mut key_offset = hash_to_scalar(&[&recv_derivation.compress().0, scalar.as_slice()].concat());
let mut key_offset =
hash_to_scalar(&[&recv_derivation.compress().0, scalar.as_slice()].concat());

if major != 0 || minor != 0 {
key_offset = key_offset + Scalar::from_bytes_mod_order(keypair.get_m(major, minor));
Expand All @@ -111,15 +122,15 @@ fn calc_output_key_offset(
key_offset
}


fn calc_key_image_private_key(
keypair: &KeyPair,
tx_pubkey: &[u8; 32],
internal_output_index: u64,
major: u32,
minor: u32,
) -> PrivateKey {
let key_offsset = calc_output_key_offset(keypair, tx_pubkey, internal_output_index, major, minor);
let key_offsset =
calc_output_key_offset(keypair, tx_pubkey, internal_output_index, major, minor);

let prv_key = keypair.spend.scalar + key_offsset;

Expand All @@ -133,27 +144,25 @@ fn generate_key_image<R: RngCore + CryptoRng>(
internal_output_index: u64,
major: u32,
minor: u32,
mut rng: R
mut rng: R,
) -> KeyImageAndSignature {
let prvkey = calc_key_image_private_key(
keypair,
tx_pubkey,
internal_output_index,
major,
minor,
);
let prvkey =
calc_key_image_private_key(keypair, tx_pubkey, internal_output_index, major, minor);

let image = generate_key_image_from_priavte_key(&prvkey.clone());

let signature =
generate_ring_signature(&image.clone().compress().0, &image.clone(), vec![PublicKey::from_bytes(pubkey).unwrap()], &prvkey, 0, &mut rng);
let signature = generate_ring_signature(
&image.clone().compress().0,
&image.clone(),
vec![PublicKey::from_bytes(pubkey).unwrap()],
&prvkey,
0,
&mut rng,
);

let signature = [signature[0][0].to_bytes(), signature[0][1].to_bytes()].concat();

KeyImageAndSignature::new(
image.compress().0,
signature.try_into().unwrap(),
)
KeyImageAndSignature::new(image.compress().0, signature.try_into().unwrap())
}

fn generate_key_image_from_offset(
Expand All @@ -179,15 +188,14 @@ pub fn try_to_generate_image(
optional_minors: Vec<u32>,
) -> Result<(Keyimage, Scalar)> {
for minor in optional_minors {
let offset = calc_output_key_offset(keypair, tx_pubkey, internal_output_index, major, minor);
let offset =
calc_output_key_offset(keypair, tx_pubkey, internal_output_index, major, minor);
match generate_key_image_from_offset(
&keypair.spend,
&offset,
&PublicKey::from_bytes(output_pubkey).unwrap(),
) {
Some(image) => return Ok(
(Keyimage::new(image.compress().to_bytes()), offset),
),
Some(image) => return Ok((Keyimage::new(image.compress().to_bytes()), offset)),
None => continue,
};
}
Expand All @@ -196,7 +204,11 @@ pub fn try_to_generate_image(
}

impl ExportedTransferDetail {
pub fn key_image<R: RngCore + CryptoRng>(&self, keypair: &KeyPair, rng: R) -> KeyImageAndSignature {
pub fn key_image<R: RngCore + CryptoRng>(
&self,
keypair: &KeyPair,
rng: R,
) -> KeyImageAndSignature {
generate_key_image(
keypair,
&self.tx_pubkey,
Expand All @@ -218,7 +230,7 @@ impl ExportedTransferDetail {

(
prvkey.get_public_key(),
Keyimage::new(generate_key_image_from_priavte_key(&prvkey).compress().0)
Keyimage::new(generate_key_image_from_priavte_key(&prvkey).compress().0),
)
}
}
Expand Down Expand Up @@ -254,7 +266,11 @@ pub fn generate_export_ur_data(keypair: KeyPair, request_data: Vec<u8>) -> Resul
.push(output.key_image(&keypair.clone(), &mut rng));
}

Ok(encrypt_data_with_pvk(keypair, key_images.to_bytes(), KEY_IMAGE_EXPORT_MAGIC))
Ok(encrypt_data_with_pvk(
keypair,
key_images.to_bytes(),
KEY_IMAGE_EXPORT_MAGIC,
))
}

#[cfg(test)]
Expand All @@ -267,7 +283,8 @@ mod tests {
.unwrap();
let data = hex::decode("4d6f6e65726f206b657920696d616765206578706f727403c2b43f259084a0587d10ce88fddf607949d1448ef00dfad2d82447c669cafc712403d954e3fa901554b67ec80b7dcf1a8b95beaa0d9b27c478b2917ce28934d8252b4903999e98de1bdf03d536fb40893dcaf16b3118a325f261de607ac3c0b7b4b4f11cf3e6e95f8c21756e49287596d4da6997f6943d561f1fbf8f5cffb76274307545a0890da57022e80e31eeb483f27c5ebc6481ca202b7e4431465d40ac54c7b74b439b13de79b3985a01caaadf1f41073f7ddeadf8198eb8d21482ef633313e9ae9feae092118772201ff309b42d364f6e34211a5b4abd13087908989e16ad1bb0fbc87494a86889a8d7a6d6dfcfe078f1f767643dd03bffc8adc18c6736bb03ac8f47f2d708b02d1138427f58270d8176b37a2d970f7ede15b2697f38d0f3dc74e8de8014477cf01c6445047bc6fedebefac3d9619b8ec4f42bbef03140e16fdfb5e836f785f379a6a17f760619f135c9fba9c299d76da04f3cf30868bead8e39fb4b56b2eccfb2fd208cbc47e37a95fbc3084426ef10e19118c4fc080a47052006558f4f7f731e3aafc261bf1136a57d7fb34ceb271f0b5c4b5a5f3e98063aaf50423111bc17f97862921cf9e4e28c83d67f622d54851f4ee81549d857203373cc8c3033494a6a1ccf5779cd4f84c7c1a3b879d640b6916ceef91c441da88c542a3cf3862820da4bc3e634638e969c439641e417982382e6bc71100752afcaed1426881003de976966b707c0e057b73a70e94e5635405a437aab095791b232348e39916e22e9168a948a94b71cbc503065c232f5301840dc8a4cb81ca3eb2a324060e764c15f4a59c9560c67460251ca6095cb6ff959c19851e69f0783667029514612e3c9722cb280e2119b9cbdcbae0b91dcd303ed573edb2af19758b73853954c486c1a4a082ece9c84cc4695cbc3a73caeca2fcdce509df2378c1743edf87239adc846de146e3993b43f58a42d65d64575509c73b2621179b20e4e0edb695a2901f55643a926df34e64de4c4fc514f77e31dbb9b1748834e75a7cbb89d9c21c3842de7cf4a7776936175784c3a93c3486f0ff5cdb0f05cfb01097a5e338522342fa3bba623d5dacd8fc77fd4ea4b552df00e3cfb7f4490f6ba9f8c101cd1a98c4ce8a97ac04111020f0d624f9df35c6764b898ea0826404bfbdb96175e7672089ea0a408095a9ac97c943b9383a08b32f9ae0b8e45edf3659e7f714341139f1073c7be2c46357881cc8373ce5667f36b2bbe5f435ad740884be1a9f1ec1611bee3df4c78d7646e8d83ec03472a2b35711aa0e75bfaafef66a89b934ab487ad01468d5730eb3fe69b4adf86a97adb141d891edffe092a137d7b51a7184624586317e3aae8c6b128516b92462cd5856ab30514f678a9a1aa5469279d7cfee6b86fe2e12c0c383d077940857cf4bc526cb2f947692409de52ec82658819bb6ee78bebc21134aab4c04b0f5bee12ad5e037fd786c70dcfe83f20b7dcf6be765414561167a2bcb0b7ad17906f87fdc913746320bdc3287e6f0417c7d33debc15011706584b9d1acb42b721008447c2434a3a745855408b6bb0f86a00caf06e280b64032623082f3f60d3fd4c62458778cae87198bbd19c185148c0854d532f64593911a85d8f93230b8d49aa7928d220a32bacb93c105983749f5e9f441e903a5b7a1ec2f03d44f5ec06673fffd6b6e7df2cbde6a33aeb2c9d2d892c5d13fb2c7b0e36f1b5b535e860fe34dc0e578bb7d052aa922fb2fec3e8a5df184f24d96ac11f3b35d2e1843077b7bedcf4854a763318443be315e134a15915d360ec47373d00b861dcb8b1303").unwrap();

let res = decrypt_data_with_pvk(pvk.try_into().unwrap(), data, KEY_IMAGE_EXPORT_MAGIC).unwrap();
let res =
decrypt_data_with_pvk(pvk.try_into().unwrap(), data, KEY_IMAGE_EXPORT_MAGIC).unwrap();

assert_eq!(
hex::encode(res.pk1.unwrap().as_bytes()),
Expand Down Expand Up @@ -334,7 +351,8 @@ mod tests {
);
let keypair = crate::key::KeyPair::new(sec_v_key.clone(), sec_s_key.clone());

let key_images_export_data = generate_export_ur_data(keypair.clone(), data.clone()).unwrap();
let key_images_export_data =
generate_export_ur_data(keypair.clone(), data.clone()).unwrap();

assert_eq!(hex::encode(key_images_export_data), "4d6f6e65726f206b657920696d616765206578706f727403a7f77b9eb360d066d49f2eaa597fe16862b5c1c90eba00af226a1e6c43b774b2b468994d6ff7ee2a7d829812c2d6adedcb9131133f043ff98223531f2b721ff7c1468885baea1a7acd4d6c929ea8ce07161c7f443e9e6ed19677c6c6f53185a50a0418f14ce26d7988c2190e09a04809346d6d7aabdfe929ce88bed228531a44d4c9f1ee2826dcd2f4d78900");
}
Expand Down
6 changes: 3 additions & 3 deletions rust/apps/monero/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
#![feature(error_in_core)]
extern crate alloc;

mod extra;
mod signed_transaction;
mod slow_hash;
mod transfer_key;
mod signed_transaction;
mod extra;

pub mod errors;
pub mod address;
pub mod errors;
pub mod key;
pub mod key_images;
pub mod outputs;
Expand Down
Loading

0 comments on commit eead8e5

Please sign in to comment.