Skip to content

Commit

Permalink
Merge pull request fedimint#6240 from tvolk131/bitcoin32_next
Browse files Browse the repository at this point in the history
chore(deps): bump Keypair en/decoding to bitcoin v0.32
  • Loading branch information
joschisan authored Oct 28, 2024
2 parents 36f1d9e + fddb403 commit 2213bbc
Show file tree
Hide file tree
Showing 20 changed files with 136 additions and 93 deletions.
6 changes: 3 additions & 3 deletions fedimint-core/src/encoding/secp256k1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,19 +71,19 @@ impl Decodable for secp256k1::schnorr::Signature {
}
}

impl Encodable for bitcoin30::key::KeyPair {
impl Encodable for bitcoin::key::Keypair {
fn consensus_encode<W: Write>(&self, writer: &mut W) -> Result<usize, Error> {
self.secret_bytes().consensus_encode(writer)
}
}

impl Decodable for bitcoin30::key::KeyPair {
impl Decodable for bitcoin::key::Keypair {
fn consensus_decode<D: Read>(
d: &mut D,
modules: &ModuleDecoderRegistry,
) -> Result<Self, DecodeError> {
let sec_bytes = <[u8; 32]>::consensus_decode(d, modules)?;
Self::from_seckey_slice(secp256k1::global::SECP256K1, &sec_bytes) // FIXME: evaluate security risk of global ctx
Self::from_seckey_slice(bitcoin::secp256k1::global::SECP256K1, &sec_bytes) // FIXME: evaluate security risk of global ctx
.map_err(DecodeError::from_err)
}
}
Expand Down
33 changes: 25 additions & 8 deletions gateway/ln-gateway/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,16 @@ use std::collections::BTreeMap;
use bitcoin::Network;
use bitcoin_hashes::sha256;
use fedimint_api_client::api::net::Connector;
use fedimint_core::bitcoin_migration::{
bitcoin30_to_bitcoin32_keypair, bitcoin32_to_bitcoin30_keypair,
};
use fedimint_core::config::FederationId;
use fedimint_core::db::{
CoreMigrationFn, DatabaseTransaction, DatabaseVersion, IDatabaseTransactionOpsCoreTyped,
};
use fedimint_core::encoding::{Decodable, Encodable};
use fedimint_core::invite_code::InviteCode;
use fedimint_core::secp256k1_29::Keypair;
use fedimint_core::{impl_db_lookup, impl_db_record, push_db_pair_items, secp256k1, Amount};
use fedimint_ln_common::serde_routing_fees;
use fedimint_lnv2_common::contracts::{IncomingContract, PaymentImage};
Expand Down Expand Up @@ -119,23 +123,32 @@ impl<Cap: Send> GatewayDbtxNcExt for DatabaseTransaction<'_, Cap> {
}

async fn load_gateway_keypair(&mut self) -> Option<KeyPair> {
self.get_value(&GatewayPublicKey).await
self.get_value(&GatewayPublicKey)
.await
.map(|kp| bitcoin32_to_bitcoin30_keypair(&kp))
}

async fn load_gateway_keypair_assert_exists(&mut self) -> KeyPair {
self.get_value(&GatewayPublicKey)
.await
.expect("Gateway keypair does not exist")
bitcoin32_to_bitcoin30_keypair(
&self
.get_value(&GatewayPublicKey)
.await
.expect("Gateway keypair does not exist"),
)
}

async fn load_or_create_gateway_keypair(&mut self) -> KeyPair {
if let Some(key_pair) = self.get_value(&GatewayPublicKey).await {
key_pair
bitcoin32_to_bitcoin30_keypair(&key_pair)
} else {
let context = Secp256k1::new();
let (secret_key, _public_key) = context.generate_keypair(&mut OsRng);
let key_pair = KeyPair::from_secret_key(&context, &secret_key);
self.insert_new_entry(&GatewayPublicKey, &key_pair).await;
self.insert_new_entry(
&GatewayPublicKey,
&bitcoin30_to_bitcoin32_keypair(&key_pair),
)
.await;
key_pair
}
}
Expand Down Expand Up @@ -312,7 +325,7 @@ struct GatewayPublicKey;

impl_db_record!(
key = GatewayPublicKey,
value = KeyPair,
value = Keypair,
db_prefix = DbKeyPrefix::GatewayPublicKey,
);

Expand Down Expand Up @@ -483,7 +496,11 @@ mod fedimint_migration_tests {
let context = secp256k1::Secp256k1::new();
let (secret, _) = context.generate_keypair(&mut OsRng);
let key_pair = secp256k1::KeyPair::from_secret_key(&context, &secret);
dbtx.insert_new_entry(&GatewayPublicKey, &key_pair).await;
dbtx.insert_new_entry(
&GatewayPublicKey,
&bitcoin30_to_bitcoin32_keypair(&key_pair),
)
.await;

let gateway_configuration = GatewayConfigurationV0 {
password: "EXAMPLE".to_string(),
Expand Down
7 changes: 4 additions & 3 deletions gateway/ln-gateway/src/gateway_module_v2/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use fedimint_client::sm::util::MapStateTransitions;
use fedimint_client::sm::{Context, DynState, ModuleNotifier, State, StateTransition};
use fedimint_client::transaction::{ClientOutput, TransactionBuilder};
use fedimint_client::{sm_enum_variant_translation, DynGlobalClientContext};
use fedimint_core::bitcoin_migration::bitcoin30_to_bitcoin32_keypair;
use fedimint_core::config::FederationId;
use fedimint_core::core::{Decoder, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId};
use fedimint_core::db::DatabaseTransaction;
Expand Down Expand Up @@ -303,7 +304,7 @@ impl GatewayClientModuleV2 {
max_delay,
min_contract_amount,
invoice: payload.invoice,
claim_keypair: self.keypair,
claim_keypair: bitcoin30_to_bitcoin32_keypair(&self.keypair),
},
state: SendSMState::Sending,
});
Expand Down Expand Up @@ -383,7 +384,7 @@ impl GatewayClientModuleV2 {
operation_id,
contract: contract.clone(),
out_point: OutPoint { txid, out_idx },
refund_keypair,
refund_keypair: bitcoin30_to_bitcoin32_keypair(&refund_keypair),
},
state: ReceiveSMState::Funding,
}),
Expand Down Expand Up @@ -436,7 +437,7 @@ impl GatewayClientModuleV2 {
operation_id,
contract: contract.clone(),
out_point: OutPoint { txid, out_idx },
refund_keypair,
refund_keypair: bitcoin30_to_bitcoin32_keypair(&refund_keypair),
},
state: ReceiveSMState::Funding,
})]
Expand Down
9 changes: 3 additions & 6 deletions gateway/ln-gateway/src/gateway_module_v2/receive_sm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@ 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;
use fedimint_core::module::ApiRequestErased;
use fedimint_core::secp256k1::KeyPair;
use fedimint_core::secp256k1_29::Keypair;
use fedimint_core::task::sleep;
use fedimint_core::{NumPeersExt, OutPoint, PeerId, TransactionId};
use fedimint_lnv2_common::contracts::IncomingContract;
Expand Down Expand Up @@ -58,7 +57,7 @@ pub struct ReceiveSMCommon {
pub operation_id: OperationId,
pub contract: IncomingContract,
pub out_point: OutPoint,
pub refund_keypair: KeyPair,
pub refund_keypair: Keypair,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
Expand Down Expand Up @@ -262,9 +261,7 @@ impl ReceiveStateMachine {
agg_decryption_key,
)),
amount: old_state.common.contract.commitment.amount,
keys: vec![bitcoin30_to_bitcoin32_keypair(
&old_state.common.refund_keypair,
)],
keys: vec![old_state.common.refund_keypair],
};

