Skip to content

Commit 4ebf258

Browse files
committed
docs!: create docs and readme.
update the modules for better visibility and documentation Signed-off-by: Gustavo Inacio <[email protected]>
1 parent 4b83a3a commit 4ebf258

File tree

26 files changed

+509
-230
lines changed

26 files changed

+509
-230
lines changed

README.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,48 @@
11
# Timeline Aggregation Protocol (TAP)
2+
3+
## Overview
4+
5+
The TAP (Timeline Aggregation Protocol) facilitates a series of payments from a sender to a receiver, who aggregates these payments into a single payment. This aggregate payment can then be verified on-chain by a payment verifier, reducing the number of transactions and simplifying the payment process.
6+
7+
## Key Components
8+
9+
- **Sender:** Initiates the payment.
10+
- **Receiver:** Receives the payment.
11+
- **Signers:** Multiple signers authorized by the sender to sign receipts.
12+
- **State Channel:** A one-way channel opened by the sender with the receiver for sending receipts.
13+
- **Receipt:** A record of payment sent by the sender to the receiver.
14+
- **ReceiptAggregateVoucher (RAV):** A signed message containing the aggregate value of the receipts.
15+
- **tap_aggregator:** An entity managed by the sender that signs RAV requests.
16+
- **EscrowAccount:** An account created in the blockchain to hold funds for the sender-receiver pair.
17+
18+
## Security Measures
19+
20+
- The protocol uses asymmetric cryptography to sign and verify messages, ensuring the integrity of receipts and RAVs.
21+
22+
## Process
23+
24+
1. **Opening a State Channel:** A state channel is opened via a blockchain contract, creating an EscrowAccount for the sender-receiver pair.
25+
2. **Sending Receipts:** The sender sends receipts to the receiver through the state channel.
26+
3. **Storing Receipts:** The receiver stores the receipts and tracks the aggregate payment.
27+
4. **Creating a RAV Request:** A RAV request consists of a list of receipts and, optionally, the previous RAV.
28+
5. **Signing the RAV:** The receiver sends the RAV request to the tap_aggregator, which signs it into a RAV.
29+
6. **Tracking Aggregate Value:** The receiver tracks the aggregate value and new receipts since the last RAV.
30+
7. **Requesting a New RAV:** The receiver sends new receipts and the last RAV to the tap_aggregator for a new RAV.
31+
8. **Closing the State Channel:** When the allocation period ends, the receiver can send the last RAV to the blockchain and receive payment from the EscrowAccount.
32+
33+
## Performance Considerations
34+
35+
- The primary performance limitations are the time required to verify receipts and network limitations for sending requests to the tap_aggregator.
36+
37+
## Use Cases
38+
39+
- The TAP protocol is suitable for systems with sequential operations that are too expensive to redeem individually on-chain. By aggregating operations and redeeming them in one transaction, costs can be reduced.
40+
41+
## Compatibility
42+
43+
- The current implementation is for EVM-compatible blockchains, with most of the system being off-chain.
44+
45+
## Contributing
46+
47+
Contributions are welcome! Please submit a pull request or open an issue to discuss potential changes.
48+
Also, make sure to follow the [Contributing Guide](CONTRIBUTING.md).

tap_core/src/error.rs

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,54 +11,75 @@ use ethers_core::types::SignatureError;
1111
use std::result::Result as StdResult;
1212
use thiserror::Error as ThisError;
1313

