Skip to content

Commit

Permalink
Cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
cygnet3 committed Jan 24, 2024
1 parent cf5789a commit 0d487f0
Show file tree
Hide file tree
Showing 7 changed files with 157 additions and 114 deletions.
13 changes: 4 additions & 9 deletions src/common.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
use secp256k1::{
PublicKey, Scalar, Secp256k1, SecretKey,
};
use bitcoin_hashes::Hash;
use crate::Result;
use crate::utils::SharedSecretHash;
use crate::Result;
use bitcoin_hashes::Hash;
use secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};

pub(crate) fn calculate_t_n(ecdh_shared_secret: &PublicKey, k: u32) -> Result<SecretKey> {
let hash = SharedSecretHash::from_ecdh_and_k(
ecdh_shared_secret,
k,
).to_byte_array();
let hash = SharedSecretHash::from_ecdh_and_k(ecdh_shared_secret, k).to_byte_array();
let sk = SecretKey::from_slice(&hash)?;

Ok(sk)
Expand Down
4 changes: 2 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub enum Error {

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self{
match self {
Error::GenericError(msg) => write!(f, "{}", msg),
Error::InvalidLabel(msg) => write!(f, "{}", msg),
Error::InvalidAddress(msg) => write!(f, "{}", msg),
Expand All @@ -27,7 +27,7 @@ impl fmt::Display for Error {
}
}

impl std::error::Error for Error {}
impl std::error::Error for Error {}

impl From<hex::FromHexError> for Error {
fn from(e: hex::FromHexError) -> Self {
Expand Down
61 changes: 40 additions & 21 deletions src/receiving.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,18 @@ use std::{
fmt,
};

use crate::{Error, Result, common::{calculate_t_n, calculate_P_n}};
use crate::{
common::{calculate_P_n, calculate_t_n},
Error, Result,
};
use bech32::ToBase32;
use bimap::BiMap;
use secp256k1::{Parity, PublicKey, Scalar, Secp256k1, SecretKey, XOnlyPublicKey};
use serde::{Serialize, ser::{SerializeStruct, SerializeTuple}, Deserializer, Deserialize, de::{Visitor, SeqAccess, self}};
use serde::{
de::{self, SeqAccess, Visitor},
ser::{SerializeStruct, SerializeTuple},
Deserialize, Deserializer, Serialize,
};

pub const NULL_LABEL: Label = Label { s: Scalar::ZERO };

Expand Down Expand Up @@ -91,7 +98,7 @@ pub struct Receiver {
pub is_testnet: bool,
}

struct SerializablePubkey([u8;33]);
struct SerializablePubkey([u8; 33]);

struct SerializableBiMap(BiMap<Label, PublicKey>);

Expand Down Expand Up @@ -122,13 +129,17 @@ impl<'de> Deserialize<'de> for SerializablePubkey {
formatter.write_str("an array of 33 bytes")
}

fn visit_seq<V>(self, mut seq: V) -> std::prelude::v1::Result<SerializablePubkey, V::Error>
fn visit_seq<V>(
self,
mut seq: V,
) -> std::prelude::v1::Result<SerializablePubkey, V::Error>
where
V: SeqAccess<'de>,
{
let mut arr = [0u8; 33];
for i in 0..33 {
arr[i] = seq.next_element()?
arr[i] = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(i, &self))?;
}
Ok(SerializablePubkey(arr))
Expand All @@ -142,12 +153,12 @@ impl<'de> Deserialize<'de> for SerializablePubkey {
impl Serialize for SerializableBiMap {
fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
where
S: serde::Serializer
S: serde::Serializer,
{
let pairs: Vec<(String, SerializablePubkey)> = self.0.iter()
.map(|(label, pubkey)| {
(label.as_string(), SerializablePubkey(pubkey.serialize()))
})
let pairs: Vec<(String, SerializablePubkey)> = self
.0
.iter()
.map(|(label, pubkey)| (label.as_string(), SerializablePubkey(pubkey.serialize())))
.collect();
// Now serialize `pairs` as a vector of tuples
pairs.serialize(serializer)
Expand All @@ -162,7 +173,10 @@ impl<'de> Deserialize<'de> for SerializableBiMap {
let pairs: Vec<(String, SerializablePubkey)> = Deserialize::deserialize(deserializer)?;
let mut bimap: BiMap<Label, PublicKey> = BiMap::new();
for (string, ser_pubkey) in pairs {
bimap.insert(Label::try_from(string).unwrap(), PublicKey::from_slice(&ser_pubkey.0).unwrap());
bimap.insert(
Label::try_from(string).unwrap(),
PublicKey::from_slice(&ser_pubkey.0).unwrap(),
);
}
Ok(SerializableBiMap(bimap))
}
Expand All @@ -171,13 +185,19 @@ impl<'de> Deserialize<'de> for SerializableBiMap {
impl Serialize for Receiver {
fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
where
S: serde::Serializer
S: serde::Serializer,
{
let mut state = serializer.serialize_struct("Receiver", 5)?;
state.serialize_field("version", &self.version)?;
state.serialize_field("is_testnet", &self.is_testnet)?;
state.serialize_field("scan_pubkey", &SerializablePubkey(self.scan_pubkey.serialize()))?;
state.serialize_field("spend_pubkey", &SerializablePubkey(self.spend_pubkey.serialize()))?;
state.serialize_field(
"scan_pubkey",
&SerializablePubkey(self.scan_pubkey.serialize()),
)?;
state.serialize_field(
"spend_pubkey",
&SerializablePubkey(self.spend_pubkey.serialize()),
)?;
state.serialize_field("labels", &SerializableBiMap(self.labels.clone()))?;
state.end()
}
Expand All @@ -203,7 +223,7 @@ impl<'de> Deserialize<'de> for Receiver {
is_testnet: helper.is_testnet,
scan_pubkey: PublicKey::from_slice(&helper.scan_pubkey.0).unwrap(),
spend_pubkey: PublicKey::from_slice(&helper.spend_pubkey.0).unwrap(),
labels: helper.labels.0,
labels: helper.labels.0,
})
}
}
Expand Down Expand Up @@ -317,12 +337,10 @@ impl Receiver {
let t_n: SecretKey = calculate_t_n(&ecdh_shared_secret, n)?;
let P_n: PublicKey = calculate_P_n(&self.spend_pubkey, t_n.into())?;
let P_n_xonly = P_n.x_only_public_key().0;
if pubkeys_to_check
.iter()
.any(|p| p.eq(&P_n_xonly))
{
if pubkeys_to_check.iter().any(|p| p.eq(&P_n_xonly)) {
n_found += 1;
found.entry(NULL_LABEL)
found
.entry(NULL_LABEL)
.or_insert_with(HashMap::new)
.insert(P_n_xonly, t_n.into());
} else if !self.labels.is_empty() {
Expand All @@ -337,7 +355,8 @@ impl Receiver {
if let Some(label) = self.labels.get_by_right(&diff) {
n_found += 1;
let t_n_label = t_n.add_tweak(label.as_inner())?;
found.entry(label.clone())
found
.entry(label.clone())
.or_insert_with(HashMap::new)
.insert(*p, t_n_label.into());
break 'outer;
Expand Down
13 changes: 7 additions & 6 deletions src/sending.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
use bech32::{FromBase32, ToBase32};

use secp256k1::{PublicKey, Secp256k1, SecretKey, XOnlyPublicKey};
use core::fmt;
use secp256k1::{PublicKey, Secp256k1, SecretKey, XOnlyPublicKey};
use std::collections::HashMap;

use crate::{
error::Error,
Result, common::calculate_t_n,
};
use crate::{common::calculate_t_n, error::Error, Result};

#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub struct SilentPaymentAddress {
Expand Down Expand Up @@ -53,7 +50,11 @@ impl SilentPaymentAddress {

impl fmt::Display for SilentPaymentAddress {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", <SilentPaymentAddress as Into<String>>::into(self.clone()))
write!(
f,
"{}",
<SilentPaymentAddress as Into<String>>::into(self.clone())
)
}
}

Expand Down
40 changes: 18 additions & 22 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
use crate::Error;
use bitcoin_hashes::{sha256t_hash_newtype, Hash, HashEngine};
use secp256k1::{
PublicKey,
Scalar,
SecretKey,
};
use secp256k1::{PublicKey, Scalar, SecretKey};

pub mod receiving;
pub mod sending;
Expand Down Expand Up @@ -36,10 +32,7 @@ sha256t_hash_newtype! {
}

impl InputsHash {
pub fn from_outpoint_and_A_sum(
smallest_outpoint: &[u8;36],
A_sum: &PublicKey,
) -> InputsHash {
pub fn from_outpoint_and_A_sum(smallest_outpoint: &[u8; 36], A_sum: &PublicKey) -> InputsHash {
let mut eng = InputsHash::engine();
eng.input(smallest_outpoint);
eng.input(&A_sum.serialize());
Expand All @@ -52,10 +45,7 @@ impl InputsHash {
}

impl LabelHash {
pub fn from_b_scan_and_m(
b_scan: SecretKey,
m: u32,
) -> LabelHash {
pub fn from_b_scan_and_m(b_scan: SecretKey, m: u32) -> LabelHash {
let mut eng = LabelHash::engine();
eng.input(&b_scan.secret_bytes());
eng.input(&m.to_be_bytes());
Expand All @@ -68,10 +58,7 @@ impl LabelHash {
}

impl SharedSecretHash {
pub fn from_ecdh_and_k(
ecdh: &PublicKey,
k: u32,
) -> SharedSecretHash {
pub fn from_ecdh_and_k(ecdh: &PublicKey, k: u32) -> SharedSecretHash {
let mut eng = SharedSecretHash::engine();
eng.input(&ecdh.serialize());
eng.input(&k.to_be_bytes());
Expand All @@ -80,20 +67,27 @@ impl SharedSecretHash {
}

pub fn hash_outpoints(outpoints_data: &[(String, u32)], A_sum: PublicKey) -> Result<Scalar, Error> {
if outpoints_data.is_empty() {return Err(Error::GenericError("No outpoints provided".to_owned()))}
if outpoints_data.is_empty() {
return Err(Error::GenericError("No outpoints provided".to_owned()));
}

let mut outpoints: Vec<[u8;36]> = Vec::with_capacity(outpoints_data.len());
let mut outpoints: Vec<[u8; 36]> = Vec::with_capacity(outpoints_data.len());

// should probably just use an OutPoints type properly at some point
for (txid, vout) in outpoints_data {
let mut bytes: Vec<u8> = hex::decode(txid.as_str())?;

if bytes.len() != 32 {return Err(Error::GenericError(format!("Invalid outpoint hex representation: {}", txid)))}
if bytes.len() != 32 {
return Err(Error::GenericError(format!(
"Invalid outpoint hex representation: {}",
txid
)));
}

// txid in string format is big endian and we need little endian
bytes.reverse();

let mut buffer = [0u8;36];
let mut buffer = [0u8; 36];

buffer[..32].copy_from_slice(&bytes);
buffer[32..].copy_from_slice(&vout.to_le_bytes());
Expand All @@ -107,6 +101,8 @@ pub fn hash_outpoints(outpoints_data: &[(String, u32)], A_sum: PublicKey) -> Res
Ok(InputsHash::from_outpoint_and_A_sum(&smallest_outpoint, &A_sum).to_scalar())
} else {
// This should never happen
Err(Error::GenericError("Unexpected empty outpoints vector".to_owned()))
Err(Error::GenericError(
"Unexpected empty outpoints vector".to_owned(),
))
}
}
Loading

0 comments on commit 0d487f0

Please sign in to comment.