|
| 1 | +// SPDX-License-Identifier: MIT |
| 2 | + |
| 3 | +//! Segregated Witness API - enables typical usage for encoding and decoding segwit addresses. |
| 4 | +//! |
| 5 | +//! [BIP-173] and [BIP-350] contain some complexity. This module aims to allow you to create modern |
| 6 | +//! Bitcoin addresses correctly and easily without intimate knowledge of the BIPs. However, if you |
| 7 | +//! do posses such knowledge and are doing unusual things you may prefer to use the `primitives` |
| 8 | +//! submodules directly. |
| 9 | +//! |
| 10 | +//! # Examples |
| 11 | +//! |
| 12 | +//! ``` |
| 13 | +//! # #[cfg(feature = "alloc")] { |
| 14 | +//! use bech32::primitives::hrp::{self, Hrp}; |
| 15 | +//! use bech32::{Fe32, segwit}; |
| 16 | +//! |
| 17 | +//! let witness_prog = [ |
| 18 | +//! 0x75, 0x1e, 0x76, 0xe8, 0x19, 0x91, 0x96, 0xd4, |
| 19 | +//! 0x54, 0x94, 0x1c, 0x45, 0xd1, 0xb3, 0xa3, 0x23, |
| 20 | +//! 0xf1, 0x43, 0x3b, 0xd6, |
| 21 | +//! ]; |
| 22 | +//! |
| 23 | +//! // Encode a taproot address suitable for use on mainnet. |
| 24 | +//! let _ = segwit::encode_v1(&hrp::BC, &witness_prog); |
| 25 | +//! |
| 26 | +//! // Encode a segwit v0 address suitable for use on testnet. |
| 27 | +//! let _ = segwit::encode_v0(&hrp::TB, &witness_prog); |
| 28 | +//! |
| 29 | +//! // If you have the witness version already you can use: |
| 30 | +//! # let witness_version = Fe32::Q; |
| 31 | +//! let _ = segwit::encode(&hrp::BC, witness_version, &witness_prog); |
| 32 | +//! |
| 33 | +//! // Decode a Bitcoin bech32 segwit address. |
| 34 | +//! let address = "bc1q2s3rjwvam9dt2ftt4sqxqjf3twav0gdx0k0q2etxflx38c3x8tnssdmnjq"; |
| 35 | +//! let (hrp, witness_version, witness_program) = segwit::decode(address).expect("failed to decode address"); |
| 36 | +//! # } |
| 37 | +//! ``` |
| 38 | +//! |
| 39 | +//! [BIP-173]: <https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki> |
| 40 | +//! [BIP-350]: <https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki> |
| 41 | +//! [`bip_173_test_vectors.rs`]: <https://github.com/rust-bitcoin/rust-bech32/blob/master/tests/bip_173_test_vectors.rs> |
| 42 | +//! [`bip_350_test_vectors.rs`]: <https://github.com/rust-bitcoin/rust-bech32/blob/master/tests/bip_350_test_vectors.rs> |
| 43 | +
|
| 44 | +#[cfg(all(feature = "alloc", not(feature = "std"), not(test)))] |
| 45 | +use alloc::{string::String, vec::Vec}; |
| 46 | +use core::fmt; |
| 47 | + |
| 48 | +#[cfg(feature = "alloc")] |
| 49 | +use crate::primitives::decode::{SegwitHrpstring, SegwitHrpstringError}; |
| 50 | +use crate::primitives::gf32::Fe32; |
| 51 | +use crate::primitives::hrp::Hrp; |
| 52 | +use crate::primitives::iter::{ByteIterExt, Fe32IterExt}; |
| 53 | +#[cfg(feature = "alloc")] |
| 54 | +use crate::primitives::segwit; |
| 55 | +use crate::primitives::segwit::{InvalidWitnessVersionError, WitnessLengthError}; |
| 56 | +use crate::primitives::{Bech32, Bech32m}; |
| 57 | +use crate::write_err; |
| 58 | + |
| 59 | +/// Decodes a segwit address. |
| 60 | +/// |
| 61 | +/// # Examples |
| 62 | +/// |
| 63 | +/// ``` |
| 64 | +/// use bech32::segwit; |
| 65 | +/// let address = "bc1py3m7vwnghyne9gnvcjw82j7gqt2rafgdmlmwmqnn3hvcmdm09rjqcgrtxs"; |
| 66 | +/// let (_hrp, _witness_version, _witness_program) = segwit::decode(address).expect("failed to decode address"); |
| 67 | +/// ``` |
| 68 | +#[cfg(feature = "alloc")] |
| 69 | +pub fn decode(s: &str) -> Result<(Hrp, Fe32, Vec<u8>), SegwitHrpstringError> { |
| 70 | + let segwit = SegwitHrpstring::new(s)?; |
| 71 | + Ok((segwit.hrp(), segwit.witness_version(), segwit.byte_iter().collect::<Vec<u8>>())) |
| 72 | +} |
| 73 | + |
| 74 | +/// Encodes a segwit address. |
| 75 | +/// |
| 76 | +/// Does validity checks on the `witness_version` and length checks on the `witness_program`. |
| 77 | +/// |
| 78 | +/// As specified by [`BIP-350`] we use the [`Bech32m`] checksum algorithm for witness versions 1 and |
| 79 | +/// above, and for witness version 0 we use the original ([`BIP-173`]) [`Bech32`] checksum |
| 80 | +/// algorithm. |
| 81 | +/// |
| 82 | +/// See also [`encode_v0`] or [`encode_v1`]. |
| 83 | +/// |
| 84 | +/// [`Bech32`]: crate::primitives::Bech32 |
| 85 | +/// [`Bech32m`]: crate::primitives::Bech32m |
| 86 | +/// [BIP-173]: <https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki> |
| 87 | +/// [BIP-350]: <https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki> |
| 88 | +#[cfg(feature = "alloc")] |
| 89 | +pub fn encode( |
| 90 | + hrp: &Hrp, |
| 91 | + witness_version: Fe32, |
| 92 | + witness_program: &[u8], |
| 93 | +) -> Result<String, EncodeError> { |
| 94 | + segwit::validate_witness_version(witness_version)?; |
| 95 | + segwit::validate_witness_program_length(witness_program.len(), witness_version)?; |
| 96 | + |
| 97 | + let mut buf = String::new(); |
| 98 | + encode_to_fmt_unchecked(&mut buf, hrp, witness_version, witness_program)?; |
| 99 | + Ok(buf) |
| 100 | +} |
| 101 | + |
| 102 | +/// Encodes a segwit version 0 address. |
| 103 | +#[cfg(feature = "alloc")] |
| 104 | +pub fn encode_v0(hrp: &Hrp, witness_program: &[u8]) -> Result<String, EncodeError> { |
| 105 | + encode(hrp, Fe32::Q, witness_program) |
| 106 | +} |
| 107 | + |
| 108 | +/// Encodes a segwit version 1 address. |
| 109 | +#[cfg(feature = "alloc")] |
| 110 | +pub fn encode_v1(hrp: &Hrp, witness_program: &[u8]) -> Result<String, EncodeError> { |
| 111 | + encode(hrp, Fe32::P, witness_program) |
| 112 | +} |
| 113 | + |
| 114 | +/// Encodes a segwit address to a writer ([`fmt::Write`]) using lowercase characters. |
| 115 | +/// |
| 116 | +/// Does not check the validity of the witness version and witness program lengths (see |
| 117 | +/// the [`crate::primitives::segwit`] module for validation functions). |
| 118 | +pub fn encode_to_fmt_unchecked<W: fmt::Write>( |
| 119 | + fmt: &mut W, |
| 120 | + hrp: &Hrp, |
| 121 | + witness_version: Fe32, |
| 122 | + witness_program: &[u8], |
| 123 | +) -> fmt::Result { |
| 124 | + let iter = witness_program.iter().copied().bytes_to_fes(); |
| 125 | + match witness_version { |
| 126 | + Fe32::Q => { |
| 127 | + for c in iter.with_checksum::<Bech32>(hrp).with_witness_version(Fe32::Q).chars() { |
| 128 | + fmt.write_char(c)?; |
| 129 | + } |
| 130 | + } |
| 131 | + version => { |
| 132 | + for c in iter.with_checksum::<Bech32m>(hrp).with_witness_version(version).chars() { |
| 133 | + fmt.write_char(c)?; |
| 134 | + } |
| 135 | + } |
| 136 | + } |
| 137 | + Ok(()) |
| 138 | +} |
| 139 | + |
| 140 | +/// Encodes a segwit address to a writer ([`fmt::Write`]) using uppercase characters. |
| 141 | +/// |
| 142 | +/// This is provided for use when creating QR codes. |
| 143 | +/// |
| 144 | +/// Does not check the validity of the witness version and witness program lengths (see |
| 145 | +/// the [`crate::primitives::segwit`] module for validation functions). |
| 146 | +pub fn encode_to_fmt_unchecked_uppercase<W: fmt::Write>( |
| 147 | + fmt: &mut W, |
| 148 | + hrp: &Hrp, |
| 149 | + witness_version: Fe32, |
| 150 | + witness_program: &[u8], |
| 151 | +) -> fmt::Result { |
| 152 | + let iter = witness_program.iter().copied().bytes_to_fes(); |
| 153 | + match witness_version { |
| 154 | + Fe32::Q => { |
| 155 | + for c in iter.with_checksum::<Bech32>(hrp).with_witness_version(Fe32::Q).chars() { |
| 156 | + fmt.write_char(c.to_ascii_uppercase())?; |
| 157 | + } |
| 158 | + } |
| 159 | + version => { |
| 160 | + for c in iter.with_checksum::<Bech32m>(hrp).with_witness_version(version).chars() { |
| 161 | + fmt.write_char(c.to_ascii_uppercase())?; |
| 162 | + } |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + Ok(()) |
| 167 | +} |
| 168 | + |
| 169 | +/// An error while constructing a [`SegwitHrpstring`] type. |
| 170 | +#[derive(Debug, Clone, PartialEq, Eq)] |
| 171 | +pub enum EncodeError { |
| 172 | + /// Invalid witness version (must be 0-16 inclusive). |
| 173 | + WitnessVersion(InvalidWitnessVersionError), |
| 174 | + /// Invalid witness length. |
| 175 | + WitnessLength(WitnessLengthError), |
| 176 | + /// Writing to formatter failed. |
| 177 | + Write(fmt::Error), |
| 178 | +} |
| 179 | + |
| 180 | +impl fmt::Display for EncodeError { |
| 181 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 182 | + use EncodeError::*; |
| 183 | + |
| 184 | + match *self { |
| 185 | + WitnessVersion(ref e) => write_err!(f, "witness version"; e), |
| 186 | + WitnessLength(ref e) => write_err!(f, "witness length"; e), |
| 187 | + Write(ref e) => write_err!(f, "writing to formatter failed"; e), |
| 188 | + } |
| 189 | + } |
| 190 | +} |
| 191 | + |
| 192 | +#[cfg(feature = "std")] |
| 193 | +impl std::error::Error for EncodeError { |
| 194 | + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { |
| 195 | + use EncodeError::*; |
| 196 | + |
| 197 | + match *self { |
| 198 | + WitnessVersion(ref e) => Some(e), |
| 199 | + WitnessLength(ref e) => Some(e), |
| 200 | + Write(ref e) => Some(e), |
| 201 | + } |
| 202 | + } |
| 203 | +} |
| 204 | + |
| 205 | +impl From<InvalidWitnessVersionError> for EncodeError { |
| 206 | + fn from(e: InvalidWitnessVersionError) -> Self { Self::WitnessVersion(e) } |
| 207 | +} |
| 208 | + |
| 209 | +impl From<WitnessLengthError> for EncodeError { |
| 210 | + fn from(e: WitnessLengthError) -> Self { Self::WitnessLength(e) } |
| 211 | +} |
| 212 | + |
| 213 | +impl From<fmt::Error> for EncodeError { |
| 214 | + fn from(e: fmt::Error) -> Self { Self::Write(e) } |
| 215 | +} |
| 216 | + |
| 217 | +#[cfg(all(test, feature = "alloc"))] |
| 218 | +mod tests { |
| 219 | + use super::*; |
| 220 | + use crate::primitives::hrp; |
| 221 | + |
| 222 | + #[test] |
| 223 | + // Just shows we handle both v0 and v1 addresses, for complete test |
| 224 | + // coverage see primitives submodules and test vectors. |
| 225 | + fn roundtrip_valid_mainnet_addresses() { |
| 226 | + // A few recent addresses from mainnet (Block 801266). |
| 227 | + let addresses = vec![ |
| 228 | + "bc1q2s3rjwvam9dt2ftt4sqxqjf3twav0gdx0k0q2etxflx38c3x8tnssdmnjq", // Segwit v0 |
| 229 | + "bc1py3m7vwnghyne9gnvcjw82j7gqt2rafgdmlmwmqnn3hvcmdm09rjqcgrtxs", // Segwit v1 |
| 230 | + ]; |
| 231 | + |
| 232 | + for address in addresses { |
| 233 | + let (hrp, version, program) = decode(address).expect("failed to decode valid address"); |
| 234 | + let encoded = encode(&hrp, version, &program).expect("failed to encode address"); |
| 235 | + assert_eq!(encoded, address); |
| 236 | + } |
| 237 | + } |
| 238 | + |
| 239 | + fn witness_program() -> [u8; 20] { |
| 240 | + [ |
| 241 | + 0x75, 0x1e, 0x76, 0xe8, 0x19, 0x91, 0x96, 0xd4, 0x54, 0x94, 0x1c, 0x45, 0xd1, 0xb3, |
| 242 | + 0xa3, 0x23, 0xf1, 0x43, 0x3b, 0xd6, |
| 243 | + ] |
| 244 | + } |
| 245 | + |
| 246 | + #[test] |
| 247 | + fn encode_to_fmt_lowercase() { |
| 248 | + let program = witness_program(); |
| 249 | + let mut address = String::new(); |
| 250 | + encode_to_fmt_unchecked(&mut address, &hrp::BC, Fe32::Q, &program) |
| 251 | + .expect("failed to encode address to QR code"); |
| 252 | + |
| 253 | + let want = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"; |
| 254 | + assert_eq!(address, want); |
| 255 | + } |
| 256 | + |
| 257 | + #[test] |
| 258 | + fn encode_to_fmt_uppercase() { |
| 259 | + let program = witness_program(); |
| 260 | + let mut address = String::new(); |
| 261 | + encode_to_fmt_unchecked_uppercase(&mut address, &hrp::BC, Fe32::Q, &program) |
| 262 | + .expect("failed to encode address to QR code"); |
| 263 | + |
| 264 | + let want = "BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4"; |
| 265 | + assert_eq!(address, want); |
| 266 | + } |
| 267 | +} |
0 commit comments