zecwallet-parser 0.0.0

A parser for ZecWallet Lite wallet files.
Documentation
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
use std::{
    collections::HashMap,
    fmt::{self, Display},
    io::{self, Read},
};

use byteorder::{LittleEndian, ReadBytesExt};
use zcash_encoding::Vector;
use zcash_primitives::{consensus::BlockHeight, transaction::TxId};

use super::transactions::WalletTx;

/// List of all transactions in a wallet.
#[derive(Debug, Clone)]
pub struct WalletTxns {
    pub current: HashMap<TxId, WalletTx>,
    pub last_txid: Option<TxId>,
}

impl Default for WalletTxns {
    fn default() -> Self {
        Self::new()
    }
}

impl Display for WalletTxns {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, ">> WalletTxns <<").unwrap();

        match self.current.is_empty() {
            true => {
                writeln!(f, "No transactions in wallet").unwrap();
            }
            false => {
                writeln!(f, "Current transactions: {}", self.current.len()).unwrap();
            }
        }

        Ok(())
    }
}

impl WalletTxns {
    pub fn new() -> Self {
        Self {
            current: HashMap::new(),
            last_txid: None,
        }
    }

    pub fn serialized_version() -> u64 {
        21
    }

    pub fn read<R: Read>(mut reader: R) -> io::Result<Self> {
        let version = reader.read_u64::<LittleEndian>()?;
        if version > Self::serialized_version() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Can't read wallettxns because of incorrect version",
            ));
        }

        let txs_tuples = Vector::read(&mut reader, |r| {
            let mut txid_bytes = [0u8; 32];
            r.read_exact(&mut txid_bytes)?;

            Ok((TxId::from_bytes(txid_bytes), WalletTx::read(r).unwrap()))
        })?;

        let current = txs_tuples.into_iter().collect::<HashMap<TxId, WalletTx>>();
        let last_txid = current
            .values()
            .fold(None, |c: Option<(TxId, BlockHeight)>, w| {
                if c.is_none() || w.block > c.unwrap().1 {
                    Some((w.txid, w.block))
                } else {
                    c
                }
            })
            .map(|v| v.0);

        let _mempool = if version <= 20 {
            Vector::read(&mut reader, |r| {
                let mut txid_bytes = [0u8; 32];
                r.read_exact(&mut txid_bytes)?;
                let wtx = WalletTx::read(r)?;

                Ok((TxId::from_bytes(txid_bytes), wtx))
            })?
            .into_iter()
            .collect()
        } else {
            vec![]
        };

        Ok(Self { current, last_txid })
    }
}

// // /// Note that the parent is expected to hold a RwLock, so we will assume that all accesses to
// // /// this struct are threadsafe/locked properly.
// // #[allow(dead_code)]
// // #[derive(Clone, Debug)]
// // pub struct WalletTxns {
// //     pub(crate) current: HashMap<TxId, WalletTx>,
// //     pub(crate) last_txid: Option<TxId>,
// // }

// #[allow(dead_code)]
// impl WalletTxns {
//     pub fn serialized_version() -> u64 {
//         21
//     }

//     pub fn read_old<R: ReadBytesExt>(mut reader: R) -> io::Result<Self> {
//         let txs_tuples = Vector::read(&mut reader, |r| {
//             let mut txid_bytes = [0u8; 32];
//             r.read_exact(&mut txid_bytes)?;

//             Ok((TxId::from_bytes(txid_bytes), WalletTx::read(r).unwrap()))
//         })?;

//         let txs = txs_tuples.into_iter().collect::<HashMap<TxId, WalletTx>>();

//         Ok(Self {
//             current: txs,
//             last_txid: None,
//         })
//     }

//     pub fn read<R: ReadBytesExt>(mut reader: R) -> io::Result<Self> {
//         let version = reader.read_u64::<LittleEndian>()?;
//         if version > Self::serialized_version() {
//             return Err(io::Error::new(
//                 io::ErrorKind::InvalidData,
//                 "Can't read wallettxns because of incorrect version",
//             ));
//         }

//         let txs_tuples = Vector::read(&mut reader, |r| {
//             let mut txid_bytes = [0u8; 32];
//             r.read_exact(&mut txid_bytes)?;

