From 70ee2c67125653c25f479ee5f11e7c7e555078b7 Mon Sep 17 00:00:00 2001 From: Gustavo Inacio Date: Sun, 10 Mar 2024 00:29:41 -0300 Subject: [PATCH 01/11] refactor!: update project structure Signed-off-by: Gustavo Inacio --- tap_aggregator/src/aggregator.rs | 13 +- tap_aggregator/src/server.rs | 8 +- tap_core/Cargo.toml | 2 + .../timeline_aggretion_protocol_benchmark.rs | 3 +- tap_core/src/adapters/mock.rs | 4 - .../src/adapters/test/escrow_adapter_test.rs | 84 ------- tap_core/src/adapters/test/mod.rs | 6 - .../adapters/test/rav_storage_adapter_test.rs | 117 --------- .../test/receipt_storage_adapter_test.rs | 223 ------------------ tap_core/src/error.rs | 2 +- tap_core/src/lib.rs | 16 +- .../src/{tap_manager => manager}/manager.rs | 57 ++--- tap_core/src/{tap_manager => manager}/mod.rs | 17 +- .../strategy/escrow.rs} | 52 +++- .../src/{adapters => manager/strategy}/mod.rs | 17 +- .../strategy/rav.rs} | 2 +- .../strategy/receipt.rs} | 2 +- .../{receipt_aggregate_voucher.rs => rav.rs} | 7 +- .../rav_request.rs => rav/request.rs} | 5 +- .../src/{tap_receipt => receipt}/checks.rs | 8 +- .../{tap_receipt/mod.rs => receipt/error.rs} | 20 +- tap_core/src/receipt/mod.rs | 19 ++ .../src/{tap_receipt => receipt}/receipt.rs | 0 .../received_receipt.rs | 23 +- ...12_signed_message.rs => signed_message.rs} | 0 tap_core/src/tap_receipt/receipt_auditor.rs | 71 ------ .../executor_mock.rs => tests/common/mock.rs} | 19 +- tap_core/tests/common/mod.rs | 5 + tap_core/tests/common/timestamp.rs | 12 + tap_core/tests/escrow_test.rs | 80 +++++++ .../tests/indexer_mock/mod.rs | 17 +- .../test => tests}/manager_test.rs | 23 +- tap_core/tests/rav_test.rs | 113 +++++++++ tap_core/tests/receipt_test.rs | 214 +++++++++++++++++ .../received_receipt_test.rs} | 21 +- .../tests/showcase.rs | 13 +- tap_integration_tests/tests/lib.rs | 6 +- 37 files changed, 624 insertions(+), 677 deletions(-) delete mode 100644 tap_core/src/adapters/mock.rs delete mode 100644 tap_core/src/adapters/test/escrow_adapter_test.rs delete mode 100644 tap_core/src/adapters/test/mod.rs delete mode 100644 tap_core/src/adapters/test/rav_storage_adapter_test.rs delete mode 100644 tap_core/src/adapters/test/receipt_storage_adapter_test.rs rename tap_core/src/{tap_manager => manager}/manager.rs (88%) rename tap_core/src/{tap_manager => manager}/mod.rs (72%) rename tap_core/src/{adapters/escrow_adapter.rs => manager/strategy/escrow.rs} (63%) rename tap_core/src/{adapters => manager/strategy}/mod.rs (84%) rename tap_core/src/{adapters/rav_storage_adapter.rs => manager/strategy/rav.rs} (98%) rename tap_core/src/{adapters/receipt_storage_adapter.rs => manager/strategy/receipt.rs} (99%) rename tap_core/src/{receipt_aggregate_voucher.rs => rav.rs} (93%) rename tap_core/src/{tap_manager/rav_request.rs => rav/request.rs} (73%) rename tap_core/src/{tap_receipt => receipt}/checks.rs (97%) rename tap_core/src/{tap_receipt/mod.rs => receipt/error.rs} (60%) create mode 100644 tap_core/src/receipt/mod.rs rename tap_core/src/{tap_receipt => receipt}/receipt.rs (100%) rename tap_core/src/{tap_receipt => receipt}/received_receipt.rs (94%) rename tap_core/src/{eip_712_signed_message.rs => signed_message.rs} (100%) delete mode 100644 tap_core/src/tap_receipt/receipt_auditor.rs rename tap_core/{src/adapters/mock/executor_mock.rs => tests/common/mock.rs} (94%) create mode 100644 tap_core/tests/common/mod.rs create mode 100644 tap_core/tests/common/timestamp.rs create mode 100644 tap_core/tests/escrow_test.rs rename {tap_integration_tests => tap_core}/tests/indexer_mock/mod.rs (94%) rename tap_core/{src/tap_manager/test => tests}/manager_test.rs (97%) create mode 100644 tap_core/tests/rav_test.rs create mode 100644 tap_core/tests/receipt_test.rs rename tap_core/{src/tap_receipt/received_receipt/received_receipt_unit_test.rs => tests/received_receipt_test.rs} (94%) rename {tap_integration_tests => tap_core}/tests/showcase.rs (99%) diff --git a/tap_aggregator/src/aggregator.rs b/tap_aggregator/src/aggregator.rs index 7479cd9c..1fc44305 100644 --- a/tap_aggregator/src/aggregator.rs +++ b/tap_aggregator/src/aggregator.rs @@ -10,8 +10,7 @@ use ethers_core::types::Signature; use ethers_signers::LocalWallet; use tap_core::{ - eip_712_signed_message::EIP712SignedMessage, - receipt_aggregate_voucher::ReceiptAggregateVoucher, tap_receipt::Receipt, + rav::ReceiptAggregateVoucher, receipt::Receipt, signed_message::EIP712SignedMessage, }; pub fn check_and_aggregate_receipts( @@ -140,9 +139,7 @@ mod tests { use rstest::*; use crate::aggregator; - use tap_core::{ - eip_712_signed_message::EIP712SignedMessage, tap_eip712_domain, tap_receipt::Receipt, - }; + use tap_core::{receipt::Receipt, signed_message::EIP712SignedMessage, tap_eip712_domain}; #[fixture] fn keys() -> (LocalWallet, Address) { @@ -248,7 +245,7 @@ mod tests { // Create rav with max_timestamp below the receipts timestamps let rav = EIP712SignedMessage::new( &domain_separator, - tap_core::receipt_aggregate_voucher::ReceiptAggregateVoucher { + tap_core::rav::ReceiptAggregateVoucher { allocationId: allocation_ids[0], timestampNs: receipt_timestamp_range.clone().min().unwrap() - 1, valueAggregate: 42, @@ -262,7 +259,7 @@ mod tests { // Aggregation should fail let rav = EIP712SignedMessage::new( &domain_separator, - tap_core::receipt_aggregate_voucher::ReceiptAggregateVoucher { + tap_core::rav::ReceiptAggregateVoucher { allocationId: allocation_ids[0], timestampNs: receipt_timestamp_range.clone().min().unwrap(), valueAggregate: 42, @@ -276,7 +273,7 @@ mod tests { // Aggregation should fail let rav = EIP712SignedMessage::new( &domain_separator, - tap_core::receipt_aggregate_voucher::ReceiptAggregateVoucher { + tap_core::rav::ReceiptAggregateVoucher { allocationId: allocation_ids[0], timestampNs: receipt_timestamp_range.clone().max().unwrap() + 1, valueAggregate: 42, diff --git a/tap_aggregator/src/server.rs b/tap_aggregator/src/server.rs index 6d0d1a6e..5a9f7eb4 100644 --- a/tap_aggregator/src/server.rs +++ b/tap_aggregator/src/server.rs @@ -19,8 +19,7 @@ use crate::api_versioning::{ use crate::error_codes::{JsonRpcErrorCode, JsonRpcWarningCode}; use crate::jsonrpsee_helpers::{JsonRpcError, JsonRpcResponse, JsonRpcResult, JsonRpcWarning}; use tap_core::{ - eip_712_signed_message::EIP712SignedMessage, - receipt_aggregate_voucher::ReceiptAggregateVoucher, tap_receipt::Receipt, + rav::ReceiptAggregateVoucher, receipt::Receipt, signed_message::EIP712SignedMessage, }; // Register the metrics into the global metrics registry. @@ -254,9 +253,8 @@ mod tests { use crate::server; use tap_core::{ - eip_712_signed_message::EIP712SignedMessage, - receipt_aggregate_voucher::ReceiptAggregateVoucher, tap_eip712_domain, - tap_receipt::Receipt, + rav::ReceiptAggregateVoucher, receipt::Receipt, signed_message::EIP712SignedMessage, + tap_eip712_domain, }; #[derive(Clone)] diff --git a/tap_core/Cargo.toml b/tap_core/Cargo.toml index 624c5bfc..49adc624 100644 --- a/tap_core/Cargo.toml +++ b/tap_core/Cargo.toml @@ -27,6 +27,8 @@ tokio = { version = "1.29.1", features = ["macros", "rt-multi-thread"] } [dev-dependencies] criterion = { version = "0.5", features = ["async_std"] } +tap_aggregator = { version = "0.2.0", path = "../tap_aggregator" } +jsonrpsee = { version = "0.18.0", features = ["http-client", "server"] } [features] diff --git a/tap_core/benches/timeline_aggretion_protocol_benchmark.rs b/tap_core/benches/timeline_aggretion_protocol_benchmark.rs index 37cbc183..1bc94be0 100644 --- a/tap_core/benches/timeline_aggretion_protocol_benchmark.rs +++ b/tap_core/benches/timeline_aggretion_protocol_benchmark.rs @@ -18,8 +18,7 @@ use ethers_core::k256::ecdsa::SigningKey; use rand_core::OsRng; use tap_core::tap_eip712_domain; use tap_core::{ - eip_712_signed_message::EIP712SignedMessage, - receipt_aggregate_voucher::ReceiptAggregateVoucher, tap_receipt::Receipt, + rav::ReceiptAggregateVoucher, receipt::Receipt, signed_message::EIP712SignedMessage, }; pub fn create_and_sign_receipt( diff --git a/tap_core/src/adapters/mock.rs b/tap_core/src/adapters/mock.rs deleted file mode 100644 index d5900997..00000000 --- a/tap_core/src/adapters/mock.rs +++ /dev/null @@ -1,4 +0,0 @@ -// Copyright 2023-, Semiotic AI, Inc. -// SPDX-License-Identifier: Apache-2.0 - -pub mod executor_mock; diff --git a/tap_core/src/adapters/test/escrow_adapter_test.rs b/tap_core/src/adapters/test/escrow_adapter_test.rs deleted file mode 100644 index c088c897..00000000 --- a/tap_core/src/adapters/test/escrow_adapter_test.rs +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2023-, Semiotic AI, Inc. -// SPDX-License-Identifier: Apache-2.0 - -#[cfg(test)] -mod escrow_adapter_unit_test { - use std::{ - collections::HashMap, - sync::{Arc, RwLock}, - }; - - use ethers::signers::{coins_bip39::English, LocalWallet, MnemonicBuilder, Signer}; - use rstest::*; - - use crate::{ - adapters::{escrow_adapter::EscrowAdapter, executor_mock::ExecutorMock}, - tap_receipt::checks::TimestampCheck, - }; - - #[fixture] - fn executor() -> ExecutorMock { - let escrow_storage = Arc::new(RwLock::new(HashMap::new())); - let rav_storage = Arc::new(RwLock::new(None)); - let receipt_storage = Arc::new(RwLock::new(HashMap::new())); - - let timestamp_check = Arc::new(TimestampCheck::new(0)); - ExecutorMock::new( - rav_storage, - receipt_storage.clone(), - escrow_storage.clone(), - timestamp_check, - ) - } - - #[rstest] - #[tokio::test] - async fn escrow_adapter_test(mut executor: ExecutorMock) { - let wallet: LocalWallet = MnemonicBuilder::::default() - .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") - .build() - .unwrap(); - let sender_id: [u8; 20] = wallet.address().into(); - let sender_id = sender_id.into(); - - let invalid_wallet: LocalWallet = MnemonicBuilder::::default() - .phrase( - "wrong century settle satisfy market forest title connect ten push alley depend", - ) - .build() - .unwrap(); - let invalid_sender_id: [u8; 20] = invalid_wallet.address().into(); - let invalid_sender_id = invalid_sender_id.into(); - - let initial_value = 500u128; - - executor.increase_escrow(sender_id, initial_value); - - // Check that sender exists and has valid value through adapter - assert!(executor.get_available_escrow(sender_id).await.is_ok()); - assert_eq!( - executor.get_available_escrow(sender_id).await.unwrap(), - initial_value - ); - - // Check that subtracting is valid for valid sender, and results in expected value - assert!(executor - .subtract_escrow(sender_id, initial_value) - .await - .is_ok()); - assert!(executor.get_available_escrow(sender_id).await.is_ok()); - assert_eq!(executor.get_available_escrow(sender_id).await.unwrap(), 0); - - // Check that subtracting to negative escrow results in err - assert!(executor - .subtract_escrow(sender_id, initial_value) - .await - .is_err()); - - // Check that accessing non initialized sender results in err - assert!(executor - .get_available_escrow(invalid_sender_id) - .await - .is_err()); - } -} diff --git a/tap_core/src/adapters/test/mod.rs b/tap_core/src/adapters/test/mod.rs deleted file mode 100644 index 33fb14c0..00000000 --- a/tap_core/src/adapters/test/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright 2023-, Semiotic AI, Inc. -// SPDX-License-Identifier: Apache-2.0 - -pub mod escrow_adapter_test; -pub mod rav_storage_adapter_test; -pub mod receipt_storage_adapter_test; diff --git a/tap_core/src/adapters/test/rav_storage_adapter_test.rs b/tap_core/src/adapters/test/rav_storage_adapter_test.rs deleted file mode 100644 index 324c596c..00000000 --- a/tap_core/src/adapters/test/rav_storage_adapter_test.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2023-, Semiotic AI, Inc. -// SPDX-License-Identifier: Apache-2.0 - -#[cfg(test)] -mod rav_storage_adapter_unit_test { - use std::collections::HashMap; - use std::sync::RwLock; - use std::{str::FromStr, sync::Arc}; - - use alloy_primitives::Address; - use alloy_sol_types::Eip712Domain; - use ethers::signers::coins_bip39::English; - use ethers::signers::{LocalWallet, MnemonicBuilder}; - use rstest::*; - - use crate::tap_receipt::checks::TimestampCheck; - use crate::{ - adapters::{ - executor_mock::ExecutorMock, - rav_storage_adapter::{RAVRead, RAVStore}, - }, - eip_712_signed_message::EIP712SignedMessage, - receipt_aggregate_voucher::ReceiptAggregateVoucher, - tap_eip712_domain, - tap_receipt::Receipt, - }; - - #[fixture] - fn domain_separator() -> Eip712Domain { - tap_eip712_domain(1, Address::from([0x11u8; 20])) - } - - #[fixture] - fn executor() -> ExecutorMock { - let escrow_storage = Arc::new(RwLock::new(HashMap::new())); - let rav_storage = Arc::new(RwLock::new(None)); - let receipt_storage = Arc::new(RwLock::new(HashMap::new())); - - let timestamp_check = Arc::new(TimestampCheck::new(0)); - ExecutorMock::new( - rav_storage, - receipt_storage.clone(), - escrow_storage.clone(), - timestamp_check, - ) - } - - #[rstest] - #[tokio::test] - async fn rav_storage_adapter_test(domain_separator: Eip712Domain, executor: ExecutorMock) { - let wallet: LocalWallet = MnemonicBuilder::::default() - .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") - .build() - .unwrap(); - - let allocation_id: [u8; 20] = - Address::from_str("0xabababababababababababababababababababab") - .unwrap() - .into(); - let allocation_id = allocation_id.into(); - - // Create receipts - let mut receipts = Vec::new(); - for value in 50..60 { - receipts.push( - EIP712SignedMessage::new( - &domain_separator, - Receipt::new(allocation_id, value).unwrap(), - &wallet, - ) - .unwrap(), - ); - } - - let signed_rav = EIP712SignedMessage::new( - &domain_separator, - ReceiptAggregateVoucher::aggregate_receipts(allocation_id, &receipts, None).unwrap(), - &wallet, - ) - .unwrap(); - - executor.update_last_rav(signed_rav.clone()).await.unwrap(); - - // Retreive rav - let retrieved_rav = executor.last_rav().await; - assert!(retrieved_rav.unwrap().unwrap() == signed_rav); - - // Testing the last rav update... - - // Create more receipts - let mut receipts = Vec::new(); - for value in 60..70 { - receipts.push( - EIP712SignedMessage::new( - &domain_separator, - Receipt::new(allocation_id, value).unwrap(), - &wallet, - ) - .unwrap(), - ); - } - - let signed_rav = EIP712SignedMessage::new( - &domain_separator, - ReceiptAggregateVoucher::aggregate_receipts(allocation_id, &receipts, None).unwrap(), - &wallet, - ) - .unwrap(); - - // Update the last rav - executor.update_last_rav(signed_rav.clone()).await.unwrap(); - - // Retreive rav - let retrieved_rav = executor.last_rav().await; - assert!(retrieved_rav.unwrap().unwrap() == signed_rav); - } -} diff --git a/tap_core/src/adapters/test/receipt_storage_adapter_test.rs b/tap_core/src/adapters/test/receipt_storage_adapter_test.rs deleted file mode 100644 index 383827fd..00000000 --- a/tap_core/src/adapters/test/receipt_storage_adapter_test.rs +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright 2023-, Semiotic AI, Inc. -// SPDX-License-Identifier: Apache-2.0 - -#[cfg(test)] -mod receipt_storage_adapter_unit_test { - use rand::seq::SliceRandom; - use rand::thread_rng; - use std::collections::HashMap; - use std::str::FromStr; - use std::sync::{Arc, RwLock}; - - use crate::tap_receipt::checks::TimestampCheck; - use crate::{ - adapters::{executor_mock::ExecutorMock, receipt_storage_adapter::ReceiptStore}, - eip_712_signed_message::EIP712SignedMessage, - tap_eip712_domain, - tap_receipt::{Receipt, ReceivedReceipt}, - }; - use alloy_primitives::Address; - use alloy_sol_types::Eip712Domain; - use ethers::signers::coins_bip39::English; - use ethers::signers::{LocalWallet, MnemonicBuilder}; - use rstest::*; - - #[fixture] - fn domain_separator() -> Eip712Domain { - tap_eip712_domain(1, Address::from([0x11u8; 20])) - } - - #[fixture] - fn executor() -> ExecutorMock { - let escrow_storage = Arc::new(RwLock::new(HashMap::new())); - let rav_storage = Arc::new(RwLock::new(None)); - let receipt_storage = Arc::new(RwLock::new(HashMap::new())); - - let timestamp_check = Arc::new(TimestampCheck::new(0)); - ExecutorMock::new( - rav_storage, - receipt_storage.clone(), - escrow_storage.clone(), - timestamp_check.clone(), - ) - } - - #[rstest] - #[tokio::test] - async fn receipt_adapter_test(domain_separator: Eip712Domain, mut executor: ExecutorMock) { - let wallet: LocalWallet = MnemonicBuilder::::default() - .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") - .build() - .unwrap(); - - let allocation_id = - Address::from_str("0xabababababababababababababababababababab").unwrap(); - - // Create receipts - let value = 100u128; - let received_receipt = ReceivedReceipt::new( - EIP712SignedMessage::new( - &domain_separator, - Receipt::new(allocation_id, value).unwrap(), - &wallet, - ) - .unwrap(), - ); - - let receipt_store_result = executor.store_receipt(received_receipt).await; - assert!(receipt_store_result.is_ok()); - let receipt_id = receipt_store_result.unwrap(); - - // Retreive receipt with id expected to be valid - assert!(executor.retrieve_receipt_by_id(receipt_id).await.is_ok()); - // Retreive receipt with arbitrary id expected to be invalid - assert!(executor.retrieve_receipt_by_id(999).await.is_err()); - - // Remove receipt with id expected to be valid - assert!(executor.remove_receipt_by_id(receipt_id).await.is_ok()); - // Remove receipt with arbitrary id expected to be invalid - assert!(executor.remove_receipt_by_id(999).await.is_err()); - - // Retreive receipt that was removed previously - assert!(executor.retrieve_receipt_by_id(receipt_id).await.is_err()); - - // Remove receipt that was removed previously - assert!(executor.remove_receipt_by_id(receipt_id).await.is_err()); - } - - #[rstest] - #[tokio::test] - async fn multi_receipt_adapter_test( - domain_separator: Eip712Domain, - mut executor: ExecutorMock, - ) { - let wallet: LocalWallet = MnemonicBuilder::::default() - .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") - .build() - .unwrap(); - - let allocation_id = - Address::from_str("0xabababababababababababababababababababab").unwrap(); - - // Create receipts - let mut received_receipts = Vec::new(); - for value in 50..60 { - received_receipts.push(ReceivedReceipt::new( - EIP712SignedMessage::new( - &domain_separator, - Receipt::new(allocation_id, value).unwrap(), - &wallet, - ) - .unwrap(), - )); - } - let mut receipt_ids = Vec::new(); - let mut receipt_timestamps = Vec::new(); - for received_receipt in received_receipts { - receipt_timestamps.push(received_receipt.signed_receipt().message.timestamp_ns); - receipt_ids.push(executor.store_receipt(received_receipt).await.unwrap()); - } - - // Retreive receipts with timestamp - assert!(executor - .retrieve_receipts_by_timestamp(receipt_timestamps[0]) - .await - .is_ok()); - assert!(!executor - .retrieve_receipts_by_timestamp(receipt_timestamps[0]) - .await - .unwrap() - .is_empty()); - - // Retreive receipts before timestamp - assert!(executor - .retrieve_receipts_upto_timestamp(receipt_timestamps[3]) - .await - .is_ok()); - assert!( - executor - .retrieve_receipts_upto_timestamp(receipt_timestamps[3]) - .await - .unwrap() - .len() - >= 4 - ); - - // Remove all receipts with one call - assert!(executor - .remove_receipts_by_ids(receipt_ids.as_slice()) - .await - .is_ok()); - // Removal should no longer be valid - assert!(executor - .remove_receipts_by_ids(receipt_ids.as_slice()) - .await - .is_err()); - // Retrieval should be invalid - for receipt_id in receipt_ids { - assert!(executor.retrieve_receipt_by_id(receipt_id).await.is_err()); - } - } - - /// The test code will shuffle the input timestamps prior to calling safe_truncate_receipts. - #[rstest] - #[case(vec![1, 2, 3, 4, 5], 3, vec![1, 2, 3])] - #[case(vec![1, 2, 3, 3, 4, 5], 3, vec![1, 2])] - #[case(vec![1, 2, 3, 4, 4, 4], 3, vec![1, 2, 3])] - #[case(vec![1, 1, 1, 1, 2, 3], 3, vec![])] - #[test] - fn safe_truncate_receipts_test( - domain_separator: Eip712Domain, - #[case] input: Vec, - #[case] limit: u64, - #[case] expected: Vec, - ) { - let wallet: LocalWallet = MnemonicBuilder::::default() - .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") - .build() - .unwrap(); - - // Vec of (id, receipt) - let mut receipts_orig: Vec<(u64, ReceivedReceipt)> = Vec::new(); - - for (i, timestamp) in input.iter().enumerate() { - // The contents of the receipt only need to be unique for this test (so we can check) - receipts_orig.push(( - i as u64, - ReceivedReceipt::new( - EIP712SignedMessage::new( - &domain_separator, - Receipt { - allocation_id: Address::ZERO, - timestamp_ns: *timestamp, - nonce: 0, - value: 0, - }, - &wallet, - ) - .unwrap(), - ), - )); - } - - let mut receipts_truncated = receipts_orig; - - // shuffle the input receipts - receipts_truncated.shuffle(&mut thread_rng()); - - crate::adapters::receipt_storage_adapter::safe_truncate_receipts( - &mut receipts_truncated, - limit, - ); - - assert_eq!(receipts_truncated.len(), expected.len()); - - for (elem_trun, expected_timestamp) in receipts_truncated.iter().zip(expected.iter()) { - // Check timestamps - assert_eq!( - elem_trun.1.signed_receipt().message.timestamp_ns, - *expected_timestamp - ); - } - } -} diff --git a/tap_core/src/error.rs b/tap_core/src/error.rs index 26caea70..d489076f 100644 --- a/tap_core/src/error.rs +++ b/tap_core/src/error.rs @@ -4,7 +4,7 @@ //! Module containing Error type and Result typedef //! -use crate::{receipt_aggregate_voucher::ReceiptAggregateVoucher, tap_receipt::ReceiptError}; +use crate::{rav::ReceiptAggregateVoucher, receipt::ReceiptError}; use alloy_primitives::Address; use ethers::signers::WalletError; use ethers_core::types::SignatureError; diff --git a/tap_core/src/lib.rs b/tap_core/src/lib.rs index af67e6be..dd938063 100644 --- a/tap_core/src/lib.rs +++ b/tap_core/src/lib.rs @@ -11,16 +11,15 @@ use std::time::{SystemTime, UNIX_EPOCH}; use alloy_sol_types::eip712_domain; use thiserror::Error; -pub mod adapters; -pub mod eip_712_signed_message; mod error; -pub mod receipt_aggregate_voucher; -pub mod tap_manager; -pub mod tap_receipt; +pub mod manager; +pub mod rav; +pub mod receipt; +pub mod signed_message; pub use error::{Error, Result}; -pub(crate) fn get_current_timestamp_u64_ns() -> Result { +fn get_current_timestamp_u64_ns() -> Result { Ok(SystemTime::now() .duration_since(UNIX_EPOCH) .map_err(|err| Error::InvalidSystemTime { @@ -51,9 +50,8 @@ mod tap_tests { use rstest::*; use crate::{ - eip_712_signed_message::EIP712SignedMessage, - receipt_aggregate_voucher::ReceiptAggregateVoucher, tap_eip712_domain, - tap_receipt::Receipt, + rav::ReceiptAggregateVoucher, receipt::Receipt, signed_message::EIP712SignedMessage, + tap_eip712_domain, }; #[fixture] diff --git a/tap_core/src/tap_manager/manager.rs b/tap_core/src/manager/manager.rs similarity index 88% rename from tap_core/src/tap_manager/manager.rs rename to tap_core/src/manager/manager.rs index fc3512f8..b544d869 100644 --- a/tap_core/src/tap_manager/manager.rs +++ b/tap_core/src/manager/manager.rs @@ -3,47 +3,38 @@ use alloy_sol_types::Eip712Domain; -use super::{RAVRequest, SignedRAV, SignedReceipt}; +use super::strategy::{EscrowHandler, RAVRead, RAVStore, ReceiptDelete, ReceiptRead, ReceiptStore}; use crate::{ - adapters::{ - escrow_adapter::EscrowAdapter, - rav_storage_adapter::{RAVRead, RAVStore}, - receipt_storage_adapter::{ReceiptDelete, ReceiptRead, ReceiptStore}, - }, - receipt_aggregate_voucher::ReceiptAggregateVoucher, - tap_receipt::{ + rav::{RAVRequest, ReceiptAggregateVoucher, SignedRAV}, + receipt::{ checks::{BatchTimestampCheck, CheckBatch, Checks, UniqueCheck}, - CategorizedReceiptsWithState, Failed, ReceiptAuditor, ReceiptWithState, ReceivedReceipt, - Reserved, + CategorizedReceiptsWithState, Failed, ReceiptWithState, ReceivedReceipt, Reserved, + SignedReceipt, }, Error, }; pub struct Manager { /// Executor that implements adapters - executor: E, + context: E, /// Checks that must be completed for each receipt before being confirmed or denied for rav request checks: Checks, /// Struct responsible for doing checks for receipt. Ownership stays with manager allowing manager /// to update configuration ( like minimum timestamp ). - receipt_auditor: ReceiptAuditor, + domain_separator: Eip712Domain, } -impl Manager -where - E: Clone, -{ +impl Manager { /// Creates new manager with provided `adapters`, any receipts received by this manager /// will complete all `required_checks` before being accepted or declined from RAV. /// `starting_min_timestamp` will be used as min timestamp until the first RAV request is created. /// - pub fn new(domain_separator: Eip712Domain, executor: E, checks: impl Into) -> Self { - let receipt_auditor = ReceiptAuditor::new(domain_separator, executor.clone()); + pub fn new(domain_separator: Eip712Domain, context: E, checks: impl Into) -> Self { Self { - executor, - receipt_auditor, + context, + domain_separator, checks: checks.into(), } } @@ -51,7 +42,7 @@ where impl Manager where - E: RAVStore + EscrowAdapter, + E: RAVStore + EscrowHandler, { /// Verify `signed_rav` matches all values on `expected_rav`, and that `signed_rav` has a valid signer. /// @@ -64,8 +55,8 @@ where expected_rav: ReceiptAggregateVoucher, signed_rav: SignedRAV, ) -> std::result::Result<(), Error> { - self.receipt_auditor - .check_rav_signature(&signed_rav) + self.context + .check_rav_signature(&signed_rav, &self.domain_separator) .await?; if signed_rav.message != expected_rav { @@ -75,7 +66,7 @@ where }); } - self.executor + self.context .update_last_rav(signed_rav) .await .map_err(|err| Error::AdapterError { @@ -92,7 +83,7 @@ where { async fn get_previous_rav(&self) -> Result, Error> { let previous_rav = self - .executor + .context .last_rav() .await .map_err(|err| Error::AdapterError { @@ -104,7 +95,7 @@ where impl Manager where - E: ReceiptRead + EscrowAdapter, + E: ReceiptRead + EscrowHandler, { async fn collect_receipts( &self, @@ -127,7 +118,7 @@ where }); } let received_receipts = self - .executor + .context .retrieve_receipts_in_timestamp_range(min_timestamp_ns..max_timestamp_ns, limit) .await .map_err(|err| Error::AdapterError { @@ -165,7 +156,7 @@ where } for checked in awaiting_reserve_receipts { match checked - .check_and_reserve_escrow(&self.receipt_auditor) + .check_and_reserve_escrow(&self.context, &self.domain_separator) .await { Ok(reserved) => reserved_receipts.push(reserved), @@ -179,7 +170,7 @@ where impl Manager where - E: ReceiptRead + RAVRead + EscrowAdapter, + E: ReceiptRead + RAVRead + EscrowHandler, { /// Completes remaining checks on all receipts up to (current time - `timestamp_buffer_ns`). Returns them in /// two lists (valid receipts and invalid receipts) along with the expected RAV that should be received @@ -257,7 +248,7 @@ where pub async fn remove_obsolete_receipts(&self) -> Result<(), Error> { match self.get_previous_rav().await? { Some(last_rav) => { - self.executor + self.context .remove_receipts_in_timestamp_range(..=last_rav.message.timestampNs) .await .map_err(|err| Error::AdapterError { @@ -297,7 +288,7 @@ where } // store the receipt - self.executor + self.context .store_receipt(received_receipt) .await .map_err(|err| Error::AdapterError { @@ -306,7 +297,3 @@ where Ok(()) } } - -#[cfg(test)] -#[path = "test/manager_test.rs"] -mod manager_test; diff --git a/tap_core/src/tap_manager/mod.rs b/tap_core/src/manager/mod.rs similarity index 72% rename from tap_core/src/tap_manager/mod.rs rename to tap_core/src/manager/mod.rs index f1bdbd27..fb72d263 100644 --- a/tap_core/src/tap_manager/mod.rs +++ b/tap_core/src/manager/mod.rs @@ -11,15 +11,12 @@ //! This design offers a high degree of flexibility, letting the user define their own behavior for these critical operations. mod manager; -mod rav_request; +pub mod strategy; -pub use manager::Manager; -pub use rav_request::RAVRequest; - -use crate::{ - eip_712_signed_message::EIP712SignedMessage, - receipt_aggregate_voucher::ReceiptAggregateVoucher, tap_receipt::Receipt, -}; +// #[cfg(test)] +// mod mock; +// +// #[cfg(test)] +// pub use mock::*; -pub type SignedReceipt = EIP712SignedMessage; -pub type SignedRAV = EIP712SignedMessage; +pub use manager::Manager; diff --git a/tap_core/src/adapters/escrow_adapter.rs b/tap_core/src/manager/strategy/escrow.rs similarity index 63% rename from tap_core/src/adapters/escrow_adapter.rs rename to tap_core/src/manager/strategy/escrow.rs index 4630c361..93760995 100644 --- a/tap_core/src/adapters/escrow_adapter.rs +++ b/tap_core/src/manager/strategy/escrow.rs @@ -2,8 +2,15 @@ // SPDX-License-Identifier: Apache-2.0 use alloy_primitives::Address; +use alloy_sol_types::Eip712Domain; use async_trait::async_trait; +use crate::{ + rav::SignedRAV, + receipt::{AwaitingReserve, ReceiptError, ReceiptResult, ReceiptWithState}, + Error, +}; + /// `EscrowAdapter` defines a trait for adapters to handle escrow related operations. /// /// This trait is designed to be implemented by users of this library who want to @@ -29,7 +36,7 @@ use async_trait::async_trait; /// For example code see [crate::adapters::escrow_adapter_mock] #[async_trait] -pub trait EscrowAdapter { +pub trait EscrowHandler: Send + Sync { /// Defines the user-specified error type. /// /// This error type should implement the `Error` and `Debug` traits from the standard library. @@ -55,4 +62,47 @@ pub trait EscrowAdapter { ) -> Result<(), Self::AdapterError>; async fn verify_signer(&self, signer_address: Address) -> Result; + + async fn check_and_reserve_escrow( + &self, + received_receipt: &ReceiptWithState, + domain_separator: &Eip712Domain, + ) -> ReceiptResult<()> { + let signed_receipt = &received_receipt.signed_receipt; + let receipt_signer_address = + signed_receipt + .recover_signer(domain_separator) + .map_err(|err| ReceiptError::InvalidSignature { + source_error_message: err.to_string(), + })?; + + if self + .subtract_escrow(receipt_signer_address, signed_receipt.message.value) + .await + .is_err() + { + return Err(ReceiptError::SubtractEscrowFailed); + } + + Ok(()) + } + + async fn check_rav_signature( + &self, + signed_rav: &SignedRAV, + domain_separator: &Eip712Domain, + ) -> Result<(), Error> { + let recovered_address = signed_rav.recover_signer(domain_separator)?; + if self + .verify_signer(recovered_address) + .await + .map_err(|e| Error::FailedToVerifySigner(e.to_string()))? + { + Ok(()) + } else { + Err(Error::InvalidRecoveredSigner { + address: recovered_address, + }) + } + } } diff --git a/tap_core/src/adapters/mod.rs b/tap_core/src/manager/strategy/mod.rs similarity index 84% rename from tap_core/src/adapters/mod.rs rename to tap_core/src/manager/strategy/mod.rs index 6b045e4e..c337b972 100644 --- a/tap_core/src/adapters/mod.rs +++ b/tap_core/src/manager/strategy/mod.rs @@ -15,15 +15,10 @@ //! //! In addition, this module also includes mock implementations of each adapter for testing and example purposes. -pub mod escrow_adapter; -pub mod rav_storage_adapter; -pub mod receipt_storage_adapter; +mod escrow; +mod rav; +mod receipt; -#[cfg(feature = "mock")] -mod mock; - -#[cfg(feature = "mock")] -pub use mock::*; - -#[cfg(test)] -mod test; +pub use escrow::EscrowHandler; +pub use rav::*; +pub use receipt::*; diff --git a/tap_core/src/adapters/rav_storage_adapter.rs b/tap_core/src/manager/strategy/rav.rs similarity index 98% rename from tap_core/src/adapters/rav_storage_adapter.rs rename to tap_core/src/manager/strategy/rav.rs index aee6c1be..f55a6dfe 100644 --- a/tap_core/src/adapters/rav_storage_adapter.rs +++ b/tap_core/src/manager/strategy/rav.rs @@ -3,7 +3,7 @@ use async_trait::async_trait; -use crate::tap_manager::SignedRAV; +use crate::rav::SignedRAV; /// `RAVStore` defines a trait for write storage adapters to handle `SignedRAV` data. /// diff --git a/tap_core/src/adapters/receipt_storage_adapter.rs b/tap_core/src/manager/strategy/receipt.rs similarity index 99% rename from tap_core/src/adapters/receipt_storage_adapter.rs rename to tap_core/src/manager/strategy/receipt.rs index af04709b..317e8816 100644 --- a/tap_core/src/adapters/receipt_storage_adapter.rs +++ b/tap_core/src/manager/strategy/receipt.rs @@ -5,7 +5,7 @@ use std::ops::RangeBounds; use async_trait::async_trait; -use crate::tap_receipt::ReceivedReceipt; +use crate::receipt::ReceivedReceipt; /// `ReceiptStore` defines a trait for write storage adapters to manage `ReceivedReceipt` data. /// diff --git a/tap_core/src/receipt_aggregate_voucher.rs b/tap_core/src/rav.rs similarity index 93% rename from tap_core/src/receipt_aggregate_voucher.rs rename to tap_core/src/rav.rs index 14304d54..0248ff00 100644 --- a/tap_core/src/receipt_aggregate_voucher.rs +++ b/tap_core/src/rav.rs @@ -8,6 +8,8 @@ //! The payment receiver would verify the received receipt and store it to be //! accumulated with other received receipts in the future. +mod request; + use std::cmp; use alloy_primitives::Address; @@ -15,7 +17,10 @@ use alloy_sol_types::sol; use serde::{Deserialize, Serialize}; use crate::Error; -use crate::{eip_712_signed_message::EIP712SignedMessage, tap_receipt::Receipt}; +use crate::{receipt::Receipt, signed_message::EIP712SignedMessage}; + +pub type SignedRAV = EIP712SignedMessage; +pub use request::RAVRequest; sol! { /// Holds information needed for promise of payment signed with ECDSA diff --git a/tap_core/src/tap_manager/rav_request.rs b/tap_core/src/rav/request.rs similarity index 73% rename from tap_core/src/tap_manager/rav_request.rs rename to tap_core/src/rav/request.rs index a2794881..3031c6db 100644 --- a/tap_core/src/tap_manager/rav_request.rs +++ b/tap_core/src/rav/request.rs @@ -3,10 +3,9 @@ use serde::{Deserialize, Serialize}; -use super::{SignedRAV, SignedReceipt}; use crate::{ - receipt_aggregate_voucher::ReceiptAggregateVoucher, - tap_receipt::{Failed, ReceiptWithState}, + rav::{ReceiptAggregateVoucher, SignedRAV}, + receipt::{Failed, ReceiptWithState, SignedReceipt}, }; #[derive(Debug, Serialize, Deserialize)] diff --git a/tap_core/src/tap_receipt/checks.rs b/tap_core/src/receipt/checks.rs similarity index 97% rename from tap_core/src/tap_receipt/checks.rs rename to tap_core/src/receipt/checks.rs index 5205e8cd..e13ff133 100644 --- a/tap_core/src/tap_receipt/checks.rs +++ b/tap_core/src/receipt/checks.rs @@ -1,7 +1,7 @@ // Copyright 2023-, Semiotic AI, Inc. // SPDX-License-Identifier: Apache-2.0 -use crate::tap_receipt::{Checking, ReceiptError, ReceiptWithState}; +use crate::receipt::{Checking, ReceiptError, ReceiptWithState}; use std::{ collections::HashSet, ops::Deref, @@ -20,6 +20,10 @@ impl Checks { pub fn new(checks: Vec) -> Self { Self(checks.into()) } + + pub fn empty() -> Self { + Self(Arc::new([])) + } } impl Deref for Checks { @@ -135,7 +139,7 @@ impl CheckBatch for UniqueCheck { pub mod mock { use super::*; - use crate::eip_712_signed_message::MessageId; + use crate::signed_message::MessageId; use alloy_primitives::Address; use alloy_sol_types::Eip712Domain; use std::collections::{HashMap, HashSet}; diff --git a/tap_core/src/tap_receipt/mod.rs b/tap_core/src/receipt/error.rs similarity index 60% rename from tap_core/src/tap_receipt/mod.rs rename to tap_core/src/receipt/error.rs index dbceb141..5e3de046 100644 --- a/tap_core/src/tap_receipt/mod.rs +++ b/tap_core/src/receipt/error.rs @@ -1,23 +1,7 @@ -// Copyright 2023-, Semiotic AI, Inc. -// SPDX-License-Identifier: Apache-2.0 - -pub mod checks; -mod receipt; -mod receipt_auditor; -mod received_receipt; - use alloy_primitives::Address; -pub use receipt::Receipt; -pub use receipt_auditor::ReceiptAuditor; -pub use received_receipt::{ - AwaitingReserve, CategorizedReceiptsWithState, Checking, Failed, ReceiptState, ReceiptWithId, - ReceiptWithState, ReceivedReceipt, Reserved, ResultReceipt, -}; - use serde::{Deserialize, Serialize}; -use thiserror::Error; -#[derive(Error, Debug, Clone, Serialize, Deserialize)] +#[derive(thiserror::Error, Debug, Clone, Serialize, Deserialize)] pub enum ReceiptError { #[error("invalid allocation ID: {received_allocation_id}")] InvalidAllocationID { received_allocation_id: Address }, @@ -37,5 +21,3 @@ pub enum ReceiptError { #[error("Issue encountered while performing check: {0}")] CheckFailedToComplete(String), } - -pub type ReceiptResult = Result; diff --git a/tap_core/src/receipt/mod.rs b/tap_core/src/receipt/mod.rs new file mode 100644 index 00000000..93142e05 --- /dev/null +++ b/tap_core/src/receipt/mod.rs @@ -0,0 +1,19 @@ +// Copyright 2023-, Semiotic AI, Inc. +// SPDX-License-Identifier: Apache-2.0 + +pub mod checks; +mod error; +mod receipt; +mod received_receipt; + +pub use error::ReceiptError; +pub use receipt::Receipt; +pub use received_receipt::{ + AwaitingReserve, CategorizedReceiptsWithState, Checking, Failed, ReceiptState, ReceiptWithId, + ReceiptWithState, ReceivedReceipt, Reserved, ResultReceipt, +}; + +use crate::signed_message::EIP712SignedMessage; + +pub type SignedReceipt = EIP712SignedMessage; +pub type ReceiptResult = Result; diff --git a/tap_core/src/tap_receipt/receipt.rs b/tap_core/src/receipt/receipt.rs similarity index 100% rename from tap_core/src/tap_receipt/receipt.rs rename to tap_core/src/receipt/receipt.rs diff --git a/tap_core/src/tap_receipt/received_receipt.rs b/tap_core/src/receipt/received_receipt.rs similarity index 94% rename from tap_core/src/tap_receipt/received_receipt.rs rename to tap_core/src/receipt/received_receipt.rs index bbf73217..f7b92435 100644 --- a/tap_core/src/tap_receipt/received_receipt.rs +++ b/tap_core/src/receipt/received_receipt.rs @@ -13,13 +13,14 @@ //! This module is useful for managing and tracking the state of received receipts, as well as //! their progress through various checks and stages of inclusion in RAV requests and received RAVs. +use alloy_sol_types::Eip712Domain; use serde::{Deserialize, Serialize}; -use super::{receipt_auditor::ReceiptAuditor, Receipt, ReceiptError, ReceiptResult}; +use super::{Receipt, ReceiptError, ReceiptResult}; use crate::{ - adapters::{escrow_adapter::EscrowAdapter, receipt_storage_adapter::StoredReceipt}, - eip_712_signed_message::EIP712SignedMessage, - tap_receipt::checks::ReceiptCheck, + manager::strategy::{EscrowHandler, StoredReceipt}, + receipt::checks::ReceiptCheck, + signed_message::EIP712SignedMessage, }; #[derive(Debug, Clone)] @@ -177,14 +178,18 @@ where } impl ReceiptWithState { - pub async fn check_and_reserve_escrow( + pub async fn check_and_reserve_escrow( self, - auditor: &ReceiptAuditor, + auditor: &E, + domain_separator: &Eip712Domain, ) -> ResultReceipt where - A: EscrowAdapter, + E: EscrowHandler, { - match auditor.check_and_reserve_escrow(&self).await { + match auditor + .check_and_reserve_escrow(&self, domain_separator) + .await + { Ok(_) => Ok(self.perform_state_changes(Reserved)), Err(e) => Err(self.perform_state_error(e)), } @@ -257,5 +262,3 @@ where &self.signed_receipt } } -#[cfg(test)] -pub mod received_receipt_unit_test; diff --git a/tap_core/src/eip_712_signed_message.rs b/tap_core/src/signed_message.rs similarity index 100% rename from tap_core/src/eip_712_signed_message.rs rename to tap_core/src/signed_message.rs diff --git a/tap_core/src/tap_receipt/receipt_auditor.rs b/tap_core/src/tap_receipt/receipt_auditor.rs deleted file mode 100644 index f3c0683a..00000000 --- a/tap_core/src/tap_receipt/receipt_auditor.rs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2023-, Semiotic AI, Inc. -// SPDX-License-Identifier: Apache-2.0 - -use alloy_sol_types::Eip712Domain; - -use crate::{ - adapters::escrow_adapter::EscrowAdapter, - tap_manager::SignedRAV, - tap_receipt::{ReceiptError, ReceiptResult}, - Error, -}; - -use super::{AwaitingReserve, ReceiptWithState}; - -pub struct ReceiptAuditor { - domain_separator: Eip712Domain, - executor: E, -} - -impl ReceiptAuditor { - pub fn new(domain_separator: Eip712Domain, executor: E) -> Self { - Self { - domain_separator, - executor, - } - } -} - -impl ReceiptAuditor -where - E: EscrowAdapter, -{ - pub async fn check_and_reserve_escrow( - &self, - received_receipt: &ReceiptWithState, - ) -> ReceiptResult<()> { - let signed_receipt = &received_receipt.signed_receipt; - let receipt_signer_address = signed_receipt - .recover_signer(&self.domain_separator) - .map_err(|err| ReceiptError::InvalidSignature { - source_error_message: err.to_string(), - })?; - - if self - .executor - .subtract_escrow(receipt_signer_address, signed_receipt.message.value) - .await - .is_err() - { - return Err(ReceiptError::SubtractEscrowFailed); - } - - Ok(()) - } - - pub async fn check_rav_signature(&self, signed_rav: &SignedRAV) -> Result<(), Error> { - let recovered_address = signed_rav.recover_signer(&self.domain_separator)?; - if self - .executor - .verify_signer(recovered_address) - .await - .map_err(|e| Error::FailedToVerifySigner(e.to_string()))? - { - Ok(()) - } else { - Err(Error::InvalidRecoveredSigner { - address: recovered_address, - }) - } - } -} diff --git a/tap_core/src/adapters/mock/executor_mock.rs b/tap_core/tests/common/mock.rs similarity index 94% rename from tap_core/src/adapters/mock/executor_mock.rs rename to tap_core/tests/common/mock.rs index 72e08fca..d131389d 100644 --- a/tap_core/src/adapters/mock/executor_mock.rs +++ b/tap_core/tests/common/mock.rs @@ -1,22 +1,17 @@ // Copyright 2023-, Semiotic AI, Inc. // SPDX-License-Identifier: Apache-2.0 -use crate::adapters::escrow_adapter::EscrowAdapter; -use crate::adapters::receipt_storage_adapter::{ - safe_truncate_receipts, ReceiptDelete, ReceiptRead, ReceiptStore, StoredReceipt, -}; -use crate::eip_712_signed_message::MessageId; -use crate::tap_receipt::checks::TimestampCheck; -use crate::tap_receipt::ReceivedReceipt; -use crate::{ - adapters::rav_storage_adapter::{RAVRead, RAVStore}, - tap_manager::SignedRAV, -}; use alloy_primitives::Address; use async_trait::async_trait; use std::ops::RangeBounds; use std::sync::RwLock; use std::{collections::HashMap, sync::Arc}; +use tap_core::{ + manager::strategy::*, + rav::SignedRAV, + receipt::{checks::TimestampCheck, ReceivedReceipt}, + signed_message::MessageId, +}; pub type EscrowStorage = Arc>>; pub type QueryAppraisals = Arc>>; @@ -234,7 +229,7 @@ impl ExecutorMock { } #[async_trait] -impl EscrowAdapter for ExecutorMock { +impl EscrowHandler for ExecutorMock { type AdapterError = AdapterErrorMock; async fn get_available_escrow(&self, sender_id: Address) -> Result { self.escrow(sender_id) diff --git a/tap_core/tests/common/mod.rs b/tap_core/tests/common/mod.rs new file mode 100644 index 00000000..8c5a98a9 --- /dev/null +++ b/tap_core/tests/common/mod.rs @@ -0,0 +1,5 @@ +mod mock; +mod timestamp; + +pub use mock::*; + diff --git a/tap_core/tests/common/timestamp.rs b/tap_core/tests/common/timestamp.rs new file mode 100644 index 00000000..8770e91e --- /dev/null +++ b/tap_core/tests/common/timestamp.rs @@ -0,0 +1,12 @@ +use std::time::{SystemTime, UNIX_EPOCH}; + +use tap_core::Error; + +pub fn get_current_timestamp_u64_ns() -> anyhow::Result { + Ok(SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|err| Error::InvalidSystemTime { + source_error_message: err.to_string(), + })? + .as_nanos() as u64) +} diff --git a/tap_core/tests/escrow_test.rs b/tap_core/tests/escrow_test.rs new file mode 100644 index 00000000..be439e25 --- /dev/null +++ b/tap_core/tests/escrow_test.rs @@ -0,0 +1,80 @@ +// Copyright 2023-, Semiotic AI, Inc. +// SPDX-License-Identifier: Apache-2.0 + +use std::{ + collections::HashMap, + sync::{Arc, RwLock}, +}; + +use ethers::signers::{coins_bip39::English, LocalWallet, MnemonicBuilder, Signer}; +use rstest::*; + +mod common; + +use common::ExecutorMock; + +use tap_core::{manager::strategy::EscrowHandler, receipt::checks::TimestampCheck}; + +#[fixture] +fn executor() -> ExecutorMock { + let escrow_storage = Arc::new(RwLock::new(HashMap::new())); + let rav_storage = Arc::new(RwLock::new(None)); + let receipt_storage = Arc::new(RwLock::new(HashMap::new())); + + let timestamp_check = Arc::new(TimestampCheck::new(0)); + ExecutorMock::new( + rav_storage, + receipt_storage.clone(), + escrow_storage.clone(), + timestamp_check, + ) +} + +#[rstest] +#[tokio::test] +async fn escrow_adapter_test(mut executor: ExecutorMock) { + let wallet: LocalWallet = MnemonicBuilder::::default() + .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") + .build() + .unwrap(); + let sender_id: [u8; 20] = wallet.address().into(); + let sender_id = sender_id.into(); + + let invalid_wallet: LocalWallet = MnemonicBuilder::::default() + .phrase("wrong century settle satisfy market forest title connect ten push alley depend") + .build() + .unwrap(); + let invalid_sender_id: [u8; 20] = invalid_wallet.address().into(); + let invalid_sender_id = invalid_sender_id.into(); + + let initial_value = 500u128; + + executor.increase_escrow(sender_id, initial_value); + + // Check that sender exists and has valid value through adapter + assert!(executor.get_available_escrow(sender_id).await.is_ok()); + assert_eq!( + executor.get_available_escrow(sender_id).await.unwrap(), + initial_value + ); + + // Check that subtracting is valid for valid sender, and results in expected value + assert!(executor + .subtract_escrow(sender_id, initial_value) + .await + .is_ok()); + assert!(executor.get_available_escrow(sender_id).await.is_ok()); + assert_eq!(executor.get_available_escrow(sender_id).await.unwrap(), 0); + + // Check that subtracting to negative escrow results in err + assert!(executor + .subtract_escrow(sender_id, initial_value) + .await + .is_err()); + + // Check that accessing non initialized sender results in err + assert!(executor + .get_available_escrow(invalid_sender_id) + .await + .is_err()); +} diff --git a/tap_integration_tests/tests/indexer_mock/mod.rs b/tap_core/tests/indexer_mock/mod.rs similarity index 94% rename from tap_integration_tests/tests/indexer_mock/mod.rs rename to tap_core/tests/indexer_mock/mod.rs index 16cb1f67..301d3cf9 100644 --- a/tap_integration_tests/tests/indexer_mock/mod.rs +++ b/tap_core/tests/indexer_mock/mod.rs @@ -17,13 +17,12 @@ use jsonrpsee::{ use tap_aggregator::jsonrpsee_helpers; use tap_core::{ - adapters::{ - escrow_adapter::EscrowAdapter, - rav_storage_adapter::{RAVRead, RAVStore}, - receipt_storage_adapter::{ReceiptRead, ReceiptStore}, + manager::{ + strategy::{EscrowHandler, RAVRead, RAVStore, ReceiptRead, ReceiptStore}, + Manager, }, - tap_manager::{Manager, SignedRAV, SignedReceipt}, - tap_receipt::checks::Checks, + rav::SignedRAV, + receipt::{checks::Checks, SignedReceipt}, }; /// Rpc trait represents a JSON-RPC server that has a single async method `request`. /// This method is designed to handle incoming JSON-RPC requests. @@ -85,7 +84,7 @@ where #[async_trait] impl RpcServer for RpcManager where - E: ReceiptStore + ReceiptRead + RAVStore + RAVRead + EscrowAdapter + Send + Sync + 'static, + E: ReceiptStore + ReceiptRead + RAVStore + RAVRead + EscrowHandler + Send + Sync + 'static, { async fn request( &self, @@ -145,7 +144,7 @@ where + ReceiptRead + RAVStore + RAVRead - + EscrowAdapter + + EscrowHandler + Clone + Send + Sync @@ -180,7 +179,7 @@ async fn request_rav( threshold: usize, ) -> Result<()> where - E: ReceiptRead + RAVRead + RAVStore + EscrowAdapter, + E: ReceiptRead + RAVRead + RAVStore + EscrowHandler, { // Create the aggregate_receipts request params let rav_request = manager.create_rav_request(time_stamp_buffer, None).await?; diff --git a/tap_core/src/tap_manager/test/manager_test.rs b/tap_core/tests/manager_test.rs similarity index 97% rename from tap_core/src/tap_manager/test/manager_test.rs rename to tap_core/tests/manager_test.rs index 080cbd40..5c067425 100644 --- a/tap_core/src/tap_manager/test/manager_test.rs +++ b/tap_core/tests/manager_test.rs @@ -11,18 +11,18 @@ use alloy_sol_types::Eip712Domain; use ethers::signers::{coins_bip39::English, LocalWallet, MnemonicBuilder, Signer}; use rstest::*; -use super::super::Manager; -use crate::{ - adapters::{ - executor_mock::{EscrowStorage, ExecutorMock, QueryAppraisals}, - receipt_storage_adapter::ReceiptRead, - }, - eip_712_signed_message::EIP712SignedMessage, - get_current_timestamp_u64_ns, tap_eip712_domain, - tap_receipt::{ +mod common; + +use common::{get_current_timestamp_u64_ns, EscrowStorage, ExecutorMock, QueryAppraisals}; + +use tap_core::{ + manager::{strategy::ReceiptRead, Manager}, + receipt::{ checks::{mock::get_full_list_of_checks, Checks, TimestampCheck}, Receipt, }, + signed_message::EIP712SignedMessage, + tap_eip712_domain, }; #[fixture] @@ -328,7 +328,7 @@ async fn manager_create_multiple_rav_requests_all_valid_receipts_consecutive_tim } = executor_mock; let starting_min_timestamp = get_current_timestamp_u64_ns().unwrap() - 500000000; - let manager = Manager::new(domain_separator.clone(), executor, checks); + let manager = Manager::new(domain_separator.clone(), executor.clone(), checks); escrow_storage.write().unwrap().insert(keys.1, 999999); @@ -407,8 +407,7 @@ async fn manager_create_multiple_rav_requests_all_valid_receipts_consecutive_tim manager.remove_obsolete_receipts().await.unwrap(); // We expect to have 10 receipts left in receipt storage assert_eq!( - manager - .executor + executor .retrieve_receipts_in_timestamp_range(.., None) .await .unwrap() diff --git a/tap_core/tests/rav_test.rs b/tap_core/tests/rav_test.rs new file mode 100644 index 00000000..e0e0828f --- /dev/null +++ b/tap_core/tests/rav_test.rs @@ -0,0 +1,113 @@ +// Copyright 2023-, Semiotic AI, Inc. +// SPDX-License-Identifier: Apache-2.0 + +use std::collections::HashMap; +use std::sync::RwLock; +use std::{str::FromStr, sync::Arc}; + +use alloy_primitives::Address; +use alloy_sol_types::Eip712Domain; +use ethers::signers::coins_bip39::English; +use ethers::signers::{LocalWallet, MnemonicBuilder}; +use rstest::*; + +mod common; + +use common::ExecutorMock; + +use tap_core::{ + manager::strategy::{RAVRead, RAVStore}, + rav::ReceiptAggregateVoucher, + receipt::{checks::TimestampCheck, Receipt}, + signed_message::EIP712SignedMessage, + tap_eip712_domain, +}; + +#[fixture] +fn domain_separator() -> Eip712Domain { + tap_eip712_domain(1, Address::from([0x11u8; 20])) +} + +#[fixture] +fn executor() -> ExecutorMock { + let escrow_storage = Arc::new(RwLock::new(HashMap::new())); + let rav_storage = Arc::new(RwLock::new(None)); + let receipt_storage = Arc::new(RwLock::new(HashMap::new())); + + let timestamp_check = Arc::new(TimestampCheck::new(0)); + ExecutorMock::new( + rav_storage, + receipt_storage.clone(), + escrow_storage.clone(), + timestamp_check, + ) +} + +#[rstest] +#[tokio::test] +async fn rav_storage_adapter_test(domain_separator: Eip712Domain, executor: ExecutorMock) { + let wallet: LocalWallet = MnemonicBuilder::::default() + .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") + .build() + .unwrap(); + + let allocation_id: [u8; 20] = Address::from_str("0xabababababababababababababababababababab") + .unwrap() + .into(); + let allocation_id = allocation_id.into(); + + // Create receipts + let mut receipts = Vec::new(); + for value in 50..60 { + receipts.push( + EIP712SignedMessage::new( + &domain_separator, + Receipt::new(allocation_id, value).unwrap(), + &wallet, + ) + .unwrap(), + ); + } + + let signed_rav = EIP712SignedMessage::new( + &domain_separator, + ReceiptAggregateVoucher::aggregate_receipts(allocation_id, &receipts, None).unwrap(), + &wallet, + ) + .unwrap(); + + executor.update_last_rav(signed_rav.clone()).await.unwrap(); + + // Retreive rav + let retrieved_rav = executor.last_rav().await; + assert!(retrieved_rav.unwrap().unwrap() == signed_rav); + + // Testing the last rav update... + + // Create more receipts + let mut receipts = Vec::new(); + for value in 60..70 { + receipts.push( + EIP712SignedMessage::new( + &domain_separator, + Receipt::new(allocation_id, value).unwrap(), + &wallet, + ) + .unwrap(), + ); + } + + let signed_rav = EIP712SignedMessage::new( + &domain_separator, + ReceiptAggregateVoucher::aggregate_receipts(allocation_id, &receipts, None).unwrap(), + &wallet, + ) + .unwrap(); + + // Update the last rav + executor.update_last_rav(signed_rav.clone()).await.unwrap(); + + // Retreive rav + let retrieved_rav = executor.last_rav().await; + assert!(retrieved_rav.unwrap().unwrap() == signed_rav); +} diff --git a/tap_core/tests/receipt_test.rs b/tap_core/tests/receipt_test.rs new file mode 100644 index 00000000..979a7360 --- /dev/null +++ b/tap_core/tests/receipt_test.rs @@ -0,0 +1,214 @@ +// Copyright 2023-, Semiotic AI, Inc. +// SPDX-License-Identifier: Apache-2.0 +use rand::seq::SliceRandom; +use rand::thread_rng; +use std::collections::HashMap; +use std::str::FromStr; +use std::sync::{Arc, RwLock}; + +mod common; + +use common::ExecutorMock; + +use alloy_primitives::Address; +use alloy_sol_types::Eip712Domain; +use ethers::signers::{coins_bip39::English, LocalWallet, MnemonicBuilder}; +use rstest::*; +use tap_core::receipt::checks::TimestampCheck; +use tap_core::{ + manager::strategy::ReceiptStore, + receipt::{Receipt, ReceivedReceipt}, + signed_message::EIP712SignedMessage, + tap_eip712_domain, +}; + +#[fixture] +fn domain_separator() -> Eip712Domain { + tap_eip712_domain(1, Address::from([0x11u8; 20])) +} + +#[fixture] +fn executor() -> ExecutorMock { + let escrow_storage = Arc::new(RwLock::new(HashMap::new())); + let rav_storage = Arc::new(RwLock::new(None)); + let receipt_storage = Arc::new(RwLock::new(HashMap::new())); + + let timestamp_check = Arc::new(TimestampCheck::new(0)); + ExecutorMock::new( + rav_storage, + receipt_storage.clone(), + escrow_storage.clone(), + timestamp_check.clone(), + ) +} + +#[rstest] +#[tokio::test] +async fn receipt_adapter_test(domain_separator: Eip712Domain, mut executor: ExecutorMock) { + let wallet: LocalWallet = MnemonicBuilder::::default() + .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") + .build() + .unwrap(); + + let allocation_id = Address::from_str("0xabababababababababababababababababababab").unwrap(); + + // Create receipts + let value = 100u128; + let received_receipt = ReceivedReceipt::new( + EIP712SignedMessage::new( + &domain_separator, + Receipt::new(allocation_id, value).unwrap(), + &wallet, + ) + .unwrap(), + ); + + let receipt_store_result = executor.store_receipt(received_receipt).await; + assert!(receipt_store_result.is_ok()); + let receipt_id = receipt_store_result.unwrap(); + + // Retreive receipt with id expected to be valid + assert!(executor.retrieve_receipt_by_id(receipt_id).await.is_ok()); + // Retreive receipt with arbitrary id expected to be invalid + assert!(executor.retrieve_receipt_by_id(999).await.is_err()); + + // Remove receipt with id expected to be valid + assert!(executor.remove_receipt_by_id(receipt_id).await.is_ok()); + // Remove receipt with arbitrary id expected to be invalid + assert!(executor.remove_receipt_by_id(999).await.is_err()); + + // Retreive receipt that was removed previously + assert!(executor.retrieve_receipt_by_id(receipt_id).await.is_err()); + + // Remove receipt that was removed previously + assert!(executor.remove_receipt_by_id(receipt_id).await.is_err()); +} + +#[rstest] +#[tokio::test] +async fn multi_receipt_adapter_test(domain_separator: Eip712Domain, mut executor: ExecutorMock) { + let wallet: LocalWallet = MnemonicBuilder::::default() + .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") + .build() + .unwrap(); + + let allocation_id = Address::from_str("0xabababababababababababababababababababab").unwrap(); + + // Create receipts + let mut received_receipts = Vec::new(); + for value in 50..60 { + received_receipts.push(ReceivedReceipt::new( + EIP712SignedMessage::new( + &domain_separator, + Receipt::new(allocation_id, value).unwrap(), + &wallet, + ) + .unwrap(), + )); + } + let mut receipt_ids = Vec::new(); + let mut receipt_timestamps = Vec::new(); + for received_receipt in received_receipts { + receipt_timestamps.push(received_receipt.signed_receipt().message.timestamp_ns); + receipt_ids.push(executor.store_receipt(received_receipt).await.unwrap()); + } + + // Retreive receipts with timestamp + assert!(executor + .retrieve_receipts_by_timestamp(receipt_timestamps[0]) + .await + .is_ok()); + assert!(!executor + .retrieve_receipts_by_timestamp(receipt_timestamps[0]) + .await + .unwrap() + .is_empty()); + + // Retreive receipts before timestamp + assert!(executor + .retrieve_receipts_upto_timestamp(receipt_timestamps[3]) + .await + .is_ok()); + assert!( + executor + .retrieve_receipts_upto_timestamp(receipt_timestamps[3]) + .await + .unwrap() + .len() + >= 4 + ); + + // Remove all receipts with one call + assert!(executor + .remove_receipts_by_ids(receipt_ids.as_slice()) + .await + .is_ok()); + // Removal should no longer be valid + assert!(executor + .remove_receipts_by_ids(receipt_ids.as_slice()) + .await + .is_err()); + // Retrieval should be invalid + for receipt_id in receipt_ids { + assert!(executor.retrieve_receipt_by_id(receipt_id).await.is_err()); + } +} + +/// The test code will shuffle the input timestamps prior to calling safe_truncate_receipts. +#[rstest] +#[case(vec![1, 2, 3, 4, 5], 3, vec![1, 2, 3])] +#[case(vec![1, 2, 3, 3, 4, 5], 3, vec![1, 2])] +#[case(vec![1, 2, 3, 4, 4, 4], 3, vec![1, 2, 3])] +#[case(vec![1, 1, 1, 1, 2, 3], 3, vec![])] +#[test] +fn safe_truncate_receipts_test( + domain_separator: Eip712Domain, + #[case] input: Vec, + #[case] limit: u64, + #[case] expected: Vec, +) { + let wallet: LocalWallet = MnemonicBuilder::::default() + .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") + .build() + .unwrap(); + + // Vec of (id, receipt) + let mut receipts_orig: Vec<(u64, ReceivedReceipt)> = Vec::new(); + + for (i, timestamp) in input.iter().enumerate() { + // The contents of the receipt only need to be unique for this test (so we can check) + receipts_orig.push(( + i as u64, + ReceivedReceipt::new( + EIP712SignedMessage::new( + &domain_separator, + Receipt { + allocation_id: Address::ZERO, + timestamp_ns: *timestamp, + nonce: 0, + value: 0, + }, + &wallet, + ) + .unwrap(), + ), + )); + } + + let mut receipts_truncated = receipts_orig; + + // shuffle the input receipts + receipts_truncated.shuffle(&mut thread_rng()); + + tap_core::manager::strategy::safe_truncate_receipts(&mut receipts_truncated, limit); + + assert_eq!(receipts_truncated.len(), expected.len()); + + for (elem_trun, expected_timestamp) in receipts_truncated.iter().zip(expected.iter()) { + // Check timestamps + assert_eq!( + elem_trun.1.signed_receipt().message.timestamp_ns, + *expected_timestamp + ); + } +} diff --git a/tap_core/src/tap_receipt/received_receipt/received_receipt_unit_test.rs b/tap_core/tests/received_receipt_test.rs similarity index 94% rename from tap_core/src/tap_receipt/received_receipt/received_receipt_unit_test.rs rename to tap_core/tests/received_receipt_test.rs index c36846e0..97a481a5 100644 --- a/tap_core/src/tap_receipt/received_receipt/received_receipt_unit_test.rs +++ b/tap_core/tests/received_receipt_test.rs @@ -1,6 +1,9 @@ // Copyright 2023-, Semiotic AI, Inc. // SPDX-License-Identifier: Apache-2.0 +mod common; + +use common::{EscrowStorage, ExecutorMock, QueryAppraisals}; use std::{ collections::HashMap, str::FromStr, @@ -11,15 +14,13 @@ use alloy_primitives::Address; use alloy_sol_types::Eip712Domain; use ethers::signers::{coins_bip39::English, LocalWallet, MnemonicBuilder, Signer}; use rstest::*; - -use crate::{ - adapters::executor_mock::{EscrowStorage, ExecutorMock, QueryAppraisals}, - eip_712_signed_message::EIP712SignedMessage, - tap_eip712_domain, - tap_receipt::{ +use tap_core::{ + receipt::{ checks::{mock::get_full_list_of_checks, ReceiptCheck, TimestampCheck}, - Receipt, ReceiptAuditor, ReceivedReceipt, + Receipt, ReceivedReceipt, }, + signed_message::EIP712SignedMessage, + tap_eip712_domain, }; #[fixture] @@ -187,7 +188,6 @@ async fn partial_then_finalize_valid_receipt( query_appraisals, .. } = executor_mock; - let receipt_auditor = ReceiptAuditor::new(domain_separator.clone(), executor); let query_value = 20u128; let signed_receipt = EIP712SignedMessage::new( @@ -221,7 +221,7 @@ async fn partial_then_finalize_valid_receipt( let awaiting_escrow_receipt = awaiting_escrow_receipt.unwrap(); let receipt = awaiting_escrow_receipt - .check_and_reserve_escrow(&receipt_auditor) + .check_and_reserve_escrow(&executor, &domain_separator) .await; assert!(receipt.is_ok()); } @@ -241,7 +241,6 @@ async fn standard_lifetime_valid_receipt( query_appraisals, .. } = executor_mock; - let receipt_auditor = ReceiptAuditor::new(domain_separator.clone(), executor); let query_value = 20u128; let signed_receipt = EIP712SignedMessage::new( @@ -276,7 +275,7 @@ async fn standard_lifetime_valid_receipt( let awaiting_escrow_receipt = awaiting_escrow_receipt.unwrap(); let receipt = awaiting_escrow_receipt - .check_and_reserve_escrow(&receipt_auditor) + .check_and_reserve_escrow(&executor, &domain_separator) .await; assert!(receipt.is_ok()); } diff --git a/tap_integration_tests/tests/showcase.rs b/tap_core/tests/showcase.rs similarity index 99% rename from tap_integration_tests/tests/showcase.rs rename to tap_core/tests/showcase.rs index dc388121..86b47c60 100644 --- a/tap_integration_tests/tests/showcase.rs +++ b/tap_core/tests/showcase.rs @@ -22,19 +22,20 @@ use jsonrpsee::{ use rand::{rngs::StdRng, Rng, SeedableRng}; use rstest::*; +use common::{ExecutorMock, QueryAppraisals}; use tap_aggregator::{jsonrpsee_helpers, server as agg_server}; use tap_core::{ - adapters::executor_mock::{ExecutorMock, QueryAppraisals}, - eip_712_signed_message::{EIP712SignedMessage, MessageId}, - tap_eip712_domain, - tap_manager::SignedRAV, - tap_receipt::{ + rav::SignedRAV, + receipt::{ checks::{mock::get_full_list_of_checks, Checks, TimestampCheck}, Receipt, }, + signed_message::{EIP712SignedMessage, MessageId}, + tap_eip712_domain, }; -use crate::indexer_mock; +mod common; +mod indexer_mock; // Fixtures for sender aggregator server #[fixture] diff --git a/tap_integration_tests/tests/lib.rs b/tap_integration_tests/tests/lib.rs index 1d207758..846ba270 100644 --- a/tap_integration_tests/tests/lib.rs +++ b/tap_integration_tests/tests/lib.rs @@ -1,5 +1,5 @@ // Copyright 2023-, Semiotic AI, Inc. // SPDX-License-Identifier: Apache-2.0 - -mod indexer_mock; -mod showcase; +// +// mod indexer_mock; +// mod showcase; From 8b77e8e118909284fe6452fe9acaa4dfc144fd63 Mon Sep 17 00:00:00 2001 From: Gustavo Inacio Date: Sun, 10 Mar 2024 11:42:54 -0300 Subject: [PATCH 02/11] refactor: remove ReceivedReceipt and StoredReceipt Signed-off-by: Gustavo Inacio --- tap_core/src/manager/manager.rs | 25 ++--- tap_core/src/manager/strategy/receipt.rs | 34 +++--- tap_core/src/receipt/mod.rs | 3 +- tap_core/src/receipt/received_receipt.rs | 131 ++--------------------- tap_core/tests/common/mock.rs | 26 ++--- tap_core/tests/common/mod.rs | 2 +- tap_core/tests/receipt_test.rs | 42 ++++---- tap_core/tests/received_receipt_test.rs | 45 +------- 8 files changed, 67 insertions(+), 241 deletions(-) diff --git a/tap_core/src/manager/manager.rs b/tap_core/src/manager/manager.rs index b544d869..34fa42a0 100644 --- a/tap_core/src/manager/manager.rs +++ b/tap_core/src/manager/manager.rs @@ -8,8 +8,7 @@ use crate::{ rav::{RAVRequest, ReceiptAggregateVoucher, SignedRAV}, receipt::{ checks::{BatchTimestampCheck, CheckBatch, Checks, UniqueCheck}, - CategorizedReceiptsWithState, Failed, ReceiptWithState, ReceivedReceipt, Reserved, - SignedReceipt, + Failed, ReceiptWithState, Reserved, SignedReceipt, }, Error, }; @@ -117,7 +116,7 @@ where max_timestamp_ns, }); } - let received_receipts = self + let checking_receipts = self .context .retrieve_receipts_in_timestamp_range(min_timestamp_ns..max_timestamp_ns, limit) .await @@ -125,17 +124,9 @@ where source_error: anyhow::Error::new(err), })?; - let CategorizedReceiptsWithState { - checking_receipts, - mut awaiting_reserve_receipts, - mut failed_receipts, - mut reserved_receipts, - } = received_receipts.into(); - - let checking_receipts = checking_receipts - .into_iter() - .map(|receipt| receipt.receipt) - .collect::>(); + let mut awaiting_reserve_receipts = vec![]; + let mut failed_receipts = vec![]; + let mut reserved_receipts = vec![]; // check for timestamp let (checking_receipts, already_failed) = @@ -280,12 +271,10 @@ where &self, signed_receipt: SignedReceipt, ) -> std::result::Result<(), Error> { - let mut received_receipt = ReceivedReceipt::new(signed_receipt); + let mut received_receipt = ReceiptWithState::new(signed_receipt); // perform checks - if let ReceivedReceipt::Checking(received_receipt) = &mut received_receipt { - received_receipt.perform_checks(&self.checks).await?; - } + received_receipt.perform_checks(&self.checks).await?; // store the receipt self.context diff --git a/tap_core/src/manager/strategy/receipt.rs b/tap_core/src/manager/strategy/receipt.rs index 317e8816..82bfd8e6 100644 --- a/tap_core/src/manager/strategy/receipt.rs +++ b/tap_core/src/manager/strategy/receipt.rs @@ -5,7 +5,7 @@ use std::ops::RangeBounds; use async_trait::async_trait; -use crate::receipt::ReceivedReceipt; +use crate::receipt::{Checking, ReceiptState, ReceiptWithState}; /// `ReceiptStore` defines a trait for write storage adapters to manage `ReceivedReceipt` data. /// @@ -46,7 +46,10 @@ pub trait ReceiptStore { /// This method should be implemented to store a new `ReceivedReceipt` into your chosen storage system. /// It returns a unique receipt_id associated with the stored receipt. Any errors that occur during /// this process should be captured and returned as an `AdapterError`. - async fn store_receipt(&self, receipt: ReceivedReceipt) -> Result; + async fn store_receipt( + &self, + receipt: ReceiptWithState, + ) -> Result; } #[async_trait] @@ -112,27 +115,17 @@ pub trait ReceiptRead { &self, timestamp_range_ns: R, limit: Option, - ) -> Result, Self::AdapterError>; -} - -pub struct StoredReceipt { - pub receipt_id: u64, - pub receipt: ReceivedReceipt, + ) -> Result>, Self::AdapterError>; } -impl From<(u64, ReceivedReceipt)> for StoredReceipt { - fn from((receipt_id, receipt): (u64, ReceivedReceipt)) -> Self { - Self { - receipt_id, - receipt, - } - } -} /// See [`ReceiptStorageAdapter::retrieve_receipts_in_timestamp_range()`] for details. /// /// WARNING: Will sort the receipts by timestamp using /// [vec::sort_unstable](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.sort_unstable). -pub fn safe_truncate_receipts(receipts: &mut Vec<(u64, ReceivedReceipt)>, limit: u64) { +pub fn safe_truncate_receipts( + receipts: &mut Vec>, + limit: u64, +) { if receipts.len() <= limit as usize { return; } else if limit == 0 { @@ -140,18 +133,15 @@ pub fn safe_truncate_receipts(receipts: &mut Vec<(u64, ReceivedReceipt)>, limit: return; } - receipts - .sort_unstable_by_key(|(_, rx_receipt)| rx_receipt.signed_receipt().message.timestamp_ns); + receipts.sort_unstable_by_key(|rx_receipt| rx_receipt.signed_receipt().message.timestamp_ns); // This one will be the last timestamp in `receipts` after naive truncation let last_timestamp = receipts[limit as usize - 1] - .1 .signed_receipt() .message .timestamp_ns; // This one is the timestamp that comes just after the one above let after_last_timestamp = receipts[limit as usize] - .1 .signed_receipt() .message .timestamp_ns; @@ -162,7 +152,7 @@ pub fn safe_truncate_receipts(receipts: &mut Vec<(u64, ReceivedReceipt)>, limit: // If the last timestamp is the same as the one that came after it, we need to // remove all the receipts with the same timestamp as the last one, because // otherwise we would leave behind part of the receipts for that timestamp. - receipts.retain(|(_, rx_receipt)| { + receipts.retain(|rx_receipt| { rx_receipt.signed_receipt().message.timestamp_ns != last_timestamp }); } diff --git a/tap_core/src/receipt/mod.rs b/tap_core/src/receipt/mod.rs index 93142e05..ca676e96 100644 --- a/tap_core/src/receipt/mod.rs +++ b/tap_core/src/receipt/mod.rs @@ -9,8 +9,7 @@ mod received_receipt; pub use error::ReceiptError; pub use receipt::Receipt; pub use received_receipt::{ - AwaitingReserve, CategorizedReceiptsWithState, Checking, Failed, ReceiptState, ReceiptWithId, - ReceiptWithState, ReceivedReceipt, Reserved, ResultReceipt, + AwaitingReserve, Checking, Failed, ReceiptState, ReceiptWithState, Reserved, ResultReceipt, }; use crate::signed_message::EIP712SignedMessage; diff --git a/tap_core/src/receipt/received_receipt.rs b/tap_core/src/receipt/received_receipt.rs index f7b92435..8e2af59c 100644 --- a/tap_core/src/receipt/received_receipt.rs +++ b/tap_core/src/receipt/received_receipt.rs @@ -16,10 +16,9 @@ use alloy_sol_types::Eip712Domain; use serde::{Deserialize, Serialize}; -use super::{Receipt, ReceiptError, ReceiptResult}; +use super::{Receipt, ReceiptError, ReceiptResult, SignedReceipt}; use crate::{ - manager::strategy::{EscrowHandler, StoredReceipt}, - receipt::checks::ReceiptCheck, + manager::strategy::EscrowHandler, receipt::checks::ReceiptCheck, signed_message::EIP712SignedMessage, }; @@ -44,127 +43,8 @@ impl ReceiptState for AwaitingReserve {} impl ReceiptState for Reserved {} impl ReceiptState for Failed {} -#[derive(Clone)] -pub enum ReceivedReceipt { - AwaitingReserve(ReceiptWithState), - Checking(ReceiptWithState), - Failed(ReceiptWithState), - Reserved(ReceiptWithState), -} - pub type ResultReceipt = std::result::Result, ReceiptWithState>; -pub struct ReceiptWithId -where - T: ReceiptState, -{ - pub receipt_id: u64, - pub(crate) receipt: ReceiptWithState, -} - -impl From<(u64, ReceiptWithState)> for ReceiptWithId -where - T: ReceiptState, -{ - fn from((receipt_id, receipt): (u64, ReceiptWithState)) -> ReceiptWithId { - Self { - receipt_id, - receipt, - } - } -} - -pub struct CategorizedReceiptsWithState { - pub(crate) awaiting_reserve_receipts: Vec>, - pub(crate) checking_receipts: Vec>, - pub(crate) failed_receipts: Vec>, - pub(crate) reserved_receipts: Vec>, -} - -impl From> for ReceivedReceipt { - fn from(val: ResultReceipt) -> Self { - match val { - Ok(checked) => ReceivedReceipt::AwaitingReserve(checked), - Err(failed) => ReceivedReceipt::Failed(failed), - } - } -} - -impl From> for ReceivedReceipt { - fn from(val: ReceiptWithState) -> Self { - ReceivedReceipt::AwaitingReserve(val) - } -} - -impl From> for ReceivedReceipt { - fn from(val: ReceiptWithState) -> Self { - ReceivedReceipt::Checking(val) - } -} - -impl From> for ReceivedReceipt { - fn from(val: ReceiptWithState) -> Self { - ReceivedReceipt::Failed(val) - } -} - -impl From> for ReceivedReceipt { - fn from(val: ReceiptWithState) -> Self { - ReceivedReceipt::Reserved(val) - } -} - -impl From> for CategorizedReceiptsWithState { - fn from(value: Vec) -> Self { - let mut awaiting_reserve_receipts = Vec::new(); - let mut checking_receipts = Vec::new(); - let mut failed_receipts = Vec::new(); - let mut reserved_receipts = Vec::new(); - - for stored_receipt in value { - let StoredReceipt { - receipt_id, - receipt, - } = stored_receipt; - match receipt { - ReceivedReceipt::AwaitingReserve(checked) => { - awaiting_reserve_receipts.push(checked) - } - ReceivedReceipt::Checking(checking) => { - checking_receipts.push((receipt_id, checking).into()) - } - ReceivedReceipt::Failed(failed) => failed_receipts.push(failed), - ReceivedReceipt::Reserved(reserved) => reserved_receipts.push(reserved), - } - } - Self { - awaiting_reserve_receipts, - checking_receipts, - failed_receipts, - reserved_receipts, - } - } -} - -impl ReceivedReceipt { - /// Initialize a new received receipt with provided signed receipt, query id, and checks - pub fn new(signed_receipt: EIP712SignedMessage) -> Self { - let received_receipt = ReceiptWithState { - signed_receipt, - _state: Checking, - }; - received_receipt.into() - } - pub fn signed_receipt(&self) -> &EIP712SignedMessage { - match self { - ReceivedReceipt::AwaitingReserve(ReceiptWithState { signed_receipt, .. }) - | ReceivedReceipt::Checking(ReceiptWithState { signed_receipt, .. }) - | ReceivedReceipt::Failed(ReceiptWithState { signed_receipt, .. }) - | ReceivedReceipt::Reserved(ReceiptWithState { signed_receipt, .. }) => signed_receipt, - } - } -} - #[derive(Debug, Clone, Serialize, Deserialize)] /// Wrapper class for metadata and state of a received receipt pub struct ReceiptWithState @@ -197,6 +77,13 @@ impl ReceiptWithState { } impl ReceiptWithState { + pub fn new(signed_receipt: SignedReceipt) -> ReceiptWithState { + ReceiptWithState { + signed_receipt, + _state: Checking, + } + } + /// Completes a list of *incomplete* check and stores the result, if the check already has a result it is skipped /// /// Returns `Err` only if unable to complete a check, returns `Ok` if the checks were completed (*Important:* this is not the result of the check, just the result of _completing_ the check) diff --git a/tap_core/tests/common/mock.rs b/tap_core/tests/common/mock.rs index d131389d..e582ee93 100644 --- a/tap_core/tests/common/mock.rs +++ b/tap_core/tests/common/mock.rs @@ -6,16 +6,15 @@ use async_trait::async_trait; use std::ops::RangeBounds; use std::sync::RwLock; use std::{collections::HashMap, sync::Arc}; +use tap_core::receipt::{Checking, ReceiptWithState}; use tap_core::{ - manager::strategy::*, - rav::SignedRAV, - receipt::{checks::TimestampCheck, ReceivedReceipt}, + manager::strategy::*, rav::SignedRAV, receipt::checks::TimestampCheck, signed_message::MessageId, }; pub type EscrowStorage = Arc>>; pub type QueryAppraisals = Arc>>; -pub type ReceiptStorage = Arc>>; +pub type ReceiptStorage = Arc>>>; pub type RAVStorage = Arc>>; use thiserror::Error; @@ -62,7 +61,7 @@ impl ExecutorMock { pub async fn retrieve_receipt_by_id( &self, receipt_id: u64, - ) -> Result { + ) -> Result, AdapterErrorMock> { let receipt_storage = self.receipt_storage.read().unwrap(); receipt_storage @@ -76,7 +75,7 @@ impl ExecutorMock { pub async fn retrieve_receipts_by_timestamp( &self, timestamp_ns: u64, - ) -> Result, AdapterErrorMock> { + ) -> Result)>, AdapterErrorMock> { let receipt_storage = self.receipt_storage.read().unwrap(); Ok(receipt_storage .iter() @@ -90,7 +89,7 @@ impl ExecutorMock { pub async fn retrieve_receipts_upto_timestamp( &self, timestamp_ns: u64, - ) -> Result, AdapterErrorMock> { + ) -> Result>, AdapterErrorMock> { self.retrieve_receipts_in_timestamp_range(..=timestamp_ns, None) .await } @@ -141,7 +140,10 @@ impl RAVRead for ExecutorMock { impl ReceiptStore for ExecutorMock { type AdapterError = AdapterErrorMock; - async fn store_receipt(&self, receipt: ReceivedReceipt) -> Result { + async fn store_receipt( + &self, + receipt: ReceiptWithState, + ) -> Result { let mut id_pointer = self.unique_id.write().unwrap(); let id_previous = *id_pointer; let mut receipt_storage = self.receipt_storage.write().unwrap(); @@ -173,20 +175,20 @@ impl ReceiptRead for ExecutorMock { &self, timestamp_range_ns: R, limit: Option, - ) -> Result, Self::AdapterError> { + ) -> Result>, Self::AdapterError> { let receipt_storage = self.receipt_storage.read().unwrap(); - let mut receipts_in_range: Vec<(u64, ReceivedReceipt)> = receipt_storage + let mut receipts_in_range: Vec> = receipt_storage .iter() .filter(|(_, rx_receipt)| { timestamp_range_ns.contains(&rx_receipt.signed_receipt().message.timestamp_ns) }) - .map(|(&id, rx_receipt)| (id, rx_receipt.clone())) + .map(|(&_id, rx_receipt)| rx_receipt.clone()) .collect(); if limit.is_some_and(|limit| receipts_in_range.len() > limit as usize) { safe_truncate_receipts(&mut receipts_in_range, limit.unwrap()); } - Ok(receipts_in_range.into_iter().map(|r| r.into()).collect()) + Ok(receipts_in_range.into_iter().collect()) } } diff --git a/tap_core/tests/common/mod.rs b/tap_core/tests/common/mod.rs index 8c5a98a9..e4c7d877 100644 --- a/tap_core/tests/common/mod.rs +++ b/tap_core/tests/common/mod.rs @@ -2,4 +2,4 @@ mod mock; mod timestamp; pub use mock::*; - +pub use timestamp::get_current_timestamp_u64_ns; diff --git a/tap_core/tests/receipt_test.rs b/tap_core/tests/receipt_test.rs index 979a7360..2b1be662 100644 --- a/tap_core/tests/receipt_test.rs +++ b/tap_core/tests/receipt_test.rs @@ -5,6 +5,7 @@ use rand::thread_rng; use std::collections::HashMap; use std::str::FromStr; use std::sync::{Arc, RwLock}; +use tap_core::receipt::{Checking, ReceiptWithState}; mod common; @@ -16,9 +17,7 @@ use ethers::signers::{coins_bip39::English, LocalWallet, MnemonicBuilder}; use rstest::*; use tap_core::receipt::checks::TimestampCheck; use tap_core::{ - manager::strategy::ReceiptStore, - receipt::{Receipt, ReceivedReceipt}, - signed_message::EIP712SignedMessage, + manager::strategy::ReceiptStore, receipt::Receipt, signed_message::EIP712SignedMessage, tap_eip712_domain, }; @@ -54,7 +53,7 @@ async fn receipt_adapter_test(domain_separator: Eip712Domain, mut executor: Exec // Create receipts let value = 100u128; - let received_receipt = ReceivedReceipt::new( + let received_receipt = ReceiptWithState::new( EIP712SignedMessage::new( &domain_separator, Receipt::new(allocation_id, value).unwrap(), @@ -97,7 +96,7 @@ async fn multi_receipt_adapter_test(domain_separator: Eip712Domain, mut executor // Create receipts let mut received_receipts = Vec::new(); for value in 50..60 { - received_receipts.push(ReceivedReceipt::new( + received_receipts.push(ReceiptWithState::new( EIP712SignedMessage::new( &domain_separator, Receipt::new(allocation_id, value).unwrap(), @@ -173,25 +172,22 @@ fn safe_truncate_receipts_test( .unwrap(); // Vec of (id, receipt) - let mut receipts_orig: Vec<(u64, ReceivedReceipt)> = Vec::new(); + let mut receipts_orig: Vec> = Vec::new(); - for (i, timestamp) in input.iter().enumerate() { + for timestamp in input.iter() { // The contents of the receipt only need to be unique for this test (so we can check) - receipts_orig.push(( - i as u64, - ReceivedReceipt::new( - EIP712SignedMessage::new( - &domain_separator, - Receipt { - allocation_id: Address::ZERO, - timestamp_ns: *timestamp, - nonce: 0, - value: 0, - }, - &wallet, - ) - .unwrap(), - ), + receipts_orig.push(ReceiptWithState::new( + EIP712SignedMessage::new( + &domain_separator, + Receipt { + allocation_id: Address::ZERO, + timestamp_ns: *timestamp, + nonce: 0, + value: 0, + }, + &wallet, + ) + .unwrap(), )); } @@ -207,7 +203,7 @@ fn safe_truncate_receipts_test( for (elem_trun, expected_timestamp) in receipts_truncated.iter().zip(expected.iter()) { // Check timestamps assert_eq!( - elem_trun.1.signed_receipt().message.timestamp_ns, + elem_trun.signed_receipt().message.timestamp_ns, *expected_timestamp ); } diff --git a/tap_core/tests/received_receipt_test.rs b/tap_core/tests/received_receipt_test.rs index 97a481a5..87cb4866 100644 --- a/tap_core/tests/received_receipt_test.rs +++ b/tap_core/tests/received_receipt_test.rs @@ -17,7 +17,7 @@ use rstest::*; use tap_core::{ receipt::{ checks::{mock::get_full_list_of_checks, ReceiptCheck, TimestampCheck}, - Receipt, ReceivedReceipt, + Receipt, ReceiptWithState, }, signed_message::EIP712SignedMessage, tap_eip712_domain, @@ -104,28 +104,6 @@ fn executor_mock( } } -#[rstest] -#[tokio::test] -async fn initialization_valid_receipt( - keys: (LocalWallet, Address), - allocation_ids: Vec
, - domain_separator: Eip712Domain, -) { - let signed_receipt = EIP712SignedMessage::new( - &domain_separator, - Receipt::new(allocation_ids[0], 10).unwrap(), - &keys.0, - ) - .unwrap(); - - let received_receipt = ReceivedReceipt::new(signed_receipt); - - match received_receipt { - ReceivedReceipt::Checking(checking) => checking, - _ => panic!("ReceivedReceipt should be in Checking state"), - }; -} - #[rstest] #[tokio::test] async fn partial_then_full_check_valid_receipt( @@ -162,12 +140,7 @@ async fn partial_then_full_check_valid_receipt( .unwrap() .insert(query_id, query_value); - let received_receipt = ReceivedReceipt::new(signed_receipt); - - let mut received_receipt = match received_receipt { - ReceivedReceipt::Checking(checking) => checking, - _ => panic!("ReceivedReceipt should be in Checking state"), - }; + let mut received_receipt = ReceiptWithState::new(signed_receipt); let result = received_receipt.perform_checks(&checks).await; assert!(result.is_ok()); @@ -209,12 +182,7 @@ async fn partial_then_finalize_valid_receipt( .unwrap() .insert(query_id, query_value); - let received_receipt = ReceivedReceipt::new(signed_receipt); - - let received_receipt = match received_receipt { - ReceivedReceipt::Checking(checking) => checking, - _ => panic!("ReceivedReceipt should be in Checking state"), - }; + let received_receipt = ReceiptWithState::new(signed_receipt); let awaiting_escrow_receipt = received_receipt.finalize_receipt_checks(&checks).await; assert!(awaiting_escrow_receipt.is_ok()); @@ -263,12 +231,7 @@ async fn standard_lifetime_valid_receipt( .unwrap() .insert(query_id, query_value); - let received_receipt = ReceivedReceipt::new(signed_receipt); - - let received_receipt = match received_receipt { - ReceivedReceipt::Checking(checking) => checking, - _ => panic!("ReceivedReceipt should be in Checking state"), - }; + let received_receipt = ReceiptWithState::new(signed_receipt); let awaiting_escrow_receipt = received_receipt.finalize_receipt_checks(&checks).await; assert!(awaiting_escrow_receipt.is_ok()); From 070e6d54c2d2d5a8a2f35393027138eb0134032e Mon Sep 17 00:00:00 2001 From: Gustavo Inacio Date: Sun, 10 Mar 2024 12:07:00 -0300 Subject: [PATCH 03/11] refactor: add in_memory context Signed-off-by: Gustavo Inacio --- tap_core/Cargo.toml | 4 +- .../mock.rs => src/manager/context/memory.rs} | 124 +++++++++++++++++- tap_core/src/manager/context/mod.rs | 1 + tap_core/src/manager/mod.rs | 12 +- .../manager/{manager.rs => tap_manager.rs} | 0 tap_core/src/receipt/checks.rs | 104 --------------- tap_core/src/receipt/mod.rs | 4 +- .../receipt/{receipt.rs => receipt_sol.rs} | 0 tap_core/tests/common/mod.rs | 5 - tap_core/tests/common/timestamp.rs | 12 -- tap_core/tests/escrow_test.rs | 9 +- tap_core/tests/manager_test.rs | 17 ++- tap_core/tests/rav_test.rs | 5 +- tap_core/tests/receipt_test.rs | 5 +- tap_core/tests/received_receipt_test.rs | 8 +- tap_integration_tests/Cargo.toml | 2 +- .../tests/indexer_mock.rs | 0 tap_integration_tests/tests/lib.rs | 6 +- .../tests/showcase.rs | 7 +- 19 files changed, 157 insertions(+), 168 deletions(-) rename tap_core/{tests/common/mock.rs => src/manager/context/memory.rs} (69%) create mode 100644 tap_core/src/manager/context/mod.rs rename tap_core/src/manager/{manager.rs => tap_manager.rs} (100%) rename tap_core/src/receipt/{receipt.rs => receipt_sol.rs} (100%) delete mode 100644 tap_core/tests/common/mod.rs delete mode 100644 tap_core/tests/common/timestamp.rs rename tap_core/tests/indexer_mock/mod.rs => tap_integration_tests/tests/indexer_mock.rs (100%) rename {tap_core => tap_integration_tests}/tests/showcase.rs (99%) diff --git a/tap_core/Cargo.toml b/tap_core/Cargo.toml index 49adc624..1b2dce41 100644 --- a/tap_core/Cargo.toml +++ b/tap_core/Cargo.toml @@ -32,8 +32,8 @@ jsonrpsee = { version = "0.18.0", features = ["http-client", "server"] } [features] -default = ["mock"] -mock = [] +default = ["in_memory"] +in_memory = [] [[bench]] name = 'timeline_aggretion_protocol_benchmark' diff --git a/tap_core/tests/common/mock.rs b/tap_core/src/manager/context/memory.rs similarity index 69% rename from tap_core/tests/common/mock.rs rename to tap_core/src/manager/context/memory.rs index e582ee93..5894d2b8 100644 --- a/tap_core/tests/common/mock.rs +++ b/tap_core/src/manager/context/memory.rs @@ -1,16 +1,17 @@ // Copyright 2023-, Semiotic AI, Inc. // SPDX-License-Identifier: Apache-2.0 +use crate::{ + manager::strategy::*, + rav::SignedRAV, + receipt::{checks::TimestampCheck, Checking, ReceiptWithState}, + signed_message::MessageId, +}; use alloy_primitives::Address; use async_trait::async_trait; use std::ops::RangeBounds; use std::sync::RwLock; use std::{collections::HashMap, sync::Arc}; -use tap_core::receipt::{Checking, ReceiptWithState}; -use tap_core::{ - manager::strategy::*, rav::SignedRAV, receipt::checks::TimestampCheck, - signed_message::MessageId, -}; pub type EscrowStorage = Arc>>; pub type QueryAppraisals = Arc>>; @@ -251,3 +252,116 @@ impl EscrowHandler for ExecutorMock { .unwrap_or(false)) } } + +pub mod checks { + use crate::{ + receipt::{ + checks::{Check, CheckResult, ReceiptCheck}, + Checking, ReceiptError, ReceiptWithState, + }, + signed_message::MessageId, + }; + use alloy_primitives::Address; + use alloy_sol_types::Eip712Domain; + use std::{ + collections::{HashMap, HashSet}, + sync::{Arc, RwLock}, + }; + + pub fn get_full_list_of_checks( + domain_separator: Eip712Domain, + valid_signers: HashSet
, + allocation_ids: Arc>>, + _query_appraisals: Arc>>, + ) -> Vec { + vec![ + // Arc::new(UniqueCheck ), + // Arc::new(ValueCheck { query_appraisals }), + Arc::new(AllocationIdCheck { allocation_ids }), + Arc::new(SignatureCheck { + domain_separator, + valid_signers, + }), + ] + } + + struct ValueCheck { + query_appraisals: Arc>>, + } + + #[async_trait::async_trait] + impl Check for ValueCheck { + async fn check(&self, receipt: &ReceiptWithState) -> CheckResult { + let value = receipt.signed_receipt().message.value; + let query_appraisals = self.query_appraisals.read().unwrap(); + let hash = receipt.signed_receipt().unique_hash(); + let appraised_value = + query_appraisals + .get(&hash) + .ok_or(ReceiptError::CheckFailedToComplete( + "Could not find query_appraisals".into(), + ))?; + + if value != *appraised_value { + Err(ReceiptError::InvalidValue { + received_value: value, + } + .into()) + } else { + Ok(()) + } + } + } + + struct AllocationIdCheck { + allocation_ids: Arc>>, + } + + #[async_trait::async_trait] + impl Check for AllocationIdCheck { + async fn check(&self, receipt: &ReceiptWithState) -> CheckResult { + let received_allocation_id = receipt.signed_receipt().message.allocation_id; + if self + .allocation_ids + .read() + .unwrap() + .contains(&received_allocation_id) + { + Ok(()) + } else { + Err(ReceiptError::InvalidAllocationID { + received_allocation_id, + } + .into()) + } + } + } + + struct SignatureCheck { + domain_separator: Eip712Domain, + valid_signers: HashSet
, + } + + #[async_trait::async_trait] + impl Check for SignatureCheck { + async fn check(&self, receipt: &ReceiptWithState) -> CheckResult { + let recovered_address = receipt + .signed_receipt() + .recover_signer(&self.domain_separator) + .map_err(|e| ReceiptError::InvalidSignature { + source_error_message: e.to_string(), + })?; + if !self.valid_signers.contains(&recovered_address) { + Err(ReceiptError::InvalidSignature { + source_error_message: "Invalid signer".to_string(), + } + .into()) + } else { + Ok(()) + } + } + } +} + +#[cfg(test)] +mod tests {} diff --git a/tap_core/src/manager/context/mod.rs b/tap_core/src/manager/context/mod.rs new file mode 100644 index 00000000..eb291915 --- /dev/null +++ b/tap_core/src/manager/context/mod.rs @@ -0,0 +1 @@ +pub mod memory; diff --git a/tap_core/src/manager/mod.rs b/tap_core/src/manager/mod.rs index fb72d263..c04d8683 100644 --- a/tap_core/src/manager/mod.rs +++ b/tap_core/src/manager/mod.rs @@ -10,13 +10,9 @@ //! The `Manager` uses user-defined adapters (see [crate::adapters]) for check and storage handling. //! This design offers a high degree of flexibility, letting the user define their own behavior for these critical operations. -mod manager; +#[cfg(feature = "in_memory")] +pub mod context; pub mod strategy; +mod tap_manager; -// #[cfg(test)] -// mod mock; -// -// #[cfg(test)] -// pub use mock::*; - -pub use manager::Manager; +pub use tap_manager::Manager; diff --git a/tap_core/src/manager/manager.rs b/tap_core/src/manager/tap_manager.rs similarity index 100% rename from tap_core/src/manager/manager.rs rename to tap_core/src/manager/tap_manager.rs diff --git a/tap_core/src/receipt/checks.rs b/tap_core/src/receipt/checks.rs index e13ff133..203297e5 100644 --- a/tap_core/src/receipt/checks.rs +++ b/tap_core/src/receipt/checks.rs @@ -134,107 +134,3 @@ impl CheckBatch for UniqueCheck { (checking, failed) } } - -#[cfg(feature = "mock")] -pub mod mock { - - use super::*; - use crate::signed_message::MessageId; - use alloy_primitives::Address; - use alloy_sol_types::Eip712Domain; - use std::collections::{HashMap, HashSet}; - - pub fn get_full_list_of_checks( - domain_separator: Eip712Domain, - valid_signers: HashSet
, - allocation_ids: Arc>>, - _query_appraisals: Arc>>, - ) -> Vec { - vec![ - // Arc::new(UniqueCheck ), - // Arc::new(ValueCheck { query_appraisals }), - Arc::new(AllocationIdCheck { allocation_ids }), - Arc::new(SignatureCheck { - domain_separator, - valid_signers, - }), - ] - } - - struct ValueCheck { - query_appraisals: Arc>>, - } - - #[async_trait::async_trait] - impl Check for ValueCheck { - async fn check(&self, receipt: &ReceiptWithState) -> CheckResult { - let value = receipt.signed_receipt().message.value; - let query_appraisals = self.query_appraisals.read().unwrap(); - let hash = receipt.signed_receipt().unique_hash(); - let appraised_value = - query_appraisals - .get(&hash) - .ok_or(ReceiptError::CheckFailedToComplete( - "Could not find query_appraisals".into(), - ))?; - - if value != *appraised_value { - Err(ReceiptError::InvalidValue { - received_value: value, - } - .into()) - } else { - Ok(()) - } - } - } - - struct AllocationIdCheck { - allocation_ids: Arc>>, - } - - #[async_trait::async_trait] - impl Check for AllocationIdCheck { - async fn check(&self, receipt: &ReceiptWithState) -> CheckResult { - let received_allocation_id = receipt.signed_receipt().message.allocation_id; - if self - .allocation_ids - .read() - .unwrap() - .contains(&received_allocation_id) - { - Ok(()) - } else { - Err(ReceiptError::InvalidAllocationID { - received_allocation_id, - } - .into()) - } - } - } - - struct SignatureCheck { - domain_separator: Eip712Domain, - valid_signers: HashSet
, - } - - #[async_trait::async_trait] - impl Check for SignatureCheck { - async fn check(&self, receipt: &ReceiptWithState) -> CheckResult { - let recovered_address = receipt - .signed_receipt() - .recover_signer(&self.domain_separator) - .map_err(|e| ReceiptError::InvalidSignature { - source_error_message: e.to_string(), - })?; - if !self.valid_signers.contains(&recovered_address) { - Err(ReceiptError::InvalidSignature { - source_error_message: "Invalid signer".to_string(), - } - .into()) - } else { - Ok(()) - } - } - } -} diff --git a/tap_core/src/receipt/mod.rs b/tap_core/src/receipt/mod.rs index ca676e96..c71dea71 100644 --- a/tap_core/src/receipt/mod.rs +++ b/tap_core/src/receipt/mod.rs @@ -3,11 +3,11 @@ pub mod checks; mod error; -mod receipt; +mod receipt_sol; mod received_receipt; pub use error::ReceiptError; -pub use receipt::Receipt; +pub use receipt_sol::Receipt; pub use received_receipt::{ AwaitingReserve, Checking, Failed, ReceiptState, ReceiptWithState, Reserved, ResultReceipt, }; diff --git a/tap_core/src/receipt/receipt.rs b/tap_core/src/receipt/receipt_sol.rs similarity index 100% rename from tap_core/src/receipt/receipt.rs rename to tap_core/src/receipt/receipt_sol.rs diff --git a/tap_core/tests/common/mod.rs b/tap_core/tests/common/mod.rs deleted file mode 100644 index e4c7d877..00000000 --- a/tap_core/tests/common/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -mod mock; -mod timestamp; - -pub use mock::*; -pub use timestamp::get_current_timestamp_u64_ns; diff --git a/tap_core/tests/common/timestamp.rs b/tap_core/tests/common/timestamp.rs deleted file mode 100644 index 8770e91e..00000000 --- a/tap_core/tests/common/timestamp.rs +++ /dev/null @@ -1,12 +0,0 @@ -use std::time::{SystemTime, UNIX_EPOCH}; - -use tap_core::Error; - -pub fn get_current_timestamp_u64_ns() -> anyhow::Result { - Ok(SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_err(|err| Error::InvalidSystemTime { - source_error_message: err.to_string(), - })? - .as_nanos() as u64) -} diff --git a/tap_core/tests/escrow_test.rs b/tap_core/tests/escrow_test.rs index be439e25..09bd0227 100644 --- a/tap_core/tests/escrow_test.rs +++ b/tap_core/tests/escrow_test.rs @@ -9,11 +9,10 @@ use std::{ use ethers::signers::{coins_bip39::English, LocalWallet, MnemonicBuilder, Signer}; use rstest::*; -mod common; - -use common::ExecutorMock; - -use tap_core::{manager::strategy::EscrowHandler, receipt::checks::TimestampCheck}; +use tap_core::{ + manager::{context::memory::ExecutorMock, strategy::EscrowHandler}, + receipt::checks::TimestampCheck, +}; #[fixture] fn executor() -> ExecutorMock { diff --git a/tap_core/tests/manager_test.rs b/tap_core/tests/manager_test.rs index 5c067425..176baa1a 100644 --- a/tap_core/tests/manager_test.rs +++ b/tap_core/tests/manager_test.rs @@ -4,6 +4,7 @@ use std::{ collections::HashMap, str::FromStr, sync::{Arc, RwLock}, + time::{SystemTime, UNIX_EPOCH}, }; use alloy_primitives::Address; @@ -11,14 +12,20 @@ use alloy_sol_types::Eip712Domain; use ethers::signers::{coins_bip39::English, LocalWallet, MnemonicBuilder, Signer}; use rstest::*; -mod common; - -use common::{get_current_timestamp_u64_ns, EscrowStorage, ExecutorMock, QueryAppraisals}; +fn get_current_timestamp_u64_ns() -> anyhow::Result { + Ok(SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos() as u64) +} use tap_core::{ - manager::{strategy::ReceiptRead, Manager}, + manager::{ + context::memory::{ + checks::get_full_list_of_checks, EscrowStorage, ExecutorMock, QueryAppraisals, + }, + strategy::ReceiptRead, + Manager, + }, receipt::{ - checks::{mock::get_full_list_of_checks, Checks, TimestampCheck}, + checks::{Checks, TimestampCheck}, Receipt, }, signed_message::EIP712SignedMessage, diff --git a/tap_core/tests/rav_test.rs b/tap_core/tests/rav_test.rs index e0e0828f..018cdb77 100644 --- a/tap_core/tests/rav_test.rs +++ b/tap_core/tests/rav_test.rs @@ -11,10 +11,7 @@ use ethers::signers::coins_bip39::English; use ethers::signers::{LocalWallet, MnemonicBuilder}; use rstest::*; -mod common; - -use common::ExecutorMock; - +use tap_core::manager::context::memory::ExecutorMock; use tap_core::{ manager::strategy::{RAVRead, RAVStore}, rav::ReceiptAggregateVoucher, diff --git a/tap_core/tests/receipt_test.rs b/tap_core/tests/receipt_test.rs index 2b1be662..ec33b19f 100644 --- a/tap_core/tests/receipt_test.rs +++ b/tap_core/tests/receipt_test.rs @@ -5,12 +5,9 @@ use rand::thread_rng; use std::collections::HashMap; use std::str::FromStr; use std::sync::{Arc, RwLock}; +use tap_core::manager::context::memory::ExecutorMock; use tap_core::receipt::{Checking, ReceiptWithState}; -mod common; - -use common::ExecutorMock; - use alloy_primitives::Address; use alloy_sol_types::Eip712Domain; use ethers::signers::{coins_bip39::English, LocalWallet, MnemonicBuilder}; diff --git a/tap_core/tests/received_receipt_test.rs b/tap_core/tests/received_receipt_test.rs index 87cb4866..516d9cdb 100644 --- a/tap_core/tests/received_receipt_test.rs +++ b/tap_core/tests/received_receipt_test.rs @@ -1,9 +1,6 @@ // Copyright 2023-, Semiotic AI, Inc. // SPDX-License-Identifier: Apache-2.0 -mod common; - -use common::{EscrowStorage, ExecutorMock, QueryAppraisals}; use std::{ collections::HashMap, str::FromStr, @@ -15,8 +12,11 @@ use alloy_sol_types::Eip712Domain; use ethers::signers::{coins_bip39::English, LocalWallet, MnemonicBuilder, Signer}; use rstest::*; use tap_core::{ + manager::context::memory::{ + checks::get_full_list_of_checks, EscrowStorage, ExecutorMock, QueryAppraisals, + }, receipt::{ - checks::{mock::get_full_list_of_checks, ReceiptCheck, TimestampCheck}, + checks::{ReceiptCheck, TimestampCheck}, Receipt, ReceiptWithState, }, signed_message::EIP712SignedMessage, diff --git a/tap_integration_tests/Cargo.toml b/tap_integration_tests/Cargo.toml index fc2a20e9..8d61345e 100644 --- a/tap_integration_tests/Cargo.toml +++ b/tap_integration_tests/Cargo.toml @@ -9,7 +9,7 @@ publish = false [dependencies] tap_aggregator = { version = "0.2.0", path = "../tap_aggregator" } -tap_core = { version = "0.7.0", path = "../tap_core" } +tap_core = { version = "0.7.0", path = "../tap_core", features = ["in_memory"]} jsonrpsee = { version = "0.18.0", features = ["http-client", "server"] } ethers = "2.0.0" clap = { version = "4.2.4", features = ["derive", "env"] } diff --git a/tap_core/tests/indexer_mock/mod.rs b/tap_integration_tests/tests/indexer_mock.rs similarity index 100% rename from tap_core/tests/indexer_mock/mod.rs rename to tap_integration_tests/tests/indexer_mock.rs diff --git a/tap_integration_tests/tests/lib.rs b/tap_integration_tests/tests/lib.rs index 846ba270..1d207758 100644 --- a/tap_integration_tests/tests/lib.rs +++ b/tap_integration_tests/tests/lib.rs @@ -1,5 +1,5 @@ // Copyright 2023-, Semiotic AI, Inc. // SPDX-License-Identifier: Apache-2.0 -// -// mod indexer_mock; -// mod showcase; + +mod indexer_mock; +mod showcase; diff --git a/tap_core/tests/showcase.rs b/tap_integration_tests/tests/showcase.rs similarity index 99% rename from tap_core/tests/showcase.rs rename to tap_integration_tests/tests/showcase.rs index 86b47c60..10cf1ec9 100644 --- a/tap_core/tests/showcase.rs +++ b/tap_integration_tests/tests/showcase.rs @@ -22,20 +22,19 @@ use jsonrpsee::{ use rand::{rngs::StdRng, Rng, SeedableRng}; use rstest::*; -use common::{ExecutorMock, QueryAppraisals}; use tap_aggregator::{jsonrpsee_helpers, server as agg_server}; use tap_core::{ + manager::context::memory::{checks::get_full_list_of_checks, *}, rav::SignedRAV, receipt::{ - checks::{mock::get_full_list_of_checks, Checks, TimestampCheck}, + checks::{Checks, TimestampCheck}, Receipt, }, signed_message::{EIP712SignedMessage, MessageId}, tap_eip712_domain, }; -mod common; -mod indexer_mock; +use crate::indexer_mock; // Fixtures for sender aggregator server #[fixture] From 9dbd9db478e0058d53b840aa2d14adc404780763 Mon Sep 17 00:00:00 2001 From: Gustavo Inacio Date: Sun, 10 Mar 2024 12:15:29 -0300 Subject: [PATCH 04/11] refactor: rename structs ExecutorMock -> InMemoryContext adapters -> strategy Signed-off-by: Gustavo Inacio --- tap_core/src/error.rs | 4 +- tap_core/src/manager/context/memory.rs | 74 ++++++++++----------- tap_core/src/manager/strategy/escrow.rs | 18 ++--- tap_core/src/manager/strategy/rav.rs | 20 +++--- tap_core/src/manager/strategy/receipt.rs | 28 ++++---- tap_core/src/manager/tap_manager.rs | 20 +++--- tap_core/tests/escrow_test.rs | 24 +++---- tap_core/tests/manager_test.rs | 58 ++++++++-------- tap_core/tests/rav_test.rs | 16 ++--- tap_core/tests/receipt_test.rs | 40 +++++------ tap_core/tests/received_receipt_test.rs | 42 ++++++------ tap_integration_tests/tests/indexer_mock.rs | 8 +-- tap_integration_tests/tests/showcase.rs | 62 ++++++++--------- 13 files changed, 207 insertions(+), 207 deletions(-) diff --git a/tap_core/src/error.rs b/tap_core/src/error.rs index d489076f..6e411cba 100644 --- a/tap_core/src/error.rs +++ b/tap_core/src/error.rs @@ -36,8 +36,8 @@ pub enum Error { received_rav: ReceiptAggregateVoucher, expected_rav: ReceiptAggregateVoucher, }, - #[error("Error from adapter.\n Caused by: {source_error}")] - AdapterError { source_error: anyhow::Error }, + #[error("Error from strategy.\n Caused by: {source_error}")] + StrategyError { source_error: anyhow::Error }, #[error("Failed to produce rav request, no valid receipts")] NoValidReceiptsForRAVRequest, #[error("Previous RAV allocation id ({prev_id}) doesn't match the allocation id from the new receipt ({new_id}).")] diff --git a/tap_core/src/manager/context/memory.rs b/tap_core/src/manager/context/memory.rs index 5894d2b8..b804f4da 100644 --- a/tap_core/src/manager/context/memory.rs +++ b/tap_core/src/manager/context/memory.rs @@ -21,13 +21,13 @@ pub type RAVStorage = Arc>>; use thiserror::Error; #[derive(Debug, Error)] -pub enum AdapterErrorMock { +pub enum InMemoryError { #[error("something went wrong: {error}")] - AdapterError { error: String }, + StrategyError { error: String }, } #[derive(Clone)] -pub struct ExecutorMock { +pub struct InMemoryContext { /// local RAV store with rwlocks to allow sharing with other compenents as needed rav_storage: RAVStorage, receipt_storage: ReceiptStorage, @@ -37,14 +37,14 @@ pub struct ExecutorMock { sender_address: Option
, } -impl ExecutorMock { +impl InMemoryContext { pub fn new( rav_storage: RAVStorage, receipt_storage: ReceiptStorage, sender_escrow_storage: EscrowStorage, timestamp_check: Arc, ) -> Self { - ExecutorMock { + InMemoryContext { rav_storage, receipt_storage, unique_id: Arc::new(RwLock::new(0)), @@ -62,13 +62,13 @@ impl ExecutorMock { pub async fn retrieve_receipt_by_id( &self, receipt_id: u64, - ) -> Result, AdapterErrorMock> { + ) -> Result, InMemoryError> { let receipt_storage = self.receipt_storage.read().unwrap(); receipt_storage .get(&receipt_id) .cloned() - .ok_or(AdapterErrorMock::AdapterError { + .ok_or(InMemoryError::StrategyError { error: "No receipt found with ID".to_owned(), }) } @@ -76,7 +76,7 @@ impl ExecutorMock { pub async fn retrieve_receipts_by_timestamp( &self, timestamp_ns: u64, - ) -> Result)>, AdapterErrorMock> { + ) -> Result)>, InMemoryError> { let receipt_storage = self.receipt_storage.read().unwrap(); Ok(receipt_storage .iter() @@ -90,24 +90,24 @@ impl ExecutorMock { pub async fn retrieve_receipts_upto_timestamp( &self, timestamp_ns: u64, - ) -> Result>, AdapterErrorMock> { + ) -> Result>, InMemoryError> { self.retrieve_receipts_in_timestamp_range(..=timestamp_ns, None) .await } - pub async fn remove_receipt_by_id(&mut self, receipt_id: u64) -> Result<(), AdapterErrorMock> { + pub async fn remove_receipt_by_id(&mut self, receipt_id: u64) -> Result<(), InMemoryError> { let mut receipt_storage = self.receipt_storage.write().unwrap(); receipt_storage .remove(&receipt_id) .map(|_| ()) - .ok_or(AdapterErrorMock::AdapterError { + .ok_or(InMemoryError::StrategyError { error: "No receipt found with ID".to_owned(), }) } pub async fn remove_receipts_by_ids( &mut self, receipt_ids: &[u64], - ) -> Result<(), AdapterErrorMock> { + ) -> Result<(), InMemoryError> { for receipt_id in receipt_ids { self.remove_receipt_by_id(*receipt_id).await?; } @@ -116,10 +116,10 @@ impl ExecutorMock { } #[async_trait] -impl RAVStore for ExecutorMock { - type AdapterError = AdapterErrorMock; +impl RAVStore for InMemoryContext { + type StrategyError = InMemoryError; - async fn update_last_rav(&self, rav: SignedRAV) -> Result<(), Self::AdapterError> { + async fn update_last_rav(&self, rav: SignedRAV) -> Result<(), Self::StrategyError> { let mut rav_storage = self.rav_storage.write().unwrap(); let timestamp = rav.message.timestampNs; *rav_storage = Some(rav); @@ -129,22 +129,22 @@ impl RAVStore for ExecutorMock { } #[async_trait] -impl RAVRead for ExecutorMock { - type AdapterError = AdapterErrorMock; +impl RAVRead for InMemoryContext { + type StrategyError = InMemoryError; - async fn last_rav(&self) -> Result, Self::AdapterError> { + async fn last_rav(&self) -> Result, Self::StrategyError> { Ok(self.rav_storage.read().unwrap().clone()) } } #[async_trait] -impl ReceiptStore for ExecutorMock { - type AdapterError = AdapterErrorMock; +impl ReceiptStore for InMemoryContext { + type StrategyError = InMemoryError; async fn store_receipt( &self, receipt: ReceiptWithState, - ) -> Result { + ) -> Result { let mut id_pointer = self.unique_id.write().unwrap(); let id_previous = *id_pointer; let mut receipt_storage = self.receipt_storage.write().unwrap(); @@ -155,13 +155,13 @@ impl ReceiptStore for ExecutorMock { } #[async_trait] -impl ReceiptDelete for ExecutorMock { - type AdapterError = AdapterErrorMock; +impl ReceiptDelete for InMemoryContext { + type StrategyError = InMemoryError; async fn remove_receipts_in_timestamp_range + std::marker::Send>( &self, timestamp_ns: R, - ) -> Result<(), Self::AdapterError> { + ) -> Result<(), Self::StrategyError> { let mut receipt_storage = self.receipt_storage.write().unwrap(); receipt_storage.retain(|_, rx_receipt| { !timestamp_ns.contains(&rx_receipt.signed_receipt().message.timestamp_ns) @@ -170,13 +170,13 @@ impl ReceiptDelete for ExecutorMock { } } #[async_trait] -impl ReceiptRead for ExecutorMock { - type AdapterError = AdapterErrorMock; +impl ReceiptRead for InMemoryContext { + type StrategyError = InMemoryError; async fn retrieve_receipts_in_timestamp_range + std::marker::Send>( &self, timestamp_range_ns: R, limit: Option, - ) -> Result>, Self::AdapterError> { + ) -> Result>, Self::StrategyError> { let receipt_storage = self.receipt_storage.read().unwrap(); let mut receipts_in_range: Vec> = receipt_storage .iter() @@ -193,13 +193,13 @@ impl ReceiptRead for ExecutorMock { } } -impl ExecutorMock { - pub fn escrow(&self, sender_id: Address) -> Result { +impl InMemoryContext { + pub fn escrow(&self, sender_id: Address) -> Result { let sender_escrow_storage = self.sender_escrow_storage.read().unwrap(); if let Some(escrow) = sender_escrow_storage.get(&sender_id) { return Ok(*escrow); } - Err(AdapterErrorMock::AdapterError { + Err(InMemoryError::StrategyError { error: "No escrow exists for provided sender ID.".to_owned(), }) } @@ -215,7 +215,7 @@ impl ExecutorMock { } } - pub fn reduce_escrow(&self, sender_id: Address, value: u128) -> Result<(), AdapterErrorMock> { + pub fn reduce_escrow(&self, sender_id: Address, value: u128) -> Result<(), InMemoryError> { let mut sender_escrow_storage = self.sender_escrow_storage.write().unwrap(); if let Some(current_value) = sender_escrow_storage.get(&sender_id) { @@ -225,27 +225,27 @@ impl ExecutorMock { return Ok(()); } } - Err(AdapterErrorMock::AdapterError { + Err(InMemoryError::StrategyError { error: "Provided value is greater than existing escrow.".to_owned(), }) } } #[async_trait] -impl EscrowHandler for ExecutorMock { - type AdapterError = AdapterErrorMock; - async fn get_available_escrow(&self, sender_id: Address) -> Result { +impl EscrowHandler for InMemoryContext { + type StrategyError = InMemoryError; + async fn get_available_escrow(&self, sender_id: Address) -> Result { self.escrow(sender_id) } async fn subtract_escrow( &self, sender_id: Address, value: u128, - ) -> Result<(), Self::AdapterError> { + ) -> Result<(), Self::StrategyError> { self.reduce_escrow(sender_id, value) } - async fn verify_signer(&self, signer_address: Address) -> Result { + async fn verify_signer(&self, signer_address: Address) -> Result { Ok(self .sender_address .map(|sender| signer_address == sender) diff --git a/tap_core/src/manager/strategy/escrow.rs b/tap_core/src/manager/strategy/escrow.rs index 93760995..a361f6d8 100644 --- a/tap_core/src/manager/strategy/escrow.rs +++ b/tap_core/src/manager/strategy/escrow.rs @@ -15,18 +15,18 @@ use crate::{ /// /// This trait is designed to be implemented by users of this library who want to /// customize the management of local accounting for available escrow. The error handling is also -/// customizable by defining an `AdapterError` type, which must implement both `Error` +/// customizable by defining an `StrategyError` type, which must implement both `Error` /// and `Debug` from the standard library. /// /// # Usage /// /// The `get_available_escrow` method should be used to retrieve the local accounting /// amount of available escrow for a specified sender. Any errors during this operation -/// should be captured and returned in the `AdapterError` format. +/// should be captured and returned in the `StrategyError` format. /// /// The `subtract_escrow` method is used to deduct a specified value from the local accounting /// of available escrow of a specified sender. Any errors during this operation should be captured -/// and returned as an `AdapterError`. +/// and returned as an `StrategyError`. /// /// This trait is utilized by [crate::tap_manager], which relies on these /// operations for managing escrow. @@ -41,27 +41,27 @@ pub trait EscrowHandler: Send + Sync { /// /// This error type should implement the `Error` and `Debug` traits from the standard library. /// Errors of this type are returned to the user when an operation fails. - type AdapterError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; + type StrategyError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; /// Retrieves the local accounting amount of available escrow for a specified sender. /// /// This method should be implemented to fetch the local accounting amount of available escrow for a /// specified sender from your system. Any errors that occur during this process should - /// be captured and returned as an `AdapterError`. - async fn get_available_escrow(&self, sender_id: Address) -> Result; + /// be captured and returned as an `StrategyError`. + async fn get_available_escrow(&self, sender_id: Address) -> Result; /// Deducts a specified value from the local accounting of available escrow for a specified sender. /// /// This method should be implemented to deduct a specified value from the local accounting of /// available escrow of a specified sender in your system. Any errors that occur during this - /// process should be captured and returned as an `AdapterError`. + /// process should be captured and returned as an `StrategyError`. async fn subtract_escrow( &self, sender_id: Address, value: u128, - ) -> Result<(), Self::AdapterError>; + ) -> Result<(), Self::StrategyError>; - async fn verify_signer(&self, signer_address: Address) -> Result; + async fn verify_signer(&self, signer_address: Address) -> Result; async fn check_and_reserve_escrow( &self, diff --git a/tap_core/src/manager/strategy/rav.rs b/tap_core/src/manager/strategy/rav.rs index f55a6dfe..1077bafb 100644 --- a/tap_core/src/manager/strategy/rav.rs +++ b/tap_core/src/manager/strategy/rav.rs @@ -9,14 +9,14 @@ use crate::rav::SignedRAV; /// /// This trait is designed to be implemented by users of this library who want to /// customize the write storage behavior of `SignedRAV` data. The error handling is also -/// customizable by defining an `AdapterError` type, which must implement both `Error` +/// customizable by defining an `StrategyError` type, which must implement both `Error` /// and `Debug` from the standard library. /// /// # Usage /// /// The `update_last_rav` method should be used to update the last validated `SignedRAV` /// in the storage managed by the adapter. Errors during this operation should be -/// captured and returned in the `AdapterError` format. +/// captured and returned in the `StrategyError` format. /// /// This trait is utilized by [crate::tap_manager], which relies on these /// operations for working with `SignedRAV` data. @@ -31,27 +31,27 @@ pub trait RAVStore { /// /// This error type should implement the `Error` and `Debug` traits from the standard library. /// Errors of this type are returned to the user when an operation fails. - type AdapterError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; + type StrategyError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; /// Updates the storage with the latest validated `SignedRAV`. /// /// This method should be implemented to store the most recent validated `SignedRAV` into your chosen storage system. - /// Any errors that occur during this process should be captured and returned as an `AdapterError`. - async fn update_last_rav(&self, rav: SignedRAV) -> Result<(), Self::AdapterError>; + /// Any errors that occur during this process should be captured and returned as an `StrategyError`. + async fn update_last_rav(&self, rav: SignedRAV) -> Result<(), Self::StrategyError>; } /// `RAVRead` defines a trait for read storage adapters to handle `SignedRAV` data. /// /// This trait is designed to be implemented by users of this library who want to /// customize the read storage behavior of `SignedRAV` data. The error handling is also -/// customizable by defining an `AdapterError` type, which must implement both `Error` +/// customizable by defining an `StrategyError` type, which must implement both `Error` /// and `Debug` from the standard library. /// /// # Usage /// /// The `last_rav` method is designed to fetch the latest `SignedRAV` from the storage. /// If there is no `SignedRAV` available, it should return `None`. Any errors during -/// this operation should be captured and returned as an `AdapterError`. +/// this operation should be captured and returned as an `StrategyError`. /// /// This trait is utilized by [crate::tap_manager], which relies on these /// operations for working with `SignedRAV` data. @@ -66,12 +66,12 @@ pub trait RAVRead { /// /// This error type should implement the `Error` and `Debug` traits from the standard library. /// Errors of this type are returned to the user when an operation fails. - type AdapterError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; + type StrategyError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; /// Retrieves the latest `SignedRAV` from the storage. /// /// This method should be implemented to fetch the latest `SignedRAV` from your storage system. /// If no `SignedRAV` is available, this method should return `None`. - /// Any errors that occur during this process should be captured and returned as an `AdapterError`. - async fn last_rav(&self) -> Result, Self::AdapterError>; + /// Any errors that occur during this process should be captured and returned as an `StrategyError`. + async fn last_rav(&self) -> Result, Self::StrategyError>; } diff --git a/tap_core/src/manager/strategy/receipt.rs b/tap_core/src/manager/strategy/receipt.rs index 82bfd8e6..702ce6d1 100644 --- a/tap_core/src/manager/strategy/receipt.rs +++ b/tap_core/src/manager/strategy/receipt.rs @@ -11,20 +11,20 @@ use crate::receipt::{Checking, ReceiptState, ReceiptWithState}; /// /// This trait is designed to be implemented by users of this library who want to /// customize the write storage behavior of `ReceivedReceipt` data. The error handling is also -/// customizable by defining an `AdapterError` type, which must implement both `Error` +/// customizable by defining an `StrategyError` type, which must implement both `Error` /// and `Debug` from the standard library. /// /// # Usage /// /// The `store_receipt` method should be used to store a new `ReceivedReceipt` in the storage /// managed by the adapter. It returns a unique receipt_id associated with the stored receipt. -/// Any errors during this operation should be captured and returned in the `AdapterError` format. +/// Any errors during this operation should be captured and returned in the `StrategyError` format. /// /// The `update_receipt_by_id` method is designed to update a specific `ReceivedReceipt` identified by a unique -/// receipt_id. Any errors during this operation should be captured and returned as an `AdapterError`. +/// receipt_id. Any errors during this operation should be captured and returned as an `StrategyError`. /// /// The `remove_receipts_in_timestamp_range` method is used to remove all `ReceivedReceipts` within a specific -/// timestamp range from the storage. Any errors during this operation should be captured and returned as an `AdapterError`. +/// timestamp range from the storage. Any errors during this operation should be captured and returned as an `StrategyError`. /// /// This trait is utilized by [crate::tap_manager], which relies on these /// operations for working with `ReceivedReceipt` data. @@ -39,17 +39,17 @@ pub trait ReceiptStore { /// /// This error type should implement the `Error` and `Debug` traits from the standard library. /// Errors of this type are returned to the user when an operation fails. - type AdapterError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; + type StrategyError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; /// Stores a new `ReceivedReceipt` into the storage. /// /// This method should be implemented to store a new `ReceivedReceipt` into your chosen storage system. /// It returns a unique receipt_id associated with the stored receipt. Any errors that occur during - /// this process should be captured and returned as an `AdapterError`. + /// this process should be captured and returned as an `StrategyError`. async fn store_receipt( &self, receipt: ReceiptWithState, - ) -> Result; + ) -> Result; } #[async_trait] @@ -58,23 +58,23 @@ pub trait ReceiptDelete { /// /// This error type should implement the `Error` and `Debug` traits from the standard library. /// Errors of this type are returned to the user when an operation fails. - type AdapterError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; + type StrategyError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; /// Removes all `ReceivedReceipts` within a specific timestamp range from the storage. /// /// This method should be implemented to remove all `ReceivedReceipts` within a specific timestamp /// range from your storage system. Any errors that occur during this process should be captured and - /// returned as an `AdapterError`. + /// returned as an `StrategyError`. async fn remove_receipts_in_timestamp_range + std::marker::Send>( &self, timestamp_ns: R, - ) -> Result<(), Self::AdapterError>; + ) -> Result<(), Self::StrategyError>; } /// `ReceiptRead` defines a trait for read storage adapters to manage `ReceivedReceipt` data. /// /// This trait is designed to be implemented by users of this library who want to /// customize the read storage behavior of `ReceivedReceipt` data. The error handling is also -/// customizable by defining an `AdapterError` type, which must implement both `Error` +/// customizable by defining an `StrategyError` type, which must implement both `Error` /// and `Debug` from the standard library. /// /// # Usage @@ -88,7 +88,7 @@ pub trait ReceiptRead { /// /// This error type should implement the `Error` and `Debug` traits from the standard library. /// Errors of this type are returned to the user when an operation fails. - type AdapterError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; + type StrategyError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; /// Retrieves all `ReceivedReceipts` within a specific timestamp range. /// @@ -110,12 +110,12 @@ pub trait ReceiptRead { /// You can use the [`safe_truncate_receipts()`] function to help with this, but feel free to /// implement a more efficient solution for your situation if you can. /// - /// Any errors that occur during this process should be captured and returned as an `AdapterError`. + /// Any errors that occur during this process should be captured and returned as an `StrategyError`. async fn retrieve_receipts_in_timestamp_range + std::marker::Send>( &self, timestamp_range_ns: R, limit: Option, - ) -> Result>, Self::AdapterError>; + ) -> Result>, Self::StrategyError>; } /// See [`ReceiptStorageAdapter::retrieve_receipts_in_timestamp_range()`] for details. diff --git a/tap_core/src/manager/tap_manager.rs b/tap_core/src/manager/tap_manager.rs index 34fa42a0..cf1d7e5e 100644 --- a/tap_core/src/manager/tap_manager.rs +++ b/tap_core/src/manager/tap_manager.rs @@ -14,7 +14,7 @@ use crate::{ }; pub struct Manager { - /// Executor that implements adapters + /// Context that implements strategies context: E, /// Checks that must be completed for each receipt before being confirmed or denied for rav request @@ -47,7 +47,7 @@ where /// /// # Errors /// - /// Returns [`Error::AdapterError`] if there are any errors while storing RAV + /// Returns [`Error::StrategyError`] if there are any errors while storing RAV /// pub async fn verify_and_store_rav( &self, @@ -68,7 +68,7 @@ where self.context .update_last_rav(signed_rav) .await - .map_err(|err| Error::AdapterError { + .map_err(|err| Error::StrategyError { source_error: anyhow::Error::new(err), })?; @@ -85,7 +85,7 @@ where .context .last_rav() .await - .map_err(|err| Error::AdapterError { + .map_err(|err| Error::StrategyError { source_error: anyhow::Error::new(err), })?; Ok(previous_rav) @@ -120,7 +120,7 @@ where .context .retrieve_receipts_in_timestamp_range(min_timestamp_ns..max_timestamp_ns, limit) .await - .map_err(|err| Error::AdapterError { + .map_err(|err| Error::StrategyError { source_error: anyhow::Error::new(err), })?; @@ -169,7 +169,7 @@ where /// /// Returns [`Error::AggregateOverflow`] if any receipt value causes aggregate value to overflow while generating expected RAV /// - /// Returns [`Error::AdapterError`] if unable to fetch previous RAV or if unable to fetch previous receipts + /// Returns [`Error::StrategyError`] if unable to fetch previous RAV or if unable to fetch previous receipts /// /// Returns [`Error::TimestampRangeError`] if the max timestamp of the previous RAV is greater than the min timestamp. Caused by timestamp buffer being too large, or requests coming too soon. /// @@ -234,7 +234,7 @@ where /// /// # Errors /// - /// Returns [`Error::AdapterError`] if there are any errors while retrieving last RAV or removing receipts + /// Returns [`Error::StrategyError`] if there are any errors while retrieving last RAV or removing receipts /// pub async fn remove_obsolete_receipts(&self) -> Result<(), Error> { match self.get_previous_rav().await? { @@ -242,7 +242,7 @@ where self.context .remove_receipts_in_timestamp_range(..=last_rav.message.timestampNs) .await - .map_err(|err| Error::AdapterError { + .map_err(|err| Error::StrategyError { source_error: anyhow::Error::new(err), })?; Ok(()) @@ -261,7 +261,7 @@ where /// /// # Errors /// - /// Returns [`Error::AdapterError`] if there are any errors while storing receipts + /// Returns [`Error::StrategyError`] if there are any errors while storing receipts /// /// Returns [`Error::InvalidStateForRequestedAction`] if the checks requested in `initial_checks` cannot be comleted due to: All other checks must be complete before `CheckAndReserveEscrow` /// @@ -280,7 +280,7 @@ where self.context .store_receipt(received_receipt) .await - .map_err(|err| Error::AdapterError { + .map_err(|err| Error::StrategyError { source_error: anyhow::Error::new(err), })?; Ok(()) diff --git a/tap_core/tests/escrow_test.rs b/tap_core/tests/escrow_test.rs index 09bd0227..d7b649ce 100644 --- a/tap_core/tests/escrow_test.rs +++ b/tap_core/tests/escrow_test.rs @@ -10,18 +10,18 @@ use ethers::signers::{coins_bip39::English, LocalWallet, MnemonicBuilder, Signer use rstest::*; use tap_core::{ - manager::{context::memory::ExecutorMock, strategy::EscrowHandler}, + manager::{context::memory::InMemoryContext, strategy::EscrowHandler}, receipt::checks::TimestampCheck, }; #[fixture] -fn executor() -> ExecutorMock { +fn in_memory_context() -> InMemoryContext { let escrow_storage = Arc::new(RwLock::new(HashMap::new())); let rav_storage = Arc::new(RwLock::new(None)); let receipt_storage = Arc::new(RwLock::new(HashMap::new())); let timestamp_check = Arc::new(TimestampCheck::new(0)); - ExecutorMock::new( + InMemoryContext::new( rav_storage, receipt_storage.clone(), escrow_storage.clone(), @@ -31,7 +31,7 @@ fn executor() -> ExecutorMock { #[rstest] #[tokio::test] -async fn escrow_adapter_test(mut executor: ExecutorMock) { +async fn escrow_handler_test(mut in_memory_context: InMemoryContext) { let wallet: LocalWallet = MnemonicBuilder::::default() .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") .build() @@ -48,31 +48,31 @@ async fn escrow_adapter_test(mut executor: ExecutorMock) { let initial_value = 500u128; - executor.increase_escrow(sender_id, initial_value); + in_memory_context.increase_escrow(sender_id, initial_value); // Check that sender exists and has valid value through adapter - assert!(executor.get_available_escrow(sender_id).await.is_ok()); + assert!(in_memory_context.get_available_escrow(sender_id).await.is_ok()); assert_eq!( - executor.get_available_escrow(sender_id).await.unwrap(), + in_memory_context.get_available_escrow(sender_id).await.unwrap(), initial_value ); // Check that subtracting is valid for valid sender, and results in expected value - assert!(executor + assert!(in_memory_context .subtract_escrow(sender_id, initial_value) .await .is_ok()); - assert!(executor.get_available_escrow(sender_id).await.is_ok()); - assert_eq!(executor.get_available_escrow(sender_id).await.unwrap(), 0); + assert!(in_memory_context.get_available_escrow(sender_id).await.is_ok()); + assert_eq!(in_memory_context.get_available_escrow(sender_id).await.unwrap(), 0); // Check that subtracting to negative escrow results in err - assert!(executor + assert!(in_memory_context .subtract_escrow(sender_id, initial_value) .await .is_err()); // Check that accessing non initialized sender results in err - assert!(executor + assert!(in_memory_context .get_available_escrow(invalid_sender_id) .await .is_err()); diff --git a/tap_core/tests/manager_test.rs b/tap_core/tests/manager_test.rs index 176baa1a..cb65914f 100644 --- a/tap_core/tests/manager_test.rs +++ b/tap_core/tests/manager_test.rs @@ -19,7 +19,7 @@ fn get_current_timestamp_u64_ns() -> anyhow::Result { use tap_core::{ manager::{ context::memory::{ - checks::get_full_list_of_checks, EscrowStorage, ExecutorMock, QueryAppraisals, + checks::get_full_list_of_checks, EscrowStorage, InMemoryContext, QueryAppraisals, }, strategy::ReceiptRead, Manager, @@ -70,26 +70,26 @@ fn domain_separator() -> Eip712Domain { tap_eip712_domain(1, Address::from([0x11u8; 20])) } -struct ExecutorFixture { - executor: ExecutorMock, +struct ContextFixture { + in_memory_context: InMemoryContext, escrow_storage: EscrowStorage, query_appraisals: QueryAppraisals, checks: Checks, } #[fixture] -fn executor_mock( +fn in_memory_context( domain_separator: Eip712Domain, allocation_ids: Vec
, sender_ids: Vec
, keys: (LocalWallet, Address), -) -> ExecutorFixture { +) -> ContextFixture { let escrow_storage = Arc::new(RwLock::new(HashMap::new())); let rav_storage = Arc::new(RwLock::new(None)); let query_appraisals = Arc::new(RwLock::new(HashMap::new())); let receipt_storage = Arc::new(RwLock::new(HashMap::new())); let timestamp_check = Arc::new(TimestampCheck::new(0)); - let executor = ExecutorMock::new( + let in_memory_context = InMemoryContext::new( rav_storage, receipt_storage.clone(), escrow_storage.clone(), @@ -106,8 +106,8 @@ fn executor_mock( checks.push(timestamp_check); let checks = Checks::new(checks); - ExecutorFixture { - executor, + ContextFixture { + in_memory_context, escrow_storage, query_appraisals, checks, @@ -120,16 +120,16 @@ async fn manager_verify_and_store_varying_initial_checks( keys: (LocalWallet, Address), allocation_ids: Vec
, domain_separator: Eip712Domain, - executor_mock: ExecutorFixture, + in_memory_context: ContextFixture, ) { - let ExecutorFixture { - executor, + let ContextFixture { + in_memory_context, checks, query_appraisals, escrow_storage, .. - } = executor_mock; - let manager = Manager::new(domain_separator.clone(), executor, checks); + } = in_memory_context; + let manager = Manager::new(domain_separator.clone(), in_memory_context, checks); let value = 20u128; let signed_receipt = EIP712SignedMessage::new( @@ -154,16 +154,16 @@ async fn manager_create_rav_request_all_valid_receipts( keys: (LocalWallet, Address), allocation_ids: Vec
, domain_separator: Eip712Domain, - executor_mock: ExecutorFixture, + in_memory_context: ContextFixture, ) { - let ExecutorFixture { - executor, + let ContextFixture { + in_memory_context, checks, query_appraisals, escrow_storage, .. - } = executor_mock; - let manager = Manager::new(domain_separator.clone(), executor, checks); + } = in_memory_context; + let manager = Manager::new(domain_separator.clone(), in_memory_context, checks); escrow_storage.write().unwrap().insert(keys.1, 999999); let mut stored_signed_receipts = Vec::new(); @@ -210,17 +210,17 @@ async fn manager_create_multiple_rav_requests_all_valid_receipts( keys: (LocalWallet, Address), allocation_ids: Vec
, domain_separator: Eip712Domain, - executor_mock: ExecutorFixture, + in_memory_context: ContextFixture, ) { - let ExecutorFixture { - executor, + let ContextFixture { + in_memory_context, checks, query_appraisals, escrow_storage, .. - } = executor_mock; + } = in_memory_context; - let manager = Manager::new(domain_separator.clone(), executor, checks); + let manager = Manager::new(domain_separator.clone(), in_memory_context, checks); escrow_storage.write().unwrap().insert(keys.1, 999999); @@ -324,18 +324,18 @@ async fn manager_create_multiple_rav_requests_all_valid_receipts_consecutive_tim allocation_ids: Vec
, domain_separator: Eip712Domain, #[values(true, false)] remove_old_receipts: bool, - executor_mock: ExecutorFixture, + in_memory_context: ContextFixture, ) { - let ExecutorFixture { - executor, + let ContextFixture { + in_memory_context, checks, query_appraisals, escrow_storage, .. - } = executor_mock; + } = in_memory_context; let starting_min_timestamp = get_current_timestamp_u64_ns().unwrap() - 500000000; - let manager = Manager::new(domain_separator.clone(), executor.clone(), checks); + let manager = Manager::new(domain_separator.clone(), in_memory_context.clone(), checks); escrow_storage.write().unwrap().insert(keys.1, 999999); @@ -414,7 +414,7 @@ async fn manager_create_multiple_rav_requests_all_valid_receipts_consecutive_tim manager.remove_obsolete_receipts().await.unwrap(); // We expect to have 10 receipts left in receipt storage assert_eq!( - executor + in_memory_context .retrieve_receipts_in_timestamp_range(.., None) .await .unwrap() diff --git a/tap_core/tests/rav_test.rs b/tap_core/tests/rav_test.rs index 018cdb77..52a1378d 100644 --- a/tap_core/tests/rav_test.rs +++ b/tap_core/tests/rav_test.rs @@ -11,7 +11,7 @@ use ethers::signers::coins_bip39::English; use ethers::signers::{LocalWallet, MnemonicBuilder}; use rstest::*; -use tap_core::manager::context::memory::ExecutorMock; +use tap_core::manager::context::memory::InMemoryContext; use tap_core::{ manager::strategy::{RAVRead, RAVStore}, rav::ReceiptAggregateVoucher, @@ -26,13 +26,13 @@ fn domain_separator() -> Eip712Domain { } #[fixture] -fn executor() -> ExecutorMock { +fn in_memory_context() -> InMemoryContext { let escrow_storage = Arc::new(RwLock::new(HashMap::new())); let rav_storage = Arc::new(RwLock::new(None)); let receipt_storage = Arc::new(RwLock::new(HashMap::new())); let timestamp_check = Arc::new(TimestampCheck::new(0)); - ExecutorMock::new( + InMemoryContext::new( rav_storage, receipt_storage.clone(), escrow_storage.clone(), @@ -42,7 +42,7 @@ fn executor() -> ExecutorMock { #[rstest] #[tokio::test] -async fn rav_storage_adapter_test(domain_separator: Eip712Domain, executor: ExecutorMock) { +async fn rav_storage_strategy_test(domain_separator: Eip712Domain, in_memory_context: InMemoryContext) { let wallet: LocalWallet = MnemonicBuilder::::default() .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") .build() @@ -73,10 +73,10 @@ async fn rav_storage_adapter_test(domain_separator: Eip712Domain, executor: Exec ) .unwrap(); - executor.update_last_rav(signed_rav.clone()).await.unwrap(); + in_memory_context.update_last_rav(signed_rav.clone()).await.unwrap(); // Retreive rav - let retrieved_rav = executor.last_rav().await; + let retrieved_rav = in_memory_context.last_rav().await; assert!(retrieved_rav.unwrap().unwrap() == signed_rav); // Testing the last rav update... @@ -102,9 +102,9 @@ async fn rav_storage_adapter_test(domain_separator: Eip712Domain, executor: Exec .unwrap(); // Update the last rav - executor.update_last_rav(signed_rav.clone()).await.unwrap(); + in_memory_context.update_last_rav(signed_rav.clone()).await.unwrap(); // Retreive rav - let retrieved_rav = executor.last_rav().await; + let retrieved_rav = in_memory_context.last_rav().await; assert!(retrieved_rav.unwrap().unwrap() == signed_rav); } diff --git a/tap_core/tests/receipt_test.rs b/tap_core/tests/receipt_test.rs index ec33b19f..ab0e15e6 100644 --- a/tap_core/tests/receipt_test.rs +++ b/tap_core/tests/receipt_test.rs @@ -5,7 +5,7 @@ use rand::thread_rng; use std::collections::HashMap; use std::str::FromStr; use std::sync::{Arc, RwLock}; -use tap_core::manager::context::memory::ExecutorMock; +use tap_core::manager::context::memory::InMemoryContext; use tap_core::receipt::{Checking, ReceiptWithState}; use alloy_primitives::Address; @@ -24,13 +24,13 @@ fn domain_separator() -> Eip712Domain { } #[fixture] -fn executor() -> ExecutorMock { +fn in_memory_context() -> InMemoryContext { let escrow_storage = Arc::new(RwLock::new(HashMap::new())); let rav_storage = Arc::new(RwLock::new(None)); let receipt_storage = Arc::new(RwLock::new(HashMap::new())); let timestamp_check = Arc::new(TimestampCheck::new(0)); - ExecutorMock::new( + InMemoryContext::new( rav_storage, receipt_storage.clone(), escrow_storage.clone(), @@ -40,7 +40,7 @@ fn executor() -> ExecutorMock { #[rstest] #[tokio::test] -async fn receipt_adapter_test(domain_separator: Eip712Domain, mut executor: ExecutorMock) { +async fn receipt_strategy_test(domain_separator: Eip712Domain, mut in_memory_context: InMemoryContext) { let wallet: LocalWallet = MnemonicBuilder::::default() .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") .build() @@ -59,30 +59,30 @@ async fn receipt_adapter_test(domain_separator: Eip712Domain, mut executor: Exec .unwrap(), ); - let receipt_store_result = executor.store_receipt(received_receipt).await; + let receipt_store_result = in_memory_context.store_receipt(received_receipt).await; assert!(receipt_store_result.is_ok()); let receipt_id = receipt_store_result.unwrap(); // Retreive receipt with id expected to be valid - assert!(executor.retrieve_receipt_by_id(receipt_id).await.is_ok()); + assert!(in_memory_context.retrieve_receipt_by_id(receipt_id).await.is_ok()); // Retreive receipt with arbitrary id expected to be invalid - assert!(executor.retrieve_receipt_by_id(999).await.is_err()); + assert!(in_memory_context.retrieve_receipt_by_id(999).await.is_err()); // Remove receipt with id expected to be valid - assert!(executor.remove_receipt_by_id(receipt_id).await.is_ok()); + assert!(in_memory_context.remove_receipt_by_id(receipt_id).await.is_ok()); // Remove receipt with arbitrary id expected to be invalid - assert!(executor.remove_receipt_by_id(999).await.is_err()); + assert!(in_memory_context.remove_receipt_by_id(999).await.is_err()); // Retreive receipt that was removed previously - assert!(executor.retrieve_receipt_by_id(receipt_id).await.is_err()); + assert!(in_memory_context.retrieve_receipt_by_id(receipt_id).await.is_err()); // Remove receipt that was removed previously - assert!(executor.remove_receipt_by_id(receipt_id).await.is_err()); + assert!(in_memory_context.remove_receipt_by_id(receipt_id).await.is_err()); } #[rstest] #[tokio::test] -async fn multi_receipt_adapter_test(domain_separator: Eip712Domain, mut executor: ExecutorMock) { +async fn multi_receipt_strategy_test(domain_separator: Eip712Domain, mut in_memory_context: InMemoryContext) { let wallet: LocalWallet = MnemonicBuilder::::default() .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") .build() @@ -106,27 +106,27 @@ async fn multi_receipt_adapter_test(domain_separator: Eip712Domain, mut executor let mut receipt_timestamps = Vec::new(); for received_receipt in received_receipts { receipt_timestamps.push(received_receipt.signed_receipt().message.timestamp_ns); - receipt_ids.push(executor.store_receipt(received_receipt).await.unwrap()); + receipt_ids.push(in_memory_context.store_receipt(received_receipt).await.unwrap()); } // Retreive receipts with timestamp - assert!(executor + assert!(in_memory_context .retrieve_receipts_by_timestamp(receipt_timestamps[0]) .await .is_ok()); - assert!(!executor + assert!(!in_memory_context .retrieve_receipts_by_timestamp(receipt_timestamps[0]) .await .unwrap() .is_empty()); // Retreive receipts before timestamp - assert!(executor + assert!(in_memory_context .retrieve_receipts_upto_timestamp(receipt_timestamps[3]) .await .is_ok()); assert!( - executor + in_memory_context .retrieve_receipts_upto_timestamp(receipt_timestamps[3]) .await .unwrap() @@ -135,18 +135,18 @@ async fn multi_receipt_adapter_test(domain_separator: Eip712Domain, mut executor ); // Remove all receipts with one call - assert!(executor + assert!(in_memory_context .remove_receipts_by_ids(receipt_ids.as_slice()) .await .is_ok()); // Removal should no longer be valid - assert!(executor + assert!(in_memory_context .remove_receipts_by_ids(receipt_ids.as_slice()) .await .is_err()); // Retrieval should be invalid for receipt_id in receipt_ids { - assert!(executor.retrieve_receipt_by_id(receipt_id).await.is_err()); + assert!(in_memory_context.retrieve_receipt_by_id(receipt_id).await.is_err()); } } diff --git a/tap_core/tests/received_receipt_test.rs b/tap_core/tests/received_receipt_test.rs index 516d9cdb..4637365d 100644 --- a/tap_core/tests/received_receipt_test.rs +++ b/tap_core/tests/received_receipt_test.rs @@ -13,7 +13,7 @@ use ethers::signers::{coins_bip39::English, LocalWallet, MnemonicBuilder, Signer use rstest::*; use tap_core::{ manager::context::memory::{ - checks::get_full_list_of_checks, EscrowStorage, ExecutorMock, QueryAppraisals, + checks::get_full_list_of_checks, EscrowStorage, InMemoryContext, QueryAppraisals, }, receipt::{ checks::{ReceiptCheck, TimestampCheck}, @@ -61,27 +61,27 @@ fn domain_separator() -> Eip712Domain { tap_eip712_domain(1, Address::from([0x11u8; 20])) } -struct ExecutorFixture { - executor: ExecutorMock, +struct ContextFixture { + in_memory_context: InMemoryContext, escrow_storage: EscrowStorage, query_appraisals: QueryAppraisals, checks: Vec, } #[fixture] -fn executor_mock( +fn in_memory_context( domain_separator: Eip712Domain, allocation_ids: Vec
, sender_ids: Vec
, keys: (LocalWallet, Address), -) -> ExecutorFixture { +) -> ContextFixture { let escrow_storage = Arc::new(RwLock::new(HashMap::new())); let rav_storage = Arc::new(RwLock::new(None)); let receipt_storage = Arc::new(RwLock::new(HashMap::new())); let query_appraisals = Arc::new(RwLock::new(HashMap::new())); let timestamp_check = Arc::new(TimestampCheck::new(0)); - let executor = ExecutorMock::new( + let in_memory_context = InMemoryContext::new( rav_storage, receipt_storage.clone(), escrow_storage.clone(), @@ -96,8 +96,8 @@ fn executor_mock( ); checks.push(timestamp_check); - ExecutorFixture { - executor, + ContextFixture { + in_memory_context, escrow_storage, query_appraisals, checks, @@ -110,14 +110,14 @@ async fn partial_then_full_check_valid_receipt( keys: (LocalWallet, Address), domain_separator: Eip712Domain, allocation_ids: Vec
, - executor_mock: ExecutorFixture, + in_memory_context: ContextFixture, ) { - let ExecutorFixture { + let ContextFixture { checks, escrow_storage, query_appraisals, .. - } = executor_mock; + } = in_memory_context; let query_value = 20u128; let signed_receipt = EIP712SignedMessage::new( @@ -152,15 +152,15 @@ async fn partial_then_finalize_valid_receipt( keys: (LocalWallet, Address), allocation_ids: Vec
, domain_separator: Eip712Domain, - executor_mock: ExecutorFixture, + in_memory_context: ContextFixture, ) { - let ExecutorFixture { + let ContextFixture { checks, - executor, + in_memory_context, escrow_storage, query_appraisals, .. - } = executor_mock; + } = in_memory_context; let query_value = 20u128; let signed_receipt = EIP712SignedMessage::new( @@ -189,7 +189,7 @@ async fn partial_then_finalize_valid_receipt( let awaiting_escrow_receipt = awaiting_escrow_receipt.unwrap(); let receipt = awaiting_escrow_receipt - .check_and_reserve_escrow(&executor, &domain_separator) + .check_and_reserve_escrow(&in_memory_context, &domain_separator) .await; assert!(receipt.is_ok()); } @@ -200,15 +200,15 @@ async fn standard_lifetime_valid_receipt( keys: (LocalWallet, Address), allocation_ids: Vec
, domain_separator: Eip712Domain, - executor_mock: ExecutorFixture, + in_memory_context: ContextFixture, ) { - let ExecutorFixture { + let ContextFixture { checks, - executor, + in_memory_context, escrow_storage, query_appraisals, .. - } = executor_mock; + } = in_memory_context; let query_value = 20u128; let signed_receipt = EIP712SignedMessage::new( @@ -238,7 +238,7 @@ async fn standard_lifetime_valid_receipt( let awaiting_escrow_receipt = awaiting_escrow_receipt.unwrap(); let receipt = awaiting_escrow_receipt - .check_and_reserve_escrow(&executor, &domain_separator) + .check_and_reserve_escrow(&in_memory_context, &domain_separator) .await; assert!(receipt.is_ok()); } diff --git a/tap_integration_tests/tests/indexer_mock.rs b/tap_integration_tests/tests/indexer_mock.rs index 301d3cf9..8fbcea80 100644 --- a/tap_integration_tests/tests/indexer_mock.rs +++ b/tap_integration_tests/tests/indexer_mock.rs @@ -59,7 +59,7 @@ where { pub fn new( domain_separator: Eip712Domain, - executor: E, + in_memory_context: E, required_checks: Checks, threshold: u64, aggregate_server_address: String, @@ -68,7 +68,7 @@ where Ok(Self { manager: Arc::new(Manager::::new( domain_separator, - executor, + in_memory_context, required_checks, )), receipt_count: Arc::new(AtomicU64::new(0)), @@ -133,7 +133,7 @@ where pub async fn run_server( port: u16, // Port on which the server will listen domain_separator: Eip712Domain, // EIP712 domain separator - executor: E, // Executor instance + in_memory_context: E, // in_memory_context instance required_checks: Checks, // Vector of required checks to be performed on each request threshold: u64, // The count at which a RAV request will be triggered aggregate_server_address: String, // Address of the aggregator server @@ -160,7 +160,7 @@ where println!("Listening on: {}", addr); let rpc_manager = RpcManager::new( domain_separator, - executor, + in_memory_context, required_checks, threshold, aggregate_server_address, diff --git a/tap_integration_tests/tests/showcase.rs b/tap_integration_tests/tests/showcase.rs index 10cf1ec9..ed7283ec 100644 --- a/tap_integration_tests/tests/showcase.rs +++ b/tap_integration_tests/tests/showcase.rs @@ -167,23 +167,23 @@ fn query_appraisals(query_price: &[u128]) -> QueryAppraisals { )) } -struct ExecutorFixture { - executor: ExecutorMock, +struct ContextFixture { + in_memory_context: InMemoryContext, checks: Checks, } #[fixture] -fn executor( +fn in_memory_context( domain_separator: Eip712Domain, allocation_ids: Vec
, sender_ids: Vec
, query_appraisals: QueryAppraisals, -) -> ExecutorFixture { +) -> ContextFixture { let receipt_storage = Arc::new(RwLock::new(HashMap::new())); let escrow_storage = Arc::new(RwLock::new(HashMap::new())); let rav_storage = Arc::new(RwLock::new(None)); let timestamp_check = Arc::new(TimestampCheck::new(0)); - let executor = ExecutorMock::new( + let in_memory_context = InMemoryContext::new( rav_storage, receipt_storage.clone(), escrow_storage.clone(), @@ -198,17 +198,17 @@ fn executor( let checks = Checks::new(checks); - ExecutorFixture { executor, checks } + ContextFixture { in_memory_context, checks } } #[fixture] -fn indexer_1_adapters(executor: ExecutorFixture) -> ExecutorFixture { - executor +fn indexer_1_context(in_memory_context: ContextFixture) -> ContextFixture { + in_memory_context } #[fixture] -fn indexer_2_adapters(executor: ExecutorFixture) -> ExecutorFixture { - executor +fn indexer_2_context(in_memory_context: ContextFixture) -> ContextFixture { + in_memory_context } // Helper fixture to generate a batch of receipts to be sent to the Indexer. @@ -356,7 +356,7 @@ async fn single_indexer_test_server( http_request_size_limit: u32, http_response_size_limit: u32, http_max_concurrent_connections: u32, - indexer_1_adapters: ExecutorFixture, + indexer_1_context: ContextFixture, available_escrow: u128, receipt_threshold_1: u64, ) -> Result<(ServerHandle, SocketAddr, ServerHandle, SocketAddr)> { @@ -369,10 +369,10 @@ async fn single_indexer_test_server( http_max_concurrent_connections, ) .await?; - let ExecutorFixture { executor, checks } = indexer_1_adapters; + let ContextFixture { in_memory_context, checks } = indexer_1_context; let (indexer_handle, indexer_addr) = start_indexer_server( domain_separator.clone(), - executor, + in_memory_context, sender_id, available_escrow, checks, @@ -395,8 +395,8 @@ async fn two_indexers_test_servers( http_request_size_limit: u32, http_response_size_limit: u32, http_max_concurrent_connections: u32, - indexer_1_adapters: ExecutorFixture, - indexer_2_adapters: ExecutorFixture, + indexer_1_context: ContextFixture, + indexer_2_context: ContextFixture, available_escrow: u128, receipt_threshold_1: u64, ) -> Result<( @@ -416,19 +416,19 @@ async fn two_indexers_test_servers( http_max_concurrent_connections, ) .await?; - let ExecutorFixture { - executor: executor_1, + let ContextFixture { + in_memory_context: in_memory_1, checks: checks_1, - } = indexer_1_adapters; + } = indexer_1_context; - let ExecutorFixture { - executor: executor_2, + let ContextFixture { + in_memory_context: in_memory_2, checks: checks_2, - } = indexer_2_adapters; + } = indexer_2_context; let (indexer_handle, indexer_addr) = start_indexer_server( domain_separator.clone(), - executor_1, + in_memory_1, sender_id, available_escrow, checks_1, @@ -439,7 +439,7 @@ async fn two_indexers_test_servers( let (indexer_handle_2, indexer_addr_2) = start_indexer_server( domain_separator.clone(), - executor_2, + in_memory_2, sender_id, available_escrow, checks_2, @@ -465,7 +465,7 @@ async fn single_indexer_wrong_sender_test_server( http_request_size_limit: u32, http_response_size_limit: u32, http_max_concurrent_connections: u32, - indexer_1_adapters: ExecutorFixture, + indexer_1_context: ContextFixture, available_escrow: u128, receipt_threshold_1: u64, ) -> Result<(ServerHandle, SocketAddr, ServerHandle, SocketAddr)> { @@ -478,13 +478,13 @@ async fn single_indexer_wrong_sender_test_server( http_max_concurrent_connections, ) .await?; - let ExecutorFixture { - executor, checks, .. - } = indexer_1_adapters; + let ContextFixture { + in_memory_context, checks, .. + } = indexer_1_context; let (indexer_handle, indexer_addr) = start_indexer_server( domain_separator.clone(), - executor, + in_memory_context, sender_id, available_escrow, checks, @@ -811,7 +811,7 @@ fn generate_requests( // Start-up a mock Indexer. Requires a Sender Aggregator to be running. async fn start_indexer_server( domain_separator: Eip712Domain, - mut executor: ExecutorMock, + mut in_memory_context: InMemoryContext, sender_id: Address, available_escrow: u128, required_checks: Checks, @@ -823,13 +823,13 @@ async fn start_indexer_server( listener.local_addr()?.port() }; - executor.increase_escrow(sender_id, available_escrow); + in_memory_context.increase_escrow(sender_id, available_escrow); let aggregate_server_address = "http://".to_string() + &agg_server_addr.to_string(); let (server_handle, socket_addr) = indexer_mock::run_server( http_port, domain_separator, - executor.with_sender_address(sender_id), + in_memory_context.with_sender_address(sender_id), required_checks, receipt_threshold, aggregate_server_address, From ab66f1336f6f28aed6bb57a6f40a532a0bc7cc44 Mon Sep 17 00:00:00 2001 From: Gustavo Inacio Date: Sun, 10 Mar 2024 12:16:26 -0300 Subject: [PATCH 05/11] style: cargo fmt Signed-off-by: Gustavo Inacio --- tap_core/tests/escrow_test.rs | 23 +++++++++-- tap_core/tests/rav_test.rs | 15 ++++++-- tap_core/tests/receipt_test.rs | 42 +++++++++++++++++---- tap_integration_tests/tests/indexer_mock.rs | 2 +- tap_integration_tests/tests/showcase.rs | 14 +++++-- 5 files changed, 77 insertions(+), 19 deletions(-) diff --git a/tap_core/tests/escrow_test.rs b/tap_core/tests/escrow_test.rs index d7b649ce..87f3e6c1 100644 --- a/tap_core/tests/escrow_test.rs +++ b/tap_core/tests/escrow_test.rs @@ -51,9 +51,15 @@ async fn escrow_handler_test(mut in_memory_context: InMemoryContext) { in_memory_context.increase_escrow(sender_id, initial_value); // Check that sender exists and has valid value through adapter - assert!(in_memory_context.get_available_escrow(sender_id).await.is_ok()); + assert!(in_memory_context + .get_available_escrow(sender_id) + .await + .is_ok()); assert_eq!( - in_memory_context.get_available_escrow(sender_id).await.unwrap(), + in_memory_context + .get_available_escrow(sender_id) + .await + .unwrap(), initial_value ); @@ -62,8 +68,17 @@ async fn escrow_handler_test(mut in_memory_context: InMemoryContext) { .subtract_escrow(sender_id, initial_value) .await .is_ok()); - assert!(in_memory_context.get_available_escrow(sender_id).await.is_ok()); - assert_eq!(in_memory_context.get_available_escrow(sender_id).await.unwrap(), 0); + assert!(in_memory_context + .get_available_escrow(sender_id) + .await + .is_ok()); + assert_eq!( + in_memory_context + .get_available_escrow(sender_id) + .await + .unwrap(), + 0 + ); // Check that subtracting to negative escrow results in err assert!(in_memory_context diff --git a/tap_core/tests/rav_test.rs b/tap_core/tests/rav_test.rs index 52a1378d..4ccedb09 100644 --- a/tap_core/tests/rav_test.rs +++ b/tap_core/tests/rav_test.rs @@ -42,7 +42,10 @@ fn in_memory_context() -> InMemoryContext { #[rstest] #[tokio::test] -async fn rav_storage_strategy_test(domain_separator: Eip712Domain, in_memory_context: InMemoryContext) { +async fn rav_storage_strategy_test( + domain_separator: Eip712Domain, + in_memory_context: InMemoryContext, +) { let wallet: LocalWallet = MnemonicBuilder::::default() .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") .build() @@ -73,7 +76,10 @@ async fn rav_storage_strategy_test(domain_separator: Eip712Domain, in_memory_con ) .unwrap(); - in_memory_context.update_last_rav(signed_rav.clone()).await.unwrap(); + in_memory_context + .update_last_rav(signed_rav.clone()) + .await + .unwrap(); // Retreive rav let retrieved_rav = in_memory_context.last_rav().await; @@ -102,7 +108,10 @@ async fn rav_storage_strategy_test(domain_separator: Eip712Domain, in_memory_con .unwrap(); // Update the last rav - in_memory_context.update_last_rav(signed_rav.clone()).await.unwrap(); + in_memory_context + .update_last_rav(signed_rav.clone()) + .await + .unwrap(); // Retreive rav let retrieved_rav = in_memory_context.last_rav().await; diff --git a/tap_core/tests/receipt_test.rs b/tap_core/tests/receipt_test.rs index ab0e15e6..35c4ff3f 100644 --- a/tap_core/tests/receipt_test.rs +++ b/tap_core/tests/receipt_test.rs @@ -40,7 +40,10 @@ fn in_memory_context() -> InMemoryContext { #[rstest] #[tokio::test] -async fn receipt_strategy_test(domain_separator: Eip712Domain, mut in_memory_context: InMemoryContext) { +async fn receipt_strategy_test( + domain_separator: Eip712Domain, + mut in_memory_context: InMemoryContext, +) { let wallet: LocalWallet = MnemonicBuilder::::default() .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") .build() @@ -64,25 +67,40 @@ async fn receipt_strategy_test(domain_separator: Eip712Domain, mut in_memory_con let receipt_id = receipt_store_result.unwrap(); // Retreive receipt with id expected to be valid - assert!(in_memory_context.retrieve_receipt_by_id(receipt_id).await.is_ok()); + assert!(in_memory_context + .retrieve_receipt_by_id(receipt_id) + .await + .is_ok()); // Retreive receipt with arbitrary id expected to be invalid assert!(in_memory_context.retrieve_receipt_by_id(999).await.is_err()); // Remove receipt with id expected to be valid - assert!(in_memory_context.remove_receipt_by_id(receipt_id).await.is_ok()); + assert!(in_memory_context + .remove_receipt_by_id(receipt_id) + .await + .is_ok()); // Remove receipt with arbitrary id expected to be invalid assert!(in_memory_context.remove_receipt_by_id(999).await.is_err()); // Retreive receipt that was removed previously - assert!(in_memory_context.retrieve_receipt_by_id(receipt_id).await.is_err()); + assert!(in_memory_context + .retrieve_receipt_by_id(receipt_id) + .await + .is_err()); // Remove receipt that was removed previously - assert!(in_memory_context.remove_receipt_by_id(receipt_id).await.is_err()); + assert!(in_memory_context + .remove_receipt_by_id(receipt_id) + .await + .is_err()); } #[rstest] #[tokio::test] -async fn multi_receipt_strategy_test(domain_separator: Eip712Domain, mut in_memory_context: InMemoryContext) { +async fn multi_receipt_strategy_test( + domain_separator: Eip712Domain, + mut in_memory_context: InMemoryContext, +) { let wallet: LocalWallet = MnemonicBuilder::::default() .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") .build() @@ -106,7 +124,12 @@ async fn multi_receipt_strategy_test(domain_separator: Eip712Domain, mut in_memo let mut receipt_timestamps = Vec::new(); for received_receipt in received_receipts { receipt_timestamps.push(received_receipt.signed_receipt().message.timestamp_ns); - receipt_ids.push(in_memory_context.store_receipt(received_receipt).await.unwrap()); + receipt_ids.push( + in_memory_context + .store_receipt(received_receipt) + .await + .unwrap(), + ); } // Retreive receipts with timestamp @@ -146,7 +169,10 @@ async fn multi_receipt_strategy_test(domain_separator: Eip712Domain, mut in_memo .is_err()); // Retrieval should be invalid for receipt_id in receipt_ids { - assert!(in_memory_context.retrieve_receipt_by_id(receipt_id).await.is_err()); + assert!(in_memory_context + .retrieve_receipt_by_id(receipt_id) + .await + .is_err()); } } diff --git a/tap_integration_tests/tests/indexer_mock.rs b/tap_integration_tests/tests/indexer_mock.rs index 8fbcea80..24221413 100644 --- a/tap_integration_tests/tests/indexer_mock.rs +++ b/tap_integration_tests/tests/indexer_mock.rs @@ -133,7 +133,7 @@ where pub async fn run_server( port: u16, // Port on which the server will listen domain_separator: Eip712Domain, // EIP712 domain separator - in_memory_context: E, // in_memory_context instance + in_memory_context: E, // in_memory_context instance required_checks: Checks, // Vector of required checks to be performed on each request threshold: u64, // The count at which a RAV request will be triggered aggregate_server_address: String, // Address of the aggregator server diff --git a/tap_integration_tests/tests/showcase.rs b/tap_integration_tests/tests/showcase.rs index ed7283ec..654e5791 100644 --- a/tap_integration_tests/tests/showcase.rs +++ b/tap_integration_tests/tests/showcase.rs @@ -198,7 +198,10 @@ fn in_memory_context( let checks = Checks::new(checks); - ContextFixture { in_memory_context, checks } + ContextFixture { + in_memory_context, + checks, + } } #[fixture] @@ -369,7 +372,10 @@ async fn single_indexer_test_server( http_max_concurrent_connections, ) .await?; - let ContextFixture { in_memory_context, checks } = indexer_1_context; + let ContextFixture { + in_memory_context, + checks, + } = indexer_1_context; let (indexer_handle, indexer_addr) = start_indexer_server( domain_separator.clone(), in_memory_context, @@ -479,7 +485,9 @@ async fn single_indexer_wrong_sender_test_server( ) .await?; let ContextFixture { - in_memory_context, checks, .. + in_memory_context, + checks, + .. } = indexer_1_context; let (indexer_handle, indexer_addr) = start_indexer_server( From 7810f4a3ac100e70a167232e254ac8649b40b12b Mon Sep 17 00:00:00 2001 From: Gustavo Inacio Date: Sun, 10 Mar 2024 12:21:10 -0300 Subject: [PATCH 06/11] refactor: remove serialize from rav request Signed-off-by: Gustavo Inacio --- tap_core/src/rav/request.rs | 4 +--- tap_core/src/receipt/received_receipt.rs | 5 ++--- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/tap_core/src/rav/request.rs b/tap_core/src/rav/request.rs index 3031c6db..347f9880 100644 --- a/tap_core/src/rav/request.rs +++ b/tap_core/src/rav/request.rs @@ -1,14 +1,12 @@ // Copyright 2023-, Semiotic AI, Inc. // SPDX-License-Identifier: Apache-2.0 -use serde::{Deserialize, Serialize}; - use crate::{ rav::{ReceiptAggregateVoucher, SignedRAV}, receipt::{Failed, ReceiptWithState, SignedReceipt}, }; -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug)] pub struct RAVRequest { pub valid_receipts: Vec, pub previous_rav: Option, diff --git a/tap_core/src/receipt/received_receipt.rs b/tap_core/src/receipt/received_receipt.rs index 8e2af59c..f20774ca 100644 --- a/tap_core/src/receipt/received_receipt.rs +++ b/tap_core/src/receipt/received_receipt.rs @@ -14,7 +14,6 @@ //! their progress through various checks and stages of inclusion in RAV requests and received RAVs. use alloy_sol_types::Eip712Domain; -use serde::{Deserialize, Serialize}; use super::{Receipt, ReceiptError, ReceiptResult, SignedReceipt}; use crate::{ @@ -25,7 +24,7 @@ use crate::{ #[derive(Debug, Clone)] pub struct Checking; -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone)] pub struct Failed { /// A list of checks to be completed for the receipt, along with their current result pub error: ReceiptError, @@ -45,7 +44,7 @@ impl ReceiptState for Failed {} pub type ResultReceipt = std::result::Result, ReceiptWithState>; -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone)] /// Wrapper class for metadata and state of a received receipt pub struct ReceiptWithState where From 42bd2dfce16d12753ade4577cb0ee47b3d82dbce Mon Sep 17 00:00:00 2001 From: Gustavo Inacio Date: Mon, 11 Mar 2024 14:23:00 -0300 Subject: [PATCH 07/11] revert: rename back to adapters Signed-off-by: Gustavo Inacio --- tap_core/src/error.rs | 4 +- .../manager/{strategy => adapters}/escrow.rs | 18 ++++----- .../src/manager/{strategy => adapters}/mod.rs | 0 .../src/manager/{strategy => adapters}/rav.rs | 20 +++++----- .../manager/{strategy => adapters}/receipt.rs | 28 ++++++------- tap_core/src/manager/context/memory.rs | 40 +++++++++---------- tap_core/src/manager/mod.rs | 2 +- tap_core/src/manager/tap_manager.rs | 20 +++++----- tap_core/src/receipt/received_receipt.rs | 2 +- tap_core/tests/escrow_test.rs | 2 +- tap_core/tests/manager_test.rs | 2 +- tap_core/tests/rav_test.rs | 4 +- tap_core/tests/receipt_test.rs | 8 ++-- tap_integration_tests/tests/indexer_mock.rs | 2 +- 14 files changed, 76 insertions(+), 76 deletions(-) rename tap_core/src/manager/{strategy => adapters}/escrow.rs (87%) rename tap_core/src/manager/{strategy => adapters}/mod.rs (100%) rename tap_core/src/manager/{strategy => adapters}/rav.rs (82%) rename tap_core/src/manager/{strategy => adapters}/receipt.rs (88%) diff --git a/tap_core/src/error.rs b/tap_core/src/error.rs index 6e411cba..d489076f 100644 --- a/tap_core/src/error.rs +++ b/tap_core/src/error.rs @@ -36,8 +36,8 @@ pub enum Error { received_rav: ReceiptAggregateVoucher, expected_rav: ReceiptAggregateVoucher, }, - #[error("Error from strategy.\n Caused by: {source_error}")] - StrategyError { source_error: anyhow::Error }, + #[error("Error from adapter.\n Caused by: {source_error}")] + AdapterError { source_error: anyhow::Error }, #[error("Failed to produce rav request, no valid receipts")] NoValidReceiptsForRAVRequest, #[error("Previous RAV allocation id ({prev_id}) doesn't match the allocation id from the new receipt ({new_id}).")] diff --git a/tap_core/src/manager/strategy/escrow.rs b/tap_core/src/manager/adapters/escrow.rs similarity index 87% rename from tap_core/src/manager/strategy/escrow.rs rename to tap_core/src/manager/adapters/escrow.rs index a361f6d8..93760995 100644 --- a/tap_core/src/manager/strategy/escrow.rs +++ b/tap_core/src/manager/adapters/escrow.rs @@ -15,18 +15,18 @@ use crate::{ /// /// This trait is designed to be implemented by users of this library who want to /// customize the management of local accounting for available escrow. The error handling is also -/// customizable by defining an `StrategyError` type, which must implement both `Error` +/// customizable by defining an `AdapterError` type, which must implement both `Error` /// and `Debug` from the standard library. /// /// # Usage /// /// The `get_available_escrow` method should be used to retrieve the local accounting /// amount of available escrow for a specified sender. Any errors during this operation -/// should be captured and returned in the `StrategyError` format. +/// should be captured and returned in the `AdapterError` format. /// /// The `subtract_escrow` method is used to deduct a specified value from the local accounting /// of available escrow of a specified sender. Any errors during this operation should be captured -/// and returned as an `StrategyError`. +/// and returned as an `AdapterError`. /// /// This trait is utilized by [crate::tap_manager], which relies on these /// operations for managing escrow. @@ -41,27 +41,27 @@ pub trait EscrowHandler: Send + Sync { /// /// This error type should implement the `Error` and `Debug` traits from the standard library. /// Errors of this type are returned to the user when an operation fails. - type StrategyError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; + type AdapterError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; /// Retrieves the local accounting amount of available escrow for a specified sender. /// /// This method should be implemented to fetch the local accounting amount of available escrow for a /// specified sender from your system. Any errors that occur during this process should - /// be captured and returned as an `StrategyError`. - async fn get_available_escrow(&self, sender_id: Address) -> Result; + /// be captured and returned as an `AdapterError`. + async fn get_available_escrow(&self, sender_id: Address) -> Result; /// Deducts a specified value from the local accounting of available escrow for a specified sender. /// /// This method should be implemented to deduct a specified value from the local accounting of /// available escrow of a specified sender in your system. Any errors that occur during this - /// process should be captured and returned as an `StrategyError`. + /// process should be captured and returned as an `AdapterError`. async fn subtract_escrow( &self, sender_id: Address, value: u128, - ) -> Result<(), Self::StrategyError>; + ) -> Result<(), Self::AdapterError>; - async fn verify_signer(&self, signer_address: Address) -> Result; + async fn verify_signer(&self, signer_address: Address) -> Result; async fn check_and_reserve_escrow( &self, diff --git a/tap_core/src/manager/strategy/mod.rs b/tap_core/src/manager/adapters/mod.rs similarity index 100% rename from tap_core/src/manager/strategy/mod.rs rename to tap_core/src/manager/adapters/mod.rs diff --git a/tap_core/src/manager/strategy/rav.rs b/tap_core/src/manager/adapters/rav.rs similarity index 82% rename from tap_core/src/manager/strategy/rav.rs rename to tap_core/src/manager/adapters/rav.rs index 1077bafb..f55a6dfe 100644 --- a/tap_core/src/manager/strategy/rav.rs +++ b/tap_core/src/manager/adapters/rav.rs @@ -9,14 +9,14 @@ use crate::rav::SignedRAV; /// /// This trait is designed to be implemented by users of this library who want to /// customize the write storage behavior of `SignedRAV` data. The error handling is also -/// customizable by defining an `StrategyError` type, which must implement both `Error` +/// customizable by defining an `AdapterError` type, which must implement both `Error` /// and `Debug` from the standard library. /// /// # Usage /// /// The `update_last_rav` method should be used to update the last validated `SignedRAV` /// in the storage managed by the adapter. Errors during this operation should be -/// captured and returned in the `StrategyError` format. +/// captured and returned in the `AdapterError` format. /// /// This trait is utilized by [crate::tap_manager], which relies on these /// operations for working with `SignedRAV` data. @@ -31,27 +31,27 @@ pub trait RAVStore { /// /// This error type should implement the `Error` and `Debug` traits from the standard library. /// Errors of this type are returned to the user when an operation fails. - type StrategyError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; + type AdapterError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; /// Updates the storage with the latest validated `SignedRAV`. /// /// This method should be implemented to store the most recent validated `SignedRAV` into your chosen storage system. - /// Any errors that occur during this process should be captured and returned as an `StrategyError`. - async fn update_last_rav(&self, rav: SignedRAV) -> Result<(), Self::StrategyError>; + /// Any errors that occur during this process should be captured and returned as an `AdapterError`. + async fn update_last_rav(&self, rav: SignedRAV) -> Result<(), Self::AdapterError>; } /// `RAVRead` defines a trait for read storage adapters to handle `SignedRAV` data. /// /// This trait is designed to be implemented by users of this library who want to /// customize the read storage behavior of `SignedRAV` data. The error handling is also -/// customizable by defining an `StrategyError` type, which must implement both `Error` +/// customizable by defining an `AdapterError` type, which must implement both `Error` /// and `Debug` from the standard library. /// /// # Usage /// /// The `last_rav` method is designed to fetch the latest `SignedRAV` from the storage. /// If there is no `SignedRAV` available, it should return `None`. Any errors during -/// this operation should be captured and returned as an `StrategyError`. +/// this operation should be captured and returned as an `AdapterError`. /// /// This trait is utilized by [crate::tap_manager], which relies on these /// operations for working with `SignedRAV` data. @@ -66,12 +66,12 @@ pub trait RAVRead { /// /// This error type should implement the `Error` and `Debug` traits from the standard library. /// Errors of this type are returned to the user when an operation fails. - type StrategyError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; + type AdapterError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; /// Retrieves the latest `SignedRAV` from the storage. /// /// This method should be implemented to fetch the latest `SignedRAV` from your storage system. /// If no `SignedRAV` is available, this method should return `None`. - /// Any errors that occur during this process should be captured and returned as an `StrategyError`. - async fn last_rav(&self) -> Result, Self::StrategyError>; + /// Any errors that occur during this process should be captured and returned as an `AdapterError`. + async fn last_rav(&self) -> Result, Self::AdapterError>; } diff --git a/tap_core/src/manager/strategy/receipt.rs b/tap_core/src/manager/adapters/receipt.rs similarity index 88% rename from tap_core/src/manager/strategy/receipt.rs rename to tap_core/src/manager/adapters/receipt.rs index 702ce6d1..82bfd8e6 100644 --- a/tap_core/src/manager/strategy/receipt.rs +++ b/tap_core/src/manager/adapters/receipt.rs @@ -11,20 +11,20 @@ use crate::receipt::{Checking, ReceiptState, ReceiptWithState}; /// /// This trait is designed to be implemented by users of this library who want to /// customize the write storage behavior of `ReceivedReceipt` data. The error handling is also -/// customizable by defining an `StrategyError` type, which must implement both `Error` +/// customizable by defining an `AdapterError` type, which must implement both `Error` /// and `Debug` from the standard library. /// /// # Usage /// /// The `store_receipt` method should be used to store a new `ReceivedReceipt` in the storage /// managed by the adapter. It returns a unique receipt_id associated with the stored receipt. -/// Any errors during this operation should be captured and returned in the `StrategyError` format. +/// Any errors during this operation should be captured and returned in the `AdapterError` format. /// /// The `update_receipt_by_id` method is designed to update a specific `ReceivedReceipt` identified by a unique -/// receipt_id. Any errors during this operation should be captured and returned as an `StrategyError`. +/// receipt_id. Any errors during this operation should be captured and returned as an `AdapterError`. /// /// The `remove_receipts_in_timestamp_range` method is used to remove all `ReceivedReceipts` within a specific -/// timestamp range from the storage. Any errors during this operation should be captured and returned as an `StrategyError`. +/// timestamp range from the storage. Any errors during this operation should be captured and returned as an `AdapterError`. /// /// This trait is utilized by [crate::tap_manager], which relies on these /// operations for working with `ReceivedReceipt` data. @@ -39,17 +39,17 @@ pub trait ReceiptStore { /// /// This error type should implement the `Error` and `Debug` traits from the standard library. /// Errors of this type are returned to the user when an operation fails. - type StrategyError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; + type AdapterError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; /// Stores a new `ReceivedReceipt` into the storage. /// /// This method should be implemented to store a new `ReceivedReceipt` into your chosen storage system. /// It returns a unique receipt_id associated with the stored receipt. Any errors that occur during - /// this process should be captured and returned as an `StrategyError`. + /// this process should be captured and returned as an `AdapterError`. async fn store_receipt( &self, receipt: ReceiptWithState, - ) -> Result; + ) -> Result; } #[async_trait] @@ -58,23 +58,23 @@ pub trait ReceiptDelete { /// /// This error type should implement the `Error` and `Debug` traits from the standard library. /// Errors of this type are returned to the user when an operation fails. - type StrategyError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; + type AdapterError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; /// Removes all `ReceivedReceipts` within a specific timestamp range from the storage. /// /// This method should be implemented to remove all `ReceivedReceipts` within a specific timestamp /// range from your storage system. Any errors that occur during this process should be captured and - /// returned as an `StrategyError`. + /// returned as an `AdapterError`. async fn remove_receipts_in_timestamp_range + std::marker::Send>( &self, timestamp_ns: R, - ) -> Result<(), Self::StrategyError>; + ) -> Result<(), Self::AdapterError>; } /// `ReceiptRead` defines a trait for read storage adapters to manage `ReceivedReceipt` data. /// /// This trait is designed to be implemented by users of this library who want to /// customize the read storage behavior of `ReceivedReceipt` data. The error handling is also -/// customizable by defining an `StrategyError` type, which must implement both `Error` +/// customizable by defining an `AdapterError` type, which must implement both `Error` /// and `Debug` from the standard library. /// /// # Usage @@ -88,7 +88,7 @@ pub trait ReceiptRead { /// /// This error type should implement the `Error` and `Debug` traits from the standard library. /// Errors of this type are returned to the user when an operation fails. - type StrategyError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; + type AdapterError: std::error::Error + std::fmt::Debug + Send + Sync + 'static; /// Retrieves all `ReceivedReceipts` within a specific timestamp range. /// @@ -110,12 +110,12 @@ pub trait ReceiptRead { /// You can use the [`safe_truncate_receipts()`] function to help with this, but feel free to /// implement a more efficient solution for your situation if you can. /// - /// Any errors that occur during this process should be captured and returned as an `StrategyError`. + /// Any errors that occur during this process should be captured and returned as an `AdapterError`. async fn retrieve_receipts_in_timestamp_range + std::marker::Send>( &self, timestamp_range_ns: R, limit: Option, - ) -> Result>, Self::StrategyError>; + ) -> Result>, Self::AdapterError>; } /// See [`ReceiptStorageAdapter::retrieve_receipts_in_timestamp_range()`] for details. diff --git a/tap_core/src/manager/context/memory.rs b/tap_core/src/manager/context/memory.rs index b804f4da..31ce9ea4 100644 --- a/tap_core/src/manager/context/memory.rs +++ b/tap_core/src/manager/context/memory.rs @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 use crate::{ - manager::strategy::*, + manager::adapters::*, rav::SignedRAV, receipt::{checks::TimestampCheck, Checking, ReceiptWithState}, signed_message::MessageId, @@ -23,7 +23,7 @@ use thiserror::Error; #[derive(Debug, Error)] pub enum InMemoryError { #[error("something went wrong: {error}")] - StrategyError { error: String }, + AdapterError { error: String }, } #[derive(Clone)] @@ -68,7 +68,7 @@ impl InMemoryContext { receipt_storage .get(&receipt_id) .cloned() - .ok_or(InMemoryError::StrategyError { + .ok_or(InMemoryError::AdapterError { error: "No receipt found with ID".to_owned(), }) } @@ -100,7 +100,7 @@ impl InMemoryContext { receipt_storage .remove(&receipt_id) .map(|_| ()) - .ok_or(InMemoryError::StrategyError { + .ok_or(InMemoryError::AdapterError { error: "No receipt found with ID".to_owned(), }) } @@ -117,9 +117,9 @@ impl InMemoryContext { #[async_trait] impl RAVStore for InMemoryContext { - type StrategyError = InMemoryError; + type AdapterError = InMemoryError; - async fn update_last_rav(&self, rav: SignedRAV) -> Result<(), Self::StrategyError> { + async fn update_last_rav(&self, rav: SignedRAV) -> Result<(), Self::AdapterError> { let mut rav_storage = self.rav_storage.write().unwrap(); let timestamp = rav.message.timestampNs; *rav_storage = Some(rav); @@ -130,21 +130,21 @@ impl RAVStore for InMemoryContext { #[async_trait] impl RAVRead for InMemoryContext { - type StrategyError = InMemoryError; + type AdapterError = InMemoryError; - async fn last_rav(&self) -> Result, Self::StrategyError> { + async fn last_rav(&self) -> Result, Self::AdapterError> { Ok(self.rav_storage.read().unwrap().clone()) } } #[async_trait] impl ReceiptStore for InMemoryContext { - type StrategyError = InMemoryError; + type AdapterError = InMemoryError; async fn store_receipt( &self, receipt: ReceiptWithState, - ) -> Result { + ) -> Result { let mut id_pointer = self.unique_id.write().unwrap(); let id_previous = *id_pointer; let mut receipt_storage = self.receipt_storage.write().unwrap(); @@ -156,12 +156,12 @@ impl ReceiptStore for InMemoryContext { #[async_trait] impl ReceiptDelete for InMemoryContext { - type StrategyError = InMemoryError; + type AdapterError = InMemoryError; async fn remove_receipts_in_timestamp_range + std::marker::Send>( &self, timestamp_ns: R, - ) -> Result<(), Self::StrategyError> { + ) -> Result<(), Self::AdapterError> { let mut receipt_storage = self.receipt_storage.write().unwrap(); receipt_storage.retain(|_, rx_receipt| { !timestamp_ns.contains(&rx_receipt.signed_receipt().message.timestamp_ns) @@ -171,12 +171,12 @@ impl ReceiptDelete for InMemoryContext { } #[async_trait] impl ReceiptRead for InMemoryContext { - type StrategyError = InMemoryError; + type AdapterError = InMemoryError; async fn retrieve_receipts_in_timestamp_range + std::marker::Send>( &self, timestamp_range_ns: R, limit: Option, - ) -> Result>, Self::StrategyError> { + ) -> Result>, Self::AdapterError> { let receipt_storage = self.receipt_storage.read().unwrap(); let mut receipts_in_range: Vec> = receipt_storage .iter() @@ -199,7 +199,7 @@ impl InMemoryContext { if let Some(escrow) = sender_escrow_storage.get(&sender_id) { return Ok(*escrow); } - Err(InMemoryError::StrategyError { + Err(InMemoryError::AdapterError { error: "No escrow exists for provided sender ID.".to_owned(), }) } @@ -225,7 +225,7 @@ impl InMemoryContext { return Ok(()); } } - Err(InMemoryError::StrategyError { + Err(InMemoryError::AdapterError { error: "Provided value is greater than existing escrow.".to_owned(), }) } @@ -233,19 +233,19 @@ impl InMemoryContext { #[async_trait] impl EscrowHandler for InMemoryContext { - type StrategyError = InMemoryError; - async fn get_available_escrow(&self, sender_id: Address) -> Result { + type AdapterError = InMemoryError; + async fn get_available_escrow(&self, sender_id: Address) -> Result { self.escrow(sender_id) } async fn subtract_escrow( &self, sender_id: Address, value: u128, - ) -> Result<(), Self::StrategyError> { + ) -> Result<(), Self::AdapterError> { self.reduce_escrow(sender_id, value) } - async fn verify_signer(&self, signer_address: Address) -> Result { + async fn verify_signer(&self, signer_address: Address) -> Result { Ok(self .sender_address .map(|sender| signer_address == sender) diff --git a/tap_core/src/manager/mod.rs b/tap_core/src/manager/mod.rs index c04d8683..66c81ca3 100644 --- a/tap_core/src/manager/mod.rs +++ b/tap_core/src/manager/mod.rs @@ -12,7 +12,7 @@ #[cfg(feature = "in_memory")] pub mod context; -pub mod strategy; +pub mod adapters; mod tap_manager; pub use tap_manager::Manager; diff --git a/tap_core/src/manager/tap_manager.rs b/tap_core/src/manager/tap_manager.rs index cf1d7e5e..ab5ecf61 100644 --- a/tap_core/src/manager/tap_manager.rs +++ b/tap_core/src/manager/tap_manager.rs @@ -3,7 +3,7 @@ use alloy_sol_types::Eip712Domain; -use super::strategy::{EscrowHandler, RAVRead, RAVStore, ReceiptDelete, ReceiptRead, ReceiptStore}; +use super::adapters::{EscrowHandler, RAVRead, RAVStore, ReceiptDelete, ReceiptRead, ReceiptStore}; use crate::{ rav::{RAVRequest, ReceiptAggregateVoucher, SignedRAV}, receipt::{ @@ -47,7 +47,7 @@ where /// /// # Errors /// - /// Returns [`Error::StrategyError`] if there are any errors while storing RAV + /// Returns [`Error::AdapterError`] if there are any errors while storing RAV /// pub async fn verify_and_store_rav( &self, @@ -68,7 +68,7 @@ where self.context .update_last_rav(signed_rav) .await - .map_err(|err| Error::StrategyError { + .map_err(|err| Error::AdapterError { source_error: anyhow::Error::new(err), })?; @@ -85,7 +85,7 @@ where .context .last_rav() .await - .map_err(|err| Error::StrategyError { + .map_err(|err| Error::AdapterError { source_error: anyhow::Error::new(err), })?; Ok(previous_rav) @@ -120,7 +120,7 @@ where .context .retrieve_receipts_in_timestamp_range(min_timestamp_ns..max_timestamp_ns, limit) .await - .map_err(|err| Error::StrategyError { + .map_err(|err| Error::AdapterError { source_error: anyhow::Error::new(err), })?; @@ -169,7 +169,7 @@ where /// /// Returns [`Error::AggregateOverflow`] if any receipt value causes aggregate value to overflow while generating expected RAV /// - /// Returns [`Error::StrategyError`] if unable to fetch previous RAV or if unable to fetch previous receipts + /// Returns [`Error::AdapterError`] if unable to fetch previous RAV or if unable to fetch previous receipts /// /// Returns [`Error::TimestampRangeError`] if the max timestamp of the previous RAV is greater than the min timestamp. Caused by timestamp buffer being too large, or requests coming too soon. /// @@ -234,7 +234,7 @@ where /// /// # Errors /// - /// Returns [`Error::StrategyError`] if there are any errors while retrieving last RAV or removing receipts + /// Returns [`Error::AdapterError`] if there are any errors while retrieving last RAV or removing receipts /// pub async fn remove_obsolete_receipts(&self) -> Result<(), Error> { match self.get_previous_rav().await? { @@ -242,7 +242,7 @@ where self.context .remove_receipts_in_timestamp_range(..=last_rav.message.timestampNs) .await - .map_err(|err| Error::StrategyError { + .map_err(|err| Error::AdapterError { source_error: anyhow::Error::new(err), })?; Ok(()) @@ -261,7 +261,7 @@ where /// /// # Errors /// - /// Returns [`Error::StrategyError`] if there are any errors while storing receipts + /// Returns [`Error::AdapterError`] if there are any errors while storing receipts /// /// Returns [`Error::InvalidStateForRequestedAction`] if the checks requested in `initial_checks` cannot be comleted due to: All other checks must be complete before `CheckAndReserveEscrow` /// @@ -280,7 +280,7 @@ where self.context .store_receipt(received_receipt) .await - .map_err(|err| Error::StrategyError { + .map_err(|err| Error::AdapterError { source_error: anyhow::Error::new(err), })?; Ok(()) diff --git a/tap_core/src/receipt/received_receipt.rs b/tap_core/src/receipt/received_receipt.rs index f20774ca..cb59f41f 100644 --- a/tap_core/src/receipt/received_receipt.rs +++ b/tap_core/src/receipt/received_receipt.rs @@ -17,7 +17,7 @@ use alloy_sol_types::Eip712Domain; use super::{Receipt, ReceiptError, ReceiptResult, SignedReceipt}; use crate::{ - manager::strategy::EscrowHandler, receipt::checks::ReceiptCheck, + manager::adapters::EscrowHandler, receipt::checks::ReceiptCheck, signed_message::EIP712SignedMessage, }; diff --git a/tap_core/tests/escrow_test.rs b/tap_core/tests/escrow_test.rs index 87f3e6c1..d9b37c86 100644 --- a/tap_core/tests/escrow_test.rs +++ b/tap_core/tests/escrow_test.rs @@ -10,7 +10,7 @@ use ethers::signers::{coins_bip39::English, LocalWallet, MnemonicBuilder, Signer use rstest::*; use tap_core::{ - manager::{context::memory::InMemoryContext, strategy::EscrowHandler}, + manager::{context::memory::InMemoryContext, adapters::EscrowHandler}, receipt::checks::TimestampCheck, }; diff --git a/tap_core/tests/manager_test.rs b/tap_core/tests/manager_test.rs index cb65914f..105fc5b3 100644 --- a/tap_core/tests/manager_test.rs +++ b/tap_core/tests/manager_test.rs @@ -21,7 +21,7 @@ use tap_core::{ context::memory::{ checks::get_full_list_of_checks, EscrowStorage, InMemoryContext, QueryAppraisals, }, - strategy::ReceiptRead, + adapters::ReceiptRead, Manager, }, receipt::{ diff --git a/tap_core/tests/rav_test.rs b/tap_core/tests/rav_test.rs index 4ccedb09..f259d676 100644 --- a/tap_core/tests/rav_test.rs +++ b/tap_core/tests/rav_test.rs @@ -13,7 +13,7 @@ use rstest::*; use tap_core::manager::context::memory::InMemoryContext; use tap_core::{ - manager::strategy::{RAVRead, RAVStore}, + manager::adapters::{RAVRead, RAVStore}, rav::ReceiptAggregateVoucher, receipt::{checks::TimestampCheck, Receipt}, signed_message::EIP712SignedMessage, @@ -42,7 +42,7 @@ fn in_memory_context() -> InMemoryContext { #[rstest] #[tokio::test] -async fn rav_storage_strategy_test( +async fn rav_storage_adapter_test( domain_separator: Eip712Domain, in_memory_context: InMemoryContext, ) { diff --git a/tap_core/tests/receipt_test.rs b/tap_core/tests/receipt_test.rs index 35c4ff3f..8ae42af1 100644 --- a/tap_core/tests/receipt_test.rs +++ b/tap_core/tests/receipt_test.rs @@ -14,7 +14,7 @@ use ethers::signers::{coins_bip39::English, LocalWallet, MnemonicBuilder}; use rstest::*; use tap_core::receipt::checks::TimestampCheck; use tap_core::{ - manager::strategy::ReceiptStore, receipt::Receipt, signed_message::EIP712SignedMessage, + manager::adapters::ReceiptStore, receipt::Receipt, signed_message::EIP712SignedMessage, tap_eip712_domain, }; @@ -40,7 +40,7 @@ fn in_memory_context() -> InMemoryContext { #[rstest] #[tokio::test] -async fn receipt_strategy_test( +async fn receipt_adapter_test( domain_separator: Eip712Domain, mut in_memory_context: InMemoryContext, ) { @@ -97,7 +97,7 @@ async fn receipt_strategy_test( #[rstest] #[tokio::test] -async fn multi_receipt_strategy_test( +async fn multi_receipt_adapter_test( domain_separator: Eip712Domain, mut in_memory_context: InMemoryContext, ) { @@ -219,7 +219,7 @@ fn safe_truncate_receipts_test( // shuffle the input receipts receipts_truncated.shuffle(&mut thread_rng()); - tap_core::manager::strategy::safe_truncate_receipts(&mut receipts_truncated, limit); + tap_core::manager::adapters::safe_truncate_receipts(&mut receipts_truncated, limit); assert_eq!(receipts_truncated.len(), expected.len()); diff --git a/tap_integration_tests/tests/indexer_mock.rs b/tap_integration_tests/tests/indexer_mock.rs index 24221413..15c264b9 100644 --- a/tap_integration_tests/tests/indexer_mock.rs +++ b/tap_integration_tests/tests/indexer_mock.rs @@ -18,7 +18,7 @@ use jsonrpsee::{ use tap_aggregator::jsonrpsee_helpers; use tap_core::{ manager::{ - strategy::{EscrowHandler, RAVRead, RAVStore, ReceiptRead, ReceiptStore}, + adapters::{EscrowHandler, RAVRead, RAVStore, ReceiptRead, ReceiptStore}, Manager, }, rav::SignedRAV, From 20576c218b3cf75c6474b51111b012997df3bc33 Mon Sep 17 00:00:00 2001 From: Gustavo Inacio Date: Mon, 11 Mar 2024 14:25:18 -0300 Subject: [PATCH 08/11] style: rename in_memory_context to context Signed-off-by: Gustavo Inacio --- tap_core/src/manager/mod.rs | 2 +- tap_core/tests/escrow_test.rs | 37 ++++-------- tap_core/tests/manager_test.rs | 44 +++++++-------- tap_core/tests/rav_test.rs | 21 ++----- tap_core/tests/receipt_test.rs | 62 ++++++--------------- tap_core/tests/received_receipt_test.rs | 28 +++++----- tap_integration_tests/tests/indexer_mock.rs | 8 +-- tap_integration_tests/tests/showcase.rs | 42 ++++++-------- 8 files changed, 93 insertions(+), 151 deletions(-) diff --git a/tap_core/src/manager/mod.rs b/tap_core/src/manager/mod.rs index 66c81ca3..d3357488 100644 --- a/tap_core/src/manager/mod.rs +++ b/tap_core/src/manager/mod.rs @@ -10,9 +10,9 @@ //! The `Manager` uses user-defined adapters (see [crate::adapters]) for check and storage handling. //! This design offers a high degree of flexibility, letting the user define their own behavior for these critical operations. +pub mod adapters; #[cfg(feature = "in_memory")] pub mod context; -pub mod adapters; mod tap_manager; pub use tap_manager::Manager; diff --git a/tap_core/tests/escrow_test.rs b/tap_core/tests/escrow_test.rs index d9b37c86..ad7b67ee 100644 --- a/tap_core/tests/escrow_test.rs +++ b/tap_core/tests/escrow_test.rs @@ -10,12 +10,12 @@ use ethers::signers::{coins_bip39::English, LocalWallet, MnemonicBuilder, Signer use rstest::*; use tap_core::{ - manager::{context::memory::InMemoryContext, adapters::EscrowHandler}, + manager::{adapters::EscrowHandler, context::memory::InMemoryContext}, receipt::checks::TimestampCheck, }; #[fixture] -fn in_memory_context() -> InMemoryContext { +fn context() -> InMemoryContext { let escrow_storage = Arc::new(RwLock::new(HashMap::new())); let rav_storage = Arc::new(RwLock::new(None)); let receipt_storage = Arc::new(RwLock::new(HashMap::new())); @@ -31,7 +31,7 @@ fn in_memory_context() -> InMemoryContext { #[rstest] #[tokio::test] -async fn escrow_handler_test(mut in_memory_context: InMemoryContext) { +async fn escrow_handler_test(mut context: InMemoryContext) { let wallet: LocalWallet = MnemonicBuilder::::default() .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") .build() @@ -48,46 +48,31 @@ async fn escrow_handler_test(mut in_memory_context: InMemoryContext) { let initial_value = 500u128; - in_memory_context.increase_escrow(sender_id, initial_value); + context.increase_escrow(sender_id, initial_value); // Check that sender exists and has valid value through adapter - assert!(in_memory_context - .get_available_escrow(sender_id) - .await - .is_ok()); + assert!(context.get_available_escrow(sender_id).await.is_ok()); assert_eq!( - in_memory_context - .get_available_escrow(sender_id) - .await - .unwrap(), + context.get_available_escrow(sender_id).await.unwrap(), initial_value ); // Check that subtracting is valid for valid sender, and results in expected value - assert!(in_memory_context + assert!(context .subtract_escrow(sender_id, initial_value) .await .is_ok()); - assert!(in_memory_context - .get_available_escrow(sender_id) - .await - .is_ok()); - assert_eq!( - in_memory_context - .get_available_escrow(sender_id) - .await - .unwrap(), - 0 - ); + assert!(context.get_available_escrow(sender_id).await.is_ok()); + assert_eq!(context.get_available_escrow(sender_id).await.unwrap(), 0); // Check that subtracting to negative escrow results in err - assert!(in_memory_context + assert!(context .subtract_escrow(sender_id, initial_value) .await .is_err()); // Check that accessing non initialized sender results in err - assert!(in_memory_context + assert!(context .get_available_escrow(invalid_sender_id) .await .is_err()); diff --git a/tap_core/tests/manager_test.rs b/tap_core/tests/manager_test.rs index 105fc5b3..43631326 100644 --- a/tap_core/tests/manager_test.rs +++ b/tap_core/tests/manager_test.rs @@ -18,10 +18,10 @@ fn get_current_timestamp_u64_ns() -> anyhow::Result { use tap_core::{ manager::{ + adapters::ReceiptRead, context::memory::{ checks::get_full_list_of_checks, EscrowStorage, InMemoryContext, QueryAppraisals, }, - adapters::ReceiptRead, Manager, }, receipt::{ @@ -71,14 +71,14 @@ fn domain_separator() -> Eip712Domain { } struct ContextFixture { - in_memory_context: InMemoryContext, + context: InMemoryContext, escrow_storage: EscrowStorage, query_appraisals: QueryAppraisals, checks: Checks, } #[fixture] -fn in_memory_context( +fn context( domain_separator: Eip712Domain, allocation_ids: Vec
, sender_ids: Vec
, @@ -89,7 +89,7 @@ fn in_memory_context( let query_appraisals = Arc::new(RwLock::new(HashMap::new())); let receipt_storage = Arc::new(RwLock::new(HashMap::new())); let timestamp_check = Arc::new(TimestampCheck::new(0)); - let in_memory_context = InMemoryContext::new( + let context = InMemoryContext::new( rav_storage, receipt_storage.clone(), escrow_storage.clone(), @@ -107,7 +107,7 @@ fn in_memory_context( let checks = Checks::new(checks); ContextFixture { - in_memory_context, + context, escrow_storage, query_appraisals, checks, @@ -120,16 +120,16 @@ async fn manager_verify_and_store_varying_initial_checks( keys: (LocalWallet, Address), allocation_ids: Vec
, domain_separator: Eip712Domain, - in_memory_context: ContextFixture, + context: ContextFixture, ) { let ContextFixture { - in_memory_context, + context, checks, query_appraisals, escrow_storage, .. - } = in_memory_context; - let manager = Manager::new(domain_separator.clone(), in_memory_context, checks); + } = context; + let manager = Manager::new(domain_separator.clone(), context, checks); let value = 20u128; let signed_receipt = EIP712SignedMessage::new( @@ -154,16 +154,16 @@ async fn manager_create_rav_request_all_valid_receipts( keys: (LocalWallet, Address), allocation_ids: Vec
, domain_separator: Eip712Domain, - in_memory_context: ContextFixture, + context: ContextFixture, ) { let ContextFixture { - in_memory_context, + context, checks, query_appraisals, escrow_storage, .. - } = in_memory_context; - let manager = Manager::new(domain_separator.clone(), in_memory_context, checks); + } = context; + let manager = Manager::new(domain_separator.clone(), context, checks); escrow_storage.write().unwrap().insert(keys.1, 999999); let mut stored_signed_receipts = Vec::new(); @@ -210,17 +210,17 @@ async fn manager_create_multiple_rav_requests_all_valid_receipts( keys: (LocalWallet, Address), allocation_ids: Vec
, domain_separator: Eip712Domain, - in_memory_context: ContextFixture, + context: ContextFixture, ) { let ContextFixture { - in_memory_context, + context, checks, query_appraisals, escrow_storage, .. - } = in_memory_context; + } = context; - let manager = Manager::new(domain_separator.clone(), in_memory_context, checks); + let manager = Manager::new(domain_separator.clone(), context, checks); escrow_storage.write().unwrap().insert(keys.1, 999999); @@ -324,18 +324,18 @@ async fn manager_create_multiple_rav_requests_all_valid_receipts_consecutive_tim allocation_ids: Vec
, domain_separator: Eip712Domain, #[values(true, false)] remove_old_receipts: bool, - in_memory_context: ContextFixture, + context: ContextFixture, ) { let ContextFixture { - in_memory_context, + context, checks, query_appraisals, escrow_storage, .. - } = in_memory_context; + } = context; let starting_min_timestamp = get_current_timestamp_u64_ns().unwrap() - 500000000; - let manager = Manager::new(domain_separator.clone(), in_memory_context.clone(), checks); + let manager = Manager::new(domain_separator.clone(), context.clone(), checks); escrow_storage.write().unwrap().insert(keys.1, 999999); @@ -414,7 +414,7 @@ async fn manager_create_multiple_rav_requests_all_valid_receipts_consecutive_tim manager.remove_obsolete_receipts().await.unwrap(); // We expect to have 10 receipts left in receipt storage assert_eq!( - in_memory_context + context .retrieve_receipts_in_timestamp_range(.., None) .await .unwrap() diff --git a/tap_core/tests/rav_test.rs b/tap_core/tests/rav_test.rs index f259d676..87c87f76 100644 --- a/tap_core/tests/rav_test.rs +++ b/tap_core/tests/rav_test.rs @@ -26,7 +26,7 @@ fn domain_separator() -> Eip712Domain { } #[fixture] -fn in_memory_context() -> InMemoryContext { +fn context() -> InMemoryContext { let escrow_storage = Arc::new(RwLock::new(HashMap::new())); let rav_storage = Arc::new(RwLock::new(None)); let receipt_storage = Arc::new(RwLock::new(HashMap::new())); @@ -42,10 +42,7 @@ fn in_memory_context() -> InMemoryContext { #[rstest] #[tokio::test] -async fn rav_storage_adapter_test( - domain_separator: Eip712Domain, - in_memory_context: InMemoryContext, -) { +async fn rav_storage_adapter_test(domain_separator: Eip712Domain, context: InMemoryContext) { let wallet: LocalWallet = MnemonicBuilder::::default() .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") .build() @@ -76,13 +73,10 @@ async fn rav_storage_adapter_test( ) .unwrap(); - in_memory_context - .update_last_rav(signed_rav.clone()) - .await - .unwrap(); + context.update_last_rav(signed_rav.clone()).await.unwrap(); // Retreive rav - let retrieved_rav = in_memory_context.last_rav().await; + let retrieved_rav = context.last_rav().await; assert!(retrieved_rav.unwrap().unwrap() == signed_rav); // Testing the last rav update... @@ -108,12 +102,9 @@ async fn rav_storage_adapter_test( .unwrap(); // Update the last rav - in_memory_context - .update_last_rav(signed_rav.clone()) - .await - .unwrap(); + context.update_last_rav(signed_rav.clone()).await.unwrap(); // Retreive rav - let retrieved_rav = in_memory_context.last_rav().await; + let retrieved_rav = context.last_rav().await; assert!(retrieved_rav.unwrap().unwrap() == signed_rav); } diff --git a/tap_core/tests/receipt_test.rs b/tap_core/tests/receipt_test.rs index 8ae42af1..c2a50feb 100644 --- a/tap_core/tests/receipt_test.rs +++ b/tap_core/tests/receipt_test.rs @@ -24,7 +24,7 @@ fn domain_separator() -> Eip712Domain { } #[fixture] -fn in_memory_context() -> InMemoryContext { +fn context() -> InMemoryContext { let escrow_storage = Arc::new(RwLock::new(HashMap::new())); let rav_storage = Arc::new(RwLock::new(None)); let receipt_storage = Arc::new(RwLock::new(HashMap::new())); @@ -40,10 +40,7 @@ fn in_memory_context() -> InMemoryContext { #[rstest] #[tokio::test] -async fn receipt_adapter_test( - domain_separator: Eip712Domain, - mut in_memory_context: InMemoryContext, -) { +async fn receipt_adapter_test(domain_separator: Eip712Domain, mut context: InMemoryContext) { let wallet: LocalWallet = MnemonicBuilder::::default() .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") .build() @@ -62,45 +59,30 @@ async fn receipt_adapter_test( .unwrap(), ); - let receipt_store_result = in_memory_context.store_receipt(received_receipt).await; + let receipt_store_result = context.store_receipt(received_receipt).await; assert!(receipt_store_result.is_ok()); let receipt_id = receipt_store_result.unwrap(); // Retreive receipt with id expected to be valid - assert!(in_memory_context - .retrieve_receipt_by_id(receipt_id) - .await - .is_ok()); + assert!(context.retrieve_receipt_by_id(receipt_id).await.is_ok()); // Retreive receipt with arbitrary id expected to be invalid - assert!(in_memory_context.retrieve_receipt_by_id(999).await.is_err()); + assert!(context.retrieve_receipt_by_id(999).await.is_err()); // Remove receipt with id expected to be valid - assert!(in_memory_context - .remove_receipt_by_id(receipt_id) - .await - .is_ok()); + assert!(context.remove_receipt_by_id(receipt_id).await.is_ok()); // Remove receipt with arbitrary id expected to be invalid - assert!(in_memory_context.remove_receipt_by_id(999).await.is_err()); + assert!(context.remove_receipt_by_id(999).await.is_err()); // Retreive receipt that was removed previously - assert!(in_memory_context - .retrieve_receipt_by_id(receipt_id) - .await - .is_err()); + assert!(context.retrieve_receipt_by_id(receipt_id).await.is_err()); // Remove receipt that was removed previously - assert!(in_memory_context - .remove_receipt_by_id(receipt_id) - .await - .is_err()); + assert!(context.remove_receipt_by_id(receipt_id).await.is_err()); } #[rstest] #[tokio::test] -async fn multi_receipt_adapter_test( - domain_separator: Eip712Domain, - mut in_memory_context: InMemoryContext, -) { +async fn multi_receipt_adapter_test(domain_separator: Eip712Domain, mut context: InMemoryContext) { let wallet: LocalWallet = MnemonicBuilder::::default() .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") .build() @@ -124,32 +106,27 @@ async fn multi_receipt_adapter_test( let mut receipt_timestamps = Vec::new(); for received_receipt in received_receipts { receipt_timestamps.push(received_receipt.signed_receipt().message.timestamp_ns); - receipt_ids.push( - in_memory_context - .store_receipt(received_receipt) - .await - .unwrap(), - ); + receipt_ids.push(context.store_receipt(received_receipt).await.unwrap()); } // Retreive receipts with timestamp - assert!(in_memory_context + assert!(context .retrieve_receipts_by_timestamp(receipt_timestamps[0]) .await .is_ok()); - assert!(!in_memory_context + assert!(!context .retrieve_receipts_by_timestamp(receipt_timestamps[0]) .await .unwrap() .is_empty()); // Retreive receipts before timestamp - assert!(in_memory_context + assert!(context .retrieve_receipts_upto_timestamp(receipt_timestamps[3]) .await .is_ok()); assert!( - in_memory_context + context .retrieve_receipts_upto_timestamp(receipt_timestamps[3]) .await .unwrap() @@ -158,21 +135,18 @@ async fn multi_receipt_adapter_test( ); // Remove all receipts with one call - assert!(in_memory_context + assert!(context .remove_receipts_by_ids(receipt_ids.as_slice()) .await .is_ok()); // Removal should no longer be valid - assert!(in_memory_context + assert!(context .remove_receipts_by_ids(receipt_ids.as_slice()) .await .is_err()); // Retrieval should be invalid for receipt_id in receipt_ids { - assert!(in_memory_context - .retrieve_receipt_by_id(receipt_id) - .await - .is_err()); + assert!(context.retrieve_receipt_by_id(receipt_id).await.is_err()); } } diff --git a/tap_core/tests/received_receipt_test.rs b/tap_core/tests/received_receipt_test.rs index 4637365d..5d903159 100644 --- a/tap_core/tests/received_receipt_test.rs +++ b/tap_core/tests/received_receipt_test.rs @@ -62,14 +62,14 @@ fn domain_separator() -> Eip712Domain { } struct ContextFixture { - in_memory_context: InMemoryContext, + context: InMemoryContext, escrow_storage: EscrowStorage, query_appraisals: QueryAppraisals, checks: Vec, } #[fixture] -fn in_memory_context( +fn context( domain_separator: Eip712Domain, allocation_ids: Vec
, sender_ids: Vec
, @@ -81,7 +81,7 @@ fn in_memory_context( let query_appraisals = Arc::new(RwLock::new(HashMap::new())); let timestamp_check = Arc::new(TimestampCheck::new(0)); - let in_memory_context = InMemoryContext::new( + let context = InMemoryContext::new( rav_storage, receipt_storage.clone(), escrow_storage.clone(), @@ -97,7 +97,7 @@ fn in_memory_context( checks.push(timestamp_check); ContextFixture { - in_memory_context, + context, escrow_storage, query_appraisals, checks, @@ -110,14 +110,14 @@ async fn partial_then_full_check_valid_receipt( keys: (LocalWallet, Address), domain_separator: Eip712Domain, allocation_ids: Vec
, - in_memory_context: ContextFixture, + context: ContextFixture, ) { let ContextFixture { checks, escrow_storage, query_appraisals, .. - } = in_memory_context; + } = context; let query_value = 20u128; let signed_receipt = EIP712SignedMessage::new( @@ -152,15 +152,15 @@ async fn partial_then_finalize_valid_receipt( keys: (LocalWallet, Address), allocation_ids: Vec
, domain_separator: Eip712Domain, - in_memory_context: ContextFixture, + context: ContextFixture, ) { let ContextFixture { checks, - in_memory_context, + context, escrow_storage, query_appraisals, .. - } = in_memory_context; + } = context; let query_value = 20u128; let signed_receipt = EIP712SignedMessage::new( @@ -189,7 +189,7 @@ async fn partial_then_finalize_valid_receipt( let awaiting_escrow_receipt = awaiting_escrow_receipt.unwrap(); let receipt = awaiting_escrow_receipt - .check_and_reserve_escrow(&in_memory_context, &domain_separator) + .check_and_reserve_escrow(&context, &domain_separator) .await; assert!(receipt.is_ok()); } @@ -200,15 +200,15 @@ async fn standard_lifetime_valid_receipt( keys: (LocalWallet, Address), allocation_ids: Vec
, domain_separator: Eip712Domain, - in_memory_context: ContextFixture, + context: ContextFixture, ) { let ContextFixture { checks, - in_memory_context, + context, escrow_storage, query_appraisals, .. - } = in_memory_context; + } = context; let query_value = 20u128; let signed_receipt = EIP712SignedMessage::new( @@ -238,7 +238,7 @@ async fn standard_lifetime_valid_receipt( let awaiting_escrow_receipt = awaiting_escrow_receipt.unwrap(); let receipt = awaiting_escrow_receipt - .check_and_reserve_escrow(&in_memory_context, &domain_separator) + .check_and_reserve_escrow(&context, &domain_separator) .await; assert!(receipt.is_ok()); } diff --git a/tap_integration_tests/tests/indexer_mock.rs b/tap_integration_tests/tests/indexer_mock.rs index 15c264b9..bad03eca 100644 --- a/tap_integration_tests/tests/indexer_mock.rs +++ b/tap_integration_tests/tests/indexer_mock.rs @@ -59,7 +59,7 @@ where { pub fn new( domain_separator: Eip712Domain, - in_memory_context: E, + context: E, required_checks: Checks, threshold: u64, aggregate_server_address: String, @@ -68,7 +68,7 @@ where Ok(Self { manager: Arc::new(Manager::::new( domain_separator, - in_memory_context, + context, required_checks, )), receipt_count: Arc::new(AtomicU64::new(0)), @@ -133,7 +133,7 @@ where pub async fn run_server( port: u16, // Port on which the server will listen domain_separator: Eip712Domain, // EIP712 domain separator - in_memory_context: E, // in_memory_context instance + context: E, // context instance required_checks: Checks, // Vector of required checks to be performed on each request threshold: u64, // The count at which a RAV request will be triggered aggregate_server_address: String, // Address of the aggregator server @@ -160,7 +160,7 @@ where println!("Listening on: {}", addr); let rpc_manager = RpcManager::new( domain_separator, - in_memory_context, + context, required_checks, threshold, aggregate_server_address, diff --git a/tap_integration_tests/tests/showcase.rs b/tap_integration_tests/tests/showcase.rs index 654e5791..9bfe4b13 100644 --- a/tap_integration_tests/tests/showcase.rs +++ b/tap_integration_tests/tests/showcase.rs @@ -168,12 +168,12 @@ fn query_appraisals(query_price: &[u128]) -> QueryAppraisals { } struct ContextFixture { - in_memory_context: InMemoryContext, + context: InMemoryContext, checks: Checks, } #[fixture] -fn in_memory_context( +fn context( domain_separator: Eip712Domain, allocation_ids: Vec
, sender_ids: Vec
, @@ -183,7 +183,7 @@ fn in_memory_context( let escrow_storage = Arc::new(RwLock::new(HashMap::new())); let rav_storage = Arc::new(RwLock::new(None)); let timestamp_check = Arc::new(TimestampCheck::new(0)); - let in_memory_context = InMemoryContext::new( + let context = InMemoryContext::new( rav_storage, receipt_storage.clone(), escrow_storage.clone(), @@ -198,20 +198,17 @@ fn in_memory_context( let checks = Checks::new(checks); - ContextFixture { - in_memory_context, - checks, - } + ContextFixture { context, checks } } #[fixture] -fn indexer_1_context(in_memory_context: ContextFixture) -> ContextFixture { - in_memory_context +fn indexer_1_context(context: ContextFixture) -> ContextFixture { + context } #[fixture] -fn indexer_2_context(in_memory_context: ContextFixture) -> ContextFixture { - in_memory_context +fn indexer_2_context(context: ContextFixture) -> ContextFixture { + context } // Helper fixture to generate a batch of receipts to be sent to the Indexer. @@ -372,13 +369,10 @@ async fn single_indexer_test_server( http_max_concurrent_connections, ) .await?; - let ContextFixture { - in_memory_context, - checks, - } = indexer_1_context; + let ContextFixture { context, checks } = indexer_1_context; let (indexer_handle, indexer_addr) = start_indexer_server( domain_separator.clone(), - in_memory_context, + context, sender_id, available_escrow, checks, @@ -423,12 +417,12 @@ async fn two_indexers_test_servers( ) .await?; let ContextFixture { - in_memory_context: in_memory_1, + context: in_memory_1, checks: checks_1, } = indexer_1_context; let ContextFixture { - in_memory_context: in_memory_2, + context: in_memory_2, checks: checks_2, } = indexer_2_context; @@ -485,14 +479,12 @@ async fn single_indexer_wrong_sender_test_server( ) .await?; let ContextFixture { - in_memory_context, - checks, - .. + context, checks, .. } = indexer_1_context; let (indexer_handle, indexer_addr) = start_indexer_server( domain_separator.clone(), - in_memory_context, + context, sender_id, available_escrow, checks, @@ -819,7 +811,7 @@ fn generate_requests( // Start-up a mock Indexer. Requires a Sender Aggregator to be running. async fn start_indexer_server( domain_separator: Eip712Domain, - mut in_memory_context: InMemoryContext, + mut context: InMemoryContext, sender_id: Address, available_escrow: u128, required_checks: Checks, @@ -831,13 +823,13 @@ async fn start_indexer_server( listener.local_addr()?.port() }; - in_memory_context.increase_escrow(sender_id, available_escrow); + context.increase_escrow(sender_id, available_escrow); let aggregate_server_address = "http://".to_string() + &agg_server_addr.to_string(); let (server_handle, socket_addr) = indexer_mock::run_server( http_port, domain_separator, - in_memory_context.with_sender_address(sender_id), + context.with_sender_address(sender_id), required_checks, receipt_threshold, aggregate_server_address, From 21e473921a911b73f1bf439d39fe09162a2c11d3 Mon Sep 17 00:00:00 2001 From: Gustavo Inacio Date: Mon, 11 Mar 2024 14:27:11 -0300 Subject: [PATCH 09/11] chore: remove unused dev deps Signed-off-by: Gustavo Inacio --- tap_core/Cargo.toml | 2 -- 1 file changed, 2 deletions(-) diff --git a/tap_core/Cargo.toml b/tap_core/Cargo.toml index 1b2dce41..48b891aa 100644 --- a/tap_core/Cargo.toml +++ b/tap_core/Cargo.toml @@ -27,8 +27,6 @@ tokio = { version = "1.29.1", features = ["macros", "rt-multi-thread"] } [dev-dependencies] criterion = { version = "0.5", features = ["async_std"] } -tap_aggregator = { version = "0.2.0", path = "../tap_aggregator" } -jsonrpsee = { version = "0.18.0", features = ["http-client", "server"] } [features] From 4cc0f7e979b43492ec44dcb4b5f360aabe012ed9 Mon Sep 17 00:00:00 2001 From: Gustavo Inacio Date: Mon, 11 Mar 2024 14:45:30 -0300 Subject: [PATCH 10/11] docs: update context description in manager Signed-off-by: Gustavo Inacio --- tap_core/src/manager/tap_manager.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tap_core/src/manager/tap_manager.rs b/tap_core/src/manager/tap_manager.rs index ab5ecf61..d5c9cf99 100644 --- a/tap_core/src/manager/tap_manager.rs +++ b/tap_core/src/manager/tap_manager.rs @@ -14,7 +14,7 @@ use crate::{ }; pub struct Manager { - /// Context that implements strategies + /// Context that implements adapters context: E, /// Checks that must be completed for each receipt before being confirmed or denied for rav request From 351cf4535269c05a39252f2f4348a53aea050d34 Mon Sep 17 00:00:00 2001 From: Gustavo Inacio Date: Mon, 11 Mar 2024 14:59:58 -0300 Subject: [PATCH 11/11] chore: add licence headers Signed-off-by: Gustavo Inacio --- tap_core/src/manager/context/mod.rs | 3 +++ tap_core/src/receipt/error.rs | 3 +++ 2 files changed, 6 insertions(+) diff --git a/tap_core/src/manager/context/mod.rs b/tap_core/src/manager/context/mod.rs index eb291915..b963976f 100644 --- a/tap_core/src/manager/context/mod.rs +++ b/tap_core/src/manager/context/mod.rs @@ -1 +1,4 @@ +// Copyright 2023-, Semiotic AI, Inc. +// SPDX-License-Identifier: Apache-2.0 + pub mod memory; diff --git a/tap_core/src/receipt/error.rs b/tap_core/src/receipt/error.rs index 5e3de046..1ad01a41 100644 --- a/tap_core/src/receipt/error.rs +++ b/tap_core/src/receipt/error.rs @@ -1,3 +1,6 @@ +// Copyright 2023-, Semiotic AI, Inc. +// SPDX-License-Identifier: Apache-2.0 + use alloy_primitives::Address; use serde::{Deserialize, Serialize};