Skip to main content

smplx_sdk_test/
utils.rs

1use bitcoin_hashes::HashEngine;
2use sha2::{Digest, Sha256};
3
4use bip39::Mnemonic;
5
6use simplicityhl::elements::{AssetId, ContractHash, OutPoint, Script};
7use simplicityhl::simplicity::bitcoin;
8use simplicityhl::simplicity::bitcoin::secp256k1;
9use simplicityhl::simplicity::hashes::{Hash, sha256};
10
11/// Generates a radom menemonic with 12 words.
12///
13/// # Panics
14/// Panics if the underlying mnemonic generation fails (e.g. invalid word count configuration).
15#[must_use]
16pub fn random_mnemonic() -> String {
17    let mnemonic = Mnemonic::generate(12).expect("word count should be valid");
18
19    mnemonic.to_string()
20}
21
22/// Generates a hardcoded "unspendable" Taproot public key.
23///
24/// # Panics
25/// Panics if the hardcoded byte slice is not exactly 32 bytes or cannot be parsed into a valid `XOnlyPublicKey` (which should never happen statically).
26#[must_use]
27pub fn tr_unspendable_key() -> secp256k1::XOnlyPublicKey {
28    secp256k1::XOnlyPublicKey::from_slice(&[
29        0x50, 0x92, 0x9b, 0x74, 0xc1, 0xa0, 0x49, 0x54, 0xb7, 0x8b, 0x4b, 0x60, 0x35, 0xe9, 0x7a, 0x5e, 0x07, 0x8a,
30        0x5a, 0x0f, 0x28, 0xec, 0x96, 0xd5, 0x47, 0xbf, 0xee, 0x9a, 0xce, 0x80, 0x3a, 0xc0,
31    ])
32    .expect("key should be valid")
33}
34
35/// Calculates new sha256 midstate and binds generated entropy to the specific outpoint.
36#[must_use]
37pub fn asset_entropy(outpoint: &OutPoint, entropy: [u8; 32]) -> sha256::Midstate {
38    let contract_hash = ContractHash::from_byte_array(entropy);
39    AssetId::generate_asset_entropy(*outpoint, contract_hash)
40}
41
42/// Computes the BIP-340 tagged hash `sha256(sha256(tag) || sha256(tag) || data)`.
43#[must_use]
44pub fn tagged_hash(tag: &str, data: &[u8]) -> sha256::Hash {
45    let tag = sha256::Hash::hash(tag.as_bytes());
46
47    let mut eng = sha256::Hash::engine();
48    eng.input(tag.as_byte_array());
49    eng.input(tag.as_byte_array());
50    eng.input(data);
51
52    sha256::Hash::from_engine(eng)
53}
54
55/// Hashes arbitrary data with and additional `TapData` and tags.
56#[must_use]
57pub fn tap_data_hash(data: &[u8]) -> sha256::Hash {
58    tagged_hash("TapData", data)
59}
60
61/// Computes the SHA-256 hash of a given script and returns the resulting 32-byte array.
62#[must_use]
63pub fn hash_script(script: &Script) -> [u8; 32] {
64    let mut hasher = Sha256::new();
65
66    sha2::digest::Update::update(&mut hasher, script.as_bytes());
67    hasher.finalize().into()
68}
69
70/// Converts Satoshi amount into BTC.
71#[must_use]
72pub fn sat2btc(sat: u64) -> f64 {
73    bitcoin::Amount::from_sat(sat).to_btc()
74}
75
76/// Converts BTC amount into Satoshi.
77#[must_use]
78pub fn btc2sat(btc: u64) -> u64 {
79    bitcoin::Amount::from_int_btc(btc).to_sat()
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    #[test]
87    fn generates_mnemonic() {
88        let _ = random_mnemonic();
89    }
90
91    #[test]
92    fn tagged_hash_doubles_the_tag_digest() {
93        let data = [0x42_u8; 32];
94        let tag_digest = Sha256::digest(b"OracleNetworkV1/Price");
95
96        let mut expected = Sha256::new();
97        expected.update(tag_digest);
98        expected.update(tag_digest);
99        expected.update(data);
100
101        assert_eq!(
102            tagged_hash("OracleNetworkV1/Price", &data).to_byte_array(),
103            <[u8; 32]>::from(expected.finalize())
104        );
105    }
106
107    #[test]
108    fn tap_data_hash_is_tagged_with_tap_data() {
109        let data = b"payload";
110
111        assert_eq!(tap_data_hash(data), tagged_hash("TapData", data));
112    }
113
114    #[test]
115    #[allow(clippy::float_cmp)]
116    fn asset_entropy_and_unit_conversions_are_deterministic() {
117        // Elements Core 0.17 reference vector (also in rust-elements issuance tests).
118        let outpoint = "05a047c98e82a848dee94efcf32462b065198bebf2404d201ba2e06db30b28f4:0"
119            .parse()
120            .unwrap();
121
122        assert_eq!(
123            asset_entropy(&outpoint, [0; 32]).to_string(),
124            "746f447f691323502cad2ef646f932613d37a83aeaa2133185b316648df4b70a"
125        );
126        assert_eq!(sat2btc(123), 0.000_001_23);
127        assert_eq!(btc2sat(1), 100_000_000);
128    }
129}