state.rs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. //! State transition rules
  2. use cashu::State;
  3. /// State transition Error
  4. #[derive(thiserror::Error, Debug)]
  5. pub enum Error {
  6. /// Pending Token
  7. #[error("Token already pending for another update")]
  8. Pending,
  9. /// Already spent
  10. #[error("Token already spent")]
  11. AlreadySpent,
  12. /// Invalid transition
  13. #[error("Invalid transition: From {0} to {1}")]
  14. InvalidTransition(State, State),
  15. }
  16. #[inline]
  17. /// Check if the state transition is allowed
  18. pub fn check_state_transition(current_state: State, new_state: State) -> Result<(), Error> {
  19. let is_valid_transition = match current_state {
  20. State::Unspent => matches!(new_state, State::Pending | State::Spent),
  21. State::Pending => matches!(new_state, State::Unspent | State::Spent),
  22. // Any other state shouldn't be updated by the mint, and the wallet does not use this
  23. // function
  24. _ => false,
  25. };
  26. if !is_valid_transition {
  27. Err(match current_state {
  28. State::Pending => Error::Pending,
  29. State::Spent => Error::AlreadySpent,
  30. _ => Error::InvalidTransition(current_state, new_state),
  31. })
  32. } else {
  33. Ok(())
  34. }
  35. }