use std::error::Error as StdError;
use std::fmt::{self, Debug};
use std::sync::Arc;
use std::time::Duration;
use blockstore::cond_send::CondSend;
pub use celestia_grpc::Endpoint;
use celestia_grpc::{GrpcClient, GrpcClientBuilder};
pub use celestia_rpc::RpcEndpoint;
use celestia_rpc::{FailoverClient, HeaderClient};
use http::Request;
use tonic::body::Body as TonicBody;
use tonic::codegen::{Bytes, Service};
use crate::blob::BlobApi;
use crate::blobstream::BlobstreamApi;
use crate::fraud::FraudApi;
use crate::header::HeaderApi;
use crate::share::ShareApi;
use crate::state::StateApi;
use crate::tx::{DocSigner, Keypair, VerifyingKey};
use crate::types::ExtendedHeader;
use crate::types::state::AccAddress;
use crate::{Error, Result};
pub struct Client {
inner: Arc<ClientInner>,
state: StateApi,
blob: BlobApi,
header: HeaderApi,
share: ShareApi,
fraud: FraudApi,
blobstream: BlobstreamApi,
fibre: Option<crate::fibre::FibreApi>,
}
pub(crate) struct ClientInner {
pub(crate) rpc: FailoverClient,
grpc: Option<GrpcClient>,
pubkey: Option<VerifyingKey>,
chain_id: tendermint::chain::Id,
}
#[derive(Default)]
pub struct ClientBuilder {
rpc_url: Option<String>,
rpc_auth_token: Option<String>,
rpc_endpoints: Vec<RpcEndpoint>,
rpc_health_check_interval: Option<Duration>,
rpc_max_head_age: Option<Duration>,
timeout: Option<Duration>,
connect_timeout: Option<Duration>,
grpc_builder: Option<GrpcClientBuilder>,
fibre_client: Option<celestia_fibre::FibreClient>,
}
impl fmt::Debug for ClientBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ClientBuilder")
.field("rpc_url", &self.rpc_url)
.field(
"rpc_auth_token",
&self.rpc_auth_token.as_ref().map(|_| "***"),
)
.field(
"rpc_endpoints",
&self
.rpc_endpoints
.iter()
.map(|e| &e.url)
.collect::<Vec<_>>(),
)
.field("rpc_health_check_interval", &self.rpc_health_check_interval)
.field("rpc_max_head_age", &self.rpc_max_head_age)
.field("timeout", &self.timeout)
.field("connect_timeout", &self.connect_timeout)
.field("grpc_builder", &self.grpc_builder)
.field(
"fibre_client",
&self.fibre_client.as_ref().map(|_| "FibreClient { .. }"),
)
.finish()
}
}
impl ClientInner {
pub(crate) fn grpc(&self) -> Result<&GrpcClient> {
self.grpc.as_ref().ok_or(Error::GrpcEndpointNotSet)
}
pub(crate) fn pubkey(&self) -> Result<&VerifyingKey> {
self.pubkey.as_ref().ok_or(Error::NoAssociatedAddress)
}
pub(crate) fn address(&self) -> Result<AccAddress> {
let pubkey = self.pubkey()?.to_owned();
Ok(AccAddress::new(pubkey.into()))
}
pub(crate) async fn get_header_validated(&self, height: u64) -> Result<ExtendedHeader> {
let header = self.rpc.header_get_by_height(height).await?;
header.validate()?;
Ok(header)
}
}
impl Client {
pub fn builder() -> ClientBuilder {
ClientBuilder::new()
}
pub fn chain_id(&self) -> &tendermint::chain::Id {
&self.inner.chain_id
}
pub fn pubkey(&self) -> Result<VerifyingKey> {
self.inner.pubkey().cloned()
}
pub fn address(&self) -> Result<AccAddress> {
self.inner.address()
}
pub fn state(&self) -> &StateApi {
&self.state
}
pub fn blob(&self) -> &BlobApi {
&self.blob
}
pub fn blobstream(&self) -> &BlobstreamApi {
&self.blobstream
}
pub fn header(&self) -> &HeaderApi {
&self.header
}
pub fn share(&self) -> &ShareApi {
&self.share
}
pub fn fraud(&self) -> &FraudApi {
&self.fraud
}
pub fn fibre(&self) -> Option<&crate::fibre::FibreApi> {
self.fibre.as_ref()
}
}
impl ClientBuilder {
pub fn new() -> ClientBuilder {
ClientBuilder::default()
}
pub fn signer<S>(mut self, pubkey: VerifyingKey, signer: S) -> ClientBuilder
where
S: DocSigner + Sync + Send + 'static,
{
let grpc_builder = self.grpc_builder.unwrap_or_default();
self.grpc_builder = Some(grpc_builder.pubkey_and_signer(pubkey, signer));
self
}
pub fn keypair<S>(mut self, keypair: S) -> ClientBuilder
where
S: DocSigner + Keypair<VerifyingKey = VerifyingKey> + Sync + Send + 'static,
{
let grpc_builder = self.grpc_builder.unwrap_or_default();
self.grpc_builder = Some(grpc_builder.signer_keypair(keypair));
self
}
pub fn private_key(mut self, bytes: &[u8]) -> ClientBuilder {
let grpc_builder = self.grpc_builder.unwrap_or_default();
self.grpc_builder = Some(grpc_builder.private_key(bytes));
self
}
pub fn private_key_hex(mut self, s: &str) -> ClientBuilder {
let grpc_builder = self.grpc_builder.unwrap_or_default();
self.grpc_builder = Some(grpc_builder.private_key_hex(s));
self
}
pub fn rpc_url(mut self, url: &str) -> ClientBuilder {
self.rpc_url = Some(url.to_owned());
self
}
pub fn rpc_auth_token(mut self, auth_token: &str) -> ClientBuilder {
self.rpc_auth_token = Some(auth_token.to_owned());
self
}
pub fn rpc_endpoint(mut self, endpoint: impl Into<RpcEndpoint>) -> ClientBuilder {
self.rpc_endpoints.push(endpoint.into());
self
}
pub fn rpc_endpoints<I, E>(mut self, endpoints: I) -> ClientBuilder
where
I: IntoIterator<Item = E>,
E: Into<RpcEndpoint>,
{
self.rpc_endpoints
.extend(endpoints.into_iter().map(Into::into));
self
}
pub fn rpc_health_check_interval(mut self, interval: Duration) -> ClientBuilder {
self.rpc_health_check_interval = Some(interval);
self
}
pub fn rpc_max_head_age(mut self, max_head_age: Duration) -> ClientBuilder {
self.rpc_max_head_age = Some(max_head_age);
self
}
pub fn timeout(mut self, timeout: Duration) -> ClientBuilder {
self.timeout = Some(timeout);
self
}
pub fn connect_timeout(mut self, connect_timeout: Duration) -> ClientBuilder {
self.connect_timeout = Some(connect_timeout);
self
}
pub fn grpc_url(self, url: impl Into<Endpoint>) -> ClientBuilder {
self.grpc_endpoint(url)
}
pub fn grpc_endpoint(mut self, endpoint: impl Into<Endpoint>) -> ClientBuilder {
let grpc_builder = self.grpc_builder.unwrap_or_default();
self.grpc_builder = Some(grpc_builder.endpoint(endpoint));
self
}
pub fn grpc_endpoints<I, E>(mut self, endpoints: I) -> ClientBuilder
where
I: IntoIterator<Item = E>,
E: Into<Endpoint>,
{
let grpc_builder = self.grpc_builder.unwrap_or_default();
self.grpc_builder = Some(grpc_builder.endpoints(endpoints));
self
}
pub fn grpc_urls<I, E>(self, urls: I) -> ClientBuilder
where
I: IntoIterator<Item = E>,
E: Into<Endpoint>,
{
self.grpc_endpoints(urls)
}
pub fn grpc_transport<B, T>(mut self, transport: T) -> Self
where
B: http_body::Body<Data = Bytes> + Send + Unpin + 'static,
<B as http_body::Body>::Error: StdError + Send + Sync,
T: Service<Request<TonicBody>, Response = http::Response<B>>
+ Send
+ Sync
+ Clone
+ 'static,
<T as Service<Request<TonicBody>>>::Error: StdError + Send + Sync + 'static,
<T as Service<Request<TonicBody>>>::Future: CondSend + 'static,
{
let grpc_builder = self.grpc_builder.unwrap_or_default();
self.grpc_builder = Some(grpc_builder.transport(transport));
self
}
pub fn fibre_client(mut self, fibre_client: celestia_fibre::FibreClient) -> Self {
self.fibre_client = Some(fibre_client);
self
}
pub async fn build(self) -> Result<Client> {
let mut rpc_endpoints = Vec::with_capacity(self.rpc_endpoints.len() + 1);
if let Some(url) = self.rpc_url {
let mut endpoint = RpcEndpoint::new(url);
if let Some(token) = self.rpc_auth_token {
endpoint = endpoint.auth_token(token);
}
rpc_endpoints.push(endpoint);
}
rpc_endpoints.extend(self.rpc_endpoints);
if rpc_endpoints.is_empty() {
return Err(Error::RpcEndpointNotSet);
}
let (grpc, pubkey) = if let Some(mut grpc_builder) = self.grpc_builder {
if let Some(timeout) = self.timeout {
grpc_builder = grpc_builder.timeout(timeout)
};
if let Some(connect_timeout) = self.connect_timeout {
grpc_builder = grpc_builder.connect_timeout(connect_timeout)
};
let client = grpc_builder.build()?;
let pubkey = client.get_account_pubkey();
(Some(client), pubkey)
} else {
(None, None)
};
let health_check_interval = (rpc_endpoints.len() > 1).then(|| {
self.rpc_health_check_interval
.unwrap_or(celestia_rpc::DEFAULT_HEALTH_CHECK_INTERVAL)
});
let max_head_age = self
.rpc_max_head_age
.unwrap_or(celestia_rpc::DEFAULT_MAX_HEAD_AGE);
let rpc = FailoverClient::new(
rpc_endpoints,
self.connect_timeout,
self.timeout,
health_check_interval,
max_head_age,
)?;
let head = rpc.header_network_head().await?;
head.validate()?;
if let Some(grpc) = &grpc
&& &grpc.chain_id().await? != head.chain_id()
{
return Err(Error::ChainIdMissmatch);
}
let inner = Arc::new(ClientInner {
rpc,
grpc,
pubkey,
chain_id: head.chain_id().to_owned(),
});
let fibre = self
.fibre_client
.map(|fc| crate::fibre::FibreApi::new(inner.clone(), fc));
Ok(Client {
inner: inner.clone(),
blob: BlobApi::new(inner.clone()),
header: HeaderApi::new(inner.clone()),
share: ShareApi::new(inner.clone()),
fraud: FraudApi::new(inner.clone()),
blobstream: BlobstreamApi::new(inner.clone()),
state: StateApi::new(inner.clone()),
fibre,
})
}
}
impl Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Client { .. }")
}
}
#[cfg(test)]
mod tests {
use super::*;
use lumina_utils::test_utils::async_test;
use crate::test_utils::{TEST_PRIV_KEY, TEST_RPC_URL};
#[async_test]
async fn reject_fibre_blob_submission() {
use crate::tx::TxConfig;
use crate::types::Blob;
use crate::types::blob::RawBlob;
use crate::types::nmt::Namespace;
let grpc = GrpcClient::builder()
.endpoint("http://127.0.0.1:1")
.timeout(Duration::from_millis(100))
.build()
.unwrap();
let rpc = FailoverClient::new(
vec![RpcEndpoint::new("http://127.0.0.1:1")],
None,
Some(Duration::from_millis(100)),
None,
celestia_rpc::DEFAULT_MAX_HEAD_AGE,
)
.unwrap();
let inner = Arc::new(ClientInner {
rpc,
grpc: Some(grpc),
pubkey: None,
chain_id: "private".parse().unwrap(),
});
let blob_api = BlobApi::new(inner.clone());
let state_api = StateApi::new(inner);
let namespace = Namespace::new_v0(b"fibre").unwrap();
let fibre = Blob::from_raw(RawBlob {
namespace_id: namespace.id().to_vec(),
namespace_version: 0,
share_version: 2,
data: vec![0; 36],
signer: vec![0xAA; 20],
})
.unwrap();
let unsigned = Blob::new(fibre.namespace, vec![1], None).unwrap();
let signed = Blob::new(fibre.namespace, vec![2], fibre.signer).unwrap();
let blobs = [unsigned, signed, fibre];
let blob_error = blob_api
.submit(&blobs, TxConfig::default())
.await
.unwrap_err();
let state_error = state_api
.submit_pay_for_blob(&blobs, TxConfig::default())
.await
.unwrap_err();
for error in [blob_error, state_error] {
assert!(matches!(
error,
Error::Grpc(celestia_grpc::Error::CelestiaTypesError(
celestia_types::Error::FibreBlobSubmission
))
));
}
}
#[cfg(not(target_arch = "wasm32"))]
#[tokio::test]
async fn read_blobs_after_blob_and_pay_for_fibre_in_same_namespace() {
use celestia_fibre::{FibreClient, FibreClientConfig};
use crate::test_utils::{new_client, node0_client};
use crate::tx::{SigningKey, TxConfig};
use crate::types::Blob;
use crate::types::nmt::Namespace;
let blob_client = new_client().await;
let (_node0_lock, node0) = node0_client().await;
let namespace = Namespace::new_v0(b"same-ns").unwrap();
let blob = Blob::new(
namespace,
b"normal blob".to_vec(),
Some(blob_client.address().unwrap()),
)
.unwrap();
let signer_key =
SigningKey::from_slice(&hex::decode(TEST_PRIV_KEY.trim()).unwrap()).unwrap();
let signer_address = node0.address().unwrap();
let blob_grpc = blob_client.inner.grpc().unwrap();
let fibre_grpc = node0.inner.grpc().unwrap();
let fibre_client = FibreClient::from_grpc_client(
fibre_grpc.clone(),
FibreClientConfig::new(node0.chain_id().as_str()).unwrap(),
)
.unwrap();
let mut common_block = None;
for _ in 0..5 {
let msg = fibre_client
.upload_and_prepare(&signer_key, namespace, b"fibre blob", &signer_address)
.await
.unwrap();
let promise = msg.payment_promise.clone().unwrap();
let (blob_tx, fibre_tx) = tokio::join!(
blob_grpc.broadcast_blobs(std::slice::from_ref(&blob), TxConfig::default()),
fibre_grpc.broadcast_message(msg, TxConfig::default()),
);
let (blob_info, fibre_info) =
tokio::join!(blob_tx.unwrap().confirm(), fibre_tx.unwrap().confirm());
let (blob_height, fibre_height) =
(blob_info.unwrap().height, fibre_info.unwrap().height);
if blob_height == fibre_height {
common_block = Some((blob_height, promise));
break;
}
}
let (height, promise) =
common_block.expect("transactions were not included in the same block");
let blobs = blob_client
.blob()
.get_all(height, &[namespace])
.await
.unwrap()
.unwrap();
assert_eq!(blobs.len(), 2);
let ordinary = blobs
.iter()
.find(|returned| returned.share_version == blob.share_version)
.expect("ordinary blob missing");
assert_eq!(ordinary.namespace, blob.namespace);
assert_eq!(ordinary.data, blob.data);
assert_eq!(ordinary.signer, blob.signer);
assert_eq!(ordinary.commitment, blob.commitment);
let fibre = blobs
.iter()
.find(|returned| returned.share_version == 2)
.expect("Fibre blob missing");
assert_eq!(fibre.namespace, namespace);
assert_eq!(fibre.signer, Some(signer_address));
assert_eq!(fibre.fibre_blob_version(), Some(promise.blob_version));
assert_eq!(
fibre.fibre_commitment().map(|c| c.to_vec()),
Some(promise.commitment)
);
}
#[async_test]
async fn builder() {
let e = Client::builder()
.rpc_url(TEST_RPC_URL)
.private_key_hex(TEST_PRIV_KEY)
.build()
.await
.unwrap_err();
assert!(matches!(e, Error::GrpcEndpointNotSet))
}
#[test]
fn connect_timeout_is_independent_of_timeout() {
assert!(ClientBuilder::default().connect_timeout.is_none());
let builder = ClientBuilder::default().timeout(Duration::from_secs(30));
assert_eq!(builder.timeout, Some(Duration::from_secs(30)));
assert!(builder.connect_timeout.is_none());
let builder = ClientBuilder::default().connect_timeout(Duration::from_secs(2));
assert_eq!(builder.connect_timeout, Some(Duration::from_secs(2)));
assert!(builder.timeout.is_none());
}
}