Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/examples/get-blob.rs:1:
/// Example how to request a blob from a remote node without using a store.
mod common;
-use cyber_bao::io::BaoContentItem;
use clap::Parser;
use common::setup_logging;
+use cyber_bao::io::BaoContentItem;
use iroh::address_lookup::PkarrResolver;
use iroh_blobs::{get::request::GetBlobItem, ticket::BlobTicket, BlobFormat};
use n0_future::StreamExt;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/api/blobs.rs:14:
pin::Pin,
};
+use bytes::Bytes;
pub use cyber_bao::io::mixed::EncodedItem;
use cyber_bao::{
io::{
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/api/blobs.rs:22:
},
BaoTree, ChunkNum, ChunkRanges,
};
-use bytes::Bytes;
use genawaiter::sync::Gen;
use iroh_io::AsyncStreamWriter;
use irpc::channel::{mpsc, oneshot};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/api/proto.rs:23:
};
use arrayvec::ArrayString;
+use bytes::Bytes;
use cyber_bao::{
io::{mixed::EncodedItem, BaoContentItem, Leaf},
ChunkRanges,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/api/proto.rs:29:
};
-use bytes::Bytes;
use irpc::{
channel::{mpsc, oneshot},
rpc_requests,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/api/remote.rs:1266:
};
let content = add_test_hash_seq_incomplete(&store, sizes, present).await?;
let info = store.remote().local(content).await?;
- let first_block_size = sizes.into_iter().map(|x| x.min(block_bytes) as u64).sum::<u64>();
+ let first_block_size = sizes
+ .into_iter()
+ .map(|x| x.min(block_bytes) as u64)
+ .sum::<u64>();
assert_eq!(info.bitfield.ranges, ChunkRanges::all());
assert_eq!(info.local_bytes(), hash_seq_size + first_block_size);
assert!(!info.is_complete());
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/api/remote.rs:1275:
GetRequest::new(
content.hash,
ChunkRangesSeq::from_ranges([
- ChunkRanges::empty(), // we have the hash seq itself
- ChunkRanges::empty(), // we always have the empty blob
- ChunkRanges::empty(), // size=1, fits in one block
- ChunkRanges::empty(), // size=1024, fits in one block
- ChunkRanges::empty(), // size=16383, fits in one block
- ChunkRanges::empty(), // size=16384, fits in one block
+ ChunkRanges::empty(), // we have the hash seq itself
+ ChunkRanges::empty(), // we always have the empty blob
+ ChunkRanges::empty(), // size=1, fits in one block
+ ChunkRanges::empty(), // size=1024, fits in one block
+ ChunkRanges::empty(), // size=16383, fits in one block
+ ChunkRanges::empty(), // size=16384, fits in one block
ChunkRanges::chunks(chunks_per_block..), // size=16385, missing from chunk 16
ChunkRanges::chunks(chunks_per_block..), // size=1MB, missing from chunk 16
ChunkRanges::chunks(chunks_per_block..), // size=8MB, missing from chunk 16
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/format/collection.rs:324:
#[tokio::test]
async fn collection_store_load() -> testresult::TestResult {
let collection = (0..3)
- .map(|i| {
- (
- format!("blob{i}"),
- crate::Hash::new(&[i as u8]),
- )
- })
+ .map(|i| (format!("blob{i}"), crate::Hash::new(&[i as u8])))
.collect::<Collection>();
let mut root = None;
let store = collection
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/get/request.rs:14:
task::{Context, Poll},
};
-use cyber_bao::{io::BaoContentItem, ChunkNum, ChunkRanges};
use bytes::Bytes;
+use cyber_bao::{io::BaoContentItem, ChunkNum, ChunkRanges};
use genawaiter::sync::{Co, Gen};
use iroh::endpoint::Connection;
use n0_error::e;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/protocol.rs:378:
ops::{Bound, RangeBounds},
};
-use cyber_bao::{io::round_up_to_chunks, ChunkNum};
use builder::GetRequestBuilder;
+use cyber_bao::{io::round_up_to_chunks, ChunkNum};
use derive_more::From;
use iroh::endpoint::VarInt;
use postcard::experimental::max_size::MaxSize;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/store/fs/bao_file.rs:6:
path::Path,
};
+use bytes::{Bytes, BytesMut};
use cyber_bao::{
- io::{
- ReadBytesAt,
- pre_order::PreOrderOutboard,
- BaoContentItem, ReadAt, WriteAt,
- },
+ io::{pre_order::PreOrderOutboard, BaoContentItem, ReadAt, ReadBytesAt, WriteAt},
BaoTree, ChunkRanges,
};
-use bytes::{Bytes, BytesMut};
use derive_more::Debug;
use irpc::channel::mpsc;
use n0_error::{Result, StdResultExt};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/store/fs/import.rs:18:
sync::Arc,
};
+use bytes::Bytes;
use cyber_bao::{
io::pre_order::{PreOrderMemOutboard, PreOrderOutboard},
BaoTree, ChunkNum,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/store/fs/import.rs:24:
};
-use bytes::Bytes;
use genawaiter::sync::Gen;
use irpc::{
channel::{mpsc, none::NoReceiver},
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/store/fs/meta.rs:8:
time::SystemTime,
};
-use cyber_bao::BaoTree;
use bytes::Bytes;
+use cyber_bao::BaoTree;
use irpc::channel::mpsc;
use n0_error::{anyerr, e, stack_error, AnyError};
use redb::{Database, DatabaseError, ReadableTable};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/store/fs.rs:77:
},
};
+use bytes::Bytes;
use cyber_bao::{
io::{
- mixed::{traverse_ranges_validated, EncodedItem}, ReadBytesAt,
+ mixed::{traverse_ranges_validated, EncodedItem},
pre_order::PreOrderOutboard,
- BaoContentItem, Leaf, ReadAt,
+ BaoContentItem, Leaf, ReadAt, ReadBytesAt,
},
BaoTree, ChunkNum, ChunkRanges,
};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/store/fs.rs:88:
-use bytes::Bytes;
use delete_set::{BaoFilePart, ProtectHandle};
use entity_manager::{EntityManagerState, SpawnArg};
use entry_state::{DataLocation, OutboardLocation};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/store/mem.rs:16:
sync::Arc,
};
+use bytes::Bytes;
use cyber_bao::{
io::{
- mixed::{traverse_ranges_validated, EncodedItem}, ReadBytesAt,
+ mixed::{traverse_ranges_validated, EncodedItem},
pre_order::PreOrderMemOutboard,
- BaoContentItem, EncodeError, Leaf, Outboard, ReadAt, WriteAt,
+ BaoContentItem, EncodeError, Leaf, Outboard, ReadAt, ReadBytesAt, WriteAt,
},
BaoTree, ChunkNum, ChunkRanges, TreeNode,
};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/store/mem.rs:27:
-use bytes::Bytes;
use irpc::channel::mpsc;
use n0_error::{Result, StdResultExt};
use n0_future::{
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/store/readonly_mem.rs:12:
path::PathBuf,
};
+use bytes::Bytes;
use cyber_bao::{
io::{
- mixed::{traverse_ranges_validated, EncodedItem}, ReadBytesAt,
+ mixed::{traverse_ranges_validated, EncodedItem},
pre_order::PreOrderMemOutboard,
- ReadAt,
- Leaf,
+ Leaf, ReadAt, ReadBytesAt,
},
BaoTree, ChunkRanges,
};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/store/readonly_mem.rs:24:
-use bytes::Bytes;
use irpc::channel::mpsc;
use n0_future::{
future::{self, yield_now},
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/store/util/mem_or_file.rs:4:
io::{self, Read, Seek},
};
-use cyber_bao::io::{
- ReadBytesAt,
- {ReadAt, Size},
-};
use bytes::Bytes;
+use cyber_bao::io::{ReadAt, ReadBytesAt, Size};
use super::SliceInfoExt;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/store/util/partial_mem_storage.rs:1:
use std::io;
use cyber_bao::{
- io::{WriteAt, BaoContentItem},
+ io::{BaoContentItem, WriteAt},
BaoTree,
};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/store/util/sparse_mem_file.rs:1:
use std::{io, ops::Deref};
-use cyber_bao::io::{
- ReadBytesAt,
- {ReadAt, Size, WriteAt},
-};
use bytes::Bytes;
+use cyber_bao::io::{ReadAt, ReadBytesAt, Size, WriteAt};
use range_collections::{range_set::RangeSetRange, RangeSet2};
/// A file that is sparse in memory
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/store/util.rs:1:
use std::{borrow::Borrow, fmt};
-use cyber_bao::io::mixed::EncodedItem;
use bytes::Bytes;
+use cyber_bao::io::mixed::EncodedItem;
use derive_more::{From, Into};
use n0_future::time::SystemTime;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/tests.rs:1:
use std::{collections::HashSet, io, ops::Range, path::PathBuf};
-use cyber_bao::ChunkRanges;
use bytes::Bytes;
+use cyber_bao::ChunkRanges;
use iroh::{address_lookup::MemoryLookup, protocol::Router, Endpoint, EndpointId, RelayMode};
use irpc::RpcMessage;
use n0_future::{task::AbortOnDropHandle, StreamExt};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/util.rs:225:
use std::io::{self, BufReader, Read};
use cyber_bao::{
- io::{
- pre_order::PreOrderOutboard,
- OutboardMut, WriteAt,
- },
+ io::{pre_order::PreOrderOutboard, OutboardMut, WriteAt},
BaoChunk, BaoTree, ChunkNum,
};
use smallvec::SmallVec;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/util.rs:235:
use super::sink::Sink;
- fn hash_subtree(start_chunk: u64, data: &[u8], is_root: bool, block_bytes: usize) -> hemera::Hash {
+ fn hash_subtree(
+ start_chunk: u64,
+ data: &[u8],
+ is_root: bool,
+ block_bytes: usize,
+ ) -> hemera::Hash {
use cyber_bao::hash::Poseidon2Backend;
cyber_bao::io::hash_block(&Poseidon2Backend, data, start_chunk, is_root, block_bytes)
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-blobs/src/util.rs:312:
#[cfg(test)]
mod tests {
- use cyber_bao::{
- io::pre_order::PreOrderOutboard,
- BaoTree,
- };
+ use cyber_bao::{io::pre_order::PreOrderOutboard, BaoTree};
use testresult::TestResult;
use crate::{
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-car/src/header.rs:77:
#[cfg(test)]
mod tests {
use multihash_codetable::MultihashDigest;
-
- use super::*;
-
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::wasm_bindgen_test;
+
+ use super::*;
#[cfg(target_arch = "wasm32")]
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-car/src/lib.rs:6:
mod util;
mod writer;
-pub use crate::error::Error;
-pub use crate::header::CarHeader;
-pub use crate::reader::CarReader;
-pub use crate::writer::CarWriter;
+pub use crate::{error::Error, header::CarHeader, reader::CarReader, writer::CarWriter};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-car/src/reader.rs:65:
use cid::Cid;
use futures::TryStreamExt;
use multihash_codetable::MultihashDigest;
-
- use crate::{header::CarHeaderV1, writer::CarWriter};
-
- use super::*;
-
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::wasm_bindgen_test;
+
+ use super::*;
+ use crate::{header::CarHeaderV1, writer::CarWriter};
#[cfg(target_arch = "wasm32")]
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-car/src/util.rs:84:
#[cfg(test)]
mod tests {
use tokio::io::{AsyncWrite, AsyncWriteExt};
-
- use super::*;
-
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::wasm_bindgen_test;
+
+ use super::*;
#[cfg(target_arch = "wasm32")]
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-car/tests/car_file_test.rs:1:
use futures::TryStreamExt;
use iroh_car::*;
use tokio::io::BufReader;
-
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::wasm_bindgen_test;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-docs/src/engine/live.rs:200:
let (replica_events_tx, replica_events_rx) = async_channel::bounded(1024);
let gossip_state = GossipState::new(gossip, sync.clone(), sync_actor_tx.clone());
let memory_lookup = MemoryLookup::new();
- endpoint.address_lookup().expect("endpoint closed").add(memory_lookup.clone());
+ endpoint
+ .address_lookup()
+ .expect("endpoint closed")
+ .add(memory_lookup.clone());
Self {
inbox,
sync,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-docs/src/ranger.rs:125:
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "32 bytes")
}
- fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Fingerprint, A::Error> {
+ fn visit_seq<A: serde::de::SeqAccess<'de>>(
+ self,
+ mut seq: A,
+ ) -> Result<Fingerprint, A::Error> {
let mut bytes = [0u8; 32];
for (i, byte) in bytes.iter_mut().enumerate() {
- *byte = seq.next_element()?.ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
+ *byte = seq
+ .next_element()?
+ .ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
}
Ok(Fingerprint(bytes))
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-gossip/src/net.rs:185:
pub fn spawn(self, endpoint: Endpoint) -> Gossip {
let metrics = Arc::new(Metrics::default());
let address_lookup = GossipAddressLookup::default();
- endpoint.address_lookup().expect("endpoint closed").add(address_lookup.clone());
+ endpoint
+ .address_lookup()
+ .expect("endpoint closed")
+ .add(address_lookup.clone());
let (actor, rpc_tx, local_tx) = Actor::new(
endpoint,
self.config,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-gossip/src/net.rs:1144:
let endpoint = create_endpoint(rng, relay_map, None).await?;
let metrics = Arc::new(Metrics::default());
let address_lookup = GossipAddressLookup::default();
- endpoint.address_lookup().expect("endpoint closed").add(address_lookup.clone());
+ endpoint
+ .address_lookup()
+ .expect("endpoint closed")
+ .add(address_lookup.clone());
let (actor, to_actor_tx, conn_tx) =
Actor::new(endpoint, config, metrics.clone(), None, address_lookup);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-gossip/src/net.rs:1202:
.await?;
if let Some(memory_lookup) = memory_lookup {
- ep.address_lookup().expect("endpoint closed").add(memory_lookup);
+ ep.address_lookup()
+ .expect("endpoint closed")
+ .add(memory_lookup);
}
ep.online().await;
Ok(ep)
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-gossip/src/net.rs:1404:
"endpoints ready"
);
- let hash_bytes: [u8; 32] = hemera::hash(b"subscription_cleanup").as_bytes()[..32].try_into().unwrap();
+ let hash_bytes: [u8; 32] = hemera::hash(b"subscription_cleanup").as_bytes()[..32]
+ .try_into()
+ .unwrap();
let topic: TopicId = hash_bytes.into();
tracing::info!(%topic, "joining");
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-gossip/src/net.rs:1443:
let addr2 = EndpointAddr::new(endpoint_id2).with_relay_url(relay_url);
let memory_lookup = MemoryLookup::new();
memory_lookup.add_endpoint_info(addr2);
- actor.endpoint.address_lookup().expect("endpoint closed").add(memory_lookup);
+ actor
+ .endpoint
+ .address_lookup()
+ .expect("endpoint closed")
+ .add(memory_lookup);
// we use a channel to signal advancing steps to the task
let (tx, mut rx) = mpsc::channel::<()>(1);
let ct1 = ct.clone();
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-gossip/src/net.rs:1545:
"endpoints ready"
);
- let hash_bytes: [u8; 32] = hemera::hash(b"can_reconnect").as_bytes()[..32].try_into().unwrap();
+ let hash_bytes: [u8; 32] = hemera::hash(b"can_reconnect").as_bytes()[..32]
+ .try_into()
+ .unwrap();
let topic: TopicId = hash_bytes.into();
tracing::info!(%topic, "joining");
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-gossip/src/net.rs:1555:
let addr1 = EndpointAddr::new(endpoint_id1).with_relay_url(relay_url.clone());
let memory_lookup = MemoryLookup::new();
memory_lookup.add_endpoint_info(addr1);
- ep2.address_lookup().expect("endpoint closed").add(memory_lookup.clone());
+ ep2.address_lookup()
+ .expect("endpoint closed")
+ .add(memory_lookup.clone());
let go2_task = async move {
let mut sub = go2.subscribe(topic, Vec::new()).await?;
sub.joined().await?;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-gossip/src/net.rs:1580:
let addr2 = EndpointAddr::new(endpoint_id2).with_relay_url(relay_url);
memory_lookup.add_endpoint_info(addr2);
- ep1.address_lookup().expect("endpoint closed").add(memory_lookup);
+ ep1.address_lookup()
+ .expect("endpoint closed")
+ .add(memory_lookup);
let mut sub = go1.subscribe(topic, vec![endpoint_id2]).await?;
// wait for subscribed notification
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-gossip/src/net.rs:1674:
let bootstrap = vec![bootstrap_addr.id];
let memory_lookup = MemoryLookup::new();
memory_lookup.add_endpoint_info(bootstrap_addr);
- router.endpoint().address_lookup().expect("endpoint closed").add(memory_lookup);
+ router
+ .endpoint()
+ .address_lookup()
+ .expect("endpoint closed")
+ .add(memory_lookup);
let mut topic = gossip.subscribe_and_join(topic_id, bootstrap).await?;
topic.broadcast(message.as_bytes().to_vec().into()).await?;
std::future::pending::<()>().await;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-gossip/src/net.rs:1791:
let id1 = addr1.id;
let memory_lookup = MemoryLookup::new();
memory_lookup.add_endpoint_info(addr1);
- router2.endpoint().address_lookup().expect("endpoint closed").add(memory_lookup);
+ router2
+ .endpoint()
+ .address_lookup()
+ .expect("endpoint closed")
+ .add(memory_lookup);
let mut topic1 = gossip1.subscribe(topic_id, vec![]).await?;
let mut topic2 = gossip2.subscribe(topic_id, vec![id1]).await?;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-gossip/src/net.rs:1843:
lookup.add_endpoint_info(addr1);
// add addr info of endpoint1 to endpoint2 and join endpoint1
- r2.endpoint().address_lookup().expect("endpoint closed").add(lookup.clone());
+ r2.endpoint()
+ .address_lookup()
+ .expect("endpoint closed")
+ .add(lookup.clone());
tx2.join_peers(vec![n1]).await?;
// await join endpoint2 -> nodde1
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-gossip/src/net.rs:1855:
.std_context("wait rx2 join")??;
// add addr info of endpoint1 to endpoint3 and join endpoint1
- r3.endpoint().address_lookup().expect("endpoint closed").add(lookup.clone());
+ r3.endpoint()
+ .address_lookup()
+ .expect("endpoint closed")
+ .add(lookup.clone());
tx3.join_peers(vec![n1]).await?;
// await join at endpoint3: n1 and n2
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-gossip/src/net.rs:1917:
let id1 = addr1.id;
let mem_lookup = MemoryLookup::new();
mem_lookup.add_endpoint_info(addr1);
- router2.endpoint().address_lookup().expect("endpoint closed").add(mem_lookup);
+ router2
+ .endpoint()
+ .address_lookup()
+ .expect("endpoint closed")
+ .add(mem_lookup);
let topic1 = gossip1.subscribe(topic_id, vec![]).await?;
let topic2 = gossip2.subscribe(topic_id, vec![id1]).await?;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-gossip/src/proto/plumtree.rs:50:
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "32 bytes")
}
- fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<MessageId, A::Error> {
+ fn visit_seq<A: serde::de::SeqAccess<'de>>(
+ self,
+ mut seq: A,
+ ) -> Result<MessageId, A::Error> {
let mut bytes = [0u8; 32];
for (i, byte) in bytes.iter_mut().enumerate() {
- *byte = seq.next_element()?.ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
+ *byte = seq
+ .next_element()?
+ .ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
}
Ok(MessageId(bytes))
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/examples/bench.rs:99:
use anyhow::Result;
use bytes::Bytes;
use futures_concurrency::future::TryJoin;
- use iroh::{Endpoint, EndpointId};
- use iroh::address_lookup::memory::MemoryLookup;
+ use iroh::{address_lookup::memory::MemoryLookup, Endpoint, EndpointId};
use iroh_willow::{
engine::{AcceptOpts, Engine},
form::EntryForm,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/examples/bench.rs:205:
pub async fn spawn_two(rng: &mut impl CryptoRngCore) -> Result<[Peer; 2]> {
let disco = MemoryLookup::new();
- let peers = [
- generate_secret_key(rng),
- generate_secret_key(rng),
- ]
- .map(|secret_key| Peer::spawn(secret_key, disco.clone(), Default::default()))
- .try_join()
- .await?;
+ let peers = [generate_secret_key(rng), generate_secret_key(rng)]
+ .map(|secret_key| Peer::spawn(secret_key, disco.clone(), Default::default()))
+ .try_join()
+ .await?;
Ok(peers)
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/engine.rs:7:
future::{MapErr, Shared},
FutureExt, TryFutureExt,
};
-use iroh::{endpoint::Connection, protocol::{AcceptError, ProtocolHandler}, Endpoint, EndpointId};
+use iroh::{
+ endpoint::Connection,
+ protocol::{AcceptError, ProtocolHandler},
+ Endpoint, EndpointId,
+};
use tokio::{
sync::{mpsc, oneshot},
task::JoinError,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/engine.rs:128:
///
/// This can freely be called multiple times for the same peer. The engine will merge the
/// intents and make sure that only a single session is opened per peer.
- pub async fn sync_with_peer(&self, peer: EndpointId, init: SessionInit) -> Result<IntentHandle> {
+ pub async fn sync_with_peer(
+ &self,
+ peer: EndpointId,
+ init: SessionInit,
+ ) -> Result<IntentHandle> {
let (intent, handle) = Intent::new(init);
self.peer_manager_inbox
.send(peer_manager::Input::SubmitIntent { peer, intent })
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/engine.rs:170:
impl ProtocolHandler for Engine {
async fn accept(&self, conn: Connection) -> Result<(), AcceptError> {
- self.handle_connection(conn).await.map_err(|e| AcceptError::from(std::io::Error::other(e)))
+ self.handle_connection(conn)
+ .await
+ .map_err(|e| AcceptError::from(std::io::Error::other(e)))
}
async fn shutdown(&self) {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/form.rs:5:
use bytes::Bytes;
use futures_lite::Stream;
-use iroh_blobs::{
- api::proto::ImportMode,
- Hash,
-};
+use iroh_blobs::{api::proto::ImportMode, Hash};
use serde::{Deserialize, Serialize};
use tokio::io::AsyncRead;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/form.rs:41:
}
impl PayloadForm {
- pub async fn submit(
- self,
- store: &iroh_blobs::api::Store,
- ) -> anyhow::Result<(Hash, u64)> {
+ pub async fn submit(self, store: &iroh_blobs::api::Store) -> anyhow::Result<(Hash, u64)> {
let blobs = store.blobs();
let (hash, len) = match self {
PayloadForm::Hash(digest) => {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/net.rs:482:
let start = Instant::now();
let mut expected_entries = BTreeSet::new();
- let handle_alfie = ActorHandle::spawn_memory(iroh_blobs::store::mem::MemStore::default().into(), node_id_alfie);
- let handle_betty = ActorHandle::spawn_memory(iroh_blobs::store::mem::MemStore::default().into(), node_id_betty);
+ let handle_alfie = ActorHandle::spawn_memory(
+ iroh_blobs::store::mem::MemStore::default().into(),
+ node_id_alfie,
+ );
+ let handle_betty = ActorHandle::spawn_memory(
+ iroh_blobs::store::mem::MemStore::default().into(),
+ node_id_betty,
+ );
let user_alfie = handle_alfie.create_user().await?;
let user_betty = handle_betty.create_user().await?;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/net.rs:618:
let (ep_alfie, node_id_alfie, _) = create_endpoint(&mut rng, &disco).await?;
let (ep_betty, node_id_betty, addr_betty) = create_endpoint(&mut rng, &disco).await?;
- let handle_alfie = ActorHandle::spawn_memory(iroh_blobs::store::mem::MemStore::default().into(), node_id_alfie);
- let handle_betty = ActorHandle::spawn_memory(iroh_blobs::store::mem::MemStore::default().into(), node_id_betty);
+ let handle_alfie = ActorHandle::spawn_memory(
+ iroh_blobs::store::mem::MemStore::default().into(),
+ node_id_alfie,
+ );
+ let handle_betty = ActorHandle::spawn_memory(
+ iroh_blobs::store::mem::MemStore::default().into(),
+ node_id_betty,
+ );
let user_alfie = handle_alfie.create_user().await?;
let user_betty = handle_betty.create_user().await?;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/proto/wgps/challenge.rs:32:
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "32 bytes")
}
- fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<ChallengeHash, A::Error> {
+ fn visit_seq<A: serde::de::SeqAccess<'de>>(
+ self,
+ mut seq: A,
+ ) -> Result<ChallengeHash, A::Error> {
let mut bytes = [0u8; 32];
for (i, byte) in bytes.iter_mut().enumerate() {
- *byte = seq.next_element()?.ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
+ *byte = seq
+ .next_element()?
+ .ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
}
Ok(ChallengeHash(bytes))
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/proto/wgps/fingerprint.rs:47:
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "32 bytes")
}
- fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Fingerprint, A::Error> {
+ fn visit_seq<A: serde::de::SeqAccess<'de>>(
+ self,
+ mut seq: A,
+ ) -> Result<Fingerprint, A::Error> {
let mut bytes = [0u8; 32];
for (i, byte) in bytes.iter_mut().enumerate() {
- *byte = seq.next_element()?.ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
+ *byte = seq
+ .next_element()?
+ .ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
}
Ok(Fingerprint(bytes))
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:55:
/// Create a new namespace in the Willow store.
pub async fn create(&self, kind: NamespaceKind, owner: UserId) -> Result<Space> {
let req = CreateNamespaceRequest { kind, owner };
- let res = self.rpc.rpc(req).await.map_err(|e| anyhow::anyhow!("{e}"))??;
+ let res = self
+ .rpc
+ .rpc(req)
+ .await
+ .map_err(|e| anyhow::anyhow!("{e}"))??;
Ok(Space::new(self.rpc.clone(), res.0))
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:62:
/// Create a new user in the Willow store.
pub async fn create_user(&self) -> Result<UserId> {
let req = CreateUserRequest;
- let res: RpcResult<CreateUserResponse> = self.rpc.rpc(req).await.map_err(|e| anyhow::anyhow!("{e}"))?;
+ let res: RpcResult<CreateUserResponse> = self
+ .rpc
+ .rpc(req)
+ .await
+ .map_err(|e| anyhow::anyhow!("{e}"))?;
let res = res?;
Ok(res.0)
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:79:
access_mode,
to,
};
- let res = self.rpc.rpc(req).await.map_err(|e| anyhow::anyhow!("{e}"))??;
+ let res = self
+ .rpc
+ .rpc(req)
+ .await
+ .map_err(|e| anyhow::anyhow!("{e}"))??;
Ok(res.0)
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:86:
/// Import capabilities.
pub async fn import_caps(&self, caps: Vec<CapabilityPack>) -> Result<()> {
let req = ImportCapsRequest { caps };
- self.rpc.rpc(req).await.map_err(|e| anyhow::anyhow!("{e}"))??;
+ self.rpc
+ .rpc(req)
+ .await
+ .map_err(|e| anyhow::anyhow!("{e}"))??;
Ok(())
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:122:
/// Synchronize with a peer.
pub async fn sync_with_peer(&self, peer: EndpointId, init: SessionInit) -> Result<SyncHandle> {
let req = SyncWithPeerRequest { peer, init };
- let (update_tx, mut event_rx) = self.rpc.bidi_streaming(req, 32, 32).await
+ let (update_tx, mut event_rx) = self
+ .rpc
+ .bidi_streaming(req, 32, 32)
+ .await
.map_err(|e| anyhow::anyhow!("{e}"))?;
let (mapped_tx, mapped_rx) = tokio::sync::mpsc::channel(32);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:142:
}
});
- let event_rx: EventReceiver = Box::pin(tokio_stream::wrappers::ReceiverStream::new(mapped_rx));
+ let event_rx: EventReceiver =
+ Box::pin(tokio_stream::wrappers::ReceiverStream::new(mapped_rx));
- let (mapped_update_tx, mut mapped_update_rx) = tokio::sync::mpsc::channel::<IntentUpdate>(32);
+ let (mapped_update_tx, mut mapped_update_rx) =
+ tokio::sync::mpsc::channel::<IntentUpdate>(32);
tokio::task::spawn(async move {
while let Some(update) = mapped_update_rx.recv().await {
if update_tx.send(SyncWithPeerUpdate(update)).await.is_err() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:153:
}
});
- let update_tx: UpdateSender = Box::pin(futures_util::sink::unfold(mapped_update_tx, |tx, item| async move {
- tx.send(item).await.map_err(|e| anyhow::anyhow!("{e}"))?;
- Ok(tx)
- }));
+ let update_tx: UpdateSender = Box::pin(futures_util::sink::unfold(
+ mapped_update_tx,
+ |tx, item| async move {
+ tx.send(item).await.map_err(|e| anyhow::anyhow!("{e}"))?;
+ Ok(tx)
+ },
+ ));
Ok(SyncHandle::new(update_tx, event_rx, Default::default()))
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:166:
let req = InsertSecretRequest {
secret: secret.into(),
};
- self.rpc.rpc(req).await.map_err(|e| anyhow::anyhow!("{e}"))??;
+ self.rpc
+ .rpc(req)
+ .await
+ .map_err(|e| anyhow::anyhow!("{e}"))??;
Ok(())
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:173:
/// Fetches the [`EndpointAddr`] for this endpoint.
pub async fn addr(&self) -> Result<EndpointAddr> {
- let addr = self.rpc.rpc(AddrRequest).await.map_err(|e| anyhow::anyhow!("{e}"))??;
+ let addr = self
+ .rpc
+ .rpc(AddrRequest)
+ .await
+ .map_err(|e| anyhow::anyhow!("{e}"))??;
Ok(addr)
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:179:
/// Adds a known endpoint address.
pub async fn add_addr(&self, addr: EndpointAddr) -> Result<()> {
- self.rpc.rpc(AddAddrRequest { addr }).await.map_err(|e| anyhow::anyhow!("{e}"))??;
+ self.rpc
+ .rpc(AddAddrRequest { addr })
+ .await
+ .map_err(|e| anyhow::anyhow!("{e}"))??;
Ok(())
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:196:
}
fn spaces(&self) -> Client {
- Client { rpc: self.rpc.clone() }
+ Client {
+ rpc: self.rpc.clone(),
+ }
}
/// Returns the identifier for this space.
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:214:
};
let auth = entry.auth;
let req = InsertEntryRequest { entry: form, auth };
- let res = self.rpc.rpc(req).await.map_err(|e| anyhow::anyhow!("{e}"))??;
+ let res = self
+ .rpc
+ .rpc(req)
+ .await
+ .map_err(|e| anyhow::anyhow!("{e}"))??;
Ok(res)
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:231:
entry: EntryForm,
payload: impl Into<Bytes>,
) -> Result<InsertEntrySuccess> {
- let tag = blobs
- .blobs()
- .add_bytes(payload.into())
- .temp_tag()
- .await?;
+ let tag = blobs.blobs().add_bytes(payload.into()).temp_tag().await?;
self.insert_hash(entry, tag.hash()).await
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:242:
/// Ingest an authorised entry.
pub async fn ingest(&self, authorised_entry: AuthorisedEntry) -> Result<()> {
let req = IngestEntryRequest { authorised_entry };
- self.rpc.rpc(req).await.map_err(|e| anyhow::anyhow!("{e}"))??;
+ self.rpc
+ .rpc(req)
+ .await
+ .map_err(|e| anyhow::anyhow!("{e}"))??;
Ok(())
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:257:
subspace,
path,
};
- let entry = self.rpc.rpc(req).await.map_err(|e| anyhow::anyhow!("{e}"))??;
+ let entry = self
+ .rpc
+ .rpc(req)
+ .await
+ .map_err(|e| anyhow::anyhow!("{e}"))??;
Ok(entry.0.map(Into::into))
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:270:
namespace: self.namespace_id,
range,
};
- let rx = self.rpc.server_streaming(req, 64).await
+ let rx = self
+ .rpc
+ .server_streaming(req, 64)
+ .await
.map_err(|e| anyhow::anyhow!("{e}"))?;
- Ok(rx.into_stream()
- .map(|res| match res {
- Ok(Ok(r)) => Ok(r.0),
- Ok(Err(e)) => Err(anyhow::anyhow!("{e}")),
- Err(e) => Err(anyhow::anyhow!("{e}")),
- }))
+ Ok(rx.into_stream().map(|res| match res {
+ Ok(Ok(r)) => Ok(r.0),
+ Ok(Err(e)) => Err(anyhow::anyhow!("{e}")),
+ Err(e) => Err(anyhow::anyhow!("{e}")),
+ }))
}
/// Syncs with a peer and quit the session after a single reconciliation.
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:338:
params,
initial_progress_id: None,
};
- let rx = self.rpc.server_streaming(req, 1024).await
+ let rx = self
+ .rpc
+ .server_streaming(req, 1024)
+ .await
.map_err(|e| anyhow::anyhow!("{e}"))?;
- let stream = rx.into_stream()
- .map(|item| match item {
- Ok(Ok(event)) => Ok(event),
- Ok(Err(e)) => Err(anyhow::anyhow!("{e}")),
- Err(e) => Err(anyhow::anyhow!("{e}")),
- });
+ let stream = rx.into_stream().map(|item| match item {
+ Ok(Ok(event)) => Ok(event),
+ Ok(Err(e)) => Err(anyhow::anyhow!("{e}")),
+ Err(e) => Err(anyhow::anyhow!("{e}")),
+ });
Ok(stream)
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:362:
params,
initial_progress_id: Some(progress_id),
};
- let rx = self.rpc.server_streaming(req, 1024).await
+ let rx = self
+ .rpc
+ .server_streaming(req, 1024)
+ .await
.map_err(|e| anyhow::anyhow!("{e}"))?;
- let stream = rx.into_stream()
- .map(|item| match item {
- Ok(Ok(event)) => Ok(event),
- Ok(Err(e)) => Err(anyhow::anyhow!("{e}")),
- Err(e) => Err(anyhow::anyhow!("{e}")),
- });
+ let stream = rx.into_stream().map(|item| match item {
+ Ok(Ok(event)) => Ok(event),
+ Ok(Err(e)) => Err(anyhow::anyhow!("{e}")),
+ Err(e) => Err(anyhow::anyhow!("{e}")),
+ });
Ok(stream)
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:392:
}
/// Sends updates into a reconciliation intent.
-pub type UpdateSender = Pin<Box<dyn futures_util::Sink<IntentUpdate, Error = anyhow::Error> + Send + 'static>>;
+pub type UpdateSender =
+ Pin<Box<dyn futures_util::Sink<IntentUpdate, Error = anyhow::Error> + Send + 'static>>;
/// Receives events for a reconciliation intent.
pub type EventReceiver = Pin<Box<dyn Stream<Item = Event> + Send + 'static>>;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/client.rs:498:
impl SyncHandleSet {
/// Add a sync intent to the set.
- pub fn insert(&mut self, peer: EndpointId, handle: SyncHandle) -> Result<(), IntentExistsError> {
+ pub fn insert(
+ &mut self,
+ peer: EndpointId,
+ handle: SyncHandle,
+ ) -> Result<(), IntentExistsError> {
if let std::collections::hash_map::Entry::Vacant(e) = self.intents.entry(peer) {
let SyncHandle {
update_tx,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/handler.rs:147:
let WithChannels { tx, rx, inner, .. } = msg;
let (events_tx, mut events_rx) = tokio::sync::mpsc::channel(32);
tokio::task::spawn(async move {
- if let Err(err) =
- sync_with_peer(&engine, inner, events_tx.clone(), rx).await
- {
+ if let Err(err) = sync_with_peer(&engine, inner, events_tx.clone(), rx).await {
let _ = events_tx.send(Err(RpcError::new(&*err))).await;
}
});
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/rpc/proto.rs:1:
use iroh::{EndpointAddr, EndpointId};
use iroh_blobs::Hash;
-use irpc::{channel::{mpsc, oneshot}, rpc_requests};
+use irpc::{
+ channel::{mpsc, oneshot},
+ rpc_requests,
+};
use serde::{Deserialize, Serialize};
use crate::{
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/session/intents.rs:192:
pub struct SendError<T>(pub T);
impl IntentHandle {
- pub fn new(
- update_tx: UpdateSender,
- event_rx: EventReceiver,
- ) -> Self {
+ pub fn new(update_tx: UpdateSender, event_rx: EventReceiver) -> Self {
Self {
update_tx,
event_rx,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/session/payload.rs:27:
) -> Result<bool, Error> {
let hash: Hash = digest.into();
let blobs = payload_store.blobs();
- let status = blobs.status(hash).await.map_err(|e| Error::PayloadStore(io::Error::other(e.to_string())))?;
+ let status = blobs
+ .status(hash)
+ .await
+ .map_err(|e| Error::PayloadStore(io::Error::other(e.to_string())))?;
let size = match status {
iroh_blobs::api::blobs::BlobStatus::Complete { size } => size,
_ => return Ok(false),
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/session/payload.rs:34:
};
// Export the blob data as a single byte range and send as chunks
- let data = blobs.export_ranges(hash, offset..size)
+ let data = blobs
+ .export_ranges(hash, offset..size)
.concatenate()
.await
.map_err(|e| Error::PayloadStore(io::Error::other(e.to_string())))?;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/session/payload.rs:112:
let fut = async move {
// Use the blobs API to import the data by collecting chunks
let stream = tokio_stream::wrappers::ReceiverStream::new(rx);
- let _temp_tag = store.blobs().add_stream(stream).await.temp_tag().await
+ let _temp_tag = store
+ .blobs()
+ .add_stream(stream)
+ .await
+ .temp_tag()
+ .await
.map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;
// Verify hash matches
if _temp_tag.hash() != hash {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/src/session/payload.rs:124:
Ok(())
};
let task = tokio::task::spawn_local(fut);
- PayloadWriter {
- task,
- sender: tx,
- }
+ PayloadWriter { task, sender: tx }
});
writer.sender.send(Ok(chunk)).await?;
state.received_length += len as u64;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/tests/basic.rs:285:
let mut rng = create_rng("read_back_write");
let disco = iroh::address_lookup::memory::MemoryLookup::new();
- let alfie = Peer::spawn(util::generate_secret_key(&mut rng), Default::default(), disco).await?;
+ let alfie = Peer::spawn(
+ util::generate_secret_key(&mut rng),
+ Default::default(),
+ disco,
+ )
+ .await?;
let user_alfie = alfie.create_user().await?;
let namespace_id = alfie
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-willow/tests/basic.rs:487:
pub async fn spawn_two(mut rng: &mut impl CryptoRngCore) -> Result<[Peer; 2]> {
let disco = iroh::address_lookup::memory::MemoryLookup::new();
- let peers = [
- generate_secret_key(&mut rng),
- generate_secret_key(&mut rng),
- ]
- .map(|secret_key| Peer::spawn(secret_key, Default::default(), disco.clone()))
- .try_join()
- .await?;
+ let peers = [generate_secret_key(&mut rng), generate_secret_key(&mut rng)]
+ .map(|secret_key| Peer::spawn(secret_key, Default::default(), disco.clone()))
+ .try_join()
+ .await?;
disco.add_endpoint_info(peers[0].endpoint.addr());
disco.add_endpoint_info(peers[1].endpoint.addr());
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/bench/src/bin/bulk.rs:5:
};
use anyhow::{Context, Result};
-use clap::Parser;
-use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};
-use tokio::sync::Semaphore;
-use tracing::{info, trace};
-
use bench::{
Opt, configure_tracing_subscriber, connect_client, drain_stream, rt, send_data_on_stream,
server_endpoint,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/bench/src/bin/bulk.rs:16:
stats::{Stats, TransferResult},
};
+use clap::Parser;
+use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};
+use tokio::sync::Semaphore;
+use tracing::{info, trace};
fn main() {
let opt = Opt::parse();
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/fuzz/fuzz_targets/streams.rs:5:
use libfuzzer_sys::fuzz_target;
extern crate proto;
-use proto::fuzzing::{ConnectionState, ResetStream, Retransmits, StreamsState};
-use proto::{Dir, Side, StreamId, VarInt};
-use proto::{SendStream, Streams};
+use proto::{
+ Dir, SendStream, Side, StreamId, Streams, VarInt,
+ fuzzing::{ConnectionState, ResetStream, Retransmits, StreamsState},
+};
#[derive(Arbitrary, Debug)]
struct StreamParams {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/perf/src/bin/perf.rs:1:
use clap::{Parser, Subcommand};
+use perf::{client, server};
use tracing::error;
use tracing_subscriber::{EnvFilter, Layer, fmt, layer::SubscriberExt, util::SubscriberInitExt};
-
-use perf::{client, server};
#[tokio::main(flavor = "current_thread")]
async fn main() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/perf/src/noprotection.rs:1:
use std::sync::Arc;
use bytes::BytesMut;
-
use quinn_proto::{
ConnectionId, PathId, Side, TransportError,
crypto::{
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/perf/src/stats.rs:1:
+use std::{
+ sync::{
+ Arc, Mutex,
+ atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
+ },
+ time::{Duration, Instant, SystemTime},
+};
+
use hdrhistogram::Histogram;
use quinn::StreamId;
-use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
-use std::sync::{Arc, Mutex};
-use std::time::{Duration, Instant, SystemTime};
#[cfg(feature = "json-output")]
use {std::fs::File, std::io, std::path::Path};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/perf/src/stats.rs:245:
#[cfg(feature = "json-output")]
mod json {
- use crate::stats;
- use crate::stats::{Stats, StreamIntervalStats};
+ use std::{
+ io::Write,
+ time::{SystemTime, UNIX_EPOCH},
+ };
+
use quinn::StreamId;
use serde::{self, Serialize, Serializer, ser::SerializeStruct};
- use std::io::Write;
- use std::time::{SystemTime, UNIX_EPOCH};
+
+ use crate::{
+ stats,
+ stats::{Stats, StreamIntervalStats},
+ };
pub(crate) fn print<W: Write>(stats: &Stats, out: W) {
let report = Report {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/radio-cli/src/main.rs:1:
-use std::fs;
-use std::io::{self, Read, Write as _};
-use std::path::PathBuf;
+use std::{
+ fs,
+ io::{self, Read, Write as _},
+ path::PathBuf,
+};
-use anyhow::{Context, Result, bail};
+use anyhow::{bail, Context, Result};
use bytes::Bytes;
use clap::{Parser, Subcommand};
+use cyber_bao::{
+ hash::Poseidon2Backend,
+ io::{decode, encode, outboard},
+ tree::BlockSize,
+};
use futures_lite::StreamExt;
-use iroh::{Endpoint, RelayMode, SecretKey};
-use iroh::protocol::Router;
-use iroh_blobs::{BlobsProtocol, Hash, store::mem::MemStore};
-use iroh_gossip::net::{Gossip, GOSSIP_ALPN};
-use iroh_gossip::proto::TopicId;
+use iroh::{protocol::Router, Endpoint, RelayMode, SecretKey};
+use iroh_blobs::{store::mem::MemStore, BlobsProtocol, Hash};
+use iroh_gossip::{
+ net::{Gossip, GOSSIP_ALPN},
+ proto::TopicId,
+};
-use cyber_bao::hash::Poseidon2Backend;
-use cyber_bao::io::{decode, encode, outboard};
-use cyber_bao::tree::BlockSize;
-
#[derive(Parser)]
#[command(name = "radio", about = "Radio network CLI", version)]
struct Cli {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/radio-cli/src/main.rs:140:
match cli.command {
Commands::Hash { action } => cmd_hash(action),
- Commands::Node { action } => {
- tokio::runtime::Builder::new_multi_thread()
- .enable_all()
- .build()?
- .block_on(cmd_node(action))
- }
- Commands::Blob { action } => {
- tokio::runtime::Builder::new_multi_thread()
- .enable_all()
- .build()?
- .block_on(cmd_blob(action))
- }
- Commands::Gossip { action } => {
- tokio::runtime::Builder::new_multi_thread()
- .enable_all()
- .build()?
- .block_on(cmd_gossip(action))
- }
+ Commands::Node { action } => tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()?
+ .block_on(cmd_node(action)),
+ Commands::Blob { action } => tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()?
+ .block_on(cmd_blob(action)),
+ Commands::Gossip { action } => tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()?
+ .block_on(cmd_gossip(action)),
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/radio-cli/src/main.rs:173:
println!("{h}");
} else {
for path in &files {
- let data = fs::read(path)
- .with_context(|| format!("reading {}", path.display()))?;
+ let data =
+ fs::read(path).with_context(|| format!("reading {}", path.display()))?;
let h = hemera::hash(&data);
if files.len() > 1 {
println!("{h} {}", path.display());
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/radio-cli/src/main.rs:185:
}
}
HashAction::Verify { file, hash } => {
- let data = fs::read(&file)
- .with_context(|| format!("reading {}", file.display()))?;
+ let data = fs::read(&file).with_context(|| format!("reading {}", file.display()))?;
let expected = parse_poseidon_hash(&hash)?;
let backend = Poseidon2Backend;
let ob = outboard::outboard(&backend, &data, BlockSize::ZERO);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/radio-cli/src/main.rs:200:
}
}
HashAction::BaoEncode { file } => {
- let data = fs::read(&file)
- .with_context(|| format!("reading {}", file.display()))?;
+ let data = fs::read(&file).with_context(|| format!("reading {}", file.display()))?;
let backend = Poseidon2Backend;
let (root, encoded) = encode::encode(&backend, &data, BlockSize::ZERO);
io::stdout().write_all(&encoded)?;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/radio-cli/src/main.rs:209:
eprintln!("encoded size: {} bytes", encoded.len());
}
HashAction::BaoDecode { file, hash } => {
- let encoded = fs::read(&file)
- .with_context(|| format!("reading {}", file.display()))?;
+ let encoded = fs::read(&file).with_context(|| format!("reading {}", file.display()))?;
let root = parse_poseidon_hash(&hash)?;
let backend = Poseidon2Backend;
match decode::decode(&backend, &encoded, &root, BlockSize::ZERO) {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/radio-cli/src/main.rs:225:
}
}
HashAction::Outboard { file } => {
- let data = fs::read(&file)
- .with_context(|| format!("reading {}", file.display()))?;
+ let data = fs::read(&file).with_context(|| format!("reading {}", file.display()))?;
let backend = Poseidon2Backend;
let ob = outboard::outboard(&backend, &data, BlockSize::ZERO);
println!("root hash: {}", ob.root);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/radio-cli/src/main.rs:241:
fn parse_poseidon_hash(hex: &str) -> Result<hemera::Hash> {
let bytes = hex_to_bytes(hex).context("invalid hex hash")?;
if bytes.len() != 32 {
- bail!("hash must be 32 bytes (64 hex chars), got {} bytes", bytes.len());
+ bail!(
+ "hash must be 32 bytes (64 hex chars), got {} bytes",
+ bytes.len()
+ );
}
let mut arr = [0u8; 32];
arr.copy_from_slice(&bytes);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/radio-cli/src/main.rs:266:
match action {
NodeAction::Id => {
let secret_key = SecretKey::generate(&mut rand::rng());
- println!("secret key: {}", data_encoding::HEXLOWER.encode(&secret_key.to_bytes()));
+ println!(
+ "secret key: {}",
+ data_encoding::HEXLOWER.encode(&secret_key.to_bytes())
+ );
println!("endpoint id: {}", secret_key.public());
}
NodeAction::Start => {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/radio-cli/src/main.rs:275:
Err(_) => {
let sk = SecretKey::generate(&mut rand::rng());
eprintln!("generated new secret key (set RADIO_SECRET to reuse):");
- eprintln!(" RADIO_SECRET={}", data_encoding::HEXLOWER.encode(&sk.to_bytes()));
+ eprintln!(
+ " RADIO_SECRET={}",
+ data_encoding::HEXLOWER.encode(&sk.to_bytes())
+ );
sk
}
};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/radio-cli/src/main.rs:326:
.accept(iroh_blobs::ALPN, blobs)
.spawn();
- let tag = store.blobs().add_path(&path).await
+ let tag = store
+ .blobs()
+ .add_path(&path)
+ .await
.with_context(|| format!("importing {}", path.display()))?;
println!("{}", tag.hash);
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/radio-cli/src/main.rs:353:
store.remote().fetch(conn, blob_hash).await?;
let data = store.blobs().get_bytes(blob_hash).await?;
- fs::write(&out, &data)
- .with_context(|| format!("writing {}", out.display()))?;
+ fs::write(&out, &data).with_context(|| format!("writing {}", out.display()))?;
println!("downloaded {} bytes to {}", data.len(), out.display());
}
BlobAction::List => {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/radio-cli/src/main.rs:363:
let mut count = 0u64;
while let Some(item) = stream.next().await {
let info = item?;
- println!("{} {:?} {}", info.hash, info.format, String::from_utf8_lossy(info.name.as_ref()));
+ println!(
+ "{} {:?} {}",
+ info.hash,
+ info.format,
+ String::from_utf8_lossy(info.name.as_ref())
+ );
count += 1;
}
if count == 0 {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/tests/integration/tests/blob_transfer.rs:1:
use anyhow::Result;
-use radio_integration_tests::{init_tracing, spawn_pair, spawn_nodes, test_rng};
+use radio_integration_tests::{init_tracing, spawn_nodes, spawn_pair, test_rng};
#[tokio::test]
async fn blob_add_and_fetch_small() -> Result<()> {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/tests/integration/tests/blob_transfer.rs:163:
.connect(nodes[0].addr(), iroh_blobs::ALPN)
.await?;
nodes[1].store.remote().fetch(conn1, tt.hash).await?;
- assert_eq!(nodes[1].store.get_bytes(tt.hash).await?.as_ref(), data.as_ref());
+ assert_eq!(
+ nodes[1].store.get_bytes(tt.hash).await?.as_ref(),
+ data.as_ref()
+ );
// Node 2 fetches from node 0
let conn2 = nodes[2]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/tests/integration/tests/blob_transfer.rs:172:
.connect(nodes[0].addr(), iroh_blobs::ALPN)
.await?;
nodes[2].store.remote().fetch(conn2, tt.hash).await?;
- assert_eq!(nodes[2].store.get_bytes(tt.hash).await?.as_ref(), data.as_ref());
+ assert_eq!(
+ nodes[2].store.get_bytes(tt.hash).await?.as_ref(),
+ data.as_ref()
+ );
for node in nodes {
node.shutdown().await?;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/tests/integration/tests/doc_sync.rs:80:
wait_for_content_ready(&mut events_a, hash_b, Duration::from_secs(30)).await?;
// Verify both entries exist on both nodes
- let entry_a_on_b = doc_b
- .get_exact(author_a, b"from_a".to_vec(), false)
- .await?;
+ let entry_a_on_b = doc_b.get_exact(author_a, b"from_a".to_vec(), false).await?;
assert!(entry_a_on_b.is_some());
- let entry_b_on_a = doc_a
- .get_exact(author_b, b"from_b".to_vec(), false)
- .await?;
+ let entry_b_on_a = doc_a.get_exact(author_b, b"from_b".to_vec(), false).await?;
assert!(entry_b_on_a.is_some());
tokio::try_join!(node_a.shutdown(), node_b.shutdown())?;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/tests/integration/tests/full_pipeline.rs:27:
// set_bytes stores the value and creates an entry whose content_hash is the hash of the value
let entry_hash = doc_a
- .set_bytes(
- author_a,
- b"pinned-file".to_vec(),
- blob_data.to_vec(),
- )
+ .set_bytes(author_a, b"pinned-file".to_vec(), blob_data.to_vec())
.await?;
// The hash from set_bytes is the content hash (BAO root of the value bytes)
assert_eq!(entry_hash, blob_hash);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/tests/integration/tests/gossip_broadcast.rs:12:
let mut rng = test_rng(b"gossip_two");
let (node_a, node_b) = spawn_pair(&mut rng).await?;
- let hash_bytes: [u8; 32] = hemera::hash(b"gossip-two-nodes").as_bytes()[..32].try_into().unwrap();
+ let hash_bytes: [u8; 32] = hemera::hash(b"gossip-two-nodes").as_bytes()[..32]
+ .try_into()
+ .unwrap();
let topic: iroh_gossip::TopicId = hash_bytes.into();
// Both nodes subscribe without blocking; node B bootstraps off node A
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/tests/integration/tests/gossip_broadcast.rs:56:
let mut rng = test_rng(b"gossip_fan_out");
let nodes = spawn_nodes(3, &mut rng).await?;
- let hash_bytes: [u8; 32] = hemera::hash(b"gossip-fan-out").as_bytes()[..32].try_into().unwrap();
+ let hash_bytes: [u8; 32] = hemera::hash(b"gossip-fan-out").as_bytes()[..32]
+ .try_into()
+ .unwrap();
let topic: iroh_gossip::TopicId = hash_bytes.into();
// All subscribe; nodes 1 and 2 bootstrap off node 0
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/tests/integration/tests/gossip_broadcast.rs:112:
let mut rng = test_rng(b"gossip_bidir");
let (node_a, node_b) = spawn_pair(&mut rng).await?;
- let hash_bytes: [u8; 32] = hemera::hash(b"gossip-bidir").as_bytes()[..32].try_into().unwrap();
+ let hash_bytes: [u8; 32] = hemera::hash(b"gossip-bidir").as_bytes()[..32]
+ .try_into()
+ .unwrap();
let topic: iroh_gossip::TopicId = hash_bytes.into();
// Both subscribe; node B bootstraps off node A
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/tests/integration/tests/gossip_broadcast.rs:156:
// --- Helpers ---
-async fn wait_for_received(
- receiver: &mut GossipReceiver,
- timeout: Duration,
-) -> Result<Bytes> {
+async fn wait_for_received(receiver: &mut GossipReceiver, timeout: Duration) -> Result<Bytes> {
let deadline = tokio::time::Instant::now() + timeout;
loop {
let item = tokio::time::timeout_at(deadline, receiver.next())
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/bench/benches/hash.rs:3:
// crystal-type: source
// crystal-domain: comp
// ---
-use criterion::{black_box, criterion_group, criterion_main, Criterion, Throughput};
+use criterion::{Criterion, Throughput, black_box, criterion_group, criterion_main};
fn bench_hash(c: &mut Criterion) {
for size in [0, 64, 256, 1024, 4096, 65536] {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/bench/benches/permutation.rs:3:
// crystal-type: source
// crystal-domain: comp
// ---
-use criterion::{black_box, criterion_group, criterion_main, Criterion};
-use cyber_hemera::field::Goldilocks;
-use cyber_hemera::permutation::permute;
-use cyber_hemera::WIDTH;
+use criterion::{Criterion, black_box, criterion_group, criterion_main};
+use cyber_hemera::{WIDTH, field::Goldilocks, permutation::permute};
fn bench_permutation(c: &mut Criterion) {
let mut state = [Goldilocks::ZERO; WIDTH];
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/bench/benches/tree.rs:3:
// crystal-type: source
// crystal-domain: comp
// ---
-use criterion::{black_box, criterion_group, criterion_main, Criterion, Throughput};
+use criterion::{Criterion, Throughput, black_box, criterion_group, criterion_main};
fn bench_tree(c: &mut Criterion) {
for size in [4096, 16384, 65536, 262144] {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/cli/src/main.rs:3:
// crystal-type: source
// crystal-domain: comp
// ---
-use std::fs::{self, File};
-use std::io::{self, Read, Write};
-use std::path::Path;
-use std::process;
-use std::time::Instant;
+use std::{
+ fs::{self, File},
+ io::{self, Read, Write},
+ path::Path,
+ process,
+ time::Instant,
+};
use cyber_hemera_wgsl::GpuContext;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/cli/src/main.rs:41:
fn progress_status(label: &str) -> impl Fn(usize, usize) + '_ {
let last_permille = std::cell::Cell::new(u16::MAX);
move |done, total| {
- if total == 0 { return; }
+ if total == 0 {
+ return;
+ }
let permille = ((done as u64 * 1000) / total as u64) as u16;
if permille != last_permille.get() {
last_permille.set(permille);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/cli/src/main.rs:169:
}
process::exit(show_tree(&args[1]));
}
- Some("prove") => {
- match args.len() {
- 2 => process::exit(prove_node(&args[1], 0, 1)),
- 3 => {
- if let Some((s, e)) = args[2].split_once(':') {
- let start: u64 = s.parse().unwrap_or_else(|_| {
- eprintln!("hemera: invalid range start: {s}");
- process::exit(1);
- });
- let end: u64 = e.parse().unwrap_or_else(|_| {
- eprintln!("hemera: invalid range end: {e}");
- process::exit(1);
- });
- process::exit(prove_node(&args[1], start, end));
- } else {
- let idx: u64 = args[2].parse().unwrap_or_else(|_| {
- eprintln!("hemera: invalid chunk index: {}", args[2]);
- process::exit(1);
- });
- process::exit(prove_node(&args[1], idx, idx + 1));
- }
+ Some("prove") => match args.len() {
+ 2 => process::exit(prove_node(&args[1], 0, 1)),
+ 3 => {
+ if let Some((s, e)) = args[2].split_once(':') {
+ let start: u64 = s.parse().unwrap_or_else(|_| {
+ eprintln!("hemera: invalid range start: {s}");
+ process::exit(1);
+ });
+ let end: u64 = e.parse().unwrap_or_else(|_| {
+ eprintln!("hemera: invalid range end: {e}");
+ process::exit(1);
+ });
+ process::exit(prove_node(&args[1], start, end));
+ } else {
+ let idx: u64 = args[2].parse().unwrap_or_else(|_| {
+ eprintln!("hemera: invalid chunk index: {}", args[2]);
+ process::exit(1);
+ });
+ process::exit(prove_node(&args[1], idx, idx + 1));
}
- _ => {
- eprintln!("hemera: prove requires <file> [chunk | start:end]");
- process::exit(1);
- }
}
- }
+ _ => {
+ eprintln!("hemera: prove requires <file> [chunk | start:end]");
+ process::exit(1);
+ }
+ },
Some("encode") => {
let ctx = Ctx::new(forced);
match args.len() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/cli/src/main.rs:210:
}
Some("decode") => match args.len() {
3 => process::exit(cmd_decode(&args[1], &args[2], None)),
- 5 if args[3] == "-o" => {
- process::exit(cmd_decode(&args[1], &args[2], Some(&args[4])))
- }
+ 5 if args[3] == "-o" => process::exit(cmd_decode(&args[1], &args[2], Some(&args[4]))),
_ => {
eprintln!("hemera: decode requires <file> <hash> [-o output]");
process::exit(1);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/cli/src/main.rs:250:
eprintln!("hemera: prove-batch requires <file> <index>...");
process::exit(1);
}
- let indices: Vec<u64> = args[2..].iter().map(|s| {
- s.parse().unwrap_or_else(|_| {
- eprintln!("hemera: invalid chunk index: {s}");
- process::exit(1);
+ let indices: Vec<u64> = args[2..]
+ .iter()
+ .map(|s| {
+ s.parse().unwrap_or_else(|_| {
+ eprintln!("hemera: invalid chunk index: {s}");
+ process::exit(1);
+ })
})
- }).collect();
+ .collect();
process::exit(cmd_prove_batch(&args[1], &indices));
}
Some("verify-batch") => {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/cli/src/main.rs:267:
}
Some("sparse") => {
if args.len() < 2 {
- eprintln!("hemera: sparse requires a subcommand (new, insert, get, prove, verify, root)");
+ eprintln!(
+ "hemera: sparse requires a subcommand (new, insert, get, prove, verify, root)"
+ );
process::exit(1);
}
process::exit(cmd_sparse(&args[1..]));
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/cli/src/main.rs:356:
#[allow(unknown_lints, rs_no_vec)]
fn hash_file(ctx: &Ctx, path: &Path) -> io::Result<(String, Backend, std::time::Duration)> {
let meta = fs::metadata(path)?;
- status(&format!("reading {} ({})", path.display(), fmt_size(meta.len())));
+ status(&format!(
+ "reading {} ({})",
+ path.display(),
+ fmt_size(meta.len())
+ ));
let mut file = File::open(path)?;
let mut data = Vec::new();
file.read_to_end(&mut data)?;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/cli/src/main.rs:385:
};
let n = cyber_hemera::tree::num_chunks(data.len());
- let tree = cyber_hemera::tree::build_tree_with_progress(&data, progress_status("building tree"));
+ let tree =
+ cyber_hemera::tree::build_tree_with_progress(&data, progress_status("building tree"));
status_clear();
println!("file: {path}");
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/cli/src/main.rs:857:
// hemera sparse verify <proof-file> <root-hash> [--value <file>] [--depth N]
// Omitting --value means non-inclusion proof.
if args.len() < 3 {
- eprintln!("hemera: sparse verify requires <proof-file> <root-hash> [--value <file>] [--depth N]");
+ eprintln!(
+ "hemera: sparse verify requires <proof-file> <root-hash> [--value <file>] [--depth N]"
+ );
return 1;
}
let proof_path = &args[1];
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/cli/src/main.rs:919:
}
#[allow(unknown_lints, rs_no_vec)]
-fn cmd_sparse_verify(proof_path: &str, root_hex: &str, value_path: Option<&str>, depth: u32) -> i32 {
+fn cmd_sparse_verify(
+ proof_path: &str,
+ root_hex: &str,
+ value_path: Option<&str>,
+ depth: u32,
+) -> i32 {
let root = match parse_hash(root_hex) {
Some(h) => h,
None => {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/cli/src/main.rs:988:
}
};
- let proof = cyber_hemera::sparse::CompressedSparseProof { key, bitmask, siblings };
+ let proof = cyber_hemera::sparse::CompressedSparseProof {
+ key,
+ bitmask,
+ siblings,
+ };
let value_data = match value_path {
Some(p) => match fs::read(p) {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/cli/src/main.rs:1002:
};
let t = Instant::now();
- let valid = cyber_hemera::sparse::SparseTree::verify(
- &proof,
- value_data.as_deref(),
- &root,
- depth,
- );
+ let valid =
+ cyber_hemera::sparse::SparseTree::verify(&proof, value_data.as_deref(), &root, depth);
let elapsed = t.elapsed();
print_timing(Backend::Cpu, elapsed);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/cli/src/main.rs:1014:
if valid {
- let kind = if value_data.is_some() { "inclusion" } else { "non-inclusion" };
+ let kind = if value_data.is_some() {
+ "inclusion"
+ } else {
+ "non-inclusion"
+ };
println!("sparse verify ({kind}): OK");
0
} else {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/async_io.rs:14:
extern crate std;
-use core::pin::Pin;
-use core::task::{Context, Poll};
+use core::{
+ pin::Pin,
+ task::{Context, Poll},
+};
/// Async byte reader.
pub trait AsyncRead {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/async_io.rs:37:
) -> Poll<std::io::Result<usize>>;
/// Flush buffered output.
- fn poll_flush(
- self: Pin<&mut Self>,
- cx: &mut Context<'_>,
- ) -> Poll<std::io::Result<()>>;
+ fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>>;
}
// โโ Helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/async_io.rs:52:
) -> std::io::Result<()> {
let mut filled = 0;
while filled < buf.len() {
- let n = core::future::poll_fn(|cx| {
- Pin::new(&mut *reader).poll_read(cx, &mut buf[filled..])
- })
- .await?;
+ let n =
+ core::future::poll_fn(|cx| Pin::new(&mut *reader).poll_read(cx, &mut buf[filled..]))
+ .await?;
if n == 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/async_io.rs:68:
}
/// Write all bytes in `buf`.
-pub async fn write_all<W: AsyncWrite + Unpin>(
- writer: &mut W,
- buf: &[u8],
-) -> std::io::Result<()> {
+pub async fn write_all<W: AsyncWrite + Unpin>(writer: &mut W, buf: &[u8]) -> std::io::Result<()> {
let mut written = 0;
while written < buf.len() {
- let n = core::future::poll_fn(|cx| {
- Pin::new(&mut *writer).poll_write(cx, &buf[written..])
- })
- .await?;
+ let n = core::future::poll_fn(|cx| Pin::new(&mut *writer).poll_write(cx, &buf[written..]))
+ .await?;
if n == 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::WriteZero,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/async_io.rs:115:
Pin::new(&mut **self.get_mut()).poll_write(cx, buf)
}
- fn poll_flush(
- self: Pin<&mut Self>,
- cx: &mut Context<'_>,
- ) -> Poll<std::io::Result<()>> {
+ fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut **self.get_mut()).poll_flush(cx)
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/async_io.rs:132:
Poll::Ready(std::io::Write::write(self.get_mut(), buf))
}
- fn poll_flush(
- self: Pin<&mut Self>,
- _cx: &mut Context<'_>,
- ) -> Poll<std::io::Result<()>> {
+ fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Poll::Ready(std::io::Write::flush(self.get_mut()))
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/batch.rs:10:
//! Construction and verification follow the same recursive tree walk,
//! so sibling ordering is deterministic.
-use crate::params::CHUNK_SIZE;
-use crate::sponge::Hash;
-use crate::tree::{hash_leaf, hash_node, merge_range, num_chunks};
+use crate::{
+ params::CHUNK_SIZE,
+ sponge::Hash,
+ tree::{hash_leaf, hash_node, merge_range, num_chunks},
+};
/// A batch Merkle inclusion proof for multiple leaves.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/batch.rs:108:
let (left_hash, right_hash) = if left_has && right_has {
// Both subtrees have targets โ recurse both, no sibling needed.
let l = collect_siblings(data, offset, split, targets, false, siblings);
- let r = collect_siblings(data, offset + split, count - split, targets, false, siblings);
+ let r = collect_siblings(
+ data,
+ offset + split,
+ count - split,
+ targets,
+ false,
+ siblings,
+ );
(l, r)
} else if left_has {
// Only left has targets โ right subtree becomes a sibling.
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/batch.rs:120:
// Only right has targets โ left subtree becomes a sibling.
let l = merge_range(data, offset, split, false);
siblings.push(l);
- let r = collect_siblings(data, offset + split, count - split, targets, false, siblings);
+ let r = collect_siblings(
+ data,
+ offset + split,
+ count - split,
+ targets,
+ false,
+ siblings,
+ );
(l, r)
};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/batch.rs:201:
}
let split = 1 << (usize::BITS - (count - 1).leading_zeros() - 1);
- let left_has = indices[lo..hi].iter().any(|&t| (t as usize) < offset + split);
- let right_has = indices[lo..hi].iter().any(|&t| (t as usize) >= offset + split);
+ let left_has = indices[lo..hi]
+ .iter()
+ .any(|&t| (t as usize) < offset + split);
+ let right_has = indices[lo..hi]
+ .iter()
+ .any(|&t| (t as usize) >= offset + split);
let (left_hash, right_hash) = if left_has && right_has {
let l = verify_subtree(chunks, indices, siblings, cursor, offset, split, false)?;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/batch.rs:209:
let r = verify_subtree(
- chunks, indices, siblings, cursor,
- offset + split, count - split, false,
+ chunks,
+ indices,
+ siblings,
+ cursor,
+ offset + split,
+ count - split,
+ false,
)?;
(l, r)
} else if left_has {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/batch.rs:228:
let l = siblings[*cursor];
*cursor += 1;
let r = verify_subtree(
- chunks, indices, siblings, cursor,
- offset + split, count - split, false,
+ chunks,
+ indices,
+ siblings,
+ cursor,
+ offset + split,
+ count - split,
+ false,
)?;
(l, r)
};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/batch.rs:241:
mod tests {
extern crate std;
use std::vec;
+
use super::*;
use crate::tree::fixed_chunk_root as root_hash;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/batch.rs:321:
let data = vec![0x42u8; CHUNK_SIZE * 4];
let (_, proof) = prove_batch(&data, &[0, 1]);
let wrong = vec![0xFF; CHUNK_SIZE];
- assert!(!verify_batch(&[&wrong, &data[CHUNK_SIZE..CHUNK_SIZE * 2]], &proof));
+ assert!(!verify_batch(
+ &[&wrong, &data[CHUNK_SIZE..CHUNK_SIZE * 2]],
+ &proof
+ ));
}
#[test]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/bootstrap.rs:16:
//! 2. Run Hemeraโ as a sponge: absorb GENESIS_SEED with 0x01 padding
//! 3. Squeeze 144 field elements as round constants for the final Hemera
-use crate::constants::NUM_CONSTANTS;
-use crate::field::Goldilocks;
-use crate::params::{RATE, RATE_BYTES, WIDTH};
-use crate::permutation::permute_with_constants;
+use crate::{
+ constants::NUM_CONSTANTS,
+ field::Goldilocks,
+ params::{RATE, RATE_BYTES, WIDTH},
+ permutation::permute_with_constants,
+};
/// Genesis seed: five bytes [0x63, 0x79, 0x62, 0x65, 0x72].
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/cdc.rs:11:
extern crate alloc;
use alloc::vec::Vec;
-use crate::sponge::Hash;
-use crate::tree::{hash_leaf, merge_leaf_hashes};
+use crate::{
+ sponge::Hash,
+ tree::{hash_leaf, merge_leaf_hashes},
+};
// โโ Gear table โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/cdc.rs:22:
/// constants, padding, domain tag, rate/capacity split, output encoding).
/// Any change to the sponge invalidates all particle_id values.
const GEAR_TABLE: [u64; 256] = [
- 0x3cee16fda88038bc, 0xeb3f0bed5aa5c5da, 0x89f51d2ea4b37853, 0x83a074e025363a05,
- 0x68cb54c27a65da0c, 0x989e7d4fa6ca7bc8, 0x90ca94da54b3094b, 0x20c4dc2b9172db1b,
- 0xb41eb49c005a6e6c, 0x0383e0caa5de0b27, 0xd18a8371f7d86311, 0xa2e74b491c8af8d1,
- 0xe3a8fa536c4b2034, 0x450130663b30f62b, 0x475be834aeae481c, 0x685d19fc14b0580d,
- 0xd02c77e54253d244, 0x3b991a3bcfec554e, 0xacff39810448f2e6, 0xa491297672297cdb,
- 0xb914e9c3f66eb5fd, 0x91013827c56342b4, 0x7438f473b7838b55, 0xce5b43b15b444b8e,
- 0x922ee5c4fde4bd60, 0xce9408781ec455ff, 0x4a679855e36af282, 0x0352e3835a88c9be,
- 0x6ee3d7b8dfbb76c6, 0xea7119ace6923987, 0xdfdfc312c06568c5, 0x29463415b5b9a5ea,
- 0x57f1e0a1531a965d, 0x0077df6ac00c6632, 0x64f65c161960a54b, 0x288a093194ef23cc,
- 0x90c8450d1773a97b, 0xc25e58080a77e237, 0x53540e49ba167c78, 0x8661781e21de3349,
- 0x4c5ea83276ddd10c, 0xdec40127893df77d, 0xb947a919c779eb4b, 0xb3efea5835c35750,
- 0xd4f7d7d27988461e, 0x31f8de42fcb5691a, 0x168fa72f2bb15de3, 0x388290904d4b8a34,
- 0xb66c4e053a9f5234, 0x4401d916d6e48c29, 0xdf5d0bb0bb2606d1, 0x421efc106baea8cb,
- 0x4fe81637898f7c67, 0x892a2050092c8118, 0x025777c137211bc9, 0x0d8f2a6e63a83fce,
- 0xed141ddb65b5a45a, 0x2e620431a908be6c, 0x97ae7a41e25c164c, 0xbf656f2af1d76fe2,
- 0x698cc9ae5f637107, 0xf88169c3ec238d46, 0xb97e7c1b727cff48, 0x9e34abc9721b1b3d,
- 0x8cb3f21a8030fa39, 0x0493ae82badba1f7, 0x89897c3013d24323, 0x0b8d907262681586,
- 0xa93f8b770f22735f, 0xccebf34ea621b450, 0xedbbfb260a4f96c1, 0xa00aa83f9bf3ffed,
- 0x2819e0bbcf867cba, 0xa456e02b81085178, 0x10ea0a71910f37b0, 0x16a8499ffcc5f8b3,
- 0x4a33b44d69025992, 0x2394329cccc9c2d6, 0xb347b089a9d0b330, 0x8a63580a2728b967,
- 0x0161d40558d91265, 0x82aaf7773aed3aba, 0xc79fbf6dc6fc741d, 0xb0d1feed8b763a7d,
- 0x27ea025a45c33e26, 0xce9e2c46d801e543, 0xa9d6ac50f857f4e7, 0x5bb0f458232c909c,
- 0xbdf74c7bbb9efa7b, 0x25fc6f3fccc950d7, 0xdb0caa3f4ca9d3dc, 0xd173d09fbf41061d,
- 0x8bda78112cb958f0, 0x98ac58d7aad11560, 0x2b76f4a7a3481ba9, 0xbfa79169a62ca8db,
- 0xd5a5b428af26b9e6, 0xde2d8790f81c4ac2, 0x107ff6e2f4f1670f, 0xb4b4cb5badd76ea0,
- 0x074f4c210f80155d, 0xcf86f83cbbd01c4a, 0x1cc7ac25016da70b, 0xcda8dd852bdacb2f,
- 0x5ebd485e5e7c9352, 0xae73935ff72b98e6, 0x049cb0ce036a6d2e, 0x4f884a76b443efc0,
- 0x072269080e39090e, 0xe179ad1b6a7965b8, 0x4b7e4771785cc58c, 0x2fc3ff2b831f72b8,
- 0xa3f522492063315b, 0x0ae52e16dd56e85d, 0xc44c6714f9c8a5d2, 0x6258323c82ff9fce,
- 0xbcd59ef962d11eda, 0x94e4d059b1a08680, 0x814cccfc4eacf5a4, 0x39111048a74a6d07,
- 0xc1fba777587402be, 0xcfb775abfa7cad4a, 0x27b0d9bc5eab8293, 0x94a054339c69e39c,
- 0x8b2eb24d778be7de, 0x3c366ba9e7fd565e, 0xa417de11b59728d9, 0x503b65803a941d26,
- 0x37d1c13ff6ce5c55, 0x920832d54e4463fb, 0xbf7ef2a4db80bf66, 0x901625f0268dce41,
- 0x7d534cceba27667d, 0xa7bd1c9132c22517, 0x21a95f6ac2a402ff, 0x6c7243715cab7a18,
- 0x633cb5bf0c8184c4, 0x48658d2c959e9338, 0x3674ec7d8c6d3d02, 0x211f649a8a7f51bf,
- 0xf81564b99b42a187, 0x2f9d5127f5263263, 0xab96b8daaedd9a1b, 0x254cc67128559262,
- 0x6084b340de0b599b, 0xa66f7d949aabf212, 0xff91ca59d34d6270, 0xb778531421b168c7,
- 0x3d8b7750edc78ed9, 0xb111ac1204ccf799, 0x9a2007eed273fb2a, 0xf5deed029880afbe,
- 0x420d0413433999e0, 0xdebd2f6e3a6d91f1, 0x7a2090ad3448cd05, 0xced530cf89a18ed1,
- 0xe2e6fe0be276942a, 0x72fc757214f57508, 0x6867ea3c642286bc, 0x04fbc94e61805705,
- 0x8598891cf8ba8fe0, 0x6e1d1cda8f7fa56a, 0x270baa26c7b78658, 0x899bd295c727a6bd,
- 0x4a7b6bb56e3d82dd, 0x3894e0ace0e03556, 0xa5449e2af60158b0, 0xf34df44d175008e5,
- 0xd7eaf1b6b3a38b05, 0xc3d7e2c0b390b207, 0xff1f0be59d7c6f09, 0x689d1a2c2b98e56f,
- 0x072df565671d0f3a, 0xe8c17ff4fd465a6e, 0x69698d12e5743678, 0x135ef28fc58dd5d8,
- 0xd6f50c186ef03188, 0xa5eb8d9264fab43d, 0xf87ff7811740be67, 0xe8ca945aa2dce5df,
- 0x54d28e365bdd589c, 0x20ddcbd837d253b6, 0x4b8c084edf432bf8, 0x3c90ff183c66c405,
- 0x4e86e64a12df4509, 0x5798d3e12f773d5e, 0x537b58c11d087ea2, 0xa024e53d558b1cc4,
- 0xd2b2cbadffb895a3, 0x63dd9afb269f3a20, 0x8ea67ce1b067266a, 0x21448ec35a8490f5,
- 0x56c4ae1088c4d73e, 0x3cbe94d87ff73e41, 0xeb6f699d4775e2de, 0x77e1d3455aeec637,
- 0x4b0a48c6c0ccddf9, 0xb25d80790085e303, 0xfb934fc1d7e5866b, 0xd78c433dd2ecb9dc,
- 0xaf5937367908dfb6, 0x8abde3e9cb44ae1c, 0xcd590541810ea843, 0xc16d66644cb6a901,
- 0x71f1fa2886fbb124, 0x59c3bf04f7a80adc, 0x15f5cf9b6e7c128b, 0xbfb7ada32df4c71a,
- 0xca295fb24e47e022, 0xaa74f361a1a22bd5, 0x79a7c767dc148691, 0xa0a36a00948c0043,
- 0x8e0d8a7da8b1d22f, 0xbb2c41e2e14c9b78, 0x834d9cad216150fc, 0xbfcec1d159a78e43,
- 0xba18a26e1009f56c, 0xadcea3bcefd99544, 0xa37f5dd5632a6df6, 0xd090d233291056f9,
- 0x91739bcdbc56fa77, 0x0b6c8365f5c661df, 0xe6a32f293c82c95c, 0x269b5d559b8582f4,
- 0x7245e2d07ebadc2e, 0x7270eaf7a78a0f39, 0xc92e61d11a2c2620, 0x5f1b563d0479633b,
- 0xe8b29885c36765eb, 0x8b0f60e6ff51007a, 0xda3bacb6ebabca2a, 0x2ff3b41ff463319c,
- 0xa3dfe89870296087, 0xecdb68da2aa107ae, 0x656e550d99c8da85, 0x3a15b068f6ba480f,
- 0x2e90e10a4629f338, 0x08c3d2f27f488aac, 0x82605e1c3e4c812b, 0xc4986aaf5a5873e6,
- 0xff51ba344855ae3b, 0xc9e18ffce06bf0e1, 0x6c6bf57d3e496e9d, 0x1fd8cbbcce3fc3e7,
- 0xe4459ecbda0011a7, 0x584fff779b8aad1b, 0xe26fe55549193600, 0x9a5909733d39d299,
- 0x0277e7ea034412d5, 0xb3bd84a478bfad88, 0x53dc76456936fd3f, 0x5b81725e5b02948d,
- 0xa5a8d8c069ad4ae9, 0xdcc06aa0277a7f95, 0xa48bb63137f4bba2, 0x4ca3941ddb6263b2,
+ 0x3cee16fda88038bc,
+ 0xeb3f0bed5aa5c5da,
+ 0x89f51d2ea4b37853,
+ 0x83a074e025363a05,
+ 0x68cb54c27a65da0c,
+ 0x989e7d4fa6ca7bc8,
+ 0x90ca94da54b3094b,
+ 0x20c4dc2b9172db1b,
+ 0xb41eb49c005a6e6c,
+ 0x0383e0caa5de0b27,
+ 0xd18a8371f7d86311,
+ 0xa2e74b491c8af8d1,
+ 0xe3a8fa536c4b2034,
+ 0x450130663b30f62b,
+ 0x475be834aeae481c,
+ 0x685d19fc14b0580d,
+ 0xd02c77e54253d244,
+ 0x3b991a3bcfec554e,
+ 0xacff39810448f2e6,
+ 0xa491297672297cdb,
+ 0xb914e9c3f66eb5fd,
+ 0x91013827c56342b4,
+ 0x7438f473b7838b55,
+ 0xce5b43b15b444b8e,
+ 0x922ee5c4fde4bd60,
+ 0xce9408781ec455ff,
+ 0x4a679855e36af282,
+ 0x0352e3835a88c9be,
+ 0x6ee3d7b8dfbb76c6,
+ 0xea7119ace6923987,
+ 0xdfdfc312c06568c5,
+ 0x29463415b5b9a5ea,
+ 0x57f1e0a1531a965d,
+ 0x0077df6ac00c6632,
+ 0x64f65c161960a54b,
+ 0x288a093194ef23cc,
+ 0x90c8450d1773a97b,
+ 0xc25e58080a77e237,
+ 0x53540e49ba167c78,
+ 0x8661781e21de3349,
+ 0x4c5ea83276ddd10c,
+ 0xdec40127893df77d,
+ 0xb947a919c779eb4b,
+ 0xb3efea5835c35750,
+ 0xd4f7d7d27988461e,
+ 0x31f8de42fcb5691a,
+ 0x168fa72f2bb15de3,
+ 0x388290904d4b8a34,
+ 0xb66c4e053a9f5234,
+ 0x4401d916d6e48c29,
+ 0xdf5d0bb0bb2606d1,
+ 0x421efc106baea8cb,
+ 0x4fe81637898f7c67,
+ 0x892a2050092c8118,
+ 0x025777c137211bc9,
+ 0x0d8f2a6e63a83fce,
+ 0xed141ddb65b5a45a,
+ 0x2e620431a908be6c,
+ 0x97ae7a41e25c164c,
+ 0xbf656f2af1d76fe2,
+ 0x698cc9ae5f637107,
+ 0xf88169c3ec238d46,
+ 0xb97e7c1b727cff48,
+ 0x9e34abc9721b1b3d,
+ 0x8cb3f21a8030fa39,
+ 0x0493ae82badba1f7,
+ 0x89897c3013d24323,
+ 0x0b8d907262681586,
+ 0xa93f8b770f22735f,
+ 0xccebf34ea621b450,
+ 0xedbbfb260a4f96c1,
+ 0xa00aa83f9bf3ffed,
+ 0x2819e0bbcf867cba,
+ 0xa456e02b81085178,
+ 0x10ea0a71910f37b0,
+ 0x16a8499ffcc5f8b3,
+ 0x4a33b44d69025992,
+ 0x2394329cccc9c2d6,
+ 0xb347b089a9d0b330,
+ 0x8a63580a2728b967,
+ 0x0161d40558d91265,
+ 0x82aaf7773aed3aba,
+ 0xc79fbf6dc6fc741d,
+ 0xb0d1feed8b763a7d,
+ 0x27ea025a45c33e26,
+ 0xce9e2c46d801e543,
+ 0xa9d6ac50f857f4e7,
+ 0x5bb0f458232c909c,
+ 0xbdf74c7bbb9efa7b,
+ 0x25fc6f3fccc950d7,
+ 0xdb0caa3f4ca9d3dc,
+ 0xd173d09fbf41061d,
+ 0x8bda78112cb958f0,
+ 0x98ac58d7aad11560,
+ 0x2b76f4a7a3481ba9,
+ 0xbfa79169a62ca8db,
+ 0xd5a5b428af26b9e6,
+ 0xde2d8790f81c4ac2,
+ 0x107ff6e2f4f1670f,
+ 0xb4b4cb5badd76ea0,
+ 0x074f4c210f80155d,
+ 0xcf86f83cbbd01c4a,
+ 0x1cc7ac25016da70b,
+ 0xcda8dd852bdacb2f,
+ 0x5ebd485e5e7c9352,
+ 0xae73935ff72b98e6,
+ 0x049cb0ce036a6d2e,
+ 0x4f884a76b443efc0,
+ 0x072269080e39090e,
+ 0xe179ad1b6a7965b8,
+ 0x4b7e4771785cc58c,
+ 0x2fc3ff2b831f72b8,
+ 0xa3f522492063315b,
+ 0x0ae52e16dd56e85d,
+ 0xc44c6714f9c8a5d2,
+ 0x6258323c82ff9fce,
+ 0xbcd59ef962d11eda,
+ 0x94e4d059b1a08680,
+ 0x814cccfc4eacf5a4,
+ 0x39111048a74a6d07,
+ 0xc1fba777587402be,
+ 0xcfb775abfa7cad4a,
+ 0x27b0d9bc5eab8293,
+ 0x94a054339c69e39c,
+ 0x8b2eb24d778be7de,
+ 0x3c366ba9e7fd565e,
+ 0xa417de11b59728d9,
+ 0x503b65803a941d26,
+ 0x37d1c13ff6ce5c55,
+ 0x920832d54e4463fb,
+ 0xbf7ef2a4db80bf66,
+ 0x901625f0268dce41,
+ 0x7d534cceba27667d,
+ 0xa7bd1c9132c22517,
+ 0x21a95f6ac2a402ff,
+ 0x6c7243715cab7a18,
+ 0x633cb5bf0c8184c4,
+ 0x48658d2c959e9338,
+ 0x3674ec7d8c6d3d02,
+ 0x211f649a8a7f51bf,
+ 0xf81564b99b42a187,
+ 0x2f9d5127f5263263,
+ 0xab96b8daaedd9a1b,
+ 0x254cc67128559262,
+ 0x6084b340de0b599b,
+ 0xa66f7d949aabf212,
+ 0xff91ca59d34d6270,
+ 0xb778531421b168c7,
+ 0x3d8b7750edc78ed9,
+ 0xb111ac1204ccf799,
+ 0x9a2007eed273fb2a,
+ 0xf5deed029880afbe,
+ 0x420d0413433999e0,
+ 0xdebd2f6e3a6d91f1,
+ 0x7a2090ad3448cd05,
+ 0xced530cf89a18ed1,
+ 0xe2e6fe0be276942a,
+ 0x72fc757214f57508,
+ 0x6867ea3c642286bc,
+ 0x04fbc94e61805705,
+ 0x8598891cf8ba8fe0,
+ 0x6e1d1cda8f7fa56a,
+ 0x270baa26c7b78658,
+ 0x899bd295c727a6bd,
+ 0x4a7b6bb56e3d82dd,
+ 0x3894e0ace0e03556,
+ 0xa5449e2af60158b0,
+ 0xf34df44d175008e5,
+ 0xd7eaf1b6b3a38b05,
+ 0xc3d7e2c0b390b207,
+ 0xff1f0be59d7c6f09,
+ 0x689d1a2c2b98e56f,
+ 0x072df565671d0f3a,
+ 0xe8c17ff4fd465a6e,
+ 0x69698d12e5743678,
+ 0x135ef28fc58dd5d8,
+ 0xd6f50c186ef03188,
+ 0xa5eb8d9264fab43d,
+ 0xf87ff7811740be67,
+ 0xe8ca945aa2dce5df,
+ 0x54d28e365bdd589c,
+ 0x20ddcbd837d253b6,
+ 0x4b8c084edf432bf8,
+ 0x3c90ff183c66c405,
+ 0x4e86e64a12df4509,
+ 0x5798d3e12f773d5e,
+ 0x537b58c11d087ea2,
+ 0xa024e53d558b1cc4,
+ 0xd2b2cbadffb895a3,
+ 0x63dd9afb269f3a20,
+ 0x8ea67ce1b067266a,
+ 0x21448ec35a8490f5,
+ 0x56c4ae1088c4d73e,
+ 0x3cbe94d87ff73e41,
+ 0xeb6f699d4775e2de,
+ 0x77e1d3455aeec637,
+ 0x4b0a48c6c0ccddf9,
+ 0xb25d80790085e303,
+ 0xfb934fc1d7e5866b,
+ 0xd78c433dd2ecb9dc,
+ 0xaf5937367908dfb6,
+ 0x8abde3e9cb44ae1c,
+ 0xcd590541810ea843,
+ 0xc16d66644cb6a901,
+ 0x71f1fa2886fbb124,
+ 0x59c3bf04f7a80adc,
+ 0x15f5cf9b6e7c128b,
+ 0xbfb7ada32df4c71a,
+ 0xca295fb24e47e022,
+ 0xaa74f361a1a22bd5,
+ 0x79a7c767dc148691,
+ 0xa0a36a00948c0043,
+ 0x8e0d8a7da8b1d22f,
+ 0xbb2c41e2e14c9b78,
+ 0x834d9cad216150fc,
+ 0xbfcec1d159a78e43,
+ 0xba18a26e1009f56c,
+ 0xadcea3bcefd99544,
+ 0xa37f5dd5632a6df6,
+ 0xd090d233291056f9,
+ 0x91739bcdbc56fa77,
+ 0x0b6c8365f5c661df,
+ 0xe6a32f293c82c95c,
+ 0x269b5d559b8582f4,
+ 0x7245e2d07ebadc2e,
+ 0x7270eaf7a78a0f39,
+ 0xc92e61d11a2c2620,
+ 0x5f1b563d0479633b,
+ 0xe8b29885c36765eb,
+ 0x8b0f60e6ff51007a,
+ 0xda3bacb6ebabca2a,
+ 0x2ff3b41ff463319c,
+ 0xa3dfe89870296087,
+ 0xecdb68da2aa107ae,
+ 0x656e550d99c8da85,
+ 0x3a15b068f6ba480f,
+ 0x2e90e10a4629f338,
+ 0x08c3d2f27f488aac,
+ 0x82605e1c3e4c812b,
+ 0xc4986aaf5a5873e6,
+ 0xff51ba344855ae3b,
+ 0xc9e18ffce06bf0e1,
+ 0x6c6bf57d3e496e9d,
+ 0x1fd8cbbcce3fc3e7,
+ 0xe4459ecbda0011a7,
+ 0x584fff779b8aad1b,
+ 0xe26fe55549193600,
+ 0x9a5909733d39d299,
+ 0x0277e7ea034412d5,
+ 0xb3bd84a478bfad88,
+ 0x53dc76456936fd3f,
+ 0x5b81725e5b02948d,
+ 0xa5a8d8c069ad4ae9,
+ 0xdcc06aa0277a7f95,
+ 0xa48bb63137f4bba2,
+ 0x4ca3941ddb6263b2,
];
// โโ Fingerprint โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/cdc.rs:179:
/// Multiple chunks โ left-balanced tree of leaf hashes.
#[allow(unknown_lints, rs_no_vec)]
pub fn section_cdc_tree(data: &[u8], element_size: usize, is_root: bool) -> Hash {
- debug_assert!(element_size >= 1 && element_size <= 64,
- "element_size {element_size} out of [1, 64]");
- debug_assert!(data.len() % element_size == 0,
- "data length {} not a multiple of element_size {element_size}", data.len());
+ debug_assert!(
+ element_size >= 1 && element_size <= 64,
+ "element_size {element_size} out of [1, 64]"
+ );
+ debug_assert!(
+ data.len() % element_size == 0,
+ "data length {} not a multiple of element_size {element_size}",
+ data.len()
+ );
let n = data.len() / element_size;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/cdc.rs:214:
mod tests {
extern crate std;
use std::vec;
+
use super::*;
- use crate::tree::hash_node;
- use crate::params::OUTPUT_BYTES;
+ use crate::{params::OUTPUT_BYTES, tree::hash_node};
// โโ Gear table verification โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/cdc.rs:285:
fn window_size_always_power_of_two() {
for s in 1..=64usize {
let w = window_size(s);
- assert!(w.is_power_of_two(), "W={w} not power of two for element_size={s}");
+ assert!(
+ w.is_power_of_two(),
+ "W={w} not power of two for element_size={s}"
+ );
assert!(w >= 64, "W must be >= 64");
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/cdc.rs:378:
// which may coincide for uniform data).
assert_ne!(window_size(1), window_size(4));
assert_ne!(window_size(4), window_size(16));
- assert_eq!(window_size(1), 4096); // baseline
+ assert_eq!(window_size(1), 4096); // baseline
assert_eq!(window_size(4), 1024);
assert_eq!(window_size(16), 256);
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/constants.rs:12:
//! Layout: 128 external (8 full rounds ร 16 elements) followed by
//! 16 internal (partial round) constants.
-use crate::field::Goldilocks;
-use crate::params::{ROUNDS_F, ROUNDS_P, WIDTH};
+use crate::{
+ field::Goldilocks,
+ params::{ROUNDS_F, ROUNDS_P, WIDTH},
+};
/// Total number of round constants.
pub const NUM_CONSTANTS: usize = ROUNDS_F * WIDTH + ROUNDS_P; // 144
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/constants.rs:21:
/// Round constants as raw u64 values (used by bootstrap verification and GPU).
pub const ROUND_CONSTANTS_U64: [u64; NUM_CONSTANTS] = [
// โโ External round 0 (16 elements) โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- 0x7E6EF67C13BC8100, 0x3A658EE0B11555F9, 0x42F4F5D6BE505B01, 0x8D6E969951FEA22C,
- 0x533E1EED0F2B887C, 0x8236CF939B5E8007, 0xBA227D8421244C78, 0x9FC47472DAD402EF,
- 0x5F7692B95C7F43E3, 0x3EC473E1CB681E91, 0x0AC11840549AF522, 0x668B69075828D9A5,
- 0xB48F65809D7F3E78, 0xAA794A8BEE357E66, 0x4A4E37EB0C2AC779, 0x96FC3FB244AE1D65,
+ 0x7E6EF67C13BC8100,
+ 0x3A658EE0B11555F9,
+ 0x42F4F5D6BE505B01,
+ 0x8D6E969951FEA22C,
+ 0x533E1EED0F2B887C,
+ 0x8236CF939B5E8007,
+ 0xBA227D8421244C78,
+ 0x9FC47472DAD402EF,
+ 0x5F7692B95C7F43E3,
+ 0x3EC473E1CB681E91,
+ 0x0AC11840549AF522,
+ 0x668B69075828D9A5,
+ 0xB48F65809D7F3E78,
+ 0xAA794A8BEE357E66,
+ 0x4A4E37EB0C2AC779,
+ 0x96FC3FB244AE1D65,
// โโ External round 1 โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- 0x84C368F3B5BF2820, 0x1EC6FB5FF3838032, 0xF8C1924D601A8277, 0xCA4A2E589AFA0C90,
- 0xB058B152205F27F2, 0xC6FCB05FD64EBB21, 0xA91E996752BD83BD, 0x8EF890328274DFB1,
- 0xB5572F24758746A9, 0xADAF7ED9A874EBC7, 0xA62D94B4525509F9, 0xD93E37690C33BF4A,
- 0x0917331B64B3918E, 0x0BF16036DE74C275, 0xEAC11F9EBCE138F3, 0x926142BB5115A911,
+ 0x84C368F3B5BF2820,
+ 0x1EC6FB5FF3838032,
+ 0xF8C1924D601A8277,
+ 0xCA4A2E589AFA0C90,
+ 0xB058B152205F27F2,
+ 0xC6FCB05FD64EBB21,
+ 0xA91E996752BD83BD,
+ 0x8EF890328274DFB1,
+ 0xB5572F24758746A9,
+ 0xADAF7ED9A874EBC7,
+ 0xA62D94B4525509F9,
+ 0xD93E37690C33BF4A,
+ 0x0917331B64B3918E,
+ 0x0BF16036DE74C275,
+ 0xEAC11F9EBCE138F3,
+ 0x926142BB5115A911,
// โโ External round 2 โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- 0x9EB1DDEEA0AFB953, 0xB564890EF6E7B4A7, 0x1106802D2381272E, 0x3AF6B13CDECFECC6,
- 0x3BFB3BFF6399FE08, 0x0FBD22233C7FF193, 0x194A2C302A7F00F3, 0x7A8CD8FC20313B40,
- 0x320DD200D8A2EAFC, 0x3C9A2A86D3D0A5C1, 0x268D9CD6B9560870, 0xD6B2C1F33C2CBB34,
- 0x7DFBC7540CCBC91B, 0x4CAC7772D90C7EF2, 0xDB97D8D76267E95F, 0xF136CE6F5C9EB4F1,
+ 0x9EB1DDEEA0AFB953,
+ 0xB564890EF6E7B4A7,
+ 0x1106802D2381272E,
+ 0x3AF6B13CDECFECC6,
+ 0x3BFB3BFF6399FE08,
+ 0x0FBD22233C7FF193,
+ 0x194A2C302A7F00F3,
+ 0x7A8CD8FC20313B40,
+ 0x320DD200D8A2EAFC,
+ 0x3C9A2A86D3D0A5C1,
+ 0x268D9CD6B9560870,
+ 0xD6B2C1F33C2CBB34,
+ 0x7DFBC7540CCBC91B,
+ 0x4CAC7772D90C7EF2,
+ 0xDB97D8D76267E95F,
+ 0xF136CE6F5C9EB4F1,
// โโ External round 3 โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- 0x586939D9FF191630, 0xEC15D6F6F81DDBC7, 0xFB46C39A99996794, 0x1D1816FCA3FAB313,
- 0xF2637820A088A973, 0x06A3BA683853A85D, 0xEC58257363D650C5, 0xB4A91673CEEA6086,
- 0xC81AE7203FC95AE8, 0x1535032D312A687D, 0x3E2C5CFC841198A9, 0x178FB3CF99036931,
- 0xA3E8DE69AC768DEC, 0x694A88260A6CC7E0, 0xC378535DC3854078, 0x4DC2B86D6692275A,
+ 0x586939D9FF191630,
+ 0xEC15D6F6F81DDBC7,
+ 0xFB46C39A99996794,
+ 0x1D1816FCA3FAB313,
+ 0xF2637820A088A973,
+ 0x06A3BA683853A85D,
+ 0xEC58257363D650C5,
+ 0xB4A91673CEEA6086,
+ 0xC81AE7203FC95AE8,
+ 0x1535032D312A687D,
+ 0x3E2C5CFC841198A9,
+ 0x178FB3CF99036931,
+ 0xA3E8DE69AC768DEC,
+ 0x694A88260A6CC7E0,
+ 0xC378535DC3854078,
+ 0x4DC2B86D6692275A,
// โโ External round 4 โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- 0x96AD08CF20193273, 0x9DF124AF5A374198, 0x833149BFDFA8AE60, 0x31EFDA6CD1484543,
- 0x43B2F0842FB3714B, 0xC6BB86AD84A77F5F, 0x8964541CF450E588, 0x0DA1B6F6D6F14A4F,
- 0xE72862B68E18BC89, 0x10B07C9857F73F34, 0x371D3F76CC583943, 0x07E97CF84627649B,
- 0xEEB50A7CE2DF1CC4, 0x108FDD4A57E033D6, 0x16F5C821A31E9966, 0xBB9B313537B0021C,
+ 0x96AD08CF20193273,
+ 0x9DF124AF5A374198,
+ 0x833149BFDFA8AE60,
+ 0x31EFDA6CD1484543,
+ 0x43B2F0842FB3714B,
+ 0xC6BB86AD84A77F5F,
+ 0x8964541CF450E588,
+ 0x0DA1B6F6D6F14A4F,
+ 0xE72862B68E18BC89,
+ 0x10B07C9857F73F34,
+ 0x371D3F76CC583943,
+ 0x07E97CF84627649B,
+ 0xEEB50A7CE2DF1CC4,
+ 0x108FDD4A57E033D6,
+ 0x16F5C821A31E9966,
+ 0xBB9B313537B0021C,
// โโ External round 5 โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- 0xBB81FFEEDF6F39F6, 0xE11DC86E2C3365C5, 0xF65FD37AD0655BC7, 0xC8ADC96DA4303235,
- 0x1BB5027F5BFB68C7, 0xA3BCA3F991212021, 0x96D31C8A1D86B96C, 0x7C1F524227785407,
- 0x2584A6A2B787F69D, 0x93BF086014C4C74D, 0x3E0309A55D227679, 0x1E1C4FD4CCFF2AC1,
- 0xDBDC46C77E67CC00, 0x467E7D5C023307D8, 0x5BF3A4515EFF73EA, 0x8548D228DB4EC3E6,
+ 0xBB81FFEEDF6F39F6,
+ 0xE11DC86E2C3365C5,
+ 0xF65FD37AD0655BC7,
+ 0xC8ADC96DA4303235,
+ 0x1BB5027F5BFB68C7,
+ 0xA3BCA3F991212021,
+ 0x96D31C8A1D86B96C,
+ 0x7C1F524227785407,
+ 0x2584A6A2B787F69D,
+ 0x93BF086014C4C74D,
+ 0x3E0309A55D227679,
+ 0x1E1C4FD4CCFF2AC1,
+ 0xDBDC46C77E67CC00,
+ 0x467E7D5C023307D8,
+ 0x5BF3A4515EFF73EA,
+ 0x8548D228DB4EC3E6,
// โโ External round 6 โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- 0xCDA9C4225DEEFD6D, 0x712F330A1D4FC861, 0x1FF0E8601F0CBE90, 0x0C9845FCF92311E5,
- 0x96F85D86B463E860, 0x0CEAE6A1DEABF2EF, 0x2856B08B1F2C8E0A, 0x685950B529313C61,
- 0x72A4683F75AA8802, 0xE57D4C658E303BFC, 0x179D9F1A754F3D65, 0xCFD34EBBFD42C1B0,
- 0xFB6DE754BFD4C7A1, 0xDA881BF5001E67B8, 0xEAB494B9FDF4B534, 0xE87C44892F095416,
+ 0xCDA9C4225DEEFD6D,
+ 0x712F330A1D4FC861,
+ 0x1FF0E8601F0CBE90,
+ 0x0C9845FCF92311E5,
+ 0x96F85D86B463E860,
+ 0x0CEAE6A1DEABF2EF,
+ 0x2856B08B1F2C8E0A,
+ 0x685950B529313C61,
+ 0x72A4683F75AA8802,
+ 0xE57D4C658E303BFC,
+ 0x179D9F1A754F3D65,
+ 0xCFD34EBBFD42C1B0,
+ 0xFB6DE754BFD4C7A1,
+ 0xDA881BF5001E67B8,
+ 0xEAB494B9FDF4B534,
+ 0xE87C44892F095416,
// โโ External round 7 โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- 0x1041D0742A1DCCD9, 0x24F2DF654BA37B8F, 0x04F709BF31859E5A, 0xED4B80ADB75C302F,
- 0x243F18917DA5518D, 0xA4F930B5FF8903AB, 0x3C06F401A282C4BB, 0xB95CEC7BCB8856E5,
- 0x84EDF516B7A2E9DC, 0xC03481FAE955433B, 0xF920E0DA5CE7A937, 0x7D644C20F1D4FE21,
- 0x8976239ECFE2C7BB, 0xF2C131FFAABDFC57, 0x1B8FD118FFC54833, 0x29415A61860444AE,
+ 0x1041D0742A1DCCD9,
+ 0x24F2DF654BA37B8F,
+ 0x04F709BF31859E5A,
+ 0xED4B80ADB75C302F,
+ 0x243F18917DA5518D,
+ 0xA4F930B5FF8903AB,
+ 0x3C06F401A282C4BB,
+ 0xB95CEC7BCB8856E5,
+ 0x84EDF516B7A2E9DC,
+ 0xC03481FAE955433B,
+ 0xF920E0DA5CE7A937,
+ 0x7D644C20F1D4FE21,
+ 0x8976239ECFE2C7BB,
+ 0xF2C131FFAABDFC57,
+ 0x1B8FD118FFC54833,
+ 0x29415A61860444AE,
// โโ Internal (partial) rounds 0โ15 โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- 0x9FB420B604D1EF1A, 0xB2D5DD13C01373DD, 0xB2663B57811E63CB, 0xEC85A5ADA6BB2282,
- 0x735D50E8146501CB, 0x76B2DE8FCD95D272, 0x41344AAEB2FBA5AA, 0xB8A921F2067FF00A,
- 0x30A71752FC82B72C, 0x2A63762DA4F8C5C0, 0x7132145659E4F118, 0xD2A7AF982176FD4F,
- 0x546B454C381AD7C9, 0x269F493C6D3A89F2, 0x99B0DB1D67FCCBB5, 0xD235ADB74B698D72,
+ 0x9FB420B604D1EF1A,
+ 0xB2D5DD13C01373DD,
+ 0xB2663B57811E63CB,
+ 0xEC85A5ADA6BB2282,
+ 0x735D50E8146501CB,
+ 0x76B2DE8FCD95D272,
+ 0x41344AAEB2FBA5AA,
+ 0xB8A921F2067FF00A,
+ 0x30A71752FC82B72C,
+ 0x2A63762DA4F8C5C0,
+ 0x7132145659E4F118,
+ 0xD2A7AF982176FD4F,
+ 0x546B454C381AD7C9,
+ 0x269F493C6D3A89F2,
+ 0x99B0DB1D67FCCBB5,
+ 0xD235ADB74B698D72,
];
/// Round constants as Goldilocks field elements (used by the permutation).
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/encoding.rs:3:
// crystal-type: source
// crystal-domain: comp
// ---
-use crate::field::Goldilocks;
-
-use crate::params::{
- INPUT_BYTES_PER_ELEMENT, OUTPUT_BYTES, OUTPUT_BYTES_PER_ELEMENT, OUTPUT_ELEMENTS, RATE,
+use crate::{
+ field::Goldilocks,
+ params::{
+ INPUT_BYTES_PER_ELEMENT, OUTPUT_BYTES, OUTPUT_BYTES_PER_ELEMENT, OUTPUT_ELEMENTS, RATE,
+ },
};
/// Encode arbitrary bytes into Goldilocks field elements.
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/encoding.rs:79:
mod tests {
extern crate std;
use std::vec;
+
use super::*;
use crate::params::RATE_BYTES;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/encoding.rs:142:
let max_7byte: u64 = (1u64 << 56) - 1;
// Goldilocks prime: p = 2^64 - 2^32 + 1 = 0xFFFF_FFFF_0000_0001
let p: u64 = 0xFFFF_FFFF_0000_0001;
- assert!(max_7byte < p, "7-byte max must be less than Goldilocks prime");
+ assert!(
+ max_7byte < p,
+ "7-byte max must be less than Goldilocks prime"
+ );
}
#[test]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/field.rs:246:
}
// Compute column sums (one per M4 column position).
- let sums: [Goldilocks; 4] = core::array::from_fn(|k| {
- (0..16).step_by(4).map(|j| state[j + k]).sum()
- });
+ let sums: [Goldilocks; 4] =
+ core::array::from_fn(|k| (0..16).step_by(4).map(|j| state[j + k]).sum());
// Add the appropriate column sum to each element.
for (i, elem) in state.iter_mut().enumerate() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/field.rs:310:
continue;
}
let a = Goldilocks::new(raw);
- assert_eq!(
- (a * a.inv()).as_canonical_u64(),
- 1,
- "inv broken at {raw}"
- );
+ assert_eq!((a * a.inv()).as_canonical_u64(), 1, "inv broken at {raw}");
}
assert_eq!(Goldilocks::ZERO.inv().as_canonical_u64(), 0);
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/lib.rs:39:
//! # Examples
//!
//! ```
-//! use cyber_hemera::{hash, derive_key};
+//! use cyber_hemera::{derive_key, hash};
//!
//! let digest = hash(b"hello world");
//! println!("{digest}");
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/lib.rs:54:
#[cfg(feature = "std")]
extern crate std;
+#[cfg(feature = "async")]
+pub mod async_io;
pub mod batch;
-pub mod stream;
pub mod bootstrap;
pub mod cdc;
pub mod constants;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/lib.rs:64:
pub mod merkle;
mod params;
pub mod permutation;
-mod sponge;
pub mod sparse;
+mod sponge;
pub mod step_sponge;
-pub mod trace;
-pub mod tree;
+pub mod stream;
#[cfg(feature = "async")]
-pub mod async_io;
-#[cfg(feature = "async")]
pub mod stream_async;
+pub mod trace;
+pub mod tree;
// Re-export all Hemera parameters so downstream crates never hardcode them.
+pub use merkle::{Side, merkle_verify_path};
pub use params::{
CAPACITY, CHUNK_SIZE, COLLISION_BITS, OUTPUT_BYTES, OUTPUT_ELEMENTS, RATE, RATE_BYTES,
ROUNDS_F, ROUNDS_P, ROUNDS_TOTAL, SBOX_DEGREE, WIDTH,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/lib.rs:81:
};
-pub use merkle::{merkle_verify_path, Side};
-pub use step_sponge::StepSponge;
pub use sponge::{Hash, Hasher, OutputReader};
+pub use step_sponge::StepSponge;
/// Hash the input bytes and return a 32-byte digest.
pub fn hash(input: &[u8]) -> Hash {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/lib.rs:115:
mod tests {
extern crate std;
use std::{vec, vec::Vec};
+
use super::*;
#[test]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/lib.rs:260:
#[cfg(test)]
mod proptests {
extern crate std;
- use super::*;
use proptest::prelude::*;
+
+ use super::*;
proptest! {
#[test]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/merkle.rs:9:
//! against a known root using hemera's Poseidon2 node-hashing convention
//! (the same convention used by `tree::hash_node`).
-use crate::sponge::Hash;
-use crate::tree::hash_node;
+use crate::{sponge::Hash, tree::hash_node};
/// The side a sibling occupies relative to the current node.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/merkle.rs:53:
for (i, (sibling, side)) in path.iter().enumerate() {
let is_root = i == last;
current = match side {
- Side::Left => hash_node(sibling, ¤t, is_root),
+ Side::Left => hash_node(sibling, ¤t, is_root),
Side::Right => hash_node(¤t, sibling, is_root),
};
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/merkle.rs:65:
mod tests {
extern crate std;
use super::*;
- use crate::tree::{hash_leaf, hash_node};
- use crate::params::OUTPUT_BYTES;
+ use crate::{
+ params::OUTPUT_BYTES,
+ tree::{hash_leaf, hash_node},
+ };
/// Build a minimal 2-leaf tree and return (root, leaf0_hash, leaf1_hash).
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/merkle.rs:79:
/// hash_node(leaf0, leaf1, is_root=true) = root.
fn two_leaf_tree() -> (Hash, Hash, Hash) {
let leaf0 = hash_leaf(b"leaf zero data", 0, false);
- let leaf1 = hash_leaf(b"leaf one data", 1, false);
- let root = hash_node(&leaf0, &leaf1, true);
+ let leaf1 = hash_leaf(b"leaf one data", 1, false);
+ let root = hash_node(&leaf0, &leaf1, true);
(root, leaf0, leaf1)
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/merkle.rs:146:
#[test]
fn empty_path_wrong_hash_fails() {
- let leaf = hash_leaf(b"solo", 0, true);
+ let leaf = hash_leaf(b"solo", 0, true);
let other = Hash::from_bytes([0x01; OUTPUT_BYTES]);
assert!(!merkle_verify_path(&leaf, &other, &[]));
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/merkle.rs:166:
let c2 = hash_leaf(b"c2", 2, false);
let c3 = hash_leaf(b"c3", 3, false);
- let p01 = hash_node(&c0, &c1, false);
- let p23 = hash_node(&c2, &c3, false);
+ let p01 = hash_node(&c0, &c1, false);
+ let p23 = hash_node(&c2, &c3, false);
let root = hash_node(&p01, &p23, true);
// c0: sibling=c1 (right), then sibling=p23 (right)
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/merkle.rs:174:
- assert!(merkle_verify_path(&root, &c0, &[(c1, Side::Right), (p23, Side::Right)]));
+ assert!(merkle_verify_path(
+ &root,
+ &c0,
+ &[(c1, Side::Right), (p23, Side::Right)]
+ ));
// c1: sibling=c0 (left), then sibling=p23 (right)
- assert!(merkle_verify_path(&root, &c1, &[(c0, Side::Left), (p23, Side::Right)]));
+ assert!(merkle_verify_path(
+ &root,
+ &c1,
+ &[(c0, Side::Left), (p23, Side::Right)]
+ ));
// c2: sibling=c3 (right), then sibling=p01 (left)
- assert!(merkle_verify_path(&root, &c2, &[(c3, Side::Right), (p01, Side::Left)]));
+ assert!(merkle_verify_path(
+ &root,
+ &c2,
+ &[(c3, Side::Right), (p01, Side::Left)]
+ ));
// c3: sibling=c2 (left), then sibling=p01 (left)
- assert!(merkle_verify_path(&root, &c3, &[(c2, Side::Left), (p01, Side::Left)]));
+ assert!(merkle_verify_path(
+ &root,
+ &c3,
+ &[(c2, Side::Left), (p01, Side::Left)]
+ ));
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/permutation.rs:7:
//!
//! Hemera parameters: R_F=8 (4+4), R_P=16, full-round S-box=x^7, partial S-box=x^(-1).
-use crate::constants::ROUND_CONSTANTS;
-use crate::field::{Goldilocks, matmul_internal, mds_light_permutation};
-use crate::trace::{FullRoundWitnesses, RoundVisitor};
+use crate::{
+ constants::ROUND_CONSTANTS,
+ field::{Goldilocks, matmul_internal, mds_light_permutation},
+ trace::{FullRoundWitnesses, RoundVisitor},
+};
/// Number of external (full) round constants: R_F * WIDTH = 8 * 16 = 128.
const NUM_EXTERNAL: usize = 128;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/permutation.rs:171:
fn traced_matches_plain() {
let mut state_plain = [Goldilocks::new(42); 16];
let mut state_traced = state_plain;
- let mut counter = RoundCounter { full: 0, partial: 0 };
+ let mut counter = RoundCounter {
+ full: 0,
+ partial: 0,
+ };
permute(&mut state_plain);
permute_traced(&mut state_traced, &mut counter);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/permutation.rs:213:
assert_eq!(rec.full_indices[i as usize], i, "full round index {i}");
}
for i in 0..16u8 {
- assert_eq!(rec.partial_indices[i as usize], i, "partial round index {i}");
+ assert_eq!(
+ rec.partial_indices[i as usize], i,
+ "partial round index {i}"
+ );
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/sparse.rs:13:
//! Keys are 32 bytes (256 bits). The path from root to leaf follows
//! key bits MSB-first: bit 0 of byte 0 is the first branching decision.
-use alloc::collections::BTreeMap;
-use alloc::vec::Vec;
+use alloc::{collections::BTreeMap, vec::Vec};
-use crate::sponge::Hash;
-use crate::tree::{hash_leaf, hash_node};
+use crate::{
+ sponge::Hash,
+ tree::{hash_leaf, hash_node},
+};
/// Default depth for 256-bit keys.
pub const DEFAULT_DEPTH: u32 = 256;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/sparse.rs:70:
let base_hash = hasher.finalize();
// Structural binding with FLAG_CHUNK, counter=0 (position encoded in tree path).
- use crate::encoding::{bytes_to_cv, hash_to_bytes};
- use crate::field::Goldilocks;
- use crate::params::{self, OUTPUT_ELEMENTS, RATE, WIDTH};
+ use crate::{
+ encoding::{bytes_to_cv, hash_to_bytes},
+ field::Goldilocks,
+ params::{self, OUTPUT_ELEMENTS, RATE, WIDTH},
+ };
let base_elems = bytes_to_cv(base_hash.as_bytes());
let mut state = [Goldilocks::new(0); WIDTH];
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/sparse.rs:158:
let bit_in_byte = 7 - (bit_pos % 8);
sib_key[byte_idx] ^= 1 << bit_in_byte;
let masked = mask_key(&sib_key, self.depth - level);
- self.nodes.get(&(level, masked)).copied().unwrap_or(self.sentinel(level))
+ self.nodes
+ .get(&(level, masked))
+ .copied()
+ .unwrap_or(self.sentinel(level))
}
/// Insert or update a key-value pair. Returns the new root.
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/sparse.rs:259:
}
/// Verify a compressed proof for inclusion (value = Some) or non-inclusion (value = None).
- pub fn verify(proof: &CompressedSparseProof, value: Option<&[u8]>, root: &Hash, depth: u32) -> bool {
+ pub fn verify(
+ proof: &CompressedSparseProof,
+ value: Option<&[u8]>,
+ root: &Hash,
+ depth: u32,
+ ) -> bool {
let sentinels = sentinel_table(depth);
Self::verify_with_sentinels(proof, value, root, depth, &sentinels)
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/sparse.rs:494:
fn key_bit_extraction() {
let mut key = [0u8; 32];
key[0] = 0b1010_0000;
- assert!(key_bit(&key, 0)); // MSB = 1
- assert!(!key_bit(&key, 1)); // 0
- assert!(key_bit(&key, 2)); // 1
- assert!(!key_bit(&key, 3)); // 0
+ assert!(key_bit(&key, 0)); // MSB = 1
+ assert!(!key_bit(&key, 1)); // 0
+ assert!(key_bit(&key, 2)); // 1
+ assert!(!key_bit(&key, 3)); // 0
}
#[test]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/sponge.rs:5:
// ---
use core::fmt;
-use crate::encoding::{bytes_to_rate_block, hash_to_bytes};
-use crate::field::Goldilocks;
-use crate::params::{self, OUTPUT_BYTES, OUTPUT_BYTES_PER_ELEMENT, OUTPUT_ELEMENTS, RATE, RATE_BYTES, WIDTH};
+use crate::{
+ encoding::{bytes_to_rate_block, hash_to_bytes},
+ field::Goldilocks,
+ params::{
+ self, OUTPUT_BYTES, OUTPUT_BYTES_PER_ELEMENT, OUTPUT_ELEMENTS, RATE, RATE_BYTES, WIDTH,
+ },
+};
/// Domain separation tags placed in `state[capacity_start + 3]` (i.e. `state[11]`).
const DOMAIN_HASH: u64 = 0x00;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/sponge.rs:75:
write!(formatter, "a byte array of length {OUTPUT_BYTES}")
}
- fn visit_seq<A: serde::de::SeqAccess<'de>>(
- self,
- mut seq: A,
- ) -> Result<Hash, A::Error> {
+ fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Hash, A::Error> {
let mut bytes = [0u8; OUTPUT_BYTES];
for (i, byte) in bytes.iter_mut().enumerate() {
*byte = seq
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/sponge.rs:309:
crate::permutation::permute_traced(&mut state, visitor);
- let output: [Goldilocks; OUTPUT_ELEMENTS] = state[..OUTPUT_ELEMENTS]
- .try_into()
- .unwrap();
+ let output: [Goldilocks; OUTPUT_ELEMENTS] = state[..OUTPUT_ELEMENTS].try_into().unwrap();
Hash(hash_to_bytes(&output))
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/sponge.rs:318:
/// Finalize and return the hash.
pub fn finalize(&self) -> Hash {
let state = self.finalize_state();
- let output: [Goldilocks; OUTPUT_ELEMENTS] = state[..OUTPUT_ELEMENTS]
- .try_into()
- .unwrap();
+ let output: [Goldilocks; OUTPUT_ELEMENTS] = state[..OUTPUT_ELEMENTS].try_into().unwrap();
Hash(hash_to_bytes(&output))
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/sponge.rs:380:
/// Squeeze one block of output from the sponge.
fn squeeze(&mut self) {
- let output_elems: [Goldilocks; OUTPUT_ELEMENTS] = self.state[..OUTPUT_ELEMENTS]
- .try_into()
- .unwrap();
+ let output_elems: [Goldilocks; OUTPUT_ELEMENTS] =
+ self.state[..OUTPUT_ELEMENTS].try_into().unwrap();
self.buffer = hash_to_bytes(&output_elems);
self.buffer_pos = 0;
params::permute(&mut self.state);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/sponge.rs:407:
mod tests {
extern crate std;
use std::{format, vec, vec::Vec};
+
use super::*;
#[test]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/sponge.rs:471:
fn domain_separation_hash_vs_keyed() {
let data = b"test data";
let plain = Hasher::new().update(data).finalize();
- let keyed = Hasher::new_keyed(&[0u8; OUTPUT_BYTES]).update(data).finalize();
+ let keyed = Hasher::new_keyed(&[0u8; OUTPUT_BYTES])
+ .update(data)
+ .finalize();
assert_ne!(plain, keyed);
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/sponge.rs:520:
#[test]
fn keyed_hash_different_keys() {
let data = b"same data";
- let h1 = Hasher::new_keyed(&[0u8; OUTPUT_BYTES]).update(data).finalize();
- let h2 = Hasher::new_keyed(&[1u8; OUTPUT_BYTES]).update(data).finalize();
+ let h1 = Hasher::new_keyed(&[0u8; OUTPUT_BYTES])
+ .update(data)
+ .finalize();
+ let h2 = Hasher::new_keyed(&[1u8; OUTPUT_BYTES])
+ .update(data)
+ .finalize();
assert_ne!(h1, h2);
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/sponge.rs:550:
let h = Hasher::new().update(&data).finalize();
let h_streamed = {
let mut hasher = Hasher::new();
- for chunk in data.chunks(17) { // odd chunk size
+ for chunk in data.chunks(17) {
+ // odd chunk size
hasher.update(chunk);
}
hasher.finalize()
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/sponge.rs:732:
.update(data)
.finalize();
- let context_only = Hasher::new_derive_key_context(
- core::str::from_utf8(data).unwrap()
- ).finalize();
+ let context_only =
+ Hasher::new_derive_key_context(core::str::from_utf8(data).unwrap()).finalize();
// All pairwise different
let hashes = [plain, keyed, derived, context_only];
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/step_sponge.rs:17:
//! tracer.record(squeeze_row(sponge.squeeze()));
//! ```
-use crate::field::{Goldilocks, mds_light_permutation};
-use crate::params::{RATE, ROUNDS_TOTAL, WIDTH};
-use crate::permutation::permute_one_round;
+use crate::{
+ field::{Goldilocks, mds_light_permutation},
+ params::{RATE, ROUNDS_TOTAL, WIDTH},
+ permutation::permute_one_round,
+};
/// Round-by-round Poseidon2 permutation.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/step_sponge.rs:86:
mod tests {
extern crate std;
use std::vec::Vec;
+
use super::*;
- use crate::field::Goldilocks;
- use crate::params::{ROUNDS_TOTAL, WIDTH};
- use crate::permutation::permute;
+ use crate::{
+ field::Goldilocks,
+ params::{ROUNDS_TOTAL, WIDTH},
+ permutation::permute,
+ };
fn zero_rate() -> Vec<Goldilocks> {
std::vec![Goldilocks::ZERO; RATE]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/step_sponge.rs:180:
assert_eq!(states.len(), ROUNDS_TOTAL);
// Consecutive round states must differ (permutation is not identity on any round).
for i in 1..states.len() {
- assert_ne!(states[i - 1], states[i], "rounds {} and {} produced identical states", i - 1, i);
+ assert_ne!(
+ states[i - 1],
+ states[i],
+ "rounds {} and {} produced identical states",
+ i - 1,
+ i
+ );
}
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream.rs:27:
use alloc::vec::Vec;
-use crate::params::{CHUNK_SIZE, OUTPUT_BYTES};
-use crate::sponge::Hash;
-use crate::tree::{hash_leaf, hash_node, num_chunks};
+use crate::{
+ params::{CHUNK_SIZE, OUTPUT_BYTES},
+ sponge::Hash,
+ tree::{hash_leaf, hash_node, num_chunks},
+};
/// Size of a serialized hash pair (left โ right).
pub const PAIR_SIZE: usize = OUTPUT_BYTES * 2;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream.rs:131:
}
let data_len = u64::from_le_bytes(encoded[..HEADER_SIZE].try_into().unwrap()) as usize;
- let n = if data_len == 0 { 1 } else { (data_len + CHUNK_SIZE - 1) / CHUNK_SIZE };
+ let n = if data_len == 0 {
+ 1
+ } else {
+ (data_len + CHUNK_SIZE - 1) / CHUNK_SIZE
+ };
let mut pos = HEADER_SIZE;
if n <= 1 {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream.rs:148:
}
let mut out = Vec::with_capacity(data_len);
- decode_subtree(encoded, &mut pos, 0, n, true, expected_root, data_len, &mut out)?;
+ decode_subtree(
+ encoded,
+ &mut pos,
+ 0,
+ n,
+ true,
+ expected_root,
+ data_len,
+ &mut out,
+ )?;
Ok(out)
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream.rs:197:
}
let split = left_subtree_chunks(count);
- decode_subtree(encoded, pos, offset, split, false, &left_hash, data_len, out)?;
- decode_subtree(encoded, pos, offset + split, count - split, false, &right_hash, data_len, out)?;
+ decode_subtree(
+ encoded, pos, offset, split, false, &left_hash, data_len, out,
+ )?;
+ decode_subtree(
+ encoded,
+ pos,
+ offset + split,
+ count - split,
+ false,
+ &right_hash,
+ data_len,
+ out,
+ )?;
Ok(())
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream.rs:273:
return Err(DecodeError::HashMismatch);
}
- let n = if data_len == 0 { 1 } else { (data_len + CHUNK_SIZE - 1) / CHUNK_SIZE };
+ let n = if data_len == 0 {
+ 1
+ } else {
+ (data_len + CHUNK_SIZE - 1) / CHUNK_SIZE
+ };
if n <= 1 {
let cv = hash_leaf(data, 0, true);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream.rs:280:
- return if cv == *expected_root { Ok(()) } else { Err(DecodeError::HashMismatch) };
+ return if cv == *expected_root {
+ Ok(())
+ } else {
+ Err(DecodeError::HashMismatch)
+ };
}
let mut pos = HEADER_SIZE;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream.rs:300:
let start = offset * CHUNK_SIZE;
let end = (start + CHUNK_SIZE).min(data.len());
let cv = hash_leaf(&data[start..end], offset as u64, false);
- return if cv == *expected { Ok(()) } else { Err(DecodeError::HashMismatch) };
+ return if cv == *expected {
+ Ok(())
+ } else {
+ Err(DecodeError::HashMismatch)
+ };
}
if *pos + PAIR_SIZE > ob.len() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream.rs:316:
let split = left_subtree_chunks(count);
verify_outboard_subtree(data, ob, pos, offset, split, false, &left_hash)?;
- verify_outboard_subtree(data, ob, pos, offset + split, count - split, false, &right_hash)?;
+ verify_outboard_subtree(
+ data,
+ ob,
+ pos,
+ offset + split,
+ count - split,
+ false,
+ &right_hash,
+ )?;
Ok(())
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream.rs:341:
mod tests {
extern crate std;
use std::vec;
+
use super::*;
use crate::tree::fixed_chunk_root as root_hash;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream.rs:407:
#[test]
fn decode_truncated_header() {
- assert_eq!(decode(b"short", &Hash::from_bytes([0; OUTPUT_BYTES])), Err(DecodeError::Truncated));
+ assert_eq!(
+ decode(b"short", &Hash::from_bytes([0; OUTPUT_BYTES])),
+ Err(DecodeError::Truncated)
+ );
}
#[test]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream.rs:465:
let data = vec![0x42; CHUNK_SIZE * 2];
let (root, ob) = outboard(&data);
let wrong = vec![0xFF; CHUNK_SIZE * 2];
- assert_eq!(verify_outboard(&wrong, &ob, &root), Err(DecodeError::HashMismatch));
+ assert_eq!(
+ verify_outboard(&wrong, &ob, &root),
+ Err(DecodeError::HashMismatch)
+ );
}
#[test]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream.rs:473:
let data = vec![0x42; CHUNK_SIZE * 2];
let (_, ob) = outboard(&data);
let wrong = Hash::from_bytes([0xFF; OUTPUT_BYTES]);
- assert_eq!(verify_outboard(&data, &ob, &wrong), Err(DecodeError::HashMismatch));
+ assert_eq!(
+ verify_outboard(&data, &ob, &wrong),
+ Err(DecodeError::HashMismatch)
+ );
}
#[test]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream.rs:488:
#[test]
fn encode_decode_roundtrip_sizes() {
- for size in [0, 1, 100, CHUNK_SIZE - 1, CHUNK_SIZE, CHUNK_SIZE + 1,
- CHUNK_SIZE * 2, CHUNK_SIZE * 3 + 7, CHUNK_SIZE * 8,
- CHUNK_SIZE * 16 + 1] {
+ for size in [
+ 0,
+ 1,
+ 100,
+ CHUNK_SIZE - 1,
+ CHUNK_SIZE,
+ CHUNK_SIZE + 1,
+ CHUNK_SIZE * 2,
+ CHUNK_SIZE * 3 + 7,
+ CHUNK_SIZE * 8,
+ CHUNK_SIZE * 16 + 1,
+ ] {
let data = vec![0x77u8; size];
let (root, encoded) = encode(&data);
let decoded = decode(&encoded, &root).unwrap();
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream.rs:500:
#[test]
fn outboard_verify_sizes() {
- for size in [0, 1, 100, CHUNK_SIZE, CHUNK_SIZE + 1,
- CHUNK_SIZE * 5, CHUNK_SIZE * 16 + 1] {
+ for size in [
+ 0,
+ 1,
+ 100,
+ CHUNK_SIZE,
+ CHUNK_SIZE + 1,
+ CHUNK_SIZE * 5,
+ CHUNK_SIZE * 16 + 1,
+ ] {
let data = vec![0x88u8; size];
let (root, ob) = outboard(&data);
verify_outboard(&data, &ob, &root).unwrap();
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream_async.rs:25:
extern crate alloc;
extern crate std;
-use alloc::vec;
-use alloc::vec::Vec;
+use alloc::{vec, vec::Vec};
-use crate::async_io::{self, AsyncRead, AsyncWrite};
-use crate::params::{CHUNK_SIZE, OUTPUT_BYTES};
-use crate::sponge::Hash;
-use crate::stream::{left_subtree_chunks, HEADER_SIZE, PAIR_SIZE};
-use crate::tree::{hash_leaf, hash_node};
+use crate::{
+ async_io::{self, AsyncRead, AsyncWrite},
+ params::{CHUNK_SIZE, OUTPUT_BYTES},
+ sponge::Hash,
+ stream::{HEADER_SIZE, PAIR_SIZE, left_subtree_chunks},
+ tree::{hash_leaf, hash_node},
+};
/// Item yielded by the async streaming decoder.
#[derive(Debug)]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream_async.rs:225:
let split = left_subtree_chunks(count as usize) as u64;
// Push RIGHT first (stack is LIFO โ left will be processed first).
- self.stack.push((
- offset + split,
- count - split,
- false,
- right_hash,
- ));
self.stack
- .push((offset, split, false, left_hash));
+ .push((offset + split, count - split, false, right_hash));
+ self.stack.push((offset, split, false, left_hash));
Ok(())
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream_async.rs:312:
async_io::read_exact(&mut reader, &mut buf)
.await
.map_err(StreamError::Io)?;
- async_io::write_all(&mut writer, &buf).await.map_err(StreamError::Io)?;
- async_io::flush(&mut writer).await.map_err(StreamError::Io)?;
+ async_io::write_all(&mut writer, &buf)
+ .await
+ .map_err(StreamError::Io)?;
+ async_io::flush(&mut writer)
+ .await
+ .map_err(StreamError::Io)?;
return Ok(hash_leaf(&buf, 0, true));
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/stream_async.rs:330:
async_io::write_all(&mut writer, &encoded[HEADER_SIZE..])
.await
.map_err(StreamError::Io)?;
- async_io::flush(&mut writer).await.map_err(StreamError::Io)?;
+ async_io::flush(&mut writer)
+ .await
+ .map_err(StreamError::Io)?;
Ok(root)
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/trace.rs:39:
///
/// `index` โ 0..8 โ rounds 0โ3 are the initial group; 4โ7 are terminal.
/// `witnesses[i] = [state_pre_sbox[i]ยฒ, state_pre_sbox[i]ยณ]`.
- fn full_round(
- &mut self,
- index: u8,
- state: &[Goldilocks; 16],
- witnesses: &FullRoundWitnesses,
- );
+ fn full_round(&mut self, index: u8, state: &[Goldilocks; 16], witnesses: &FullRoundWitnesses);
/// After a partial round: add_rc on state[0] + x^(โ1) S-box + matmul_internal.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:8:
//! `hash_leaf` hashes leaf data into a chaining value.
//! `hash_node` combines two child chaining values into a parent node.
-use crate::encoding::{bytes_to_cv, hash_to_bytes};
-use crate::field::Goldilocks;
-use crate::params::{self, CHUNK_SIZE, MAX_TREE_DEPTH, OUTPUT_ELEMENTS, RATE, WIDTH};
-use crate::sponge::Hash;
+use crate::{
+ encoding::{bytes_to_cv, hash_to_bytes},
+ field::Goldilocks,
+ params::{self, CHUNK_SIZE, MAX_TREE_DEPTH, OUTPUT_ELEMENTS, RATE, WIDTH},
+ sponge::Hash,
+};
/// Flags encoded in the capacity for tree operations.
const FLAG_ROOT: u64 = 1 << 0;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:97:
/// Extends `hash_node` with namespace bounds committed in capacity:
/// `state[12] = ns_min`, `state[13] = ns_max`. When both are zero this
/// reduces to `hash_node`. See spec ยง4.6.4.
-pub fn hash_node_nmt(
- left: &Hash,
- right: &Hash,
- ns_min: u64,
- ns_max: u64,
- is_root: bool,
-) -> Hash {
+pub fn hash_node_nmt(left: &Hash, right: &Hash, ns_min: u64, ns_max: u64, is_root: bool) -> Hash {
let left_elems = bytes_to_cv(left.as_bytes());
let right_elems = bytes_to_cv(right.as_bytes());
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:190:
tick: &impl Fn(&core::cell::Cell<usize>),
) -> Hash {
debug_assert!(count > 0);
- let n_total = if data.is_empty() { 1 } else { (data.len() + CHUNK_SIZE - 1) / CHUNK_SIZE };
+ let n_total = if data.is_empty() {
+ 1
+ } else {
+ (data.len() + CHUNK_SIZE - 1) / CHUNK_SIZE
+ };
if count == 1 {
let start = offset * CHUNK_SIZE;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:212:
/// computing leaf hashes on demand from the data slice.
pub(crate) fn merge_range(data: &[u8], offset: usize, count: usize, is_root: bool) -> Hash {
debug_assert!(count > 0);
- let n_total = if data.is_empty() { 1 } else { (data.len() + CHUNK_SIZE - 1) / CHUNK_SIZE };
+ let n_total = if data.is_empty() {
+ 1
+ } else {
+ (data.len() + CHUNK_SIZE - 1) / CHUNK_SIZE
+ };
if count == 1 {
let start = offset * CHUNK_SIZE;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:286:
impl<'de> serde::Deserialize<'de> for InclusionProof {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
use alloc::vec::Vec as AllocVec;
+
use serde::de::{self, MapAccess, SeqAccess};
#[derive(serde::Deserialize)]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:292:
#[serde(field_identifier, rename_all = "snake_case")]
- enum Field { StartChunk, EndChunk, NumChunks, Siblings }
+ enum Field {
+ StartChunk,
+ EndChunk,
+ NumChunks,
+ Siblings,
+ }
struct InclusionProofVisitor;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:302:
}
fn visit_seq<V: SeqAccess<'de>>(self, mut seq: V) -> Result<InclusionProof, V::Error> {
- let start_chunk = seq.next_element()?.ok_or_else(|| de::Error::invalid_length(0, &self))?;
- let end_chunk = seq.next_element()?.ok_or_else(|| de::Error::invalid_length(1, &self))?;
- let num_chunks = seq.next_element()?.ok_or_else(|| de::Error::invalid_length(2, &self))?;
- let siblings: AllocVec<Sibling> = seq.next_element()?.ok_or_else(|| de::Error::invalid_length(3, &self))?;
+ let start_chunk = seq
+ .next_element()?
+ .ok_or_else(|| de::Error::invalid_length(0, &self))?;
+ let end_chunk = seq
+ .next_element()?
+ .ok_or_else(|| de::Error::invalid_length(1, &self))?;
+ let num_chunks = seq
+ .next_element()?
+ .ok_or_else(|| de::Error::invalid_length(2, &self))?;
+ let siblings: AllocVec<Sibling> = seq
+ .next_element()?
+ .ok_or_else(|| de::Error::invalid_length(3, &self))?;
if siblings.len() > MAX_TREE_DEPTH {
return Err(de::Error::custom("too many siblings"));
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:312:
let mut buf = [SIBLING_ZERO; MAX_TREE_DEPTH];
buf[..siblings.len()].copy_from_slice(&siblings);
- Ok(InclusionProof { start_chunk, end_chunk, num_chunks, buf, depth: siblings.len() })
+ Ok(InclusionProof {
+ start_chunk,
+ end_chunk,
+ num_chunks,
+ buf,
+ depth: siblings.len(),
+ })
}
fn visit_map<V: MapAccess<'de>>(self, mut map: V) -> Result<InclusionProof, V::Error> {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:321:
let mut siblings: Option<AllocVec<Sibling>> = None;
while let Some(key) = map.next_key()? {
match key {
- Field::StartChunk => { start_chunk = Some(map.next_value()?); }
- Field::EndChunk => { end_chunk = Some(map.next_value()?); }
- Field::NumChunks => { num_chunks = Some(map.next_value()?); }
- Field::Siblings => { siblings = Some(map.next_value()?); }
+ Field::StartChunk => {
+ start_chunk = Some(map.next_value()?);
+ }
+ Field::EndChunk => {
+ end_chunk = Some(map.next_value()?);
+ }
+ Field::NumChunks => {
+ num_chunks = Some(map.next_value()?);
+ }
+ Field::Siblings => {
+ siblings = Some(map.next_value()?);
+ }
}
}
- let start_chunk = start_chunk.ok_or_else(|| de::Error::missing_field("start_chunk"))?;
+ let start_chunk =
+ start_chunk.ok_or_else(|| de::Error::missing_field("start_chunk"))?;
let end_chunk = end_chunk.ok_or_else(|| de::Error::missing_field("end_chunk"))?;
- let num_chunks = num_chunks.ok_or_else(|| de::Error::missing_field("num_chunks"))?;
+ let num_chunks =
+ num_chunks.ok_or_else(|| de::Error::missing_field("num_chunks"))?;
let siblings = siblings.ok_or_else(|| de::Error::missing_field("siblings"))?;
if siblings.len() > MAX_TREE_DEPTH {
return Err(de::Error::custom("too many siblings"));
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:336:
}
let mut buf = [SIBLING_ZERO; MAX_TREE_DEPTH];
buf[..siblings.len()].copy_from_slice(&siblings);
- Ok(InclusionProof { start_chunk, end_chunk, num_chunks, buf, depth: siblings.len() })
+ Ok(InclusionProof {
+ start_chunk,
+ end_chunk,
+ num_chunks,
+ buf,
+ depth: siblings.len(),
+ })
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:361:
/// Returns the root hash and the proof. Panics if the range is invalid.
/// No heap allocation โ uses a fixed-size siblings buffer.
pub fn prove_range(data: &[u8], start: u64, end: u64) -> (Hash, InclusionProof) {
- let n = if data.is_empty() { 1u64 } else { ((data.len() + CHUNK_SIZE - 1) / CHUNK_SIZE) as u64 };
- assert!(start < end && end <= n, "invalid range [{start}..{end}) for {n} chunks");
+ let n = if data.is_empty() {
+ 1u64
+ } else {
+ ((data.len() + CHUNK_SIZE - 1) / CHUNK_SIZE) as u64
+ };
+ assert!(
+ start < end && end <= n,
+ "invalid range [{start}..{end}) for {n} chunks"
+ );
if n == 1 {
let cv = hash_leaf(data, 0, true);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:421:
return merge_range(data, offset, count, is_root);
}
- assert!(count > 1, "target range does not align to a subtree boundary");
+ assert!(
+ count > 1,
+ "target range does not align to a subtree boundary"
+ );
let split = 1 << (usize::BITS - (count - 1).leading_zeros() - 1);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:431:
buf[*depth] = Sibling::Right(right);
*depth += 1;
let left = prove_subtree_data(
- data, offset, split, target_start, target_end, false, buf, depth,
+ data,
+ offset,
+ split,
+ target_start,
+ target_end,
+ false,
+ buf,
+ depth,
);
hash_node(&left, &right, is_root)
} else if target_start >= offset + split {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:440:
buf[*depth] = Sibling::Left(left);
*depth += 1;
let right = prove_subtree_data(
- data, offset + split, count - split, target_start, target_end, false, buf, depth,
+ data,
+ offset + split,
+ count - split,
+ target_start,
+ target_end,
+ false,
+ buf,
+ depth,
);
hash_node(&left, &right, is_root)
} else {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:457:
/// Given the raw chunk data, recomputes the leaf hash and walks the
/// proof path up to the root. Returns `true` if the recomputed root
/// matches `expected_root`.
-pub fn verify_proof(
- chunk_data: &[u8],
- proof: &InclusionProof,
- expected_root: &Hash,
-) -> bool {
+pub fn verify_proof(chunk_data: &[u8], proof: &InclusionProof, expected_root: &Hash) -> bool {
assert_eq!(
proof.end_chunk - proof.start_chunk,
1,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:474:
return current == *expected_root;
}
- walk_proof(&mut current, proof.siblings())
- == *expected_root
+ walk_proof(&mut current, proof.siblings()) == *expected_root
}
/// Verify an inclusion proof for an internal node (subtree hash) against
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:482:
/// an expected root hash.
-pub fn verify_node_proof(
- node_hash: &Hash,
- proof: &InclusionProof,
- expected_root: &Hash,
-) -> bool {
+pub fn verify_node_proof(node_hash: &Hash, proof: &InclusionProof, expected_root: &Hash) -> bool {
if proof.siblings().is_empty() {
return *node_hash == *expected_root;
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:491:
let mut current = *node_hash;
- walk_proof(&mut current, proof.siblings())
- == *expected_root
+ walk_proof(&mut current, proof.siblings()) == *expected_root
}
/// Walk siblings from leaf toward root, returning the computed root.
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/src/tree.rs:832:
mod tests {
extern crate std;
use std::vec;
+
use super::*;
use crate::params::OUTPUT_BYTES;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/rs/tests/vectors.rs:5:
// ---
//! Test that hemera-rs matches the pinned test vectors in vectors/hemera.json.
-use cyber_hemera::{hash, derive_key, tree::root_hash};
+use cyber_hemera::{derive_key, hash, tree::root_hash};
#[test]
fn hash_empty() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:27:
use std::num::NonZeroU64;
-use cyber_hemera::field::Goldilocks;
-use cyber_hemera::sparse::CompressedSparseProof;
-use cyber_hemera::tree::{InclusionProof, Sibling};
-use cyber_hemera::{Hash, CHUNK_SIZE, OUTPUT_BYTES, OUTPUT_ELEMENTS, WIDTH};
+use cyber_hemera::{
+ CHUNK_SIZE, Hash, OUTPUT_BYTES, OUTPUT_ELEMENTS, WIDTH,
+ field::Goldilocks,
+ sparse::CompressedSparseProof,
+ tree::{InclusionProof, Sibling},
+};
use wgpu::util::DeviceExt;
/// Pre-compiled GPU compute pipelines and device handles.
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:161:
})
}
- fn bind(&self, io: &wgpu::Buffer, params: &wgpu::Buffer, aux: &wgpu::Buffer) -> wgpu::BindGroup {
+ fn bind(
+ &self,
+ io: &wgpu::Buffer,
+ params: &wgpu::Buffer,
+ aux: &wgpu::Buffer,
+ ) -> wgpu::BindGroup {
self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &self.bind_group_layout,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:168:
entries: &[
- wgpu::BindGroupEntry { binding: 0, resource: io.as_entire_binding() },
- wgpu::BindGroupEntry { binding: 1, resource: self.rc_buffer.as_entire_binding() },
- wgpu::BindGroupEntry { binding: 2, resource: params.as_entire_binding() },
- wgpu::BindGroupEntry { binding: 3, resource: self.diag_buffer.as_entire_binding() },
- wgpu::BindGroupEntry { binding: 4, resource: aux.as_entire_binding() },
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: io.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: self.rc_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: params.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: self.diag_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: aux.as_entire_binding(),
+ },
],
})
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:212:
}
fn params_buf(&self, p: [u32; 8]) -> wgpu::Buffer {
- self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
- label: None,
- contents: bytemuck::cast_slice(&p),
- usage: wgpu::BufferUsages::UNIFORM,
- })
+ self.device
+ .create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: None,
+ contents: bytemuck::cast_slice(&p),
+ usage: wgpu::BufferUsages::UNIFORM,
+ })
}
- fn dispatch_hash(&self, pipeline: &wgpu::ComputePipeline, aux: &[u8], p: [u32; 8], n: u32) -> Vec<Hash> {
+ fn dispatch_hash(
+ &self,
+ pipeline: &wgpu::ComputePipeline,
+ aux: &[u8],
+ p: [u32; 8],
+ n: u32,
+ ) -> Vec<Hash> {
let io = self.device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: (n as u64) * 16 * 4,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:226:
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
- let aux_buf = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
- label: None,
- contents: aux,
- usage: wgpu::BufferUsages::STORAGE,
- });
+ let aux_buf = self
+ .device
+ .create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: None,
+ contents: aux,
+ usage: wgpu::BufferUsages::STORAGE,
+ });
let pb = self.params_buf(p);
let bg = self.bind(&io, &pb, &aux_buf);
u32s_to_hashes(&self.dispatch_readback(pipeline, &bg, &io, n), n as usize)
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:240:
/// Run batch Poseidon2 permutations on GPU.
pub async fn batch_permute(&self, states: &Goldilocks; WIDTH) -> Vec<[Goldilocks; WIDTH]> {
- if states.is_empty() { return vec![]; }
+ if states.is_empty() {
+ return vec![];
+ }
let n = states.len() as u32;
let data = flatten_states(states);
- let io = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
- label: None,
- contents: bytemuck::cast_slice(&data),
- usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
- });
+ let io = self
+ .device
+ .create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: None,
+ contents: bytemuck::cast_slice(&data),
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ });
let pb = self.params_buf([n, 0, 0, 0, 0, 0, 0, 0]);
let bg = self.bind(&io, &pb, &self.dummy_buffer);
- unflatten_states(&self.dispatch_readback(&self.permute_pipeline, &bg, &io, n), states.len())
+ unflatten_states(
+ &self.dispatch_readback(&self.permute_pipeline, &bg, &io, n),
+ states.len(),
+ )
}
/// Batch sponge hash of data chunks (plain hash, no tree domain).
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:257:
pub async fn batch_hash(&self, data: &[u8], chunk_size: usize) -> Vec<Hash> {
- if data.is_empty() { return vec![]; }
+ if data.is_empty() {
+ return vec![];
+ }
let n = data.len().div_ceil(chunk_size) as u32;
self.dispatch_hash(
&self.hash_chunk_pipeline,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:262:
&pad4(data),
- [n, DOMAIN_HASH, chunk_size as u32, data.len() as u32, 0, 0, 0, 0],
+ [
+ n,
+ DOMAIN_HASH,
+ chunk_size as u32,
+ data.len() as u32,
+ 0,
+ 0,
+ 0,
+ 0,
+ ],
n,
)
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:267:
/// Batch keyed hash โ key read from aux[0..64) by GPU, no per-chunk duplication.
- pub async fn batch_keyed_hash(&self, key: &[u8; OUTPUT_BYTES], data: &[u8], chunk_size: usize) -> Vec<Hash> {
- if data.is_empty() { return vec![]; }
+ pub async fn batch_keyed_hash(
+ &self,
+ key: &[u8; OUTPUT_BYTES],
+ data: &[u8],
+ chunk_size: usize,
+ ) -> Vec<Hash> {
+ if data.is_empty() {
+ return vec![];
+ }
let n = data.len().div_ceil(chunk_size) as u32;
let mut buf = Vec::with_capacity(OUTPUT_BYTES + data.len());
buf.extend_from_slice(key);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:281:
}
/// Derive key: context hash on CPU, material hash on GPU.
- pub async fn batch_derive_key(&self, context: &str, data: &[u8], chunk_size: usize) -> Vec<Hash> {
- if data.is_empty() { return vec![]; }
+ pub async fn batch_derive_key(
+ &self,
+ context: &str,
+ data: &[u8],
+ chunk_size: usize,
+ ) -> Vec<Hash> {
+ if data.is_empty() {
+ return vec![];
+ }
let ctx_hash = cyber_hemera::Hasher::new_derive_key_context(context).finalize();
- self.batch_derive_key_material(&ctx_hash, data, chunk_size).await
+ self.batch_derive_key_material(&ctx_hash, data, chunk_size)
+ .await
}
/// Derive key material phase, seeded by a pre-computed context hash.
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:291:
- pub async fn batch_derive_key_material(&self, ctx: &Hash, data: &[u8], chunk_size: usize) -> Vec<Hash> {
- if data.is_empty() { return vec![]; }
+ pub async fn batch_derive_key_material(
+ &self,
+ ctx: &Hash,
+ data: &[u8],
+ chunk_size: usize,
+ ) -> Vec<Hash> {
+ if data.is_empty() {
+ return vec![];
+ }
let n = data.len().div_ceil(chunk_size) as u32;
let mut aux_u32s: Vec<u32> = Vec::new();
push_hash_u32s(&mut aux_u32s, ctx);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:310:
/// For large inputs, dispatches in batches to avoid GPU timeouts.
/// The counter offset (param slot ns_min_lo) ensures each leaf gets
/// its correct global chunk index regardless of batch boundaries.
- pub async fn batch_hash_leaves(&self, data: &[u8], chunk_size: usize, is_root: bool) -> Vec<Hash> {
- if data.is_empty() { return vec![]; }
+ pub async fn batch_hash_leaves(
+ &self,
+ data: &[u8],
+ chunk_size: usize,
+ is_root: bool,
+ ) -> Vec<Hash> {
+ if data.is_empty() {
+ return vec![];
+ }
let total_chunks = data.len().div_ceil(chunk_size);
if total_chunks <= Self::LEAF_BATCH {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:338:
let hashes = self.dispatch_hash(
&self.hash_leaf_pipeline,
&pad4(slice),
- [n, 0, chunk_size as u32, slice.len() as u32, counter_offset, 0, 0, 0],
+ [
+ n,
+ 0,
+ chunk_size as u32,
+ slice.len() as u32,
+ counter_offset,
+ 0,
+ 0,
+ 0,
+ ],
n,
);
all_hashes.extend(hashes);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:356:
total: usize,
progress: &impl Fn(usize, usize),
) -> Vec<Hash> {
- if data.is_empty() { return vec![]; }
+ if data.is_empty() {
+ return vec![];
+ }
let total_chunks = data.len().div_ceil(chunk_size);
if total_chunks <= Self::LEAF_BATCH {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:384:
let hashes = self.dispatch_hash(
&self.hash_leaf_pipeline,
&pad4(slice),
- [n, 0, chunk_size as u32, slice.len() as u32, counter_offset, 0, 0, 0],
+ [
+ n,
+ 0,
+ chunk_size as u32,
+ slice.len() as u32,
+ counter_offset,
+ 0,
+ 0,
+ 0,
+ ],
n,
);
all_hashes.extend(hashes);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:396:
/// Combine pairs of child hashes into parent hashes.
pub async fn batch_hash_nodes(&self, pairs: &[(Hash, Hash)], is_root: bool) -> Vec<Hash> {
- if pairs.is_empty() { return vec![]; }
+ if pairs.is_empty() {
+ return vec![];
+ }
let n = pairs.len() as u32;
let flags = if is_root { FLAG_ROOT } else { 0 };
self.dispatch_hash(
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:409:
/// Combine pairs with namespace bounds (NMT). Full u64 ns support.
pub async fn batch_hash_nodes_nmt(
- &self, pairs: &[(Hash, Hash)], ns_min: u64, ns_max: u64, is_root: bool,
+ &self,
+ pairs: &[(Hash, Hash)],
+ ns_min: u64,
+ ns_max: u64,
+ is_root: bool,
) -> Vec<Hash> {
- if pairs.is_empty() { return vec![]; }
+ if pairs.is_empty() {
+ return vec![];
+ }
let n = pairs.len() as u32;
let flags = if is_root { FLAG_ROOT } else { 0 };
self.dispatch_hash(
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:418:
&self.hash_node_nmt_pipeline,
&flatten_pairs(pairs),
- [n, flags, 0, 0,
- ns_min as u32, (ns_min >> 32) as u32,
- ns_max as u32, (ns_max >> 32) as u32],
+ [
+ n,
+ flags,
+ 0,
+ 0,
+ ns_min as u32,
+ (ns_min >> 32) as u32,
+ ns_max as u32,
+ (ns_max >> 32) as u32,
+ ],
n,
)
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:447:
}
let n = data.len().div_ceil(CHUNK_SIZE);
if n == 1 {
- return self.batch_hash_leaves(data, CHUNK_SIZE, true).await.remove(0);
+ return self
+ .batch_hash_leaves(data, CHUNK_SIZE, true)
+ .await
+ .remove(0);
}
let total = 2 * n - 1;
progress(0, total);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:454:
- let leaves = self.batch_hash_leaves_progress(data, CHUNK_SIZE, false, total, &progress).await;
- self.merge_tree_with_progress(leaves, n, total, &progress).await
+ let leaves = self
+ .batch_hash_leaves_progress(data, CHUNK_SIZE, false, total, &progress)
+ .await;
+ self.merge_tree_with_progress(leaves, n, total, &progress)
+ .await
}
/// Merge tree with progress reporting.
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:490:
let height = size.trailing_zeros();
if height <= round {
// Already complete or size-1.
- if size > 1 { offset += size >> round; }
+ if size > 1 {
+ offset += size >> round;
+ }
continue;
}
let cur_count = size >> round;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:501:
offset += cur_count;
}
- if pairs.is_empty() { break; }
+ if pairs.is_empty() {
+ break;
+ }
// Determine is_root: only if single segment and final round.
let is_root = num_segments == 1 && round + 1 == max_height;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:508:
let num_pairs = pairs.len();
let results = self.batch_hash_nodes(&pairs, is_root).await;
done += num_pairs;
- if total > 0 { progress(done, total); }
+ if total > 0 {
+ progress(done, total);
+ }
let mut ri = 0;
for (si, &(_, size)) in segments.iter().enumerate() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:543:
let result = self.batch_hash_nodes(&[(left, right)], is_root).await;
roots.push(result[0]);
done += 1;
- if total > 0 { progress(done, total); }
+ if total > 0 {
+ progress(done, total);
+ }
}
roots.pop().unwrap()
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:555:
/// and serializes parent pairs in pre-order.
/// Returns `(root_hash, outboard_bytes)` matching `cyber_hemera::stream::outboard`.
pub async fn outboard(&self, data: &[u8]) -> (Hash, Vec<u8>) {
- let n = if data.is_empty() { 1 } else { data.len().div_ceil(CHUNK_SIZE) };
+ let n = if data.is_empty() {
+ 1
+ } else {
+ data.len().div_ceil(CHUNK_SIZE)
+ };
if n <= 1 {
- let root = self.batch_hash_leaves(data, CHUNK_SIZE, true).await.remove(0);
+ let root = self
+ .batch_hash_leaves(data, CHUNK_SIZE, true)
+ .await
+ .remove(0);
let mut out = Vec::with_capacity(8);
out.extend_from_slice(&(data.len() as u64).to_le_bytes());
return (root, out);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:583:
&self,
proofs: &[(&[u8], &InclusionProof, &Hash)],
) -> Vec<bool> {
- if proofs.is_empty() { return vec![]; }
+ if proofs.is_empty() {
+ return vec![];
+ }
let max_depth = proofs.iter().map(|(_, p, _)| p.depth()).max().unwrap_or(0);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:590:
// Compute initial hashes (leaf or subtree root).
- let mut current: Vec<Hash> = proofs.iter().map(|(chunk, proof, _)| {
- let start = proof.start_chunk;
- let end = proof.end_chunk;
- if end - start == 1 {
- cyber_hemera::tree::hash_leaf(chunk, start, proof.num_chunks == 1)
- } else {
- cyber_hemera::tree::root_hash(chunk)
- }
- }).collect();
+ let mut current: Vec<Hash> = proofs
+ .iter()
+ .map(|(chunk, proof, _)| {
+ let start = proof.start_chunk;
+ let end = proof.end_chunk;
+ if end - start == 1 {
+ cyber_hemera::tree::hash_leaf(chunk, start, proof.num_chunks == 1)
+ } else {
+ cyber_hemera::tree::root_hash(chunk)
+ }
+ })
+ .collect();
if max_depth == 0 {
- return proofs.iter().enumerate()
+ return proofs
+ .iter()
+ .enumerate()
.map(|(i, (_, _, root))| current[i] == **root)
.collect();
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:616:
let siblings = proof.siblings();
// level 0 = leaf-most sibling (last in array).
let sib_idx = siblings.len().checked_sub(1 + level);
- let Some(sib_idx) = sib_idx else { continue; };
+ let Some(sib_idx) = sib_idx else {
+ continue;
+ };
let is_root = sib_idx == 0;
let pair = match siblings[sib_idx] {
Sibling::Left(sib) => (sib, current[i]),
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:645:
}
}
- proofs.iter().enumerate().map(|(i, (_, _, root))| current[i] == **root).collect()
+ proofs
+ .iter()
+ .enumerate()
+ .map(|(i, (_, _, root))| current[i] == **root)
+ .collect()
}
/// Verify multiple sparse Merkle proofs in batch on GPU.
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:658:
proofs: &[(&CompressedSparseProof, Option<&[u8]>, &Hash)],
depth: u32,
) -> Vec<bool> {
- if proofs.is_empty() { return vec![]; }
+ if proofs.is_empty() {
+ return vec![];
+ }
// Compute sentinel table on CPU (done once).
let sentinels = cyber_hemera::sparse::sentinel_table(depth);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:665:
// Compute initial leaf hashes on CPU.
let n = proofs.len();
- let mut current_hashes: Vec<Hash> = proofs.iter().map(|(proof, value, _)| {
- match value {
- Some(v) => cyber_hemera::tree::hash_leaf(
- &[proof.key.as_slice(), *v].concat(), 0, false,
- ),
+ let mut current_hashes: Vec<Hash> = proofs
+ .iter()
+ .map(|(proof, value, _)| match value {
+ Some(v) => {
+ cyber_hemera::tree::hash_leaf(&[proof.key.as_slice(), *v].concat(), 0, false)
+ }
None => sentinels[0],
- }
- }).collect();
+ })
+ .collect();
let mut cursors = vec![0usize; n];
for level in 0..depth {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:732:
}
}
- proofs.iter().enumerate().map(|(i, (proof, _, root))| {
- current_hashes[i] == **root && cursors[i] == proof.siblings.len()
- }).collect()
+ proofs
+ .iter()
+ .enumerate()
+ .map(|(i, (proof, _, root))| {
+ current_hashes[i] == **root && cursors[i] == proof.siblings.len()
+ })
+ .collect()
}
/// Batch XOF squeeze: given finalized sponge states, produce `count`
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/src/lib.rs:744:
states: &Goldilocks; WIDTH,
count: usize,
) -> Vec<Vec<[u8; OUTPUT_BYTES]>> {
- if states.is_empty() || count == 0 { return vec![vec![]; states.len()]; }
+ if states.is_empty() || count == 0 {
+ return vec![vec![]; states.len()];
+ }
let n = states.len();
let mut result = vec![Vec::with_capacity(count); n];
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/tests/gpu.rs:3:
// crystal-type: source
// crystal-domain: comp
// ---
-use cyber_hemera::field::Goldilocks;
-use cyber_hemera::permutation::permute;
-use cyber_hemera::sparse::SparseTree;
-use cyber_hemera::{Hash, CHUNK_SIZE, OUTPUT_BYTES, WIDTH};
+use cyber_hemera::{
+ CHUNK_SIZE, Hash, OUTPUT_BYTES, WIDTH, field::Goldilocks, permutation::permute,
+ sparse::SparseTree,
+};
use cyber_hemera_wgsl::GpuContext;
fn gpu() -> Option<GpuContext> {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/tests/gpu.rs:115:
let gpu_hashes = pollster::block_on(gpu.batch_hash(&data, chunk_size));
assert_eq!(gpu_hashes.len(), 2);
for (i, chunk) in data.chunks(chunk_size).enumerate() {
- assert_eq!(gpu_hashes[i], cyber_hemera::hash(chunk), "chunk {i} mismatch");
+ assert_eq!(
+ gpu_hashes[i],
+ cyber_hemera::hash(chunk),
+ "chunk {i} mismatch"
+ );
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/tests/gpu.rs:309:
let nmt_hash = cyber_hemera::tree::hash_node_nmt(&left, &right, 0, 0, false);
assert_eq!(node_hash, nmt_hash);
- let gpu_nmt =
- pollster::block_on(gpu.batch_hash_nodes_nmt(&[(left, right)], 0, 0, false));
+ let gpu_nmt = pollster::block_on(gpu.batch_hash_nodes_nmt(&[(left, right)], 0, 0, false));
assert_eq!(gpu_nmt[0], node_hash);
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/tests/gpu.rs:521:
assert_eq!(gpu_blocks[0].len(), 3);
// Compare with CPU XOF.
- let mut xof = cyber_hemera::Hasher::new().update(b"xof test").finalize_xof();
+ let mut xof = cyber_hemera::Hasher::new()
+ .update(b"xof test")
+ .finalize_xof();
for block in &gpu_blocks[0] {
let mut cpu_block = [0u8; OUTPUT_BYTES];
xof.fill(&mut cpu_block);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/tests/gpu.rs:532:
#[test]
fn gpu_squeeze_batch() {
require_gpu!(gpu);
- let states: Vec<[Goldilocks; WIDTH]> = (0..3).map(|i| {
- let mut h = cyber_hemera::Hasher::new();
- h.update(&[i as u8; 10]);
- h.finalize_state()
- }).collect();
+ let states: Vec<[Goldilocks; WIDTH]> = (0..3)
+ .map(|i| {
+ let mut h = cyber_hemera::Hasher::new();
+ h.update(&[i as u8; 10]);
+ h.finalize_state()
+ })
+ .collect();
let gpu_blocks = pollster::block_on(gpu.batch_squeeze(&states, 2));
assert_eq!(gpu_blocks.len(), 3);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/tests/gpu.rs:543:
for (i, blocks) in gpu_blocks.iter().enumerate() {
- let mut xof = cyber_hemera::Hasher::new().update(&[i as u8; 10]).finalize_xof();
+ let mut xof = cyber_hemera::Hasher::new()
+ .update(&[i as u8; 10])
+ .finalize_xof();
for block in blocks {
let mut cpu_block = [0u8; OUTPUT_BYTES];
xof.fill(&mut cpu_block);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/tests/gpu.rs:578:
let proof = tree.prove(&absent);
let root = tree.root();
- let results = pollster::block_on(
- gpu.batch_verify_sparse_proofs(&[(&proof, None, &root)], 8),
- );
+ let results = pollster::block_on(gpu.batch_verify_sparse_proofs(&[(&proof, None, &root)], 8));
assert_eq!(results, vec![true]);
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/tests/gpu.rs:629:
fn gpu_verify_sparse_matches_cpu() {
require_gpu!(gpu);
let mut tree = SparseTree::new(16);
- let keys: Vec<[u8; 32]> = (0..5).map(|i| {
- let mut k = [0u8; 32];
- k[0] = i;
- k
- }).collect();
+ let keys: Vec<[u8; 32]> = (0..5)
+ .map(|i| {
+ let mut k = [0u8; 32];
+ k[0] = i;
+ k
+ })
+ .collect();
for (i, key) in keys.iter().enumerate() {
tree.insert(key, &[i as u8; 10]);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/hemera/wgsl/tests/gpu.rs:647:
assert!(SparseTree::verify(proof, Some(&values[i]), &root, 16));
}
- let entries: Vec<_> = proofs.iter().enumerate().map(|(i, p)| {
- (p, Some(values[i].as_slice()), &root)
- }).collect();
+ let entries: Vec<_> = proofs
+ .iter()
+ .enumerate()
+ .map(|(i, p)| (p, Some(values[i].as_slice()), &root))
+ .collect();
let results = pollster::block_on(gpu.batch_verify_sparse_proofs(&entries, 16));
assert_eq!(results, vec![true; 5]);
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/hash.rs:27:
/// - `left`: left child hash
/// - `right`: right child hash
/// - `is_root`: true if this is the tree root
- fn parent_hash(
- &self,
- left: &Self::Hash,
- right: &Self::Hash,
- is_root: bool,
- ) -> Self::Hash;
+ fn parent_hash(&self, left: &Self::Hash, right: &Self::Hash, is_root: bool) -> Self::Hash;
/// Size of the hash output in bytes.
fn hash_size(&self) -> usize;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/decode.rs:4:
//! and verifies every hash against the trusted root. Invalid data is
//! rejected immediately.
-use crate::hash::HashBackend;
-use crate::tree::{BaoChunk, BaoTree, BlockSize, CHUNK_SIZE};
+use crate::{
+ hash::HashBackend,
+ tree::{BaoChunk, BaoTree, BlockSize, CHUNK_SIZE},
+};
/// Error during decoding / verification.
#[derive(Debug, Clone, PartialEq, Eq)]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/decode.rs:185:
#[cfg(test)]
mod tests {
use super::*;
- use crate::hash::Poseidon2Backend;
- use crate::io::encode;
+ use crate::{hash::Poseidon2Backend, io::encode};
#[test]
fn decode_single_block() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/decode.rs:268:
#[test]
fn roundtrip_various_sizes() {
let backend = Poseidon2Backend;
- for size in [0, 1, 512, CHUNK_SIZE, CHUNK_SIZE + 1, CHUNK_SIZE * 2, CHUNK_SIZE * 3 - 1000, CHUNK_SIZE * 4, CHUNK_SIZE * 5 - 1000, CHUNK_SIZE * 8] {
+ for size in [
+ 0,
+ 1,
+ 512,
+ CHUNK_SIZE,
+ CHUNK_SIZE + 1,
+ CHUNK_SIZE * 2,
+ CHUNK_SIZE * 3 - 1000,
+ CHUNK_SIZE * 4,
+ CHUNK_SIZE * 5 - 1000,
+ CHUNK_SIZE * 8,
+ ] {
let data: Vec<u8> = (0..size).map(|i| (i % 256) as u8).collect();
let (root, encoded) = encode::encode(&backend, &data, BlockSize::ZERO);
let decoded = decode(&backend, &encoded, &root, BlockSize::ZERO).unwrap();
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/decode.rs:280:
fn roundtrip_block_size_nonzero() {
let backend = Poseidon2Backend;
let bs = BlockSize::from_chunk_log(1); // 2KB blocks
- for size in [0, CHUNK_SIZE, CHUNK_SIZE * 2, CHUNK_SIZE * 3 - 1000, CHUNK_SIZE * 4, CHUNK_SIZE * 8, CHUNK_SIZE * 10] {
+ for size in [
+ 0,
+ CHUNK_SIZE,
+ CHUNK_SIZE * 2,
+ CHUNK_SIZE * 3 - 1000,
+ CHUNK_SIZE * 4,
+ CHUNK_SIZE * 8,
+ CHUNK_SIZE * 10,
+ ] {
let data: Vec<u8> = (0..size).map(|i| (i % 256) as u8).collect();
let (root, encoded) = encode::encode(&backend, &data, bs);
let decoded = decode(&backend, &encoded, &root, bs).unwrap();
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/decode.rs:287:
- assert_eq!(decoded, data, "roundtrip failed for size {size} with BlockSize(1)");
+ assert_eq!(
+ decoded, data,
+ "roundtrip failed for size {size} with BlockSize(1)"
+ );
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/decode.rs:292:
fn roundtrip_block_size_default() {
let backend = Poseidon2Backend;
let bs = BlockSize::DEFAULT; // 16KiB blocks
- for size in [0, CHUNK_SIZE, CHUNK_SIZE * 4, CHUNK_SIZE * 8, CHUNK_SIZE * 12] {
+ for size in [
+ 0,
+ CHUNK_SIZE,
+ CHUNK_SIZE * 4,
+ CHUNK_SIZE * 8,
+ CHUNK_SIZE * 12,
+ ] {
let data: Vec<u8> = (0..size).map(|i| (i % 256) as u8).collect();
let (root, encoded) = encode::encode(&backend, &data, bs);
let decoded = decode(&backend, &encoded, &root, bs).unwrap();
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/decode.rs:299:
- assert_eq!(decoded, data, "roundtrip failed for size {size} with BlockSize::DEFAULT");
+ assert_eq!(
+ decoded, data,
+ "roundtrip failed for size {size} with BlockSize::DEFAULT"
+ );
}
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/encode.rs:9:
//! Parent nodes appear before their children, so the decoder can verify
//! each piece as it arrives without buffering the entire file.
-use crate::hash::HashBackend;
-use crate::io::outboard;
-use crate::tree::{BaoChunk, BlockSize, CHUNK_SIZE};
+use crate::{
+ hash::HashBackend,
+ io::outboard,
+ tree::{BaoChunk, BlockSize, CHUNK_SIZE},
+};
/// Encode data into the combined (pre-order) format.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/encode.rs:75:
// Header (8 bytes) + data (CHUNK_SIZE bytes), no parents
assert_eq!(encoded.len(), 8 + CHUNK_SIZE);
- assert_eq!(u64::from_le_bytes(encoded[..8].try_into().unwrap()), CHUNK_SIZE as u64);
+ assert_eq!(
+ u64::from_le_bytes(encoded[..8].try_into().unwrap()),
+ CHUNK_SIZE as u64
+ );
assert_eq!(&encoded[8..], &data[..]);
assert_eq!(root, backend.chunk_hash(&data, 0, true));
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/error.rs:107:
use std::{fmt, io};
use serde::{
- de::{self, Visitor},
Deserializer, Serializer,
+ de::{self, Visitor},
};
pub fn serialize<S>(error: &io::Error, serializer: S) -> Result<S::Ok, S::Error>
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/fsm.rs:5:
use std::io;
+use hemera::OUTPUT_BYTES;
use smallvec::SmallVec;
-use hemera::OUTPUT_BYTES;
+use crate::{
+ ChunkRanges,
+ hash::HashBackend,
+ io::{
+ content::{BaoContentItem, Leaf, Parent},
+ error::DecodeError,
+ },
+ tree::{BaoChunk, BaoTree, CHUNK_SIZE, ChunkNum, TreeNode},
+};
-use crate::hash::HashBackend;
-use crate::io::content::{BaoContentItem, Leaf, Parent};
-use crate::io::error::DecodeError;
-use crate::tree::{BaoChunk, BaoTree, ChunkNum, TreeNode, CHUNK_SIZE};
-use crate::ChunkRanges;
-
/// Size of a hash pair (two hashes concatenated).
const PAIR_SIZE: usize = OUTPUT_BYTES * 2;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/fsm.rs:95:
/// Create a new decoder for the given root hash, ranges, tree, and reader.
///
/// Only items matching the requested ranges will be read from the stream.
- pub fn new(
- hash: hemera::Hash,
- ranges: ChunkRanges,
- tree: BaoTree,
- encoded: R,
- ) -> Self {
+ pub fn new(hash: hemera::Hash, ranges: ChunkRanges, tree: BaoTree, encoded: R) -> Self {
let items = tree.pre_order_chunks_filtered(&ranges);
let mut stack = SmallVec::new();
stack.push(hash.clone());
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/fsm.rs:140:
}
}
- async fn next0(
- &mut self,
- ) -> Option<Result<BaoContentItem<hemera::Hash>, DecodeError>> {
+ async fn next0(&mut self) -> Option<Result<BaoContentItem<hemera::Hash>, DecodeError>> {
let inner = &mut self.inner;
if inner.pos >= inner.items.len() {
// Final length validation: decoded bytes must not exceed tree size
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/fsm.rs:162:
let block_bytes = inner.tree.block_size().bytes();
match chunk {
- BaoChunk::Parent { node, is_root, left: visit_left, right: visit_right } => {
+ BaoChunk::Parent {
+ node,
+ is_root,
+ left: visit_left,
+ right: visit_right,
+ } => {
let pair_buf: [u8; PAIR_SIZE] = match inner.encoded.read().await {
Ok(buf) => buf,
Err(e) => return Some(Err(DecodeError::Io(e))),
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/fsm.rs:169:
};
- let left =
- hemera::Hash::from_bytes(pair_buf[..OUTPUT_BYTES].try_into().unwrap());
- let right =
- hemera::Hash::from_bytes(pair_buf[OUTPUT_BYTES..].try_into().unwrap());
+ let left = hemera::Hash::from_bytes(pair_buf[..OUTPUT_BYTES].try_into().unwrap());
+ let right = hemera::Hash::from_bytes(pair_buf[OUTPUT_BYTES..].try_into().unwrap());
let computed = backend.parent_hash(&left, &right, is_root);
let expected = match inner.stack.pop() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/fsm.rs:214:
Err(e) => return Some(Err(DecodeError::Io(e))),
};
- let computed =
- hash_block(&backend, &leaf_data, start_chunk, is_root, block_bytes);
+ let computed = hash_block(&backend, &leaf_data, start_chunk, is_root, block_bytes);
let expected = match inner.stack.pop() {
Some(h) => h,
None => {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/fsm.rs:243:
#[cfg(test)]
mod tests {
- use super::*;
use bytes::Bytes;
- use crate::hash::Poseidon2Backend;
- use crate::io::encode;
- use crate::tree::BlockSize;
+ use super::*;
+ use crate::{hash::Poseidon2Backend, io::encode, tree::BlockSize};
+
#[tokio::test]
async fn fsm_decode_two_blocks() {
let backend = Poseidon2Backend;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/fsm.rs:257:
let tree = BaoTree::new(CHUNK_SIZE as u64 * 2, BlockSize::ZERO);
let encoded_bytes = Bytes::from(encoded[8..].to_vec());
- let decoder =
- ResponseDecoder::new(root, ChunkRanges::all(), tree, encoded_bytes);
+ let decoder = ResponseDecoder::new(root, ChunkRanges::all(), tree, encoded_bytes);
assert_eq!(decoder.tree(), tree);
assert_eq!(*decoder.hash(), root);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/fsm.rs:291:
let ranges = ChunkRanges::from(ChunkNum(0)..ChunkNum(1));
// Build the encoded stream for just this range using sync encoder
- use crate::io::pre_order::PreOrderMemOutboard;
- use crate::io::sync::encode_ranges_validated;
+ use crate::io::{pre_order::PreOrderMemOutboard, sync::encode_ranges_validated};
let outboard = PreOrderMemOutboard::create(&data, BlockSize::ZERO);
let mut range_encoded = Vec::new();
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/mixed.rs:8:
use smallvec::SmallVec;
-use crate::hash::HashBackend;
-use crate::io::content::{Leaf, Parent};
-use crate::io::error::EncodeError;
-use crate::io::traits::{Outboard, ReadBytesAt};
-use crate::tree::{BaoChunk, BaoTree, ChunkNum, CHUNK_SIZE};
-use crate::ChunkRanges;
+use crate::{
+ ChunkRanges,
+ hash::HashBackend,
+ io::{
+ content::{Leaf, Parent},
+ error::EncodeError,
+ traits::{Outboard, ReadBytesAt},
+ },
+ tree::{BaoChunk, BaoTree, CHUNK_SIZE, ChunkNum},
+};
/// An item in the encoded BAO stream.
#[derive(Debug)]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/mixed.rs:94:
for chunk in &pre_order {
match chunk {
- BaoChunk::Parent { node, is_root, left, right } => {
+ BaoChunk::Parent {
+ node,
+ is_root,
+ left,
+ right,
+ } => {
let pair = match outboard.load(*node) {
Ok(Some(pair)) => pair,
Ok(None) => {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/mixed.rs:118:
stack.push(pair.0.clone());
}
- send.send(EncodedItem::Parent(Parent {
- node: *node,
- pair,
- }))
- .await?;
+ send.send(EncodedItem::Parent(Parent { node: *node, pair }))
+ .await?;
}
BaoChunk::Leaf {
start_chunk,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/mixed.rs:136:
};
let chunk_num = ChunkNum(*start_chunk);
- let computed =
- hash_block(&backend, &leaf_data, *start_chunk, *is_root, block_size.bytes());
+ let computed = hash_block(
+ &backend,
+ &leaf_data,
+ *start_chunk,
+ *is_root,
+ block_size.bytes(),
+ );
let expected = match stack.pop() {
Some(h) => h,
None => return Ok(Err(EncodeError::LeafHashMismatch(chunk_num))),
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/mod.rs:20:
// Re-export commonly used types at the io level.
pub use content::{BaoContentItem, Leaf, Parent};
pub use error::{DecodeError, EncodeError};
+use range_collections::range_set::RangeSetRange;
pub use traits::{Outboard, OutboardMut, ReadAt, ReadBytesAt, Size, WriteAt};
-use range_collections::range_set::RangeSetRange;
-
-use crate::hash::{HashBackend, Poseidon2Backend};
-use crate::tree::{BlockSize, ChunkNum, CHUNK_SIZE};
-use crate::{ByteRanges, ChunkRanges};
+use crate::{
+ ByteRanges, ChunkRanges,
+ hash::{HashBackend, Poseidon2Backend},
+ tree::{BlockSize, CHUNK_SIZE, ChunkNum},
+};
/// Compute the root hash for a single block (possibly multi-chunk).
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/outboard.rs:6:
use std::collections::HashMap;
-use crate::hash::HashBackend;
-use crate::tree::{BaoChunk, BaoTree, BlockSize, CHUNK_SIZE};
+use crate::{
+ hash::HashBackend,
+ tree::{BaoChunk, BaoTree, BlockSize, CHUNK_SIZE},
+};
/// Result of computing the outboard for a blob.
#[derive(Debug, Clone)]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/pre_order.rs:10:
use hemera::OUTPUT_BYTES;
-use crate::io::outboard as outboard_fn;
-use crate::io::traits::{Outboard, OutboardMut, ReadAt, WriteAt};
-use crate::tree::{BaoTree, BlockSize, TreeNode};
+use crate::{
+ io::{
+ outboard as outboard_fn,
+ traits::{Outboard, OutboardMut, ReadAt, WriteAt},
+ },
+ tree::{BaoTree, BlockSize, TreeNode},
+};
/// Size of a hash pair (two hashes concatenated).
const PAIR_SIZE: usize = OUTPUT_BYTES * 2;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/pre_order.rs:129:
if byte_offset + PAIR_SIZE > self.data.len() {
return Ok(None);
}
- let left = H::from(<[u8; OUTPUT_BYTES]>::try_from(&self.data[byte_offset..byte_offset + OUTPUT_BYTES]).unwrap());
- let right =
- H::from(<[u8; OUTPUT_BYTES]>::try_from(&self.data[byte_offset + OUTPUT_BYTES..byte_offset + PAIR_SIZE]).unwrap());
+ let left = H::from(
+ <[u8; OUTPUT_BYTES]>::try_from(&self.data[byte_offset..byte_offset + OUTPUT_BYTES])
+ .unwrap(),
+ );
+ let right = H::from(
+ <[u8; OUTPUT_BYTES]>::try_from(
+ &self.data[byte_offset + OUTPUT_BYTES..byte_offset + PAIR_SIZE],
+ )
+ .unwrap(),
+ );
Ok(Some((left, right)))
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/pre_order.rs:303:
if byte_offset + PAIR_SIZE > self.data.len() {
return Ok(None);
}
- let left =
- H::from(<[u8; OUTPUT_BYTES]>::try_from(&self.data[byte_offset..byte_offset + OUTPUT_BYTES]).unwrap());
- let right =
- H::from(<[u8; OUTPUT_BYTES]>::try_from(&self.data[byte_offset + OUTPUT_BYTES..byte_offset + PAIR_SIZE]).unwrap());
+ let left = H::from(
+ <[u8; OUTPUT_BYTES]>::try_from(&self.data[byte_offset..byte_offset + OUTPUT_BYTES])
+ .unwrap(),
+ );
+ let right = H::from(
+ <[u8; OUTPUT_BYTES]>::try_from(
+ &self.data[byte_offset + OUTPUT_BYTES..byte_offset + PAIR_SIZE],
+ )
+ .unwrap(),
+ );
Ok(Some((left, right)))
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/pre_order.rs:339:
#[cfg(test)]
mod tests {
use super::*;
- use crate::hash::Poseidon2Backend;
- use crate::io::outboard::outboard;
- use crate::tree::CHUNK_SIZE;
+ use crate::{hash::Poseidon2Backend, io::outboard::outboard, tree::CHUNK_SIZE};
#[test]
fn pre_order_outboard_roundtrip() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/pre_order.rs:398:
#[test]
fn post_order_can_validate_via_encode_ranges() {
- use crate::io::sync::encode_ranges_validated;
- use crate::ChunkRanges;
+ use crate::{ChunkRanges, io::sync::encode_ranges_validated};
let data = vec![0x42u8; CHUNK_SIZE * 4];
let post_ob = PostOrderMemOutboard::create(&data, BlockSize::ZERO);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/slice.rs:7:
use std::ops::Range;
-use crate::hash::HashBackend;
-use crate::io::outboard;
-use crate::tree::{BaoChunk, BaoTree, BlockSize, ChunkNum, CHUNK_SIZE};
-use crate::{ChunkRanges, ChunkRangesRef};
+use crate::{
+ ChunkRanges, ChunkRangesRef,
+ hash::HashBackend,
+ io::outboard,
+ tree::{BaoChunk, BaoTree, BlockSize, CHUNK_SIZE, ChunkNum},
+};
/// Extract a slice (proof + data) for the given byte range.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/slice.rs:65:
outboard_offset += pair_size;
}
BaoChunk::Leaf {
- start_chunk,
- size,
- ..
+ start_chunk, size, ..
} => {
let chunks_per_block = 1u64 << block_size.chunk_log();
let block_idx = *start_chunk / chunks_per_block;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/slice.rs:74:
let leaf_start = block_idx * chunks_per_block;
let leaf_end = leaf_start + chunks_per_block;
- let leaf_range =
- ChunkRanges::from(ChunkNum(leaf_start)..ChunkNum(leaf_end));
+ let leaf_range = ChunkRanges::from(ChunkNum(leaf_start)..ChunkNum(leaf_end));
if !leaf_range.is_disjoint(ranges) {
let byte_start = (*start_chunk * CHUNK_SIZE as u64) as usize;
let byte_end = (byte_start + *size).min(data.len());
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/slice.rs:269:
fn slice_full_range_matches_encode() {
let backend = Poseidon2Backend;
let data = vec![0x42u8; CHUNK_SIZE * 2];
- let (root, slice) = extract_slice(&backend, &data, 0..CHUNK_SIZE as u64 * 2, BlockSize::ZERO);
+ let (root, slice) =
+ extract_slice(&backend, &data, 0..CHUNK_SIZE as u64 * 2, BlockSize::ZERO);
assert_eq!(slice.len(), 8 + PAIR_SIZE + CHUNK_SIZE * 2);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/slice.rs:283:
fn slice_partial_range_is_smaller() {
let backend = Poseidon2Backend;
let data = vec![0x42u8; CHUNK_SIZE * 4];
- let (root_full, full_slice) = extract_slice(&backend, &data, 0..CHUNK_SIZE as u64 * 4, BlockSize::ZERO);
+ let (root_full, full_slice) =
+ extract_slice(&backend, &data, 0..CHUNK_SIZE as u64 * 4, BlockSize::ZERO);
let (root_partial, partial_slice) =
extract_slice(&backend, &data, 0..CHUNK_SIZE as u64, BlockSize::ZERO);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/slice.rs:296:
let backend = Poseidon2Backend;
let data = vec![0x42u8; CHUNK_SIZE * 4];
let (root1, _) = extract_slice(&backend, &data, 0..CHUNK_SIZE as u64, BlockSize::ZERO);
- let (root2, _) = extract_slice(&backend, &data, CHUNK_SIZE as u64..CHUNK_SIZE as u64 * 2, BlockSize::ZERO);
+ let (root2, _) = extract_slice(
+ &backend,
+ &data,
+ CHUNK_SIZE as u64..CHUNK_SIZE as u64 * 2,
+ BlockSize::ZERO,
+ );
let (root3, _) = extract_slice(&backend, &data, 0..CHUNK_SIZE as u64 * 4, BlockSize::ZERO);
assert_eq!(root1, root2);
assert_eq!(root2, root3);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/slice.rs:387:
let ranges = ChunkRanges::all();
let (root, slice) = extract_slice_ranges(&backend, &data, &ranges, bs);
- let results = decode_slice(&backend, &slice, &root, &ranges, bs)
- .expect("decode should succeed");
+ let results =
+ decode_slice(&backend, &slice, &root, &ranges, bs).expect("decode should succeed");
let mut decoded = vec![0u8; CHUNK_SIZE * 8];
for (offset, chunk) in &results {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/sync.rs:5:
use std::io::{self, Write};
+use hemera::OUTPUT_BYTES;
use smallvec::SmallVec;
-use hemera::OUTPUT_BYTES;
+use crate::{
+ ChunkRangesRef,
+ hash::{HashBackend, Poseidon2Backend},
+ io::{
+ error::EncodeError,
+ traits::{Outboard, ReadAt},
+ },
+ tree::{CHUNK_SIZE, ChunkNum},
+};
-use crate::hash::{HashBackend, Poseidon2Backend};
-use crate::io::error::EncodeError;
-use crate::io::traits::{Outboard, ReadAt};
-use crate::tree::{ChunkNum, CHUNK_SIZE};
-use crate::ChunkRangesRef;
-
/// Size of a hash pair (two hashes concatenated).
const PAIR_SIZE: usize = OUTPUT_BYTES * 2;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/sync.rs:47:
for chunk in &pre_order {
match chunk {
- crate::tree::BaoChunk::Parent { node, is_root, left, right } => {
+ crate::tree::BaoChunk::Parent {
+ node,
+ is_root,
+ left,
+ right,
+ } => {
let (l_hash, r_hash) = outboard.load(*node)?.unwrap();
let actual = backend.parent_hash(&l_hash, &r_hash, *is_root);
let expected = stack.pop().unwrap();
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/sync.rs:101:
D: ReadAt + 'a,
{
genawaiter::sync::Gen::new(move |co| async move {
- if let Err(cause) =
- validate_ranges_impl(outboard, data, ranges, &co).await
- {
+ if let Err(cause) = validate_ranges_impl(outboard, data, ranges, &co).await {
co.yield_(Err(cause)).await;
}
})
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/sync.rs:228:
let ranges = truncate_ranges(ranges, tree.size());
validate_node_rec(
- &outboard, &data, &backend, &tree, tree.root(), outboard.root(),
- true, ranges, co,
- ).await;
+ &outboard,
+ &data,
+ &backend,
+ &tree,
+ tree.root(),
+ outboard.root(),
+ true,
+ ranges,
+ co,
+ )
+ .await;
Ok(())
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/sync.rs:246:
is_root: bool,
ranges: &ChunkRangesRef,
co: &genawaiter::sync::Co<io::Result<std::ops::Range<ChunkNum>>>,
-)
-where
+) where
O: Outboard<Hash = hemera::Hash>,
D: ReadAt,
{
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/sync.rs:281:
if actual == expected_hash {
let chunks_per_block = 1u64 << tree.block_size().chunk_log();
let leaf_end_chunk = start_chunk + chunks_per_block;
- co.yield_(Ok(ChunkNum(start_chunk)..ChunkNum(leaf_end_chunk))).await;
+ co.yield_(Ok(ChunkNum(start_chunk)..ChunkNum(leaf_end_chunk)))
+ .await;
}
return;
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/sync.rs:296:
// No right child โ skip parent, recurse left with inherited is_root
if let Some(left) = node.left_child() {
Box::pin(validate_node_rec(
- outboard, data, backend, tree, left, expected_hash,
- is_root, ranges, co,
- )).await;
+ outboard,
+ data,
+ backend,
+ tree,
+ left,
+ expected_hash,
+ is_root,
+ ranges,
+ co,
+ ))
+ .await;
}
return;
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/sync.rs:318:
// Recurse into children
if let Some(left) = node.left_child() {
Box::pin(validate_node_rec(
- outboard, data, backend, tree, left, l_hash,
- false, ranges, co,
- )).await;
+ outboard, data, backend, tree, left, l_hash, false, ranges, co,
+ ))
+ .await;
}
if let Some(right) = node.right_child() {
Box::pin(validate_node_rec(
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/sync.rs:327:
- outboard, data, backend, tree, right, r_hash,
- false, ranges, co,
- )).await;
+ outboard, data, backend, tree, right, r_hash, false, ranges, co,
+ ))
+ .await;
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/io/sync.rs:333:
#[cfg(test)]
mod tests {
use super::*;
- use crate::io::pre_order::PreOrderMemOutboard;
- use crate::tree::{BlockSize, ChunkNum};
- use crate::ChunkRanges;
+ use crate::{
+ ChunkRanges,
+ io::pre_order::PreOrderMemOutboard,
+ tree::{BlockSize, ChunkNum},
+ };
#[test]
fn encode_ranges_validated_full() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/lib.rs:16:
pub mod tree;
pub use hash::{HashBackend, Poseidon2Backend};
-pub use tree::{BaoChunk, BaoTree, BlockSize, ChunkNum, PostOrderChunkIter, TreeNode, CHUNK_SIZE};
+pub use tree::{BaoChunk, BaoTree, BlockSize, CHUNK_SIZE, ChunkNum, PostOrderChunkIter, TreeNode};
/// A set of chunk ranges (used for partial downloads, range requests, etc.).
pub type ChunkRanges = range_collections::RangeSet2<ChunkNum>;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/tree.rs:4:
//! The tree uses in-order indexing (same as bao-tree): leaves at
//! even positions, parents at odd positions, level = trailing ones count.
-use std::fmt;
-use std::ops::Range;
+use std::{fmt, ops::Range};
use hemera::OUTPUT_BYTES;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/tree.rs:541:
}
// Both children exist โ emit parent, then recurse left and right
- out.push(BaoChunk::Parent { node, is_root, left: true, right: true });
+ out.push(BaoChunk::Parent {
+ node,
+ is_root,
+ left: true,
+ right: true,
+ });
if let Some(left) = node.left_child() {
self.pre_order_recurse(left, false, total_blocks, out);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/tree.rs:622:
}
// Parent after children
- out.push(BaoChunk::Parent { node, is_root, left: true, right: true });
+ out.push(BaoChunk::Parent {
+ node,
+ is_root,
+ left: true,
+ right: true,
+ });
}
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/tree.rs:642:
}
if blocks == 1 {
let chunk_bytes = self.size.min(self.block_size.bytes() as u64) as usize;
- let leaf_range = range_collections::RangeSet2::from(ChunkNum(0)..ChunkNum(1u64 << self.block_size.0));
+ let leaf_range = range_collections::RangeSet2::from(
+ ChunkNum(0)..ChunkNum(1u64 << self.block_size.0),
+ );
if leaf_range.is_disjoint(ranges) {
return vec![];
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/tree.rs:668:
) {
// Check if this node's subtree overlaps the ranges (actual chunk space)
let actual_range = self.node_actual_chunk_range(node);
- let node_chunks =
- range_collections::RangeSet2::from(actual_range.start..actual_range.end);
+ let node_chunks = range_collections::RangeSet2::from(actual_range.start..actual_range.end);
if node_chunks.is_disjoint(ranges) {
return;
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/tree.rs:727:
}
// Emit the parent โ the hash pair is needed to verify children
- out.push(BaoChunk::Parent { node, is_root, left: left_overlaps, right: right_overlaps });
+ out.push(BaoChunk::Parent {
+ node,
+ is_root,
+ left: left_overlaps,
+ right: right_overlaps,
+ });
// Only recurse into children that overlap the ranges
if left_overlaps {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/cyber-bao/src/tree.rs:795:
#[test]
fn block_size_from_bytes() {
- assert_eq!(BlockSize::from_bytes(CHUNK_SIZE as u64), Some(BlockSize::ZERO));
- assert_eq!(BlockSize::from_bytes(CHUNK_SIZE as u64 * 4), Some(BlockSize::DEFAULT));
+ assert_eq!(
+ BlockSize::from_bytes(CHUNK_SIZE as u64),
+ Some(BlockSize::ZERO)
+ );
+ assert_eq!(
+ BlockSize::from_bytes(CHUNK_SIZE as u64 * 4),
+ Some(BlockSize::DEFAULT)
+ );
assert_eq!(BlockSize::from_bytes(512), None);
assert_eq!(BlockSize::from_bytes(3000), None);
}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/bench/src/iroh.rs:4:
};
use bytes::Bytes;
+use n0_error::{Result, StackResultExt, StdResultExt};
use radio::{
Endpoint, EndpointAddr, RelayMode, RelayUrl,
endpoint::{Connection, ConnectionError, QuicTransportConfig, RecvStream, SendStream},
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/bench/src/iroh.rs:10:
};
-use n0_error::{Result, StackResultExt, StdResultExt};
use tracing::{trace, warn};
use crate::{
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/0rtt.rs:2:
use clap::Parser;
use data_encoding::HEXLOWER;
+use n0_error::{Result, StackResultExt, StdResultExt};
+use n0_future::StreamExt;
use radio::{
EndpointId, SecretKey,
address_lookup::AddressLookup,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/0rtt.rs:8:
endpoint::{RecvStream, SendStream, ZeroRttStatus},
};
-use n0_error::{Result, StackResultExt, StdResultExt};
-use n0_future::StreamExt;
use tracing::{info, trace};
const PINGPONG_ALPN: &[u8] = b"0rtt-pingpong";
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/auth-hook.rs:4:
//! It allows to put authentication in front of iroh protocols. The protocols don't need any special support.
//! Authentication is handled prior to establishing the connections, over a separate connection.
-use radio::{Endpoint, EndpointAddr, protocol::Router};
use n0_error::{Result, StdResultExt};
+use radio::{Endpoint, EndpointAddr, protocol::Router};
use crate::echo::Echo;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/auth-hook.rs:60:
mod echo {
//! A bare-bones protocol with no knowledge of auth whatsoever.
+ use n0_error::{Result, StdResultExt, anyerr};
use radio::{
Endpoint, EndpointAddr,
endpoint::Connection,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/auth-hook.rs:66:
protocol::{AcceptError, ProtocolHandler},
};
- use n0_error::{Result, StdResultExt, anyerr};
#[derive(Debug, Clone)]
pub struct Echo;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/auth-hook.rs:111:
sync::{Arc, Mutex},
};
+ use n0_error::{AnyError, Result, StackResultExt, StdResultExt, anyerr};
+ use n0_future::task::AbortOnDropHandle;
use radio::{
Endpoint, EndpointAddr, EndpointId,
endpoint::{
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/auth-hook.rs:118:
},
protocol::{AcceptError, ProtocolHandler},
};
- use n0_error::{AnyError, Result, StackResultExt, StdResultExt, anyerr};
- use n0_future::task::AbortOnDropHandle;
use tokio::{
sync::{mpsc, oneshot},
task::JoinSet,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/connect-unreliable.rs:8:
use std::net::SocketAddr;
use clap::Parser;
-use radio::{Endpoint, EndpointAddr, RelayMode, RelayUrl, SecretKey};
use iroh_base::TransportAddr;
use n0_error::{Result, StdResultExt};
+use radio::{Endpoint, EndpointAddr, RelayMode, RelayUrl, SecretKey};
use tracing::info;
// An example ALPN that we are using to communicate over the `Endpoint`
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/connect.rs:8:
use std::net::SocketAddr;
use clap::Parser;
-use radio::{Endpoint, EndpointAddr, RelayMode, RelayUrl, SecretKey, TransportAddr};
use n0_error::{Result, StdResultExt};
+use radio::{Endpoint, EndpointAddr, RelayMode, RelayUrl, SecretKey, TransportAddr};
use tracing::info;
// An example ALPN that we are using to communicate over the `Endpoint`
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/dht_address_lookup.rs:11:
use std::str::FromStr;
use clap::Parser;
-use radio::{Endpoint, EndpointId};
use n0_error::{Result, StdResultExt};
+use radio::{Endpoint, EndpointId};
use tracing::warn;
use url::Url;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/echo-no-router.rs:7:
//!
//! cargo run --example echo-no-router --features=examples
-use radio::{Endpoint, EndpointAddr};
use n0_error::{AnyError as Error, Result, StdResultExt};
+use radio::{Endpoint, EndpointAddr};
/// Each protocol is identified by its ALPN string.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/echo.rs:6:
//!
//! cargo run --example echo --features=examples
+use n0_error::{Result, StdResultExt};
use radio::{
Endpoint, EndpointAddr,
endpoint::Connection,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/echo.rs:12:
protocol::{AcceptError, ProtocolHandler, Router},
};
-use n0_error::{Result, StdResultExt};
/// Each protocol is identified by its ALPN string.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/listen-unreliable.rs:3:
//! This example uses the default relay servers to attempt to holepunch, and will use that relay server to relay packets if the two devices cannot establish a direct UDP connection.
//! run this example from the project root:
//! $ cargo run --example listen-unreliable
-use radio::{Endpoint, RelayMode, SecretKey};
use n0_error::{AnyError as Error, Result, StdResultExt};
+use radio::{Endpoint, RelayMode, SecretKey};
use tracing::{info, warn};
// An example ALPN that we are using to communicate over the `Endpoint`
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/listen.rs:5:
//! $ cargo run --example listen
use std::time::Duration;
-use radio::{Endpoint, RelayMode, SecretKey, endpoint::ConnectionError};
use n0_error::{Result, StdResultExt};
+use radio::{Endpoint, RelayMode, SecretKey, endpoint::ConnectionError};
use tracing::{debug, info, warn};
// An example ALPN that we are using to communicate over the `Endpoint`
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/mdns_address_lookup.rs:5:
//! This is an async, non-determinate process, so the number of EndpointIDs discovered each time may be different. If you have other iroh endpoints or iroh endpoints with [`address_lookup::MdnsAddressLookup`] enabled, it may discover those endpoints as well.
use std::time::Duration;
-use radio::{Endpoint, EndpointId, address_lookup, endpoint_info::UserData};
use n0_error::Result;
use n0_future::StreamExt;
+use radio::{Endpoint, EndpointId, address_lookup, endpoint_info::UserData};
use tokio::task::JoinSet;
#[tokio::main]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/monitor-connections.rs:1:
use std::{sync::Arc, time::Duration};
+use n0_error::{Result, StackResultExt, StdResultExt, ensure_any};
+use n0_future::task::AbortOnDropHandle;
use radio::{
Endpoint, RelayMode, Watcher,
endpoint::{AfterHandshakeOutcome, ConnectionInfo, EndpointHooks},
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/monitor-connections.rs:6:
};
-use n0_error::{Result, StackResultExt, StdResultExt, ensure_any};
-use n0_future::task::AbortOnDropHandle;
use tokio::{
sync::mpsc::{UnboundedReceiver, UnboundedSender},
task::JoinSet,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/remote-info.rs:7:
use std::time::{Duration, SystemTime};
-use radio::{Endpoint, EndpointAddr};
use n0_error::{Result, StackResultExt, StdResultExt, ensure_any};
use n0_future::IterExt;
+use radio::{Endpoint, EndpointAddr};
use tracing::{Instrument, info, info_span};
use crate::remote_map::RemoteMap;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/remote-info.rs:165:
time::{Duration, SystemTime},
};
+ use n0_future::task::AbortOnDropHandle;
use radio::{
EndpointId, Watcher,
endpoint::{AfterHandshakeOutcome, ConnectionInfo, EndpointHooks, PathInfo},
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/remote-info.rs:171:
};
- use n0_future::task::AbortOnDropHandle;
use tokio::{sync::mpsc, task::JoinSet};
use tokio_stream::StreamExt;
use tracing::{Instrument, debug, info, info_span};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/screening-connection.rs:12:
atomic::{AtomicU64, Ordering},
};
+use n0_error::{Result, StdResultExt, e};
use radio::{
Endpoint, EndpointAddr,
endpoint::{Accepting, Connection},
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/screening-connection.rs:18:
protocol::{AcceptError, ProtocolHandler, Router},
};
-use n0_error::{Result, StdResultExt, e};
/// Each protocol is identified by its ALPN string.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/search.rs:32:
use std::{collections::BTreeSet, sync::Arc};
use clap::Parser;
+use n0_error::{Result, StdResultExt};
use radio::{
Endpoint, EndpointId,
endpoint::Connection,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/search.rs:38:
protocol::{AcceptError, ProtocolHandler, Router},
};
-use n0_error::{Result, StdResultExt};
use tokio::sync::Mutex;
use tracing_subscriber::{EnvFilter, prelude::*};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/transfer.rs:37:
use data_encoding::HEXLOWER;
use derive_more::{Display, From};
use indicatif::HumanBytes;
+use n0_error::{Result, StackResultExt, StdResultExt, anyerr, ensure_any};
+use n0_future::{stream::StreamExt, task::AbortOnDropHandle};
+use netdev::ipnet::{Ipv4Net, Ipv6Net};
+use postcard::experimental::max_size::MaxSize;
#[cfg(feature = "qlog")]
use radio::endpoint::QuicTransportConfig;
use radio::{
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/examples/transfer.rs:52:
WriteError,
},
};
-use n0_error::{Result, StackResultExt, StdResultExt, anyerr, ensure_any};
-use n0_future::{stream::StreamExt, task::AbortOnDropHandle};
-use netdev::ipnet::{Ipv4Net, Ipv6Net};
-use postcard::experimental::max_size::MaxSize;
use serde::{Deserialize, Serialize, Serializer};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/src/address_lookup/mdns.rs:8:
//! ```no_run
//! use std::time::Duration;
//!
+//! use n0_future::StreamExt;
//! use radio::{
//! RelayMode, SecretKey,
//! address_lookup::{DiscoveryEvent, MdnsAddressLookup},
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/src/address_lookup/mdns.rs:14:
//! endpoint::{Endpoint, Source},
//! };
-//! use n0_future::StreamExt;
//!
//! #[tokio::main]
//! async fn main() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/src/address_lookup/memory.rs:37:
/// # Examples
///
/// ```rust
-/// use radio::{Endpoint, EndpointAddr, TransportAddr, address_lookup::memory::MemoryLookup};
/// use iroh_base::SecretKey;
+/// use radio::{Endpoint, EndpointAddr, TransportAddr, address_lookup::memory::MemoryLookup};
///
/// # #[tokio::main]
/// # async fn main() -> n0_error::Result<()> {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/src/lib.rs:170:
//! The central struct is the [`Endpoint`], which allows you to connect to other endpoints:
//!
//! ```no_run
-//! use radio::{Endpoint, EndpointAddr};
//! use n0_error::{Result, StackResultExt, StdResultExt};
+//! use radio::{Endpoint, EndpointAddr};
//!
//! async fn connect(addr: EndpointAddr) -> Result<()> {
//! // The Endpoint is the central object that manages an iroh node.
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/src/lib.rs:195:
//! Every [`Endpoint`] can also accept connections:
//!
//! ```no_run
-//! use radio::{Endpoint, EndpointAddr};
//! use n0_error::{Result, StackResultExt, StdResultExt};
//! use n0_future::StreamExt;
+//! use radio::{Endpoint, EndpointAddr};
//!
//! async fn accept() -> Result<()> {
//! // To accept connections at least one ALPN must be configured.
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/tests/integration.rs:9:
//!
//! In the past we've hit relay rate-limits from all the tests in our CI, but I expect
//! we won't hit these with only this integration test.
-use radio::{
- Endpoint, RelayMode,
- address_lookup::{AddressLookup, pkarr::PkarrResolver},
-};
use n0_error::{Result, StdResultExt};
use n0_future::{
StreamExt, task,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh/tests/integration.rs:19:
time::{self, Duration},
+};
+use radio::{
+ Endpoint, RelayMode,
+ address_lookup::{AddressLookup, pkarr::PkarrResolver},
};
#[cfg(not(wasm_browser))]
use tokio::test;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/iroh-relay/src/protos/handshake.rs:592:
// we simulate something like exporting keying material using hemera
let label_key = hemera::hash(label);
- let context_key =
- hemera::keyed_hash(label_key.as_bytes(), context.unwrap_or(&[]));
+ let context_key = hemera::keyed_hash(label_key.as_bytes(), context.unwrap_or(&[]));
let mut hasher = hemera::Hasher::new_keyed(context_key.as_bytes());
hasher.update(&self.shared_secret?.to_le_bytes());
hasher.finalize_xof().fill(output.as_mut());
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/particle/src/main.rs:1:
-use std::fs;
-use std::io::{self, Read};
-use std::process;
+use std::{
+ fs,
+ io::{self, Read},
+ process,
+};
-use cyber_bao::hash::Poseidon2Backend;
-use cyber_bao::io::{decode, encode, outboard};
-use cyber_bao::tree::BlockSize;
+use cyber_bao::{
+ hash::Poseidon2Backend,
+ io::{decode, encode, outboard},
+ tree::BlockSize,
+};
fn main() {
let args: Vec<String> = std::env::args().collect();
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/particle/src/main.rs:51:
println!("{h}");
} else {
for path in args {
- let data =
- fs::read(path).unwrap_or_else(|e| fatal(&format!("reading {path}: {e}")));
+ let data = fs::read(path).unwrap_or_else(|e| fatal(&format!("reading {path}: {e}")));
let h = hemera::hash(&data);
if args.len() > 1 {
println!("{h} {path}");
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/particle/src/main.rs:90:
let path = &args[0];
let hash_hex = &args[1];
- let encoded =
- fs::read(path).unwrap_or_else(|e| fatal(&format!("reading {path}: {e}")));
+ let encoded = fs::read(path).unwrap_or_else(|e| fatal(&format!("reading {path}: {e}")));
let root = parse_hash(hash_hex);
let backend = Poseidon2Backend;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/docs/book/src/bin/set-up-connection.rs:1:
+use std::{
+ error::Error,
+ net::{IpAddr, Ipv4Addr, SocketAddr},
+};
+
use quinn::{Endpoint, ServerConfig};
-use std::error::Error;
-use std::net::{IpAddr, Ipv4Addr, SocketAddr};
fn main() {}
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/benches/bench.rs:5:
};
use criterion::{Criterion, criterion_group, criterion_main};
+use iroh_quinn::{self as quinn, Endpoint, TokioRuntime};
use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};
use tokio::runtime::{Builder, Runtime};
use tracing::error_span;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/benches/bench.rs:11:
use tracing_futures::Instrument as _;
-
-use iroh_quinn::{self as quinn, Endpoint, TokioRuntime};
criterion_group!(
benches,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/examples/common/mod.rs:1:
#![cfg(any(feature = "rustls-aws-lc-rs", feature = "rustls-ring"))]
//! Commonly used code in most examples.
+use std::{error::Error, net::SocketAddr, sync::Arc};
+
use iroh_quinn::{ClientConfig, Endpoint, ServerConfig};
use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};
-
-use std::{error::Error, net::SocketAddr, sync::Arc};
/// Constructs a QUIC endpoint configured for use a client only.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/examples/common/mod.rs:1:
#![cfg(any(feature = "rustls-aws-lc-rs", feature = "rustls-ring"))]
//! Commonly used code in most examples.
+use std::{error::Error, net::SocketAddr, sync::Arc};
+
use iroh_quinn::{ClientConfig, Endpoint, ServerConfig};
use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};
-
-use std::{error::Error, net::SocketAddr, sync::Arc};
/// Constructs a QUIC endpoint configured for use a client only.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/examples/common/mod.rs:1:
#![cfg(any(feature = "rustls-aws-lc-rs", feature = "rustls-ring"))]
//! Commonly used code in most examples.
+use std::{error::Error, net::SocketAddr, sync::Arc};
+
use iroh_quinn::{ClientConfig, Endpoint, ServerConfig};
use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};
-
-use std::{error::Error, net::SocketAddr, sync::Arc};
/// Constructs a QUIC endpoint configured for use a client only.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/examples/common/mod.rs:1:
#![cfg(any(feature = "rustls-aws-lc-rs", feature = "rustls-ring"))]
//! Commonly used code in most examples.
+use std::{error::Error, net::SocketAddr, sync::Arc};
+
use iroh_quinn::{ClientConfig, Endpoint, ServerConfig};
use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};
-
-use std::{error::Error, net::SocketAddr, sync::Arc};
/// Constructs a QUIC endpoint configured for use a client only.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/examples/common/mod.rs:1:
#![cfg(any(feature = "rustls-aws-lc-rs", feature = "rustls-ring"))]
//! Commonly used code in most examples.
+use std::{error::Error, net::SocketAddr, sync::Arc};
+
use iroh_quinn::{ClientConfig, Endpoint, ServerConfig};
use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};
-
-use std::{error::Error, net::SocketAddr, sync::Arc};
/// Constructs a QUIC endpoint configured for use a client only.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/connection.rs:12:
use bytes::Bytes;
use pin_project_lite::pin_project;
+use proto::{
+ ConnectionError, ConnectionHandle, ConnectionStats, Dir, EndpointEvent, FourTuple, PathError,
+ PathEvent, PathId, PathStats, PathStatus, Side, StreamEvent, StreamId, TransportError,
+ TransportErrorCode, congestion::Controller, iroh_hp,
+};
use rustc_hash::FxHashMap;
use thiserror::Error;
use tokio::sync::{Notify, futures::Notified, mpsc, oneshot, watch};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/connection.rs:26:
runtime::{AsyncTimer, Runtime, UdpSender},
send_stream::SendStream,
udp_transmit,
-};
-use proto::{
- ConnectionError, ConnectionHandle, ConnectionStats, Dir, EndpointEvent, FourTuple, PathError,
- PathEvent, PathId, PathStats, PathStatus, Side, StreamEvent, StreamId, TransportError,
- TransportErrorCode, congestion::Controller, iroh_hp,
};
/// In-progress connection attempt future
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/endpoint.rs:12:
task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
};
-#[cfg(all(
- not(wasm_browser),
- any(feature = "runtime-tokio", feature = "runtime-smol"),
- any(feature = "aws-lc-rs", feature = "ring"),
-))]
-use crate::runtime::default_runtime;
-use crate::{
- Instant,
- runtime::{AsyncUdpSocket, Runtime, UdpSender},
- udp_transmit,
-};
use bytes::{Bytes, BytesMut};
use pin_project_lite::pin_project;
use proto::{
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/endpoint.rs:40:
use tracing::{Instrument, Span, trace};
use udp::{BATCH_SIZE, RecvMeta};
+#[cfg(all(
+ not(wasm_browser),
+ any(feature = "runtime-tokio", feature = "runtime-smol"),
+ any(feature = "aws-lc-rs", feature = "ring"),
+))]
+use crate::runtime::default_runtime;
use crate::{
- ConnectionEvent, EndpointConfig, IO_LOOP_BOUND, RECV_TIME_BOUND, VarInt,
- connection::Connecting, incoming::Incoming, work_limiter::WorkLimiter,
+ ConnectionEvent, EndpointConfig, IO_LOOP_BOUND, Instant, RECV_TIME_BOUND, VarInt,
+ connection::Connecting,
+ incoming::Incoming,
+ runtime::{AsyncUdpSocket, Runtime, UdpSender},
+ udp_transmit,
+ work_limiter::WorkLimiter,
};
/// A QUIC endpoint.
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/lib.rs:39:
//! encryption alone.
#![warn(missing_docs)]
-use std::pin::Pin;
-use std::sync::Arc;
+use std::{pin::Pin, sync::Arc};
mod connection;
mod endpoint;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/lib.rs:54:
#[cfg(not(wasm_browser))]
pub(crate) use std::time::{Duration, Instant};
-#[cfg(wasm_browser)]
-pub(crate) use web_time::{Duration, Instant};
#[cfg(feature = "bloom")]
pub use proto::BloomTokenLog;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/lib.rs:73:
#[cfg(any(feature = "rustls-aws-lc-rs", feature = "rustls-ring"))]
pub use rustls;
pub use udp;
+#[cfg(wasm_browser)]
+pub(crate) use web_time::{Duration, Instant};
-pub use crate::connection::{
- AcceptBi, AcceptUni, Connecting, Connection, OnClosed, OpenBi, OpenUni, ReadDatagram,
- SendDatagram, SendDatagramError, WeakConnectionHandle, ZeroRttAccepted,
-};
-pub use crate::endpoint::{Accept, Endpoint, EndpointStats};
-pub use crate::incoming::{Incoming, IncomingFuture, RetryError};
-pub use crate::path::{AddressDiscovery, OpenPath, Path, WeakPathHandle};
-pub use crate::recv_stream::{
- ReadError, ReadExactError, ReadToEndError, RecvStream, ResetError, UnorderedRecvStream,
-};
#[cfg(feature = "runtime-smol")]
pub use crate::runtime::SmolRuntime;
#[cfg(feature = "runtime-tokio")]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/lib.rs:90:
pub use crate::runtime::TokioRuntime;
#[cfg(any(feature = "runtime-tokio", feature = "runtime-smol"))]
pub use crate::runtime::default_runtime;
-pub use crate::runtime::{AsyncTimer, AsyncUdpSocket, Runtime, UdpSender};
-pub use crate::send_stream::{SendStream, Stopped, StoppedError, WriteError};
+pub use crate::{
+ connection::{
+ AcceptBi, AcceptUni, Connecting, Connection, OnClosed, OpenBi, OpenUni, ReadDatagram,
+ SendDatagram, SendDatagramError, WeakConnectionHandle, ZeroRttAccepted,
+ },
+ endpoint::{Accept, Endpoint, EndpointStats},
+ incoming::{Incoming, IncomingFuture, RetryError},
+ path::{AddressDiscovery, OpenPath, Path, WeakPathHandle},
+ recv_stream::{
+ ReadError, ReadExactError, ReadToEndError, RecvStream, ResetError, UnorderedRecvStream,
+ },
+ runtime::{AsyncTimer, AsyncUdpSocket, Runtime, UdpSender},
+ send_stream::{SendStream, Stopped, StoppedError, WriteError},
+};
#[cfg(test)]
mod tests;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/mutex.rs:5:
#[cfg(feature = "lock_tracking")]
mod tracking {
- use super::*;
- use crate::{Duration, Instant};
use std::collections::VecDeque;
+
use tracing::warn;
+
+ use super::*;
+ use crate::{Duration, Instant};
#[derive(Debug)]
struct Inner<T> {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/path.rs:1:
-use std::future::Future;
-use std::net::SocketAddr;
-use std::pin::Pin;
-use std::sync::Arc;
-use std::task::{Context, Poll, ready};
-use std::time::Duration;
+use std::{
+ future::Future,
+ net::SocketAddr,
+ pin::Pin,
+ sync::Arc,
+ task::{Context, Poll, ready},
+ time::Duration,
+};
use proto::{
ClosePathError, ClosedPath, PathError, PathEvent, PathId, PathStats, PathStatus,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/path.rs:12:
use tokio::sync::watch;
use tokio_stream::{Stream, wrappers::WatchStream};
-use crate::connection::ConnectionRef;
-use crate::{Runtime, WeakConnectionHandle};
+use crate::{Runtime, WeakConnectionHandle, connection::ConnectionRef};
/// Future produced by [`crate::Connection::open_path`]
pub struct OpenPath(OpenPathInner);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/runtime/smol.rs:1:
use std::{
future::Future,
+ io,
num::NonZeroUsize,
pin::Pin,
- task::{Context, Poll},
+ sync::Arc,
+ task::{Context, Poll, ready},
time::Instant,
};
-use std::{io, sync::Arc, task::ready};
-use async_io::Async;
-use async_io::Timer;
+use async_io::{Async, Timer};
-use super::AsyncTimer;
-use super::{AsyncUdpSocket, Runtime, UdpSender, UdpSenderHelper, UdpSenderHelperSocket};
+use super::{
+ AsyncTimer, AsyncUdpSocket, Runtime, UdpSender, UdpSenderHelper, UdpSenderHelperSocket,
+};
/// A Quinn runtime for smol
#[derive(Debug)]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/tests.rs:1:
#![cfg(any(feature = "rustls-aws-lc-rs", feature = "rustls-ring"))]
-#[cfg(all(feature = "rustls-aws-lc-rs", not(feature = "rustls-ring")))]
-use rustls::crypto::aws_lc_rs::default_provider;
-#[cfg(feature = "rustls-ring")]
-use rustls::crypto::ring::default_provider;
-use testresult::TestResult;
-use tokio_stream::StreamExt;
-
use std::{
convert::TryInto,
io,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/tests.rs:15:
sync::Arc,
};
-use crate::runtime::TokioRuntime;
-use crate::{Duration, Instant};
use bytes::Bytes;
use proto::{ConnectionError, RandomConnectionIdGenerator, crypto::rustls::QuicClientConfig};
use rand::{RngCore, SeedableRng, rngs::StdRng};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/tests.rs:23:
+#[cfg(all(feature = "rustls-aws-lc-rs", not(feature = "rustls-ring")))]
+use rustls::crypto::aws_lc_rs::default_provider;
+#[cfg(feature = "rustls-ring")]
+use rustls::crypto::ring::default_provider;
use rustls::{
RootCertStore,
pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/tests.rs:26:
};
+use testresult::TestResult;
use tokio::runtime::{Builder, Runtime};
+use tokio_stream::StreamExt;
use tracing::{error_span, info, info_span};
use tracing_futures::Instrument as _;
use tracing_subscriber::EnvFilter;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/tests.rs:31:
use super::{ClientConfig, Endpoint, EndpointConfig, RecvStream, SendStream, TransportConfig};
+use crate::{Duration, Instant, runtime::TokioRuntime};
/// Detect if running under Wine (test helper).
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/src/work_limiter.rs:126:
#[cfg(test)]
mod tests {
- use super::*;
use std::cell::RefCell;
+
+ use super::*;
#[test]
fn limit_work() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/tests/many_connections.rs:7:
};
use crc::Crc;
-use iroh_quinn::{self as quinn, ConnectionError, ReadError, StoppedError, TransportConfig, WriteError};
+use iroh_quinn::{
+ self as quinn, ConnectionError, ReadError, StoppedError, TransportConfig, WriteError,
+};
use rand::{self, RngCore};
use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};
use tokio::runtime::Builder;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/tests/post_quantum.rs:6:
sync::Arc,
};
+use iroh_quinn::{
+ Endpoint,
+ crypto::rustls::{HandshakeData, QuicClientConfig, QuicServerConfig},
+};
use rustls::{
NamedGroup,
pki_types::{CertificateDer, PrivatePkcs8KeyDer},
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn/tests/post_quantum.rs:12:
};
use tracing::info;
-
-use iroh_quinn::{
- Endpoint,
- crypto::rustls::{HandshakeData, QuicClientConfig, QuicServerConfig},
-};
#[tokio::test]
async fn post_quantum_key_worst_case_header() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/bloom_token_log.rs:254:
#[cfg(test)]
mod test {
- use super::*;
use rand::prelude::*;
use rand_pcg::Pcg32;
+
+ use super::*;
fn new_rng() -> impl Rng {
Pcg32::from_seed(0xdeadbeefdeadbeefdeadbeefdeadbeef_u128.to_le_bytes())
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/cid_generator.rs:2:
use rand::{Rng, RngCore};
-use crate::Duration;
-use crate::MAX_CID_SIZE;
-use crate::shared::ConnectionId;
+use crate::{Duration, MAX_CID_SIZE, shared::ConnectionId};
/// Generates connection IDs for incoming connections
pub trait ConnectionIdGenerator: Send + Sync {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/config/mod.rs:31:
#[cfg(feature = "qlog")]
pub use qlog::{QlogConfig, QlogFactory, QlogFileFactory};
-pub use transport::{AckFrequencyConfig, IdleTimeout, MtuDiscoveryConfig, TransportConfig};
-
#[cfg(doc)]
pub use transport::DEFAULT_CONCURRENT_MULTIPATH_PATHS_WHEN_ENABLED;
+pub use transport::{AckFrequencyConfig, IdleTimeout, MtuDiscoveryConfig, TransportConfig};
/// Global configuration for the endpoint, affecting all connections
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/congestion/bbr/mod.rs:1:
-use std::any::Any;
-use std::fmt::Debug;
-use std::sync::Arc;
+use std::{any::Any, fmt::Debug, sync::Arc};
use rand::{Rng, SeedableRng};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/congestion/bbr/mod.rs:7:
-use crate::congestion::ControllerMetrics;
-use crate::congestion::bbr::bw_estimation::BandwidthEstimation;
-use crate::congestion::bbr::min_max::MinMax;
-use crate::connection::RttEstimator;
-use crate::{Duration, Instant};
-
use super::{BASE_DATAGRAM_SIZE, Controller, ControllerFactory};
+use crate::{
+ Duration, Instant,
+ congestion::{
+ ControllerMetrics,
+ bbr::{bw_estimation::BandwidthEstimation, min_max::MinMax},
+ },
+ connection::RttEstimator,
+};
mod bw_estimation;
mod min_max;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/congestion/cubic.rs:1:
-use std::any::Any;
-use std::cmp;
-use std::sync::Arc;
+use std::{any::Any, cmp, sync::Arc};
use super::{BASE_DATAGRAM_SIZE, Controller, ControllerFactory};
-use crate::connection::RttEstimator;
-use crate::{Duration, Instant};
+use crate::{Duration, Instant, connection::RttEstimator};
/// CUBIC Constants.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/congestion/new_reno.rs:1:
-use std::any::Any;
-use std::sync::Arc;
+use std::{any::Any, sync::Arc};
use super::{BASE_DATAGRAM_SIZE, Controller, ControllerFactory};
-use crate::Instant;
-use crate::connection::RttEstimator;
+use crate::{Instant, connection::RttEstimator};
/// A simple, standard congestion controller
#[derive(Debug, Clone)]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/congestion.rs:1:
//! Logic for controlling the rate at which data is sent
-use crate::Instant;
-use crate::connection::RttEstimator;
-use std::any::Any;
-use std::sync::Arc;
+use std::{any::Any, sync::Arc};
+
+use crate::{Instant, connection::RttEstimator};
mod bbr;
mod cubic;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/ack_frequency.rs:1:
-use crate::Duration;
-use crate::frame::AckFrequency;
-use crate::transport_parameters::TransportParameters;
-use crate::{AckFrequencyConfig, TIMER_GRANULARITY, TransportError, VarInt};
-
use super::PathId;
+use crate::{
+ AckFrequencyConfig, Duration, TIMER_GRANULARITY, TransportError, VarInt, frame::AckFrequency,
+ transport_parameters::TransportParameters,
+};
/// State associated to ACK frequency
pub(super) struct AckFrequencyState {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/assembler.rs:339:
#[cfg(test)]
mod test {
- use super::*;
use assert_matches::assert_matches;
+
+ use super::*;
#[test]
fn assemble_ordered() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/mod.rs:10:
use bytes::{Bytes, BytesMut};
use frame::StreamMetaVec;
-
use rand::{Rng, SeedableRng, rngs::StdRng};
use rustc_hash::{FxHashMap, FxHashSet};
use thiserror::Error;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/mtud.rs:1:
-use crate::{Instant, MAX_UDP_PAYLOAD, MtuDiscoveryConfig, packet::SpaceId};
use std::cmp;
+
use tracing::trace;
+use crate::{Instant, MAX_UDP_PAYLOAD, MtuDiscoveryConfig, packet::SpaceId};
+
/// Implements Datagram Packetization Layer Path Maximum Transmission Unit Discovery
///
/// See [`MtuDiscoveryConfig`] for details
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/mtud.rs:523:
#[cfg(test)]
mod tests {
- use super::*;
- use crate::Duration;
- use crate::MAX_UDP_PAYLOAD;
- use crate::packet::SpaceId;
use assert_matches::assert_matches;
+
+ use super::*;
+ use crate::{Duration, MAX_UDP_PAYLOAD, packet::SpaceId};
fn default_mtud() -> MtuDiscovery {
let config = MtuDiscoveryConfig::default();
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/pacing.rs:1:
//! Pacing of packet transmissions.
-use crate::{Duration, Instant};
-
use tracing::warn;
+
+use crate::{Duration, Instant};
/// A simple token-bucket pacer
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/packet_crypto.rs:1:
-use std::mem;
-use std::ops::{Index, IndexMut};
+use std::{
+ mem,
+ ops::{Index, IndexMut},
+};
+use rand::Rng;
use tracing::{debug, trace};
-use crate::connection::assembler::Assembler;
-use crate::crypto::{self, HeaderKey, KeyPair, Keys, PacketKey};
-use crate::packet::{Packet, PartialDecode, SpaceId};
-use crate::token::ResetToken;
-use rand::Rng;
-
-use crate::{ConnectionId, Instant, Side};
-use crate::{RESET_TOKEN_SIZE, TransportError};
-
-use super::PathId;
-use super::spaces::PacketSpace;
+use super::{PathId, spaces::PacketSpace};
+use crate::{
+ ConnectionId, Instant, RESET_TOKEN_SIZE, Side, TransportError,
+ connection::assembler::Assembler,
+ crypto::{self, HeaderKey, KeyPair, Keys, PacketKey},
+ packet::{Packet, PartialDecode, SpaceId},
+ token::ResetToken,
+};
/// Perform key updates this many packets before the AEAD confidentiality limit.
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/paths.rs:1:
use std::{cmp, net::SocketAddr};
use identity_hash::IntMap;
+#[cfg(feature = "qlog")]
+use qlog::events::quic::RecoveryMetricsUpdated;
use thiserror::Error;
use tracing::{debug, trace};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/paths.rs:17:
frame::ObservedAddr,
packet::SpaceId,
};
-
-#[cfg(feature = "qlog")]
-use qlog::events::quic::RecoveryMetricsUpdated;
/// Id representing different paths when using multipath extension
#[cfg_attr(test, derive(test_strategy::Arbitrary))]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/send_buffer.rs:583:
#[cfg(all(test, not(target_family = "wasm")))]
mod proptests {
- use super::*;
-
use proptest::prelude::*;
use test_strategy::{Arbitrary, proptest};
- use crate::tests::subscribe;
use tracing::trace;
+
+ use super::*;
+ use crate::tests::subscribe;
#[derive(Debug, Clone, Arbitrary)]
enum Op {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/state.rs:1:
use bytes::Bytes;
use tracing::trace;
-use crate::frame::Close;
-use crate::{ApplicationClose, ConnectionClose, ConnectionError, TransportError, TransportErrorCode};
+use crate::{
+ ApplicationClose, ConnectionClose, ConnectionError, TransportError, TransportErrorCode,
+ frame::Close,
+};
#[allow(unreachable_pub)] // fuzzing only
#[derive(Debug, Clone)]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/stats.rs:1:
//! Connection statistics
-use crate::Duration;
-use crate::FrameType;
+use crate::{Duration, FrameType};
/// Statistics about UDP datagrams transmitted or received on a connection
///
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/streams/recv.rs:1:
-use std::collections::hash_map::Entry;
-use std::mem;
+use std::{collections::hash_map::Entry, mem};
use thiserror::Error;
use tracing::debug;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/streams/recv.rs:6:
-use super::state::get_or_insert_recv;
-use super::{ClosedStream, Retransmits, ShouldTransmit, StreamId, StreamsState};
-use crate::connection::assembler::{Assembler, Chunk, IllegalOrderedRead};
-use crate::connection::streams::state::StreamRecv;
-use crate::{TransportError, VarInt, frame};
+use super::{
+ ClosedStream, Retransmits, ShouldTransmit, StreamId, StreamsState, state::get_or_insert_recv,
+};
+use crate::{
+ TransportError, VarInt,
+ connection::{
+ assembler::{Assembler, Chunk, IllegalOrderedRead},
+ streams::state::StreamRecv,
+ },
+ frame,
+};
#[derive(Debug, Default)]
pub(super) struct Recv {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/streams/recv.rs:445:
mod tests {
use bytes::Bytes;
- use crate::{Dir, Side};
-
use super::*;
+ use crate::{Dir, Side};
#[test]
fn reordered_frames_while_stopped() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/streams/state.rs:940:
#[cfg(test)]
mod tests {
+ use bytes::Bytes;
+
use super::*;
use crate::{
ReadableError, RecvStream, SendStream, TransportErrorCode, WriteError,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/streams/state.rs:946:
- connection::State as ConnState, connection::Streams,
+ connection::{State as ConnState, Streams},
};
- use bytes::Bytes;
fn make(side: Side) -> StreamsState {
StreamsState::new(
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/timer.rs:1:
use identity_hash::{IdentityHashable, IntMap};
+use super::PathId;
use crate::{
Instant,
connection::qlog::{QlogSink, QlogSinkWithTime},
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/timer.rs:6:
};
-use super::PathId;
-
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub(crate) enum Timer {
/// Per connection timers.
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/connection/timer.rs:397:
mod tests {
use std::time::Duration;
- use crate::connection::qlog::QlogSink;
-
use super::*;
+ use crate::connection::qlog::QlogSink;
#[test]
fn timer_table() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/frame.rs:6:
};
use bytes::{Buf, BufMut, Bytes};
+#[cfg(test)]
+use proptest::{collection, prelude::any, strategy::Strategy};
+#[cfg(test)]
+use test_strategy::Arbitrary;
use tinyvec::TinyVec;
+#[cfg(feature = "qlog")]
+use super::connection::qlog::ToQlog;
+#[cfg(test)]
+use crate::varint::varint_u64;
use crate::{
Dir, MAX_CID_SIZE, RESET_TOKEN_SIZE, ResetToken, StreamId, TransportError, TransportErrorCode,
VarInt,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/frame.rs:17:
shared::{ConnectionId, EcnCodepoint},
};
-#[cfg(feature = "qlog")]
-use super::connection::qlog::ToQlog;
-
-#[cfg(test)]
-use crate::varint::varint_u64;
-#[cfg(test)]
-use proptest::{collection, prelude::any, strategy::Strategy};
-#[cfg(test)]
-use test_strategy::Arbitrary;
-
#[derive(
Copy, Clone, Eq, PartialEq, derive_more::Debug, derive_more::Display, enum_assoc::Assoc,
)]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/frame.rs:2488:
#[cfg(test)]
mod test {
+ use assert_matches::assert_matches;
+
use super::*;
use crate::coding::Encodable;
- use assert_matches::assert_matches;
#[test]
fn frame_type() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/lib.rs:42:
pub use bloom_token_log::BloomTokenLog;
pub(crate) mod connection;
+#[cfg(feature = "rustls")]
+pub use rustls;
+#[cfg(test)]
+use test_strategy::Arbitrary;
+
pub use crate::connection::{
Chunk, Chunks, ClosePathError, ClosedPath, ClosedStream, Connection, ConnectionError,
ConnectionStats, Datagrams, Event, FinishError, FrameStats, MultipathNotNegotiated,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/lib.rs:49:
ReadableError, RecvStream, RttEstimator, SendDatagramError, SendStream, SetPathStatusError,
ShouldTransmit, StreamEvent, Streams, UdpStats, WriteError, Written,
};
-#[cfg(test)]
-use test_strategy::Arbitrary;
-#[cfg(feature = "rustls")]
-pub use rustls;
-
mod config;
#[cfg(doc)]
pub use config::DEFAULT_CONCURRENT_MULTIPATH_PATHS_WHEN_ENABLED;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/lib.rs:115:
// Deal with time
#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
pub(crate) use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
pub(crate) use web_time::{Duration, Instant, SystemTime, UNIX_EPOCH};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/lib.rs:126:
#[cfg(fuzzing)]
pub mod fuzzing {
- pub use crate::connection::{Retransmits, State as ConnectionState, StreamsState};
- pub use crate::frame::ResetStream;
- pub use crate::packet::PartialDecode;
- pub use crate::transport_parameters::TransportParameters;
- pub use bytes::{BufMut, BytesMut};
-
#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Result, Unstructured};
+ pub use bytes::{BufMut, BytesMut};
+
+ pub use crate::{
+ connection::{Retransmits, State as ConnectionState, StreamsState},
+ frame::ResetStream,
+ packet::PartialDecode,
+ transport_parameters::TransportParameters,
+ };
#[cfg(feature = "arbitrary")]
impl<'arbitrary> Arbitrary<'arbitrary> for TransportParameters {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/packet.rs:867:
impl LongHeaderType {
fn from_byte(b: u8) -> Result<Self, PacketDecodeError> {
- use {LongHeaderType::*, LongType::*};
+ use LongHeaderType::*;
+ use LongType::*;
debug_assert!(b & LONG_HEADER_FORM != 0, "not a long packet");
Ok(match (b & 0x30) >> 4 {
0x0 => Initial,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/packet.rs:881:
impl From<LongHeaderType> for u8 {
fn from(ty: LongHeaderType) -> Self {
- use {LongHeaderType::*, LongType::*};
+ use LongHeaderType::*;
+ use LongType::*;
match ty {
Initial => LONG_HEADER_FORM | FIXED_BIT,
Standard(ZeroRtt) => LONG_HEADER_FORM | FIXED_BIT | (0x1 << 4),
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/packet.rs:978:
#[cfg(test)]
mod tests {
- use super::*;
- use hex_literal::hex;
use std::io;
+ use hex_literal::hex;
+
+ use super::*;
+
fn check_pn(typed: PacketNumber, encoded: &[u8]) {
let mut buf = Vec::new();
typed.encode(&mut buf);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/packet.rs:1018:
#[cfg(any(feature = "rustls-aws-lc-rs", feature = "rustls-ring"))]
#[test]
fn header_encoding() {
- use crate::Side;
- use crate::crypto::rustls::{initial_keys, initial_suite_from_provider};
#[cfg(all(feature = "rustls-aws-lc-rs", not(feature = "rustls-ring")))]
use rustls::crypto::aws_lc_rs::default_provider;
#[cfg(feature = "rustls-ring")]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/packet.rs:1026:
use rustls::crypto::ring::default_provider;
use rustls::quic::Version;
+
+ use crate::{
+ Side,
+ crypto::rustls::{initial_keys, initial_suite_from_provider},
+ };
let dcid = ConnectionId::new(&hex!("06b858ec6f80452b"));
let provider = default_provider();
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/range_set/array_range_set.rs:1:
-use std::fmt::{self, Write};
-use std::ops::Range;
+use std::{
+ fmt::{self, Write},
+ ops::Range,
+};
use tinyvec::TinyVec;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/shared.rs:2:
use bytes::{Buf, BufMut, BytesMut};
-use crate::FourTuple;
-use crate::PathId;
-use crate::{Duration, Instant, MAX_CID_SIZE, ResetToken, coding::BufExt, packet::PartialDecode};
+use crate::{
+ Duration, FourTuple, Instant, MAX_CID_SIZE, PathId, ResetToken, coding::BufExt,
+ packet::PartialDecode,
+};
/// Events sent from an Endpoint to a Connection
#[derive(Debug)]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/tests/encode_decode.rs:1:
use bytes::{BufMut, BytesMut};
+use proptest::{prelude::*, prop_assert_ne};
use test_strategy::proptest;
-use proptest::{prop_assert_ne, prelude::*};
use crate::{
FrameType,
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/tests/multipath.rs:1:
//! Tests for multipath
-use std::net::SocketAddr;
-use std::num::NonZeroU32;
-use std::sync::Arc;
-use std::time::Duration;
+use std::{net::SocketAddr, num::NonZeroU32, sync::Arc, time::Duration};
use assert_matches::assert_matches;
use testresult::TestResult;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/tests/multipath.rs:10:
use tracing::info;
-use crate::tests::RoutingTable;
-use crate::tests::util::{CLIENT_PORTS, ConnPair, SERVER_PORTS};
+use super::{
+ Pair, client_config, server_config,
+ util::{min_opt, subscribe},
+};
use crate::{
- ClientConfig, ClosePathError, ConnectionId, ConnectionIdGenerator, Endpoint, EndpointConfig,
- FourTuple, LOCAL_CID_COUNT, NetworkChangeHint, PathId, PathStatus, RandomConnectionIdGenerator,
- ServerConfig, Side::*, TransportConfig, cid_queue::CidQueue,
+ ClientConfig, ClosePathError, ConnectionId, ConnectionIdGenerator, Dir, Endpoint,
+ EndpointConfig, Event, FourTuple, LOCAL_CID_COUNT, NetworkChangeHint, PathError, PathEvent,
+ PathId, PathStatus, RandomConnectionIdGenerator, ServerConfig,
+ Side::*,
+ StreamEvent, TransportConfig,
+ cid_queue::CidQueue,
+ tests::{
+ RoutingTable,
+ util::{CLIENT_PORTS, ConnPair, SERVER_PORTS},
+ },
};
-use crate::{Dir, Event, PathError, PathEvent, StreamEvent};
-
-use super::util::{min_opt, subscribe};
-use super::{Pair, client_config, server_config};
const MAX_PATHS: u32 = 3;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/tests/token.rs:1:
//! Tests specifically for tokens
-use super::*;
-
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
use wasm_bindgen_test::wasm_bindgen_test as test;
+
+use super::*;
#[test]
fn stateless_retry() {
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/tests/util.rs:21:
};
use tracing::{debug, info_span, trace};
-use super::crypto::rustls::{QuicClientConfig, QuicServerConfig, configured_provider};
-use super::*;
+use super::{
+ crypto::rustls::{QuicClientConfig, QuicServerConfig, configured_provider},
+ *,
+};
use crate::{Duration, Instant, congestion::Controller};
pub(super) const DEFAULT_MTU: usize = 1452;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/token.rs:408:
#[cfg(all(test, any(feature = "aws-lc-rs", feature = "ring")))]
mod test {
- use super::*;
#[cfg(all(feature = "aws-lc-rs", not(feature = "ring")))]
use aws_lc_rs::hkdf;
use rand::prelude::*;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/token.rs:415:
#[cfg(feature = "ring")]
use ring::hkdf;
+ use super::*;
+
fn token_round_trip(payload: TokenPayload) -> TokenPayload {
let rng = &mut rand::rng();
let token = Token::new(payload, rng);
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/token.rs:429:
#[test]
fn retry_token_sanity() {
- use crate::MAX_CID_SIZE;
- use crate::cid_generator::{ConnectionIdGenerator, RandomConnectionIdGenerator};
- use crate::{Duration, UNIX_EPOCH};
-
use std::net::Ipv6Addr;
+ use crate::{
+ Duration, MAX_CID_SIZE, UNIX_EPOCH,
+ cid_generator::{ConnectionIdGenerator, RandomConnectionIdGenerator},
+ };
+
let address_1 = SocketAddr::new(Ipv6Addr::LOCALHOST.into(), 4433);
let orig_dst_cid_1 = RandomConnectionIdGenerator::new(MAX_CID_SIZE).generate_cid();
let issued_1 = UNIX_EPOCH + Duration::from_secs(42); // Fractional seconds would be lost
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/token.rs:459:
#[test]
fn validation_token_sanity() {
- use crate::{Duration, UNIX_EPOCH};
-
use std::net::Ipv6Addr;
+ use crate::{Duration, UNIX_EPOCH};
+
let ip_1 = Ipv6Addr::LOCALHOST.into();
let issued_1 = UNIX_EPOCH + Duration::from_secs(42); // Fractional seconds would be lost
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/token.rs:484:
#[test]
fn invalid_token_returns_err() {
- use super::*;
use rand::RngCore;
+
+ use super::*;
let rng = &mut rand::rng();
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/token_memory_cache.rs:154:
mod tests {
use std::collections::VecDeque;
- use super::*;
use rand::prelude::*;
use rand_pcg::Pcg32;
use tracing::info;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-proto/src/token_memory_cache.rs:161:
+
+ use super::*;
fn new_rng() -> impl Rng {
Pcg32::from_seed(0xdeadbeefdeadbeefdeadbeefdeadbeefu128.to_le_bytes())
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-udp/benches/throughput.rs:6:
};
use criterion::{Criterion, criterion_group, criterion_main};
-use tokio::{io::Interest, runtime::Runtime};
-
use iroh_quinn_udp::{BATCH_SIZE, RecvMeta, Transmit, UdpSocketState};
+use tokio::{io::Interest, runtime::Runtime};
pub fn criterion_benchmark(c: &mut Criterion) {
const TOTAL_BYTES: usize = 10 * 1024 * 1024;
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-udp/src/lib.rs:58:
mod log {
#[cfg(all(feature = "log", not(feature = "tracing-log")))]
pub(crate) use log::{debug, error, info, trace, warn};
-
#[cfg(feature = "tracing-log")]
pub(crate) use tracing::{debug, error, info, trace, warn};
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-udp/src/lib.rs:70:
macro_rules! log_warn ( ($($tt:tt)*) => {{}} );
macro_rules! error ( ($($tt:tt)*) => {{}} );
- pub(crate) use {debug, error, info, log_warn as warn, trace};
+ pub(crate) use debug;
+ pub(crate) use error;
+ pub(crate) use info;
+ pub(crate) use log_warn as warn;
+ pub(crate) use trace;
}
#[cfg(not(any(feature = "log", feature = "tracing-log")))]
Diff in /private/tmp/radio-export-pairs.FbuGlp/candidate/radio/quinn/quinn-udp/src/unix.rs:817:
#[cfg(any(target_os = "linux", target_os = "android"))]
mod gso {
- use super::*;
use std::{ffi::CStr, mem, str::FromStr, sync::OnceLock};
+
+ use super::*;
// Support for UDP GSO has been added to linux kernel in version 4.18
// https://github.com/torvalds/linux/commit/cb586c63e3fc5b227c51fd8c4cb40b34d3750645