Skip to content

Commit

Permalink
feat: add return the hash of output scripts as an option
Browse files Browse the repository at this point in the history
  • Loading branch information
reednaa committed Sep 11, 2024
1 parent aba79f5 commit 085764f
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/library/BtcScript.sol
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,50 @@ library BtcScript {
function scriptP2TR(bytes32 witnessProgram) internal pure returns(bytes memory) {
return bytes.concat(OP_1, PUSH_32, witnessProgram);
}

/**
* @notice Global helper for encoding Bitcoin scripts. Returns the hash of the script
* instead of the script itself.
* @param addressType Enum of address type. Used to specify which script is used.
* @param implementationHash P2PKH, address hash or P2SH, script hash.
*/
function getBitcoinScriptHash(AddressType addressType, bytes32 implementationHash) internal pure returns(bytes32 outputScriptHash) {
// Check if segwit
if (addressType == AddressType.P2PKH) return scriptP2PKHHash(bytes20(implementationHash));
if (addressType == AddressType.P2SH) return scriptP2SHHash(bytes20(implementationHash));
if (addressType == AddressType.P2WPKH) {
return scriptP2WPKHHash(bytes20(implementationHash));
}
if (addressType == AddressType.P2SH) {
return scriptP2WSHHash(implementationHash);
}
if (addressType == AddressType.P2TR) {
return scriptP2TRHash(implementationHash);
}
}

/// @notice Get the associated script out for a P2PKH address
function scriptP2PKHHash(bytes20 pHash) internal pure returns(bytes32) {
// OP_DUB, OP_HASH160, <pubKeyHash 20>, OP_EQUALVERIFY, OP_CHECKSIG
return keccak256(bytes.concat(OP_DUB, OP_HASH160, PUSH_20, pHash, OP_EQUALVERIFY, OP_CHECKSIG));
}

/// @notice Get the associated script out for a P2SH address
function scriptP2SHHash(bytes20 sHash) internal pure returns(bytes32) {
// OP_HASH160, <data 20>, OP_EQUAL
return keccak256(bytes.concat(OP_HASH160, PUSH_20, sHash, OP_EQUAL));
}

function scriptP2WPKHHash(bytes20 witnessProgram) internal pure returns(bytes32) {
// OP_0, <data 20>
return keccak256(bytes.concat(OP_0, PUSH_20, witnessProgram));
}

function scriptP2WSHHash(bytes32 witnessProgram) internal pure returns(bytes32) {
return keccak256(bytes.concat(OP_0, PUSH_32, witnessProgram));
}

function scriptP2TRHash(bytes32 witnessProgram) internal pure returns(bytes32) {
return keccak256(bytes.concat(OP_1, PUSH_32, witnessProgram));
}
}

0 comments on commit 085764f

Please sign in to comment.