Skip to content
Open
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
61 changes: 60 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 @@ -115,6 +115,7 @@ sui-types = { package = "sui-sdk-types", version = "0.2.2", features = [
"serde",
] }
k256 = { version = "0.13.4", features = ["ecdsa", "sha256"] }
bitcoin = { version = "0.32", default-features = false, features = ["std"] }

uniffi = { version = "0.31.0" }
regex = { version = "1.12.3" }
Expand Down
3 changes: 2 additions & 1 deletion crates/gem_bitcoin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ publish = false
[features]
default = []
rpc = ["dep:chain_traits", "dep:gem_client"]
signer = ["dep:signer", "dep:gem_hash", "dep:hex"]
signer = ["dep:signer", "dep:gem_hash", "dep:hex", "dep:bitcoin"]
reqwest = ["gem_client/reqwest"]
chain_integration_tests = ["rpc", "reqwest", "settings/testkit"]

Expand All @@ -28,6 +28,7 @@ serde_serializers = { path = "../serde_serializers", features = ["bigint"] }
signer = { path = "../signer", optional = true }
gem_hash = { path = "../gem_hash", optional = true }
hex = { workspace = true, optional = true }
bitcoin = { workspace = true, optional = true }

[dev-dependencies]
tokio = { workspace = true, features = ["macros", "rt"] }
Expand Down
25 changes: 20 additions & 5 deletions crates/gem_bitcoin/src/provider/preload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ use std::error::Error;

use gem_client::Client;
use primitives::{
BitcoinChain, FeePriority, FeeRate, GasPriceType, TransactionInputType, TransactionLoadData, TransactionLoadInput, TransactionLoadMetadata, TransactionPreloadInput, UTXO,
BitcoinChain, FeePriority, FeeRate, GasPriceType, SwapProvider, TransactionFee, TransactionInputType, TransactionLoadData, TransactionLoadInput, TransactionLoadMetadata,
TransactionPreloadInput, UTXO, swap::SwapQuoteDataType,
};

use crate::models::Address;
Expand All @@ -32,10 +33,11 @@ impl<C: Client> ChainTransactionLoad for BitcoinClient<C> {
}

async fn get_transaction_load(&self, input: TransactionLoadInput) -> Result<TransactionLoadData, Box<dyn Error + Sync + Send>> {
Ok(TransactionLoadData {
fee: input.default_fee(),
metadata: input.metadata,
})
let fee = match swap_provider_fee(&input) {
Some(result) => result?,
None => input.default_fee(),
};
Ok(TransactionLoadData { fee, metadata: input.metadata })
}

async fn get_transaction_fee_rates(&self, _input_type: TransactionInputType) -> Result<Vec<FeeRate>, Box<dyn Error + Sync + Send>> {
Expand Down Expand Up @@ -64,6 +66,19 @@ impl<C: Client> BitcoinClient<C> {
}
}

fn swap_provider_fee(input: &TransactionLoadInput) -> Option<Result<TransactionFee, &'static str>> {
let swap_data = input.input_type.get_swap_data().ok()?;
if swap_data.data.data_type != SwapQuoteDataType::Contract {
return None;
}
let provider = swap_data.quote.provider_data.provider;
if !matches!(provider, SwapProvider::Relay) {
return None;
}
let limit = swap_data.data.gas_limit.as_deref()?;
Some(limit.parse::<BigInt>().map(TransactionFee::new_from_fee).map_err(|_| "invalid swap fee"))
}

