zakura-client-sqlite 0.1.0-rc0

An SQLite-based Zcash light client
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
//! Functions and types related to encoding and decoding wallet data for storage in the wallet
//! database.

use bitflags::bitflags;
use transparent::address::TransparentAddress::*;
use zcash_address::{
    ConversionError, TryFromAddress,
    unified::{Container, Receiver},
};
use zcash_client_backend::data_api::AccountSource;
use zcash_keys::{
    address::{Address, UnifiedAddress},
    keys::{ReceiverRequirement, ReceiverRequirements},
};
use zcash_protocol::{PoolType, ShieldedPool, consensus::NetworkType, memo::MemoBytes};
use zip32::DiversifierIndex;
#[cfg(feature = "transparent-inputs")]
use {
    super::transparent::SchedulingError,
    std::time::{Duration, SystemTime},
    transparent::keys::TransparentKeyScope,
    zcash_client_backend::data_api::TransparentKeyOrigin,
    zcash_keys::keys::AddressGenerationError,
};

use crate::error::SqliteClientError;

#[cfg(feature = "zcashd-compat")]
use zcash_keys::keys::zcashd;

/// The sentinel value representing an unset `zcashd_legacy_address_index` column.
pub(crate) const LEGACY_ADDRESS_INDEX_NULL: i64 = -1;

pub(crate) fn pool_code(pool_type: PoolType) -> i64 {
    // These constants are *incidentally* shared with the typecodes
    // for unified addresses, but this is exclusively an internal
    // implementation detail.
    match pool_type {
        PoolType::Transparent => 0i64,
        PoolType::Shielded(ShieldedPool::Sapling) => 2i64,
        PoolType::Shielded(ShieldedPool::Orchard) => 3i64,
        PoolType::Shielded(ShieldedPool::Ironwood) => 4i64,
    }
}

pub(crate) fn parse_pool_code(code: i64) -> Result<PoolType, SqliteClientError> {
    match code {
        0i64 => Ok(PoolType::Transparent),
        2i64 => Ok(PoolType::SAPLING),
        3i64 => Ok(PoolType::ORCHARD),
        4i64 => Ok(PoolType::IRONWOOD),
        _ => Err(SqliteClientError::CorruptedData(format!(
            "Invalid pool code: {code}"
        ))),
    }
}

pub(crate) fn account_kind_code(value: &AccountSource) -> u32 {
    match value {
        AccountSource::Derived { .. } => 0,
        AccountSource::Imported { .. } => 1,
    }
}

pub(crate) fn encode_diversifier_index_be(idx: DiversifierIndex) -> [u8; 11] {
    let mut di_be = *idx.as_bytes();
    di_be.reverse();
    di_be
}

pub(crate) fn decode_diversifier_index_be(
    di_be: Option<Vec<u8>>,
) -> Result<Option<DiversifierIndex>, SqliteClientError> {
    di_be
        .map(|di_be_bytes| {
            let mut di_be: [u8; 11] = di_be_bytes.try_into().map_err(|_| {
                SqliteClientError::CorruptedData(
                    "Diversifier index is not an 11-byte value".to_owned(),
                )
            })?;
            di_be.reverse();
            Ok(DiversifierIndex::from(di_be))
        })
        .transpose()
}

pub(crate) fn memo_repr(memo: Option<&MemoBytes>) -> Option<&[u8]> {
    memo.map(|m| {
        if m == &MemoBytes::empty() {
            // we store the empty memo as a single 0xf6 byte
            &[0xf6]
        } else {
            m.as_slice()
        }
    })
}

#[cfg(feature = "transparent-inputs")]
pub(crate) fn epoch_seconds(t: SystemTime) -> Result<i64, SchedulingError> {
    let integer_seconds_since_epoch =
        i64::try_from(t.duration_since(SystemTime::UNIX_EPOCH)?.as_secs())?;

    Ok(integer_seconds_since_epoch)
}

#[cfg(feature = "transparent-inputs")]
pub(crate) fn decode_epoch_seconds(i: i64) -> Result<SystemTime, SchedulingError> {
    Ok(SystemTime::UNIX_EPOCH + Duration::from_secs(u64::try_from(i)?))
}

/// An enumeration of the scopes of keys that are generated by the `zcash_client_sqlite`
/// implementation of the `WalletWrite` trait.
///
/// This extends the [`zip32::Scope`] type to include the custom scope used to generate keys for
/// ephemeral transparent addresses.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum KeyScope {
    /// A key scope corresponding to a [`zip32::Scope`].
    Zip32(zip32::Scope),
    /// An ephemeral transparent address, which is derived from an account's transparent
    /// [`AccountPubKey`] with the BIP 44 path `change` level index set to the value `2`.
    ///
    /// [`AccountPubKey`]: transparent::keys::AccountPubKey
    Ephemeral,
    /// A transparent address that is logically associated with an account (i.e. funds
    /// controlled by the correponding secret key contribute to that account's balance)
    /// but where the address is not associated with the account by any HD derivation relationship.
    /// This scope is used to represent the situation where a standalone spending key has been
    /// imported into a wallet and associated with an account for balance purposes.
    Foreign,
}

