Skip to content

Commit

Permalink
chore: bump fedimint-client to bitcoin v0.32
Browse files Browse the repository at this point in the history
  • Loading branch information
tvolk131 committed Oct 27, 2024
1 parent 82baf27 commit 49b0531
Show file tree
Hide file tree
Showing 31 changed files with 137 additions and 52 deletions.
4 changes: 3 additions & 1 deletion Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ reqwest = { version = "0.12.8", features = [
], default-features = false }
ring = "0.17.8"
secp256k1 = { version = "0.27.0", default-features = false }
secp256k1_29 = { package = "secp256k1", version = "0.29.0", default-features = false }
semver = "1.0.23"
serde = { version = "1.0.213", features = ["derive"] }
serdect = "0.2.0"
Expand Down
3 changes: 2 additions & 1 deletion fedimint-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ anyhow = { workspace = true }
aquamarine = { workspace = true }
async-stream = { workspace = true }
async-trait = { workspace = true }
bitcoin30 = { workspace = true }
bitcoin = { workspace = true }
fedimint-aead = { workspace = true }
fedimint-api-client = { path = "../fedimint-api-client", version = "=0.5.0-alpha", default-features = false }
fedimint-core = { workspace = true }
Expand All @@ -38,6 +38,7 @@ futures = { workspace = true }
itertools = { workspace = true }
rand = { workspace = true }
reqwest = { workspace = true }
secp256k1 = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
strum = { workspace = true }
Expand Down
3 changes: 2 additions & 1 deletion fedimint-client/src/api_announcements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::sync::Arc;
use std::time::Duration;

use anyhow::{bail, Context};
use fedimint_core::bitcoin_migration::bitcoin32_to_bitcoin30_secp256k1_pubkey;
use fedimint_core::config::ClientConfig;
use fedimint_core::db::{Database, IDatabaseTransactionOpsCoreTyped};
use fedimint_core::encoding::{Decodable, Encodable};
Expand Down Expand Up @@ -66,7 +67,7 @@ pub async fn run_api_announcement_sync(client_inner: Arc<Client>) {
bail!("Guardian public key not found for peer {}", peer_id);
};

if !announcement.verify(SECP256K1, guardian_pub_key) {
if !announcement.verify(SECP256K1, &bitcoin32_to_bitcoin30_secp256k1_pubkey(guardian_pub_key)) {
bail!("Failed to verify announcement for peer {}", peer_id);
}
}
Expand Down
29 changes: 17 additions & 12 deletions fedimint-client/src/backup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ use std::collections::{BTreeMap, BTreeSet};
use std::io::{Cursor, Error, Read, Write};

use anyhow::{bail, ensure, Context, Result};
use bitcoin30::secp256k1::{KeyPair, PublicKey, Secp256k1, SignOnly};
use bitcoin::secp256k1::{Keypair, PublicKey};
use fedimint_api_client::api::DynGlobalApi;
use fedimint_core::bitcoin_migration::bitcoin30_to_bitcoin32_secp256k1_pubkey;
use fedimint_core::bitcoin_migration::{
bitcoin30_to_bitcoin32_keypair, bitcoin32_to_bitcoin30_keypair,
};
use fedimint_core::core::backup::{
BackupRequest, SignedBackupRequest, BACKUP_REQUEST_MAX_PAYLOAD_SIZE_BYTES,
};
Expand All @@ -15,6 +17,7 @@ use fedimint_core::encoding::{Decodable, DecodeError, Encodable};
use fedimint_core::module::registry::ModuleDecoderRegistry;
use fedimint_derive_secret::DerivableSecret;
use fedimint_logging::{LOG_CLIENT, LOG_CLIENT_BACKUP, LOG_CLIENT_RECOVERY};
use secp256k1::{Secp256k1, SignOnly};
use serde::{Deserialize, Serialize};
use tracing::{debug, info, warn};

Expand Down Expand Up @@ -224,14 +227,16 @@ impl EncryptedClientBackup {
)?)
}

