Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use native-tls for better close_notify handling #41

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@ panic = "abort"
[dependencies]
serde = { version = "1.0.0", features = ["derive"] }
serde_json = "1.0.0"
ureq = {version = "2.8.0", features = ["json"]}
ureq = { version = "2.9.7", features = ["json", "native-tls"] }
bip39 = "2.0.0"
electrum-client = "0.19.0"
bitcoin = {version = "0.31.1", features = ["rand", "base64", "rand-std"]}
elements = { version = "0.24.0", features = ["serde"] }
lightning-invoice = "0.26.0"
native-tls = "0.2.11"
tungstenite = { version = "0.21.0", features = ["native-tls-vendored"] }
url = "2.5.0"
log = "^0.4"
Expand Down
13 changes: 11 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,17 @@ pub mod swaps;
/// utilities (key, preimage, error)
pub mod util;

pub use bitcoin::{PublicKey,secp256k1::{Keypair, Secp256k1}, Address,blockdata::locktime::absolute::LockTime,hashes::hash160::Hash, Amount};
pub use elements::{secp256k1_zkp::{Keypair as ZKKeyPair, Secp256k1 as ZKSecp256k1}, address::Address as ElementsAddress, locktime::LockTime as ElementsLockTime};
pub use bitcoin::{
blockdata::locktime::absolute::LockTime,
hashes::hash160::Hash,
secp256k1::{Keypair, Secp256k1},
Address, Amount, PublicKey,
};
pub use elements::{
address::Address as ElementsAddress,
locktime::LockTime as ElementsLockTime,
secp256k1_zkp::{Keypair as ZKKeyPair, Secp256k1 as ZKSecp256k1},
};
pub use lightning_invoice::Bolt11Invoice;

pub use swaps::boltz::{SwapTxKind, SwapType};
Expand Down
9 changes: 6 additions & 3 deletions src/network/electrum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,13 @@ pub struct ElectrumConfig {
}

