Skip to main content

zecwallet_parser/zwl/
sapling_data.rs

1use std::io::{self};
2
3use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
4use sapling_crypto::{Diversifier, Rseed, value::NoteValue, zip32::ExtendedFullViewingKey};
5use zcash_encoding::{Optional, Vector};
6use zcash_primitives::{
7    memo::{Memo, MemoBytes},
8    merkle_tree::{read_incremental_witness, write_incremental_witness},
9    transaction::TxId,
10};
11
12use super::transactions::WitnessCache;
13
14// Reading a note also needs the corresponding address to read from.
15fn read_rseed<R: ReadBytesExt>(mut reader: R) -> io::Result<Rseed> {
16    let note_type = reader.read_u8()?;
17
18    let mut r_bytes: [u8; 32] = [0; 32];
19    reader.read_exact(&mut r_bytes)?;
20
21    let r = match note_type {
22        1 => Rseed::BeforeZip212(jubjub::Fr::from_bytes(&r_bytes).unwrap()),
23        2 => Rseed::AfterZip212(r_bytes),
24        _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, "Bad note type")),
25    };
26
27    Ok(r)
28}
29
30fn write_rseed<W: WriteBytesExt>(mut writer: W, rseed: &Rseed) -> io::Result<()> {
31    let note_type = match rseed {
32        Rseed::BeforeZip212(_) => 1,
33        Rseed::AfterZip212(_) => 2,
34    };
35    writer.write_u8(note_type)?;
36
37    match rseed {
38        Rseed::BeforeZip212(fr) => writer.write_all(&fr.to_bytes()),
39        Rseed::AfterZip212(b) => writer.write_all(b),
40    }
41}
42
43#[derive(Clone, Debug)]
44pub struct SaplingNoteData {
45    // Technically, this should be recoverable from the account number,
46    // but we're going to refactor this in the future, so I'll write it again here.
47    pub extfvk: ExtendedFullViewingKey,
48
49    pub diversifier: Diversifier,
50    pub note: sapling_crypto::Note,
51
52    // Witnesses for the last 100 blocks. witnesses.last() is the latest witness
53    pub witnesses: WitnessCache,
54    pub nullifier: sapling_crypto::Nullifier,
55    pub spent: Option<(TxId, u32)>, // If this note was confirmed spent
56
57    // If this note was spent in a send, but has not yet been confirmed.
58    // Contains the txid and height at which it was broadcast
59    pub unconfirmed_spent: Option<(TxId, u32)>,
60    pub memo: Option<Memo>,
61    pub is_change: bool,
62
63    // If the spending key is available in the wallet (i.e., whether to keep witness up-to-date)
64    pub have_spending_key: bool,
65}
66
67impl SaplingNoteData {
68    fn serialized_version() -> u64 {
69        20
70    }
71
72    // Reading a note also needs the corresponding address to read from.
73    pub fn read<R: ReadBytesExt>(mut reader: R) -> io::Result<Self> {
74        let version = reader.read_u64::<LittleEndian>()?;
75
76        let _account = if version <= 5 {
77            reader.read_u64::<LittleEndian>()?
78        } else {
79            0
80        };
81
82        let extfvk = ExtendedFullViewingKey::read(&mut reader)?;
83
84        let mut diversifier_bytes = [0u8; 11];
85        reader.read_exact(&mut diversifier_bytes)?;
86        let diversifier = Diversifier(diversifier_bytes);
87
88        // To recover the note, read the value and r, and then use the payment address
89        // to recreate the note
90        let (value, rseed) = if version <= 3 {
91            let value = reader.read_u64::<LittleEndian>()?;
92
93            let mut r_bytes: [u8; 32] = [0; 32];
94            reader.read_exact(&mut r_bytes)?;
95
96            let r = jubjub::Fr::from_bytes(&r_bytes).unwrap();
97
98            (value, Rseed::BeforeZip212(r))
99        } else {
100            let value = reader.read_u64::<LittleEndian>()?;
101            let rseed = read_rseed(&mut reader)?;
102
103            (value, rseed)
104        };
105
106        let note = extfvk
107            .fvk
108            .vk
109            .to_payment_address(diversifier)
110            .unwrap()
111            .create_note(NoteValue::from_raw(value), rseed);
112
113        let witnesses_vec = Vector::read(&mut reader, |r| read_incremental_witness(r))?;
114        let top_height = if version < 20 {
115            0
116        } else {
117            reader.read_u64::<LittleEndian>()?
118        };
119        let witnesses = WitnessCache::new(witnesses_vec, top_height);
120
121        let mut nullifier = [0u8; 32];
122        reader.read_exact(&mut nullifier)?;
123        let nullifier = sapling_crypto::Nullifier(nullifier);
124
125        // Note that this is only the spent field, we ignore the unconfirmed_spent field.
126        // The reason is that unconfirmed spents are only in memory, and we need to get the actual value of spent
127        // from the blockchain anyway.
128        let spent = if version <= 5 {
129            let spent = Optional::read(&mut reader, |r| {
130                let mut txid_bytes = [0u8; 32];
131                r.read_exact(&mut txid_bytes)?;
132                Ok(TxId::from_bytes(txid_bytes))
133            })?;
134
135            let spent_at_height = if version >= 2 {
136                Optional::read(&mut reader, |r| r.read_i32::<LittleEndian>())?
137            } else {
138                None
139            };
140
141            if spent.is_some() && spent_at_height.is_some() {
142                Some((spent.unwrap(), spent_at_height.unwrap() as u32))
143            } else {
144                None
145            }
146        } else {
147            Optional::read(&mut reader, |r| {
148                let mut txid_bytes = [0u8; 32];
149                r.read_exact(&mut txid_bytes)?;
150                let height = r.read_u32::<LittleEndian>()?;
151                Ok((TxId::from_bytes(txid_bytes), height))
152            })?
153        };
154
155        let unconfirmed_spent = if version <= 4 {
156            None
157        } else {
158            Optional::read(&mut reader, |r| {
159                let mut txbytes = [0u8; 32];
160                r.read_exact(&mut txbytes)?;
161
162                let height = r.read_u32::<LittleEndian>()?;
163                Ok((TxId::from_bytes(txbytes), height))
164            })?
165        };
166
167        let memo = Optional::read(&mut reader, |r| {
168            let mut memo_bytes = [0u8; 512];
169            r.read_exact(&mut memo_bytes)?;
170
171            // Attempt to read memo, first as text, else as arbitrary 512 bytes
172            match MemoBytes::from_bytes(&memo_bytes) {
173                Ok(mb) => match Memo::try_from(mb.clone()) {
174                    Ok(m) => Ok(m),
175                    Err(_) => Ok(Memo::Future(mb)),
176                },
177                Err(e) => Err(io::Error::new(
178                    io::ErrorKind::InvalidInput,
179                    format!("Couldn't create memo: {}", e),
180                )),
181            }
182        })?;
183
184        let is_change: bool = reader.read_u8()? > 0;
185
186        let have_spending_key = if version <= 2 {
187            true // Will get populated in the lightwallet::read() method, for now assume true
188        } else {
189            reader.read_u8()? > 0
190        };
191
192        Ok(SaplingNoteData {
193            extfvk,
194            diversifier,
195            note,
196            witnesses,
197            nullifier,
198            spent,
199            unconfirmed_spent,
200            memo,
201            is_change,
202            have_spending_key,
203        })
204    }
205
206    pub fn write<W: WriteBytesExt>(&self, mut writer: W) -> io::Result<()> {
207        // Write a version number first, so we can later upgrade this if needed.
208        writer.write_u64::<LittleEndian>(Self::serialized_version())?;
209
210        self.extfvk.write(&mut writer)?;
211
212        writer.write_all(&self.diversifier.0)?;
213
214        // Writing the note means writing the note.value and note.r. The Note is recoverable
215        // from these 2 values and the Payment address.
216        writer.write_u64::<LittleEndian>(self.note.value().inner())?;
217
218        write_rseed(&mut writer, self.note.rseed())?;
219
220        Vector::write(&mut writer, &self.witnesses.witnesses, |wr, wi| {
221            write_incremental_witness(wi, wr)
222        })?;
223        writer.write_u64::<LittleEndian>(self.witnesses.top_height)?;
224
225        writer.write_all(&self.nullifier.0)?;
226
227        Optional::write(&mut writer, self.spent, |w, (txid, h)| {
228            w.write_all(txid.as_ref())?;
229            w.write_u32::<LittleEndian>(h)
230        })?;
231
232        Optional::write(&mut writer, self.unconfirmed_spent, |w, (txid, height)| {
233            w.write_all(txid.as_ref())?;
234            w.write_u32::<LittleEndian>(height)
235        })?;
236
237        Optional::write(&mut writer, self.memo.as_ref(), |w, m| {
238            w.write_all(m.encode().as_array())
239        })?;
240
241        writer.write_u8(if self.is_change { 1 } else { 0 })?;
242
243        writer.write_u8(if self.have_spending_key { 1 } else { 0 })?;
244
245        // Note that we don't write the unconfirmed_spent field, because if the wallet is restarted,
246        // we don't want to be beholden to any expired txns
247
248        Ok(())
249    }
250}