//             Ok((TxId::from_bytes(txid_bytes), WalletTx::read(r).unwrap()))
//         })?;

//         let current = txs_tuples.into_iter().collect::<HashMap<TxId, WalletTx>>();
//         let last_txid = current
//             .values()
//             .fold(None, |c: Option<(TxId, BlockHeight)>, w| {
//                 if c.is_none() || w.block > c.unwrap().1 {
//                     Some((w.txid, w.block))
//                 } else {
//                     c
//                 }
//             })
//             .map(|v| v.0);

//         let _mempool = if version <= 20 {
//             Vector::read(&mut reader, |r| {
//                 let mut txid_bytes = [0u8; 32];
//                 r.read_exact(&mut txid_bytes)?;
//                 let wtx = WalletTx::read(r)?;

//                 Ok((TxId::from_bytes(txid_bytes), wtx))
//             })?
//             .into_iter()
//             .collect()
//         } else {
//             vec![]
//         };

//         Ok(Self { current, last_txid })
//     }

//     pub fn write<W: WriteBytesExt>(&self, mut writer: W) -> io::Result<()> {
//         // Write the version
//         writer.write_u64::<LittleEndian>(Self::serialized_version())?;

//         // The hashmap, write as a set of tuples. Store them sorted so that wallets are
//         // deterministically saved
//         {
//             let mut txns = self.current.iter().collect::<Vec<(&TxId, &WalletTx)>>();
//             txns.sort_by(|a, b| a.0.partial_cmp(b.0).unwrap());

//             Vector::write(&mut writer, &txns, |w, (k, v)| {
//                 w.write_all(k.as_ref())?;
//                 v.write(w)
//             })?;
//         }

//         Ok(())
//     }

//     pub fn clear(&mut self) {
//         self.current.clear();
//     }

//     pub fn adjust_spendable_status(&mut self, spendable_keys: Vec<ExtendedFullViewingKey>) {
//         self.current.values_mut().for_each(|tx| {
//             tx.sapling_notes.iter_mut().for_each(|nd| {
//                 nd.have_spending_key = spendable_keys.contains(&nd.extfvk);
//                 if !nd.have_spending_key {
//                     nd.witnesses.clear();
//                 }
//             })
//         });
//     }

//     pub fn remove_txids(&mut self, txids_to_remove: Vec<TxId>) {
//         for txid in &txids_to_remove {
//             self.current.remove(txid);
//         }

//         // We also need to update any sapling note data and utxos in existing transactions that
//         // were spent in any of the txids that were removed
//         self.current.values_mut().for_each(|wtx| {
//             // Update notes to rollback any spent notes
//             wtx.sapling_notes.iter_mut().for_each(|nd| {
//                 // Mark note as unspent if the txid being removed spent it.
//                 if nd.spent.is_some() && txids_to_remove.contains(&nd.spent.unwrap().0) {
//                     nd.spent = None;
//                 }

//                 // Remove unconfirmed spends too
//                 if nd.unconfirmed_spent.is_some()
//                     && txids_to_remove.contains(&nd.unconfirmed_spent.unwrap().0)
//                 {
//                     nd.unconfirmed_spent = None;
//                 }
//             });

//             // Update UTXOs to rollback any spent utxos
//             wtx.utxos.iter_mut().for_each(|utxo| {
//                 if utxo.spent.is_some() && txids_to_remove.contains(&utxo.spent.unwrap()) {
//                     utxo.spent = None;
//                     utxo.spent_at_height = None;
//                 }

//                 if utxo.unconfirmed_spent.is_some()
//                     && txids_to_remove.contains(&utxo.unconfirmed_spent.unwrap().0)
//                 {
//                     utxo.unconfirmed_spent = None;
//                 }
//             })
//         });
//     }

//     // During reorgs, we need to remove all txns at a given height, and all spends that refer to any removed txns.
//     pub fn remove_txns_at_height(&mut self, reorg_height: u64) {
//         let reorg_height = BlockHeight::from_u32(reorg_height as u32);

