From 8e831839feee2b16a51575026179ef1a60f239ad Mon Sep 17 00:00:00 2001 From: Brooks Date: Fri, 11 Oct 2024 11:39:13 -0400 Subject: [PATCH] Displays LtHash's Checksum as base58 (#3142) --- Cargo.lock | 1 + lattice-hash/Cargo.toml | 1 + lattice-hash/src/lt_hash.rs | 20 +++++++++++++++++--- programs/sbf/Cargo.lock | 1 + 4 files changed, 20 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4b7d175c4e06ef..78438b2e9ea6a3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6874,6 +6874,7 @@ version = "2.1.0" dependencies = [ "base64 0.22.1", "blake3", + "bs58", "bytemuck", "criterion", "rand 0.8.5", diff --git a/lattice-hash/Cargo.toml b/lattice-hash/Cargo.toml index 44d257091f642f..3fce6f0180fa01 100644 --- a/lattice-hash/Cargo.toml +++ b/lattice-hash/Cargo.toml @@ -10,6 +10,7 @@ edition = { workspace = true } [dependencies] base64 = { workspace = true } blake3 = { workspace = true } +bs58 = { workspace = true } bytemuck = { workspace = true, features = ["must_cast"] } [dev-dependencies] diff --git a/lattice-hash/src/lt_hash.rs b/lattice-hash/src/lt_hash.rs index 100c9a10a6d53a..9cdfe555eb24ec 100644 --- a/lattice-hash/src/lt_hash.rs +++ b/lattice-hash/src/lt_hash.rs @@ -1,6 +1,6 @@ use { base64::{display::Base64Display, prelude::BASE64_STANDARD}, - std::fmt, + std::{fmt, str}, }; /// A 16-bit, 1024 element lattice-based incremental hash based on blake3 @@ -77,8 +77,14 @@ impl Checksum { impl fmt::Display for Checksum { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let base64 = Base64Display::new(&self.0, &BASE64_STANDARD); - write!(f, "{base64}") + /// Maximum string length of a base58 encoded Checksum. + const MAX_BASE58_LEN: usize = 44; + let mut buf = [0u8; MAX_BASE58_LEN]; + // SAFETY: The only error is if the buffer is too small + let len = bs58::encode(&self.0).onto(buf.as_mut_slice()).unwrap(); + // SAFETY: The base58 alphabet is utf8 + let str = str::from_utf8(&buf[..len]).unwrap(); + write!(f, "{str}") } } @@ -377,4 +383,12 @@ mod tests { assert_eq!(actual_checksum, expected_checksum); } } + + #[test] + fn test_checksum_display() { + let lt_hash = LtHash::identity(); + let checksum = lt_hash.checksum(); + let str = checksum.to_string(); + assert_eq!(str.as_str(), "DoL6fvKuTpTQCyUh83NxQw2ewKzWYtq9gsTKp1eQiGC2"); + } } diff --git a/programs/sbf/Cargo.lock b/programs/sbf/Cargo.lock index 617dce0e924299..6900b5ac87e17d 100644 --- a/programs/sbf/Cargo.lock +++ b/programs/sbf/Cargo.lock @@ -5427,6 +5427,7 @@ version = "2.1.0" dependencies = [ "base64 0.22.1", "blake3", + "bs58", "bytemuck", ]