2019-03-08 18:16:00 -08:00
|
|
|
//! *An SQLite-based Zcash light client.*
|
|
|
|
//!
|
2021-03-25 21:22:45 -07:00
|
|
|
//! `zcash_client_sqlite` contains complete SQLite-based implementations of the [`WalletRead`],
|
|
|
|
//! [`WalletWrite`], and [`BlockSource`] traits from the [`zcash_client_backend`] crate. In
|
|
|
|
//! combination with [`zcash_client_backend`], it provides a full implementation of a SQLite-backed
|
|
|
|
//! client for the Zcash network.
|
2019-03-08 18:16:00 -08:00
|
|
|
//!
|
|
|
|
//! # Design
|
|
|
|
//!
|
|
|
|
//! The light client is built around two SQLite databases:
|
|
|
|
//!
|
|
|
|
//! - A cache database, used to inform the light client about new [`CompactBlock`]s. It is
|
|
|
|
//! read-only within all light client APIs *except* for [`init_cache_database`] which
|
|
|
|
//! can be used to initialize the database.
|
|
|
|
//!
|
|
|
|
//! - A data database, where the light client's state is stored. It is read-write within
|
|
|
|
//! the light client APIs, and **assumed to be read-only outside these APIs**. Callers
|
|
|
|
//! **MUST NOT** write to the database without using these APIs. Callers **MAY** read
|
|
|
|
//! the database directly in order to extract information for display to users.
|
|
|
|
//!
|
2024-01-03 12:14:41 -08:00
|
|
|
//! ## Feature flags
|
|
|
|
#![doc = document_features::document_features!()]
|
2019-04-08 04:24:49 -07:00
|
|
|
//!
|
2021-03-25 21:22:45 -07:00
|
|
|
//! [`WalletRead`]: zcash_client_backend::data_api::WalletRead
|
|
|
|
//! [`WalletWrite`]: zcash_client_backend::data_api::WalletWrite
|
2022-10-17 10:35:14 -07:00
|
|
|
//! [`BlockSource`]: zcash_client_backend::data_api::chain::BlockSource
|
2019-03-08 18:16:00 -08:00
|
|
|
//! [`CompactBlock`]: zcash_client_backend::proto::compact_formats::CompactBlock
|
2021-03-04 14:17:25 -08:00
|
|
|
//! [`init_cache_database`]: crate::chain::init::init_cache_database
|
2019-03-08 18:16:00 -08:00
|
|
|
|
2024-01-04 11:03:11 -08:00
|
|
|
#![cfg_attr(docsrs, feature(doc_cfg))]
|
|
|
|
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
2021-03-26 12:27:17 -07:00
|
|
|
// Catch documentation errors caused by code changes.
|
2022-07-29 14:56:44 -07:00
|
|
|
#![deny(rustdoc::broken_intra_doc_links)]
|
2021-03-26 12:27:17 -07:00
|
|
|
|
2023-07-25 06:57:10 -07:00
|
|
|
use maybe_rayon::{
|
|
|
|
prelude::{IndexedParallelIterator, ParallelIterator},
|
|
|
|
slice::ParallelSliceMut,
|
|
|
|
};
|
2023-06-09 10:02:00 -07:00
|
|
|
use rusqlite::{self, Connection};
|
2022-09-13 15:43:04 -07:00
|
|
|
use secrecy::{ExposeSecret, SecretVec};
|
2023-08-11 15:41:38 -07:00
|
|
|
use std::{
|
|
|
|
borrow::Borrow, collections::HashMap, convert::AsRef, fmt, num::NonZeroU32, ops::Range,
|
|
|
|
path::Path,
|
|
|
|
};
|
2019-03-08 18:16:00 -08:00
|
|
|
|
2023-04-03 12:53:43 -07:00
|
|
|
use incrementalmerkletree::Position;
|
2023-10-02 17:02:06 -07:00
|
|
|
use shardtree::{error::ShardTreeError, ShardTree};
|
2020-08-05 13:27:40 -07:00
|
|
|
use zcash_primitives::{
|
2020-08-05 18:14:45 -07:00
|
|
|
block::BlockHash,
|
2020-08-05 13:27:40 -07:00
|
|
|
consensus::{self, BlockHeight},
|
2023-04-24 15:00:43 -07:00
|
|
|
memo::{Memo, MemoBytes},
|
2022-11-09 07:13:34 -08:00
|
|
|
transaction::{
|
2023-10-02 17:02:06 -07:00
|
|
|
components::amount::{Amount, NonNegativeAmount},
|
2022-11-09 07:13:34 -08:00
|
|
|
Transaction, TxId,
|
|
|
|
},
|
2023-10-31 09:03:37 -07:00
|
|
|
zip32::{AccountId, DiversifierIndex, Scope},
|
2019-04-08 04:24:49 -07:00
|
|
|
};
|
|
|
|
|
2020-08-05 18:14:45 -07:00
|
|
|
use zcash_client_backend::{
|
2024-02-10 11:50:53 -08:00
|
|
|
address::UnifiedAddress,
|
2021-03-09 17:10:44 -08:00
|
|
|
data_api::{
|
2023-06-19 18:05:35 -07:00
|
|
|
self,
|
|
|
|
chain::{BlockSource, CommitmentTreeRoot},
|
2023-07-11 19:56:37 -07:00
|
|
|
scanning::{ScanPriority, ScanRange},
|
2023-12-04 13:45:22 -08:00
|
|
|
AccountBirthday, BlockMetadata, DecryptedTransaction, InputSource, NullifierQuery,
|
2024-02-14 13:44:30 -08:00
|
|
|
ScannedBlock, SentTransaction, WalletCommitmentTrees, WalletRead, WalletSummary,
|
|
|
|
WalletWrite, SAPLING_SHARD_HEIGHT,
|
2021-03-09 17:10:44 -08:00
|
|
|
},
|
2024-02-05 16:59:55 -08:00
|
|
|
keys::{
|
|
|
|
AddressGenerationError, UnifiedAddressRequest, UnifiedFullViewingKey, UnifiedSpendingKey,
|
|
|
|
},
|
2020-08-05 18:14:45 -07:00
|
|
|
proto::compact_formats::CompactBlock,
|
2023-12-04 13:45:22 -08:00
|
|
|
wallet::{Note, NoteId, ReceivedNote, Recipient, WalletTransparentOutput},
|
2024-01-09 09:50:17 -08:00
|
|
|
DecryptedOutput, ShieldedProtocol, TransferType,
|
2020-08-05 18:14:45 -07:00
|
|
|
};
|
|
|
|
|
2023-06-16 13:42:36 -07:00
|
|
|
use crate::{error::SqliteClientError, wallet::commitment_tree::SqliteShardStore};
|
2020-08-06 13:11:25 -07:00
|
|
|
|
2024-01-05 15:33:52 -08:00
|
|
|
#[cfg(feature = "orchard")]
|
|
|
|
use zcash_client_backend::data_api::ORCHARD_SHARD_HEIGHT;
|
|
|
|
|
2023-10-02 17:02:06 -07:00
|
|
|
#[cfg(feature = "transparent-inputs")]
|
2024-02-14 13:44:30 -08:00
|
|
|
use {
|
|
|
|
zcash_client_backend::wallet::TransparentAddressMetadata,
|
|
|
|
zcash_primitives::{legacy::TransparentAddress, transaction::components::OutPoint},
|
|
|
|
};
|
2023-10-02 17:02:06 -07:00
|
|
|
|
2022-07-28 16:21:04 -07:00
|
|
|
#[cfg(feature = "unstable")]
|
|
|
|
use {
|
|
|
|
crate::chain::{fsblockdb_with_blocks, BlockMeta},
|
|
|
|
std::path::PathBuf,
|
2023-08-03 10:19:40 -07:00
|
|
|
std::{fs, io},
|
2022-07-28 16:21:04 -07:00
|
|
|
};
|
|
|
|
|
2019-05-02 03:27:43 -07:00
|
|
|
pub mod chain;
|
2019-03-08 18:16:00 -08:00
|
|
|
pub mod error;
|
2023-07-06 07:37:28 -07:00
|
|
|
|
2020-08-25 14:20:12 -07:00
|
|
|
pub mod wallet;
|
2023-08-15 07:35:07 -07:00
|
|
|
use wallet::{
|
2023-10-02 17:02:06 -07:00
|
|
|
commitment_tree::{self, put_shard_roots},
|
2023-08-15 07:35:07 -07:00
|
|
|
SubtreeScanProgress,
|
|
|
|
};
|
2019-03-08 18:16:00 -08:00
|
|
|
|
2023-08-03 10:28:09 -07:00
|
|
|
#[cfg(test)]
|
|
|
|
mod testing;
|
|
|
|
|
2021-10-01 10:58:23 -07:00
|
|
|
/// The maximum number of blocks the wallet is allowed to rewind. This is
|
|
|
|
/// consistent with the bound in zcashd, and allows block data deeper than
|
|
|
|
/// this delta from the chain tip to be pruned.
|
2023-07-03 16:06:43 -07:00
|
|
|
pub(crate) const PRUNING_DEPTH: u32 = 100;
|
2021-04-13 10:02:35 -07:00
|
|
|
|
2023-07-19 09:02:28 -07:00
|
|
|
/// The number of blocks to verify ahead when the chain tip is updated.
|
|
|
|
pub(crate) const VERIFY_LOOKAHEAD: u32 = 10;
|
2023-07-06 07:37:28 -07:00
|
|
|
|
2023-07-01 17:16:23 -07:00
|
|
|
pub(crate) const SAPLING_TABLES_PREFIX: &str = "sapling";
|
2023-06-29 15:26:22 -07:00
|
|
|
|
2024-02-07 12:51:48 -08:00
|
|
|
#[cfg(not(feature = "transparent-inputs"))]
|
|
|
|
pub(crate) const UA_TRANSPARENT: bool = false;
|
|
|
|
#[cfg(feature = "transparent-inputs")]
|
|
|
|
pub(crate) const UA_TRANSPARENT: bool = true;
|
|
|
|
|
|
|
|
pub(crate) const DEFAULT_UA_REQUEST: UnifiedAddressRequest =
|
|
|
|
UnifiedAddressRequest::unsafe_new(false, true, UA_TRANSPARENT);
|
2024-01-26 14:01:05 -08:00
|
|
|
|
2023-08-02 12:45:49 -07:00
|
|
|
/// A newtype wrapper for received note identifiers.
|
2022-10-17 10:35:14 -07:00
|
|
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
2023-08-02 12:45:49 -07:00
|
|
|
pub struct ReceivedNoteId(pub(crate) i64);
|
2020-08-18 12:48:59 -07:00
|
|
|
|
2023-08-07 11:24:05 -07:00
|
|
|
impl fmt::Display for ReceivedNoteId {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
match self {
|
|
|
|
ReceivedNoteId(id) => write!(f, "Received Note {}", id),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-22 06:10:13 -08:00
|
|
|
/// A newtype wrapper for sqlite primary key values for the utxos
|
|
|
|
/// table.
|
2022-10-01 11:58:01 -07:00
|
|
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
2021-02-12 13:08:31 -08:00
|
|
|
pub struct UtxoId(pub i64);
|
2020-12-22 06:10:13 -08:00
|
|
|
|
2021-03-25 21:22:45 -07:00
|
|
|
/// A wrapper for the SQLite connection to the wallet database.
|
2023-06-09 10:02:00 -07:00
|
|
|
pub struct WalletDb<C, P> {
|
|
|
|
conn: C,
|
2021-01-12 17:24:18 -08:00
|
|
|
params: P,
|
|
|
|
}
|
2020-08-05 18:14:45 -07:00
|
|
|
|
2023-06-09 10:02:00 -07:00
|
|
|
/// A wrapper for a SQLite transaction affecting the wallet database.
|
2023-06-13 10:20:18 -07:00
|
|
|
pub struct SqlTransaction<'conn>(pub(crate) &'conn rusqlite::Transaction<'conn>);
|
2023-06-09 10:02:00 -07:00
|
|
|
|
2023-06-12 11:17:20 -07:00
|
|
|
impl Borrow<rusqlite::Connection> for SqlTransaction<'_> {
|
2023-06-09 10:02:00 -07:00
|
|
|
fn borrow(&self) -> &rusqlite::Connection {
|
2023-06-13 10:20:18 -07:00
|
|
|
self.0
|
2023-06-09 10:02:00 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<P: consensus::Parameters + Clone> WalletDb<Connection, P> {
|
2021-01-11 17:13:40 -08:00
|
|
|
/// Construct a connection to the wallet database stored at the specified path.
|
2021-01-12 17:24:18 -08:00
|
|
|
pub fn for_path<F: AsRef<Path>>(path: F, params: P) -> Result<Self, rusqlite::Error> {
|
2022-11-09 07:13:34 -08:00
|
|
|
Connection::open(path).and_then(move |conn| {
|
|
|
|
rusqlite::vtab::array::load_module(&conn)?;
|
|
|
|
Ok(WalletDb { conn, params })
|
|
|
|
})
|
2020-08-05 18:14:45 -07:00
|
|
|
}
|
2021-01-08 11:49:10 -08:00
|
|
|
|
2023-04-03 12:53:43 -07:00
|
|
|
pub fn transactionally<F, A, E: From<rusqlite::Error>>(&mut self, f: F) -> Result<A, E>
|
2023-06-09 10:02:00 -07:00
|
|
|
where
|
2023-04-03 12:53:43 -07:00
|
|
|
F: FnOnce(&mut WalletDb<SqlTransaction<'_>, P>) -> Result<A, E>,
|
2023-06-09 10:02:00 -07:00
|
|
|
{
|
2023-06-13 10:20:18 -07:00
|
|
|
let tx = self.conn.transaction()?;
|
2023-04-03 12:53:43 -07:00
|
|
|
let mut wdb = WalletDb {
|
2023-06-13 10:20:18 -07:00
|
|
|
conn: SqlTransaction(&tx),
|
2023-06-09 10:02:00 -07:00
|
|
|
params: self.params.clone(),
|
|
|
|
};
|
2023-04-03 12:53:43 -07:00
|
|
|
let result = f(&mut wdb)?;
|
2023-06-13 10:20:18 -07:00
|
|
|
tx.commit()?;
|
2023-06-09 10:02:00 -07:00
|
|
|
Ok(result)
|
2021-01-08 11:49:10 -08:00
|
|
|
}
|
2020-08-05 18:14:45 -07:00
|
|
|
}
|
|
|
|
|
2023-12-04 13:45:22 -08:00
|
|
|
impl<C: Borrow<rusqlite::Connection>, P: consensus::Parameters> InputSource for WalletDb<C, P> {
|
2021-01-13 14:20:11 -08:00
|
|
|
type Error = SqliteClientError;
|
2023-08-02 12:45:49 -07:00
|
|
|
type NoteRef = ReceivedNoteId;
|
2024-02-27 19:02:08 -08:00
|
|
|
type AccountId = AccountId;
|
2020-08-05 18:14:45 -07:00
|
|
|
|
2023-12-04 13:45:22 -08:00
|
|
|
fn get_spendable_note(
|
2023-10-12 12:48:20 -07:00
|
|
|
&self,
|
|
|
|
txid: &TxId,
|
2024-02-21 16:32:15 -08:00
|
|
|
protocol: ShieldedProtocol,
|
2023-10-12 12:48:20 -07:00
|
|
|
index: u32,
|
2023-12-04 13:45:22 -08:00
|
|
|
) -> Result<Option<ReceivedNote<Self::NoteRef, Note>>, Self::Error> {
|
2024-02-21 16:32:15 -08:00
|
|
|
match protocol {
|
|
|
|
ShieldedProtocol::Sapling => wallet::sapling::get_spendable_sapling_note(
|
|
|
|
self.conn.borrow(),
|
|
|
|
&self.params,
|
|
|
|
txid,
|
|
|
|
index,
|
|
|
|
),
|
|
|
|
ShieldedProtocol::Orchard => Ok(None),
|
|
|
|
}
|
2023-10-12 12:48:20 -07:00
|
|
|
}
|
|
|
|
|
2023-12-04 13:45:22 -08:00
|
|
|
fn select_spendable_notes(
|
2023-10-02 17:02:06 -07:00
|
|
|
&self,
|
|
|
|
account: AccountId,
|
|
|
|
target_value: Amount,
|
2023-12-04 13:45:22 -08:00
|
|
|
_sources: &[ShieldedProtocol],
|
2023-10-02 17:02:06 -07:00
|
|
|
anchor_height: BlockHeight,
|
|
|
|
exclude: &[Self::NoteRef],
|
2023-12-04 13:45:22 -08:00
|
|
|
) -> Result<Vec<ReceivedNote<Self::NoteRef, Note>>, Self::Error> {
|
2023-10-02 17:02:06 -07:00
|
|
|
wallet::sapling::select_spendable_sapling_notes(
|
|
|
|
self.conn.borrow(),
|
2023-11-28 09:58:51 -08:00
|
|
|
&self.params,
|
2023-10-02 17:02:06 -07:00
|
|
|
account,
|
|
|
|
target_value,
|
|
|
|
anchor_height,
|
|
|
|
exclude,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2023-12-04 13:45:22 -08:00
|
|
|
#[cfg(feature = "transparent-inputs")]
|
2023-10-12 12:48:20 -07:00
|
|
|
fn get_unspent_transparent_output(
|
|
|
|
&self,
|
2023-11-14 09:44:21 -08:00
|
|
|
outpoint: &OutPoint,
|
2023-10-12 12:48:20 -07:00
|
|
|
) -> Result<Option<WalletTransparentOutput>, Self::Error> {
|
2023-11-14 09:44:21 -08:00
|
|
|
wallet::get_unspent_transparent_output(self.conn.borrow(), outpoint)
|
2023-10-12 12:48:20 -07:00
|
|
|
}
|
|
|
|
|
2023-12-04 13:45:22 -08:00
|
|
|
#[cfg(feature = "transparent-inputs")]
|
2023-10-02 17:02:06 -07:00
|
|
|
fn get_unspent_transparent_outputs(
|
|
|
|
&self,
|
|
|
|
address: &TransparentAddress,
|
|
|
|
max_height: BlockHeight,
|
|
|
|
exclude: &[OutPoint],
|
|
|
|
) -> Result<Vec<WalletTransparentOutput>, Self::Error> {
|
|
|
|
wallet::get_unspent_transparent_outputs(
|
|
|
|
self.conn.borrow(),
|
|
|
|
&self.params,
|
|
|
|
address,
|
|
|
|
max_height,
|
|
|
|
exclude,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<C: Borrow<rusqlite::Connection>, P: consensus::Parameters> WalletRead for WalletDb<C, P> {
|
|
|
|
type Error = SqliteClientError;
|
2024-02-27 19:02:08 -08:00
|
|
|
type AccountId = AccountId;
|
2023-10-02 17:02:06 -07:00
|
|
|
|
2024-03-01 14:35:43 -08:00
|
|
|
fn validate_seed(
|
|
|
|
&self,
|
|
|
|
account_id: Self::AccountId,
|
|
|
|
seed: &SecretVec<u8>,
|
|
|
|
) -> Result<bool, Self::Error> {
|
|
|
|
self.get_unified_full_viewing_keys().and_then(|keys| {
|
|
|
|
keys.get(&account_id).map_or(Ok(false), |ufvk| {
|
|
|
|
let usk = UnifiedSpendingKey::from_seed(
|
|
|
|
&self.params,
|
|
|
|
&seed.expose_secret()[..],
|
|
|
|
account_id,
|
|
|
|
)
|
|
|
|
.map_err(|_| SqliteClientError::KeyDerivationError(account_id))?;
|
|
|
|
|
|
|
|
// Keys are not comparable with `Eq`, but addresses are, so we derive what should
|
|
|
|
// be equivalent addresses for each key and use those to check for key equality.
|
|
|
|
UnifiedAddressRequest::all().map_or(Ok(false), |ua_request| {
|
2024-02-05 16:59:55 -08:00
|
|
|
match (
|
|
|
|
usk.to_unified_full_viewing_key()
|
|
|
|
.default_address(ua_request),
|
|
|
|
ufvk.default_address(ua_request),
|
|
|
|
) {
|
|
|
|
(Ok(a), Ok(b)) => Ok(a == b),
|
|
|
|
(Err(e), _) => Err(e.into()),
|
|
|
|
(_, Err(e)) => Err(e.into()),
|
|
|
|
}
|
2024-03-01 14:35:43 -08:00
|
|
|
})
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-08-11 15:41:38 -07:00
|
|
|
fn chain_height(&self) -> Result<Option<BlockHeight>, Self::Error> {
|
|
|
|
wallet::scan_queue_extrema(self.conn.borrow())
|
2023-09-27 09:31:36 -07:00
|
|
|
.map(|h| h.map(|range| *range.end()))
|
2023-08-11 15:41:38 -07:00
|
|
|
.map_err(SqliteClientError::from)
|
2020-08-05 18:14:45 -07:00
|
|
|
}
|
|
|
|
|
2023-07-01 17:16:23 -07:00
|
|
|
fn block_metadata(&self, height: BlockHeight) -> Result<Option<BlockMetadata>, Self::Error> {
|
2023-10-25 13:00:09 -07:00
|
|
|
wallet::block_metadata(self.conn.borrow(), &self.params, height)
|
2023-07-01 17:16:23 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
fn block_fully_scanned(&self) -> Result<Option<BlockMetadata>, Self::Error> {
|
2023-10-25 13:00:09 -07:00
|
|
|
wallet::block_fully_scanned(self.conn.borrow(), &self.params)
|
2023-04-03 12:53:43 -07:00
|
|
|
}
|
|
|
|
|
2023-09-06 07:47:51 -07:00
|
|
|
fn block_max_scanned(&self) -> Result<Option<BlockMetadata>, Self::Error> {
|
2023-10-25 13:00:09 -07:00
|
|
|
wallet::block_max_scanned(self.conn.borrow(), &self.params)
|
2023-09-06 07:47:51 -07:00
|
|
|
}
|
|
|
|
|
2023-07-06 07:37:28 -07:00
|
|
|
fn suggest_scan_ranges(&self) -> Result<Vec<ScanRange>, Self::Error> {
|
2023-07-11 19:56:37 -07:00
|
|
|
wallet::scanning::suggest_scan_ranges(self.conn.borrow(), ScanPriority::Historic)
|
2023-07-06 07:37:28 -07:00
|
|
|
.map_err(SqliteClientError::from)
|
2023-04-03 12:53:43 -07:00
|
|
|
}
|
|
|
|
|
2023-08-11 15:41:38 -07:00
|
|
|
fn get_target_and_anchor_heights(
|
|
|
|
&self,
|
|
|
|
min_confirmations: NonZeroU32,
|
|
|
|
) -> Result<Option<(BlockHeight, BlockHeight)>, Self::Error> {
|
|
|
|
wallet::get_target_and_anchor_heights(self.conn.borrow(), min_confirmations)
|
|
|
|
.map_err(SqliteClientError::from)
|
|
|
|
}
|
|
|
|
|
2023-04-26 15:27:56 -07:00
|
|
|
fn get_min_unspent_height(&self) -> Result<Option<BlockHeight>, Self::Error> {
|
2023-06-09 10:02:00 -07:00
|
|
|
wallet::get_min_unspent_height(self.conn.borrow()).map_err(SqliteClientError::from)
|
2023-04-26 15:27:56 -07:00
|
|
|
}
|
|
|
|
|
2020-08-05 18:14:45 -07:00
|
|
|
fn get_block_hash(&self, block_height: BlockHeight) -> Result<Option<BlockHash>, Self::Error> {
|
2023-06-09 10:02:00 -07:00
|
|
|
wallet::get_block_hash(self.conn.borrow(), block_height).map_err(SqliteClientError::from)
|
2020-08-05 18:14:45 -07:00
|
|
|
}
|
|
|
|
|
2023-08-11 15:41:38 -07:00
|
|
|
fn get_max_height_hash(&self) -> Result<Option<(BlockHeight, BlockHash)>, Self::Error> {
|
|
|
|
wallet::get_max_height_hash(self.conn.borrow()).map_err(SqliteClientError::from)
|
|
|
|
}
|
|
|
|
|
2020-08-25 14:02:44 -07:00
|
|
|
fn get_tx_height(&self, txid: TxId) -> Result<Option<BlockHeight>, Self::Error> {
|
2023-06-09 10:02:00 -07:00
|
|
|
wallet::get_tx_height(self.conn.borrow(), txid).map_err(SqliteClientError::from)
|
2020-08-25 14:02:44 -07:00
|
|
|
}
|
|
|
|
|
2023-08-16 10:15:10 -07:00
|
|
|
fn get_wallet_birthday(&self) -> Result<Option<BlockHeight>, Self::Error> {
|
|
|
|
wallet::wallet_birthday(self.conn.borrow()).map_err(SqliteClientError::from)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_account_birthday(&self, account: AccountId) -> Result<BlockHeight, Self::Error> {
|
|
|
|
wallet::account_birthday(self.conn.borrow(), account).map_err(SqliteClientError::from)
|
|
|
|
}
|
|
|
|
|
2023-07-01 17:16:23 -07:00
|
|
|
fn get_current_address(
|
|
|
|
&self,
|
|
|
|
account: AccountId,
|
|
|
|
) -> Result<Option<UnifiedAddress>, Self::Error> {
|
|
|
|
wallet::get_current_address(self.conn.borrow(), &self.params, account)
|
|
|
|
.map(|res| res.map(|(addr, _)| addr))
|
|
|
|
}
|
|
|
|
|
2022-06-13 17:57:20 -07:00
|
|
|
fn get_unified_full_viewing_keys(
|
2020-08-26 14:47:47 -07:00
|
|
|
&self,
|
2022-06-13 17:57:20 -07:00
|
|
|
) -> Result<HashMap<AccountId, UnifiedFullViewingKey>, Self::Error> {
|
2023-06-09 10:02:00 -07:00
|
|
|
wallet::get_unified_full_viewing_keys(self.conn.borrow(), &self.params)
|
2020-08-26 14:47:47 -07:00
|
|
|
}
|
|
|
|
|
2022-10-03 13:44:04 -07:00
|
|
|
fn get_account_for_ufvk(
|
|
|
|
&self,
|
|
|
|
ufvk: &UnifiedFullViewingKey,
|
|
|
|
) -> Result<Option<AccountId>, Self::Error> {
|
2023-06-09 10:02:00 -07:00
|
|
|
wallet::get_account_for_ufvk(self.conn.borrow(), &self.params, ufvk)
|
2022-10-03 13:44:04 -07:00
|
|
|
}
|
|
|
|
|
2023-08-15 07:35:07 -07:00
|
|
|
fn get_wallet_summary(
|
2020-08-26 14:47:47 -07:00
|
|
|
&self,
|
2023-08-15 07:35:07 -07:00
|
|
|
min_confirmations: u32,
|
2024-02-27 19:02:08 -08:00
|
|
|
) -> Result<Option<WalletSummary<Self::AccountId>>, Self::Error> {
|
2024-01-24 12:33:55 -08:00
|
|
|
// This will return a runtime error if we call `get_wallet_summary` from two
|
|
|
|
// threads at the same time, as transactions cannot nest.
|
2023-10-25 13:00:09 -07:00
|
|
|
wallet::get_wallet_summary(
|
2024-01-24 12:33:55 -08:00
|
|
|
&self.conn.borrow().unchecked_transaction()?,
|
2023-10-25 13:00:09 -07:00
|
|
|
&self.params,
|
|
|
|
min_confirmations,
|
|
|
|
&SubtreeScanProgress,
|
|
|
|
)
|
2020-08-05 16:01:22 -07:00
|
|
|
}
|
2020-08-06 09:23:15 -07:00
|
|
|
|
2023-08-02 12:45:49 -07:00
|
|
|
fn get_memo(&self, note_id: NoteId) -> Result<Option<Memo>, Self::Error> {
|
|
|
|
let sent_memo = wallet::get_sent_memo(self.conn.borrow(), note_id)?;
|
|
|
|
if sent_memo.is_some() {
|
|
|
|
Ok(sent_memo)
|
|
|
|
} else {
|
|
|
|
wallet::get_received_memo(self.conn.borrow(), note_id)
|
2021-01-19 11:27:48 -08:00
|
|
|
}
|
2020-08-17 10:46:44 -07:00
|
|
|
}
|
|
|
|
|
2023-08-02 12:45:49 -07:00
|
|
|
fn get_transaction(&self, txid: TxId) -> Result<Transaction, Self::Error> {
|
|
|
|
wallet::get_transaction(self.conn.borrow(), &self.params, txid).map(|(_, tx)| tx)
|
2023-07-01 17:16:23 -07:00
|
|
|
}
|
|
|
|
|
2023-04-03 12:53:43 -07:00
|
|
|
fn get_sapling_nullifiers(
|
|
|
|
&self,
|
2023-04-03 12:53:43 -07:00
|
|
|
query: NullifierQuery,
|
2023-04-03 12:53:43 -07:00
|
|
|
) -> Result<Vec<(AccountId, sapling::Nullifier)>, Self::Error> {
|
|
|
|
match query {
|
2023-06-09 10:02:00 -07:00
|
|
|
NullifierQuery::Unspent => wallet::sapling::get_sapling_nullifiers(self.conn.borrow()),
|
|
|
|
NullifierQuery::All => wallet::sapling::get_all_sapling_nullifiers(self.conn.borrow()),
|
2023-04-03 12:53:43 -07:00
|
|
|
}
|
2021-04-14 10:20:56 -07:00
|
|
|
}
|
|
|
|
|
2024-02-27 19:02:08 -08:00
|
|
|
#[cfg(feature = "orchard")]
|
|
|
|
fn get_orchard_nullifiers(
|
|
|
|
&self,
|
|
|
|
_query: NullifierQuery,
|
|
|
|
) -> Result<Vec<(AccountId, orchard::note::Nullifier)>, Self::Error> {
|
2024-02-26 18:50:54 -08:00
|
|
|
// FIXME! Orchard.
|
|
|
|
Ok(vec![])
|
2024-02-27 19:02:08 -08:00
|
|
|
}
|
|
|
|
|
2024-02-14 13:44:30 -08:00
|
|
|
#[cfg(feature = "transparent-inputs")]
|
2022-09-08 11:48:06 -07:00
|
|
|
fn get_transparent_receivers(
|
|
|
|
&self,
|
2024-02-27 19:02:08 -08:00
|
|
|
account: AccountId,
|
2024-02-13 17:34:33 -08:00
|
|
|
) -> Result<HashMap<TransparentAddress, Option<TransparentAddressMetadata>>, Self::Error> {
|
2024-02-27 19:02:08 -08:00
|
|
|
wallet::get_transparent_receivers(self.conn.borrow(), &self.params, account)
|
2022-09-08 11:48:06 -07:00
|
|
|
}
|
|
|
|
|
2024-02-14 13:44:30 -08:00
|
|
|
#[cfg(feature = "transparent-inputs")]
|
2022-10-25 11:04:02 -07:00
|
|
|
fn get_transparent_balances(
|
|
|
|
&self,
|
2024-02-27 19:02:08 -08:00
|
|
|
account: AccountId,
|
|
|
|
max_height: BlockHeight,
|
2022-10-25 11:04:02 -07:00
|
|
|
) -> Result<HashMap<TransparentAddress, Amount>, Self::Error> {
|
2024-02-27 19:02:08 -08:00
|
|
|
wallet::get_transparent_balances(self.conn.borrow(), &self.params, account, max_height)
|
2023-12-04 13:45:22 -08:00
|
|
|
}
|
2024-01-09 19:58:17 -08:00
|
|
|
|
|
|
|
fn get_account_ids(&self) -> Result<Vec<AccountId>, Self::Error> {
|
|
|
|
wallet::get_account_ids(self.conn.borrow())
|
|
|
|
}
|
2020-08-20 10:41:43 -07:00
|
|
|
}
|
|
|
|
|
2023-06-09 10:02:00 -07:00
|
|
|
impl<P: consensus::Parameters> WalletWrite for WalletDb<rusqlite::Connection, P> {
|
2022-10-13 19:58:43 -07:00
|
|
|
type UtxoRef = UtxoId;
|
|
|
|
|
2022-09-13 15:43:04 -07:00
|
|
|
fn create_account(
|
|
|
|
&mut self,
|
2022-09-14 11:20:39 -07:00
|
|
|
seed: &SecretVec<u8>,
|
2023-08-16 10:15:10 -07:00
|
|
|
birthday: AccountBirthday,
|
2022-09-13 15:43:04 -07:00
|
|
|
) -> Result<(AccountId, UnifiedSpendingKey), Self::Error> {
|
2023-06-09 10:02:00 -07:00
|
|
|
self.transactionally(|wdb| {
|
2023-06-13 10:20:18 -07:00
|
|
|
let account = wallet::get_max_account_id(wdb.conn.0)?
|
2023-12-05 04:38:06 -08:00
|
|
|
.map(|a| a.next().ok_or(SqliteClientError::AccountIdOutOfRange))
|
|
|
|
.transpose()?
|
2023-12-06 10:19:15 -08:00
|
|
|
.unwrap_or(AccountId::ZERO);
|
2022-09-14 12:38:00 -07:00
|
|
|
|
2023-06-09 10:02:00 -07:00
|
|
|
let usk = UnifiedSpendingKey::from_seed(&wdb.params, seed.expose_secret(), account)
|
|
|
|
.map_err(|_| SqliteClientError::KeyDerivationError(account))?;
|
2022-09-13 15:43:04 -07:00
|
|
|
let ufvk = usk.to_unified_full_viewing_key();
|
|
|
|
|
2023-08-16 10:15:10 -07:00
|
|
|
wallet::add_account(wdb.conn.0, &wdb.params, account, &ufvk, birthday)?;
|
2022-09-13 15:43:04 -07:00
|
|
|
|
|
|
|
Ok((account, usk))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-09-12 11:42:12 -07:00
|
|
|
fn get_next_available_address(
|
|
|
|
&mut self,
|
|
|
|
account: AccountId,
|
2023-04-28 10:40:16 -07:00
|
|
|
request: UnifiedAddressRequest,
|
2022-09-12 11:42:12 -07:00
|
|
|
) -> Result<Option<UnifiedAddress>, Self::Error> {
|
2023-06-09 10:02:00 -07:00
|
|
|
self.transactionally(
|
|
|
|
|wdb| match wdb.get_unified_full_viewing_keys()?.get(&account) {
|
|
|
|
Some(ufvk) => {
|
|
|
|
let search_from =
|
2023-06-13 10:20:18 -07:00
|
|
|
match wallet::get_current_address(wdb.conn.0, &wdb.params, account)? {
|
2023-06-09 10:02:00 -07:00
|
|
|
Some((_, mut last_diversifier_index)) => {
|
2024-02-05 16:59:55 -08:00
|
|
|
last_diversifier_index.increment().map_err(|_| {
|
|
|
|
AddressGenerationError::DiversifierSpaceExhausted
|
|
|
|
})?;
|
2023-06-09 10:02:00 -07:00
|
|
|
last_diversifier_index
|
|
|
|
}
|
|
|
|
None => DiversifierIndex::default(),
|
|
|
|
};
|
2022-09-12 11:42:12 -07:00
|
|
|
|
2024-02-05 16:59:55 -08:00
|
|
|
let (addr, diversifier_index) = ufvk.find_address(search_from, request)?;
|
2023-06-09 10:02:00 -07:00
|
|
|
|
|
|
|
wallet::insert_address(
|
2023-06-13 10:20:18 -07:00
|
|
|
wdb.conn.0,
|
2023-06-09 10:02:00 -07:00
|
|
|
&wdb.params,
|
|
|
|
account,
|
|
|
|
diversifier_index,
|
|
|
|
&addr,
|
|
|
|
)?;
|
|
|
|
|
|
|
|
Ok(Some(addr))
|
|
|
|
}
|
|
|
|
None => Ok(None),
|
|
|
|
},
|
|
|
|
)
|
2022-09-12 11:42:12 -07:00
|
|
|
}
|
|
|
|
|
2023-07-05 22:08:00 -07:00
|
|
|
#[tracing::instrument(skip_all, fields(height = blocks.first().map(|b| u32::from(b.height()))))]
|
2021-03-09 19:55:44 -08:00
|
|
|
#[allow(clippy::type_complexity)]
|
2023-07-05 22:08:00 -07:00
|
|
|
fn put_blocks(
|
2020-08-20 10:41:43 -07:00
|
|
|
&mut self,
|
2024-02-23 13:40:45 -08:00
|
|
|
blocks: Vec<ScannedBlock<Self::AccountId>>,
|
2023-08-02 12:45:49 -07:00
|
|
|
) -> Result<(), Self::Error> {
|
2023-06-09 10:02:00 -07:00
|
|
|
self.transactionally(|wdb| {
|
2023-07-06 07:37:28 -07:00
|
|
|
let start_positions = blocks.first().map(|block| {
|
|
|
|
(
|
|
|
|
block.height(),
|
|
|
|
Position::from(
|
2024-01-03 08:17:24 -08:00
|
|
|
u64::from(block.sapling().final_tree_size())
|
|
|
|
- u64::try_from(block.sapling().commitments().len()).unwrap(),
|
2023-07-06 07:37:28 -07:00
|
|
|
),
|
2023-07-05 22:08:00 -07:00
|
|
|
)
|
|
|
|
});
|
|
|
|
let mut sapling_commitments = vec![];
|
2023-07-12 09:12:14 -07:00
|
|
|
let mut last_scanned_height = None;
|
2023-07-06 07:37:28 -07:00
|
|
|
let mut note_positions = vec![];
|
2023-07-05 22:08:00 -07:00
|
|
|
for block in blocks.into_iter() {
|
2023-07-12 09:12:14 -07:00
|
|
|
if last_scanned_height
|
|
|
|
.iter()
|
|
|
|
.any(|prev| block.height() != *prev + 1)
|
|
|
|
{
|
2023-07-06 07:18:57 -07:00
|
|
|
return Err(SqliteClientError::NonSequentialBlocks);
|
|
|
|
}
|
|
|
|
|
2023-07-05 22:08:00 -07:00
|
|
|
// Insert the block into the database.
|
|
|
|
wallet::put_block(
|
|
|
|
wdb.conn.0,
|
|
|
|
block.height(),
|
|
|
|
block.block_hash(),
|
|
|
|
block.block_time(),
|
2024-01-03 08:17:24 -08:00
|
|
|
block.sapling().final_tree_size(),
|
|
|
|
block.sapling().commitments().len().try_into().unwrap(),
|
2023-07-05 22:08:00 -07:00
|
|
|
)?;
|
|
|
|
|
|
|
|
for tx in block.transactions() {
|
|
|
|
let tx_row = wallet::put_tx_meta(wdb.conn.0, tx, block.height())?;
|
|
|
|
|
|
|
|
// Mark notes as spent and remove them from the scanning cache
|
2024-02-23 13:40:45 -08:00
|
|
|
for spend in tx.sapling_spends() {
|
2023-07-05 22:08:00 -07:00
|
|
|
wallet::sapling::mark_sapling_note_spent(wdb.conn.0, tx_row, spend.nf())?;
|
|
|
|
}
|
|
|
|
|
2024-02-23 13:40:45 -08:00
|
|
|
for output in tx.sapling_outputs() {
|
2023-07-21 11:01:52 -07:00
|
|
|
// Check whether this note was spent in a later block range that
|
|
|
|
// we previously scanned.
|
2024-02-23 13:40:45 -08:00
|
|
|
let spent_in = output
|
|
|
|
.nf()
|
|
|
|
.map(|nf| {
|
|
|
|
wallet::query_nullifier_map::<_, Scope>(
|
|
|
|
wdb.conn.0,
|
|
|
|
ShieldedProtocol::Sapling,
|
|
|
|
nf,
|
|
|
|
)
|
|
|
|
})
|
|
|
|
.transpose()?
|
|
|
|
.flatten();
|
2023-07-21 11:01:52 -07:00
|
|
|
|
2023-08-02 12:45:49 -07:00
|
|
|
wallet::sapling::put_received_note(wdb.conn.0, output, tx_row, spent_in)?;
|
2023-07-05 22:08:00 -07:00
|
|
|
}
|
2021-03-09 17:10:44 -08:00
|
|
|
}
|
2020-08-20 10:41:43 -07:00
|
|
|
|
2023-07-21 11:01:52 -07:00
|
|
|
// Insert the new nullifiers from this block into the nullifier map.
|
|
|
|
wallet::insert_nullifier_map(
|
|
|
|
wdb.conn.0,
|
|
|
|
block.height(),
|
|
|
|
ShieldedProtocol::Sapling,
|
2024-01-03 08:17:24 -08:00
|
|
|
block.sapling().nullifier_map(),
|
2023-07-21 11:01:52 -07:00
|
|
|
)?;
|
|
|
|
|
2023-07-06 07:37:28 -07:00
|
|
|
note_positions.extend(block.transactions().iter().flat_map(|wtx| {
|
2024-02-23 13:40:45 -08:00
|
|
|
wtx.sapling_outputs()
|
2023-07-06 07:37:28 -07:00
|
|
|
.iter()
|
|
|
|
.map(|out| out.note_commitment_tree_position())
|
|
|
|
}));
|
|
|
|
|
2023-07-12 09:12:14 -07:00
|
|
|
last_scanned_height = Some(block.height());
|
2024-01-03 08:17:24 -08:00
|
|
|
let block_commitments = block.into_commitments();
|
|
|
|
sapling_commitments.extend(block_commitments.sapling.into_iter().map(Some));
|
2021-03-09 17:10:44 -08:00
|
|
|
}
|
|
|
|
|
2023-07-21 11:01:52 -07:00
|
|
|
// Prune the nullifier map of entries we no longer need.
|
|
|
|
if let Some(meta) = wdb.block_fully_scanned()? {
|
|
|
|
wallet::prune_nullifier_map(
|
|
|
|
wdb.conn.0,
|
|
|
|
meta.block_height().saturating_sub(PRUNING_DEPTH),
|
|
|
|
)?;
|
|
|
|
}
|
|
|
|
|
2023-07-12 09:12:14 -07:00
|
|
|
// We will have a start position and a last scanned height in all cases where
|
|
|
|
// `blocks` is non-empty.
|
|
|
|
if let Some(((start_height, start_position), last_scanned_height)) =
|
|
|
|
start_positions.zip(last_scanned_height)
|
2023-07-06 07:37:28 -07:00
|
|
|
{
|
2023-07-25 06:57:10 -07:00
|
|
|
// Create subtrees from the note commitments in parallel.
|
|
|
|
const CHUNK_SIZE: usize = 1024;
|
|
|
|
let subtrees = sapling_commitments
|
|
|
|
.par_chunks_mut(CHUNK_SIZE)
|
|
|
|
.enumerate()
|
|
|
|
.filter_map(|(i, chunk)| {
|
|
|
|
let start = start_position + (i * CHUNK_SIZE) as u64;
|
|
|
|
let end = start + chunk.len() as u64;
|
|
|
|
|
|
|
|
shardtree::LocatedTree::from_iter(
|
|
|
|
start..end,
|
|
|
|
SAPLING_SHARD_HEIGHT.into(),
|
|
|
|
chunk.iter_mut().map(|n| n.take().expect("always Some")),
|
|
|
|
)
|
|
|
|
})
|
|
|
|
.map(|res| (res.subtree, res.checkpoints))
|
|
|
|
.collect::<Vec<_>>();
|
|
|
|
|
2023-07-05 22:08:00 -07:00
|
|
|
// Update the Sapling note commitment tree with all newly read note commitments
|
2023-07-25 06:57:10 -07:00
|
|
|
let mut subtrees = subtrees.into_iter();
|
2023-10-02 17:02:06 -07:00
|
|
|
wdb.with_sapling_tree_mut::<_, _, Self::Error>(move |sapling_tree| {
|
2023-07-25 06:57:10 -07:00
|
|
|
for (tree, checkpoints) in &mut subtrees {
|
|
|
|
sapling_tree.insert_tree(tree, checkpoints)?;
|
|
|
|
}
|
|
|
|
|
2023-07-05 22:08:00 -07:00
|
|
|
Ok(())
|
|
|
|
})?;
|
|
|
|
|
|
|
|
// Update now-expired transactions that didn't get mined.
|
2023-07-12 09:12:14 -07:00
|
|
|
wallet::update_expired_notes(wdb.conn.0, last_scanned_height)?;
|
2023-07-06 07:37:28 -07:00
|
|
|
|
|
|
|
wallet::scanning::scan_complete(
|
|
|
|
wdb.conn.0,
|
|
|
|
&wdb.params,
|
|
|
|
Range {
|
|
|
|
start: start_height,
|
2023-07-12 09:12:14 -07:00
|
|
|
end: last_scanned_height + 1,
|
2023-07-06 07:37:28 -07:00
|
|
|
},
|
|
|
|
¬e_positions,
|
|
|
|
)?;
|
2023-07-05 22:08:00 -07:00
|
|
|
}
|
2021-03-09 17:18:24 -08:00
|
|
|
|
2023-08-02 12:45:49 -07:00
|
|
|
Ok(())
|
2021-03-09 17:10:44 -08:00
|
|
|
})
|
2020-08-25 14:02:44 -07:00
|
|
|
}
|
|
|
|
|
2023-07-06 07:37:28 -07:00
|
|
|
fn update_chain_tip(&mut self, tip_height: BlockHeight) -> Result<(), Self::Error> {
|
|
|
|
let tx = self.conn.transaction()?;
|
|
|
|
wallet::scanning::update_chain_tip(&tx, &self.params, tip_height)?;
|
|
|
|
tx.commit()?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2024-02-27 19:02:08 -08:00
|
|
|
fn store_decrypted_tx(
|
|
|
|
&mut self,
|
|
|
|
d_tx: DecryptedTransaction<AccountId>,
|
|
|
|
) -> Result<(), Self::Error> {
|
2023-06-09 10:02:00 -07:00
|
|
|
self.transactionally(|wdb| {
|
2023-06-30 09:42:48 -07:00
|
|
|
let tx_ref = wallet::put_tx_data(wdb.conn.0, d_tx.tx, None, None)?;
|
|
|
|
|
|
|
|
let mut spending_account_id: Option<AccountId> = None;
|
|
|
|
for output in d_tx.sapling_outputs {
|
|
|
|
match output.transfer_type {
|
|
|
|
TransferType::Outgoing | TransferType::WalletInternal => {
|
2024-01-09 09:50:17 -08:00
|
|
|
let value = output.note.value();
|
2023-06-30 09:42:48 -07:00
|
|
|
let recipient = if output.transfer_type == TransferType::Outgoing {
|
|
|
|
Recipient::Sapling(output.note.recipient())
|
|
|
|
} else {
|
2023-06-26 09:12:59 -07:00
|
|
|
Recipient::InternalAccount(
|
|
|
|
output.account,
|
2024-01-09 09:50:17 -08:00
|
|
|
Note::Sapling(output.note.clone()),
|
2023-06-26 09:12:59 -07:00
|
|
|
)
|
2023-06-30 09:42:48 -07:00
|
|
|
};
|
2023-04-24 15:00:43 -07:00
|
|
|
|
2023-06-30 09:42:48 -07:00
|
|
|
wallet::put_sent_output(
|
|
|
|
wdb.conn.0,
|
|
|
|
&wdb.params,
|
|
|
|
output.account,
|
|
|
|
tx_ref,
|
|
|
|
output.index,
|
|
|
|
&recipient,
|
2024-01-09 09:50:17 -08:00
|
|
|
NonNegativeAmount::from_u64(value.inner()).map_err(|_| {
|
2023-06-30 09:42:48 -07:00
|
|
|
SqliteClientError::CorruptedData(
|
|
|
|
"Note value is not a valid Zcash amount.".to_string(),
|
|
|
|
)
|
|
|
|
})?,
|
|
|
|
Some(&output.memo),
|
|
|
|
)?;
|
|
|
|
|
|
|
|
if matches!(recipient, Recipient::InternalAccount(_, _)) {
|
2023-07-21 11:01:52 -07:00
|
|
|
wallet::sapling::put_received_note(wdb.conn.0, output, tx_ref, None)?;
|
2023-06-30 09:42:48 -07:00
|
|
|
}
|
2022-09-26 09:59:50 -07:00
|
|
|
}
|
2023-06-30 09:42:48 -07:00
|
|
|
TransferType::Incoming => {
|
|
|
|
match spending_account_id {
|
|
|
|
Some(id) => {
|
|
|
|
if id != output.account {
|
|
|
|
panic!("Unable to determine a unique account identifier for z->t spend.");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
None => {
|
|
|
|
spending_account_id = Some(output.account);
|
2021-03-29 13:55:15 -07:00
|
|
|
}
|
|
|
|
}
|
2023-06-09 10:02:00 -07:00
|
|
|
|
2023-07-21 11:01:52 -07:00
|
|
|
wallet::sapling::put_received_note(wdb.conn.0, output, tx_ref, None)?;
|
2023-06-30 09:42:48 -07:00
|
|
|
}
|
2021-03-09 17:10:44 -08:00
|
|
|
}
|
|
|
|
}
|
2020-08-20 10:41:43 -07:00
|
|
|
|
2023-04-03 12:53:43 -07:00
|
|
|
// If any of the utxos spent in the transaction are ours, mark them as spent.
|
|
|
|
#[cfg(feature = "transparent-inputs")]
|
|
|
|
for txin in d_tx.tx.transparent_bundle().iter().flat_map(|b| b.vin.iter()) {
|
2023-06-13 10:20:18 -07:00
|
|
|
wallet::mark_transparent_utxo_spent(wdb.conn.0, tx_ref, &txin.prevout)?;
|
2023-04-03 12:53:43 -07:00
|
|
|
}
|
2022-10-13 19:20:46 -07:00
|
|
|
|
2023-04-03 12:53:43 -07:00
|
|
|
// If we have some transparent outputs:
|
|
|
|
if d_tx.tx.transparent_bundle().iter().any(|b| !b.vout.is_empty()) {
|
|
|
|
let nullifiers = wdb.get_sapling_nullifiers(NullifierQuery::All)?;
|
|
|
|
// If the transaction contains shielded spends from our wallet, we will store z->t
|
|
|
|
// transactions we observe in the same way they would be stored by
|
|
|
|
// create_spend_to_address.
|
|
|
|
if let Some((account_id, _)) = nullifiers.iter().find(
|
|
|
|
|(_, nf)|
|
|
|
|
d_tx.tx.sapling_bundle().iter().flat_map(|b| b.shielded_spends().iter())
|
|
|
|
.any(|input| nf == input.nullifier())
|
|
|
|
) {
|
|
|
|
for (output_index, txout) in d_tx.tx.transparent_bundle().iter().flat_map(|b| b.vout.iter()).enumerate() {
|
|
|
|
if let Some(address) = txout.recipient_address() {
|
|
|
|
wallet::put_sent_output(
|
2023-06-13 10:20:18 -07:00
|
|
|
wdb.conn.0,
|
2023-04-03 12:53:43 -07:00
|
|
|
&wdb.params,
|
|
|
|
*account_id,
|
|
|
|
tx_ref,
|
|
|
|
output_index,
|
|
|
|
&Recipient::Transparent(address),
|
|
|
|
txout.value,
|
|
|
|
None
|
|
|
|
)?;
|
|
|
|
}
|
2021-03-29 13:55:15 -07:00
|
|
|
}
|
2021-03-29 13:35:18 -07:00
|
|
|
}
|
|
|
|
}
|
2023-06-30 09:42:48 -07:00
|
|
|
|
2023-08-02 12:45:49 -07:00
|
|
|
Ok(())
|
2021-03-09 17:10:44 -08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2024-02-27 19:02:08 -08:00
|
|
|
fn store_sent_tx(&mut self, sent_tx: &SentTransaction<AccountId>) -> Result<(), Self::Error> {
|
2023-06-09 10:02:00 -07:00
|
|
|
self.transactionally(|wdb| {
|
2022-09-01 20:03:39 -07:00
|
|
|
let tx_ref = wallet::put_tx_data(
|
2023-06-13 10:20:18 -07:00
|
|
|
wdb.conn.0,
|
2022-09-01 20:03:39 -07:00
|
|
|
sent_tx.tx,
|
|
|
|
Some(sent_tx.fee_amount),
|
|
|
|
Some(sent_tx.created),
|
|
|
|
)?;
|
2021-03-09 17:10:44 -08:00
|
|
|
|
|
|
|
// Mark notes as spent.
|
|
|
|
//
|
|
|
|
// This locks the notes so they aren't selected again by a subsequent call to
|
|
|
|
// create_spend_to_address() before this transaction has been mined (at which point the notes
|
|
|
|
// get re-marked as spent).
|
|
|
|
//
|
|
|
|
// Assumes that create_spend_to_address() will never be called in parallel, which is a
|
|
|
|
// reasonable assumption for a light client such as a mobile phone.
|
2021-05-12 23:16:40 -07:00
|
|
|
if let Some(bundle) = sent_tx.tx.sapling_bundle() {
|
2022-12-10 14:27:09 -08:00
|
|
|
for spend in bundle.shielded_spends() {
|
2023-06-07 14:03:20 -07:00
|
|
|
wallet::sapling::mark_sapling_note_spent(
|
2023-06-13 10:20:18 -07:00
|
|
|
wdb.conn.0,
|
2023-06-07 14:03:20 -07:00
|
|
|
tx_ref,
|
|
|
|
spend.nullifier(),
|
|
|
|
)?;
|
2021-04-07 14:58:30 -07:00
|
|
|
}
|
2020-12-22 06:10:13 -08:00
|
|
|
}
|
|
|
|
|
2022-01-20 13:33:29 -08:00
|
|
|
#[cfg(feature = "transparent-inputs")]
|
2020-12-22 06:10:13 -08:00
|
|
|
for utxo_outpoint in &sent_tx.utxos_spent {
|
2023-06-13 10:20:18 -07:00
|
|
|
wallet::mark_transparent_utxo_spent(wdb.conn.0, tx_ref, utxo_outpoint)?;
|
2021-03-09 17:10:44 -08:00
|
|
|
}
|
|
|
|
|
2021-04-09 13:40:35 -07:00
|
|
|
for output in &sent_tx.outputs {
|
2023-06-07 14:41:52 -07:00
|
|
|
wallet::insert_sent_output(
|
2023-06-13 10:20:18 -07:00
|
|
|
wdb.conn.0,
|
2023-06-09 10:02:00 -07:00
|
|
|
&wdb.params,
|
2023-06-07 14:41:52 -07:00
|
|
|
tx_ref,
|
|
|
|
sent_tx.account,
|
|
|
|
output,
|
|
|
|
)?;
|
2023-04-24 15:00:43 -07:00
|
|
|
|
2024-01-09 09:50:17 -08:00
|
|
|
match output.recipient() {
|
|
|
|
Recipient::InternalAccount(account, Note::Sapling(note)) => {
|
|
|
|
wallet::sapling::put_received_note(
|
|
|
|
wdb.conn.0,
|
|
|
|
&DecryptedOutput {
|
|
|
|
index: output.output_index(),
|
|
|
|
note: note.clone(),
|
|
|
|
account: *account,
|
|
|
|
memo: output
|
|
|
|
.memo()
|
|
|
|
.map_or_else(MemoBytes::empty, |memo| memo.clone()),
|
|
|
|
transfer_type: TransferType::WalletInternal,
|
|
|
|
},
|
|
|
|
tx_ref,
|
|
|
|
None,
|
|
|
|
)?;
|
|
|
|
}
|
|
|
|
#[cfg(feature = "orchard")]
|
|
|
|
Recipient::InternalAccount(_account, Note::Orchard(_note)) => {
|
|
|
|
todo!();
|
|
|
|
}
|
|
|
|
_ => (),
|
2023-04-24 15:00:43 -07:00
|
|
|
}
|
2021-04-09 13:40:35 -07:00
|
|
|
}
|
2021-03-09 17:10:44 -08:00
|
|
|
|
2023-08-02 12:45:49 -07:00
|
|
|
Ok(())
|
2021-03-09 17:10:44 -08:00
|
|
|
})
|
2020-08-20 10:41:43 -07:00
|
|
|
}
|
|
|
|
|
2023-04-26 15:27:56 -07:00
|
|
|
fn truncate_to_height(&mut self, block_height: BlockHeight) -> Result<(), Self::Error> {
|
2023-06-09 10:02:00 -07:00
|
|
|
self.transactionally(|wdb| {
|
2023-06-13 10:20:18 -07:00
|
|
|
wallet::truncate_to_height(wdb.conn.0, &wdb.params, block_height)
|
2023-06-09 10:02:00 -07:00
|
|
|
})
|
2020-08-20 10:41:43 -07:00
|
|
|
}
|
2022-01-31 15:22:20 -08:00
|
|
|
|
|
|
|
fn put_received_transparent_utxo(
|
|
|
|
&mut self,
|
2022-10-13 19:58:43 -07:00
|
|
|
_output: &WalletTransparentOutput,
|
2022-01-31 15:22:20 -08:00
|
|
|
) -> Result<Self::UtxoRef, Self::Error> {
|
2022-10-13 19:58:43 -07:00
|
|
|
#[cfg(feature = "transparent-inputs")]
|
2023-06-09 10:02:00 -07:00
|
|
|
return wallet::put_received_transparent_utxo(&self.conn, &self.params, _output);
|
2022-10-13 19:58:43 -07:00
|
|
|
|
|
|
|
#[cfg(not(feature = "transparent-inputs"))]
|
2022-10-17 10:35:14 -07:00
|
|
|
panic!(
|
|
|
|
"The wallet must be compiled with the transparent-inputs feature to use this method."
|
|
|
|
);
|
2022-01-31 15:22:20 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-03 12:53:43 -07:00
|
|
|
impl<P: consensus::Parameters> WalletCommitmentTrees for WalletDb<rusqlite::Connection, P> {
|
2023-08-03 10:19:40 -07:00
|
|
|
type Error = commitment_tree::Error;
|
2023-06-15 12:50:07 -07:00
|
|
|
type SaplingShardStore<'a> =
|
|
|
|
SqliteShardStore<&'a rusqlite::Transaction<'a>, sapling::Node, SAPLING_SHARD_HEIGHT>;
|
2023-04-03 12:53:43 -07:00
|
|
|
|
|
|
|
fn with_sapling_tree_mut<F, A, E>(&mut self, mut callback: F) -> Result<A, E>
|
|
|
|
where
|
|
|
|
for<'a> F: FnMut(
|
|
|
|
&'a mut ShardTree<
|
|
|
|
Self::SaplingShardStore<'a>,
|
|
|
|
{ sapling::NOTE_COMMITMENT_TREE_DEPTH },
|
|
|
|
SAPLING_SHARD_HEIGHT,
|
|
|
|
>,
|
|
|
|
) -> Result<A, E>,
|
2023-08-03 10:19:40 -07:00
|
|
|
E: From<ShardTreeError<Self::Error>>,
|
2023-04-03 12:53:43 -07:00
|
|
|
{
|
2023-04-03 12:53:43 -07:00
|
|
|
let tx = self
|
|
|
|
.conn
|
|
|
|
.transaction()
|
2023-08-03 10:19:40 -07:00
|
|
|
.map_err(|e| ShardTreeError::Storage(commitment_tree::Error::Query(e)))?;
|
2023-06-29 15:26:22 -07:00
|
|
|
let shard_store = SqliteShardStore::from_connection(&tx, SAPLING_TABLES_PREFIX)
|
2023-08-03 10:19:40 -07:00
|
|
|
.map_err(|e| ShardTreeError::Storage(commitment_tree::Error::Query(e)))?;
|
2023-04-03 12:53:43 -07:00
|
|
|
let result = {
|
2023-07-03 16:06:43 -07:00
|
|
|
let mut shardtree = ShardTree::new(shard_store, PRUNING_DEPTH.try_into().unwrap());
|
2023-04-03 12:53:43 -07:00
|
|
|
callback(&mut shardtree)?
|
|
|
|
};
|
2023-06-19 18:05:35 -07:00
|
|
|
|
2023-04-03 12:53:43 -07:00
|
|
|
tx.commit()
|
2023-08-03 10:19:40 -07:00
|
|
|
.map_err(|e| ShardTreeError::Storage(commitment_tree::Error::Query(e)))?;
|
2023-04-03 12:53:43 -07:00
|
|
|
Ok(result)
|
|
|
|
}
|
2023-06-19 18:05:35 -07:00
|
|
|
|
|
|
|
fn put_sapling_subtree_roots(
|
|
|
|
&mut self,
|
|
|
|
start_index: u64,
|
|
|
|
roots: &[CommitmentTreeRoot<sapling::Node>],
|
|
|
|
) -> Result<(), ShardTreeError<Self::Error>> {
|
|
|
|
let tx = self
|
|
|
|
.conn
|
|
|
|
.transaction()
|
2023-08-03 10:19:40 -07:00
|
|
|
.map_err(|e| ShardTreeError::Storage(commitment_tree::Error::Query(e)))?;
|
2023-06-19 18:05:35 -07:00
|
|
|
put_shard_roots::<_, { sapling::NOTE_COMMITMENT_TREE_DEPTH }, SAPLING_SHARD_HEIGHT>(
|
|
|
|
&tx,
|
|
|
|
SAPLING_TABLES_PREFIX,
|
|
|
|
start_index,
|
|
|
|
roots,
|
|
|
|
)?;
|
|
|
|
tx.commit()
|
2023-08-03 10:19:40 -07:00
|
|
|
.map_err(|e| ShardTreeError::Storage(commitment_tree::Error::Query(e)))?;
|
2023-06-19 18:05:35 -07:00
|
|
|
Ok(())
|
|
|
|
}
|
2024-01-05 15:33:52 -08:00
|
|
|
|
|
|
|
#[cfg(feature = "orchard")]
|
|
|
|
type OrchardShardStore<'a> = SqliteShardStore<
|
|
|
|
&'a rusqlite::Transaction<'a>,
|
|
|
|
orchard::tree::MerkleHashOrchard,
|
|
|
|
ORCHARD_SHARD_HEIGHT,
|
|
|
|
>;
|
|
|
|
|
|
|
|
#[cfg(feature = "orchard")]
|
|
|
|
fn with_orchard_tree_mut<F, A, E>(&mut self, _callback: F) -> Result<A, E>
|
|
|
|
where
|
|
|
|
for<'a> F: FnMut(
|
|
|
|
&'a mut ShardTree<
|
|
|
|
Self::OrchardShardStore<'a>,
|
|
|
|
{ ORCHARD_SHARD_HEIGHT * 2 },
|
|
|
|
ORCHARD_SHARD_HEIGHT,
|
|
|
|
>,
|
|
|
|
) -> Result<A, E>,
|
|
|
|
E: From<ShardTreeError<Self::Error>>,
|
|
|
|
{
|
|
|
|
todo!()
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature = "orchard")]
|
|
|
|
fn put_orchard_subtree_roots(
|
|
|
|
&mut self,
|
|
|
|
_start_index: u64,
|
|
|
|
_roots: &[CommitmentTreeRoot<orchard::tree::MerkleHashOrchard>],
|
|
|
|
) -> Result<(), ShardTreeError<Self::Error>> {
|
|
|
|
todo!()
|
|
|
|
}
|
2023-04-03 12:53:43 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'conn, P: consensus::Parameters> WalletCommitmentTrees for WalletDb<SqlTransaction<'conn>, P> {
|
2023-08-03 10:19:40 -07:00
|
|
|
type Error = commitment_tree::Error;
|
2023-06-15 12:50:07 -07:00
|
|
|
type SaplingShardStore<'a> =
|
|
|
|
SqliteShardStore<&'a rusqlite::Transaction<'a>, sapling::Node, SAPLING_SHARD_HEIGHT>;
|
2023-04-03 12:53:43 -07:00
|
|
|
|
|
|
|
fn with_sapling_tree_mut<F, A, E>(&mut self, mut callback: F) -> Result<A, E>
|
|
|
|
where
|
|
|
|
for<'a> F: FnMut(
|
|
|
|
&'a mut ShardTree<
|
|
|
|
Self::SaplingShardStore<'a>,
|
|
|
|
{ sapling::NOTE_COMMITMENT_TREE_DEPTH },
|
|
|
|
SAPLING_SHARD_HEIGHT,
|
|
|
|
>,
|
|
|
|
) -> Result<A, E>,
|
2023-08-03 10:19:40 -07:00
|
|
|
E: From<ShardTreeError<commitment_tree::Error>>,
|
2023-04-03 12:53:43 -07:00
|
|
|
{
|
|
|
|
let mut shardtree = ShardTree::new(
|
2023-06-29 15:26:22 -07:00
|
|
|
SqliteShardStore::from_connection(self.conn.0, SAPLING_TABLES_PREFIX)
|
2023-08-03 10:19:40 -07:00
|
|
|
.map_err(|e| ShardTreeError::Storage(commitment_tree::Error::Query(e)))?,
|
2023-07-03 16:06:43 -07:00
|
|
|
PRUNING_DEPTH.try_into().unwrap(),
|
2023-04-03 12:53:43 -07:00
|
|
|
);
|
|
|
|
let result = callback(&mut shardtree)?;
|
|
|
|
|
|
|
|
Ok(result)
|
|
|
|
}
|
2023-06-19 18:05:35 -07:00
|
|
|
|
|
|
|
fn put_sapling_subtree_roots(
|
|
|
|
&mut self,
|
|
|
|
start_index: u64,
|
|
|
|
roots: &[CommitmentTreeRoot<sapling::Node>],
|
|
|
|
) -> Result<(), ShardTreeError<Self::Error>> {
|
|
|
|
put_shard_roots::<_, { sapling::NOTE_COMMITMENT_TREE_DEPTH }, SAPLING_SHARD_HEIGHT>(
|
|
|
|
self.conn.0,
|
|
|
|
SAPLING_TABLES_PREFIX,
|
|
|
|
start_index,
|
|
|
|
roots,
|
|
|
|
)
|
|
|
|
}
|
2024-01-05 15:33:52 -08:00
|
|
|
|
|
|
|
#[cfg(feature = "orchard")]
|
|
|
|
type OrchardShardStore<'a> = SqliteShardStore<
|
|
|
|
&'a rusqlite::Transaction<'a>,
|
|
|
|
orchard::tree::MerkleHashOrchard,
|
|
|
|
ORCHARD_SHARD_HEIGHT,
|
|
|
|
>;
|
|
|
|
|
|
|
|
#[cfg(feature = "orchard")]
|
|
|
|
fn with_orchard_tree_mut<F, A, E>(&mut self, _callback: F) -> Result<A, E>
|
|
|
|
where
|
|
|
|
for<'a> F: FnMut(
|
|
|
|
&'a mut ShardTree<
|
|
|
|
Self::OrchardShardStore<'a>,
|
|
|
|
{ ORCHARD_SHARD_HEIGHT * 2 },
|
|
|
|
ORCHARD_SHARD_HEIGHT,
|
|
|
|
>,
|
|
|
|
) -> Result<A, E>,
|
|
|
|
E: From<ShardTreeError<Self::Error>>,
|
|
|
|
{
|
|
|
|
todo!()
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature = "orchard")]
|
|
|
|
fn put_orchard_subtree_roots(
|
|
|
|
&mut self,
|
|
|
|
_start_index: u64,
|
|
|
|
_roots: &[CommitmentTreeRoot<orchard::tree::MerkleHashOrchard>],
|
|
|
|
) -> Result<(), ShardTreeError<Self::Error>> {
|
|
|
|
todo!()
|
|
|
|
}
|
2023-04-03 12:53:43 -07:00
|
|
|
}
|
|
|
|
|
2022-07-28 16:21:04 -07:00
|
|
|
/// A handle for the SQLite block source.
|
2021-03-26 22:17:54 -07:00
|
|
|
pub struct BlockDb(Connection);
|
2020-08-05 18:14:45 -07:00
|
|
|
|
2021-03-26 22:17:54 -07:00
|
|
|
impl BlockDb {
|
2021-03-25 22:47:59 -07:00
|
|
|
/// Opens a connection to the wallet database stored at the specified path.
|
2020-08-05 18:14:45 -07:00
|
|
|
pub fn for_path<P: AsRef<Path>>(path: P) -> Result<Self, rusqlite::Error> {
|
2021-03-26 22:17:54 -07:00
|
|
|
Connection::open(path).map(BlockDb)
|
2020-08-05 18:14:45 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-26 22:17:54 -07:00
|
|
|
impl BlockSource for BlockDb {
|
2021-01-13 14:20:11 -08:00
|
|
|
type Error = SqliteClientError;
|
2020-08-05 18:14:45 -07:00
|
|
|
|
2023-07-01 17:16:23 -07:00
|
|
|
fn with_blocks<F, DbErrT>(
|
2020-08-18 15:33:34 -07:00
|
|
|
&self,
|
2022-12-08 18:46:32 -08:00
|
|
|
from_height: Option<BlockHeight>,
|
2023-07-06 07:37:28 -07:00
|
|
|
limit: Option<usize>,
|
2020-08-18 15:33:34 -07:00
|
|
|
with_row: F,
|
2023-07-01 17:16:23 -07:00
|
|
|
) -> Result<(), data_api::chain::error::Error<DbErrT, Self::Error>>
|
2020-08-18 15:33:34 -07:00
|
|
|
where
|
2023-07-01 17:16:23 -07:00
|
|
|
F: FnMut(CompactBlock) -> Result<(), data_api::chain::error::Error<DbErrT, Self::Error>>,
|
2020-08-18 15:33:34 -07:00
|
|
|
{
|
2022-07-28 16:21:04 -07:00
|
|
|
chain::blockdb_with_blocks(self, from_height, limit, with_row)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A block source that reads block data from disk and block metadata from a SQLite database.
|
|
|
|
///
|
|
|
|
/// This block source expects each compact block to be stored on disk in the `blocks` subdirectory
|
|
|
|
/// of the `blockstore_root` path provided at the time of construction. Each block should be
|
|
|
|
/// written, as the serialized bytes of its protobuf representation, where the path for each block
|
|
|
|
/// has the pattern:
|
|
|
|
///
|
|
|
|
/// `<blockstore_root>/blocks/<block_height>-<block_hash>-compactblock`
|
|
|
|
///
|
|
|
|
/// where `<block_height>` is the decimal value of the height at which the block was mined, and
|
|
|
|
/// `<block_hash>` is the hexadecimal representation of the block hash, as produced by the
|
2022-10-17 10:35:14 -07:00
|
|
|
/// [`fmt::Display`] implementation for [`zcash_primitives::block::BlockHash`].
|
2022-07-28 16:21:04 -07:00
|
|
|
///
|
|
|
|
/// This block source is intended to be used with the following data flow:
|
|
|
|
/// * When the cache is being filled:
|
|
|
|
/// * The caller requests the current maximum height height at which cached data is available
|
|
|
|
/// using [`FsBlockDb::get_max_cached_height`]. If no cached data is available, the caller
|
|
|
|
/// can use the wallet's synced-to height for the following operations instead.
|
|
|
|
/// * (recommended for privacy) the caller should round the returned height down to some 100- /
|
|
|
|
/// 1000-block boundary.
|
|
|
|
/// * The caller uses the lightwalletd's `getblock` gRPC method to obtain a stream of blocks.
|
|
|
|
/// For each block returned, the caller writes the compact block to `blocks_dir` using the
|
|
|
|
/// path format specified above. It is fine to overwrite an existing block, since block hashes
|
|
|
|
/// are immutable and collision-resistant.
|
|
|
|
/// * Once a caller-determined number of blocks have been successfully written to disk, the
|
|
|
|
/// caller should invoke [`FsBlockDb::write_block_metadata`] with the metadata for each block
|
|
|
|
/// written to disk.
|
|
|
|
/// * The cache can then be scanned using the [`BlockSource`] implementation, providing the
|
|
|
|
/// wallet's synced-to-height as a starting point.
|
|
|
|
/// * When part of the cache is no longer needed:
|
|
|
|
/// * The caller determines some height `H` that is the earliest block data it needs to preserve.
|
|
|
|
/// This might be determined based on where the wallet is fully-synced to, or other heuristics.
|
|
|
|
/// * The caller searches the defined filesystem folder for all files beginning in `HEIGHT-*` where
|
|
|
|
/// `HEIGHT < H`, and deletes those files.
|
|
|
|
///
|
|
|
|
/// Note: This API is unstable, and may change in the future. In particular, the [`BlockSource`]
|
|
|
|
/// API and the above description currently assume that scanning is performed in linear block
|
|
|
|
/// order; this assumption is likely to be weakened and/or removed in a future update.
|
|
|
|
#[cfg(feature = "unstable")]
|
|
|
|
pub struct FsBlockDb {
|
|
|
|
conn: Connection,
|
|
|
|
blocks_dir: PathBuf,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Errors that can be generated by the filesystem/sqlite-backed
|
|
|
|
/// block source.
|
|
|
|
#[derive(Debug)]
|
|
|
|
#[cfg(feature = "unstable")]
|
|
|
|
pub enum FsBlockDbError {
|
2022-12-08 15:22:00 -08:00
|
|
|
Fs(io::Error),
|
|
|
|
Db(rusqlite::Error),
|
2022-10-17 10:35:14 -07:00
|
|
|
Protobuf(prost::DecodeError),
|
2022-12-09 01:47:20 -08:00
|
|
|
MissingBlockPath(PathBuf),
|
2022-07-28 16:21:04 -07:00
|
|
|
InvalidBlockstoreRoot(PathBuf),
|
|
|
|
InvalidBlockPath(PathBuf),
|
|
|
|
CorruptedData(String),
|
2023-08-09 10:31:23 -07:00
|
|
|
CacheMiss(BlockHeight),
|
2022-07-28 16:21:04 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature = "unstable")]
|
|
|
|
impl From<io::Error> for FsBlockDbError {
|
|
|
|
fn from(err: io::Error) -> Self {
|
2022-12-08 15:22:00 -08:00
|
|
|
FsBlockDbError::Fs(err)
|
2022-07-28 16:21:04 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature = "unstable")]
|
|
|
|
impl From<rusqlite::Error> for FsBlockDbError {
|
|
|
|
fn from(err: rusqlite::Error) -> Self {
|
2022-12-08 15:22:00 -08:00
|
|
|
FsBlockDbError::Db(err)
|
2022-07-28 16:21:04 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-17 10:35:14 -07:00
|
|
|
#[cfg(feature = "unstable")]
|
|
|
|
impl From<prost::DecodeError> for FsBlockDbError {
|
|
|
|
fn from(e: prost::DecodeError) -> Self {
|
|
|
|
FsBlockDbError::Protobuf(e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-28 16:21:04 -07:00
|
|
|
#[cfg(feature = "unstable")]
|
|
|
|
impl FsBlockDb {
|
|
|
|
/// Creates a filesystem-backed block store at the given path.
|
|
|
|
///
|
|
|
|
/// This will construct or open a SQLite database at the path
|
|
|
|
/// `<fsblockdb_root>/blockmeta.sqlite` and will ensure that a directory exists at
|
|
|
|
/// `<fsblockdb_root>/blocks` where this block store will expect to find serialized block
|
|
|
|
/// files as described for [`FsBlockDb`].
|
2023-01-26 13:33:50 -08:00
|
|
|
///
|
|
|
|
/// An application using this constructor should ensure that they call
|
2023-11-08 16:31:23 -08:00
|
|
|
/// [`crate::chain::init::init_blockmeta_db`] at application startup to ensure
|
2023-01-26 13:33:50 -08:00
|
|
|
/// that the resulting metadata database is properly initialized and has had all required
|
|
|
|
/// migrations applied before use.
|
2022-07-28 16:21:04 -07:00
|
|
|
pub fn for_path<P: AsRef<Path>>(fsblockdb_root: P) -> Result<Self, FsBlockDbError> {
|
2022-12-08 15:22:00 -08:00
|
|
|
let meta = fs::metadata(&fsblockdb_root).map_err(FsBlockDbError::Fs)?;
|
2022-07-28 16:21:04 -07:00
|
|
|
if meta.is_dir() {
|
|
|
|
let db_path = fsblockdb_root.as_ref().join("blockmeta.sqlite");
|
|
|
|
let blocks_dir = fsblockdb_root.as_ref().join("blocks");
|
|
|
|
fs::create_dir_all(&blocks_dir)?;
|
|
|
|
Ok(FsBlockDb {
|
2022-12-08 15:22:00 -08:00
|
|
|
conn: Connection::open(db_path).map_err(FsBlockDbError::Db)?,
|
2022-07-28 16:21:04 -07:00
|
|
|
blocks_dir,
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
Err(FsBlockDbError::InvalidBlockstoreRoot(
|
|
|
|
fsblockdb_root.as_ref().to_path_buf(),
|
|
|
|
))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the maximum height of blocks known to the block metadata database.
|
|
|
|
pub fn get_max_cached_height(&self) -> Result<Option<BlockHeight>, FsBlockDbError> {
|
|
|
|
Ok(chain::blockmetadb_get_max_cached_height(&self.conn)?)
|
|
|
|
}
|
|
|
|
|
2023-07-19 09:38:03 -07:00
|
|
|
/// Adds a set of block metadata entries to the metadata database, overwriting any
|
|
|
|
/// existing entries at the given block heights.
|
2022-07-28 16:21:04 -07:00
|
|
|
///
|
|
|
|
/// This will return an error if any block file corresponding to one of these metadata records
|
|
|
|
/// is absent from the blocks directory.
|
|
|
|
pub fn write_block_metadata(&self, block_meta: &[BlockMeta]) -> Result<(), FsBlockDbError> {
|
|
|
|
for m in block_meta {
|
|
|
|
let block_path = m.block_file_path(&self.blocks_dir);
|
2022-12-09 01:47:20 -08:00
|
|
|
match fs::metadata(&block_path) {
|
|
|
|
Err(e) => {
|
|
|
|
return Err(match e.kind() {
|
|
|
|
io::ErrorKind::NotFound => FsBlockDbError::MissingBlockPath(block_path),
|
|
|
|
_ => FsBlockDbError::Fs(e),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
Ok(meta) => {
|
|
|
|
if !meta.is_file() {
|
|
|
|
return Err(FsBlockDbError::InvalidBlockPath(block_path));
|
|
|
|
}
|
|
|
|
}
|
2022-07-28 16:21:04 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(chain::blockmetadb_insert(&self.conn, block_meta)?)
|
|
|
|
}
|
2023-01-24 15:30:04 -08:00
|
|
|
|
|
|
|
/// Returns the metadata for the block with the given height, if it exists in the
|
|
|
|
/// database.
|
|
|
|
pub fn find_block(&self, height: BlockHeight) -> Result<Option<BlockMeta>, FsBlockDbError> {
|
|
|
|
Ok(chain::blockmetadb_find_block(&self.conn, height)?)
|
|
|
|
}
|
|
|
|
|
2023-01-11 15:07:21 -08:00
|
|
|
/// Rewinds the BlockMeta Db to the `block_height` provided.
|
|
|
|
///
|
|
|
|
/// This doesn't delete any files referenced by the records
|
|
|
|
/// stored in BlockMeta.
|
|
|
|
///
|
|
|
|
/// If the requested height is greater than or equal to the height
|
|
|
|
/// of the last scanned block, or if the DB is empty, this function
|
|
|
|
/// does nothing.
|
2023-04-26 15:27:56 -07:00
|
|
|
pub fn truncate_to_height(&self, block_height: BlockHeight) -> Result<(), FsBlockDbError> {
|
|
|
|
Ok(chain::blockmetadb_truncate_to_height(
|
2023-01-11 15:07:21 -08:00
|
|
|
&self.conn,
|
|
|
|
block_height,
|
|
|
|
)?)
|
|
|
|
}
|
2022-07-28 16:21:04 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature = "unstable")]
|
|
|
|
impl BlockSource for FsBlockDb {
|
2022-10-17 10:35:14 -07:00
|
|
|
type Error = FsBlockDbError;
|
2022-07-28 16:21:04 -07:00
|
|
|
|
2023-07-01 17:16:23 -07:00
|
|
|
fn with_blocks<F, DbErrT>(
|
2022-07-28 16:21:04 -07:00
|
|
|
&self,
|
2022-12-08 18:46:32 -08:00
|
|
|
from_height: Option<BlockHeight>,
|
2023-07-06 07:37:28 -07:00
|
|
|
limit: Option<usize>,
|
2022-07-28 16:21:04 -07:00
|
|
|
with_row: F,
|
2023-07-01 17:16:23 -07:00
|
|
|
) -> Result<(), data_api::chain::error::Error<DbErrT, Self::Error>>
|
2022-07-28 16:21:04 -07:00
|
|
|
where
|
2023-07-01 17:16:23 -07:00
|
|
|
F: FnMut(CompactBlock) -> Result<(), data_api::chain::error::Error<DbErrT, Self::Error>>,
|
2022-07-28 16:21:04 -07:00
|
|
|
{
|
|
|
|
fsblockdb_with_blocks(self, from_height, limit, with_row)
|
2020-08-18 15:33:34 -07:00
|
|
|
}
|
2020-08-05 18:14:45 -07:00
|
|
|
}
|
2019-04-08 04:24:49 -07:00
|
|
|
|
2022-12-13 15:13:55 -08:00
|
|
|
#[cfg(feature = "unstable")]
|
|
|
|
impl std::fmt::Display for FsBlockDbError {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
|
|
|
match self {
|
|
|
|
FsBlockDbError::Fs(io_error) => {
|
|
|
|
write!(f, "Failed to access the file system: {}", io_error)
|
|
|
|
}
|
|
|
|
FsBlockDbError::Db(e) => {
|
|
|
|
write!(f, "There was a problem with the sqlite db: {}", e)
|
|
|
|
}
|
|
|
|
FsBlockDbError::Protobuf(e) => {
|
|
|
|
write!(f, "Failed to parse protobuf-encoded record: {}", e)
|
|
|
|
}
|
|
|
|
FsBlockDbError::MissingBlockPath(block_path) => {
|
|
|
|
write!(
|
|
|
|
f,
|
|
|
|
"CompactBlock file expected but not found at {}",
|
|
|
|
block_path.display(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
FsBlockDbError::InvalidBlockstoreRoot(fsblockdb_root) => {
|
|
|
|
write!(
|
|
|
|
f,
|
|
|
|
"The block storage root {} is not a directory",
|
|
|
|
fsblockdb_root.display(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
FsBlockDbError::InvalidBlockPath(block_path) => {
|
|
|
|
write!(
|
|
|
|
f,
|
|
|
|
"CompactBlock path {} is not a file",
|
|
|
|
block_path.display(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
FsBlockDbError::CorruptedData(e) => {
|
|
|
|
write!(
|
|
|
|
f,
|
|
|
|
"The block cache has corrupted data and this caused an error: {}",
|
|
|
|
e,
|
|
|
|
)
|
|
|
|
}
|
2023-08-09 10:31:23 -07:00
|
|
|
FsBlockDbError::CacheMiss(height) => {
|
|
|
|
write!(
|
|
|
|
f,
|
|
|
|
"Requested height {} does not exist in the block cache",
|
|
|
|
height
|
|
|
|
)
|
|
|
|
}
|
2022-12-13 15:13:55 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-17 10:35:14 -07:00
|
|
|
#[cfg(test)]
|
|
|
|
#[macro_use]
|
|
|
|
extern crate assert_matches;
|
|
|
|
|
2019-03-08 19:12:31 -08:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2024-03-01 14:35:43 -08:00
|
|
|
use secrecy::SecretVec;
|
2024-01-26 14:01:05 -08:00
|
|
|
use zcash_client_backend::data_api::{AccountBirthday, WalletRead, WalletWrite};
|
2020-08-05 13:27:40 -07:00
|
|
|
|
2024-03-01 14:35:43 -08:00
|
|
|
use crate::{testing::TestBuilder, DEFAULT_UA_REQUEST};
|
|
|
|
use zip32::AccountId;
|
2019-03-08 19:12:31 -08:00
|
|
|
|
2023-08-03 10:28:09 -07:00
|
|
|
#[cfg(feature = "unstable")]
|
2023-08-16 10:15:10 -07:00
|
|
|
use {
|
|
|
|
crate::testing::AddressType,
|
|
|
|
zcash_client_backend::keys::sapling,
|
2023-08-28 18:09:14 -07:00
|
|
|
zcash_primitives::{
|
|
|
|
consensus::Parameters, transaction::components::amount::NonNegativeAmount,
|
|
|
|
},
|
2023-08-16 10:15:10 -07:00
|
|
|
};
|
2023-01-25 07:29:22 -08:00
|
|
|
|
2024-03-01 14:35:43 -08:00
|
|
|
#[test]
|
|
|
|
fn validate_seed() {
|
|
|
|
let st = TestBuilder::new()
|
|
|
|
.with_test_account(AccountBirthday::from_sapling_activation)
|
|
|
|
.build();
|
|
|
|
|
|
|
|
assert!({
|
|
|
|
let account = st.test_account().unwrap().0;
|
|
|
|
st.wallet()
|
|
|
|
.validate_seed(account, st.test_seed().unwrap())
|
|
|
|
.unwrap()
|
|
|
|
});
|
|
|
|
|
|
|
|
// check that passing an invalid account results in a failure
|
|
|
|
assert!({
|
|
|
|
let account = AccountId::try_from(1u32).unwrap();
|
|
|
|
!st.wallet()
|
|
|
|
.validate_seed(account, st.test_seed().unwrap())
|
|
|
|
.unwrap()
|
|
|
|
});
|
|
|
|
|
|
|
|
// check that passing an invalid seed results in a failure
|
|
|
|
assert!({
|
|
|
|
let account = st.test_account().unwrap().0;
|
|
|
|
!st.wallet()
|
|
|
|
.validate_seed(account, &SecretVec::new(vec![1u8; 32]))
|
|
|
|
.unwrap()
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-09-12 11:42:12 -07:00
|
|
|
#[test]
|
|
|
|
pub(crate) fn get_next_available_address() {
|
2023-08-16 10:15:10 -07:00
|
|
|
let mut st = TestBuilder::new()
|
2023-08-16 10:15:10 -07:00
|
|
|
.with_test_account(AccountBirthday::from_sapling_activation)
|
2023-08-16 10:15:10 -07:00
|
|
|
.build();
|
2022-09-12 11:42:12 -07:00
|
|
|
|
2023-12-05 04:38:06 -08:00
|
|
|
let account = AccountId::ZERO;
|
2023-08-28 11:54:35 -07:00
|
|
|
let current_addr = st.wallet().get_current_address(account).unwrap();
|
2022-09-12 11:42:12 -07:00
|
|
|
assert!(current_addr.is_some());
|
|
|
|
|
2023-04-28 10:40:16 -07:00
|
|
|
// TODO: Add Orchard
|
|
|
|
let addr2 = st
|
|
|
|
.wallet_mut()
|
2024-01-26 14:01:05 -08:00
|
|
|
.get_next_available_address(account, DEFAULT_UA_REQUEST)
|
2023-04-28 10:40:16 -07:00
|
|
|
.unwrap();
|
2022-09-12 11:42:12 -07:00
|
|
|
assert!(addr2.is_some());
|
|
|
|
assert_ne!(current_addr, addr2);
|
|
|
|
|
2023-08-28 11:54:35 -07:00
|
|
|
let addr2_cur = st.wallet().get_current_address(account).unwrap();
|
2022-09-12 11:42:12 -07:00
|
|
|
assert_eq!(addr2, addr2_cur);
|
|
|
|
}
|
|
|
|
|
2022-09-08 11:48:06 -07:00
|
|
|
#[cfg(feature = "transparent-inputs")]
|
|
|
|
#[test]
|
|
|
|
fn transparent_receivers() {
|
2023-08-16 10:15:10 -07:00
|
|
|
// Add an account to the wallet.
|
2023-08-28 11:54:35 -07:00
|
|
|
let st = TestBuilder::new()
|
2023-08-28 09:31:02 -07:00
|
|
|
.with_block_cache()
|
2023-08-16 10:15:10 -07:00
|
|
|
.with_test_account(AccountBirthday::from_sapling_activation)
|
2023-08-28 09:31:02 -07:00
|
|
|
.build();
|
2022-09-08 11:48:06 -07:00
|
|
|
|
2023-08-16 10:15:10 -07:00
|
|
|
let (_, usk, _) = st.test_account().unwrap();
|
|
|
|
let ufvk = usk.to_unified_full_viewing_key();
|
|
|
|
let (taddr, _) = usk.default_transparent_address();
|
2022-09-08 11:48:06 -07:00
|
|
|
|
2023-12-05 04:38:06 -08:00
|
|
|
let receivers = st
|
|
|
|
.wallet()
|
|
|
|
.get_transparent_receivers(AccountId::ZERO)
|
|
|
|
.unwrap();
|
2022-09-08 11:48:06 -07:00
|
|
|
|
|
|
|
// The receiver for the default UA should be in the set.
|
2024-01-26 14:01:05 -08:00
|
|
|
assert!(receivers.contains_key(
|
|
|
|
ufvk.default_address(DEFAULT_UA_REQUEST)
|
2024-02-05 16:59:55 -08:00
|
|
|
.expect("A valid default address exists for the UFVK")
|
2024-01-26 14:01:05 -08:00
|
|
|
.0
|
|
|
|
.transparent()
|
|
|
|
.unwrap()
|
|
|
|
));
|
2022-09-08 11:48:06 -07:00
|
|
|
|
|
|
|
// The default t-addr should be in the set.
|
2022-10-25 09:54:12 -07:00
|
|
|
assert!(receivers.contains_key(&taddr));
|
2022-09-08 11:48:06 -07:00
|
|
|
}
|
|
|
|
|
2023-01-25 07:29:22 -08:00
|
|
|
#[cfg(feature = "unstable")]
|
|
|
|
#[test]
|
|
|
|
pub(crate) fn fsblockdb_api() {
|
2024-02-02 16:28:14 -08:00
|
|
|
use zcash_primitives::consensus::NetworkConstants;
|
|
|
|
|
2023-08-28 11:54:35 -07:00
|
|
|
let mut st = TestBuilder::new().with_fs_block_cache().build();
|
2023-01-25 07:29:22 -08:00
|
|
|
|
|
|
|
// The BlockMeta DB starts off empty.
|
2023-08-28 11:54:35 -07:00
|
|
|
assert_eq!(st.cache().get_max_cached_height().unwrap(), None);
|
2023-01-25 07:29:22 -08:00
|
|
|
|
|
|
|
// Generate some fake CompactBlocks.
|
|
|
|
let seed = [0u8; 32];
|
2023-12-05 04:38:06 -08:00
|
|
|
let account = AccountId::ZERO;
|
2024-02-02 16:28:14 -08:00
|
|
|
let extsk = sapling::spending_key(
|
|
|
|
&seed,
|
|
|
|
st.wallet().params.network_type().coin_type(),
|
|
|
|
account,
|
|
|
|
);
|
2023-01-25 07:29:22 -08:00
|
|
|
let dfvk = extsk.to_diversifiable_full_viewing_key();
|
2023-08-28 11:54:35 -07:00
|
|
|
let (h1, meta1, _) = st.generate_next_block(
|
2023-01-25 07:29:22 -08:00
|
|
|
&dfvk,
|
|
|
|
AddressType::DefaultExternal,
|
2023-08-28 18:09:14 -07:00
|
|
|
NonNegativeAmount::const_from_u64(5),
|
2023-01-25 07:29:22 -08:00
|
|
|
);
|
2023-08-28 11:54:35 -07:00
|
|
|
let (h2, meta2, _) = st.generate_next_block(
|
2023-01-25 07:29:22 -08:00
|
|
|
&dfvk,
|
|
|
|
AddressType::DefaultExternal,
|
2023-08-28 18:09:14 -07:00
|
|
|
NonNegativeAmount::const_from_u64(10),
|
2023-01-25 07:29:22 -08:00
|
|
|
);
|
|
|
|
|
|
|
|
// The BlockMeta DB is not updated until we do so explicitly.
|
2023-08-28 11:54:35 -07:00
|
|
|
assert_eq!(st.cache().get_max_cached_height().unwrap(), None);
|
2023-01-25 07:29:22 -08:00
|
|
|
|
|
|
|
// Inform the BlockMeta DB about the newly-persisted CompactBlocks.
|
2023-08-28 11:54:35 -07:00
|
|
|
st.cache().write_block_metadata(&[meta1, meta2]).unwrap();
|
2023-01-25 07:29:22 -08:00
|
|
|
|
|
|
|
// The BlockMeta DB now sees blocks up to height 2.
|
2023-08-28 11:54:35 -07:00
|
|
|
assert_eq!(st.cache().get_max_cached_height().unwrap(), Some(h2),);
|
|
|
|
assert_eq!(st.cache().find_block(h1).unwrap(), Some(meta1));
|
|
|
|
assert_eq!(st.cache().find_block(h2).unwrap(), Some(meta2));
|
|
|
|
assert_eq!(st.cache().find_block(h2 + 1).unwrap(), None);
|
2023-01-25 07:29:22 -08:00
|
|
|
|
|
|
|
// Rewinding to height 1 should cause the metadata for height 2 to be deleted.
|
2023-08-28 11:54:35 -07:00
|
|
|
st.cache().truncate_to_height(h1).unwrap();
|
|
|
|
assert_eq!(st.cache().get_max_cached_height().unwrap(), Some(h1));
|
|
|
|
assert_eq!(st.cache().find_block(h1).unwrap(), Some(meta1));
|
|
|
|
assert_eq!(st.cache().find_block(h2).unwrap(), None);
|
|
|
|
assert_eq!(st.cache().find_block(h2 + 1).unwrap(), None);
|
2023-01-25 07:29:22 -08:00
|
|
|
}
|
2019-03-08 19:12:31 -08:00
|
|
|
}
|