1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
mod selection;
mod signing;
mod state;
pub use self::selection::{FilterVtxos, RefreshStrategy, VtxoFilter};
pub use self::state::{VtxoState, VtxoStateKind, WalletVtxo};
use log::{debug, error, trace};
use ark::{ProtocolEncoding, Vtxo};
use ark::vtxo::{Full, VtxoRef};
use crate::Wallet;
use crate::movement::MovementId;
impl Wallet {
/// Attempts to lock VTXOs with the given [VtxoId](ark::VtxoId) values. This will only work if the current
/// [VtxoState] is contained by [VtxoStateKind::UNSPENT_STATES].
///
/// # Errors
/// - If the VTXO is not in a lockable [VtxoState].
/// - If the VTXO doesn't exist.
/// - If a database error occurs.
pub async fn lock_vtxos(
&self,
vtxos: impl IntoIterator<Item = impl VtxoRef>,
movement_id: Option<MovementId>,
) -> anyhow::Result<()> {
self.set_vtxo_states(
vtxos, &VtxoState::Locked { movement_id }, &VtxoStateKind::UNSPENT_STATES,
).await
}
/// Marks VTXOs as [VtxoState::Spent].
///
/// This operation is idempotent: VTXOs already in [VtxoState::Spent] will
/// remain spent without inserting a redundant state entry.
///
/// # Errors
/// - If the VTXO doesn't exist.
/// - If a database error occurs.
pub async fn mark_vtxos_as_spent(
&self,
vtxos: impl IntoIterator<Item = impl VtxoRef>,
) -> anyhow::Result<()> {
const ALLOWED: &[VtxoStateKind] = &[
VtxoStateKind::Spendable,
VtxoStateKind::Locked,
VtxoStateKind::Spent,
];
self.set_vtxo_states(vtxos, &VtxoState::Spent, ALLOWED).await
}
/// Updates the state set the [VtxoState] of VTXOs corresponding to each given
/// [VtxoId](ark::VtxoId) while validating if the transition is allowed based
/// on the current state and allowed transitions.
///
/// # Parameters
/// - `vtxos`: The [VtxoId](ark::VtxoId) of each [Vtxo] to update.
/// - `state`: A reference to the new [VtxoState] that the VTXOs should be transitioned to.
/// - `allowed_states`: A slice of [VtxoStateKind] representing the permissible current states
/// from which the VTXOs are allowed to transition to the given `state`. If an empty
/// slice is passed, all states are allowed.
///
/// # Errors
/// - The database operation to update the states fails.
/// - The state transition is invalid or does not match the allowed transitions.
pub async fn set_vtxo_states(
&self,
vtxos: impl IntoIterator<Item = impl VtxoRef>,
state: &VtxoState,
mut allowed_states: &[VtxoStateKind],
) -> anyhow::Result<()> {
if allowed_states.is_empty() {
allowed_states = VtxoStateKind::ALL;
}
let mut problematic_vtxos = Vec::new();
for vtxo in vtxos {
let id = vtxo.vtxo_id();
if let Err(e) = self.db.update_vtxo_state_checked(
id,
state.clone(),
allowed_states,
).await {
error!(
"Failed to set {} state with allowed states {:?} for VTXO {}: {:#}",
state.kind(), allowed_states, id, e,
);
problematic_vtxos.push(id);
}
}
if problematic_vtxos.is_empty() {
Ok(())
} else {
Err(anyhow!(
"Failed to set {} state for {} VTXOs: {:?}",
state.kind(),
problematic_vtxos.len(),
problematic_vtxos
))
}
}
/// Stores the given collection of VTXOs in the wallet with an initial state of
/// [VtxoState::Locked].
///
/// It does nothing if the VTXOs already exist.
///
/// # Parameters
/// - `vtxos`: The VTXOs to store in the wallet.
pub async fn store_locked_vtxos<'a>(
&self,
vtxos: impl IntoIterator<Item = &'a Vtxo<Full>>,
movement_id: Option<MovementId>,
) -> anyhow::Result<()> {
self.store_vtxos(vtxos, &VtxoState::Locked { movement_id }).await
}
/// Stores the given collection of VTXOs in the wallet with an initial state of
/// [VtxoState::Spendable].
///
/// It does nothing if the VTXOs already exist.
///
/// Also posts the vtxo IDs to the server's recovery mailbox (non-critical, errors are logged).
///
/// # Parameters
/// - `vtxos`: The VTXOs to store in the wallet.
pub async fn store_spendable_vtxos<'a>(
&self,
vtxos: impl IntoIterator<Item = &'a Vtxo<Full>> + Clone,
) -> anyhow::Result<()> {
self.store_vtxos(vtxos.clone(), &VtxoState::Spendable).await?;
// Post vtxo IDs to server for recovery (non-critical, just log errors)
if let Err(e) = self.post_recovery_vtxo_ids(vtxos.into_iter().map(|v| v.id())).await {
error!("Failed to post recovery vtxo IDs to server: {:#}", e);
}
Ok(())
}
/// Stores the given collection of VTXOs in the wallet with an initial state of
/// [VtxoState::Spent].
///
/// It does nothing if the VTXOs already exist.
///
/// # Parameters
/// - `vtxos`: The VTXOs to store in the wallet.
pub async fn store_spent_vtxos<'a>(
&self,
vtxos: impl IntoIterator<Item = &'a Vtxo<Full>>,
) -> anyhow::Result<()> {
self.store_vtxos(vtxos, &VtxoState::Spent).await
}
/// Stores the given collection of VTXOs in the wallet with the given initial state.
///
/// It does nothing if the VTXOs already exist.
///
/// # Parameters
/// - `vtxos`: The VTXOs to store in the wallet.
/// - `state`: The initial state of the VTXOs.
pub async fn store_vtxos<'a>(
&self,
vtxos: impl IntoIterator<Item = &'a Vtxo<Full>>,
state: &VtxoState,
) -> anyhow::Result<()> {
let vtxos = vtxos.into_iter().map(|v| (v, state)).collect::<Vec<_>>();
if let Err(e) = self.db.store_vtxos(&vtxos).await {
error!("An error occurred while storing {} VTXOs: {:#}", vtxos.len(), e);
error!("Raw VTXOs for debugging:");
for (vtxo, _) in vtxos {
error!(" - {}", vtxo.serialize_hex());
}
Err(e)
} else {
debug!("Stored {} VTXOs", vtxos.len());
trace!("New VTXO IDs: {:?}", vtxos.into_iter().map(|(v, _)| v.id()).collect::<Vec<_>>());
Ok(())
}
}
/// Attempts to unlock VTXOs with the given [VtxoId](ark::VtxoId) values. This will only work if the current
/// [VtxoState] is [VtxoStateKind::Locked] or [VtxoStateKind::Spendable].
///
/// This operation is idempotent: VTXOs already in [VtxoState::Spendable] will
/// remain spendable without inserting a redundant state entry.
///
/// # Errors
/// - If the VTXO is not currently locked or spendable.
/// - If the VTXO doesn't exist.
/// - If a database error occurs.
pub async fn unlock_vtxos(
&self,
vtxos: impl IntoIterator<Item = impl VtxoRef>,
) -> anyhow::Result<()> {
self.set_vtxo_states(
vtxos, &VtxoState::Spendable, &[VtxoStateKind::Locked, VtxoStateKind::Spendable],
).await
}
}