· 7 years ago · Nov 11, 2018, 02:08 AM
1pub fn sign_transaction(
2 mut tx: Transaction,
3 input_index: usize,
4 previous_script: &Script,
5 secret_key: &SecretKey,
6 public_key: &PublicKey,
7 is_compressed: bool
8) -> Result<Transaction, Error> {
9 if input_index >= tx.input.len() {
10 return Err(Error::OutOfRange(format!("no input with index {}", input_index)));
11 }
12
13 let signature_hash = tx.signature_hash(input_index, &previous_script, 1);
14
15 let secp = Secp256k1::new();
16 let mut signature = secp.sign(&signature_hash.to_bytes().into(), &secret_key);
17 signature.normalize_s(&secp); // Doesn't seem to matter wheter I call this function or not
18
19 let mut signature = signature.serialize_der(&secp);
20 signature.push(SigHashType::All as u8);
21
22 let ser_public_key: Vec<u8> = match is_compressed {
23 true => public_key.serialize().to_vec(),
24 false => public_key.serialize_uncompressed().to_vec(),
25 };
26
27 let script_sig = ScriptBuilder::new()
28 .push_int(signature.len() as i64)
29 .push_slice(&signature)
30 .push_int(ser_public_key.len() as i64)
31 .push_slice(&ser_public_key)
32 .into_script();
33
34 // Is safe because we checked the vec's length at the start of the function
35 tx.input[input_index].script_sig = script_sig;
36
37 Ok(tx)
38}