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
// Copyright 2023 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 super::{
    keys::{get_main_key, store_new_keypair},
    wallet_file::{
        create_received_cash_notes_dir, get_unconfirmed_spend_requests, get_wallet, load_cash_note,
        load_received_cash_notes, store_created_cash_notes, store_unconfirmed_spend_requests,
        store_wallet,
    },
    Error, KeyLessWallet, Result,
};

use crate::{
    transfers::{create_offline_transfer, ContentPaymentsIdMap, OfflineTransfer},
    CashNoteRedemption, SignedSpend, Transfer,
};
use crate::{
    CashNote, DerivationIndex, DerivedSecretKey, Hash, MainPubkey, MainSecretKey, NanoTokens,
    UniquePubkey,
};
use itertools::Itertools;
use xor_name::XorName;

use std::{
    collections::{BTreeMap, BTreeSet},
    path::{Path, PathBuf},
};

const WALLET_DIR_NAME: &str = "wallet";

/// A wallet that can only receive tokens.
pub struct LocalWallet {
    /// The secret key with which we can access
    /// all the tokens in the available_cash_notes.
    key: MainSecretKey,
    /// The wallet containing all data.
    wallet: KeyLessWallet,
    /// The dir of the wallet file, main key, public address, and new cash_notes.
    wallet_dir: PathBuf,
    /// These have not yet been successfully sent to the network
    /// and need to be, to reach network validity.
    unconfirmed_spend_requests: BTreeSet<SignedSpend>,
}

impl LocalWallet {
    /// Stores the wallet to disk.
    pub fn store(&self) -> Result<()> {
        store_wallet(&self.wallet_dir, &self.wallet)
    }

    /// Stores the given cash_notes to the `created cash_notes dir` in the wallet dir.
    /// These can then be sent to the recipients out of band, over any channel preferred.
    pub fn store_cash_note(&mut self, cash_note: &CashNote) -> Result<()> {
        store_created_cash_notes(vec![cash_note], &self.wallet_dir)
    }

    /// Stores the given cash_notes to the `created cash_notes dir` in the wallet dir.
    /// These can then be sent to the recipients out of band, over any channel preferred.
    pub fn store_cash_notes(&mut self, cash_note: Vec<&CashNote>) -> Result<()> {
        store_created_cash_notes(cash_note, &self.wallet_dir)
    }

    pub fn get_cash_note(&mut self, unique_pubkey: &UniquePubkey) -> Option<CashNote> {
        load_cash_note(unique_pubkey, &self.wallet_dir)
    }

    /// Store unconfirmed_spend_requests to disk.
    pub fn store_unconfirmed_spend_requests(&mut self) -> Result<()> {
        store_unconfirmed_spend_requests(&self.wallet_dir, self.unconfirmed_spend_requests())
    }

    pub fn unconfirmed_spend_requests_exist(&self) -> bool {
        !self.unconfirmed_spend_requests.is_empty()
    }

    /// Try to load any new cash_notes from the `received cash_notes dir` in the wallet dir.
    pub fn try_load_deposits(&mut self) -> Result<()> {
        let deposited = load_received_cash_notes(&self.wallet_dir)?;
        self.deposit(&deposited)?;
        Ok(())
    }

    /// Loads a serialized wallet from a path and given main key.
    pub fn load_from_main_key(root_dir: &Path, main_key: MainSecretKey) -> Result<Self> {
        let wallet_dir = root_dir.join(WALLET_DIR_NAME);
        // This creates the received_cash_notes dir if it doesn't exist.
        std::fs::create_dir_all(&wallet_dir)?;
        // This creates the main_key file if it doesn't exist.
        let (key, wallet, unconfirmed_spend_requests) =
            load_from_path(&wallet_dir, Some(main_key))?;
        Ok(Self {
            key,
            wallet,
            wallet_dir: wallet_dir.to_path_buf(),
            unconfirmed_spend_requests,
        })
    }