14+
/// Error type for the TAP protocol
1415
#[derive(ThisError, Debug)]
1516
pub enum Error {
17+
/// Error when trying to aggregate receipts and the result overflows
1618
#[error("Aggregating receipt results in overflow")]
1719
AggregateOverflow,
18-
#[error("Failed to encode to EIP712 hash:\n{source_error_message}")]
19-
EIP712EncodeError { source_error_message: String },
20-
#[error(
21-
"Unexpected check: \"{check_string}\". Only checks provided in initial checklist are valid"
22-
)]
23-
InvalidCheckError { check_string: String },
24-
#[error("The requested action is invalid for current receipt state: {state}")]
25-
InvalidStateForRequestedAction { state: String },
20+
/// Error when Rust fails to get the current system time
2621
#[error("Failed to get current system time: {source_error_message} ")]
2722
InvalidSystemTime { source_error_message: String },
23+
/// `ethers` wallet error
2824
#[error(transparent)]
2925
WalletError(#[from] WalletError),
26+
/// Error when signature verification fails
3027
#[error(transparent)]
3128
SignatureError(#[from] SignatureError),
32-
#[error("Recovered sender address invalid {address}")]
33-
InvalidRecoveredSigner { address: Address },
29+
30+
/// Error when the received RAV does not match the expected RAV
3431
#[error("Received RAV does not match expexted RAV")]
3532
InvalidReceivedRAV {
3633
received_rav: ReceiptAggregateVoucher,
3734
expected_rav: ReceiptAggregateVoucher,
3835
},
36+
/// Generic error from the adapter
3937
#[error("Error from adapter.\n Caused by: {source_error}")]
4038
AdapterError { source_error: anyhow::Error },
39+
/// Error when no valid receipts are found for a RAV request
4140
#[error("Failed to produce rav request, no valid receipts")]
4241
NoValidReceiptsForRAVRequest,
42+
43+
/// Error when the previous RAV allocation id does not match the allocation id from the new receipt
4344
#[error("Previous RAV allocation id ({prev_id}) doesn't match the allocation id from the new receipt ({new_id}).")]
4445
RavAllocationIdMismatch { prev_id: String, new_id: String },
46+
47+
/// Error when all receipts do not have the same allocation id
48+
///
49+
/// Used in tap_aggregator
4550
#[error("All receipts should have the same allocation id, but they don't")]
4651
RavAllocationIdNotUniform,
52+
/// Error when the receipt signature is duplicated.
53+
///
54+
/// Used in tap_aggregator
4755
#[error("Duplicate receipt signature: {0}")]
4856
DuplicateReceiptSignature(String),
4957
#[error(
5058
"Receipt timestamp ({receipt_ts}) is less or equal than previous rav timestamp ({rav_ts})"
5159
)]
5260
ReceiptTimestampLowerThanRav { rav_ts: u64, receipt_ts: u64 },
61+
62+
63+
/// Error when the min timestamp is greater than the max timestamp
64+
/// Used by [`crate::manager::Manager::create_rav_request()`]
5365
#[error("Timestamp range error: min_timestamp_ns: {min_timestamp_ns}, max_timestamp_ns: {max_timestamp_ns}. Adjust timestamp buffer.")]
5466
TimestampRangeError {
5567
min_timestamp_ns: u64,
5668
max_timestamp_ns: u64,
5769
},
5870

71+
/// Error on the receipt side
5972
#[error("Receipt error: {0}")]
6073
ReceiptError(#[from] ReceiptError),
6174

75+
76+
/// Error when the recovered signer address is invalid
77+
/// Used by [`crate::manager::adapters::EscrowHandler`]
78+
#[error("Recovered sender address invalid {address}")]
79+
InvalidRecoveredSigner { address: Address },
80+
81+
/// Indicates a failure while verifying the signer
82+
/// Used by [`crate::manager::adapters::EscrowHandler`]
6283
#[error("Failed to check the signer: {0}")]
6384
FailedToVerifySigner(String),
6485
}

tap_core/src/lib.rs

Lines changed: 85 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,74 @@
11
// Copyright 2023-, Semiotic AI, Inc.
22
// SPDX-License-Identifier: Apache-2.0
33