impl KeyScope {
    pub(crate) const EXTERNAL: KeyScope = KeyScope::Zip32(zip32::Scope::External);
    pub(crate) const INTERNAL: KeyScope = KeyScope::Zip32(zip32::Scope::Internal);

    pub(crate) fn encode(&self) -> i64 {
        match self {
            KeyScope::Zip32(zip32::Scope::External) => 0i64,
            KeyScope::Zip32(zip32::Scope::Internal) => 1i64,
            KeyScope::Ephemeral => 2i64,
            KeyScope::Foreign => -1i64,
        }
    }

    pub(crate) fn decode(code: i64) -> Result<Self, SqliteClientError> {
        match code {
            0i64 => Ok(KeyScope::EXTERNAL),
            1i64 => Ok(KeyScope::INTERNAL),
            2i64 => Ok(KeyScope::Ephemeral),
            -1i64 => Ok(KeyScope::Foreign),
            other => Err(SqliteClientError::CorruptedData(format!(
                "Invalid key scope code: {other}"
            ))),
        }
    }

    #[cfg(feature = "transparent-inputs")]
    pub(crate) fn as_transparent(&self) -> Option<TransparentKeyScope> {
        match self {
            KeyScope::Zip32(scope) => Some(TransparentKeyScope::from(*scope)),
            KeyScope::Ephemeral => Some(TransparentKeyScope::custom(2).expect("valid scope")),
            KeyScope::Foreign => None,
        }
    }

    #[cfg(feature = "transparent-inputs")]
    pub(crate) fn as_key_origin(&self) -> TransparentKeyOrigin {
        match self {
            KeyScope::Zip32(scope) => TransparentKeyOrigin::Derived {
                scope: TransparentKeyScope::from(*scope),
            },
            KeyScope::Ephemeral => TransparentKeyOrigin::Derived {
                scope: TransparentKeyScope::custom(2).expect("valid scope"),
            },
            KeyScope::Foreign => TransparentKeyOrigin::Imported,
        }
    }
}

impl From<zip32::Scope> for KeyScope {
    fn from(value: zip32::Scope) -> Self {
        KeyScope::Zip32(value)
    }
}

#[cfg(feature = "transparent-inputs")]
impl From<KeyScope> for Option<TransparentKeyScope> {
    fn from(value: KeyScope) -> Self {
        value.as_transparent()
    }
}

#[cfg(feature = "transparent-inputs")]
impl TryFrom<TransparentKeyScope> for KeyScope {
    type Error = AddressGenerationError;
    fn try_from(value: TransparentKeyScope) -> Result<Self, Self::Error> {
        match value {
            TransparentKeyScope::EXTERNAL => Ok(KeyScope::EXTERNAL),
            TransparentKeyScope::INTERNAL => Ok(KeyScope::INTERNAL),
            TransparentKeyScope::EPHEMERAL => Ok(KeyScope::Ephemeral),
            _ => Err(AddressGenerationError::UnsupportedTransparentKeyScope(
                value,
            )),
        }
    }
}

impl TryFrom<KeyScope> for zip32::Scope {
    type Error = ();

    fn try_from(value: KeyScope) -> Result<Self, Self::Error> {
        match value {
            KeyScope::Zip32(scope) => Ok(scope),
            KeyScope::Ephemeral | KeyScope::Foreign => Err(()),
        }
    }
}

bitflags! {
    /// A set of flags describing the type(s) of outputs that a Zcash address can receive.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub(crate) struct ReceiverFlags: i64 {
        /// The address did not contain any recognized receiver types.
        const UNKNOWN = 0b00000000;
        /// The associated address can receive transparent p2pkh outputs.
        const P2PKH = 0b00000001;
        /// The associated address can receive transparent p2sh outputs.
        const P2SH = 0b00000010;
        /// The associated address can receive Sapling outputs.
        const SAPLING = 0b00000100;
        /// The associated address can receive Orchard outputs.
        const ORCHARD = 0b00001000;
    }
}

impl ReceiverFlags {
    pub(crate) fn required(request: ReceiverRequirements) -> Self {
        let mut flags = ReceiverFlags::UNKNOWN;
        if matches!(request.orchard(), ReceiverRequirement::Require) {
            flags |= ReceiverFlags::ORCHARD;
        }
        if matches!(request.sapling(), ReceiverRequirement::Require) {
            flags |= ReceiverFlags::SAPLING;
        }
        if matches!(request.p2pkh(), ReceiverRequirement::Require) {
            flags |= ReceiverFlags::P2PKH;
        }
        flags
    }

    pub(crate) fn omitted(request: ReceiverRequirements) -> Self {
        let mut flags = ReceiverFlags::UNKNOWN;
        if matches!(request.orchard(), ReceiverRequirement::Omit) {
            flags |= ReceiverFlags::ORCHARD;
        }
        if matches!(request.sapling(), ReceiverRequirement::Omit) {
            flags |= ReceiverFlags::SAPLING;
        }
        if matches!(request.p2pkh(), ReceiverRequirement::Omit) {
            flags |= ReceiverFlags::P2PKH;
        }
        flags
    }
}

