bech32 0.12.0

Encodes and decodes the Bech32 format and implements the bech32 and bech32m checksums
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
// SPDX-License-Identifier: MIT

//! Degree-2 [BCH] code checksum.
//!
//! [BCH]: <https://en.wikipedia.org/wiki/BCH_code>

use core::marker::PhantomData;
use core::{fmt, mem, ops};

use super::Polynomial;
use crate::primitives::hrp::Hrp;
use crate::{Fe1024, Fe32};

/// Trait defining a particular checksum.
///
/// 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
    /// same width).
    ///
    /// Generally, this is the number of characters in the checksum times 5. So e.g.
    /// for bech32, which has a 6-character checksum, we need 30 bits, so we can use
    /// u32 here.
    ///
    /// The smallest type possible should be used, for efficiency reasons, but the
    /// only operations we do on these types are bitwise xor and shifts, so it should
    /// 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
    /// checksum!) for the code to retain its error-correcting properties.
    const CODE_LENGTH: usize;

    /// The number of characters in the checksum.
    ///
    /// Alternately, the degree of the generator polynomial. This is **not** the same
    /// as `Self::CODE_LENGTH`.
    const CHECKSUM_LENGTH: usize;

    /// The coefficients of the generator polynomial, except the leading monic term,
    /// in "big-endian" (highest-degree coefficients get leftmost bits) order, along
    /// with the 4 shifts of the generator.
    ///
    /// The shifts are literally the generator polynomial left-shifted (i.e. multiplied
    /// by the appropriate power of 2) in the field. That is, the 5 entries in this
    /// array are the generator times { P, Z, Y, G, S } in that order.
    ///
    /// These cannot be usefully pre-computed because of Rust's limited constfn support
    /// as of 1.67, so they must be specified manually for each checksum. To check the
    /// values for consistency, run [`Self::sanity_check`].
    const GENERATOR_SH: [Self::MidstateRepr; 5];

    /// The residue, modulo the generator polynomial, that a valid codeword will have.
    const TARGET_RESIDUE: Self::MidstateRepr;

    /// Sanity checks that the various constants of the trait are set in a way that they
    /// are consistent with each other.
    ///
    /// This function never needs to be called by users, but anyone defining a checksum
    /// should add a unit test to their codebase which calls this.
    fn sanity_check() {
        // Check that the declared midstate type can actually hold the whole checksum.
        assert!(Self::CHECKSUM_LENGTH <= Self::MidstateRepr::WIDTH);

        // Check that the provided generator polynomials are, indeed, the same polynomial just shifted.
        for i in 1..5 {
            for j in 0..Self::MidstateRepr::WIDTH {
                let last = Self::GENERATOR_SH[i - 1].unpack(j);
                let curr = Self::GENERATOR_SH[i].unpack(j);
                // GF32 is defined by extending GF2 with a root of x^5 + x^3 + 1 = 0
                // which when written as bit coefficients is 41 = 0. Hence xoring
                // (adding, in GF32) by 41 is the way to reduce x^5.
                assert_eq!(
                    curr,
                    (last << 1) ^ if last & 0x10 == 0x10 { 41 } else { 0 },
                    "Element {} of generator << 2^{} was incorrectly computed. (Should have been {} << 1)",
                    j, i, last,
                );
            }
        }
    }
}

