New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Address to optimized QR string #581
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
b9d5200
Access Display and Formatter with fmt:: like in other places
RCasatta d18554e
Address to string conversion optimized for qr codes
RCasatta cac3f46
improve to_qr_string doc
RCasatta 104836a
implements alternate formatting for address
RCasatta 85ae82f
use the char trick to avoid allocation
RCasatta bc406bf
Use &mut dyn fmt::Write instead of bool
Kixunil 3158ced
document alternate formatting
RCasatta 0a91496
rename to_qr_string into to_qr_uri returning also the schema
RCasatta File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -36,7 +36,7 @@ | |
//! let address = Address::p2pkh(&public_key, Network::Bitcoin); | ||
//! ``` | ||
|
||
use std::fmt::{self, Display, Formatter}; | ||
use std::fmt; | ||
use std::str::FromStr; | ||
use std::error; | ||
|
||
|
@@ -352,10 +352,27 @@ impl Address { | |
pub fn script_pubkey(&self) -> script::Script { | ||
self.payload.script_pubkey() | ||
} | ||
|
||
/// Creates a URI string *bitcoin:address* optimized to be encoded in QR codes. | ||
/// | ||
/// If the address is bech32, both the schema and the address become uppercase. | ||
/// If the address is base58, the schema is lowercase and the address is left mixed case. | ||
/// | ||
/// Quoting BIP 173 "inside QR codes uppercase SHOULD be used, as those permit the use of | ||
/// alphanumeric mode, which is 45% more compact than the normal byte mode." | ||
pub fn to_qr_uri(&self) -> String { | ||
let schema = match self.payload { | ||
Payload::WitnessProgram { .. } => "BITCOIN", | ||
_ => "bitcoin", | ||
}; | ||
format!("{}:{:#}", schema, self) | ||
} | ||
} | ||
|
||
impl Display for Address { | ||
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { | ||
// Alternate formatting `{:#}` is used to return uppercase version of bech32 addresses which should | ||
// be used in QR codes, see [Address::to_qr_uri] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I suggest informing the readers of best practices:
|
||
impl fmt::Display for Address { | ||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||
match self.payload { | ||
Payload::PubkeyHash(ref hash) => { | ||
let mut prefixed = [0; 21]; | ||
|
@@ -381,17 +398,35 @@ impl Display for Address { | |
} => { | ||
let hrp = match self.network { | ||
Network::Bitcoin => "bc", | ||
Network::Testnet | Network::Signet => "tb", | ||
Network::Testnet | Network::Signet => "tb", | ||
Network::Regtest => "bcrt", | ||
}; | ||
sgeisler marked this conversation as resolved.
Show resolved
Hide resolved
|
||
let mut bech32_writer = bech32::Bech32Writer::new(hrp, fmt)?; | ||
let mut upper_writer; | ||
let writer = if fmt.alternate() { | ||
upper_writer = UpperWriter(fmt); | ||
&mut upper_writer as &mut dyn fmt::Write | ||
} else { | ||
fmt as &mut dyn fmt::Write | ||
}; | ||
let mut bech32_writer = bech32::Bech32Writer::new(hrp, writer)?; | ||
bech32::WriteBase32::write_u5(&mut bech32_writer, ver)?; | ||
bech32::ToBase32::write_base32(&prog, &mut bech32_writer) | ||
} | ||
} | ||
} | ||
} | ||
|
||
struct UpperWriter<W: fmt::Write>(W); | ||
|
||
impl<W: fmt::Write> fmt::Write for UpperWriter<W> { | ||
fn write_str(&mut self, s: &str) -> fmt::Result { | ||
for c in s.chars() { | ||
self.0.write_char(c.to_ascii_uppercase())?; | ||
} | ||
Ok(()) | ||
} | ||
} | ||
|
||
/// Extract the bech32 prefix. | ||
/// Returns the same slice when no prefix is found. | ||
fn find_bech32_prefix(bech32: &str) -> &str { | ||
|
@@ -743,4 +778,18 @@ mod tests { | |
hex_script!("001454d26dddb59c7073c6a197946ea1841951fa7a74") | ||
); | ||
} | ||
|
||
#[test] | ||
fn test_qr_string() { | ||
for el in ["132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM", "33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k"].iter() { | ||
let addr = Address::from_str(el).unwrap(); | ||
assert_eq!(addr.to_qr_uri(), format!("bitcoin:{}", el)); | ||
} | ||
|
||
for el in ["bcrt1q2nfxmhd4n3c8834pj72xagvyr9gl57n5r94fsl", "bc1qwqdg6squsna38e46795at95yu9atm8azzmyvckulcc7kytlcckxswvvzej"].iter() { | ||
let addr = Address::from_str(el).unwrap(); | ||
assert_eq!(addr.to_qr_uri(), format!("BITCOIN:{}", el.to_ascii_uppercase()) ); | ||
} | ||
} | ||
|
||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Still not sure about the best naming, since the function returns URI string, not URI object
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's good enough imo, I'm no fan of unneccesarily duplicating the signature in the name and the returned string is a valid URI.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I was thinking about this too since if we later add URI, then This will suck.
However, in reality, if you call a method like this you probably want to display it or encode it (e.g. using serde), not inspect its contents in the same way you would after parsing. It may be not beautiful, but it's pragmatic.