use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use crate::error::{Result, WalletError};
use crate::types::{Amount, CoinRecipe, TokenType};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct UtxoId {
pub intent_hash: [u8; 32],
pub output_no: u32,
}
impl UtxoId {
#[inline]
#[must_use]
pub const fn new(intent_hash: [u8; 32], output_no: u32) -> Self {
Self {
intent_hash,
output_no,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct UnshieldedUtxo {
pub id: UtxoId,
pub value: u128,
pub token_type: TokenType,
pub owner: [u8; 32],
}
impl UnshieldedUtxo {
#[inline]
#[must_use]
pub fn new(id: UtxoId, value: u128, token_type: TokenType, owner: [u8; 32]) -> Self {
Self {
id,
value,
token_type,
owner,
}
}
}
impl CoinRecipe for UnshieldedUtxo {
#[inline]
fn token_type(&self) -> &TokenType {
&self.token_type
}
#[inline]
fn value(&self) -> Amount {
Amount::from(self.value)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct UtxoMeta {
pub ctime: i64,
pub registered_for_dust_generation: bool,
}
impl UtxoMeta {
#[inline]
#[must_use]
pub const fn new(ctime: i64, registered_for_dust_generation: bool) -> Self {
Self {
ctime,
registered_for_dust_generation,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UtxoWithMeta {
pub utxo: UnshieldedUtxo,
pub meta: UtxoMeta,
}
impl UtxoWithMeta {
#[inline]
#[must_use]
pub fn new(utxo: UnshieldedUtxo, meta: UtxoMeta) -> Self {
Self { utxo, meta }
}
#[inline]
#[must_use]
pub fn id(&self) -> UtxoId {
self.utxo.id
}
}
impl CoinRecipe for UtxoWithMeta {
#[inline]
fn token_type(&self) -> &TokenType {
self.utxo.token_type()
}
#[inline]
fn value(&self) -> Amount {
self.utxo.value()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum UpdateStatus {
Success,
Failure,
PartialSuccess,
}
impl UpdateStatus {
#[inline]
#[must_use]
pub fn is_success_or_partial(self) -> bool {
matches!(self, Self::Success | Self::PartialSuccess)
}
#[inline]
#[must_use]
pub fn is_failure(self) -> bool {
matches!(self, Self::Failure)
}
#[must_use]
pub fn as_label(self) -> &'static str {
match self {
Self::Success => "SUCCESS",
Self::Failure => "FAILURE",
Self::PartialSuccess => "PARTIAL_SUCCESS",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UnshieldedUpdate {
pub created_utxos: Vec<UtxoWithMeta>,
pub spent_utxos: Vec<UtxoWithMeta>,
pub status: UpdateStatus,
}
impl UnshieldedUpdate {
#[must_use]
pub fn success(created: Vec<UtxoWithMeta>, spent: Vec<UtxoWithMeta>) -> Self {
Self {
created_utxos: created,
spent_utxos: spent,
status: UpdateStatus::Success,
}
}
#[must_use]
pub fn failure(created: Vec<UtxoWithMeta>, spent: Vec<UtxoWithMeta>) -> Self {
Self {
created_utxos: created,
spent_utxos: spent,
status: UpdateStatus::Failure,
}
}
#[must_use]
pub fn partial_success(created: Vec<UtxoWithMeta>, spent: Vec<UtxoWithMeta>) -> Self {
Self {
created_utxos: created,
spent_utxos: spent,
status: UpdateStatus::PartialSuccess,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct UnshieldedState {
available: IndexMap<UtxoId, UtxoWithMeta>,
pending: IndexMap<UtxoId, UtxoWithMeta>,
}
impl UnshieldedState {
#[inline]
#[must_use]
pub fn empty() -> Self {
Self::default()
}
#[must_use]
pub fn restore(
available: impl IntoIterator<Item = UtxoWithMeta>,
pending: impl IntoIterator<Item = UtxoWithMeta>,
) -> Self {
let mut s = Self::empty();
for u in available {
s.available.insert(u.id(), u);
}
for u in pending {
s.pending.insert(u.id(), u);
}
s
}
#[inline]
pub fn available(&self) -> impl ExactSizeIterator<Item = &UtxoWithMeta> {
self.available.values()
}
#[inline]
pub fn pending(&self) -> impl ExactSizeIterator<Item = &UtxoWithMeta> {
self.pending.values()
}
#[inline]
#[must_use]
pub fn has_available(&self, id: &UtxoId) -> bool {
self.available.contains_key(id)
}
#[inline]
#[must_use]
pub fn has_pending(&self, id: &UtxoId) -> bool {
self.pending.contains_key(id)
}
#[inline]
#[must_use]
pub fn available_len(&self) -> usize {
self.available.len()
}
#[inline]
#[must_use]
pub fn pending_len(&self) -> usize {
self.pending.len()
}
#[must_use]
pub fn to_arrays(&self) -> (Vec<UtxoWithMeta>, Vec<UtxoWithMeta>) {
(
self.available.values().cloned().collect(),
self.pending.values().cloned().collect(),
)
}
pub fn spend(mut self, utxo: &UtxoWithMeta) -> Result<Self> {
let id = utxo.id();
if self.available.shift_remove(&id).is_none() {
return Err(WalletError::UtxoNotFound { id });
}
self.pending.insert(id, utxo.clone());
Ok(self)
}
pub fn spend_by_id(self, id: UtxoId) -> Result<Self> {
let Some(found) = self.available.get(&id).cloned() else {
return Err(WalletError::UtxoNotFound { id });
};
self.spend(&found)
}
#[must_use]
pub fn rollback_spend(mut self, utxo: &UtxoWithMeta) -> Self {
let id = utxo.id();
if self.pending.shift_remove(&id).is_none() {
return self;
}
self.available.insert(id, utxo.clone());
self
}
#[must_use]
pub fn rollback_spend_by_id(mut self, id: UtxoId) -> Self {
if let Some(found) = self.pending.shift_remove(&id) {
self.available.insert(id, found);
}
self
}
pub fn apply_update(mut self, update: &UnshieldedUpdate) -> Result<Self> {
if !update.status.is_success_or_partial() {
return Err(WalletError::InvalidUpdateStatus {
expected: "SUCCESS or PARTIAL_SUCCESS",
got: update.status.as_label(),
});
}
for spent in &update.spent_utxos {
let id = spent.id();
self.available.shift_remove(&id);
self.pending.shift_remove(&id);
}
for created in &update.created_utxos {
self.available.insert(created.id(), created.clone());
}
Ok(self)
}
pub fn apply_failed_update(mut self, update: &UnshieldedUpdate) -> Result<Self> {
if !update.status.is_failure() {
return Err(WalletError::InvalidUpdateStatus {
expected: "FAILURE",
got: update.status.as_label(),
});
}
for spent in &update.spent_utxos {
let id = spent.id();
self.pending.shift_remove(&id);
self.available.insert(id, spent.clone());
}
Ok(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn token() -> TokenType {
TokenType::new("native")
}
fn mock_utxo(intent_byte: u8, output_no: u32) -> UtxoWithMeta {
UtxoWithMeta::new(
UnshieldedUtxo::new(
UtxoId::new([intent_byte; 32], output_no),
1_000,
token(),
[intent_byte; 32],
),
UtxoMeta::new(0, false),
)
}
#[allow(clippy::cast_possible_truncation)] fn make_update(status: UpdateStatus, created: usize, spent: usize) -> UnshieldedUpdate {
let created_utxos: Vec<_> = (0..created)
.map(|i| mock_utxo(0xC0 | (i as u8), i as u32))
.collect();
let spent_utxos: Vec<_> = (0..spent)
.map(|i| mock_utxo(0xD0 | (i as u8), i as u32))
.collect();
UnshieldedUpdate {
created_utxos,
spent_utxos,
status,
}
}
#[test]
fn apply_update_success_creates_utxo() {
let s = UnshieldedState::empty()
.apply_update(&make_update(UpdateStatus::Success, 1, 0))
.unwrap();
assert_eq!(s.available_len(), 1);
assert_eq!(s.pending_len(), 0);
}
#[test]
fn apply_update_success_creates_multiple_utxos() {
let s = UnshieldedState::empty()
.apply_update(&make_update(UpdateStatus::Success, 3, 0))
.unwrap();
assert_eq!(s.available_len(), 3);
assert_eq!(s.pending_len(), 0);
}
#[test]
fn apply_update_rejects_failure_status() {
let err = UnshieldedState::empty()
.apply_update(&make_update(UpdateStatus::Failure, 1, 0))
.unwrap_err();
assert!(matches!(err, WalletError::InvalidUpdateStatus { .. }));
}
#[test]
fn apply_update_partial_success_behaves_like_success() {
let created = mock_utxo(0xAA, 0);
let upd = UnshieldedUpdate::partial_success(vec![created.clone()], vec![]);
let s = UnshieldedState::empty().apply_update(&upd).unwrap();
assert!(s.has_available(&created.id()));
assert_eq!(s.available_len(), 1);
assert_eq!(s.pending_len(), 0);
}
#[test]
fn apply_update_creates_and_spends_in_one_step() {
let existing = mock_utxo(0x10, 0);
let created = mock_utxo(0x20, 0);
let initial = UnshieldedState::empty()
.apply_update(&UnshieldedUpdate::success(vec![existing.clone()], vec![]))
.unwrap();
let after = initial
.apply_update(&UnshieldedUpdate::success(
vec![created.clone()],
vec![existing.clone()],
))
.unwrap();
assert!(after.has_available(&created.id()));
assert!(!after.has_available(&existing.id()));
assert_eq!(after.available_len(), 1);
assert_eq!(after.pending_len(), 0);
}
#[test]
fn apply_update_removes_confirmed_spent_from_pending() {
let u = mock_utxo(0x33, 0);
let s = UnshieldedState::empty()
.apply_update(&UnshieldedUpdate::success(vec![u.clone()], vec![]))
.unwrap()
.spend(&u)
.unwrap();
assert!(s.has_pending(&u.id()));
let after = s
.apply_update(&UnshieldedUpdate::success(vec![], vec![u.clone()]))
.unwrap();
assert!(!after.has_pending(&u.id()));
assert!(!after.has_available(&u.id()));
}
#[test]
fn apply_update_empty_is_noop() {
let seed = mock_utxo(0xAB, 0);
let before = UnshieldedState::empty()
.apply_update(&UnshieldedUpdate::success(vec![seed.clone()], vec![]))
.unwrap();
let after = before
.apply_update(&UnshieldedUpdate::success(vec![], vec![]))
.unwrap();
assert!(after.has_available(&seed.id()));
assert_eq!(after.available_len(), 1);
assert_eq!(after.pending_len(), 0);
}
#[test]
fn apply_update_silently_ignores_unknown_spent() {
let present = mock_utxo(0x01, 0);
let ghost = mock_utxo(0x02, 0);
let state = UnshieldedState::empty()
.apply_update(&UnshieldedUpdate::success(vec![present.clone()], vec![]))
.unwrap()
.apply_update(&UnshieldedUpdate::success(vec![], vec![ghost.clone()]))
.unwrap();
assert!(state.has_available(&present.id()));
assert_eq!(state.available_len(), 1);
assert_eq!(state.pending_len(), 0);
}
#[test]
fn apply_update_places_each_created_by_its_id() {
let a = mock_utxo(0xAA, 0);
let b = mock_utxo(0xBB, 1);
let state = UnshieldedState::empty()
.apply_update(&UnshieldedUpdate::success(
vec![a.clone(), b.clone()],
vec![],
))
.unwrap();
assert_eq!(state.available().find(|u| u.id() == a.id()), Some(&a));
assert_eq!(state.available().find(|u| u.id() == b.id()), Some(&b));
assert_eq!(state.available_len(), 2);
}
#[test]
fn apply_failed_update_restores_pending() {
let update = make_update(UpdateStatus::Success, 1, 0);
let utxo_to_spend = update.created_utxos[0].clone();
let failed = UnshieldedUpdate::failure(vec![], vec![utxo_to_spend.clone()]);
let state = UnshieldedState::empty()
.apply_update(&update)
.unwrap()
.spend(&utxo_to_spend)
.unwrap()
.apply_failed_update(&failed)
.unwrap();
assert_eq!(state.available_len(), 1);
assert_eq!(state.pending_len(), 0);
}
#[test]
fn apply_failed_update_rejects_success_status() {
let err = UnshieldedState::empty()
.apply_failed_update(&make_update(UpdateStatus::Success, 0, 1))
.unwrap_err();
assert!(matches!(err, WalletError::InvalidUpdateStatus { .. }));
}
#[test]
fn apply_failed_update_rejects_partial_success() {
let err = UnshieldedState::empty()
.apply_failed_update(&UnshieldedUpdate::partial_success(vec![], vec![]))
.unwrap_err();
assert!(matches!(err, WalletError::InvalidUpdateStatus { .. }));
}
#[test]
fn apply_failed_update_restores_spent_and_clears_pending() {
let a = mock_utxo(0xAA, 0);
let b = mock_utxo(0xBB, 0);
let after = UnshieldedState::empty()
.apply_update(&UnshieldedUpdate::success(
vec![a.clone(), b.clone()],
vec![],
))
.unwrap()
.spend(&a)
.unwrap();
assert!(after.has_pending(&a.id()));
assert!(!after.has_available(&a.id()));
assert!(after.has_available(&b.id()));
let recovered = after
.apply_failed_update(&UnshieldedUpdate::failure(vec![], vec![a.clone()]))
.unwrap();
assert!(recovered.has_available(&a.id()));
assert!(recovered.has_available(&b.id()));
assert_eq!(recovered.available_len(), 2);
assert!(!recovered.has_pending(&a.id()));
assert_eq!(recovered.pending_len(), 0);
}
#[test]
fn apply_failed_update_for_unknown_spent_inserts_into_available() {
let present = mock_utxo(0x01, 0);
let ghost = mock_utxo(0x02, 0);
let after = UnshieldedState::empty()
.apply_update(&UnshieldedUpdate::success(vec![present.clone()], vec![]))
.unwrap()
.apply_failed_update(&UnshieldedUpdate::failure(vec![], vec![ghost.clone()]))
.unwrap();
assert!(after.has_available(&present.id()));
assert!(after.has_available(&ghost.id()));
assert_eq!(after.pending_len(), 0);
}
#[test]
fn spend_moves_utxo_to_pending() {
let update = make_update(UpdateStatus::Success, 1, 0);
let state = UnshieldedState::empty()
.apply_update(&update)
.unwrap()
.spend(&update.created_utxos[0])
.unwrap();
assert_eq!(state.available_len(), 0);
assert_eq!(state.pending_len(), 1);
}
#[test]
fn spend_errors_when_utxo_not_available() {
let update = make_update(UpdateStatus::Success, 1, 0);
let ghost = mock_utxo(0xFF, 7);
let err = UnshieldedState::empty()
.apply_update(&update)
.unwrap()
.spend(&ghost)
.unwrap_err();
match err {
WalletError::UtxoNotFound { id } => assert_eq!(id, ghost.id()),
other => panic!("wrong error: {other:?}"),
}
}
#[test]
fn spend_by_id_succeeds_when_available() {
let update = make_update(UpdateStatus::Success, 1, 0);
let id = update.created_utxos[0].id();
let state = UnshieldedState::empty()
.apply_update(&update)
.unwrap()
.spend_by_id(id)
.unwrap();
assert_eq!(state.available_len(), 0);
assert_eq!(state.pending_len(), 1);
}
#[test]
fn spend_by_id_errors_when_not_available() {
let ghost = mock_utxo(0x77, 0);
let err = UnshieldedState::empty()
.spend_by_id(ghost.id())
.unwrap_err();
match err {
WalletError::UtxoNotFound { id } => assert_eq!(id, ghost.id()),
other => panic!("wrong error: {other:?}"),
}
}
#[test]
fn rollback_spend_returns_pending_to_available() {
let update = make_update(UpdateStatus::Success, 1, 0);
let u = update.created_utxos[0].clone();
let state = UnshieldedState::empty()
.apply_update(&update)
.unwrap()
.spend(&u)
.unwrap()
.rollback_spend(&u);
assert_eq!(state.available_len(), 1);
assert_eq!(state.pending_len(), 0);
}
#[test]
fn rollback_spend_by_id_is_idempotent() {
let update = make_update(UpdateStatus::Success, 1, 0);
let id = update.created_utxos[0].id();
let state = UnshieldedState::empty()
.apply_update(&update)
.unwrap()
.spend_by_id(id)
.unwrap()
.rollback_spend_by_id(id)
.rollback_spend_by_id(id); assert_eq!(state.available_len(), 1);
assert_eq!(state.pending_len(), 0);
}
#[test]
fn restore_and_to_arrays_round_trip() {
let u1 = mock_utxo(0x01, 0);
let u2 = mock_utxo(0x02, 0);
let pending = mock_utxo(0x03, 0);
let state = UnshieldedState::restore([u1.clone(), u2.clone()], [pending.clone()]);
assert_eq!(state.available_len(), 2);
assert_eq!(state.pending_len(), 1);
let (av, pd) = state.to_arrays();
assert_eq!(av.len(), 2);
assert_eq!(pd.len(), 1);
}
#[test]
fn lifecycle_create_spend_confirm_empties_both_collections() {
let u = mock_utxo(0xA0, 0);
let after = UnshieldedState::empty()
.apply_update(&UnshieldedUpdate::success(vec![u.clone()], vec![]))
.unwrap()
.spend(&u)
.unwrap()
.apply_update(&UnshieldedUpdate::success(vec![], vec![u.clone()]))
.unwrap();
assert_eq!(after.available_len(), 0);
assert_eq!(after.pending_len(), 0);
}
#[test]
fn lifecycle_create_spend_fail_restores_available() {
let u = mock_utxo(0xB0, 0);
let after = UnshieldedState::empty()
.apply_update(&UnshieldedUpdate::success(vec![u.clone()], vec![]))
.unwrap()
.spend(&u)
.unwrap()
.apply_failed_update(&UnshieldedUpdate::failure(vec![], vec![u.clone()]))
.unwrap();
assert!(after.has_available(&u.id()));
assert_eq!(after.available_len(), 1);
assert_eq!(after.pending_len(), 0);
}
#[test]
fn unshielded_utxo_implements_coin_recipe() {
let u = UnshieldedUtxo::new(UtxoId::new([0; 32], 0), 42, token(), [0; 32]);
assert_eq!(u.token_type(), &token());
assert_eq!(u.value(), Amount::from(42_u32));
}
#[test]
fn utxo_with_meta_implements_coin_recipe() {
let u = mock_utxo(0xAA, 0);
assert_eq!(u.token_type(), &token());
assert_eq!(u.value(), Amount::from(1_000_u32));
}
}