Skip to content

Commit cf5e64d

Browse files
committed
refactor: use SignedReceipt in generic over Receipt
refactor: remove unused escrow handler Signed-off-by: Gustavo Inacio <[email protected]>
1 parent e74bc2c commit cf5e64d

File tree

25 files changed

+270
-411
lines changed

25 files changed

+270
-411
lines changed

tap_aggregator/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ name = "tap_aggregator"
1212
path = "src/main.rs"
1313

1414
[dependencies]
15-
tap_core = { path = "../tap_core", version = "2.0.0" }
15+
tap_core = { path = "../tap_core", version = "2.0.0", features = ["test"] }
1616
serde.workspace = true
1717
alloy.workspace = true
1818
anyhow.workspace = true

tap_aggregator/src/aggregator.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,19 +10,19 @@ use alloy::{
1010
use anyhow::{bail, Ok, Result};
1111
use rayon::prelude::*;
1212
use tap_core::{
13-
rav::ReceiptAggregateVoucher,
13+
rav::{Aggregate, ReceiptAggregateVoucher},
1414
receipt::Receipt,
1515
signed_message::{EIP712SignedMessage, SignatureBytes, SignatureBytesExt},
1616
};
1717

1818
pub fn check_and_aggregate_receipts(
1919
domain_separator: &Eip712Domain,
20-
receipts: &[EIP712SignedMessage<Receipt>],
20+
receipts: Vec<EIP712SignedMessage<Receipt>>,
2121
previous_rav: Option<EIP712SignedMessage<ReceiptAggregateVoucher>>,
2222
wallet: &PrivateKeySigner,
2323
accepted_addresses: &HashSet<Address>,
2424
) -> Result<EIP712SignedMessage<ReceiptAggregateVoucher>> {
25-
check_signatures_unique(receipts)?;
25+
check_signatures_unique(&receipts)?;
2626

2727
// Check that the receipts are signed by an accepted signer address
2828
receipts.par_iter().try_for_each(|receipt| {
@@ -39,7 +39,7 @@ pub fn check_and_aggregate_receipts(
3939
}
4040

4141
// Check that the receipts timestamp is greater than the previous rav
42-
check_receipt_timestamps(receipts, previous_rav.as_ref())?;
42+
check_receipt_timestamps(&receipts, previous_rav.as_ref())?;
4343

4444
// Get the allocation id from the first receipt, return error if there are no receipts
4545
let allocation_id = match receipts.first() {
@@ -48,7 +48,7 @@ pub fn check_and_aggregate_receipts(
4848
};
4949

5050
// Check that the receipts all have the same allocation id
51-
check_allocation_id(receipts, allocation_id)?;
51+
check_allocation_id(&receipts, allocation_id)?;
5252

5353
// Check that the rav has the correct allocation id
5454
if let Some(previous_rav) = &previous_rav {
@@ -62,8 +62,10 @@ pub fn check_and_aggregate_receipts(
6262
}
6363
}
6464

65+
let receipts = receipts.into_iter().map(Into::into).collect::<Vec<_>>();
66+
6567
// Aggregate the receipts
66-
let rav = ReceiptAggregateVoucher::aggregate_receipts(allocation_id, receipts, previous_rav)?;
68+
let rav = ReceiptAggregateVoucher::aggregate_receipts(&receipts, previous_rav)?;
6769

6870
// Sign the rav and return
6971
Ok(EIP712SignedMessage::new(domain_separator, rav, wallet)?)

tap_aggregator/src/server.rs

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ fn aggregate_receipts_(
159159
let res = match api_version {
160160
TapRpcApiVersion::V0_0 => check_and_aggregate_receipts(
161161
domain_separator,
162-
&receipts,
162+
receipts,
163163
previous_rav,
164164
wallet,
165165
accepted_addresses,
@@ -202,7 +202,7 @@ impl TapAggregator for RpcImpl {
202202

203203
match check_and_aggregate_receipts(
204204
&self.domain_separator,
205-
receipts.as_slice(),
205+
receipts,
206206
previous_rav,
207207
&self.wallet,
208208
&self.accepted_addresses,
@@ -494,6 +494,8 @@ mod tests {
494494
#[values(0, 1, 2)] random_seed: u64,
495495
) {
496496
// The keys that will be used to sign the new RAVs
497+
498+
use tap_core::rav::Aggregate;
497499
let keys_main = keys();
498500
// Extra keys to test the server's ability to accept multiple signers as input
499501
let keys_0 = keys();
@@ -546,9 +548,11 @@ mod tests {
546548

547549
let remote_rav = res.data;
548550

549-
let local_rav =
550-
ReceiptAggregateVoucher::aggregate_receipts(allocation_ids[0], &receipts, None)
551-
.unwrap();
551+
let local_rav = ReceiptAggregateVoucher::aggregate_receipts(
552+
&receipts.into_iter().map(Into::into).collect::<Vec<_>>(),
553+
None,
554+
)
555+
.unwrap();
552556

553557
assert!(remote_rav.message.allocationId == local_rav.allocationId);
554558
assert!(remote_rav.message.timestampNs == local_rav.timestampNs);
@@ -574,6 +578,8 @@ mod tests {
574578
#[values(0, 1, 2, 3, 4)] random_seed: u64,
575579
) {
576580
// The keys that will be used to sign the new RAVs
581+
582+
use tap_core::rav::Aggregate;
577583
let keys_main = keys();
578584
// Extra keys to test the server's ability to accept multiple signers as input
579585
let keys_0 = keys();
@@ -614,10 +620,10 @@ mod tests {
614620
);
615621
}
616622

623+
let checked_receipt = receipts.iter().cloned().map(Into::into).collect::<Vec<_>>();
617624
// Create previous RAV from first half of receipts locally
618625
let prev_rav = ReceiptAggregateVoucher::aggregate_receipts(
619-
allocation_ids[0],
620-
&receipts[0..receipts.len() / 2],
626+
&checked_receipt[0..checked_receipt.len() / 2],
621627
None,
622628
)
623629
.unwrap();

tap_core/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,12 @@ criterion = { version = "0.5", features = ["async_std"] }
2222
rstest.workspace = true
2323
insta.workspace = true
2424
serde_json.workspace = true
25+
tap_core = { path = ".", features = ["test"] }
2526

2627

2728
[features]
2829
default = ["in_memory"]
30+
test = []
2931
in_memory = []
3032

3133
[[bench]]

tap_core/benches/timeline_aggretion_protocol_benchmark.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ use std::str::FromStr;
1313
use alloy::{dyn_abi::Eip712Domain, primitives::Address, signers::local::PrivateKeySigner};
1414
use criterion::{black_box, criterion_group, criterion_main, Criterion};
1515
use tap_core::{
16-
rav::ReceiptAggregateVoucher, receipt::Receipt, signed_message::EIP712SignedMessage,
16+
rav::{Aggregate, ReceiptAggregateVoucher},
17+
receipt::Receipt,
18+
signed_message::EIP712SignedMessage,
1719
tap_eip712_domain,
1820
};
1921

@@ -66,15 +68,16 @@ pub fn criterion_benchmark(c: &mut Criterion) {
6668

6769
for log_number_of_receipts in 10..30 {
6870
let receipts = (0..2 ^ log_number_of_receipts)
69-
.map(|_| create_and_sign_receipt(&domain_seperator, allocation_id, value, &wallet))
71+
.map(|_| {
72+
create_and_sign_receipt(&domain_seperator, allocation_id, value, &wallet).into()
73+
})
7074
.collect::<Vec<_>>();
7175

7276
rav_group.bench_function(
7377
format!("Create RAV w/ 2^{} receipt's", log_number_of_receipts),
7478
|b| {
7579
b.iter(|| {
7680
ReceiptAggregateVoucher::aggregate_receipts(
77-
black_box(allocation_id),
7881
black_box(&receipts),
7982
black_box(None),
8083
)
@@ -84,7 +87,7 @@ pub fn criterion_benchmark(c: &mut Criterion) {
8487

8588
let signed_rav = EIP712SignedMessage::new(
8689
&domain_seperator,
87-
ReceiptAggregateVoucher::aggregate_receipts(allocation_id, &receipts, None).unwrap(),
90+
ReceiptAggregateVoucher::aggregate_receipts(&receipts, None).unwrap(),
8891
&wallet,
8992
)
9093
.unwrap();

tap_core/src/lib.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ mod tap_tests {
6464
use rstest::*;
6565

6666
use crate::{
67-
rav::ReceiptAggregateVoucher, receipt::Receipt, signed_message::EIP712SignedMessage,
67+
rav::{Aggregate, ReceiptAggregateVoucher},
68+
receipt::Receipt,
69+
signed_message::EIP712SignedMessage,
6870
tap_eip712_domain,
6971
};
7072

@@ -102,6 +104,7 @@ mod tap_tests {
102104
#[case] values: Vec<u128>,
103105
) {
104106
// Create receipts
107+
105108
let mut receipts = Vec::new();
106109
for value in values {
107110
receipts.push(
@@ -110,14 +113,14 @@ mod tap_tests {
110113
Receipt::new(allocation_ids[0], value).unwrap(),
111114
&keys.0,
112115
)
113-
.unwrap(),
116+
.unwrap()
117+
.into(),
114118
);
115119
}
116120

117121
// Skipping receipts validation in this test, aggregate_receipts assumes receipts are valid.
118122

119-
let rav = ReceiptAggregateVoucher::aggregate_receipts(allocation_ids[0], &receipts, None)
120-
.unwrap();
123+
let rav = ReceiptAggregateVoucher::aggregate_receipts(&receipts, None).unwrap();
121124
let signed_rav = EIP712SignedMessage::new(&domain_separator, rav, &keys.0).unwrap();
122125
assert!(signed_rav.recover_signer(&domain_separator).unwrap() == keys.1);
123126
}
@@ -141,23 +144,20 @@ mod tap_tests {
141144
Receipt::new(allocation_ids[0], value).unwrap(),
142145
&keys.0,
143146
)
144-
.unwrap(),
147+
.unwrap()
148+
.into(),
145149
);
146150
}
147151

148152
// Create previous RAV from first half of receipts
149-
let prev_rav = ReceiptAggregateVoucher::aggregate_receipts(
150-
allocation_ids[0],
151-
&receipts[0..receipts.len() / 2],
152-
None,
153-
)
154-
.unwrap();
153+
let prev_rav =
154+
ReceiptAggregateVoucher::aggregate_receipts(&receipts[0..receipts.len() / 2], None)
155+
.unwrap();
155156
let signed_prev_rav =
156157
EIP712SignedMessage::new(&domain_separator, prev_rav, &keys.0).unwrap();
157158

158159
// Create new RAV from last half of receipts and prev_rav
159160
let rav = ReceiptAggregateVoucher::aggregate_receipts(
160-
allocation_ids[0],
161161
&receipts[receipts.len() / 2..receipts.len()],
162162
Some(signed_prev_rav),
163163
)

tap_core/src/manager/adapters/escrow.rs

Lines changed: 10 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,7 @@
44
use alloy::{dyn_abi::Eip712Domain, primitives::Address, sol_types::SolStruct};
55
use async_trait::async_trait;
66

7-
use crate::{
8-
manager::WithValueAndTimestamp,
9-
receipt::{state::AwaitingReserve, ReceiptError, ReceiptResult, ReceiptWithState},
10-
signed_message::EIP712SignedMessage,
11-
Error,
12-
};
7+
use crate::{signed_message::EIP712SignedMessage, Error};
138

149
/// Manages the escrow operations
1510
///
@@ -26,46 +21,21 @@ pub trait EscrowHandler: Send + Sync {
2621
/// Errors of this type are returned to the user when an operation fails.
2722
type AdapterError: std::error::Error + std::fmt::Debug + Send + Sync + 'static;
2823

29-
/// Retrieves the local accounting amount of available escrow for a specified sender.
30-
async fn get_available_escrow(&self, sender_id: Address) -> Result<u128, Self::AdapterError>;
31-
32-
/// Deducts a specified value from the local accounting of available escrow for a specified sender.
33-
async fn subtract_escrow(
34-
&self,
35-
sender_id: Address,
36-
value: u128,
37-
) -> Result<(), Self::AdapterError>;
24+
///// Retrieves the local accounting amount of available escrow for a specified sender.
25+
//async fn get_available_escrow(&self, sender_id: Address) -> Result<u128, Self::AdapterError>;
26+
//
27+
///// Deducts a specified value from the local accounting of available escrow for a specified sender.
28+
//async fn subtract_escrow(
29+
// &self,
30+
// sender_id: Address,
31+
// value: u128,
32+
//) -> Result<(), Self::AdapterError>;
3833

3934
/// Verifies the signer of the receipt
4035
///
4136
/// Used by [`Self::check_rav_signature`] to verify the signer of the receipt
4237
async fn verify_signer(&self, signer_address: Address) -> Result<bool, Self::AdapterError>;
4338

44-
/// Checks and reserves escrow for the received receipt
45-
async fn check_and_reserve_escrow<T: SolStruct + WithValueAndTimestamp + Sync>(
46-
&self,
47-
received_receipt: &ReceiptWithState<AwaitingReserve, T>,
48-
domain_separator: &Eip712Domain,
49-
) -> ReceiptResult<()> {
50-
let signed_receipt = &received_receipt.signed_receipt;
51-
let receipt_signer_address =
52-
signed_receipt
53-
.recover_signer(domain_separator)
54-
.map_err(|err| ReceiptError::InvalidSignature {
55-
source_error_message: err.to_string(),
56-
})?;
57-
58-
if self
59-
.subtract_escrow(receipt_signer_address, signed_receipt.message.value())
60-
.await
61-
.is_err()
62-
{
63-
return Err(ReceiptError::SubtractEscrowFailed);
64-
}
65-
66-
Ok(())
67-
}
68-
6939
/// Checks the signature of the RAV
7040
async fn check_rav_signature<R: SolStruct + Sync>(
7141
&self,

tap_core/src/manager/adapters/receipt.rs

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44
use std::ops::RangeBounds;
55

6-
use alloy::sol_types::SolStruct;
76
use async_trait::async_trait;
87

98
use crate::{
@@ -20,10 +19,7 @@ use crate::{
2019
///
2120
/// For example code see [crate::manager::context::memory::ReceiptStorage]
2221
#[async_trait]
23-
pub trait ReceiptStore<T>
24-
where
25-
T: SolStruct,
26-
{
22+
pub trait ReceiptStore<T> {
2723
/// Defines the user-specified error type.
2824
///
2925
/// This error type should implement the `Error` and `Debug` traits from the standard library.
@@ -69,10 +65,7 @@ pub trait ReceiptDelete {
6965
///
7066
/// For example code see [crate::manager::context::memory::ReceiptStorage]
7167
#[async_trait]
72-
pub trait ReceiptRead<T>
73-
where
74-
T: SolStruct,
75-
{
68+
pub trait ReceiptRead<T> {
7669
/// Defines the user-specified error type.
7770
///
7871
/// This error type should implement the `Error` and `Debug` traits from
@@ -109,7 +102,7 @@ where
109102
///
110103
/// WARNING: Will sort the receipts by timestamp using
111104
/// [vec::sort_unstable](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.sort_unstable).
112-
pub fn safe_truncate_receipts<T: ReceiptState, R: SolStruct + WithValueAndTimestamp>(
105+
pub fn safe_truncate_receipts<T: ReceiptState, R: WithValueAndTimestamp>(
113106
receipts: &mut Vec<ReceiptWithState<T, R>>,
114107
limit: u64,
115108
) {
@@ -120,26 +113,19 @@ pub fn safe_truncate_receipts<T: ReceiptState, R: SolStruct + WithValueAndTimest
120113
return;
121114
}
122115

123-
receipts.sort_unstable_by_key(|rx_receipt| rx_receipt.signed_receipt().message.timestamp());
116+
receipts.sort_unstable_by_key(|rx_receipt| rx_receipt.signed_receipt().timestamp());
124117

125118
// This one will be the last timestamp in `receipts` after naive truncation
126-
let last_timestamp = receipts[limit as usize - 1]
127-
.signed_receipt()
128-
.message
129-
.timestamp();
119+
let last_timestamp = receipts[limit as usize - 1].signed_receipt().timestamp();
130120
// This one is the timestamp that comes just after the one above
131-
let after_last_timestamp = receipts[limit as usize]
132-
.signed_receipt()
133-
.message
134-
.timestamp();
121+
let after_last_timestamp = receipts[limit as usize].signed_receipt().timestamp();
135122

136123
receipts.truncate(limit as usize);
137124

138125
if last_timestamp == after_last_timestamp {
139126
// If the last timestamp is the same as the one that came after it, we need to
140127
// remove all the receipts with the same timestamp as the last one, because
141128
// otherwise we would leave behind part of the receipts for that timestamp.
142-
receipts
143-
.retain(|rx_receipt| rx_receipt.signed_receipt().message.timestamp() != last_timestamp);
129+
receipts.retain(|rx_receipt| rx_receipt.signed_receipt().timestamp() != last_timestamp);
144130
}
145131
}

0 commit comments

Comments
 (0)