Skip to content

Commit

Permalink
Added push_x_only_key to allow for XOnlyPublicKeys.
Browse files Browse the repository at this point in the history
  • Loading branch information
mplsgrant committed Mar 30, 2022
1 parent 8d602b8 commit 04bbf73
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/blockdata/script.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ use OutPoint;
use util::key::PublicKey;
use util::address::WitnessVersion;
use util::taproot::{LeafVersion, TapBranchHash, TapLeafHash};
use secp256k1::{Secp256k1, Verification};
use secp256k1::{Secp256k1, Verification, XOnlyPublicKey};
use schnorr::{TapTweak, TweakedPublicKey, UntweakedPublicKey};

/// A Bitcoin script.
Expand Down Expand Up @@ -919,6 +919,11 @@ impl Builder {
}
}

/// Adds instructions to push an XOnly public key onto the stack.
pub fn push_x_only_key(self, key: &XOnlyPublicKey) -> Builder {
self.push_slice(&key.serialize())
}

/// Adds a single opcode to the script.
pub fn push_opcode(mut self, data: opcodes::All) -> Builder {
self.0.push(data.into_u8());
Expand Down Expand Up @@ -1112,6 +1117,18 @@ mod test {
let key = PublicKey::from_str(&keystr[2..]).unwrap();
script = script.push_key(&key); comp.extend(Vec::from_hex(keystr).unwrap().iter().cloned()); assert_eq!(&script[..], &comp[..]);

// XOnly keys
// Notice the "20" which prepends each keystr. That 20 is hexidecimal for "32". The Builder automatically adds the 32 opcode
// to our script in order to give a heads up to the script compiler that it should add the next 32 bytes to the stack.
// To mimic the Builder's automatic insertion of the 32 opcode, we manually add it to the Vec and slice it out in the from_str.
let keystr = "209997a497d964fc1a62885b05a51166a65a90df00492c8d7cf61d6accf54803be"; // From: https://github.com/bitcoin-core/btcdeb/blob/e8c2750c4a4702768c52d15640ed03bf744d2601/doc/tapscript-example.md?plain=1#L43
let key = XOnlyPublicKey::from_str(&keystr[2..]).unwrap();
script = script.push_x_only_key(&key); comp.extend(Vec::from_hex(keystr).unwrap().iter().cloned()); assert_eq!(&script[..], &comp[..]);
let keystr = "204edfcf9dfe6c0b5c83d1ab3f78d1b39a46ebac6798e08e19761f5ed89ec83c10"; // From: https://github.com/bitcoin-core/btcdeb/blob/e8c2750c4a4702768c52d15640ed03bf744d2601/doc/tapscript-example.md?plain=1#L44
let key = XOnlyPublicKey::from_str(&keystr[2..]).unwrap();
script = script.push_x_only_key(&key); comp.extend(Vec::from_hex(keystr).unwrap().iter().cloned()); assert_eq!(&script[..], &comp[..]);


// opcodes
script = script.push_opcode(opcodes::all::OP_CHECKSIG); comp.push(0xACu8); assert_eq!(&script[..], &comp[..]);
script = script.push_opcode(opcodes::all::OP_CHECKSIG); comp.push(0xACu8); assert_eq!(&script[..], &comp[..]);
Expand Down

0 comments on commit 04bbf73

Please sign in to comment.