From 94f4a6fe1ae6053ea18a6b9c0c16f2ba6cf2b40b Mon Sep 17 00:00:00 2001 From: Tommy Volk Date: Thu, 7 Nov 2024 10:27:29 -0600 Subject: [PATCH 1/6] chore(deps): remove unused bitcoin30 dep from modules/fedimint-wallet-server --- Cargo.lock | 1 - modules/fedimint-wallet-server/Cargo.toml | 1 - 2 files changed, 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 54b16dfacd6..ab41bdf04c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3437,7 +3437,6 @@ version = "0.5.0-alpha" dependencies = [ "anyhow", "async-trait", - "bitcoin 0.30.2", "bitcoin 0.32.4", "erased-serde", "fedimint-bitcoind", diff --git a/modules/fedimint-wallet-server/Cargo.toml b/modules/fedimint-wallet-server/Cargo.toml index 73a644ff6df..0ee82b44c7f 100644 --- a/modules/fedimint-wallet-server/Cargo.toml +++ b/modules/fedimint-wallet-server/Cargo.toml @@ -19,7 +19,6 @@ path = "src/lib.rs" anyhow = { workspace = true } async-trait = { workspace = true } bitcoin = { workspace = true } -bitcoin30 = { workspace = true } erased-serde = { workspace = true } fedimint-bitcoind = { workspace = true } fedimint-core = { workspace = true } From 3498d49c196c3a2daf272ae3a1d7c56400d001d9 Mon Sep 17 00:00:00 2001 From: Tommy Volk Date: Thu, 7 Nov 2024 14:42:09 -0600 Subject: [PATCH 2/6] chore: implement Encodable and Decodable for bitcoin v0.32 sha256 hash --- fedimint-core/src/encoding/btc.rs | 34 +++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/fedimint-core/src/encoding/btc.rs b/fedimint-core/src/encoding/btc.rs index 3f4e091e31b..b9fdddb367d 100644 --- a/fedimint-core/src/encoding/btc.rs +++ b/fedimint-core/src/encoding/btc.rs @@ -3,16 +3,17 @@ use std::str::FromStr; use anyhow::format_err; use bitcoin::address::NetworkUnchecked; -use bitcoin30::hashes::Hash as BitcoinHash; +use bitcoin::hashes::Hash as BitcoinHash; use hex::{FromHex, ToHex}; use miniscript::{Descriptor, MiniscriptKey}; use super::SimpleBitcoinRead; use crate::bitcoin_migration::{ bitcoin29_to_bitcoin32_network_magic, bitcoin29_to_bitcoin32_psbt, - bitcoin30_to_bitcoin32_network, bitcoin32_checked_address_to_unchecked_address, - bitcoin32_to_bitcoin29_network_magic, bitcoin32_to_bitcoin29_psbt, - bitcoin32_to_bitcoin30_address, + bitcoin30_to_bitcoin32_network, bitcoin30_to_bitcoin32_sha256_hash, + bitcoin32_checked_address_to_unchecked_address, bitcoin32_to_bitcoin29_network_magic, + bitcoin32_to_bitcoin29_psbt, bitcoin32_to_bitcoin30_address, + bitcoin32_to_bitcoin30_sha256_hash, }; use crate::encoding::{Decodable, DecodeError, Encodable}; use crate::module::registry::ModuleDecoderRegistry; @@ -236,11 +237,28 @@ impl Decodable for bitcoin::Address { impl Encodable for bitcoin30::hashes::sha256::Hash { fn consensus_encode(&self, writer: &mut W) -> Result { - self.to_byte_array().consensus_encode(writer) + bitcoin30_to_bitcoin32_sha256_hash(self).consensus_encode(writer) } } impl Decodable for bitcoin30::hashes::sha256::Hash { + fn consensus_decode( + d: &mut D, + modules: &ModuleDecoderRegistry, + ) -> Result { + Ok(bitcoin32_to_bitcoin30_sha256_hash( + &Decodable::consensus_decode(d, modules)?, + )) + } +} + +impl Encodable for bitcoin::hashes::sha256::Hash { + fn consensus_encode(&self, writer: &mut W) -> Result { + self.to_byte_array().consensus_encode(writer) + } +} + +impl Decodable for bitcoin::hashes::sha256::Hash { fn consensus_decode( d: &mut D, modules: &ModuleDecoderRegistry, @@ -256,17 +274,17 @@ mod tests { use std::io::Cursor; use std::str::FromStr; - use bitcoin30::hashes::Hash as BitcoinHash; + use bitcoin::hashes::Hash as BitcoinHash; use crate::encoding::{Decodable, Encodable}; use crate::ModuleDecoderRegistry; #[test_log::test] fn sha256_roundtrip() { - let hash = bitcoin30::hashes::sha256::Hash::hash(b"Hello world!"); + let hash = bitcoin::hashes::sha256::Hash::hash(b"Hello world!"); let mut encoded = Vec::new(); hash.consensus_encode(&mut encoded).unwrap(); - let hash_decoded = bitcoin30::hashes::sha256::Hash::consensus_decode( + let hash_decoded = bitcoin::hashes::sha256::Hash::consensus_decode( &mut Cursor::new(encoded), &ModuleDecoderRegistry::default(), ) From 3bd0798b6a2733e1606efcfbd6734c028b77fe79 Mon Sep 17 00:00:00 2001 From: Tommy Volk Date: Fri, 8 Nov 2024 09:48:17 -0600 Subject: [PATCH 3/6] chore(deps): bump FederationId and ClientConfig to secp256k1 v0.29 --- crypto/derive-secret/src/lib.rs | 3 +-- fedimint-core/src/config.rs | 8 ++++---- fedimint-core/src/invite_code.rs | 2 +- fedimint-server/src/config/distributedgen.rs | 13 +++---------- fedimint-server/src/config/mod.rs | 2 +- modules/fedimint-mint-client/src/lib.rs | 11 ++++------- 6 files changed, 14 insertions(+), 25 deletions(-) diff --git a/crypto/derive-secret/src/lib.rs b/crypto/derive-secret/src/lib.rs index 6178301641d..207a2b64d9f 100644 --- a/crypto/derive-secret/src/lib.rs +++ b/crypto/derive-secret/src/lib.rs @@ -19,9 +19,8 @@ use bls12_381::Scalar; use fedimint_core::config::FederationId; use fedimint_core::encoding::{Decodable, Encodable}; use fedimint_core::secp256k1::{Keypair, Secp256k1, Signing}; -use fedimint_core::BitcoinHash; use hkdf::hashes::Sha512; -use hkdf::Hkdf; +use hkdf::{BitcoinHash, Hkdf}; use ring::aead; const CHILD_TAG: &[u8; 8] = b"childkey"; diff --git a/fedimint-core/src/config.rs b/fedimint-core/src/config.rs index ec7fd141b22..0cfa62f1901 100644 --- a/fedimint-core/src/config.rs +++ b/fedimint-core/src/config.rs @@ -6,16 +6,16 @@ use std::path::Path; use std::str::FromStr; use anyhow::{bail, format_err, Context}; +use bitcoin::hashes::sha256::{Hash as Sha256, HashEngine}; +use bitcoin::hashes::{hex, sha256, Hash as BitcoinHash}; use bitcoin29::hashes::hex::format_hex; -use bitcoin30::hashes::sha256::{Hash as Sha256, HashEngine}; -use bitcoin30::hashes::{hex, sha256}; use bls12_381::Scalar; use fedimint_core::core::{ModuleInstanceId, ModuleKind}; use fedimint_core::encoding::{DynRawFallback, Encodable}; use fedimint_core::module::registry::ModuleRegistry; use fedimint_core::task::Cancelled; use fedimint_core::util::SafeUrl; -use fedimint_core::{BitcoinHash, ModuleDecoderRegistry}; +use fedimint_core::ModuleDecoderRegistry; use fedimint_logging::LOG_CORE; use hex::FromHex; use secp256k1::PublicKey; @@ -216,7 +216,7 @@ impl GlobalClientConfig { /// 0.4.0 and later uses a hash of broadcast public keys to calculate the /// federation id. 0.3.x and earlier use a hash of api endpoints pub fn calculate_federation_id(&self) -> FederationId { - FederationId(self.api_endpoints.consensus_hash_bitcoin30()) + FederationId(self.api_endpoints.consensus_hash()) } /// Federation name from config metadata (if set) diff --git a/fedimint-core/src/invite_code.rs b/fedimint-core/src/invite_code.rs index f4621aabb3b..213ce8f329c 100644 --- a/fedimint-core/src/invite_code.rs +++ b/fedimint-core/src/invite_code.rs @@ -285,7 +285,7 @@ mod tests { peer: PeerId::new(0), }, crate::invite_code::InviteCodePart::FederationId(FederationId( - bitcoin30::hashes::sha256::Hash::from_str( + bitcoin::hashes::sha256::Hash::from_str( "bea7ff4116f2b1d324c7b5d699cce4ac7408cee41db2c88027e21b76fff3b9f4" ) .expect("valid hash") diff --git a/fedimint-server/src/config/distributedgen.rs b/fedimint-server/src/config/distributedgen.rs index e695bee34ee..d0b057411ca 100644 --- a/fedimint-server/src/config/distributedgen.rs +++ b/fedimint-server/src/config/distributedgen.rs @@ -9,9 +9,6 @@ use bitcoin::hashes::sha256::{Hash as Sha256, HashEngine}; use bitcoin::hashes::Hash as BitcoinHash; use bitcoin::secp256k1; use bls12_381::Scalar; -use fedimint_core::bitcoin_migration::{ - bitcoin30_to_bitcoin32_sha256_hash, bitcoin32_to_bitcoin30_sha256_hash, -}; use fedimint_core::config::{ DkgError, DkgGroup, DkgMessage, DkgPeerMsg, DkgResult, ISupportedDkgMessage, }; @@ -92,9 +89,7 @@ impl Dkg { let hashed = Dkg::hash(&commit); dkg.commitments.insert(our_id, commit); dkg.hashed_commits.insert(our_id, hashed); - let step = dkg.broadcast(&DkgMessage::HashedCommit( - bitcoin32_to_bitcoin30_sha256_hash(&hashed), - )); + let step = dkg.broadcast(&DkgMessage::HashedCommit(hashed)); (dkg, step) } @@ -104,12 +99,10 @@ impl Dkg { match msg { DkgMessage::HashedCommit(hashed) => { match self.hashed_commits.get(&peer) { - Some(old) if *old != bitcoin30_to_bitcoin32_sha256_hash(&hashed) => { + Some(old) if *old != hashed => { return Err(format_err!("{peer} sent us two hashes!")) } - _ => self - .hashed_commits - .insert(peer, bitcoin30_to_bitcoin32_sha256_hash(&hashed)), + _ => self.hashed_commits.insert(peer, hashed), }; if self.hashed_commits.len() == self.peers.len() { diff --git a/fedimint-server/src/config/mod.rs b/fedimint-server/src/config/mod.rs index 6e2be9fe6e2..d641bfe4aa9 100644 --- a/fedimint-server/src/config/mod.rs +++ b/fedimint-server/src/config/mod.rs @@ -268,7 +268,7 @@ impl ServerConfig { } pub fn calculate_federation_id(&self) -> FederationId { - FederationId(self.consensus.api_endpoints.consensus_hash_bitcoin30()) + FederationId(self.consensus.api_endpoints.consensus_hash()) } pub fn add_modules(&mut self, modules: BTreeMap) { diff --git a/modules/fedimint-mint-client/src/lib.rs b/modules/fedimint-mint-client/src/lib.rs index 8f9c1164a5c..9ad327bf63c 100644 --- a/modules/fedimint-mint-client/src/lib.rs +++ b/modules/fedimint-mint-client/src/lib.rs @@ -2382,7 +2382,6 @@ mod tests { use std::str::FromStr; use bitcoin_hashes::Hash; - use fedimint_core::bitcoin_migration::bitcoin32_to_bitcoin30_sha256_hash; use fedimint_core::config::FederationId; use fedimint_core::encoding::Decodable; use fedimint_core::invite_code::{InviteCode, InviteCodeV2}; @@ -2583,13 +2582,11 @@ mod tests { #[test] fn notes_encode_decode() { - let federation_id_1 = FederationId(bitcoin32_to_bitcoin30_sha256_hash( - &bitcoin_hashes::sha256::Hash::from_byte_array([0x21; 32]), - )); + let federation_id_1 = + FederationId(bitcoin_hashes::sha256::Hash::from_byte_array([0x21; 32])); let federation_id_prefix_1 = federation_id_1.to_prefix(); - let federation_id_2 = FederationId(bitcoin32_to_bitcoin30_sha256_hash( - &bitcoin_hashes::sha256::Hash::from_byte_array([0x42; 32]), - )); + let federation_id_2 = + FederationId(bitcoin_hashes::sha256::Hash::from_byte_array([0x42; 32])); let federation_id_prefix_2 = federation_id_2.to_prefix(); let notes = vec![( From 3cc4dffbe214e9ad7e40d0746512b345e07ba0b7 Mon Sep 17 00:00:00 2001 From: Tommy Volk Date: Fri, 8 Nov 2024 10:00:13 -0600 Subject: [PATCH 4/6] chore(deps): bump modules/fedimint-lnv2-* to bitcoin v0.32 --- Cargo.lock | 2 -- gateway/ln-gateway/src/gateway_module_v2/mod.rs | 4 +++- .../ln-gateway/src/gateway_module_v2/send_sm.rs | 6 ++++-- gateway/ln-gateway/src/lib.rs | 13 ++++++++++--- gateway/ln-gateway/src/lightning/lnd.rs | 7 ++++--- gateway/ln-gateway/tests/tests.rs | 6 +++--- modules/fedimint-lnv2-client/Cargo.toml | 1 - modules/fedimint-lnv2-client/src/lib.rs | 17 ++++++++++------- modules/fedimint-lnv2-common/Cargo.toml | 1 - modules/fedimint-lnv2-common/src/contracts.rs | 12 ++++++------ modules/fedimint-lnv2-common/src/lib.rs | 2 +- modules/fedimint-lnv2-tests/tests/mock.rs | 3 ++- 12 files changed, 43 insertions(+), 31 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ab41bdf04c4..aac59559089 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2783,7 +2783,6 @@ dependencies = [ "aquamarine", "async-stream", "async-trait", - "bitcoin 0.30.2", "bitcoin 0.32.4", "clap", "erased-serde", @@ -2809,7 +2808,6 @@ version = "0.5.0-alpha" dependencies = [ "anyhow", "async-trait", - "bitcoin 0.30.2", "bitcoin 0.32.4", "fedimint-api-client", "fedimint-core", diff --git a/gateway/ln-gateway/src/gateway_module_v2/mod.rs b/gateway/ln-gateway/src/gateway_module_v2/mod.rs index 8d075a89662..e734b9bcfa4 100644 --- a/gateway/ln-gateway/src/gateway_module_v2/mod.rs +++ b/gateway/ln-gateway/src/gateway_module_v2/mod.rs @@ -20,6 +20,7 @@ use fedimint_client::transaction::{ ClientOutput, ClientOutputBundle, ClientOutputSM, TransactionBuilder, }; use fedimint_client::{sm_enum_variant_translation, DynGlobalClientContext}; +use fedimint_core::bitcoin_migration::bitcoin30_to_bitcoin32_sha256_hash; use fedimint_core::config::FederationId; use fedimint_core::core::{Decoder, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId}; use fedimint_core::db::DatabaseTransaction; @@ -294,7 +295,8 @@ impl GatewayClientModuleV2 { }; ensure!( - PaymentImage::Hash(*payment_hash) == payload.contract.payment_image, + PaymentImage::Hash(bitcoin30_to_bitcoin32_sha256_hash(payment_hash)) + == payload.contract.payment_image, "The invoices payment hash does not match the contracts payment hash" ); diff --git a/gateway/ln-gateway/src/gateway_module_v2/send_sm.rs b/gateway/ln-gateway/src/gateway_module_v2/send_sm.rs index 016b1bf246b..60bf3edeba5 100644 --- a/gateway/ln-gateway/src/gateway_module_v2/send_sm.rs +++ b/gateway/ln-gateway/src/gateway_module_v2/send_sm.rs @@ -3,7 +3,9 @@ use std::fmt; use fedimint_client::sm::{ClientSMDatabaseTransaction, State, StateTransition}; use fedimint_client::transaction::{ClientInput, ClientInputBundle}; use fedimint_client::DynGlobalClientContext; -use fedimint_core::bitcoin_migration::bitcoin32_to_bitcoin30_secp256k1_pubkey; +use fedimint_core::bitcoin_migration::{ + bitcoin30_to_bitcoin32_sha256_hash, bitcoin32_to_bitcoin30_secp256k1_pubkey, +}; use fedimint_core::core::OperationId; use fedimint_core::encoding::{Decodable, Encodable}; use fedimint_core::secp256k1::Keypair; @@ -174,7 +176,7 @@ impl SendStateMachine { let (contract, client) = context .gateway .get_registered_incoming_contract_and_client_v2( - PaymentImage::Hash(*invoice.payment_hash()), + PaymentImage::Hash(bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash())), invoice .amount_milli_satoshis() .expect("The amount invoice has been checked previously"), diff --git a/gateway/ln-gateway/src/lib.rs b/gateway/ln-gateway/src/lib.rs index e98c779987d..531946d56b0 100644 --- a/gateway/ln-gateway/src/lib.rs +++ b/gateway/ln-gateway/src/lib.rs @@ -47,6 +47,9 @@ use fedimint_bip39::{Bip39RootSecretStrategy, Language, Mnemonic}; use fedimint_client::module::init::ClientModuleInitRegistry; use fedimint_client::secret::RootSecretStrategy; use fedimint_client::{Client, ClientHandleArc}; +use fedimint_core::bitcoin_migration::{ + bitcoin30_to_bitcoin32_sha256_hash, bitcoin32_to_bitcoin30_sha256_hash, +}; use fedimint_core::config::FederationId; use fedimint_core::core::{ ModuleInstanceId, ModuleKind, LEGACY_HARDCODED_INSTANCE_ID_MINT, @@ -665,7 +668,9 @@ impl Gateway { // not a Fedimint. let (contract, client) = self .get_registered_incoming_contract_and_client_v2( - PaymentImage::Hash(htlc_request.payment_hash), + PaymentImage::Hash(bitcoin30_to_bitcoin32_sha256_hash( + &htlc_request.payment_hash, + )), htlc_request.amount_msat, ) .await?; @@ -2037,7 +2042,7 @@ impl Gateway { let invoice = self .create_invoice_via_lnrpc_v2( - payment_hash, + bitcoin32_to_bitcoin30_sha256_hash(&payment_hash), payload.amount, payload.description.clone(), payload.expiry_secs, @@ -2097,7 +2102,9 @@ impl Gateway { payment_hash: Some(payment_hash), amount_msat: amount.msats, expiry_secs: expiry_time, - description: Some(InvoiceDescription::Hash(hash)), + description: Some(InvoiceDescription::Hash( + bitcoin32_to_bitcoin30_sha256_hash(&hash), + )), }) .await? } diff --git a/gateway/ln-gateway/src/lightning/lnd.rs b/gateway/ln-gateway/src/lightning/lnd.rs index 2d9a431e8eb..84eb2cb5ba6 100644 --- a/gateway/ln-gateway/src/lightning/lnd.rs +++ b/gateway/ln-gateway/src/lightning/lnd.rs @@ -6,7 +6,8 @@ use std::time::Duration; use anyhow::ensure; use async_trait::async_trait; -use bitcoin_hashes::{sha256, Hash}; +use bitcoin::hashes::{sha256, Hash}; +use bitcoin_hashes::Hash as Bitcoin30Hash; use fedimint_core::db::Database; use fedimint_core::task::{sleep, TaskGroup}; use fedimint_core::{secp256k1, Amount, BitcoinAmountOrAll}; @@ -175,7 +176,7 @@ impl GatewayLndClient { if hold.state() == InvoiceState::Accepted { let intercept = InterceptPaymentRequest { - payment_hash: Hash::from_slice(&hold.r_hash.clone()) + payment_hash: Bitcoin30Hash::from_slice(&hold.r_hash.clone()) .expect("Failed to convert to Hash"), amount_msat: hold.amt_paid_msat as u64, // The rest of the fields are not used in LNv2 and can be removed once LNv1 @@ -421,7 +422,7 @@ impl GatewayLndClient { // Forward all HTLCs to gatewayd, gatewayd will filter them based on scid let intercept = InterceptPaymentRequest { - payment_hash: Hash::from_slice(&htlc.payment_hash).expect("Failed to convert payment Hash"), + payment_hash: Bitcoin30Hash::from_slice(&htlc.payment_hash).expect("Failed to convert payment Hash"), amount_msat: htlc.outgoing_amount_msat, expiry: htlc.incoming_expiry, short_channel_id: Some(htlc.outgoing_requested_chan_id), diff --git a/gateway/ln-gateway/tests/tests.rs b/gateway/ln-gateway/tests/tests.rs index 8271bee670d..03974661a51 100644 --- a/gateway/ln-gateway/tests/tests.rs +++ b/gateway/ln-gateway/tests/tests.rs @@ -981,7 +981,7 @@ async fn lnv2_incoming_contract_with_invalid_preimage_is_refunded() -> anyhow::R tpe::AggregatePublicKey(G1Affine::generator()), [42; 32], [0; 32], - PaymentImage::Hash([0_u8; 32].consensus_hash_bitcoin30()), + PaymentImage::Hash([0_u8; 32].consensus_hash()), Amount::from_sats(1000), u64::MAX, Keypair::new(secp256k1::SECP256K1, &mut rand::thread_rng()).public_key(), @@ -1025,7 +1025,7 @@ async fn lnv2_expired_incoming_contract_is_rejected() -> anyhow::Result<()> { .tpe_agg_pk, [42; 32], [0; 32], - PaymentImage::Hash([0_u8; 32].consensus_hash_bitcoin30()), + PaymentImage::Hash([0_u8; 32].consensus_hash()), Amount::from_sats(1000), 0, // this incoming contract expired on the 1st of January 1970 Keypair::new(secp256k1::SECP256K1, &mut rand::thread_rng()).public_key(), @@ -1069,7 +1069,7 @@ async fn lnv2_malleated_incoming_contract_is_rejected() -> anyhow::Result<()> { .tpe_agg_pk, [42; 32], [0; 32], - PaymentImage::Hash([0_u8; 32].consensus_hash_bitcoin30()), + PaymentImage::Hash([0_u8; 32].consensus_hash()), Amount::from_sats(1000), u64::MAX, Keypair::new(secp256k1::SECP256K1, &mut rand::thread_rng()).public_key(), diff --git a/modules/fedimint-lnv2-client/Cargo.toml b/modules/fedimint-lnv2-client/Cargo.toml index 8a95cd81306..956e23abc14 100644 --- a/modules/fedimint-lnv2-client/Cargo.toml +++ b/modules/fedimint-lnv2-client/Cargo.toml @@ -24,7 +24,6 @@ aquamarine = { workspace = true } async-stream = { workspace = true } async-trait = { workspace = true } bitcoin = { workspace = true } -bitcoin30 = { workspace = true } clap = { workspace = true, optional = true } erased-serde = { workspace = true } fedimint-api-client = { workspace = true } diff --git a/modules/fedimint-lnv2-client/src/lib.rs b/modules/fedimint-lnv2-client/src/lib.rs index 65084a84e76..bf46a04db09 100644 --- a/modules/fedimint-lnv2-client/src/lib.rs +++ b/modules/fedimint-lnv2-client/src/lib.rs @@ -16,8 +16,8 @@ use std::sync::Arc; use std::time::Duration; use async_stream::stream; +use bitcoin::hashes::{sha256, Hash}; use bitcoin::secp256k1; -use bitcoin30::hashes::{sha256, Hash}; use db::GatewayKey; use fedimint_api_client::api::DynModuleApi; use fedimint_client::module::init::{ClientModuleInit, ClientModuleInitArgs}; @@ -31,7 +31,8 @@ use fedimint_client::transaction::{ }; use fedimint_client::{sm_enum_variant_translation, DynGlobalClientContext}; use fedimint_core::bitcoin_migration::{ - bitcoin30_to_bitcoin32_secp256k1_pubkey, bitcoin32_to_bitcoin30_network, + bitcoin30_to_bitcoin32_secp256k1_pubkey, bitcoin30_to_bitcoin32_sha256_hash, + bitcoin32_to_bitcoin30_network, }; use fedimint_core::config::FederationId; use fedimint_core::core::{IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId}; @@ -548,7 +549,9 @@ impl LightningClientModule { .map_err(|e| SendPaymentError::FederationError(e.to_string()))?; let contract = OutgoingContract { - payment_image: PaymentImage::Hash(*invoice.payment_hash()), + payment_image: PaymentImage::Hash(bitcoin30_to_bitcoin32_sha256_hash( + invoice.payment_hash(), + )), amount: send_fee.add_to(amount), expiration: consensus_block_count + expiration_delta + CONTRACT_CONFIRMATION_BUFFER, claim_pk: routing_info.module_public_key, @@ -775,11 +778,11 @@ impl LightningClientModule { let (ephemeral_tweak, ephemeral_pk) = generate_ephemeral_tweak(recipient_static_pk); let encryption_seed = ephemeral_tweak - .consensus_hash_bitcoin30::() + .consensus_hash::() .to_byte_array(); let preimage = encryption_seed - .consensus_hash_bitcoin30::() + .consensus_hash::() .to_byte_array(); let (gateway, routing_info) = match gateway { @@ -823,7 +826,7 @@ impl LightningClientModule { self.cfg.tpe_agg_pk, encryption_seed, preimage, - PaymentImage::Hash(preimage.consensus_hash_bitcoin30()), + PaymentImage::Hash(preimage.consensus_hash()), contract_amount, expiration, claim_pk, @@ -909,7 +912,7 @@ impl LightningClientModule { .secret_bytes(); let encryption_seed = ephemeral_tweak - .consensus_hash_bitcoin30::() + .consensus_hash::() .to_byte_array(); let claim_keypair = self diff --git a/modules/fedimint-lnv2-common/Cargo.toml b/modules/fedimint-lnv2-common/Cargo.toml index 90a9c9a7547..0cdd55e8abc 100644 --- a/modules/fedimint-lnv2-common/Cargo.toml +++ b/modules/fedimint-lnv2-common/Cargo.toml @@ -18,7 +18,6 @@ path = "src/lib.rs" anyhow = { workspace = true } async-trait = { workspace = true } bitcoin = { workspace = true } -bitcoin30 = { workspace = true } fedimint-api-client = { workspace = true } fedimint-core = { workspace = true } fedimint-ln-common = { workspace = true } diff --git a/modules/fedimint-lnv2-common/src/contracts.rs b/modules/fedimint-lnv2-common/src/contracts.rs index cf82e01a74d..05a3499a167 100644 --- a/modules/fedimint-lnv2-common/src/contracts.rs +++ b/modules/fedimint-lnv2-common/src/contracts.rs @@ -1,5 +1,5 @@ +use bitcoin::hashes::sha256; use bitcoin::secp256k1; -use bitcoin30::hashes::sha256; use fedimint_core::encoding::{Decodable, Encodable}; use fedimint_core::Amount; use secp256k1::schnorr::Signature; @@ -71,7 +71,7 @@ impl IncomingContract { } pub fn contract_id(&self) -> ContractId { - ContractId(self.consensus_hash_bitcoin30()) + ContractId(self.consensus_hash()) } pub fn verify(&self) -> bool { @@ -138,7 +138,7 @@ pub struct OutgoingContract { impl OutgoingContract { pub fn contract_id(&self) -> ContractId { - ContractId(self.consensus_hash_bitcoin30()) + ContractId(self.consensus_hash()) } pub fn forfeit_message(&self) -> Message { @@ -179,7 +179,7 @@ impl OutgoingContract { fn verify_preimage(payment_image: &PaymentImage, preimage: &[u8; 32]) -> bool { match payment_image { - PaymentImage::Hash(hash) => preimage.consensus_hash_bitcoin30::() == *hash, + PaymentImage::Hash(hash) => preimage.consensus_hash::() == *hash, PaymentImage::Point(pk) => match SecretKey::from_slice(preimage) { Ok(sk) => sk.public_key(secp256k1::SECP256K1) == *pk, Err(..) => false, @@ -189,10 +189,10 @@ fn verify_preimage(payment_image: &PaymentImage, preimage: &[u8; 32]) -> bool { #[test] fn test_verify_preimage() { - use bitcoin30::hashes::Hash; + use bitcoin::hashes::Hash; assert!(verify_preimage( - &PaymentImage::Hash(bitcoin30::hashes::sha256::Hash::hash(&[42; 32])), + &PaymentImage::Hash(bitcoin::hashes::sha256::Hash::hash(&[42; 32])), &[42; 32] )); diff --git a/modules/fedimint-lnv2-common/src/lib.rs b/modules/fedimint-lnv2-common/src/lib.rs index 132b1064e13..9523a614612 100644 --- a/modules/fedimint-lnv2-common/src/lib.rs +++ b/modules/fedimint-lnv2-common/src/lib.rs @@ -14,8 +14,8 @@ pub mod contracts; pub mod endpoint_constants; pub mod gateway_api; +use bitcoin::hashes::sha256; use bitcoin::secp256k1::schnorr::Signature; -use bitcoin30::hashes::sha256; use config::LightningClientConfig; use fedimint_core::core::{Decoder, ModuleInstanceId, ModuleKind}; use fedimint_core::encoding::{Decodable, Encodable}; diff --git a/modules/fedimint-lnv2-tests/tests/mock.rs b/modules/fedimint-lnv2-tests/tests/mock.rs index 2a9fc1e25b6..36b2f4f6a3d 100644 --- a/modules/fedimint-lnv2-tests/tests/mock.rs +++ b/modules/fedimint-lnv2-tests/tests/mock.rs @@ -4,6 +4,7 @@ use bitcoin::hashes::{sha256, Hash}; use bitcoin::secp256k1::{SecretKey, SECP256K1}; use fedimint_core::bitcoin_migration::{ bitcoin30_to_bitcoin32_keypair, bitcoin32_to_bitcoin30_secp256k1_secret_key, + bitcoin32_to_bitcoin30_sha256_hash, }; use fedimint_core::config::FederationId; use fedimint_core::secp256k1::rand::rngs::OsRng; @@ -119,7 +120,7 @@ impl GatewayConnection for MockGatewayConnection { expiry_time: u32, ) -> Result { let payment_hash = match contract.commitment.payment_image { - PaymentImage::Hash(payment_hash) => payment_hash, + PaymentImage::Hash(payment_hash) => bitcoin32_to_bitcoin30_sha256_hash(&payment_hash), PaymentImage::Point(..) => panic!("PaymentImage is not a payment hash"), }; From 341fc8941fbec5141d834d02cb8f65d54712d97b Mon Sep 17 00:00:00 2001 From: Tommy Volk Date: Fri, 8 Nov 2024 11:32:08 -0600 Subject: [PATCH 5/6] chore(deps): mostly bump bitcoin to v0.32 --- Cargo.lock | 6 +- devimint/src/external.rs | 9 +- devimint/src/tests.rs | 29 +-- fedimint-bitcoind/src/esplora.rs | 7 +- fedimint-core/src/bitcoin_migration.rs | 206 +----------------- fedimint-core/src/core/backup.rs | 4 +- fedimint-core/src/encoding/btc.rs | 24 +- fedimint-core/src/encoding/mod.rs | 21 +- fedimint-core/src/lib.rs | 31 ++- fedimint-core/src/net/api_announcement.rs | 17 +- fedimint-core/src/transaction.rs | 2 +- fedimint-core/src/txoproof.rs | 23 +- fedimint-testing/src/btc/mock.rs | 7 +- fedimint-testing/src/ln.rs | 2 +- gateway/ln-gateway/Cargo.toml | 1 - gateway/ln-gateway/src/bin/cln_extension.rs | 20 +- gateway/ln-gateway/src/db.rs | 4 +- .../src/gateway_module_v2/complete_sm.rs | 4 +- .../ln-gateway/src/gateway_module_v2/mod.rs | 2 +- gateway/ln-gateway/src/lib.rs | 15 +- gateway/ln-gateway/src/lightning/ldk.rs | 2 +- gateway/ln-gateway/src/lightning/lnd.rs | 5 +- gateway/ln-gateway/src/rpc/rpc_server.rs | 2 +- .../ln-gateway/src/state_machine/complete.rs | 2 +- gateway/ln-gateway/src/state_machine/mod.rs | 2 +- gateway/ln-gateway/src/state_machine/pay.rs | 2 +- gateway/ln-gateway/tests/tests.rs | 19 +- modules/fedimint-ln-client/Cargo.toml | 2 +- modules/fedimint-ln-client/src/api.rs | 2 +- modules/fedimint-ln-client/src/db.rs | 2 +- modules/fedimint-ln-client/src/incoming.rs | 2 +- modules/fedimint-ln-client/src/lib.rs | 77 +++---- modules/fedimint-ln-client/src/pay.rs | 12 +- modules/fedimint-ln-client/src/receive.rs | 28 +-- modules/fedimint-ln-common/Cargo.toml | 1 - .../src/contracts/incoming.rs | 8 +- .../fedimint-ln-common/src/contracts/mod.rs | 4 +- .../src/contracts/outgoing.rs | 10 +- modules/fedimint-ln-common/src/lib.rs | 10 +- modules/fedimint-ln-server/Cargo.toml | 2 +- modules/fedimint-ln-server/src/lib.rs | 17 +- modules/fedimint-ln-tests/tests/tests.rs | 31 +-- modules/fedimint-lnv2-client/src/lib.rs | 2 +- modules/fedimint-lnv2-server/src/lib.rs | 15 +- modules/fedimint-lnv2-tests/tests/mock.rs | 27 ++- modules/fedimint-mint-client/src/lib.rs | 3 +- modules/fedimint-wallet-common/src/lib.rs | 3 +- .../fedimint-wallet-common/src/txoproof.rs | 14 +- modules/fedimint-wallet-server/src/lib.rs | 11 +- .../src/bin/circular-deposit-test.rs | 14 +- modules/fedimint-wallet-tests/tests/tests.rs | 14 +- 51 files changed, 241 insertions(+), 538 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index aac59559089..04f1b1f641a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2618,7 +2618,7 @@ dependencies = [ "aquamarine", "async-stream", "async-trait", - "bitcoin 0.30.2", + "bitcoin 0.32.4", "clap", "erased-serde", "fedimint-api-client", @@ -2646,7 +2646,6 @@ name = "fedimint-ln-common" version = "0.5.0-alpha" dependencies = [ "anyhow", - "bitcoin 0.30.2", "bitcoin 0.32.4", "fedimint-client", "fedimint-core", @@ -2672,7 +2671,6 @@ dependencies = [ "axum 0.7.7", "axum-macros", "bitcoin 0.32.4", - "bitcoin_hashes 0.12.0", "clap", "cln-plugin", "cln-rpc", @@ -2730,7 +2728,7 @@ dependencies = [ "anyhow", "assert_matches", "async-trait", - "bitcoin_hashes 0.12.0", + "bitcoin_hashes 0.14.0", "erased-serde", "fedimint-bitcoind", "fedimint-core", diff --git a/devimint/src/external.rs b/devimint/src/external.rs index 984c0e3cead..10cbdff826f 100644 --- a/devimint/src/external.rs +++ b/devimint/src/external.rs @@ -12,12 +12,13 @@ use bitcoincore_rpc::jsonrpc::error::RpcError; use bitcoincore_rpc::RpcApi; use cln_rpc::primitives::{Amount as ClnRpcAmount, AmountOrAny}; use cln_rpc::ClnRpc; -use fedimint_core::bitcoin_migration::bitcoin32_to_bitcoin30_sha256_hash; +use fedimint_core::bitcoin_migration::{ + bitcoin30_to_bitcoin32_sha256_hash, bitcoin32_to_bitcoin30_sha256_hash, +}; use fedimint_core::encoding::Encodable; use fedimint_core::task::jit::{JitTry, JitTryAnyhow}; use fedimint_core::task::{block_in_place, block_on, sleep, timeout}; use fedimint_core::util::write_overwrite_async; -use fedimint_core::BitcoinHash; use fedimint_logging::LOG_DEVIMINT; use fedimint_testing::gateway::LightningNodeType; use futures::StreamExt; @@ -812,7 +813,9 @@ impl Lnd { .invoices_client_lock() .await? .subscribe_single_invoice(tonic_lnd::invoicesrpc::SubscribeSingleInvoiceRequest { - r_hash: payment_hash.to_byte_array().to_vec(), + r_hash: bitcoin30_to_bitcoin32_sha256_hash(&payment_hash) + .to_byte_array() + .to_vec(), }) .await? .into_inner(); diff --git a/devimint/src/tests.rs b/devimint/src/tests.rs index 6f03a833173..d8fef808c49 100644 --- a/devimint/src/tests.rs +++ b/devimint/src/tests.rs @@ -8,9 +8,6 @@ use std::{env, ffi}; use anyhow::{anyhow, bail, Context, Result}; use bitcoin::Txid; use clap::Subcommand; -use fedimint_core::bitcoin_migration::{ - bitcoin32_to_bitcoin30_script_buf, bitcoin32_to_bitcoin30_tx, -}; use fedimint_core::core::LEGACY_HARDCODED_INSTANCE_ID_WALLET; use fedimint_core::encoding::Decodable; use fedimint_core::envs::is_env_var_set; @@ -1055,13 +1052,11 @@ pub async fn cli_tests(dev_fed: DevFed) -> Result<()> { let tx_hex = bitcoind.poll_get_transaction(txid).await?; - let tx = bitcoin32_to_bitcoin30_tx(&bitcoin::Transaction::consensus_decode_hex( - &tx_hex, - &ModuleRegistry::default(), - )?); - assert!(tx.output.iter().any(|o| o.script_pubkey - == bitcoin32_to_bitcoin30_script_buf(&address.script_pubkey()) - && o.value == 50000)); + let tx = bitcoin::Transaction::consensus_decode_hex(&tx_hex, &ModuleRegistry::default())?; + assert!(tx + .output + .iter() + .any(|o| o.script_pubkey == address.script_pubkey() && o.value.to_sat() == 50000)); let post_withdraw_walletng_balance = client.balance().await?; let expected_wallet_balance = initial_walletng_balance - 50_000_000 - (fees_sat * 1000); @@ -2000,25 +1995,19 @@ pub async fn recoverytool_test(dev_fed: DevFed) -> Result<()> { .expect("txid should be parsable"); let tx_hex = bitcoind.poll_get_transaction(txid).await?; - let tx = bitcoin32_to_bitcoin30_tx(&bitcoin::Transaction::consensus_decode_hex( - &tx_hex, - &ModuleRegistry::default(), - )?); + let tx = bitcoin::Transaction::consensus_decode_hex(&tx_hex, &ModuleRegistry::default())?; assert_eq!(tx.input.len(), 1); assert_eq!(tx.output.len(), 2); let change_output = tx .output .iter() - .find(|o| { - o.to_owned().script_pubkey - != bitcoin32_to_bitcoin30_script_buf(&withdrawal_address.script_pubkey()) - }) + .find(|o| o.to_owned().script_pubkey != withdrawal_address.script_pubkey()) .expect("withdrawal must have change output"); - assert!(fed_utxos_sats.insert(change_output.value)); + assert!(fed_utxos_sats.insert(change_output.value.to_sat())); // Remove the utxo consumed from the withdrawal tx - let total_output_sats = tx.output.iter().map(|o| o.value).sum::(); + let total_output_sats = tx.output.iter().map(|o| o.value.to_sat()).sum::(); let input_sats = total_output_sats + fees_sat; assert!(fed_utxos_sats.remove(&input_sats)); diff --git a/fedimint-bitcoind/src/esplora.rs b/fedimint-bitcoind/src/esplora.rs index 6888aded63f..a6aef4d3a75 100644 --- a/fedimint-bitcoind/src/esplora.rs +++ b/fedimint-bitcoind/src/esplora.rs @@ -2,9 +2,6 @@ use std::collections::HashMap; use anyhow::{bail, format_err}; use bitcoin::{BlockHash, Network, ScriptBuf, Transaction, Txid}; -use fedimint_core::bitcoin_migration::{ - bitcoin32_to_bitcoin30_block_header, bitcoin32_to_bitcoin30_partial_merkle_tree, -}; use fedimint_core::envs::BitcoinRpcConfig; use fedimint_core::task::TaskHandle; use fedimint_core::txoproof::TxOutProof; @@ -164,8 +161,8 @@ impl IBitcoindRpc for EsploraClient { .ok_or(format_err!("No merkle proof found"))?; Ok(TxOutProof { - block_header: bitcoin32_to_bitcoin30_block_header(&proof.header), - merkle_proof: bitcoin32_to_bitcoin30_partial_merkle_tree(&proof.txn), + block_header: proof.header, + merkle_proof: proof.txn, }) } diff --git a/fedimint-core/src/bitcoin_migration.rs b/fedimint-core/src/bitcoin_migration.rs index e7f9b370573..0bc7644487a 100644 --- a/fedimint-core/src/bitcoin_migration.rs +++ b/fedimint-core/src/bitcoin_migration.rs @@ -1,7 +1,7 @@ use std::str::FromStr; -use bitcoin::consensus::{Decodable, Encodable}; -use bitcoin30::consensus::{Decodable as Bitcoin30Decodable, Encodable as Bitcoin30Encodable}; +use bitcoin::consensus::Decodable; +use bitcoin30::consensus::Encodable; use bitcoin30::hashes::Hash; pub fn bitcoin29_to_bitcoin32_psbt( @@ -44,13 +44,6 @@ pub fn bitcoin32_to_bitcoin29_network_magic(magic: &bitcoin::p2p::Magic) -> u32 | u32::from(bytes[0]) } -pub fn bitcoin30_checked_address_to_unchecked_address( - address: &bitcoin30::Address, -) -> bitcoin30::Address { - bincode::deserialize(&bincode::serialize(address).expect("Failed to serialize bitcoin address")) - .expect("Failed to convert checked bitcoin address to unchecked bitcoin address") -} - pub fn bitcoin32_checked_address_to_unchecked_address( address: &bitcoin::Address, ) -> bitcoin::Address { @@ -64,40 +57,6 @@ pub fn bitcoin30_to_bitcoin32_invoice( .expect("Failed to convert bitcoin30 invoice to bitcoin32 invoice") } -pub fn bitcoin30_to_bitcoin32_keypair( - keypair: &bitcoin30::secp256k1::KeyPair, -) -> bitcoin::secp256k1::Keypair { - bitcoin::secp256k1::Keypair::from_secret_key( - bitcoin::secp256k1::SECP256K1, - &bitcoin30_to_bitcoin32_secp256k1_secret_key(&keypair.secret_key()), - ) -} - -pub fn bitcoin32_to_bitcoin30_keypair( - keypair: &bitcoin::secp256k1::Keypair, -) -> bitcoin30::secp256k1::KeyPair { - bitcoin30::secp256k1::KeyPair::from_secret_key( - bitcoin30::secp256k1::SECP256K1, - &bitcoin32_to_bitcoin30_secp256k1_secret_key(&keypair.secret_key()), - ) -} - -pub fn bitcoin30_to_bitcoin32_secp256k1_secret_key( - secret_key: &bitcoin30::secp256k1::SecretKey, -) -> bitcoin::secp256k1::SecretKey { - bitcoin::secp256k1::SecretKey::from_slice(secret_key.as_ref()).expect( - "Failed to convert bitcoin30 secp256k1 secret key to bitcoin32 secp256k1 secret key", - ) -} - -pub fn bitcoin32_to_bitcoin30_secp256k1_secret_key( - secret_key: &bitcoin::secp256k1::SecretKey, -) -> bitcoin30::secp256k1::SecretKey { - bitcoin30::secp256k1::SecretKey::from_slice(secret_key.as_ref()).expect( - "Failed to convert bitcoin32 secp256k1 secret key to bitcoin30 secp256k1 secret key", - ) -} - pub fn bitcoin30_to_bitcoin32_secp256k1_pubkey( pubkey: &bitcoin30::secp256k1::PublicKey, ) -> bitcoin::secp256k1::PublicKey { @@ -112,15 +71,6 @@ pub fn bitcoin32_to_bitcoin30_secp256k1_pubkey( .expect("Failed to convert bitcoin32 secp256k1 pubkey to bitcoin30 secp256k1 pubkey") } -pub fn bitcoin30_to_bitcoin32_address(address: &bitcoin30::Address) -> bitcoin::Address { - // The bitcoin crate only allows for deserializing an address as unchecked. - // However, we can safely call `assume_checked()` since the input address is - // checked. - bitcoin::Address::from_str(&address.to_string()) - .expect("Failed to convert bitcoin30 address to bitcoin32 address") - .assume_checked() -} - pub fn bitcoin32_to_bitcoin30_address(address: &bitcoin::Address) -> bitcoin30::Address { // The bitcoin crate only allows for deserializing an address as unchecked. // However, we can safely call `assume_checked()` since the input address is @@ -130,52 +80,6 @@ pub fn bitcoin32_to_bitcoin30_address(address: &bitcoin::Address) -> bitcoin30:: .assume_checked() } -pub fn bitcoin30_to_bitcoin32_block_header( - block_header: &bitcoin30::block::Header, -) -> bitcoin::block::Header { - bitcoin::block::Header { - version: bitcoin::block::Version::from_consensus(block_header.version.to_consensus()), - prev_blockhash: bitcoin::block::BlockHash::from_raw_hash( - bitcoin30_to_bitcoin32_sha256d_hash(&block_header.prev_blockhash.to_raw_hash()), - ), - merkle_root: bitcoin::hash_types::TxMerkleNode::from_raw_hash( - bitcoin30_to_bitcoin32_sha256d_hash(&block_header.merkle_root.to_raw_hash()), - ), - time: block_header.time, - bits: bitcoin::pow::CompactTarget::from_consensus(block_header.bits.to_consensus()), - nonce: block_header.nonce, - } -} - -pub fn bitcoin32_to_bitcoin30_block_header( - block_header: &bitcoin::block::Header, -) -> bitcoin30::block::Header { - bitcoin30::block::Header { - version: bitcoin30::block::Version::from_consensus(block_header.version.to_consensus()), - prev_blockhash: bitcoin30::block::BlockHash::from_raw_hash( - bitcoin32_to_bitcoin30_sha256d_hash(&block_header.prev_blockhash.to_raw_hash()), - ), - merkle_root: bitcoin30::hash_types::TxMerkleNode::from_raw_hash( - bitcoin32_to_bitcoin30_sha256d_hash(&block_header.merkle_root.to_raw_hash()), - ), - time: block_header.time, - bits: bitcoin30::pow::CompactTarget::from_consensus(block_header.bits.to_consensus()), - nonce: block_header.nonce, - } -} - -pub fn bitcoin32_to_bitcoin30_partial_merkle_tree( - partial_merkle_tree: &bitcoin::merkle_tree::PartialMerkleTree, -) -> bitcoin30::merkle_tree::PartialMerkleTree { - let mut bytes = vec![]; - partial_merkle_tree - .consensus_encode(&mut bytes) - .expect("Failed to consensus-encode bitcoin32 partial merkle tree"); - let mut cursor = std::io::Cursor::new(bytes); - bitcoin30::merkle_tree::PartialMerkleTree::consensus_decode(&mut cursor) - .expect("Failed to convert bitcoin32 partial merkle tree to bitcoin30 partial merkle tree") -} - fn bitcoin30_to_bitcoin32_witness(witness: &bitcoin30::Witness) -> bitcoin::Witness { let mut bytes = vec![]; witness @@ -186,16 +90,6 @@ fn bitcoin30_to_bitcoin32_witness(witness: &bitcoin30::Witness) -> bitcoin::Witn .expect("Failed to convert bitcoin30 witness to bitcoin32 witness") } -fn bitcoin32_to_bitcoin30_witness(witness: &bitcoin::Witness) -> bitcoin30::Witness { - let mut bytes = vec![]; - witness - .consensus_encode(&mut bytes) - .expect("Failed to consensus-encode bitcoin32 witness"); - let mut cursor = std::io::Cursor::new(bytes); - bitcoin30::Witness::consensus_decode(&mut cursor) - .expect("Failed to convert bitcoin32 witness to bitcoin30 witness") -} - fn bitcoin30_to_bitcoin32_txin(txin: &bitcoin30::TxIn) -> bitcoin::TxIn { bitcoin::TxIn { previous_output: bitcoin30_to_bitcoin32_outpoint(&txin.previous_output), @@ -205,15 +99,6 @@ fn bitcoin30_to_bitcoin32_txin(txin: &bitcoin30::TxIn) -> bitcoin::TxIn { } } -fn bitcoin32_to_bitcoin30_txin(txin: &bitcoin::TxIn) -> bitcoin30::TxIn { - bitcoin30::TxIn { - previous_output: bitcoin32_to_bitcoin30_outpoint(&txin.previous_output), - script_sig: bitcoin32_to_bitcoin30_script_buf(&txin.script_sig), - sequence: bitcoin30::Sequence(txin.sequence.0), - witness: bitcoin32_to_bitcoin30_witness(&txin.witness), - } -} - fn bitcoin30_to_bitcoin32_txout(txout: &bitcoin30::TxOut) -> bitcoin::TxOut { bitcoin::TxOut { value: bitcoin::Amount::from_sat(txout.value), @@ -221,13 +106,6 @@ fn bitcoin30_to_bitcoin32_txout(txout: &bitcoin30::TxOut) -> bitcoin::TxOut { } } -fn bitcoin32_to_bitcoin30_txout(txout: &bitcoin::TxOut) -> bitcoin30::TxOut { - bitcoin30::TxOut { - value: bitcoin32_to_bitcoin30_amount(&txout.value).to_sat(), - script_pubkey: bitcoin32_to_bitcoin30_script_buf(&txout.script_pubkey), - } -} - fn bitcoin30_to_bitcoin32_locktime( locktime: bitcoin30::blockdata::locktime::absolute::LockTime, ) -> bitcoin::blockdata::locktime::absolute::LockTime { @@ -248,35 +126,6 @@ fn bitcoin30_to_bitcoin32_locktime( } } -fn bitcoin32_to_bitcoin30_locktime( - locktime: bitcoin::blockdata::locktime::absolute::LockTime, -) -> bitcoin30::blockdata::locktime::absolute::LockTime { - match locktime { - bitcoin::blockdata::locktime::absolute::LockTime::Blocks(height) => { - bitcoin30::blockdata::locktime::absolute::LockTime::Blocks( - bitcoin30::blockdata::locktime::absolute::Height::from_consensus( - height.to_consensus_u32(), - ) - .expect("Failed to convert bitcoin32 block height locktime to bitcoin30 block height locktime"), - ) - } - bitcoin::blockdata::locktime::absolute::LockTime::Seconds(time) => { - bitcoin30::blockdata::locktime::absolute::LockTime::Seconds( - bitcoin30::blockdata::locktime::absolute::Time::from_consensus(time.to_consensus_u32()).expect("Failed to convert bitcoin32 timestamp locktime to bitcoin30 timestamp locktime"), - ) - } - } -} - -pub fn bitcoin32_to_bitcoin30_tx(tx: &bitcoin::Transaction) -> bitcoin30::Transaction { - bitcoin30::Transaction { - version: tx.version.0, - lock_time: bitcoin32_to_bitcoin30_locktime(tx.lock_time), - input: tx.input.iter().map(bitcoin32_to_bitcoin30_txin).collect(), - output: tx.output.iter().map(bitcoin32_to_bitcoin30_txout).collect(), - } -} - pub fn bitcoin30_to_bitcoin32_tx(tx: &bitcoin30::Transaction) -> bitcoin::Transaction { bitcoin::Transaction { version: bitcoin::blockdata::transaction::Version(tx.version), @@ -286,14 +135,7 @@ pub fn bitcoin30_to_bitcoin32_tx(tx: &bitcoin30::Transaction) -> bitcoin::Transa } } -pub fn bitcoin_32_to_bitcoin30_txout(txout: &bitcoin::TxOut) -> bitcoin30::TxOut { - bitcoin30::TxOut { - value: bitcoin32_to_bitcoin30_amount(&txout.value).to_sat(), - script_pubkey: bitcoin32_to_bitcoin30_script_buf(&txout.script_pubkey), - } -} - -pub fn bitcoin30_to_bitcoin32_script_buf(script: &bitcoin30::ScriptBuf) -> bitcoin::ScriptBuf { +fn bitcoin30_to_bitcoin32_script_buf(script: &bitcoin30::ScriptBuf) -> bitcoin::ScriptBuf { bitcoin::ScriptBuf::from(script.as_bytes().to_vec()) } @@ -317,15 +159,6 @@ pub fn bitcoin32_to_bitcoin30_block_hash( )) } -pub fn bitcoin30_to_bitcoin32_unchecked_address( - address: &bitcoin30::Address, -) -> bitcoin::Address { - // The bitcoin crate only implements `ToString` for checked addresses. - // However, this is fine since we're returning an unchecked address. - bitcoin::Address::from_str(&address.clone().assume_checked().to_string()) - .expect("Failed to convert bitcoin30 address to bitcoin32 address") -} - pub fn bitcoin32_to_bitcoin30_unchecked_address( address: &bitcoin::Address, ) -> bitcoin30::Address { @@ -335,14 +168,6 @@ pub fn bitcoin32_to_bitcoin30_unchecked_address( .expect("Failed to convert bitcoin32 address to bitcoin30 address") } -pub fn bitcoin30_to_bitcoin32_amount(amount: &bitcoin30::Amount) -> bitcoin::Amount { - bitcoin::Amount::from_sat(amount.to_sat()) -} - -pub fn bitcoin32_to_bitcoin30_amount(amount: &bitcoin::Amount) -> bitcoin30::Amount { - bitcoin30::Amount::from_sat(amount.to_sat()) -} - pub fn bitcoin30_to_bitcoin32_network(network: &bitcoin30::Network) -> bitcoin::Network { match *network { bitcoin30::Network::Bitcoin => bitcoin::Network::Bitcoin, @@ -363,7 +188,7 @@ pub fn bitcoin32_to_bitcoin30_network(network: &bitcoin::Network) -> bitcoin30:: } } -pub fn bitcoin30_to_bitcoin32_txid(txid: &bitcoin30::Txid) -> bitcoin::Txid { +fn bitcoin30_to_bitcoin32_txid(txid: &bitcoin30::Txid) -> bitcoin::Txid { bitcoin::Txid::from_str(&txid.to_string()) .expect("Failed to convert bitcoin30 txid to bitcoin32 txid") } @@ -373,20 +198,13 @@ pub fn bitcoin32_to_bitcoin30_txid(txid: &bitcoin::Txid) -> bitcoin30::Txid { .expect("Failed to convert bitcoin32 txid to bitcoin30 txid") } -pub fn bitcoin30_to_bitcoin32_outpoint(outpoint: &bitcoin30::OutPoint) -> bitcoin::OutPoint { +fn bitcoin30_to_bitcoin32_outpoint(outpoint: &bitcoin30::OutPoint) -> bitcoin::OutPoint { bitcoin::OutPoint { txid: bitcoin30_to_bitcoin32_txid(&outpoint.txid), vout: outpoint.vout, } } -pub fn bitcoin32_to_bitcoin30_outpoint(outpoint: &bitcoin::OutPoint) -> bitcoin30::OutPoint { - bitcoin30::OutPoint { - txid: bitcoin32_to_bitcoin30_txid(&outpoint.txid), - vout: outpoint.vout, - } -} - pub fn bitcoin30_to_bitcoin32_payment_preimage( preimage: &lightning::ln::PaymentPreimage, ) -> lightning_types::payment::PaymentPreimage { @@ -417,20 +235,6 @@ fn bitcoin32_to_bitcoin30_sha256d_hash( bitcoin30::hashes::sha256d::Hash::from_byte_array(*hash.as_ref()) } -pub fn bitcoin30_to_bitcoin32_schnorr_signature( - signature: &bitcoin30::secp256k1::schnorr::Signature, -) -> bitcoin::secp256k1::schnorr::Signature { - bitcoin::secp256k1::schnorr::Signature::from_slice(signature.as_ref()) - .expect("Failed to convert bitcoin30 schnorr signature to bitcoin32 schnorr signature") -} - -pub fn bitcoin32_to_bitcoin30_schnorr_signature( - signature: &bitcoin::secp256k1::schnorr::Signature, -) -> bitcoin30::secp256k1::schnorr::Signature { - bitcoin30::secp256k1::schnorr::Signature::from_slice(signature.as_ref()) - .expect("Failed to convert bitcoin32 schnorr signature to bitcoin30 schnorr signature") -} - pub fn bitcoin32_to_bitcoin30_recoverable_signature( signature: &bitcoin::secp256k1::ecdsa::RecoverableSignature, ) -> bitcoin30::secp256k1::ecdsa::RecoverableSignature { diff --git a/fedimint-core/src/core/backup.rs b/fedimint-core/src/core/backup.rs index c821476ff0b..9309bdd2dc6 100644 --- a/fedimint-core/src/core/backup.rs +++ b/fedimint-core/src/core/backup.rs @@ -1,6 +1,6 @@ use std::fmt::Debug; -use bitcoin30::hashes::{sha256, Hash}; +use bitcoin::hashes::{sha256, Hash}; use fedimint_core::encoding::{Decodable, Encodable}; use secp256k1::{Keypair, Message, Secp256k1, Signing, Verification}; use serde::{Deserialize, Serialize}; @@ -24,7 +24,7 @@ pub struct BackupRequest { impl BackupRequest { fn hash(&self) -> sha256::Hash { - self.consensus_hash_bitcoin30() + self.consensus_hash() } pub fn sign(self, keypair: &Keypair) -> anyhow::Result { diff --git a/fedimint-core/src/encoding/btc.rs b/fedimint-core/src/encoding/btc.rs index b9fdddb367d..3f0eabb5a19 100644 --- a/fedimint-core/src/encoding/btc.rs +++ b/fedimint-core/src/encoding/btc.rs @@ -10,10 +10,9 @@ use miniscript::{Descriptor, MiniscriptKey}; use super::SimpleBitcoinRead; use crate::bitcoin_migration::{ bitcoin29_to_bitcoin32_network_magic, bitcoin29_to_bitcoin32_psbt, - bitcoin30_to_bitcoin32_network, bitcoin30_to_bitcoin32_sha256_hash, - bitcoin32_checked_address_to_unchecked_address, bitcoin32_to_bitcoin29_network_magic, - bitcoin32_to_bitcoin29_psbt, bitcoin32_to_bitcoin30_address, - bitcoin32_to_bitcoin30_sha256_hash, + bitcoin30_to_bitcoin32_network, bitcoin32_checked_address_to_unchecked_address, + bitcoin32_to_bitcoin29_network_magic, bitcoin32_to_bitcoin29_psbt, + bitcoin32_to_bitcoin30_address, }; use crate::encoding::{Decodable, DecodeError, Encodable}; use crate::module::registry::ModuleDecoderRegistry; @@ -235,23 +234,6 @@ impl Decodable for bitcoin::Address { } } -impl Encodable for bitcoin30::hashes::sha256::Hash { - fn consensus_encode(&self, writer: &mut W) -> Result { - bitcoin30_to_bitcoin32_sha256_hash(self).consensus_encode(writer) - } -} - -impl Decodable for bitcoin30::hashes::sha256::Hash { - fn consensus_decode( - d: &mut D, - modules: &ModuleDecoderRegistry, - ) -> Result { - Ok(bitcoin32_to_bitcoin30_sha256_hash( - &Decodable::consensus_decode(d, modules)?, - )) - } -} - impl Encodable for bitcoin::hashes::sha256::Hash { fn consensus_encode(&self, writer: &mut W) -> Result { self.to_byte_array().consensus_encode(writer) diff --git a/fedimint-core/src/encoding/mod.rs b/fedimint-core/src/encoding/mod.rs index d866e7118b4..6c830ac238d 100644 --- a/fedimint-core/src/encoding/mod.rs +++ b/fedimint-core/src/encoding/mod.rs @@ -113,22 +113,6 @@ pub trait Encodable { .expect("encoding to bytes can't fail for io reasons") } - /// Generate a SHA256 hash of the consensus encoding using the default hash - /// engine for `H`. - /// - /// Can be used to validate all federation members agree on state without - /// revealing the object - fn consensus_hash_bitcoin30(&self) -> H - where - H: bitcoin30::hashes::Hash, - H::Engine: std::io::Write, - { - let mut engine = H::engine(); - self.consensus_encode(&mut engine) - .expect("writing to HashEngine cannot fail"); - H::from_engine(engine) - } - /// Generate a SHA256 hash of the consensus encoding using the default hash /// engine for `H`. /// @@ -1222,7 +1206,6 @@ mod tests { use std::str::FromStr; use super::*; - use crate::bitcoin_migration::bitcoin30_to_bitcoin32_txid; use crate::db::DatabaseValue; use crate::encoding::{Decodable, Encodable}; @@ -1531,12 +1514,12 @@ mod tests { #[test] fn test_bitcoin_consensus_encoding() { // encodings should follow the bitcoin consensus encoding - let txid = bitcoin30::Txid::from_str( + let txid = bitcoin::Txid::from_str( "51f7ed2f23e58cc6e139e715e9ce304a1e858416edc9079dd7b74fa8d2efc09a", ) .unwrap(); test_roundtrip_expected( - &bitcoin30_to_bitcoin32_txid(&txid), + &txid, &[ 154, 192, 239, 210, 168, 79, 183, 215, 157, 7, 201, 237, 22, 132, 133, 30, 74, 48, 206, 233, 21, 231, 57, 225, 198, 140, 229, 35, 47, 237, 247, 81, diff --git a/fedimint-core/src/lib.rs b/fedimint-core/src/lib.rs index be7370fa71e..d5fe2bd1915 100644 --- a/fedimint-core/src/lib.rs +++ b/fedimint-core/src/lib.rs @@ -44,9 +44,7 @@ use std::str::FromStr; pub use amount::*; /// Mostly re-exported for [`Decodable`] macros. pub use anyhow; -use bitcoin30::hashes::hash_newtype; -use bitcoin30::hashes::sha256::Hash as Sha256; -pub use bitcoin30::hashes::Hash as BitcoinHash; +pub use bitcoin::hashes::Hash as BitcoinHash; pub use macro_rules_attribute::apply; pub use module::ServerModule; pub use peer_id::*; @@ -119,10 +117,19 @@ pub mod version; /// Atomic BFT unit containing consensus items pub mod session_outcome; -hash_newtype!( - /// A transaction id for peg-ins, peg-outs and reissuances - pub struct TransactionId(Sha256); -); +// It's necessary to wrap `hash_newtype!` in a module because the generated code +// references a module called "core", but we export a conflicting module in this +// file. +mod txid { + use bitcoin::hashes::hash_newtype; + use bitcoin::hashes::sha256::Hash as Sha256; + + hash_newtype!( + /// A transaction id for peg-ins, peg-outs and reissuances + pub struct TransactionId(Sha256); + ); +} +pub use txid::TransactionId; /// Amount of bitcoin to send, or `All` to send all available funds #[derive(Debug, Eq, PartialEq, Copy, Hash, Clone, Serialize, Deserialize)] @@ -224,13 +231,13 @@ pub struct Feerate { } impl Feerate { - pub fn calculate_fee(&self, weight: u64) -> bitcoin30::Amount { + pub fn calculate_fee(&self, weight: u64) -> bitcoin::Amount { let sats = weight_to_vbytes(weight) * self.sats_per_kvb / 1000; - bitcoin30::Amount::from_sat(sats) + bitcoin::Amount::from_sat(sats) } } -const WITNESS_SCALE_FACTOR: u64 = bitcoin30::constants::WITNESS_SCALE_FACTOR as u64; +const WITNESS_SCALE_FACTOR: u64 = bitcoin::constants::WITNESS_SCALE_FACTOR as u64; /// Converts weight to virtual bytes, defined in [BIP-141] as weight / 4 /// (rounded up to the next integer). @@ -259,8 +266,8 @@ mod tests { #[test] fn calculate_fee() { let feerate = Feerate { sats_per_kvb: 1000 }; - assert_eq!(bitcoin30::Amount::from_sat(25), feerate.calculate_fee(100)); - assert_eq!(bitcoin30::Amount::from_sat(26), feerate.calculate_fee(101)); + assert_eq!(bitcoin::Amount::from_sat(25), feerate.calculate_fee(100)); + assert_eq!(bitcoin::Amount::from_sat(26), feerate.calculate_fee(101)); } #[test] diff --git a/fedimint-core/src/net/api_announcement.rs b/fedimint-core/src/net/api_announcement.rs index 5f27217319d..73e8a5849ef 100644 --- a/fedimint-core/src/net/api_announcement.rs +++ b/fedimint-core/src/net/api_announcement.rs @@ -1,7 +1,7 @@ use std::collections::BTreeMap; -use bitcoin30::hashes::{sha256, Hash}; -use bitcoin30::secp256k1::Message; +use bitcoin::hashes::{sha256, Hash}; +use bitcoin::secp256k1::Message; use fedimint_core::db::DatabaseLookup; use fedimint_core::encoding::{Decodable, Encodable}; use fedimint_core::task::MaybeSend; @@ -10,7 +10,6 @@ use futures::StreamExt; use jsonrpsee_core::Serialize; use serde::Deserialize; -use crate::bitcoin_migration::bitcoin30_to_bitcoin32_secp256k1_message; use crate::db::{ Database, DatabaseKey, DatabaseKeyPrefix, DatabaseRecord, IDatabaseTransactionOpsCoreTyped, }; @@ -55,7 +54,7 @@ impl ApiAnnouncement { ctx: &secp256k1::Secp256k1, key: &secp256k1::Keypair, ) -> SignedApiAnnouncement { - let msg = bitcoin30_to_bitcoin32_secp256k1_message(&self.tagged_hash().into()); + let msg = Message::from_digest(*self.tagged_hash().as_ref()); let signature = ctx.sign_schnorr(&msg, key); SignedApiAnnouncement { api_announcement: self.clone(), @@ -71,13 +70,9 @@ impl SignedApiAnnouncement { ctx: &secp256k1::Secp256k1, pk: &secp256k1::PublicKey, ) -> bool { - let msg: Message = self.api_announcement.tagged_hash().into(); - ctx.verify_schnorr( - &self.signature, - &bitcoin30_to_bitcoin32_secp256k1_message(&msg), - &pk.x_only_public_key().0, - ) - .is_ok() + let msg = Message::from_digest(*self.api_announcement.tagged_hash().as_ref()); + ctx.verify_schnorr(&self.signature, &msg, &pk.x_only_public_key().0) + .is_ok() } } diff --git a/fedimint-core/src/transaction.rs b/fedimint-core/src/transaction.rs index 01a04671a66..1df511c4ab9 100644 --- a/fedimint-core/src/transaction.rs +++ b/fedimint-core/src/transaction.rs @@ -1,4 +1,4 @@ -use bitcoin30::hashes::Hash as BitcoinHash; +use bitcoin::hashes::Hash; use fedimint_core::core::{DynInput, DynOutput}; use fedimint_core::encoding::{Decodable, Encodable}; use fedimint_core::module::SerdeModuleEncoding; diff --git a/fedimint-core/src/txoproof.rs b/fedimint-core/src/txoproof.rs index f54a7676dee..ed5cbe7358f 100644 --- a/fedimint-core/src/txoproof.rs +++ b/fedimint-core/src/txoproof.rs @@ -4,25 +4,18 @@ use std::io::Cursor; use bitcoin::block::Header as BlockHeader; use bitcoin::merkle_tree::PartialMerkleTree; -use bitcoin30::block::Header as BlockHeader30; -use bitcoin30::consensus::Encodable as Encodable30; -use bitcoin30::merkle_tree::PartialMerkleTree as PartialMerkleTree30; -use bitcoin30::{BlockHash, Txid}; +use bitcoin::{BlockHash, Txid}; use hex::{FromHex, ToHex}; use serde::de::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use crate::bitcoin_migration::{ - bitcoin30_to_bitcoin32_block_header, bitcoin32_to_bitcoin30_block_header, - bitcoin32_to_bitcoin30_partial_merkle_tree, -}; use crate::encoding::{Decodable, DecodeError, Encodable}; use crate::module::registry::ModuleDecoderRegistry; #[derive(Clone, Debug)] pub struct TxOutProof { - pub block_header: BlockHeader30, - pub merkle_proof: PartialMerkleTree30, + pub block_header: BlockHeader, + pub merkle_proof: PartialMerkleTree, } impl TxOutProof { @@ -49,11 +42,8 @@ impl Decodable for TxOutProof { d: &mut D, modules: &ModuleDecoderRegistry, ) -> Result { - let block_header = - bitcoin32_to_bitcoin30_block_header(&BlockHeader::consensus_decode(d, modules)?); - let merkle_proof = bitcoin32_to_bitcoin30_partial_merkle_tree( - &PartialMerkleTree::consensus_decode(d, modules)?, - ); + let block_header = BlockHeader::consensus_decode(d, modules)?; + let merkle_proof = PartialMerkleTree::consensus_decode(d, modules)?; let mut transactions = Vec::new(); let mut indices = Vec::new(); @@ -78,8 +68,7 @@ impl Encodable for TxOutProof { fn consensus_encode(&self, writer: &mut W) -> Result { let mut written = 0; - written += - bitcoin30_to_bitcoin32_block_header(&self.block_header).consensus_encode(writer)?; + written += self.block_header.consensus_encode(writer)?; written += self.merkle_proof.consensus_encode(writer)?; Ok(written) diff --git a/fedimint-testing/src/btc/mock.rs b/fedimint-testing/src/btc/mock.rs index cc905a58037..b10a4951bad 100644 --- a/fedimint-testing/src/btc/mock.rs +++ b/fedimint-testing/src/btc/mock.rs @@ -18,9 +18,6 @@ use fedimint_bitcoind::{ register_bitcoind, DynBitcoindRpc, IBitcoindRpc, IBitcoindRpcFactory, Result as BitcoinRpcResult, }; -use fedimint_core::bitcoin_migration::{ - bitcoin32_to_bitcoin30_block_header, bitcoin32_to_bitcoin30_partial_merkle_tree, -}; use fedimint_core::envs::BitcoinRpcConfig; use fedimint_core::task::{sleep_in_test, TaskHandle}; use fedimint_core::txoproof::TxOutProof; @@ -235,8 +232,8 @@ impl BitcoinTest for FakeBitcoinTest { FakeBitcoinTest::mine_block(addresses, blocks, pending, txid_to_block_height); let block_header = inner.blocks.last().unwrap().header; let proof = TxOutProof { - block_header: bitcoin32_to_bitcoin30_block_header(&block_header), - merkle_proof: bitcoin32_to_bitcoin30_partial_merkle_tree(&merkle_proof), + block_header, + merkle_proof, }; inner .proofs diff --git a/fedimint-testing/src/ln.rs b/fedimint-testing/src/ln.rs index b0c99fc5c44..4d7f0cc7a1a 100644 --- a/fedimint-testing/src/ln.rs +++ b/fedimint-testing/src/ln.rs @@ -235,7 +235,7 @@ impl ILnRpcClient for FakeLightningTest { let invoice = match create_invoice_request.payment_hash { Some(payment_hash) => InvoiceBuilder::new(Currency::Regtest) .description(String::new()) - .payment_hash(payment_hash) + .payment_hash(bitcoin32_to_bitcoin30_sha256_hash(&payment_hash)) .current_timestamp() .min_final_cltv_expiry_delta(0) .payment_secret(PaymentSecret([0; 32])) diff --git a/gateway/ln-gateway/Cargo.toml b/gateway/ln-gateway/Cargo.toml index cde4e42ebd6..a80314ad706 100644 --- a/gateway/ln-gateway/Cargo.toml +++ b/gateway/ln-gateway/Cargo.toml @@ -36,7 +36,6 @@ async-trait = { workspace = true } axum = { version = "0.7.7", features = [ "json" ] } axum-macros = "0.4.2" bitcoin = { workspace = true } -bitcoin_hashes = { package = "bitcoin_hashes", version = "0.12.0" } clap = { workspace = true } cln-plugin = "0.2.0" cln-rpc = { workspace = true } diff --git a/gateway/ln-gateway/src/bin/cln_extension.rs b/gateway/ln-gateway/src/bin/cln_extension.rs index 472906a3786..5939d2f9444 100644 --- a/gateway/ln-gateway/src/bin/cln_extension.rs +++ b/gateway/ln-gateway/src/bin/cln_extension.rs @@ -10,7 +10,7 @@ use axum::body::{Body, Bytes}; use axum::response::{IntoResponse, Response}; use axum::routing::{get, post}; use axum::{Extension, Json, Router}; -use bitcoin_hashes::sha256; +use bitcoin::hashes::sha256; use clap::Parser; use cln_plugin::options::{self, StringConfigOption}; use cln_plugin::{Builder, Plugin}; @@ -21,7 +21,7 @@ use cln_rpc::primitives::{AmountOrAll, ChannelState, ShortChannelId}; use fedimint_core::bitcoin_migration::{ bitcoin30_to_bitcoin32_secp256k1_message, bitcoin30_to_bitcoin32_secp256k1_pubkey, bitcoin32_to_bitcoin30_network, bitcoin32_to_bitcoin30_recoverable_signature, - bitcoin32_to_bitcoin30_secp256k1_pubkey, + bitcoin32_to_bitcoin30_secp256k1_pubkey, bitcoin32_to_bitcoin30_sha256_hash, }; use fedimint_core::secp256k1::{PublicKey, SecretKey, SECP256K1}; use fedimint_core::task::timeout; @@ -558,7 +558,7 @@ async fn cln_create_invoice( let invoice_builder = InvoiceBuilder::new(Currency::from(network)) .amount_milli_satoshis(amount_msat) - .payment_hash(payment_hash) + .payment_hash(bitcoin32_to_bitcoin30_sha256_hash(&payment_hash)) .payment_secret(PaymentSecret(OsRng.gen())) .duration_since_epoch(fedimint_core::time::duration_since_epoch()) .min_final_cltv_expiry_delta(18) @@ -570,9 +570,11 @@ async fn cln_create_invoice( &lightning_invoice::Description::new(description).expect("Description is valid"), ), ), - InvoiceDescription::Hash(hash) => invoice_builder.invoice_description( - lightning_invoice::Bolt11InvoiceDescription::Hash(&lightning_invoice::Sha256(hash)), - ), + InvoiceDescription::Hash(hash) => { + invoice_builder.invoice_description(lightning_invoice::Bolt11InvoiceDescription::Hash( + &lightning_invoice::Sha256(bitcoin32_to_bitcoin30_sha256_hash(&hash)), + )) + } }; let invoice = invoice_builder @@ -892,7 +894,7 @@ struct Htlc { // TODO: use these to validate we can actually redeem the HTLC in time cltv_expiry: u32, cltv_expiry_relative: u32, - payment_hash: bitcoin_hashes::sha256::Hash, + payment_hash: bitcoin::hashes::sha256::Hash, // The short channel id of the incoming channel short_channel_id: String, // The ID of the HTLC @@ -1112,7 +1114,7 @@ impl ClnRpcService { partid: None, payment_metadata: None, payment_secret, - payment_hash, + payment_hash: bitcoin32_to_bitcoin30_sha256_hash(&payment_hash), route, })) .await?; @@ -1132,7 +1134,7 @@ impl ClnRpcService { groupid: None, partid: None, timeout: None, - payment_hash, + payment_hash: bitcoin32_to_bitcoin30_sha256_hash(&payment_hash), }, )) .await; diff --git a/gateway/ln-gateway/src/db.rs b/gateway/ln-gateway/src/db.rs index a28124e0ec9..2f8be041fd1 100644 --- a/gateway/ln-gateway/src/db.rs +++ b/gateway/ln-gateway/src/db.rs @@ -1,7 +1,7 @@ use std::collections::BTreeMap; +use bitcoin::hashes::sha256; use bitcoin::Network; -use bitcoin_hashes::sha256; use fedimint_api_client::api::net::Connector; use fedimint_core::config::FederationId; use fedimint_core::db::{ @@ -447,7 +447,7 @@ mod fedimint_migration_tests { use std::str::FromStr; use anyhow::ensure; - use bitcoin_hashes::Hash; + use bitcoin::hashes::Hash; use fedimint_core::db::Database; use fedimint_core::module::registry::ModuleDecoderRegistry; use fedimint_core::util::SafeUrl; diff --git a/gateway/ln-gateway/src/gateway_module_v2/complete_sm.rs b/gateway/ln-gateway/src/gateway_module_v2/complete_sm.rs index 2d961c0bdba..95778c2593e 100644 --- a/gateway/ln-gateway/src/gateway_module_v2/complete_sm.rs +++ b/gateway/ln-gateway/src/gateway_module_v2/complete_sm.rs @@ -54,7 +54,7 @@ impl fmt::Display for CompleteStateMachine { #[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)] pub struct CompleteSMCommon { pub operation_id: OperationId, - pub payment_hash: bitcoin_hashes::sha256::Hash, + pub payment_hash: bitcoin::hashes::sha256::Hash, pub incoming_chan_id: u64, pub htlc_id: u64, } @@ -127,7 +127,7 @@ impl CompleteStateMachine { async fn await_completion( context: GatewayClientContextV2, - payment_hash: bitcoin_hashes::sha256::Hash, + payment_hash: bitcoin::hashes::sha256::Hash, final_receive_state: FinalReceiveState, incoming_chan_id: u64, htlc_id: u64, diff --git a/gateway/ln-gateway/src/gateway_module_v2/mod.rs b/gateway/ln-gateway/src/gateway_module_v2/mod.rs index e734b9bcfa4..eaed37e3aea 100644 --- a/gateway/ln-gateway/src/gateway_module_v2/mod.rs +++ b/gateway/ln-gateway/src/gateway_module_v2/mod.rs @@ -372,7 +372,7 @@ impl GatewayClientModuleV2 { pub async fn relay_incoming_htlc( &self, - payment_hash: bitcoin_hashes::sha256::Hash, + payment_hash: sha256::Hash, incoming_chan_id: u64, htlc_id: u64, contract: IncomingContract, diff --git a/gateway/ln-gateway/src/lib.rs b/gateway/ln-gateway/src/lib.rs index 531946d56b0..59432ae141b 100644 --- a/gateway/ln-gateway/src/lib.rs +++ b/gateway/ln-gateway/src/lib.rs @@ -33,8 +33,8 @@ use std::sync::Arc; use std::time::Duration; use anyhow::{anyhow, Context}; +use bitcoin::hashes::sha256; use bitcoin::{Address, Network, Txid}; -use bitcoin_hashes::sha256; use clap::Parser; use client::GatewayClientBuilder; use config::GatewayOpts; @@ -47,9 +47,6 @@ use fedimint_bip39::{Bip39RootSecretStrategy, Language, Mnemonic}; use fedimint_client::module::init::ClientModuleInitRegistry; use fedimint_client::secret::RootSecretStrategy; use fedimint_client::{Client, ClientHandleArc}; -use fedimint_core::bitcoin_migration::{ - bitcoin30_to_bitcoin32_sha256_hash, bitcoin32_to_bitcoin30_sha256_hash, -}; use fedimint_core::config::FederationId; use fedimint_core::core::{ ModuleInstanceId, ModuleKind, LEGACY_HARDCODED_INSTANCE_ID_MINT, @@ -668,9 +665,7 @@ impl Gateway { // not a Fedimint. let (contract, client) = self .get_registered_incoming_contract_and_client_v2( - PaymentImage::Hash(bitcoin30_to_bitcoin32_sha256_hash( - &htlc_request.payment_hash, - )), + PaymentImage::Hash(htlc_request.payment_hash), htlc_request.amount_msat, ) .await?; @@ -2042,7 +2037,7 @@ impl Gateway { let invoice = self .create_invoice_via_lnrpc_v2( - bitcoin32_to_bitcoin30_sha256_hash(&payment_hash), + payment_hash, payload.amount, payload.description.clone(), payload.expiry_secs, @@ -2102,9 +2097,7 @@ impl Gateway { payment_hash: Some(payment_hash), amount_msat: amount.msats, expiry_secs: expiry_time, - description: Some(InvoiceDescription::Hash( - bitcoin32_to_bitcoin30_sha256_hash(&hash), - )), + description: Some(InvoiceDescription::Hash(hash)), }) .await? } diff --git a/gateway/ln-gateway/src/lightning/ldk.rs b/gateway/ln-gateway/src/lightning/ldk.rs index fc4c9298b54..82b90477b91 100644 --- a/gateway/ln-gateway/src/lightning/ldk.rs +++ b/gateway/ln-gateway/src/lightning/ldk.rs @@ -4,8 +4,8 @@ use std::sync::Arc; use std::time::Duration; use async_trait::async_trait; +use bitcoin::hashes::Hash; use bitcoin::{Network, OutPoint}; -use bitcoin_hashes::Hash; use fedimint_bip39::Mnemonic; use fedimint_core::bitcoin_migration::{ bitcoin30_to_bitcoin32_invoice, bitcoin30_to_bitcoin32_payment_preimage, diff --git a/gateway/ln-gateway/src/lightning/lnd.rs b/gateway/ln-gateway/src/lightning/lnd.rs index 84eb2cb5ba6..1b210f5ce7c 100644 --- a/gateway/ln-gateway/src/lightning/lnd.rs +++ b/gateway/ln-gateway/src/lightning/lnd.rs @@ -7,7 +7,6 @@ use std::time::Duration; use anyhow::ensure; use async_trait::async_trait; use bitcoin::hashes::{sha256, Hash}; -use bitcoin_hashes::Hash as Bitcoin30Hash; use fedimint_core::db::Database; use fedimint_core::task::{sleep, TaskGroup}; use fedimint_core::{secp256k1, Amount, BitcoinAmountOrAll}; @@ -176,7 +175,7 @@ impl GatewayLndClient { if hold.state() == InvoiceState::Accepted { let intercept = InterceptPaymentRequest { - payment_hash: Bitcoin30Hash::from_slice(&hold.r_hash.clone()) + payment_hash: Hash::from_slice(&hold.r_hash.clone()) .expect("Failed to convert to Hash"), amount_msat: hold.amt_paid_msat as u64, // The rest of the fields are not used in LNv2 and can be removed once LNv1 @@ -422,7 +421,7 @@ impl GatewayLndClient { // Forward all HTLCs to gatewayd, gatewayd will filter them based on scid let intercept = InterceptPaymentRequest { - payment_hash: Bitcoin30Hash::from_slice(&htlc.payment_hash).expect("Failed to convert payment Hash"), + payment_hash: Hash::from_slice(&htlc.payment_hash).expect("Failed to convert payment Hash"), amount_msat: htlc.outgoing_amount_msat, expiry: htlc.incoming_expiry, short_channel_id: Some(htlc.outgoing_requested_chan_id), diff --git a/gateway/ln-gateway/src/rpc/rpc_server.rs b/gateway/ln-gateway/src/rpc/rpc_server.rs index 36c49c2fb8b..86fe70f8f14 100644 --- a/gateway/ln-gateway/src/rpc/rpc_server.rs +++ b/gateway/ln-gateway/src/rpc/rpc_server.rs @@ -6,7 +6,7 @@ use axum::middleware::{self, Next}; use axum::response::IntoResponse; use axum::routing::{get, post}; use axum::{Extension, Json, Router}; -use bitcoin_hashes::{sha256, Hash}; +use bitcoin::hashes::{sha256, Hash}; use fedimint_core::config::FederationId; use fedimint_core::encoding::Encodable; use fedimint_core::task::TaskGroup; diff --git a/gateway/ln-gateway/src/state_machine/complete.rs b/gateway/ln-gateway/src/state_machine/complete.rs index 56594eb6f77..aa6ff2d4a3d 100644 --- a/gateway/ln-gateway/src/state_machine/complete.rs +++ b/gateway/ln-gateway/src/state_machine/complete.rs @@ -60,7 +60,7 @@ impl fmt::Display for GatewayCompleteStates { #[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)] pub struct GatewayCompleteCommon { pub operation_id: OperationId, - pub payment_hash: bitcoin_hashes::sha256::Hash, + pub payment_hash: bitcoin::hashes::sha256::Hash, pub incoming_chan_id: u64, pub htlc_id: u64, } diff --git a/gateway/ln-gateway/src/state_machine/mod.rs b/gateway/ln-gateway/src/state_machine/mod.rs index 095a894107c..0b3280d7129 100644 --- a/gateway/ln-gateway/src/state_machine/mod.rs +++ b/gateway/ln-gateway/src/state_machine/mod.rs @@ -8,9 +8,9 @@ use std::time::Duration; use anyhow::ensure; use async_stream::stream; +use bitcoin::hashes::{sha256, Hash}; use bitcoin::key::Secp256k1; use bitcoin::secp256k1::All; -use bitcoin_hashes::{sha256, Hash}; use fedimint_api_client::api::DynModuleApi; use fedimint_client::derivable_secret::ChildId; use fedimint_client::module::init::{ClientModuleInit, ClientModuleInitArgs}; diff --git a/gateway/ln-gateway/src/state_machine/pay.rs b/gateway/ln-gateway/src/state_machine/pay.rs index e22bcf053d8..cf684790a4a 100644 --- a/gateway/ln-gateway/src/state_machine/pay.rs +++ b/gateway/ln-gateway/src/state_machine/pay.rs @@ -1,6 +1,6 @@ use std::fmt::{self, Display}; -use bitcoin_hashes::sha256; +use bitcoin::hashes::sha256; use fedimint_client::sm::{ClientSMDatabaseTransaction, State, StateTransition}; use fedimint_client::transaction::{ ClientInput, ClientInputBundle, ClientOutput, ClientOutputBundle, diff --git a/gateway/ln-gateway/tests/tests.rs b/gateway/ln-gateway/tests/tests.rs index 03974661a51..e6541692c57 100644 --- a/gateway/ln-gateway/tests/tests.rs +++ b/gateway/ln-gateway/tests/tests.rs @@ -7,11 +7,12 @@ use std::sync::Arc; use std::time::Duration; use assert_matches::assert_matches; -use bitcoin_hashes::{sha256, Hash}; +use bitcoin::hashes::{sha256, Hash}; use fedimint_client::transaction::{ ClientInput, ClientInputBundle, ClientOutput, ClientOutputBundle, TransactionBuilder, }; use fedimint_client::ClientHandleArc; +use fedimint_core::bitcoin_migration::bitcoin30_to_bitcoin32_sha256_hash; use fedimint_core::config::FederationId; use fedimint_core::core::{IntoDynInstance, OperationId}; use fedimint_core::encoding::Encodable; @@ -395,7 +396,9 @@ async fn test_gateway_cannot_claim_invalid_preimage() -> anyhow::Result<()> { ClientInputBundle::new_no_sm(vec![client_input]).into_dyn(gateway_module.id), ); let operation_meta_gen = |_: TransactionId, _: Vec| GatewayMeta::Pay {}; - let operation_id = OperationId(invoice.payment_hash().to_byte_array()); + let operation_id = OperationId( + bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()).to_byte_array(), + ); let (txid, _) = gateway_client .finalize_and_submit_transaction( operation_id, @@ -508,7 +511,7 @@ async fn test_gateway_client_intercept_valid_htlc() -> anyhow::Result<()> { // Run gateway state machine let htlc = Htlc { - payment_hash: *invoice.payment_hash(), + payment_hash: bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()), incoming_amount_msat: Amount::from_msats(invoice.amount_milli_satoshis().unwrap()), outgoing_amount_msat: Amount::from_msats(invoice.amount_milli_satoshis().unwrap()), incoming_expiry: u32::MAX, @@ -599,7 +602,7 @@ async fn test_gateway_client_intercept_htlc_no_funds() -> anyhow::Result<()> { // Run gateway state machine let htlc = Htlc { - payment_hash: *invoice.payment_hash(), + payment_hash: bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()), incoming_amount_msat: Amount::from_msats(invoice.amount_milli_satoshis().unwrap()), outgoing_amount_msat: Amount::from_msats(invoice.amount_milli_satoshis().unwrap()), incoming_expiry: u32::MAX, @@ -648,7 +651,7 @@ async fn test_gateway_client_intercept_htlc_invalid_offer() -> anyhow::Result<() let preimage = BYTE_33; let ln_output = LightningOutput::new_v0_offer(IncomingContractOffer { amount, - hash: *invoice.payment_hash(), + hash: bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()), encrypted_preimage: EncryptedPreimage::new( &PreimageKey(preimage), &user_lightning_module.cfg.threshold_pub_key, @@ -675,7 +678,9 @@ async fn test_gateway_client_intercept_htlc_invalid_offer() -> anyhow::Result<() .expect("Failed to serialize string into json"), }; - let operation_id = OperationId(invoice.payment_hash().to_byte_array()); + let operation_id = OperationId( + bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()).to_byte_array(), + ); let (txid, _) = user_client .finalize_and_submit_transaction( operation_id, @@ -693,7 +698,7 @@ async fn test_gateway_client_intercept_htlc_invalid_offer() -> anyhow::Result<() // Run gateway state machine let htlc = Htlc { - payment_hash: *invoice.payment_hash(), + payment_hash: bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()), incoming_amount_msat: Amount::from_msats(invoice.amount_milli_satoshis().unwrap()), outgoing_amount_msat: Amount::from_msats(invoice.amount_milli_satoshis().unwrap()), incoming_expiry: u32::MAX, diff --git a/modules/fedimint-ln-client/Cargo.toml b/modules/fedimint-ln-client/Cargo.toml index 714e9ff3092..3d8133a8ae0 100644 --- a/modules/fedimint-ln-client/Cargo.toml +++ b/modules/fedimint-ln-client/Cargo.toml @@ -28,7 +28,7 @@ anyhow = { workspace = true } aquamarine = { workspace = true } async-stream = { workspace = true } async-trait = { workspace = true } -bitcoin30 = { workspace = true } +bitcoin = { workspace = true } clap = { workspace = true, optional = true } erased-serde = { workspace = true } fedimint-api-client = { workspace = true } diff --git a/modules/fedimint-ln-client/src/api.rs b/modules/fedimint-ln-client/src/api.rs index fc91a059173..c94782bf462 100644 --- a/modules/fedimint-ln-client/src/api.rs +++ b/modules/fedimint-ln-client/src/api.rs @@ -1,7 +1,7 @@ use std::collections::{BTreeMap, HashMap}; use std::time::Duration; -use bitcoin30::hashes::sha256::{self, Hash as Sha256Hash}; +use bitcoin::hashes::sha256::{self, Hash as Sha256Hash}; use fedimint_api_client::api::{ FederationApiExt, FederationError, FederationResult, IModuleFederationApi, }; diff --git a/modules/fedimint-ln-client/src/db.rs b/modules/fedimint-ln-client/src/db.rs index 2927e92db1d..278e3487dc3 100644 --- a/modules/fedimint-ln-client/src/db.rs +++ b/modules/fedimint-ln-client/src/db.rs @@ -1,6 +1,6 @@ use std::io::Cursor; -use bitcoin30::hashes::sha256; +use bitcoin::hashes::sha256; use fedimint_core::core::OperationId; use fedimint_core::encoding::{Decodable, Encodable}; use fedimint_core::module::registry::ModuleDecoderRegistry; diff --git a/modules/fedimint-ln-client/src/incoming.rs b/modules/fedimint-ln-client/src/incoming.rs index eda41a5b521..8de421fb2db 100644 --- a/modules/fedimint-ln-client/src/incoming.rs +++ b/modules/fedimint-ln-client/src/incoming.rs @@ -10,7 +10,7 @@ use core::fmt; use std::time::Duration; -use bitcoin30::hashes::sha256; +use bitcoin::hashes::sha256; use fedimint_client::sm::{ClientSMDatabaseTransaction, State, StateTransition}; use fedimint_client::transaction::{ClientInput, ClientInputBundle}; use fedimint_client::DynGlobalClientContext; diff --git a/modules/fedimint-ln-client/src/lib.rs b/modules/fedimint-ln-client/src/lib.rs index b6a69aa3db8..98bf45f0bdf 100644 --- a/modules/fedimint-ln-client/src/lib.rs +++ b/modules/fedimint-ln-client/src/lib.rs @@ -23,9 +23,8 @@ use std::time::Duration; use anyhow::{anyhow, bail, ensure, format_err, Context}; use api::LnFederationApi; use async_stream::{stream, try_stream}; -use bitcoin30::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine}; -use bitcoin30::secp256k1::ThirtyTwoByteHash; -use bitcoin30::Network; +use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine}; +use bitcoin::Network; use db::{ DbKeyPrefix, LightningGatewayKey, LightningGatewayKeyPrefix, PaymentResult, PaymentResultKey, }; @@ -44,9 +43,9 @@ use fedimint_client::transaction::{ }; use fedimint_client::{sm_enum_variant_translation, DynGlobalClientContext}; use fedimint_core::bitcoin_migration::{ - bitcoin30_to_bitcoin32_secp256k1_message, bitcoin30_to_bitcoin32_secp256k1_pubkey, + bitcoin30_to_bitcoin32_secp256k1_message, bitcoin30_to_bitcoin32_sha256_hash, bitcoin32_to_bitcoin30_network, bitcoin32_to_bitcoin30_recoverable_signature, - bitcoin32_to_bitcoin30_secp256k1_pubkey, + bitcoin32_to_bitcoin30_secp256k1_pubkey, bitcoin32_to_bitcoin30_sha256_hash, }; use fedimint_core::config::FederationId; use fedimint_core::core::{Decoder, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId}; @@ -58,6 +57,7 @@ use fedimint_core::module::{ use fedimint_core::secp256k1::{ All, Keypair, PublicKey, Scalar, Secp256k1, SecretKey, Signing, Verification, }; +use fedimint_core::secp256k1_27::ThirtyTwoByteHash; use fedimint_core::task::{timeout, MaybeSend, MaybeSync}; use fedimint_core::util::update_merge::UpdateMerge; use fedimint_core::util::{backoff_util, retry, BoxStream}; @@ -733,8 +733,8 @@ impl LightningClientModule { let user_sk = Keypair::new(&self.secp, &mut rng); - let preimage_auth = self.get_preimage_authentication(invoice.payment_hash()); - let payment_hash = *invoice.payment_hash(); + let payment_hash = bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()); + let preimage_auth = self.get_preimage_authentication(&payment_hash); let contract = OutgoingContract { hash: payment_hash, gateway_key: gateway.gateway_redeem_key, @@ -803,7 +803,7 @@ impl LightningClientModule { ClientOutputSM, ContractId, )> { - let payment_hash = invoice.payment_hash(); + let payment_hash = bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()); let invoice_amount = Amount { msats: invoice .amount_milli_satoshis() @@ -814,7 +814,7 @@ impl LightningClientModule { let (incoming_output, amount, contract_id) = create_incoming_contract_output( &self.module_api, - *payment_hash, + payment_hash, invoice_amount, &self.redeem_key, ) @@ -832,7 +832,7 @@ impl LightningClientModule { common: IncomingSmCommon { operation_id, contract_id, - payment_hash: *invoice.payment_hash(), + payment_hash, }, state: IncomingSmStates::FundingOffer(FundingOfferState { txid }), }, @@ -939,17 +939,18 @@ impl LightningClientModule { let duration_since_epoch = fedimint_core::time::duration_since_epoch(); - let mut invoice_builder = InvoiceBuilder::new(network.into()) - .amount_milli_satoshis(amount.msats) - .invoice_description(description) - .payment_hash(payment_hash) - .payment_secret(PaymentSecret(rng.gen())) - .duration_since_epoch(duration_since_epoch) - .min_final_cltv_expiry_delta(18) - .payee_pub_key(bitcoin32_to_bitcoin30_secp256k1_pubkey(&node_public_key)) - .expiry_time(Duration::from_secs( - expiry_time.unwrap_or(DEFAULT_INVOICE_EXPIRY_TIME.as_secs()), - )); + let mut invoice_builder = + InvoiceBuilder::new(bitcoin32_to_bitcoin30_network(&network).into()) + .amount_milli_satoshis(amount.msats) + .invoice_description(description) + .payment_hash(bitcoin32_to_bitcoin30_sha256_hash(&payment_hash)) + .payment_secret(PaymentSecret(rng.gen())) + .duration_since_epoch(duration_since_epoch) + .min_final_cltv_expiry_delta(18) + .payee_pub_key(bitcoin32_to_bitcoin30_secp256k1_pubkey(&node_public_key)) + .expiry_time(Duration::from_secs( + expiry_time.unwrap_or(DEFAULT_INVOICE_EXPIRY_TIME.as_secs()), + )); for rh in final_route_hints { invoice_builder = invoice_builder.private_route(rh); @@ -962,7 +963,8 @@ impl LightningClientModule { )) })?; - let operation_id = OperationId(invoice.payment_hash().to_byte_array()); + let operation_id = + OperationId(bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()).to_byte_array()); let sm_invoice = invoice.clone(); let sm_gen = Arc::new(move |txid: TransactionId, _| { @@ -1000,7 +1002,7 @@ impl LightningClientModule { state_machines: sm_gen, }], ), - preimage.into_32(), + bitcoin32_to_bitcoin30_sha256_hash(&preimage).into_32(), )) } @@ -1115,11 +1117,12 @@ impl LightningClientModule { extra_meta: M, ) -> anyhow::Result { let mut dbtx = self.client_ctx.module_db().begin_transaction().await; - let maybe_gateway_id = maybe_gateway - .as_ref() - .map(|g| bitcoin32_to_bitcoin30_secp256k1_pubkey(&g.gateway_id)); + let maybe_gateway_id = maybe_gateway.as_ref().map(|g| g.gateway_id); let prev_payment_result = self - .get_prev_payment_result(invoice.payment_hash(), &mut dbtx.to_ref_nc()) + .get_prev_payment_result( + &bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()), + &mut dbtx.to_ref_nc(), + ) .await; if let Some(completed_payment) = prev_payment_result.completed_payment { @@ -1128,7 +1131,7 @@ impl LightningClientModule { // Verify that no previous payment attempt is still running let prev_operation_id = LightningClientModule::get_payment_operation_id( - invoice.payment_hash(), + &bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()), prev_payment_result.index, ); if self.client_ctx.has_active_states(prev_operation_id).await { @@ -1140,8 +1143,10 @@ impl LightningClientModule { } let next_index = prev_payment_result.index + 1; - let operation_id = - LightningClientModule::get_payment_operation_id(invoice.payment_hash(), next_index); + let operation_id = LightningClientModule::get_payment_operation_id( + &bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()), + next_index, + ); let new_payment_result = PaymentResult { index: next_index, @@ -1150,7 +1155,7 @@ impl LightningClientModule { dbtx.insert_entry( &PaymentResultKey { - payment_hash: *invoice.payment_hash(), + payment_hash: bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()), }, &new_payment_result, ) @@ -1246,7 +1251,7 @@ impl LightningClientModule { change, is_internal_payment, contract_id, - gateway_id: maybe_gateway_id.map(|pk| bitcoin30_to_bitcoin32_secp256k1_pubkey(&pk)), + gateway_id: maybe_gateway_id, }), extra_meta: extra_meta.clone(), }; @@ -1618,9 +1623,7 @@ impl LightningClientModule { extra_meta: M, gateway: Option, ) -> anyhow::Result<(OperationId, Bolt11Invoice, [u8; 32])> { - let gateway_id = gateway - .as_ref() - .map(|g| bitcoin32_to_bitcoin30_secp256k1_pubkey(&g.gateway_id)); + let gateway_id = gateway.as_ref().map(|g| g.gateway_id); let (src_node_id, short_channel_id, route_hints) = if let Some(current_gateway) = gateway { ( current_gateway.node_pub_key, @@ -1644,7 +1647,7 @@ impl LightningClientModule { src_node_id, short_channel_id, &route_hints, - bitcoin32_to_bitcoin30_network(&self.cfg.network), + self.cfg.network, )?; let tx = @@ -1654,7 +1657,7 @@ impl LightningClientModule { variant: LightningOperationMetaVariant::Receive { out_point: OutPoint { txid, out_idx: 0 }, invoice: invoice.clone(), - gateway_id: gateway_id.map(|pk| bitcoin30_to_bitcoin32_secp256k1_pubkey(&pk)), + gateway_id, }, extra_meta: extra_meta.clone(), }; diff --git a/modules/fedimint-ln-client/src/pay.rs b/modules/fedimint-ln-client/src/pay.rs index 4c07d193653..7fb169151ee 100644 --- a/modules/fedimint-ln-client/src/pay.rs +++ b/modules/fedimint-ln-client/src/pay.rs @@ -1,10 +1,12 @@ use std::time::{Duration, SystemTime}; -use bitcoin30::hashes::sha256; +use bitcoin::hashes::sha256; use fedimint_client::sm::{ClientSMDatabaseTransaction, State, StateTransition}; use fedimint_client::transaction::{ClientInput, ClientInputBundle}; use fedimint_client::DynGlobalClientContext; -use fedimint_core::bitcoin_migration::bitcoin30_to_bitcoin32_secp256k1_pubkey; +use fedimint_core::bitcoin_migration::{ + bitcoin30_to_bitcoin32_secp256k1_pubkey, bitcoin30_to_bitcoin32_sha256_hash, +}; use fedimint_core::config::FederationId; use fedimint_core::core::{Decoder, OperationId}; use fedimint_core::encoding::{Decodable, Encodable}; @@ -297,7 +299,7 @@ impl LightningPayFunded { let payload = self.payload.clone(); let contract_id = self.payload.contract_id; let timelock = self.timelock; - let payment_hash = *common.invoice.payment_hash(); + let payment_hash = bitcoin30_to_bitcoin32_sha256_hash(common.invoice.payment_hash()); let success_common = common.clone(); let timeout_common = common.clone(); let timeout_global_context = global_context.clone(); @@ -641,7 +643,9 @@ impl PaymentData { pub fn payment_hash(&self) -> sha256::Hash { match self { - PaymentData::Invoice(invoice) => *invoice.payment_hash(), + PaymentData::Invoice(invoice) => { + bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()) + } PaymentData::PrunedInvoice(PrunedInvoice { payment_hash, .. }) => *payment_hash, } } diff --git a/modules/fedimint-ln-client/src/receive.rs b/modules/fedimint-ln-client/src/receive.rs index 2d8ad195d78..40037e29c39 100644 --- a/modules/fedimint-ln-client/src/receive.rs +++ b/modules/fedimint-ln-client/src/receive.rs @@ -1,13 +1,10 @@ use std::time::Duration; -use bitcoin30::key::KeyPair; use fedimint_api_client::api::DynModuleApi; use fedimint_client::sm::{ClientSMDatabaseTransaction, DynState, State, StateTransition}; use fedimint_client::transaction::{ClientInput, ClientInputBundle}; use fedimint_client::DynGlobalClientContext; -use fedimint_core::bitcoin_migration::{ - bitcoin30_to_bitcoin32_keypair, bitcoin32_to_bitcoin30_keypair, -}; +use fedimint_core::bitcoin_migration::bitcoin30_to_bitcoin32_sha256_hash; use fedimint_core::core::{IntoDynInstance, ModuleInstanceId, OperationId}; use fedimint_core::encoding::{Decodable, Encodable}; use fedimint_core::secp256k1::Keypair; @@ -204,7 +201,7 @@ impl LightningReceiveConfirmedInvoice { invoice: Bolt11Invoice, global_context: DynGlobalClientContext, ) -> Result { - let contract_id = (*invoice.payment_hash()).into(); + let contract_id = bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()).into(); loop { // Consider time before the api call to account for network delays let now_epoch = fedimint_core::time::duration_since_epoch(); @@ -251,13 +248,9 @@ impl LightningReceiveConfirmedInvoice { Ok(contract) => { match receiving_key { ReceivingKey::Personal(keypair) => { - let (txid, out_points) = Self::claim_incoming_contract( - dbtx, - contract, - bitcoin32_to_bitcoin30_keypair(&keypair), - global_context, - ) - .await; + let (txid, out_points) = + Self::claim_incoming_contract(dbtx, contract, keypair, global_context) + .await; LightningReceiveStateMachine { operation_id: old_state.operation_id, state: LightningReceiveStates::Funded(LightningReceiveFunded { @@ -285,14 +278,14 @@ impl LightningReceiveConfirmedInvoice { async fn claim_incoming_contract( dbtx: &mut ClientSMDatabaseTransaction<'_, '_>, contract: IncomingContractAccount, - keypair: KeyPair, + keypair: Keypair, global_context: DynGlobalClientContext, ) -> (TransactionId, Vec) { let input = contract.claim(); let client_input = ClientInput:: { input, amount: contract.amount, - keys: vec![bitcoin30_to_bitcoin32_keypair(&keypair)], + keys: vec![keypair], }; global_context @@ -399,9 +392,10 @@ impl LightningReceiveFunded { #[cfg(test)] mod tests { - use bitcoin30::hashes::{sha256, Hash}; + use bitcoin::hashes::{sha256, Hash}; use fedimint_core::bitcoin_migration::{ bitcoin30_to_bitcoin32_secp256k1_message, bitcoin32_to_bitcoin30_recoverable_signature, + bitcoin32_to_bitcoin30_sha256_hash, }; use fedimint_core::secp256k1::{Secp256k1, SecretKey}; use lightning_invoice::{Currency, InvoiceBuilder, PaymentSecret}; @@ -443,7 +437,9 @@ mod tests { let secret_key = SecretKey::new(&mut rand::thread_rng()); Ok(InvoiceBuilder::new(Currency::Regtest) .description(String::new()) - .payment_hash(sha256::Hash::hash(&[0; 32])) + .payment_hash(bitcoin32_to_bitcoin30_sha256_hash(&sha256::Hash::hash( + &[0; 32], + ))) .duration_since_epoch(now_epoch) .min_final_cltv_expiry_delta(0) .payment_secret(PaymentSecret([0; 32])) diff --git a/modules/fedimint-ln-common/Cargo.toml b/modules/fedimint-ln-common/Cargo.toml index baf37750e01..a4ac4759401 100644 --- a/modules/fedimint-ln-common/Cargo.toml +++ b/modules/fedimint-ln-common/Cargo.toml @@ -22,7 +22,6 @@ path = "src/lib.rs" [dependencies] anyhow = { workspace = true } bitcoin = { workspace = true } -bitcoin30 = { workspace = true } fedimint-client = { workspace = true } fedimint-core = { workspace = true } lightning = { workspace = true } diff --git a/modules/fedimint-ln-common/src/contracts/incoming.rs b/modules/fedimint-ln-common/src/contracts/incoming.rs index f266f022b47..0bd00830db8 100644 --- a/modules/fedimint-ln-common/src/contracts/incoming.rs +++ b/modules/fedimint-ln-common/src/contracts/incoming.rs @@ -1,7 +1,7 @@ use std::io::Error; -use bitcoin30::hashes::sha256::Hash as Sha256; -use bitcoin30::hashes::{hash_newtype, Hash as BitcoinHash}; +use bitcoin::hashes::sha256::Hash as Sha256; +use bitcoin::hashes::{hash_newtype, Hash as BitcoinHash}; use fedimint_core::encoding::{Decodable, DecodeError, Encodable}; use fedimint_core::module::registry::ModuleDecoderRegistry; use fedimint_core::{secp256k1, Amount, OutPoint}; @@ -14,7 +14,7 @@ use crate::LightningInput; pub struct IncomingContractOffer { /// Amount for which the user is willing to sell the preimage pub amount: fedimint_core::Amount, - pub hash: bitcoin30::hashes::sha256::Hash, + pub hash: bitcoin::hashes::sha256::Hash, pub encrypted_preimage: EncryptedPreimage, pub expiry_time: Option, } @@ -57,7 +57,7 @@ impl IncomingContractOffer { #[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)] pub struct IncomingContract { /// Payment hash which's corresponding preimage is being sold - pub hash: bitcoin30::hashes::sha256::Hash, + pub hash: bitcoin::hashes::sha256::Hash, /// Encrypted preimage as specified in offer pub encrypted_preimage: EncryptedPreimage, /// Status of preimage decryption, will either end in failure or contain the diff --git a/modules/fedimint-ln-common/src/contracts/mod.rs b/modules/fedimint-ln-common/src/contracts/mod.rs index 2dab13975eb..81f17d81689 100644 --- a/modules/fedimint-ln-common/src/contracts/mod.rs +++ b/modules/fedimint-ln-common/src/contracts/mod.rs @@ -3,8 +3,8 @@ pub mod outgoing; use std::io::Error; -use bitcoin30::hashes::sha256::Hash as Sha256; -use bitcoin30::hashes::{hash_newtype, Hash as BitcoinHash}; +use bitcoin::hashes::sha256::Hash as Sha256; +use bitcoin::hashes::{hash_newtype, Hash as BitcoinHash}; use fedimint_core::encoding::{Decodable, DecodeError, Encodable}; use fedimint_core::module::registry::ModuleDecoderRegistry; use fedimint_core::{secp256k1, OutPoint}; diff --git a/modules/fedimint-ln-common/src/contracts/outgoing.rs b/modules/fedimint-ln-common/src/contracts/outgoing.rs index f4ab2a4ca5f..e10bb010bdd 100644 --- a/modules/fedimint-ln-common/src/contracts/outgoing.rs +++ b/modules/fedimint-ln-common/src/contracts/outgoing.rs @@ -1,4 +1,4 @@ -use bitcoin30::hashes::Hash as BitcoinHash; +use bitcoin::hashes::Hash as BitcoinHash; use fedimint_core::encoding::{Decodable, Encodable}; use fedimint_core::secp256k1::PublicKey; use fedimint_core::Amount; @@ -19,7 +19,7 @@ const CANCELLATION_TAG: &str = "outgoing contract cancellation"; #[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)] pub struct OutgoingContract { /// Hash that can be used to spend the output before the timelock expires - pub hash: bitcoin30::hashes::sha256::Hash, + pub hash: bitcoin::hashes::sha256::Hash, /// Public key of the LN gateway allowed to claim the HTLC before the /// timelock expires pub gateway_key: PublicKey, @@ -45,12 +45,12 @@ impl IdentifiableContract for OutgoingContract { } impl OutgoingContract { - pub fn cancellation_message(&self) -> bitcoin30::hashes::sha256::Hash { - let mut engine = bitcoin30::hashes::sha256::Hash::engine(); + pub fn cancellation_message(&self) -> bitcoin::hashes::sha256::Hash { + let mut engine = bitcoin::hashes::sha256::Hash::engine(); Encodable::consensus_encode(&CANCELLATION_TAG.as_bytes(), &mut engine) .expect("Hashing never fails"); Encodable::consensus_encode(&self.contract_id(), &mut engine).expect("Hashing never fails"); - bitcoin30::hashes::sha256::Hash::from_engine(engine) + bitcoin::hashes::sha256::Hash::from_engine(engine) } } diff --git a/modules/fedimint-ln-common/src/lib.rs b/modules/fedimint-ln-common/src/lib.rs index 5c052eed756..571d26bd552 100644 --- a/modules/fedimint-ln-common/src/lib.rs +++ b/modules/fedimint-ln-common/src/lib.rs @@ -30,7 +30,9 @@ use bitcoin::hashes::{sha256, Hash}; use config::LightningClientConfig; use fedimint_client::oplog::OperationLogEntry; use fedimint_client::ClientHandleArc; -use fedimint_core::bitcoin_migration::bitcoin30_to_bitcoin32_secp256k1_pubkey; +use fedimint_core::bitcoin_migration::{ + bitcoin30_to_bitcoin32_secp256k1_pubkey, bitcoin30_to_bitcoin32_sha256_hash, +}; use fedimint_core::core::{Decoder, ModuleInstanceId, ModuleKind, OperationId}; use fedimint_core::encoding::{Decodable, DecodeError, Encodable}; use fedimint_core::module::registry::ModuleDecoderRegistry; @@ -47,7 +49,7 @@ use serde::{Deserialize, Serialize}; use thiserror::Error; use threshold_crypto::PublicKey; use tracing::error; -pub use {bitcoin30 as bitcoin, lightning_invoice}; +pub use {bitcoin, lightning_invoice}; use crate::contracts::incoming::OfferId; use crate::contracts::{Contract, ContractId, ContractOutcome, Preimage, PreimageDecryptionShare}; @@ -627,7 +629,7 @@ pub enum LightningOutputError { #[error("The incoming LN account requires more funding (need {0} got {1})")] InsufficientIncomingFunding(Amount, Amount), #[error("No offer found for payment hash {0}")] - NoOffer(bitcoin30::secp256k1::hashes::sha256::Hash), + NoOffer(bitcoin::secp256k1::hashes::sha256::Hash), #[error("Only outgoing contracts support cancellation")] NotOutgoingContract, #[error("Cancellation request wasn't properly signed")] @@ -697,7 +699,7 @@ impl PrunedInvoice { .unwrap_or_else(|| invoice.recover_payee_pub_key()), ), destination_features, - payment_hash: *invoice.payment_hash(), + payment_hash: bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()), payment_secret: invoice.payment_secret().0, route_hints: invoice.route_hints().into_iter().map(Into::into).collect(), min_final_cltv_delta: invoice.min_final_cltv_expiry_delta(), diff --git a/modules/fedimint-ln-server/Cargo.toml b/modules/fedimint-ln-server/Cargo.toml index 78bf3595aed..ba2de85121b 100644 --- a/modules/fedimint-ln-server/Cargo.toml +++ b/modules/fedimint-ln-server/Cargo.toml @@ -18,7 +18,7 @@ path = "src/lib.rs" [dependencies] anyhow = { workspace = true } async-trait = { workspace = true } -bitcoin_hashes = { package = "bitcoin_hashes", version = "0.12.0" } +bitcoin_hashes = { workspace = true } erased-serde = { workspace = true } fedimint-bitcoind = { workspace = true } fedimint-core = { workspace = true } diff --git a/modules/fedimint-ln-server/src/lib.rs b/modules/fedimint-ln-server/src/lib.rs index 4906be79813..6d38e8fc068 100644 --- a/modules/fedimint-ln-server/src/lib.rs +++ b/modules/fedimint-ln-server/src/lib.rs @@ -11,7 +11,6 @@ use std::time::Duration; use anyhow::{bail, Context}; use bitcoin_hashes::{sha256, Hash as BitcoinHash}; use fedimint_bitcoind::{create_bitcoind, DynBitcoindRpc}; -use fedimint_core::bitcoin_migration::bitcoin30_to_bitcoin32_secp256k1_message; use fedimint_core::config::{ ConfigGenModuleParams, DkgResult, ServerModuleConfig, ServerModuleConsensusConfig, TypedServerModuleConfig, TypedServerModuleConsensusConfig, @@ -25,7 +24,7 @@ use fedimint_core::module::{ ModuleConsensusVersion, ModuleInit, PeerHandle, ServerModuleInit, ServerModuleInitArgs, SupportedModuleApiVersions, TransactionItemAmount, CORE_CONSENSUS_VERSION, }; -use fedimint_core::secp256k1::{PublicKey, SECP256K1}; +use fedimint_core::secp256k1::{Message, PublicKey, SECP256K1}; use fedimint_core::server::DynServerModule; use fedimint_core::task::{sleep, TaskGroup}; use fedimint_core::{ @@ -707,9 +706,7 @@ impl ServerModule for Lightning { // Check that each preimage is only offered for sale once, see #1397 if dbtx .insert_entry( - &EncryptedPreimageIndexKey( - offer.encrypted_preimage.consensus_hash_bitcoin30(), - ), + &EncryptedPreimageIndexKey(offer.encrypted_preimage.consensus_hash()), &(), ) .await @@ -753,9 +750,7 @@ impl ServerModule for Lightning { SECP256K1 .verify_schnorr( gateway_signature, - &bitcoin30_to_bitcoin32_secp256k1_message( - &outgoing_contract.cancellation_message().into(), - ), + &Message::from_digest(*outgoing_contract.cancellation_message().as_ref()), &outgoing_contract.gateway_key.x_only_public_key().0, ) .map_err(|_| LightningOutputError::InvalidCancellationSignature)?; @@ -1323,7 +1318,7 @@ mod tests { let preimage = [42u8; 32]; let encrypted_preimage = EncryptedPreimage(client_cfg.threshold_pub_key.encrypt([42; 32])); - let hash = preimage.consensus_hash_bitcoin30(); + let hash = preimage.consensus_hash(); let offer = IncomingContractOffer { amount: Amount::from_sats(10), hash, @@ -1348,7 +1343,7 @@ mod tests { .await .expect("First time works"); - let hash2 = [21u8, 32].consensus_hash_bitcoin30(); + let hash2 = [21u8, 32].consensus_hash(); let offer2 = IncomingContractOffer { amount: Amount::from_sats(1), hash: hash2, @@ -1446,7 +1441,7 @@ mod tests { let preimage = Preimage([42u8; 32]); let gateway_key = random_pub_key(); let outgoing_contract = FundedContract::Outgoing(OutgoingContract { - hash: preimage.consensus_hash_bitcoin30(), + hash: preimage.consensus_hash(), gateway_key, timelock: 1_000_000, user_key: random_pub_key(), diff --git a/modules/fedimint-ln-tests/tests/tests.rs b/modules/fedimint-ln-tests/tests/tests.rs index e065181b327..5f320360792 100644 --- a/modules/fedimint-ln-tests/tests/tests.rs +++ b/modules/fedimint-ln-tests/tests/tests.rs @@ -617,7 +617,6 @@ mod fedimint_migration_tests { }; use fedimint_core::encoding::Encodable; use fedimint_core::module::DynServerModuleInit; - use fedimint_core::secp256k1_27::hashes::Hash; use fedimint_core::util::SafeUrl; use fedimint_core::{secp256k1, Amount, OutPoint, PeerId, TransactionId}; use fedimint_ln_client::db::{PaymentResult, PaymentResultKey, PaymentResultPrefix}; @@ -687,9 +686,7 @@ mod fedimint_migration_tests { let threshold_key = threshold_crypto::PublicKey::from(G1Projective::identity()); let (_, pk) = fedimint_core::secp256k1::generate_keypair(&mut OsRng); let incoming_contract = IncomingContract { - hash: bitcoin32_to_bitcoin30_sha256_hash(&secp256k1::hashes::sha256::Hash::hash( - &BYTE_8, - )), + hash: secp256k1::hashes::sha256::Hash::hash(&BYTE_8), encrypted_preimage: EncryptedPreimage::new(&PreimageKey(BYTE_33), &threshold_key), decrypted_preimage: DecryptedPreimage::Some(PreimageKey(BYTE_33)), gateway_key: pk, @@ -711,9 +708,7 @@ mod fedimint_migration_tests { ) .await; let outgoing_contract = FundedContract::Outgoing(outgoing::OutgoingContract { - hash: bitcoin32_to_bitcoin30_sha256_hash(&secp256k1::hashes::sha256::Hash::hash(&[ - 0, 2, 3, 4, 5, 6, 7, 8, - ])), + hash: secp256k1::hashes::sha256::Hash::hash(&[0, 2, 3, 4, 5, 6, 7, 8]), gateway_key: pk, timelock: 1000000, user_key: pk, @@ -730,9 +725,7 @@ mod fedimint_migration_tests { let incoming_offer = IncomingContractOffer { amount: fedimint_core::Amount { msats: 1000 }, - hash: bitcoin32_to_bitcoin30_sha256_hash(&secp256k1::hashes::sha256::Hash::hash( - &BYTE_8, - )), + hash: secp256k1::hashes::sha256::Hash::hash(&BYTE_8), encrypted_preimage: EncryptedPreimage::new(&PreimageKey(BYTE_33), &threshold_key), expiry_time: None, }; @@ -787,11 +780,8 @@ mod fedimint_migration_tests { dbtx.insert_new_entry(&BlockCountVoteKey(PeerId::from(0)), &1) .await; - dbtx.insert_new_entry( - &EncryptedPreimageIndexKey("foobar".consensus_hash_bitcoin30()), - &(), - ) - .await; + dbtx.insert_new_entry(&EncryptedPreimageIndexKey("foobar".consensus_hash()), &()) + .await; dbtx.insert_new_entry( &LightningAuditItemKey::from_funded_contract(&incoming_contract), @@ -864,14 +854,13 @@ mod fedimint_migration_tests { dbtx.insert_new_entry( &PaymentResultKey { - payment_hash: bitcoin32_to_bitcoin30_sha256_hash(&sha256::Hash::hash(&BYTE_8)), + payment_hash: sha256::Hash::hash(&BYTE_8), }, &PaymentResult { index: 0, completed_payment: Some(OutgoingLightningPayment { payment_type: fedimint_ln_client::PayType::Lightning(OperationId(BYTE_32)), - contract_id: bitcoin32_to_bitcoin30_sha256_hash(&sha256::Hash::hash(&BYTE_8)) - .into(), + contract_id: sha256::Hash::hash(&BYTE_8).into(), fee: Amount::from_sats(1000), }), }, @@ -956,7 +945,7 @@ mod fedimint_migration_tests { let (sk, pk) = secp256k1::generate_keypair(&mut OsRng); let outgoing_contract = OutgoingContract { - hash: bitcoin32_to_bitcoin30_sha256_hash(&sha256::Hash::hash(&BYTE_32)), + hash: sha256::Hash::hash(&BYTE_32), gateway_key: pk, timelock: 1000, user_key: pk, @@ -975,7 +964,7 @@ mod fedimint_migration_tests { federation_id: FederationId::dummy(), contract, gateway_fee: Amount::from_msats(1000), - preimage_auth: bitcoin32_to_bitcoin30_sha256_hash(&sha256::Hash::hash(&BYTE_32)), + preimage_auth: sha256::Hash::hash(&BYTE_32), invoice: invoice.clone(), }; @@ -1008,7 +997,7 @@ mod fedimint_migration_tests { federation_id: FederationId::dummy(), contract_id: outgoing_contract.contract_id(), payment_data: PaymentData::Invoice(invoice), - preimage_auth: bitcoin32_to_bitcoin30_sha256_hash(&sha256::Hash::hash(&BYTE_32)), + preimage_auth: sha256::Hash::hash(&BYTE_32), } .consensus_encode(&mut funded_state) .expect("PayInvoicePayload is encodable"); diff --git a/modules/fedimint-lnv2-client/src/lib.rs b/modules/fedimint-lnv2-client/src/lib.rs index bf46a04db09..5f3c321d620 100644 --- a/modules/fedimint-lnv2-client/src/lib.rs +++ b/modules/fedimint-lnv2-client/src/lib.rs @@ -847,7 +847,7 @@ impl LightningClientModule { .await .map_err(ReceiveError::GatewayConnectionError)?; - if invoice.payment_hash() != &preimage.consensus_hash_bitcoin30() { + if bitcoin30_to_bitcoin32_sha256_hash(invoice.payment_hash()) != preimage.consensus_hash() { return Err(ReceiveError::InvalidInvoicePaymentHash); } diff --git a/modules/fedimint-lnv2-server/src/lib.rs b/modules/fedimint-lnv2-server/src/lib.rs index 0e19712e004..93bfc232a14 100644 --- a/modules/fedimint-lnv2-server/src/lib.rs +++ b/modules/fedimint-lnv2-server/src/lib.rs @@ -10,9 +10,6 @@ use std::time::Duration; use anyhow::{anyhow, ensure, Context}; use bls12_381::{G1Projective, Scalar}; use fedimint_bitcoind::{create_bitcoind, DynBitcoindRpc}; -use fedimint_core::bitcoin_migration::{ - bitcoin30_to_bitcoin32_secp256k1_pubkey, bitcoin32_to_bitcoin30_secp256k1_pubkey, -}; use fedimint_core::config::{ ConfigGenModuleParams, DkgResult, ServerModuleConfig, ServerModuleConsensusConfig, TypedServerModuleConfig, TypedServerModuleConsensusConfig, @@ -427,10 +424,7 @@ impl ServerModule for Lightning { } }; - ( - bitcoin32_to_bitcoin30_secp256k1_pubkey(&pub_key), - contract.amount, - ) + (pub_key, contract.amount) } LightningInputV0::Incoming(contract_id, agg_decryption_key) => { let contract = dbtx @@ -449,10 +443,7 @@ impl ServerModule for Lightning { None => contract.commitment.refund_pk, }; - ( - bitcoin32_to_bitcoin30_secp256k1_pubkey(&pub_key), - contract.commitment.amount, - ) + (pub_key, contract.commitment.amount) } }; @@ -461,7 +452,7 @@ impl ServerModule for Lightning { amount, fee: self.cfg.consensus.fee_consensus.fee(amount), }, - pub_key: bitcoin30_to_bitcoin32_secp256k1_pubkey(&pub_key), + pub_key, }) } diff --git a/modules/fedimint-lnv2-tests/tests/mock.rs b/modules/fedimint-lnv2-tests/tests/mock.rs index 36b2f4f6a3d..20637de4235 100644 --- a/modules/fedimint-lnv2-tests/tests/mock.rs +++ b/modules/fedimint-lnv2-tests/tests/mock.rs @@ -3,7 +3,7 @@ use std::time::Duration; use bitcoin::hashes::{sha256, Hash}; use bitcoin::secp256k1::{SecretKey, SECP256K1}; use fedimint_core::bitcoin_migration::{ - bitcoin30_to_bitcoin32_keypair, bitcoin32_to_bitcoin30_secp256k1_secret_key, + bitcoin30_to_bitcoin32_secp256k1_message, bitcoin32_to_bitcoin30_recoverable_signature, bitcoin32_to_bitcoin30_sha256_hash, }; use fedimint_core::config::FederationId; @@ -37,11 +37,9 @@ pub fn gateway() -> SafeUrl { } pub fn gateway_keypair() -> Keypair { - bitcoin30_to_bitcoin32_keypair( - &SecretKey::from_slice(&GATEWAY_SECRET) - .expect("32 bytes; within curve order") - .keypair(SECP256K1), - ) + SecretKey::from_slice(&GATEWAY_SECRET) + .expect("32 bytes; within curve order") + .keypair(SECP256K1) } pub fn payable_invoice() -> Bolt11Invoice { @@ -62,13 +60,18 @@ fn bolt_11_invoice(payment_secret: [u8; 32], currency: Currency) -> Bolt11Invoic InvoiceBuilder::new(currency) .description(String::new()) - .payment_hash(payment_hash) + .payment_hash(bitcoin32_to_bitcoin30_sha256_hash(&payment_hash)) .current_timestamp() .min_final_cltv_expiry_delta(0) .payment_secret(PaymentSecret(payment_secret)) .amount_milli_satoshis(1_000_000) .expiry_time(Duration::from_secs(DEFAULT_EXPIRY_TIME)) - .build_signed(|m| SECP256K1.sign_ecdsa_recoverable(m, &sk)) + .build_signed(|m| { + bitcoin32_to_bitcoin30_recoverable_signature( + &SECP256K1 + .sign_ecdsa_recoverable(&bitcoin30_to_bitcoin32_secp256k1_message(m), &sk), + ) + }) .expect("Invoice creation failed") } @@ -133,10 +136,10 @@ impl GatewayConnection for MockGatewayConnection { .amount_milli_satoshis(invoice_amount.msats) .expiry_time(Duration::from_secs(expiry_time as u64)) .build_signed(|m| { - SECP256K1.sign_ecdsa_recoverable( - m, - &bitcoin32_to_bitcoin30_secp256k1_secret_key(&self.keypair.secret_key()), - ) + bitcoin32_to_bitcoin30_recoverable_signature(&SECP256K1.sign_ecdsa_recoverable( + &bitcoin30_to_bitcoin32_secp256k1_message(m), + &self.keypair.secret_key(), + )) }) .unwrap()) } diff --git a/modules/fedimint-mint-client/src/lib.rs b/modules/fedimint-mint-client/src/lib.rs index 9ad327bf63c..6adae450d88 100644 --- a/modules/fedimint-mint-client/src/lib.rs +++ b/modules/fedimint-mint-client/src/lib.rs @@ -2388,8 +2388,7 @@ mod tests { use fedimint_core::module::registry::ModuleRegistry; use fedimint_core::util::SafeUrl; use fedimint_core::{ - secp256k1, Amount, BitcoinHash, OutPoint, PeerId, Tiered, TieredCounts, TieredMulti, - TransactionId, + secp256k1, Amount, OutPoint, PeerId, Tiered, TieredCounts, TieredMulti, TransactionId, }; use fedimint_mint_common::config::FeeConsensus; use itertools::Itertools; diff --git a/modules/fedimint-wallet-common/src/lib.rs b/modules/fedimint-wallet-common/src/lib.rs index 81c86dc503b..440b2b0d426 100644 --- a/modules/fedimint-wallet-common/src/lib.rs +++ b/modules/fedimint-wallet-common/src/lib.rs @@ -11,7 +11,6 @@ use bitcoin::address::NetworkUnchecked; use bitcoin::psbt::raw::ProprietaryKey; use bitcoin::{secp256k1, Address, Amount, BlockHash, Network, Txid}; use config::WalletClientConfig; -use fedimint_core::bitcoin_migration::bitcoin30_to_bitcoin32_amount; use fedimint_core::core::{Decoder, ModuleInstanceId, ModuleKind}; use fedimint_core::encoding::{Decodable, Encodable}; use fedimint_core::module::{CommonModuleInit, ModuleCommon, ModuleConsensusVersion}; @@ -231,7 +230,7 @@ impl PegOutFees { } pub fn amount(&self) -> Amount { - bitcoin30_to_bitcoin32_amount(&self.fee_rate.calculate_fee(self.total_weight)) + self.fee_rate.calculate_fee(self.total_weight) } } diff --git a/modules/fedimint-wallet-common/src/txoproof.rs b/modules/fedimint-wallet-common/src/txoproof.rs index a716827c7cc..8d127a13dc4 100644 --- a/modules/fedimint-wallet-common/src/txoproof.rs +++ b/modules/fedimint-wallet-common/src/txoproof.rs @@ -4,9 +4,6 @@ use std::hash::Hash; use anyhow::format_err; use bitcoin::secp256k1::{PublicKey, Secp256k1, Signing, Verification}; use bitcoin::{Amount, BlockHash, OutPoint, Transaction}; -use fedimint_core::bitcoin_migration::{ - bitcoin30_to_bitcoin32_block_hash, bitcoin32_to_bitcoin30_txid, -}; use fedimint_core::encoding::{Decodable, DecodeError, Encodable}; use fedimint_core::module::registry::ModuleDecoderRegistry; use fedimint_core::txoproof::TxOutProof; @@ -68,7 +65,7 @@ impl PegInProof { tweak_contract_key: PublicKey, ) -> Result { // TODO: remove redundancy with serde validation - if !txout_proof.contains_tx(bitcoin32_to_bitcoin30_txid(&transaction.compute_txid())) { + if !txout_proof.contains_tx(transaction.compute_txid()) { return Err(PegInProofError::TransactionNotInProof); } @@ -114,7 +111,7 @@ impl PegInProof { } pub fn proof_block(&self) -> BlockHash { - bitcoin30_to_bitcoin32_block_hash(&self.txout_proof.block()) + self.txout_proof.block() } pub fn tweak_contract_key(&self) -> &PublicKey { @@ -174,9 +171,10 @@ impl Tweakable for Descriptor { } fn validate_peg_in_proof(proof: &PegInProof) -> Result<(), anyhow::Error> { - if !proof.txout_proof.contains_tx(bitcoin32_to_bitcoin30_txid( - &proof.transaction.compute_txid(), - )) { + if !proof + .txout_proof + .contains_tx(proof.transaction.compute_txid()) + { return Err(format_err!("Supplied transaction is not included in proof",)); } diff --git a/modules/fedimint-wallet-server/src/lib.rs b/modules/fedimint-wallet-server/src/lib.rs index e047eae84bc..4f5604a63e0 100644 --- a/modules/fedimint-wallet-server/src/lib.rs +++ b/modules/fedimint-wallet-server/src/lib.rs @@ -34,8 +34,7 @@ use common::{ }; use fedimint_bitcoind::{create_bitcoind, DynBitcoindRpc}; use fedimint_core::bitcoin_migration::{ - bitcoin30_to_bitcoin32_amount, bitcoin30_to_bitcoin32_network, - bitcoin32_to_bitcoin30_unchecked_address, + bitcoin30_to_bitcoin32_network, bitcoin32_to_bitcoin30_unchecked_address, }; use fedimint_core::config::{ ConfigGenModuleParams, DkgResult, ServerModuleConfig, ServerModuleConsensusConfig, @@ -1544,11 +1543,7 @@ impl<'a> StatelessWallet<'a> { let mut selected_utxos: Vec<(UTXOKey, SpendableUTXO)> = vec![]; let mut fees = fee_rate.calculate_fee(total_weight); - while total_selected_value - < peg_out_amount - + change_script.minimal_non_dust() - + bitcoin30_to_bitcoin32_amount(&fees) - { + while total_selected_value < peg_out_amount + change_script.minimal_non_dust() + fees { match included_utxos.pop() { Some((utxo_key, utxo)) => { total_selected_value += utxo.amount; @@ -1562,7 +1557,7 @@ impl<'a> StatelessWallet<'a> { // We always pay ourselves change back to ensure that we don't lose anything due // to dust - let change = total_selected_value - bitcoin30_to_bitcoin32_amount(&fees) - peg_out_amount; + let change = total_selected_value - fees - peg_out_amount; let output: Vec = vec![ TxOut { value: peg_out_amount, diff --git a/modules/fedimint-wallet-tests/src/bin/circular-deposit-test.rs b/modules/fedimint-wallet-tests/src/bin/circular-deposit-test.rs index 1261baab0fe..cbffe026821 100644 --- a/modules/fedimint-wallet-tests/src/bin/circular-deposit-test.rs +++ b/modules/fedimint-wallet-tests/src/bin/circular-deposit-test.rs @@ -6,9 +6,6 @@ use bitcoincore_rpc::bitcoin::address::Address; use bitcoincore_rpc::bitcoin::Txid; use devimint::cmd; use devimint::federation::Client; -use fedimint_core::bitcoin_migration::{ - bitcoin32_to_bitcoin30_script_buf, bitcoin32_to_bitcoin30_tx, -}; use fedimint_core::encoding::Decodable; use tokio::try_join; @@ -46,15 +43,10 @@ async fn assert_withdrawal( let tx_hex = bitcoind.poll_get_transaction(txid).await?; let parsed_address = Address::from_str(&deposit_address)?; - let tx = bitcoin32_to_bitcoin30_tx(&Transaction::consensus_decode_hex( - &tx_hex, - &Default::default(), - )?); + let tx = Transaction::consensus_decode_hex(&tx_hex, &Default::default())?; assert!(tx.output.iter().any(|o| o.script_pubkey - == bitcoin32_to_bitcoin30_script_buf( - &parsed_address.clone().assume_checked().script_pubkey() - ) - && o.value == withdrawal_amount_sats)); + == parsed_address.clone().assume_checked().script_pubkey() + && o.value.to_sat() == withdrawal_amount_sats)); // Verify the receive client gets the deposit try_join!( diff --git a/modules/fedimint-wallet-tests/tests/tests.rs b/modules/fedimint-wallet-tests/tests/tests.rs index 5eb1901e495..d4198b23efb 100644 --- a/modules/fedimint-wallet-tests/tests/tests.rs +++ b/modules/fedimint-wallet-tests/tests/tests.rs @@ -7,9 +7,7 @@ use assert_matches::assert_matches; use bitcoin::secp256k1; use fedimint_client::secret::{PlainRootSecretStrategy, RootSecretStrategy}; use fedimint_client::ClientHandleArc; -use fedimint_core::bitcoin_migration::{ - bitcoin32_checked_address_to_unchecked_address, bitcoin32_to_bitcoin30_block_hash, -}; +use fedimint_core::bitcoin_migration::bitcoin32_checked_address_to_unchecked_address; use fedimint_core::db::mem_impl::MemDatabase; use fedimint_core::db::{DatabaseTransaction, IRawDatabaseExt}; use fedimint_core::envs::BitcoinRpcConfig; @@ -148,11 +146,9 @@ async fn sanity_check_bitcoin_blocks() -> anyhow::Result<()> { bitcoin.get_tx_block_height(&tx.compute_txid()).await, Some(expected_transaction_height), ); - let expected_transaction_block_hash = bitcoin32_to_bitcoin30_block_hash( - &dyn_bitcoin_rpc - .get_block_hash(expected_transaction_height) - .await?, - ); + let expected_transaction_block_hash = dyn_bitcoin_rpc + .get_block_hash(expected_transaction_height) + .await?; assert_eq!(proof.block(), expected_transaction_block_hash); Ok(()) @@ -1008,7 +1004,7 @@ mod fedimint_migration_tests { Database, DatabaseVersion, DatabaseVersionKeyV0, IDatabaseTransactionOpsCoreTyped, }; use fedimint_core::module::DynServerModuleInit; - use fedimint_core::{BitcoinHash, Feerate, OutPoint, PeerId, TransactionId}; + use fedimint_core::{Feerate, OutPoint, PeerId, TransactionId}; use fedimint_logging::TracingSetup; use fedimint_testing::db::{ snapshot_db_migrations, snapshot_db_migrations_client, validate_migrations_client, From d31a807cda15d8037b1d49e80f4a5bbb217b6d7d Mon Sep 17 00:00:00 2001 From: Tommy Volk Date: Fri, 8 Nov 2024 12:36:45 -0600 Subject: [PATCH 6/6] chore(deps): remove secp256k1 v0.27 --- Cargo.lock | 2 -- Cargo.toml | 1 - fedimint-core/Cargo.toml | 1 - fedimint-core/src/lib.rs | 2 +- modules/fedimint-ln-client/src/lib.rs | 3 +-- 5 files changed, 2 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 04f1b1f641a..639384374d5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2388,7 +2388,6 @@ dependencies = [ "miniscript", "parity-scale-codec", "rand", - "secp256k1 0.27.0", "secp256k1 0.29.1", "serde", "serde_json", @@ -6690,7 +6689,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25996b82292a7a57ed3508f052cfff8640d38d32018784acd714758b43da9c8f" dependencies = [ "bitcoin_hashes 0.12.0", - "rand", "secp256k1-sys 0.8.1", "serde", ] diff --git a/Cargo.toml b/Cargo.toml index 5adfc91d479..94ad1944c20 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -169,7 +169,6 @@ reqwest = { version = "0.12.9", features = [ ], default-features = false } ring = "0.17.8" secp256k1 = { version = "0.29.0", default-features = false } -secp256k1_27 = { package = "secp256k1", version = "0.27.0", default-features = false } semver = "1.0.23" serde = { version = "1.0.214", features = ["derive"] } serdect = "0.2.0" diff --git a/fedimint-core/Cargo.toml b/fedimint-core/Cargo.toml index d5cb631f5d1..e94986ab3c4 100644 --- a/fedimint-core/Cargo.toml +++ b/fedimint-core/Cargo.toml @@ -53,7 +53,6 @@ miniscript = { workspace = true, features = ["serde"] } parity-scale-codec = { version = "3.6.12", features = ["derive"] } rand = { workspace = true } secp256k1 = { workspace = true, features = ["global-context", "rand-std"] } -secp256k1_27 = { workspace = true, features = ["global-context", "rand-std"] } serde = { workspace = true } serde_json = { workspace = true } serdect = { workspace = true } diff --git a/fedimint-core/src/lib.rs b/fedimint-core/src/lib.rs index d5fe2bd1915..41f3dae1af4 100644 --- a/fedimint-core/src/lib.rs +++ b/fedimint-core/src/lib.rs @@ -52,7 +52,7 @@ use serde::{Deserialize, Serialize}; use thiserror::Error; pub use tiered::Tiered; pub use tiered_multi::*; -pub use {hex, secp256k1, secp256k1_27}; +pub use {hex, secp256k1}; pub use crate::core::server; use crate::encoding::{Decodable, DecodeError, Encodable}; diff --git a/modules/fedimint-ln-client/src/lib.rs b/modules/fedimint-ln-client/src/lib.rs index 98bf45f0bdf..3d4b3a28b15 100644 --- a/modules/fedimint-ln-client/src/lib.rs +++ b/modules/fedimint-ln-client/src/lib.rs @@ -57,7 +57,6 @@ use fedimint_core::module::{ use fedimint_core::secp256k1::{ All, Keypair, PublicKey, Scalar, Secp256k1, SecretKey, Signing, Verification, }; -use fedimint_core::secp256k1_27::ThirtyTwoByteHash; use fedimint_core::task::{timeout, MaybeSend, MaybeSync}; use fedimint_core::util::update_merge::UpdateMerge; use fedimint_core::util::{backoff_util, retry, BoxStream}; @@ -1002,7 +1001,7 @@ impl LightningClientModule { state_machines: sm_gen, }], ), - bitcoin32_to_bitcoin30_sha256_hash(&preimage).into_32(), + *preimage.as_ref(), )) }