Skip to content

Commit

Permalink
Update bitcoin + ldk + secpzkp
Browse files Browse the repository at this point in the history
  • Loading branch information
Tibo-lg committed Jan 31, 2024
1 parent f303972 commit 943b76a
Show file tree
Hide file tree
Showing 70 changed files with 482 additions and 485 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,5 @@ members = [
"dlc-sled-storage-provider",
"electrs-blockchain-provider",
]

resolver = "2"
8 changes: 4 additions & 4 deletions bitcoin-rpc-provider/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ name = "bitcoin-rpc-provider"
version = "0.1.0"

[dependencies]
bitcoin = {version = "0.29.2"}
bitcoincore-rpc = {version = "0.16.0"}
bitcoincore-rpc-json = {version = "0.16.0"}
bitcoin = {version = "0.30.2"}
bitcoincore-rpc = {version = "0.17.0"}
bitcoincore-rpc-json = {version = "0.17.0"}
dlc-manager = {path = "../dlc-manager"}
lightning = { version = "0.0.118" }
lightning = { version = "0.0.121" }
log = "0.4.14"
rust-bitcoin-coin-selection = { version = "0.1.0", git = "https://github.com/p2pderivatives/rust-bitcoin-coin-selection", rev = "405451929568422f7df809e35d6ad8f36fccce90", features = ["rand"] }
simple-wallet = {path = "../simple-wallet"}
27 changes: 14 additions & 13 deletions bitcoin-rpc-provider/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
//! # Bitcoin rpc provider