pub fn into_backup_request(self, keypair: &KeyPair) -> Result<SignedBackupRequest> {
pub fn into_backup_request(self, keypair: &Keypair) -> Result<SignedBackupRequest> {
let keypair = bitcoin32_to_bitcoin30_keypair(keypair);

let request = BackupRequest {
id: keypair.public_key(),
timestamp: fedimint_core::time::now(),
payload: self.0,
};

request.sign(keypair)
request.sign(&keypair)
}

pub fn len(&self) -> usize {
Expand Down Expand Up @@ -353,9 +358,7 @@ impl Client {
) -> Result<Option<ClientBackup>> {
debug!(target: LOG_CLIENT, "Downloading backup from the federation");
let mut responses: Vec<_> = api
.download_backup(&bitcoin30_to_bitcoin32_secp256k1_pubkey(
&Client::get_backup_id_static(root_secret),
))
.download_backup(&Client::get_backup_id_static(root_secret))
.await?
.into_iter()
.filter_map(|(peer, backup)| {
Expand Down Expand Up @@ -405,17 +408,19 @@ impl Client {

/// Static version of [`Self::get_derived_backup_signing_key`] for testing
/// without creating whole `MintClient`
fn get_derived_backup_signing_key_static(secret: &DerivableSecret) -> KeyPair {
secret
.derive_backup_secret()
.to_secp_key(&Secp256k1::<SignOnly>::gen_new())
fn get_derived_backup_signing_key_static(secret: &DerivableSecret) -> Keypair {
bitcoin30_to_bitcoin32_keypair(
&secret
.derive_backup_secret()
.to_secp_key(&Secp256k1::<SignOnly>::gen_new()),
)
}

fn get_derived_backup_encryption_key(&self) -> fedimint_aead::LessSafeKey {
Self::get_derived_backup_encryption_key_static(&self.root_secret())
}

fn get_derived_backup_signing_key(&self) -> KeyPair {
fn get_derived_backup_signing_key(&self) -> Keypair {
Self::get_derived_backup_signing_key_static(&self.root_secret())
}

Expand Down
5 changes: 3 additions & 2 deletions fedimint-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ use anyhow::{anyhow, bail, ensure, format_err, Context};
use api::ClientRawFederationApiExt as _;
use async_stream::{stream, try_stream};
use backup::ClientBackup;
use bitcoin30::secp256k1;
use bitcoin::secp256k1;
use db::event_log::{
self, run_event_log_ordering_task, DBTransactionEventLogExt, Event, EventKind, EventLogEntry,
EventLogId,
Expand All @@ -107,6 +107,7 @@ use fedimint_api_client::api::{
ApiVersionSet, DynGlobalApi, DynModuleApi, FederationApiExt, GlobalFederationApiWithCacheExt,
IGlobalFederationApi, WsFederationApi,
};
use fedimint_core::bitcoin_migration::bitcoin30_to_bitcoin32_secp256k1_pubkey;
use fedimint_core::config::{
ClientConfig, FederationId, GlobalClientConfig, JsonClientConfig, ModuleInitRegistry,
};
Expand Down Expand Up @@ -2076,7 +2077,7 @@ impl Client {
dbtx.insert_entry(&ClientConfigKey, &new_config).await;
*(self.config.write().await) = new_config;
guardian_pub_keys
};
}.into_iter().map(|(peer_id, pubkey)| (peer_id, bitcoin30_to_bitcoin32_secp256k1_pubkey(&pubkey))).collect();

Result::<_, ()>::Ok(guardian_pub_keys)
}), None).await.expect("Will retry forever")
Expand Down
2 changes: 1 addition & 1 deletion fedimint-client/src/module/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::sync::Arc;
use std::{ffi, marker, ops};

use anyhow::{anyhow, bail};
use bitcoin30::secp256k1::PublicKey;
use bitcoin::secp256k1::PublicKey;
use fedimint_api_client::api::DynGlobalApi;
use fedimint_core::config::ClientConfig;
use fedimint_core::core::{
Expand Down
13 changes: 8 additions & 5 deletions fedimint-client/src/transaction/builder.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use std::sync::Arc;

use bitcoin30::key::KeyPair;
use bitcoin30::secp256k1;
use bitcoin::key::Keypair;
use bitcoin::secp256k1;
use fedimint_core::bitcoin_migration::bitcoin32_to_bitcoin30_schnorr_signature;
use fedimint_core::core::{DynInput, DynOutput, IInput, IntoDynInstance, ModuleInstanceId};
use fedimint_core::encoding::{Decodable, Encodable};
use fedimint_core::task::{MaybeSend, MaybeSync};
Expand All @@ -21,7 +22,7 @@ use crate::{
#[derive(Clone)]
pub struct ClientInput<I = DynInput> {
pub input: I,
pub keys: Vec<KeyPair>,
pub keys: Vec<Keypair>,
pub amount: Amount,
}

Expand Down Expand Up @@ -294,12 +295,14 @@ impl TransactionBuilder {
let nonce: [u8; 8] = rng.gen();

let txid = Transaction::tx_hash_from_parts(&inputs, &outputs, nonce);
let msg = secp256k1::Message::from_slice(&txid[..]).expect("txid has right length");
let msg = secp256k1::Message::from_digest_slice(&txid[..]).expect("txid has right length");

let signatures = input_keys
.into_iter()
.flatten()
.map(|keypair| secp_ctx.sign_schnorr(&msg, &keypair))
.map(|keypair| {
bitcoin32_to_bitcoin30_schnorr_signature(&secp_ctx.sign_schnorr(&msg, &keypair))
})
.collect();

let transaction = Transaction {
Expand Down
1 change: 1 addition & 0 deletions fedimint-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ 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_29 = { workspace = true, features = ["global-context", "rand-std"] }
serde = { workspace = true }
serde_json = { workspace = true }
serdect = { workspace = true }
Expand Down
27 changes: 27 additions & 0 deletions fedimint-core/src/bitcoin_migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,24 @@ 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 {
bincode::deserialize(
&bincode::serialize(&keypair).expect("Failed to serialize bitcoin30 keypair"),
)
.expect("Failed to convert bitcoin30 keypair to bitcoin32 keypair")
}

pub fn bitcoin32_to_bitcoin30_keypair(
keypair: &bitcoin::secp256k1::Keypair,
) -> bitcoin30::secp256k1::KeyPair {
bincode::deserialize(
&bincode::serialize(&keypair).expect("Failed to serialize bitcoin32 keypair"),
)
.expect("Failed to convert bitcoin32 keypair to bitcoin30 keypair")
}

pub fn bitcoin30_to_bitcoin32_secp256k1_secret_key(
secret_key: &bitcoin30::secp256k1::SecretKey,
) -> bitcoin::secp256k1::SecretKey {
Expand Down Expand Up @@ -171,6 +189,15 @@ pub fn bitcoin30_to_bitcoin32_sha256_hash(
.expect("Failed to convert bitcoin30 sha256 hash to bitcoin32 sha256 hash")
}

pub fn bitcoin32_to_bitcoin30_schnorr_signature(
signature: &bitcoin::secp256k1::schnorr::Signature,
) -> bitcoin30::secp256k1::schnorr::Signature {
bincode::deserialize(
&bincode::serialize(&signature).expect("Failed to serialize bitcoin32 schnorr signature"),
)
.expect("Failed to convert bitcoin32 schnorr signature to bitcoin30 schnorr signature")
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
8 changes: 4 additions & 4 deletions fedimint-core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,10 +402,10 @@ impl FederationId {
/// other LN senders will know that they cannot pay the invoice.
pub fn to_fake_ln_pub_key(
&self,
secp: &secp256k1::Secp256k1<secp256k1::All>,
) -> anyhow::Result<secp256k1::PublicKey> {
let sk = secp256k1::SecretKey::from_slice(&self.0.to_byte_array())?;
Ok(secp256k1::PublicKey::from_secret_key(secp, &sk))
secp: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>,
) -> anyhow::Result<bitcoin::secp256k1::PublicKey> {
let sk = bitcoin::secp256k1::SecretKey::from_slice(&self.0.to_byte_array())?;
Ok(bitcoin::secp256k1::PublicKey::from_secret_key(secp, &sk))
}
}

Expand Down
2 changes: 1 addition & 1 deletion fedimint-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ use serde::{Deserialize, Serialize};
use thiserror::Error;
pub use tiered::Tiered;
pub use tiered_multi::*;
pub use {hex, secp256k1};
pub use {hex, secp256k1, secp256k1_29};

pub use crate::core::server;
use crate::encoding::{Decodable, DecodeError, Encodable};
Expand Down
5 changes: 4 additions & 1 deletion gateway/ln-gateway/src/gateway_module_v2/receive_sm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use fedimint_api_client::query::FilterMapThreshold;
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_keypair;
use fedimint_core::core::{Decoder, OperationId};
use fedimint_core::encoding::{Decodable, Encodable};
use fedimint_core::endpoint_constants::AWAIT_OUTPUT_OUTCOME_ENDPOINT;
Expand Down Expand Up @@ -261,7 +262,9 @@ impl ReceiveStateMachine {
agg_decryption_key,
)),
amount: old_state.common.contract.commitment.amount,
keys: vec![old_state.common.refund_keypair],
keys: vec![bitcoin30_to_bitcoin32_keypair(
&old_state.common.refund_keypair,
)],
};

let outpoints = global_context
Expand Down
5 changes: 4 additions & 1 deletion gateway/ln-gateway/src/gateway_module_v2/send_sm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ 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::bitcoin30_to_bitcoin32_keypair;
use fedimint_core::core::OperationId;
use fedimint_core::encoding::{Decodable, Encodable};
use fedimint_core::secp256k1::KeyPair;
Expand Down Expand Up @@ -218,7 +219,9 @@ impl SendStateMachine {
OutgoingWitness::Claim(preimage),
)),
amount: old_state.common.contract.amount,
keys: vec![old_state.common.claim_keypair],
keys: vec![bitcoin30_to_bitcoin32_keypair(
&old_state.common.claim_keypair,
)],
};

let outpoints = global_context
Expand Down
3 changes: 2 additions & 1 deletion gateway/ln-gateway/src/state_machine/pay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use bitcoin_hashes::sha256;
use fedimint_client::sm::{ClientSMDatabaseTransaction, State, StateTransition};
use fedimint_client::transaction::{ClientInput, ClientInputBundle, ClientOutput};
use fedimint_client::{ClientHandleArc, DynGlobalClientContext};
use fedimint_core::bitcoin_migration::bitcoin30_to_bitcoin32_keypair;
use fedimint_core::config::FederationId;
use fedimint_core::core::OperationId;
use fedimint_core::encoding::{Decodable, Encodable};
Expand Down Expand Up @@ -712,7 +713,7 @@ impl GatewayPayClaimOutgoingContract {
let client_input = ClientInput::<LightningInput> {
input: claim_input,
amount: contract.amount,
keys: vec![context.redeem_key],
keys: vec![bitcoin30_to_bitcoin32_keypair(&context.redeem_key)],
};

let out_points = global_context
Expand Down
3 changes: 2 additions & 1 deletion gateway/ln-gateway/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use assert_matches::assert_matches;
use bitcoin_hashes::{sha256, Hash};
use fedimint_client::transaction::{ClientInput, ClientOutput, TransactionBuilder};
use fedimint_client::ClientHandleArc;
use fedimint_core::bitcoin_migration::bitcoin30_to_bitcoin32_keypair;
use fedimint_core::config::FederationId;
use fedimint_core::core::{IntoDynInstance, OperationId};
use fedimint_core::encoding::Encodable;
Expand Down Expand Up @@ -386,7 +387,7 @@ async fn test_gateway_cannot_claim_invalid_preimage() -> anyhow::Result<()> {
let client_input = ClientInput::<LightningInput> {
input: claim_input,
amount: outgoing_contract.amount,
keys: vec![gateway_module.redeem_key],
keys: vec![bitcoin30_to_bitcoin32_keypair(&gateway_module.redeem_key)],
};

let tx = TransactionBuilder::new().with_input(client_input.into_dyn(gateway_module.id));
Expand Down
5 changes: 3 additions & 2 deletions modules/fedimint-dummy-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use fedimint_client::sm::{Context, ModuleNotifier};
use fedimint_client::transaction::{
ClientInput, ClientInputBundle, ClientInputSM, ClientOutput, TransactionBuilder,
};
use fedimint_core::bitcoin_migration::bitcoin30_to_bitcoin32_keypair;
use fedimint_core::core::{Decoder, ModuleKind, OperationId};
use fedimint_core::db::{
Database, DatabaseTransaction, DatabaseVersion, IDatabaseTransactionOpsCoreTyped,
Expand Down Expand Up @@ -127,7 +128,7 @@ impl ClientModule for DummyClientModule {
account: self.key.public_key(),
},
amount: missing_input_amount,
keys: vec![self.key],
keys: vec![bitcoin30_to_bitcoin32_keypair(&self.key)],
};
let input_sm = ClientInputSM {
state_machines: Arc::new(move |txid, _| {
Expand Down Expand Up @@ -229,7 +230,7 @@ impl DummyClientModule {
account: account_kp.public_key(),
},
amount,
keys: vec![account_kp],
keys: vec![bitcoin30_to_bitcoin32_keypair(&account_kp)],
};

// Build and send tx to the fed
Expand Down
Loading

0 comments on commit 49b0531

Please sign in to comment.