Skip to content

Commit

Permalink
Merge pull request #637 from nuttycom/wallet/create_account
Browse files Browse the repository at this point in the history
Add WalletWrite::create_account function
  • Loading branch information
nuttycom committed Sep 14, 2022
2 parents abe452d + d086c57 commit 3bc8627
Show file tree
Hide file tree
Showing 12 changed files with 211 additions and 57 deletions.
1 change: 1 addition & 0 deletions zcash_client_backend/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ and this library adheres to Rust's notion of
- `WalletRead::get_unified_full_viewing_keys`
- `WalletRead::get_current_address`
- `WalletRead::get_all_nullifiers`
- `WalletWrite::create_account`
- `WalletWrite::remove_unmined_tx` (behind the `unstable` feature flag).
- `WalletWrite::get_next_available_address`
- `zcash_client_backend::proto`:
Expand Down
1 change: 1 addition & 0 deletions zcash_client_backend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ rand_core = "0.6"
rayon = "1.5"
ripemd = { version = "0.1", optional = true }
secp256k1 = { version = "0.21", optional = true }
secrecy = "0.8"
sha2 = { version = "0.10.1", optional = true }
subtle = "2.2.3"
time = "0.2"
Expand Down
42 changes: 38 additions & 4 deletions zcash_client_backend/src/data_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::fmt::Debug;
#[cfg(feature = "transparent-inputs")]
use std::collections::HashSet;