4-
//! The Timeline Aggregation Protocol (TAP) is a micro-trust
5-
//! state channel payment solution allowing one-way payments
6-
//! from a payment sender to be aggregated then cheaply
7-
//! verified on-chain by a payment receiver.
4+
5+
//! # Timeline Aggregation Protocol
6+
//!
7+
//! ## Overview
8+
//!
9+
//! The TAP (Timeline Aggregation Protocol) facilitates a series of payments from
10+
//! a sender to a receiver, who aggregates these payments into a single payment.
11+
//! This aggregate payment can then be verified on-chain by a payment verifier,
12+
//! reducing the number of transactions and simplifying the payment process.
13+
//!
14+
//! ## Key Components
15+
//!
16+
//! - **Sender:** Initiates the payment.
17+
//! - **Receiver:** Receives the payment.
18+
//! - **Signers:** Multiple signers authorized by the sender to sign receipts.
19+
//! - **State Channel:** A one-way channel opened by the sender with the receiver
20+
//! for sending receipts.
21+
//! - **Receipt:** A record of payment sent by the sender to the receiver.
22+
//! - **ReceiptAggregateVoucher (RAV):** A signed message containing the aggregate
23+
//! value of the receipts.
24+
//! - **tap_aggregator:** An entity managed by the sender that signs RAV requests.
25+
//! - **EscrowAccount:** An account created in the blockchain to hold funds for
26+
//! the sender-receiver pair.
27+
//!
28+
//! ## Security Measures
29+
//!
30+
//! - The protocol uses asymmetric cryptography to sign and verify messages,
31+
//! ensuring the integrity of receipts and RAVs.
32+
//!
33+
//! ## Process
34+
//!
35+
//! 1. **Opening a State Channel:** A state channel is opened via a blockchain
36+
//! contract, creating an EscrowAccount for the sender-receiver pair.
37+
//! 2. **Sending Receipts:** The sender sends receipts to the receiver through
38+
//! the state channel.
39+
//! 3. **Storing Receipts:** The receiver stores the receipts and tracks the
40+
//! aggregate payment.
41+
//! 4. **Creating a RAV Request:** A RAV request consists of a list of receipts
42+
//! and, optionally, the previous RAV.
43+
//! 5. **Signing the RAV:** The receiver sends the RAV request to the
44+
//! tap_aggregator, which signs it into a RAV.
45+
//! 6. **Tracking Aggregate Value:** The receiver tracks the aggregate value and
46+
//! new receipts since the last RAV.
47+
//! 7. **Requesting a New RAV:** The receiver sends new receipts and the last
48+
//! RAV to the tap_aggregator for a new RAV.
49+
//! 8. **Closing the State Channel:** When the allocation period ends, the receiver
50+
//! can send the last RAV to the blockchain and receive payment from the EscrowAccount.
51+
//!
52+
//! ## Performance Considerations
53+
//!
54+
//! - The primary performance limitations are the time required to verify receipts
55+
//! and network limitations for sending requests to the tap_aggregator.
56+
//!
57+
//! ## Use Cases
58+
//!
59+
//! - The TAP protocol is suitable for systems with sequential operations that
60+
//! are too expensive to redeem individually on-chain. By aggregating operations
61+
//! and redeeming them in one transaction, costs can be reduced.
62+
//!
63+
//! ## Compatibility
64+
//!
65+
//! - The current implementation is for EVM-compatible blockchains, with most
66+
//! of the system being off-chain.
67+
//!
68+
//! ## Getting started
69+
//!
70+
//! To get started with the TAP protocol, take a look on the [`manager`] module
71+
//! to see how to manage the state channel and implement the needed adapters.
872
973
use std::time::{SystemTime, UNIX_EPOCH};
1074

@@ -17,7 +81,8 @@ pub mod rav;
1781
pub mod receipt;
1882
pub mod signed_message;
1983

20-
pub use error::{Error, Result};
84+
pub use error::Error;
85+
use error::Result;
2186

