mirror of
https://github.com/talaia-labs/rust-teos.git
synced 2026-08-20 13:28:17 +02:00
Formats strings to use inline params when possible
This commit is contained in:
parent
125709be65
commit
4bcfbf7c5d
24 changed files with 165 additions and 258 deletions
|
|
@ -95,7 +95,7 @@ impl std::str::FromStr for AppointmentStatus {
|
|||
"being_watched" => Ok(AppointmentStatus::BeingWatched),
|
||||
"dispute_responded" => Ok(AppointmentStatus::DisputeResponded),
|
||||
"not_found" => Ok(AppointmentStatus::NotFound),
|
||||
_ => Err(format!("Unknown status: {}", s)),
|
||||
_ => Err(format!("Unknown status: {s}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -107,7 +107,7 @@ impl fmt::Display for AppointmentStatus {
|
|||
AppointmentStatus::DisputeResponded => "dispute_responded",
|
||||
AppointmentStatus::NotFound => "not_found",
|
||||
};
|
||||
write!(f, "{}", s)
|
||||
write!(f, "{s}")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -75,8 +75,7 @@ impl TryFrom<serde_json::Value> for UserId {
|
|||
UserId::try_from(a.pop().unwrap())
|
||||
} else {
|
||||
Err(format!(
|
||||
"Unexpected json format. Expected a single parameter. Received: {}",
|
||||
param_count
|
||||
"Unexpected json format. Expected a single parameter. Received: {param_count}"
|
||||
))
|
||||
}
|
||||
}
|
||||
|
|
@ -84,8 +83,7 @@ impl TryFrom<serde_json::Value> for UserId {
|
|||
let param_count = m.len();
|
||||
if param_count > 1 {
|
||||
Err(format!(
|
||||
"Unexpected json format. Expected a single parameter. Received: {}",
|
||||
param_count
|
||||
"Unexpected json format. Expected a single parameter. Received: {param_count}"
|
||||
))
|
||||
} else {
|
||||
UserId::try_from(json!(m
|
||||
|
|
@ -95,8 +93,7 @@ impl TryFrom<serde_json::Value> for UserId {
|
|||
}
|
||||
}
|
||||
_ => Err(format!(
|
||||
"Unexpected request format. Expected: user_id/tower_id. Received: '{}'",
|
||||
value
|
||||
"Unexpected request format. Expected: user_id/tower_id. Received: '{value}'"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,6 @@ impl std::fmt::Display for Endpoint {
|
|||
|
||||
impl Endpoint {
|
||||
pub fn path(&self) -> String {
|
||||
format!("/{}", self)
|
||||
format!("/{self}")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ impl std::str::FromStr for AddressType {
|
|||
match s {
|
||||
"ipv4" => Ok(AddressType::IpV4),
|
||||
"torv3" => Ok(AddressType::TorV3),
|
||||
_ => Err(format!("Unknown type: {}", s)),
|
||||
_ => Err(format!("Unknown type: {s}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -38,7 +38,7 @@ impl fmt::Display for AddressType {
|
|||
AddressType::IpV4 => "ipv4",
|
||||
AddressType::TorV3 => "torv3",
|
||||
};
|
||||
write!(f, "{}", s)
|
||||
write!(f, "{s}")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -36,14 +36,14 @@ impl ApiError {
|
|||
|
||||
fn missing_field(field_name: &str) -> Rejection {
|
||||
reject::custom(Self::new(
|
||||
format!("missing field `{}`", field_name),
|
||||
format!("missing field `{field_name}`"),
|
||||
errors::MISSING_FIELD,
|
||||
))
|
||||
}
|
||||
|
||||
fn empty_field(field_name: &str) -> Rejection {
|
||||
reject::custom(Self::new(
|
||||
format!("`{}` field is empty", field_name),
|
||||
format!("`{field_name}` field is empty"),
|
||||
errors::EMPTY_FIELD,
|
||||
))
|
||||
}
|
||||
|
|
@ -51,8 +51,7 @@ impl ApiError {
|
|||
fn wrong_field_length(field_name: &str, field_size: usize, expected_size: usize) -> Rejection {
|
||||
reject::custom(Self::new(
|
||||
format!(
|
||||
"Wrong `{}` field size. Expected {}, received {}",
|
||||
field_name, expected_size, field_size
|
||||
"Wrong `{field_name}` field size. Expected {expected_size}, received {field_size}"
|
||||
),
|
||||
errors::WRONG_FIELD_SIZE,
|
||||
))
|
||||
|
|
@ -104,7 +103,7 @@ fn parse_grpc_response<T: serde::Serialize>(
|
|||
}
|
||||
Err(s) => {
|
||||
let (status_code, error_code) = match_status(&s);
|
||||
log::debug!("Request failed, error_code={}", error_code);
|
||||
log::debug!("Request failed, error_code={error_code}");
|
||||
log::debug!("Response: {}", serde_json::json!(s.message()));
|
||||
(
|
||||
reply::json(&ApiError::new(s.message().into(), error_code)),
|
||||
|
|
|
|||
|
|
@ -133,7 +133,7 @@ impl PublicTowerServices for Arc<InternalAPI> {
|
|||
)),
|
||||
AddAppointmentFailure::SubscriptionExpired(x) => Err(Status::new(
|
||||
Code::Unauthenticated,
|
||||
format!("Your subscription expired at {}", x),
|
||||
format!("Your subscription expired at {x}"),
|
||||
)),
|
||||
AddAppointmentFailure::AlreadyTriggered => Err(Status::new(
|
||||
Code::AlreadyExists,
|
||||
|
|
@ -191,7 +191,7 @@ impl PublicTowerServices for Arc<InternalAPI> {
|
|||
)),
|
||||
GetAppointmentFailure::SubscriptionExpired(x) => Err(Status::new(
|
||||
Code::Unauthenticated,
|
||||
format!("Your subscription expired at {}", x),
|
||||
format!("Your subscription expired at {x}"),
|
||||
)),
|
||||
},
|
||||
}
|
||||
|
|
@ -213,7 +213,7 @@ impl PublicTowerServices for Arc<InternalAPI> {
|
|||
),
|
||||
GetSubscriptionInfoFailure::SubscriptionExpired(x) => Status::new(
|
||||
Code::Unauthenticated,
|
||||
format!("Your subscription expired at {}", x),
|
||||
format!("Your subscription expired at {x}"),
|
||||
),
|
||||
})?;
|
||||
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ impl TorAPI {
|
|||
log::info!("Loading Tor secret key from disk");
|
||||
let key = fs::read(path.join("onion_v3_sk"))
|
||||
.await
|
||||
.map_err(|e| log::warn!("Tor secret key cannot be loaded. {}", e))
|
||||
.map_err(|e| log::warn!("Tor secret key cannot be loaded. {e}"))
|
||||
.ok()?;
|
||||
let key: [u8; 64] = key
|
||||
.try_into()
|
||||
|
|
@ -62,7 +62,7 @@ impl TorAPI {
|
|||
/// Stores a Tor key to disk.
|
||||
async fn store_sk(key: &TorSecretKeyV3, path: PathBuf) {
|
||||
if let Err(e) = fs::write(path.join("onion_v3_sk"), key.as_bytes()).await {
|
||||
log::error!("Cannot store Tor secret key. {}", e);
|
||||
log::error!("Cannot store Tor secret key. {e}");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -125,7 +125,7 @@ impl TorAPI {
|
|||
.map_err(|e| {
|
||||
Error::new(
|
||||
ErrorKind::Other,
|
||||
format!("failed to create onion hidden service: {}", e),
|
||||
format!("failed to create onion hidden service: {e}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
|
|
|
|||
|
|
@ -79,7 +79,7 @@ impl<'a> BitcoindClient<'a> {
|
|||
teos_network: &'a str,
|
||||
) -> std::io::Result<BitcoindClient<'a>> {
|
||||
let http_endpoint = HttpEndpoint::for_host(host.to_owned()).with_port(port);
|
||||
let rpc_credentials = base64::encode(&format!("{}:{}", rpc_user, rpc_password));
|
||||
let rpc_credentials = base64::encode(&format!("{rpc_user}:{rpc_password}"));
|
||||
let bitcoind_rpc_client = RpcClient::new(&rpc_credentials, http_endpoint)?;
|
||||
|
||||
let client = Self {
|
||||
|
|
@ -97,10 +97,7 @@ impl<'a> BitcoindClient<'a> {
|
|||
if btc_network != teos_network {
|
||||
Err(Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
format!(
|
||||
"bitcoind is running on {} but teosd is set to run on {}",
|
||||
btc_network, teos_network
|
||||
),
|
||||
format!("bitcoind is running on {btc_network} but teosd is set to run on {teos_network}"),
|
||||
))
|
||||
} else {
|
||||
Ok(client)
|
||||
|
|
|
|||
|
|
@ -96,11 +96,11 @@ impl Carrier {
|
|||
Err(JsonRpcError(RpcError(rpcerr))) => match rpcerr.code {
|
||||
// Since we're pushing a raw transaction to the network we can face several rejections
|
||||
rpc_errors::RPC_VERIFY_REJECTED => {
|
||||
log::error!("Transaction couldn't be broadcast. {:?}", rpcerr);
|
||||
log::error!("Transaction couldn't be broadcast. {rpcerr:?}");
|
||||
ConfirmationStatus::Rejected(rpc_errors::RPC_VERIFY_REJECTED)
|
||||
}
|
||||
rpc_errors::RPC_VERIFY_ERROR => {
|
||||
log::error!("Transaction couldn't be broadcast. {:?}", rpcerr);
|
||||
log::error!("Transaction couldn't be broadcast. {rpcerr:?}");
|
||||
ConfirmationStatus::Rejected(rpc_errors::RPC_VERIFY_ERROR)
|
||||
}
|
||||
rpc_errors::RPC_VERIFY_ALREADY_IN_CHAIN => {
|
||||
|
|
@ -122,10 +122,7 @@ impl Carrier {
|
|||
}
|
||||
_ => {
|
||||
// If something else happens (unlikely but possible) log it so we can treat it in future releases.
|
||||
log::error!(
|
||||
"Unexpected rpc error when calling sendrawtransaction: {:?}",
|
||||
rpcerr
|
||||
);
|
||||
log::error!("Unexpected rpc error when calling sendrawtransaction: {rpcerr:?}");
|
||||
ConfirmationStatus::Rejected(errors::UNKNOWN_JSON_RPC_EXCEPTION)
|
||||
}
|
||||
},
|
||||
|
|
@ -137,7 +134,7 @@ impl Carrier {
|
|||
}
|
||||
Err(e) => {
|
||||
// TODO: This may need finer catching.
|
||||
log::error!("Unexpected error when calling sendrawtransaction: {:?}", e);
|
||||
log::error!("Unexpected error when calling sendrawtransaction: {e:?}");
|
||||
ConfirmationStatus::Rejected(errors::UNKNOWN_JSON_RPC_EXCEPTION)
|
||||
}
|
||||
};
|
||||
|
|
@ -159,15 +156,12 @@ impl Carrier {
|
|||
Ok(tx) => tx.blockhash.is_none(),
|
||||
Err(JsonRpcError(RpcError(rpcerr))) => match rpcerr.code {
|
||||
rpc_errors::RPC_INVALID_ADDRESS_OR_KEY => {
|
||||
log::info!("Transaction not found in mempool: {}", txid);
|
||||
log::info!("Transaction not found in mempool: {txid}");
|
||||
false
|
||||
}
|
||||
e => {
|
||||
// DISCUSS: This could result in a silent error with unknown consequences
|
||||
log::error!(
|
||||
"Unexpected error code when calling getrawtransaction: {}",
|
||||
e
|
||||
);
|
||||
log::error!("Unexpected error code when calling getrawtransaction: {e}");
|
||||
false
|
||||
}
|
||||
},
|
||||
|
|
@ -180,10 +174,7 @@ impl Carrier {
|
|||
// TODO: This may need finer catching.
|
||||
Err(e) => {
|
||||
// DISCUSS: This could result in a silent error with unknown consequences
|
||||
log::error!(
|
||||
"Unexpected JSONRPCError when calling getrawtransaction: {}",
|
||||
e
|
||||
);
|
||||
log::error!("Unexpected JSONRPCError when calling getrawtransaction: {e}");
|
||||
false
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -100,7 +100,7 @@ where
|
|||
Err(e) => match e.kind() {
|
||||
BlockSourceErrorKind::Persistent => {
|
||||
// FIXME: This may need finer catching
|
||||
log::error!("Unexpected persistent error: {:?}", e);
|
||||
log::error!("Unexpected persistent error: {e:?}");
|
||||
}
|
||||
BlockSourceErrorKind::Transient => {
|
||||
// Treating all transient as connection errors at least for now.
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ async fn main() {
|
|||
|
||||
// Create data dir if it does not exist
|
||||
fs::create_dir_all(&path).await.unwrap_or_else(|e| {
|
||||
eprintln!("Cannot create data dir: {:?}", e);
|
||||
eprintln!("Cannot create data dir: {e:?}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
|
|
@ -51,13 +51,13 @@ async fn main() {
|
|||
.expect("Cannot create channel from endpoint")
|
||||
.tls_config(tls)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("Could not configure tls: {:?}", e);
|
||||
eprintln!("Could not configure tls: {e:?}");
|
||||
std::process::exit(1);
|
||||
})
|
||||
.connect()
|
||||
.await
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("Could not connect to tower: {:?}", e);
|
||||
eprintln!("Could not connect to tower: {e:?}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
|
|
@ -83,7 +83,7 @@ async fn main() {
|
|||
Err(status) => println!("{}", status.message()),
|
||||
}
|
||||
}
|
||||
Err(e) => println!("{}", e),
|
||||
Err(e) => println!("{e}"),
|
||||
};
|
||||
}
|
||||
Command::GetTowerInfo => {
|
||||
|
|
@ -109,7 +109,7 @@ async fn main() {
|
|||
Err(status) => println!("{}", status.message()),
|
||||
}
|
||||
}
|
||||
Err(e) => println!("{}", e),
|
||||
Err(e) => println!("{e}"),
|
||||
};
|
||||
}
|
||||
Command::Stop => {
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ pub fn from_file<T: Default + serde::de::DeserializeOwned>(path: PathBuf) -> T {
|
|||
match std::fs::read(path) {
|
||||
Ok(file_content) => toml::from_slice::<T>(&file_content).map_or_else(
|
||||
|e| {
|
||||
eprintln!("Couldn't parse config file: {}", e);
|
||||
eprintln!("Couldn't parse config file: {e}");
|
||||
T::default()
|
||||
},
|
||||
|config| config,
|
||||
|
|
|
|||
|
|
@ -107,11 +107,11 @@ impl DBM {
|
|||
],
|
||||
) {
|
||||
Ok(x) => {
|
||||
log::debug!("User successfully stored: {}", user_id);
|
||||
log::debug!("User successfully stored: {user_id}");
|
||||
Ok(x)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Couldn't store user: {}. Error: {:?}", user_id, e);
|
||||
log::error!("Couldn't store user: {user_id}. Error: {e:?}");
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
|
|
@ -131,10 +131,10 @@ impl DBM {
|
|||
],
|
||||
) {
|
||||
Ok(_) => {
|
||||
log::debug!("User's info successfully updated: {}", user_id);
|
||||
log::debug!("User's info successfully updated: {user_id}");
|
||||
}
|
||||
Err(_) => {
|
||||
log::error!("User not found, data cannot be updated: {}", user_id);
|
||||
log::error!("User not found, data cannot be updated: {user_id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -205,18 +205,15 @@ impl DBM {
|
|||
let query = "DELETE FROM users WHERE user_id IN ".to_owned();
|
||||
let placeholders = format!("(?{})", (", ?").repeat(chunk.len() - 1));
|
||||
|
||||
match tx.execute(
|
||||
&format!("{}{}", query, placeholders),
|
||||
params_from_iter(chunk),
|
||||
) {
|
||||
match tx.execute(&format!("{query}{placeholders}"), params_from_iter(chunk)) {
|
||||
Ok(_) => log::debug!("Users deletion added to db transaction"),
|
||||
Err(e) => log::error!("Couldn't add deletion query to transaction. Error: {:?}", e),
|
||||
Err(e) => log::error!("Couldn't add deletion query to transaction. Error: {e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
match tx.commit() {
|
||||
Ok(_) => log::debug!("Users successfully deleted"),
|
||||
Err(e) => log::error!("Couldn't delete users. Error: {:?}", e),
|
||||
Err(e) => log::error!("Couldn't delete users. Error: {e:?}"),
|
||||
}
|
||||
|
||||
(users.len() as f64 / limit as f64).ceil() as usize
|
||||
|
|
@ -242,11 +239,11 @@ impl DBM {
|
|||
],
|
||||
) {
|
||||
Ok(x) => {
|
||||
log::debug!("Appointment successfully stored: {}", uuid);
|
||||
log::debug!("Appointment successfully stored: {uuid}");
|
||||
Ok(x)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Couldn't store appointment: {}. Error: {:?}", uuid, e);
|
||||
log::error!("Couldn't store appointment: {uuid}. Error: {e:?}");
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
|
|
@ -268,10 +265,10 @@ impl DBM {
|
|||
],
|
||||
) {
|
||||
Ok(_) => {
|
||||
log::debug!("Appointment successfully updated: {}", uuid);
|
||||
log::debug!("Appointment successfully updated: {uuid}");
|
||||
}
|
||||
Err(_) => {
|
||||
log::error!("Appointment not found, data cannot be updated: {}", uuid);
|
||||
log::error!("Appointment not found, data cannot be updated: {uuid}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -360,10 +357,10 @@ impl DBM {
|
|||
let query = "DELETE FROM appointments WHERE UUID=(?)";
|
||||
match self.remove_data(query, params![uuid.to_vec()]) {
|
||||
Ok(_) => {
|
||||
log::debug!("Appointment successfully removed: {}", uuid);
|
||||
log::debug!("Appointment successfully removed: {uuid}");
|
||||
}
|
||||
Err(_) => {
|
||||
log::error!("Appointment not found, data cannot be removed: {}", uuid);
|
||||
log::error!("Appointment not found, data cannot be removed: {uuid}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -386,12 +383,9 @@ impl DBM {
|
|||
let query = "DELETE FROM appointments WHERE UUID IN ".to_owned();
|
||||
let placeholders = format!("(?{})", (", ?").repeat(chunk.len() - 1));
|
||||
|
||||
match tx.execute(
|
||||
&format!("{}{}", query, placeholders),
|
||||
params_from_iter(chunk),
|
||||
) {
|
||||
match tx.execute(&format!("{query}{placeholders}"), params_from_iter(chunk)) {
|
||||
Ok(_) => log::debug!("Appointments deletion added to db transaction"),
|
||||
Err(e) => log::error!("Couldn't add deletion query to transaction. Error: {:?}", e),
|
||||
Err(e) => log::error!("Couldn't add deletion query to transaction. Error: {e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -399,13 +393,13 @@ impl DBM {
|
|||
let query = "UPDATE users SET available_slots=(?1) WHERE user_id=(?2)";
|
||||
match tx.execute(query, params![info.available_slots, id.to_vec(),]) {
|
||||
Ok(_) => log::debug!("User update added to db transaction"),
|
||||
Err(e) => log::error!("Couldn't add update query to transaction. Error: {:?}", e),
|
||||
Err(e) => log::error!("Couldn't add update query to transaction. Error: {e:?}"),
|
||||
};
|
||||
}
|
||||
|
||||
match tx.commit() {
|
||||
Ok(_) => log::debug!("Appointments successfully deleted"),
|
||||
Err(e) => log::error!("Couldn't delete appointments. Error: {:?}", e),
|
||||
Err(e) => log::error!("Couldn't delete appointments. Error: {e:?}"),
|
||||
}
|
||||
|
||||
(appointments.len() as f64 / limit as f64).ceil() as usize
|
||||
|
|
@ -446,11 +440,11 @@ impl DBM {
|
|||
],
|
||||
) {
|
||||
Ok(x) => {
|
||||
log::debug!("Tracker successfully stored: {}", uuid);
|
||||
log::debug!("Tracker successfully stored: {uuid}");
|
||||
Ok(x)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Couldn't store tracker: {}. Error: {:?}", uuid, e);
|
||||
log::error!("Couldn't store tracker: {uuid}. Error: {e:?}");
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ async fn main() {
|
|||
|
||||
// Create data dir if it does not exist
|
||||
fs::create_dir_all(&path).unwrap_or_else(|e| {
|
||||
eprintln!("Cannot create data dir: {:?}", e);
|
||||
eprintln!("Cannot create data dir: {e:?}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
|
|
@ -81,7 +81,7 @@ async fn main() {
|
|||
let is_default = conf.is_default();
|
||||
conf.patch_with_options(opt);
|
||||
conf.verify().unwrap_or_else(|e| {
|
||||
eprintln!("{}", e);
|
||||
eprintln!("{e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
|
|
@ -112,7 +112,7 @@ async fn main() {
|
|||
// Create network dir
|
||||
let path_network = path.join(conf.btc_network.clone());
|
||||
fs::create_dir_all(&path_network).unwrap_or_else(|e| {
|
||||
eprintln!("Cannot create network dir: {:?}", e);
|
||||
eprintln!("Cannot create network dir: {e:?}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
let dbm = Arc::new(Mutex::new(
|
||||
|
|
@ -136,7 +136,7 @@ async fn main() {
|
|||
}
|
||||
}
|
||||
};
|
||||
log::info!("tower_id: {}", tower_pk);
|
||||
log::info!("tower_id: {tower_pk}");
|
||||
|
||||
// Initialize our bitcoind client
|
||||
let (bitcoin_cli, bitcoind_reachable) = match BitcoindClient::new(
|
||||
|
|
@ -157,7 +157,7 @@ async fn main() {
|
|||
ErrorKind::InvalidData => "invalid btcrpcuser or btcrpcpassword".into(),
|
||||
_ => e.to_string(),
|
||||
};
|
||||
log::error!("Failed to connect to bitcoind. Error: {}", e_msg);
|
||||
log::error!("Failed to connect to bitcoind. Error: {e_msg}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
|
@ -171,7 +171,7 @@ async fn main() {
|
|||
};
|
||||
let rpc = Arc::new(
|
||||
Client::new(
|
||||
&format!("{}{}:{}", schema, conf.btc_rpc_connect, conf.btc_rpc_port),
|
||||
&format!("{schema}{}:{}", conf.btc_rpc_connect, conf.btc_rpc_port),
|
||||
Auth::UserPass(conf.btc_rpc_user.clone(), conf.btc_rpc_password.clone()),
|
||||
)
|
||||
.unwrap(),
|
||||
|
|
@ -196,8 +196,7 @@ async fn main() {
|
|||
// could pull from the backend. Adding this functionality just for regtest seemed unnecessary though, hence the check.
|
||||
if tip.height < IRREVOCABLY_RESOLVED {
|
||||
log::error!(
|
||||
"Not enough blocks to start teosd (required: {}). Mine at least {} more",
|
||||
IRREVOCABLY_RESOLVED,
|
||||
"Not enough blocks to start teosd (required: {IRREVOCABLY_RESOLVED}). Mine at least {} more",
|
||||
IRREVOCABLY_RESOLVED - tip.height
|
||||
);
|
||||
std::process::exit(1);
|
||||
|
|
@ -323,7 +322,7 @@ async fn main() {
|
|||
// Generate mtls certificates to data directory so the admin can securely connect
|
||||
// to the server to perform administrative tasks.
|
||||
let (identity, ca_cert) = tls_init(&path).unwrap_or_else(|e| {
|
||||
eprintln!("Couldn't generate tls certificates: {:?}", e);
|
||||
eprintln!("Couldn't generate tls certificates: {e:?}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
|
|
@ -370,7 +369,7 @@ async fn main() {
|
|||
.expose_onion_service(tor_service_ready, shutdown_signal_tor)
|
||||
.await
|
||||
{
|
||||
eprintln!("Cannot connect to the Tor backend: {}", e);
|
||||
eprintln!("Cannot connect to the Tor backend: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}));
|
||||
|
|
|
|||
|
|
@ -263,7 +263,7 @@ impl Responder {
|
|||
.unwrap()
|
||||
.store_tracker(uuid, &tracker)
|
||||
.unwrap();
|
||||
log::info!("New tracker added (uuid={}).", uuid);
|
||||
log::info!("New tracker added (uuid={uuid})");
|
||||
}
|
||||
|
||||
/// Checks whether a given tracker can be found in the [Responder].
|
||||
|
|
@ -318,7 +318,7 @@ impl Responder {
|
|||
// Tracker is deep enough in the chain, it can be deleted
|
||||
completed_trackers.insert(*uuid);
|
||||
} else {
|
||||
log::info!("{} received a confirmation (count={})", uuid, confirmations);
|
||||
log::info!("{uuid} received a confirmation (count={confirmations})");
|
||||
}
|
||||
} else if txids.contains(&tracker.penalty_txid) {
|
||||
// First confirmation was received
|
||||
|
|
@ -423,9 +423,8 @@ impl Responder {
|
|||
let status = carrier.send_transaction(&dispute_tx);
|
||||
if let ConfirmationStatus::Rejected(e) = status {
|
||||
log::error!(
|
||||
"Reorged dispute transaction rejected during rebroadcast: {} (reason: {:?})",
|
||||
dispute_tx.txid(),
|
||||
e
|
||||
"Reorged dispute transaction rejected during rebroadcast: {} (reason: {e})",
|
||||
dispute_tx.txid()
|
||||
);
|
||||
status
|
||||
} else {
|
||||
|
|
@ -466,9 +465,9 @@ impl Responder {
|
|||
let mut tx_tracker_map = self.tx_tracker_map.lock().unwrap();
|
||||
for uuid in uuids.iter() {
|
||||
match reason {
|
||||
DeletionReason::Completed => log::info!("Appointment completed. Penalty transaction was irrevocably confirmed: {}", uuid),
|
||||
DeletionReason::Outdated => log::info!("Appointment couldn't be completed. Expiry reached but penalty didn't make it to the chain: {}", uuid),
|
||||
DeletionReason::Rejected => log::info!("Appointment couldn't be completed. Either the dispute or the penalty txs where rejected during rebroadcast: {}", uuid),
|
||||
DeletionReason::Completed => log::info!("Appointment completed. Penalty transaction was irrevocably confirmed: {uuid}"),
|
||||
DeletionReason::Outdated => log::info!("Appointment couldn't be completed. Expiry reached but penalty didn't make it to the chain: {uuid}"),
|
||||
DeletionReason::Rejected => log::info!("Appointment couldn't be completed. Either the dispute or the penalty txs where rejected during rebroadcast: {uuid}"),
|
||||
}
|
||||
|
||||
match trackers.remove(uuid) {
|
||||
|
|
@ -488,7 +487,7 @@ impl Responder {
|
|||
}
|
||||
None => {
|
||||
// This should never happen. Logging just in case so we can fix it if so
|
||||
log::error!("Completed tracker not found when cleaning: {}", uuid);
|
||||
log::error!("Completed tracker not found when cleaning: {uuid}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -67,21 +67,14 @@ fn generate_or_load_identity(
|
|||
parent: Option<&Identity>,
|
||||
) -> Result<Identity, GenCertificateFailure> {
|
||||
// Just our naming convention here.
|
||||
let cert_path = directory.join(format!("{}.pem", filename));
|
||||
let key_path = directory.join(format!("{}-key.pem", filename));
|
||||
let cert_path = directory.join(format!("{filename}.pem"));
|
||||
let key_path = directory.join(format!("{filename}-key.pem"));
|
||||
// Did we have to generate a new key? In that case we also need to regenerate the certificate.
|
||||
if !key_path.exists() || !cert_path.exists() {
|
||||
log::debug!(
|
||||
"Generating a new keypair in {:?}, it didn't exist",
|
||||
&key_path
|
||||
);
|
||||
log::debug!("Generating a new keypair in {key_path:?}, it didn't exist",);
|
||||
let keypair = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?;
|
||||
std::fs::write(&key_path, keypair.serialize_pem())?;
|
||||
log::debug!(
|
||||
"Generating a new certificate for key {:?} at {:?}",
|
||||
&key_path,
|
||||
&cert_path
|
||||
);
|
||||
log::debug!("Generating a new certificate for key {key_path:?} at {cert_path:?}",);
|
||||
|
||||
// Configure the certificate we want.
|
||||
let subject_alt_names = vec!["cln".to_string(), "localhost".to_string()];
|
||||
|
|
|
|||
|
|
@ -189,7 +189,7 @@ where
|
|||
// Blocks should be disconnected from last backwards. Log if that's not the case so we can revisit this and fix it.
|
||||
if let Some(ref h) = self.blocks.pop_back() {
|
||||
if h != block_hash {
|
||||
log::error!("Disconnected block does not match the oldest block stored in the TxIndex ({} != {})", block_hash, h);
|
||||
log::error!("Disconnected block does not match the oldest block stored in the TxIndex ({block_hash} != {h})");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
|
@ -204,7 +204,7 @@ where
|
|||
let ks = self.tx_in_block.remove(&h).unwrap();
|
||||
self.index.retain(|k, _| !ks.contains(k));
|
||||
|
||||
log::info!("Oldest block removed from index: {}", h);
|
||||
log::info!("Oldest block removed from index: {h}");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -217,7 +217,7 @@ impl Watcher {
|
|||
let uuid = UUID::new(extended_appointment.locator(), user_id);
|
||||
|
||||
if self.responder.has_tracker(uuid) {
|
||||
log::info!("Tracker for {} already found in Responder", uuid);
|
||||
log::info!("Tracker for {uuid} already found in Responder");
|
||||
return Err(AddAppointmentFailure::AlreadyTriggered);
|
||||
}
|
||||
|
||||
|
|
@ -286,9 +286,8 @@ impl Watcher {
|
|||
.insert(uuid)
|
||||
{
|
||||
log::debug!(
|
||||
"Adding an additional appointment to locator {}: {}",
|
||||
appointment.locator(),
|
||||
uuid
|
||||
"Adding an additional appointment to locator {}: {uuid}",
|
||||
appointment.locator()
|
||||
);
|
||||
self.dbm
|
||||
.lock()
|
||||
|
|
@ -297,7 +296,7 @@ impl Watcher {
|
|||
.unwrap();
|
||||
StoredAppointment::Collision
|
||||
} else {
|
||||
log::debug!("Update received for {}, locator map not modified", uuid);
|
||||
log::debug!("Update received for {uuid}, locator map not modified");
|
||||
self.dbm
|
||||
.lock()
|
||||
.unwrap()
|
||||
|
|
@ -339,7 +338,7 @@ impl Watcher {
|
|||
) {
|
||||
// DISCUSS: We could either free the slots or keep it occupied as if this was misbehavior.
|
||||
// Keeping it for now.
|
||||
log::warn!("Appointment bounced in the Responder. Reason: {:?}", reason);
|
||||
log::warn!("Appointment bounced in the Responder. Reason: {reason:?}");
|
||||
|
||||
self.dbm.lock().unwrap().remove_appointment(uuid);
|
||||
TriggeredAppointment::Rejected
|
||||
|
|
@ -375,7 +374,7 @@ impl Watcher {
|
|||
locator: Locator,
|
||||
user_signature: &str,
|
||||
) -> Result<AppointmentInfo, GetAppointmentFailure> {
|
||||
let message = format!("get appointment {}", locator);
|
||||
let message = format!("get appointment {locator}");
|
||||
|
||||
let user_id = self
|
||||
.gatekeeper
|
||||
|
|
@ -405,7 +404,7 @@ impl Watcher {
|
|||
.get_tracker(uuid)
|
||||
.map(AppointmentInfo::Tracker)
|
||||
.ok_or_else(|| {
|
||||
log::info!("Cannot find {}", locator);
|
||||
log::info!("Cannot find {locator}");
|
||||
GetAppointmentFailure::NotFound
|
||||
})
|
||||
}
|
||||
|
|
@ -511,16 +510,14 @@ impl Watcher {
|
|||
|
||||
for uuid in uuids {
|
||||
match reason {
|
||||
DeletionReason::Outdated => log::info!(
|
||||
"End time reached by {} without breach. Deleting appointment",
|
||||
uuid
|
||||
),
|
||||
DeletionReason::Outdated => {
|
||||
log::info!("End time reached by {uuid} without breach. Deleting appointment")
|
||||
}
|
||||
DeletionReason::Invalid => log::info!(
|
||||
"{} cannot be completed, it contains invalid data. Deleting appointment",
|
||||
uuid
|
||||
"{uuid} cannot be completed, it contains invalid data. Deleting appointment"
|
||||
),
|
||||
DeletionReason::Accepted => {
|
||||
log::info!("{} accepted by the Responder. Deleting appointment", uuid)
|
||||
log::info!("{uuid} accepted by the Responder. Deleting appointment")
|
||||
}
|
||||
};
|
||||
match appointments.remove(uuid) {
|
||||
|
|
@ -537,7 +534,7 @@ impl Watcher {
|
|||
}
|
||||
None => {
|
||||
// This should never happen. Logging just in case so we can fix it if so
|
||||
log::error!("Appointment not found when cleaning: {}", uuid);
|
||||
log::error!("Appointment not found when cleaning: {uuid}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -642,12 +639,11 @@ impl Watcher {
|
|||
match dbm.load_locator(*uuid) {
|
||||
Ok(locator) => locators.push(locator),
|
||||
Err(_) => log::error!(
|
||||
"Tracker found in Responder but not in DB (uuid = {})",
|
||||
uuid
|
||||
"Tracker found in Responder but not in DB (uuid = {uuid})"
|
||||
),
|
||||
}
|
||||
} else {
|
||||
log::error!("Appointment found in the Gatekeeper but not in the Watcher nor the Responder (uuid = {})", uuid)
|
||||
log::error!("Appointment found in the Gatekeeper but not in the Watcher nor the Responder (uuid = {uuid})")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -703,10 +699,7 @@ impl chain::Listen for Watcher {
|
|||
let mut appointments_to_delete = HashSet::from_iter(invalid_breaches.into_keys());
|
||||
let mut delivered_appointments = HashSet::new();
|
||||
for (uuid, breach) in valid_breaches {
|
||||
log::info!(
|
||||
"Notifying Responder and deleting appointment (uuid: {})",
|
||||
uuid
|
||||
);
|
||||
log::info!("Notifying Responder and deleting appointment (uuid: {uuid})");
|
||||
|
||||
if let ConfirmationStatus::Rejected(_) = self.responder.handle_breach(
|
||||
uuid,
|
||||
|
|
|
|||
|
|
@ -22,10 +22,10 @@ pub enum RegisterError {
|
|||
impl std::fmt::Display for RegisterError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
RegisterError::InvalidId(x) => write!(f, "{}", x),
|
||||
RegisterError::InvalidHost(x) => write!(f, "{}", x),
|
||||
RegisterError::InvalidPort(x) => write!(f, "{}", x),
|
||||
RegisterError::InvalidFormat(x) => write!(f, "{}", x),
|
||||
RegisterError::InvalidId(x) => write!(f, "{x}"),
|
||||
RegisterError::InvalidHost(x) => write!(f, "{x}"),
|
||||
RegisterError::InvalidPort(x) => write!(f, "{x}"),
|
||||
RegisterError::InvalidFormat(x) => write!(f, "{x}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -80,8 +80,7 @@ impl RegisterParams {
|
|||
fn with_port(self, port: u64) -> Result<Self, RegisterError> {
|
||||
if port > u16::MAX as u64 {
|
||||
Err(RegisterError::InvalidPort(format!(
|
||||
"port must be a 16-byte integer. Received: {}",
|
||||
port
|
||||
"port must be a 16-byte integer. Received: {port}"
|
||||
)))
|
||||
} else {
|
||||
Ok(Self {
|
||||
|
|
@ -109,7 +108,7 @@ impl TryFrom<serde_json::Value> for RegisterParams {
|
|||
let port = if let Some(p) = v.next() {
|
||||
p.parse()
|
||||
.map(Some)
|
||||
.map_err(|_| RegisterError::InvalidPort(format!("Port is not a number: {}", p)))?
|
||||
.map_err(|_| RegisterError::InvalidPort(format!("Port is not a number: {p}")))?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
|
@ -128,14 +127,14 @@ impl TryFrom<serde_json::Value> for RegisterParams {
|
|||
let tower_id = a.get(0).unwrap().as_str().ok_or_else(|| RegisterError::InvalidId("tower_id must be a string".to_string()))?;
|
||||
let host = Some(a.get(1).unwrap().as_str().ok_or_else(|| RegisterError::InvalidHost("host must be a string".to_string()))?);
|
||||
let port = if let Some(p) = a.get(2) {
|
||||
Some(p.as_u64().ok_or_else(|| RegisterError::InvalidPort(format!("port must be a number. Received: {}", p)))?)
|
||||
Some(p.as_u64().ok_or_else(|| RegisterError::InvalidPort(format!("port must be a number. Received: {p}")))?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
RegisterParams::new(tower_id, host, port)
|
||||
}
|
||||
_ => Err(RegisterError::InvalidFormat(format!("Unexpected request format. The request needs 1-3 parameters. Received: {}", param_count))),
|
||||
_ => Err(RegisterError::InvalidFormat(format!("Unexpected request format. The request needs 1-3 parameters. Received: {param_count}"))),
|
||||
}
|
||||
},
|
||||
serde_json::Value::Object(mut m) => {
|
||||
|
|
@ -143,7 +142,7 @@ impl TryFrom<serde_json::Value> for RegisterParams {
|
|||
let param_count = m.len();
|
||||
|
||||
if m.is_empty() || param_count > allowed_keys.len() {
|
||||
Err(RegisterError::InvalidFormat(format!("Unexpected request format. The request needs 1-3 parameters. Received: {}", param_count)))
|
||||
Err(RegisterError::InvalidFormat(format!("Unexpected request format. The request needs 1-3 parameters. Received: {param_count}")))
|
||||
} else if !m.contains_key(allowed_keys[0]){
|
||||
Err(RegisterError::InvalidId(format!("{} is mandatory", allowed_keys[0])))
|
||||
} else if !m.iter().all(|(k, _)| allowed_keys.contains(&k.as_str())) {
|
||||
|
|
@ -160,7 +159,7 @@ impl TryFrom<serde_json::Value> for RegisterParams {
|
|||
}
|
||||
},
|
||||
_ => Err(RegisterError::InvalidFormat(
|
||||
format!("Unexpected request format. Expected: 'tower_id[@host][:port]' or 'tower_id [host] [port]'. Received: '{}'", value),
|
||||
format!("Unexpected request format. Expected: 'tower_id[@host][:port]' or 'tower_id [host] [port]'. Received: '{value}'"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
|
@ -177,9 +176,9 @@ pub enum GetAppointmentError {
|
|||
impl std::fmt::Display for GetAppointmentError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
GetAppointmentError::InvalidId(x) => write!(f, "{}", x),
|
||||
GetAppointmentError::InvalidLocator(x) => write!(f, "{}", x),
|
||||
GetAppointmentError::InvalidFormat(x) => write!(f, "{}", x),
|
||||
GetAppointmentError::InvalidId(x) => write!(f, "{x}"),
|
||||
GetAppointmentError::InvalidLocator(x) => write!(f, "{x}"),
|
||||
GetAppointmentError::InvalidFormat(x) => write!(f, "{x}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -200,8 +199,7 @@ impl TryFrom<serde_json::Value> for GetAppointmentParams {
|
|||
let param_count = a.len();
|
||||
if param_count != 2 {
|
||||
Err(GetAppointmentError::InvalidFormat(format!(
|
||||
"Unexpected request format. The request needs 2 parameter. Received: {}",
|
||||
param_count
|
||||
"Unexpected request format. The request needs 2 parameter. Received: {param_count}"
|
||||
)))
|
||||
} else {
|
||||
let tower_id = if let Some(s) = a.get(0).unwrap().as_str() {
|
||||
|
|
@ -240,8 +238,7 @@ impl TryFrom<serde_json::Value> for GetAppointmentParams {
|
|||
for k in allowed_keys.iter() {
|
||||
if !m.contains_key(*k) {
|
||||
return Err(GetAppointmentError::InvalidFormat(format!(
|
||||
"{} is mandatory",
|
||||
k
|
||||
"{k} is mandatory"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
|
@ -255,8 +252,7 @@ impl TryFrom<serde_json::Value> for GetAppointmentParams {
|
|||
GetAppointmentParams::try_from(json!(params))
|
||||
}
|
||||
_ => Err(GetAppointmentError::InvalidFormat(format!(
|
||||
"Unexpected request format. Expected: tower_id locator. Received: '{}'",
|
||||
value
|
||||
"Unexpected request format. Expected: tower_id locator. Received: '{value}'"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
|
@ -338,21 +334,18 @@ mod tests {
|
|||
#[test]
|
||||
fn test_try_from_json_string() {
|
||||
let ok = [
|
||||
format!("{}@host:80", VALID_ID),
|
||||
format!("{}@host", VALID_ID),
|
||||
format!("{VALID_ID}@host:80"),
|
||||
format!("{VALID_ID}@host"),
|
||||
VALID_ID.to_string(),
|
||||
];
|
||||
let wrong_id = ["", "id@host:80", "@host:80", "@:80"];
|
||||
let wrong_host = [
|
||||
format!("{}@", VALID_ID),
|
||||
format!("{}@ ", VALID_ID),
|
||||
format!("{}@ host", VALID_ID),
|
||||
format!("{}@:80", VALID_ID),
|
||||
];
|
||||
let wrong_port = [
|
||||
format!("{}@host:", VALID_ID),
|
||||
format!("{}@host:port", VALID_ID),
|
||||
format!("{VALID_ID}@"),
|
||||
format!("{VALID_ID}@ "),
|
||||
format!("{VALID_ID}@ host"),
|
||||
format!("{VALID_ID}@:80"),
|
||||
];
|
||||
let wrong_port = [format!("{VALID_ID}@host:"), format!("{VALID_ID}@host:port")];
|
||||
|
||||
for s in ok {
|
||||
let v = serde_json::Value::Array(vec![serde_json::Value::String(s.to_string())]);
|
||||
|
|
|
|||
|
|
@ -393,10 +393,7 @@ impl DBM {
|
|||
// TODO: Can this be prepared instead of formatted (using ?1 seems to fail)?
|
||||
let mut stmt = self
|
||||
.connection
|
||||
.prepare(&format!(
|
||||
"SELECT locator FROM {} WHERE tower_id = ?",
|
||||
status
|
||||
))
|
||||
.prepare(&format!("SELECT locator FROM {status} WHERE tower_id = ?"))
|
||||
.unwrap();
|
||||
|
||||
let mut rows = stmt.query(params![tower_id.to_vec()]).unwrap();
|
||||
|
|
@ -552,7 +549,7 @@ impl DBM {
|
|||
let mut appointments = Vec::new();
|
||||
let mut stmt = self
|
||||
.connection
|
||||
.prepare(&format!("SELECT a.locator, a.encrypted_blob, a.to_self_delay FROM appointments as a, {} as t WHERE a.locator = t.locator AND t.tower_id = ?", table))
|
||||
.prepare(&format!("SELECT a.locator, a.encrypted_blob, a.to_self_delay FROM appointments as a, {table} as t WHERE a.locator = t.locator AND t.tower_id = ?"))
|
||||
.unwrap();
|
||||
let mut rows = stmt.query([tower_id.to_vec()]).unwrap();
|
||||
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ fn to_cln_error(e: RequestError) -> Error {
|
|||
RequestError::DeserializeError(e) => anyhow!(e),
|
||||
RequestError::Unexpected(e) => anyhow!(e),
|
||||
};
|
||||
log::info!("{}", e);
|
||||
log::info!("{e}");
|
||||
e
|
||||
}
|
||||
|
||||
|
|
@ -50,11 +50,7 @@ fn send_to_retrier(state: &MutexGuard<WTClient>, tower_id: TowerId, locator: Loc
|
|||
.send((tower_id, RevocationData::Fresh(locator)))
|
||||
.unwrap();
|
||||
} else {
|
||||
log::debug!(
|
||||
"Not sending data to idle retrier ({}, {})",
|
||||
tower_id,
|
||||
locator
|
||||
)
|
||||
log::debug!("Not sending data to idle retrier ({tower_id}, {locator})")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -85,9 +81,9 @@ async fn register(
|
|||
|
||||
let tower_net_addr = {
|
||||
if !host.starts_with("http://") {
|
||||
host = format!("http://{}", host)
|
||||
host = format!("http://{host}")
|
||||
}
|
||||
NetAddr::new(format!("{}:{}", host, port))
|
||||
NetAddr::new(format!("{host}:{port}"))
|
||||
};
|
||||
|
||||
let proxy = plugin.state().lock().unwrap().proxy.clone();
|
||||
|
|
@ -141,10 +137,7 @@ async fn get_registration_receipt(
|
|||
let state = plugin.state().lock().unwrap();
|
||||
|
||||
let response = state.get_registration_receipt(tower_id).map_err(|_| {
|
||||
anyhow!(
|
||||
"Cannot find {} within the known towers. Have you registered?",
|
||||
tower_id
|
||||
)
|
||||
anyhow!("Cannot find {tower_id} within the known towers. Have you registered?")
|
||||
})?;
|
||||
|
||||
Ok(json!(response))
|
||||
|
|
@ -162,7 +155,7 @@ async fn get_subscription_info(
|
|||
if let Some(info) = state.towers.get(&tower_id) {
|
||||
Ok((state.user_sk, info.net_addr.clone(), state.proxy.clone()))
|
||||
} else {
|
||||
Err(anyhow!("Unknown tower id: {}", tower_id))
|
||||
Err(anyhow!("Unknown tower id: {tower_id}"))
|
||||
}
|
||||
}?;
|
||||
|
||||
|
|
@ -291,10 +284,7 @@ async fn get_tower_info(
|
|||
let state = plugin.state().lock().unwrap();
|
||||
let tower_id = TowerId::try_from(v).map_err(|e| anyhow!(e))?;
|
||||
let tower_info = state.load_tower_info(tower_id).map_err(|_| {
|
||||
anyhow!(
|
||||
"Cannot find {} within the known towers. Have you registered?",
|
||||
tower_id
|
||||
)
|
||||
anyhow!("Cannot find {tower_id} within the known towers. Have you registered?")
|
||||
})?;
|
||||
|
||||
// Notice we need to check the status in memory since we cannot distinguish between unreachable and temporary unreachable
|
||||
|
|
@ -323,7 +313,7 @@ async fn retry_tower(
|
|||
.map_err(|e| anyhow!(e))?;
|
||||
} else {
|
||||
// Status can only be running or idle for data in the retriers map.
|
||||
return Err(anyhow!("{} is already being retried", tower_id));
|
||||
return Err(anyhow!("{tower_id} is already being retried"));
|
||||
}
|
||||
} else if tower_status.is_retryable() {
|
||||
// We do send associated data here given there is no retrier associated to this tower.
|
||||
|
|
@ -349,9 +339,9 @@ async fn retry_tower(
|
|||
));
|
||||
}
|
||||
} else {
|
||||
return Err(anyhow!("Unknown tower {}", tower_id));
|
||||
return Err(anyhow!("Unknown tower {tower_id}"));
|
||||
}
|
||||
Ok(json!(format!("Retrying {}", tower_id)))
|
||||
Ok(json!(format!("Retrying {tower_id}")))
|
||||
}
|
||||
|
||||
/// Forgets about a tower wiping out all local data associated to it.
|
||||
|
|
@ -363,9 +353,9 @@ async fn abandon_tower(
|
|||
let mut state = plugin.state().lock().unwrap();
|
||||
if state.towers.get(&tower_id).is_some() {
|
||||
state.remove_tower(tower_id).unwrap();
|
||||
Ok(json!(format!("{} successfully abandoned", tower_id)))
|
||||
Ok(json!(format!("{tower_id} successfully abandoned")))
|
||||
} else {
|
||||
Err(anyhow!("Unknown tower {}", tower_id))
|
||||
Err(anyhow!("Unknown tower {tower_id}"))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -377,7 +367,7 @@ async fn on_commitment_revocation(
|
|||
v: serde_json::Value,
|
||||
) -> Result<serde_json::Value, Error> {
|
||||
let commitment_revocation = serde_json::from_value::<CommitmentRevocation>(v)
|
||||
.map_err(|e| anyhow!("Cannot decode commitment_revocation data. Error: {}", e))?;
|
||||
.map_err(|e| anyhow!("Cannot decode commitment_revocation data. Error: {e}"))?;
|
||||
log::debug!(
|
||||
"New commitment revocation received for channel {}. Commit number {}",
|
||||
commitment_revocation.channel_id,
|
||||
|
|
@ -430,8 +420,7 @@ async fn on_commitment_revocation(
|
|||
AddAppointmentError::RequestError(e) => {
|
||||
if e.is_connection() {
|
||||
log::warn!(
|
||||
"{} cannot be reached. Adding {} to pending appointments",
|
||||
tower_id,
|
||||
"{tower_id} cannot be reached. Adding {} to pending appointments",
|
||||
appointment.locator
|
||||
);
|
||||
let mut state = plugin.state().lock().unwrap();
|
||||
|
|
@ -443,8 +432,7 @@ async fn on_commitment_revocation(
|
|||
AddAppointmentError::ApiError(e) => match e.error_code {
|
||||
errors::INVALID_SIGNATURE_OR_SUBSCRIPTION_ERROR => {
|
||||
log::warn!(
|
||||
"There is a subscription issue with {}. Adding {} to pending",
|
||||
tower_id,
|
||||
"There is a subscription issue with {tower_id}. Adding {} to pending",
|
||||
appointment.locator
|
||||
);
|
||||
let mut state = plugin.state().lock().unwrap();
|
||||
|
|
@ -455,8 +443,7 @@ async fn on_commitment_revocation(
|
|||
|
||||
_ => {
|
||||
log::warn!(
|
||||
"{} rejected the appointment. Error: {}, error_code: {}",
|
||||
tower_id,
|
||||
"{tower_id} rejected the appointment. Error: {}, error_code: {}",
|
||||
e.error,
|
||||
e.error_code
|
||||
);
|
||||
|
|
@ -478,22 +465,16 @@ async fn on_commitment_revocation(
|
|||
},
|
||||
};
|
||||
} else if status.is_misbehaving() {
|
||||
log::warn!(
|
||||
"{} is misbehaving. Not sending any further appointments",
|
||||
tower_id
|
||||
);
|
||||
log::warn!("{tower_id} is misbehaving. Not sending any further appointments",);
|
||||
} else {
|
||||
if status.is_subscription_error() {
|
||||
log::warn!(
|
||||
"There is a subscription issue with {}. Adding {} to pending",
|
||||
tower_id,
|
||||
"There is a subscription issue with {tower_id}. Adding {} to pending",
|
||||
appointment.locator
|
||||
);
|
||||
} else {
|
||||
log::warn!(
|
||||
"{} is {}. Adding {} to pending",
|
||||
tower_id,
|
||||
status,
|
||||
"{tower_id} is {status}. Adding {} to pending",
|
||||
appointment.locator,
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,7 +62,7 @@ pub async fn register(
|
|||
tower_net_addr: &NetAddr,
|
||||
proxy: &Option<ProxyInfo>,
|
||||
) -> Result<RegistrationReceipt, RequestError> {
|
||||
log::info!("Registering in the Eye of Satoshi (tower_id={})", tower_id);
|
||||
log::info!("Registering in the Eye of Satoshi (tower_id={tower_id})");
|
||||
process_post_response(
|
||||
post_request(
|
||||
tower_net_addr,
|
||||
|
|
@ -95,13 +95,12 @@ pub async fn add_appointment(
|
|||
signature: &str,
|
||||
) -> Result<(u32, AppointmentReceipt), AddAppointmentError> {
|
||||
log::debug!(
|
||||
"Sending appointment {} to tower {}",
|
||||
appointment.locator,
|
||||
tower_id
|
||||
"Sending appointment {} to tower {tower_id}",
|
||||
appointment.locator
|
||||
);
|
||||
let (response, receipt) =
|
||||
send_appointment(tower_id, tower_net_addr, proxy, appointment, signature).await?;
|
||||
log::debug!("Appointment accepted and signed by {}", tower_id);
|
||||
log::debug!("Appointment accepted and signed by {tower_id}");
|
||||
log::debug!("Remaining slots: {}", response.available_slots);
|
||||
log::debug!("Start block: {}", response.start_block);
|
||||
|
||||
|
|
@ -167,10 +166,10 @@ pub async fn post_request<S: Serialize>(
|
|||
reqwest::Client::builder()
|
||||
.proxy(
|
||||
reqwest::Proxy::http(proxy.get_socks_addr())
|
||||
.map_err(|e| RequestError::ConnectionError(format!("{}", e)))?,
|
||||
.map_err(|e| RequestError::ConnectionError(format!("{e}")))?,
|
||||
)
|
||||
.build()
|
||||
.map_err(|e| RequestError::ConnectionError(format!("{}", e)))?
|
||||
.map_err(|e| RequestError::ConnectionError(format!("{e}")))?
|
||||
} else {
|
||||
reqwest::Client::new()
|
||||
}
|
||||
|
|
@ -190,7 +189,7 @@ pub async fn post_request<S: Serialize>(
|
|||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
log::debug!("An error ocurred when sending data to the tower: {}", e);
|
||||
log::debug!("An error ocurred when sending data to the tower: {e}");
|
||||
if e.is_connect() | e.is_timeout() {
|
||||
RequestError::ConnectionError(
|
||||
"Cannot connect to the tower. Connection refused".to_owned(),
|
||||
|
|
@ -210,7 +209,7 @@ pub async fn process_post_response<T: DeserializeOwned>(
|
|||
// TODO: Check if this can be switched for a map. Not sure how to handle async with maps
|
||||
match post_request {
|
||||
Ok(r) => r.json().await.map_err(|e| {
|
||||
RequestError::DeserializeError(format!("Unexpected response body. Error: {}", e))
|
||||
RequestError::DeserializeError(format!("Unexpected response body. Error: {e}"))
|
||||
}),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ enum RetryError {
|
|||
impl Display for RetryError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
RetryError::Subscription(r, _) => write!(f, "{}", r),
|
||||
RetryError::Subscription(r, _) => write!(f, "{r}"),
|
||||
RetryError::Unreachable => write!(f, "Tower cannot be reached"),
|
||||
RetryError::Misbehaving(_) => write!(f, "Tower misbehaved"),
|
||||
RetryError::Abandoned => write!(f, "Tower was abandoned. Skipping retry"),
|
||||
|
|
@ -99,11 +99,11 @@ impl RetryManager {
|
|||
.towers
|
||||
.contains_key(&tower_id)
|
||||
{
|
||||
log::info!("Skipping retrying abandoned tower {}", tower_id);
|
||||
log::info!("Skipping retrying abandoned tower {tower_id}");
|
||||
} else if let Some(retrier) = self.retriers.get(&tower_id) {
|
||||
if retrier.is_idle() {
|
||||
if !data.is_none() {
|
||||
log::error!("Data was send to an idle retier. This should have never happened. Please report! ({:?})", data);
|
||||
log::error!("Data was send to an idle retier. This should have never happened. Please report! ({data:?})");
|
||||
continue;
|
||||
}
|
||||
log::info!(
|
||||
|
|
@ -181,7 +181,7 @@ impl RetryManager {
|
|||
/// If the tower is not currently being retried, a new entry for it is created, otherwise, the data is appended to the existing entry.
|
||||
fn add_pending_appointments(&mut self, tower_id: TowerId, locators: HashSet<Locator>) {
|
||||
if let std::collections::hash_map::Entry::Vacant(e) = self.retriers.entry(tower_id) {
|
||||
log::debug!("Creating a new entry for tower {} ", tower_id);
|
||||
log::debug!("Creating a new entry for tower {tower_id}");
|
||||
e.insert(Arc::new(Retrier::new(
|
||||
self.wt_client.clone(),
|
||||
tower_id,
|
||||
|
|
@ -196,11 +196,7 @@ impl RetryManager {
|
|||
.lock()
|
||||
.unwrap();
|
||||
for locator in locators {
|
||||
log::debug!(
|
||||
"Adding pending appointment {} to existing tower {}",
|
||||
locator,
|
||||
tower_id
|
||||
);
|
||||
log::debug!("Adding pending appointment {locator} to existing tower {tower_id}",);
|
||||
pending_appointments.insert(locator);
|
||||
}
|
||||
}
|
||||
|
|
@ -373,7 +369,7 @@ impl Retrier {
|
|||
},
|
||||
|| async { self.run().await },
|
||||
|err, _| {
|
||||
log::warn!("Retry error happened with {}. {}", self.tower_id, err);
|
||||
log::warn!("Retry error happened with {}. {err}", self.tower_id);
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
|
@ -392,7 +388,7 @@ impl Retrier {
|
|||
Err(e) => {
|
||||
// Notice we'll end up here after a permanent error. That is, either after finishing the backoff strategy
|
||||
// unsuccessfully or by manually raising such an error (like when facing a tower misbehavior).
|
||||
log::warn!("Retry strategy gave up for {}. {}", self.tower_id, e);
|
||||
log::warn!("Retry strategy gave up for {}. {e}", self.tower_id);
|
||||
if e.is_permanent() {
|
||||
self.set_status(RetrierStatus::Failed);
|
||||
}
|
||||
|
|
@ -456,7 +452,7 @@ impl Retrier {
|
|||
let receipt = http::register(tower_id, user_id, &net_addr, &proxy)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
log::debug!("Cannot renew registration with tower. Error: {:?}", e);
|
||||
log::debug!("Cannot renew registration with tower. Error: {e:?}");
|
||||
Error::transient(RetryError::Subscription(
|
||||
"Cannot renew registration with tower".to_owned(),
|
||||
false,
|
||||
|
|
@ -516,15 +512,14 @@ impl Retrier {
|
|||
AddAppointmentError::RequestError(e) => {
|
||||
if e.is_connection() {
|
||||
log::warn!(
|
||||
"{} cannot be reached. Tower will be retried later",
|
||||
tower_id,
|
||||
"{tower_id} cannot be reached. Tower will be retried later"
|
||||
);
|
||||
return Err(Error::transient(RetryError::Unreachable));
|
||||
}
|
||||
}
|
||||
AddAppointmentError::ApiError(e) => match e.error_code {
|
||||
errors::INVALID_SIGNATURE_OR_SUBSCRIPTION_ERROR => {
|
||||
log::warn!("There is a subscription issue with {}", tower_id);
|
||||
log::warn!("There is a subscription issue with {tower_id}");
|
||||
self.wt_client
|
||||
.lock()
|
||||
.unwrap()
|
||||
|
|
@ -536,8 +531,7 @@ impl Retrier {
|
|||
}
|
||||
_ => {
|
||||
log::warn!(
|
||||
"{} rejected the appointment. Error: {}, error_code: {}",
|
||||
tower_id,
|
||||
"{tower_id} rejected the appointment. Error: {}, error_code: {}",
|
||||
e.error,
|
||||
e.error_code
|
||||
);
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ impl std::fmt::Debug for RevocationData {
|
|||
f,
|
||||
"{}",
|
||||
match self {
|
||||
RevocationData::Fresh(l) => format!("Fresh: {}", l),
|
||||
RevocationData::Fresh(l) => format!("Fresh: {l}"),
|
||||
RevocationData::Stale(hs) => format!(
|
||||
"Stale: {:?}",
|
||||
hs.iter().map(|l| l.to_string()).collect::<Vec<_>>()
|
||||
|
|
@ -90,7 +90,7 @@ impl WTClient {
|
|||
) -> Self {
|
||||
// Create data dir if it does not exist
|
||||
fs::create_dir_all(&data_dir).await.unwrap_or_else(|e| {
|
||||
log::error!("Cannot create data dir: {:?}", e);
|
||||
log::error!("Cannot create data dir: {e:?}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
|
|
@ -120,10 +120,7 @@ impl WTClient {
|
|||
}
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"Plugin watchtower client initialized. User id = {}",
|
||||
user_id
|
||||
);
|
||||
log::info!("Plugin watchtower client initialized. User id = {user_id}");
|
||||
|
||||
WTClient {
|
||||
towers,
|
||||
|
|
@ -206,14 +203,10 @@ impl WTClient {
|
|||
if tower.status != status {
|
||||
tower.status = status
|
||||
} else {
|
||||
log::debug!("{} status is already {}", tower_id, status)
|
||||
log::debug!("{tower_id} status is already {status}")
|
||||
}
|
||||
} else {
|
||||
log::error!(
|
||||
"Cannot change tower status to {}. Unknown tower_id: {}",
|
||||
status,
|
||||
tower_id
|
||||
);
|
||||
log::error!("Cannot change tower status to {status}. Unknown tower_id: {tower_id}");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -238,10 +231,7 @@ impl WTClient {
|
|||
.store_appointment_receipt(tower_id, locator, available_slots, receipt)
|
||||
.unwrap();
|
||||
} else {
|
||||
log::error!(
|
||||
"Cannot add appointment receipt to tower. Unknown tower_id: {}",
|
||||
tower_id
|
||||
);
|
||||
log::error!("Cannot add appointment receipt to tower. Unknown tower_id: {tower_id}");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -263,10 +253,7 @@ impl WTClient {
|
|||
.store_pending_appointment(tower_id, appointment)
|
||||
.unwrap();
|
||||
} else {
|
||||
log::error!(
|
||||
"Cannot add pending appointment to tower. Unknown tower_id: {}",
|
||||
tower_id
|
||||
);
|
||||
log::error!("Cannot add pending appointment to tower. Unknown tower_id: {tower_id}");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -279,10 +266,7 @@ impl WTClient {
|
|||
.delete_pending_appointment(tower_id, locator)
|
||||
.unwrap();
|
||||
} else {
|
||||
log::error!(
|
||||
"Cannot remove pending appointment to tower. Unknown tower_id: {}",
|
||||
tower_id
|
||||
);
|
||||
log::error!("Cannot remove pending appointment to tower. Unknown tower_id: {tower_id}");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -295,10 +279,7 @@ impl WTClient {
|
|||
.store_invalid_appointment(tower_id, appointment)
|
||||
.unwrap();
|
||||
} else {
|
||||
log::error!(
|
||||
"Cannot add invalid appointment to tower. Unknown tower_id: {}",
|
||||
tower_id
|
||||
);
|
||||
log::error!("Cannot add invalid appointment to tower. Unknown tower_id: {tower_id}");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -308,7 +289,7 @@ impl WTClient {
|
|||
self.dbm.store_misbehaving_proof(tower_id, &proof).unwrap();
|
||||
tower.status = TowerStatus::Misbehaving;
|
||||
} else {
|
||||
log::error!("Cannot flag tower. Unknown tower_id: {}", tower_id);
|
||||
log::error!("Cannot flag tower. Unknown tower_id: {tower_id}");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue