Skip to content

Commit

Permalink
Merge #120: Add segwit API
Browse files Browse the repository at this point in the history
024ed01 Add segwit version field element consts (Tobin C. Harding)
6c1379b Add segwit API (Tobin C. Harding)

Pull request description:

  Add a `segwit` API with the aim that "typical" modern bitcoin usage is easy and correct.

  Done in a separate module so as not to impact the main crate API.

ACKs for top commit:
  apoelstra:
    ACK 024ed01

Tree-SHA512: 169e1a836f122fa3344857eec5945034afc2c727d1d6df57d5f3c5cde7a994d79398060cca5561a3706af0c835efafebaaa619df7b49f5c64acee01587259832
  • Loading branch information
apoelstra committed Aug 16, 2023
2 parents 72e7dd8 + 024ed01 commit f52be3d
Show file tree
Hide file tree
Showing 7 changed files with 397 additions and 62 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ pub use crate::primitives::{Bech32, Bech32m};

mod error;
pub mod primitives;
pub mod segwit;

pub use primitives::gf32::Fe32 as u5;

Expand Down
63 changes: 10 additions & 53 deletions src/primitives/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
//! ```
//! use bech32::{Bech32, Bech32m, Fe32, Hrp};
//! use bech32::primitives::decode::{CheckedHrpstring, SegwitHrpstring, UncheckedHrpstring};
//! use bech32::segwit::VERSION_1;
//!
//! // An arbitrary HRP and a string of valid bech32 characters.
//! let s = "abcd143hj65vxw49rts6kcw35u6r6tgzguyr03vvveeewjqpn05efzq444444";
Expand Down Expand Up @@ -66,7 +67,7 @@
//! let segwit = SegwitHrpstring::new(address).expect("valid segwit address");
//! let _encoded_data = segwit.byte_iter();
//! assert_eq!(segwit.hrp(), Hrp::parse("bc").unwrap());
//! assert_eq!(segwit.witness_version(), Fe32::P);
//! assert_eq!(segwit.witness_version(), VERSION_1);
//! ```
//!
//! [BIP-173]: <https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki>
Expand All @@ -78,6 +79,7 @@ use crate::primitives::checksum::{self, Checksum};
use crate::primitives::gf32::Fe32;
use crate::primitives::hrp::{self, Hrp};
use crate::primitives::iter::{Fe32IterExt, FesToBytes};
use crate::primitives::segwit::{self, WitnessLengthError, VERSION_0};
use crate::{write_err, Bech32, Bech32m};

/// Separator between the hrp and payload (as defined by BIP-173).
Expand Down Expand Up @@ -274,7 +276,7 @@ impl<'s> CheckedHrpstring<'s> {
self.data = &self.data[1..]; // Remove the witness version byte from data.

self.validate_padding()?;
self.validate_witness_length(witness_version)?;
self.validate_witness_program_length(witness_version)?;

Ok(SegwitHrpstring { hrp: self.hrp(), witness_version, data: self.data })
}
Expand Down Expand Up @@ -319,21 +321,11 @@ impl<'s> CheckedHrpstring<'s> {
/// Validates the segwit witness length rules.
///
/// Must be called after the witness version byte is removed from the data.
#[allow(clippy::manual_range_contains)] // For witness length range check.
fn validate_witness_length(&self, witness_version: Fe32) -> Result<(), WitnessLengthError> {
use WitnessLengthError::*;

let witness_len = self.byte_iter().len();
if witness_len < 2 {
return Err(TooShort);
}
if witness_len > 40 {
return Err(TooLong);
}
if witness_version == Fe32::Q && witness_len != 20 && witness_len != 32 {
return Err(InvalidSegwitV0);
}
Ok(())
fn validate_witness_program_length(
&self,
witness_version: Fe32,
) -> Result<(), WitnessLengthError> {
segwit::validate_witness_program_length(self.byte_iter().len(), witness_version)
}
}

Expand Down Expand Up @@ -383,7 +375,7 @@ impl<'s> SegwitHrpstring<'s> {
}

let checked: CheckedHrpstring<'s> = match witness_version {
Fe32::Q => unchecked.validate_and_remove_checksum::<Bech32>()?,
VERSION_0 => unchecked.validate_and_remove_checksum::<Bech32>()?,
_ => unchecked.validate_and_remove_checksum::<Bech32m>()?,
};

