v0.2.5-pre.010.fix.001

This commit is contained in:
2026-08-20 11:17:12 +02:00
parent 5bf9651038
commit c0b131bf6f
97 changed files with 2277 additions and 655 deletions

View File

@@ -1,90 +1,89 @@
// file: crates/ksp-wallet-lib/src/constants.rs
// version: 5
// version: 6
//! Wallet-owned constants.
/// Exact magic string required by every native `.kspwallet` document.
pub const KSPWALLET_MAGIC: &str = "KSPWALLET";
/// Native Wallet format version implemented by the V1 codec.
pub const KSPWALLET_FORMAT_VERSION_V1: u32 = 1;
/// Exact magic string required by every native `.kspwallet` document.
pub const KSPWALLET_MAGIC: &str = "KSPWALLET";
/// Maximum accepted `.kspwallet` document size before JSON parsing.
pub const KSPWALLET_MAX_FILE_BYTES: usize = 1024 * 1024;
/// Maximum accepted Solana CLI keypair JSON transfer size before parsing.
pub const KSPWALLET_TRANSFER_MAX_SOLANA_CLI_JSON_BYTES: usize = 1024;
/// Maximum accepted canonical Base58 keypair transfer size before decoding.
pub const KSPWALLET_TRANSFER_MAX_BASE58_BYTES: usize = 128;
/// Maximum protected alias size in UTF-8 bytes for metadata V1.
pub const KSPWALLET_V1_MAX_ALIAS_BYTES: usize = 256;
/// Maximum number of protected notes in metadata V1.
pub const KSPWALLET_V1_MAX_NOTES: usize = 64;
/// Maximum protected note text size in UTF-8 bytes for metadata V1.
pub const KSPWALLET_V1_MAX_NOTE_TEXT_BYTES: usize = 8 * 1024;
/// Maximum metadata plaintext size before V1 encryption.
pub const KSPWALLET_V1_MAX_METADATA_PLAINTEXT_BYTES: usize = 64 * 1024;
/// Maximum password size in exact UTF-8 input bytes.
pub const KSPWALLET_V1_MAX_PASSWORD_BYTES: usize = 1024;
/// Byte length of every V1 key-slot identifier.
pub const KSPWALLET_V1_SLOT_ID_BYTES: usize = 16;
/// Byte length of every protected metadata note identifier.
pub const KSPWALLET_V1_NOTE_ID_BYTES: usize = 16;
/// Byte length of an Ed25519 public key used as Wallet format authority.
pub const KSPWALLET_V1_ED25519_PUBLIC_KEY_BYTES: usize = 32;
/// Byte length of an Ed25519 detached state signature.
pub const KSPWALLET_V1_ED25519_SIGNATURE_BYTES: usize = 64;
/// Byte length of every Solana Ed25519 message signature returned by Wallet OWNER.
pub const KSPWALLET_SOLANA_SIGNATURE_BYTES: usize = 64;
/// Byte length of an XChaCha20-Poly1305 nonce.
pub const KSPWALLET_V1_XCHACHA_NONCE_BYTES: usize = 24;
/// Maximum accepted canonical Base58 keypair transfer size before decoding.
pub const KSPWALLET_TRANSFER_MAX_BASE58_BYTES: usize = 128;
/// Maximum accepted Solana CLI keypair JSON transfer size before parsing.
pub const KSPWALLET_TRANSFER_MAX_SOLANA_CLI_JSON_BYTES: usize = 1024;
/// Byte length of the Poly1305 authentication tag appended to each ciphertext.
pub const KSPWALLET_V1_AEAD_TAG_BYTES: usize = 16;
/// Argon2 version serialized by V1 key slots.
pub const KSPWALLET_V1_ARGON2_VERSION: u32 = 19;
/// Default Argon2id memory cost for newly created V1 key slots, calibrated on the 2026-08-19 operator benchmark.
pub const KSPWALLET_V1_DEFAULT_ARGON2_MEMORY_KIB: u32 = 65_536;
/// Default Argon2id iteration count for newly created V1 key slots.
pub const KSPWALLET_V1_DEFAULT_ARGON2_ITERATIONS: u32 = 3;
/// Default Argon2id memory cost for newly created V1 key slots, calibrated on the 2026-08-19 operator benchmark.
pub const KSPWALLET_V1_DEFAULT_ARGON2_MEMORY_KIB: u32 = 65_536;
/// Default Argon2id parallelism for newly created V1 key slots.
pub const KSPWALLET_V1_DEFAULT_ARGON2_PARALLELISM: u32 = 1;
/// Salt size generated independently for every newly created V1 key slot.
pub const KSPWALLET_V1_DEFAULT_KDF_SALT_BYTES: usize = 32;
/// Exact plaintext size of the V1 OWNER-control compartment.
pub const KSPWALLET_V1_OWNER_CONTROL_PLAINTEXT_BYTES: usize = 96;
/// Exact plaintext size of the V1 Solana secret compartment.
pub const KSPWALLET_V1_SECRET_PLAINTEXT_BYTES: usize = 64;
/// Minimum accepted Argon2 salt size in bytes.
pub const KSPWALLET_V1_MIN_KDF_SALT_BYTES: usize = 16;
/// Maximum accepted Argon2 salt size in bytes.
pub const KSPWALLET_V1_MAX_KDF_SALT_BYTES: usize = 64;
/// Structural V1 ceiling for serialized Argon2 memory cost; creation defaults are benchmarked separately.
pub const KSPWALLET_V1_MAX_ARGON2_MEMORY_KIB: u32 = 1024 * 1024;
/// Byte length of an Ed25519 public key used as Wallet format authority.
pub const KSPWALLET_V1_ED25519_PUBLIC_KEY_BYTES: usize = 32;
/// Byte length of an Ed25519 detached state signature.
pub const KSPWALLET_V1_ED25519_SIGNATURE_BYTES: usize = 64;
/// Initial protected payload version used independently by control, metadata and secret compartments.
pub const KSPWALLET_V1_INITIAL_PAYLOAD_VERSION: u32 = 1;
/// Maximum protected alias size in UTF-8 bytes for metadata V1.
pub const KSPWALLET_V1_MAX_ALIAS_BYTES: usize = 256;
/// Structural V1 ceiling for serialized Argon2 iteration cost; creation defaults are benchmarked separately.
pub const KSPWALLET_V1_MAX_ARGON2_ITERATIONS: u32 = 64;
/// Structural V1 ceiling for serialized Argon2 memory cost; creation defaults are benchmarked separately.
pub const KSPWALLET_V1_MAX_ARGON2_MEMORY_KIB: u32 = 1024 * 1024;
/// Structural V1 ceiling for serialized Argon2 parallelism; creation defaults are benchmarked separately.
pub const KSPWALLET_V1_MAX_ARGON2_PARALLELISM: u32 = 64;
/// Maximum accepted Argon2 salt size in bytes.
pub const KSPWALLET_V1_MAX_KDF_SALT_BYTES: usize = 64;
/// Maximum number of key slots understood by format V1: exactly one OWNER plus optional VIEW.
pub const KSPWALLET_V1_MAX_KEY_SLOTS: usize = 2;
/// Maximum ciphertext size of one wrapped capability payload.
pub const KSPWALLET_V1_MAX_KEY_WRAP_CIPHERTEXT_BYTES: usize = 4096;
/// Maximum OWNER-control ciphertext size accepted by envelope V1.
pub const KSPWALLET_V1_MAX_OWNER_CONTROL_CIPHERTEXT_BYTES: usize = 4096;
/// Maximum metadata ciphertext size, including the AEAD tag over the bounded 64-KiB plaintext.
pub const KSPWALLET_V1_MAX_METADATA_CIPHERTEXT_BYTES: usize = KSPWALLET_V1_MAX_METADATA_PLAINTEXT_BYTES + KSPWALLET_V1_AEAD_TAG_BYTES;
/// Maximum metadata plaintext size before V1 encryption.
pub const KSPWALLET_V1_MAX_METADATA_PLAINTEXT_BYTES: usize = 64 * 1024;
/// Maximum number of protected notes in metadata V1.
pub const KSPWALLET_V1_MAX_NOTES: usize = 64;
/// Maximum protected note text size in UTF-8 bytes for metadata V1.
pub const KSPWALLET_V1_MAX_NOTE_TEXT_BYTES: usize = 8 * 1024;
/// Maximum OWNER-control ciphertext size accepted by envelope V1.
pub const KSPWALLET_V1_MAX_OWNER_CONTROL_CIPHERTEXT_BYTES: usize = 4096;
/// Maximum password size in exact UTF-8 input bytes.
pub const KSPWALLET_V1_MAX_PASSWORD_BYTES: usize = 1024;
/// Maximum OWNER-only secret ciphertext size accepted by envelope V1.
pub const KSPWALLET_V1_MAX_SECRET_CIPHERTEXT_BYTES: usize = 4096;
/// Initial protected payload version used independently by control, metadata and secret compartments.
pub const KSPWALLET_V1_INITIAL_PAYLOAD_VERSION: u32 = 1;
/// Domain separator for the OWNER state-signature transcript.
pub const KSPWALLET_V1_STATE_TRANSCRIPT_DOMAIN: &[u8] = b"KSPWALLET-V1-STATE";
/// Domain separator for OWNER key-slot wrapping AAD.
pub const KSPWALLET_V1_OWNER_SLOT_AAD_DOMAIN: &[u8] = b"KSPWALLET-V1-AAD-OWNER-SLOT";
/// Domain separator for VIEW key-slot wrapping AAD.
pub const KSPWALLET_V1_VIEW_SLOT_AAD_DOMAIN: &[u8] = b"KSPWALLET-V1-AAD-VIEW-SLOT";
/// Domain separator for OWNER-control compartment AAD.
pub const KSPWALLET_V1_OWNER_CONTROL_AAD_DOMAIN: &[u8] = b"KSPWALLET-V1-AAD-OWNER-CONTROL";
/// Domain separator for metadata compartment AAD.
pub const KSPWALLET_V1_METADATA_AAD_DOMAIN: &[u8] = b"KSPWALLET-V1-AAD-METADATA";
/// Minimum accepted Argon2 salt size in bytes.
pub const KSPWALLET_V1_MIN_KDF_SALT_BYTES: usize = 16;
/// Byte length of every protected metadata note identifier.
pub const KSPWALLET_V1_NOTE_ID_BYTES: usize = 16;
/// Domain separator for OWNER-control compartment AAD.
pub const KSPWALLET_V1_OWNER_CONTROL_AAD_DOMAIN: &[u8] = b"KSPWALLET-V1-AAD-OWNER-CONTROL";
/// Exact plaintext size of the V1 OWNER-control compartment.
pub const KSPWALLET_V1_OWNER_CONTROL_PLAINTEXT_BYTES: usize = 96;
/// Domain separator for OWNER key-slot wrapping AAD.
pub const KSPWALLET_V1_OWNER_SLOT_AAD_DOMAIN: &[u8] = b"KSPWALLET-V1-AAD-OWNER-SLOT";
/// Domain separator for OWNER-only secret compartment AAD.
pub const KSPWALLET_V1_SECRET_AAD_DOMAIN: &[u8] = b"KSPWALLET-V1-AAD-SECRET";
/// Exact plaintext size of the V1 Solana secret compartment.
pub const KSPWALLET_V1_SECRET_PLAINTEXT_BYTES: usize = 64;
/// Byte length of every V1 key-slot identifier.
pub const KSPWALLET_V1_SLOT_ID_BYTES: usize = 16;
/// Domain separator for the OWNER state-signature transcript.
pub const KSPWALLET_V1_STATE_TRANSCRIPT_DOMAIN: &[u8] = b"KSPWALLET-V1-STATE";
/// Domain separator for VIEW key-slot wrapping AAD.
pub const KSPWALLET_V1_VIEW_SLOT_AAD_DOMAIN: &[u8] = b"KSPWALLET-V1-AAD-VIEW-SLOT";
/// Byte length of an XChaCha20-Poly1305 nonce.
pub const KSPWALLET_V1_XCHACHA_NONCE_BYTES: usize = 24;
/// Owning tracing target for events emitted by the Wallet crate.
pub(crate) const TRACING_TARGET: &str = "ksp-wallet-lib";

View File

