use std::io::Cursor;
use moonproof_ledger::ledger::dust::{
DustLocalState, DustNullifier, DustParameters, DustSecretKey, QualifiedDustOutput,
};
use moonproof_ledger::serialize::{tagged_deserialize, tagged_serialize};
use moonproof_ledger::zswap::keys::SecretKeys as ZswapSecretKeys;
use moonproof_ledger::zswap::local::State as ZswapLocalState;
use serde::{Deserialize, Serialize};
use crate::abstractions::{NetworkId, ProtocolVersion, SyncProgress};
use crate::dust::{DustState, PendingDustSpend};
use crate::error::{Result, WalletError};
use crate::facade::FacadeState;
use crate::shielded::state::Db as ShieldedDb;
use crate::shielded::ShieldedState;
use crate::unshielded::{UnshieldedState, UtxoWithMeta};
pub const SNAPSHOT_FORMAT_VERSION: u32 = 1;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WalletSnapshot {
pub format_version: u32,
pub network_id: NetworkId,
pub protocol_version: ProtocolVersion,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub chain_id: Option<String>,
pub shielded: ShieldedSnapshot,
pub unshielded: UnshieldedSnapshot,
pub dust: DustSnapshot,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShieldedSnapshot {
pub progress: SyncProgress,
pub local_state_hex: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnshieldedSnapshot {
pub progress: SyncProgress,
pub available: Vec<UtxoWithMeta>,
pub pending: Vec<UtxoWithMeta>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DustSnapshot {
pub progress: SyncProgress,
pub local_state_hex: String,
pub pending_dust_hex: Vec<String>,
}
impl WalletSnapshot {
pub fn capture_for_chain(state: &FacadeState, chain_id: Option<String>) -> Result<Self> {
let mut snap = Self::capture(state)?;
snap.chain_id = chain_id;
Ok(snap)
}
pub fn capture(state: &FacadeState) -> Result<Self> {
Ok(Self {
format_version: SNAPSHOT_FORMAT_VERSION,
network_id: state.network_id().clone(),
protocol_version: state.protocol_version(),
chain_id: None,
shielded: ShieldedSnapshot::capture(&state.shielded)?,
unshielded: UnshieldedSnapshot::capture(&state.unshielded, state.unshielded_progress()),
dust: DustSnapshot::capture(&state.dust)?,
})
}
pub fn restore(
self,
zswap_keys: &ZswapSecretKeys,
dust_secret: &DustSecretKey,
dust_params: DustParameters,
) -> Result<FacadeState> {
if self.format_version > SNAPSHOT_FORMAT_VERSION {
return Err(WalletError::Serialization(format!(
"snapshot format_version {} is newer than this build supports ({})",
self.format_version, SNAPSHOT_FORMAT_VERSION
)));
}
let WalletSnapshot {
format_version: _,
network_id,
protocol_version,
chain_id: _,
shielded,
unshielded,
dust,
} = self;
let shielded_state = shielded.restore(zswap_keys, network_id.clone(), protocol_version)?;
let unshielded_progress = unshielded.progress;
let unshielded_state = unshielded.restore();
let dust_state = dust.restore(
dust_secret,
dust_params,
network_id.clone(),
protocol_version,
)?;
let facade = FacadeState::new(shielded_state, unshielded_state, dust_state, network_id)
.with_protocol_version(protocol_version)
.with_unshielded_progress(unshielded_progress);
Ok(facade)
}
pub fn to_bytes(&self) -> Result<Vec<u8>> {
serde_json::to_vec_pretty(self)
.map_err(|e| WalletError::Serialization(format!("encode wallet snapshot: {e}")))
}
pub fn to_bytes_compact(&self) -> Result<Vec<u8>> {
serde_json::to_vec(self)
.map_err(|e| WalletError::Serialization(format!("encode wallet snapshot: {e}")))
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
let snap: Self = serde_json::from_slice(bytes)
.map_err(|e| WalletError::Serialization(format!("decode wallet snapshot: {e}")))?;
if snap.format_version > SNAPSHOT_FORMAT_VERSION {
return Err(WalletError::Serialization(format!(
"snapshot format_version {} is newer than this build supports ({})",
snap.format_version, SNAPSHOT_FORMAT_VERSION
)));
}
Ok(snap)
}
}
impl ShieldedSnapshot {
fn capture(state: &ShieldedState) -> Result<Self> {
let mut bytes = Vec::new();
tagged_serialize(state.local(), &mut bytes).map_err(|e| {
WalletError::Serialization(format!("tagged_serialize(ZswapLocalState): {e}"))
})?;
Ok(Self {
progress: state.progress(),
local_state_hex: hex::encode(&bytes),
})
}
fn restore(
self,
zswap_keys: &ZswapSecretKeys,
network_id: NetworkId,
protocol_version: ProtocolVersion,
) -> Result<ShieldedState> {
let bytes = hex::decode(&self.local_state_hex).map_err(|e| {
WalletError::Serialization(format!(
"shielded snapshot: local_state_hex is not hex: {e}"
))
})?;
let mut cursor = Cursor::new(bytes);
let local: ZswapLocalState<ShieldedDb> = tagged_deserialize(&mut cursor).map_err(|e| {
WalletError::Serialization(format!("tagged_deserialize(ZswapLocalState): {e}"))
})?;
let mut state = ShieldedState::init(local, zswap_keys, network_id);
state = state.with_protocol_version(protocol_version);
state = state.with_progress_update(
Some(self.progress.applied_index),
Some(self.progress.highest_relevant_wallet_index),
Some(self.progress.highest_index),
Some(self.progress.highest_relevant_index),
Some(self.progress.is_connected),
);
Ok(state)
}
}
impl UnshieldedSnapshot {
fn capture(state: &UnshieldedState, progress: SyncProgress) -> Self {
let (available, pending) = state.to_arrays();
Self {
progress,
available,
pending,
}
}
fn restore(self) -> UnshieldedState {
UnshieldedState::restore(self.available, self.pending)
}
}
impl DustSnapshot {
fn capture(state: &DustState) -> Result<Self> {
let mut local_bytes = Vec::new();
tagged_serialize(state.local(), &mut local_bytes).map_err(|e| {
WalletError::Serialization(format!("tagged_serialize(DustLocalState): {e}"))
})?;
let mut pending_dust_hex = Vec::with_capacity(state.pending_len());
for p in state.pending() {
let mut buf = Vec::new();
tagged_serialize(&p.utxo, &mut buf).map_err(|e| {
WalletError::Serialization(format!("tagged_serialize(QualifiedDustOutput): {e}"))
})?;
let utxo_len = u32::try_from(buf.len()).map_err(|_| {
WalletError::Serialization("QualifiedDustOutput tagged size > u32::MAX".to_owned())
})?;
let mut framed = Vec::with_capacity(4 + buf.len() + 64);
framed.extend_from_slice(&utxo_len.to_le_bytes());
framed.extend_from_slice(&buf);
tagged_serialize(&p.nullifier, &mut framed).map_err(|e| {
WalletError::Serialization(format!("tagged_serialize(DustNullifier): {e}"))
})?;
pending_dust_hex.push(hex::encode(&framed));
}
Ok(Self {
progress: state.progress(),
local_state_hex: hex::encode(&local_bytes),
pending_dust_hex,
})
}
fn restore(
self,
secret_key: &DustSecretKey,
_dust_params: DustParameters,
network_id: NetworkId,
protocol_version: ProtocolVersion,
) -> Result<DustState> {
let bytes = hex::decode(&self.local_state_hex).map_err(|e| {
WalletError::Serialization(format!("dust snapshot: local_state_hex is not hex: {e}"))
})?;
let mut cursor = Cursor::new(bytes);
let local: DustLocalState<crate::dust::ledger_adapter::Db> =
tagged_deserialize(&mut cursor).map_err(|e| {
WalletError::Serialization(format!("tagged_deserialize(DustLocalState): {e}"))
})?;
let mut pending = Vec::with_capacity(self.pending_dust_hex.len());
for hex_blob in &self.pending_dust_hex {
let raw = hex::decode(hex_blob).map_err(|e| {
WalletError::Serialization(format!("dust pending entry: not hex: {e}"))
})?;
if raw.len() < 4 {
return Err(WalletError::Serialization(
"dust pending entry: missing length prefix".to_owned(),
));
}
let utxo_len = u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]) as usize;
if 4 + utxo_len > raw.len() {
return Err(WalletError::Serialization(
"dust pending entry: declared length overruns blob".to_owned(),
));
}
let mut utxo_cursor = Cursor::new(&raw[4..4 + utxo_len]);
let utxo: QualifiedDustOutput = tagged_deserialize(&mut utxo_cursor).map_err(|e| {
WalletError::Serialization(format!("tagged_deserialize(QualifiedDustOutput): {e}"))
})?;
let mut null_cursor = Cursor::new(&raw[4 + utxo_len..]);
let nullifier: DustNullifier = tagged_deserialize(&mut null_cursor).map_err(|e| {
WalletError::Serialization(format!("tagged_deserialize(DustNullifier): {e}"))
})?;
pending.push(PendingDustSpend::new(utxo, nullifier));
}
let public_key = moonproof_ledger::ledger::dust::DustPublicKey::from(secret_key.clone());
let state = DustState::restore(
local,
public_key,
pending,
self.progress,
protocol_version,
network_id,
);
Ok(state)
}
}
#[cfg(test)]
mod tests {
use super::*;
use moonproof_ledger::base_crypto::time::Duration;
use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
use moonproof_ledger::zswap::keys::Seed as ZswapSeed;
fn zswap_keys() -> ZswapSecretKeys {
ZswapSecretKeys::from(ZswapSeed::from([0x01u8; 32]))
}
fn dust_params() -> DustParameters {
DustParameters {
night_dust_ratio: 1_000,
generation_decay_rate: 1,
dust_grace_period: Duration::from_secs(60),
}
}
fn dust_sk() -> DustSecretKey {
DustSecretKey::derive_secret_key(&[0x02u8; 32])
}
fn empty_facade() -> FacadeState {
let sh = ShieldedState::init_empty(&zswap_keys(), NetworkId::Undeployed);
let un = UnshieldedState::empty();
let du = DustState::init_empty(dust_params(), &dust_sk(), NetworkId::Undeployed);
FacadeState::new(sh, un, du, NetworkId::Undeployed)
}
#[test]
fn capture_then_restore_round_trips_an_empty_facade() {
let facade = empty_facade();
let snap = WalletSnapshot::capture(&facade).expect("capture");
let bytes = snap.to_bytes().expect("encode");
let decoded = WalletSnapshot::from_bytes(&bytes).expect("decode");
let restored = decoded
.restore(&zswap_keys(), &dust_sk(), dust_params())
.expect("restore");
assert_eq!(restored.network_id(), facade.network_id());
assert_eq!(restored.protocol_version(), facade.protocol_version());
assert_eq!(restored.shielded.coin_count(), 0);
assert_eq!(restored.unshielded.available_len(), 0);
assert_eq!(restored.unshielded.pending_len(), 0);
assert_eq!(restored.dust.pending_len(), 0);
}
#[test]
fn snapshot_format_version_is_one() {
let snap = WalletSnapshot::capture(&empty_facade()).unwrap();
assert_eq!(snap.format_version, SNAPSHOT_FORMAT_VERSION);
assert_eq!(SNAPSHOT_FORMAT_VERSION, 1);
}
#[test]
fn newer_format_version_rejected_on_decode() {
let mut snap = WalletSnapshot::capture(&empty_facade()).unwrap();
snap.format_version = 9999;
let bytes = serde_json::to_vec(&snap).unwrap();
let err = WalletSnapshot::from_bytes(&bytes).unwrap_err();
assert!(matches!(err, WalletError::Serialization(ref m) if m.contains("format_version")));
}
#[test]
fn pretty_and_compact_decode_to_same_struct() {
let facade = empty_facade();
let snap = WalletSnapshot::capture(&facade).unwrap();
let pretty = snap.to_bytes().unwrap();
let compact = snap.to_bytes_compact().unwrap();
let a = WalletSnapshot::from_bytes(&pretty).unwrap();
let b = WalletSnapshot::from_bytes(&compact).unwrap();
assert_eq!(a.network_id, b.network_id);
assert_eq!(a.shielded.local_state_hex, b.shielded.local_state_hex);
assert_eq!(a.dust.local_state_hex, b.dust.local_state_hex);
}
}