use crate::certificate::{
CertificateDecodeLimits, PreparedRootKey, TimePolicy, VerificationLimits, VerifyError,
authenticate_certificate, authenticate_subnet_time, decode_certificate,
};
use candidate_types::Principal;
use ic_transport_types::{Envelope, EnvelopeContent, QueryResponse, ReadStateResponse};
use std::{borrow::Cow, collections::BTreeMap, time::Duration};
mod query;
mod subnet;
pub use ic_transport_types::SubnetMetrics;
pub use subnet::SubnetObservation;
#[derive(Clone, Debug)]
pub struct ReadConfig {
pub endpoint: String,
pub root: PreparedRootKey,
pub root_subnet: Principal,
pub message_bytes: usize,
pub request_timeout: Duration,
pub verification: VerificationLimits,
}
#[derive(Debug, thiserror::Error)]
pub enum ReadError {
#[error("invalid native read configuration")]
Configuration,
#[error("native HTTP request failed: {0}")]
Http(#[from] reqwest::Error),
#[error("native message exceeds byte allowance")]
ByteLimit,
#[error("invalid native packet")]
Packet,
#[error("invalid native certificate: {0}")]
Decode(#[from] crate::certificate::DecodeError),
#[error("native certificate refused: {0}")]
Verification(#[from] VerifyError),
#[error("selected certified path unavailable")]
MissingPath,
#[error("query node signature refused")]
QuerySignature,
#[error("query response signature time refused")]
QueryTime,
#[error("query rejected ({code}): {message}")]
Rejected {
code: u64,
message: String,
error_code: Option<String>,
},
}
#[derive(Clone)]
pub struct ReadClient {
config: ReadConfig,
http: reqwest::Client,
endpoint: reqwest::Url,
}
impl ReadClient {
pub fn new(config: ReadConfig) -> Result<Self, ReadError> {
let endpoint =
reqwest::Url::parse(&config.endpoint).map_err(|_| ReadError::Configuration)?;
if !matches!(endpoint.scheme(), "http" | "https")
|| endpoint.host_str().is_none()
|| !endpoint.username().is_empty()
|| endpoint.password().is_some()
|| endpoint.path() != "/"
|| endpoint.query().is_some()
|| endpoint.fragment().is_some()
|| config.message_bytes == 0
|| config.request_timeout.is_zero()
{
return Err(ReadError::Configuration);
}
let http = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.retry(reqwest::retry::never())
.no_proxy()
.timeout(config.request_timeout)
.build()?;
Ok(Self {
config,
http,
endpoint,
})
}
#[must_use]
pub const fn root(&self) -> &PreparedRootKey {
&self.config.root
}
async fn post(&self, path: &str, content: &EnvelopeContent) -> Result<Vec<u8>, ReadError> {
let envelope = Envelope {
content: Cow::Borrowed(content),
sender_pubkey: None,
sender_sig: None,
sender_delegation: None,
};
let body = envelope.encode_bytes();
if body.len() > self.config.message_bytes {
return Err(ReadError::ByteLimit);
}
let url = self
.endpoint
.join(path)
.map_err(|_| ReadError::Configuration)?;
let mut response = self
.http
.post(url)
.header("content-type", "application/cbor")
.body(body)
.send()
.await?
.error_for_status()?;
if response
.content_length()
.is_some_and(|n| n > self.config.message_bytes as u64)
{
return Err(ReadError::ByteLimit);
}
let mut bytes = Vec::new();
while let Some(chunk) = response.chunk().await? {
if chunk.len() > self.config.message_bytes.saturating_sub(bytes.len()) {
return Err(ReadError::ByteLimit);
}
bytes.extend_from_slice(&chunk);
}
Ok(bytes)
}
async fn state(
&self,
kind: &str,
target: Principal,
paths: Vec<Vec<Vec<u8>>>,
expiry: u64,
) -> Result<Vec<u8>, ReadError> {
let content = EnvelopeContent::ReadState {
sender: Principal::anonymous()
.to_string()
.parse()
.map_err(|_| ReadError::Packet)?,
ingress_expiry: expiry,
paths: paths
.into_iter()
.map(|path| path.into_iter().map(Into::into).collect())
.collect(),
};
let bytes = self
.post(&format!("api/v3/{kind}/{target}/read_state"), &content)
.await?;
let response: ReadStateResponse =
serde_cbor::from_slice(&bytes).map_err(|_| ReadError::Packet)?;
Ok(response.certificate)
}
fn decode<'a>(
&self,
bytes: &'a [u8],
) -> Result<crate::certificate::DecodedCertificate<'a>, ReadError> {
Ok(decode_certificate(
bytes,
CertificateDecodeLimits {
bytes: self.config.message_bytes,
},
)?)
}
}