fn calculate_fee_rate(fee_sat_per_kb: &str, minimum_byte_fee: u32) -> Result<BigInt, Box<dyn Error + Sync + Send>> {
let rate = BigNumberFormatter::value_from_amount(fee_sat_per_kb, 8)?.parse::<f64>()? / 1000.0;
let minimum_byte_fee = minimum_byte_fee as f64;
Expand Down
23 changes: 23 additions & 0 deletions crates/gem_bitcoin/src/signer/chain_signer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use primitives::{ChainSigner, SignerError, SwapProvider, TransactionLoadInput};

use super::psbt::sign_psbt;

#[derive(Default)]
pub struct BitcoinChainSigner;

impl ChainSigner for BitcoinChainSigner {
fn sign_swap(&self, input: &TransactionLoadInput, private_key: &[u8]) -> Result<Vec<String>, SignerError> {
let swap_data = input.input_type.get_swap_data().map_err(SignerError::invalid_input)?;
let provider = &swap_data.quote.provider_data.provider;

match provider {
SwapProvider::Relay => {
let psbt_hex = &swap_data.data.data;
let signed = sign_psbt(psbt_hex, private_key)?;
Ok(vec![signed])
}
SwapProvider::Thorchain | SwapProvider::Chainflip => Err(SignerError::signing_error("bitcoin transfer swaps not yet implemented in Rust")),
other => Err(SignerError::signing_error(format!("unsupported swap provider for Bitcoin: {:?}", other))),
}
}
}
3 changes: 3 additions & 0 deletions crates/gem_bitcoin/src/signer/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
mod chain_signer;
mod encoding;
mod psbt;
mod signature;
mod types;

pub use chain_signer::BitcoinChainSigner;
pub use signature::sign_personal;
pub use types::{BitcoinSignDataResponse, BitcoinSignMessageData};
162 changes: 162 additions & 0 deletions crates/gem_bitcoin/src/signer/psbt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
use std::collections::BTreeMap;

use bitcoin::{
NetworkKind, PrivateKey, Psbt, PublicKey, Witness,
bip32::{DerivationPath, Fingerprint, KeySource},
secp256k1::Secp256k1,
};
use primitives::SignerError;

pub fn sign_psbt(psbt_hex: &str, private_key: &[u8]) -> Result<String, SignerError> {
let psbt_bytes = hex::decode(psbt_hex).map_err(|e| SignerError::invalid_input(format!("hex decode: {e}")))?;
let mut psbt = Psbt::deserialize(&psbt_bytes).map_err(|e| SignerError::invalid_input(format!("psbt parse: {e}")))?;

let secp = Secp256k1::new();
let key = PrivateKey::from_slice(private_key, NetworkKind::Main).map_err(|e| SignerError::invalid_input(format!("private key: {e}")))?;
let pub_key = PublicKey::from_private_key(&secp, &key);

prepare_inputs(&mut psbt, &pub_key);
sign(&mut psbt, &pub_key, &key, &secp)?;
finalize_inputs(&mut psbt, &pub_key)?;

let tx = psbt.extract_tx_unchecked_fee_rate();
Ok(hex::encode(bitcoin::consensus::serialize(&tx)))
}

fn prepare_inputs(psbt: &mut Psbt, pub_key: &PublicKey) {
let (x_only_key, _) = pub_key.inner.x_only_public_key();
let default_origin: KeySource = (Fingerprint::default(), DerivationPath::master());

for input in &mut psbt.inputs {
let is_taproot = input.witness_utxo.as_ref().is_some_and(|utxo| utxo.script_pubkey.is_p2tr());

if is_taproot {
input.tap_internal_key.get_or_insert(x_only_key);
if input.tap_key_origins.is_empty() {
input.tap_key_origins.insert(x_only_key, (vec![], default_origin.clone()));
}
} else if input.bip32_derivation.is_empty() {
input.bip32_derivation.insert(pub_key.inner, default_origin.clone());
}
}
}

fn sign(psbt: &mut Psbt, pub_key: &PublicKey, key: &PrivateKey, secp: &Secp256k1<bitcoin::secp256k1::All>) -> Result<(), SignerError> {
let keys = BTreeMap::from([(*pub_key, *key)]);
psbt.sign(&keys, secp).map(|_| ()).map_err(|(_ok, errors)| {
let messages: Vec<String> = errors.into_iter().map(|(idx, e)| format!("input {idx}: {e}")).collect();
SignerError::signing_error(messages.join(", "))
})
}

fn finalize_inputs(psbt: &mut Psbt, pub_key: &PublicKey) -> Result<(), SignerError> {
for (idx, input) in psbt.inputs.iter_mut().enumerate() {
let script = &input
.witness_utxo
.as_ref()
.ok_or_else(|| SignerError::signing_error(format!("missing witness_utxo for input {idx}")))?
.script_pubkey;

let witness = build_witness(input, pub_key, script, idx)?;
input.final_script_witness = Some(witness);
input.partial_sigs.clear();
input.sighash_type = None;
input.redeem_script = None;
input.witness_script = None;
input.bip32_derivation.clear();
}
Ok(())
}

fn build_witness(input: &bitcoin::psbt::Input, pub_key: &PublicKey, script: &bitcoin::ScriptBuf, idx: usize) -> Result<Witness, SignerError> {
if script.is_p2wpkh() {
let sig = input
.partial_sigs
.get(pub_key)
.ok_or_else(|| SignerError::signing_error(format!("missing signature for input {idx}")))?;
let mut w = Witness::new();
w.push(sig.to_vec());
w.push(pub_key.to_bytes());
Ok(w)
} else if script.is_p2tr() {
let sig = input
.tap_key_sig
.ok_or_else(|| SignerError::signing_error(format!("missing taproot signature for input {idx}")))?;
let mut w = Witness::new();
w.push(sig.to_vec());
Ok(w)
} else {
Err(SignerError::signing_error(format!("unsupported script type for input {idx}")))
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::testkit::TEST_PRIVATE_KEY;
use bitcoin::{Amount, OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Txid, hashes::Hash, secp256k1::Secp256k1};

fn build_test_psbt(script_pubkey: ScriptBuf) -> Psbt {
let utxo = TxOut {
value: Amount::from_sat(100_000),
script_pubkey: script_pubkey.clone(),
};
let tx = Transaction {
version: bitcoin::transaction::Version(2),
lock_time: bitcoin::absolute::LockTime::ZERO,
input: vec![TxIn {
previous_output: OutPoint::new(Txid::all_zeros(), 0),
script_sig: ScriptBuf::new(),
sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
witness: Witness::new(),
}],
output: vec![TxOut {
value: Amount::from_sat(90_000),
script_pubkey,
}],
};
let mut psbt = Psbt::from_unsigned_tx(tx).unwrap();
psbt.inputs[0].witness_utxo = Some(utxo);
psbt
}

fn sign_and_verify(psbt: Psbt) {
let psbt_hex = hex::encode(psbt.serialize());
let result = sign_psbt(&psbt_hex, &TEST_PRIVATE_KEY).unwrap();
assert!(!result.is_empty());

let tx: Transaction = bitcoin::consensus::deserialize(&hex::decode(&result).unwrap()).unwrap();
assert_eq!(tx.input.len(), 1);
assert!(!tx.input[0].witness.is_empty());
}

#[test]
fn test_sign_p2wpkh_psbt() {
let secp = Secp256k1::new();
let key = PrivateKey::from_slice(&TEST_PRIVATE_KEY, NetworkKind::Main).unwrap();
let pub_key = PublicKey::from_private_key(&secp, &key);
let script = ScriptBuf::new_p2wpkh(&pub_key.wpubkey_hash().unwrap());

sign_and_verify(build_test_psbt(script));
}

#[test]
fn test_sign_p2tr_psbt() {
let secp = Secp256k1::new();
let key = PrivateKey::from_slice(&TEST_PRIVATE_KEY, NetworkKind::Main).unwrap();
let (x_only, _) = key.public_key(&secp).inner.x_only_public_key();
let script = ScriptBuf::new_p2tr(&secp, x_only, None);

sign_and_verify(build_test_psbt(script));
}

#[test]
fn test_sign_psbt_invalid_hex() {
assert!(sign_psbt("not_hex!", &TEST_PRIVATE_KEY).is_err());
}

#[test]
fn test_sign_psbt_invalid_psbt() {
assert!(sign_psbt("deadbeef", &TEST_PRIVATE_KEY).is_err());
}
}
2 changes: 2 additions & 0 deletions crates/gem_bitcoin/src/testkit/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
pub mod transaction_mock;

pub const TEST_PRIVATE_KEY: [u8; 32] = [0xab; 32];
3 changes: 2 additions & 1 deletion crates/primitives/src/swap/approval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub struct ApprovalData {
pub value: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[typeshare(swift = "Equatable, Hashable, Sendable")]
#[serde(rename_all = "lowercase")]
pub enum SwapQuoteDataType {
Expand All @@ -30,6 +30,7 @@ pub struct SwapQuoteData {
pub data: String,
pub memo: Option<String>,
pub approval: Option<ApprovalData>,
#[serde(alias = "gasLimit")]
pub gas_limit: Option<String>,
}

Expand Down
Loading
Loading