use std::iter;
#[cfg(feature = "uniffi")]
use std::sync::Arc;
use serde::{Deserialize, Serialize};
#[cfg(all(feature = "wasm-bindgen", target_arch = "wasm32"))]
use wasm_bindgen::prelude::*;
mod commitment;
mod msg_pay_for_blobs;
mod proof;
use crate::consts::appconsts;
#[cfg(feature = "uniffi")]
use crate::error::UniffiResult;
use crate::nmt::Namespace;
use crate::state::{AccAddress, AddressTrait};
use crate::{Error, Result, Share, bail_validation, validation_error};
pub use self::commitment::Commitment;
pub use self::msg_pay_for_blobs::MsgPayForBlobs;
pub use self::proof::BlobProof;
pub use celestia_proto::celestia::blob::v1::MsgPayForBlobs as RawMsgPayForBlobs;
pub use celestia_proto::proto::blob::v4::BlobProto as RawBlob;
pub use celestia_proto::proto::blob::v4::BlobTx as RawBlobTx;
const FIBRE_BLOB_DATA_SIZE: usize = 4 + 32;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "custom_serde::SerdeBlob", into = "custom_serde::SerdeBlob")]
#[cfg_attr(
all(feature = "wasm-bindgen", target_arch = "wasm32"),
wasm_bindgen(getter_with_clone, inspectable)
)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Object))]
pub struct Blob {
pub namespace: Namespace,
pub data: Vec<u8>,
pub share_version: u8,
pub commitment: Commitment,
pub index: Option<u64>,
pub signer: Option<AccAddress>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(
all(feature = "wasm-bindgen", target_arch = "wasm32"),
wasm_bindgen(getter_with_clone, inspectable)
)]
pub struct BlobParams {
pub gas_per_blob_byte: u32,
pub gov_max_square_size: u64,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[cfg_attr(
all(feature = "wasm-bindgen", target_arch = "wasm32"),
wasm_bindgen(getter_with_clone, inspectable)
)]
pub struct BlobsAtHeight {
pub height: u64,
pub blobs: Vec<Blob>,
}
impl Blob {
pub fn new(namespace: Namespace, data: Vec<u8>, signer: Option<AccAddress>) -> Result<Blob> {
let share_version = if signer.is_none() {
appconsts::SHARE_VERSION_ZERO
} else {
appconsts::SHARE_VERSION_ONE
};
let commitment =
Commitment::from_blob(namespace, &data[..], share_version, signer.as_ref())?;
Ok(Blob {
namespace,
data,
share_version,
commitment,
index: None,
signer,
})
}
pub fn from_raw(raw: RawBlob) -> Result<Blob> {
let namespace_version = u8::try_from(raw.namespace_version)
.map_err(|_| validation_error!("namespace version must be single byte"))?;
let namespace = Namespace::new(namespace_version, &raw.namespace_id)?;
let share_version =
u8::try_from(raw.share_version).map_err(|_| Error::UnsupportedShareVersion(u8::MAX))?;
let signer = if raw.signer.is_empty() {
None
} else {
Some(AccAddress::new(
raw.signer
.try_into()
.map_err(|_| validation_error!("invalid signer length"))?,
))
};
let commitment =
Commitment::from_blob(namespace, &raw.data[..], share_version, signer.as_ref())?;
Ok(Blob {
namespace,
data: raw.data,
share_version,
commitment,
index: None,
signer,
})
}
pub fn fibre_commitment(&self) -> Option<[u8; 32]> {
self.fibre_payload().map(|(_, commitment)| *commitment)
}
pub fn fibre_blob_version(&self) -> Option<u32> {
self.fibre_payload()
.map(|(version, _)| u32::from_be_bytes(*version))
}
fn fibre_payload(&self) -> Option<(&[u8; 4], &[u8; 32])> {
if self.share_version != appconsts::SHARE_VERSION_TWO {
return None;
}
let (version, commitment) = self.data.split_first_chunk::<4>()?;
Some((version, commitment.try_into().ok()?))
}
pub fn validate(&self) -> Result<()> {
let computed_commitment = Commitment::from_blob(
self.namespace,
&self.data,
self.share_version,
self.signer.as_ref(),
)?;
if self.commitment != computed_commitment {
bail_validation!("blob commitment != locally computed commitment")
}
Ok(())
}
pub fn validate_with_commitment(&self, commitment: &Commitment) -> Result<()> {
self.validate()?;
if self.commitment != *commitment {
bail_validation!("blob commitment != commitment");
}
Ok(())
}
pub fn to_shares(&self) -> Result<Vec<Share>> {
commitment::split_blob_to_shares(
self.namespace,
self.share_version,
&self.data,
self.signer.as_ref(),
)
}
pub fn reconstruct<'a, I>(shares: I) -> Result<Self>
where
I: IntoIterator<Item = &'a Share>,
{
let mut shares = shares.into_iter();
let first_share = shares.next().ok_or(Error::MissingShares)?;
let blob_len = first_share
.sequence_length()
.ok_or(Error::ExpectedShareWithSequenceStart)?;
let namespace = first_share.namespace();
if namespace.is_reserved() {
return Err(Error::UnexpectedReservedNamespace);
}
let share_version = first_share.info_byte().expect("non parity").version();
let signer = first_share.signer();
commitment::validate_blob(share_version, signer.is_some(), blob_len as usize)?;
let shares_needed = shares_needed_for_blob(blob_len as usize, signer.is_some());
let mut data = Vec::new();
data.extend_from_slice(first_share.payload().expect("non parity"));
for _ in 1..shares_needed {
let share = shares.next().ok_or(Error::MissingShares)?;
if share.namespace() != namespace {
return Err(Error::BlobSharesMetadataMismatch(format!(
"expected namespace ({:?}) got ({:?})",
namespace,
share.namespace()
)));
}
let version = share.info_byte().expect("non parity").version();
if version != share_version {
return Err(Error::BlobSharesMetadataMismatch(format!(
"expected share version ({share_version}) got ({version})"
)));
}
if share.sequence_length().is_some() {
return Err(Error::UnexpectedSequenceStart);
}
data.extend_from_slice(share.payload().expect("non parity"));
}
data.truncate(blob_len as usize);
let commitment = Commitment::from_blob(namespace, &data, share_version, signer.as_ref())?;
Ok(Self {
namespace,
data,
share_version,
commitment,
index: None,
signer,
})
}
pub fn reconstruct_all<'a, I>(shares: I) -> Result<Vec<Self>>
where
I: IntoIterator<Item = &'a Share>,
{
let mut shares = shares
.into_iter()
.filter(|shr| !shr.namespace().is_reserved());
let mut blobs = Vec::with_capacity(2);
loop {
let mut blob = {
let Some(start) =
shares.find(|&shr| shr.sequence_length().is_some_and(|len| len > 0))
else {
break;
};
iter::once(start).chain(&mut shares)
};
blobs.push(Blob::reconstruct(&mut blob)?);
}
Ok(blobs)
}
pub fn shares_len(&self) -> usize {
shares_needed_for_blob(self.data.len(), self.signer.is_some())
}
}
#[cfg(feature = "uniffi")]
#[uniffi::export]
impl Blob {
#[uniffi::constructor(name = "create")]
pub fn uniffi_new(namespace: Arc<Namespace>, data: Vec<u8>) -> UniffiResult<Self> {
let namespace = Arc::unwrap_or_clone(namespace);
Ok(Blob::new(namespace, data, None)?)
}
#[uniffi::constructor(name = "create_with_signer")]
pub fn uniffi_new_with_signer(
namespace: Arc<Namespace>,
data: Vec<u8>,
signer: AccAddress,
) -> UniffiResult<Blob> {
let namespace = Arc::unwrap_or_clone(namespace);
Ok(Blob::new(namespace, data, Some(signer))?)
}
#[uniffi::method(name = "namespace")]
pub fn get_namespace(&self) -> Namespace {
self.namespace
}
#[uniffi::method(name = "data")]
pub fn get_data(&self) -> Vec<u8> {
self.data.clone()
}
#[uniffi::method(name = "share_version")]
pub fn get_share_version(&self) -> u8 {
self.share_version
}
#[uniffi::method(name = "commitment")]
pub fn get_commitment(&self) -> Commitment {
self.commitment
}
#[uniffi::method(name = "index")]
pub fn get_index(&self) -> Option<u64> {
self.index
}
#[uniffi::method(name = "signer")]
pub fn get_signer(&self) -> Option<AccAddress> {
self.signer
}
}
#[cfg(all(feature = "wasm-bindgen", target_arch = "wasm32"))]
#[wasm_bindgen]
impl Blob {
#[wasm_bindgen(constructor)]
pub fn js_new(namespace: &Namespace, data: Vec<u8>) -> Result<Blob> {
Self::new(*namespace, data, None)
}
#[wasm_bindgen(js_name = clone)]
pub fn js_clone(&self) -> Blob {
self.clone()
}
}
impl From<Blob> for RawBlob {
fn from(value: Blob) -> RawBlob {
RawBlob {
namespace_id: value.namespace.id().to_vec(),
namespace_version: value.namespace.version() as u32,
data: value.data,
share_version: value.share_version as u32,
signer: value
.signer
.map(|addr| addr.as_bytes().to_vec())
.unwrap_or_default(),
}
}
}
fn shares_needed_for_blob(blob_len: usize, has_signer: bool) -> usize {
let mut first_share_content = appconsts::FIRST_SPARSE_SHARE_CONTENT_SIZE;
if has_signer {
first_share_content -= appconsts::SIGNER_SIZE;
}
let Some(without_first_share) = blob_len.checked_sub(first_share_content) else {
return 1;
};
1 + without_first_share.div_ceil(appconsts::CONTINUATION_SPARSE_SHARE_CONTENT_SIZE)
}
mod custom_serde {
use serde::de::Error as _;
use serde::ser::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use tendermint_proto::serializers::bytes::base64string;
use crate::nmt::Namespace;
use crate::state::{AccAddress, AddressTrait};
use crate::{Error, Result};
use super::{Blob, Commitment, commitment};
mod index_serde {
use super::*;
pub fn serialize<S>(value: &Option<u64>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let x = value
.map(i64::try_from)
.transpose()
.map_err(S::Error::custom)?
.unwrap_or(-1);
serializer.serialize_i64(x)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
where
D: Deserializer<'de>,
{
i64::deserialize(deserializer).map(|val| if val >= 0 { Some(val as u64) } else { None })
}
}
mod signer_serde {
use super::*;
pub fn serialize<S>(value: &Option<AccAddress>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if let Some(ref addr) = value.as_ref().map(|addr| addr.as_bytes()) {
base64string::serialize(addr, serializer)
} else {
serializer.serialize_none()
}
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<AccAddress>, D::Error>
where
D: Deserializer<'de>,
{
let bytes: Vec<u8> = base64string::deserialize(deserializer)?;
if bytes.is_empty() {
Ok(None)
} else {
let addr = AccAddress::new(bytes.try_into().map_err(D::Error::custom)?);
Ok(Some(addr))
}
}
}
#[derive(Serialize, Deserialize)]
pub(super) struct SerdeBlob {
namespace: Namespace,
#[serde(with = "base64string")]
data: Vec<u8>,
share_version: u8,
commitment: Commitment,
#[serde(default, with = "index_serde")]
index: Option<u64>,
#[serde(default, with = "signer_serde")]
signer: Option<AccAddress>,
}
impl From<Blob> for SerdeBlob {
fn from(value: Blob) -> Self {
Self {
namespace: value.namespace,
data: value.data,
share_version: value.share_version,
commitment: value.commitment,
index: value.index,
signer: value.signer,
}
}
}
impl TryFrom<SerdeBlob> for Blob {
type Error = Error;
fn try_from(value: SerdeBlob) -> Result<Self> {
commitment::validate_blob(
value.share_version,
value.signer.is_some(),
value.data.len(),
)?;
Ok(Blob {
namespace: value.namespace,
data: value.data,
share_version: value.share_version,
commitment: value.commitment,
index: value.index,
signer: value.signer,
})
}
}
}
#[cfg(test)]
mod tests {
use base64::prelude::*;
use prost::Message;
use super::*;
use crate::ExtendedDataSquare;
use crate::nmt::{NS_ID_SIZE, NS_SIZE};
use crate::test_utils::random_bytes;
#[test]
fn signed_blob_share_count_matches_encoding() {
let ns = Namespace::new_v0(&[1, 2, 3]).unwrap();
let signer = AccAddress::from([1; 20]);
for size in [1, 458, 459, 478, 479, 940, 941, 960, 961] {
let blob = Blob::new(ns, vec![7; size], Some(signer)).unwrap();
assert_eq!(blob.shares_len(), blob.to_shares().unwrap().len(), "{size}");
}
}
#[test]
fn raw_blob_rejects_wrapped_namespace_version_and_bad_signer() {
let ns = Namespace::new_v0(&[1, 2, 3]).unwrap();
let mut raw = RawBlob::from(Blob::new(ns, vec![1], None).unwrap());
raw.namespace_version = 256;
assert!(Blob::from_raw(raw.clone()).is_err());
raw.namespace_version = 0;
raw.signer = vec![1];
assert!(Blob::from_raw(raw).is_err());
}
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::wasm_bindgen_test as test;
fn sample_blob() -> Blob {
serde_json::from_str(
r#"{
"namespace": "AAAAAAAAAAAAAAAAAAAAAAAAAAAADCBNOWAP3dM=",
"data": "8fIMqAB+kQo7+LLmHaDya8oH73hxem6lQWX1",
"share_version": 0,
"commitment": "D6YGsPWdxR8ju2OcOspnkgPG2abD30pSHxsFdiPqnVk=",
"index": -1
}"#,
)
.unwrap()
}
fn sample_blob_with_signer() -> Blob {
serde_json::from_str(
r#"{
"namespace": "AAAAAAAAAAAAAAAAAAAAAAAAALwwSWpxCuQb5+A=",
"data": "lQnnMKE=",
"share_version": 1,
"commitment": "dujykaNN+Ey7ET3QNdPG0g2uveriBvZusA3fLSOdMKU=",
"index": -1,
"signer": "Yjc3XldhbdYke5i8aSlggYxCCLE="
}"#,
)
.unwrap()
}
fn fibre_fixture() -> (Blob, Share) {
#[derive(Deserialize)]
struct Fixture {
blob: Blob,
share: String,
}
let fixture: Fixture =
serde_json::from_str(include_str!("../test_data/fibre_blob_v2.json")).unwrap();
let raw_share = BASE64_STANDARD.decode(fixture.share).unwrap();
(fixture.blob, Share::from_raw(&raw_share).unwrap())
}
#[test]
fn fibre_blob_roundtrip() {
let (blob, share) = fibre_fixture();
assert_eq!(blob.share_version, 2);
assert_eq!(blob.data.len(), 36);
assert_eq!(blob.fibre_blob_version(), Some(0));
assert_eq!(blob.fibre_commitment(), Some([0xBB; 32]));
let info_byte = share.info_byte().unwrap();
assert_eq!(info_byte.version(), appconsts::SHARE_VERSION_TWO);
assert!(info_byte.is_sequence_start());
assert_eq!(share.sequence_length(), Some(36));
assert_eq!(share.signer(), Some([0xAA; 20].into()));
assert_eq!(&share.payload().unwrap()[..36], blob.data);
assert_eq!(blob.shares_len(), 1);
assert_eq!(blob.to_shares().unwrap(), vec![share.clone()]);
assert_eq!(Blob::reconstruct([&share]).unwrap(), blob);
blob.validate().unwrap();
let json = serde_json::to_string(&blob).unwrap();
assert_eq!(serde_json::from_str::<Blob>(&json).unwrap(), blob);
let encoded = RawBlob::from(blob.clone()).encode_to_vec();
let raw = RawBlob::decode(encoded.as_slice()).unwrap();
assert_eq!(Blob::from_raw(raw).unwrap(), blob);
let mut tampered = blob;
tampered.data[4] ^= 1;
assert!(matches!(tampered.validate(), Err(Error::Validation(_))));
}
#[test]
fn fibre_blob_accessors() {
let (blob, _) = fibre_fixture();
for signer in [None, blob.signer] {
let ordinary = Blob::new(blob.namespace, blob.data.clone(), signer).unwrap();
assert!(ordinary.fibre_commitment().is_none());
assert!(ordinary.fibre_blob_version().is_none());
}
let mut raw = RawBlob::from(blob);
raw.data[..4].copy_from_slice(&0x01020304u32.to_be_bytes());
let future = Blob::from_raw(raw).unwrap();
assert_eq!(future.fibre_blob_version(), Some(0x01020304));
assert_eq!(future.fibre_commitment(), Some([0xBB; 32]));
assert_eq!(
Blob::reconstruct(&future.to_shares().unwrap()).unwrap(),
future
);
}
#[test]
fn reject_invalid_fibre_blob_payload() {
let (blob, _) = fibre_fixture();
for len in [0, 35, 37, 458, 459] {
let mut invalid = blob.clone();
invalid.data.resize(len, 0);
assert!(invalid.fibre_commitment().is_none());
assert!(invalid.fibre_blob_version().is_none());
assert!(
matches!(invalid.validate(), Err(Error::InvalidLength(actual, 36)) if actual == len)
);
assert!(
matches!(invalid.to_shares(), Err(Error::InvalidLength(actual, 36)) if actual == len)
);
assert!(
matches!(Blob::from_raw(invalid.clone().into()), Err(Error::InvalidLength(actual, 36)) if actual == len)
);
assert!(
serde_json::from_str::<Blob>(&serde_json::to_string(&invalid).unwrap()).is_err()
);
}
let mut invalid = blob.clone();
invalid.signer = None;
assert!(matches!(invalid.validate(), Err(Error::MissingSigner)));
assert!(matches!(invalid.to_shares(), Err(Error::MissingSigner)));
assert!(matches!(
Blob::from_raw(invalid.clone().into()),
Err(Error::MissingSigner)
));
assert!(serde_json::from_str::<Blob>(&serde_json::to_string(&invalid).unwrap()).is_err());
let mut invalid = blob;
invalid.share_version = 3;
assert!(invalid.fibre_commitment().is_none());
assert!(invalid.fibre_blob_version().is_none());
assert!(matches!(
invalid.validate(),
Err(Error::UnsupportedShareVersion(3))
));
assert!(matches!(
invalid.to_shares(),
Err(Error::UnsupportedShareVersion(3))
));
}
#[test]
fn reject_invalid_fibre_sequence_length() {
let (_, share) = fibre_fixture();
for len in [0u32, 35, 37, u32::MAX] {
let mut invalid = share.clone();
invalid.as_mut()[NS_SIZE + 1..NS_SIZE + 5].copy_from_slice(&len.to_be_bytes());
assert!(
matches!(Blob::reconstruct([&invalid]), Err(Error::InvalidLength(actual, 36)) if actual == len as usize)
);
}
}
#[test]
fn reconstruct_mixed_blobs_from_eds() {
let (fibre, _) = fibre_fixture();
let mut other_fibre = RawBlob::from(fibre.clone());
other_fibre.data[4] ^= 1;
let blobs = vec![
Blob::new(fibre.namespace, vec![1; 1024], None).unwrap(),
fibre.clone(),
Blob::from_raw(other_fibre).unwrap(),
Blob::new(fibre.namespace, vec![2; 1024], fibre.signer).unwrap(),
];
let mut shares = Vec::new();
for namespace in [
Namespace::PAY_FOR_BLOB,
Namespace::PAY_FOR_FIBRE,
Namespace::PRIMARY_RESERVED_PADDING,
] {
let mut reserved = [0; appconsts::SHARE_SIZE];
reserved[..NS_SIZE].copy_from_slice(namespace.as_bytes());
if namespace != Namespace::PRIMARY_RESERVED_PADDING {
reserved[NS_SIZE] = 1;
reserved[NS_SIZE + 1..NS_SIZE + 5].copy_from_slice(&1u32.to_be_bytes());
}
shares.push(Share::from_raw(&reserved).unwrap());
}
for (index, blob) in blobs.iter().enumerate() {
shares.extend(blob.to_shares().unwrap());
if index == 1 {
continue;
}
let mut padding = [0; appconsts::SHARE_SIZE];
padding[..NS_SIZE].copy_from_slice(blob.namespace.as_bytes());
padding[NS_SIZE] = (blob.share_version << 1) | 1;
shares.push(Share::from_raw(&padding).unwrap());
}
let mut tail_padding = [0; appconsts::SHARE_SIZE];
tail_padding[..NS_SIZE].copy_from_slice(Namespace::TAIL_PADDING.as_bytes());
shares.resize(16, Share::from_raw(&tail_padding).unwrap());
let eds = ExtendedDataSquare::from_ods(shares.iter().map(Share::to_vec).collect()).unwrap();
assert_eq!(Blob::reconstruct_all(eds.data_square()).unwrap(), blobs);
}
#[test]
fn create_new_blob_unsigned() {
use crate::consts::appconsts;
let ns = Namespace::new_v0(&[1, 2, 3, 4, 5]).expect("Invalid namespace");
let blob = Blob::new(ns, b"some data to store on blockchain".to_vec(), None)
.expect("Failed to create blob");
let shares = blob.to_shares().expect("to_shares failed");
assert!(!shares.is_empty(), "expected at least one share");
let first = &shares[0];
assert!(
first.sequence_length().is_some(),
"first share must be a sequence start"
);
let version = first.info_byte().expect("non parity share").version();
assert_eq!(
version,
appconsts::SHARE_VERSION_ZERO,
"unexpected share version for unsigned blob"
);
assert_eq!(
first.signer(),
None,
"unsigned blob must not carry a signer"
);
}
#[test]
fn create_new_blob_signed() {
use crate::consts::appconsts;
let ns = Namespace::new_v0(&[1, 2, 3, 4, 5]).expect("Invalid namespace");
let signer: AccAddress = "celestia1377k5an3f94v6wyaceu0cf4nq6gk2jtpc46g7h"
.parse()
.expect("invalid signer");
let blob = Blob::new(
ns,
b"some data to store on blockchain".to_vec(),
Some(signer),
)
.expect("Failed to create signed blob");
let shares = blob.to_shares().expect("to_shares failed");
assert!(!shares.is_empty(), "expected at least one share");
let first = &shares[0];
assert!(
first.sequence_length().is_some(),
"first share must be a sequence start"
);
let version = first.info_byte().expect("non parity share").version();
assert_eq!(
version,
appconsts::SHARE_VERSION_ONE,
"unexpected share version for signed blob"
);
assert_eq!(
first.signer(),
Some(signer),
"first share must carry the expected signer"
);
}
#[test]
fn create_from_raw() {
let expected = sample_blob();
let raw = RawBlob::from(expected.clone());
let created = Blob::from_raw(raw).unwrap();
assert_eq!(created, expected);
}
#[test]
fn create_from_raw_with_signer() {
let expected = sample_blob_with_signer();
let raw = RawBlob::from(expected.clone());
let created = Blob::from_raw(raw).unwrap();
assert_eq!(created, expected);
}
#[test]
fn validate_blob() {
sample_blob().validate().unwrap();
}
#[test]
fn validate_blob_with_signer() {
sample_blob_with_signer().validate().unwrap();
}
#[test]
fn validate_blob_commitment_mismatch() {
let mut blob = sample_blob();
blob.commitment = Commitment::new([7; 32]);
blob.validate().unwrap_err();
}
#[test]
fn deserialize_blob_with_missing_index() {
serde_json::from_str::<Blob>(
r#"{
"namespace": "AAAAAAAAAAAAAAAAAAAAAAAAAAAADCBNOWAP3dM=",
"data": "8fIMqAB+kQo7+LLmHaDya8oH73hxem6lQWX1",
"share_version": 0,
"commitment": "D6YGsPWdxR8ju2OcOspnkgPG2abD30pSHxsFdiPqnVk="
}"#,
)
.unwrap();
}
#[test]
fn deserialize_blob_with_share_version_and_signer_mismatch() {
serde_json::from_str::<Blob>(
r#"{
"namespace": "AAAAAAAAAAAAAAAAAAAAAAAAALwwSWpxCuQb5+A=",
"data": "lQnnMKE=",
"share_version": 0,
"commitment": "dujykaNN+Ey7ET3QNdPG0g2uveriBvZusA3fLSOdMKU=",
"signer": "Yjc3XldhbdYke5i8aSlggYxCCLE="
}"#,
)
.unwrap_err();
serde_json::from_str::<Blob>(
r#"{
"namespace": "AAAAAAAAAAAAAAAAAAAAAAAAALwwSWpxCuQb5+A=",
"data": "lQnnMKE=",
"share_version": 1,
"commitment": "dujykaNN+Ey7ET3QNdPG0g2uveriBvZusA3fLSOdMKU=",
}"#,
)
.unwrap_err();
}
#[test]
fn reconstruct() {
for _ in 0..10 {
let len = rand::random::<usize>() % (1024 * 1024) + 1;
let data = random_bytes(len);
let ns = Namespace::const_v0(rand::random());
let blob = Blob::new(ns, data, None).unwrap();
let shares = blob.to_shares().unwrap();
assert_eq!(blob, Blob::reconstruct(&shares).unwrap());
}
}
#[test]
fn reconstruct_with_signer() {
for _ in 0..10 {
let len = rand::random::<usize>() % (1024 * 1024) + 1;
let data = random_bytes(len);
let ns = Namespace::const_v0(rand::random());
let signer = rand::random::<[u8; 20]>().into();
let blob = Blob::new(ns, data, Some(signer)).unwrap();
let shares = blob.to_shares().unwrap();
assert_eq!(blob, Blob::reconstruct(&shares).unwrap());
}
}
#[test]
fn reconstruct_empty() {
assert!(matches!(
Blob::reconstruct(&Vec::<Share>::new()),
Err(Error::MissingShares)
));
}
#[test]
fn reconstruct_not_sequence_start() {
let len = rand::random::<usize>() % (1024 * 1024) + 1;
let data = random_bytes(len);
let ns = Namespace::const_v0(rand::random());
let mut shares = Blob::new(ns, data, None).unwrap().to_shares().unwrap();
shares[0].as_mut()[NS_SIZE] &= 0b11111110;
assert!(matches!(
Blob::reconstruct(&shares),
Err(Error::ExpectedShareWithSequenceStart)
));
}
#[test]
fn reconstruct_reserved_namespace() {
for ns in (0..255).flat_map(|n| {
let mut v0 = [0; NS_ID_SIZE];
*v0.last_mut().unwrap() = n;
let mut v255 = [0xff; NS_ID_SIZE];
*v255.last_mut().unwrap() = n;
[Namespace::new_v0(&v0), Namespace::new_v255(&v255)]
}) {
let len = (rand::random::<usize>() % 1023 + 1) * 2;
let data = random_bytes(len);
let shares = Blob::new(ns.unwrap(), data, None)
.unwrap()
.to_shares()
.unwrap();
assert!(matches!(
Blob::reconstruct(&shares),
Err(Error::UnexpectedReservedNamespace)
));
}
}
#[test]
fn reconstruct_not_enough_shares() {
let len = rand::random::<usize>() % 1024 * 1024 + 2048;
let data = random_bytes(len);
let ns = Namespace::const_v0(rand::random());
let shares = Blob::new(ns, data, None).unwrap().to_shares().unwrap();
assert!(matches!(
Blob::reconstruct(&shares[..2]),
Err(Error::MissingShares)
));
}
#[test]
fn reconstruct_inconsistent_share_version() {
let len = rand::random::<usize>() % (1024 * 1024) + 512;
let data = random_bytes(len);
let ns = Namespace::const_v0(rand::random());
let mut shares = Blob::new(ns, data, None).unwrap().to_shares().unwrap();
shares[1].as_mut()[NS_SIZE] = 0b11111110;
assert!(matches!(
Blob::reconstruct(&shares),
Err(Error::BlobSharesMetadataMismatch(..))
));
}
#[test]
fn reconstruct_inconsistent_namespace() {
let len = rand::random::<usize>() % (1024 * 1024) + 512;
let data = random_bytes(len);
let ns = Namespace::const_v0(rand::random());
let ns2 = Namespace::const_v0(rand::random());
let mut shares = Blob::new(ns, data, None).unwrap().to_shares().unwrap();
shares[1].as_mut()[..NS_SIZE].copy_from_slice(ns2.as_bytes());
assert!(matches!(
Blob::reconstruct(&shares),
Err(Error::BlobSharesMetadataMismatch(..))
));
}
#[test]
fn reconstruct_unexpected_sequence_start() {
let len = rand::random::<usize>() % (1024 * 1024) + 512;
let data = random_bytes(len);
let ns = Namespace::const_v0(rand::random());
let mut shares = Blob::new(ns, data, None).unwrap().to_shares().unwrap();
shares[1].as_mut()[NS_SIZE] |= 0b00000001;
assert!(matches!(
Blob::reconstruct(&shares),
Err(Error::UnexpectedSequenceStart)
));
}
#[test]
fn reconstruct_all() {
let blobs: Vec<_> = (0..rand::random::<usize>() % 16 + 3)
.map(|_| {
let len = rand::random::<usize>() % (1024 * 1024) + 512;
let data = random_bytes(len);
let ns = Namespace::const_v0(rand::random());
Blob::new(ns, data, None).unwrap()
})
.collect();
let shares: Vec<_> = blobs
.iter()
.flat_map(|blob| blob.to_shares().unwrap())
.collect();
let reconstructed = Blob::reconstruct_all(&shares).unwrap();
assert_eq!(blobs, reconstructed);
}
}