//         // First, collect txids that need to be removed
//         let txids_to_remove = self
//             .current
//             .values()
//             .filter_map(|wtx| {
//                 if wtx.block >= reorg_height {
//                     Some(wtx.txid)
//                 } else {
//                     None
//                 }
//             })
//             .collect::<Vec<_>>();
//         self.remove_txids(txids_to_remove);

//         // Of the notes that still remain, unroll the witness.
//         // Trim all witnesses for the invalidated blocks
//         for tx in self.current.values_mut() {
//             // We only want to trim the witness for "existing" notes, i.e., notes that were created before the block that is being removed
//             if tx.block < reorg_height {
//                 for nd in tx.sapling_notes.iter_mut() {
//                     // The latest witness is at the last() position, so just pop() it.
//                     // We should be checking if there is a witness at all, but if there is none, it is an
//                     // empty vector, for which pop() is a no-op.
//                     nd.witnesses.pop(u64::from(reorg_height));
//                 }
//             }
//         }
//     }

//     pub fn get_last_txid(&self) -> &'_ Option<TxId> {
//         &self.last_txid
//     }

//     pub fn get_notes_for_updating(
//         &self,
//         before_block: u64,
//     ) -> Vec<(TxId, sapling_crypto::Nullifier)> {
//         let before_block = BlockHeight::from_u32(before_block as u32);

//         self.current
//             .iter()
//             .filter(|(_, wtx)| !wtx.unconfirmed) // Update only confirmed notes
//             .flat_map(|(txid, wtx)| {
//                 // Fetch notes that are before the before_block.
//                 wtx.sapling_notes.iter().filter_map(move |snd| {
//                     if wtx.block <= before_block
//                         && snd.have_spending_key
//                         && !snd.witnesses.is_empty()
//                         && snd.spent.is_none()
//                     {
//                         Some((*txid, snd.nullifier))
//                     } else {
//                         None
//                     }
//                 })
//             })
//             .collect()
//     }

//     pub fn total_funds_spent_in(&self, txid: &TxId) -> u64 {
//         self.current
//             .get(txid)
//             .map(|t| t.total_funds_spent())
//             .unwrap_or(0)
//     }

//     pub fn get_unspent_s_nullifiers(&self) -> Vec<(sapling_crypto::Nullifier, u64, TxId)> {
//         self.current
//             .iter()
//             .flat_map(|(_, wtx)| {
//                 wtx.sapling_notes
//                     .iter()
//                     .filter(|nd| nd.spent.is_none())
//                     .map(move |nd| (nd.nullifier, nd.note.value().inner(), wtx.txid))
//             })
//             .collect()
//     }

//     pub fn get_unspent_o_nullifiers(&self) -> Vec<(orchard_old::note::Nullifier, u64, TxId)> {
//         self.current
//             .iter()
//             .flat_map(|(_, wtx)| {
//                 wtx.orchard_notes
//                     .iter()
//                     .filter(|nd| nd.spent.is_none())
//                     .map(move |nd| {
//                         (
//                             nd.note.nullifier(&nd.fvk),
//                             nd.note.value().inner(),
//                             wtx.txid,
//                         )
//                     })
//             })
//             .collect()
//     }

//     pub(crate) fn get_note_witness(
//         &self,
//         txid: &TxId,
//         nullifier: &Nullifier,
//     ) -> Option<(WitnessCache, BlockHeight)> {
//         self.current.get(txid).map(|wtx| {
//             wtx.sapling_notes
//                 .iter()
//                 .find(|nd| nd.nullifier == *nullifier)
//                 .map(|nd| (nd.witnesses.clone(), wtx.block))
//         })?
//     }

//     pub(crate) fn set_o_note_witness(
//         &mut self,
//         (height, tx_num, output_num): (u64, usize, u32),
//         pos: Option<Position>,
//     ) {
//         self.current.iter_mut().for_each(|(_, wtx)| {
//             wtx.orchard_notes
//                 .iter_mut()
//                 .filter(|on| on.witness_position.is_none())
//                 .find(|on| {
//                     let (h, t, p) = on.created_at;
//                     height == h && t == tx_num && output_num == p
//                 })
//                 .map(|on| on.witness_position = pos);
//         });
//     }