use std::cmp::max;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
Expand All @@ -11,10 +10,9 @@ use bitcoin::psbt::PartiallySignedTransaction;
use bitcoin::secp256k1::rand::thread_rng;
use bitcoin::secp256k1::{PublicKey, SecretKey};
use bitcoin::{
consensus::Decodable, network::constants::Network, Amount, PrivateKey, Script, Transaction,
Txid,
consensus::Decodable, network::constants::Network, Amount, PrivateKey, Transaction, Txid,
};
use bitcoin::{Address, OutPoint, TxOut};
use bitcoin::{Address, OutPoint, ScriptBuf, TxOut};
use bitcoincore_rpc::{json, Auth, Client, RpcApi};
use bitcoincore_rpc_json::AddressType;
use dlc_manager::error::Error as ManagerError;
Expand Down Expand Up @@ -104,10 +102,6 @@ impl BitcoinCoreProvider {
let client = Arc::new(Mutex::new(rpc_client));
let mut fees: HashMap<ConfirmationTarget, AtomicU32> = HashMap::new();
fees.insert(ConfirmationTarget::OnChainSweep, AtomicU32::new(5000));
fees.insert(
ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee,
AtomicU32::new(25 * 250),
);
fees.insert(
ConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
AtomicU32::new(MIN_FEERATE),
Expand Down Expand Up @@ -245,6 +239,7 @@ impl Wallet for BitcoinCoreProvider {
.lock()
.unwrap()
.get_new_address(None, Some(AddressType::Bech32))
.map(|x| x.assume_checked())
.map_err(rpc_err_to_manager_err)
}

Expand Down Expand Up @@ -295,8 +290,17 @@ impl Wallet for BitcoinCoreProvider {
txid: x.txid,
vout: x.vout,
},
address: x.address.as_ref().ok_or(Error::InvalidState)?.clone(),
redeem_script: x.redeem_script.as_ref().unwrap_or(&Script::new()).clone(),
address: x
.address
.as_ref()
.ok_or(Error::InvalidState)?
.clone()
.assume_checked(),
redeem_script: x
.redeem_script
.as_ref()
.cloned()
.unwrap_or(ScriptBuf::new()),
reserved: false,
}))
})
Expand Down Expand Up @@ -467,9 +471,6 @@ fn poll_for_fee_estimates(
fees.get(&ConfirmationTarget::OnChainSweep)
.unwrap()
.store(fee_rate, Ordering::Release);
fees.get(&ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee)
.unwrap()
.store(max(25 * 250, fee_rate * 10), Ordering::Release);
}
Err(e) => {
error!("Error querying fee estimate: {}", e);
Expand Down
6 changes: 3 additions & 3 deletions bitcoin-test-utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ name = "bitcoin-test-utils"
version = "0.1.0"

[dependencies]
bitcoin = { version = "0.29.2", default-features = false }
bitcoincore-rpc = {version = "0.16"}
bitcoincore-rpc-json = {version = "0.16"}
bitcoin = { version = "0.30.2", default-features = false }
bitcoincore-rpc = {version = "0.17"}
bitcoincore-rpc-json = {version = "0.17"}
9 changes: 6 additions & 3 deletions bitcoin-test-utils/src/rpc_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,16 @@ pub fn init_clients() -> (Client, Client, Client) {

let offer_address = offer_rpc
.get_new_address(None, Some(AddressType::Bech32))
.unwrap();
.unwrap()
.assume_checked();
let accept_address = accept_rpc
.get_new_address(None, Some(AddressType::Bech32))
.unwrap();
.unwrap()
.assume_checked();
let sink_address = sink_rpc
.get_new_address(None, Some(AddressType::Bech32))
.unwrap();
.unwrap()
.assume_checked();

sink_rpc.generate_to_address(1, &offer_address).unwrap();
sink_rpc.generate_to_address(1, &accept_address).unwrap();
Expand Down
12 changes: 6 additions & 6 deletions dlc-manager/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,28 +17,28 @@ use-serde = ["serde", "dlc/use-serde", "dlc-messages/serde", "dlc-trie/use-serde

[dependencies]
async-trait = "0.1.50"
bitcoin = { version = "0.29.2", default-features = false }
bitcoin = { version = "0.30.2", default-features = false }
dlc = { version = "0.4.0", default-features = false, path = "../dlc" }
dlc-messages = { version = "0.4.0", default-features = false, path = "../dlc-messages" }
dlc-trie = { version = "0.4.0", default-features = false, path = "../dlc-trie" }
lightning = { version = "0.0.118", default-features = false, features = ["grind_signatures"] }
lightning = { version = "0.0.121", default-features = false, features = ["grind_signatures"] }
log = "0.4.14"
rand_chacha = {version = "0.3.1", optional = true}
secp256k1-zkp = {version = "0.7.0"}
secp256k1-zkp = {version = "0.9.2"}
serde = {version = "1.0", optional = true}

[dev-dependencies]
bitcoin-rpc-provider = {path = "../bitcoin-rpc-provider"}
bitcoin-test-utils = {path = "../bitcoin-test-utils"}
bitcoincore-rpc = {version = "0.16.0"}
bitcoincore-rpc-json = {version = "0.16.0"}
bitcoincore-rpc = {version = "0.17"}
bitcoincore-rpc-json = {version = "0.17"}
criterion = "0.4.0"
dlc-manager = { path = ".", default-features = false, features = ["use-serde"] }
dlc-messages = { path = "../dlc-messages", default-features = false, features = ["serde"] }
electrs-blockchain-provider = {path = "../electrs-blockchain-provider"}
env_logger = "0.9.1"
mocks = {path = "../mocks"}
secp256k1-zkp = {version = "0.7.0", features = ["bitcoin_hashes", "rand", "rand-std", "global-context", "use-serde"]}
secp256k1-zkp = {version = "0.9.2", features = ["bitcoin_hashes", "rand", "rand-std", "global-context", "serde"]}
serde = "1.0"
serde_json = "1.0"
simple-wallet = {path = "../simple-wallet"}
Expand Down
6 changes: 3 additions & 3 deletions dlc-manager/src/channel/accepted_channel.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! # Structure and methods for channels that have been accepted.

use bitcoin::{Script, Transaction};
use bitcoin::{ScriptBuf, Transaction};
use dlc_messages::channel::AcceptChannel;
use secp256k1_zkp::{EcdsaAdaptorSignature, PublicKey};

Expand Down Expand Up @@ -29,7 +29,7 @@ pub struct AcceptedChannel {
/// The buffer transaction for the initial contract in the channel.
pub buffer_transaction: Transaction,
/// The script pubkey of the buffer transaction output.
pub buffer_script_pubkey: Script,
pub buffer_script_pubkey: ScriptBuf,
/// The temporary id of the channel.
pub temporary_channel_id: ChannelId,
/// The actual id of the channel.
Expand All @@ -53,7 +53,7 @@ impl AcceptedChannel {
funding_pubkey: contract.accept_params.fund_pubkey,
payout_spk: contract.accept_params.payout_script_pubkey.clone(),
payout_serial_id: contract.accept_params.payout_serial_id,
funding_inputs: contract.funding_inputs.iter().map(|x| x.into()).collect(),
funding_inputs: contract.funding_inputs.clone(),
change_spk: contract.accept_params.change_script_pubkey.clone(),
change_serial_id: contract.accept_params.change_serial_id,
cet_adaptor_signatures: cet_adaptor_signatures.into(),
Expand Down
1 change: 1 addition & 0 deletions dlc-manager/src/channel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ pub mod offered_channel;
pub mod party_points;
pub mod ser;
pub mod signed_channel;
mod utils;

/// Enumeration containing the possible state a DLC channel can be in.
#[derive(Clone)]
Expand Down
12 changes: 2 additions & 10 deletions dlc-manager/src/channel/offered_channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,7 @@ impl OfferedChannel {
payout_spk: offered_contract.offer_params.payout_script_pubkey.clone(),
payout_serial_id: offered_contract.offer_params.payout_serial_id,
offer_collateral: offered_contract.offer_params.collateral,
funding_inputs: offered_contract
.funding_inputs_info
.iter()
.map(|x| x.into())
.collect(),
funding_inputs: offered_contract.funding_inputs.clone(),
change_spk: offered_contract.offer_params.change_script_pubkey.clone(),
change_serial_id: offered_contract.offer_params.change_serial_id,
cet_locktime: offered_contract.cet_locktime,
Expand Down Expand Up @@ -122,11 +118,7 @@ impl OfferedChannel {
refund_locktime: offer_channel.refund_locktime,
fee_rate_per_vb: offer_channel.fee_rate_per_vb,
fund_output_serial_id: offer_channel.fund_output_serial_id,
funding_inputs_info: offer_channel
.funding_inputs
.iter()
.map(|x| x.into())
.collect(),
funding_inputs: offer_channel.funding_inputs.clone(),
total_collateral: offer_channel.contract_info.get_total_collateral(),
};

Expand Down
2 changes: 1 addition & 1 deletion dlc-manager/src/channel/party_points.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
//! of states possible. This module contain a structure containing them and methods
//! useful for derivation.

use super::utils::{derive_public_key, derive_public_revocation_key};
use bitcoin::PublicKey as BitcoinPublicKey;
use dlc::channel::RevokeParams;
use lightning::ln::chan_utils::{derive_public_key, derive_public_revocation_key};
use secp256k1_zkp::{All, PublicKey, Secp256k1, Signing, Verification};

/// Base points used by a party of a DLC channel to derive public and private
Expand Down
8 changes: 4 additions & 4 deletions dlc-manager/src/channel/signed_channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//! transaction inputs. This module contains the model for a signed channel,
//! the possible states in which it can be as well as methods to work with it.

use bitcoin::{Script, Transaction, Txid};
use bitcoin::{ScriptBuf, Transaction, Txid};
use dlc::PartyParams;
use dlc_messages::oracle_msgs::OracleAttestation;
use lightning::ln::chan_utils::CounterpartyCommitmentSecrets;
Expand Down Expand Up @@ -216,7 +216,7 @@ typed_enum!(
/// The buffer transaction.
buffer_transaction: Transaction,
/// The buffer transaction script pubkey.
buffer_script_pubkey: Script,
buffer_script_pubkey: ScriptBuf,
/// The adaptor signature for the buffer transaction generated by
/// the accept party.
accept_buffer_adaptor_signature: EcdsaAdaptorSignature,
Expand All @@ -240,7 +240,7 @@ typed_enum!(
/// The buffer transaction.
buffer_transaction: Transaction,
/// The buffer transaction script pubkey.
buffer_script_pubkey: Script,
buffer_script_pubkey: ScriptBuf,
/// The adaptor signature for the buffer transaction generated by
/// the offer party.
offer_buffer_adaptor_signature: EcdsaAdaptorSignature,
Expand Down Expand Up @@ -354,7 +354,7 @@ pub struct SignedChannel {
/// The fund transaction for the channel.
pub fund_tx: Transaction,
/// The script pubkey for the funding output.
pub fund_script_pubkey: Script,
pub fund_script_pubkey: ScriptBuf,
/// The vout of the funding output.
pub fund_output_index: usize,
/// The latest "stable" state in which the channel was (if already in a "stable")
Expand Down
101 changes: 74 additions & 27 deletions dlc-manager/src/channel/utils.rs
Original file line number Diff line number Diff line change
@@ -1,37 +1,84 @@
//! #

use bitcoin::PublicKey as BitcoinPublicKey;
use lightning::ln::chan_utils::{derive_public_key, derive_public_revocation_key};
use secp256k1_zkp::{PublicKey, Secp256k1, Signing, Verification};
use bitcoin::hashes::HashEngine;
use bitcoin::hashes::{sha256::Hash as Sha256, Hash};
use secp256k1_zkp::{PublicKey, Scalar, Secp256k1, SecretKey};

use crate::error::Error;

pub(crate) fn derive_bitcoin_public_key<C: Signing>(
secp: &Secp256k1<C>,
/// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
/// from the base point and the per_commitment_key. This is the public equivalent of
/// derive_private_key - using only public keys to derive a public key instead of private keys.
///
/// Taken from a previous version of ldk as it was refactored into something less practical to use
/// externally.
pub(crate) fn derive_public_key<T: secp256k1_zkp::Signing>(
secp_ctx: &Secp256k1<T>,
per_commitment_point: &PublicKey,
base_point: &PublicKey,
) -> Result<BitcoinPublicKey, Error> {
let key = derive_public_key(secp, per_commitment_point, base_point)
.map_err(|e| Error::InvalidParameters(format!("Invalid point was given {}", e)))?;
Ok(BitcoinPublicKey {
compressed: true,
key,
})
) -> PublicKey {
let mut sha = Sha256::engine();
sha.input(&per_commitment_point.serialize());
sha.input(&base_point.serialize());
let res = Sha256::from_engine(sha).to_byte_array();

let hashkey = PublicKey::from_secret_key(
secp_ctx,
&SecretKey::from_slice(&res)
.expect("Hashes should always be valid keys unless SHA-256 is broken"),
);
base_point.combine(&hashkey)
.expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak contains the hash of the key.")
}

pub(crate) fn derive_bitcoin_public_revocation_key<C: Verification>(
secp: &Secp256k1<C>,
/// Derives a per-commitment-transaction revocation public key from its constituent parts. This is
/// the public equivalend of derive_private_revocation_key - using only public keys to derive a
/// public key instead of private keys.
///
/// Only the cheating participant owns a valid witness to propagate a revoked
/// commitment transaction, thus per_commitment_point always come from cheater
/// and revocation_base_point always come from punisher, which is the broadcaster
/// of the transaction spending with this key knowledge.
///
/// Note that this is infallible iff we trust that at least one of the two input keys are randomly
/// generated (ie our own).
///
/// Taken from a previous version of ldk as it was refactored into something less practical to use
/// externally.
pub fn derive_public_revocation_key<T: secp256k1_zkp::Verification>(
secp_ctx: &Secp256k1<T>,
per_commitment_point: &PublicKey,
countersignatory_revocation_base_point: &PublicKey,
) -> Result<BitcoinPublicKey, Error> {
let key = derive_public_revocation_key(
secp,
per_commitment_point,
countersignatory_revocation_base_point,
)
.map_err(|e| Error::InvalidParameters(format!("Could not derive revocation secret: {}", e)))?;
Ok(BitcoinPublicKey {
compressed: true,
key,
})
) -> PublicKey {
let rev_append_commit_hash_key = {
let mut sha = Sha256::engine();
sha.input(&countersignatory_revocation_base_point.serialize());
sha.input(&per_commitment_point.serialize());

Sha256::from_engine(sha).to_byte_array()
};
let commit_append_rev_hash_key = {
let mut sha = Sha256::engine();
sha.input(&per_commitment_point.serialize());
sha.input(&countersignatory_revocation_base_point.serialize());

Sha256::from_engine(sha).to_byte_array()
};

let countersignatory_contrib = countersignatory_revocation_base_point
.mul_tweak(
secp_ctx,
&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap(),
)
.expect(
"Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs",
);
let broadcaster_contrib = per_commitment_point
.mul_tweak(
secp_ctx,
&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap(),
)
.expect(
"Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs",
);
countersignatory_contrib.combine(&broadcaster_contrib)
.expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
}
Loading

0 comments on commit 943b76a

Please sign in to comment.