    /// Loads a serialized wallet from a path.
    pub fn load_from(root_dir: &Path) -> Result<Self> {
        let wallet_dir = root_dir.join(WALLET_DIR_NAME);
        // This creates the received_cash_notes dir if it doesn't exist.
        std::fs::create_dir_all(&wallet_dir)?;
        let (key, wallet, unconfirmed_spend_requests) = load_from_path(&wallet_dir, None)?;
        Ok(Self {
            key,
            wallet,
            wallet_dir: wallet_dir.to_path_buf(),
            unconfirmed_spend_requests,
        })
    }

    /// Tries to loads a serialized wallet from a path, bailing out if it doesn't exist.
    pub fn try_load_from(root_dir: &Path) -> Result<Self> {
        let wallet_dir = root_dir.join(WALLET_DIR_NAME);
        let (key, wallet, unconfirmed_spend_requests) = load_from_path(&wallet_dir, None)?;
        Ok(Self {
            key,
            wallet,
            wallet_dir: wallet_dir.to_path_buf(),
            unconfirmed_spend_requests,
        })
    }

    pub fn address(&self) -> MainPubkey {
        self.key.main_pubkey()
    }

    pub fn unconfirmed_spend_requests(&self) -> &BTreeSet<SignedSpend> {
        &self.unconfirmed_spend_requests
    }

    pub fn clear_unconfirmed_spend_requests(&mut self) {
        self.unconfirmed_spend_requests = Default::default();
    }

    pub fn balance(&self) -> NanoTokens {
        self.wallet.balance()
    }

    pub fn sign(&self, msg: &[u8]) -> bls::Signature {
        self.key.sign(msg)
    }

    pub fn available_cash_notes(&self) -> Vec<(CashNote, DerivedSecretKey)> {
        let mut available_cash_notes = vec![];

        for (id, _token) in self.wallet.available_cash_notes.iter() {
            let held_cash_note = load_cash_note(id, &self.wallet_dir);
            if let Some(cash_note) = held_cash_note {
                if let Ok(derived_key) = cash_note.derived_key(&self.key) {
                    available_cash_notes.push((cash_note.clone(), derived_key));
                } else {
                    warn!(
                        "Skipping CashNote {:?} because we don't have the key to spend it",
                        cash_note.unique_pubkey()
                    );
                }
            } else {
                warn!("Skipping CashNote {:?} because we don't have it", id);
            }
        }
        available_cash_notes
    }

    /// Return the payment cash_note ids for the given content address name if cached.
    pub fn get_payment_unique_pubkeys(&self, name: &XorName) -> Option<&Vec<UniquePubkey>> {
        self.wallet.payment_transactions.get(name)
    }

    /// Return the payment cash_note ids for the given content address name if cached.
    pub fn get_payment_cash_notes(&self, name: &XorName) -> Vec<CashNote> {
        let ids = self.get_payment_unique_pubkeys(name);
        // now grab all those cash_notes
        let mut cash_notes: Vec<CashNote> = vec![];

        if let Some(ids) = ids {
            for id in ids {
                if let Some(cash_note) = load_cash_note(id, &self.wallet_dir) {
                    cash_notes.push(cash_note);
                }
            }
        }

        cash_notes
    }

    /// Make a transfer and return all created cash_notes
    pub fn local_send(
        &mut self,
        to: Vec<(NanoTokens, MainPubkey)>,
        reason_hash: Option<Hash>,
    ) -> Result<Vec<CashNote>> {
        let mut rng = &mut rand::rngs::OsRng;
        // create a unique key for each output
        let to_unique_keys: Vec<_> = to
            .into_iter()
            .map(|(amount, address)| {
                (
                    amount,
                    address,
                    UniquePubkey::random_derivation_index(&mut rng),
                )
            })
            .collect();

        let available_cash_notes = self.available_cash_notes();
        debug!(
            "Available CashNotes for local send: {:#?}",
            available_cash_notes
        );

        let reason_hash = reason_hash.unwrap_or_default();

        let transfer = create_offline_transfer(
            available_cash_notes,
            to_unique_keys,
            self.address(),
            reason_hash,
        )?;

        let created_cash_notes = transfer.created_cash_notes.clone();

        self.update_local_wallet(transfer)?;

        Ok(created_cash_notes)
    }

