Skip to content

Commit d9b2684

Browse files
committed
fix(bolt12): Make CurrencyCode a validated wrapper type
Convert CurrencyCode from type alias to struct with validation, ensuring ISO 4217 compliance (3 ASCII uppercase letters) at construction time rather than parsing time.
1 parent 78fee88 commit d9b2684

File tree

4 files changed

+112
-10
lines changed

4 files changed

+112
-10
lines changed

lightning/src/offers/invoice_request.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1468,7 +1468,7 @@ mod tests {
14681468
#[cfg(c_bindings)]
14691469
use crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder;
14701470
use crate::offers::offer::{
1471-
Amount, ExperimentalOfferTlvStreamRef, OfferTlvStreamRef, Quantity,
1471+
Amount, CurrencyCode, ExperimentalOfferTlvStreamRef, OfferTlvStreamRef, Quantity,
14721472
};
14731473
use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
14741474
use crate::offers::payer::PayerTlvStreamRef;
@@ -1997,7 +1997,10 @@ mod tests {
19971997
assert_eq!(tlv_stream.amount, None);
19981998

19991999
let invoice_request = OfferBuilder::new(recipient_pubkey())
2000-
.amount(Amount::Currency { iso4217_code: *b"USD", amount: 10 })
2000+
.amount(Amount::Currency {
2001+
iso4217_code: CurrencyCode::from_str("USD").unwrap(),
2002+
amount: 10,
2003+
})
20012004
.build_unchecked()
20022005
.request_invoice(&expanded_key, nonce, &secp_ctx, payment_id)
20032006
.unwrap()
@@ -2372,7 +2375,10 @@ mod tests {
23722375

23732376
let invoice_request = OfferBuilder::new(recipient_pubkey())
23742377
.description("foo".to_string())
2375-
.amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
2378+
.amount(Amount::Currency {
2379+
iso4217_code: CurrencyCode::from_str("USD").unwrap(),
2380+
amount: 1000,
2381+
})
23762382
.build_unchecked()
23772383
.request_invoice(&expanded_key, nonce, &secp_ctx, payment_id)
23782384
.unwrap()

lightning/src/offers/merkle.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,7 @@ mod tests {
287287
use crate::ln::inbound_payment::ExpandedKey;
288288
use crate::offers::invoice_request::{InvoiceRequest, UnsignedInvoiceRequest};
289289
use crate::offers::nonce::Nonce;
290-
use crate::offers::offer::{Amount, OfferBuilder};
290+
use crate::offers::offer::{Amount, CurrencyCode, OfferBuilder};
291291
use crate::offers::parse::Bech32Encode;
292292
use crate::offers::signer::Metadata;
293293
use crate::offers::test_utils::recipient_pubkey;
@@ -355,7 +355,10 @@ mod tests {
355355
// BOLT 12 test vectors
356356
let invoice_request = OfferBuilder::new(recipient_pubkey)
357357
.description("A Mathematical Treatise".into())
358-
.amount(Amount::Currency { iso4217_code: *b"USD", amount: 100 })
358+
.amount(Amount::Currency {
359+
iso4217_code: CurrencyCode::from_str("USD").unwrap(),
360+
amount: 100,
361+
})
359362
.build_unchecked()
360363
// Override the payer metadata and signing pubkey to match the test vectors
361364
.request_invoice(&expanded_key, nonce, &secp_ctx, payment_id)

lightning/src/offers/offer.rs

Lines changed: 96 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -999,7 +999,9 @@ impl OfferContents {
999999
let (currency, amount) = match &self.amount {
10001000
None => (None, None),
10011001
Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
1002-
Some(Amount::Currency { iso4217_code, amount }) => (Some(iso4217_code), Some(*amount)),
1002+
Some(Amount::Currency { iso4217_code, amount }) => {
1003+
(Some(iso4217_code.as_bytes()), Some(*amount))
1004+
},
10031005
};
10041006

10051007
let features = {
@@ -1076,7 +1078,61 @@ pub enum Amount {
10761078
}
10771079

10781080
/// An ISO 4217 three-letter currency code (e.g., USD).
1079-
pub type CurrencyCode = [u8; 3];
1081+
///
1082+
/// Currency codes must be exactly 3 ASCII uppercase letters.
1083+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1084+
pub struct CurrencyCode([u8; 3]);
1085+
1086+
impl CurrencyCode {
1087+
/// Creates a new CurrencyCode from a 3-byte array.
1088+
///
1089+
/// Returns an error if the bytes are not valid UTF-8 or not all ASCII uppercase.
1090+
pub fn new(code: [u8; 3]) -> Result<Self, Bolt12SemanticError> {
1091+
let currency_str =
1092+
core::str::from_utf8(&code).map_err(|_| Bolt12SemanticError::InvalidCurrencyCode)?;
1093+
1094+
if !currency_str.chars().all(|c| c.is_ascii_uppercase()) {
1095+
return Err(Bolt12SemanticError::InvalidCurrencyCode);
1096+
}
1097+
1098+
Ok(Self(code))
1099+
}
1100+
1101+
/// Creates a CurrencyCode from a string slice.
1102+
///
1103+
/// Returns an error if the string is not exactly 3 ASCII uppercase letters.
1104+
pub fn from_str(s: &str) -> Result<Self, Bolt12SemanticError> {
1105+
if s.len() != 3 {
1106+
return Err(Bolt12SemanticError::InvalidCurrencyCode);
1107+
}
1108+
1109+
let mut code = [0u8; 3];
1110+
code.copy_from_slice(s.as_bytes());
1111+
Self::new(code)
1112+
}
1113+
1114+
/// Returns the currency code as a byte array.
1115+
pub fn as_bytes(&self) -> &[u8; 3] {
1116+
&self.0
1117+
}
1118+
1119+
/// Returns the currency code as a string slice.
1120+
pub fn as_str(&self) -> &str {
1121+
unsafe { core::str::from_utf8_unchecked(&self.0) }
1122+
}
1123+
}
1124+
1125+
impl AsRef<[u8]> for CurrencyCode {
1126+
fn as_ref(&self) -> &[u8] {
1127+
&self.0
1128+
}
1129+
}
1130+
1131+
impl core::fmt::Display for CurrencyCode {
1132+
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1133+
f.write_str(self.as_str())
1134+
}
1135+
}
10801136

10811137
/// Quantity of items supported by an [`Offer`].
10821138
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -1115,7 +1171,7 @@ const OFFER_ISSUER_ID_TYPE: u64 = 22;
11151171
tlv_stream!(OfferTlvStream, OfferTlvStreamRef<'a>, OFFER_TYPES, {
11161172
(2, chains: (Vec<ChainHash>, WithoutLength)),
11171173
(OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
1118-
(6, currency: CurrencyCode),
1174+
(6, currency: [u8; 3]),
11191175
(8, amount: (u64, HighZeroBytesDroppedBigSize)),
11201176
(10, description: (String, WithoutLength)),
11211177
(12, features: (OfferFeatures, WithoutLength)),
@@ -1209,7 +1265,10 @@ impl TryFrom<FullOfferTlvStream> for OfferContents {
12091265
},
12101266
(None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
12111267
(Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
1212-
(Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
1268+
(Some(currency_bytes), Some(amount)) => {
1269+
let iso4217_code = CurrencyCode::new(currency_bytes)?;
1270+
Some(Amount::Currency { iso4217_code, amount })
1271+
},
12131272
};
12141273

12151274
if amount.is_some() && description.is_none() {
@@ -1273,6 +1332,7 @@ mod tests {
12731332
use crate::ln::inbound_payment::ExpandedKey;
12741333
use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
12751334
use crate::offers::nonce::Nonce;
1335+
use crate::offers::offer::CurrencyCode;
12761336
use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
12771337
use crate::offers::test_utils::*;
12781338
use crate::types::features::OfferFeatures;
@@ -1541,7 +1601,8 @@ mod tests {
15411601
#[test]
15421602
fn builds_offer_with_amount() {
15431603
let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1544-
let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1604+
let currency_amount =
1605+
Amount::Currency { iso4217_code: CurrencyCode::from_str("USD").unwrap(), amount: 10 };
15451606

15461607
let offer = OfferBuilder::new(pubkey(42)).amount_msats(1000).build().unwrap();
15471608
let tlv_stream = offer.as_tlv_stream();
@@ -1820,6 +1881,36 @@ mod tests {
18201881
Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)
18211882
),
18221883
}
1884+
1885+
let mut tlv_stream = offer.as_tlv_stream();
1886+
tlv_stream.0.amount = Some(1000);
1887+
tlv_stream.0.currency = Some(b"\xFF\xFE\xFD"); // invalid UTF-8 bytes
1888+
1889+
let mut encoded_offer = Vec::new();
1890+
tlv_stream.write(&mut encoded_offer).unwrap();
1891+
1892+
match Offer::try_from(encoded_offer) {
1893+
Ok(_) => panic!("expected error"),
1894+
Err(e) => assert_eq!(
1895+
e,
1896+
Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidCurrencyCode)
1897+
),
1898+
}
1899+
1900+
let mut tlv_stream = offer.as_tlv_stream();
1901+
tlv_stream.0.amount = Some(1000);
1902+
tlv_stream.0.currency = Some(b"usd"); // invalid ISO 4217 code
1903+
1904+
let mut encoded_offer = Vec::new();
1905+
tlv_stream.write(&mut encoded_offer).unwrap();
1906+
1907+
match Offer::try_from(encoded_offer) {
1908+
Ok(_) => panic!("expected error"),
1909+
Err(e) => assert_eq!(
1910+
e,
1911+
Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidCurrencyCode)
1912+
),
1913+
}
18231914
}
18241915

18251916
#[test]

lightning/src/offers/parse.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,8 @@ pub enum Bolt12SemanticError {
149149
MissingAmount,
150150
/// The amount exceeded the total bitcoin supply or didn't match an expected amount.
151151
InvalidAmount,
152+
/// The currency code did not contain valid ASCII uppercase letters.
153+
InvalidCurrencyCode,
152154
/// An amount was provided but was not sufficient in value.
153155
InsufficientAmount,
154156
/// An amount was provided but was not expected.

0 commit comments

Comments
 (0)