//     pub(crate) fn set_s_note_witnesses(
//         &mut self,
//         txid: &TxId,
//         nullifier: &Nullifier,
//         witnesses: WitnessCache,
//     ) {
//         self.current
//             .get_mut(txid)
//             .unwrap()
//             .sapling_notes
//             .iter_mut()
//             .find(|nd| nd.nullifier == *nullifier)
//             .unwrap()
//             .witnesses = witnesses;
//     }

//     pub(crate) fn clear_old_witnesses(&mut self, latest_height: u64) {
//         let cutoff = (latest_height.saturating_sub(MAX_REORG as u64)) as u32;

//         self.current.iter_mut().for_each(|(_, wtx)| {
//             wtx.sapling_notes
//                 .iter_mut()
//                 .filter(|n| {
//                     !n.witnesses.is_empty() && n.spent.is_some() && n.spent.unwrap().1 < cutoff
//                 })
//                 .for_each(|n| n.witnesses.clear());
//         });
//     }

//     pub(crate) fn clear_expired_mempool(&mut self, latest_height: u64) {
//         let cutoff = BlockHeight::from_u32((latest_height.saturating_sub(MAX_REORG as u64)) as u32);

//         let txids_to_remove = self
//             .current
//             .iter()
//             .filter(|(_, wtx)| wtx.unconfirmed && wtx.block < cutoff)
//             .map(|(_, wtx)| wtx.txid)
//             .collect::<Vec<_>>();

//         txids_to_remove
//             .iter()
//             .for_each(|t| println!("Removing expired mempool tx {}", t));

//         self.remove_txids(txids_to_remove);
//     }

//     // Will mark the nullifier of the given txid as spent. Returns the amount of the nullifier
//     pub fn mark_txid_o_nf_spent(
//         &mut self,
//         txid: &TxId,
//         nullifier: &orchard_old::note::Nullifier,
//         spent_txid: &TxId,
//         spent_at_height: BlockHeight,
//     ) -> u64 {
//         let note_data = self
//             .current
//             .get_mut(txid)
//             .unwrap()
//             .orchard_notes
//             .iter_mut()
//             .find(|n| n.note.nullifier(&n.fvk) == *nullifier)
//             .unwrap();

//         note_data.spent = Some((*spent_txid, spent_at_height.into()));
//         note_data.unconfirmed_spent = None;
//         note_data.note.value().inner()
//     }

//     // Will mark the nullifier of the given txid as spent. Returns the amount of the nullifier
//     pub fn mark_txid_s_nf_spent(
//         &mut self,
//         txid: &TxId,
//         nullifier: &Nullifier,
//         spent_txid: &TxId,
//         spent_at_height: BlockHeight,
//     ) -> u64 {
//         let note_data = self
//             .current
//             .get_mut(txid)
//             .unwrap()
//             .sapling_notes
//             .iter_mut()
//             .find(|n| n.nullifier == *nullifier)
//             .unwrap();

//         note_data.spent = Some((*spent_txid, spent_at_height.into()));
//         note_data.unconfirmed_spent = None;
//         note_data.note.value().inner()
//     }

//     // Check this transaction to see if it is an outgoing transaction, and if it is, mark all recieved notes in this
//     // transction as change. i.e., If any funds were spent in this transaction, all recieved notes are change notes.
//     pub fn check_notes_mark_change(&mut self, txid: &TxId) {
//         if self.total_funds_spent_in(txid) > 0 {
//             self.current.get_mut(txid).map(|wtx| {
//                 wtx.sapling_notes.iter_mut().for_each(|n| {
//                     n.is_change = true;
//                 });

//                 wtx.orchard_notes.iter_mut().for_each(|n| {
//                     n.is_change = true;
//                 });
//             });
//         }
//     }

//     fn get_or_create_tx(
//         &mut self,
//         txid: &TxId,
//         height: BlockHeight,
//         unconfirmed: bool,
//         datetime: u64,
//     ) -> &'_ mut WalletTx {
//         if !self.current.contains_key(txid) {
//             self.current
//                 .insert(*txid, WalletTx::new(height, datetime, txid, unconfirmed));
//             self.last_txid = Some(*txid);
//         }
//         let wtx = self.current.get_mut(txid).expect("Txid should be present");

