Skip to content

Commit

Permalink
Merge #203: Extend Field and Checksum for error correction
Browse files Browse the repository at this point in the history
f47ec0b field: add Powers iterator (Andrew Poelstra)
c389d72 checksum: add new error-correction fields to the Checksum trait (Andrew Poelstra)
14e4f7b field: add Default bound to Field (Andrew Poelstra)
011674d field: add format_as_rust_code utility method (Andrew Poelstra)
3c97cd1 field: split trait into "normal" field trait and sealed trait (Andrew Poelstra)
8eaec9d field: use UFCS in macro (Andrew Poelstra)

Pull request description:

  The first couple commits of this PR split the `Field` trait into two -- a general `Field` trait which has the algebraic functionality of a field, and a sealed `Bech32Field` trait which has the functionality that is specific to this crate.

  The rest add new functionality to the traits which describe extra properties of our checksums needed for error correction.

  The next PRs will:

  * Introduce a `FieldVec` type to back `Polynomial` to make it work in a no-alloc setting (at least for small checksums, for a configurable notion of "small")
  * Implement error correction :)

ACKs for top commit:
  clarkmoody:
    ACK f47ec0b

Tree-SHA512: 880e0e4cb2f21effd657ef57ddff45a807f55283f7a0fad6aeec67518f0bbec0daa719bbedd5c9490dd1ed22538ea3a9b071db3cb6eac142cbd91d1e65919103
  • Loading branch information
apoelstra committed Sep 19, 2024
2 parents 7a6d9cc + f47ec0b commit 86a5bdc
Show file tree
Hide file tree
Showing 6 changed files with 254 additions and 161 deletions.
6 changes: 5 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,18 @@
//!
//! ```
//! # #[cfg(feature = "alloc")] {
//! use bech32::Checksum;
//! use bech32::{Checksum, Fe32, Fe1024};
//!
//! /// The codex32 checksum algorithm, defined in BIP-93.
//! #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
//! pub enum Codex32 {}
//!
//! impl Checksum for Codex32 {
//! type MidstateRepr = u128;
//! type CorrectionField = bech32::primitives::gf32_ext::Fe32Ext<2>;
//! const ROOT_GENERATOR: Self::CorrectionField = Fe1024::new([Fe32::_9, Fe32::_9]);
//! const ROOT_EXPONENTS: core::ops::RangeInclusive<usize> = 77..=84;
//!
//! const CHECKSUM_LENGTH: usize = 13;
//! const CODE_LENGTH: usize = 93;
//! // Copied from BIP-93
Expand Down
35 changes: 31 additions & 4 deletions src/primitives/checksum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ use crate::Fe32;
///
/// For users, this can be treated as a marker trait; none of the associated data
/// are end-user relevant.
///
/// For developers, implementations of this trait can be computed by starting with
/// a couple of values and using the [`PrintImpl`] object to generate the rest.
/// See the documentation for that type and its unit tests for examples.
pub trait Checksum {
/// An unsigned integer type capable of holding a packed version of the generator
/// polynomial (without its leading 1) and target residue (which will have the
Expand All @@ -37,6 +41,16 @@ pub trait Checksum {
/// be pretty efficient no matter what.
type MidstateRepr: PackedFe32;

/// The extension field in which error correction happens.
type CorrectionField: super::ExtensionField<BaseField = Fe32>;

/// The generator of the consecutive roots of the generator polynomial.
const ROOT_GENERATOR: Self::CorrectionField;

/// The consecutive powers of [`Self::ROOT_GENERATOR`] which are roots
/// of the generator polynomial.
const ROOT_EXPONENTS: core::ops::RangeInclusive<usize>;

/// The length of the code.
///
/// The length of the code is how long a coded message can be (including the
Expand Down Expand Up @@ -224,7 +238,7 @@ impl<'a, ExtField> PrintImpl<'a, ExtField> {
#[cfg(feature = "alloc")]
impl<'a, ExtField> fmt::Display for PrintImpl<'a, ExtField>
where
ExtField: super::ExtensionField + From<Fe32>,
ExtField: super::Bech32Field + super::ExtensionField<BaseField = Fe32>,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Generator polynomial as a polynomial over GF1024
Expand All @@ -234,7 +248,7 @@ where
v.extend(self.generator.iter().cloned().map(ExtField::from));
Polynomial::new(v)
};
let (_gen, length, _exponents) = gen_poly.bch_generator_primitive_element();
let (gen, length, exponents) = gen_poly.bch_generator_primitive_element();

write!(f, "// Code block generated by Checksum::print_impl polynomial ")?;
for fe in self.generator {
Expand All @@ -251,6 +265,18 @@ where
" type MidstateRepr = {}; // checksum packs into {} bits",
self.midstate_repr, self.bit_len
)?;
f.write_str("\n")?;
writeln!(f, " type CorrectionField = {};", core::any::type_name::<ExtField>())?;
f.write_str(" const ROOT_GENERATOR: Self::CorrectionField = ")?;
gen.format_as_rust_code(f)?;
f.write_str(";\n")?;
writeln!(
f,
" const ROOT_EXPONENTS: core::ops::RangeInclusive<usize> = {}..={};",
exponents.start(),
exponents.end()
)?;
f.write_str("\n")?;
writeln!(f, " const CODE_LENGTH: usize = {};", length)?;
writeln!(f, " const CHECKSUM_LENGTH: usize = {};", gen_poly.degree())?;
writeln!(f, " const GENERATOR_SH: [{}; 5] = [", self.midstate_repr)?;
Expand All @@ -263,9 +289,10 @@ where
writeln!(f, " ];")?;
writeln!(
f,
" const TARGET_RESIDUE: {} = {:?};",
" const TARGET_RESIDUE: {} = 0x{:0width$x};",
self.midstate_repr,
u128::pack(self.target.iter().copied().map(From::from))
u128::pack(self.target.iter().copied().map(From::from)),
width = self.hex_width,
)?;
f.write_str("}")
}
Expand Down
Loading

0 comments on commit 86a5bdc

Please sign in to comment.