let outpoints = global_context
Expand Down
9 changes: 3 additions & 6 deletions gateway/ln-gateway/src/gateway_module_v2/send_sm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +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::bitcoin30_to_bitcoin32_keypair;
use fedimint_core::core::OperationId;
use fedimint_core::encoding::{Decodable, Encodable};
use fedimint_core::secp256k1::KeyPair;
use fedimint_core::secp256k1_29::Keypair;
use fedimint_core::{Amount, OutPoint};
use fedimint_lnv2_client::LightningInvoice;
use fedimint_lnv2_common::contracts::{OutgoingContract, PaymentImage};
Expand Down Expand Up @@ -48,7 +47,7 @@ pub struct SendSMCommon {
pub max_delay: u64,
pub min_contract_amount: Amount,
pub invoice: LightningInvoice,
pub claim_keypair: KeyPair,
pub claim_keypair: Keypair,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
Expand Down Expand Up @@ -219,9 +218,7 @@ impl SendStateMachine {
OutgoingWitness::Claim(preimage),
)),
amount: old_state.common.contract.amount,
keys: vec![bitcoin30_to_bitcoin32_keypair(
&old_state.common.claim_keypair,
)],
keys: vec![old_state.common.claim_keypair],
};

let outpoints = global_context
Expand Down
15 changes: 10 additions & 5 deletions modules/fedimint-ln-client/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ use bitcoin30::hashes::sha256;
use fedimint_core::core::OperationId;
use fedimint_core::encoding::{Decodable, Encodable};
use fedimint_core::module::registry::ModuleDecoderRegistry;
use fedimint_core::secp256k1_29::Keypair;
use fedimint_core::{impl_db_lookup, impl_db_record, OutPoint, TransactionId};
use fedimint_ln_common::{LightningGateway, LightningGatewayRegistration};
use lightning_invoice::Bolt11Invoice;
use secp256k1::{KeyPair, PublicKey};
use secp256k1::PublicKey;
use serde::Serialize;
use strum_macros::EnumIter;

