Skip to content

Commit

Permalink
Merge pull request #51 from BP-WG/baid58
Browse files Browse the repository at this point in the history
Add chunking support for Baid58-based ids
  • Loading branch information
dr-orlovsky authored Jul 25, 2023
2 parents e44b479 + 67d5c69 commit 848a153
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 35 deletions.
12 changes: 9 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dbc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ path = "src/lib.rs"

[dependencies]
amplify = { workspace = true }
baid58 = "0.4.1"
base85 = "1.1.1"
strict_encoding = { workspace = true }
commit_verify = { workspace = true, features = ["rand"] }
bp-primitives = { version = "0.10.6", path = "../primitives" }
Expand Down
49 changes: 28 additions & 21 deletions dbc/src/tapret/tapscript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fmt::{self, Display, Formatter};
use std::io;
use std::str::FromStr;

use amplify::confinement::Confined;
use baid58::{Baid58ParseError, FromBaid58, ToBaid58};
use bc::{TapCode, TapScript};
use commit_verify::{mpc, CommitEncode, CommitVerify};
use strict_encoding::{StrictDeserialize, StrictSerialize};
use strict_encoding::{DecodeError, DeserializeError, StrictDeserialize, StrictSerialize};

use super::Lnpbp12;
use crate::LIB_NAME_BPCORE;
Expand All @@ -39,8 +39,7 @@ pub const TAPRET_SCRIPT_COMMITMENT_PREFIX: [u8; 31] = [
];

/// Information about tapret commitment.
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Display)]
#[display(Self::to_baid58_string)]
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_BPCORE)]
#[derive(CommitEncode)]
Expand All @@ -66,23 +65,32 @@ impl From<[u8; 33]> for TapretCommitment {
}
}