/// Given a polynomial representation for your generator polynomial and your
/// target residue, outputs a `impl Checksum` block.
///
/// You must specify an extension field. You should try [`crate::Fe1024`], and if
/// you get an error about a polynomial not splitting, try [`crate::Fe32768`].
///
/// Used like
///
/// ```
/// # #[cfg(feature = "alloc")] {
/// use core::convert::TryFrom;
///
/// use bech32::{Fe32, Fe1024, PrintImpl};
/// use bech32::primitives::checksum::PackedFe32;
///
/// // In codes specified in BIPs, the code generator polynomial and residue
/// // are often only given indirectly, in the reference code which encodes
/// // it in a packed form (shifted multiple times).
/// //
/// // For example in the BIP173 Python reference code you will see an array
/// // called `generator` whose first entry is 0x3b6a57b2. This first entry
/// // is the generator polynomial in packed form.
/// //
/// // To get the expanded polynomial form you can use `u128::unpack` like so:
/// let unpacked_poly = (0..6)
///     .rev() // Note .rev() to convert from BE integer literal to LE polynomial!
///     .map(|i| 0x3b6a57b2u128.unpack(i))
///     .map(|u| Fe32::try_from(u).unwrap())
///     .collect::<Vec<_>>();
/// let unpacked_residue = (0..6)
///     .rev()
///     .map(|i| 0x1u128.unpack(i))
///     .map(|u| Fe32::try_from(u).unwrap())
///     .collect::<Vec<_>>();
/// println!(
///     "{}",
///     PrintImpl::<Fe1024>::new(
///         "Bech32",
///         &unpacked_poly,
///         &unpacked_residue,
///     ),
/// );
/// # }
/// ```
///
/// The awkward API is to allow this type to be used in the widest set of
/// circumstances, including in nostd settings. (However, the underlying
/// polynomial math requires the `alloc` feature.)
///
/// Both polynomial representations should be in little-endian order, so that
/// the coefficient of x^i appears in the ith slot. The generator polynomial
/// should be a monic polynomial but you should not include the monic term,
/// so that both `generator` and `target` are arrays of the same length.
///
/// **This function should never need to be called by users, but will be helpful
/// for developers.**
///
/// In general, when defining a checksum, it is best to call this method (and
/// to add a unit test that calls [`Checksum::sanity_check`] rather than trying
/// to compute the values yourself. The reason is that the specific values
/// used depend on the representation of extension fields, which may differ
/// between implementations (and between specifications) of your BCH code.
pub struct PrintImpl<'a, ExtField = Fe1024> {
    name: &'a str,
    generator: Polynomial<Fe32>,
    target: &'a [Fe32],
    bit_len: usize,
    hex_width: usize,
    midstate_repr: &'static str,
    phantom: PhantomData<ExtField>,
}

impl<'a, ExtField> PrintImpl<'a, ExtField> {
    /// Constructor for an object to print an impl-block for the [`Checksum`] trait.
    ///
    /// # Panics
    ///
    /// Panics if any of the input values fail various sanity checks.
    pub fn new(name: &'a str, generator: &'a [Fe32], target: &'a [Fe32]) -> Self {
        // Sanity checks.
        assert_ne!(name.len(), 0, "type name cannot be the empty string",);
        assert_ne!(
            generator.len(),
            0,
            "generator polynomial cannot be the empty string (constant 1)"
        );
        assert_ne!(target.len(), 0, "target residue cannot be the empty string");
        if generator.len() != target.len() {
            let hint = if generator.len() == target.len() + 1 {
                " (you should not include the monic term of the generator polynomial"
            } else if generator.len() > target.len() {
                " (you may need to zero-pad your target residue)"
            } else {
                ""
            };
            panic!(
                "Generator length {} does not match target residue length {}{}",
                generator.len(),
                target.len(),
                hint
            );
        }

        let bit_len = 5 * target.len();
        let (hex_width, midstate_repr) = if bit_len <= 32 {
            (8, "u32")
        } else if bit_len <= 64 {
            (16, "u64")
        } else if bit_len <= 128 {
            (32, "u128")
        } else {
            panic!("Generator length {} cannot exceed 25, as we cannot represent it by packing bits into a Rust numeric type", generator.len());
        };
        // End sanity checks.
        PrintImpl {
            name,
            generator: Polynomial::with_monic_leading_term(generator),
            target,
            bit_len,
            hex_width,
            midstate_repr,
            phantom: PhantomData,
        }
    }
}

