diff --git a/.license.ignore b/.license.ignore index a1d61e4568..d322f8cb8c 100644 --- a/.license.ignore +++ b/.license.ignore @@ -13,6 +13,7 @@ ./applications/tari_console_wallet/linux/start_tari_console_wallet ./base_layer/contacts/src/schema.rs ./base_layer/key_manager/Makefile +./base_layer/key_manager/src/schema.rs ./base_layer/p2p/src/dns/roots/tls.rs ./base_layer/wallet/src/schema.rs ./buildtools/docker/torrc diff --git a/Cargo.lock b/Cargo.lock index 8a9d057a20..f2be66c43c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5295,6 +5295,7 @@ name = "tari_common_types" version = "0.49.0-pre.5" dependencies = [ "borsh", + "chacha20poly1305 0.10.1", "digest 0.9.0", "lazy_static", "newtype-ops", @@ -5636,23 +5637,34 @@ name = "tari_key_manager" version = "0.49.0-pre.5" dependencies = [ "argon2", + "async-trait", "blake2 0.9.2", "chacha20 0.7.3", + "chacha20poly1305 0.10.1", + "chrono", "console_error_panic_hook", "crc32fast", "derivative", + "diesel", + "diesel_migrations", "digest 0.9.0", + "futures 0.3.26", "js-sys", + "log", "rand 0.7.3", "serde", "sha2 0.9.9", "strum", "strum_macros", "subtle", + "tari_common_sqlite", "tari_common_types", "tari_crypto", + "tari_service_framework", "tari_utilities", + "tempfile", "thiserror", + "tokio", "wasm-bindgen", "wasm-bindgen-test", "zeroize", diff --git a/applications/tari_console_wallet/src/automation/commands.rs b/applications/tari_console_wallet/src/automation/commands.rs index 4ef12afa6f..e81303b233 100644 --- a/applications/tari_console_wallet/src/automation/commands.rs +++ b/applications/tari_console_wallet/src/automation/commands.rs @@ -56,11 +56,11 @@ use tari_core::transactions::{ transaction_components::{OutputFeatures, TransactionOutput, UnblindedOutput}, }; use tari_crypto::ristretto::RistrettoSecretKey; +use tari_key_manager::key_manager_service::NextKeyResult; use tari_utilities::{hex::Hex, ByteArray}; use tari_wallet::{ connectivity_service::WalletConnectivityInterface, error::WalletError, - key_manager_service::NextKeyResult, output_manager_service::{handle::OutputManagerHandle, UtxoSelectionCriteria}, transaction_service::handle::{TransactionEvent, TransactionServiceHandle}, TransactionStage, diff --git a/applications/tari_console_wallet/src/automation/error.rs b/applications/tari_console_wallet/src/automation/error.rs index 90f54a4d62..337d882cf7 100644 --- a/applications/tari_console_wallet/src/automation/error.rs +++ b/applications/tari_console_wallet/src/automation/error.rs @@ -29,10 +29,10 @@ use log::*; use tari_common::exit_codes::{ExitCode, ExitError}; use tari_common_types::types::FixedHashSizeError; use tari_core::transactions::{tari_amount::MicroTariError, transaction_components::TransactionError}; +use tari_key_manager::key_manager_service::KeyManagerServiceError; use tari_utilities::{hex::HexError, ByteArrayError}; use tari_wallet::{ error::{WalletError, WalletStorageError}, - key_manager_service::KeyManagerServiceError, output_manager_service::error::OutputManagerError, transaction_service::error::TransactionServiceError, }; diff --git a/base_layer/common_types/Cargo.toml b/base_layer/common_types/Cargo.toml index e59b946db5..00e37bdace 100644 --- a/base_layer/common_types/Cargo.toml +++ b/base_layer/common_types/Cargo.toml @@ -13,6 +13,7 @@ tari_utilities = "0.4.10" tari_common = { path = "../../common" } +chacha20poly1305 = "0.10.1" borsh = "0.9.3" digest = "0.9.0" lazy_static = "1.4.0" diff --git a/base_layer/wallet/src/util/encryption.rs b/base_layer/common_types/src/encryption.rs similarity index 98% rename from base_layer/wallet/src/util/encryption.rs rename to base_layer/common_types/src/encryption.rs index d7c40afeb6..8983b26187 100644 --- a/base_layer/wallet/src/util/encryption.rs +++ b/base_layer/common_types/src/encryption.rs @@ -114,7 +114,7 @@ mod test { use rand::{rngs::OsRng, RngCore}; use tari_utilities::{ByteArray, Hidden}; - use crate::util::encryption::{decrypt_bytes_integral_nonce, encrypt_bytes_integral_nonce}; + use super::*; #[test] fn test_encrypt_decrypt() { diff --git a/base_layer/common_types/src/lib.rs b/base_layer/common_types/src/lib.rs index ecacad6bcd..be272da839 100644 --- a/base_layer/common_types/src/lib.rs +++ b/base_layer/common_types/src/lib.rs @@ -24,6 +24,7 @@ pub mod burnt_proof; pub mod chain_metadata; pub mod dammsum; pub mod emoji; +pub mod encryption; pub mod epoch; pub mod grpc_authentication; pub mod tari_address; diff --git a/base_layer/key_manager/Cargo.toml b/base_layer/key_manager/Cargo.toml index 29329c346b..6b65ee63e4 100644 --- a/base_layer/key_manager/Cargo.toml +++ b/base_layer/key_manager/Cargo.toml @@ -12,10 +12,20 @@ crate-type = ["lib", "cdylib"] # NB: All dependencies must support or be gated for the WASM target. [dependencies] -tari_common_types = { path = "../../base_layer/common_types", optional = true } -tari_crypto = { version = "0.16.11"} +tari_crypto = "0.16.11" tari_utilities = "0.4.10" +tari_common_sqlite = { path = "../../common_sqlite" } +tari_common_types = { path = "../../base_layer/common_types"} +tari_service_framework = { path = "../service_framework" } +async-trait = {version = "0.1.50"} +chrono = { version = "0.4.19", default-features = false, features = ["serde"] } +chacha20poly1305 = "0.10.1" +tokio = { version = "1.23", features = ["sync", "macros"]} +futures = { version = "^0.3.1", features = ["compat", "std"] } +log = {version = "0.4.6"} +diesel = { version = "2.0.3", features = ["sqlite", "serde_json", "chrono", "64-column-tables"]} +diesel_migrations = {version = "2.0.0"} argon2 = { version = "0.4.1", features = ["std", "alloc"] } blake2 = "0.9.1" chacha20 = "0.7.1" @@ -36,8 +46,11 @@ subtle = "2.4.1" [dev-dependencies] sha2 = "0.9.8" wasm-bindgen-test = "0.3.28" +tempfile = "3.1.0" [features] +default = [] +key_manager_service = [] avx2 = ["tari_crypto/simd_backend"] js = [ "js-sys"] -wasm = ["tari_crypto/wasm", "wasm-bindgen", "js", "tari_common_types", "console_error_panic_hook"] +wasm = ["tari_crypto/wasm", "wasm-bindgen", "js", "console_error_panic_hook"] diff --git a/base_layer/key_manager/diesel.toml b/base_layer/key_manager/diesel.toml new file mode 100644 index 0000000000..35a12ff0db --- /dev/null +++ b/base_layer/key_manager/diesel.toml @@ -0,0 +1,8 @@ +# For documentation on how to configure this file, +# see https://diesel.rs/guides/configuring-diesel-cli + +[print_schema] +file = "src/schema.rs" + +[migrations_directory] +dir = "migrations" diff --git a/base_layer/key_manager/migrations/2023-03-31-130611_initial/down.sql b/base_layer/key_manager/migrations/2023-03-31-130611_initial/down.sql new file mode 100644 index 0000000000..d890deb69e --- /dev/null +++ b/base_layer/key_manager/migrations/2023-03-31-130611_initial/down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS key_manager_states; diff --git a/base_layer/key_manager/migrations/2023-03-31-130611_initial/up.sql b/base_layer/key_manager/migrations/2023-03-31-130611_initial/up.sql new file mode 100644 index 0000000000..9dc048eb96 --- /dev/null +++ b/base_layer/key_manager/migrations/2023-03-31-130611_initial/up.sql @@ -0,0 +1,6 @@ +CREATE TABLE key_manager_states ( + id INTEGER PRIMARY KEY NOT NULL, + branch_seed TEXT UNIQUE NOT NULL, + primary_key_index BLOB NOT NULL, + timestamp DATETIME NOT NULL +); \ No newline at end of file diff --git a/base_layer/wallet/src/key_manager_service/error.rs b/base_layer/key_manager/src/key_manager_service/error.rs similarity index 92% rename from base_layer/wallet/src/key_manager_service/error.rs rename to base_layer/key_manager/src/key_manager_service/error.rs index 07a7ac0208..26246a433b 100644 --- a/base_layer/wallet/src/key_manager_service/error.rs +++ b/base_layer/key_manager/src/key_manager_service/error.rs @@ -22,11 +22,11 @@ use diesel::result::Error as DieselError; use tari_common_sqlite::error::SqliteStorageError; -use tari_key_manager::error::KeyManagerError as KMError; -use tari_script::ScriptError; use tari_utilities::{hex::HexError, ByteArrayError}; -use crate::error::WalletStorageError; +use crate::error::KeyManagerError as KMError; + +// use crate::error::WalletStorageError; /// Error enum for the [KeyManagerService] #[derive(Debug, thiserror::Error)] pub enum KeyManagerServiceError { @@ -60,8 +60,6 @@ pub enum KeyManagerStorageError { ConversionError { reason: String }, #[error("Key Manager not initialized")] KeyManagerNotInitialized, - #[error("Wallet storage error: `{0}`")] - WalletStorageError(#[from] WalletStorageError), #[error("Diesel error: `{0}`")] DieselError(#[from] DieselError), #[error("Diesel connection error: `{0}`")] @@ -76,8 +74,6 @@ pub enum KeyManagerStorageError { ByteArrayError(#[from] ByteArrayError), #[error("Aead error: `{0}`")] AeadError(String), - #[error("Tari script error : {0}")] - ScriptError(#[from] ScriptError), #[error("Binary not stored as valid hex:{0}")] HexError(#[from] HexError), #[error("Tari Key Manager error: `{0}`")] diff --git a/base_layer/wallet/src/key_manager_service/handle.rs b/base_layer/key_manager/src/key_manager_service/handle.rs similarity index 93% rename from base_layer/wallet/src/key_manager_service/handle.rs rename to base_layer/key_manager/src/key_manager_service/handle.rs index 83a23d17b6..e622d150f5 100644 --- a/base_layer/wallet/src/key_manager_service/handle.rs +++ b/base_layer/key_manager/src/key_manager_service/handle.rs @@ -23,16 +23,18 @@ use std::sync::Arc; use tari_common_types::types::PrivateKey; -use tari_key_manager::cipher_seed::CipherSeed; use tokio::sync::RwLock; -use crate::key_manager_service::{ - error::KeyManagerServiceError, - interface::NextKeyResult, - storage::database::{KeyManagerBackend, KeyManagerDatabase}, - AddResult, - KeyManagerInner, - KeyManagerInterface, +use crate::{ + cipher_seed::CipherSeed, + key_manager_service::{ + error::KeyManagerServiceError, + interface::NextKeyResult, + storage::database::{KeyManagerBackend, KeyManagerDatabase}, + AddResult, + KeyManagerInner, + KeyManagerInterface, + }, }; /// The key manager provides a hierarchical key derivation function (KDF) that derives uniformly random secret keys from /// a single seed key for arbitrary branches, using an implementation of `KeyManagerBackend` to store the current index diff --git a/base_layer/wallet/src/key_manager_service/initializer.rs b/base_layer/key_manager/src/key_manager_service/initializer.rs similarity index 95% rename from base_layer/wallet/src/key_manager_service/initializer.rs rename to base_layer/key_manager/src/key_manager_service/initializer.rs index 2166176d92..9309bd9934 100644 --- a/base_layer/wallet/src/key_manager_service/initializer.rs +++ b/base_layer/key_manager/src/key_manager_service/initializer.rs @@ -28,12 +28,14 @@ // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -use tari_key_manager::cipher_seed::CipherSeed; use tari_service_framework::{async_trait, ServiceInitializationError, ServiceInitializer, ServiceInitializerContext}; -use crate::key_manager_service::{ - storage::database::{KeyManagerBackend, KeyManagerDatabase}, - KeyManagerHandle, +use crate::{ + cipher_seed::CipherSeed, + key_manager_service::{ + storage::database::{KeyManagerBackend, KeyManagerDatabase}, + KeyManagerHandle, + }, }; /// Initializes the key manager service by implementing the [ServiceInitializer] trait. diff --git a/base_layer/wallet/src/key_manager_service/interface.rs b/base_layer/key_manager/src/key_manager_service/interface.rs similarity index 100% rename from base_layer/wallet/src/key_manager_service/interface.rs rename to base_layer/key_manager/src/key_manager_service/interface.rs diff --git a/base_layer/wallet/src/key_manager_service/mock.rs b/base_layer/key_manager/src/key_manager_service/mock.rs similarity index 97% rename from base_layer/wallet/src/key_manager_service/mock.rs rename to base_layer/key_manager/src/key_manager_service/mock.rs index c4c18d8029..4aa4a08a36 100644 --- a/base_layer/wallet/src/key_manager_service/mock.rs +++ b/base_layer/key_manager/src/key_manager_service/mock.rs @@ -24,21 +24,22 @@ use std::{collections::HashMap, sync::Arc}; use log::*; use tari_common_types::types::PrivateKey; -use tari_key_manager::{cipher_seed::CipherSeed, key_manager::KeyManager}; use tokio::sync::RwLock; use crate::{ + cipher_seed::CipherSeed, + key_manager::KeyManager, key_manager_service::{ error::KeyManagerServiceError, interface::NextKeyResult, storage::database::KeyManagerState, AddResult, + KeyDigest, KeyManagerInterface, }, - types::KeyDigest, }; -const LOG_TARGET: &str = "wallet::Key_manager_mock"; +const LOG_TARGET: &str = "key_manager::Key_manager_mock"; const KEY_MANAGER_MAX_SEARCH_DEPTH: u64 = 1_000_000; /// Testing Mock for the key manager service diff --git a/base_layer/wallet/src/key_manager_service/mod.rs b/base_layer/key_manager/src/key_manager_service/mod.rs similarity index 70% rename from base_layer/wallet/src/key_manager_service/mod.rs rename to base_layer/key_manager/src/key_manager_service/mod.rs index 5d4f8af137..029f63ac6b 100644 --- a/base_layer/wallet/src/key_manager_service/mod.rs +++ b/base_layer/key_manager/src/key_manager_service/mod.rs @@ -20,6 +20,21 @@ // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// Note: For help in getting started with diesel as well as how to update the tables look here: +// http://diesel.rs/guides/getting-started/ +// - You also need to ensure that you installed diesel with the sqlite feature flag: +// - 'cargo install diesel_cli --no-default-features --features sqlite' +// - If you updated the tables the following needs to be run from the base_layer/key_manager/ folder: +// - 'diesel setup --database-url test.sqlite3' +// - 'diesel migration run --database-url test.sqlite3' +// - After running this, make sure that the diesel update did not change BigInt to Integer in 'schema.rs' (check for +// any unwanted changes) + +use tari_crypto::hash::blake2::Blake256; + +/// Specify the Hash function used by the key manager +pub type KeyDigest = Blake256; + mod error; pub use error::KeyManagerServiceError; diff --git a/base_layer/wallet/src/key_manager_service/service.rs b/base_layer/key_manager/src/key_manager_service/service.rs similarity index 97% rename from base_layer/wallet/src/key_manager_service/service.rs rename to base_layer/key_manager/src/key_manager_service/service.rs index 19ba36c17a..64f271f8b8 100644 --- a/base_layer/wallet/src/key_manager_service/service.rs +++ b/base_layer/key_manager/src/key_manager_service/service.rs @@ -24,19 +24,20 @@ use std::collections::HashMap; use futures::lock::Mutex; use log::*; use tari_common_types::types::PrivateKey; -use tari_key_manager::{cipher_seed::CipherSeed, key_manager::KeyManager}; use crate::{ + cipher_seed::CipherSeed, + key_manager::KeyManager, key_manager_service::{ error::KeyManagerServiceError, interface::NextKeyResult, storage::database::{KeyManagerBackend, KeyManagerDatabase, KeyManagerState}, AddResult, + KeyDigest, }, - types::KeyDigest, }; -const LOG_TARGET: &str = "wallet::key_manager"; +const LOG_TARGET: &str = "key_manager::key_manager_service"; const KEY_MANAGER_MAX_SEARCH_DEPTH: u64 = 1_000_000; pub struct KeyManagerInner { diff --git a/base_layer/wallet/src/key_manager_service/storage/database/backend.rs b/base_layer/key_manager/src/key_manager_service/storage/database/backend.rs similarity index 100% rename from base_layer/wallet/src/key_manager_service/storage/database/backend.rs rename to base_layer/key_manager/src/key_manager_service/storage/database/backend.rs diff --git a/base_layer/wallet/src/key_manager_service/storage/database/mod.rs b/base_layer/key_manager/src/key_manager_service/storage/database/mod.rs similarity index 100% rename from base_layer/wallet/src/key_manager_service/storage/database/mod.rs rename to base_layer/key_manager/src/key_manager_service/storage/database/mod.rs diff --git a/base_layer/wallet/src/key_manager_service/storage/mod.rs b/base_layer/key_manager/src/key_manager_service/storage/mod.rs similarity index 100% rename from base_layer/wallet/src/key_manager_service/storage/mod.rs rename to base_layer/key_manager/src/key_manager_service/storage/mod.rs diff --git a/base_layer/wallet/src/key_manager_service/storage/sqlite_db/key_manager_state.rs b/base_layer/key_manager/src/key_manager_service/storage/sqlite_db/key_manager_state.rs similarity index 98% rename from base_layer/wallet/src/key_manager_service/storage/sqlite_db/key_manager_state.rs rename to base_layer/key_manager/src/key_manager_service/storage/sqlite_db/key_manager_state.rs index 7bd6cc7b49..888744edb3 100644 --- a/base_layer/wallet/src/key_manager_service/storage/sqlite_db/key_manager_state.rs +++ b/base_layer/key_manager/src/key_manager_service/storage/sqlite_db/key_manager_state.rs @@ -26,6 +26,7 @@ use chacha20poly1305::XChaCha20Poly1305; use chrono::{NaiveDateTime, Utc}; use diesel::{prelude::*, SqliteConnection}; use tari_common_sqlite::util::diesel_ext::ExpectedRowsExtension; +use tari_common_types::encryption::{decrypt_bytes_integral_nonce, encrypt_bytes_integral_nonce}; use tari_utilities::Hidden; use crate::{ @@ -34,7 +35,6 @@ use crate::{ storage::{database::KeyManagerState, sqlite_db::Encryptable}, }, schema::key_manager_states, - util::encryption::{decrypt_bytes_integral_nonce, encrypt_bytes_integral_nonce}, }; /// Represents a row in the key_manager_states table. diff --git a/base_layer/wallet/src/key_manager_service/storage/sqlite_db/mod.rs b/base_layer/key_manager/src/key_manager_service/storage/sqlite_db/mod.rs similarity index 80% rename from base_layer/wallet/src/key_manager_service/storage/sqlite_db/mod.rs rename to base_layer/key_manager/src/key_manager_service/storage/sqlite_db/mod.rs index b503755bbc..9a7c8c1113 100644 --- a/base_layer/wallet/src/key_manager_service/storage/sqlite_db/mod.rs +++ b/base_layer/key_manager/src/key_manager_service/storage/sqlite_db/mod.rs @@ -22,52 +22,75 @@ use std::{ convert::TryFrom, + io::Write, sync::{Arc, RwLock}, }; use chacha20poly1305::XChaCha20Poly1305; +use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness}; pub use key_manager_state::{KeyManagerStateSql, NewKeyManagerStateSql}; use log::*; -use tari_common_sqlite::sqlite_connection_pool::PooledDbConnection; +use tari_common_sqlite::{error::SqliteStorageError, sqlite_connection_pool::PooledDbConnection}; +use tari_common_types::encryption::Encryptable; +use tari_utilities::acquire_read_lock; use tokio::time::Instant; -use crate::{ - key_manager_service::{ - error::KeyManagerStorageError, - storage::database::{KeyManagerBackend, KeyManagerState}, - }, - storage::sqlite_utilities::wallet_db_connection::WalletDbConnection, - util::encryption::Encryptable, +use crate::key_manager_service::{ + error::KeyManagerStorageError, + storage::database::{KeyManagerBackend, KeyManagerState}, }; - mod key_manager_state; +const MIGRATIONS: EmbeddedMigrations = embed_migrations!("./migrations"); const LOG_TARGET: &str = "wallet::key_manager_service::database::wallet"; /// A Sqlite backend for the Output Manager Service. The Backend is accessed via a connection pool to the Sqlite file. #[derive(Clone)] -pub struct KeyManagerSqliteDatabase { - database_connection: WalletDbConnection, +pub struct KeyManagerSqliteDatabase { + database_connection: Arc, cipher: Arc>, } -impl KeyManagerSqliteDatabase { +impl + Clone> + KeyManagerSqliteDatabase +{ /// Creates a new sql backend from provided wallet db connection /// * `cipher` is used to encrypt the sensitive fields in the database, a cipher is derived /// from a provided password, which we enforce for class instantiation - pub fn new( - database_connection: WalletDbConnection, - cipher: XChaCha20Poly1305, - ) -> Result { - let db = Self { - database_connection, + fn new(database_connection: TKeyManagerDbConnection, cipher: XChaCha20Poly1305) -> Self { + Self { + database_connection: Arc::new(database_connection), cipher: Arc::new(RwLock::new(cipher)), - }; - Ok(db) + } + } + + pub fn init(database_connection: TKeyManagerDbConnection, cipher: XChaCha20Poly1305) -> Self { + let db = Self::new(database_connection, cipher); + db.run_migrations().expect("Migrations to run"); + db + } + + fn run_migrations(&self) -> Result, SqliteStorageError> { + let mut conn = self.database_connection.get_pooled_connection()?; + conn.run_pending_migrations(MIGRATIONS) + .map(|v| { + v.into_iter() + .map(|b| { + let m = format!("Running migration {}", b); + std::io::stdout() + .write_all(m.as_ref()) + .expect("Couldn't write migration number to stdout"); + m + }) + .collect::>() + }) + .map_err(|e| SqliteStorageError::DieselR2d2Error(e.to_string())) } } -impl KeyManagerBackend for KeyManagerSqliteDatabase { +impl + Send + Sync + Clone> KeyManagerBackend + for KeyManagerSqliteDatabase +{ fn get_key_manager(&self, branch: String) -> Result, KeyManagerStorageError> { let start = Instant::now(); let mut conn = self.database_connection.get_pooled_connection()?; @@ -184,14 +207,14 @@ mod test { use diesel::{sql_query, Connection, RunQueryDsl, SqliteConnection}; use diesel_migrations::{EmbeddedMigrations, MigrationHarness}; - use tari_test_utils::random; use tempfile::tempdir; + use super::*; use crate::key_manager_service::storage::sqlite_db::{KeyManagerState, KeyManagerStateSql, NewKeyManagerStateSql}; #[test] fn test_key_manager_crud() { - let db_name = format!("{}.sqlite3", random::string(8).as_str()); + let db_name = format!("{}.sqlite3", "test"); let temp_dir = tempdir().unwrap(); let db_folder = temp_dir.path().to_str().unwrap().to_string(); let db_path = format!("{}{}", db_folder, db_name); @@ -215,7 +238,7 @@ mod test { .expect("Migrations failed"); sql_query("PRAGMA foreign_keys = ON").execute(&mut conn).unwrap(); - let branch = random::string(8); + let branch = "branch_key".to_string(); assert!(KeyManagerStateSql::get_state(&branch, &mut conn).is_err()); let state1 = KeyManagerState { diff --git a/base_layer/wallet/src/key_manager_service/test.rs b/base_layer/key_manager/src/key_manager_service/test.rs similarity index 97% rename from base_layer/wallet/src/key_manager_service/test.rs rename to base_layer/key_manager/src/key_manager_service/test.rs index 9b5dea2f16..6e7db2b584 100644 --- a/base_layer/wallet/src/key_manager_service/test.rs +++ b/base_layer/key_manager/src/key_manager_service/test.rs @@ -20,9 +20,7 @@ // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -use tari_key_manager::cipher_seed::CipherSeed; - -use crate::key_manager_service::KeyManagerMock; +use crate::{cipher_seed::CipherSeed, key_manager_service::KeyManagerMock}; #[tokio::test] async fn get_next_key_test_mock() { diff --git a/base_layer/key_manager/src/lib.rs b/base_layer/key_manager/src/lib.rs index 0a2434e331..e68d467056 100644 --- a/base_layer/key_manager/src/lib.rs +++ b/base_layer/key_manager/src/lib.rs @@ -21,8 +21,12 @@ pub mod cipher_seed; pub mod diacritics; pub mod error; pub mod key_manager; +#[cfg(feature = "key_manager_service")] +pub mod key_manager_service; pub mod mnemonic; pub mod mnemonic_wordlists; +#[cfg(feature = "key_manager_service")] +pub mod schema; // https://github.com/rustwasm/wasm-bindgen/issues/2774 #[allow(clippy::unused_unit)] #[cfg(feature = "wasm")] diff --git a/base_layer/key_manager/src/schema.rs b/base_layer/key_manager/src/schema.rs new file mode 100644 index 0000000000..ade85676d9 --- /dev/null +++ b/base_layer/key_manager/src/schema.rs @@ -0,0 +1,10 @@ +// @generated automatically by Diesel CLI. + +diesel::table! { + key_manager_states (id) { + id -> Integer, + branch_seed -> Text, + primary_key_index -> Binary, + timestamp -> Timestamp, + } +} diff --git a/base_layer/wallet/Cargo.toml b/base_layer/wallet/Cargo.toml index 40c24b57c0..28b800fb53 100644 --- a/base_layer/wallet/Cargo.toml +++ b/base_layer/wallet/Cargo.toml @@ -13,7 +13,7 @@ tari_common_types = { path = "../../base_layer/common_types" } tari_comms = { path = "../../comms/core" } tari_comms_dht = { path = "../../comms/dht" } tari_crypto = "0.16.11" -tari_key_manager = { path = "../key_manager" } +tari_key_manager = { path = "../key_manager", features = ["key_manager_service"] } tari_p2p = { path = "../p2p", features = ["auto-update"] } tari_script = { path = "../../infrastructure/tari_script" } tari_service_framework = { path = "../service_framework" } diff --git a/base_layer/wallet/migrations/2022-08-08-134037_initial/up.sql b/base_layer/wallet/migrations/2022-08-08-134037_initial/up.sql index 4f0e465494..9b2e28e5cb 100644 --- a/base_layer/wallet/migrations/2022-08-08-134037_initial/up.sql +++ b/base_layer/wallet/migrations/2022-08-08-134037_initial/up.sql @@ -39,13 +39,6 @@ CREATE TABLE inbound_transactions ( last_send_timestamp DATETIME NULL ); -CREATE TABLE key_manager_states ( - id INTEGER PRIMARY KEY NOT NULL, - branch_seed TEXT UNIQUE NOT NULL, - primary_key_index BLOB NOT NULL, - timestamp DATETIME NOT NULL -); - CREATE TABLE known_one_sided_payment_scripts ( script_hash BLOB PRIMARY KEY NOT NULL, private_key BLOB NOT NULL, diff --git a/base_layer/wallet/src/error.rs b/base_layer/wallet/src/error.rs index 83307fc78f..101d6316ce 100644 --- a/base_layer/wallet/src/error.rs +++ b/base_layer/wallet/src/error.rs @@ -33,7 +33,7 @@ use tari_comms::{ use tari_comms_dht::store_forward::StoreAndForwardError; use tari_contacts::contacts_service::error::ContactsServiceError; use tari_core::transactions::transaction_components::TransactionError; -use tari_key_manager::error::KeyManagerError; +use tari_key_manager::{error::KeyManagerError, key_manager_service::KeyManagerServiceError}; use tari_p2p::{initialization::CommsInitializationError, services::liveness::error::LivenessError}; use tari_service_framework::{reply_channel::TransportChannelError, ServiceInitializationError}; use tari_utilities::{hex::HexError, ByteArrayError}; @@ -41,7 +41,6 @@ use thiserror::Error; use crate::{ base_node_service::error::BaseNodeServiceError, - key_manager_service::KeyManagerServiceError, output_manager_service::error::OutputManagerError, storage::database::DbKey, transaction_service::error::TransactionServiceError, diff --git a/base_layer/wallet/src/lib.rs b/base_layer/wallet/src/lib.rs index c43b399958..1a3291ead8 100644 --- a/base_layer/wallet/src/lib.rs +++ b/base_layer/wallet/src/lib.rs @@ -31,16 +31,15 @@ extern crate diesel; extern crate diesel_migrations; mod config; -pub mod key_manager_service; pub mod schema; pub mod utxo_scanner_service; pub use config::{TransactionStage, WalletConfig}; use tari_contacts::contacts_service::storage::sqlite_db::ContactsServiceSqliteDatabase; +use tari_key_manager::key_manager_service::storage::sqlite_db::KeyManagerSqliteDatabase; pub use wallet::Wallet; use crate::{ - key_manager_service::storage::sqlite_db::KeyManagerSqliteDatabase, output_manager_service::storage::sqlite_db::OutputManagerSqliteDatabase, storage::{sqlite_db::wallet::WalletSqliteDatabase, sqlite_utilities::WalletDbConnection}, transaction_service::storage::sqlite_db::TransactionServiceSqliteDatabase, @@ -56,5 +55,5 @@ pub type WalletSqlite = Wallet< TransactionServiceSqliteDatabase, OutputManagerSqliteDatabase, ContactsServiceSqliteDatabase, - KeyManagerSqliteDatabase, + KeyManagerSqliteDatabase, >; diff --git a/base_layer/wallet/src/output_manager_service/error.rs b/base_layer/wallet/src/output_manager_service/error.rs index 034e16ee4d..418c1638d3 100644 --- a/base_layer/wallet/src/output_manager_service/error.rs +++ b/base_layer/wallet/src/output_manager_service/error.rs @@ -30,7 +30,10 @@ use tari_core::transactions::{ transaction_protocol::TransactionProtocolError, CoinbaseBuildError, }; -use tari_key_manager::error::{KeyManagerError, MnemonicError}; +use tari_key_manager::{ + error::{KeyManagerError, MnemonicError}, + key_manager_service::KeyManagerServiceError, +}; use tari_script::ScriptError; use tari_service_framework::reply_channel::TransportChannelError; use tari_utilities::{hex::HexError, ByteArrayError}; @@ -39,7 +42,6 @@ use thiserror::Error; use crate::{ base_node_service::error::BaseNodeServiceError, error::WalletStorageError, - key_manager_service::KeyManagerServiceError, output_manager_service::UtxoSelectionCriteria, }; diff --git a/base_layer/wallet/src/output_manager_service/mod.rs b/base_layer/wallet/src/output_manager_service/mod.rs index 49a49371b4..0dc44416fe 100644 --- a/base_layer/wallet/src/output_manager_service/mod.rs +++ b/base_layer/wallet/src/output_manager_service/mod.rs @@ -39,6 +39,7 @@ use futures::future; use log::*; use tari_comms::NodeIdentity; use tari_core::{consensus::NetworkConsensus, transactions::CryptoFactories}; +use tari_key_manager::key_manager_service::{storage::database::KeyManagerBackend, KeyManagerHandle}; use tari_service_framework::{ async_trait, reply_channel, @@ -51,7 +52,6 @@ use tokio::sync::broadcast; use crate::{ base_node_service::handle::BaseNodeServiceHandle, connectivity_service::WalletConnectivityHandle, - key_manager_service::{storage::database::KeyManagerBackend, KeyManagerHandle}, output_manager_service::{ config::OutputManagerServiceConfig, handle::OutputManagerHandle, diff --git a/base_layer/wallet/src/output_manager_service/recovery/standard_outputs_recoverer.rs b/base_layer/wallet/src/output_manager_service/recovery/standard_outputs_recoverer.rs index 32e3805f71..079e2e51af 100644 --- a/base_layer/wallet/src/output_manager_service/recovery/standard_outputs_recoverer.rs +++ b/base_layer/wallet/src/output_manager_service/recovery/standard_outputs_recoverer.rs @@ -38,10 +38,10 @@ use tari_crypto::{ keys::{PublicKey as PublicKeyTrait, SecretKey}, tari_utilities::hex::Hex, }; +use tari_key_manager::key_manager_service::KeyManagerInterface; use tari_script::{inputs, script, Opcode}; use crate::{ - key_manager_service::KeyManagerInterface, output_manager_service::{ error::{OutputManagerError, OutputManagerStorageError}, handle::RecoveredOutput, diff --git a/base_layer/wallet/src/output_manager_service/service.rs b/base_layer/wallet/src/output_manager_service/service.rs index 5e2024cfe4..766ccdca8f 100644 --- a/base_layer/wallet/src/output_manager_service/service.rs +++ b/base_layer/wallet/src/output_manager_service/service.rs @@ -65,6 +65,7 @@ use tari_crypto::{ errors::RangeProofError, keys::{PublicKey as PublicKeyTrait, SecretKey}, }; +use tari_key_manager::key_manager_service::KeyManagerInterface; use tari_script::{inputs, script, Opcode, TariScript}; use tari_service_framework::reply_channel; use tari_shutdown::ShutdownSignal; @@ -74,7 +75,6 @@ use tokio::sync::Mutex; use crate::{ base_node_service::handle::{BaseNodeEvent, BaseNodeServiceHandle}, connectivity_service::WalletConnectivityInterface, - key_manager_service::KeyManagerInterface, output_manager_service::{ config::OutputManagerServiceConfig, error::{OutputManagerError, OutputManagerProtocolError, OutputManagerStorageError}, diff --git a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs index 8761170602..6ef5dfb3fc 100644 --- a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs +++ b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs @@ -39,6 +39,7 @@ pub use new_output_sql::NewOutputSql; pub use output_sql::OutputSql; use tari_common_sqlite::{sqlite_connection_pool::PooledDbConnection, util::diesel_ext::ExpectedRowsExtension}; use tari_common_types::{ + encryption::{decrypt_bytes_integral_nonce, encrypt_bytes_integral_nonce, Encryptable}, transaction::TxId, types::{Commitment, FixedHash, PrivateKey}, }; @@ -62,9 +63,7 @@ use crate::{ }, schema::{known_one_sided_payment_scripts, outputs}, storage::sqlite_utilities::wallet_db_connection::WalletDbConnection, - util::encryption::{decrypt_bytes_integral_nonce, encrypt_bytes_integral_nonce, Encryptable}, }; - mod new_output_sql; mod output_sql; const LOG_TARGET: &str = "wallet::output_manager_service::database::wallet"; @@ -1385,7 +1384,7 @@ mod test { use diesel::{sql_query, Connection, RunQueryDsl, SqliteConnection}; use diesel_migrations::{EmbeddedMigrations, MigrationHarness}; use rand::{rngs::OsRng, RngCore}; - use tari_common_types::types::CommitmentFactory; + use tari_common_types::{encryption::Encryptable, types::CommitmentFactory}; use tari_core::transactions::{ tari_amount::MicroTari, test_helpers::{create_unblinded_output, TestParams as TestParamsHelpers}, @@ -1397,13 +1396,10 @@ mod test { use tari_utilities::ByteArray; use tempfile::tempdir; - use crate::{ - output_manager_service::storage::{ - models::DbUnblindedOutput, - sqlite_db::{new_output_sql::NewOutputSql, output_sql::OutputSql, OutputStatus, UpdateOutput}, - OutputSource, - }, - util::encryption::Encryptable, + use crate::output_manager_service::storage::{ + models::DbUnblindedOutput, + sqlite_db::{new_output_sql::NewOutputSql, output_sql::OutputSql, OutputStatus, UpdateOutput}, + OutputSource, }; pub fn make_input(val: MicroTari) -> (TransactionInput, UnblindedOutput) { diff --git a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/new_output_sql.rs b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/new_output_sql.rs index f67ffccde3..7ae47fbd26 100644 --- a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/new_output_sql.rs +++ b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/new_output_sql.rs @@ -24,7 +24,10 @@ use borsh::BorshSerialize; use chacha20poly1305::XChaCha20Poly1305; use derivative::Derivative; use diesel::{prelude::*, SqliteConnection}; -use tari_common_types::transaction::TxId; +use tari_common_types::{ + encryption::{decrypt_bytes_integral_nonce, encrypt_bytes_integral_nonce, Encryptable}, + transaction::TxId, +}; use tari_utilities::{ByteArray, Hidden}; use crate::{ @@ -33,7 +36,6 @@ use crate::{ storage::{models::DbUnblindedOutput, OutputStatus}, }, schema::outputs, - util::encryption::{decrypt_bytes_integral_nonce, encrypt_bytes_integral_nonce, Encryptable}, }; /// This struct represents an Output in the Sql database. A distinct struct is required to define the Sql friendly diff --git a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/output_sql.rs b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/output_sql.rs index 9f696503b1..9a823a1014 100644 --- a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/output_sql.rs +++ b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/output_sql.rs @@ -30,6 +30,7 @@ use diesel::{prelude::*, sql_query, SqliteConnection}; use log::*; use tari_common_sqlite::util::diesel_ext::ExpectedRowsExtension; use tari_common_types::{ + encryption::{decrypt_bytes_integral_nonce, encrypt_bytes_integral_nonce, Encryptable}, transaction::TxId, types::{ComAndPubSignature, Commitment, PrivateKey, PublicKey}, }; @@ -59,7 +60,6 @@ use crate::{ UtxoSelectionOrdering, }, schema::outputs, - util::encryption::{decrypt_bytes_integral_nonce, encrypt_bytes_integral_nonce, Encryptable}, }; const LOG_TARGET: &str = "wallet::output_manager_service::database::wallet"; diff --git a/base_layer/wallet/src/schema.rs b/base_layer/wallet/src/schema.rs index 0855605133..20b42551ce 100644 --- a/base_layer/wallet/src/schema.rs +++ b/base_layer/wallet/src/schema.rs @@ -47,15 +47,6 @@ diesel::table! { } } -diesel::table! { - key_manager_states (id) { - id -> Integer, - branch_seed -> Text, - primary_key_index -> Binary, - timestamp -> Timestamp, - } -} - diesel::table! { known_one_sided_payment_scripts (script_hash) { script_hash -> Binary, @@ -143,7 +134,6 @@ diesel::allow_tables_to_appear_in_same_query!( client_key_values, completed_transactions, inbound_transactions, - key_manager_states, known_one_sided_payment_scripts, outbound_transactions, outputs, diff --git a/base_layer/wallet/src/storage/sqlite_db/wallet.rs b/base_layer/wallet/src/storage/sqlite_db/wallet.rs index 44deffabe8..649a842f6b 100644 --- a/base_layer/wallet/src/storage/sqlite_db/wallet.rs +++ b/base_layer/wallet/src/storage/sqlite_db/wallet.rs @@ -36,7 +36,10 @@ use diesel::{prelude::*, result::Error, SqliteConnection}; use digest::{generic_array::GenericArray, FixedOutput}; use log::*; use tari_common_sqlite::sqlite_connection_pool::PooledDbConnection; -use tari_common_types::chain_metadata::ChainMetadata; +use tari_common_types::{ + chain_metadata::ChainMetadata, + encryption::{decrypt_bytes_integral_nonce, encrypt_bytes_integral_nonce, Encryptable}, +}; use tari_comms::{ multiaddr::Multiaddr, peer_manager::{IdentitySignature, PeerFeatures}, @@ -62,7 +65,6 @@ use crate::{ sqlite_db::scanned_blocks::ScannedBlockSql, sqlite_utilities::wallet_db_connection::WalletDbConnection, }, - util::encryption::{decrypt_bytes_integral_nonce, encrypt_bytes_integral_nonce, Encryptable}, utxo_scanner_service::service::ScannedBlock, }; @@ -889,6 +891,7 @@ impl Encryptable for ClientKeyValueSql { #[cfg(test)] mod test { use tari_common_sqlite::sqlite_connection_pool::PooledDbConnection; + use tari_common_types::encryption::{decrypt_bytes_integral_nonce, Encryptable}; use tari_key_manager::cipher_seed::CipherSeed; use tari_test_utils::random::string; use tari_utilities::{ @@ -898,15 +901,11 @@ mod test { }; use tempfile::tempdir; - use crate::{ - storage::{ - database::{DbKey, DbValue, WalletBackend}, - sqlite_db::wallet::{ClientKeyValueSql, WalletSettingSql, WalletSqliteDatabase}, - sqlite_utilities::run_migration_and_create_sqlite_connection, - }, - util::encryption::{decrypt_bytes_integral_nonce, Encryptable}, + use crate::storage::{ + database::{DbKey, DbValue, WalletBackend}, + sqlite_db::wallet::{ClientKeyValueSql, WalletSettingSql, WalletSqliteDatabase}, + sqlite_utilities::run_migration_and_create_sqlite_connection, }; - #[test] fn test_passphrase() { // Set up a database diff --git a/base_layer/wallet/src/storage/sqlite_utilities/mod.rs b/base_layer/wallet/src/storage/sqlite_utilities/mod.rs index b08d36b46b..d52c75741b 100644 --- a/base_layer/wallet/src/storage/sqlite_utilities/mod.rs +++ b/base_layer/wallet/src/storage/sqlite_utilities/mod.rs @@ -27,12 +27,12 @@ use fs2::FileExt; use log::*; use tari_common_sqlite::sqlite_connection_pool::SqliteConnectionPool; use tari_contacts::contacts_service::storage::sqlite_db::ContactsServiceSqliteDatabase; +use tari_key_manager::key_manager_service::storage::sqlite_db::KeyManagerSqliteDatabase; use tari_utilities::SafePassword; pub use wallet_db_connection::WalletDbConnection; use crate::{ error::WalletStorageError, - key_manager_service::storage::sqlite_db::KeyManagerSqliteDatabase, output_manager_service::storage::sqlite_db::OutputManagerSqliteDatabase, storage::{ database::DbKey, @@ -106,6 +106,7 @@ pub fn acquire_exclusive_file_lock(db_path: &Path) -> Result>( db_path: P, passphrase: SafePassword, @@ -116,7 +117,7 @@ pub fn initialize_sqlite_database_backends>( TransactionServiceSqliteDatabase, OutputManagerSqliteDatabase, ContactsServiceSqliteDatabase, - KeyManagerSqliteDatabase, + KeyManagerSqliteDatabase, ), WalletStorageError, > { @@ -132,11 +133,7 @@ pub fn initialize_sqlite_database_backends>( let transaction_backend = TransactionServiceSqliteDatabase::new(connection.clone(), wallet_backend.cipher()); let output_manager_backend = OutputManagerSqliteDatabase::new(connection.clone(), wallet_backend.cipher()); let contacts_backend = ContactsServiceSqliteDatabase::init(connection.clone()); - let key_manager_backend = KeyManagerSqliteDatabase::new(connection, wallet_backend.cipher()).map_err(|e| { - error!(target: LOG_TARGET, "Error migrating key manager database: {:?}", e); - WalletStorageError::DatabaseMigrationError(e.to_string()) - })?; - + let key_manager_backend = KeyManagerSqliteDatabase::init(connection, wallet_backend.cipher()); Ok(( wallet_backend, transaction_backend, diff --git a/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs b/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs index 02f4c573c7..93ce9f6b27 100644 --- a/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs +++ b/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs @@ -33,6 +33,7 @@ use diesel::{prelude::*, result::Error as DieselError, SqliteConnection}; use log::*; use tari_common_sqlite::{sqlite_connection_pool::PooledDbConnection, util::diesel_ext::ExpectedRowsExtension}; use tari_common_types::{ + encryption::{decrypt_bytes_integral_nonce, encrypt_bytes_integral_nonce, Encryptable}, tari_address::TariAddress, transaction::{ TransactionConversionError, @@ -69,7 +70,6 @@ use crate::{ }, }, }, - util::encryption::{decrypt_bytes_integral_nonce, encrypt_bytes_integral_nonce, Encryptable}, }; const LOG_TARGET: &str = "wallet::transaction_service::database::wallet"; @@ -2256,6 +2256,7 @@ mod test { use tari_common::configuration::Network; use tari_common_sqlite::sqlite_connection_pool::SqliteConnectionPool; use tari_common_types::{ + encryption::Encryptable, tari_address::TariAddress, transaction::{TransactionDirection, TransactionStatus, TxId}, types::{PrivateKey, PublicKey, Signature}, @@ -2292,7 +2293,6 @@ mod test { UpdateCompletedTransactionSql, }, }, - util::encryption::Encryptable, }; #[test] diff --git a/base_layer/wallet/src/types.rs b/base_layer/wallet/src/types.rs index 8e5fd34f45..581732ae1d 100644 --- a/base_layer/wallet/src/types.rs +++ b/base_layer/wallet/src/types.rs @@ -26,9 +26,6 @@ use tari_crypto::{hash::blake2::Blake256, hash_domain, hasher}; use crate::error::WalletError; -/// Specify the Hash function used by the key manager -pub type KeyDigest = Blake256; - pub(crate) trait PersistentKeyManager { fn create_and_store_new(&mut self) -> Result; } diff --git a/base_layer/wallet/src/util/mod.rs b/base_layer/wallet/src/util/mod.rs index fce0d924d6..8f3ab61a3e 100644 --- a/base_layer/wallet/src/util/mod.rs +++ b/base_layer/wallet/src/util/mod.rs @@ -21,7 +21,6 @@ // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. pub mod burn_proof; -pub mod encryption; pub mod one_sided; pub mod wallet_identity; pub mod watch; diff --git a/base_layer/wallet/src/wallet.rs b/base_layer/wallet/src/wallet.rs index 60ae3ed301..ad56e0594c 100644 --- a/base_layer/wallet/src/wallet.rs +++ b/base_layer/wallet/src/wallet.rs @@ -62,6 +62,7 @@ use tari_crypto::{ use tari_key_manager::{ cipher_seed::CipherSeed, key_manager::KeyManager, + key_manager_service::{storage::database::KeyManagerBackend, KeyDigest, KeyManagerHandle, KeyManagerInitializer}, mnemonic::{Mnemonic, MnemonicLanguage}, SeedWords, }; @@ -84,7 +85,6 @@ use crate::{ connectivity_service::{WalletConnectivityHandle, WalletConnectivityInitializer, WalletConnectivityInterface}, consts, error::{WalletError, WalletStorageError}, - key_manager_service::{storage::database::KeyManagerBackend, KeyManagerHandle, KeyManagerInitializer}, output_manager_service::{ error::OutputManagerError, handle::OutputManagerHandle, @@ -100,7 +100,6 @@ use crate::{ storage::database::TransactionBackend, TransactionServiceInitializer, }, - types::KeyDigest, util::wallet_identity::WalletIdentity, utxo_scanner_service::{handle::UtxoScannerHandle, initializer::UtxoScannerServiceInitializer, RECOVERY_KEY}, }; diff --git a/base_layer/wallet/tests/key_manager_service_tests/service.rs b/base_layer/wallet/tests/key_manager_service_tests/service.rs index 1cd0744817..d5ce5d36f0 100644 --- a/base_layer/wallet/tests/key_manager_service_tests/service.rs +++ b/base_layer/wallet/tests/key_manager_service_tests/service.rs @@ -24,12 +24,14 @@ use std::mem::size_of; use chacha20poly1305::{Key, KeyInit, XChaCha20Poly1305}; use rand::{rngs::OsRng, RngCore}; -use tari_key_manager::cipher_seed::CipherSeed; -use tari_wallet::key_manager_service::{ - storage::{database::KeyManagerDatabase, sqlite_db::KeyManagerSqliteDatabase}, - AddResult, - KeyManagerHandle, - KeyManagerInterface, +use tari_key_manager::{ + cipher_seed::CipherSeed, + key_manager_service::{ + storage::{database::KeyManagerDatabase, sqlite_db::KeyManagerSqliteDatabase}, + AddResult, + KeyManagerHandle, + KeyManagerInterface, + }, }; use crate::support::data::get_temp_sqlite_database_connection; @@ -44,7 +46,7 @@ async fn get_key_at_test_with_encryption() { let db_cipher = XChaCha20Poly1305::new(key_ga); let key_manager = KeyManagerHandle::new( cipher, - KeyManagerDatabase::new(KeyManagerSqliteDatabase::new(connection, db_cipher).unwrap()), + KeyManagerDatabase::new(KeyManagerSqliteDatabase::init(connection, db_cipher)), ); key_manager.add_new_branch("branch1").await.unwrap(); let key_1 = key_manager.get_next_key("branch1").await.unwrap(); @@ -72,7 +74,7 @@ async fn key_manager_multiple_branches() { let key_manager = KeyManagerHandle::new( cipher, - KeyManagerDatabase::new(KeyManagerSqliteDatabase::new(connection, db_cipher).unwrap()), + KeyManagerDatabase::new(KeyManagerSqliteDatabase::init(connection, db_cipher)), ); assert_eq!( key_manager.add_new_branch("branch1").await.unwrap(), @@ -114,7 +116,7 @@ async fn key_manager_find_index() { let key_manager = KeyManagerHandle::new( cipher, - KeyManagerDatabase::new(KeyManagerSqliteDatabase::new(connection, db_cipher).unwrap()), + KeyManagerDatabase::new(KeyManagerSqliteDatabase::init(connection, db_cipher)), ); key_manager.add_new_branch("branch1").await.unwrap(); let _next_key = key_manager.get_next_key("branch1").await.unwrap(); @@ -137,7 +139,7 @@ async fn key_manager_update_current_key_index_if_higher() { let key_manager = KeyManagerHandle::new( cipher, - KeyManagerDatabase::new(KeyManagerSqliteDatabase::new(connection, db_cipher).unwrap()), + KeyManagerDatabase::new(KeyManagerSqliteDatabase::init(connection, db_cipher)), ); key_manager.add_new_branch("branch1").await.unwrap(); let _next_key_result = key_manager.get_next_key("branch1").await.unwrap(); @@ -170,7 +172,7 @@ async fn key_manager_test_index() { let key_manager = KeyManagerHandle::new( cipher, - KeyManagerDatabase::new(KeyManagerSqliteDatabase::new(connection, db_cipher).unwrap()), + KeyManagerDatabase::new(KeyManagerSqliteDatabase::init(connection, db_cipher)), ); key_manager.add_new_branch("branch1").await.unwrap(); key_manager.add_new_branch("branch2").await.unwrap(); diff --git a/base_layer/wallet/tests/output_manager_service_tests/service.rs b/base_layer/wallet/tests/output_manager_service_tests/service.rs index 07afceae51..933bf44aa2 100644 --- a/base_layer/wallet/tests/output_manager_service_tests/service.rs +++ b/base_layer/wallet/tests/output_manager_service_tests/service.rs @@ -54,7 +54,20 @@ use tari_crypto::{ commitment::HomomorphicCommitmentFactory, keys::{PublicKey as PublicKeyTrait, SecretKey}, }; -use tari_key_manager::{cipher_seed::CipherSeed, mnemonic::Mnemonic, SeedWords}; +use tari_key_manager::{ + cipher_seed::CipherSeed, + key_manager_service::{ + storage::{ + database::{KeyManagerBackend, KeyManagerDatabase}, + sqlite_db::KeyManagerSqliteDatabase, + }, + KeyManagerHandle, + KeyManagerInterface, + KeyManagerMock, + }, + mnemonic::Mnemonic, + SeedWords, +}; use tari_script::{inputs, script, TariScript}; use tari_service_framework::reply_channel; use tari_shutdown::Shutdown; @@ -65,15 +78,6 @@ use tari_wallet::{ service::BaseNodeState, }, connectivity_service::{create_wallet_connectivity_mock, WalletConnectivityMock}, - key_manager_service::{ - storage::{ - database::{KeyManagerBackend, KeyManagerDatabase}, - sqlite_db::KeyManagerSqliteDatabase, - }, - KeyManagerHandle, - KeyManagerInterface, - KeyManagerMock, - }, output_manager_service::{ config::OutputManagerServiceConfig, error::{OutputManagerError, OutputManagerStorageError}, @@ -340,7 +344,7 @@ async fn fee_estimate() { let cipher = XChaCha20Poly1305::new(key_ga); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let factories = CryptoFactories::default(); let mut oms = setup_output_manager_service(backend, ks_backend, true).await; @@ -757,7 +761,7 @@ async fn send_not_enough_funds() { let (connection, _tempdir) = get_temp_sqlite_database_connection(); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let mut oms = setup_output_manager_service(backend, ks_backend, true).await; let num_outputs = 20; @@ -802,7 +806,7 @@ async fn send_no_change() { let cipher = XChaCha20Poly1305::new(key_ga); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let mut oms = setup_output_manager_service(backend, ks_backend, true).await; @@ -880,7 +884,7 @@ async fn send_not_enough_for_change() { let cipher = XChaCha20Poly1305::new(key_ga); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let mut oms = setup_output_manager_service(backend, ks_backend, true).await; @@ -947,7 +951,7 @@ async fn cancel_transaction() { let cipher = XChaCha20Poly1305::new(key_ga); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let mut oms = setup_output_manager_service(backend, ks_backend, true).await; @@ -1004,7 +1008,7 @@ async fn cancel_transaction_and_reinstate_inbound_tx() { let cipher = XChaCha20Poly1305::new(key_ga); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let mut oms = setup_output_manager_service(backend, ks_backend, true).await; @@ -1047,7 +1051,7 @@ async fn test_get_balance() { let cipher = XChaCha20Poly1305::new(key_ga); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let mut oms = setup_output_manager_service(backend, ks_backend, true).await; @@ -1113,7 +1117,7 @@ async fn sending_transaction_persisted_while_offline() { let cipher = XChaCha20Poly1305::new(key_ga); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let mut oms = setup_output_manager_service(backend.clone(), ks_backend.clone(), true).await; @@ -1204,7 +1208,7 @@ async fn coin_split_with_change() { let cipher = XChaCha20Poly1305::new(key_ga); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let mut oms = setup_output_manager_service(backend, ks_backend, true).await; let val1 = 6_000 * uT; @@ -1250,7 +1254,7 @@ async fn coin_split_no_change() { let cipher = XChaCha20Poly1305::new(key_ga); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let mut oms = setup_output_manager_service(backend, ks_backend, true).await; let fee_per_gram = MicroTari::from(4); @@ -1296,7 +1300,7 @@ async fn handle_coinbase_with_bulletproofs_rewinding() { let cipher = XChaCha20Poly1305::new(key_ga); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let mut oms = setup_output_manager_service(backend, ks_backend, true).await; let reward1 = MicroTari::from(1000); @@ -1376,7 +1380,7 @@ async fn test_txo_validation() { let cipher = XChaCha20Poly1305::new(key_ga); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let oms_db = backend.clone(); let mut oms = setup_output_manager_service(backend, ks_backend, true).await; @@ -1938,7 +1942,7 @@ async fn test_txo_revalidation() { let (connection, _tempdir) = get_temp_sqlite_database_connection(); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let mut oms = setup_output_manager_service(backend, ks_backend, true).await; @@ -2110,7 +2114,7 @@ async fn test_get_status_by_tx_id() { let cipher = XChaCha20Poly1305::new(key_ga); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let mut oms = setup_output_manager_service(backend, ks_backend, true).await; @@ -2151,7 +2155,7 @@ async fn scan_for_recovery_test() { let cipher = XChaCha20Poly1305::new(key_ga); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let mut oms = setup_output_manager_service(backend.clone(), ks_backend, true).await; const NUM_REWINDABLE: usize = 5; @@ -2276,7 +2280,7 @@ async fn recovered_output_key_not_in_keychain() { let cipher = XChaCha20Poly1305::new(key_ga); let backend = OutputManagerSqliteDatabase::new(connection.clone(), cipher.clone()); - let ks_backend = KeyManagerSqliteDatabase::new(connection, cipher).unwrap(); + let ks_backend = KeyManagerSqliteDatabase::init(connection, cipher); let mut oms = setup_output_manager_service(backend.clone(), ks_backend, true).await; let (_ti, uo) = make_input(&mut OsRng, MicroTari::from(1000u64), &factories.commitment).await; diff --git a/base_layer/wallet/tests/transaction_service_tests/service.rs b/base_layer/wallet/tests/transaction_service_tests/service.rs index a296a227dc..b299f15990 100644 --- a/base_layer/wallet/tests/transaction_service_tests/service.rs +++ b/base_layer/wallet/tests/transaction_service_tests/service.rs @@ -96,7 +96,10 @@ use tari_crypto::{ hash::blake2::Blake256, keys::{PublicKey as PK, SecretKey as SK}, }; -use tari_key_manager::cipher_seed::CipherSeed; +use tari_key_manager::{ + cipher_seed::CipherSeed, + key_manager_service::{storage::sqlite_db::KeyManagerSqliteDatabase, KeyManagerInitializer, KeyManagerMock}, +}; use tari_p2p::{comms_connector::pubsub_connector, domain_message::DomainMessage, Network}; use tari_script::{inputs, one_sided_payment_script, script, ExecutionStack, TariScript}; use tari_service_framework::{reply_channel, RegisterHandle, StackBuilder}; @@ -112,7 +115,6 @@ use tari_wallet::{ WalletConnectivityInterface, WalletConnectivityMock, }, - key_manager_service::{storage::sqlite_db::KeyManagerSqliteDatabase, KeyManagerInitializer, KeyManagerMock}, output_manager_service::{ config::OutputManagerServiceConfig, handle::{OutputManagerEvent, OutputManagerHandle}, @@ -198,7 +200,7 @@ async fn setup_transaction_service>( let ts_backend = TransactionServiceSqliteDatabase::new(db_connection.clone(), cipher.clone()); let oms_backend = OutputManagerSqliteDatabase::new(db_connection.clone(), cipher.clone()); - let kms_backend = KeyManagerSqliteDatabase::new(db_connection, cipher).unwrap(); + let kms_backend = KeyManagerSqliteDatabase::init(db_connection, cipher); let wallet_identity = WalletIdentity::new(node_identity, Network::LocalNet); let cipher = CipherSeed::new(); @@ -207,7 +209,7 @@ async fn setup_transaction_service>( .add_initializer(RegisterHandle::new(comms.connectivity())) .add_initializer(OutputManagerServiceInitializer::< OutputManagerSqliteDatabase, - KeyManagerSqliteDatabase, + KeyManagerSqliteDatabase, >::new( OutputManagerServiceConfig::default(), oms_backend, diff --git a/base_layer/wallet/tests/wallet.rs b/base_layer/wallet/tests/wallet.rs index bb22db00a5..c7e91a1aca 100644 --- a/base_layer/wallet/tests/wallet.rs +++ b/base_layer/wallet/tests/wallet.rs @@ -56,7 +56,12 @@ use tari_core::{ }, }; use tari_crypto::keys::{PublicKey as PublicKeyTrait, SecretKey}; -use tari_key_manager::{cipher_seed::CipherSeed, mnemonic::Mnemonic, SeedWords}; +use tari_key_manager::{ + cipher_seed::CipherSeed, + key_manager_service::storage::sqlite_db::KeyManagerSqliteDatabase, + mnemonic::Mnemonic, + SeedWords, +}; use tari_p2p::{ auto_update::AutoUpdateConfig, comms_connector::InboundDomainConnector, @@ -74,7 +79,6 @@ use tari_test_utils::{collect_recv, comms_and_services::get_next_memory_address, use tari_utilities::{Hidden, SafePassword}; use tari_wallet::{ error::{WalletError, WalletStorageError}, - key_manager_service::storage::sqlite_db::KeyManagerSqliteDatabase, output_manager_service::storage::sqlite_db::OutputManagerSqliteDatabase, storage::{ database::{DbKeyValuePair, WalletBackend, WalletDatabase, WriteOperation}, @@ -712,7 +716,7 @@ async fn test_import_utxo() { TransactionServiceSqliteDatabase::new(connection.clone(), cipher.clone()), output_manager_backend, ContactsServiceSqliteDatabase::init(connection.clone()), - KeyManagerSqliteDatabase::new(connection.clone(), cipher.clone()).unwrap(), + KeyManagerSqliteDatabase::init(connection.clone(), cipher.clone()), shutdown.to_signal(), CipherSeed::new(), )