    /// Performs a CashNote payment for each content address, returning outputs for each.
    pub fn local_send_storage_payment(
        &mut self,
        all_data_payments: BTreeMap<XorName, Vec<(MainPubkey, NanoTokens)>>,
        reason_hash: Option<Hash>,
    ) -> Result<()> {
        // create a unique key for each output
        let mut all_payees_only = vec![];
        for (_content_addr, payees) in all_data_payments.clone().into_iter() {
            let mut rng = &mut rand::thread_rng();
            let unique_key_vec: Vec<(NanoTokens, MainPubkey, [u8; 32])> = payees
                .into_iter()
                .map(|(address, amount)| {
                    (
                        amount,
                        address,
                        UniquePubkey::random_derivation_index(&mut rng),
                    )
                })
                .collect_vec();
            all_payees_only.extend(unique_key_vec.clone());
        }

        let reason_hash = reason_hash.unwrap_or_default();

        let available_cash_notes = self.available_cash_notes();
        debug!("Available CashNotes: {:#?}", available_cash_notes);
        let transfer_outputs = create_offline_transfer(
            available_cash_notes,
            all_payees_only,
            self.address(),
            reason_hash,
        )?;

        let mut all_transfers_per_address = BTreeMap::default();

        let mut used_cash_notes = std::collections::HashSet::new();

        for (content_addr, payees) in all_data_payments {
            for (payee, _token) in payees {
                if let Some(cash_note) =
                    &transfer_outputs
                        .created_cash_notes
                        .iter()
                        .find(|cash_note| {
                            cash_note.main_pubkey() == &payee
                                && !used_cash_notes.contains(&cash_note.unique_pubkey().to_bytes())
                        })
                {
                    used_cash_notes.insert(cash_note.unique_pubkey().to_bytes());
                    let cash_notes_for_content: &mut Vec<UniquePubkey> =
                        all_transfers_per_address.entry(content_addr).or_default();
                    cash_notes_for_content.push(cash_note.unique_pubkey());
                }
            }
        }

        self.update_local_wallet(transfer_outputs)?;
        println!("Transfers applied locally");

        self.wallet
            .payment_transactions
            .extend(all_transfers_per_address);

        // get the content payment map stored
        store_wallet(&self.wallet_dir, &self.wallet)?;

        Ok(())
    }

    fn update_local_wallet(&mut self, transfer: OfflineTransfer) -> Result<()> {
        // First of all, update client local state.
        let spent_unique_pubkeys: BTreeSet<_> = transfer
            .tx
            .inputs
            .iter()
            .map(|input| input.unique_pubkey())
            .collect();

        // Use retain to remove spent CashNotes in one pass, improving performance
        self.wallet
            .available_cash_notes
            .retain(|k, _| !spent_unique_pubkeys.contains(k));
        for spent in spent_unique_pubkeys {
            self.wallet.spent_cash_notes.insert(spent);
        }

        if let Some(cash_note) = transfer.change_cash_note {
            self.deposit(&vec![cash_note])?;
        }

        for cash_note in &transfer.created_cash_notes {
            self.wallet
                .cash_notes_created_for_others
                .insert(cash_note.unique_pubkey());
        }
        // Store created CashNotes in a batch, improving IO performance
        self.store_cash_notes(transfer.created_cash_notes.iter().collect())?;

        for request in transfer.all_spend_requests {
            self.unconfirmed_spend_requests.insert(request);
        }
        Ok(())
    }

    pub fn deposit(&mut self, cash_notes: &Vec<CashNote>) -> Result<()> {
        if cash_notes.is_empty() {
            return Ok(());
        }

        for cash_note in cash_notes {
            let id = cash_note.unique_pubkey();

            if self.wallet.spent_cash_notes.contains(&id) {
                debug!("cash_note is spent");
                return Ok(());
            }

            if cash_note.derived_key(&self.key).is_err() {
                debug!("cash_note is not our key");
                continue;
            }

            let value = cash_note.value()?;
            self.wallet.available_cash_notes.insert(id, value);

            if let Some(_cash_note) = load_cash_note(&id, &self.wallet_dir) {
                debug!("cash_note exists");
                return Ok(());
            }

            self.store_cash_note(cash_note)?;
        }

        Ok(())
    }

