1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
// Copyright 2024 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.
use crate::Error;
use super::{error::Result, Client};
use backoff::{backoff::Backoff, ExponentialBackoff};
use futures::{future::join_all, TryFutureExt};
use libp2p::PeerId;
use sn_networking::target_arch::Instant;
use sn_networking::{GetRecordError, PayeeQuote};
use sn_protocol::NetworkAddress;
use sn_transfers::{
CashNote, DerivationIndex, HotWallet, MainPubkey, NanoTokens, Payment, PaymentQuote,
SignedSpend, SpendAddress, Transaction, Transfer, UniquePubkey, WalletError, WalletResult,
};
use std::{
collections::{BTreeMap, BTreeSet},
iter::Iterator,
};
use tokio::{
task::JoinSet,
time::{sleep, Duration},
};
use xor_name::XorName;
const MAX_RESEND_PENDING_TX_ATTEMPTS: usize = 10;
/// A wallet client can be used to send and receive tokens to and from other wallets.
pub struct WalletClient {
client: Client,
wallet: HotWallet,
}
/// The result of the payment made for a set of Content Addresses
pub struct StoragePaymentResult {
pub storage_cost: NanoTokens,
pub royalty_fees: NanoTokens,
pub skipped_chunks: Vec<XorName>,
}
impl WalletClient {
/// Create a new wallet client.
///
/// # Arguments
/// * `client` - A instance of the struct [`sn_client::Client`](Client)
/// * `wallet` - An instance of the struct [`HotWallet`]
///
/// # Example
/// ```no_run
/// use sn_client::{Client, WalletClient, Error};
/// use tempfile::TempDir;
/// use bls::SecretKey;
/// use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// let client = Client::new(SecretKey::random(), None, None, None).await?;
/// let tmp_path = TempDir::new()?.path().to_owned();
/// let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// let mut wallet_client = WalletClient::new(client, wallet);
/// # Ok(())
/// # }
/// ```
pub fn new(client: Client, wallet: HotWallet) -> Self {
Self { client, wallet }
}
/// Stores the wallet to the local wallet directory.
/// # Example
/// ```no_run
/// # use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// # use bls::SecretKey;
/// # use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// # let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// # let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// let mut wallet_client = WalletClient::new(client, wallet);
/// wallet_client.store_local_wallet()?;
/// # Ok(())
/// # }
pub fn store_local_wallet(&mut self) -> WalletResult<()> {
self.wallet.deposit_and_store_to_disk(&vec![])
}
/// Display the wallet balance
/// # Example
/// ```no_run
/// // Display the wallet balance in the terminal
/// # use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// # use bls::SecretKey;
/// # use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// # let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// # let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// let mut wallet_client = WalletClient::new(client, wallet);
/// println!("{}" ,wallet_client.balance());
/// # Ok(())
/// # }
pub fn balance(&self) -> NanoTokens {
self.wallet.balance()
}
/// See if any unconfirmed transactions exist.
/// # Example
/// ```no_run
/// // Print unconfirmed spends to the terminal
/// # use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// # use bls::SecretKey;
/// # use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// # let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// # let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// let mut wallet_client = WalletClient::new(client, wallet);
/// if wallet_client.unconfirmed_spend_requests_exist() {println!("Unconfirmed spends exist!")};
/// # Ok(())
/// # }
pub fn unconfirmed_spend_requests_exist(&self) -> bool {
self.wallet.unconfirmed_spend_requests_exist()
}
/// Returns the most recent cached Payment for a provided NetworkAddress. This function does not check if the
/// quote has expired or not. Use get_non_expired_payment_for_addr if you want to get a non expired one.
///
/// If multiple payments have been made to the same address, then we pick the last one as it is the most recent.
///
/// # Arguments
/// * `address` - The [`NetworkAddress`].
///
/// # Example
/// ```no_run
/// // Getting the payment for an address using a random PeerId
/// # use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// # use bls::SecretKey;
/// # use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// # use std::io::Bytes;
/// # let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// # let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// use libp2p_identity::PeerId;
/// use sn_protocol::NetworkAddress;
///
/// let mut wallet_client = WalletClient::new(client, wallet);
/// let network_address = NetworkAddress::from_peer(PeerId::random());
/// let payment = wallet_client.get_recent_payment_for_addr(&network_address)?;
/// # Ok(())
/// # }
/// ```
pub fn get_recent_payment_for_addr(
&self,
address: &NetworkAddress,
) -> WalletResult<(Payment, PeerId)> {
let xorname = address
.as_xorname()
.ok_or(WalletError::InvalidAddressType)?;
let payment_detail = self.wallet.api().get_recent_payment(&xorname)?;
let payment = payment_detail.to_payment();
trace!("Payment retrieved for {xorname:?} from wallet: {payment:?}");
let peer_id = PeerId::from_bytes(&payment_detail.peer_id_bytes)
.map_err(|_| WalletError::NoPaymentForAddress(xorname))?;
Ok((payment, peer_id))
}
/// Returns the all cached Payment for a provided NetworkAddress.
///
/// # Arguments
/// * `address` - The [`NetworkAddress`].
///
/// # Example
/// ```no_run
/// // Getting the payment for an address using a random PeerId
/// # use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// # use bls::SecretKey;
/// # use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// # use std::io::Bytes;
/// # let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// # let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// use libp2p_identity::PeerId;
/// use sn_protocol::NetworkAddress;
///
/// let mut wallet_client = WalletClient::new(client, wallet);
/// let network_address = NetworkAddress::from_peer(PeerId::random());
/// let payments = wallet_client.get_all_payments_for_addr(&network_address)?;
/// # Ok(())
/// # }
/// ```
pub fn get_all_payments_for_addr(
&self,
address: &NetworkAddress,
) -> WalletResult<Vec<(Payment, PeerId)>> {
let xorname = address
.as_xorname()
.ok_or(WalletError::InvalidAddressType)?;
let payment_details = self.wallet.api().get_all_payments(&xorname)?;
let payments = payment_details
.into_iter()
.map(|details| {
let payment = details.to_payment();
match PeerId::from_bytes(&details.peer_id_bytes) {
Ok(peer_id) => Ok((payment, peer_id)),
Err(_) => Err(WalletError::NoPaymentForAddress(xorname)),
}
})
.collect::<WalletResult<Vec<_>>>()?;
trace!(
"{} Payment retrieved for {xorname:?} from wallet: {payments:?}",
payments.len()
);
Ok(payments)
}
/// Remove the payment for a given network address from disk.
///
/// # Arguments
/// * `address` - The [`NetworkAddress`].
///
/// # Example
/// ```no_run
/// // Removing a payment address using a random PeerId
/// # use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// # use bls::SecretKey;
/// # use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// # use std::io::Bytes;
/// # let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// # let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// use libp2p_identity::PeerId;
/// use sn_protocol::NetworkAddress;
///
/// let mut wallet_client = WalletClient::new(client, wallet);
/// let network_address = NetworkAddress::from_peer(PeerId::random());
/// let payment = wallet_client.remove_payment_for_addr(&network_address)?;
/// # Ok(())
/// # }
/// ```
pub fn remove_payment_for_addr(&self, address: &NetworkAddress) -> WalletResult<()> {
match &address.as_xorname() {
Some(xorname) => {
self.wallet.api().remove_payment_transaction(xorname);
Ok(())
}
None => Err(WalletError::InvalidAddressType),
}
}
/// Send tokens to another wallet. Can also verify the store has been successful.
/// Verification will be attempted via GET request through a Spend on the network.
///
/// # Arguments
/// * `amount` - [`NanoTokens`].
/// * `to` - [`MainPubkey`].
/// * `verify_store` - A boolean to verify store. Set this to true for mandatory verification.
///
/// # Example
/// ```no_run
/// # use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// # use bls::SecretKey;
/// # use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// # use std::io::Bytes;
/// # let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// # let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// use sn_transfers::NanoTokens;
/// let mut wallet_client = WalletClient::new(client, wallet);
/// let nano = NanoTokens::from(10);
/// let main_pub_key = MainSecretKey::random().main_pubkey();
/// let payment = wallet_client.send_cash_note(nano,main_pub_key, true);
/// # Ok(())
/// # }
/// ```
pub async fn send_cash_note(
&mut self,
amount: NanoTokens,
to: MainPubkey,
verify_store: bool,
) -> WalletResult<CashNote> {
let created_cash_notes = self.wallet.local_send(vec![(amount, to)], None)?;
// send to network
if let Err(error) = self
.client
.send_spends(
self.wallet.unconfirmed_spend_requests().iter(),
verify_store,
)
.await
{
return Err(WalletError::CouldNotSendMoney(format!(
"The transfer was not successfully registered in the network: {error:?}"
)));
} else {
// clear unconfirmed txs
self.wallet.clear_confirmed_spend_requests();
}
// return the first CashNote (assuming there is only one because we only sent to one recipient)
match &created_cash_notes[..] {
[cashnote] => Ok(cashnote.clone()),
[_multiple, ..] => Err(WalletError::CouldNotSendMoney(
"Multiple CashNotes were returned from the transaction when only one was expected. This is a BUG."
.into(),
)),
[] => Err(WalletError::CouldNotSendMoney(
"No CashNotes were returned from the wallet.".into(),
)),
}
}
/// Send signed spends to another wallet.
/// Can optionally verify if the store has been successful.
/// Verification will be attempted via GET request through a Spend on the network.
async fn send_signed_spends(
&mut self,
signed_spends: BTreeSet<SignedSpend>,
tx: Transaction,
change_id: UniquePubkey,
output_details: BTreeMap<UniquePubkey, (MainPubkey, DerivationIndex)>,
verify_store: bool,
) -> WalletResult<CashNote> {
let created_cash_notes =
self.wallet
.prepare_signed_transfer(signed_spends, tx, change_id, output_details)?;
// send to network
if let Err(error) = self
.client
.send_spends(
self.wallet.unconfirmed_spend_requests().iter(),
verify_store,
)
.await
{
return Err(WalletError::CouldNotSendMoney(format!(
"The transfer was not successfully registered in the network: {error:?}"
)));
} else {
// clear unconfirmed txs
self.wallet.clear_confirmed_spend_requests();
}
// return the first CashNote (assuming there is only one because we only sent to one recipient)
match &created_cash_notes[..] {
[cashnote] => Ok(cashnote.clone()),
[_multiple, ..] => Err(WalletError::CouldNotSendMoney(
"Multiple CashNotes were returned from the transaction when only one was expected. This is a BUG."
.into(),
)),
[] => Err(WalletError::CouldNotSendMoney(
"No CashNotes were returned from the wallet.".into(),
)),
}
}
/// Get storecost from the network
/// Returns the MainPubkey of the node to pay and the price in NanoTokens
///
/// # Arguments
/// - content_addrs - [Iterator]<Items = [`NetworkAddress`]>
///
/// # Returns:
/// * [WalletResult]<[StoragePaymentResult]>
///
/// # Example
///```no_run
/// # use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// # use bls::SecretKey;
/// # use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// # use xor_name::XorName;
/// use sn_protocol::NetworkAddress;
/// use libp2p_identity::PeerId;
/// use sn_registers::{Permissions, RegisterAddress};
/// let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// # let mut rng = rand::thread_rng();
/// # let xor_name = XorName::random(&mut rng);
/// let network_address = NetworkAddress::from_peer(PeerId::random());
/// let mut wallet_client = WalletClient::new(client, wallet);
/// // Use get_store_cost_at_address(network_address) to get a storecost from the network.
/// let cost = wallet_client.get_store_cost_at_address(network_address).await?.2.cost.as_nano();
/// # Ok(())
/// # }
pub async fn get_store_cost_at_address(
&self,
address: NetworkAddress,
) -> WalletResult<PayeeQuote> {
self.client
.network
.get_store_costs_from_network(address, vec![])
.await
.map_err(|error| WalletError::CouldNotSendMoney(error.to_string()))
}
/// Send tokens to nodes closest to the data we want to make storage payment for. Runs mandatory verification.
///
/// # Arguments
/// - content_addrs - [Iterator]<Items = [`NetworkAddress`]>
///
/// # Returns:
/// * [WalletResult]<[StoragePaymentResult]>
///
/// # Example
///```no_run
/// # use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// # use bls::SecretKey;
/// # use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// # use xor_name::XorName;
/// use sn_protocol::NetworkAddress;
/// use sn_registers::{Permissions, RegisterAddress};
/// let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// # let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// let mut wallet_client = WalletClient::new(client.clone(), wallet);
/// let mut rng = rand::thread_rng();
/// let xor_name = XorName::random(&mut rng);
/// let address = RegisterAddress::new(xor_name, client.signer_pk());
/// let net_addr = NetworkAddress::from_register_address(address);
///
/// // Paying for a random Register Address
/// let cost = wallet_client.pay_for_storage(std::iter::once(net_addr)).await?;
/// # Ok(())
/// # }
pub async fn pay_for_storage(
&mut self,
content_addrs: impl Iterator<Item = NetworkAddress>,
) -> WalletResult<StoragePaymentResult> {
let verify_store = true;
let c: Vec<_> = content_addrs.collect();
// Using default ExponentialBackoff doesn't make sense,
// as it will just fail after the first payment failure.
let mut backoff = ExponentialBackoff::default();
let mut last_err = "No retries".to_string();
while let Some(delay) = backoff.next_backoff() {
trace!("Paying for storage (w/backoff retries) for: {:?}", c);
match self
.pay_for_storage_once(c.clone().into_iter(), verify_store)
.await
{
Ok(payment_result) => return Ok(payment_result),
Err(WalletError::CouldNotSendMoney(err)) => {
warn!("Attempt to pay for data failed: {err:?}");
last_err = err;
sleep(delay).await;
}
Err(err) => return Err(err),
}
}
Err(WalletError::CouldNotSendMoney(last_err))
}
/// Existing chunks will have the store cost set to Zero.
/// The payment procedure shall be skipped, and the chunk upload as well.
/// Hence the list of existing chunks will be returned.
async fn pay_for_storage_once(
&mut self,
content_addrs: impl Iterator<Item = NetworkAddress>,
verify_store: bool,
) -> WalletResult<StoragePaymentResult> {
// get store cost from network in parallel
let mut tasks = JoinSet::new();
for content_addr in content_addrs {
let client = self.client.clone();
tasks.spawn(async move {
let cost = client
.network
.get_store_costs_from_network(content_addr.clone(), vec![])
.await
.map_err(|error| WalletError::CouldNotSendMoney(error.to_string()));
debug!("Storecosts retrieved for {content_addr:?} {cost:?}");
(content_addr, cost)
});
}
debug!("Pending store cost tasks: {:?}", tasks.len());
// collect store costs
let mut cost_map = BTreeMap::default();
let mut skipped_chunks = vec![];
#[allow(clippy::mutable_key_type)]
while let Some(res) = tasks.join_next().await {
match res {
Ok((content_addr, Ok(cost))) => {
if let Some(xorname) = content_addr.as_xorname() {
if cost.2.cost == NanoTokens::zero() {
skipped_chunks.push(xorname);
debug!("Skipped existing chunk {content_addr:?}");
} else {
debug!("Storecost inserted into payment map for {content_addr:?}");
let _ = cost_map.insert(xorname, (cost.1, cost.2, cost.0.to_bytes()));
}
} else {
warn!("Cannot get store cost for a content that is not a data type: {content_addr:?}");
}
}
Ok((content_addr, Err(err))) => {
warn!("Cannot get store cost for {content_addr:?} with error {err:?}");
return Err(err);
}
Err(e) => {
return Err(WalletError::CouldNotSendMoney(format!(
"Storecost get task failed: {e:?}"
)));
}
}
}
info!("Storecosts retrieved for all the provided content addrs");
// pay for records
let (storage_cost, royalty_fees) = self.pay_for_records(&cost_map, verify_store).await?;
let res = StoragePaymentResult {
storage_cost,
royalty_fees,
skipped_chunks,
};
Ok(res)
}
/// Send tokens to nodes closest to the data that we want to make storage payments for.
/// # Returns:
///
/// * [WalletResult]<([NanoTokens], [NanoTokens])>
///
/// This return contains the amount paid for storage. Including the network royalties fee paid.
///
/// # Params:
/// * cost_map - [BTreeMap]([XorName],([MainPubkey], [PaymentQuote]))
/// * verify_store - This optional check can verify if the store has been successful.
///
/// Verification will be attempted via GET request through a Spend on the network.
///
/// # Example
///```no_run
/// # use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// # use bls::SecretKey;
/// # use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// # use std::collections::BTreeMap;
/// use xor_name::XorName;
/// use sn_transfers::{MainPubkey, Payment, PaymentQuote};
/// let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// # let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// let mut wallet_client = WalletClient::new(client, wallet);
/// let mut cost_map:BTreeMap<XorName,(MainPubkey,PaymentQuote,Vec<u8>)> = BTreeMap::new();
/// wallet_client.pay_for_records(&cost_map,true).await?;
/// # Ok(())
/// # }
pub async fn pay_for_records(
&mut self,
cost_map: &BTreeMap<XorName, (MainPubkey, PaymentQuote, Vec<u8>)>,
verify_store: bool,
) -> WalletResult<(NanoTokens, NanoTokens)> {
// Before wallet progress, there shall be no `unconfirmed_spend_requests`
self.resend_pending_transaction_until_success(verify_store)
.await?;
let start = Instant::now();
let total_cost = self.wallet.local_send_storage_payment(cost_map)?;
trace!(
"local_send_storage_payment of {} chunks completed in {:?}",
cost_map.len(),
start.elapsed()
);
// send to network
trace!("Sending storage payment transfer to the network");
let start = Instant::now();
let spend_attempt_result = self
.client
.send_spends(
self.wallet.unconfirmed_spend_requests().iter(),
verify_store,
)
.await;
trace!(
"send_spends of {} chunks completed in {:?}",
cost_map.len(),
start.elapsed()
);
// Here is bit risky that for the whole bunch of spends to the chunks' store_costs and royalty_fee
// they will get re-paid again for ALL, if any one of the payment failed to be put.
let start = Instant::now();
if let Err(error) = spend_attempt_result {
warn!("The storage payment transfer was not successfully registered in the network: {error:?}. It will be retried later.");
// if we have a DoubleSpend error, lets remove the CashNote from the wallet
if let WalletError::DoubleSpendAttemptedForCashNotes(spent_cash_notes) = &error {
for cash_note_key in spent_cash_notes {
warn!("Removing double spends CashNote from wallet: {cash_note_key:?}");
self.wallet.mark_notes_as_spent([cash_note_key]);
self.wallet.clear_specific_spend_request(*cash_note_key);
}
}
self.wallet.store_unconfirmed_spend_requests()?;
return Err(WalletError::CouldNotSendMoney(format!(
"The storage payment transfer was not successfully registered in the network: {error:?}"
)));
} else {
info!("Spend has completed: {:?}", spend_attempt_result);
self.wallet.clear_confirmed_spend_requests();
}
trace!(
"clear up spends of {} chunks completed in {:?}",
cost_map.len(),
start.elapsed()
);
Ok(total_cost)
}
/// Resend failed transactions. This can optionally verify the store has been successful.
/// This will attempt to GET the cash_note from the network.
async fn resend_pending_transactions(&mut self, verify_store: bool) {
if self
.client
.send_spends(
self.wallet.unconfirmed_spend_requests().iter(),
verify_store,
)
.await
.is_ok()
{
self.wallet.clear_confirmed_spend_requests();
}
}
/// Try resending failed transactions multiple times until it succeeds or until we reach max attempts.
async fn resend_pending_transaction_until_success(
&mut self,
verify_store: bool,
) -> WalletResult<()> {
let mut did_error = false;
// Wallet shall be all clear to progress forward.
let mut attempts = 0;
while self.wallet.unconfirmed_spend_requests_exist() {
info!("Pre-Unconfirmed transactions exist, sending again after 1 second...");
sleep(Duration::from_secs(1)).await;
self.resend_pending_transactions(verify_store).await;
if attempts > MAX_RESEND_PENDING_TX_ATTEMPTS {
// save the error state, but break out of the loop so we can save
did_error = true;
break;
}
attempts += 1;
}
if did_error {
error!("Wallet has pre-unconfirmed transactions, can't progress further.");
Err(WalletError::UnconfirmedTxAfterRetries)
} else {
Ok(())
}
}
/// Returns the wallet:
///
/// Return type: [HotWallet]
///
/// # Example
/// ```no_run
/// # use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// # use bls::SecretKey;
/// # use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// # let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// # let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// let mut wallet_client = WalletClient::new(client, wallet);
/// let paying_wallet = wallet_client.into_wallet();
/// // Display the wallet balance in the terminal
/// println!("{}",paying_wallet.balance());
/// # Ok(())
/// # }
pub fn into_wallet(self) -> HotWallet {
self.wallet
}
/// Returns a mutable wallet instance
///
/// Return type: [HotWallet]
///
/// # Example
/// ```no_run
/// # use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// # use bls::SecretKey;
/// # use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// # let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// # let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// let mut wallet_client = WalletClient::new(client, wallet);
/// let paying_wallet = wallet_client.mut_wallet();
/// // Display the mutable wallet balance in the terminal
/// println!("{}",paying_wallet.balance());
/// # Ok(())
/// # }
pub fn mut_wallet(&mut self) -> &mut HotWallet {
&mut self.wallet
}
}
impl Client {
/// Send spend requests to the network.
/// This can optionally verify the spends have been correctly stored before returning
///
/// # Arguments
/// * spend_requests - [Iterator]<[SignedSpend]>
/// * verify_store - Boolean. Set to true for mandatory verification via a GET request through a Spend on the network.
///
/// # Example
/// ```no_run
/// use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// use bls::SecretKey;
/// use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// // An example of sending storage payment transfers over the network with validation
/// client.send_spends(wallet.unconfirmed_spend_requests().iter(),true).await?;
/// # Ok(())
/// # }
/// ```
pub async fn send_spends(
&self,
spend_requests: impl Iterator<Item = &SignedSpend>,
verify_store: bool,
) -> 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:#?}",
spend_request.unique_pubkey()
);
let the_task = async move {
let cash_note_key = spend_request.unique_pubkey();
let result = self
.network_store_spend(spend_request.clone(), verify_store)
.await;
(cash_note_key, result)
};
tasks.push(the_task);
}
// 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::NetworkError::GetRecordError(
GetRecordError::RecordDoesNotMatch(_),
)))
| Err(Error::Network(sn_networking::NetworkError::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:?}");
}
}
}
// 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.
///
/// # Arguments
/// * transfer: &[Transfer] - Borrowed value for [Transfer]
/// * wallet: &[HotWallet] - Borrowed value for [HotWallet]
///
/// # Return Value
/// * [WalletResult]<[Vec]<[CashNote]>>
///
/// # Example
/// ```no_run
/// use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// use bls::SecretKey;
/// use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// use tracing::error;
/// use sn_transfers::Transfer;
/// let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// let transfer = Transfer::from_hex("13abc").unwrap();
/// // An example for using client.receive() for cashNotes
/// let cash_notes = match client.receive(&transfer, &wallet).await {
/// Ok(cash_notes) => cash_notes,
/// Err(err) => {
/// println!("Failed to verify and redeem transfer: {err:?}");
/// error!("Failed to verify and redeem transfer: {err:?}");
/// return Err(err.into());
/// }
/// };
/// # Ok(())
///
/// # }
/// ```
pub async fn receive(
&self,
transfer: &Transfer,
wallet: &HotWallet,
) -> WalletResult<Vec<CashNote>> {
let cashnotes = self
.network
.verify_and_unpack_transfer(transfer, wallet)
.map_err(|e| WalletError::CouldNotReceiveMoney(format!("{e:?}")))
.await?;
let valuable_cashnotes = self.filter_out_already_spend_cash_notes(cashnotes).await?;
Ok(valuable_cashnotes)
}
/// Check that the redeemed CashNotes are not already spent
async fn filter_out_already_spend_cash_notes(
&self,
mut cash_notes: Vec<CashNote>,
) -> WalletResult<Vec<CashNote>> {
trace!("Validating CashNotes are not already spent");
let mut tasks = JoinSet::new();
for cn in &cash_notes {
let pk = cn.unique_pubkey();
let addr = SpendAddress::from_unique_pubkey(&pk);
let self_clone = self.network.clone();
let _ = tasks.spawn(async move { self_clone.get_spend(addr).await });
}
while let Some(result) = tasks.join_next().await {
let res = result.map_err(|e| WalletError::FailedToGetSpend(format!("{e}")))?;
match res {
// if we get a RecordNotFound, it means the CashNote is not spent, which is good
Err(sn_networking::NetworkError::GetRecordError(
GetRecordError::RecordNotFound,
)) => (),
// if we get a spend, it means the CashNote is already spent
Ok(s) => {
warn!(
"CashNoteRedemption contains a CashNote that is already spent, skipping it: {:?}",
s.unique_pubkey()
);
cash_notes.retain(|c| &c.unique_pubkey() != s.unique_pubkey());
}
// report all other errors
Err(e) => return Err(WalletError::FailedToGetSpend(format!("{e}"))),
}
}
if cash_notes.is_empty() {
return Err(WalletError::CouldNotVerifyTransfer(
"All the redeemed CashNotes are already spent".to_string(),
));
}
Ok(cash_notes)
}
/// Verify that the spends referred to (in the CashNote) exist on the network.
///
/// # Arguments
/// * cash_note - [CashNote]
///
/// # Return value
/// [WalletResult]
///
/// # Example
/// ```no_run
/// use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// use bls::SecretKey;
/// use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// use tracing::error;
/// use sn_transfers::Transfer;
/// let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// let transfer = Transfer::from_hex("").unwrap();
/// let cash_notes = client.receive(&transfer, &wallet).await?;
/// // Verification:
/// for cash_note in cash_notes {
/// println!("{:?}" , client.verify_cashnote(&cash_note).await.unwrap());
/// }
/// # Ok(())
///
/// # }
/// ```
pub async fn verify_cashnote(&self, cash_note: &CashNote) -> WalletResult<()> {
// We need to get all the spends in the cash_note from the network,
// and compare them to the spends in the cash_note, to know if the
// transfer is considered valid in the network.
let mut tasks = Vec::new();
for spend in &cash_note.signed_spends {
let address = SpendAddress::from_unique_pubkey(spend.unique_pubkey());
debug!(
"Getting spend for pubkey {:?} from network at {address:?}",
spend.unique_pubkey()
);
tasks.push(self.get_spend_from_network(address));
}
let mut received_spends = std::collections::BTreeSet::new();
for result in join_all(tasks).await {
let network_valid_spend =
result.map_err(|err| WalletError::CouldNotVerifyTransfer(err.to_string()))?;
let _ = received_spends.insert(network_valid_spend);
}
// If all the spends in the cash_note are the same as the ones in the network,
// we have successfully verified that the cash_note is globally recognised and therefor valid.
if received_spends == cash_note.signed_spends {
return Ok(());
}
Err(WalletError::CouldNotVerifyTransfer(
"The spends in network were not the same as the ones in the CashNote. The parents of this CashNote are probably double spends.".into(),
))
}
}
/// Use the client to send a CashNote from a local wallet to an address.
/// This marks the spent CashNote as spent in the Network
///
/// # Arguments
/// * from - [HotWallet]
/// * amount - [NanoTokens]
/// * to - [MainPubkey]
/// * client - [Client]
/// * verify_store - Boolean. Set to true for mandatory verification via a GET request through a Spend on the network.
///
/// # Example
/// ```no_run
/// use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// use bls::SecretKey;
/// use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// use tracing::error;
/// use sn_client::send;
/// use sn_transfers::Transfer;
/// let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// let mut first_wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// let mut second_wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// let tokens = send(
/// first_wallet, // From
/// second_wallet.balance(), // To
/// second_wallet.address(), // Amount
/// &client, // Client
/// true, // Verification
/// ).await?;
/// # Ok(())
/// # }
/// ```
pub async fn send(
from: HotWallet,
amount: NanoTokens,
to: MainPubkey,
client: &Client,
verify_store: bool,
) -> Result<CashNote> {
if amount.is_zero() {
return Err(Error::AmountIsZero);
}
let mut wallet_client = WalletClient::new(client.clone(), from);
if let Err(err) = wallet_client
.resend_pending_transaction_until_success(verify_store)
.await
{
println!("Wallet has pre-unconfirmed transactions, can't progress further.");
return Err(err.into());
}
let new_cash_note = wallet_client
.send_cash_note(amount, to, verify_store)
.await
.map_err(|err| {
error!("Could not send cash note, err: {err:?}");
err
})?;
wallet_client
.resend_pending_transaction_until_success(verify_store)
.await?;
wallet_client
.into_wallet()
.deposit_and_store_to_disk(&vec![new_cash_note.clone()])?;
Ok(new_cash_note)
}
/// Send tokens to another wallet. Can optionally verify the store has been successful.
///
/// Verification will be attempted via GET request through a Spend on the network.
///
/// # Arguments
/// * from - [HotWallet],
/// * client - [Client],
/// * signed_spends - [BTreeSet]<[SignedSpend]>,
/// * transaction - [Transaction],
/// * change_id - [UniquePubkey],
/// * output_details - [BTreeMap]<[UniquePubkey], ([MainPubkey], [DerivationIndex])>,
/// * verify_store - Boolean. Set to true for mandatory verification via a GET request through a Spend on the network.
///
/// # Return value
/// [WalletResult]<[CashNote]>
/// # Example
/// ```no_run
/// use sn_client::{Client, WalletClient, Error};
/// # use tempfile::TempDir;
/// use bls::SecretKey;
/// use sn_transfers::{HotWallet, MainSecretKey};
/// # #[tokio::main]
/// # async fn main() -> Result<(),Error>{
/// use std::collections::{BTreeMap, BTreeSet};
/// use tracing::error;
/// use sn_transfers::{Transaction, Transfer, UniquePubkey};
/// let client = Client::new(SecretKey::random(), None, None, None).await?;
/// # let tmp_path = TempDir::new()?.path().to_owned();
/// let mut wallet = HotWallet::load_from_path(&tmp_path,Some(MainSecretKey::new(SecretKey::random())))?;
/// let transaction = Transaction {inputs: Vec::new(),outputs: Vec::new(),};
/// let secret_key = UniquePubkey::new(SecretKey::random().public_key());
///
/// println!("Broadcasting the transaction to the network...");
/// let cash_note = sn_client::broadcast_signed_spends(
/// wallet,
/// &client,
/// BTreeSet::default(),
/// transaction,
/// secret_key,
/// BTreeMap::new(),
/// true
/// ).await?;
///
/// # Ok(())
/// # }
/// ```
pub async fn broadcast_signed_spends(
from: HotWallet,
client: &Client,
signed_spends: BTreeSet<SignedSpend>,
tx: Transaction,
change_id: UniquePubkey,
output_details: BTreeMap<UniquePubkey, (MainPubkey, DerivationIndex)>,
verify_store: bool,
) -> WalletResult<CashNote> {
let mut wallet_client = WalletClient::new(client.clone(), from);
// Wallet shall be all clear to progress forward.
if let Err(err) = wallet_client
.resend_pending_transaction_until_success(verify_store)
.await
{
println!("Wallet has pre-unconfirmed transactions, can't progress further.");
return Err(err);
}
let new_cash_note = wallet_client
.send_signed_spends(signed_spends, tx, change_id, output_details, verify_store)
.await
.map_err(|err| {
error!("Could not send signed spends, err: {err:?}");
err
})?;
wallet_client
.resend_pending_transaction_until_success(verify_store)
.await?;
wallet_client
.into_wallet()
.deposit_and_store_to_disk(&vec![new_cash_note.clone()])?;
Ok(new_cash_note)
}