Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 14 additions & 11 deletions crates/origin-shared/benches/object.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Encoding, hashing and signing throughput of the object model.
//! Benchmarks encoding, hashing and signing objects.

use divan::counter::BytesCount;
use divan::{Bencher, black_box};
Expand All @@ -12,7 +12,8 @@ fn main() {
divan::main();
}

/// Hashing a blob: the cost of snapshotting a changed file.
/// Benchmarks hashing a blob of `len` bytes, as snapshotting a changed
/// file does.
#[divan::bench(args = [4 * 1024, 1024 * 1024, 64 * 1024 * 1024])]
fn hash_blob(bencher: Bencher<'_, '_>, len: usize) {
let content = vec![0xa5_u8; len];
Expand All @@ -35,26 +36,26 @@ fn tree(len: usize) -> Tree {
.collect()
}

/// Encoding and hashing a directory listing.
/// Benchmarks encoding and hashing a tree of `len` entries.
#[divan::bench(args = [16, 1024])]
fn encode_tree(bencher: Bencher<'_, '_>, len: usize) {
let tree = Object::Tree(tree(len));
bencher.bench(|| black_box(&tree).encode());
}

/// Decoding a directory listing: the cost of every tree read.
/// Benchmarks decoding a tree of `len` entries, as every tree read does.
#[divan::bench(args = [16, 1024])]
fn decode_tree(bencher: Bencher<'_, '_>, len: usize) {
let encoded = Object::Tree(tree(len)).encode();
bencher.bench(|| black_box(&encoded).decode_as::<Tree>().unwrap());
}

/// An id of any type, from a seed.
/// Builds an id of any type by hashing `seed` as a blob.
fn id<T: From<ObjectId>>(seed: &str) -> T {
EncodedObject::blob(seed.as_bytes()).id().into()
}

/// A CI result with declared inputs: the most common record.
/// Builds a CI result with declared inputs, the most common statement.
fn statement() -> Statement {
Statement {
subject: RecordId::Revision(id("revision")),
Expand All @@ -75,21 +76,21 @@ fn statement() -> Statement {
}
}

/// Encoding and hashing a statement.
/// Benchmarks encoding and hashing a statement.
#[divan::bench]
fn encode_statement(bencher: Bencher<'_, '_>) {
let statement = statement();
bencher.bench(|| black_box(&statement).encode());
}

/// Decoding a statement: the cost of every statement read.
/// Benchmarks decoding a statement, as every statement read does.
#[divan::bench]
fn decode_statement(bencher: Bencher<'_, '_>) {
let encoded = statement().encode();
bencher.bench(|| black_box(&encoded).decode_as::<Statement>().unwrap());
}

/// Encoding and hashing a revision.
/// Benchmarks encoding and hashing a revision.
#[divan::bench]
fn encode_revision(bencher: Bencher<'_, '_>) {
let revision = Revision {
Expand All @@ -116,7 +117,8 @@ fn acceptance() -> AcceptanceBody {
}
}

/// Signing an acceptance: once per landing, by the target's authority.
/// Benchmarks signing an acceptance. A target's authority signs one per
/// landing.
#[divan::bench]
fn sign_acceptance(bencher: Bencher<'_, '_>) {
let key = NodeKey::from_bytes(&[42; 32]);
Expand All @@ -126,7 +128,8 @@ fn sign_acceptance(bencher: Bencher<'_, '_>) {
.bench_values(|body| body.sign(&key));
}

/// Verifying an acceptance: once per acceptance of every chain fetched.
/// Benchmarks verifying an acceptance. A fetch verifies each acceptance
/// of every chain it brings.
#[divan::bench]
fn verify_acceptance(bencher: Bencher<'_, '_>) {
let key = NodeKey::from_bytes(&[42; 32]);
Expand Down
43 changes: 23 additions & 20 deletions crates/origin-shared/src/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ macro_rules! ids {
hex::string(&self.0)
}

/// An abbreviated id for display to humans.
/// The first 12 hex digits of the id, for display to humans.
#[must_use]
pub fn short(&self) -> String {
let mut hex = self.to_hex();
Expand Down Expand Up @@ -76,9 +76,9 @@ macro_rules! ids {
)*};
}

/// Defines ids of objects of one kind. They convert to and from
/// [`ObjectId`]: converting from one vouches for the kind, which reading the
/// object checks.
/// Defines ids of objects of one kind, which convert to and from
/// [`ObjectId`]. Converting from an [`ObjectId`] doesn't check the kind;
/// reading the object does.
macro_rules! object_ids {
($($(#[$meta:meta])* $name:ident $(=> $record:ty)?;)*) => {
ids! { $($(#[$meta])* $name(32);)* }
Expand All @@ -105,16 +105,16 @@ macro_rules! object_ids {
ids! {
/// Identifies an object by the BLAKE3 hash of its encoding.
///
/// The typed ids ([`TreeId`], [`RevisionId`], ...) name objects of one
/// kind, and convert to and from this one.
/// The typed ids ([`TreeId`], [`RevisionId`], ...) identify objects of one
/// kind and convert to and from this one.
ObjectId(32);

/// Identifies a change across all its revisions: random, so two changes
/// never share one, whoever creates them and wherever.
/// Identifies a change across all its revisions. It is random, so two
/// changes never share one.
ChangeId(16);

/// Identifies a target: the hash of its name, so user-chosen names never
/// become file names.
/// Identifies a target by the hash of its name. Targets are stored under
/// their id, so user-chosen names never become file names.
TargetId(32);

/// A BLAKE3 hash of something that isn't an object, such as a check's
Expand All @@ -125,7 +125,8 @@ ids! {
object_ids! {
/// Identifies a blob: file contents, a description or a payload.
BlobId;
/// Identifies a tree, the root of which is a snapshot.
/// Identifies a tree. A snapshot is identified by the id of its root
/// tree.
TreeId => Tree;
/// Identifies a revision.
RevisionId => Revision;
Expand All @@ -135,14 +136,15 @@ object_ids! {
AcceptanceId => Acceptance;
}

/// The id of a record of one type, which reading the record returns.
/// An id of a record of one known type: reading it returns a
/// [`TypedId::Record`].
pub trait TypedId: Copy + Into<ObjectId> {
/// The record the id names.
type Record: Record;
}

impl ObjectId {
/// Hashes an object encoding.
/// Hashes an object's encoding into its id.
pub(crate) fn hash(encoded: &[u8]) -> Self {
Self(*blake3::hash(encoded).as_bytes())
}
Expand Down Expand Up @@ -170,8 +172,8 @@ impl Digest {
}

impl TargetId {
/// The BLAKE3 key derivation context, which keeps target ids apart from
/// every other hash.
/// The BLAKE3 key derivation context for target ids, which keeps them
/// apart from every other hash.
const CONTEXT: &str = "origin 2026-10 target name";

/// The id of the target named `name`.
Expand All @@ -190,22 +192,22 @@ pub struct ParseIdError {
pub input: String,
}

/// Lowercase hex.
/// Lowercase hex encoding and decoding.
pub(crate) mod hex {
const DIGITS: &[u8; 16] = b"0123456789abcdef";

/// Number of hex digits a short id has.
pub const SHORT_LEN: usize = 12;

/// `bytes` as a string of lowercase hex.
/// Encodes `bytes` as a string of lowercase hex.
pub fn string(bytes: &[u8]) -> String {
let mut hex = vec![0; 2 * bytes.len()];
encode(bytes, &mut hex);
String::from_utf8(hex).expect("hex digits are ASCII")
}

/// Writes the two digits of each byte of `bytes` to `out`, which is
/// twice as long.
/// Writes each byte of `bytes` to `out` as two lowercase hex digits.
/// `out` must be twice as long as `bytes`.
pub fn encode(bytes: &[u8], out: &mut [u8]) {
for (byte, pair) in bytes.iter().zip(out.as_chunks_mut::<2>().0) {
*pair = [
Expand All @@ -215,7 +217,8 @@ pub(crate) mod hex {
}
}

/// Parses exactly `2 * N` hex digits, in either case.
/// Parses exactly `2 * N` hex digits, in either case. Returns `None` for
/// anything else.
pub fn decode<const N: usize>(input: &str) -> Option<[u8; N]> {
let input = input.as_bytes();
if input.len() != 2 * N {
Expand Down
12 changes: 6 additions & 6 deletions crates/origin-shared/src/name.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
//! Strings restricted to valid names: file names, target names, statement
//! kinds and principals.

/// Defines string types holding only valid names. Each type defines
/// `fn is_valid(name: &str) -> bool` in its own `impl` block, where
/// constants can also borrow a static name: `Self(Cow::Borrowed("main"))`.
/// Defines string types that hold only valid names. Each type defines
/// `fn is_valid(name: &str) -> bool` in its own `impl` block. Its constants
/// can borrow a static name: `Self(Cow::Borrowed("main"))`.
///
/// Names are encoded as a `u32` length and their UTF-8 bytes.
/// A name is encoded as a `u32` length and its UTF-8 bytes.
macro_rules! names {
($($(#[$meta:meta])* $name:ident($what:literal);)*) => {$(
$(#[$meta])*
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct $name(std::borrow::Cow<'static, str>);

impl $name {
/// Validates a name.
/// Creates a name, checking that it is valid.
///
/// # Errors
///
/// Fails if the name breaks the rules above.
/// Fails if the name breaks the type's rules.
pub fn new(name: impl Into<String>) -> Result<Self, $crate::InvalidName> {
let name = name.into();
if Self::is_valid(&name) {
Expand Down
29 changes: 14 additions & 15 deletions crates/origin-shared/src/object/acceptance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub use ed25519_dalek::Signature;

/// One landing on a target, signed by the target's authority.
///
/// Acceptances form a hash chain per target: each names the one before it,
/// A target's acceptances form a hash chain: each names the one before it,
/// and its sequence number is its position in the target's log.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Acceptance {
Expand All @@ -26,7 +26,7 @@ impl Record for Acceptance {
}

impl Acceptance {
/// What landed, and where.
/// The body: what landed, and where.
#[must_use]
pub fn body(&self) -> &AcceptanceBody {
&self.body
Expand Down Expand Up @@ -64,11 +64,10 @@ pub struct AcceptanceBody {
pub state: TreeId,
/// What landed.
pub landed: Vec<Source>,
/// The statements the policy relied on.
/// The statements the policy relied on to accept the landing.
pub evidence: Vec<StatementId>,
/// The acceptance of the `policy` target in force when this one landed.
/// Absent only for the first acceptance of `policy`, which nothing
/// precedes.
/// Absent only for the first acceptance of `policy` itself.
pub policy: Option<AcceptanceId>,
}

Expand All @@ -83,7 +82,7 @@ fields!(AcceptanceBody {
});

impl AcceptanceBody {
/// Signs the body as `authority`.
/// Signs the body as `authority`, returning the acceptance.
#[must_use]
pub fn sign(self, authority: &NodeKey) -> Acceptance {
let signature = authority.0.sign(&self.signed_bytes());
Expand All @@ -93,9 +92,9 @@ impl AcceptanceBody {
}
}

/// The bytes signed: the acceptance's encoding without its signature,
/// which starts with the object kind, so the signature can't be passed
/// off as one of anything else.
/// The bytes the authority signs: the acceptance's encoding without the
/// signature. They start with the object kind, so the signature can't be
/// reused for an object of another kind.
fn signed_bytes(&self) -> Vec<u8> {
let mut bytes = vec![ObjectKind::Acceptance as u8];
self.write(&mut bytes);
Expand Down Expand Up @@ -127,8 +126,8 @@ impl Field for Signature {
}
}

/// A node's ed25519 key pair. As a target's authority, the node signs the
/// acceptances it writes.
/// A node's ed25519 key pair. A node signs the acceptances of the targets
/// it is the authority of.
pub struct NodeKey(SigningKey);

impl NodeKey {
Expand All @@ -149,20 +148,20 @@ impl NodeKey {
Self(SigningKey::from_bytes(secret))
}

/// The secret key, to keep the key pair somewhere safe.
/// The secret key, for storing the key pair.
#[must_use]
pub fn to_bytes(&self) -> [u8; ed25519_dalek::SECRET_KEY_LENGTH] {
self.0.to_bytes()
}

/// The public half, which verifies the node's signatures.
/// The public key, which verifies the node's signatures.
#[must_use]
pub fn public(&self) -> NodePublicKey {
NodePublicKey(self.0.verifying_key())
}
}

/// Never prints the secret key.
/// Prints only the public key, never the secret key.
impl fmt::Debug for NodeKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("NodeKey").field(&self.public()).finish()
Expand Down Expand Up @@ -194,7 +193,7 @@ impl FromStr for NodePublicKey {
}
}

/// A signature that the claimed signer did not make.
/// A signature the claimed signer did not make.
#[derive(Debug, thiserror::Error)]
#[error("the signature does not match the signer's key")]
pub struct BadSignature(#[source] ed25519_dalek::SignatureError);
Loading
Loading