use secrecy::SecretVec;
use zcash_primitives::{
block::BlockHash,
consensus::BlockHeight,
Expand All @@ -20,7 +21,7 @@ use zcash_primitives::{
use crate::{
address::{RecipientAddress, UnifiedAddress},
decrypt::DecryptedOutput,
keys::UnifiedFullViewingKey,
keys::{UnifiedFullViewingKey, UnifiedSpendingKey},
proto::compact_formats::CompactBlock,
wallet::{SpendableNote, WalletTx},
};
Expand Down Expand Up @@ -269,6 +270,26 @@ pub struct SentTransactionOutput<'a> {
/// This trait encapsulates the write capabilities required to update stored
/// wallet data.
pub trait WalletWrite: WalletRead {
/// Tells the wallet to track the next available account-level spend authority, given
/// the current set of [ZIP 316] account identifiers known to the wallet database.
///
/// Returns the account identifier for the newly-created wallet database entry, along
/// with the associated [`UnifiedSpendingKey`].
///
/// If `seed` was imported from a backup and this method is being used to restore a
/// previous wallet state, you should use this method to add all of the desired
/// accounts before scanning the chain from the seed's birthday height.
///
/// By convention, wallets should only allow a new account to be generated after funds
/// have been received by the currently-available account (in order to enable
/// automated account recovery).
///
/// [ZIP 316]: https://zips.z.cash/zip-0316
fn create_account(
&mut self,
seed: &SecretVec<u8>,
) -> Result<(AccountId, UnifiedSpendingKey), Self::Error>;

/// Generates and persists the next available diversified address, given the current
/// addresses known to the wallet.
///
Expand Down Expand Up @@ -353,14 +374,15 @@ pub trait BlockSource {

#[cfg(feature = "test-dependencies")]
pub mod testing {
use secrecy::{ExposeSecret, SecretVec};
use std::collections::HashMap;

#[cfg(feature = "transparent-inputs")]
use std::collections::HashSet;

use zcash_primitives::{
block::BlockHash,
consensus::BlockHeight,
consensus::{BlockHeight, Network},
legacy::TransparentAddress,
memo::Memo,
merkle_tree::{CommitmentTree, IncrementalWitness},
Expand All @@ -371,7 +393,7 @@ pub mod testing {

use crate::{
address::UnifiedAddress,
keys::UnifiedFullViewingKey,
keys::{UnifiedFullViewingKey, UnifiedSpendingKey},
proto::compact_formats::CompactBlock,
wallet::{SpendableNote, WalletTransparentOutput},
};
Expand Down Expand Up @@ -402,7 +424,9 @@ pub mod testing {
}
}

pub struct MockWalletDb {}
pub struct MockWalletDb {
pub network: Network,
}

impl WalletRead for MockWalletDb {
type Error = Error<u32>;
Expand Down Expand Up @@ -521,6 +545,16 @@ pub mod testing {
}

impl WalletWrite for MockWalletDb {
fn create_account(
&mut self,
seed: &SecretVec<u8>,
) -> Result<(AccountId, UnifiedSpendingKey), Self::Error> {
let account = AccountId::from(0);
UnifiedSpendingKey::from_seed(&self.network, seed.expose_secret(), account)
.map(|k| (account, k))
.map_err(|_| Error::KeyDerivationError(account))
}

fn get_next_available_address(
&mut self,
_account: AccountId,
Expand Down
4 changes: 3 additions & 1 deletion zcash_client_backend/src/data_api/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@
//! # fn test() -> Result<(), Error<u32>> {
//! let network = Network::TestNetwork;
//! let db_cache = testing::MockBlockSource {};
//! let mut db_data = testing::MockWalletDb {};
//! let mut db_data = testing::MockWalletDb {
//! network: Network::TestNetwork
//! };
//!
//! // 1) Download new CompactBlocks into db_cache.
//!
Expand Down
5 changes: 5 additions & 0 deletions zcash_client_backend/src/data_api/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ pub enum Error<NoteId> {

/// It is forbidden to provide a memo when constructing a transparent output.
MemoForbidden,

/// An error occurred deriving a spending key from a seed and an account
/// identifier.
KeyDerivationError(AccountId),
}

impl ChainInvalid {
Expand Down Expand Up @@ -122,6 +126,7 @@ impl<N: fmt::Display> fmt::Display for Error<N> {
Error::Protobuf(e) => write!(f, "{}", e),
Error::SaplingNotActive => write!(f, "Could not determine Sapling upgrade activation height."),
Error::MemoForbidden => write!(f, "It is not possible to send a memo to a transparent address."),
Error::KeyDerivationError(acct_id) => write!(f, "Key derivation failed for account {:?}", acct_id),
}
}
}
Expand Down
4 changes: 3 additions & 1 deletion zcash_client_backend/src/data_api/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,9 @@ where
/// let extsk = sapling::spending_key(&[0; 32][..], COIN_TYPE, account);
/// let to = extsk.default_address().1.into();
///
/// let mut db_read = testing::MockWalletDb {};
/// let mut db_read = testing::MockWalletDb {
/// network: Network::TestNetwork
/// };
///
/// create_spend_to_address(
/// &mut db_read,
Expand Down
4 changes: 4 additions & 0 deletions zcash_client_sqlite/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ and this library adheres to Rust's notion of
rewinds exceed supported bounds.
- `SqliteClientError::DiversifierIndexOutOfRange`, to report when the space
of available diversifier indices has been exhausted.
- `SqliteClientError::AccountIdDiscontinuity`, to report when a user attempts
to initialize the accounts table with a noncontiguous set of account identifiers.
- `SqliteClientError::AccountIdOutOfRange`, to report when the maximum account
identifier has been reached.
- An `unstable` feature flag; this is added to parts of the API that may change
in any release. It enables `zcash_client_backend`'s `unstable` feature flag.
- New summary views that may be directly accessed in the sqlite database.
Expand Down
16 changes: 15 additions & 1 deletion zcash_client_sqlite/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use zcash_client_backend::{
data_api,
encoding::{Bech32DecodeError, TransparentCodecError},
};
use zcash_primitives::consensus::BlockHeight;
use zcash_primitives::{consensus::BlockHeight, zip32::AccountId};

use crate::{NoteId, PRUNING_HEIGHT};

Expand Down Expand Up @@ -69,6 +69,17 @@ pub enum SqliteClientError {
/// The space of allocatable diversifier indices has been exhausted for
/// the given account.
DiversifierIndexOutOfRange,

/// An error occurred deriving a spending key from a seed and an account
/// identifier.
KeyDerivationError(AccountId),

/// A caller attempted to initialize the accounts table with a discontinuous
/// set of account identifiers.
AccountIdDiscontinuity,

/// A caller attempted to construct a new account with an invalid account identifier.
AccountIdOutOfRange,
}

impl error::Error for SqliteClientError {
Expand Down Expand Up @@ -108,6 +119,9 @@ impl fmt::Display for SqliteClientError {
SqliteClientError::InvalidMemo(e) => write!(f, "{}", e),
SqliteClientError::BackendError(e) => write!(f, "{}", e),
SqliteClientError::DiversifierIndexOutOfRange => write!(f, "The space of available diversifier indices is exhausted"),
SqliteClientError::KeyDerivationError(acct_id) => write!(f, "Key derivation failed for account {:?}", acct_id),
SqliteClientError::AccountIdDiscontinuity => write!(f, "Wallet account identifiers must be sequential."),
SqliteClientError::AccountIdOutOfRange => write!(f, "Wallet account identifiers must be less than 0x7FFFFFFF."),
}
}
}
Expand Down
30 changes: 29 additions & 1 deletion zcash_client_sqlite/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
// Catch documentation errors caused by code changes.
#![deny(rustdoc::broken_intra_doc_links)]

use secrecy::{ExposeSecret, SecretVec};
use std::collections::HashMap;
use std::fmt;
use std::path::Path;
Expand All @@ -56,7 +57,7 @@ use zcash_client_backend::{
data_api::{
BlockSource, DecryptedTransaction, PrunedBlock, SentTransaction, WalletRead, WalletWrite,
},
keys::UnifiedFullViewingKey,
keys::{UnifiedFullViewingKey, UnifiedSpendingKey},
proto::compact_formats::CompactBlock,
wallet::SpendableNote,
};
Expand Down Expand Up @@ -402,6 +403,33 @@ impl<'a, P: consensus::Parameters> DataConnStmtCache<'a, P> {

#[allow(deprecated)]
impl<'a, P: consensus::Parameters> WalletWrite for DataConnStmtCache<'a, P> {
fn create_account(
&mut self,
seed: &SecretVec<u8>,
) -> Result<(AccountId, UnifiedSpendingKey), Self::Error> {
self.transactionally(|stmts| {
let account = wallet::get_max_account_id(stmts.wallet_db)?
.map(|a| AccountId::from(u32::from(a) + 1))
.unwrap_or_else(|| AccountId::from(0));

if u32::from(account) >= 0x7FFFFFFF {
return Err(SqliteClientError::AccountIdOutOfRange);
}

let usk = UnifiedSpendingKey::from_seed(
&stmts.wallet_db.params,
seed.expose_secret(),
account,
)
.map_err(|_| SqliteClientError::KeyDerivationError(account))?;
let ufvk = usk.to_unified_full_viewing_key();

wallet::add_account(stmts.wallet_db, account, &ufvk)?;

Ok((account, usk))
})
}

fn get_next_available_address(
&mut self,
account: AccountId,
Expand Down
54 changes: 54 additions & 0 deletions zcash_client_sqlite/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,60 @@ pub fn get_address<P: consensus::Parameters>(
})
}

pub(crate) fn get_max_account_id<P>(
wdb: &WalletDb<P>,
) -> Result<Option<AccountId>, SqliteClientError> {
// This returns the most recently generated address.
Ok(wdb
.conn
.query_row("SELECT MAX(account) FROM accounts", NO_PARAMS, |row| {
row.get::<_, u32>(0).map(AccountId::from)
})
.optional()?)
}

pub(crate) fn add_account<P: consensus::Parameters>(
wdb: &WalletDb<P>,
account: AccountId,
key: &UnifiedFullViewingKey,
) -> Result<(), SqliteClientError> {
add_account_internal(&wdb.conn, &wdb.params, "accounts", account, key)
}

pub(crate) fn add_account_internal<P: consensus::Parameters, E: From<rusqlite::Error>>(
conn: &rusqlite::Connection,
network: &P,
accounts_table: &'static str,
account: AccountId,
key: &UnifiedFullViewingKey,
) -> Result<(), E> {
let ufvk_str: String = key.encode(network);
conn.execute_named(
&format!(
"INSERT INTO {} (account, ufvk) VALUES (:account, :ufvk)",
accounts_table
),
&[(":account", &<u32>::from(account)), (":ufvk", &ufvk_str)],
)?;

// Always derive the default Unified Address for the account.
let (address, mut idx) = key.default_address();
let address_str: String = address.encode(network);
// the diversifier index is stored in big-endian order to allow sorting
idx.0.reverse();
conn.execute_named(
"INSERT INTO addresses (account, diversifier_index_be, address)
VALUES (:account, :diversifier_index_be, :address)",
&[
(":account", &<u32>::from(account)),
(":diversifier_index_be", &&idx.0[..]),
(":address", &address_str),
],
)?;

Ok(())
}

pub(crate) fn get_current_address<P: consensus::Parameters>(
wdb: &WalletDb<P>,
account: AccountId,
Expand Down
Loading

0 comments on commit 3bc8627

Please sign in to comment.