impl<ExtField> fmt::Display for PrintImpl<'_, ExtField>
where
    ExtField: super::Bech32Field + super::ExtensionField<BaseField = Fe32>,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Generator polynomial as a polynomial over GF1024
        let (gen, length, exponents) = self.generator.bch_generator_primitive_element::<ExtField>();

        write!(f, "// Code block generated by Checksum::print_impl polynomial ")?;
        for fe in self.generator.as_inner() {
            write!(f, "{}", fe)?;
        }
        write!(f, " target ")?;
        for fe in self.target {
            write!(f, "{}", fe)?;
        }
        f.write_str("\n")?;
        writeln!(f, "impl Checksum for {} {{", self.name)?;
        writeln!(
            f,
            "    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 = {};", self.generator.degree())?;
        writeln!(f, "    const GENERATOR_SH: [{}; 5] = [", self.midstate_repr)?;
        let mut gen5 = self.generator.clone().into_inner();
        for _ in 0..5 {
            let gen_packed = u128::pack(gen5.iter().copied().map(From::from));
            writeln!(f, "        0x{:0width$x},", gen_packed, width = self.hex_width)?;
            gen5.iter_mut().for_each(|x| *x *= Fe32::Z);
        }
        writeln!(f, "    ];")?;
        writeln!(
            f,
            "    const TARGET_RESIDUE: {} = 0x{:0width$x};",
            self.midstate_repr,
            u128::pack(self.target.iter().copied().map(From::from)),
            width = self.hex_width,
        )?;
        f.write_str("}")
    }
}

/// A checksum engine, which can be used to compute or verify a checksum.
///
/// Use this to verify a checksum, feed it the data to be checksummed using
/// the `Self::input_*` methods.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Engine<Ck: Checksum> {
    residue: Ck::MidstateRepr,
}

impl<Ck: Checksum> Default for Engine<Ck> {
    fn default() -> Self { Self::new() }
}

impl<Ck: Checksum> Engine<Ck> {
    /// Constructs a new checksum engine with no data input.
    #[inline]
    pub fn new() -> Self { Engine { residue: Ck::MidstateRepr::ONE } }

    /// Feeds `hrp` into the checksum engine.
    #[inline]
    pub fn input_hrp(&mut self, hrp: Hrp) {
        for fe in HrpFe32Iter::new(&hrp) {
            self.input_fe(fe)
        }
    }

    /// Adds a single gf32 element to the checksum engine.
    ///
    /// This is where the actual checksum computation magic happens.
    #[inline]
    pub fn input_fe(&mut self, e: Fe32) {
        let xn = self.residue.mul_by_x_then_add(Ck::CHECKSUM_LENGTH, e.into());
        for i in 0..5 {
            if xn & (1 << i) != 0 {
                self.residue = self.residue ^ Ck::GENERATOR_SH[i];
            }
        }
    }

    /// Inputs the target residue of the checksum.
    ///
    /// Checksums are generated by appending the target residue to the input
    /// string, then computing the actual residue, and then replacing the
    /// target with the actual. This method lets us compute the actual residue
    /// without doing any string concatenations.
    #[inline]
    pub fn input_target_residue(&mut self) {
        for i in 0..Ck::CHECKSUM_LENGTH {
            self.input_fe(Fe32(Ck::TARGET_RESIDUE.unpack(Ck::CHECKSUM_LENGTH - i - 1)));
        }
    }

    /// Returns for the current checksum residue.
    #[inline]
    pub fn residue(&self) -> &Ck::MidstateRepr { &self.residue }
}

/// Trait describing an integer type which can be used as a "packed" sequence of Fe32s.
///
/// This is implemented for u32, u64 and u128, as a way to treat these primitive types as
/// packed coefficients of polynomials over GF32 (up to some maximal degree, of course).
///
/// This is useful because then multiplication by x reduces to simply left-shifting by 5,
/// and addition of entire polynomials can be done by xor.
pub trait PackedFe32: Copy + PartialEq + Eq + ops::BitXor<Self, Output = Self> {
    /// The one constant, for which stdlib provides no existing trait.
    const ONE: Self;

    /// The number of fe32s that can fit into the type; computed as floor(bitwidth / 5).
    const WIDTH: usize = mem::size_of::<Self>() * 8 / 5;

    /// Takes an iterator of `u8`s (or [`Fe32`]s converted to `u8`s) and packs
    /// them into a [`Self`].
    ///
    /// For sequences representing polynomials, the iterator should yield the
    /// coefficients in little-endian order, i.e. the 0th coefficien first.
    ///
    /// # Panics
    ///
    /// May panic if the iterator yields more items than can fit into the bit-packed
    /// type.
    fn pack<I: Iterator<Item = u8>>(iter: I) -> Self;

