Skip to content

Commit

Permalink
add rustfmt rules
Browse files Browse the repository at this point in the history
  • Loading branch information
Ash-L2L committed Aug 1, 2023
1 parent 634a46b commit 4a52f34
Show file tree
Hide file tree
Showing 14 changed files with 298 additions and 100 deletions.
6 changes: 6 additions & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
edition = "2021"
max_width = 80

# unstable features
# unstable_features = true
# reorder_impl_items = true
# group_imports = "StdExternalCrate"
18 changes: 15 additions & 3 deletions src/archive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,21 @@ impl<
})
}

pub fn get_header(&self, txn: &RoTxn, height: u32) -> Result<Option<Header>, Error> {
pub fn get_header(
&self,
txn: &RoTxn,
height: u32,
) -> Result<Option<Header>, Error> {
let height = height.to_be_bytes();
let header = self.headers.get(txn, &height)?;
Ok(header)
}

pub fn get_body(&self, txn: &RoTxn, height: u32) -> Result<Option<Body<A, C>>, Error> {
pub fn get_body(
&self,
txn: &RoTxn,
height: u32,
) -> Result<Option<Body<A, C>>, Error> {
let height = height.to_be_bytes();
let header = self.bodies.get(txn, &height)?;
Ok(header)
Expand Down Expand Up @@ -77,7 +85,11 @@ impl<
Ok(())
}

pub fn append_header(&self, txn: &mut RwTxn, header: &Header) -> Result<(), Error> {
pub fn append_header(
&self,
txn: &mut RwTxn,
header: &Header,
) -> Result<(), Error> {
let height = self.get_height(txn)?;
let best_hash = self.get_best_hash(txn)?;
if header.prev_side_hash != best_hash {
Expand Down
51 changes: 33 additions & 18 deletions src/authorization.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use crate::types::blake3;
use crate::types::{Address, AuthorizedTransaction, Body, GetAddress, Transaction, Verify};
pub use ed25519_dalek::{Keypair, PublicKey, Signature, SignatureError, Signer, Verifier};
use crate::types::{
Address, AuthorizedTransaction, Body, GetAddress, Transaction, Verify,
};
pub use ed25519_dalek::{
Keypair, PublicKey, Signature, SignatureError, Signer, Verifier,
};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};

Expand All @@ -16,9 +20,13 @@ impl GetAddress for Authorization {
}
}

impl<C: Clone + Serialize + for<'de> Deserialize<'de> + Send + Sync> Verify<C> for Authorization {
impl<C: Clone + Serialize + for<'de> Deserialize<'de> + Send + Sync> Verify<C>
for Authorization
{
type Error = Error;
fn verify_transaction(transaction: &AuthorizedTransaction<Self, C>) -> Result<(), Self::Error>
fn verify_transaction(
transaction: &AuthorizedTransaction<Self, C>,
) -> Result<(), Self::Error>
where
Self: Sized,
{
Expand Down Expand Up @@ -56,16 +64,17 @@ pub fn verify_authorized_transaction<C: Clone + Serialize + Sync>(
let messages: Vec<_> = std::iter::repeat(serialized_transaction.as_slice())
.take(transaction.authorizations.len())
.collect();
let (public_keys, signatures): (Vec<PublicKey>, Vec<Signature>) = transaction
.authorizations
.iter()
.map(
|Authorization {
public_key,
signature,
}| (public_key, signature),
)
.unzip();
let (public_keys, signatures): (Vec<PublicKey>, Vec<Signature>) =
transaction
.authorizations
.iter()
.map(
|Authorization {
public_key,
signature,
}| (public_key, signature),
)
.unzip();
ed25519_dalek::verify_batch(&messages, &signatures, &public_keys)?;
Ok(())
}
Expand All @@ -82,7 +91,8 @@ pub fn verify_authorizations<C: Clone + Serialize + Sync>(
.par_iter()
.map(bincode::serialize)
.collect::<Result<_, _>>()?;
let serialized_transactions = serialized_transactions.iter().map(Vec::as_slice);
let serialized_transactions =
serialized_transactions.iter().map(Vec::as_slice);
let messages = input_numbers.zip(serialized_transactions).flat_map(
|(input_number, serialized_transaction)| {
std::iter::repeat(serialized_transaction).take(input_number)
Expand All @@ -101,7 +111,9 @@ pub fn verify_authorizations<C: Clone + Serialize + Sync>(
signatures: Vec::with_capacity(package_size),
public_keys: Vec::with_capacity(package_size),
};
for (authorization, message) in &pairs[i * package_size..(i + 1) * package_size] {
for (authorization, message) in
&pairs[i * package_size..(i + 1) * package_size]
{
package.messages.push(*message);
package.signatures.push(authorization.signature);
package.public_keys.push(authorization.public_key);
Expand All @@ -128,7 +140,9 @@ pub fn verify_authorizations<C: Clone + Serialize + Sync>(
messages,
signatures,
public_keys,
}| ed25519_dalek::verify_batch(messages, signatures, public_keys),
}| {
ed25519_dalek::verify_batch(messages, signatures, public_keys)
},
)
.collect::<Result<(), SignatureError>>()?;
Ok(())
Expand All @@ -146,7 +160,8 @@ pub fn authorize<C: Clone + Serialize>(
addresses_keypairs: &[(Address, &Keypair)],
transaction: Transaction<C>,
) -> Result<AuthorizedTransaction<Authorization, C>, Error> {
let mut authorizations: Vec<Authorization> = Vec::with_capacity(addresses_keypairs.len());
let mut authorizations: Vec<Authorization> =
Vec::with_capacity(addresses_keypairs.len());
let message = bincode::serialize(&transaction)?;
for (address, keypair) in addresses_keypairs {
let hash_public_key = get_address(&keypair.public);
Expand Down
22 changes: 17 additions & 5 deletions src/drivechain/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,19 @@ pub trait Main {
nsidechain: u8,
) -> Result<Vec<WithdrawalStatus>, jsonrpsee::core::Error>;
#[method(name = "listspentwithdrawals")]
async fn listspentwithdrawals(&self) -> Result<Vec<SpentWithdrawal>, jsonrpsee::core::Error>;
async fn listspentwithdrawals(
&self,
) -> Result<Vec<SpentWithdrawal>, jsonrpsee::core::Error>;
#[method(name = "listfailedwithdrawals")]
async fn listfailedwithdrawals(&self) -> Result<Vec<FailedWithdrawal>, jsonrpsee::core::Error>;
async fn listfailedwithdrawals(
&self,
) -> Result<Vec<FailedWithdrawal>, jsonrpsee::core::Error>;
#[method(name = "getblockcount")]
async fn getblockcount(&self) -> Result<usize, jsonrpsee::core::Error>;
#[method(name = "getbestblockhash")]
async fn getbestblockhash(&self) -> Result<bitcoin::BlockHash, jsonrpsee::core::Error>;
async fn getbestblockhash(
&self,
) -> Result<bitcoin::BlockHash, jsonrpsee::core::Error>;
#[method(name = "getblock")]
async fn getblock(
&self,
Expand Down Expand Up @@ -121,14 +127,20 @@ pub trait Main {
) -> Result<serde_json::Value, jsonrpsee::core::Error>;

#[method(name = "generate")]
async fn generate(&self, num: u32) -> Result<serde_json::Value, jsonrpsee::core::Error>;
async fn generate(
&self,
num: u32,
) -> Result<serde_json::Value, jsonrpsee::core::Error>;

#[method(name = "getnewaddress")]
async fn getnewaddress(
&self,
account: &str,
address_type: &str,
) -> Result<bitcoin::Address<bitcoin::address::NetworkUnchecked>, jsonrpsee::core::Error>;
) -> Result<
bitcoin::Address<bitcoin::address::NetworkUnchecked>,
jsonrpsee::core::Error,
>;

#[method(name = "createsidechaindeposit")]
async fn createsidechaindeposit(
Expand Down
28 changes: 21 additions & 7 deletions src/drivechain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ impl<C> Drivechain<C> {
.nextblockhash
.ok_or(Error::NoNextBlock { prev_main_hash })?;
self.client
.verifybmm(&block_hash, &header.hash().into(), self.sidechain_number)
.verifybmm(
&block_hash,
&header.hash().into(),
self.sidechain_number,
)
.await?;
Ok(())
}
Expand All @@ -38,7 +42,8 @@ impl<C> Drivechain<C> {
end: bitcoin::BlockHash,
start: Option<bitcoin::BlockHash>,
) -> Result<TwoWayPegData<C>, Error> {
let (deposits, deposit_block_hash) = self.get_deposit_outputs(end, start).await?;
let (deposits, deposit_block_hash) =
self.get_deposit_outputs(end, start).await?;
let bundle_statuses = self.get_withdrawal_bundle_statuses().await?;
let two_way_peg_data = TwoWayPegData {
deposits,
Expand All @@ -65,18 +70,24 @@ impl<C> Drivechain<C> {
&self,
end: bitcoin::BlockHash,
start: Option<bitcoin::BlockHash>,
) -> Result<(HashMap<OutPoint, Output<C>>, Option<bitcoin::BlockHash>), Error> {
) -> Result<(HashMap<OutPoint, Output<C>>, Option<bitcoin::BlockHash>), Error>
{
let deposits = self
.client
.listsidechaindepositsbyblock(self.sidechain_number, Some(end), start)
.listsidechaindepositsbyblock(
self.sidechain_number,
Some(end),
start,
)
.await?;
let mut last_block_hash = None;
let mut last_total = 0;
let mut outputs = HashMap::new();
for deposit in &deposits {
let transaction = hex::decode(&deposit.txhex)?;
let transaction =
bitcoin::Transaction::consensus_decode(&mut std::io::Cursor::new(transaction))?;
let transaction = bitcoin::Transaction::consensus_decode(
&mut std::io::Cursor::new(transaction),
)?;
if let Some(start) = start {
if deposit.hashblock == start {
last_total = transaction.output[deposit.nburnindex].value;
Expand Down Expand Up @@ -125,7 +136,10 @@ impl<C> Drivechain<C> {
Ok(statuses)
}

pub fn new(sidechain_number: u8, main_addr: SocketAddr) -> Result<Self, Error> {
pub fn new(
sidechain_number: u8,
main_addr: SocketAddr,
) -> Result<Self, Error> {
let mut headers = HeaderMap::new();
let auth = format!("{}:{}", "user", "password");
let header_value = format!(
Expand Down
12 changes: 9 additions & 3 deletions src/mempool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ use serde::{Deserialize, Serialize};

#[derive(Clone)]
pub struct MemPool<A, C> {
pub transactions: Database<OwnedType<[u8; 32]>, SerdeBincode<AuthorizedTransaction<A, C>>>,
pub transactions: Database<
OwnedType<[u8; 32]>,
SerdeBincode<AuthorizedTransaction<A, C>>,
>,
pub spent_utxos: Database<SerdeBincode<OutPoint>, Unit>,
}

Expand Down Expand Up @@ -40,8 +43,11 @@ impl<
}
self.spent_utxos.put(txn, input, &())?;
}
self.transactions
.put(txn, &transaction.transaction.txid().into(), &transaction)?;
self.transactions.put(
txn,
&transaction.transaction.txid().into(),
&transaction,
)?;
Ok(())
}

Expand Down
15 changes: 11 additions & 4 deletions src/miner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ pub struct Miner<A, C> {
}

impl<A: Clone, C: Clone + GetValue + Serialize> Miner<A, C> {
pub fn new(sidechain_number: u8, main_addr: SocketAddr) -> Result<Self, Error> {
pub fn new(
sidechain_number: u8,
main_addr: SocketAddr,
) -> Result<Self, Error> {
let drivechain = Drivechain::new(sidechain_number, main_addr)?;
Ok(Self {
drivechain,
Expand Down Expand Up @@ -55,14 +58,18 @@ impl<A: Clone, C: Clone + GetValue + Serialize> Miner<A, C> {
)
.await
.map_err(crate::drivechain::Error::from)?;
bitcoin::Txid::from_str(value["txid"]["txid"].as_str().ok_or(Error::InvalidJson)?)
.map_err(crate::drivechain::Error::from)?;
bitcoin::Txid::from_str(
value["txid"]["txid"].as_str().ok_or(Error::InvalidJson)?,
)
.map_err(crate::drivechain::Error::from)?;
assert_eq!(header.merkle_root, body.compute_merkle_root());
self.block = Some((header, body));
Ok(())
}

pub async fn confirm_bmm(&mut self) -> Result<Option<(Header, Body<A, C>)>, Error> {
pub async fn confirm_bmm(
&mut self,
) -> Result<Option<(Header, Body<A, C>)>, Error> {
if let Some((header, body)) = self.block.clone() {
self.drivechain.verify_bmm(&header).await?;
self.block = None;
Expand Down
12 changes: 9 additions & 3 deletions src/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,10 @@ impl Net {
Ok(peer)
}

pub async fn disconnect(&self, stable_id: usize) -> Result<Option<Peer>, Error> {
pub async fn disconnect(
&self,
stable_id: usize,
) -> Result<Option<Peer>, Error> {
let peer = self.peers.write().await.remove(&stable_id);
Ok(peer)
}
Expand All @@ -139,7 +142,9 @@ pub fn make_client_endpoint(bind_addr: SocketAddr) -> Result<Endpoint, Error> {
/// - a stream of incoming QUIC connections
/// - server certificate serialized into DER format
#[allow(unused)]
pub fn make_server_endpoint(bind_addr: SocketAddr) -> Result<(Endpoint, Vec<u8>), Error> {
pub fn make_server_endpoint(
bind_addr: SocketAddr,
) -> Result<(Endpoint, Vec<u8>), Error> {
let (server_config, server_cert) = configure_server()?;
let endpoint = Endpoint::server(server_config, bind_addr)?;
Ok((endpoint, server_cert))
Expand All @@ -153,7 +158,8 @@ fn configure_server() -> Result<(ServerConfig, Vec<u8>), Error> {
let priv_key = rustls::PrivateKey(priv_key);
let cert_chain = vec![rustls::Certificate(cert_der.clone())];

let mut server_config = ServerConfig::with_single_cert(cert_chain, priv_key)?;
let mut server_config =
ServerConfig::with_single_cert(cert_chain, priv_key)?;
let transport_config = Arc::get_mut(&mut server_config.transport).unwrap();
transport_config.max_concurrent_uni_streams(1_u8.into());

Expand Down
Loading

0 comments on commit 4a52f34

Please sign in to comment.