v0.2.6-pre.008
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
// file: crates/ksp-app-wallet-desk/src/app_state.rs
|
||||
// version: 8
|
||||
// version: 9
|
||||
|
||||
//! Shared backend state owned by the Wallet Desk Tauri application.
|
||||
|
||||
@@ -11,6 +11,7 @@ pub(crate) struct AppState {
|
||||
splash_sequence_started: std::sync::atomic::AtomicBool,
|
||||
transport_runtime: crate::TransportRuntime,
|
||||
wallet_config_startup: crate::WalletConfigStartup,
|
||||
wallet_import_source: std::sync::Mutex<std::option::Option<crate::PendingWalletImport>>,
|
||||
wallet_session: std::sync::Mutex<crate::WalletSession>,
|
||||
}
|
||||
|
||||
@@ -69,6 +70,7 @@ impl AppState {
|
||||
splash_sequence_started: std::sync::atomic::AtomicBool::new(false),
|
||||
transport_runtime,
|
||||
wallet_config_startup,
|
||||
wallet_import_source: std::sync::Mutex::new(std::option::Option::None),
|
||||
wallet_session: std::sync::Mutex::new(crate::WalletSession::no_selection()),
|
||||
});
|
||||
}
|
||||
@@ -124,7 +126,7 @@ impl AppState {
|
||||
effective_wallets_directory_created_on_startup: self.wallet_config_startup.effective_directory_created_on_startup(),
|
||||
fallback_logging_active: runtime.fallback_active,
|
||||
root_wallets_directory_created_on_startup: self.wallet_config_startup.root_directory_created_on_startup(),
|
||||
shell_phase: "pre.007-wallet-balance".to_owned(),
|
||||
shell_phase: "pre.008-wallet-import".to_owned(),
|
||||
startup_diagnostic: runtime.startup_diagnostic.clone(),
|
||||
transport_available_endpoint_count,
|
||||
transport_clusters: self.transport_runtime.clusters(),
|
||||
@@ -220,6 +222,102 @@ impl AppState {
|
||||
return std::result::Result::Ok(dto);
|
||||
}
|
||||
|
||||
/// Replaces any previous native-picker transfer source with one newly validated bounded Rust-only source.
|
||||
pub(crate) async fn stage_import_source(
|
||||
&self,
|
||||
source: std::path::PathBuf,
|
||||
format: crate::WalletTransferFormatDto,
|
||||
) -> ksp_core_lib::Result<crate::WalletTransferInspectionDto> {
|
||||
let staged = crate::stage_wallet_import_source(source, format).await;
|
||||
let staged = match staged {
|
||||
std::result::Result::Ok(value) => value,
|
||||
std::result::Result::Err(error) => return std::result::Result::Err(error),
|
||||
};
|
||||
let dto = staged.safe_projection();
|
||||
let slot = self.wallet_import_source.lock();
|
||||
let mut slot = match slot {
|
||||
std::result::Result::Ok(value) => value,
|
||||
std::result::Result::Err(_) => return std::result::Result::Err(import_source_lock_error()),
|
||||
};
|
||||
let previous = std::mem::replace(&mut *slot, std::option::Option::Some(staged));
|
||||
drop(previous);
|
||||
ksp_logging_lib::info!(target: crate::TRACING_TARGET, domain = crate::TRACING_DOMAIN_WALLET_IMPORT, transfer_format = dto.format.code(), "Wallet transfer source inspected and staged in Rust-only memory");
|
||||
return std::result::Result::Ok(dto);
|
||||
}
|
||||
|
||||
/// Clears any staged external transfer source and zeroizes its bounded secret bytes.
|
||||
pub(crate) fn clear_import_source(&self) -> ksp_core_lib::Result<()> {
|
||||
let slot = self.wallet_import_source.lock();
|
||||
let mut slot = match slot {
|
||||
std::result::Result::Ok(value) => value,
|
||||
std::result::Result::Err(_) => return std::result::Result::Err(import_source_lock_error()),
|
||||
};
|
||||
let previous = slot.take();
|
||||
drop(previous);
|
||||
return std::result::Result::Ok(());
|
||||
}
|
||||
|
||||
/// Imports the staged Solana transfer bytes into a new root-scoped native Wallet and retains the returned OWNER handle only in Rust.
|
||||
pub(crate) async fn import_wallet(&self, request: crate::WalletImportRequestDto) -> ksp_core_lib::Result<crate::WalletAuthorizedDto> {
|
||||
let pending = {
|
||||
let slot = self.wallet_import_source.lock();
|
||||
let mut slot = match slot {
|
||||
std::result::Result::Ok(value) => value,
|
||||
std::result::Result::Err(_) => return std::result::Result::Err(import_source_lock_error()),
|
||||
};
|
||||
slot.take()
|
||||
};
|
||||
let pending = match pending {
|
||||
std::option::Option::Some(value) => value,
|
||||
std::option::Option::None => {
|
||||
return std::result::Result::Err(ksp_core_lib::Error::new(
|
||||
crate::ERROR_CODE_WALLET_IMPORT_SOURCE_MISSING,
|
||||
"Wallet import requires one inspected native-picker transfer source",
|
||||
));
|
||||
},
|
||||
};
|
||||
let deselected = self.deselect_wallet();
|
||||
if let std::result::Result::Err(error) = deselected {
|
||||
return std::result::Result::Err(error);
|
||||
}
|
||||
let crate::WalletImportRequestDto { alias, filename, initial_note, owner_password, view_password } = request;
|
||||
let root = self.wallet_inventory_root().to_path_buf();
|
||||
let destination = crate::new_wallet_destination(root.as_path(), filename.as_str());
|
||||
let destination = match destination {
|
||||
std::result::Result::Ok(value) => value,
|
||||
std::result::Result::Err(error) => return std::result::Result::Err(error),
|
||||
};
|
||||
let view_enabled = view_password.is_some();
|
||||
let owner_password = ksp_wallet_lib::OwnerPassword::new(owner_password);
|
||||
let view_password = view_password.map(ksp_wallet_lib::ViewPassword::new);
|
||||
let alias = normalize_optional_text(alias);
|
||||
let note = normalize_optional_text(initial_note);
|
||||
let note_texts = note.into_iter().collect::<std::vec::Vec<_>>();
|
||||
let metadata = ksp_wallet_lib::WalletCreateMetadataV1::new(alias, note_texts);
|
||||
let transfer_format = pending.wallet_format();
|
||||
ksp_logging_lib::debug!(target: crate::TRACING_TARGET, domain = crate::TRACING_DOMAIN_WALLET_IMPORT, wallet_id = filename.as_str(), transfer_format = transfer_format.code(), view_enabled, "Wallet transfer import requested under effective Config root");
|
||||
let imported =
|
||||
ksp_wallet_lib::import_wallet_transfer_v1(destination.as_path(), pending.source_bytes(), transfer_format, owner_password, view_password, metadata)
|
||||
.await;
|
||||
let owner = match imported {
|
||||
std::result::Result::Ok(value) => value,
|
||||
std::result::Result::Err(error) => {
|
||||
ksp_logging_lib::warn!(target: crate::TRACING_TARGET, domain = crate::TRACING_DOMAIN_WALLET_IMPORT, wallet_id = filename.as_str(), transfer_format = transfer_format.code(), error_domain = error.code().domain(), error_code = error.code().code(), "Wallet transfer import failed");
|
||||
return std::result::Result::Err(error);
|
||||
},
|
||||
};
|
||||
let configured_secret_candidate_count = self.secret_candidate_count_or_zero(filename.as_str());
|
||||
let dto = crate::owner_projection(filename.as_str(), view_enabled, configured_secret_candidate_count, &owner);
|
||||
let session = self.wallet_session.lock();
|
||||
let mut session = match session {
|
||||
std::result::Result::Ok(value) => value,
|
||||
std::result::Result::Err(_) => return std::result::Result::Err(session_lock_error()),
|
||||
};
|
||||
*session = crate::WalletSession::Owner { wallet_id: filename.clone(), path: destination, wallet: std::boxed::Box::new(owner) };
|
||||
ksp_logging_lib::info!(target: crate::TRACING_TARGET, domain = crate::TRACING_DOMAIN_WALLET_IMPORT, wallet_id = filename.as_str(), transfer_format = transfer_format.code(), view_enabled, "Wallet transfer imported and OWNER session opened");
|
||||
return std::result::Result::Ok(dto);
|
||||
}
|
||||
|
||||
/// Opens the selected locked Wallet with one manual VIEW password supplied frontend -> Rust.
|
||||
pub(crate) async fn unlock_wallet_view_manual(&self, request: crate::WalletUnlockRequestDto) -> ksp_core_lib::Result<crate::WalletAuthorizedDto> {
|
||||
let context = self.begin_unlock_operation(crate::WalletUnlockCapability::View);
|
||||
@@ -656,6 +754,10 @@ fn normalize_optional_text(value: std::option::Option<String>) -> std::option::O
|
||||
});
|
||||
}
|
||||
|
||||
fn import_source_lock_error() -> ksp_core_lib::Error {
|
||||
return ksp_core_lib::Error::new(crate::ERROR_CODE_APP_STATE_LOCK_FAILED, "Wallet Desk staged import source lock is poisoned");
|
||||
}
|
||||
|
||||
fn session_lock_error() -> ksp_core_lib::Error {
|
||||
return ksp_core_lib::Error::new(crate::ERROR_CODE_APP_STATE_LOCK_FAILED, "Wallet Desk Wallet session state lock is poisoned");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// file: crates/ksp-app-wallet-desk/src/constants.rs
|
||||
// version: 6
|
||||
// version: 7
|
||||
|
||||
//! Logging targets, domains and composite component identifiers owned by Wallet Desk.
|
||||
|
||||
@@ -19,6 +19,8 @@ pub(crate) const TRACING_DOMAIN_SHELL: &str = "wallet.shell";
|
||||
pub(crate) const TRACING_DOMAIN_TRANSPORT: &str = "wallet.transport";
|
||||
/// Structured domain used while preparing Wallet filesystem roots.
|
||||
pub(crate) const TRACING_DOMAIN_WALLET_CONFIG: &str = "wallet.config";
|
||||
/// Structured domain used by native-picker Wallet transfer import operations.
|
||||
pub(crate) const TRACING_DOMAIN_WALLET_IMPORT: &str = "wallet.import";
|
||||
/// Structured domain used while enumerating and inspecting locked Wallet files.
|
||||
pub(crate) const TRACING_DOMAIN_WALLET_INVENTORY: &str = "wallet.inventory";
|
||||
/// Structured domain used by Config-owned Wallet password candidate operations.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// file: crates/ksp-app-wallet-desk/src/errors.rs
|
||||
// version: 6
|
||||
// version: 7
|
||||
|
||||
//! Application-local error codes for Wallet Desk composition and desktop runtime surfaces.
|
||||
|
||||
@@ -34,6 +34,10 @@ pub(crate) const ERROR_CODE_WALLET_DIRECTORY_INVALID: ksp_core_lib::ErrorCode =
|
||||
/// Wallet Desk could not inspect or create the configured Wallet directory tree.
|
||||
pub(crate) const ERROR_CODE_WALLET_DIRECTORY_PREPARE_FAILED: ksp_core_lib::ErrorCode =
|
||||
ksp_core_lib::ErrorCode::new("wallet_desk", "wallet_directory_prepare_failed");
|
||||
/// A native-picker Wallet transfer source is not a supported regular file or cannot be staged safely.
|
||||
pub(crate) const ERROR_CODE_WALLET_IMPORT_SOURCE_INVALID: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet_desk", "wallet_import_source_invalid");
|
||||
/// Wallet import was requested without one previously inspected native-picker source.
|
||||
pub(crate) const ERROR_CODE_WALLET_IMPORT_SOURCE_MISSING: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet_desk", "wallet_import_source_missing");
|
||||
/// Wallet Desk cannot enumerate or inspect its effective Wallet inventory directory.
|
||||
pub(crate) const ERROR_CODE_WALLET_INVENTORY_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet_desk", "wallet_inventory_failed");
|
||||
/// No effective Config-owned Wallet password candidate is available for the explicit configured-secret unlock action.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// file: crates/ksp-app-wallet-desk/src/lib.rs
|
||||
// version: 7
|
||||
// version: 8
|
||||
|
||||
//! Tauri desktop application shell for KSP Wallet management and inspection.
|
||||
|
||||
@@ -21,6 +21,7 @@ mod tw_main;
|
||||
mod tw_splash;
|
||||
mod wallet_balance;
|
||||
mod wallet_config;
|
||||
mod wallet_import;
|
||||
mod wallet_inventory;
|
||||
mod wallet_secrets;
|
||||
mod wallet_session;
|
||||
@@ -56,6 +57,8 @@ pub(crate) use self::constants::TRACING_DOMAIN_SHELL;
|
||||
pub(crate) use self::constants::TRACING_DOMAIN_TRANSPORT;
|
||||
/// Structured domain used while preparing Wallet filesystem roots.
|
||||
pub(crate) use self::constants::TRACING_DOMAIN_WALLET_CONFIG;
|
||||
/// Structured domain used by native-picker Wallet transfer import operations.
|
||||
pub(crate) use self::constants::TRACING_DOMAIN_WALLET_IMPORT;
|
||||
/// Structured domain used while enumerating and inspecting locked Wallet files.
|
||||
pub(crate) use self::constants::TRACING_DOMAIN_WALLET_INVENTORY;
|
||||
/// Structured domain used by Config-owned Wallet password candidate operations.
|
||||
@@ -106,6 +109,10 @@ pub(crate) use self::errors::ERROR_CODE_WALLET_AUTHORIZATION_REQUIRED;
|
||||
pub(crate) use self::errors::ERROR_CODE_WALLET_DIRECTORY_INVALID;
|
||||
/// Wallet Desk could not inspect or create the configured Wallet directory tree.
|
||||
pub(crate) use self::errors::ERROR_CODE_WALLET_DIRECTORY_PREPARE_FAILED;
|
||||
/// Native-picker transfer source is invalid or cannot be staged.
|
||||
pub(crate) use self::errors::ERROR_CODE_WALLET_IMPORT_SOURCE_INVALID;
|
||||
/// Wallet import has no staged native-picker source.
|
||||
pub(crate) use self::errors::ERROR_CODE_WALLET_IMPORT_SOURCE_MISSING;
|
||||
/// Wallet inventory filesystem operation failed.
|
||||
pub(crate) use self::errors::ERROR_CODE_WALLET_INVENTORY_FAILED;
|
||||
/// No effective Config-owned Wallet password candidate is available.
|
||||
@@ -146,6 +153,18 @@ pub(crate) use self::wallet_balance::format_lamports_as_sol;
|
||||
pub(crate) use self::wallet_config::WalletConfigStartup;
|
||||
/// Resolves the composite-selected Wallet Config and prepares its application-owned directory tree.
|
||||
pub(crate) use self::wallet_config::initialize_wallet_config;
|
||||
/// Rust-only staged import source containing bounded zeroizing transfer bytes.
|
||||
pub(crate) use self::wallet_import::PendingWalletImport;
|
||||
/// Import request whose new native Wallet credentials move frontend -> Rust only.
|
||||
pub(crate) use self::wallet_import::WalletImportRequestDto;
|
||||
/// Native picker request containing only the expected transfer format.
|
||||
pub(crate) use self::wallet_import::WalletImportSourceRequestDto;
|
||||
/// Safe transfer format DTO used by the import picker.
|
||||
pub(crate) use self::wallet_import::WalletTransferFormatDto;
|
||||
/// Safe inspection projection for one staged external transfer source.
|
||||
pub(crate) use self::wallet_import::WalletTransferInspectionDto;
|
||||
/// Loads and validates one native-picker import source into bounded zeroizing Rust memory.
|
||||
pub(crate) use self::wallet_import::stage_wallet_import_source;
|
||||
/// Safe locked Wallet projection returned after selection.
|
||||
pub(crate) use self::wallet_inventory::LockedWalletDto;
|
||||
/// Locked inspection outcome exposed by Wallet inventory rows in crate unit tests.
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
// file: crates/ksp-app-wallet-desk/src/tauri.rs
|
||||
// version: 5
|
||||
// version: 6
|
||||
|
||||
//! Tauri runtime assembly for the KSP wallet desktop application.
|
||||
|
||||
use tauri_plugin_dialog::DialogExt; // rust-rules: trait-import
|
||||
|
||||
/// Runs the Wallet Desk application.
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run(arguments: &[std::ffi::OsString]) -> ksp_core_lib::Result<()> {
|
||||
@@ -32,16 +34,19 @@ fn configure_state(builder: tauri::Builder<tauri::Wry>, app_state: crate::AppSta
|
||||
|
||||
fn configure_plugins(builder: tauri::Builder<tauri::Wry>) -> tauri::Builder<tauri::Wry> {
|
||||
let tracing_plugin = tauri_plugin_tracing::Builder::new().build::<tauri::Wry>();
|
||||
return builder.plugin(tracing_plugin);
|
||||
return builder.plugin(tauri_plugin_dialog::init()).plugin(tracing_plugin);
|
||||
}
|
||||
|
||||
#[allow(clippy::question_mark_used)] // Tauri generates the question-mark operator internally for async command dispatch.
|
||||
fn configure_commands(builder: tauri::Builder<tauri::Wry>) -> tauri::Builder<tauri::Wry> {
|
||||
return builder.invoke_handler(tauri::generate_handler![
|
||||
clear_import_source,
|
||||
create_wallet,
|
||||
deselect_wallet,
|
||||
emit_frontend_log,
|
||||
get_runtime_status,
|
||||
import_wallet,
|
||||
inspect_import_source,
|
||||
list_wallets,
|
||||
lock_wallet,
|
||||
refresh_wallet_balance,
|
||||
@@ -70,6 +75,15 @@ fn configure_setup(builder: tauri::Builder<tauri::Wry>) -> tauri::Builder<tauri:
|
||||
});
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn clear_import_source(state: tauri::State<'_, crate::AppState>) -> std::result::Result<(), crate::CommandErrorDto> {
|
||||
let result = state.clear_import_source();
|
||||
return match result {
|
||||
std::result::Result::Ok(()) => std::result::Result::Ok(()),
|
||||
std::result::Result::Err(error) => std::result::Result::Err(crate::CommandErrorDto::from_error(&error)),
|
||||
};
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn create_wallet(
|
||||
request: crate::WalletCreateRequestDto,
|
||||
@@ -109,6 +123,59 @@ fn get_runtime_status(state: tauri::State<'_, crate::AppState>) -> std::result::
|
||||
};
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn import_wallet(
|
||||
request: crate::WalletImportRequestDto,
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
) -> std::result::Result<crate::WalletAuthorizedDto, crate::CommandErrorDto> {
|
||||
let result = state.import_wallet(request).await;
|
||||
return match result {
|
||||
std::result::Result::Ok(value) => std::result::Result::Ok(value),
|
||||
std::result::Result::Err(error) => std::result::Result::Err(crate::CommandErrorDto::from_error(&error)),
|
||||
};
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn inspect_import_source(
|
||||
app: tauri::AppHandle,
|
||||
request: crate::WalletImportSourceRequestDto,
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
) -> std::result::Result<std::option::Option<crate::WalletTransferInspectionDto>, crate::CommandErrorDto> {
|
||||
let cleared = state.clear_import_source();
|
||||
if let std::result::Result::Err(error) = cleared {
|
||||
return std::result::Result::Err(crate::CommandErrorDto::from_error(&error));
|
||||
}
|
||||
let format = request.format;
|
||||
let extensions = [format.default_extension()];
|
||||
let selected = app
|
||||
.dialog()
|
||||
.file()
|
||||
.set_title("Select Solana keypair transfer source")
|
||||
.add_filter("Solana keypair transfer", &extensions)
|
||||
.blocking_pick_file();
|
||||
let selected = match selected {
|
||||
std::option::Option::Some(value) => value,
|
||||
std::option::Option::None => {
|
||||
ksp_logging_lib::debug!(target: crate::TRACING_TARGET, domain = crate::TRACING_DOMAIN_WALLET_IMPORT, transfer_format = format.code(), "Wallet import native picker cancelled");
|
||||
return std::result::Result::Ok(std::option::Option::None);
|
||||
},
|
||||
};
|
||||
let path = selected.into_path();
|
||||
let path = match path {
|
||||
std::result::Result::Ok(value) => value,
|
||||
std::result::Result::Err(_) => {
|
||||
let error =
|
||||
ksp_core_lib::Error::new(crate::ERROR_CODE_WALLET_IMPORT_SOURCE_INVALID, "Selected Wallet transfer source is not a local filesystem path");
|
||||
return std::result::Result::Err(crate::CommandErrorDto::from_error(&error));
|
||||
},
|
||||
};
|
||||
let result = state.stage_import_source(path, format).await;
|
||||
return match result {
|
||||
std::result::Result::Ok(value) => std::result::Result::Ok(std::option::Option::Some(value)),
|
||||
std::result::Result::Err(error) => std::result::Result::Err(crate::CommandErrorDto::from_error(&error)),
|
||||
};
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn refresh_wallet_balance(state: tauri::State<'_, crate::AppState>) -> std::result::Result<crate::WalletBalanceDto, crate::CommandErrorDto> {
|
||||
let result = state.refresh_wallet_balance().await;
|
||||
|
||||
190
crates/ksp-app-wallet-desk/src/wallet_import.rs
Normal file
190
crates/ksp-app-wallet-desk/src/wallet_import.rs
Normal file
@@ -0,0 +1,190 @@
|
||||
// file: crates/ksp-app-wallet-desk/src/wallet_import.rs
|
||||
// version: 1
|
||||
|
||||
//! Native-picker transfer import staging with bounded secret material kept only in Rust.
|
||||
|
||||
use tokio::io::AsyncReadExt; // rust-rules: trait-import
|
||||
use ts_rs::TS; // rust-rules: trait-import
|
||||
|
||||
/// Transfer format selected before opening the native import picker.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[ts(export, export_to = "../frontend/ts/bindings/ksp_app_wallet_desk/wallet_import/WalletTransferFormatDto.ts")]
|
||||
pub(crate) enum WalletTransferFormatDto {
|
||||
/// Standard Solana CLI keypair JSON array containing 64 byte values.
|
||||
SolanaCliJson,
|
||||
/// Canonical Base58 encoding of the complete 64-byte Solana keypair.
|
||||
SolanaKeypairBase58,
|
||||
}
|
||||
|
||||
impl WalletTransferFormatDto {
|
||||
/// Maps the desktop DTO to the stable Wallet transfer format.
|
||||
#[must_use]
|
||||
pub(crate) const fn wallet_format(self) -> ksp_wallet_lib::WalletTransferFormat {
|
||||
return match self {
|
||||
Self::SolanaCliJson => ksp_wallet_lib::WalletTransferFormat::SolanaCliJson,
|
||||
Self::SolanaKeypairBase58 => ksp_wallet_lib::WalletTransferFormat::SolanaKeypairBase58,
|
||||
};
|
||||
}
|
||||
|
||||
/// Returns the native picker extension used as a convenience filter.
|
||||
#[must_use]
|
||||
pub(crate) const fn default_extension(self) -> &'static str {
|
||||
return match self {
|
||||
Self::SolanaCliJson => "json",
|
||||
Self::SolanaKeypairBase58 => "txt",
|
||||
};
|
||||
}
|
||||
|
||||
/// Returns the stable transfer format code used by safe diagnostics.
|
||||
#[must_use]
|
||||
pub(crate) const fn code(self) -> &'static str {
|
||||
return match self {
|
||||
Self::SolanaCliJson => "solana_cli_json",
|
||||
Self::SolanaKeypairBase58 => "solana_keypair_base58",
|
||||
};
|
||||
}
|
||||
|
||||
const fn maximum_source_bytes(self) -> usize {
|
||||
return match self {
|
||||
Self::SolanaCliJson => ksp_wallet_lib::KSPWALLET_TRANSFER_MAX_SOLANA_CLI_JSON_BYTES,
|
||||
Self::SolanaKeypairBase58 => ksp_wallet_lib::KSPWALLET_TRANSFER_MAX_BASE58_BYTES,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Request that chooses only the transfer format; the source path comes from the native Rust picker.
|
||||
#[derive(serde::Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "../frontend/ts/bindings/ksp_app_wallet_desk/wallet_import/WalletImportSourceRequestDto.ts")]
|
||||
pub(crate) struct WalletImportSourceRequestDto {
|
||||
/// Transfer encoding expected for the selected external file.
|
||||
pub(crate) format: WalletTransferFormatDto,
|
||||
}
|
||||
|
||||
/// Safe projection returned after validating one native-picker import source.
|
||||
#[derive(Clone, serde::Serialize, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "../frontend/ts/bindings/ksp_app_wallet_desk/wallet_import/WalletTransferInspectionDto.ts")]
|
||||
pub(crate) struct WalletTransferInspectionDto {
|
||||
/// Transfer format used to validate the secret source.
|
||||
pub(crate) format: WalletTransferFormatDto,
|
||||
/// Public identity derived from the imported keypair.
|
||||
pub(crate) pubkey: String,
|
||||
/// Basename only; no parent path is ever projected.
|
||||
pub(crate) source_name: String,
|
||||
}
|
||||
|
||||
/// Import request whose new native Wallet credentials move frontend -> Rust only.
|
||||
#[derive(serde::Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "../frontend/ts/bindings/ksp_app_wallet_desk/wallet_import/WalletImportRequestDto.ts")]
|
||||
pub(crate) struct WalletImportRequestDto {
|
||||
/// Optional protected internal alias stored in the new native Wallet.
|
||||
pub(crate) alias: std::option::Option<String>,
|
||||
/// Root-scoped destination filename under the effective Wallet directory.
|
||||
pub(crate) filename: String,
|
||||
/// Optional first protected note stored in the imported Wallet.
|
||||
pub(crate) initial_note: std::option::Option<String>,
|
||||
/// New OWNER password transported only frontend -> Rust.
|
||||
pub(crate) owner_password: String,
|
||||
/// Optional new VIEW password; `None` keeps VIEW disabled.
|
||||
pub(crate) view_password: std::option::Option<String>,
|
||||
}
|
||||
|
||||
/// Rust-only staged transfer source. Secret bytes are bounded and zeroized on drop.
|
||||
pub(crate) struct PendingWalletImport {
|
||||
bytes: zeroize::Zeroizing<std::vec::Vec<u8>>,
|
||||
format: WalletTransferFormatDto,
|
||||
inspection: WalletTransferInspectionDto,
|
||||
}
|
||||
|
||||
impl PendingWalletImport {
|
||||
/// Returns the safe inspection projection without exposing source bytes or path.
|
||||
#[must_use]
|
||||
pub(crate) fn safe_projection(&self) -> WalletTransferInspectionDto {
|
||||
return self.inspection.clone();
|
||||
}
|
||||
|
||||
/// Returns the bounded secret transfer bytes for one immediate Wallet import operation.
|
||||
#[must_use]
|
||||
pub(crate) fn source_bytes(&self) -> &[u8] {
|
||||
return self.bytes.as_slice();
|
||||
}
|
||||
|
||||
/// Returns the stable Wallet transfer format corresponding to the staged source.
|
||||
#[must_use]
|
||||
pub(crate) const fn wallet_format(&self) -> ksp_wallet_lib::WalletTransferFormat {
|
||||
return self.format.wallet_format();
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads, bounds and validates one native-picker transfer source while retaining no external path.
|
||||
pub(crate) async fn stage_wallet_import_source(source: std::path::PathBuf, format: WalletTransferFormatDto) -> ksp_core_lib::Result<PendingWalletImport> {
|
||||
let metadata = tokio::fs::symlink_metadata(source.as_path()).await;
|
||||
let metadata = match metadata {
|
||||
std::result::Result::Ok(value) => value,
|
||||
std::result::Result::Err(error) => {
|
||||
return std::result::Result::Err(
|
||||
ksp_core_lib::Error::new(crate::ERROR_CODE_WALLET_IMPORT_SOURCE_INVALID, "Cannot inspect the selected Wallet transfer source")
|
||||
.with_source(error),
|
||||
);
|
||||
},
|
||||
};
|
||||
if metadata.file_type().is_symlink() || !metadata.is_file() {
|
||||
return std::result::Result::Err(ksp_core_lib::Error::new(
|
||||
crate::ERROR_CODE_WALLET_IMPORT_SOURCE_INVALID,
|
||||
"Selected Wallet transfer source must be one regular non-symlink file",
|
||||
));
|
||||
}
|
||||
let source_name = source.file_name().and_then(std::ffi::OsStr::to_str);
|
||||
let source_name = match source_name {
|
||||
std::option::Option::Some(value) if !value.is_empty() => value.to_owned(),
|
||||
_ => "selected-transfer".to_owned(),
|
||||
};
|
||||
let file = tokio::fs::File::open(source.as_path()).await;
|
||||
let file = match file {
|
||||
std::result::Result::Ok(value) => value,
|
||||
std::result::Result::Err(error) => {
|
||||
return std::result::Result::Err(
|
||||
ksp_core_lib::Error::new(crate::ERROR_CODE_WALLET_IMPORT_SOURCE_INVALID, "Cannot open the selected Wallet transfer source").with_source(error),
|
||||
);
|
||||
},
|
||||
};
|
||||
let maximum_source_bytes = format.maximum_source_bytes();
|
||||
let read_limit = maximum_source_bytes.saturating_add(1);
|
||||
let read_limit = u64::try_from(read_limit);
|
||||
let read_limit = match read_limit {
|
||||
std::result::Result::Ok(value) => value,
|
||||
std::result::Result::Err(error) => {
|
||||
return std::result::Result::Err(
|
||||
ksp_core_lib::Error::new(crate::ERROR_CODE_APP_STATE_INVALID, "Wallet transfer source bound exceeds platform range").with_source(error),
|
||||
);
|
||||
},
|
||||
};
|
||||
let mut reader = file.take(read_limit);
|
||||
let mut bytes = zeroize::Zeroizing::new(std::vec::Vec::with_capacity(maximum_source_bytes.saturating_add(1)));
|
||||
let read_result = reader.read_to_end(&mut *bytes).await;
|
||||
if let std::result::Result::Err(error) = read_result {
|
||||
return std::result::Result::Err(
|
||||
ksp_core_lib::Error::new(crate::ERROR_CODE_WALLET_IMPORT_SOURCE_INVALID, "Cannot read the selected Wallet transfer source").with_source(error),
|
||||
);
|
||||
}
|
||||
if bytes.len() > maximum_source_bytes {
|
||||
return std::result::Result::Err(ksp_core_lib::Error::new(
|
||||
crate::ERROR_CODE_WALLET_IMPORT_SOURCE_INVALID,
|
||||
"Selected Wallet transfer source exceeds the supported format bound",
|
||||
));
|
||||
}
|
||||
let inspection = ksp_wallet_lib::inspect_wallet_transfer(bytes.as_slice(), format.wallet_format());
|
||||
let inspection = match inspection {
|
||||
std::result::Result::Ok(value) => value,
|
||||
std::result::Result::Err(error) => return std::result::Result::Err(error),
|
||||
};
|
||||
let dto = WalletTransferInspectionDto { format, pubkey: inspection.pubkey().to_string(), source_name };
|
||||
return std::result::Result::Ok(PendingWalletImport { bytes, format, inspection: dto });
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../unit_tests/wallet_import.rs"]
|
||||
mod tests;
|
||||
Reference in New Issue
Block a user