-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathaggregator.rs
323 lines (284 loc) · 10.4 KB
/
aggregator.rs
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
use std::collections::hash_set;
use anyhow::{Ok, Result};
use ethers_core::types::{Address, Signature};
use ethers_signers::{LocalWallet, Signer};
use tap_core::{
eip_712_signed_message::EIP712SignedMessage,
receipt_aggregate_voucher::ReceiptAggregateVoucher, tap_receipt::Receipt,
};
pub async fn check_and_aggregate_receipts(
receipts: &[EIP712SignedMessage<Receipt>],
previous_rav: Option<EIP712SignedMessage<ReceiptAggregateVoucher>>,
wallet: LocalWallet,
) -> Result<EIP712SignedMessage<ReceiptAggregateVoucher>> {
// Check that the receipts are unique
check_signatures_unique(receipts)?;
// Check that the receipts are signed by ourselves
for receipt in receipts.iter() {
if receipt.recover_signer()? != wallet.address() {
return Err(tap_core::Error::InvalidCheckError {
check_string: "Receipt is not signed by ourselves".into(),
}
.into());
};
}
// Check that the previous rav is signed by ourselves
if let Some(previous_rav) = &previous_rav {
if previous_rav.recover_signer()? != wallet.address() {
return Err(tap_core::Error::InvalidCheckError {
check_string: "Previous rav is not signed by ourselves".into(),
}
.into());
};
}
// Check that the receipts timestamp is greater than the previous rav
check_receipt_timestamps(receipts, previous_rav.as_ref())?;
// Get the allocation id from the first receipt, return error if there are no receipts
let allocation_id = match receipts.get(0) {
Some(receipt) => receipt.message.allocation_id,
None => {
return Err(tap_core::Error::InvalidCheckError {
check_string: "No receipts".into(),
}
.into())
}
};
// Check that the receipts all have the same allocation id
check_allocation_id(receipts, allocation_id)?;
// Check that the rav has the correct allocation id
if let Some(previous_rav) = &previous_rav {
if previous_rav.message.allocation_id != allocation_id {
return Err(tap_core::Error::InvalidCheckError {
check_string: "Previous rav allocation id does not match receipts".into(),
}
.into());
}
}
// Aggregate the receipts
let rav = ReceiptAggregateVoucher::aggregate_receipts(allocation_id, receipts, previous_rav)?;
// Sign the rav and return
Ok(EIP712SignedMessage::new(rav, &wallet).await?)
}
fn check_allocation_id(
receipts: &[EIP712SignedMessage<Receipt>],
allocation_id: Address,
) -> Result<()> {
for receipt in receipts.iter() {
let receipt = &receipt.message;
if receipt.allocation_id != allocation_id {
return Err(tap_core::Error::InvalidCheckError {
check_string: "Receipts allocation id is not uniform".into(),
}
.into());
}
}
Ok(())
}
fn check_signatures_unique(receipts: &[EIP712SignedMessage<Receipt>]) -> Result<()> {
let mut receipt_signatures: hash_set::HashSet<Signature> = hash_set::HashSet::new();
for receipt in receipts.iter() {
let signature = receipt.signature;
if receipt_signatures.contains(&signature) {
return Err(tap_core::Error::InvalidCheckError {
check_string: "Duplicate receipt signature".into(),
}
.into());
}
receipt_signatures.insert(signature);
}
Ok(())
}
fn check_receipt_timestamps(
receipts: &[EIP712SignedMessage<Receipt>],
previous_rav: Option<&EIP712SignedMessage<ReceiptAggregateVoucher>>,
) -> Result<()> {
if let Some(previous_rav) = &previous_rav {
for receipt in receipts.iter() {
let receipt = &receipt.message;
if previous_rav.message.timestamp_ns > receipt.timestamp_ns {
return Err(tap_core::Error::InvalidCheckError {
check_string: "Receipt timestamp is less or equal then previous rav timestamp"
.into(),
}
.into());
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use std::{
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use ethers_core::types::Address;
use ethers_signers::{coins_bip39::English, LocalWallet, MnemonicBuilder, Signer};
use rstest::*;
use crate::aggregator;
use tap_core::{eip_712_signed_message::EIP712SignedMessage, tap_receipt::Receipt};
#[fixture]
fn keys() -> (LocalWallet, Address) {
let wallet: LocalWallet = MnemonicBuilder::<English>::default()
.phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about")
.build()
.unwrap();
let address = wallet.address();
(wallet, address)
}
#[fixture]
fn allocation_ids() -> Vec<Address> {
vec![
Address::from_str("0xabababababababababababababababababababab").unwrap(),
Address::from_str("0xdeaddeaddeaddeaddeaddeaddeaddeaddeaddead").unwrap(),
Address::from_str("0xbeefbeefbeefbeefbeefbeefbeefbeefbeefbeef").unwrap(),
Address::from_str("0x1234567890abcdef1234567890abcdef12345678").unwrap(),
]
}
#[rstest]
#[tokio::test]
async fn check_signatures_unique_fail(
keys: (LocalWallet, Address),
allocation_ids: Vec<Address>,
) {
// Create the same receipt twice (replay attack)
let mut receipts = Vec::new();
let receipt =
EIP712SignedMessage::new(Receipt::new(allocation_ids[0], 42).unwrap(), &keys.0)
.await
.unwrap();
receipts.push(receipt.clone());
receipts.push(receipt.clone());
let res = aggregator::check_signatures_unique(&receipts);
assert!(res.is_err());
}
#[rstest]
#[tokio::test]
async fn check_signatures_unique_ok(
keys: (LocalWallet, Address),
allocation_ids: Vec<Address>,
) {
// Create 2 different receipts
let mut receipts = Vec::new();
receipts.push(
EIP712SignedMessage::new(Receipt::new(allocation_ids[0], 42).unwrap(), &keys.0)
.await
.unwrap(),
);
receipts.push(
EIP712SignedMessage::new(Receipt::new(allocation_ids[0], 43).unwrap(), &keys.0)
.await
.unwrap(),
);
let res = aggregator::check_signatures_unique(&receipts);
assert!(res.is_ok());
}
#[rstest]
#[tokio::test]
/// Test that a receipt with a timestamp greater then the rav timestamp passes
async fn check_receipt_timestamps_ok(
keys: (LocalWallet, Address),
allocation_ids: Vec<Address>,
) {
let time = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
// Create rav
let rav = EIP712SignedMessage::new(
tap_core::receipt_aggregate_voucher::ReceiptAggregateVoucher {
allocation_id: allocation_ids[0],
timestamp_ns: time,
value_aggregate: 42,
},
&keys.0,
)
.await
.unwrap();
let mut receipts = Vec::new();
receipts.push(
EIP712SignedMessage::new(Receipt::new(allocation_ids[0], 42).unwrap(), &keys.0)
.await
.unwrap(),
);
aggregator::check_receipt_timestamps(&receipts, Some(&rav)).unwrap();
}
#[rstest]
#[tokio::test]
/// Test that a receipt with a timestamp less then the rav timestamp fails
async fn check_receipt_timestamps_fail(
keys: (LocalWallet, Address),
allocation_ids: Vec<Address>,
) {
let mut receipts = Vec::new();
receipts.push(
EIP712SignedMessage::new(Receipt::new(allocation_ids[0], 42).unwrap(), &keys.0)
.await
.unwrap(),
);
let time = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
// Create rav
let rav = EIP712SignedMessage::new(
tap_core::receipt_aggregate_voucher::ReceiptAggregateVoucher {
allocation_id: allocation_ids[0],
timestamp_ns: time,
value_aggregate: 42,
},
&keys.0,
)
.await
.unwrap();
let res = aggregator::check_receipt_timestamps(&receipts, Some(&rav));
assert!(res.is_err());
}
#[rstest]
#[tokio::test]
/// Test check_allocation_id with 2 receipts that have the correct allocation id
/// and 1 receipt that has the wrong allocation id
async fn check_allocation_id_fail(keys: (LocalWallet, Address), allocation_ids: Vec<Address>) {
let mut receipts = Vec::new();
receipts.push(
EIP712SignedMessage::new(Receipt::new(allocation_ids[0], 42).unwrap(), &keys.0)
.await
.unwrap(),
);
receipts.push(
EIP712SignedMessage::new(Receipt::new(allocation_ids[0], 43).unwrap(), &keys.0)
.await
.unwrap(),
);
receipts.push(
EIP712SignedMessage::new(Receipt::new(allocation_ids[1], 44).unwrap(), &keys.0)
.await
.unwrap(),
);
let res = aggregator::check_allocation_id(&receipts, allocation_ids[0]);
assert!(res.is_err());
}
#[rstest]
#[tokio::test]
/// Test check_allocation_id with 3 receipts that have the correct allocation id
async fn check_allocation_id_ok(keys: (LocalWallet, Address), allocation_ids: Vec<Address>) {
let mut receipts = Vec::new();
receipts.push(
EIP712SignedMessage::new(Receipt::new(allocation_ids[0], 42).unwrap(), &keys.0)
.await
.unwrap(),
);
receipts.push(
EIP712SignedMessage::new(Receipt::new(allocation_ids[0], 43).unwrap(), &keys.0)
.await
.unwrap(),
);
receipts.push(
EIP712SignedMessage::new(Receipt::new(allocation_ids[0], 44).unwrap(), &keys.0)
.await
.unwrap(),
);
let res = aggregator::check_allocation_id(&receipts, allocation_ids[0]);
assert!(res.is_ok());
}
}