Skip to main content

ant_protocol/
lib.rs

1//! # ant-protocol
2//!
3//! Wire protocol for the Autonomi decentralized network (`WithAutonomi` fork).
4//!
5//! This crate is the contract between `ant-client` and `ant-node`:
6//! wire message types, serialization, content addressing, and the
7//! pure-verification halves of the post-quantum signing scheme. Both
8//! crates depend on `ant-protocol` and on nothing else from each other.
9//!
10//! ## Scope
11//!
12//! - [`chunk`] — chunk request/response messages, protocol constants,
13//!   `ProtocolError`, close-group sizing, proof-type tag bytes.
14//! - [`data_types`] — pure helpers on 32-byte addresses (`compute_address`,
15//!   `xor_distance`, `peer_id_to_xor_name`) and `DataChunk`.
16//! - [`chunk_protocol`] — a shared "subscribe → send → poll" helper
17//!   [`chunk_protocol::send_and_await_chunk_response`] that both the
18//!   client and node test harness use to exchange chunk messages on
19//!   a `saorsa-core::P2PNode`.
20//! - [`payment`] — on-wire payment artifacts: `PaymentProof`,
21//!   `SingleNodePayment` (with `pay` and `verify` co-located), and
22//!   ML-DSA-65 verification of quotes and merkle candidates.
23//!
24//! ## What is **not** here
25//!
26//! - Quote generation and node-side signing keys (stay in `ant-node`).
27//! - On-chain verification cache and payment verifier state machine
28//!   (stay in `ant-node`).
29//! - `LocalDevnet` and node process management (stay in `ant-client`
30//!   and `ant-node` respectively).
31//!
32//! ## Logging
33//!
34//! The `logging` feature re-exports [`tracing`] macros. When disabled
35//! the macros become no-ops with zero runtime cost.
36
37#![deny(unsafe_code)]
38#![warn(missing_docs)]
39#![warn(clippy::all)]
40#![warn(clippy::pedantic)]
41// Variables used only inside log macros become unused when `logging` is off.
42#![cfg_attr(not(feature = "logging"), allow(unused_variables, unused_assignments))]
43
44pub mod chunk;
45#[cfg(feature = "native")]
46pub mod chunk_protocol;
47pub mod data_types;
48pub mod devnet_manifest;
49pub mod error;
50pub mod logging;
51pub mod payment;
52pub mod pointer;
53
54// =============================================================================
55// Public surface re-exports
56// =============================================================================
57
58pub use chunk::{
59    advertises_get_or_closer, client_update_required_message, settlement_compatibility,
60    ChunkGetOrCloserRequest, ChunkGetOrCloserResponse, ChunkGetRequest, ChunkGetResponse,
61    ChunkMessage, ChunkMessageBody, ChunkPutRequest, ChunkPutResponse, ChunkQuoteRequest,
62    ChunkQuoteRequestV2, ChunkQuoteResponse, MerkleCandidateQuoteRequest,
63    MerkleCandidateQuoteRequestV2, MerkleCandidateQuoteResponse, PointerGetRequest,
64    PointerGetResponse, PointerPutRequest, PointerPutResponse, ProtocolError,
65    SettlementCompatibility, XorName, CHUNK_PROTOCOL_ID, CLOSE_GROUP_MAJORITY, CLOSE_GROUP_SIZE,
66    CURRENT_SETTLEMENT_VERSION, DATA_TYPE_CHUNK, GET_OR_CLOSER_AGENT_TOKEN, MAX_CHUNK_SIZE,
67    MAX_WIRE_MESSAGE_SIZE, MIN_SUPPORTED_SETTLEMENT_VERSION, PROOF_TAG_MERKLE,
68    PROOF_TAG_SINGLE_NODE, PROTOCOL_VERSION, XORNAME_LEN,
69};
70#[cfg(feature = "native")]
71pub use chunk_protocol::{
72    send_and_await_chunk_response, send_and_await_chunk_response_with_metadata,
73    ChunkProtocolResponse,
74};
75pub use data_types::{compute_address, peer_id_to_xor_name, xor_distance, ChunkStats, DataChunk};
76pub use devnet_manifest::{DevnetEvmInfo, DevnetManifest};
77pub use error::{Error, Result};
78pub use payment::{
79    deserialize_merkle_proof, deserialize_proof, detect_proof_type, serialize_merkle_proof,
80    serialize_single_node_proof, verify_merkle_candidate_signature, verify_quote_content,
81    verify_quote_signature, PaymentProof, ProofType, QuotePaymentInfo, SingleNodePayment,
82};
83pub use pointer::{
84    pointer_address, state_id_for_body, ParsedPointer, Pointer, PointerError, PointerState,
85    PointerTarget, PointerTargetKind, DATA_TYPE_POINTER, FINAL_COUNTER, POINTER_BODY_LEN,
86    POINTER_FORMAT_VERSION, POINTER_WIRE_LEN, TARGET_WIRE_LEN,
87};
88
89// =============================================================================
90// Transitive-dep re-exports
91//
92// `ant-client` and `ant-node` must compile against the *same* major version
93// of `evmlib`, `saorsa-core`, and `saorsa-pqc`. Re-exporting them here makes
94// `ant-protocol` the single version-pin point: bump the version here and
95// both sides move together. Adding a direct dependency on any of these
96// crates in `ant-client` risks a silent version skew that only manifests
97// at runtime (different `ProofOfPayment` layout, incompatible `P2PNode`
98// behaviours, etc.).
99//
100// These modules hold only `pub use` — no code of our own. They exist as
101// a policy gate, not an abstraction.
102// =============================================================================
103
104/// EVM payment primitives re-exported from [`evmlib`].
105///
106/// Use `ant_protocol::evm::…` in downstream crates instead of a direct
107/// `evmlib` dependency. This guarantees client and node always link the
108/// same `evmlib` major version.
109pub mod evm {
110    pub use evmlib::common::{Address, Amount, QuoteHash, TxHash, U256};
111    pub use evmlib::merkle_batch_payment::PoolCommitment;
112    pub use evmlib::merkle_payments::{
113        MerklePaymentCandidateNode, MerklePaymentCandidatePool, MerklePaymentProof,
114        MerklePaymentVerificationError, MerkleTree, MidpointProof, CANDIDATES_PER_POOL, MAX_LEAVES,
115        MERKLE_PAYMENT_EXPIRATION,
116    };
117    #[cfg(feature = "native")]
118    pub use evmlib::wallet::journal;
119    #[cfg(feature = "rpc")]
120    pub use evmlib::wallet::{PayForQuotesError, Wallet};
121    pub use evmlib::{
122        CustomNetwork, EncodedPeerId, Network, PaymentQuote, ProofOfPayment, RewardsAddress,
123    };
124
125    /// Anvil-backed testnet used by devnets and E2E tests.
126    ///
127    /// Exposed so downstream `LocalDevnet` wrappers and test harnesses
128    /// don't need a direct `evmlib` dep just for the Anvil bindings.
129    #[cfg(feature = "native")]
130    pub mod testnet {
131        pub use evmlib::testnet::Testnet;
132    }
133
134    /// Lower-level `evmlib` surface (RPC provider, contract interface,
135    /// and payment-vault bindings). Re-exported for the node's verifier
136    /// and the Anvil-based tests; most client code will not need these.
137    #[cfg(feature = "rpc")]
138    pub mod contract {
139        pub use evmlib::contract::payment_vault;
140    }
141
142    /// HTTP provider + transaction-config helpers used by on-chain
143    /// verification flows.
144    #[cfg(feature = "rpc")]
145    pub mod utils {
146        pub use evmlib::transaction_config::TransactionConfig;
147        pub use evmlib::utils::{dummy_address, dummy_hash, http_provider};
148    }
149}
150
151/// Saorsa transport primitives re-exported from [`saorsa_core`].
152///
153/// Use `ant_protocol::transport::…` in downstream crates instead of a
154/// direct `saorsa-core` dependency.
155pub mod transport {
156    /// Browser RPC capability requiring owner-signed V2 address records.
157    /// This does not select native DHT protocols; native peers send both versions.
158    pub const ADDRESS_V2_CAPABILITY: &str = "addr-v2";
159
160    pub use saorsa_core::client_routing;
161    pub use saorsa_core::dht_lookup::{
162        DEFAULT_ALPHA_VALUE, DEFAULT_K_VALUE, ITERATION_GRACE_TIMEOUT_SECS, LOOKUP_TIMEOUT_SECS,
163    };
164    pub use saorsa_core::identity::{NodeIdentity, PeerId};
165    pub use saorsa_core::signed_address;
166    pub use saorsa_core::{
167        collect_after_first_with_grace, run_iterative_lookup, xor_distance, AddressType, DHTNode,
168        IterativeLookup, KnownReachability, LookupConfig, LookupKey, LookupNode, LookupQuery,
169        LookupQueryOutcome, LookupRunError, LookupTermination, MlDsa65, MultiAddr, ResponderView,
170        TransportAddressRecord, WitnessedCloseGroup,
171    };
172    #[cfg(feature = "native")]
173    pub use saorsa_core::{
174        IPDiversityConfig, NodeConfig as CoreNodeConfig, NodeMode, P2PEvent, P2PNode, PeerRouteKind,
175    };
176}
177
178/// Post-quantum crypto primitives re-exported from [`saorsa_pqc`].
179///
180/// Both API paths are re-exported:
181/// - `ant_protocol::pqc::ops::*` (lower-level `pqc::*` module) — used
182///   by the node and by this crate's own verification code.
183/// - `ant_protocol::pqc::api::*` (higher-level `api::sig::*` module) —
184///   used by the client's binary-update signature verification.
185pub mod pqc {
186    /// Lower-level `pqc::*` API (types + `MlDsaOperations` trait).
187    pub mod ops {
188        pub use saorsa_pqc::pqc::types::{MlDsaPublicKey, MlDsaSecretKey, MlDsaSignature};
189        pub use saorsa_pqc::pqc::MlDsaOperations;
190    }
191
192    /// Higher-level `api::sig::*` API (used for release signatures).
193    pub mod api {
194        pub use saorsa_pqc::api::sig::{
195            ml_dsa_65, MlDsaPublicKey, MlDsaSecretKey, MlDsaSignature, MlDsaVariant,
196        };
197    }
198}