impl ToBaid58<33> for TapretCommitment {
const HRI: &'static str = "tapret";
fn to_baid58_payload(&self) -> [u8; 33] {
let mut data = io::Cursor::new([0u8; 33]);
self.commit_encode(&mut data);
data.into_inner()
impl TapretCommitment {
/// Returns serialized representation of the commitment data.
pub fn to_vec(&self) -> Vec<u8> {
self.to_strict_serialized::<33>()
.expect("exact size match")
.into_inner()
}
}
impl FromBaid58<33> for TapretCommitment {}

impl TapretCommitment {
fn to_baid58_string(&self) -> String { format!("{:0^}", self.to_baid58()) }
impl Display for TapretCommitment {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let s = base85::encode(&self.to_vec());
f.write_str(&s)
}
}

impl FromStr for TapretCommitment {
type Err = Baid58ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> { Self::from_baid58_str(s) }
type Err = DeserializeError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let data = base85::decode(s).ok_or_else(|| {
DecodeError::DataIntegrityError(format!(
"invalid Base85 encoding of tapret data \"{s}\""
))
})?;
let data = Confined::try_from(data).map_err(DecodeError::from)?;
Self::from_strict_serialized::<33>(data)
}
}

impl TapretCommitment {
Expand Down Expand Up @@ -110,12 +118,14 @@ impl CommitVerify<TapretCommitment, Lnpbp12> for TapScript {
#[cfg(test)]
mod test {
use amplify::RawArray;
use commit_verify::{Digest, Sha256};

use super::*;

pub fn commitment() -> TapretCommitment {
let msg = Sha256::digest("test data");
TapretCommitment {
mpc: mpc::Commitment::from_raw_array([0x6Cu8; 32]),
mpc: mpc::Commitment::from_raw_array(msg),
nonce: 8,
}
}
Expand All @@ -137,11 +147,8 @@ mod test {
#[test]
pub fn tapret_commitment_baid58() {
let commitment = commitment();
let encoded = commitment.to_baid58();
let decoded = TapretCommitment::from_baid58(encoded).unwrap();
let s = commitment.to_string();
assert_eq!(s, "tapret04dm9azJKdXhE27U4MHX8GsmibZEJ6WBMNmeKXGLPJDNaLPKNm9R");
assert_eq!(s, "k#7JerF92P=PEN7cf&`GWfS*?rIEdfEup1%zausI2m");
assert_eq!(Ok(commitment.clone()), TapretCommitment::from_str(&s));
assert_eq!(decoded, commitment);
}
}
2 changes: 1 addition & 1 deletion seals/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ amplify = { workspace = true }
single_use_seals = { workspace = true }
commit_verify = { workspace = true }
strict_encoding = { workspace = true }
baid58 = "0.4.1"
baid58 = "0.4.4"
bp-primitives = { version = "0.10.6", path = "../primitives" }
bp-dbc = { version = "0.10.6", path = "../dbc" }
rand = "0.8.5"
Expand Down
28 changes: 19 additions & 9 deletions seals/src/txout/blind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use std::hash::Hash;
use std::str::FromStr;

use amplify::{hex, Bytes32, Wrapper};
use baid58::{Baid58ParseError, FromBaid58, ToBaid58};
use baid58::{Baid58ParseError, Chunking, FromBaid58, ToBaid58, CHUNKING_32CHECKSUM};
use bc::{Outpoint, Txid, Vout};
use commit_verify::{CommitVerify, Conceal};
use dbc::tapret::Lnpbp12;
Expand Down Expand Up @@ -334,13 +334,12 @@ where Self: TxoSeal
}

/// Blind version of transaction outpoint-based single-use-seal
#[derive(Wrapper, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display, From)]
#[derive(Wrapper, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, From)]
#[wrapper(Index, RangeOps, BorrowSlice, Hex)]
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[strict_type(lib = dbc::LIB_NAME_BPCORE)]
#[derive(CommitEncode)]
#[commit_encode(strategy = strict)]
#[display(Self::to_baid58_string)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
Expand All @@ -354,17 +353,25 @@ pub struct SecretSeal(

impl ToBaid58<32> for SecretSeal {
const HRI: &'static str = "utxob";
const CHUNKING: Option<Chunking> = CHUNKING_32CHECKSUM;
fn to_baid58_payload(&self) -> [u8; 32] { self.0.into_inner() }
fn to_baid58_string(&self) -> String { self.to_string() }
}
impl FromBaid58<32> for SecretSeal {}
impl FromStr for SecretSeal {
type Err = Baid58ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> { SecretSeal::from_baid58_str(s) }
fn from_str(s: &str) -> Result<Self, Self::Err> {
SecretSeal::from_baid58_maybe_chunked_str(s, ':', ' ')
}
}
impl SecretSeal {
/// Returns Baid58 string representation of the secret seal. Equal to
/// `Display`
pub fn to_baid58_string(&self) -> String { format!("{:0^}", self.to_baid58()) }
impl Display for SecretSeal {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
if f.alternate() {
write!(f, "{::^}", self.to_baid58())
} else {
write!(f, "{::^.3}", self.to_baid58())
}
}
}

impl From<Outpoint> for SecretSeal {
Expand Down Expand Up @@ -409,11 +416,14 @@ mod test {
}
.to_concealed_seal();

let baid58 = "utxob02eFrirURjqLnqR74AKRfdnc9MDpvSRjmZGmFPrw7nvuTe1wy83";
let baid58 = "utxob:2eFrirU-RjqLnqR74-AKRfdnc9M-DpvSRjmZG-mFPrw7nvu-Te1wy83";
assert_eq!(baid58, seal.to_string());
assert_eq!(baid58.replace('-', ""), format!("{seal:#}"));
assert_eq!(seal.to_string(), seal.to_baid58_string());
let reconstructed = SecretSeal::from_str(baid58).unwrap();
assert_eq!(reconstructed, seal);
let reconstructed = SecretSeal::from_str(&baid58.replace('-', "")).unwrap();
assert_eq!(reconstructed, seal);
}

#[test]
Expand Down

0 comments on commit 848a153

Please sign in to comment.