diff --git a/src/btc.rs b/src/btc.rs index 8280d43..79df720 100644 --- a/src/btc.rs +++ b/src/btc.rs @@ -813,8 +813,8 @@ impl PairedBitBox { } } - /// Sign a Bitcoin transaction. Returns one 64 byte signature (compact serlization of the R and - /// S values) per input. + /// Sign a Bitcoin transaction. Returns one 64 byte signature (compact serialization of the R + /// and S values) per input, in transaction input order. pub async fn btc_sign( &self, coin: pb::BtcCoin, @@ -860,7 +860,7 @@ impl PairedBitBox { self.validate_version(">=9.24.0")?; } - let mut sigs: Vec> = Vec::new(); + let mut sigs: Vec> = vec![Vec::new(); transaction.inputs.len()]; let mut next_response = self .get_next_response(Request::BtcSignInit(pb::BtcSignInitRequest { @@ -883,7 +883,13 @@ impl PairedBitBox { { pb::btc_sign_next_response::Type::Input => { let input_index: usize = next_response.index as _; - let tx_input: &TxInput = &transaction.inputs[input_index]; + let tx_input = transaction + .inputs + .get(input_index) + .ok_or(Error::UnexpectedResponse)?; + if !sigs[input_index].is_empty() { + return Err(Error::UnexpectedResponse); + } let input_is_schnorr = is_schnorr( &transaction.script_configs[tx_input.script_config_index as usize], @@ -945,7 +951,10 @@ impl PairedBitBox { if !next_response.has_signature { return Err(Error::UnexpectedResponse); } - sigs.push(next_response.signature.clone()); + if next_response.signature.len() != 64 { + return Err(Error::InvalidSignature); + } + sigs[input_index] = next_response.signature.clone(); } if input_index == transaction.inputs.len() - 1 { is_inputs_pass2 = true @@ -1025,7 +1034,12 @@ impl PairedBitBox { }; next_response = self.get_next_response(request).await?; } - pb::btc_sign_next_response::Type::Done => break, + pb::btc_sign_next_response::Type::Done => { + if sigs.iter().any(Vec::is_empty) { + return Err(Error::UnexpectedResponse); + } + break; + } pb::btc_sign_next_response::Type::HostNonce => { return Err(Error::UnexpectedResponse); }