Files
khadhroony-solana-project/crates/ksp-wallet-lib/src/owner.rs
2026-08-22 09:39:13 +02:00

351 lines
16 KiB
Rust

// file: crates/ksp-wallet-lib/src/owner.rs
// version: 8
/// Authorized OWNER capability handle.
///
/// OWNER exposes protected metadata, Solana message signing and the authenticated administration operations defined by the authenticated native Wallet format. Secret key
/// material remains encapsulated and is never exposed through a general-purpose getter.
pub struct WalletOwner {
info: crate::WalletInfo,
state: crate::OwnerState,
}
impl WalletOwner {
/// Builds `WalletOwner` from unlocked.
pub(crate) fn from_unlocked(info: crate::WalletInfo, state: crate::OwnerState) -> Self {
return Self { info, state };
}
/// Returns the native Wallet format version backing this authorized handle.
#[must_use]
pub const fn format_version(&self) -> u32 {
return self.info.format_version();
}
/// Returns the authorization capability represented by this handle.
#[must_use]
pub const fn capability(&self) -> crate::WalletCapability {
return crate::WalletCapability::Owner;
}
/// Returns the authorized Solana public key.
#[must_use]
pub const fn pubkey(&self) -> &ksp_core_lib::Pubkey {
return self.info.pubkey();
}
/// Returns the protected internal alias, when present.
#[must_use]
pub fn alias(&self) -> std::option::Option<&str> {
return self.info.alias();
}
/// Returns the protected notes.
#[must_use]
pub fn notes(&self) -> &[crate::WalletNote] {
return self.info.notes();
}
/// Returns the complete safe metadata projection for this OWNER capability.
#[must_use]
pub fn info(&self) -> &crate::WalletInfo {
ksp_logging_lib::trace!(
target: crate::TRACING_TARGET,
operation = "wallet_info_projection",
capability = "owner",
"wallet metadata projection requested"
);
return &self.info;
}
/// Returns one short-lived V1 Solana keypair copy for crate-internal authenticated migration.
pub(crate) fn clone_v1_solana_keypair_for_migration(&self) -> ksp_core_lib::Result<solana_keypair::Keypair> {
return match &self.state {
crate::OwnerState::V1(state) => state.clone_solana_keypair_for_migration(),
crate::OwnerState::V2(_) => {
std::result::Result::Err(ksp_core_lib::Error::new(crate::ERROR_CODE_MIGRATION_INVALID, "Wallet migration source is not V1"))
},
};
}
/// Replaces protected metadata exactly in memory during authenticated migration, preserving stable note identifiers.
pub(crate) fn replace_metadata_for_migration(&mut self, payload: crate::MetadataPayloadV1) -> ksp_core_lib::Result<()> {
let (envelope, info) = match self.state.stage_metadata_payload(payload) {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
if let std::result::Result::Err(error) = self.state.apply_envelope(envelope) {
return std::result::Result::Err(error);
}
self.info = info;
return std::result::Result::Ok(());
}
/// Exports the immutable Solana keypair through one explicitly selected transfer adapter.
///
/// The returned bytes contain secret key material and are owned by the caller. Callers should minimize their lifetime and zeroize the buffer after use.
/// VIEW has no corresponding export API.
pub fn export_transfer(&self, format: crate::WalletTransferFormat) -> ksp_core_lib::Result<std::vec::Vec<u8>> {
let encoded = self.state.export_transfer(format);
if let std::result::Result::Ok(value) = encoded.as_ref() {
ksp_logging_lib::debug!(
target: crate::TRACING_TARGET,
operation = "wallet_export_transfer",
capability = "owner",
transfer_format = format.code(),
transfer_bytes = value.len(),
"wallet secret encoded through explicit OWNER transfer adapter"
);
}
return encoded;
}
/// Exports the immutable Solana keypair to a new no-clobber transfer file.
///
/// The destination parent must already exist. On Unix, Wallet attempts `0600` permissions as filesystem hygiene, but OS ACLs are not part of the
/// `.kspwallet` cryptographic security guarantee. Existing destinations are never overwritten.
pub async fn export_transfer_file(
&self,
destination: impl std::convert::AsRef<std::path::Path>,
format: crate::WalletTransferFormat,
) -> ksp_core_lib::Result<()> {
let encoded = match self.state.export_transfer(format) {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let result = crate::write_wallet_transfer_file(destination.as_ref().to_path_buf(), encoded, format).await;
if result.is_ok() {
ksp_logging_lib::debug!(
target: crate::TRACING_TARGET,
operation = "wallet_export_transfer_file",
capability = "owner",
transfer_format = format.code(),
"wallet secret exported through explicit OWNER transfer adapter"
);
}
return result;
}
/// Signs one caller-provided message with the Wallet's immutable Solana keypair.
///
/// The returned bytes are the 64-byte Ed25519 signature. The Solana secret key is never returned or logged.
pub fn sign(&self, message: &[u8]) -> ksp_core_lib::Result<[u8; crate::KSPWALLET_SOLANA_SIGNATURE_BYTES]> {
let signature = self.state.sign_message(message);
if signature.is_ok() {
ksp_logging_lib::debug!(
target: crate::TRACING_TARGET,
operation = "wallet_sign",
capability = "owner",
message_bytes = message.len(),
"wallet message signed"
);
}
return signature;
}
/// Updates or clears the protected internal alias and atomically replaces the existing wallet file.
pub async fn update_alias(
&mut self,
destination: impl std::convert::AsRef<std::path::Path>,
alias: std::option::Option<std::string::String>,
) -> ksp_core_lib::Result<()> {
let mut payload = crate::MetadataPayloadV1::from_info(&self.info);
let mutation_result = payload.set_alias(alias);
if let std::result::Result::Err(error) = mutation_result {
return std::result::Result::Err(error);
}
return self.persist_metadata_payload(destination.as_ref().to_path_buf(), payload, "wallet_update_alias").await;
}
/// Adds one protected note and returns its generated stable note identifier after successful persistence.
pub async fn add_note(
&mut self,
destination: impl std::convert::AsRef<std::path::Path>,
text: std::string::String,
) -> ksp_core_lib::Result<std::string::String> {
let mut payload = crate::MetadataPayloadV1::from_info(&self.info);
let note_id = match payload.add_note(text) {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let persist_result = self.persist_metadata_payload(destination.as_ref().to_path_buf(), payload, "wallet_add_note").await;
if let std::result::Result::Err(error) = persist_result {
return std::result::Result::Err(error);
}
return std::result::Result::Ok(note_id);
}
/// Updates one protected note selected by its stable identifier.
pub async fn update_note(
&mut self,
destination: impl std::convert::AsRef<std::path::Path>,
note_id: &str,
text: std::string::String,
) -> ksp_core_lib::Result<()> {
let mut payload = crate::MetadataPayloadV1::from_info(&self.info);
let mutation_result = payload.update_note(note_id, text);
if let std::result::Result::Err(error) = mutation_result {
return std::result::Result::Err(error);
}
return self.persist_metadata_payload(destination.as_ref().to_path_buf(), payload, "wallet_update_note").await;
}
/// Deletes one protected note selected by its stable identifier.
pub async fn delete_note(&mut self, destination: impl std::convert::AsRef<std::path::Path>, note_id: &str) -> ksp_core_lib::Result<()> {
let mut payload = crate::MetadataPayloadV1::from_info(&self.info);
let mutation_result = payload.delete_note(note_id);
if let std::result::Result::Err(error) = mutation_result {
return std::result::Result::Err(error);
}
return self.persist_metadata_payload(destination.as_ref().to_path_buf(), payload, "wallet_delete_note").await;
}
/// Rotates the OWNER password while preserving the Wallet identity, metadata content key and Solana keypair.
pub async fn rotate_owner_password(
&mut self,
destination: impl std::convert::AsRef<std::path::Path>,
new_password: crate::OwnerPassword,
) -> ksp_core_lib::Result<()> {
let envelope = match self.state.stage_owner_password_rotation(new_password).await {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let persist_result = self.state.persist_staged(destination.as_ref().to_path_buf(), &envelope).await;
if let std::result::Result::Err(error) = persist_result {
return std::result::Result::Err(error);
}
if let std::result::Result::Err(error) = self.state.apply_envelope(envelope) {
return std::result::Result::Err(error);
}
ksp_logging_lib::debug!(
target: crate::TRACING_TARGET,
operation = "wallet_rotate_owner_password",
capability = "owner",
"wallet OWNER password rotated"
);
return std::result::Result::Ok(());
}
/// Rotates the existing VIEW password without knowing the previous VIEW password.
///
/// This is a credential rotation only: it rewraps the same metadata content key in the same OWNER-signed VIEW slot descriptor.
pub async fn rotate_view_password(
&mut self,
destination: impl std::convert::AsRef<std::path::Path>,
new_password: crate::ViewPassword,
) -> ksp_core_lib::Result<()> {
let envelope = match self.state.stage_view_password_rotation(new_password).await {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let persist_result = self.state.persist_staged(destination.as_ref().to_path_buf(), &envelope).await;
if let std::result::Result::Err(error) = persist_result {
return std::result::Result::Err(error);
}
if let std::result::Result::Err(error) = self.state.apply_envelope(envelope) {
return std::result::Result::Err(error);
}
ksp_logging_lib::debug!(
target: crate::TRACING_TARGET,
operation = "wallet_rotate_view_password",
capability = "owner",
"wallet VIEW password rotated by OWNER"
);
return std::result::Result::Ok(());
}
/// Strongly disables VIEW by generating a new metadata content key and removing the VIEW slot/descriptor.
///
/// Existing historical copies remain outside the revocation guarantee, but the old VIEW metadata key cannot decrypt future metadata states.
pub async fn disable_view(&mut self, destination: impl std::convert::AsRef<std::path::Path>) -> ksp_core_lib::Result<()> {
let (envelope, metadata_key) = match self.state.stage_disable_view() {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let persist_result = self.state.persist_staged(destination.as_ref().to_path_buf(), &envelope).await;
if let std::result::Result::Err(error) = persist_result {
return std::result::Result::Err(error);
}
if let std::result::Result::Err(error) = self.state.apply_strong_view_state(envelope, metadata_key) {
return std::result::Result::Err(error);
}
ksp_logging_lib::debug!(
target: crate::TRACING_TARGET,
operation = "wallet_disable_view",
capability = "owner",
"wallet VIEW capability strongly disabled"
);
return std::result::Result::Ok(());
}
/// Strongly recreates VIEW with a fresh metadata content key, fresh slot identifier and new VIEW password.
pub async fn recreate_view(
&mut self,
destination: impl std::convert::AsRef<std::path::Path>,
new_password: crate::ViewPassword,
) -> ksp_core_lib::Result<()> {
let (envelope, metadata_key) = match self.state.stage_recreate_view(new_password).await {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let persist_result = self.state.persist_staged(destination.as_ref().to_path_buf(), &envelope).await;
if let std::result::Result::Err(error) = persist_result {
return std::result::Result::Err(error);
}
if let std::result::Result::Err(error) = self.state.apply_strong_view_state(envelope, metadata_key) {
return std::result::Result::Err(error);
}
ksp_logging_lib::debug!(
target: crate::TRACING_TARGET,
operation = "wallet_recreate_view",
capability = "owner",
"wallet VIEW capability strongly recreated"
);
return std::result::Result::Ok(());
}
/// Serializes the complete locked native Wallet in its current V1 or V2 wire format.
pub fn to_native_bytes(&self) -> ksp_core_lib::Result<std::vec::Vec<u8>> {
return self.state.native_bytes();
}
/// Serializes a V1 handle as its historical JSON document.
///
/// V2 handles return a format error instead of being converted implicitly.
pub fn to_json_bytes(&self) -> ksp_core_lib::Result<std::vec::Vec<u8>> {
return self.state.json_bytes_v1();
}
async fn persist_metadata_payload(
&mut self,
destination: std::path::PathBuf,
payload: crate::MetadataPayloadV1,
operation: &'static str,
) -> ksp_core_lib::Result<()> {
let (envelope, info) = match self.state.stage_metadata_payload(payload) {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let persist_result = self.state.persist_staged(destination, &envelope).await;
if let std::result::Result::Err(error) = persist_result {
return std::result::Result::Err(error);
}
if let std::result::Result::Err(error) = self.state.apply_envelope(envelope) {
return std::result::Result::Err(error);
}
self.info = info;
ksp_logging_lib::debug!(target: crate::TRACING_TARGET, operation = operation, capability = "owner", "wallet protected metadata updated");
return std::result::Result::Ok(());
}
}
impl std::fmt::Debug for WalletOwner {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
return formatter.debug_struct("WalletOwner").field("info", &self.info).field("unlocked_state", &"<redacted>").finish();
}
}
#[cfg(test)]
#[path = "../unit_tests/administration.rs"]
mod tests;