Skip to content

Commit

Permalink
use tracing library, instead of log.
Browse files Browse the repository at this point in the history
  • Loading branch information
b-yap committed May 9, 2024
1 parent 7f2bced commit 74c01ca
Show file tree
Hide file tree
Showing 14 changed files with 46 additions and 42 deletions.
2 changes: 1 addition & 1 deletion clients/stellar-relay-lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ wallet = { path = "../wallet" }

[dependencies]
hex = "0.4.3"
log = {version = "0.4.14"}
tracing = { version = "0.1", features = ["log"] }

base64 = "0.13.0"
rand = "0.8.5"
Expand Down
2 changes: 1 addition & 1 deletion clients/stellar-relay-lib/examples/connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
ScpStatementPledges::ScpStExternalize(_) => "ScpStExternalize",
ScpStatementPledges::ScpStNominate(_) => "ScpStNominate ",
};
log::info!(
tracing::info!(
"{} sent StellarMessage of type {} for ledger {}",
node_id,
stmt_type,
Expand Down
2 changes: 1 addition & 1 deletion clients/stellar-relay-lib/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ impl StellarOverlayConfig {

let public_key = secret_key.get_public().to_encoding();
let public_key = std::str::from_utf8(&public_key).unwrap();
log::info!(
tracing::info!(
"connection_info(): Connecting to Stellar overlay network using public key: {public_key}"
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ pub fn create_auth_cert(

let signature: Signature = Signature::new(keypair.create_signature(raw_sig_data).to_vec())
.map_err(|e| {
log::error!("create_auth_cert(): {e:?}");
tracing::error!("create_auth_cert(): {e:?}");
Error::AuthSignatureFailed
})?;

Expand Down Expand Up @@ -87,7 +87,7 @@ pub fn verify_remote_auth_cert(
match auth_cert_sig.try_into() {
Ok(raw_sig) => remote_pub_key.verify_signature(raw_data, &raw_sig),
Err(_) => {
log::warn!(
tracing::warn!(
"failed to convert auth cert signature of size {} to fixed array of 64.",
sig_len
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use substrate_stellar_sdk::{
types::{AuthenticatedMessageV0, Curve25519Public, HmacSha256Mac, MessageType},
XdrCodec,
};
use tracing::{debug, error, trace};

use crate::{
connection::{
Expand Down Expand Up @@ -86,7 +87,7 @@ impl Connector {
body: &[u8],
) -> Result<(), Error> {
let remote_info = self.remote_info.as_ref().ok_or(Error::NoRemoteInfo)?;
log::trace!(
trace!(
"verify_auth(): remote sequence: {}, auth message sequence: {}",
remote_info.sequence(),
auth_msg.sequence
Expand All @@ -96,7 +97,7 @@ impl Connector {
let auth_msg_xdr =
String::from_utf8(auth_msg_xdr.clone()).unwrap_or(format!("{:?}", auth_msg_xdr));

log::debug!("verify_auth(): received auth message from Stellar Node: {auth_msg_xdr}");
debug!("verify_auth(): received auth message from Stellar Node: {auth_msg_xdr}");

if remote_info.sequence() != auth_msg.sequence {
// must be handled on main thread because workers could mix up order of messages.
Expand Down Expand Up @@ -169,7 +170,7 @@ impl Connector {

pub fn stop(&mut self) {
if let Err(e) = self.tcp_stream.shutdown(Shutdown::Both) {
log::error!("stop(): failed to shutdown tcp stream: {}", e);
error!("stop(): failed to shutdown tcp stream: {}", e);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use substrate_stellar_sdk::{
types::{ErrorCode, Hello, MessageType, StellarMessage},
XdrCodec,
};

use tracing::{error, warn, trace};
use crate::connection::{
authentication::verify_remote_auth_cert,
helper::{error_to_string, time_now},
Expand Down Expand Up @@ -33,13 +33,13 @@ impl Connector {

MessageType::ErrorMsg => match auth_msg.message {
StellarMessage::ErrorMsg(e) => {
log::error!(
error!(
"process_raw_message(): Received ErrorMsg during authentication: {}",
error_to_string(e.clone())
);
return Err(Error::from(e))
},
other => log::error!(
other => error!(
"process_raw_message(): Received ErrorMsg during authentication: {:?}",
other
),
Expand All @@ -50,7 +50,7 @@ impl Connector {
if self.is_handshake_created() {
self.verify_auth(&auth_msg, &data[4..(data.len() - 32)])?;
self.increment_remote_sequence()?;
log::trace!(
trace!(
"process_raw_message(): Processing {msg_type:?} message: auth verified"
);
}
Expand Down Expand Up @@ -80,15 +80,15 @@ impl Connector {
} else {
self.send_auth_message().await?;
}
log::info!("process_stellar_message(): Hello message processed successfully");
info!("process_stellar_message(): Hello message processed successfully");
},

StellarMessage::Auth(_) => {
self.process_auth_message().await?;
},

StellarMessage::ErrorMsg(e) => {
log::error!(
error!(
"process_stellar_message(): Received ErrorMsg during authentication: {e:?}"
);
if e.code == ErrorCode::ErrConf || e.code == ErrorCode::ErrAuth {
Expand All @@ -98,7 +98,7 @@ impl Connector {
},

other => {
log::trace!(
trace!(
"process_stellar_message(): Processing {} message: received from overlay",
String::from_utf8(other.to_base64_xdr())
.unwrap_or(format!("{:?}", other.to_base64_xdr()))
Expand All @@ -124,7 +124,7 @@ impl Connector {
remote.node().overlay_version,
);
} else {
log::warn!("process_auth_message(): No remote overlay version after handshake.");
warn!("process_auth_message(): No remote overlay version after handshake.");
}

self.check_to_send_more(MessageType::Auth).await
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::connection::{xdr_converter::get_xdr_message_length, Connector, Error,
use async_std::io::ReadExt;
use substrate_stellar_sdk::{types::StellarMessage, XdrCodec};
use tokio::sync::{mpsc, mpsc::error::TryRecvError};

use tracing::{debug, error, info, trace, warn};
/// Polls for messages coming from the Stellar Node and communicates it back to the user
///
/// # Arguments
Expand All @@ -15,11 +15,11 @@ pub(crate) async fn poll_messages_from_stellar(
send_to_user_sender: mpsc::Sender<StellarMessage>,
mut send_to_node_receiver: mpsc::Receiver<StellarMessage>,
) {
log::info!("poll_messages_from_stellar(): started.");
info!("poll_messages_from_stellar(): started.");

loop {
if send_to_user_sender.is_closed() {
log::info!("poll_messages_from_stellar(): closing receiver during disconnection");
info!("poll_messages_from_stellar(): closing receiver during disconnection");
// close this channel as communication to user was closed.
break
}
Expand All @@ -28,7 +28,7 @@ pub(crate) async fn poll_messages_from_stellar(
match send_to_node_receiver.try_recv() {
Ok(msg) =>
if let Err(e) = connector.send_to_node(msg).await {
log::error!("poll_messages_from_stellar(): Error occurred during sending message to node: {e:?}");
error!("poll_messages_from_stellar(): Error occurred during sending message to node: {e:?}");
},
Err(TryRecvError::Disconnected) => break,
Err(TryRecvError::Empty) => {},
Expand All @@ -37,7 +37,7 @@ pub(crate) async fn poll_messages_from_stellar(
// check for messages from Stellar Node.
let xdr = match read_message_from_stellar(&mut connector).await {
Err(e) => {
log::error!("poll_messages_from_stellar(): {e:?}");
error!("poll_messages_from_stellar(): {e:?}");
break
},
Ok(xdr) => xdr,
Expand All @@ -47,14 +47,14 @@ pub(crate) async fn poll_messages_from_stellar(
Ok(Some(stellar_msg)) =>
// push message to user
if let Err(e) = send_to_user_sender.send(stellar_msg.clone()).await {
log::warn!("poll_messages_from_stellar(): Error occurred during sending message {} to user: {e:?}",
warn!("poll_messages_from_stellar(): Error occurred during sending message {} to user: {e:?}",
String::from_utf8(stellar_msg.to_base64_xdr())
.unwrap_or_else(|_| format!("{:?}", stellar_msg.to_base64_xdr()))
);
},
Ok(None) => {},
Err(e) => {
log::error!("poll_messages_from_stellar(): Error occurred during processing xdr message: {e:?}");
error!("poll_messages_from_stellar(): Error occurred during processing xdr message: {e:?}");
break
},
}
Expand All @@ -65,7 +65,7 @@ pub(crate) async fn poll_messages_from_stellar(
send_to_node_receiver.close();
drop(send_to_user_sender);

log::debug!("poll_messages_from_stellar(): stopped.");
debug!("poll_messages_from_stellar(): stopped.");
}

/// Returns Xdr format of the `StellarMessage` sent from the Stellar Node
Expand All @@ -89,7 +89,7 @@ async fn read_message_from_stellar(connector: &mut Connector) -> Result<Xdr, Err
// If it's not enough, skip it.
if expect_msg_len == 0 {
// there's nothing to read; wait for the next iteration
log::trace!("read_message_from_stellar(): expect_msg_len == 0");
trace!("read_message_from_stellar(): expect_msg_len == 0");
continue
}

Expand All @@ -107,7 +107,7 @@ async fn read_message_from_stellar(connector: &mut Connector) -> Result<Xdr, Err
Ok(None) => continue,
Ok(Some(xdr)) => return Ok(xdr),
Err(e) => {
log::trace!("read_message_from_stellar(): ERROR: {e:?}");
trace!("read_message_from_stellar(): ERROR: {e:?}");
return Err(e)
},
}
Expand All @@ -126,14 +126,14 @@ async fn read_message_from_stellar(connector: &mut Connector) -> Result<Xdr, Err
Ok(None) => continue,
Ok(Some(xdr)) => return Ok(xdr),
Err(e) => {
log::trace!("read_message_from_stellar(): ERROR: {e:?}");
trace!("read_message_from_stellar(): ERROR: {e:?}");
return Err(e)
},
}
},

Err(e) => {
log::trace!("read_message_from_stellar(): ERROR reading messages: {e:?}");
trace!("read_message_from_stellar(): ERROR reading messages: {e:?}");
return Err(Error::ReadFailed(e.to_string()))
},
}
Expand Down Expand Up @@ -170,7 +170,7 @@ async fn read_message(
// save it and read it on the next loop.
*lack_bytes_from_prev = xpect_msg_len - actual_msg_len;
*readbuf = readbuf[0..actual_msg_len].to_owned();
log::trace!(
trace!(
"read_message(): received only partial message. Need {lack_bytes_from_prev} bytes to complete."
);

Expand Down Expand Up @@ -201,7 +201,7 @@ async fn read_unfinished_message(

// this partial message completes the previous message.
if actual_msg_len == *lack_bytes_from_prev {
log::trace!("read_unfinished_message(): received continuation from the previous message.");
trace!("read_unfinished_message(): received continuation from the previous message.");
readbuf.append(&mut cont_buf);

return Ok(Some(readbuf.clone()))
Expand All @@ -212,7 +212,7 @@ async fn read_unfinished_message(
*lack_bytes_from_prev -= actual_msg_len;
cont_buf = cont_buf[0..actual_msg_len].to_owned();
readbuf.append(&mut cont_buf);
log::trace!(
trace!(
"read_unfinished_message(): not enough bytes to complete the previous message. Need {lack_bytes_from_prev} bytes to complete."
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use async_std::io::WriteExt;
use std::time::Duration;
use substrate_stellar_sdk::types::{MessageType, SendMore, StellarMessage};
use tokio::time::timeout;
use tracing::info;

use crate::connection::{
flow_controller::MAX_FLOOD_MSG_CAP,
Expand All @@ -28,14 +29,14 @@ impl Connector {

pub async fn send_hello_message(&mut self) -> Result<(), Error> {
let msg = self.create_hello_message(time_now())?;
log::info!("send_hello_message(): Sending Hello Message: {}", to_base64_xdr_string(&msg));
info!("send_hello_message(): Sending Hello Message: {}", to_base64_xdr_string(&msg));

self.send_to_node(msg).await
}

pub(super) async fn send_auth_message(&mut self) -> Result<(), Error> {
let msg = create_auth_message();
log::info!("send_auth_message(): Sending Auth Message: {}", to_base64_xdr_string(&msg));
info!("send_auth_message(): Sending Auth Message: {}", to_base64_xdr_string(&msg));

self.send_to_node(create_auth_message()).await
}
Expand Down
2 changes: 1 addition & 1 deletion clients/stellar-relay-lib/src/connection/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ impl From<substrate_stellar_sdk::types::Error> for Error {
ErrorCode::ErrConf => Self::ConfigError(error_to_string(value)),
ErrorCode::ErrAuth => Self::AuthFailed(error_to_string(value)),
other => {
log::error!("Stellar Node returned error: {}", error_to_string(value));
tracing::error!("Stellar Node returned error: {}", error_to_string(value));
Self::OverlayError(other)
},
}
Expand Down
2 changes: 1 addition & 1 deletion clients/stellar-relay-lib/src/connection/handshake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub fn create_hello_message(
overlay_min_version: node_info.overlay_min_version,
network_id: node_info.network_id,
version_str: LimitedString::<100>::new(version_str.clone()).map_err(|e| {
log::error!("create_hello_message(): {e:?}");
tracing::error!("create_hello_message(): {e:?}");
Error::VersionStrTooLong
})?,
listening_port: i32::try_from(listening_port).unwrap_or(11625),
Expand Down
2 changes: 1 addition & 1 deletion clients/stellar-relay-lib/src/connection/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub fn secret_key_binary(key: &str) -> [u8; 32] {
pub fn time_now() -> u64 {
let valid_at = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis();
u64::try_from(valid_at).unwrap_or_else(|_| {
log::warn!("could not convert time at u128 to u64.");
tracing::warn!("could not convert time at u128 to u64.");
u64::MAX
})
}
Expand Down
5 changes: 3 additions & 2 deletions clients/stellar-relay-lib/src/connection/hmac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::Error;
use hmac::{Hmac, Mac};
use sha2::Sha256;
use substrate_stellar_sdk::types::{HmacSha256Mac, Uint256};
use tracing::warn;

pub struct HMacKeys {
sending: HmacSha256Mac,
Expand Down Expand Up @@ -95,13 +96,13 @@ pub fn create_sha256_hmac(data_buffer: &[u8], mac_key_buffer: &Buffer) -> Option
return match hmac_vec.try_into() {
Ok(mac) => Some(HmacSha256Mac { mac }),
Err(_) => {
log::warn!("failed to convert hmac of size {} into an array of 32.", hmac_vec_len);
warn!("failed to convert hmac of size {} into an array of 32.", hmac_vec_len);
None
},
}
}

log::warn!("Invalid length of mac key buffer size {}", mac_key_buffer.len());
warn!("Invalid length of mac key buffer size {}", mac_key_buffer.len());
None
}

Expand Down
2 changes: 1 addition & 1 deletion clients/stellar-relay-lib/src/connection/xdr_converter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ fn message_to_bytes<T: XdrCodec>(message: &T) -> Result<Vec<u8>, Error> {
}

pub fn log_decode_error<T: Debug>(source: &str, error: T) -> Error {
log::error!("decode error: {:?}", error);
tracing::error!("decode error: {:?}", error);
Error::DecodeError(source.to_string())
}

Expand Down
7 changes: 4 additions & 3 deletions clients/stellar-relay-lib/src/overlay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use tokio::sync::{
Sender,
},
};
use tracing::{error, info};

use crate::{
connection::{poll_messages_from_stellar, ConnectionInfo, Connector},
Expand Down Expand Up @@ -34,7 +35,7 @@ impl StellarOverlayConnection {
local_node_info: NodeInfo,
conn_info: ConnectionInfo,
) -> Result<Self, Error> {
log::info!("connect(): connecting to {conn_info:?}");
info!("connect(): connecting to {conn_info:?}");

// this is a channel to communicate with the user/caller.
let (send_to_user_sender, send_to_user_receiver) = mpsc::channel::<StellarMessage>(1024);
Expand Down Expand Up @@ -63,7 +64,7 @@ impl StellarOverlayConnection {

match self.receiver.try_recv() {
Ok(StellarMessage::ErrorMsg(e)) => {
log::error!("listen(): received error message: {e:?}");
error!("listen(): received error message: {e:?}");
if e.code == ErrorCode::ErrConf || e.code == ErrorCode::ErrAuth {
return Err(Error::ConnectionFailed(error_to_string(e)))
}
Expand All @@ -88,7 +89,7 @@ impl StellarOverlayConnection {
}

pub fn stop(&mut self) {
log::info!("stop(): closing connection to overlay network");
info!("stop(): closing connection to overlay network");
self.receiver.close();
}
}
Expand Down

0 comments on commit 74c01ca

Please sign in to comment.