Skip to main content

zecwallet_parser/zwl/
transactions.rs

1use std::io::{self};
2
3use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
4use sapling_crypto::IncrementalWitness;
5use zcash_encoding::{Optional, Vector};
6use zcash_primitives::{
7    consensus::BlockHeight,
8    memo::{Memo, MemoBytes},
9    transaction::{
10        TxId,
11        components::OutPoint,
12    },
13};
14
15use super::{orchard_data::OrchardNoteData, sapling_data::SaplingNoteData};
16
17pub const MAX_REORG: usize = 100;
18
19#[derive(Clone, Debug)]
20pub struct WalletTx {
21    // Block in which this tx was included
22    pub block: BlockHeight,
23
24    // Is this Tx unconfirmed (i.e., not yet mined)
25    pub unconfirmed: bool,
26
27    // Timestamp of Tx. Added in v4
28    pub datetime: u64,
29
30    // Txid of this transaction. It's duplicated here (It is also the Key in the HashMap that points to this
31    // WalletTx in LightWallet::txs)
32    pub txid: TxId,
33
34    // List of all nullifiers spent in this Tx. These nullifiers belong to the wallet.
35    pub s_spent_nullifiers: Vec<sapling_crypto::Nullifier>,
36
37    // List of all orchard nullifiers spent in this Tx.
38    pub o_spent_nullifiers: Vec<orchard_old::note::Nullifier>,
39
40    // List of all notes received in this tx. Some of these might be change notes.
41    pub sapling_notes: Vec<SaplingNoteData>,
42
43    // List of all orchard notes recieved in this tx. Some of these might be change.
44    pub orchard_notes: Vec<OrchardNoteData>,
45
46    // List of all Utxos received in this Tx. Some of these might be change notes
47    pub utxos: Vec<Utxo>,
48
49    // Total value of all orchard nullifiers that were spent in this Tx
50    pub total_orchard_value_spent: u64,
51
52    // Total value of all the sapling nullifiers that were spent in this Tx
53    pub total_sapling_value_spent: u64,
54
55    // Total amount of transparent funds that belong to us that were spent in this Tx.
56    pub total_transparent_value_spent: u64,
57
58    // All outgoing sapling sends to addresses outside this wallet
59    pub outgoing_metadata: Vec<OutgoingTxMetadata>,
60
61    // Whether this TxID was downloaded from the server and scanned for Memos
62    pub full_tx_scanned: bool,
63
64    // Price of Zec when this Tx was created
65    pub zec_price: Option<f64>,
66}
67
68#[allow(dead_code)]
69impl WalletTx {
70    pub fn serialized_version() -> u64 {
71        23
72    }
73
74    pub fn new_txid(txid: &Vec<u8>) -> TxId {
75        let mut txid_bytes = [0u8; 32];
76        txid_bytes.copy_from_slice(txid);
77        TxId::from_bytes(txid_bytes)
78    }
79
80    pub fn new(height: BlockHeight, datetime: u64, txid: &TxId, unconfirmed: bool) -> Self {
81        WalletTx {
82            block: height,
83            unconfirmed,
84            datetime,
85            txid: *txid,
86            o_spent_nullifiers: vec![],
87            s_spent_nullifiers: vec![],
88            sapling_notes: vec![],
89            orchard_notes: vec![],
90            utxos: vec![],
91            total_transparent_value_spent: 0,
92            total_sapling_value_spent: 0,
93            total_orchard_value_spent: 0,
94            outgoing_metadata: vec![],
95            full_tx_scanned: false,
96            zec_price: None,
97        }
98    }
99
100    pub fn read<R: ReadBytesExt>(mut reader: R) -> io::Result<Self> {
101        let version = reader.read_u64::<LittleEndian>()?;
102
103        let block = BlockHeight::from_u32(reader.read_i32::<LittleEndian>()? as u32);
104
105        let unconfirmed = if version <= 20 {
106            false
107        } else {
108            reader.read_u8()? == 1
109        };
110
111        let datetime = if version >= 4 {
112            reader.read_u64::<LittleEndian>()?
113        } else {
114            0
115        };
116
117        let mut txid_bytes = [0u8; 32];
118        reader.read_exact(&mut txid_bytes)?;
119
120        let txid = TxId::from_bytes(txid_bytes);
121
122        let s_notes = Vector::read(&mut reader, |r| SaplingNoteData::read(r))?;
123        let utxos = Vector::read(&mut reader, |r| Utxo::read(r))?;
124
125        let total_orchard_value_spent = if version <= 22 {
126            0
127        } else {
128            reader.read_u64::<LittleEndian>()?
129        };
130        let total_sapling_value_spent = reader.read_u64::<LittleEndian>()?;
131        let total_transparent_value_spent = reader.read_u64::<LittleEndian>()?;
132
133        // Outgoing metadata was only added in version 2
134        let outgoing_metadata = Vector::read(&mut reader, |r| OutgoingTxMetadata::read(r))?;
135
136        let full_tx_scanned = reader.read_u8()? > 0;
137
138        let zec_price = if version <= 4 {
139            None
140        } else {
141            Optional::read(&mut reader, |r| r.read_f64::<LittleEndian>())?
142        };
143
144        let s_spent_nullifiers = if version <= 5 {
145            vec![]
146        } else {
147            Vector::read(&mut reader, |r| {
148                let mut n = [0u8; 32];
149                r.read_exact(&mut n)?;
150                Ok(sapling_crypto::Nullifier(n))
151            })?
152        };
153
154        let o_notes = if version <= 21 {
155            vec![]
156        } else {
157            Vector::read(&mut reader, |r| OrchardNoteData::read(r))?
158        };
159
160        let o_spent_nullifiers = if version <= 21 {
161            vec![]
162        } else {
163            Vector::read(&mut reader, |r| {
164                let mut rho_bytes = [0u8; 32];
165                r.read_exact(&mut rho_bytes)?;
166                Ok(orchard_old::note::Nullifier::from_bytes(&rho_bytes).unwrap())
167            })?
168        };
169
170        Ok(Self {
171            block,
172            unconfirmed,
173            datetime,
174            txid,
175            sapling_notes: s_notes,
176            orchard_notes: o_notes,
177            utxos,
178            s_spent_nullifiers,
179            o_spent_nullifiers,
180            total_sapling_value_spent,
181            total_orchard_value_spent,
182            total_transparent_value_spent,
183            outgoing_metadata,
184            full_tx_scanned,
185            zec_price,
186        })
187    }
188
189    pub fn write<W: WriteBytesExt>(&self, mut writer: W) -> io::Result<()> {
190        writer.write_u64::<LittleEndian>(Self::serialized_version())?;
191
192        let block: u32 = self.block.into();
193        writer.write_i32::<LittleEndian>(block as i32)?;
194
195        writer.write_u8(if self.unconfirmed { 1 } else { 0 })?;
196
197        writer.write_u64::<LittleEndian>(self.datetime)?;
198
199        writer.write_all(self.txid.as_ref())?;
200
201        Vector::write(&mut writer, &self.sapling_notes, |w, nd| nd.write(w))?;
202        Vector::write(&mut writer, &self.utxos, |w, u| u.write(w))?;
203
204        writer.write_u64::<LittleEndian>(self.total_orchard_value_spent)?;
205        writer.write_u64::<LittleEndian>(self.total_sapling_value_spent)?;
206        writer.write_u64::<LittleEndian>(self.total_transparent_value_spent)?;
207
208        // Write the outgoing metadata
209        Vector::write(&mut writer, &self.outgoing_metadata, |w, om| om.write(w))?;
210
211        writer.write_u8(if self.full_tx_scanned { 1 } else { 0 })?;
212
213        Optional::write(&mut writer, self.zec_price, |w, p| {
214            w.write_f64::<LittleEndian>(p)
215        })?;
216
217        Vector::write(&mut writer, &self.s_spent_nullifiers, |w, n| {
218            w.write_all(&n.0)
219        })?;
220
221        Vector::write(&mut writer, &self.orchard_notes, |w, n| n.write(w))?;
222
223        Vector::write(&mut writer, &self.o_spent_nullifiers, |w, n| {
224            w.write_all(&n.to_bytes())
225        })?;
226
227        Ok(())
228    }
229
230    pub fn total_funds_spent(&self) -> u64 {
231        self.total_orchard_value_spent
232            + self.total_sapling_value_spent
233            + self.total_transparent_value_spent
234    }
235}
236
237#[derive(Clone, Debug)]
238pub struct Utxo {
239    pub address: String,
240    pub txid: TxId,
241    pub output_index: u64,
242    pub script: Vec<u8>,
243    pub value: u64,
244    pub height: i32,
245
246    pub spent_at_height: Option<i32>,
247    pub spent: Option<TxId>, // If this utxo was confirmed spent
248
249    // If this utxo was spent in a send, but has not yet been confirmed.
250    // Contains the txid and height at which the Tx was broadcast
251    pub unconfirmed_spent: Option<(TxId, u32)>,
252}
253
254#[allow(dead_code)]
255impl Utxo {
256    pub fn serialized_version() -> u64 {
257        3
258    }
259
260    pub fn to_outpoint(&self) -> OutPoint {
261        OutPoint::new(*self.txid.as_ref(), self.output_index as u32)
262    }
263
264    pub fn read<R: ReadBytesExt>(mut reader: R) -> io::Result<Self> {
265        let version = reader.read_u64::<LittleEndian>()?;
266
267        let address_len = reader.read_i32::<LittleEndian>()?;
268        let mut address_bytes = vec![0; address_len as usize];
269        reader.read_exact(&mut address_bytes)?;
270        let address = String::from_utf8(address_bytes).unwrap();
271        assert_eq!(address.chars().take(1).collect::<Vec<char>>()[0], 't');
272
273        let mut txid_bytes = [0; 32];
274        reader.read_exact(&mut txid_bytes)?;
275        let txid = TxId::from_bytes(txid_bytes);
276
277        let output_index = reader.read_u64::<LittleEndian>()?;
278        let value = reader.read_u64::<LittleEndian>()?;
279        let height = reader.read_i32::<LittleEndian>()?;
280
281        let script = Vector::read(&mut reader, |r| {
282            let mut byte = [0; 1];
283            r.read_exact(&mut byte)?;
284            Ok(byte[0])
285        })?;
286
287        let spent = Optional::read(&mut reader, |r| {
288            let mut txbytes = [0u8; 32];
289            r.read_exact(&mut txbytes)?;
290            Ok(TxId::from_bytes(txbytes))
291        })?;
292
293        let spent_at_height = if version <= 1 {
294            None
295        } else {
296            Optional::read(&mut reader, |r| r.read_i32::<LittleEndian>())?
297        };
298
299        let unconfirmed_spent = if version <= 2 {
300            None
301        } else {
302            Optional::read(&mut reader, |r| {
303                let mut txbytes = [0u8; 32];
304                r.read_exact(&mut txbytes)?;
305
306                let height = r.read_u32::<LittleEndian>()?;
307                Ok((TxId::from_bytes(txbytes), height))
308            })?
309        };
310
311        Ok(Utxo {
312            address,
313            txid,
314            output_index,
315            script,
316            value,
317            height,
318            spent_at_height,
319            spent,
320            unconfirmed_spent,
321        })
322    }
323
324    pub fn write<W: WriteBytesExt>(&self, mut writer: W) -> io::Result<()> {
325        writer.write_u64::<LittleEndian>(Self::serialized_version())?;
326
327        writer.write_u32::<LittleEndian>(self.address.len() as u32)?;
328        writer.write_all(self.address.as_bytes())?;
329
330        writer.write_all(self.txid.as_ref())?;
331
332        writer.write_u64::<LittleEndian>(self.output_index)?;
333        writer.write_u64::<LittleEndian>(self.value)?;
334        writer.write_i32::<LittleEndian>(self.height)?;
335
336        Vector::write(&mut writer, &self.script, |w, b| w.write_all(&[*b]))?;
337
338        Optional::write(&mut writer, self.spent, |w, txid| {
339            w.write_all(txid.as_ref())
340        })?;
341
342        Optional::write(&mut writer, self.spent_at_height, |w, s| {
343            w.write_i32::<LittleEndian>(s)
344        })?;
345
346        Optional::write(&mut writer, self.unconfirmed_spent, |w, (txid, height)| {
347            w.write_all(txid.as_ref())?;
348            w.write_u32::<LittleEndian>(height)
349        })?;
350
351        Ok(())
352    }
353}
354
355#[derive(Clone, Debug)]
356pub struct WitnessCache {
357    pub witnesses: Vec<IncrementalWitness>,
358    pub top_height: u64,
359}
360
361#[allow(dead_code)]
362impl WitnessCache {
363    pub fn new(witnesses: Vec<IncrementalWitness>, top_height: u64) -> Self {
364        Self {
365            witnesses,
366            top_height,
367        }
368    }
369
370    pub fn empty() -> Self {
371        Self {
372            witnesses: vec![],
373            top_height: 0,
374        }
375    }
376
377    pub fn len(&self) -> usize {
378        self.witnesses.len()
379    }
380
381    pub fn is_empty(&self) -> bool {
382        self.witnesses.is_empty()
383    }
384
385    pub fn clear(&mut self) {
386        self.witnesses.clear();
387    }
388
389    pub fn get(&self, i: usize) -> Option<&IncrementalWitness> {
390        self.witnesses.get(i)
391    }
392
393    #[cfg(test)]
394    pub fn get_from_last(&self, i: usize) -> Option<&IncrementalWitness> {
395        self.witnesses.get(self.len() - i - 1)
396    }
397
398    pub fn last(&self) -> Option<&IncrementalWitness> {
399        self.witnesses.last()
400    }
401
402    // pub fn into_fsb(self, fsb: &mut FixedSizeBuffer<IncrementalWitness>) {
403    //     self.witnesses.into_iter().for_each(|w| fsb.push(w));
404    // }
405
406    pub fn pop(&mut self, at_height: u64) {
407        while !self.witnesses.is_empty() && self.top_height >= at_height {
408            self.witnesses.pop();
409            self.top_height -= 1;
410        }
411    }
412
413    // pub fn get_as_string(&self, i: usize) -> String {
414    //     if i >= self.witnesses.len() {
415    //         return "".to_string();
416    //     }
417
418    //     let mut buf = vec![];
419    //     self.get(i).unwrap().write(&mut buf).unwrap();
420    //     return hex::encode(buf);
421    // }
422}
423
424#[derive(PartialEq, Clone, Debug)]
425pub struct OutgoingTxMetadata {
426    pub address: String,
427    pub value: u64,
428    pub memo: Memo,
429}
430
431impl OutgoingTxMetadata {
432    pub fn read<R: ReadBytesExt>(mut reader: R) -> io::Result<Self> {
433        let address_len = reader.read_u64::<LittleEndian>()?;
434        let mut address_bytes = vec![0; address_len as usize];
435        reader.read_exact(&mut address_bytes)?;
436        let address = String::from_utf8(address_bytes).unwrap();
437
438        let value = reader.read_u64::<LittleEndian>()?;
439
440        let mut memo_bytes = [0u8; 512];
441        reader.read_exact(&mut memo_bytes)?;
442        let memo = match MemoBytes::from_bytes(&memo_bytes) {
443            Ok(mb) => match Memo::try_from(mb.clone()) {
444                Ok(m) => Ok(m),
445                Err(_) => Ok(Memo::Future(mb)),
446            },
447            Err(e) => Err(io::Error::new(
448                io::ErrorKind::InvalidInput,
449                format!("Couldn't create memo: {}", e),
450            )),
451        }?;
452
453        Ok(OutgoingTxMetadata {
454            address,
455            value,
456            memo,
457        })
458    }
459
460    pub fn write<W: WriteBytesExt>(&self, mut writer: W) -> io::Result<()> {
461        // Strings are written as len + utf8
462        writer.write_u64::<LittleEndian>(self.address.len() as u64)?;
463        writer.write_all(self.address.as_bytes())?;
464
465        writer.write_u64::<LittleEndian>(self.value)?;
466        writer.write_all(self.memo.encode().as_array())
467    }
468}