/// Computes the [`ReceiverFlags`] describing the types of outputs that the provided
/// [`UnifiedAddress`] can receive.
impl From<&UnifiedAddress> for ReceiverFlags {
    fn from(value: &UnifiedAddress) -> Self {
        let mut flags = ReceiverFlags::UNKNOWN;
        match value.transparent() {
            Some(PublicKeyHash(_)) => {
                flags |= ReceiverFlags::P2PKH;
            }
            Some(ScriptHash(_)) => {
                flags |= ReceiverFlags::P2SH;
            }
            _ => {}
        }
        if value.has_sapling() {
            flags |= ReceiverFlags::SAPLING;
        }
        if value.has_orchard() {
            flags |= ReceiverFlags::ORCHARD;
        }
        flags
    }
}

/// Computes the [`ReceiverFlags`] describing the types of outputs that the provided
/// [`Address`] can receive.
impl From<&Address> for ReceiverFlags {
    fn from(address: &Address) -> Self {
        match address {
            Address::Sapling(_) => ReceiverFlags::SAPLING,
            Address::Transparent(addr) => match addr {
                PublicKeyHash(_) => ReceiverFlags::P2PKH,
                ScriptHash(_) => ReceiverFlags::P2SH,
            },
            Address::Unified(ua) => ReceiverFlags::from(ua),
            Address::Tex(_) => ReceiverFlags::P2PKH,
        }
    }
}

impl TryFromAddress for ReceiverFlags {
    type Error = ();

    fn try_from_sapling(
        _net: NetworkType,
        _data: [u8; 43],
    ) -> Result<Self, ConversionError<Self::Error>> {
        Ok(ReceiverFlags::SAPLING)
    }

    fn try_from_unified(
        _net: NetworkType,
        data: zcash_address::unified::Address,
    ) -> Result<Self, ConversionError<Self::Error>> {
        let mut result = ReceiverFlags::UNKNOWN;
        for i in data.items() {
            match i {
                Receiver::Orchard(_) => result |= ReceiverFlags::ORCHARD,
                Receiver::Sapling(_) => result |= ReceiverFlags::SAPLING,
                Receiver::P2pkh(_) => result |= ReceiverFlags::P2PKH,
                Receiver::P2sh(_) => result |= ReceiverFlags::P2SH,
                Receiver::Unknown { .. } => {}
            }
        }

        Ok(result)
    }

    fn try_from_transparent_p2pkh(
        _net: NetworkType,
        _data: [u8; 20],
    ) -> Result<Self, ConversionError<Self::Error>> {
        Ok(ReceiverFlags::P2PKH)
    }

    fn try_from_transparent_p2sh(
        _net: NetworkType,
        _data: [u8; 20],
    ) -> Result<Self, ConversionError<Self::Error>> {
        Ok(ReceiverFlags::P2SH)
    }

    fn try_from_tex(
        _net: NetworkType,
        _data: [u8; 20],
    ) -> Result<Self, ConversionError<Self::Error>> {
        Ok(ReceiverFlags::P2PKH)
    }
}

#[cfg(feature = "zcashd-compat")]
pub(crate) fn decode_legacy_account_index(
    legacy_account_index: i64,
) -> Result<Option<zcashd::LegacyAddressIndex>, SqliteClientError> {
    match legacy_account_index {
        LEGACY_ADDRESS_INDEX_NULL => Ok(None),
        _ => u32::try_from(legacy_account_index)
            .map_err(|_| ())
            .and_then(zcashd::LegacyAddressIndex::try_from)
            .map(Some)
            .map_err(|_| {
                SqliteClientError::CorruptedData(
                    "Legacy zcashd address index is out of range.".to_string(),
                )
            }),
    }
}

#[cfg(feature = "zcashd-compat")]
pub(crate) fn encode_legacy_account_index(
    legacy_account_index: Option<zcashd::LegacyAddressIndex>,
) -> i64 {
    legacy_account_index
        .map(u32::from)
        .map_or(LEGACY_ADDRESS_INDEX_NULL, i64::from)
}

#[cfg(test)]
mod tests {
    use zcash_protocol::{PoolType, ShieldedPool};

    use super::{parse_pool_code, pool_code};

    #[test]
    fn pool_code_round_trips() {
        for pool in [
            PoolType::Transparent,
            PoolType::Shielded(ShieldedPool::Sapling),
            PoolType::Shielded(ShieldedPool::Orchard),
            PoolType::Shielded(ShieldedPool::Ironwood),
        ] {
            assert_eq!(parse_pool_code(pool_code(pool)).unwrap(), pool);
        }
    }

    #[test]
    fn ironwood_pool_code_is_distinct() {
        let codes = [
            pool_code(PoolType::Transparent),
            pool_code(PoolType::Shielded(ShieldedPool::Sapling)),
            pool_code(PoolType::Shielded(ShieldedPool::Orchard)),
            pool_code(PoolType::Shielded(ShieldedPool::Ironwood)),
        ];
        let unique: std::collections::BTreeSet<_> = codes.iter().collect();
        assert_eq!(unique.len(), codes.len(), "pool codes must be distinct");
    }
}