Expand Down Expand Up @@ -770,41 +762,6 @@ impl std::error::Error for ChecksumError {
}
}

/// Witness program invalid because of incorrect length.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum WitnessLengthError {
/// The witness data is too short.
TooShort,
/// The witness data is too long.
TooLong,
/// The segwit v0 witness is not 20 or 32 bytes long.
InvalidSegwitV0,
}

impl fmt::Display for WitnessLengthError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use WitnessLengthError::*;

match *self {
TooShort => write!(f, "witness program is less than 2 bytes long"),
TooLong => write!(f, "witness program is more than 40 bytes long"),
InvalidSegwitV0 => write!(f, "the segwit v0 witness is not 20 or 32 bytes long"),
}
}
}

#[cfg(feature = "std")]
impl std::error::Error for WitnessLengthError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use WitnessLengthError::*;

match *self {
TooShort | TooLong | InvalidSegwitV0 => None,
}
}
}

/// Error validating the padding bits on the witness data.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PaddingError {
Expand Down
1 change: 1 addition & 0 deletions src/primitives/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub mod encode;
pub mod gf32;
pub mod hrp;
pub mod iter;
pub mod segwit;

use checksum::{Checksum, PackedNull};

Expand Down
103 changes: 103 additions & 0 deletions src/primitives/segwit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// SPDX-License-Identifier: MIT

//! Segregated Witness functionality - useful for enforcing parts of [`BIP-173`] and [`BIP-350`].
//!
//! [BIP-173]: <https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki>
//! [BIP-350]: <https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki>

use core::fmt;

use crate::primitives::gf32::Fe32;

/// The field element representing segwit version 0.
pub const VERSION_0: Fe32 = Fe32::Q;
/// The field element representing segwit version 1 (taproot).
pub const VERSION_1: Fe32 = Fe32::P;

/// Returns true if given field element represents a valid segwit version.
pub fn is_valid_witness_version(witness_version: Fe32) -> bool {
validate_witness_version(witness_version).is_ok()
}

/// Returns true if `length` represents a valid witness program length for `witness_version`.
pub fn is_valid_witness_program_length(length: usize, witness_version: Fe32) -> bool {
validate_witness_program_length(length, witness_version).is_ok()
}

/// Checks that the given field element represents a valid segwit witness version.
pub fn validate_witness_version(witness_version: Fe32) -> Result<(), InvalidWitnessVersionError> {
if witness_version.to_u8() > 16 {
Err(InvalidWitnessVersionError(witness_version))
} else {
Ok(())
}
}

/// Validates the segwit witness program `length` rules for witness `version`.
pub fn validate_witness_program_length(
length: usize,
version: Fe32,
) -> Result<(), WitnessLengthError> {
use WitnessLengthError::*;

if length < 2 {
return Err(TooShort);
}
if length > 40 {
return Err(TooLong);
}
if version == VERSION_0 && length != 20 && length != 32 {
return Err(InvalidSegwitV0);
}
Ok(())
}

/// Field element does not represent a valid witness version.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidWitnessVersionError(Fe32);

impl fmt::Display for InvalidWitnessVersionError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "field element does not represent a valid witness version")
}
}

#[cfg(feature = "std")]
impl std::error::Error for InvalidWitnessVersionError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None }
}

/// Witness program invalid because of incorrect length.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum WitnessLengthError {
/// The witness data is too short.
TooShort,
/// The witness data is too long.
TooLong,
/// The segwit v0 witness is not 20 or 32 bytes long.
InvalidSegwitV0,
}

impl fmt::Display for WitnessLengthError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use WitnessLengthError::*;

match *self {
TooShort => write!(f, "witness program is less than 2 bytes long"),
TooLong => write!(f, "witness program is more than 40 bytes long"),
InvalidSegwitV0 => write!(f, "the segwit v0 witness is not 20 or 32 bytes long"),
}
}
}

#[cfg(feature = "std")]
impl std::error::Error for WitnessLengthError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use WitnessLengthError::*;

match *self {
TooShort | TooLong | InvalidSegwitV0 => None,
}
}
}
Loading

0 comments on commit f52be3d

Please sign in to comment.