//         // Make sure the unconfirmed status matches
//         if wtx.unconfirmed != unconfirmed {
//             wtx.unconfirmed = unconfirmed;
//             wtx.block = height;
//             wtx.datetime = datetime;
//         }

//         wtx
//     }

//     pub fn set_price(&mut self, txid: &TxId, price: Option<f64>) {
//         price.map(|p| self.current.get_mut(txid).map(|tx| tx.zec_price = Some(p)));
//     }

//     pub fn add_new_o_spent(
//         &mut self,
//         txid: TxId,
//         height: BlockHeight,
//         unconfirmed: bool,
//         timestamp: u32,
//         nullifier: orchard_old::note::Nullifier,
//         value: u64,
//         source_txid: TxId,
//     ) -> Option<Position> {
//         // Record this Tx as having spent some funds
//         {
//             let wtx = self.get_or_create_tx(&txid, height, unconfirmed, timestamp as u64);

//             // Mark the height correctly, in case this was previously a mempool or unconfirmed tx.
//             wtx.block = height;

//             if !wtx.o_spent_nullifiers.iter().any(|nf| *nf == nullifier) {
//                 wtx.o_spent_nullifiers.push(nullifier);
//                 wtx.total_orchard_value_spent += value;
//             }
//         }

//         // Since this Txid has spent some funds, output notes in this Tx that are sent to us are actually change.
//         self.check_notes_mark_change(&txid);

//         // Mark the source note's nullifier as spent
//         if !unconfirmed {
//             let wtx = self
//                 .current
//                 .get_mut(&source_txid)
//                 .expect("Txid should be present");

//             wtx.orchard_notes
//                 .iter_mut()
//                 .find(|n| n.note.nullifier(&n.fvk) == nullifier)
//                 .and_then(|nd| {
//                     // Record the spent height
//                     nd.spent = Some((txid, height.into()));
//                     nd.witness_position
//                 })
//         } else {
//             None
//         }
//     }

//     // Records a TxId as having spent some nullifiers from the wallet.
//     pub fn add_new_s_spent(
//         &mut self,
//         txid: TxId,
//         height: BlockHeight,
//         unconfirmed: bool,
//         timestamp: u32,
//         nullifier: Nullifier,
//         value: u64,
//         source_txid: TxId,
//     ) {
//         // Record this Tx as having spent some funds
//         {
//             let wtx = self.get_or_create_tx(&txid, height, unconfirmed, timestamp as u64);

//             // Mark the height correctly, in case this was previously a mempool or unconfirmed tx.
//             wtx.block = height;

//             if !wtx.s_spent_nullifiers.iter().any(|nf| *nf == nullifier) {
//                 wtx.s_spent_nullifiers.push(nullifier);
//                 wtx.total_sapling_value_spent += value;
//             }
//         }

//         // Since this Txid has spent some funds, output notes in this Tx that are sent to us are actually change.
//         self.check_notes_mark_change(&txid);

//         // Mark the source note's nullifier as spent
//         if !unconfirmed {
//             let wtx = self
//                 .current
//                 .get_mut(&source_txid)
//                 .expect("Txid should be present");

//             if let Some(nd) = wtx
//                 .sapling_notes
//                 .iter_mut()
//                 .find(|n| n.nullifier == nullifier)
//             {
//                 nd.spent = Some((txid, height.into()));
//             }
//         }
//     }

//     pub fn add_taddr_spent(
//         &mut self,
//         txid: TxId,
//         height: BlockHeight,
//         unconfirmed: bool,
//         timestamp: u64,
//         total_transparent_value_spent: u64,
//     ) {
//         let wtx = self.get_or_create_tx(&txid, height, unconfirmed, timestamp);
//         wtx.total_transparent_value_spent = total_transparent_value_spent;

//         self.check_notes_mark_change(&txid);
//     }