@@ -1,10 +1,10 @@
// file: crates/ksp-wallet-lib/src/crypto.rs
// version: 3
// version: 4
//! In-memory cryptographic primitives for native `.kspwallet` V1.
use chacha20poly1305::KeyInit; // rust-rules: derive-import
use chacha20poly1305::aead::Aead; // rust-rules: derive-import
use chacha20poly1305::KeyInit; // rust-rules: trait-import
use chacha20poly1305::aead::Aead; // rust-rules: trait-import
/// Exact V1 content-key and password-derived-key size in bytes.
pub(crate) const SECRET_KEY_BYTES: usize = 32;
@@ -165,7 +165,6 @@ fn derive_argon2id(password: &[u8], salt: &[u8], memory_kib: u32, iterations: u3
{
return std::result::Result::Err(crypto_parameter_error());
}
let params_result = argon2::Params::new(memory_kib, iterations, parallelism, std::option::Option::Some(SECRET_KEY_BYTES));
let params = match params_result {
std::result::Result::Ok(params) => params,

View File

@@ -1,37 +1,37 @@
// file: crates/ksp-wallet-lib/src/error.rs
// version: 4
// version: 5
/// Error code used when an atomic Wallet persistence operation cannot publish a valid replacement.
pub const ERROR_CODE_ATOMIC_PERSISTENCE_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "atomic_persistence_failed");
/// Error code used when an authenticated Wallet structure cannot be verified.
pub const ERROR_CODE_AUTHENTICATION_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "authentication_failed");
/// Error code used when an operation requires a capability that the caller does not own.
pub const ERROR_CODE_CAPABILITY_INSUFFICIENT: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "capability_insufficient");
/// Error code used when an internal blocking cryptographic operation cannot complete.
pub const ERROR_CODE_CRYPTO_OPERATION_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "crypto_operation_failed");
/// Error code used when serialized cryptographic parameters are invalid or unsupported.
pub const ERROR_CODE_CRYPTO_PARAMETERS_INVALID: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "crypto_parameters_invalid");
/// Error code used when a no-clobber create or import destination already exists.
pub const ERROR_CODE_DESTINATION_EXISTS: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "destination_exists");
/// Error code used when a native Wallet structure is invalid.
pub const ERROR_CODE_FORMAT_INVALID: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "format_invalid");
/// Error code used when a native Wallet format version is unsupported.
pub const ERROR_CODE_FORMAT_VERSION_UNSUPPORTED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "format_version_unsupported");
/// Error code used when serialized cryptographic parameters are invalid or unsupported.
pub const ERROR_CODE_CRYPTO_PARAMETERS_INVALID: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "crypto_parameters_invalid");
/// Error code used when the operating-system cryptographic random source cannot provide bytes.
pub const ERROR_CODE_RANDOMNESS_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "randomness_failed");
/// Error code used when an authenticated Wallet structure cannot be verified.
pub const ERROR_CODE_AUTHENTICATION_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "authentication_failed");
/// Error code used when an internal blocking cryptographic operation cannot complete.
pub const ERROR_CODE_CRYPTO_OPERATION_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "crypto_operation_failed");
/// Error code used when a VIEW unlock attempt fails without exposing a finer cryptographic oracle.
pub const ERROR_CODE_VIEW_UNLOCK_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "view_unlock_failed");
/// Error code used when an OWNER unlock attempt fails without exposing a finer cryptographic oracle.
pub const ERROR_CODE_OWNER_UNLOCK_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "owner_unlock_failed");
/// Error code used when an operation requires a capability that the caller does not own.
pub const ERROR_CODE_CAPABILITY_INSUFFICIENT: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "capability_insufficient");
/// Error code used when Wallet filesystem I/O fails.
pub const ERROR_CODE_IO_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "io_failed");
/// Error code used when a no-clobber create or import destination already exists.
pub const ERROR_CODE_DESTINATION_EXISTS: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "destination_exists");
/// Error code used when an atomic Wallet persistence operation cannot publish a valid replacement.
pub const ERROR_CODE_ATOMIC_PERSISTENCE_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "atomic_persistence_failed");
/// Error code used when an import/export transfer format is unsupported.
pub const ERROR_CODE_TRANSFER_FORMAT_UNSUPPORTED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "transfer_format_unsupported");
/// Error code used when imported or decoded key material is invalid.
pub const ERROR_CODE_KEY_MATERIAL_INVALID: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "key_material_invalid");
/// Error code used when a Wallet signing operation fails.
pub const ERROR_CODE_SIGNATURE_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "signature_failed");
/// Error code used when a protected Wallet note identifier is not present.
pub const ERROR_CODE_NOTE_NOT_FOUND: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "note_not_found");
/// Error code used when an OWNER unlock attempt fails without exposing a finer cryptographic oracle.
pub const ERROR_CODE_OWNER_UNLOCK_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "owner_unlock_failed");
/// Error code used when the operating-system cryptographic random source cannot provide bytes.
pub const ERROR_CODE_RANDOMNESS_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "randomness_failed");
/// Error code used when a Wallet signing operation fails.
pub const ERROR_CODE_SIGNATURE_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "signature_failed");
/// Error code used when an administrative replacement targets a different or stale Wallet state.
pub const ERROR_CODE_STATE_CONFLICT: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "state_conflict");
/// Error code used when an import/export transfer format is unsupported.
pub const ERROR_CODE_TRANSFER_FORMAT_UNSUPPORTED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "transfer_format_unsupported");
/// Error code used when a VIEW unlock attempt fails without exposing a finer cryptographic oracle.
pub const ERROR_CODE_VIEW_UNLOCK_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("wallet", "view_unlock_failed");

View File

@@ -1,5 +1,5 @@
// file: crates/ksp-wallet-lib/src/lib.rs
// version: 10
// version: 11
#![warn(missing_docs)]
#![deny(unreachable_pub)]
@@ -245,10 +245,32 @@ pub(crate) use self::crypto::random_nonce;
pub(crate) use self::crypto::unwrap_key;
/// Wraps one 32-byte content key with XChaCha20-Poly1305 and caller-provided domain-separated AAD.
pub(crate) use self::crypto::wrap_key;
/// Crate-internal `MetadataPayloadV1` state shared across the owning crate.
pub(crate) use self::payload::MetadataPayloadV1;
/// Decodes metadata payload.
pub(crate) use self::payload::decode_metadata_payload;
/// Decodes owner control payload.
pub(crate) use self::payload::decode_owner_control_payload;
/// Encodes initial metadata payload.
pub(crate) use self::payload::encode_initial_metadata_payload;
/// Encodes owner control payload.
pub(crate) use self::payload::encode_owner_control_payload;
/// Internal no-clobber native persistence path shared by transfer adapters.
pub(crate) use self::persistence::persist_new_wallet_content_v1;
/// Persists new wallet fault before publish.
#[cfg(test)]
pub(crate) use self::persistence::persist_new_wallet_fault_before_publish;
/// Persists new wallet for test.
#[cfg(test)]
pub(crate) use self::persistence::persist_new_wallet_for_test;
/// Replaces wallet fault before publish.
#[cfg(test)]
pub(crate) use self::persistence::replace_wallet_fault_before_publish;
/// Replaces wallet file v1.
pub(crate) use self::persistence::replace_wallet_file_v1;
/// Replaces wallet for test.
#[cfg(test)]
pub(crate) use self::persistence::replace_wallet_for_test;
/// Internal deterministic compartment-AAD codec shared by Wallet crypto layers.
pub(crate) use self::transcript::compartment_aad;
/// Internal deterministic key-slot-AAD codec shared by Wallet crypto layers.
@@ -257,5 +279,11 @@ pub(crate) use self::transcript::slot_aad;
pub(crate) use self::transcript::state_transcript;
/// Internal no-clobber transfer-file writer used only by OWNER export.
pub(crate) use self::transfer::write_wallet_transfer_file_v1;
/// Crate-internal `OwnerStateV1` state shared across the owning crate.
pub(crate) use self::wallet::OwnerStateV1;
/// Crate-internal `ViewStateV1` state shared across the owning crate.
pub(crate) use self::wallet::ViewStateV1;
/// Internal imported-keypair creation path shared by transfer adapters.
pub(crate) use self::wallet::create_wallet_v1_from_keypair;
/// Verifies state signature.
pub(crate) use self::wallet::verify_state_signature;

View File