2287
fn get_current_timestamp_u64_ns() -> Result<u64> {
2388
Ok(SystemTime::now()
@@ -28,6 +93,21 @@ fn get_current_timestamp_u64_ns() -> Result<u64> {
2893
.as_nanos() as u64)
2994
}
3095

96+
/// The EIP712 domain separator builder for the TAP protocol.
97+
///
98+
/// This is the current domain separator that is used for the [EIP712](https://eips.ethereum.org/EIPS/eip-712) signature scheme.
99+
///
100+
///
101+
/// It's used to validate the signature of the `ReceiptAggregateVoucher` and `Receipt` structs.
102+
///
103+
/// You can take a look on deployed [TAPVerfiers](https://github.com/semiotic-ai/timeline-aggregation-protocol-contracts/blob/4dc87fc616680c924b99dbaf285bdd449c777261/src/TAPVerifier.sol)
104+
/// contracts [here](https://github.com/semiotic-ai/timeline-aggregation-protocol-contracts/blob/4dc87fc616680c924b99dbaf285bdd449c777261/addresses.json)
105+
///
106+
/// The domain separator is defined as:
107+
/// - `name`: "TAP"
108+
/// - `version`: "1"
109+
/// - `chain_id`: The chain ID of the chain where the domain separator is deployed.
110+
/// - `verifying_contract`: The address of the contract that is verifying the signature.
31111
pub fn tap_eip712_domain(
32112
chain_id: u64,
33113
verifying_contract_address: alloy_primitives::Address,

tap_core/src/manager/adapters/escrow.rs

Lines changed: 8 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -7,33 +7,15 @@ use async_trait::async_trait;
77

88
use crate::{
99
rav::SignedRAV,
10-
receipt::{AwaitingReserve, ReceiptError, ReceiptResult, ReceiptWithState},
10+
receipt::{state::AwaitingReserve, ReceiptError, ReceiptResult, ReceiptWithState},
1111
Error,
1212
};
1313

14-
/// `EscrowAdapter` defines a trait for adapters to handle escrow related operations.
15-
///
16-
/// This trait is designed to be implemented by users of this library who want to
17-
/// customize the management of local accounting for available escrow. The error handling is also
18-
/// customizable by defining an `AdapterError` type, which must implement both `Error`
19-
/// and `Debug` from the standard library.
20-
///
21-
/// # Usage
22-
///
23-
/// The `get_available_escrow` method should be used to retrieve the local accounting
24-
/// amount of available escrow for a specified sender. Any errors during this operation
25-
/// should be captured and returned in the `AdapterError` format.
26-
///
27-
/// The `subtract_escrow` method is used to deduct a specified value from the local accounting
28-
/// of available escrow of a specified sender. Any errors during this operation should be captured
29-
/// and returned as an `AdapterError`.
30-
///
31-
/// This trait is utilized by [crate::tap_manager], which relies on these
32-
/// operations for managing escrow.
14+
/// Manages the escrow operations
3315
///
3416
/// # Example
3517
///
36-
/// For example code see [crate::adapters::escrow_adapter_mock]
18+
/// For example code see [crate::manager::context::memory::EscrowStorage]
3719
3820
#[async_trait]
3921
pub trait EscrowHandler: Send + Sync {
@@ -44,25 +26,21 @@ pub trait EscrowHandler: Send + Sync {
4426
type AdapterError: std::error::Error + std::fmt::Debug + Send + Sync + 'static;
4527

4628
/// Retrieves the local accounting amount of available escrow for a specified sender.
47-
///
48-
/// This method should be implemented to fetch the local accounting amount of available escrow for a
49-
/// specified sender from your system. Any errors that occur during this process should
50-
/// be captured and returned as an `AdapterError`.
5129
async fn get_available_escrow(&self, sender_id: Address) -> Result<u128, Self::AdapterError>;
5230

5331
/// Deducts a specified value from the local accounting of available escrow for a specified sender.
54-
///
55-
/// This method should be implemented to deduct a specified value from the local accounting of
56-
/// available escrow of a specified sender in your system. Any errors that occur during this
57-
/// process should be captured and returned as an `AdapterError`.
5832
async fn subtract_escrow(
5933
&self,
6034
sender_id: Address,
6135
value: u128,
6236
) -> Result<(), Self::AdapterError>;
6337

38+
/// Verifies the signer of the receipt
39+
///
40+
/// Used by [`Self::check_rav_signature`] to verify the signer of the receipt
6441
async fn verify_signer(&self, signer_address: Address) -> Result<bool, Self::AdapterError>;
6542

43+
/// Checks and reserves escrow for the received receipt
6644
async fn check_and_reserve_escrow(
6745
&self,
6846
received_receipt: &ReceiptWithState<AwaitingReserve>,
@@ -87,6 +65,7 @@ pub trait EscrowHandler: Send + Sync {
8765
Ok(())
8866
}
8967

68+
/// Checks the signature of the RAV
9069
async fn check_rav_signature(
9170
&self,
9271
signed_rav: &SignedRAV,

tap_core/src/manager/adapters/mod.rs

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,11 @@
11
// Copyright 2023-, Semiotic AI, Inc.
22
// SPDX-License-Identifier: Apache-2.0
33

4-
//! The adapters module provides interfaces that allow flexibility in storing and verifying TAP components.
4+
//! Context adapters for the TAP manager.
55
//!
66
//! Each adapter should be defined by the user of the library based on their specific storage and verification requirements. This modular design
77
//! allows for easy integration with various storage solutions and verification procedures, thereby making the library adaptable to a wide range
88
//! of use cases.
9-
//!
10-
//! The following adapters are defined:
11-
//! - `escrow_adapter`: An interface for checking and updating escrow availability.
12-
//! - `rav_storage_adapter`: An interface for storing and retrieving/replacing RAVs.
13-
//! - `receipt_checks_adapter`: An interface for verifying TAP receipts.
14-
//! - `receipt_storage_adapter`: An interface for storing, retrieving, updating, and removing TAP receipts.
15-
//!
16-
//! In addition, this module also includes mock implementations of each adapter for testing and example purposes.
179
1810
mod escrow;
1911
mod rav;

0 commit comments

Comments
 (0)