    pub fn unwrap_transfer(&self, transfer: Transfer) -> Result<Vec<CashNoteRedemption>> {
        transfer
            .cashnote_redemptions(&self.key)
            .map_err(|_| Error::FailedToDecypherTransfer)
    }

    pub fn derive_key(&self, derivation_index: &DerivationIndex) -> DerivedSecretKey {
        self.key.derive_key(derivation_index)
    }
}

/// Loads a serialized wallet from a path.
fn load_from_path(
    wallet_dir: &Path,
    main_key: Option<MainSecretKey>,
) -> Result<(MainSecretKey, KeyLessWallet, BTreeSet<SignedSpend>)> {
    let key = match get_main_key(wallet_dir)? {
        Some(key) => key,
        None => {
            let key = main_key.unwrap_or(MainSecretKey::random());
            store_new_keypair(wallet_dir, &key)?;
            warn!("No main key found when loading wallet from path, generating a new one with pubkey: {:?}", key.main_pubkey());
            key
        }
    };
    let unconfirmed_spend_requests = match get_unconfirmed_spend_requests(wallet_dir)? {
        Some(unconfirmed_spend_requests) => unconfirmed_spend_requests,
        None => Default::default(),
    };
    let wallet = match get_wallet(wallet_dir)? {
        Some(wallet) => {
            debug!(
                "Loaded wallet from {:#?} with balance {:?}",
                wallet_dir,
                wallet.balance()
            );
            wallet
        }
        None => {
            let wallet = KeyLessWallet::new();
            store_wallet(wallet_dir, &wallet)?;
            create_received_cash_notes_dir(wallet_dir)?;
            wallet
        }
    };

    Ok((key, wallet, unconfirmed_spend_requests))
}

impl KeyLessWallet {
    fn new() -> Self {
        Self {
            available_cash_notes: Default::default(),
            cash_notes_created_for_others: Default::default(),
            spent_cash_notes: Default::default(),
            payment_transactions: ContentPaymentsIdMap::default(),
        }
    }

    fn balance(&self) -> NanoTokens {
        // loop through avaiable bcs and get total token count
        let mut balance = 0;
        for (_unique_pubkey, value) in self.available_cash_notes.iter() {
            balance += value.as_nano();
        }

        NanoTokens::from(balance)
    }
}

#[cfg(test)]
mod tests {
    use super::{get_wallet, store_wallet, LocalWallet};
    use crate::{
        genesis::{create_first_cash_note_from_key, GENESIS_CASHNOTE_AMOUNT},
        wallet::{local_store::WALLET_DIR_NAME, KeyLessWallet},
        MainSecretKey, NanoTokens, SpendAddress,
    };
    use assert_fs::TempDir;
    use eyre::Result;

    #[tokio::test]
    async fn keyless_wallet_to_and_from_file() -> Result<()> {
        let key = MainSecretKey::random();
        let mut wallet = KeyLessWallet::new();
        let genesis = create_first_cash_note_from_key(&key).expect("Genesis creation to succeed.");

        let dir = create_temp_dir();
        let wallet_dir = dir.path().to_path_buf();

        wallet
            .available_cash_notes
            .insert(genesis.unique_pubkey(), genesis.value()?);

        store_wallet(&wallet_dir, &wallet)?;

        let deserialized = get_wallet(&wallet_dir)?.expect("There to be a wallet on disk.");

        assert_eq!(GENESIS_CASHNOTE_AMOUNT, wallet.balance().as_nano());
        assert_eq!(GENESIS_CASHNOTE_AMOUNT, deserialized.balance().as_nano());

        Ok(())
    }

