Skip to content

Commit

Permalink
chore: clean swarm commands errs and spend errors
Browse files Browse the repository at this point in the history
  • Loading branch information
grumbach authored and joshuef committed Mar 5, 2024
1 parent 2421f95 commit 64402a2
Show file tree
Hide file tree
Showing 17 changed files with 158 additions and 160 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions sn_cli/src/subcommands/gossipsub.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub enum GossipsubCmds {
pub(crate) async fn gossipsub_cmds(cmds: GossipsubCmds, client: &Client) -> Result<()> {
match cmds {
GossipsubCmds::Subscribe { topic } => {
client.subscribe_to_topic(topic.clone())?;
client.subscribe_to_topic(topic.clone());
println!("Subscribed to topic '{topic}'. Listening for messages published on it...");
let mut events_channel = client.events_channel();
while let Ok(event) = events_channel.recv().await {
Expand All @@ -50,11 +50,11 @@ pub(crate) async fn gossipsub_cmds(cmds: GossipsubCmds, client: &Client) -> Resu
}
}
GossipsubCmds::Unsubscribe { topic } => {
client.unsubscribe_from_topic(topic.clone())?;
client.unsubscribe_from_topic(topic.clone());
println!("Unsubscribed from topic '{topic}'.");
}
GossipsubCmds::Publish { topic, msg } => {
client.publish_on_topic(topic.clone(), msg.into())?;
client.publish_on_topic(topic.clone(), msg.into());
println!("Message published on topic '{topic}'.");
}
}
Expand Down
2 changes: 1 addition & 1 deletion sn_cli/src/subcommands/wallet/wo_wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ async fn listen_notifs_and_deposit(root_dir: &Path, client: &Client, pk_hex: Str
let main_pk = wallet.address();
let pk = main_pk.public_key();

client.subscribe_to_topic(ROYALTY_TRANSFER_NOTIF_TOPIC.to_string())?;
client.subscribe_to_topic(ROYALTY_TRANSFER_NOTIF_TOPIC.to_string());
let mut events_receiver = client.events_channel();

println!("Current balance in local wallet: {}", wallet.balance());
Expand Down
23 changes: 10 additions & 13 deletions sn_client/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -961,15 +961,14 @@ impl Client {
/// # async fn main() -> Result<(),Error>{
/// let client = Client::new(SecretKey::random(), None, false, None, None).await?;
/// // Subscribing to the gossipsub topic "Royalty Transfer Notification"
/// client.subscribe_to_topic(String::from("ROYALTY_TRANSFER_NOTIFICATION"))?;
/// client.subscribe_to_topic(String::from("ROYALTY_TRANSFER_NOTIFICATION"));
/// # Ok(())
/// # }
/// ```
pub fn subscribe_to_topic(&self, topic_id: String) -> Result<()> {
pub fn subscribe_to_topic(&self, topic_id: String) {
info!("Subscribing to topic id: {topic_id}");
self.network.subscribe_to_topic(topic_id)?;
self.network.start_handle_gossip()?;
Ok(())
self.network.subscribe_to_topic(topic_id);
self.network.start_handle_gossip();
}

/// Unsubscribe from given gossipsub topic
Expand All @@ -985,14 +984,13 @@ impl Client {
/// # async fn main() -> Result<(),Error>{
/// let client = Client::new(SecretKey::random(), None, false, None, None).await?;
/// // Unsubscribing to the gossipsub topic "Royalty Transfer Notification"
/// client.unsubscribe_from_topic(String::from("ROYALTY_TRANSFER_NOTIFICATION"))?;
/// client.unsubscribe_from_topic(String::from("ROYALTY_TRANSFER_NOTIFICATION"));
/// # Ok(())
/// # }
/// ```
pub fn unsubscribe_from_topic(&self, topic_id: String) -> Result<()> {
pub fn unsubscribe_from_topic(&self, topic_id: String) {
info!("Unsubscribing from topic id: {topic_id}");
self.network.unsubscribe_from_topic(topic_id)?;
Ok(())
self.network.unsubscribe_from_topic(topic_id);
}

/// Publish message on given topic
Expand All @@ -1010,14 +1008,13 @@ impl Client {
/// let client = Client::new(SecretKey::random(), None, false, None, None).await?;
/// let msg = String::from("Transfer Successful.");
/// // Note the use of .into() to set the argument as bytes
/// client.publish_on_topic(String::from("ROYALTY_TRANSFER_NOTIFICATION"), msg.into())?;
/// client.publish_on_topic(String::from("ROYALTY_TRANSFER_NOTIFICATION"), msg.into());
/// # Ok(())
/// # }
/// ```
pub fn publish_on_topic(&self, topic_id: String, msg: Bytes) -> Result<()> {
pub fn publish_on_topic(&self, topic_id: String, msg: Bytes) {
info!("Publishing msg on topic id: {topic_id}");
self.network.publish_on_topic(topic_id, msg)?;
Ok(())
self.network.publish_on_topic(topic_id, msg);
}

/// This function is used to receive a Vector of CashNoteRedemptions and turn them back into spendable CashNotes.
Expand Down
60 changes: 41 additions & 19 deletions sn_client/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -722,6 +722,7 @@ impl Client {
) -> WalletResult<()> {
let mut tasks = Vec::new();

// send spends to the network in parralel
for spend_request in spend_requests {
debug!(
"sending spend request to the network: {:?}: {spend_request:#?}",
Expand All @@ -739,29 +740,50 @@ impl Client {
tasks.push(the_task);
}

let mut spent_cash_notes = BTreeSet::default();
for (cash_note_key, spend_attempt_result) in join_all(tasks).await {
// This is a record mismatch on spend, we need to clean up and remove the spent CashNote from the wallet
// This only happens if we're verifying the store
if let Err(Error::Network(sn_networking::Error::GetRecordError(
GetRecordError::RecordDoesNotMatch(record_key),
))) = spend_attempt_result
{
warn!("Record mismatch on spend, removing CashNote from wallet: {record_key:?}");
spent_cash_notes.insert(*cash_note_key);
} else {
return spend_attempt_result
.map_err(|err| WalletError::CouldNotSendMoney(err.to_string()));
// wait for all the tasks to complete and gather the errors
let mut errors = Vec::new();
let mut double_spent_keys = BTreeSet::new();
for (spend_key, spend_attempt_result) in join_all(tasks).await {
match spend_attempt_result {
Err(Error::Network(sn_networking::Error::GetRecordError(
GetRecordError::RecordDoesNotMatch(_),
)))
| Err(Error::Network(sn_networking::Error::GetRecordError(
GetRecordError::SplitRecord { .. },
))) => {
warn!(
"Double spend detected while trying to spend: {:?}",
spend_key
);
double_spent_keys.insert(*spend_key);
}
Err(e) => {
warn!("Spend request errored out when sent to the network {spend_key:?}: {e}");
errors.push((spend_key, e));
}
Ok(()) => {
trace!("Spend request was successfully sent to the network: {spend_key:?}");
}
}
}

if spent_cash_notes.is_empty() {
Ok(())
} else {
Err(WalletError::DoubleSpendAttemptedForCashNotes(
spent_cash_notes,
))
// report errors accordingly
// double spend errors in priority as they should be dealt with by the wallet
if !double_spent_keys.is_empty() {
return Err(WalletError::DoubleSpendAttemptedForCashNotes(
double_spent_keys,
));
}
if !errors.is_empty() {
let mut err_report = "Failed to send spend requests to the network:".to_string();
for (spend_key, e) in &errors {
warn!("Failed to send spend request to the network: {spend_key:?}: {e}");
err_report.push_str(&format!("{spend_key:?}: {e}"));
}
return Err(WalletError::CouldNotSendMoney(err_report));
}

Ok(())
}

/// Receive a Transfer, verify and redeem CashNotes from the Network.
Expand Down
3 changes: 2 additions & 1 deletion sn_networking/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ pub enum Error {
// GetRecord query errors
#[error("GetRecord Query Error {0:?}")]
GetRecordError(#[from] GetRecordError),
#[error("Record not stored by nodes, it could be invalid, else you should retry: {0:?}")]
RecordNotStoredByNodes(NetworkAddress),

// The RecordKind that was obtained did not match with the expected one
#[error("The RecordKind obtained from the Record did not match with the expected kind: {0}")]
Expand All @@ -135,7 +137,6 @@ pub enum Error {
// ---------- Spend Errors
#[error("Spend not found: {0:?}")]
NoSpendFoundInsideRecord(SpendAddress),

#[error("A double spend was detected. Two diverging signed spends: {0:?}, {1:?}")]
DoubleSpendAttempt(Box<SignedSpend>, Box<SignedSpend>),

Expand Down
Loading

0 comments on commit 64402a2

Please sign in to comment.