impl ElectrumConfig {

pub fn default(chain: Chain, regtest_url: Option<String>) -> Result<Self, Error> {
if (chain == Chain::LiquidRegtest || chain == Chain::BitcoinRegtest ) && regtest_url.is_none() {
return Err(Error::Electrum(electrum_client::Error::Message("Regtest requires using a custom url".to_string())))
if (chain == Chain::LiquidRegtest || chain == Chain::BitcoinRegtest)
&& regtest_url.is_none()
{
return Err(Error::Electrum(electrum_client::Error::Message(
"Regtest requires using a custom url".to_string(),
)));
}
match chain {
Chain::Bitcoin => Ok(ElectrumConfig::new(
Expand Down
83 changes: 40 additions & 43 deletions src/swaps/bitcoinv2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ use crate::{
use bitcoin::{blockdata::locktime::absolute::LockTime, hashes::hash160};

use super::boltz::SwapType;
use super::boltzv2::{BoltzApiClientV2, ClaimTxResponse, CreateSubmarineResponse, CreateReverseResponse};
use super::boltzv2::{
BoltzApiClientV2, ClaimTxResponse, CreateReverseResponse, CreateSubmarineResponse,
};

use elements::secp256k1_zkp::{
MusigAggNonce, MusigKeyAggCache, MusigPartialSignature, MusigPubNonce, MusigSession,
Expand Down Expand Up @@ -241,12 +243,10 @@ impl BtcSwapScriptV2 {

let taproot_builder = TaprootBuilder::new();

let taproot_builder = taproot_builder
.add_leaf_with_ver(1, self.claim_script(), LeafVersion::TapScript)
?;
let taproot_builder = taproot_builder
.add_leaf_with_ver(1, self.refund_script(), LeafVersion::TapScript)
?;
let taproot_builder =
taproot_builder.add_leaf_with_ver(1, self.claim_script(), LeafVersion::TapScript)?;
let taproot_builder =
taproot_builder.add_leaf_with_ver(1, self.refund_script(), LeafVersion::TapScript)?;

let taproot_spend_info = taproot_builder.finalize(&secp, internal_key).unwrap();

Expand Down Expand Up @@ -448,9 +448,7 @@ impl BtcSwapTxV2 {

let session_id = MusigSessionId::new(&mut thread_rng());

let msg = Message::from_digest_slice(
&Vec::from_hex(&claim_tx_response.transaction_hash)?,
)?;
let msg = Message::from_digest_slice(&Vec::from_hex(&claim_tx_response.transaction_hash)?)?;

// Step 4: Start the Musig2 Signing session
let mut extra_rand = [0u8; 32];
Expand Down Expand Up @@ -534,8 +532,7 @@ impl BtcSwapTxV2 {
0,
&Prevouts::All(&[&self.utxo.1]),
bitcoin::TapSighashType::Default,
)
?;
)?;

let msg = Message::from_digest_slice(claim_tx_taproot_hash.as_byte_array())?;

Expand All @@ -557,24 +554,29 @@ impl BtcSwapTxV2 {
let mut extra_rand = [0u8; 32];
OsRng.fill_bytes(&mut extra_rand);

let (sec_nonce, pub_nonce) = key_agg_cache
.nonce_gen(&secp, session_id, keys.public_key(), msg, Some(extra_rand))
?;
let (sec_nonce, pub_nonce) = key_agg_cache.nonce_gen(
&secp,
session_id,
keys.public_key(),
msg,
Some(extra_rand),
)?;

// Step 7: Get boltz's partail sig
let claim_tx_hex = serialize(&claim_tx).to_lower_hex_string();
let partial_sig_resp = boltz_api
.get_reverse_partial_sig(&swap_id, &preimage, &pub_nonce, &claim_tx_hex)
?;
let partial_sig_resp = boltz_api.get_reverse_partial_sig(
&swap_id,
&preimage,
&pub_nonce,
&claim_tx_hex,
)?;

let boltz_public_nonce =
MusigPubNonce::from_slice(&Vec::from_hex(&partial_sig_resp.pub_nonce)?)
?;
MusigPubNonce::from_slice(&Vec::from_hex(&partial_sig_resp.pub_nonce)?)?;

let boltz_partial_sig = MusigPartialSignature::from_slice(
&Vec::from_hex(&partial_sig_resp.partial_signature)?,
)
?;
let boltz_partial_sig = MusigPartialSignature::from_slice(&Vec::from_hex(
&partial_sig_resp.partial_signature,
)?)?;

// Aggregate Our's and Other's Nonce and start the Musig session.
let agg_nonce = MusigAggNonce::new(&secp, &[boltz_public_nonce, pub_nonce]);
Expand All @@ -592,9 +594,8 @@ impl BtcSwapTxV2 {

assert!(boltz_partial_sig_verify == true);

let our_partial_sig = musig_session
.partial_sign(&secp, sec_nonce, &keys, &key_agg_cache)
?;
let our_partial_sig =
musig_session.partial_sign(&secp, sec_nonce, &keys, &key_agg_cache)?;

let schnorr_sig = musig_session.partial_sig_agg(&[boltz_partial_sig, our_partial_sig]);

Expand All @@ -618,14 +619,12 @@ impl BtcSwapTxV2 {
let leaf_hash =
TapLeafHash::from_script(&self.swap_script.claim_script(), LeafVersion::TapScript);

let sighash = SighashCache::new(claim_tx.clone())
.taproot_script_spend_signature_hash(
0,
&Prevouts::All(&[&self.utxo.1]),
leaf_hash,
TapSighashType::Default,
)
?;
let sighash = SighashCache::new(claim_tx.clone()).taproot_script_spend_signature_hash(
0,
&Prevouts::All(&[&self.utxo.1]),
leaf_hash,
TapSighashType::Default,
)?;

let msg = Message::from_digest_slice(sighash.as_byte_array())?;

Expand Down Expand Up @@ -720,14 +719,12 @@ impl BtcSwapTxV2 {
let leaf_hash =
TapLeafHash::from_script(&self.swap_script.refund_script(), LeafVersion::TapScript);

let sighash = SighashCache::new(spending_tx.clone())
.taproot_script_spend_signature_hash(
0,
&Prevouts::All(&[&self.utxo.1]),
leaf_hash,
TapSighashType::Default,
)
?;
let sighash = SighashCache::new(spending_tx.clone()).taproot_script_spend_signature_hash(
0,
&Prevouts::All(&[&self.utxo.1]),
leaf_hash,
TapSighashType::Default,
)?;

let msg = Message::from_digest_slice(sighash.as_byte_array())?;

Expand Down
21 changes: 19 additions & 2 deletions src/swaps/boltz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@
//! assert!((output_amount - base_fees) == response.onchain_amount?);

//! ```
use std::str::FromStr;
use std::sync::Arc;

use crate::error::Error;
use crate::network::Chain;
use bitcoin::absolute::LockTime;
Expand All @@ -51,7 +54,7 @@ use crate::util::secrets::Preimage;
use serde::Serializer;
use serde::{Deserialize, Serialize};
use serde_json;
use std::str::FromStr;
use ureq::{AgentBuilder, TlsConnector};

pub const BOLTZ_TESTNET_URL: &str = "https://testnet.boltz.exchange/api";
pub const BOLTZ_MAINNET_URL: &str = "https://api.boltz.exchange";
Expand Down Expand Up @@ -82,7 +85,21 @@ impl BoltzApiClient {
/// Make a Post request. Returns the Response
fn post(&self, end_point: &str, data: Value) -> Result<String, Error> {
let url = format!("{}/{}", self.base_url, end_point);
Ok(ureq::post(&url).send_json(data)?.into_string()?)

let response = match native_tls::TlsConnector::new() {
// If native_tls is available, use that for TLS
// It has better handling of close_notify, which avoids some POST call failures
// See https://github.com/SatoshiPortal/boltz-rust/issues/39
Ok(tls_connector) => AgentBuilder::new()
.tls_connector(Arc::new(tls_connector))
.build()
.request("POST", &url)
.send_json(data)?
.into_string()?,
// If native_tls is not available, fallback to the default (rustls)
Err(_) => ureq::post(&url).send_json(data)?.into_string()?,
};
Ok(response)
}
/// In order to create a swap, one first has to know which pairs are supported and what kind of rates, limits and fees are applied when creating a new swap.
/// The following call returns this information.
Expand Down
5 changes: 4 additions & 1 deletion src/swaps/boltzv2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,10 @@ impl BoltzApiClientV2 {
Ok(serde_json::from_str(&self.post(&endpoint, data)?)?)
}

pub fn post_reverse_req(&self, req: CreateReverseRequest) -> Result<CreateReverseResponse, Error> {
pub fn post_reverse_req(
&self,
req: CreateReverseRequest,
) -> Result<CreateReverseResponse, Error> {
Ok(serde_json::from_str(&self.post("swap/reverse", req)?)?)
}

Expand Down
8 changes: 5 additions & 3 deletions src/swaps/liquidv2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ use elements::{

use super::{
boltz::SwapType,
boltzv2::{BoltzApiClientV2, ClaimTxResponse, CreateSubmarineResponse, CreateReverseResponse},
boltzv2::{BoltzApiClientV2, ClaimTxResponse, CreateReverseResponse, CreateSubmarineResponse},
};

/// Liquid v2 swap script helper.
Expand Down Expand Up @@ -675,8 +675,10 @@ impl LBtcSwapTxV2 {
self.swap_script.sender_pubkey.inner,
);

if (!boltz_partial_sig_verify){
return Err(Error::Taproot(("Unable to verify Partial Signature".to_string())))
if (!boltz_partial_sig_verify) {
return Err(Error::Taproot(
("Unable to verify Partial Signature".to_string()),
));
}

let our_partial_sig =
Expand Down
Loading