Expand Down Expand Up @@ -101,7 +102,7 @@ pub(crate) fn get_v1_migrated_state(
#[derive(Debug, Clone, Decodable)]
pub struct LightningReceiveConfirmedInvoiceV0 {
invoice: Bolt11Invoice,
receiving_key: KeyPair,
receiving_key: Keypair,
}

let decoders = ModuleDecoderRegistry::default();
Expand Down Expand Up @@ -265,6 +266,7 @@ mod tests {
use std::str::FromStr;

use fedimint_client::db::migrate_state;
use fedimint_core::bitcoin_migration::bitcoin30_to_bitcoin32_keypair;
use fedimint_core::core::{IntoDynInstance, OperationId};
use fedimint_core::encoding::Encodable;
use fedimint_core::{BitcoinHash, TransactionId};
Expand All @@ -288,7 +290,8 @@ mod tests {
cqp2rzjq0ag45qspt2vd47jvj3t5nya5vsn0hlhf5wel8h779npsrspm6eeuqtjuuqqqqgqqyqqqqqqqqqqqqqqqc9q\
yysgqddrv0jqhyf3q6z75rt7nrwx0crxme87s8rx2rt8xr9slzu0p3xg3f3f0zmqavtmsnqaj5v0y5mdzszah7thrmg\
2we42dvjggjkf44egqheymyw",).expect("Invalid invoice");
let claim_key = KeyPair::new(secp256k1::SECP256K1, &mut thread_rng());
let claim_key =
bitcoin30_to_bitcoin32_keypair(&KeyPair::new(secp256k1::SECP256K1, &mut thread_rng()));
let operation_id = OperationId::new_random();
let txid = TransactionId::from_byte_array([42; 32]);

Expand Down Expand Up @@ -366,7 +369,8 @@ mod tests {
async fn test_sm_migration_to_v2_confirmed() -> anyhow::Result<()> {
let operation_id = OperationId::new_random();
let instance_id = 0x42;
let claim_key = KeyPair::new(secp256k1::SECP256K1, &mut thread_rng());
let claim_key =
bitcoin30_to_bitcoin32_keypair(&KeyPair::new(secp256k1::SECP256K1, &mut thread_rng()));
let dummy_invoice = Bolt11Invoice::from_str("lntbs1u1pj8308gsp5xhxz908q5usddjjm6mfq6nwc2nu62twwm6za69d32kyx8h49a4hqpp5j5egfqw9kf5e96nk\
6htr76a8kggl0xyz3pzgemv887pya4flguzsdp5235xzmntwvsxvmmjypex2en4dejxjmn8yp6xsefqvesh2cm9wsss\
cqp2rzjq0ag45qspt2vd47jvj3t5nya5vsn0hlhf5wel8h779npsrspm6eeuqtjuuqqqqgqqyqqqqqqqqqqqqqqqc9q\
Expand Down Expand Up @@ -436,7 +440,8 @@ mod tests {
cqp2rzjq0ag45qspt2vd47jvj3t5nya5vsn0hlhf5wel8h779npsrspm6eeuqtjuuqqqqgqqyqqqqqqqqqqqqqqqc9q\
yysgqddrv0jqhyf3q6z75rt7nrwx0crxme87s8rx2rt8xr9slzu0p3xg3f3f0zmqavtmsnqaj5v0y5mdzszah7thrmg\
2we42dvjggjkf44egqheymyw",).expect("Invalid invoice");
let claim_key = KeyPair::new(secp256k1::SECP256K1, &mut thread_rng());
let claim_key =
bitcoin30_to_bitcoin32_keypair(&KeyPair::new(secp256k1::SECP256K1, &mut thread_rng()));
let operation_id = OperationId::new_random();
let txid = TransactionId::from_byte_array([42; 32]);

Expand Down
15 changes: 10 additions & 5 deletions modules/fedimint-ln-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ use fedimint_core::encoding::{Decodable, Encodable};
use fedimint_core::module::{
ApiVersion, CommonModuleInit, ModuleCommon, ModuleInit, MultiApiVersion,
};
use fedimint_core::secp256k1_29::Keypair;
use fedimint_core::task::{timeout, MaybeSend, MaybeSync};
use fedimint_core::util::update_merge::UpdateMerge;
use fedimint_core::util::{backoff_util, retry, BoxStream};
Expand Down Expand Up @@ -146,7 +147,7 @@ impl PayType {
pub enum ReceivingKey {
/// The keypair used to receive payments for ourselves, we will use this to
/// sweep to our own ecash wallet on success
Personal(KeyPair),
Personal(Keypair),
/// A public key of another user, the lightning payment will be locked to
/// this key for them to claim on success
External(PublicKey),
Expand All @@ -156,7 +157,9 @@ impl ReceivingKey {
/// The public key of the receiving key
pub fn public_key(&self) -> PublicKey {
match self {
ReceivingKey::Personal(keypair) => keypair.public_key(),
ReceivingKey::Personal(keypair) => {
bitcoin32_to_bitcoin30_secp256k1_pubkey(&keypair.public_key())
}
ReceivingKey::External(public_key) => *public_key,
}
}
Expand Down Expand Up @@ -725,7 +728,7 @@ impl LightningClientModule {
};

let outgoing_payment = OutgoingContractData {
recovery_key: user_sk,
recovery_key: bitcoin30_to_bitcoin32_keypair(&user_sk),
contract_account: OutgoingContractAccount {
amount: contract_amount,
contract: contract.clone(),
Expand Down Expand Up @@ -1507,8 +1510,10 @@ impl LightningClientModule {
extra_meta: M,
gateway: Option<LightningGateway>,
) -> anyhow::Result<(OperationId, Bolt11Invoice, [u8; 32])> {
let receiving_key =
ReceivingKey::Personal(KeyPair::new(&self.secp, &mut rand::rngs::OsRng));
let receiving_key = ReceivingKey::Personal(bitcoin30_to_bitcoin32_keypair(&KeyPair::new(
&self.secp,
&mut rand::rngs::OsRng,
)));
self.create_bolt11_invoice_internal(
amount,
description,
Expand Down
3 changes: 1 addition & 2 deletions modules/fedimint-ln-client/src/pay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use bitcoin30::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_keypair;
use fedimint_core::config::FederationId;
use fedimint_core::core::{Decoder, OperationId};
use fedimint_core::encoding::{Decodable, Encodable};
Expand Down Expand Up @@ -547,7 +546,7 @@ async fn try_refund_outgoing_contract(
let refund_client_input = ClientInput::<LightningInput> {
input: refund_input,
amount: contract_data.contract_account.amount,
keys: vec![bitcoin30_to_bitcoin32_keypair(&refund_key)],
keys: vec![refund_key],
};

let (txid, out_points) = global_context
Expand Down
17 changes: 12 additions & 5 deletions modules/fedimint-ln-client/src/receive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ 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;
use fedimint_core::bitcoin_migration::{
bitcoin30_to_bitcoin32_keypair, bitcoin32_to_bitcoin30_keypair,
};
use fedimint_core::core::{IntoDynInstance, ModuleInstanceId, OperationId};
use fedimint_core::encoding::{Decodable, Encodable};
use fedimint_core::secp256k1_29::Keypair;
use fedimint_core::task::sleep;
use fedimint_core::{OutPoint, TransactionId};
use fedimint_ln_common::contracts::incoming::IncomingContractAccount;
Expand Down Expand Up @@ -93,7 +96,7 @@ impl IntoDynInstance for LightningReceiveStateMachine {
pub struct LightningReceiveSubmittedOfferV0 {
pub offer_txid: TransactionId,
pub invoice: Bolt11Invoice,
pub payment_keypair: KeyPair,
pub payment_keypair: Keypair,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
Expand Down Expand Up @@ -248,9 +251,13 @@ impl LightningReceiveConfirmedInvoice {
Ok(contract) => {
match receiving_key {
ReceivingKey::Personal(keypair) => {
let (txid, out_points) =
Self::claim_incoming_contract(dbtx, contract, keypair, global_context)
.await;
let (txid, out_points) = Self::claim_incoming_contract(
dbtx,
contract,
bitcoin32_to_bitcoin30_keypair(&keypair),
global_context,
)
.await;
LightningReceiveStateMachine {
operation_id: old_state.operation_id,
state: LightningReceiveStates::Funded(LightningReceiveFunded {
Expand Down
2 changes: 1 addition & 1 deletion modules/fedimint-ln-common/src/contracts/outgoing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ impl OutgoingContract {

#[derive(Debug, Clone, Eq, PartialEq, Hash, Encodable, Decodable, Serialize, Deserialize)]
pub struct OutgoingContractData {
pub recovery_key: bitcoin30::key::KeyPair,
pub recovery_key: bitcoin::key::Keypair,
pub contract_account: OutgoingContractAccount,
}

Expand Down
Loading

0 comments on commit 2213bbc

Please sign in to comment.