    #[test]
    fn wallet_basics() -> Result<()> {
        let key = MainSecretKey::random();
        let main_pubkey = key.main_pubkey();
        let dir = create_temp_dir();

        let deposit_only = LocalWallet {
            key,
            unconfirmed_spend_requests: Default::default(),

            wallet: KeyLessWallet::new(),
            wallet_dir: dir.path().to_path_buf(),
        };

        assert_eq!(main_pubkey, deposit_only.address());
        assert_eq!(NanoTokens::zero(), deposit_only.balance());

        assert!(deposit_only.wallet.available_cash_notes.is_empty());
        assert!(deposit_only.wallet.cash_notes_created_for_others.is_empty());
        assert!(deposit_only.wallet.spent_cash_notes.is_empty());

        Ok(())
    }

    /// -----------------------------------
    /// <-------> DepositWallet <--------->
    /// -----------------------------------

    #[tokio::test]
    async fn deposit_empty_list_does_nothing() -> Result<()> {
        let dir = create_temp_dir();

        let mut deposit_only = LocalWallet {
            key: MainSecretKey::random(),
            unconfirmed_spend_requests: Default::default(),

            wallet: KeyLessWallet::new(),
            wallet_dir: dir.path().to_path_buf(),
        };

        deposit_only.deposit(&vec![])?;

        assert_eq!(NanoTokens::zero(), deposit_only.balance());

        assert!(deposit_only.wallet.available_cash_notes.is_empty());
        assert!(deposit_only.wallet.cash_notes_created_for_others.is_empty());
        assert!(deposit_only.wallet.spent_cash_notes.is_empty());

        Ok(())
    }

    #[tokio::test]
    async fn deposit_adds_cash_notes_that_belongs_to_the_wallet() -> Result<()> {
        let key = MainSecretKey::random();
        let genesis = create_first_cash_note_from_key(&key).expect("Genesis creation to succeed.");
        let dir = create_temp_dir();

        let mut deposit_only = LocalWallet {
            key,
            unconfirmed_spend_requests: Default::default(),

            wallet: KeyLessWallet::new(),
            wallet_dir: dir.path().to_path_buf(),
        };

        deposit_only.deposit(&vec![genesis])?;

        assert_eq!(GENESIS_CASHNOTE_AMOUNT, deposit_only.balance().as_nano());

        Ok(())
    }

    #[tokio::test]
    async fn deposit_does_not_add_cash_notes_not_belonging_to_the_wallet() -> Result<()> {
        let genesis = create_first_cash_note_from_key(&MainSecretKey::random())
            .expect("Genesis creation to succeed.");
        let dir = create_temp_dir();

        let mut local_wallet = LocalWallet {
            key: MainSecretKey::random(),
            unconfirmed_spend_requests: Default::default(),

            wallet: KeyLessWallet::new(),
            wallet_dir: dir.path().to_path_buf(),
        };

        local_wallet.deposit(&vec![genesis])?;

        assert_eq!(NanoTokens::zero(), local_wallet.balance());

        Ok(())
    }

    #[tokio::test]
    async fn deposit_is_idempotent() -> Result<()> {
        let key = MainSecretKey::random();
        let genesis_0 =
            create_first_cash_note_from_key(&key).expect("Genesis creation to succeed.");
        let genesis_1 =
            create_first_cash_note_from_key(&key).expect("Genesis creation to succeed.");
        let dir = create_temp_dir();

        let mut deposit_only = LocalWallet {
            key,
            wallet: KeyLessWallet::new(),
            unconfirmed_spend_requests: Default::default(),
            wallet_dir: dir.path().to_path_buf(),
        };

        deposit_only.deposit(&vec![genesis_0.clone()])?;
        assert_eq!(GENESIS_CASHNOTE_AMOUNT, deposit_only.balance().as_nano());

        deposit_only.deposit(&vec![genesis_0])?;
        assert_eq!(GENESIS_CASHNOTE_AMOUNT, deposit_only.balance().as_nano());

        deposit_only.deposit(&vec![genesis_1])?;
        assert_eq!(GENESIS_CASHNOTE_AMOUNT, deposit_only.balance().as_nano());

        Ok(())
    }