    /// Extracts the coefficient of the x^n from the packed polynomial.
    fn unpack(&self, n: usize) -> u8;

    /// Multiply the polynomial by x, drop its highest coefficient (and return it), and
    /// add a new field element to the now-0 constant coefficient.
    ///
    /// Takes the degree of the polynomial as an input; for checksum applications
    /// this should basically always be `Checksum::CHECKSUM_WIDTH`.
    fn mul_by_x_then_add(&mut self, degree: usize, add: u8) -> u8;
}

/// A placeholder type used as part of the [`NoChecksum`] "checksum".
///
/// [`NoChecksum`]: crate::primitives::NoChecksum
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct PackedNull;

impl ops::BitXor<PackedNull> for PackedNull {
    type Output = PackedNull;
    #[inline]
    fn bitxor(self, _: PackedNull) -> PackedNull { PackedNull }
}

impl PackedFe32 for PackedNull {
    const ONE: Self = PackedNull;
    #[inline]
    fn unpack(&self, _: usize) -> u8 { 0 }
    #[inline]
    fn mul_by_x_then_add(&mut self, _: usize, _: u8) -> u8 { 0 }

    #[inline]
    fn pack<I: Iterator<Item = u8>>(mut iter: I) -> Self {
        if iter.next().is_some() {
            panic!("Cannot pack anything into a PackedNull");
        }
        Self
    }
}

macro_rules! impl_packed_fe32 {
    ($ty:ident) => {
        impl PackedFe32 for $ty {
            const ONE: Self = 1;

            #[inline]
            fn unpack(&self, n: usize) -> u8 {
                debug_assert!(n < Self::WIDTH);
                (*self >> (n * 5)) as u8 & 0x1f
            }

            #[inline]
            fn mul_by_x_then_add(&mut self, degree: usize, add: u8) -> u8 {
                debug_assert!(degree > 0);
                debug_assert!(degree <= Self::WIDTH);
                debug_assert!(add < 32);
                let ret = self.unpack(degree - 1);
                *self &= !(0x1f << ((degree - 1) * 5));
                *self <<= 5;
                *self |= Self::from(add);
                ret
            }

            #[inline]
            fn pack<I: Iterator<Item = u8>>(iter: I) -> Self {
                let mut ret: Self = 0;
                for (n, elem) in iter.enumerate() {
                    debug_assert!(elem < 32);
                    debug_assert!(n < Self::WIDTH);
                    ret <<= 5;
                    ret |= Self::from(elem);
                }
                ret
            }
        }
    };
}
impl_packed_fe32!(u32);
impl_packed_fe32!(u64);
impl_packed_fe32!(u128);

/// Iterator that yields the field elements that are input into a checksum algorithm for an [`Hrp`].
pub struct HrpFe32Iter<'hrp> {
    /// `None` once the hrp high fes have been yielded.
    high_iter: Option<crate::primitives::hrp::LowercaseByteIter<'hrp>>,
    /// `None` once the hrp low fes have been yielded.
    low_iter: Option<crate::primitives::hrp::LowercaseByteIter<'hrp>>,
}

impl<'hrp> HrpFe32Iter<'hrp> {
    /// Creates an iterator that yields the field elements of `hrp` as they are input into the
    /// checksum algorithm.
    #[inline]
    pub fn new(hrp: &'hrp Hrp) -> Self {
        let high_iter = hrp.lowercase_byte_iter();
        let low_iter = hrp.lowercase_byte_iter();

        Self { high_iter: Some(high_iter), low_iter: Some(low_iter) }
    }
}