@@ -1,5 +1,5 @@
// file: crates/ksp-wallet-lib/src/metadata.rs
// version: 3
// version: 4
/// Protected metadata requested when creating a new native Wallet.
///
@@ -17,6 +17,7 @@ impl WalletCreateMetadataV1 {
return Self { alias, note_texts };
}
/// Consumes this value and returns parts.
pub(crate) fn into_parts(self) -> (std::option::Option<std::string::String>, std::vec::Vec<std::string::String>) {
return (self.alias, self.note_texts);
}
@@ -40,6 +41,7 @@ pub struct WalletNote {
}
impl WalletNote {
/// Creates a new `WalletNote` value.
pub(crate) fn new(id: std::string::String, text: std::string::String) -> Self {
return Self { id, text };
}
@@ -74,6 +76,7 @@ pub struct WalletInfo {
}
impl WalletInfo {
/// Creates a new `WalletInfo` value.
pub(crate) fn new(
capability: crate::WalletCapability,
pubkey: ksp_core_lib::Pubkey,
@@ -135,6 +138,7 @@ pub struct LockedWalletInfo {
}
impl LockedWalletInfo {
/// Creates a new `LockedWalletInfo` value.
pub(crate) const fn new(view_enabled: bool) -> Self {
return Self { format_version: crate::KSPWALLET_FORMAT_VERSION_V1, view_enabled };
}

View File

@@ -1,5 +1,5 @@
// file: crates/ksp-wallet-lib/src/owner.rs
// version: 5
// version: 6
/// Authorized OWNER capability handle.
///
@@ -7,11 +7,12 @@
/// material remains encapsulated and is never exposed through a general-purpose getter.
pub struct WalletOwner {
info: crate::WalletInfo,
state: crate::wallet::OwnerStateV1,
state: crate::OwnerStateV1,
}
impl WalletOwner {
pub(crate) fn from_unlocked(info: crate::WalletInfo, state: crate::wallet::OwnerStateV1) -> Self {
/// Builds `WalletOwner` from unlocked.
pub(crate) fn from_unlocked(info: crate::WalletInfo, state: crate::OwnerStateV1) -> Self {
return Self { info, state };
}
@@ -307,7 +308,7 @@ async fn persist_staged(
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
return crate::persistence::replace_wallet_file_v1(destination, expected_current.clone(), serialized).await;
return crate::replace_wallet_file_v1(destination, expected_current.clone(), serialized).await;
}
#[cfg(test)]

View File

@@ -1,11 +1,12 @@
// file: crates/ksp-wallet-lib/src/payload.rs
// version: 4
// version: 5
//! Plaintext payload codecs protected inside native `.kspwallet` V1 compartments.
use base64::Engine; // rust-rules: derive-import
use std::str::FromStr; // rust-rules: derive-import
use base64::Engine; // rust-rules: trait-import
use std::str::FromStr; // rust-rules: trait-import
/// Crate-internal `MetadataPayloadV1` state shared across the owning crate.
pub(crate) struct MetadataPayloadV1 {
pubkey: ksp_core_lib::Pubkey,
alias: std::option::Option<std::string::String>,
@@ -13,16 +14,19 @@ pub(crate) struct MetadataPayloadV1 {
}
impl crate::MetadataPayloadV1 {
/// Returns the current pubkey.
pub(crate) const fn pubkey(&self) -> &ksp_core_lib::Pubkey {
return &self.pubkey;
}
/// Builds `MetadataPayloadV1` from info.
pub(crate) fn from_info(info: &crate::WalletInfo) -> Self {
let alias = info.alias().map(std::string::String::from);
let notes = info.notes().to_vec();
return Self { pubkey: *info.pubkey(), alias, notes };
}
/// Updates alias.
pub(crate) fn set_alias(&mut self, alias: std::option::Option<std::string::String>) -> ksp_core_lib::Result<()> {
let validation_result = validate_alias(alias.as_deref());
if let std::result::Result::Err(error) = validation_result {
@@ -32,6 +36,7 @@ impl crate::MetadataPayloadV1 {
return std::result::Result::Ok(());
}
/// Adds note.
pub(crate) fn add_note(&mut self, text: std::string::String) -> ksp_core_lib::Result<std::string::String> {
if self.notes.len() >= crate::KSPWALLET_V1_MAX_NOTES {
return std::result::Result::Err(metadata_error("Wallet note count exceeds the V1 limit", "metadata.notes"));
@@ -40,7 +45,7 @@ impl crate::MetadataPayloadV1 {
if let std::result::Result::Err(error) = validation_result {
return std::result::Result::Err(error);
}
let note_id_bytes = match crate::crypto::random_bytes::<{ crate::KSPWALLET_V1_NOTE_ID_BYTES }>() {
let note_id_bytes = match crate::random_bytes::<{ crate::KSPWALLET_V1_NOTE_ID_BYTES }>() {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
@@ -54,6 +59,7 @@ impl crate::MetadataPayloadV1 {
return std::result::Result::Ok(note_id);
}
/// Updates note.
pub(crate) fn update_note(&mut self, note_id: &str, text: std::string::String) -> ksp_core_lib::Result<()> {
let validation_result = validate_note_text(text.as_str());
if let std::result::Result::Err(error) = validation_result {
@@ -70,6 +76,7 @@ impl crate::MetadataPayloadV1 {
return std::result::Result::Err(note_not_found_error());
}
/// Deletes note.
pub(crate) fn delete_note(&mut self, note_id: &str) -> ksp_core_lib::Result<()> {
let mut index = 0_usize;
while index < self.notes.len() {
@@ -82,6 +89,7 @@ impl crate::MetadataPayloadV1 {
return std::result::Result::Err(note_not_found_error());
}
/// Executes the crate-internal encode operation for `MetadataPayloadV1`.
pub(crate) fn encode(&self) -> ksp_core_lib::Result<std::vec::Vec<u8>> {
let validation_result = validate_alias(self.alias.as_deref());
if let std::result::Result::Err(error) = validation_result {
@@ -110,23 +118,26 @@ impl crate::MetadataPayloadV1 {
return std::result::Result::Ok(serialized);
}
/// Consumes this value and returns info.
pub(crate) fn into_info(self, capability: crate::WalletCapability) -> crate::WalletInfo {
return crate::WalletInfo::new(capability, self.pubkey, self.alias, self.notes);
}
}
/// Crate-internal `OwnerControlMaterialV1` state shared across the owning crate.
pub(crate) struct OwnerControlMaterialV1 {
admin_signing_secret: [u8; crate::crypto::SECRET_KEY_BYTES],
admin_signing_secret: [u8; crate::SECRET_KEY_BYTES],
metadata_key: crate::SecretKeyV1,
secret_key: crate::SecretKeyV1,
}
impl OwnerControlMaterialV1 {
pub(crate) fn into_parts(mut self) -> ([u8; crate::crypto::SECRET_KEY_BYTES], crate::SecretKeyV1, crate::SecretKeyV1) {
let mut admin_signing_secret = [0_u8; crate::crypto::SECRET_KEY_BYTES];
/// Consumes this value and returns parts.
pub(crate) fn into_parts(mut self) -> ([u8; crate::SECRET_KEY_BYTES], crate::SecretKeyV1, crate::SecretKeyV1) {
let mut admin_signing_secret = [0_u8; crate::SECRET_KEY_BYTES];
std::mem::swap(&mut admin_signing_secret, &mut self.admin_signing_secret);
let metadata_key = std::mem::replace(&mut self.metadata_key, crate::SecretKeyV1::from_bytes([0_u8; crate::crypto::SECRET_KEY_BYTES]));
let secret_key = std::mem::replace(&mut self.secret_key, crate::SecretKeyV1::from_bytes([0_u8; crate::crypto::SECRET_KEY_BYTES]));
let metadata_key = std::mem::replace(&mut self.metadata_key, crate::SecretKeyV1::from_bytes([0_u8; crate::SECRET_KEY_BYTES]));
let secret_key = std::mem::replace(&mut self.secret_key, crate::SecretKeyV1::from_bytes([0_u8; crate::SECRET_KEY_BYTES]));
return (admin_signing_secret, metadata_key, secret_key);
}
}
@@ -152,6 +163,7 @@ struct RawMetadataNoteV1 {
text: std::string::String,
}
/// Encodes initial metadata payload.
pub(crate) fn encode_initial_metadata_payload(
pubkey: ksp_core_lib::Pubkey,
metadata: crate::WalletCreateMetadataV1,
@@ -164,7 +176,6 @@ pub(crate) fn encode_initial_metadata_payload(
if note_texts.len() > crate::KSPWALLET_V1_MAX_NOTES {
return std::result::Result::Err(metadata_error("Wallet note count exceeds the V1 limit", "metadata.notes"));
}
let mut notes = std::vec::Vec::with_capacity(note_texts.len());
let mut note_ids = std::collections::BTreeSet::new();
for text in note_texts {
@@ -172,7 +183,7 @@ pub(crate) fn encode_initial_metadata_payload(
if let std::result::Result::Err(error) = validation_result {
return std::result::Result::Err(error);
}
let note_id_bytes = match crate::crypto::random_bytes::<{ crate::KSPWALLET_V1_NOTE_ID_BYTES }>() {
let note_id_bytes = match crate::random_bytes::<{ crate::KSPWALLET_V1_NOTE_ID_BYTES }>() {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
@@ -182,7 +193,6 @@ pub(crate) fn encode_initial_metadata_payload(
}
notes.push(crate::WalletNote::new(note_id, text));
}
let payload = crate::MetadataPayloadV1 { pubkey, alias, notes };
let serialized = match payload.encode() {
std::result::Result::Ok(value) => value,
@@ -191,6 +201,7 @@ pub(crate) fn encode_initial_metadata_payload(
return std::result::Result::Ok((serialized, payload));
}
/// Decodes metadata payload.
pub(crate) fn decode_metadata_payload(source: &[u8]) -> ksp_core_lib::Result<crate::MetadataPayloadV1> {
if source.len() > crate::KSPWALLET_V1_MAX_METADATA_PLAINTEXT_BYTES {
return std::result::Result::Err(metadata_error("Wallet metadata payload exceeds the V1 plaintext limit", "metadata"));
@@ -207,7 +218,6 @@ pub(crate) fn decode_metadata_payload(source: &[u8]) -> ksp_core_lib::Result<cra
if raw.notes.len() > crate::KSPWALLET_V1_MAX_NOTES {
return std::result::Result::Err(metadata_error("Wallet note count exceeds the V1 limit", "metadata.notes"));
}
let pubkey_result = ksp_core_lib::Pubkey::from_str(raw.pubkey.as_str());
let pubkey = match pubkey_result {
std::result::Result::Ok(value) => value,
@@ -216,7 +226,6 @@ pub(crate) fn decode_metadata_payload(source: &[u8]) -> ksp_core_lib::Result<cra
if pubkey.to_string() != raw.pubkey {
return std::result::Result::Err(metadata_error("Wallet metadata Pubkey is not canonical Base58", "metadata.pubkey"));
}
let mut notes = std::vec::Vec::with_capacity(raw.notes.len());
let mut note_ids = std::collections::BTreeSet::new();
for raw_note in raw.notes {
@@ -239,8 +248,9 @@ pub(crate) fn decode_metadata_payload(source: &[u8]) -> ksp_core_lib::Result<cra
return std::result::Result::Ok(crate::MetadataPayloadV1 { pubkey, alias: raw.alias, notes });
}
/// Encodes owner control payload.
pub(crate) fn encode_owner_control_payload(
admin_signing_secret: &[u8; crate::crypto::SECRET_KEY_BYTES],
admin_signing_secret: &[u8; crate::SECRET_KEY_BYTES],
metadata_key: &crate::SecretKeyV1,
secret_key: &crate::SecretKeyV1,
) -> [u8; crate::KSPWALLET_V1_OWNER_CONTROL_PLAINTEXT_BYTES] {
@@ -251,15 +261,16 @@ pub(crate) fn encode_owner_control_payload(
return output;
}
/// Decodes owner control payload.
pub(crate) fn decode_owner_control_payload(source: &[u8]) -> ksp_core_lib::Result<OwnerControlMaterialV1> {
if source.len() != crate::KSPWALLET_V1_OWNER_CONTROL_PLAINTEXT_BYTES {
return std::result::Result::Err(metadata_error("Wallet OWNER-control payload length is invalid", "owner_control"));
}
let mut admin_signing_secret = [0_u8; crate::crypto::SECRET_KEY_BYTES];
let mut admin_signing_secret = [0_u8; crate::SECRET_KEY_BYTES];
admin_signing_secret.copy_from_slice(&source[0..32]);
let mut metadata_key = [0_u8; crate::crypto::SECRET_KEY_BYTES];
let mut metadata_key = [0_u8; crate::SECRET_KEY_BYTES];
metadata_key.copy_from_slice(&source[32..64]);
let mut secret_key = [0_u8; crate::crypto::SECRET_KEY_BYTES];
let mut secret_key = [0_u8; crate::SECRET_KEY_BYTES];
secret_key.copy_from_slice(&source[64..96]);
return std::result::Result::Ok(OwnerControlMaterialV1 {
admin_signing_secret,

View File

@@ -1,10 +1,10 @@
// file: crates/ksp-wallet-lib/src/persistence.rs
// version: 6
// version: 7
//! Async-first native Wallet V1 filesystem persistence.
use std::io::Read; // rust-rules: derive-import
use std::io::Write; // rust-rules: derive-import
use std::io::Read; // rust-rules: trait-import
use std::io::Write; // rust-rules: trait-import
/// Creates a new native `.kspwallet` V1 at `destination` without overwriting an existing path.
///
@@ -83,10 +83,12 @@ pub async fn inspect_locked_wallet_file_v1(source: impl std::convert::AsRef<std:
return crate::inspect_locked_wallet_v1(bytes.as_slice());
}
/// Persists new wallet content v1.
pub(crate) async fn persist_new_wallet_content_v1(destination: std::path::PathBuf, content: std::vec::Vec<u8>) -> ksp_core_lib::Result<()> {
return persist_new_wallet_async(destination, content).await;
}
/// Replaces wallet file v1.
pub(crate) async fn replace_wallet_file_v1(
destination: std::path::PathBuf,
expected_current: crate::KspWalletEnvelopeV1,
@@ -131,7 +133,6 @@ fn read_wallet_file_blocking(source: &std::path::Path) -> ksp_core_lib::Result<s
if metadata.len() > crate::KSPWALLET_MAX_FILE_BYTES as u64 {
return std::result::Result::Err(oversized_document_error());
}
let capacity = std::cmp::min(metadata.len(), crate::KSPWALLET_MAX_FILE_BYTES as u64) as usize;
let mut bytes = std::vec::Vec::with_capacity(capacity);
let mut bounded = file.take((crate::KSPWALLET_MAX_FILE_BYTES + 1) as u64);
@@ -175,7 +176,7 @@ fn verify_expected_wallet_state(destination: &std::path::Path, expected_current:
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let verify_result = crate::wallet::verify_state_signature(&current);
let verify_result = crate::verify_state_signature(&current);
if let std::result::Result::Err(error) = verify_result {
return std::result::Result::Err(error);
}
@@ -207,7 +208,6 @@ where
if !existing_metadata.is_file() {
return std::result::Result::Err(atomic_error("replace_destination", "Wallet replacement destination is not a regular file"));
}
let temporary_result = tempfile::Builder::new().prefix(".kspwallet-replace-").suffix(".tmp").tempfile_in(parent);
let mut temporary = match temporary_result {
std::result::Result::Ok(value) => value,
@@ -225,7 +225,6 @@ where
if let std::result::Result::Err(error) = hook_result {
return std::result::Result::Err(error);
}
let persist_result = temporary.persist(destination);
let persisted = match persist_result {
std::result::Result::Ok(value) => value,
@@ -254,7 +253,6 @@ where
if destination.file_name().is_none() {
return std::result::Result::Err(atomic_error("destination", "Wallet destination has no file name"));
}
let temporary_result = tempfile::Builder::new().prefix(".kspwallet-write-").suffix(".tmp").tempfile_in(parent);
let mut temporary = match temporary_result {
std::result::Result::Ok(value) => value,
@@ -268,12 +266,10 @@ where
if let std::result::Result::Err(error) = sync_result {
return std::result::Result::Err(atomic_io_error("temporary_sync", error));
}
let hook_result = before_publish();
if let std::result::Result::Err(error) = hook_result {
return std::result::Result::Err(error);
}
let persist_result = temporary.persist_noclobber(destination);
let persisted = match persist_result {
std::result::Result::Ok(value) => value,
@@ -371,6 +367,7 @@ fn blocking_atomic_error(operation: &'static str, source: tokio::task::JoinError
.with_source(source);
}
/// Persists new wallet fault before publish.
#[cfg(test)]
pub(crate) fn persist_new_wallet_fault_before_publish(destination: &std::path::Path, content: &[u8]) -> ksp_core_lib::Result<()> {
return persist_new_wallet_with_hook(destination, content, || {
@@ -378,11 +375,13 @@ pub(crate) fn persist_new_wallet_fault_before_publish(destination: &std::path::P
});
}
/// Persists new wallet for test.
#[cfg(test)]
pub(crate) fn persist_new_wallet_for_test(destination: &std::path::Path, content: &[u8]) -> ksp_core_lib::Result<()> {
return persist_new_wallet_blocking(destination, content);
}
/// Replaces wallet fault before publish.
#[cfg(test)]
pub(crate) fn replace_wallet_fault_before_publish(destination: &std::path::Path, content: &[u8]) -> ksp_core_lib::Result<()> {
return replace_wallet_file_with_hook(destination, content, || {
@@ -390,6 +389,7 @@ pub(crate) fn replace_wallet_fault_before_publish(destination: &std::path::Path,
});
}
/// Replaces wallet for test.
#[cfg(test)]
pub(crate) fn replace_wallet_for_test(destination: &std::path::Path, content: &[u8]) -> ksp_core_lib::Result<()> {
return replace_wallet_file_blocking(destination, content);

View File

@@ -1,31 +1,31 @@
// file: crates/ksp-wallet-lib/src/transcript.rs
// version: 1
// version: 2
//! Deterministic `.kspwallet` V1 state-transcript and AEAD-AAD encoding.
const TAG_MAGIC: u16 = 0x0001;
const TAG_COMPARTMENT_ALGORITHM: u16 = 0x0202;
const TAG_COMPARTMENT_CIPHERTEXT: u16 = 0x0204;
const TAG_COMPARTMENT_KIND: u16 = 0x0200;
const TAG_COMPARTMENT_NONCE: u16 = 0x0203;
const TAG_COMPARTMENT_VERSION: u16 = 0x0201;
const TAG_FORMAT_VERSION: u16 = 0x0002;
const TAG_KDF_ALGORITHM: u16 = 0x0102;
const TAG_KDF_ITERATIONS: u16 = 0x0105;
const TAG_KDF_MEMORY_KIB: u16 = 0x0104;
const TAG_KDF_PARALLELISM: u16 = 0x0106;
const TAG_KDF_SALT: u16 = 0x0107;
const TAG_KDF_VERSION: u16 = 0x0103;
const TAG_MAGIC: u16 = 0x0001;
const TAG_OWNER_AUTH_PUBLIC_KEY: u16 = 0x0003;
const TAG_SLOT_ID: u16 = 0x0100;
const TAG_SLOT_ROLE: u16 = 0x0101;
const TAG_STATE_SIGNATURE_ALGORITHM: u16 = 0x0500;
const TAG_VIEW_ENABLED: u16 = 0x0010;
const TAG_VIEW_ROLE: u16 = 0x0011;
const TAG_VIEW_SLOT_ID: u16 = 0x0012;
const TAG_SLOT_ID: u16 = 0x0100;
const TAG_SLOT_ROLE: u16 = 0x0101;
const TAG_KDF_ALGORITHM: u16 = 0x0102;
const TAG_KDF_VERSION: u16 = 0x0103;
const TAG_KDF_MEMORY_KIB: u16 = 0x0104;
const TAG_KDF_ITERATIONS: u16 = 0x0105;
const TAG_KDF_PARALLELISM: u16 = 0x0106;
const TAG_KDF_SALT: u16 = 0x0107;
const TAG_WRAP_ALGORITHM: u16 = 0x0108;
const TAG_WRAP_NONCE: u16 = 0x0109;
const TAG_WRAP_CIPHERTEXT: u16 = 0x010A;
const TAG_COMPARTMENT_KIND: u16 = 0x0200;
const TAG_COMPARTMENT_VERSION: u16 = 0x0201;
const TAG_COMPARTMENT_ALGORITHM: u16 = 0x0202;
const TAG_COMPARTMENT_NONCE: u16 = 0x0203;
const TAG_COMPARTMENT_CIPHERTEXT: u16 = 0x0204;
const TAG_STATE_SIGNATURE_ALGORITHM: u16 = 0x0500;
const TAG_WRAP_NONCE: u16 = 0x0109;
/// Builds the normative OWNER state-signature transcript for one validated V1 envelope.
pub(crate) fn state_transcript(envelope: &crate::KspWalletEnvelopeV1) -> std::vec::Vec<u8> {
@@ -37,7 +37,6 @@ pub(crate) fn state_transcript(envelope: &crate::KspWalletEnvelopeV1) -> std::ve
std::option::Option::Some(slot_id) => push_bytes(&mut output, TAG_VIEW_SLOT_ID, slot_id),
std::option::Option::None => push_bytes(&mut output, TAG_VIEW_SLOT_ID, &[]),
}
push_slot(&mut output, envelope.owner_slot(), true);
push_compartment(&mut output, envelope.owner_control(), true);
push_compartment(&mut output, envelope.metadata(), true);

View File

@@ -1,13 +1,13 @@
// file: crates/ksp-wallet-lib/src/transfer.rs
// version: 2
// version: 3
//! Explicit OWNER-only Solana keypair import/export adapters.
use std::io::Read; // rust-rules: derive-import
use std::io::Write; // rust-rules: derive-import
use std::io::Read; // rust-rules: trait-import
use std::io::Write; // rust-rules: trait-import
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt; // rust-rules: derive-import
use zeroize::Zeroize; // rust-rules: derive-import
use std::os::unix::fs::PermissionsExt; // rust-rules: trait-import
use zeroize::Zeroize; // rust-rules: trait-import
/// Explicit secret-transfer formats supported by Wallet `0.2.5`.
#[non_exhaustive]
@@ -161,6 +161,7 @@ pub async fn import_wallet_transfer_file_v1(
return import_wallet_transfer_v1(destination, bytes.as_slice(), format, owner_password, view_password, metadata).await;
}
/// Executes the crate-internal write wallet transfer file v1 operation for the owning module.
pub(crate) async fn write_wallet_transfer_file_v1(
destination: std::path::PathBuf,
content: std::vec::Vec<u8>,

View File

@@ -1,5 +1,5 @@
// file: crates/ksp-wallet-lib/src/view.rs
// version: 3
// version: 4
/// Authorized VIEW capability handle.
///
@@ -7,11 +7,12 @@
/// Solana secret, OWNER administration material or metadata-write authority.
pub struct WalletView {
info: crate::WalletInfo,
state: crate::wallet::ViewStateV1,
state: crate::ViewStateV1,
}
impl WalletView {
pub(crate) fn from_unlocked(info: crate::WalletInfo, state: crate::wallet::ViewStateV1) -> Self {
/// Builds `WalletView` from unlocked.
pub(crate) fn from_unlocked(info: crate::WalletInfo, state: crate::ViewStateV1) -> Self {
return Self { info, state };
}
@@ -68,7 +69,7 @@ impl WalletView {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let persist_result = crate::persistence::replace_wallet_file_v1(destination.as_ref().to_path_buf(), self.state.envelope().clone(), serialized).await;
let persist_result = crate::replace_wallet_file_v1(destination.as_ref().to_path_buf(), self.state.envelope().clone(), serialized).await;
if let std::result::Result::Err(error) = persist_result {
return std::result::Result::Err(error);
}

View File

@@ -1,11 +1,12 @@
// file: crates/ksp-wallet-lib/src/wallet.rs
// version: 7
// version: 8
//! In-memory native Wallet V1 create/open orchestration.
use ed25519_dalek::Signer; // rust-rules: derive-import
use zeroize::Zeroize; // rust-rules: derive-import
use ed25519_dalek::Signer; // rust-rules: trait-import
use zeroize::Zeroize; // rust-rules: trait-import
/// Crate-internal `OwnerStateV1` state shared across the owning crate.
pub(crate) struct OwnerStateV1 {
envelope: crate::KspWalletEnvelopeV1,
owner_root: std::option::Option<crate::SecretKeyV1>,
@@ -16,6 +17,7 @@ pub(crate) struct OwnerStateV1 {
}
impl OwnerStateV1 {
/// Creates a new `OwnerStateV1` value.
pub(crate) fn new(
envelope: crate::KspWalletEnvelopeV1,
owner_root: crate::SecretKeyV1,
@@ -34,15 +36,18 @@ impl OwnerStateV1 {
};
}
/// Returns the current envelope.
pub(crate) const fn envelope(&self) -> &crate::KspWalletEnvelopeV1 {
return &self.envelope;
}
/// Applies envelope.
pub(crate) fn apply_envelope(&mut self, envelope: crate::KspWalletEnvelopeV1) {
self.envelope = envelope;
return;
}
/// Applies strong view state.
pub(crate) fn apply_strong_view_state(&mut self, envelope: crate::KspWalletEnvelopeV1, metadata_key: crate::SecretKeyV1) {
self.envelope = envelope;
let previous = self.metadata_key.replace(metadata_key);
@@ -50,6 +55,7 @@ impl OwnerStateV1 {
return;
}
/// Executes the crate-internal export transfer operation for `OwnerStateV1`.
pub(crate) fn export_transfer(&self, format: crate::WalletTransferFormat) -> ksp_core_lib::Result<std::vec::Vec<u8>> {
let keypair = match self.solana_keypair.as_ref() {
std::option::Option::Some(value) => value,
@@ -74,6 +80,7 @@ impl OwnerStateV1 {
};
}
/// Executes the crate-internal sign message operation for `OwnerStateV1`.
pub(crate) fn sign_message(&self, message: &[u8]) -> ksp_core_lib::Result<[u8; crate::KSPWALLET_SOLANA_SIGNATURE_BYTES]> {
let keypair = match self.solana_keypair.as_ref() {
std::option::Option::Some(value) => value,
@@ -89,6 +96,7 @@ impl OwnerStateV1 {
return std::result::Result::Ok(signature);
}
/// Executes the crate-internal stage metadata payload operation for `OwnerStateV1`.
pub(crate) fn stage_metadata_payload(&self, payload: crate::MetadataPayloadV1) -> ksp_core_lib::Result<(crate::KspWalletEnvelopeV1, crate::WalletInfo)> {
let metadata_key = match self.metadata_key.as_ref() {
std::option::Option::Some(value) => value,
@@ -138,6 +146,7 @@ impl OwnerStateV1 {
return std::result::Result::Ok((envelope, payload.into_info(crate::WalletCapability::Owner)));
}
/// Executes the crate-internal stage owner password rotation operation for `OwnerStateV1`.
pub(crate) async fn stage_owner_password_rotation(&self, new_password: crate::OwnerPassword) -> ksp_core_lib::Result<crate::KspWalletEnvelopeV1> {
let owner_root = match self.owner_root.as_ref() {
std::option::Option::Some(value) => value,
@@ -172,6 +181,7 @@ impl OwnerStateV1 {
return verify_and_return(envelope);
}
/// Executes the crate-internal stage view password rotation operation for `OwnerStateV1`.
pub(crate) async fn stage_view_password_rotation(&self, new_password: crate::ViewPassword) -> ksp_core_lib::Result<crate::KspWalletEnvelopeV1> {
let metadata_key = match self.metadata_key.as_ref() {
std::option::Option::Some(value) => value,
@@ -201,6 +211,7 @@ impl OwnerStateV1 {
return verify_and_return(envelope);
}
/// Executes the crate-internal stage disable view operation for `OwnerStateV1`.
pub(crate) fn stage_disable_view(&self) -> ksp_core_lib::Result<(crate::KspWalletEnvelopeV1, crate::SecretKeyV1)> {
if !self.envelope.view_descriptor().enabled() {
return std::result::Result::Err(capability_error("Wallet VIEW capability is already disabled"));
@@ -208,6 +219,7 @@ impl OwnerStateV1 {
return self.stage_strong_view_change(std::option::Option::None);
}
/// Executes the crate-internal stage recreate view operation for `OwnerStateV1`.
pub(crate) async fn stage_recreate_view(
&self,
new_password: crate::ViewPassword,
@@ -260,7 +272,6 @@ impl OwnerStateV1 {
std::option::Option::Some(value) => value,
std::option::Option::None => return std::result::Result::Err(crypto_operation_error()),
};
let current_plaintext_result = crate::decrypt_bytes(
current_metadata_key,
self.envelope.metadata().nonce(),
@@ -290,9 +301,8 @@ impl OwnerStateV1 {
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let metadata = crate::WalletEncryptedCompartmentV1::new(crate::WalletCompartmentKindV1::Metadata, metadata_nonce, metadata_ciphertext);
let mut admin_secret = admin_signing_key.to_bytes();
let mut owner_control_plaintext = crate::payload::encode_owner_control_payload(&admin_secret, &new_metadata_key, secret_key);
let mut owner_control_plaintext = crate::encode_owner_control_payload(&admin_secret, &new_metadata_key, secret_key);
admin_secret.zeroize();
let owner_control_nonce = match crate::random_nonce() {
std::result::Result::Ok(value) => value,
@@ -314,7 +324,6 @@ impl OwnerStateV1 {
};
let owner_control =
crate::WalletEncryptedCompartmentV1::new(crate::WalletCompartmentKindV1::OwnerControl, owner_control_nonce, owner_control_ciphertext);
let view_descriptor = match view_slot.as_ref() {
std::option::Option::Some(slot) => crate::WalletViewDescriptorV1::enabled_for_slot(*slot.slot_id()),
std::option::Option::None => crate::WalletViewDescriptorV1::disabled(),
@@ -352,25 +361,30 @@ impl std::ops::Drop for OwnerStateV1 {
}
}
/// Crate-internal `ViewStateV1` state shared across the owning crate.
pub(crate) struct ViewStateV1 {
envelope: crate::KspWalletEnvelopeV1,
metadata_key: std::option::Option<crate::SecretKeyV1>,
}
impl ViewStateV1 {
/// Creates a new `ViewStateV1` value.
pub(crate) fn new(envelope: crate::KspWalletEnvelopeV1, metadata_key: crate::SecretKeyV1) -> Self {
return Self { envelope, metadata_key: std::option::Option::Some(metadata_key) };
}
/// Returns the current envelope.
pub(crate) const fn envelope(&self) -> &crate::KspWalletEnvelopeV1 {
return &self.envelope;
}
/// Applies envelope.
pub(crate) fn apply_envelope(&mut self, envelope: crate::KspWalletEnvelopeV1) {
self.envelope = envelope;
return;
}
/// Executes the crate-internal stage view password rotation operation for `ViewStateV1`.
pub(crate) async fn stage_view_password_rotation(&self, new_password: crate::ViewPassword) -> ksp_core_lib::Result<crate::KspWalletEnvelopeV1> {
let metadata_key = match self.metadata_key.as_ref() {
std::option::Option::Some(value) => value,
@@ -526,7 +540,7 @@ pub async fn open_wallet_owner_v1(source: &[u8], password: crate::OwnerPassword)
std::result::Result::Ok(value) => value,
std::result::Result::Err(_) => return std::result::Result::Err(owner_unlock_error()),
};
let control_result = crate::payload::decode_owner_control_payload(owner_control_plaintext.as_slice());
let control_result = crate::decode_owner_control_payload(owner_control_plaintext.as_slice());
owner_control_plaintext.zeroize();
let control = match control_result {
std::result::Result::Ok(value) => value,
@@ -538,7 +552,6 @@ pub async fn open_wallet_owner_v1(source: &[u8], password: crate::OwnerPassword)
if admin_signing_key.verifying_key().to_bytes() != *envelope.owner_auth_public_key() {
return std::result::Result::Err(authentication_error());
}
let metadata_plaintext_result = crate::decrypt_bytes(
&metadata_key,
envelope.metadata().nonce(),
@@ -555,7 +568,6 @@ pub async fn open_wallet_owner_v1(source: &[u8], password: crate::OwnerPassword)
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let secret_plaintext_result = crate::decrypt_bytes(
&secret_key,
envelope.secret().nonce(),
@@ -590,7 +602,6 @@ pub async fn open_wallet_owner_v1(source: &[u8], password: crate::OwnerPassword)
if &secret_pubkey != metadata_payload.pubkey() {
return std::result::Result::Err(key_material_error());
}
let info = metadata_payload.into_info(crate::WalletCapability::Owner);
let state = OwnerStateV1::new(envelope, owner_root, metadata_key, secret_key, admin_signing_key, solana_keypair);
ksp_logging_lib::debug!(
@@ -616,6 +627,7 @@ pub fn inspect_locked_wallet_v1(source: &[u8]) -> ksp_core_lib::Result<crate::Lo
return std::result::Result::Ok(crate::LockedWalletInfo::new(envelope.view_descriptor().enabled()));
}
/// Executes the crate-internal create wallet v1 from keypair operation for the owning module.
pub(crate) async fn create_wallet_v1_from_keypair(
owner_password: crate::OwnerPassword,
view_password: std::option::Option<crate::ViewPassword>,
@@ -634,14 +646,12 @@ pub(crate) async fn create_wallet_v1_from_keypair(
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let mut admin_secret = match crate::random_bytes::<{ crate::SECRET_KEY_BYTES }>() {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let admin_signing_key = ed25519_dalek::SigningKey::from_bytes(&admin_secret);
let owner_auth_public_key = admin_signing_key.verifying_key().to_bytes();
let mut solana_keypair_bytes = solana_keypair.to_bytes();
let pubkey_result = pubkey_from_keypair_bytes(&solana_keypair_bytes);
let pubkey = match pubkey_result {
@@ -652,8 +662,7 @@ pub(crate) async fn create_wallet_v1_from_keypair(
return std::result::Result::Err(error);
},
};
let metadata_encoded_result = crate::payload::encode_initial_metadata_payload(pubkey, metadata);
let metadata_encoded_result = crate::encode_initial_metadata_payload(pubkey, metadata);
let (mut metadata_plaintext, metadata_payload) = match metadata_encoded_result {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => {
@@ -662,9 +671,8 @@ pub(crate) async fn create_wallet_v1_from_keypair(
return std::result::Result::Err(error);
},
};
let mut owner_control_plaintext = crate::payload::encode_owner_control_payload(&admin_secret, &metadata_key, &secret_key);
let mut owner_control_plaintext = crate::encode_owner_control_payload(&admin_secret, &metadata_key, &secret_key);
admin_secret.zeroize();
let owner_slot_id = match crate::random_bytes::<{ crate::KSPWALLET_V1_SLOT_ID_BYTES }>() {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => {
@@ -684,7 +692,6 @@ pub(crate) async fn create_wallet_v1_from_keypair(
return cleanup_create_error(error, &mut owner_control_plaintext, &mut metadata_plaintext, &mut solana_keypair_bytes);
},
};
let view_material_result = prepare_view_creation(view_password);
let view_material = match view_material_result {
std::result::Result::Ok(value) => value,
@@ -692,7 +699,6 @@ pub(crate) async fn create_wallet_v1_from_keypair(
return cleanup_create_error(error, &mut owner_control_plaintext, &mut metadata_plaintext, &mut solana_keypair_bytes);
},
};
let owner_control_nonce = match crate::random_nonce() {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => {
@@ -711,7 +717,6 @@ pub(crate) async fn create_wallet_v1_from_keypair(
return cleanup_create_error(error, &mut owner_control_plaintext, &mut metadata_plaintext, &mut solana_keypair_bytes);
},
};
let provisional = provisional_envelope(
owner_auth_public_key,
owner_slot_id,
@@ -722,7 +727,6 @@ pub(crate) async fn create_wallet_v1_from_keypair(
metadata_nonce,
secret_nonce,
);
let owner_derived_result = derive_owner_password_key_async(owner_password, owner_kdf.clone()).await;
let owner_derived = match owner_derived_result {
std::result::Result::Ok(value) => value,
@@ -737,7 +741,6 @@ pub(crate) async fn create_wallet_v1_from_keypair(
return cleanup_create_error(error, &mut owner_control_plaintext, &mut metadata_plaintext, &mut solana_keypair_bytes);
},
};
let view_slot_result = seal_view_slot(&provisional, view_material, &metadata_key).await;
let view_slot = match view_slot_result {
std::result::Result::Ok(value) => value,
@@ -745,7 +748,6 @@ pub(crate) async fn create_wallet_v1_from_keypair(
return cleanup_create_error(error, &mut owner_control_plaintext, &mut metadata_plaintext, &mut solana_keypair_bytes);
},
};
let owner_control_ciphertext_result = crate::encrypt_bytes(
&owner_root,
&owner_control_nonce,
@@ -759,7 +761,6 @@ pub(crate) async fn create_wallet_v1_from_keypair(
},
};
owner_control_plaintext.zeroize();
let metadata_ciphertext_result = crate::encrypt_bytes(
&metadata_key,
&metadata_nonce,
@@ -773,7 +774,6 @@ pub(crate) async fn create_wallet_v1_from_keypair(
},
};
metadata_plaintext.zeroize();
let secret_ciphertext_result = crate::encrypt_bytes(
&secret_key,
&secret_nonce,
@@ -787,7 +787,6 @@ pub(crate) async fn create_wallet_v1_from_keypair(
},
};
solana_keypair_bytes.zeroize();
let owner_slot =
crate::WalletKeySlotV1::new(owner_slot_id, crate::WalletKeySlotRoleV1::Owner, owner_kdf, crate::WalletKeyWrapV1::new(owner_wrap_nonce, owner_wrapped));
let view_descriptor = match view_slot.as_ref() {
@@ -822,7 +821,6 @@ pub(crate) async fn create_wallet_v1_from_keypair(
if let std::result::Result::Err(error) = verify_result {
return std::result::Result::Err(error);
}
let info = metadata_payload.into_info(crate::WalletCapability::Owner);
let state = OwnerStateV1::new(envelope, owner_root, metadata_key, secret_key, admin_signing_key, solana_keypair);
ksp_logging_lib::debug!(
@@ -835,6 +833,7 @@ pub(crate) async fn create_wallet_v1_from_keypair(
return std::result::Result::Ok(crate::WalletOwner::from_unlocked(info, state));
}
/// Verifies state signature.
pub(crate) fn verify_state_signature(envelope: &crate::KspWalletEnvelopeV1) -> ksp_core_lib::Result<()> {
let verifying_key_result = ed25519_dalek::VerifyingKey::from_bytes(envelope.owner_auth_public_key());
let verifying_key = match verifying_key_result {

View File

@@ -1,9 +1,9 @@
// file: crates/ksp-wallet-lib/src/wire.rs
// version: 6
// version: 7
//! Strict native `.kspwallet` V1 wire envelope.
use base64::Engine; // rust-rules: derive-import
use base64::Engine; // rust-rules: trait-import
/// Password KDF supported by `.kspwallet` V1 key slots.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -105,6 +105,7 @@ pub struct WalletKdfParametersV1 {
}
impl WalletKdfParametersV1 {
/// Creates a new creation value for `WalletKdfParametersV1`.
pub(crate) fn new_creation(salt: std::vec::Vec<u8>) -> Self {
return Self {
algorithm: WalletKdfAlgorithmV1::Argon2id,
@@ -176,6 +177,7 @@ pub struct WalletKeyWrapV1 {
}
impl WalletKeyWrapV1 {
/// Creates a new `WalletKeyWrapV1` value.
pub(crate) fn new(nonce: [u8; crate::KSPWALLET_V1_XCHACHA_NONCE_BYTES], ciphertext: std::vec::Vec<u8>) -> Self {
return Self { algorithm: WalletAeadAlgorithmV1::XChaCha20Poly1305, nonce, ciphertext };
}
@@ -220,6 +222,7 @@ pub struct WalletKeySlotV1 {
}
impl WalletKeySlotV1 {
/// Creates a new `WalletKeySlotV1` value.
pub(crate) fn new(slot_id: [u8; crate::KSPWALLET_V1_SLOT_ID_BYTES], role: WalletKeySlotRoleV1, kdf: WalletKdfParametersV1, wrap: WalletKeyWrapV1) -> Self {
return Self { slot_id, role, kdf, wrap };
}
@@ -269,10 +272,12 @@ pub struct WalletViewDescriptorV1 {
}
impl WalletViewDescriptorV1 {
/// Executes the crate-internal disabled operation for `WalletViewDescriptorV1`.
pub(crate) const fn disabled() -> Self {
return Self { enabled: false, slot_id: std::option::Option::None };
}
/// Executes the crate-internal enabled for slot operation for `WalletViewDescriptorV1`.
pub(crate) const fn enabled_for_slot(slot_id: [u8; crate::KSPWALLET_V1_SLOT_ID_BYTES]) -> Self {
return Self { enabled: true, slot_id: std::option::Option::Some(slot_id) };
}
@@ -301,6 +306,7 @@ pub struct WalletEncryptedCompartmentV1 {
}
impl WalletEncryptedCompartmentV1 {
/// Creates a new `WalletEncryptedCompartmentV1` value.
pub(crate) fn new(kind: WalletCompartmentKindV1, nonce: [u8; crate::KSPWALLET_V1_XCHACHA_NONCE_BYTES], ciphertext: std::vec::Vec<u8>) -> Self {
return Self {
kind,
@@ -363,6 +369,7 @@ pub struct WalletStateSignatureV1 {
}
impl WalletStateSignatureV1 {
/// Creates a new `WalletStateSignatureV1` value.
pub(crate) const fn new(signature: [u8; crate::KSPWALLET_V1_ED25519_SIGNATURE_BYTES]) -> Self {
return Self { algorithm: WalletStateSignatureAlgorithmV1::Ed25519, signature };
}
@@ -404,6 +411,7 @@ pub struct KspWalletEnvelopeV1 {
}
impl KspWalletEnvelopeV1 {
/// Creates a new internal value for `KspWalletEnvelopeV1`.
pub(crate) fn new_internal(
owner_auth_public_key: [u8; crate::KSPWALLET_V1_ED25519_PUBLIC_KEY_BYTES],
view_descriptor: WalletViewDescriptorV1,
@@ -434,7 +442,6 @@ impl KspWalletEnvelopeV1 {
if source.len() > crate::KSPWALLET_MAX_FILE_BYTES {
return std::result::Result::Err(format_error("Wallet document exceeds the V1 maximum size", "document"));
}
let probe_result = serde_json::from_slice::<RawVersionProbe>(source);
let probe = match probe_result {
std::result::Result::Ok(probe) => probe,
@@ -449,7 +456,6 @@ impl KspWalletEnvelopeV1 {
.with_context("format_version", probe.format_version.to_string()),
);
}
let raw_result = serde_json::from_slice::<RawEnvelopeV1>(source);
let raw = match raw_result {
std::result::Result::Ok(raw) => raw,
@@ -793,7 +799,6 @@ fn parse_raw_envelope(raw: RawEnvelopeV1) -> ksp_core_lib::Result<KspWalletEnvel
.with_context("format_version", raw.format_version.to_string()),
);
}
let owner_auth_public_key =
match decode_fixed::<{ crate::KSPWALLET_V1_ED25519_PUBLIC_KEY_BYTES }>(raw.owner_auth_public_key.as_str(), "owner_auth_public_key") {
std::result::Result::Ok(value) => value,
@@ -803,7 +808,6 @@ fn parse_raw_envelope(raw: RawEnvelopeV1) -> ksp_core_lib::Result<KspWalletEnvel
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
if raw.key_slots.is_empty() || raw.key_slots.len() > crate::KSPWALLET_V1_MAX_KEY_SLOTS {
return std::result::Result::Err(format_error("Wallet key_slots count is invalid for V1", "key_slots"));
}
@@ -853,7 +857,6 @@ fn parse_raw_envelope(raw: RawEnvelopeV1) -> ksp_core_lib::Result<KspWalletEnvel
} else if view_slot.is_some() {
return std::result::Result::Err(format_error("Disabled VIEW descriptor forbids a VIEW key slot", "key_slots"));
}
let owner_control = match parse_compartment(
WalletCompartmentKindV1::OwnerControl,
raw.owner_control.control_version,
@@ -891,7 +894,6 @@ fn parse_raw_envelope(raw: RawEnvelopeV1) -> ksp_core_lib::Result<KspWalletEnvel
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
return std::result::Result::Ok(KspWalletEnvelopeV1 {
owner_auth_public_key,
view_descriptor,

View File

@@ -1,5 +1,5 @@
// file: crates/ksp-wallet-lib/tests/dependency_boundary.rs
// version: 10
// version: 11
//! Wallet-specific dependency and ownership canaries.
@@ -38,6 +38,10 @@ fn wallet_manifest_preserves_dependency_firewall() -> std::io::Result<()> {
std::result::Result::Ok(manifest) => manifest,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let workspace_manifest = match std::fs::read_to_string(crate_root().join("../../Cargo.toml")) {
std::result::Result::Ok(workspace_manifest) => workspace_manifest,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
assert!(manifest.contains("ksp-core-lib"));
assert!(manifest.contains("ksp-logging-lib"));
assert!(manifest.contains("argon2 = { workspace = true, features = [\"alloc\", \"zeroize\"] }"));
@@ -51,6 +55,7 @@ fn wallet_manifest_preserves_dependency_firewall() -> std::io::Result<()> {
assert!(manifest.contains("tokio = { workspace = true, features = [\"rt\"] }"));
assert!(manifest.contains("tempfile.workspace = true"));
assert!(manifest.contains("zeroize.workspace = true"));
assert!(workspace_manifest.contains("ed25519-dalek = { version = \"^3.0\", default-features = false }"));
for forbidden in [
"ksp-config-lib",
"ksp-onchain-transport-lib",

View File

@@ -1,5 +1,5 @@
// file: crates/ksp-wallet-lib/tests/public_api.rs
// version: 8
// version: 9
//! Public API canaries for the Wallet foundation.
@@ -102,15 +102,12 @@ fn public_pre_006_file_persistence_surface_is_available_from_crate_root() {
let create_future =
ksp_wallet_lib::create_wallet_file_v1(path, owner_password, std::option::Option::None, ksp_wallet_lib::WalletCreateMetadataV1::default());
drop(create_future);
let view_password = ksp_wallet_lib::ViewPassword::new(std::string::String::from("public-pre006-view-password"));
let view_future = ksp_wallet_lib::open_wallet_view_file_v1(path, view_password);
drop(view_future);
let owner_password = ksp_wallet_lib::OwnerPassword::new(std::string::String::from("public-pre006-owner-password"));
let owner_future = ksp_wallet_lib::open_wallet_owner_file_v1(path, owner_password);
drop(owner_future);
let inspect_future = ksp_wallet_lib::inspect_locked_wallet_file_v1(path);
drop(inspect_future);
}
@@ -137,7 +134,6 @@ fn public_pre_008_transfer_adapters_are_available_from_crate_root() {
let inspect_method: fn(&[u8], ksp_wallet_lib::WalletTransferFormat) -> ksp_core_lib::Result<ksp_wallet_lib::WalletTransferInspection> =
ksp_wallet_lib::inspect_wallet_transfer;
let _ = inspect_method;
let path = std::path::Path::new("not-polled-transfer");
let inspect_file_future = ksp_wallet_lib::inspect_wallet_transfer_file(path, formats[0]);
drop(inspect_file_future);

View File

@@ -1,5 +1,5 @@
// file: crates/ksp-wallet-lib/unit_tests/administration.rs
// version: 1
// version: 2
const FULL_VECTOR: &[u8] = include_bytes!("../tests/fixtures/kspwallet_v1_full_vector.json");
@@ -10,7 +10,7 @@ fn runtime() -> tokio::runtime::Runtime {
fn published_vector(name: &str) -> (tempfile::TempDir, std::path::PathBuf) {
let directory = tempfile::Builder::new().prefix("ksp-wallet-admin-").tempdir().expect("Wallet administration test directory must be creatable");
let path = directory.path().join(name);
crate::persistence::persist_new_wallet_for_test(path.as_path(), FULL_VECTOR).expect("full Wallet vector must publish for administration test");
crate::persist_new_wallet_for_test(path.as_path(), FULL_VECTOR).expect("full Wallet vector must publish for administration test");
return (directory, path);
}
@@ -26,14 +26,11 @@ fn owner_signing_is_deterministic_and_owner_rotation_preserves_solana_identity()
let signature_before = owner.sign(message).expect("OWNER must sign");
let signature_repeat = owner.sign(message).expect("OWNER repeated signature must succeed");
assert_eq!(signature_before, signature_repeat);
runtime
.block_on(owner.rotate_owner_password(path.as_path(), crate::OwnerPassword::new(std::string::String::from("pre007-new-owner-password"))))
.expect("OWNER password rotation must persist");
let old = runtime.block_on(crate::open_wallet_owner_file_v1(path.as_path(), crate::OwnerPassword::new(std::string::String::from("pre005-owner-password"))));
assert_eq!(old.expect_err("old OWNER password must stop unlocking current file").code(), crate::ERROR_CODE_OWNER_UNLOCK_FAILED);
let reopened = runtime
.block_on(crate::open_wallet_owner_file_v1(path.as_path(), crate::OwnerPassword::new(std::string::String::from("pre007-new-owner-password"))))
.expect("new OWNER password must unlock current file");
@@ -51,21 +48,17 @@ fn view_self_rotation_changes_only_the_current_view_credential() {
let pubkey = *view.pubkey();
let alias = view.alias().map(std::string::String::from);
let notes = view.notes().to_vec();
runtime
.block_on(view.rotate_view_password(path.as_path(), crate::ViewPassword::new(std::string::String::from("pre007-new-view-password"))))
.expect("VIEW self-rotation must persist");
let old = runtime.block_on(crate::open_wallet_view_file_v1(path.as_path(), crate::ViewPassword::new(std::string::String::from("pre005-view-password"))));
assert_eq!(old.expect_err("old VIEW password must stop unlocking current file").code(), crate::ERROR_CODE_VIEW_UNLOCK_FAILED);
let reopened = runtime
.block_on(crate::open_wallet_view_file_v1(path.as_path(), crate::ViewPassword::new(std::string::String::from("pre007-new-view-password"))))
.expect("new VIEW password must unlock current file");
assert_eq!(*reopened.pubkey(), pubkey);
assert_eq!(reopened.alias(), alias.as_deref());
assert_eq!(reopened.notes(), notes.as_slice());
let owner = runtime
.block_on(crate::open_wallet_owner_file_v1(path.as_path(), crate::OwnerPassword::new(std::string::String::from("pre005-owner-password"))))
.expect("VIEW self-rotation must not change OWNER credential");
@@ -80,11 +73,9 @@ fn owner_rotates_view_without_old_view_password() {
.block_on(crate::open_wallet_owner_file_v1(path.as_path(), crate::OwnerPassword::new(std::string::String::from("pre005-owner-password"))))
.expect("OWNER fixture must open");
let pubkey = *owner.pubkey();
runtime
.block_on(owner.rotate_view_password(path.as_path(), crate::ViewPassword::new(std::string::String::from("pre007-owner-set-view-password"))))
.expect("OWNER must rotate VIEW without old VIEW password");
let old = runtime.block_on(crate::open_wallet_view_file_v1(path.as_path(), crate::ViewPassword::new(std::string::String::from("pre005-view-password"))));
assert_eq!(old.expect_err("old VIEW password must stop unlocking current file").code(), crate::ERROR_CODE_VIEW_UNLOCK_FAILED);
let reopened = runtime
@@ -101,7 +92,6 @@ fn owner_metadata_administration_is_visible_to_view_but_does_not_change_pubkey()
.block_on(crate::open_wallet_owner_file_v1(path.as_path(), crate::OwnerPassword::new(std::string::String::from("pre005-owner-password"))))
.expect("OWNER fixture must open");
let pubkey = *owner.pubkey();
runtime
.block_on(owner.update_alias(path.as_path(), std::option::Option::Some(std::string::String::from("pre007-updated-alias"))))
.expect("OWNER alias update must persist");
@@ -109,14 +99,12 @@ fn owner_metadata_administration_is_visible_to_view_but_does_not_change_pubkey()
runtime
.block_on(owner.update_note(path.as_path(), note_id.as_str(), std::string::String::from("pre007-updated-note")))
.expect("OWNER note update must persist");
let view = runtime
.block_on(crate::open_wallet_view_file_v1(path.as_path(), crate::ViewPassword::new(std::string::String::from("pre005-view-password"))))
.expect("VIEW must read OWNER-updated metadata");
assert_eq!(*view.pubkey(), pubkey);
assert_eq!(view.alias(), std::option::Option::Some("pre007-updated-alias"));
assert!(view.notes().iter().any(|note| return note.id() == note_id.as_str() && note.text() == "pre007-updated-note"));
runtime.block_on(owner.delete_note(path.as_path(), note_id.as_str())).expect("OWNER note delete must persist");
let view_after_delete = runtime
.block_on(crate::open_wallet_view_file_v1(path.as_path(), crate::ViewPassword::new(std::string::String::from("pre005-view-password"))))
@@ -139,14 +127,12 @@ fn strong_view_disable_and_recreate_change_current_view_authority_without_changi
let before = crate::KspWalletEnvelopeV1::parse_json(before_bytes.as_slice()).expect("current Wallet must parse");
let old_slot_id = *before.view_descriptor().slot_id().expect("fixture VIEW descriptor must have slot ID");
let old_metadata_ciphertext = before.metadata().ciphertext().to_vec();
runtime.block_on(owner.disable_view(path.as_path())).expect("OWNER strong VIEW disable must persist");
let locked_disabled = runtime.block_on(crate::inspect_locked_wallet_file_v1(path.as_path())).expect("disabled Wallet must inspect");
assert!(!locked_disabled.view_enabled());
let disabled_view =
runtime.block_on(crate::open_wallet_view_file_v1(path.as_path(), crate::ViewPassword::new(std::string::String::from("pre005-view-password"))));
assert_eq!(disabled_view.expect_err("disabled VIEW must not open").code(), crate::ERROR_CODE_CAPABILITY_INSUFFICIENT);
runtime
.block_on(owner.recreate_view(path.as_path(), crate::ViewPassword::new(std::string::String::from("pre007-recreated-view-password"))))
.expect("OWNER strong VIEW recreate must persist");
@@ -155,7 +141,6 @@ fn strong_view_disable_and_recreate_change_current_view_authority_without_changi
let new_slot_id = *recreated.view_descriptor().slot_id().expect("recreated VIEW descriptor must have slot ID");
assert_ne!(new_slot_id, old_slot_id);
assert_ne!(recreated.metadata().ciphertext(), old_metadata_ciphertext.as_slice());
let old = runtime.block_on(crate::open_wallet_view_file_v1(path.as_path(), crate::ViewPassword::new(std::string::String::from("pre005-view-password"))));
assert_eq!(old.expect_err("historical VIEW password must not unlock recreated current state").code(), crate::ERROR_CODE_VIEW_UNLOCK_FAILED);
let recreated_view = runtime
@@ -173,7 +158,6 @@ fn owner_note_mutation_reports_missing_identifier_without_persisting() {
let mut owner = runtime
.block_on(crate::open_wallet_owner_file_v1(path.as_path(), crate::OwnerPassword::new(std::string::String::from("pre005-owner-password"))))
.expect("OWNER fixture must open");
let result = runtime.block_on(owner.update_note(path.as_path(), "AAAAAAAAAAAAAAAAAAAAAA", std::string::String::from("must-not-persist")));
assert_eq!(result.expect_err("missing note identifier must be rejected").code(), crate::ERROR_CODE_NOTE_NOT_FOUND);
assert_eq!(std::fs::read(path.as_path()).expect("Wallet bytes must remain readable"), before);
@@ -189,13 +173,11 @@ fn stale_owner_handle_cannot_overwrite_a_newer_authenticated_wallet_state() {
let mut stale = runtime
.block_on(crate::open_wallet_owner_file_v1(path.as_path(), crate::OwnerPassword::new(std::string::String::from("pre005-owner-password"))))
.expect("second OWNER handle must open on the same state");
runtime
.block_on(first.update_alias(path.as_path(), std::option::Option::Some(std::string::String::from("first-writer"))))
.expect("first OWNER mutation must persist");
let stale_result = runtime.block_on(stale.update_alias(path.as_path(), std::option::Option::Some(std::string::String::from("stale-writer"))));
assert_eq!(stale_result.expect_err("stale OWNER handle must not overwrite newer state").code(), crate::ERROR_CODE_STATE_CONFLICT);
let current = runtime
.block_on(crate::open_wallet_view_file_v1(path.as_path(), crate::ViewPassword::new(std::string::String::from("pre005-view-password"))))
.expect("VIEW must open the first writer's state");
@@ -213,14 +195,12 @@ fn owner_handle_cannot_replace_a_different_authenticated_wallet_state() {
let mut second = runtime
.block_on(crate::open_wallet_owner_file_v1(second_path.as_path(), crate::OwnerPassword::new(std::string::String::from("pre005-owner-password"))))
.expect("second OWNER handle must open");
runtime
.block_on(second.update_alias(second_path.as_path(), std::option::Option::Some(std::string::String::from("different-authenticated-state"))))
.expect("second Wallet must diverge before wrong-target canary");
let wrong_target =
runtime.block_on(first.update_alias(second_path.as_path(), std::option::Option::Some(std::string::String::from("must-not-overwrite-second-wallet"))));
assert_eq!(wrong_target.expect_err("OWNER handle must not replace a different authenticated Wallet state").code(), crate::ERROR_CODE_STATE_CONFLICT);
let unchanged_first = runtime
.block_on(crate::open_wallet_view_file_v1(first_path.as_path(), crate::ViewPassword::new(std::string::String::from("pre005-view-password"))))
.expect("first Wallet must remain unchanged");

View File

@@ -1,7 +1,7 @@
// file: crates/ksp-wallet-lib/unit_tests/crypto.rs
// version: 2
// version: 3
use base64::Engine; // rust-rules: derive-import
use base64::Engine; // rust-rules: trait-import
const VECTOR: &[u8] = include_bytes!("../tests/fixtures/kspwallet_v1_crypto_vectors.json");
@@ -62,14 +62,12 @@ fn deterministic_argon2id_and_xchacha_wrap_vector_matches_external_canary() -> k
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let derived_result = super::derive_argon2id(vector.password_utf8.as_bytes(), salt.as_slice(), vector.memory_kib, vector.iterations, vector.parallelism);
let derived = match derived_result {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
assert_eq!(derived.as_bytes(), &expected_derived);
let content = crate::SecretKeyV1::from_bytes(content_key);
let wrapped_result = crate::wrap_key(&derived, &content, &nonce, aad.as_slice());
let wrapped = match wrapped_result {
@@ -77,7 +75,6 @@ fn deterministic_argon2id_and_xchacha_wrap_vector_matches_external_canary() -> k
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
assert_eq!(wrapped, expected_wrapped);
let unwrapped_result = crate::unwrap_key(&derived, &nonce, aad.as_slice(), wrapped.as_slice());
let unwrapped = match unwrapped_result {
std::result::Result::Ok(value) => value,

View File

@@ -1,7 +1,7 @@
// file: crates/ksp-wallet-lib/unit_tests/payload.rs
// version: 2
// version: 3
use base64::Engine; // rust-rules: derive-import
use base64::Engine; // rust-rules: trait-import
#[test]
fn metadata_payload_rejects_duplicate_note_identifiers() -> ksp_core_lib::Result<()> {

View File

@@ -1,5 +1,5 @@
// file: crates/ksp-wallet-lib/unit_tests/persistence.rs
// version: 3
// version: 4
fn temp_directory() -> std::io::Result<tempfile::TempDir> {
return tempfile::tempdir();
@@ -11,9 +11,8 @@ fn no_clobber_create_keeps_the_first_published_document() {
let destination = directory.path().join("wallet.kspwallet");
let first = b"first-wallet";
let second = b"second-wallet";
crate::persistence::persist_new_wallet_for_test(destination.as_path(), first).expect("first no-clobber publication must succeed");
let second_result = crate::persistence::persist_new_wallet_for_test(destination.as_path(), second);
crate::persist_new_wallet_for_test(destination.as_path(), first).expect("first no-clobber publication must succeed");
let second_result = crate::persist_new_wallet_for_test(destination.as_path(), second);
let error = second_result.expect_err("second publication must not overwrite an existing wallet");
assert_eq!(error.code(), crate::ERROR_CODE_DESTINATION_EXISTS);
let persisted = std::fs::read(destination.as_path()).expect("published wallet must remain readable");
@@ -24,11 +23,10 @@ fn no_clobber_create_keeps_the_first_published_document() {
fn injected_failure_before_publish_leaves_no_destination_or_partial_wallet() {
let directory = temp_directory().expect("Wallet persistence test directory must be creatable");
let destination = directory.path().join("wallet.kspwallet");
let result = crate::persistence::persist_new_wallet_fault_before_publish(destination.as_path(), b"candidate-wallet");
let result = crate::persist_new_wallet_fault_before_publish(destination.as_path(), b"candidate-wallet");
let error = result.expect_err("fault injection must abort before publication");
assert_eq!(error.code(), crate::ERROR_CODE_ATOMIC_PERSISTENCE_FAILED);
assert!(!destination.exists());
let entries = std::fs::read_dir(directory.path()).expect("Wallet persistence test directory must remain readable");
let count = entries.count();
assert_eq!(count, 0, "temporary artifacts should be cleaned on ordinary error unwinding");
@@ -40,17 +38,15 @@ fn concurrent_no_clobber_publish_has_exactly_one_winner() {
let destination = directory.path().join("wallet.kspwallet");
let barrier = std::sync::Arc::new(std::sync::Barrier::new(8));
let mut handles = std::vec::Vec::new();
for index in 0_u8..8 {
let destination = destination.clone();
let barrier = std::sync::Arc::clone(&barrier);
handles.push(std::thread::spawn(move || {
barrier.wait();
let content = [index; 32];
return crate::persistence::persist_new_wallet_for_test(destination.as_path(), content.as_slice());
return crate::persist_new_wallet_for_test(destination.as_path(), content.as_slice());
}));
}
let mut success_count = 0_usize;
let mut exists_count = 0_usize;
let mut unexpected_code = std::option::Option::None;
@@ -74,7 +70,6 @@ fn bounded_reader_rejects_oversized_wallet_before_parser_allocation() {
let destination = directory.path().join("oversized.kspwallet");
let oversized = std::vec![b'x'; crate::KSPWALLET_MAX_FILE_BYTES + 1];
std::fs::write(destination.as_path(), oversized).expect("oversized fixture must be writable");
let runtime = tokio::runtime::Builder::new_current_thread().build().expect("Wallet persistence test runtime must build");
let result = runtime.block_on(crate::inspect_locked_wallet_file_v1(destination.as_path()));
let error = result.expect_err("oversized Wallet file must be rejected before parsing");
@@ -91,7 +86,6 @@ fn public_file_create_and_locked_inspect_round_trip_without_revealing_identity()
.block_on(crate::create_wallet_file_v1(destination.as_path(), owner_password, std::option::Option::None, crate::WalletCreateMetadataV1::default()))
.expect("native Wallet file creation must succeed");
let locked = runtime.block_on(crate::inspect_locked_wallet_file_v1(destination.as_path())).expect("persisted Wallet must inspect successfully");
assert!(!locked.view_enabled());
assert_eq!(created.capability(), crate::WalletCapability::Owner);
assert!(destination.exists());
@@ -110,8 +104,7 @@ fn persisted_full_vector_opens_view_and_owner_through_file_apis() {
let directory = temp_directory().expect("Wallet persistence test directory must be creatable");
let destination = directory.path().join("vector.kspwallet");
let vector = include_bytes!("../tests/fixtures/kspwallet_v1_full_vector.json");
crate::persistence::persist_new_wallet_for_test(destination.as_path(), vector).expect("full vector must publish through no-clobber persistence");
crate::persist_new_wallet_for_test(destination.as_path(), vector).expect("full vector must publish through no-clobber persistence");
let runtime = tokio::runtime::Builder::new_current_thread().build().expect("Wallet persistence test runtime must build");
let view_password = crate::ViewPassword::new(std::string::String::from("pre005-view-password"));
let view = runtime
@@ -121,7 +114,6 @@ fn persisted_full_vector_opens_view_and_owner_through_file_apis() {
let owner = runtime
.block_on(crate::open_wallet_owner_file_v1(destination.as_path(), owner_password))
.expect("persisted full vector must open through OWNER file API");
assert_eq!(view.capability(), crate::WalletCapability::View);
assert_eq!(owner.capability(), crate::WalletCapability::Owner);
assert_eq!(view.pubkey(), owner.pubkey());
@@ -136,8 +128,7 @@ fn replacement_fault_before_publish_preserves_the_previous_wallet_bytes() {
let original = b"ORIGINAL-WALLET-CANARY";
let replacement = b"REPLACEMENT-WALLET-CANARY";
std::fs::write(destination.as_path(), original).expect("replacement test original must be writable");
let result = crate::persistence::replace_wallet_fault_before_publish(destination.as_path(), replacement);
let result = crate::replace_wallet_fault_before_publish(destination.as_path(), replacement);
assert_eq!(result.expect_err("injected replacement fault must fail").code(), crate::ERROR_CODE_ATOMIC_PERSISTENCE_FAILED);
assert_eq!(std::fs::read(destination.as_path()).expect("original Wallet bytes must remain readable"), original);
}
@@ -146,10 +137,9 @@ fn replacement_fault_before_publish_preserves_the_previous_wallet_bytes() {
fn replacement_requires_an_existing_regular_file_and_replaces_complete_content() {
let directory = temp_directory().expect("Wallet replacement test directory must be creatable");
let destination = directory.path().join("replace.kspwallet");
let missing = crate::persistence::replace_wallet_for_test(destination.as_path(), b"replacement");
let missing = crate::replace_wallet_for_test(destination.as_path(), b"replacement");
assert_eq!(missing.expect_err("replacement must not create a missing Wallet destination").code(), crate::ERROR_CODE_IO_FAILED);
std::fs::write(destination.as_path(), b"old").expect("replacement test original must be writable");
crate::persistence::replace_wallet_for_test(destination.as_path(), b"new-complete-wallet").expect("existing Wallet replacement must succeed");
crate::replace_wallet_for_test(destination.as_path(), b"new-complete-wallet").expect("existing Wallet replacement must succeed");
assert_eq!(std::fs::read(destination.as_path()).expect("replaced Wallet must be readable"), b"new-complete-wallet");
}

View File

@@ -1,9 +1,9 @@
// file: crates/ksp-wallet-lib/unit_tests/security.rs
// version: 2
// version: 3
//! Adversarial security canaries for native `.kspwallet` V1.
use base64::Engine; // rust-rules: derive-import
use base64::Engine; // rust-rules: trait-import
const FULL_VECTOR: &[u8] = include_bytes!("../tests/fixtures/kspwallet_v1_full_vector.json");
@@ -27,10 +27,8 @@ fn owner_signed_regions_reject_canonical_tampering_before_unlock() {
fn owner_signature_verification_precedes_owner_and_view_password_kdf() {
let tampered = tamper_base64url_field(FULL_VECTOR, "/metadata/ciphertext");
let runtime = runtime();
let owner = runtime.block_on(crate::open_wallet_owner_v1(tampered.as_slice(), crate::OwnerPassword::new(std::string::String::new())));
assert_eq!(owner.expect_err("tampered state must fail before an empty OWNER password reaches Argon2").code(), crate::ERROR_CODE_AUTHENTICATION_FAILED);
let view = runtime.block_on(crate::open_wallet_view_v1(tampered.as_slice(), crate::ViewPassword::new(std::string::String::new())));
assert_eq!(view.expect_err("tampered state must fail before an empty VIEW password reaches Argon2").code(), crate::ERROR_CODE_AUTHENTICATION_FAILED);
}
@@ -40,12 +38,10 @@ fn view_credential_tampering_does_not_forge_owner_state_and_cannot_unlock_view()
let tampered = tamper_base64url_field(FULL_VECTOR, "/key_slots/1/wrap/ciphertext");
let locked = crate::inspect_locked_wallet_v1(tampered.as_slice()).expect("VIEW wrapping credentials are intentionally outside the OWNER state transcript");
assert!(locked.view_enabled());
let runtime = runtime();
let owner =
runtime.block_on(crate::open_wallet_owner_v1(tampered.as_slice(), crate::OwnerPassword::new(std::string::String::from("pre005-owner-password"))));
assert!(owner.is_ok(), "VIEW credential tampering must not invalidate OWNER unlock");
let view = runtime.block_on(crate::open_wallet_view_v1(tampered.as_slice(), crate::ViewPassword::new(std::string::String::from("pre005-view-password"))));
assert_eq!(view.expect_err("tampered VIEW wrapping must not unlock metadata").code(), crate::ERROR_CODE_VIEW_UNLOCK_FAILED);
}
@@ -55,13 +51,11 @@ fn unlock_failures_do_not_echo_password_material() {
let owner_canary = "OWNER-PASSWORD-LEAK-CANARY";
let view_canary = "VIEW-PASSWORD-LEAK-CANARY";
let runtime = runtime();
let owner = runtime.block_on(crate::open_wallet_owner_v1(FULL_VECTOR, crate::OwnerPassword::new(std::string::String::from(owner_canary))));
let owner_error = owner.expect_err("wrong OWNER password must fail");
assert_eq!(owner_error.code(), crate::ERROR_CODE_OWNER_UNLOCK_FAILED);
assert!(!owner_error.to_string().contains(owner_canary));
assert!(!format!("{owner_error:?}").contains(owner_canary));
let view = runtime.block_on(crate::open_wallet_view_v1(FULL_VECTOR, crate::ViewPassword::new(std::string::String::from(view_canary))));
let view_error = view.expect_err("wrong VIEW password must fail");
assert_eq!(view_error.code(), crate::ERROR_CODE_VIEW_UNLOCK_FAILED);

View File

@@ -1,7 +1,7 @@
// file: crates/ksp-wallet-lib/unit_tests/transcript.rs
// version: 2
// version: 3
use base64::Engine; // rust-rules: derive-import
use base64::Engine; // rust-rules: trait-import
const FIXTURE: &[u8] = include_bytes!("../tests/fixtures/kspwallet_v1_wire_only.json");

View File

@@ -1,9 +1,9 @@
// file: crates/ksp-wallet-lib/unit_tests/transfer.rs
// version: 2
// version: 3
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt; // rust-rules: derive-import
use zeroize::Zeroize; // rust-rules: derive-import
use std::os::unix::fs::PermissionsExt; // rust-rules: trait-import
use zeroize::Zeroize; // rust-rules: trait-import
fn runtime() -> tokio::runtime::Runtime {
return tokio::runtime::Builder::new_current_thread().build().expect("Wallet transfer test runtime must build");
@@ -41,7 +41,6 @@ fn in_memory_inspection_accepts_cli_json_and_canonical_base58_without_exposing_s
crate::inspect_wallet_transfer(json.as_slice(), crate::WalletTransferFormat::SolanaCliJson).expect("Solana CLI JSON inspection must succeed");
let base58_inspection =
crate::inspect_wallet_transfer(base58.as_bytes(), crate::WalletTransferFormat::SolanaKeypairBase58).expect("canonical Base58 inspection must succeed");
assert_eq!(json_inspection.pubkey(), base58_inspection.pubkey());
assert_eq!(json_inspection.format(), crate::WalletTransferFormat::SolanaCliJson);
assert_eq!(base58_inspection.format(), crate::WalletTransferFormat::SolanaKeypairBase58);
@@ -63,7 +62,6 @@ fn external_seed7_transfer_canary_matches_known_solana_keypair_encodings() {
assert_eq!(actual_keypair_bytes, expected_keypair_bytes);
let mut actual_base58 = keypair.to_base58_string();
assert_eq!(actual_base58, expected_base58);
let mut json = serde_json::to_vec(expected_keypair_bytes.as_slice()).expect("external keypair canary must encode as JSON");
let json_inspection =
crate::inspect_wallet_transfer(json.as_slice(), crate::WalletTransferFormat::SolanaCliJson).expect("external Solana CLI JSON canary must inspect");
@@ -71,7 +69,6 @@ fn external_seed7_transfer_canary_matches_known_solana_keypair_encodings() {
.expect("external Base58 canary must inspect");
assert_eq!(json_inspection.pubkey().to_string(), expected_pubkey);
assert_eq!(base58_inspection.pubkey().to_string(), expected_pubkey);
json.zeroize();
actual_base58.zeroize();
actual_keypair_bytes.zeroize();
@@ -84,7 +81,6 @@ fn transfer_decoders_reject_short_inconsistent_or_noncanonical_sources() {
crate::inspect_wallet_transfer(short_json, crate::WalletTransferFormat::SolanaCliJson).expect_err("short Solana CLI JSON must fail").code(),
crate::ERROR_CODE_KEY_MATERIAL_INVALID
);
let keypair = test_keypair();
let mut bytes = keypair.to_bytes();
bytes[63] ^= 0x01;
@@ -97,7 +93,6 @@ fn transfer_decoders_reject_short_inconsistent_or_noncanonical_sources() {
);
bytes.zeroize();
inconsistent_json.zeroize();
assert_eq!(
crate::inspect_wallet_transfer(b"not valid base58 !!!", crate::WalletTransferFormat::SolanaKeypairBase58)
.expect_err("invalid Base58 must fail")
@@ -136,7 +131,6 @@ fn cli_json_import_creates_new_no_clobber_wallet_with_imported_identity_and_meta
.expect("Solana CLI JSON import must succeed");
assert_eq!(owner.pubkey(), expected.pubkey());
assert_eq!(owner.alias(), std::option::Option::Some("imported-wallet"));
let second_password = crate::OwnerPassword::new(std::string::String::from("pre008-second-owner-password"));
let second = runtime.block_on(crate::import_wallet_transfer_v1(
destination.as_path(),
@@ -172,7 +166,6 @@ fn transfer_file_import_is_non_destructive_and_bounded() {
))
.expect("transfer-file import must succeed");
assert_eq!(std::fs::read(source_path.as_path()).expect("source must survive import"), original);
let oversized_path = directory.path().join("oversized.json");
std::fs::write(oversized_path.as_path(), std::vec![b'1'; crate::KSPWALLET_TRANSFER_MAX_SOLANA_CLI_JSON_BYTES + 1])
.expect("oversized transfer fixture must be writable");
@@ -202,13 +195,11 @@ fn owner_exports_cli_json_and_base58_that_roundtrip_to_the_same_imported_keypair
crate::WalletCreateMetadataV1::default(),
))
.expect("Base58 import must succeed");
let mut exported_json = owner.export_transfer(crate::WalletTransferFormat::SolanaCliJson).expect("OWNER JSON export must succeed");
let mut decoded_json: std::vec::Vec<u8> = serde_json::from_slice(exported_json.as_slice()).expect("OWNER JSON export must be valid JSON");
assert_eq!(decoded_json.as_slice(), expected_bytes.as_slice());
let mut exported_base58 = owner.export_transfer(crate::WalletTransferFormat::SolanaKeypairBase58).expect("OWNER Base58 export must succeed");
assert_eq!(exported_base58.as_slice(), source_base58.as_bytes());
exported_json.zeroize();
decoded_json.zeroize();
exported_base58.zeroize();
@@ -233,7 +224,6 @@ fn owner_transfer_file_export_is_no_clobber() {
let second = runtime.block_on(owner.export_transfer_file(export_path.as_path(), crate::WalletTransferFormat::SolanaCliJson));
assert_eq!(second.expect_err("OWNER transfer-file export must not overwrite").code(), crate::ERROR_CODE_DESTINATION_EXISTS);
assert_eq!(std::fs::read(export_path.as_path()).expect("first export must remain intact"), first);
#[cfg(unix)]
{
let mode = std::fs::metadata(export_path.as_path()).expect("export metadata must be readable").permissions().mode() & 0o777;

View File

@@ -1,5 +1,5 @@
// file: crates/ksp-wallet-lib/unit_tests/wallet.rs
// version: 3
// version: 4
const FULL_VECTOR: &[u8] = include_bytes!("../tests/fixtures/kspwallet_v1_full_vector.json");
const FULL_VECTOR_META: &[u8] = include_bytes!("../tests/fixtures/kspwallet_v1_full_vector_meta.json");
@@ -25,7 +25,6 @@ fn externally_generated_full_vector_opens_view_and_owner_independently() -> ksp_
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let view_result = runtime.block_on(crate::open_wallet_view_v1(FULL_VECTOR, crate::ViewPassword::new(vector.view_password_utf8)));
let view = match view_result {
std::result::Result::Ok(value) => value,
@@ -35,7 +34,6 @@ fn externally_generated_full_vector_opens_view_and_owner_independently() -> ksp_
assert_eq!(view.pubkey().to_string(), vector.expected_pubkey);
assert_eq!(view.alias(), std::option::Option::Some(vector.expected_alias.as_str()));
assert_note_texts(view.notes(), vector.expected_notes.as_slice());
let owner_result = runtime.block_on(crate::open_wallet_owner_v1(FULL_VECTOR, crate::OwnerPassword::new(vector.owner_password_utf8)));
let owner = match owner_result {
std::result::Result::Ok(value) => value,
@@ -58,21 +56,18 @@ fn wrong_passwords_do_not_cross_unlock_capabilities() -> ksp_core_lib::Result<()
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let wrong_view = runtime.block_on(crate::open_wallet_view_v1(FULL_VECTOR, crate::ViewPassword::new(std::string::String::from("wrong-view-password"))));
let wrong_view_error = match wrong_view {
std::result::Result::Ok(_) => return std::result::Result::Err(test_error("wrong VIEW password unexpectedly unlocked Wallet")),
std::result::Result::Err(error) => error,
};
assert_eq!(wrong_view_error.code(), crate::ERROR_CODE_VIEW_UNLOCK_FAILED);
let wrong_owner = runtime.block_on(crate::open_wallet_owner_v1(FULL_VECTOR, crate::OwnerPassword::new(std::string::String::from("wrong-owner-password"))));
let wrong_owner_error = match wrong_owner {
std::result::Result::Ok(_) => return std::result::Result::Err(test_error("wrong OWNER password unexpectedly unlocked Wallet")),
std::result::Result::Err(error) => error,
};
assert_eq!(wrong_owner_error.code(), crate::ERROR_CODE_OWNER_UNLOCK_FAILED);
let view_as_owner = runtime.block_on(crate::open_wallet_owner_v1(FULL_VECTOR, crate::OwnerPassword::new(vector.view_password_utf8)));
let view_as_owner_error = match view_as_owner {
std::result::Result::Ok(_) => return std::result::Result::Err(test_error("VIEW password unexpectedly unlocked OWNER")),
@@ -112,7 +107,6 @@ fn view_wrap_can_change_without_breaking_owner_authenticated_state() -> ksp_core
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
assert!(inspected.view_enabled());
let runtime = match test_runtime() {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
@@ -121,7 +115,6 @@ fn view_wrap_can_change_without_breaking_owner_authenticated_state() -> ksp_core
if let std::result::Result::Err(error) = owner_result {
return std::result::Result::Err(error);
}
let view_result = runtime.block_on(crate::open_wallet_view_v1(tampered.as_slice(), crate::ViewPassword::new(vector.view_password_utf8)));
let view_error = match view_result {
std::result::Result::Ok(_) => return std::result::Result::Err(test_error("modified VIEW wrapping unexpectedly unlocked metadata")),
@@ -197,7 +190,6 @@ fn create_uses_calibrated_defaults_and_keeps_locked_projection_private() -> ksp_
std::option::Option::None => return std::result::Result::Err(test_error("created Wallet is missing initial note")),
};
assert_eq!(created_note.text(), note.as_str());
let locked_bytes = match owner.to_json_bytes() {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
@@ -209,7 +201,6 @@ fn create_uses_calibrated_defaults_and_keeps_locked_projection_private() -> ksp_
assert!(!locked_text.contains(alias.as_str()));
assert!(!locked_text.contains(note.as_str()));
assert!(!locked_text.contains(owner.pubkey().to_string().as_str()));
let envelope = match crate::KspWalletEnvelopeV1::parse_json(locked_bytes.as_slice()) {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),

View File

@@ -1,5 +1,5 @@
// file: crates/ksp-wallet-lib/unit_tests/wire.rs
// version: 3
// version: 4
const FIXTURE: &[u8] = include_bytes!("../tests/fixtures/kspwallet_v1_wire_only.json");
@@ -16,7 +16,6 @@ fn strict_v1_fixture_parses_and_round_trips_semantically() -> ksp_core_lib::Resu
assert_eq!(parsed.owner_control().payload_version(), 1);
assert_eq!(parsed.metadata().payload_version(), 1);
assert_eq!(parsed.secret().payload_version(), 1);
let serialized = match parsed.to_json_bytes() {
std::result::Result::Ok(serialized) => serialized,
std::result::Result::Err(error) => return std::result::Result::Err(error),
@@ -89,7 +88,6 @@ fn zero_or_pathological_kdf_parameters_are_rejected_before_crypto() {
std::result::Result::Ok(_) => return,
};
assert_eq!(zero_error.code(), crate::ERROR_CODE_CRYPTO_PARAMETERS_INVALID);
let high_source = std::string::String::from_utf8_lossy(FIXTURE).replacen("\"memory_kib\": 65536", "\"memory_kib\": 1048577", 1);
let high_result = crate::KspWalletEnvelopeV1::parse_json(high_source.as_bytes());
assert!(high_result.is_err());