Skip to main content

ant_node/
browser.rs

1//! Shared browser-client discovery types.
2//!
3//! These types describe the public read and paid immutable-write capabilities
4//! exposed by browser-enabled nodes. Wallet secrets never form part of these
5//! records: browsers sign EVM transactions locally and send only payment
6//! receipts to nodes.
7
8pub use saorsa_transport::webrtc::{BrowserEndpoint, BrowserPaymentNetwork, WebRtcDirectEndpoint};
9use serde::{Deserialize, Serialize};
10
11/// Version of the local browser bootstrap manifest.
12pub const BROWSER_MANIFEST_VERSION: u16 = 6;
13
14/// A bootstrap node that a browser can authenticate and contact directly.
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16pub struct BrowserBootstrapNode {
17    /// Self-contained browser endpoint for this node.
18    #[serde(flatten)]
19    pub endpoint: BrowserEndpoint,
20}
21
22/// Metadata for immutable content published into a browser-enabled devnet.
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24pub struct BrowserPublicFile {
25    /// Human-readable filename suggested to the browser.
26    pub name: String,
27    /// Address of the publicly stored `MessagePack` `DataMap`.
28    pub address: String,
29    /// Plaintext content length in bytes.
30    pub size: usize,
31    /// MIME type used by the browser when saving the content.
32    pub content_type: String,
33    /// BLAKE3 hash of the fully reconstructed plaintext file.
34    pub blake3: String,
35    /// Size of the publicly stored `MessagePack` `DataMap` chunk.
36    pub data_map_size: usize,
37    /// Resolved root `DataMap` used to reconstruct the file.
38    pub chunks: Vec<BrowserChunkInfo>,
39    /// Minimum number of devnet nodes that admitted every required record.
40    pub replicas: usize,
41}
42
43/// One resolved self-encryption chunk descriptor.
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45pub struct BrowserChunkInfo {
46    /// Zero-based plaintext order.
47    pub index: usize,
48    /// Address of the encrypted chunk stored by nodes.
49    pub dst_hash: String,
50    /// BLAKE3 hash of the plaintext chunk and self-encryption key input.
51    pub src_hash: String,
52    /// Expected plaintext chunk size.
53    pub src_size: usize,
54}
55
56/// Resolve the public payment identity without exposing the verifier's RPC URL.
57#[cfg(any(feature = "webrtc-direct", test))]
58pub(crate) async fn browser_payment_network(
59    network: &evmlib::Network,
60) -> crate::Result<BrowserPaymentNetwork> {
61    let chain_id = match network {
62        evmlib::Network::ArbitrumOne => 42_161,
63        evmlib::Network::ArbitrumSepoliaTest => 421_614,
64        evmlib::Network::Custom(_) => payment_chain_id(network.rpc_url()).await?,
65    };
66    Ok(BrowserPaymentNetwork {
67        chain_id,
68        payment_token_address: format!("{:?}", network.payment_token_address()),
69        payment_vault_address: format!("{:?}", network.payment_vault_address()),
70    })
71}
72
73#[cfg(any(feature = "webrtc-direct", test))]
74async fn payment_chain_id(rpc_url: &reqwest::Url) -> crate::Result<u64> {
75    // Neither provider errors nor response bodies may escape into errors: they
76    // can contain the operator's credentials, API keys, or internal addresses.
77    let unavailable = || {
78        crate::Error::Config(
79            "could not resolve the custom EVM chain ID for browser payment metadata".to_string(),
80        )
81    };
82    let invalid = || {
83        crate::Error::Config("custom EVM RPC returned an invalid eth_chainId response".to_string())
84    };
85    let client = reqwest::Client::builder()
86        .timeout(std::time::Duration::from_secs(10))
87        .redirect(reqwest::redirect::Policy::none())
88        .build()
89        .map_err(|_| unavailable())?;
90    let mut response = client
91        .post(rpc_url.clone())
92        .json(
93            &serde_json::json!({"jsonrpc": "2.0", "id": 1, "method": "eth_chainId", "params": []}),
94        )
95        .send()
96        .await
97        .map_err(|_| unavailable())?
98        .error_for_status()
99        .map_err(|_| unavailable())?;
100    let mut body = Vec::new();
101    while let Some(chunk) = response.chunk().await.map_err(|_| unavailable())? {
102        if body.len() + chunk.len() > 4096 {
103            return Err(invalid());
104        }
105        body.extend_from_slice(&chunk);
106    }
107    let response: serde_json::Value = serde_json::from_slice(&body).map_err(|_| invalid())?;
108    if response["jsonrpc"] != "2.0" || response["id"] != 1 || response.get("error").is_some() {
109        return Err(invalid());
110    }
111    let hex = response["result"]
112        .as_str()
113        .and_then(|value| value.strip_prefix("0x"))
114        .filter(|hex| {
115            !hex.is_empty()
116                && (hex.len() == 1 || !hex.starts_with('0'))
117                && hex.bytes().all(|byte| byte.is_ascii_hexdigit())
118        })
119        .ok_or_else(invalid)?;
120    u64::from_str_radix(hex, 16).map_err(|_| invalid())
121}
122
123/// Local-devnet handoff consumed by the browser application.
124///
125/// This manifest is intentionally a local testnet bootstrap artifact. The
126/// production design replaces it with the ML-DSA-signed endpoint records from
127/// ADR-0015.
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
129pub struct BrowserDevnetManifest {
130    /// Manifest schema version.
131    pub version: u16,
132    /// Opaque identifier that distinguishes concurrent local devnets.
133    pub network_id: String,
134    /// Creation time in RFC 3339 form.
135    pub created_at: String,
136    /// Direct node endpoints available as initial browser contacts.
137    pub endpoints: Vec<BrowserBootstrapNode>,
138    /// Public payment chain and contracts used by browser uploads.
139    pub payment: BrowserPaymentNetwork,
140    /// Immutable files published when the devnet started.
141    pub files: Vec<BrowserPublicFile>,
142}
143
144impl BrowserDevnetManifest {
145    /// Construct a versioned local browser manifest.
146    #[must_use]
147    pub fn new(
148        network_id: String,
149        created_at: String,
150        endpoints: Vec<BrowserBootstrapNode>,
151        payment: BrowserPaymentNetwork,
152        files: Vec<BrowserPublicFile>,
153    ) -> Self {
154        Self {
155            version: BROWSER_MANIFEST_VERSION,
156            network_id,
157            created_at,
158            endpoints,
159            payment,
160            files,
161        }
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::browser_payment_network;
168
169    #[tokio::test]
170    async fn builtin_payment_identity_contains_only_chain_and_contracts(
171    ) -> Result<(), Box<dyn std::error::Error>> {
172        for (network, chain_id) in [
173            (evmlib::Network::ArbitrumOne, 42_161),
174            (evmlib::Network::ArbitrumSepoliaTest, 421_614),
175        ] {
176            let identity = browser_payment_network(&network).await?;
177            assert_eq!(identity.chain_id, chain_id);
178            assert_eq!(
179                serde_json::to_value(identity)?,
180                serde_json::json!({
181                    "chain_id": chain_id,
182                    "payment_token_address": format!("{:?}", network.payment_token_address()),
183                    "payment_vault_address": format!("{:?}", network.payment_vault_address()),
184                })
185            );
186        }
187        Ok(())
188    }
189}