Skip to main content

zecwallet_parser/zwl/
orchard_data.rs

1use std::io::{self};
2
3use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
4use incrementalmerkletree::Position;
5use orchard_old::{
6    Address, keys::FullViewingKey, note::RandomSeed, tree::MerkleHashOrchard, value::NoteValue,
7};
8use zcash_encoding::Optional;
9use zcash_primitives::{
10    memo::{Memo, MemoBytes},
11    transaction::TxId,
12};
13
14pub const MERKLE_DEPTH: u8 = 32;
15
16pub const SER_V1: u8 = 1;
17
18/// A hashable node within a Merkle tree.
19#[allow(dead_code)]
20pub trait HashSer {
21    /// Parses a node from the given byte source.
22    fn read<R: ReadBytesExt>(reader: R) -> io::Result<Self>
23    where
24        Self: Sized;
25
26    /// Serializes this node.
27    fn write<W: WriteBytesExt>(&self, writer: W) -> io::Result<()>;
28}
29
30impl HashSer for MerkleHashOrchard {
31    fn read<R: ReadBytesExt>(mut reader: R) -> io::Result<Self>
32    where
33        Self: Sized,
34    {
35        let mut repr = [0u8; 32];
36        reader.read_exact(&mut repr)?;
37        <Option<_>>::from(Self::from_bytes(&repr)).ok_or_else(|| {
38            io::Error::new(
39                io::ErrorKind::InvalidInput,
40                "Non-canonical encoding of Pallas base field value.",
41            )
42        })
43    }
44
45    fn write<W: WriteBytesExt>(&self, mut writer: W) -> io::Result<()> {
46        writer.write_all(&self.to_bytes())
47    }
48}
49
50#[allow(dead_code)]
51#[derive(Clone, Debug)]
52pub struct OrchardNoteData {
53    pub(super) fvk: FullViewingKey,
54
55    pub note: orchard_old::Note,
56
57    // (Block number, tx_num, output_num)
58    pub created_at: (u64, usize, u32),
59    pub witness_position: Option<Position>,
60
61    // Info needed to recreate note
62    pub spent: Option<(TxId, u32)>, // If this note was confirmed spent
63
64    // If this note was spent in a send, but has not yet been confirmed.
65    // Contains the txid and height at which it was broadcast
66    pub unconfirmed_spent: Option<(TxId, u32)>,
67    pub memo: Option<Memo>,
68    pub is_change: bool,
69
70    // If the spending key is available in the wallet (i.e., whether to keep witness up-to-date)
71    pub have_spending_key: bool,
72}
73
74impl OrchardNoteData {
75    fn serialized_version() -> u64 {
76        22
77    }
78
79    // Reading a note also needs the corresponding address to read from.
80    pub fn read<R: ReadBytesExt>(mut reader: R) -> io::Result<Self> {
81        let version = reader.read_u64::<LittleEndian>()?;
82        assert!(version <= Self::serialized_version());
83
84        let fvk = FullViewingKey::read(&mut reader)?;
85
86        // Read the parts of the note
87        // Raw address bytes is 43
88        let mut address_bytes = [0u8; 43];
89        reader.read_exact(&mut address_bytes)?;
90        let note_address = Address::from_raw_address_bytes(&address_bytes).unwrap();
91        let note_value = reader.read_u64::<LittleEndian>()?;
92        let mut rho_bytes = [0u8; 32];
93        reader.read_exact(&mut rho_bytes)?;
94        let note_rho = orchard_old::note::Nullifier::from_bytes(&rho_bytes).unwrap();
95        let mut note_rseed_bytes = [0u8; 32];
96        reader.read_exact(&mut note_rseed_bytes)?;
97        let note_rseed = RandomSeed::from_bytes(note_rseed_bytes, &note_rho).unwrap();
98
99        let note = orchard_old::Note::from_parts(
100            note_address,
101            NoteValue::from_raw(note_value),
102            note_rho,
103            note_rseed,
104        )
105        .unwrap();
106
107        let witness_position = Optional::read(&mut reader, |r| {
108            let pos = r.read_u64::<LittleEndian>()?;
109            Ok(Position::from(pos as usize))
110        })?;
111
112        let spent = Optional::read(&mut reader, |r| {
113            let mut txid_bytes = [0u8; 32];
114            r.read_exact(&mut txid_bytes)?;
115            let height = r.read_u32::<LittleEndian>()?;
116            Ok((TxId::from_bytes(txid_bytes), height))
117        })?;
118
119        let unconfirmed_spent = Optional::read(&mut reader, |r| {
120            let mut txbytes = [0u8; 32];
121            r.read_exact(&mut txbytes)?;
122
123            let height = r.read_u32::<LittleEndian>()?;
124            Ok((TxId::from_bytes(txbytes), height))
125        })?;
126
127        let memo = Optional::read(&mut reader, |r| {
128            let mut memo_bytes = [0u8; 512];
129            r.read_exact(&mut memo_bytes)?;
130
131            // Attempt to read memo, first as text, else as arbitrary 512 bytes
132            match MemoBytes::from_bytes(&memo_bytes) {
133                Ok(mb) => match Memo::try_from(mb.clone()) {
134                    Ok(m) => Ok(m),
135                    Err(_) => Ok(Memo::Future(mb)),
136                },
137                Err(e) => Err(io::Error::new(
138                    io::ErrorKind::InvalidInput,
139                    format!("Couldn't create memo: {}", e),
140                )),
141            }
142        })?;
143
144        let is_change: bool = reader.read_u8()? > 0;
145
146        let have_spending_key = reader.read_u8()? > 0;
147
148        Ok(OrchardNoteData {
149            fvk,
150            note,
151            created_at: (0, 0, 0),
152            witness_position,
153            spent,
154            unconfirmed_spent,
155            memo,
156            is_change,
157            have_spending_key,
158        })
159    }
160
161    #[allow(dead_code)]
162    pub fn write<W: WriteBytesExt>(&self, mut writer: W) -> io::Result<()> {
163        // Write a version number first, so we can later upgrade this if needed.
164        writer.write_u64::<LittleEndian>(Self::serialized_version())?;
165
166        self.fvk.write(&mut writer)?;
167
168        // Write the components of the note
169        writer.write_all(&self.note.recipient().to_raw_address_bytes())?;
170        writer.write_u64::<LittleEndian>(self.note.value().inner())?;
171        writer.write_all(&self.note.rho().to_bytes())?;
172        writer.write_all(self.note.rseed().as_bytes())?;
173
174        // We don't write the created_at, because it should be temporary
175        Optional::write(&mut writer, self.witness_position, |w, p| {
176            w.write_u64::<LittleEndian>(p.into())
177        })?;
178
179        Optional::write(&mut writer, self.spent, |w, (txid, h)| {
180            w.write_all(txid.as_ref())?;
181            w.write_u32::<LittleEndian>(h)
182        })?;
183
184        Optional::write(&mut writer, self.unconfirmed_spent, |w, (txid, height)| {
185            w.write_all(txid.as_ref())?;
186            w.write_u32::<LittleEndian>(height)
187        })?;
188
189        Optional::write(&mut writer, self.memo.as_ref(), |w, m| {
190            w.write_all(m.encode().as_array())
191        })?;
192
193        writer.write_u8(if self.is_change { 1 } else { 0 })?;
194
195        writer.write_u8(if self.have_spending_key { 1 } else { 0 })?;
196
197        // Note that we don't write the unconfirmed_spent field, because if the wallet is restarted,
198        // we don't want to be beholden to any expired txns
199
200        Ok(())
201    }
202}