//     pub fn mark_txid_utxo_spent(
//         &mut self,
//         spent_txid: TxId,
//         output_num: u32,
//         source_txid: TxId,
//         source_height: u32,
//     ) -> u64 {
//         // Find the UTXO
//         let value = if let Some(utxo_wtx) = self.current.get_mut(&spent_txid) {
//             if let Some(spent_utxo) = utxo_wtx
//                 .utxos
//                 .iter_mut()
//                 .find(|u| u.txid == spent_txid && u.output_index == output_num as u64)
//             {
//                 // Mark this one as spent
//                 spent_utxo.spent = Some(source_txid);
//                 spent_utxo.spent_at_height = Some(source_height as i32);
//                 spent_utxo.unconfirmed_spent = None;

//                 spent_utxo.value
//             } else {
//                 println!("Couldn't find UTXO that was spent");
//                 0
//             }
//         } else {
//             println!("Couldn't find TxID that was spent!");
//             0
//         };

//         // Return the value of the note that was spent.
//         value
//     }

//     pub fn add_new_taddr_output(
//         &mut self,
//         txid: TxId,
//         taddr: String,
//         height: u32,
//         unconfirmed: bool,
//         timestamp: u64,
//         vout: &TxOut,
//         output_num: u32,
//     ) {
//         // Read or create the current TxId
//         let wtx = self.get_or_create_tx(&txid, BlockHeight::from(height), unconfirmed, timestamp);

//         // Add this UTXO if it doesn't already exist
//         if let Some(utxo) = wtx
//             .utxos
//             .iter_mut()
//             .find(|utxo| utxo.txid == txid && utxo.output_index == output_num as u64)
//         {
//             // If it already exists, it is likely an mempool tx, so update the height
//             utxo.height = height as i32
//         } else {
//             wtx.utxos.push(Utxo {
//                 address: taddr,
//                 txid,
//                 output_index: output_num as u64,
//                 script: vout.script_pubkey.0.clone(),
//                 value: vout.value.into(),
//                 height: height as i32,
//                 spent_at_height: None,
//                 spent: None,
//                 unconfirmed_spent: None,
//             });
//         }
//     }

//     pub fn add_pending_note(
//         &mut self,
//         txid: TxId,
//         height: BlockHeight,
//         timestamp: u64,
//         note: Note,
//         to: PaymentAddress,
//         extfvk: &ExtendedFullViewingKey,
//     ) {
//         // Check if this is a change note
//         let is_change = self.total_funds_spent_in(&txid) > 0;

//         let wtx = self.get_or_create_tx(&txid, height, true, timestamp);
//         // Update the block height, in case this was a mempool or unconfirmed tx.
//         wtx.block = height;

//         if !wtx.sapling_notes.iter_mut().any(|n| n.note == note) {
//             let nd = SaplingNoteData {
//                 extfvk: extfvk.clone(),
//                 diversifier: *to.diversifier(),
//                 note,
//                 witnesses: WitnessCache::empty(),
//                 nullifier: Nullifier([0u8; 32]),
//                 spent: None,
//                 unconfirmed_spent: None,
//                 memo: None,
//                 is_change,
//                 have_spending_key: false,
//             };

//             wtx.sapling_notes.push(nd);
//         }
//     }

//     pub fn add_new_orchard_note(
//         &mut self,
//         txid: TxId,
//         height: BlockHeight,
//         unconfirmed: bool,
//         timestamp: u64,
//         note: orchard_old::Note,
//         created_at: (u64, usize, u32),
//         fvk: &FullViewingKey,
//         have_spending_key: bool,
//     ) {
//         // Check if this is a change note
//         let is_change = self.total_funds_spent_in(&txid) > 0;

//         let wtx = self.get_or_create_tx(&txid, height, unconfirmed, timestamp);
//         // Update the block height, in case this was a mempool or unconfirmed tx.
//         wtx.block = height;

//         let note_nullifier = note.nullifier(fvk);

//         match wtx
//             .orchard_notes
//             .iter_mut()
//             .find(|n| n.note.nullifier(fvk) == note_nullifier)
//         {
//             None => {
//                 let nd = OrchardNoteData {
//                     fvk: fvk.clone(),
//                     note,
//                     spent: None,
//                     unconfirmed_spent: None,
//                     created_at,
//                     witness_position: None,
//                     memo: None,
//                     is_change,
//                     have_spending_key,
//                 };

//                 wtx.orchard_notes.push(nd);