    #[tokio::test]
    async fn deposit_wallet_to_and_from_file() -> Result<()> {
        let dir = create_temp_dir();
        let root_dir = dir.path().to_path_buf();

        let mut depositor = LocalWallet::load_from(&root_dir)?;
        let genesis =
            create_first_cash_note_from_key(&depositor.key).expect("Genesis creation to succeed.");
        depositor.deposit(&vec![genesis])?;
        depositor.store()?;

        let deserialized = LocalWallet::load_from(&root_dir)?;

        assert_eq!(depositor.address(), deserialized.address());
        assert_eq!(GENESIS_CASHNOTE_AMOUNT, depositor.balance().as_nano());
        assert_eq!(GENESIS_CASHNOTE_AMOUNT, deserialized.balance().as_nano());

        assert_eq!(1, depositor.wallet.available_cash_notes.len());
        assert_eq!(0, depositor.wallet.cash_notes_created_for_others.len());
        assert_eq!(0, depositor.wallet.spent_cash_notes.len());

        assert_eq!(1, deserialized.wallet.available_cash_notes.len());
        assert_eq!(0, deserialized.wallet.cash_notes_created_for_others.len());
        assert_eq!(0, deserialized.wallet.spent_cash_notes.len());

        let a_available = depositor
            .wallet
            .available_cash_notes
            .values()
            .last()
            .expect("There to be an available CashNote.");
        let b_available = deserialized
            .wallet
            .available_cash_notes
            .values()
            .last()
            .expect("There to be an available CashNote.");
        assert_eq!(a_available, b_available);

        Ok(())
    }

    /// --------------------------------
    /// <-------> SendWallet <--------->
    /// --------------------------------

    #[tokio::test]
    async fn sending_decreases_balance() -> Result<()> {
        let dir = create_temp_dir();
        let root_dir = dir.path().to_path_buf();

        let mut sender = LocalWallet::load_from(&root_dir)?;
        let sender_cash_note =
            create_first_cash_note_from_key(&sender.key).expect("Genesis creation to succeed.");
        sender.deposit(&vec![sender_cash_note])?;

        assert_eq!(GENESIS_CASHNOTE_AMOUNT, sender.balance().as_nano());

        // We send to a new address.
        let send_amount = 100;
        let recipient_key = MainSecretKey::random();
        let recipient_main_pubkey = recipient_key.main_pubkey();
        let to = vec![(NanoTokens::from(send_amount), recipient_main_pubkey)];
        let created_cash_notes = sender.local_send(to, None)?;

        assert_eq!(1, created_cash_notes.len());
        assert_eq!(
            GENESIS_CASHNOTE_AMOUNT - send_amount,
            sender.balance().as_nano()
        );

        let recipient_cash_note = &created_cash_notes[0];
        assert_eq!(NanoTokens::from(send_amount), recipient_cash_note.value()?);
        assert_eq!(&recipient_main_pubkey, recipient_cash_note.main_pubkey());

        Ok(())
    }

