Created
September 28, 2022 21:55
-
-
Save 0ex-d/7942b8c2b2e40aa3c42a62bd7ca39699 to your computer and use it in GitHub Desktop.
A plugin for validating some selected cryptocurrency wallet address using regular expressions (regex). Note: TDD approach used
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_use] | |
extern crate lazy_static; | |
use regex::{Captures, Regex}; | |
// starts with "1" or "3" or "bc1" | |
// doesn’t contain ambiguous characters | |
// consists of uppercase or lowercase alphabetic and numeric characters | |
// except the uppercase letter "O", uppercase letter "I", lowercase letter "l", and the number "0" | |
// check that the string is 26-35 characters long | |
const BITCOIN_REG_EX: &str = r"([13]|bc1)[A-HJ-NP-Za-km-z1-9]{27,34}"; | |
fn main() {} | |
fn get_bitcoin_address(address: &str) -> Option<Captures> { | |
// use lazy-static crate for memoization since re-compiling RegEx are expensive | |
// https://crates.io/crates/lazy_static | |
lazy_static! { | |
static ref REGEX: Regex = Regex::new(BITCOIN_REG_EX).unwrap(); | |
} | |
if REGEX.is_match(address) == false { | |
return None; | |
} | |
// return regex match groups | |
Some(REGEX.captures(address).unwrap()) | |
} | |
#[cfg(test)] | |
mod test { | |
use super::*; | |
#[test] | |
fn it_should_be_valid_bitcoin_wallet_address() { | |
let addresses = vec![ | |
get_bitcoin_address("3J78t1WpEZ73CNmQviecrnyiWrnqRhWKXc"), | |
get_bitcoin_address("1dice8EMZmqKvrGE4Qc9bUFf9PX3xaYDp"), | |
]; | |
assert!(!addresses[0].is_none()); | |
assert!(!addresses[1].is_none()); | |
} | |
#[test] | |
fn it_should_be_invalid_bitcoin_wallet_address() { | |
let address = get_bitcoin_address("bc1nxr1srrr0xfkvy5r643hydnw9re59gtzzwf5pzr"); | |
assert!(address.is_none()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment