Skip to content

Commit ff77d66

Browse files
committed
refactor!: manager generic over receipt
Signed-off-by: Gustavo Inacio <[email protected]>
1 parent e5511ff commit ff77d66

File tree

15 files changed

+226
-151
lines changed

15 files changed

+226
-151
lines changed

tap_core/src/manager/adapters/receipt.rs

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use async_trait::async_trait;
77

88
use crate::receipt::{
99
state::{Checking, ReceiptState},
10-
ReceiptWithState,
10+
ReceiptWithState, WithValueAndTimestamp,
1111
};
1212

1313
/// Stores receipts in the storage.
@@ -16,7 +16,7 @@ use crate::receipt::{
1616
///
1717
/// For example code see [crate::manager::context::memory::ReceiptStorage]
1818
#[async_trait]
19-
pub trait ReceiptStore {
19+
pub trait ReceiptStore<Rcpt> {
2020
/// Defines the user-specified error type.
2121
///
2222
/// This error type should implement the `Error` and `Debug` traits from the standard library.
@@ -29,7 +29,7 @@ pub trait ReceiptStore {
2929
/// this process should be captured and returned as an `AdapterError`.
3030
async fn store_receipt(
3131
&self,
32-
receipt: ReceiptWithState<Checking>,
32+
receipt: ReceiptWithState<Checking, Rcpt>,
3333
) -> Result<u64, Self::AdapterError>;
3434
}
3535

@@ -62,7 +62,7 @@ pub trait ReceiptDelete {
6262
///
6363
/// For example code see [crate::manager::context::memory::ReceiptStorage]
6464
#[async_trait]
65-
pub trait ReceiptRead {
65+
pub trait ReceiptRead<Rcpt> {
6666
/// Defines the user-specified error type.
6767
///
6868
/// This error type should implement the `Error` and `Debug` traits from
@@ -92,15 +92,15 @@ pub trait ReceiptRead {
9292
&self,
9393
timestamp_range_ns: R,
9494
limit: Option<u64>,
95-
) -> Result<Vec<ReceiptWithState<Checking>>, Self::AdapterError>;
95+
) -> Result<Vec<ReceiptWithState<Checking, Rcpt>>, Self::AdapterError>;
9696
}
9797

9898
/// See [`ReceiptRead::retrieve_receipts_in_timestamp_range()`] for details.
9999
///
100100
/// WARNING: Will sort the receipts by timestamp using
101101
/// [vec::sort_unstable](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.sort_unstable).
102-
pub fn safe_truncate_receipts<T: ReceiptState>(
103-
receipts: &mut Vec<ReceiptWithState<T>>,
102+
pub fn safe_truncate_receipts<T: ReceiptState, Rcpt: WithValueAndTimestamp>(
103+
receipts: &mut Vec<ReceiptWithState<T, Rcpt>>,
104104
limit: u64,
105105
) {
106106
if receipts.len() <= limit as usize {
@@ -110,27 +110,19 @@ pub fn safe_truncate_receipts<T: ReceiptState>(
110110
return;
111111
}
112112

113-
receipts.sort_unstable_by_key(|rx_receipt| rx_receipt.signed_receipt().message.timestamp_ns);
113+
receipts.sort_unstable_by_key(|rx_receipt| rx_receipt.signed_receipt().timestamp_ns());
114114

115115
// This one will be the last timestamp in `receipts` after naive truncation
116-
let last_timestamp = receipts[limit as usize - 1]
117-
.signed_receipt()
118-
.message
119-
.timestamp_ns;
116+
let last_timestamp = receipts[limit as usize - 1].signed_receipt().timestamp_ns();
120117
// This one is the timestamp that comes just after the one above
121-
let after_last_timestamp = receipts[limit as usize]
122-
.signed_receipt()
123-
.message
124-
.timestamp_ns;
118+
let after_last_timestamp = receipts[limit as usize].signed_receipt().timestamp_ns();
125119

126120
receipts.truncate(limit as usize);
127121

128122
if last_timestamp == after_last_timestamp {
129123
// If the last timestamp is the same as the one that came after it, we need to
130124
// remove all the receipts with the same timestamp as the last one, because
131125
// otherwise we would leave behind part of the receipts for that timestamp.
132-
receipts.retain(|rx_receipt| {
133-
rx_receipt.signed_receipt().message.timestamp_ns != last_timestamp
134-
});
126+
receipts.retain(|rx_receipt| rx_receipt.signed_receipt().timestamp_ns() != last_timestamp);
135127
}
136128
}

tap_core/src/manager/context/memory.rs

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@ use async_trait::async_trait;
1818
use crate::{
1919
manager::adapters::*,
2020
rav::SignedRAV,
21-
receipt::{checks::StatefulTimestampCheck, state::Checking, ReceiptWithState},
21+
receipt::{checks::StatefulTimestampCheck, state::Checking, ReceiptWithState, SignedReceipt},
2222
signed_message::MessageId,
2323
};
2424

2525
pub type EscrowStorage = Arc<RwLock<HashMap<Address, u128>>>;
2626
pub type QueryAppraisals = Arc<RwLock<HashMap<MessageId, u128>>>;
27-
pub type ReceiptStorage = Arc<RwLock<HashMap<u64, ReceiptWithState<Checking>>>>;
27+
pub type ReceiptStorage = Arc<RwLock<HashMap<u64, ReceiptWithState<Checking, SignedReceipt>>>>;
2828
pub type RAVStorage = Arc<RwLock<Option<SignedRAV>>>;
2929

3030
use thiserror::Error;
@@ -71,7 +71,7 @@ impl InMemoryContext {
7171
pub async fn retrieve_receipt_by_id(
7272
&self,
7373
receipt_id: u64,
74-
) -> Result<ReceiptWithState<Checking>, InMemoryError> {
74+
) -> Result<ReceiptWithState<Checking, SignedReceipt>, InMemoryError> {
7575
let receipt_storage = self.receipt_storage.read().unwrap();
7676

7777
receipt_storage
@@ -85,7 +85,7 @@ impl InMemoryContext {
8585
pub async fn retrieve_receipts_by_timestamp(
8686
&self,
8787
timestamp_ns: u64,
88-
) -> Result<Vec<(u64, ReceiptWithState<Checking>)>, InMemoryError> {
88+
) -> Result<Vec<(u64, ReceiptWithState<Checking, SignedReceipt>)>, InMemoryError> {
8989
let receipt_storage = self.receipt_storage.read().unwrap();
9090
Ok(receipt_storage
9191
.iter()
@@ -99,7 +99,7 @@ impl InMemoryContext {
9999
pub async fn retrieve_receipts_upto_timestamp(
100100
&self,
101101
timestamp_ns: u64,
102-
) -> Result<Vec<ReceiptWithState<Checking>>, InMemoryError> {
102+
) -> Result<Vec<ReceiptWithState<Checking, SignedReceipt>>, InMemoryError> {
103103
self.retrieve_receipts_in_timestamp_range(..=timestamp_ns, None)
104104
.await
105105
}
@@ -147,12 +147,12 @@ impl RAVRead for InMemoryContext {
147147
}
148148

149149
#[async_trait]
150-
impl ReceiptStore for InMemoryContext {
150+
impl ReceiptStore<SignedReceipt> for InMemoryContext {
151151
type AdapterError = InMemoryError;
152152

153153
async fn store_receipt(
154154
&self,
155-
receipt: ReceiptWithState<Checking>,
155+
receipt: ReceiptWithState<Checking, SignedReceipt>,
156156
) -> Result<u64, Self::AdapterError> {
157157
let mut id_pointer = self.unique_id.write().unwrap();
158158
let id_previous = *id_pointer;
@@ -179,15 +179,15 @@ impl ReceiptDelete for InMemoryContext {
179179
}
180180
}
181181
#[async_trait]
182-
impl ReceiptRead for InMemoryContext {
182+
impl ReceiptRead<SignedReceipt> for InMemoryContext {
183183
type AdapterError = InMemoryError;
184184
async fn retrieve_receipts_in_timestamp_range<R: RangeBounds<u64> + std::marker::Send>(
185185
&self,
186186
timestamp_range_ns: R,
187187
limit: Option<u64>,
188-
) -> Result<Vec<ReceiptWithState<Checking>>, Self::AdapterError> {
188+
) -> Result<Vec<ReceiptWithState<Checking, SignedReceipt>>, Self::AdapterError> {
189189
let receipt_storage = self.receipt_storage.read().unwrap();
190-
let mut receipts_in_range: Vec<ReceiptWithState<Checking>> = receipt_storage
190+
let mut receipts_in_range: Vec<ReceiptWithState<Checking, SignedReceipt>> = receipt_storage
191191
.iter()
192192
.filter(|(_, rx_receipt)| {
193193
timestamp_range_ns.contains(&rx_receipt.signed_receipt().message.timestamp_ns)
@@ -264,7 +264,7 @@ pub mod checks {
264264
receipt::{
265265
checks::{Check, CheckError, CheckResult, ReceiptCheck},
266266
state::Checking,
267-
Context, ReceiptError, ReceiptWithState,
267+
Context, ReceiptError, ReceiptWithState, SignedReceipt,
268268
},
269269
signed_message::MessageId,
270270
};
@@ -274,7 +274,7 @@ pub mod checks {
274274
valid_signers: HashSet<Address>,
275275
allocation_ids: Arc<RwLock<HashSet<Address>>>,
276276
_query_appraisals: Arc<RwLock<HashMap<MessageId, u128>>>,
277-
) -> Vec<ReceiptCheck> {
277+
) -> Vec<ReceiptCheck<SignedReceipt>> {
278278
vec![
279279
// Arc::new(UniqueCheck ),
280280
// Arc::new(ValueCheck { query_appraisals }),
@@ -291,8 +291,12 @@ pub mod checks {
291291
}
292292

293293
#[async_trait::async_trait]
294-
impl Check for AllocationIdCheck {
295-
async fn check(&self, _: &Context, receipt: &ReceiptWithState<Checking>) -> CheckResult {
294+
impl Check<SignedReceipt> for AllocationIdCheck {
295+
async fn check(
296+
&self,
297+
_: &Context,
298+
receipt: &ReceiptWithState<Checking, SignedReceipt>,
299+
) -> CheckResult {
296300
let received_allocation_id = receipt.signed_receipt().message.allocation_id;
297301
if self
298302
.allocation_ids
@@ -318,8 +322,12 @@ pub mod checks {
318322
}
319323

320324
#[async_trait::async_trait]
321-
impl Check for SignatureCheck {
322-
async fn check(&self, _: &Context, receipt: &ReceiptWithState<Checking>) -> CheckResult {
325+
impl Check<SignedReceipt> for SignatureCheck {
326+
async fn check(
327+
&self,
328+
_: &Context,
329+
receipt: &ReceiptWithState<Checking, SignedReceipt>,
330+
) -> CheckResult {
323331
let recovered_address = receipt
324332
.signed_receipt()
325333
.recover_signer(&self.domain_separator)

tap_core/src/manager/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,10 @@
5151
//! struct MyContext;
5252
//!
5353
//! #[async_trait]
54-
//! impl ReceiptStore for MyContext {
54+
//! impl<T: Send + 'static> ReceiptStore<T> for MyContext {
5555
//! type AdapterError = ReceiptError;
5656
//!
57-
//! async fn store_receipt(&self, receipt: ReceiptWithState<Checking>) -> Result<u64, Self::AdapterError> {
57+
//! async fn store_receipt(&self, receipt: ReceiptWithState<Checking, T>) -> Result<u64, Self::AdapterError> {
5858
//! // ...
5959
//! # Ok(0)
6060
//! }

tap_core/src/manager/tap_manager.rs

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -11,38 +11,44 @@ use crate::{
1111
receipt::{
1212
checks::{CheckBatch, CheckList, TimestampCheck, UniqueCheck},
1313
state::{Checked, Failed},
14-
Context, ReceiptError, ReceiptWithState, SignedReceipt,
14+
Context, ReceiptError, ReceiptWithState, SignedReceipt, WithUniqueId,
15+
WithValueAndTimestamp,
1516
},
1617
Error,
1718
};
1819

19-
pub struct Manager<E> {
20+
pub struct Manager<E, Rcpt> {
2021
/// Context that implements adapters
2122
context: E,
2223

2324
/// Checks that must be completed for each receipt before being confirmed or denied for rav request
24-
checks: CheckList,
25+
checks: CheckList<Rcpt>,
2526

2627
/// Struct responsible for doing checks for receipt. Ownership stays with manager allowing manager
2728
/// to update configuration ( like minimum timestamp ).
2829
domain_separator: Eip712Domain,
2930
}
3031

31-
impl<E> Manager<E> {
32+
impl<E, Rcpt> Manager<E, Rcpt> {
3233
/// Creates new manager with provided `adapters`, any receipts received by this manager
3334
/// will complete all `required_checks` before being accepted or declined from RAV.
3435
/// `starting_min_timestamp` will be used as min timestamp until the first RAV request is created.
3536
///
36-
pub fn new(domain_separator: Eip712Domain, context: E, checks: impl Into<CheckList>) -> Self {
37+
pub fn new(
38+
domain_separator: Eip712Domain,
39+
context: E,
40+
checks: impl Into<CheckList<Rcpt>>,
41+
) -> Self {
3742
Self {
3843
context,
3944
domain_separator,
4045
checks: checks.into(),
46+
//_phantom: PhantomData,
4147
}
4248
}
4349
}
4450

45-
impl<E> Manager<E>
51+
impl<E, Rcpt> Manager<E, Rcpt>
4652
where
4753
E: RAVStore + SignatureChecker,
4854
{
@@ -79,7 +85,7 @@ where
7985
}
8086
}
8187

82-
impl<E> Manager<E>
88+
impl<E, Rcpt> Manager<E, Rcpt>
8389
where
8490
E: RAVRead,
8591
{
@@ -95,9 +101,10 @@ where
95101
}
96102
}
97103

98-
impl<E> Manager<E>
104+
impl<E, Rcpt> Manager<E, Rcpt>
99105
where
100-
E: ReceiptRead + SignatureChecker,
106+
E: ReceiptRead<Rcpt> + SignatureChecker,
107+
Rcpt: WithUniqueId + WithValueAndTimestamp + Sync,
101108
{
102109
async fn collect_receipts(
103110
&self,
@@ -107,8 +114,8 @@ where
107114
limit: Option<u64>,
108115
) -> Result<
109116
(
110-
Vec<ReceiptWithState<Checked>>,
111-
Vec<ReceiptWithState<Failed>>,
117+
Vec<ReceiptWithState<Checked, Rcpt>>,
118+
Vec<ReceiptWithState<Failed, Rcpt>>,
112119
),
113120
Error,
114121
> {
@@ -156,9 +163,11 @@ where
156163
}
157164
}
158165

159-
impl<E> Manager<E>
166+
// TODO make create_rav_request generic over receipt
167+
impl<E> Manager<E, SignedReceipt>
160168
where
161-
E: ReceiptRead + RAVRead + SignatureChecker,
169+
E: ReceiptRead<SignedReceipt> + RAVRead + SignatureChecker,
170+
//Rcpt: WithUniqueId + WithValueAndTimestamp + Sync,
162171
{
163172
/// Completes remaining checks on all receipts up to
164173
/// (current time - `timestamp_buffer_ns`). Returns them in two lists
@@ -180,7 +189,7 @@ where
180189
ctx: &Context,
181190
timestamp_buffer_ns: u64,
182191
receipts_limit: Option<u64>,
183-
) -> Result<RAVRequest, Error> {
192+
) -> Result<RAVRequest<SignedReceipt>, Error> {
184193
let previous_rav = self.get_previous_rav().await?;
185194
let min_timestamp_ns = previous_rav
186195
.as_ref()
@@ -202,7 +211,7 @@ where
202211
}
203212

204213
fn generate_expected_rav(
205-
receipts: &[ReceiptWithState<Checked>],
214+
receipts: &[ReceiptWithState<Checked, SignedReceipt>],
206215
previous_rav: Option<SignedRAV>,
207216
) -> Result<ReceiptAggregateVoucher, Error> {
208217
if receipts.is_empty() {
@@ -221,7 +230,7 @@ where
221230
}
222231
}
223232

224-
impl<E> Manager<E>
233+
impl<E, Rcpt> Manager<E, Rcpt>
225234
where
226235
E: ReceiptDelete + RAVRead,
227236
{
@@ -251,9 +260,9 @@ where
251260
}
252261
}
253262

254-
impl<E> Manager<E>
263+
impl<E, Rcpt> Manager<E, Rcpt>
255264
where
256-
E: ReceiptStore,
265+
E: ReceiptStore<Rcpt>,
257266
{
258267
/// Runs `initial_checks` on `signed_receipt` for initial verification,
259268
/// then stores received receipt.
@@ -266,7 +275,7 @@ where
266275
pub async fn verify_and_store_receipt(
267276
&self,
268277
ctx: &Context,
269-
signed_receipt: SignedReceipt,
278+
signed_receipt: Rcpt,
270279
) -> std::result::Result<(), Error> {
271280
let mut received_receipt = ReceiptWithState::new(signed_receipt);
272281

tap_core/src/rav/request.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@ use crate::{
1212

1313
/// Request to `tap_aggregator` to aggregate receipts into a Signed RAV.
1414
#[derive(Debug)]
15-
pub struct RAVRequest {
15+
pub struct RAVRequest<Rcpt> {
1616
/// List of checked and reserved receipts to aggregate
17-
pub valid_receipts: Vec<ReceiptWithState<Checked>>,
17+
pub valid_receipts: Vec<ReceiptWithState<Checked, Rcpt>>,
1818
/// Optional previous RAV to aggregate with
1919
pub previous_rav: Option<SignedRAV>,
2020
/// List of failed receipt used to log invalid receipts
21-
pub invalid_receipts: Vec<ReceiptWithState<Failed>>,
21+
pub invalid_receipts: Vec<ReceiptWithState<Failed, Rcpt>>,
2222
/// Expected RAV to be created
2323
pub expected_rav: Result<ReceiptAggregateVoucher, Error>,
2424
}

0 commit comments

Comments
 (0)