//                 // TODO: Remove pending notes for this tx.
//             }
//             Some(_) => {
//                 // If this note already exists, then just reset the witnesses, because we'll start scanning the witnesses
//                 // again after this.
//                 // This is likely to happen if the previous wallet wasn't synced properly or was aborted in the middle of a sync,
//                 // and has some dangling witnesses
//                 println!("Orchard note already exists in wallet!");
//             }
//         }
//     }

//     pub fn add_new_sapling_note(
//         &mut self,
//         txid: TxId,
//         height: BlockHeight,
//         unconfirmed: bool,
//         timestamp: u64,
//         note: Note,
//         to: PaymentAddress,
//         extfvk: &ExtendedFullViewingKey,
//         have_spending_key: bool,
//         witness: IncrementalWitness,
//     ) {
//         // Check if this is a change note
//         let is_change = self.total_funds_spent_in(&txid) > 0;

//         let wtx = self.get_or_create_tx(&txid, height, unconfirmed, timestamp);
//         // Update the block height, in case this was a mempool or unconfirmed tx.
//         wtx.block = height;

//         let nullifier = note.nf(&extfvk.fvk.vk.nk, u64::from(witness.witnessed_position()));
//         let witnesses = if have_spending_key {
//             WitnessCache::new(vec![witness], u64::from(height))
//         } else {
//             WitnessCache::empty()
//         };

//         match wtx
//             .sapling_notes
//             .iter_mut()
//             .find(|n| n.nullifier == nullifier)
//         {
//             None => {
//                 let nd = SaplingNoteData {
//                     extfvk: extfvk.clone(),
//                     diversifier: *to.diversifier(),
//                     note,
//                     witnesses,
//                     nullifier,
//                     spent: None,
//                     unconfirmed_spent: None,
//                     memo: None,
//                     is_change,
//                     have_spending_key,
//                 };

//                 wtx.sapling_notes.push(nd);

//                 // Also remove any pending notes.
//                 wtx.sapling_notes.retain(|n| n.nullifier.0 != [0u8; 32]);
//             }
//             Some(n) => {
//                 // If this note already exists, then just reset the witnesses, because we'll start scanning the witnesses
//                 // again after this.
//                 // This is likely to happen if the previous wallet wasn't synced properly or was aborted in the middle of a sync,
//                 // and has some dangling witnesses
//                 n.witnesses = witnesses;
//             }
//         }
//     }

//     // Update the memo for a sapling note if it already exists. If the note doesn't exist, then nothing happens.
//     pub fn add_memo_to_s_note(&mut self, txid: &TxId, note: Note, memo: Memo) {
//         if let Some(wtx) = self.current.get_mut(txid) {
//             wtx.sapling_notes
//                 .iter_mut()
//                 .find(|n| n.note == note)
//                 .map(|n| n.memo = Some(memo));
//         }
//     }

//     // Update the memo for a orchard note if it already exists. The note has to already exist.
//     pub fn add_memo_to_o_note(
//         &mut self,
//         txid: &TxId,
//         fvk: &FullViewingKey,
//         note: orchard_old::Note,
//         memo: Memo,
//     ) {
//         // println!("Adding memo to orchard note");
//         let note_nullifier = note.nullifier(fvk);

//         if let Some(wtx) = self.current.get_mut(txid) {
//             wtx.orchard_notes
//                 .iter_mut()
//                 .find(|n| n.note.nullifier(fvk) == note_nullifier)
//                 .map(|n| n.memo = Some(memo));
//         }
//     }

//     pub fn add_outgoing_metadata(
//         &mut self,
//         txid: &TxId,
//         outgoing_metadata: Vec<OutgoingTxMetadata>,
//     ) {
//         if let Some(wtx) = self.current.get_mut(txid) {
//             // This is n^2 search, but this is likely very small struct, limited by the protocol, so...
//             let new_omd: Vec<_> = outgoing_metadata
//                 .into_iter()
//                 .filter(|om| !wtx.outgoing_metadata.iter().any(|o| *o == *om))
//                 .collect();

//             wtx.outgoing_metadata.extend(new_omd);
//         } else {
//             println!(
//                 "TxId {} should be present while adding metadata, but wasn't",
//                 txid
//             );
//         }
//     }
// }