impl Iterator for HrpFe32Iter<'_> {
    type Item = Fe32;
    #[inline]
    fn next(&mut self) -> Option<Fe32> {
        if let Some(ref mut high_iter) = &mut self.high_iter {
            match high_iter.next() {
                Some(high) => return Some(Fe32(high >> 5)),
                None => {
                    self.high_iter = None;
                    return Some(Fe32::Q);
                }
            }
        }
        if let Some(ref mut low_iter) = &mut self.low_iter {
            match low_iter.next() {
                Some(low) => return Some(Fe32(low & 0x1f)),
                None => self.low_iter = None,
            }
        }
        None
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let high = match &self.high_iter {
            Some(high_iter) => {
                let (min, max) = high_iter.size_hint();
                (min + 1, max.map(|max| max + 1)) // +1 for the extra Q
            }
            None => (0, Some(0)),
        };
        let low = match &self.low_iter {
            Some(low_iter) => low_iter.size_hint(),
            None => (0, Some(0)),
        };

        let min = high.0 + low.0;
        let max = high.1.zip(low.1).map(|(high, low)| high + low);

        (min, max)
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "alloc")]
    use alloc::vec::Vec;
    #[cfg(feature = "alloc")]
    use core::convert::TryFrom;

    use super::*;

    #[test]
    fn pack_unpack() {
        let packed = u128::pack([0, 0, 0, 1].iter().copied());
        assert_eq!(packed, 1);
        assert_eq!(packed.unpack(0), 1);
        assert_eq!(packed.unpack(3), 0);

        let packed = u128::pack([1, 2, 3, 4].iter().copied());
        assert_eq!(packed, 0b00001_00010_00011_00100);
        assert_eq!(packed.unpack(0), 4);
        assert_eq!(packed.unpack(1), 3);
        assert_eq!(packed.unpack(2), 2);
        assert_eq!(packed.unpack(3), 1);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn bech32() {
        // In codes that Pieter specifies typically the generator polynomial is
        // only given indirectly, in the reference code which encodes it in a
        // packed form (shifted multiple times).
        //
        // For example in the BIP173 Python reference code you will see an array
        // called `generator` whose first entry is 0x3b6a57b2. This first entry
        // is the generator polynomial in packed form.
        //
        // To get the expanded polynomial form you can use `u128::unpack` like so:
        let unpacked_poly = (0..6)
            .rev() // Note .rev() to convert from BE integer literal to LE polynomial!
            .map(|i| 0x3b6a57b2u128.unpack(i))
            .map(|u| Fe32::try_from(u).unwrap())
            .collect::<Vec<_>>();
        assert_eq!(unpacked_poly, [Fe32::A, Fe32::K, Fe32::_5, Fe32::_4, Fe32::A, Fe32::J],);
        // To get a version of the above with bech32 chars instead of Fe32s, which
        // can be a bit hard to print, just stick a `.map(Fe32::to_char)` into the
        // above iterator chain.

        // Ok, exposition over. The actual unit test follows.

        // Run with -- --nocapture to see the output of this. This unit test
        // does not check the exact output because it is not deterministic,
        // and cannot check the code semantics because Rust does not have
        // any sort of `eval`, but you can manually check the output works.
        let _s = PrintImpl::<Fe1024>::new(
            "Bech32",
            &[Fe32::A, Fe32::K, Fe32::_5, Fe32::_4, Fe32::A, Fe32::J],
            &[Fe32::Q, Fe32::Q, Fe32::Q, Fe32::Q, Fe32::Q, Fe32::P],
        )
        .to_string();
        #[cfg(feature = "std")]
        println!("{}", _s);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn descriptor() {
        // This magic constant came from Bitcoin Core, src/script/descriptor.cpp.
        //
        // Note that this generator polynomial has degree 8, not 6, reflected
        // in the initial range being (0..8).
        let unpacked_poly = (0..8)
            .rev() // Note .rev() to convert from BE integer literal to LE polynomial!
            .map(|i| 0xf5dee51989u64.unpack(i))
            .map(|u| Fe32::try_from(u).unwrap())
            .collect::<Vec<_>>();
        assert_eq!(
            unpacked_poly,
            [Fe32::_7, Fe32::H, Fe32::_0, Fe32::W, Fe32::_2, Fe32::X, Fe32::V, Fe32::F],
        );

        // Run with -- --nocapture to see the output of this. This unit test
        // does not check the exact output because it is not deterministic,
        // and cannot check the code semantics because Rust does not have
        // any sort of `eval`, but you can manually check the output works.
        let _s = PrintImpl::<crate::Fe32768>::new(
            "DescriptorChecksum",
            &[Fe32::_7, Fe32::H, Fe32::_0, Fe32::W, Fe32::_2, Fe32::X, Fe32::V, Fe32::F],
            &[Fe32::Q, Fe32::Q, Fe32::Q, Fe32::Q, Fe32::Q, Fe32::Q, Fe32::Q, Fe32::P],
        )
        .to_string();
        #[cfg(feature = "std")]
        println!("{}", _s);
    }

    #[test]
    #[should_panic]
    fn sanity_check_panics_on_bad_checksums() {
        enum BadGeneratorShifts {}
        impl Checksum for BadGeneratorShifts {
            type MidstateRepr = u32;
            type CorrectionField = crate::Fe1024;
            const ROOT_GENERATOR: Self::CorrectionField = crate::Fe1024::new([Fe32::P, Fe32::X]);
            const ROOT_EXPONENTS: core::ops::RangeInclusive<usize> = 24..=26;
            const CODE_LENGTH: usize = 1023;
            const CHECKSUM_LENGTH: usize = 6;
            const GENERATOR_SH: [u32; 5] = [1, 1, 1, 1, 1];
            const TARGET_RESIDUE: u32 = 1;
        }

        BadGeneratorShifts::sanity_check();
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn print_impl_renders_expected_bech32_impl() {
        let rendered = PrintImpl::<crate::Fe1024>::new(
            "Bech32",
            &[Fe32::A, Fe32::K, Fe32::_5, Fe32::_4, Fe32::A, Fe32::J],
            &[Fe32::Q, Fe32::Q, Fe32::Q, Fe32::Q, Fe32::Q, Fe32::P],
        )
        .to_string();

        let generator_shift = "0x4eb8406b0"; // generator << 2^3
        assert!(
            rendered.contains(generator_shift),
            "generated impl missing expected fragment: {}\n\n{}",
            generator_shift,
            rendered
        );
    }

    #[test]
    fn packed_null() {
        let mut packed = PackedNull;
        assert_eq!(packed.unpack(0), 0);
        assert_eq!(packed.mul_by_x_then_add(1, 31), 0);
    }

    #[test]
    fn hrp_fe32_iter_size_hint_matches_remaining_length() {
        let hrp = Hrp::parse_unchecked("ab");
        let mut iter = HrpFe32Iter::new(&hrp);

        for remaining in (0..=(2 * hrp.len() + 1)).rev() {
            assert_eq!(iter.size_hint(), (remaining, Some(remaining)));
            if remaining > 0 {
                iter.next().expect("iterator has more elements");
            }
        }
    }
}

#[cfg(bench)]
mod benches {
    use std::io::{sink, Write};

    use test::{black_box, Bencher};

    use crate::{Fe1024, Fe32, Fe32768, PrintImpl};

    #[bench]
    fn compute_bech32_params(bh: &mut Bencher) {
        bh.iter(|| {
            let im = PrintImpl::<Fe1024>::new(
                "Bech32",
                &[Fe32::A, Fe32::K, Fe32::_5, Fe32::_4, Fe32::A, Fe32::J],
                &[Fe32::Q, Fe32::Q, Fe32::Q, Fe32::Q, Fe32::Q, Fe32::P],
            );
            let res = write!(sink(), "{}", im);
            black_box(&im);
            black_box(&res);
        })
    }

    #[bench]
    fn compute_descriptor_params(bh: &mut Bencher) {
        bh.iter(|| {
            let im = PrintImpl::<Fe32768>::new(
                "DescriptorChecksum",
                &[Fe32::_7, Fe32::H, Fe32::_0, Fe32::W, Fe32::_2, Fe32::X, Fe32::V, Fe32::F],
                &[Fe32::Q, Fe32::Q, Fe32::Q, Fe32::Q, Fe32::Q, Fe32::Q, Fe32::Q, Fe32::P],
            );
            let res = write!(sink(), "{}", im);
            black_box(&im);
            black_box(&res);
        })
    }
}