    #[tokio::test]
    async fn send_wallet_to_and_from_file() -> Result<()> {
        let dir = create_temp_dir();
        let root_dir = dir.path().to_path_buf();

        let mut sender = LocalWallet::load_from(&root_dir)?;
        let sender_cash_note =
            create_first_cash_note_from_key(&sender.key).expect("Genesis creation to succeed.");
        sender.deposit(&vec![sender_cash_note])?;

        // We send to a new address.
        let send_amount = 100;
        let recipient_key = MainSecretKey::random();
        let recipient_main_pubkey = recipient_key.main_pubkey();
        let to = vec![(NanoTokens::from(send_amount), recipient_main_pubkey)];
        let _created_cash_notes = sender.local_send(to, None)?;

        sender.store()?;

        let deserialized = LocalWallet::load_from(&root_dir)?;

        assert_eq!(sender.address(), deserialized.address());
        assert_eq!(
            GENESIS_CASHNOTE_AMOUNT - send_amount,
            sender.balance().as_nano()
        );
        assert_eq!(
            GENESIS_CASHNOTE_AMOUNT - send_amount,
            deserialized.balance().as_nano()
        );

        assert_eq!(1, sender.wallet.available_cash_notes.len());
        assert_eq!(1, sender.wallet.cash_notes_created_for_others.len());
        assert_eq!(1, sender.wallet.spent_cash_notes.len());

        assert_eq!(1, deserialized.wallet.available_cash_notes.len());
        assert_eq!(1, deserialized.wallet.cash_notes_created_for_others.len());
        assert_eq!(1, deserialized.wallet.spent_cash_notes.len());

        let a_available = sender
            .wallet
            .available_cash_notes
            .values()
            .last()
            .expect("There to be an available CashNote.");
        let b_available = deserialized
            .wallet
            .available_cash_notes
            .values()
            .last()
            .expect("There to be an available CashNote.");
        assert_eq!(a_available, b_available);

        let a_created_for_others = &sender.wallet.cash_notes_created_for_others;
        let b_created_for_others = &deserialized.wallet.cash_notes_created_for_others;
        assert_eq!(a_created_for_others, b_created_for_others);

        let a_spent = sender
            .wallet
            .spent_cash_notes
            .iter()
            .last()
            .expect("There to be a spent CashNote.");
        let b_spent = deserialized
            .wallet
            .spent_cash_notes
            .iter()
            .last()
            .expect("There to be a spent CashNote.");
        assert_eq!(a_spent, b_spent);

        Ok(())
    }

    #[tokio::test]
    async fn store_created_cash_note_gives_file_that_try_load_deposits_can_use() -> Result<()> {
        let sender_root_dir = create_temp_dir();
        let sender_root_dir = sender_root_dir.path().to_path_buf();

        let mut sender = LocalWallet::load_from(&sender_root_dir)?;
        let sender_cash_note =
            create_first_cash_note_from_key(&sender.key).expect("Genesis creation to succeed.");
        sender.deposit(&vec![sender_cash_note])?;

        let send_amount = 100;

        // Send to a new address.
        let recipient_root_dir = create_temp_dir();
        let recipient_root_dir = recipient_root_dir.path().to_path_buf();
        let mut recipient = LocalWallet::load_from(&recipient_root_dir)?;
        let recipient_main_pubkey = recipient.key.main_pubkey();

        let to = vec![(NanoTokens::from(send_amount), recipient_main_pubkey)];
        let created_cash_notes = sender.local_send(to, None)?;
        let cash_note = created_cash_notes[0].clone();
        let unique_pubkey = cash_note.unique_pubkey();
        sender.store_cash_note(&cash_note)?;

        let unique_pubkey_name = *SpendAddress::from_unique_pubkey(&unique_pubkey).xorname();
        let unique_pubkey_file_name = format!("{}.cash_note", hex::encode(unique_pubkey_name));

        let created_cash_notes_dir = sender_root_dir
            .join(WALLET_DIR_NAME)
            .join("created_cash_notes");
        let created_cash_note_file = created_cash_notes_dir.join(&unique_pubkey_file_name);

        let received_cash_note_dir = recipient_root_dir
            .join(WALLET_DIR_NAME)
            .join("received_cash_notes");

        std::fs::create_dir_all(&received_cash_note_dir)?;
        let received_cash_note_file = received_cash_note_dir.join(&unique_pubkey_file_name);

        // Move the created cash_note to the recipient's received_cash_notes dir.
        std::fs::rename(created_cash_note_file, received_cash_note_file)?;

        assert_eq!(0, recipient.wallet.balance().as_nano());

        recipient.try_load_deposits()?;

        assert_eq!(1, recipient.wallet.available_cash_notes.len());

        let available = recipient
            .wallet
            .available_cash_notes
            .keys()
            .last()
            .expect("There to be an available CashNote.");

        assert_eq!(available, &unique_pubkey);
        assert_eq!(send_amount, recipient.wallet.balance().as_nano());

        Ok(())
    }

    fn create_temp_dir() -> TempDir {
        TempDir::new().expect("Should be able to create a temp dir.")
    }
}