Skip to content

Commit

Permalink
Merge pull request #214 from semiotic-ai/gusinacio/tap-agent-integration
Browse files Browse the repository at this point in the history
Gusinacio/tap agent integration
  • Loading branch information
gusinacio committed Mar 8, 2024
2 parents b577d19 + 2c1bd89 commit 66ec313
Show file tree
Hide file tree
Showing 17 changed files with 302 additions and 682 deletions.
2 changes: 0 additions & 2 deletions tap_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ strum = "0.24.1"
strum_macros = "0.24.3"
async-trait = "0.1.72"
tokio = { version = "1.29.1", features = ["macros", "rt-multi-thread"] }
typetag = "0.2.14"
futures = "0.3.17"

[dev-dependencies]
criterion = { version = "0.5", features = ["async_std"] }
Expand Down
2 changes: 2 additions & 0 deletions tap_core/src/adapters/escrow_adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,6 @@ pub trait EscrowAdapter {
sender_id: Address,
value: u128,
) -> Result<(), Self::AdapterError>;

async fn verify_signer(&self, signer_address: Address) -> Result<bool, Self::AdapterError>;
}
42 changes: 22 additions & 20 deletions tap_core/src/adapters/mock/executor_mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@

use crate::adapters::escrow_adapter::EscrowAdapter;
use crate::adapters::receipt_storage_adapter::{
safe_truncate_receipts, ReceiptRead, ReceiptStore, StoredReceipt,
safe_truncate_receipts, ReceiptDelete, ReceiptRead, ReceiptStore, StoredReceipt,
};
use crate::checks::TimestampCheck;
use crate::eip_712_signed_message::MessageId;
use crate::tap_receipt::ReceivedReceipt;
use crate::{
adapters::rav_storage_adapter::{RAVRead, RAVStore},
Expand All @@ -18,7 +19,7 @@ use std::sync::RwLock;
use std::{collections::HashMap, sync::Arc};

pub type EscrowStorage = Arc<RwLock<HashMap<Address, u128>>>;
pub type QueryAppraisals = Arc<RwLock<HashMap<u64, u128>>>;
pub type QueryAppraisals = Arc<RwLock<HashMap<MessageId, u128>>>;
pub type ReceiptStorage = Arc<RwLock<HashMap<u64, ReceivedReceipt>>>;
pub type RAVStorage = Arc<RwLock<Option<SignedRAV>>>;

Expand All @@ -36,10 +37,9 @@ pub struct ExecutorMock {
rav_storage: RAVStorage,
receipt_storage: ReceiptStorage,
unique_id: Arc<RwLock<u64>>,

sender_escrow_storage: EscrowStorage,

timestamp_check: Arc<TimestampCheck>,
sender_address: Option<Address>,
}

impl ExecutorMock {
Expand All @@ -55,9 +55,15 @@ impl ExecutorMock {
unique_id: Arc::new(RwLock::new(0)),
sender_escrow_storage,
timestamp_check,
sender_address: None,
}
}

pub fn with_sender_address(mut self, sender_address: Address) -> Self {
self.sender_address = Some(sender_address);
self
}

pub async fn retrieve_receipt_by_id(
&self,
receipt_id: u64,
Expand Down Expand Up @@ -139,6 +145,7 @@ impl RAVRead for ExecutorMock {
#[async_trait]
impl ReceiptStore for ExecutorMock {
type AdapterError = AdapterErrorMock;

async fn store_receipt(&self, receipt: ReceivedReceipt) -> Result<u64, Self::AdapterError> {
let mut id_pointer = self.unique_id.write().unwrap();
let id_previous = *id_pointer;
Expand All @@ -147,23 +154,12 @@ impl ReceiptStore for ExecutorMock {
*id_pointer += 1;
Ok(id_previous)
}
async fn update_receipt_by_id(
&self,
receipt_id: u64,
receipt: ReceivedReceipt,
) -> Result<(), Self::AdapterError> {
let mut receipt_storage = self.receipt_storage.write().unwrap();
}

if !receipt_storage.contains_key(&receipt_id) {
return Err(AdapterErrorMock::AdapterError {
error: "Invalid receipt_id".to_owned(),
});
};
#[async_trait]
impl ReceiptDelete for ExecutorMock {
type AdapterError = AdapterErrorMock;

receipt_storage.insert(receipt_id, receipt);
*self.unique_id.write().unwrap() += 1;
Ok(())
}
async fn remove_receipts_in_timestamp_range<R: RangeBounds<u64> + std::marker::Send>(
&self,
timestamp_ns: R,
Expand All @@ -175,7 +171,6 @@ impl ReceiptStore for ExecutorMock {
Ok(())
}
}

#[async_trait]
impl ReceiptRead for ExecutorMock {
type AdapterError = AdapterErrorMock;
Expand Down Expand Up @@ -251,4 +246,11 @@ impl EscrowAdapter for ExecutorMock {
) -> Result<(), Self::AdapterError> {
self.reduce_escrow(sender_id, value)
}

async fn verify_signer(&self, signer_address: Address) -> Result<bool, Self::AdapterError> {
Ok(self
.sender_address
.map(|sender| signer_address == sender)
.unwrap_or(false))
}
}
17 changes: 7 additions & 10 deletions tap_core/src/adapters/receipt_storage_adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,15 @@ pub trait ReceiptStore {
/// 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<u64, Self::AdapterError>;
}

/// Updates a specific `ReceivedReceipt` identified by a unique receipt_id.
#[async_trait]
pub trait ReceiptDelete {
/// Defines the user-specified error type.
///
/// This method should be implemented to update a specific `ReceivedReceipt` identified by a unique
/// receipt_id in your storage system. Any errors that occur during this process should be captured
/// and returned as an `AdapterError`.
async fn update_receipt_by_id(
&self,
receipt_id: u64,
receipt: ReceivedReceipt,
) -> Result<(), Self::AdapterError>;

/// 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;
/// Removes all `ReceivedReceipts` within a specific timestamp range from the storage.
///
/// This method should be implemented to remove all `ReceivedReceipts` within a specific timestamp
Expand Down
64 changes: 10 additions & 54 deletions tap_core/src/adapters/test/receipt_storage_adapter_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@
mod receipt_storage_adapter_unit_test {
use rand::seq::SliceRandom;
use rand::thread_rng;
use std::collections::{HashMap, HashSet};
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::{Arc, RwLock};

use crate::checks::TimestampCheck;
use crate::{
adapters::{executor_mock::ExecutorMock, receipt_storage_adapter::ReceiptStore},
checks::{mock::get_full_list_of_checks, ReceiptCheck},
eip_712_signed_message::EIP712SignedMessage,
tap_eip712_domain,
tap_receipt::{Receipt, ReceivedReceipt},
Expand All @@ -28,45 +27,24 @@ mod receipt_storage_adapter_unit_test {
tap_eip712_domain(1, Address::from([0x11u8; 20]))
}

struct ExecutorFixture {
executor: ExecutorMock,
checks: Vec<ReceiptCheck>,
}

#[fixture]
fn executor_mock(domain_separator: Eip712Domain) -> ExecutorFixture {
fn executor() -> ExecutorMock {
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(
ExecutorMock::new(
rav_storage,
receipt_storage.clone(),
escrow_storage.clone(),
timestamp_check.clone(),
);
let mut checks = get_full_list_of_checks(
domain_separator,
HashSet::new(),
Arc::new(RwLock::new(HashSet::new())),
receipt_storage,
query_appraisals.clone(),
);
checks.push(timestamp_check);

ExecutorFixture { executor, checks }
)
}

#[rstest]
#[tokio::test]
async fn receipt_adapter_test(domain_separator: Eip712Domain, executor_mock: ExecutorFixture) {
let ExecutorFixture {
mut executor,
checks,
} = executor_mock;

async fn receipt_adapter_test(domain_separator: Eip712Domain, mut executor: ExecutorMock) {
let wallet: LocalWallet = MnemonicBuilder::<English>::default()
.phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about")
.build()
Expand All @@ -76,7 +54,6 @@ mod receipt_storage_adapter_unit_test {
Address::from_str("0xabababababababababababababababababababab").unwrap();

// Create receipts
let query_id = 10u64;
let value = 100u128;
let received_receipt = ReceivedReceipt::new(
EIP712SignedMessage::new(
Expand All @@ -85,8 +62,6 @@ mod receipt_storage_adapter_unit_test {
&wallet,
)
.unwrap(),
query_id,
&checks,
);

let receipt_store_result = executor.store_receipt(received_receipt).await;
Expand Down Expand Up @@ -114,13 +89,8 @@ mod receipt_storage_adapter_unit_test {
#[tokio::test]
async fn multi_receipt_adapter_test(
domain_separator: Eip712Domain,
executor_mock: ExecutorFixture,
mut executor: ExecutorMock,
) {
let ExecutorFixture {
mut executor,
checks,
} = executor_mock;

let wallet: LocalWallet = MnemonicBuilder::<English>::default()
.phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about")
.build()
Expand All @@ -131,28 +101,21 @@ mod receipt_storage_adapter_unit_test {

// Create receipts
let mut received_receipts = Vec::new();
for (query_id, value) in (50..60).enumerate() {
for value in 50..60 {
received_receipts.push(ReceivedReceipt::new(
EIP712SignedMessage::new(
&domain_separator,
Receipt::new(allocation_id, value).unwrap(),
&wallet,
)
.unwrap(),
query_id as u64,
&checks,
));
}
let mut receipt_ids = Vec::new();
let mut receipt_timestamps = Vec::new();
for received_receipt in received_receipts {
receipt_ids.push(
executor
.store_receipt(received_receipt.clone())
.await
.unwrap(),
);
receipt_timestamps.push(received_receipt.signed_receipt().message.timestamp_ns)
receipt_timestamps.push(received_receipt.signed_receipt().message.timestamp_ns);
receipt_ids.push(executor.store_receipt(received_receipt).await.unwrap());
}

// Retreive receipts with timestamp
Expand Down Expand Up @@ -205,7 +168,6 @@ mod receipt_storage_adapter_unit_test {
#[test]
fn safe_truncate_receipts_test(
domain_separator: Eip712Domain,
executor_mock: ExecutorFixture,
#[case] input: Vec<u64>,
#[case] limit: u64,
#[case] expected: Vec<u64>,
Expand All @@ -214,7 +176,6 @@ mod receipt_storage_adapter_unit_test {
.phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about")
.build()
.unwrap();
let checks = executor_mock.checks;

// Vec of (id, receipt)
let mut receipts_orig: Vec<(u64, ReceivedReceipt)> = Vec::new();
Expand All @@ -235,13 +196,11 @@ mod receipt_storage_adapter_unit_test {
&wallet,
)
.unwrap(),
i as u64, // Will use that to check the IDs
&checks,
),
));
}

let mut receipts_truncated = receipts_orig.clone();
let mut receipts_truncated = receipts_orig;

// shuffle the input receipts
receipts_truncated.shuffle(&mut thread_rng());
Expand All @@ -259,9 +218,6 @@ mod receipt_storage_adapter_unit_test {
elem_trun.1.signed_receipt().message.timestamp_ns,
*expected_timestamp
);

// Check that the IDs are fine
assert_eq!(elem_trun.0, elem_trun.1.query_id());
}
}
}
Loading

0 comments on commit 66ec313

Please sign in to comment.