Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: fix linter warnings #2

Merged
merged 2 commits into from
Jun 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,8 @@ jobs:
- name: Build
run: cargo build

- name: Lint
run: cargo clippy

- name: Run tests
run: cargo test --verbose
14 changes: 7 additions & 7 deletions src/api/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ pub async fn post_covenant_claim(
return CovenantClaimResponse::Error(ErrorResponse {
error: format!(
"could not parse blinding key: {}",
blinding_key.err().unwrap().to_string()
blinding_key.err().unwrap()
),
});
}
Expand All @@ -97,7 +97,7 @@ pub async fn post_covenant_claim(
Ok(res) => res,
Err(err) => {
return CovenantClaimResponse::Error(ErrorResponse {
error: format!("could not parse swap tree: {}", err.to_string()),
error: format!("could not parse swap tree: {}", err),
})
}
};
Expand All @@ -109,15 +109,15 @@ pub async fn post_covenant_claim(
Ok(res) => res,
Err(err) => {
return CovenantClaimResponse::Error(ErrorResponse {
error: format!("could not parse refundPublicKey: {}", err.to_string()),
error: format!("could not parse refundPublicKey: {}", err),
})
}
},
match PublicKey::from_slice(body.claim_public_key.as_ref()) {
Ok(res) => res,
Err(err) => {
return CovenantClaimResponse::Error(ErrorResponse {
error: format!("could not parse claimPublicKey: {}", err.to_string()),
error: format!("could not parse claimPublicKey: {}", err),
})
}
},
Expand All @@ -126,7 +126,7 @@ pub async fn post_covenant_claim(
let internal_key = Vec::from(aggregate.agg_pk().serialize());

let preimage_hash: hashes::hash160::Hash = Hash::hash(body.preimage.clone().as_ref());
if Vec::from(preimage_hash.as_byte_array()) != covenant_details.preimage_hash {
if covenant_details.preimage_hash != *preimage_hash.as_byte_array() {
return CovenantClaimResponse::Error(ErrorResponse {
error: "invalid preimage".to_string(),
});
Expand All @@ -145,7 +145,7 @@ pub async fn post_covenant_claim(
&body
.tree
.clone()
.address(internal_key, &state.address_params)
.address(internal_key, state.address_params)
.script_pubkey(),
),
tx_id: None,
Expand All @@ -170,7 +170,7 @@ fn parse_address(
Ok(res) => res,
Err(err) => {
return Err(ErrorResponse {
error: format!("could not parse address: {}", err.to_string()),
error: format!("could not parse address: {}", err),
});
}
};
Expand Down
2 changes: 1 addition & 1 deletion src/api/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,5 @@ pub async fn start_server(
return Err(listener.err().unwrap());
}

return Ok(axum::serve(listener.unwrap(), app.clone()).await);
Ok(axum::serve(listener.unwrap(), app.clone()).await)
}
10 changes: 9 additions & 1 deletion src/boltz/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ pub struct Client {

impl Client {
pub fn new(endpoint: String) -> Self {
Client { endpoint }
Client {
endpoint: crate::utils::string::trim_suffix(endpoint, '/'),
}
}

pub async fn send_raw_transaction(&self, hex: String) -> Result<String, Box<dyn Error>> {
Expand Down Expand Up @@ -65,6 +67,12 @@ mod client_test {

const ENDPOINT: &str = "https://api.testnet.boltz.exchange/v2";

#[test]
fn test_trim_suffix() {
assert_eq!(Client::new(ENDPOINT.to_string() + "/").endpoint, ENDPOINT);
assert_eq!(Client::new(ENDPOINT.to_string()).endpoint, ENDPOINT);
}

#[tokio::test]
async fn test_send_raw_transaction_error_handling() {
let client = Client::new(ENDPOINT.to_string());
Expand Down
12 changes: 3 additions & 9 deletions src/chain/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl ChainClient {
};
trace!("Using Elements endpoint: {}", client.url);

return client;
client
}

pub async fn connect(mut self) -> Result<ChainClient, Box<dyn Error>> {
Expand All @@ -69,11 +69,7 @@ impl ChainClient {
self.cookie = Some(format!("Basic {}", BASE64_STANDARD.encode(file)));

let notifications = self.clone().get_zmq_notifications().await?;

match self.zmq_client.clone().connect(notifications).await {
Err(e) => return Err(e),
_ => {}
};
self.zmq_client.clone().connect(notifications).await?;

Ok(self)
}
Expand Down Expand Up @@ -143,9 +139,7 @@ impl ChainBackend for ChainClient {
}

async fn get_block(&self, hash: String) -> Result<Block, Box<dyn Error>> {
let mut params = Vec::<StringOrU64>::new();
params.push(StringOrU64::Str(hash));
params.push(StringOrU64::Num(0));
let params = vec![StringOrU64::Str(hash), StringOrU64::Num(0)];

let block_hex = self
.clone()
Expand Down
33 changes: 12 additions & 21 deletions src/chain/esplora.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,40 +39,31 @@ impl EsploraClient {
max_reqs_per_second: u64,
boltz_endpoint: String,
) -> Result<Self, Box<dyn Error>> {
let trimmed_endpoint = match endpoint.strip_suffix("/") {
Some(s) => s.to_string(),
None => endpoint,
};

let (tx_sender, tx_receiver) = crossbeam_channel::bounded::<Transaction>(1);
let (block_sender, block_receiver) = crossbeam_channel::unbounded::<Block>();

let rate_limit: Option<Arc<Ratelimiter>>;

if max_reqs_per_second > 0 {
let rate_limit = if max_reqs_per_second > 0 {
info!(
"Rate limiting requests to {} requests/second",
max_reqs_per_second
);
rate_limit = Some(Arc::new(
Some(Arc::new(
Ratelimiter::builder(max_reqs_per_second, Duration::from_secs(1))
.max_tokens(max_reqs_per_second)
.build()?,
));
))
} else {
info!("Not rate limiting");
rate_limit = None;
}

let boltz_client: Option<Client>;
None
};

if !boltz_endpoint.is_empty() {
let boltz_client = if !boltz_endpoint.is_empty() {
info!("Broadcasting transactions with Boltz API");
boltz_client = Some(Client::new(boltz_endpoint));
Some(Client::new(boltz_endpoint))
} else {
info!("Broadcasting transactions with Esplora");
boltz_client = None;
}
None
};

Ok(EsploraClient {
tx_sender,
Expand All @@ -82,7 +73,7 @@ impl EsploraClient {
boltz_client,
poll_interval,
block_receiver,
endpoint: trimmed_endpoint,
endpoint: crate::utils::string::trim_suffix(endpoint, '/'),
})
}

Expand Down Expand Up @@ -280,11 +271,11 @@ impl ChainBackend for EsploraClient {
}

fn get_tx_receiver(&self) -> Receiver<Transaction> {
return self.tx_receiver.clone();
self.tx_receiver.clone()
}

fn get_block_receiver(&self) -> Receiver<Block> {
return self.block_receiver.clone();
self.block_receiver.clone()
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/chain/zmq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ impl ZmqClient {
handler: F,
) -> Result<(), ZmqError>
where
F: Fn(ZmqMessage) -> () + Send + 'static,
F: Fn(ZmqMessage) + Send + 'static,
{
debug!(
"Connecting to {} ZMQ at {}",
Expand Down
15 changes: 7 additions & 8 deletions src/claimer/constructor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ impl Constructor {
Ok(_) => {}
Err(err) => {
warn!("Could not schedule covenant claim: {}", err);
return;
}
};
}
Expand All @@ -106,7 +105,7 @@ impl Constructor {
}
};

if covenants.len() == 0 {
if covenants.is_empty() {
return;
}

Expand Down Expand Up @@ -192,7 +191,7 @@ impl Constructor {
let is_blinded = prevout.asset.is_confidential() && prevout.value.is_confidential();
let tx_secrets = match is_blinded {
true => match prevout.unblind(
&secp,
secp,
match SecretKey::from_slice(
match covenant.clone().blinding_key {
Some(res) => res,
Expand Down Expand Up @@ -232,7 +231,7 @@ impl Constructor {
});

if is_blinded {
let mut rng = OsRng::default();
let mut rng = OsRng;

let op_return_script = Builder::new()
.push_opcode(opcodes::all::OP_RETURN)
Expand All @@ -241,13 +240,13 @@ impl Constructor {
let out_abf = AssetBlindingFactor::new(&mut rng);
let (blinded_asset, surjection_proof) = Asset::Explicit(utxo_asset).blind(
&mut rng,
&secp,
secp,
out_abf,
&[tx_secrets.unwrap()],
)?;

let final_vbf = ValueBlindingFactor::last(
&secp,
secp,
1,
out_abf,
&[(
Expand All @@ -269,9 +268,9 @@ impl Constructor {
],
);
let (blinded_value, nonce, rangeproof) = Value::Explicit(1).blind(
&secp,
secp,
final_vbf,
SecretKey::new(&mut rng).public_key(&secp),
SecretKey::new(&mut rng).public_key(secp),
SecretKey::new(&mut rng),
&op_return_script.clone(),
&elements::RangeProofMessage {
Expand Down
31 changes: 15 additions & 16 deletions src/claimer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,22 +216,21 @@ impl Claimer {
for vout in 0..tx.output.len() {
let out = &tx.output[vout];

match get_pending_covenant_for_output(self.db.clone(), out.script_pubkey.as_bytes()) {
Some(covenant) => {
info!(
"Found covenant {} to claim in {}:{}",
hex::encode(covenant.clone().output_script),
tx.txid().to_string(),
vout
);

self.clone()
.constructor
.schedule_broadcast(covenant, tx.clone())
.await;
}
None => {}
};
if let Some(covenant) =
get_pending_covenant_for_output(self.db.clone(), out.script_pubkey.as_bytes())
{
info!(
"Found covenant {} to claim in {}:{}",
hex::encode(covenant.clone().output_script),
tx.txid().to_string(),
vout
);

self.clone()
.constructor
.schedule_broadcast(covenant, tx.clone())
.await;
}
}
}
}
5 changes: 1 addition & 4 deletions src/claimer/tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,10 @@ impl SwapTree {
) -> Option<(TxOut, u32)> {
let script_pubkey = self.address(internal_key, params).script_pubkey();

let mut vout: u32 = 0;
for out in lockup_tx.output {
for (vout, out) in (0_u32..).zip(lockup_tx.output.into_iter()) {
if out.script_pubkey.eq(&script_pubkey) {
return Some((out, vout));
}

vout += 1;
}

None
Expand Down
4 changes: 2 additions & 2 deletions src/db/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub fn get_block_height(con: db::Pool) -> Option<u64> {
.load(&mut con.get().unwrap())
{
Ok(res) => {
if res.len() == 0 {
if res.is_empty() {
return None;
}

Expand Down Expand Up @@ -89,7 +89,7 @@ pub fn get_pending_covenant_for_output(con: db::Pool, script: &[u8]) -> Option<P
.load(&mut con.get().unwrap())
{
Ok(res) => {
if res.len() == 0 {
if res.is_empty() {
return None;
}

Expand Down
1 change: 1 addition & 0 deletions src/db/models.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use diesel::internal::derives::multiconnection::chrono;
use diesel::prelude::*;

#[derive(Copy, Clone)]
pub enum PendingCovenantStatus {
Pending = 0,
TransactionFound = 1,
Expand Down
3 changes: 2 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ mod boltz;
mod chain;
mod claimer;
mod db;
mod utils;

pub mod built_info {
include!(concat!(env!("OUT_DIR"), "/built.rs"));
Expand Down Expand Up @@ -139,7 +140,7 @@ async fn get_chain_backend() -> Arc<Box<dyn ChainBackend + Send + Sync>> {
}
};

return Arc::new(client);
Arc::new(client)
}

fn get_address_params() -> &'static AddressParams {
Expand Down
1 change: 1 addition & 0 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod string;
6 changes: 6 additions & 0 deletions src/utils/string.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
pub fn trim_suffix(string: String, suffix: char) -> String {
match string.strip_suffix(suffix) {
Some(s) => s.to_string(),
None => string,
}
}