Skip to content

Commit

Permalink
BIP21 parser: add tests that cover rounding errors (#1073)
Browse files Browse the repository at this point in the history
* BIP21 parser: add tests that cover rounding errors

* Enable liquid feature in CI tests

* Move liquid BIP21 rounding test to liquid module

* Fix BIP21 amount parsing for Liquid

* Add test for reverse BIP21 amount parsing for Liquid

* Cargo fmt
  • Loading branch information
ok300 authored Aug 13, 2024
1 parent 575c261 commit 9503166
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 6 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ jobs:

- name: Run sdk-common tests
working-directory: libs/sdk-common
run: cargo test
run: cargo test --features liquid

- name: Check git status
env:
Expand Down
28 changes: 28 additions & 0 deletions libs/sdk-common/src/input_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,34 @@ pub(crate) mod tests {
Ok(())
}

/// BIP21 amounts which can lead to rounding errors.
/// The format is: (sat amount, BIP21 BTC amount)
pub(crate) fn get_bip21_rounding_test_vectors() -> Vec<(u64, f64)> {
vec![
(999, 0.0000_0999),
(1_000, 0.0000_1000),
(59_810, 0.0005_9810),
]
}

#[tokio::test]
async fn test_bitcoin_address_bip21_rounding() -> Result<()> {
for (amount_sat, amount_btc) in get_bip21_rounding_test_vectors() {
let addr = format!("bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?amount={amount_btc}");

match parse(&addr).await? {
InputType::BitcoinAddress {
address: addr_with_amount_parsed,
} => {
assert_eq!(addr_with_amount_parsed.amount_sat, Some(amount_sat));
}
_ => return Err(anyhow!("Invalid type parsed")),
}
}

Ok(())
}

#[tokio::test]
#[cfg(feature = "liquid")]
async fn test_liquid_address() -> Result<()> {
Expand Down
11 changes: 6 additions & 5 deletions libs/sdk-common/src/liquid/bip21.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use bitcoin::util::amount::ParseAmountError;
use bitcoin::Denomination;
use elements::{
address::{Address, AddressError, AddressParams},
hashes::hex::HexToArrayError,
issuance::AssetId,
};
use serde::Serialize;
use std::collections::HashMap;
use std::{num::ParseFloatError, str::FromStr, string::FromUtf8Error};
use std::{str::FromStr, string::FromUtf8Error};
use urlencoding::decode;

use crate::prelude::{Network, URISerializationError};
Expand Down Expand Up @@ -78,7 +80,7 @@ pub enum DeserializeError {
UnknownParameter,
AssetNotProvided,
InvalidString(FromUtf8Error),
InvalidAmount(ParseFloatError),
InvalidAmount(ParseAmountError),
InvalidAsset(HexToArrayError),
InvalidAddress(AddressError),
}
Expand Down Expand Up @@ -117,10 +119,9 @@ impl LiquidAddressData {
if let Some((key, val)) = pair.split_once('=') {
match key {
"amount" => {
let parsed_amount = val
.parse::<f64>()
amount_sat = bitcoin::Amount::from_str_in(val, Denomination::Bitcoin)
.map(|amt| Some(amt.to_sat()))
.map_err(DeserializeError::InvalidAmount)?;
amount_sat = Some((parsed_amount * 100_000_000.0) as u64);
}
"assetid" => {
val.parse::<AssetId>()
Expand Down
51 changes: 51 additions & 0 deletions libs/sdk-common/src/liquid/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,53 @@
pub mod bip21;
pub use bip21::*;

#[cfg(test)]
mod tests {
use anyhow::{anyhow, Result};
use elements::AssetId;

use crate::input_parser::tests::get_bip21_rounding_test_vectors;
use crate::input_parser::*;
use crate::liquid::LiquidAddressData;

#[tokio::test]
async fn test_liquid_address_bip21_rounding() -> Result<()> {
let asset_id = AssetId::LIQUID_BTC.to_string();
for (amount_sat, amount_btc) in get_bip21_rounding_test_vectors() {
let addr = format!("liquidnetwork:tlq1qqw5ur50rnvcx33vmljjtnez3hrtl6n7vs44tdj2c9fmnxrrgzgwnhw6jtpn8cljkmlr8tgfw9hemrr5y8u2nu024hhak3tpdk?amount={amount_btc}&assetid={asset_id}");

match parse(&addr).await? {
InputType::LiquidAddress {
address: addr_with_amount_parsed,
} => {
assert_eq!(addr_with_amount_parsed.amount_sat, Some(amount_sat));
}
_ => return Err(anyhow!("Invalid type parsed")),
}
}

Ok(())
}

#[tokio::test]
async fn test_liquid_address_bip21_rounding_reverse() -> Result<()> {
for (amount_sat, amount_btc) in get_bip21_rounding_test_vectors() {
let data = LiquidAddressData {
address: "tlq1qqw5ur50rnvcx33vmljjtnez3hrtl6n7vs44tdj2c9fmnxrrgzgwnhw6jtpn8cljkmlr8tgfw9hemrr5y8u2nu024hhak3tpdk".to_string(),
network: crate::model::Network::Bitcoin,
asset_id: Some(AssetId::LIQUID_BTC.to_string()),
amount_sat: Some(amount_sat),
label: None,
message: None,
};

let serialized = data
.to_uri()
.map_err(|e| anyhow!("BIP21 URI serialization error {e:?}"))?;

assert!(serialized.contains(&format!("amount={amount_btc}")));
}

Ok(())
}
}

0 comments on commit 9503166

Please sign in to comment.