Verified contractPartialMIT
BTCProofOfPossession
Address0x01b78cc08151e4ef63351fb22685a407dbfb854c
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.28
- Same code
1 more contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,376,244
- Creation transaction
- 0x4f8735bd0c…e99025a4b9
- Libraries
- lib/vault-contracts/src/protocol/lib/BTCProofOfPossession.sol:BIP340Utils0xb870…ec67cc
8 files
- lib/vault-contracts/src/protocol/lib/BTCProofOfPossession.solmain24.51 KB
- lib/vault-contracts/lib/elliptic-curve-solidity/contracts/EllipticCurve.sol13.69 KB
- lib/vault-contracts/src/protocol/lib/helpers/BIP322Utils.sol13.6 KB
- lib/vault-contracts/src/protocol/lib/helpers/BIP340Utils.sol4.71 KB
- lib/vault-contracts/src/protocol/lib/helpers/CompactSize.sol8.53 KB
- lib/vault-contracts/src/protocol/lib/helpers/Secp256k1.sol3.32 KB
- lib/vault-contracts/src/protocol/lib/taproot/BIP341.sol15.55 KB
- lib/vault-contracts/src/protocol/lib/taproot/TaprootConstants.sol2.39 KB
lib/vault-contracts/src/protocol/lib/BTCProofOfPossession.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "./helpers/Secp256k1.sol";
import "./helpers/BIP340Utils.sol";
import "./helpers/BIP322Utils.sol";
/**
* @title BTCProofOfPossession
* @notice Library for verifying Bitcoin BIP-322 proof of possession signatures
* @dev Verifies that a BTC private key signed a message containing an Ethereum
* address hex representation to prove ownership
* @dev BIP-322 verification supports P2WPKH (using ECDSA) and P2TR key-path
* (using Schnorr) address types
* @dev This library is deployed as an EXTERNAL library to reduce contract size
*/
library BTCProofOfPossession {
// ========== CONSTANTS ==========
/// @notice Action constants for PoP signature context
bytes32 internal constant ACTION_REGISTER = keccak256("register");
/// @notice Action constant for declaring/rotating an operation BTC key
bytes32 internal constant ACTION_SET_OPERATION_BTC_KEY = keccak256("set_operation_btc_key");
/// @notice Minimum valid BIP-322 PoP signature length (P2TR with
/// SIGHASH_DEFAULT: 1 count + 1 length + 64 sig)
uint256 internal constant MIN_POP_SIGNATURE_LENGTH = 66;
/// @notice Maximum valid BIP-322 PoP signature length (P2WPKH: 1 count +
/// 1 sigLen + 73 DER+sighash + 1 pkLen + 33 pk)
uint256 internal constant MAX_POP_SIGNATURE_LENGTH = 109;
// ========== ERRORS ==========
/// @notice Error for invalid BTC PoP signature length
error InvalidBTCPopSignatureLength(uint256 length, uint256 minLength, uint256 maxLength);
/// @notice Error for invalid action string
error InvalidAction(bytes32 action);
/// @notice Error for public key mismatch
error PublicKeyMismatch(bytes32 expected, bytes32 actual);
/// @notice Error for invalid S value (not normalized)
error InvalidSValue(bytes32 s);
/// @notice Error for unsupported address type
error UnsupportedAddressType(uint8 witnessItemCount);
/// @notice Error for invalid BIP-322 signature
error InvalidBIP322Signature(uint256 offset, uint256 length);
/// @notice Error for invalid witness data
error InvalidWitnessData(uint256 offset, uint256 expected, uint256 actual);
// ========== EXTERNAL FUNCTIONS ==========
/**
* @notice Verify a BIP-322 proof of possession
* @dev Verifies that the BTC private key corresponding to bip340PubKeyX
* signed the owner address
* @dev Includes chain ID, action, and verifying contract address to prevent
* cross-chain, cross-context, and cross-contract replay attacks
* @dev Message format:
* "0x<address>:<chainId>:<action>:<verifying_contract>"
* @dev Both address and verifying_contract are lowercase hex strings
* @dev BIP-322 signatures are witness-encoded and must be between 66 and
* 109 bytes
* @param signature The BIP-322 witness-encoded signature
* @param bip340PubKeyX The 32-byte BIP-340 x-only public key to verify
* against
* @param owner The Ethereum address that was in the signed message
* @param action The action context for the signature
* @return True if the signature is valid
*/
function verify(bytes memory signature, bytes32 bip340PubKeyX, address owner, bytes32 action)
external
view
returns (bool)
{
if (action != ACTION_REGISTER) {
revert InvalidAction(action);
}
bytes memory message = buildMessage(owner, block.chainid, action, address(this));
if (signature.length < MIN_POP_SIGNATURE_LENGTH || signature.length > MAX_POP_SIGNATURE_LENGTH) {
revert InvalidBTCPopSignatureLength(signature.length, MIN_POP_SIGNATURE_LENGTH, MAX_POP_SIGNATURE_LENGTH);
}
return verify(signature, bip340PubKeyX, message);
}
/**
* @notice Verify a BIP-322 proof of possession bound to an extra payload
* @dev Message format:
* "0x<address>:<chainId>:<action>:<verifying_contract>:<payload_hex>"
* Lowercase hex for address, verifying_contract and payload.
* @dev The payload is included in the signed message, so an attacker
* cannot replay a signature with a different payload.
* @param signature The BIP-322 witness-encoded signature
* @param bip340PubKeyX The 32-byte BIP-340 x-only public key to verify
* against
* @param owner The Ethereum address that was in the signed message
* @param action The action context (ACTION_SET_OPERATION_BTC_KEY)
* @param payload Arbitrary payload bytes bound into the signed message
* @return True if the signature is valid
*/
function verifyWithPayload(
bytes memory signature,
bytes32 bip340PubKeyX,
address owner,
bytes32 action,
bytes memory payload
) external view returns (bool) {
if (action != ACTION_SET_OPERATION_BTC_KEY) {
revert InvalidAction(action);
}
bytes memory message = buildMessageWithPayload(owner, block.chainid, action, address(this), payload);
if (signature.length < MIN_POP_SIGNATURE_LENGTH || signature.length > MAX_POP_SIGNATURE_LENGTH) {
revert InvalidBTCPopSignatureLength(signature.length, MIN_POP_SIGNATURE_LENGTH, MAX_POP_SIGNATURE_LENGTH);
}
return verify(signature, bip340PubKeyX, message);
}
// ========== INTERNAL FUNCTIONS ==========
/**
* @notice Verify BIP-322 proof of possession signature
* @dev Detects address type from witness structure
* - P2TR key-path: 1 witness item (Schnorr signature)
* - P2WPKH: 2 witness items (ECDSA signature + compressed public key)
* @param signature The BIP-322 simple signature bytes (witness data)
* @param bip340PubKeyX The 32-byte BIP-340 x-only public key to verify
* against
* @param message The message that was signed
* @return True if the signature is valid and matches the public key
*/
function verify(bytes memory signature, bytes32 bip340PubKeyX, bytes memory message) internal pure returns (bool) {
if (signature.length == 0 || message.length == 0) {
revert InvalidBIP322Signature(signature.length, message.length);
}
if (signature.length < 2) {
revert InvalidWitnessData(0, 2, signature.length);
}
uint8 witnessItemCount = uint8(signature[0]);
if (witnessItemCount == 1) {
return verifyBIP322P2TR(signature, bip340PubKeyX, message);
}
if (witnessItemCount == 2) {
return verifyBIP322P2WPKH(signature, bip340PubKeyX, message);
}
revert UnsupportedAddressType(witnessItemCount);
}
/**
* @notice Verify BIP-322 signature for P2TR (Taproot) address with key-path spending
* @dev Uses BIP-340 Schnorr signature verification with tweaked output key
* @dev Accepts both SIGHASH_DEFAULT (0x00) and SIGHASH_ALL (0x01) for wallet compatibility
* @param signature The witness data containing the Schnorr signature
* @param bip340PubKeyX The x-only internal public key
* @param message The message that was signed
* @return True if verification succeeds
*/
function verifyBIP322P2TR(bytes memory signature, bytes32 bip340PubKeyX, bytes memory message)
internal
pure
returns (bool)
{
uint8 witnessItemCount = uint8(signature[0]);
if (witnessItemCount != 1) {
revert InvalidWitnessData(0, 1, witnessItemCount);
}
uint8 sigLength = uint8(signature[1]);
if (sigLength != 64 && sigLength != 65) {
revert InvalidWitnessData(1, 64, sigLength);
}
// Canonical BIP-322 P2TR witness is exactly 2 + sigLength bytes
// (1 witnessItemCount + 1 sigLength + sigLength). Trailing bytes
// are rejected to prevent proof malleability.
if (signature.length != 2 + uint256(sigLength)) {
revert InvalidWitnessData(0, 2 + uint256(sigLength), signature.length);
}
uint8 hashType = 0x00;
if (sigLength == 65) {
hashType = uint8(signature[66]);
if (hashType != 0x01) {
revert InvalidWitnessData(66, 0x01, hashType);
}
}
bytes32 r;
bytes32 s;
assembly {
r := mload(add(signature, 34))
s := mload(add(signature, 66))
}
bytes32 msgHash = BIP322Utils.calculateBIP322SigHashP2TR(message, bip340PubKeyX, hashType);
bytes32 tweakedPubKeyX = BIP322Utils.taprootTweakPubKey(bip340PubKeyX);
bool valid = BIP340Utils.verify(uint256(tweakedPubKeyX), uint256(r), uint256(s), msgHash);
if (!valid) {
revert InvalidBIP322Signature(2, sigLength);
}
return true;
}
/**
* @notice Verify BIP-322 signature for P2WPKH (SegWit) address
* @dev Uses ECDSA signature verification and recovers the public key
* @param signature The witness data containing ECDSA signature and public key
* @param bip340PubKeyX The x-only public key to verify against
* @param message The message that was signed
* @return True if verification succeeds
*/
function verifyBIP322P2WPKH(bytes memory signature, bytes32 bip340PubKeyX, bytes memory message)
internal
pure
returns (bool)
{
(bytes32 r, bytes32 s, bytes memory compressedPubKey) = parseP2WPKHWitnessWithPubKey(signature);
bytes32 pubKeyX;
assembly {
let dataStart := add(compressedPubKey, 32)
pubKeyX := mload(add(dataStart, 1))
}
if (pubKeyX != bip340PubKeyX) {
revert PublicKeyMismatch(bip340PubKeyX, pubKeyX);
}
if (!Secp256k1.isNormalizedSignature(s)) {
revert InvalidSValue(s);
}
bytes32 msgHash = BIP322Utils.calculateBIP322SigHashP2WPKH(message, compressedPubKey);
return verifyECDSARecoveryWithCompressedKey(msgHash, r, s, compressedPubKey);
}
function parseP2WPKHWitnessWithPubKey(bytes memory signature)
internal
pure
returns (bytes32 r, bytes32 s, bytes memory compressedPubKey)
{
// For P2WPKH, witness contains: [signature, pubkey]
// BIP-322 witness format: [num_items, sig_length, signature, pubkey_length, pubkey]
if (uint8(signature[0]) != 2) {
revert InvalidWitnessData(0, 2, uint8(signature[0]));
}
uint8 sigLength = uint8(signature[1]);
// Canonical P2WPKH witness is exactly 2 (header) + sigLength
// (DER+sighash) + 1 (pubkey length byte) + 33 (compressed pubkey)
// bytes. The sigLength floor of 9 corresponds to the shortest
// canonical ECDSA DER signature (0x30 0x06 0x02 0x01 <r> 0x02 0x01
// <s>) plus the sighash byte. Reject non-canonical lengths to
// prevent witness malleability.
if (sigLength < 9 || signature.length != uint256(sigLength) + 36) {
revert InvalidWitnessData(1, uint256(sigLength) + 36, signature.length);
}
uint256 offset = 2;
// The signature must use the SIGHASH_ALL (0x01) flag at the end
uint8 lastByte = uint8(signature[offset + sigLength - 1]);
if (lastByte != 0x01) {
revert InvalidWitnessData(offset + sigLength - 1, 0x01, lastByte);
}
uint8 derLength = sigLength - 1;
// Parse DER signature
(r, s) = parseDERSignature(signature, offset, derLength);
offset += sigLength;
// Extract public key
if (uint8(signature[offset]) != 33) {
revert InvalidWitnessData(offset, 33, uint8(signature[offset]));
}
offset++;
// Get compressed public key (33 bytes) - optimized with assembly
compressedPubKey = new bytes(33);
assembly {
let src := add(add(signature, 32), offset)
let dst := add(compressedPubKey, 32)
// Copy bytes 0..31 of the compressed pubkey
// (= signature[offset .. offset+32)).
mstore(dst, mload(src))
// Copy byte 32 only. mload at src+1 reads
// signature[offset+1 .. offset+33), whose low byte
// (selected via byte(31, _)) is signature[offset+32].
// mstore8 writes a single byte, keeping the destination
// write strictly within the 33-byte buffer. Previously
// a second `mstore` at src+32 read 32 bytes past the
// signature tail and wrote 32 bytes past compressedPubKey.
mstore8(add(dst, 32), byte(31, mload(add(src, 1))))
}
return (r, s, compressedPubKey);
}
function verifyECDSARecoveryWithCompressedKey(bytes32 msgHash, bytes32 r, bytes32 s, bytes memory compressedPubKey)
internal
pure
returns (bool)
{
require(compressedPubKey.length == 33, "Invalid compressed key length");
bytes32 expectedPubKeyX;
assembly {
let dataStart := add(compressedPubKey, 32)
expectedPubKeyX := mload(add(dataStart, 1))
}
uint8 prefix = uint8(compressedPubKey[0]);
require(prefix == 0x02 || prefix == 0x03, "Invalid compressed key prefix");
uint8 expectedYParity = prefix - 0x02;
for (uint8 v = 27; v <= 28; v++) {
uint8 recoveryId = v - 27;
(uint256 recoveredX, uint256 recoveredY) =
Secp256k1.recover(uint256(msgHash), recoveryId, uint256(r), uint256(s));
if (recoveredX != 0 && recoveredY != 0) {
if (bytes32(recoveredX) == expectedPubKeyX) {
uint8 recoveredYParity = uint8(recoveredY & 1);
if (recoveredYParity == expectedYParity) {
return true;
}
}
}
}
revert InvalidBIP322Signature(0, 64);
}
function buildMessage(address owner, uint256 chainId, bytes32 action, address verifyingContract)
private
pure
returns (bytes memory)
{
string memory actionString;
if (action == ACTION_REGISTER) {
actionString = "register";
} else if (action == ACTION_SET_OPERATION_BTC_KEY) {
actionString = "set_operation_btc_key";
} else {
revert InvalidAction(action);
}
return abi.encodePacked(
addressToHex(owner), ":", uintToBytes(chainId), ":", actionString, ":", addressToHex(verifyingContract)
);
}
/// @notice Encode the high 16 bytes of `data` as 32 lowercase ASCII hex
/// characters using SWAR (SIMD-within-a-register) nibble expansion.
/// @dev Adapted from Mikhail Vladimirov's toHex16. The final correction term
/// uses `* 39` (0x27) instead of the original `* 7`: `* 7` maps nibbles
/// >= 10 to uppercase A-F, `* 39` maps them to lowercase a-f, which is the
/// casing the signed proof-of-possession message requires.
/// @param data The 16 bytes to encode (held in the high half of the value)
/// @return result 32 bytes, each an ASCII hex character for one input nibble
function _toHex16(bytes16 data) internal pure returns (bytes32 result) {
result = (bytes32(data) & 0xFFFFFFFFFFFFFFFF000000000000000000000000000000000000000000000000)
| (bytes32(data) & 0x0000000000000000FFFFFFFFFFFFFFFF00000000000000000000000000000000) >> 64;
result = (result & 0xFFFFFFFF000000000000000000000000FFFFFFFF000000000000000000000000)
| (result & 0x00000000FFFFFFFF000000000000000000000000FFFFFFFF0000000000000000) >> 32;
result = (result & 0xFFFF000000000000FFFF000000000000FFFF000000000000FFFF000000000000)
| (result & 0x0000FFFF000000000000FFFF000000000000FFFF000000000000FFFF00000000) >> 16;
result = (result & 0xFF000000FF000000FF000000FF000000FF000000FF000000FF000000FF000000)
| (result & 0x00FF000000FF000000FF000000FF000000FF000000FF000000FF000000FF0000) >> 8;
result = (result & 0xF000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000) >> 4
| (result & 0x0F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F00) >> 8;
result = bytes32(
0x3030303030303030303030303030303030303030303030303030303030303030 + uint256(result)
+ (((uint256(result) + 0x0606060606060606060606060606060606060606060606060606060606060606) >> 4)
& 0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F) * 39
);
}
function buildMessageWithPayload(
address owner,
uint256 chainId,
bytes32 action,
address verifyingContract,
bytes memory payload
) private pure returns (bytes memory) {
return abi.encodePacked(buildMessage(owner, chainId, action, verifyingContract), ":", bytesToHex(payload));
}
/// @notice Lowercase hex-encode arbitrary-length bytes, without a `0x` prefix
/// @dev Full 16-byte chunks are encoded with `_toHex16` and written in a single MSTORE; a
/// trailing 1..15-byte chunk is encoded then copied char-by-char so the write stays within
/// `result`. Optimized form from #507 (audit follow-up); equivalent to the naive loop.
function bytesToHex(bytes memory data) internal pure returns (bytes memory) {
uint256 len = data.length;
bytes memory result = new bytes(len * 2);
uint256 offset;
while (offset + 16 <= len) {
bytes16 chunk;
assembly {
// Load data[offset..offset+16) into the high half of `chunk` and zero the low half.
// MLOAD reads 32 bytes; bytes [offset+16, offset+32) may extend past the data
// contents into adjacent allocated memory, so they are masked off here.
chunk := and(
mload(add(add(data, 0x20), offset)),
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000
)
}
bytes32 hexed = _toHex16(chunk);
assembly {
// offset + 16 <= len, so this 32-byte write stays within result.
mstore(add(add(result, 0x20), mul(offset, 2)), hexed)
}
offset += 16;
}
if (offset < len) {
bytes16 chunk;
assembly {
chunk := and(
mload(add(add(data, 0x20), offset)),
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000
)
}
bytes32 hexed = _toHex16(chunk);
uint256 tailChars = (len - offset) * 2;
for (uint256 j = 0; j < tailChars; j++) {
result[offset * 2 + j] = hexed[j];
}
}
return result;
}
/// @notice Lowercase hex-encode a 20-byte address with a `0x` prefix
/// @dev The address is left-aligned into a word; the first 16 bytes encode to
/// 32 chars and bytes 16..19 to the leading 8 chars of the second half
/// (the remaining chars encode the zero padding and are dropped).
function addressToHex(address addr) internal pure returns (bytes memory) {
bytes32 word = bytes32(bytes20(addr));
return abi.encodePacked("0x", _toHex16(bytes16(word)), bytes8(_toHex16(bytes16(word << 128))));
}
function uintToBytes(uint256 value) private pure returns (bytes memory) {
if (value == 0) return "0";
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits;
while (value != 0) {
index--;
buffer[index] = bytes1(uint8(48 + value % 10));
value /= 10;
}
return buffer;
}
function parseDERSignature(bytes memory data, uint256 offset, uint256 length)
private
pure
returns (bytes32 r, bytes32 s)
{
// Minimum valid DER: 0x30 LEN 0x02 0x01 <r> 0x02 0x01 <s> = 8 bytes
if (length < 8 || data[offset] != 0x30) {
revert InvalidBIP322Signature(offset, length);
}
// BIP-66: outer SEQUENCE length must cover the remaining bytes exactly.
// Rejects trailing garbage and length-field/content disagreement.
if (uint8(data[offset + 1]) != length - 2) {
revert InvalidBIP322Signature(offset + 1, length);
}
uint256 end = offset + length;
uint256 pos = offset + 2;
(r, pos) = parseDERInteger(data, pos, end);
(s, pos) = parseDERInteger(data, pos, end);
if (pos != end) {
revert InvalidBIP322Signature(pos, end);
}
return (r, s);
}
/**
* @notice Parse a single BIP-66 canonical DER INTEGER into a bytes32 value
* @dev Enforces minimal encoding: rejects non-canonical leading 0x00 bytes
* and rejects high-bit-set first bytes (negative-integer encoding)
* @param data The buffer containing the DER-encoded signature
* @param pos The offset of the INTEGER tag within `data`
* @param end The exclusive upper bound within which the integer must fit
* @return value The integer left-padded into a bytes32 (big-endian)
* @return newPos The offset immediately after the parsed integer
*/
function parseDERInteger(bytes memory data, uint256 pos, uint256 end)
private
pure
returns (bytes32 value, uint256 newPos)
{
// INTEGER tag + length byte must fit within the remaining bytes
if (pos + 2 > end || data[pos] != 0x02) {
revert InvalidBIP322Signature(pos, end);
}
pos++;
uint8 intLength = uint8(data[pos]);
pos++;
// secp256k1 scalars fit in 32 bytes; canonical DER allows up to 33
// bytes when a leading 0x00 padding is required. Length 0 is invalid.
if (intLength == 0 || intLength > 33 || pos + intLength > end) {
revert InvalidBIP322Signature(pos, intLength);
}
uint8 firstByte = uint8(data[pos]);
// High bit set on the first byte would encode a negative integer.
// BIP-66 requires ECDSA scalars to be encoded as positive integers.
if (firstByte & 0x80 != 0) {
revert InvalidBIP322Signature(pos, intLength);
}
// A 33-byte encoding is only canonical when it is exactly 0x00 padding
// of a 32-byte value whose high bit is set. Any other 33-byte content
// would represent a scalar >= 2**256, which is out of range.
if (intLength == 33 && firstByte != 0x00) {
revert InvalidBIP322Signature(pos, intLength);
}
// A leading 0x00 byte is only canonical when it is strictly required
// to keep the integer positive (next byte has its high bit set).
// Rejecting redundant 0x00 padding enforces BIP-66 signature
// malleability resistance.
if (intLength > 1 && firstByte == 0x00 && uint8(data[pos + 1]) & 0x80 == 0) {
revert InvalidBIP322Signature(pos, intLength);
}
uint256 valueStart = pos;
uint8 valueLen = intLength;
if (intLength == 33) {
// Strip the mandatory 0x00 padding; the scalar fits in 32 bytes.
valueStart++;
valueLen = 32;
}
value = bytesToBytes32(data, valueStart, valueLen);
newPos = pos + intLength;
}
function bytesToBytes32(bytes memory data, uint256 offset, uint256 length) private pure returns (bytes32 result) {
require(length <= 32, "Length exceeds 32 bytes");
// Defense-in-depth: callers within this library already enforce
// offset + length <= data.length, but checking it at the unsafe-assembly
// boundary localizes the safety property and guards against future
// callers that might violate the invariant.
require(offset + length <= data.length, "Out of bounds");
assembly {
result := mload(add(add(data, 32), offset))
if lt(length, 32) { result := shr(mul(sub(32, length), 8), result) }
}
return result;
}
}
lib/vault-contracts/lib/elliptic-curve-solidity/contracts/EllipticCurve.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
** @title Elliptic Curve Library
** @dev Library providing arithmetic operations over elliptic curves.
** This library does not check whether the inserted points belong to the curve
** `isOnCurve` function should be used by the library user to check the aforementioned statement.
** @author Witnet Foundation
*/
library EllipticCurve {
// Pre-computed constant for 2 ** 255
uint256 private constant U255_MAX_PLUS_1 =
57896044618658097711785492504343953926634992332820282019728792003956564819968;
/// @dev Modular euclidean inverse of a number (mod p).
/// @param _x The number
/// @param _pp The modulus
/// @return q such that x*q = 1 (mod _pp)
function invMod(uint256 _x, uint256 _pp) internal pure returns (uint256) {
require(_x != 0 && _x != _pp && _pp != 0, "Invalid number");
uint256 q = 0;
uint256 newT = 1;
uint256 r = _pp;
uint256 t;
while (_x != 0) {
t = r / _x;
(q, newT) = (newT, addmod(q, (_pp - mulmod(t, newT, _pp)), _pp));
(r, _x) = (_x, r - t * _x);
}
return q;
}
/// @dev Modular exponentiation, b^e % _pp.
/// Source: https://github.com/androlo/standard-contracts/blob/master/contracts/src/crypto/ECCMath.sol
/// @param _base base
/// @param _exp exponent
/// @param _pp modulus
/// @return r such that r = b**e (mod _pp)
function expMod(
uint256 _base,
uint256 _exp,
uint256 _pp
)
internal pure
returns (uint256)
{
require(_pp != 0, "EllipticCurve: modulus is zero");
if (_base == 0) return 0;
if (_exp == 0) return 1;
uint256 r = 1;
uint256 bit = U255_MAX_PLUS_1;
assembly {
for {
} gt(bit, 0) {
} {
r := mulmod(
mulmod(r, r, _pp),
exp(_base, iszero(iszero(and(_exp, bit)))),
_pp
)
r := mulmod(
mulmod(r, r, _pp),
exp(_base, iszero(iszero(and(_exp, div(bit, 2))))),
_pp
)
r := mulmod(
mulmod(r, r, _pp),
exp(_base, iszero(iszero(and(_exp, div(bit, 4))))),
_pp
)
r := mulmod(
mulmod(r, r, _pp),
exp(_base, iszero(iszero(and(_exp, div(bit, 8))))),
_pp
)
bit := div(bit, 16)
}
}
return r;
}
/// @dev Converts a point (x, y, z) expressed in Jacobian coordinates to affine coordinates (x', y', 1).
/// @param _x coordinate x
/// @param _y coordinate y
/// @param _z coordinate z
/// @param _pp the modulus
/// @return (x', y') affine coordinates
function toAffine(
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _pp
)
internal pure
returns (uint256, uint256)
{
uint256 zInv = invMod(_z, _pp);
uint256 zInv2 = mulmod(zInv, zInv, _pp);
uint256 x2 = mulmod(_x, zInv2, _pp);
uint256 y2 = mulmod(_y, mulmod(zInv, zInv2, _pp), _pp);
return (x2, y2);
}
/// @dev Derives the y coordinate from a compressed-format point x [[SEC-1]](https://www.secg.org/SEC1-Ver-1.0.pdf).
/// @param _prefix parity byte (0x02 even, 0x03 odd)
/// @param _x coordinate x
/// @param _aa constant of curve
/// @param _bb constant of curve
/// @param _pp the modulus
/// @return y coordinate y
function deriveY(
uint8 _prefix,
uint256 _x,
uint256 _aa,
uint256 _bb,
uint256 _pp
)
internal pure
returns (uint256)
{
require(
_prefix == 0x02 || _prefix == 0x03,
"EllipticCurve:innvalid compressed EC point prefix"
);
// x^3 + ax + b
uint256 y2 = addmod(
mulmod(_x, mulmod(_x, _x, _pp), _pp),
addmod(mulmod(_x, _aa, _pp), _bb, _pp),
_pp
);
y2 = expMod(y2, (_pp + 1) / 4, _pp);
// uint256 cmp = yBit ^ y_ & 1;
uint256 y = (y2 + _prefix) % 2 == 0 ? y2 : _pp - y2;
return y;
}
/// @dev Check whether point (x,y) is on curve defined by a, b, and _pp.
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _aa constant of curve
/// @param _bb constant of curve
/// @param _pp the modulus
/// @return true if x,y in the curve, false else
function isOnCurve(
uint _x,
uint _y,
uint _aa,
uint _bb,
uint _pp
)
internal pure
returns (bool)
{
if (0 == _x || _x >= _pp || 0 == _y || _y >= _pp) {
return false;
}
// y^2
uint lhs = mulmod(_y, _y, _pp);
// x^3
uint rhs = mulmod(mulmod(_x, _x, _pp), _x, _pp);
if (_aa != 0) {
// x^3 + a*x
rhs = addmod(rhs, mulmod(_x, _aa, _pp), _pp);
}
if (_bb != 0) {
// x^3 + a*x + b
rhs = addmod(rhs, _bb, _pp);
}
return lhs == rhs;
}
/// @dev Calculate inverse (x, -y) of point (x, y).
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _pp the modulus
/// @return (x, -y)
function ecInv(
uint256 _x,
uint256 _y,
uint256 _pp
)
internal pure
returns (uint256, uint256)
{
return (_x, (_pp - _y) % _pp);
}
/// @dev Add two points (x1, y1) and (x2, y2) in affine coordinates.
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _x2 coordinate x of P2
/// @param _y2 coordinate y of P2
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = P1+P2 in affine coordinates
function ecAdd(
uint256 _x1,
uint256 _y1,
uint256 _x2,
uint256 _y2,
uint256 _aa,
uint256 _pp
)
internal pure
returns (uint256, uint256)
{
uint x = 0;
uint y = 0;
uint z = 0;
// Double if x1==x2 else add
if (_x1 == _x2) {
// y1 = -y2 mod p
if (addmod(_y1, _y2, _pp) == 0) {
return (0, 0);
} else {
// P1 = P2
(x, y, z) = jacDouble(_x1, _y1, 1, _aa, _pp);
}
} else {
(x, y, z) = jacAdd(_x1, _y1, 1, _x2, _y2, 1, _pp);
}
// Get back to affine
return toAffine(x, y, z, _pp);
}
/// @dev Substract two points (x1, y1) and (x2, y2) in affine coordinates.
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _x2 coordinate x of P2
/// @param _y2 coordinate y of P2
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = P1-P2 in affine coordinates
function ecSub(
uint256 _x1,
uint256 _y1,
uint256 _x2,
uint256 _y2,
uint256 _aa,
uint256 _pp
)
internal pure
returns (uint256, uint256)
{
// invert square
(uint256 x, uint256 y) = ecInv(_x2, _y2, _pp);
// P1-square
return ecAdd(_x1, _y1, x, y, _aa, _pp);
}
/// @dev Multiply point (x1, y1, z1) times d in affine coordinates.
/// @param _k scalar to multiply
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = d*P in affine coordinates
function ecMul(
uint256 _k,
uint256 _x,
uint256 _y,
uint256 _aa,
uint256 _pp
)
internal pure
returns (uint256, uint256)
{
// Jacobian multiplication
(uint256 x1, uint256 y1, uint256 z1) = jacMul(_k, _x, _y, 1, _aa, _pp);
// Get back to affine
return toAffine(x1, y1, z1, _pp);
}
/// @dev Adds two points (x1, y1, z1) and (x2 y2, z2).
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _z1 coordinate z of P1
/// @param _x2 coordinate x of square
/// @param _y2 coordinate y of square
/// @param _z2 coordinate z of square
/// @param _pp the modulus
/// @return (qx, qy, qz) P1+square in Jacobian
function jacAdd(
uint256 _x1,
uint256 _y1,
uint256 _z1,
uint256 _x2,
uint256 _y2,
uint256 _z2,
uint256 _pp
)
internal pure
returns (uint256, uint256, uint256)
{
if (_x1 == 0 && _y1 == 0) return (_x2, _y2, _z2);
if (_x2 == 0 && _y2 == 0) return (_x1, _y1, _z1);
// We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
uint[4] memory zs; // z1^2, z1^3, z2^2, z2^3
zs[0] = mulmod(_z1, _z1, _pp);
zs[1] = mulmod(_z1, zs[0], _pp);
zs[2] = mulmod(_z2, _z2, _pp);
zs[3] = mulmod(_z2, zs[2], _pp);
// u1, s1, u2, s2
zs = [
mulmod(_x1, zs[2], _pp),
mulmod(_y1, zs[3], _pp),
mulmod(_x2, zs[0], _pp),
mulmod(_y2, zs[1], _pp)
];
// In case of zs[0] == zs[2] && zs[1] == zs[3], double function should be used
require(
zs[0] != zs[2] || zs[1] != zs[3],
"Use jacDouble function instead"
);
uint[4] memory hr;
//h
hr[0] = addmod(zs[2], _pp - zs[0], _pp);
//r
hr[1] = addmod(zs[3], _pp - zs[1], _pp);
//h^2
hr[2] = mulmod(hr[0], hr[0], _pp);
// h^3
hr[3] = mulmod(hr[2], hr[0], _pp);
// qx = -h^3 -2u1h^2+r^2
uint256 qx = addmod(mulmod(hr[1], hr[1], _pp), _pp - hr[3], _pp);
qx = addmod(qx, _pp - mulmod(2, mulmod(zs[0], hr[2], _pp), _pp), _pp);
// qy = -s1*z1*h^3+r(u1*h^2 -x^3)
uint256 qy = mulmod(
hr[1],
addmod(mulmod(zs[0], hr[2], _pp), _pp - qx, _pp),
_pp
);
qy = addmod(qy, _pp - mulmod(zs[1], hr[3], _pp), _pp);
// qz = h*z1*z2
uint256 qz = mulmod(hr[0], mulmod(_z1, _z2, _pp), _pp);
return (qx, qy, qz);
}
/// @dev Doubles a points (x, y, z).
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _z coordinate z of P1
/// @param _aa the a scalar in the curve equation
/// @param _pp the modulus
/// @return (qx, qy, qz) 2P in Jacobian
function jacDouble(
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _aa,
uint256 _pp
)
internal pure
returns (uint256, uint256, uint256)
{
if (_z == 0) return (_x, _y, _z);
// We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
// Note: there is a bug in the paper regarding the m parameter, M=3*(x1^2)+a*(z1^4)
// x, y, z at this point represent the squares of _x, _y, _z
uint256 x = mulmod(_x, _x, _pp); //x1^2
uint256 y = mulmod(_y, _y, _pp); //y1^2
uint256 z = mulmod(_z, _z, _pp); //z1^2
// s
uint s = mulmod(4, mulmod(_x, y, _pp), _pp);
// m
uint m = addmod(
mulmod(3, x, _pp),
mulmod(_aa, mulmod(z, z, _pp), _pp),
_pp
);
// x, y, z at this point will be reassigned and rather represent qx, qy, qz from the paper
// This allows to reduce the gas cost and stack footprint of the algorithm
// qx
x = addmod(mulmod(m, m, _pp), _pp - addmod(s, s, _pp), _pp);
// qy = -8*y1^4 + M(S-T)
y = addmod(
mulmod(m, addmod(s, _pp - x, _pp), _pp),
_pp - mulmod(8, mulmod(y, y, _pp), _pp),
_pp
);
// qz = 2*y1*z1
z = mulmod(2, mulmod(_y, _z, _pp), _pp);
return (x, y, z);
}
/// @dev Multiply point (x, y, z) times d.
/// @param _d scalar to multiply
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _z coordinate z of P1
/// @param _aa constant of curve
/// @param _pp the modulus
/// @return (qx, qy, qz) d*P1 in Jacobian
function jacMul(
uint256 _d,
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _aa,
uint256 _pp
)
internal pure
returns (uint256, uint256, uint256)
{
// Early return in case that `_d == 0`
if (_d == 0) {
return (_x, _y, _z);
}
uint256 remaining = _d;
uint256 qx = 0;
uint256 qy = 0;
uint256 qz = 1;
// Double and add algorithm
while (remaining != 0) {
if ((remaining & 1) != 0) {
(qx, qy, qz) = jacAdd(qx, qy, qz, _x, _y, _z, _pp);
}
remaining = remaining / 2;
(_x, _y, _z) = jacDouble(_x, _y, _z, _aa, _pp);
}
return (qx, qy, qz);
}
}
lib/vault-contracts/src/protocol/lib/helpers/BIP322Utils.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {BIP341} from "../taproot/BIP341.sol";
/**
* @title BIP322Utils
* @notice Utility functions for BIP-322 signature verification
* @dev Implements BIP-322 transaction construction and sighash calculation
* @dev Reference: https://github.com/bitcoin/bips/blob/master/bip-0322.mediawiki
* @dev NOTE: for wallet compatibility SIGHASH_DEFAULT (0x00) and SIGHASH_ALL (0x01) are supported
* for Taproot addresses; only SIGHASH_ALL is supported for P2WPKH addresses.
*/
library BIP322Utils {
/// @notice Maximum scriptPubKey length encodable as a single-byte Bitcoin
/// compact size. Values 0xFD-0xFF are reserved as multi-byte size
/// prefixes, so a 1-byte length cast is only canonical for lengths
/// 0..0xFC (= 252).
uint256 internal constant MAX_SINGLE_BYTE_COMPACT_SIZE = 252;
/// @notice Thrown when a scriptPubKey exceeds the single-byte compact-size
/// length encoding range used by buildToSpendTx and calculateTaprootSigHash.
error ScriptPubKeyTooLong();
/**
* @notice Compute the Taproot tweaked output key for key-path spending
* @dev For key-path only (no script tree), output_key = internal_key + hash("TapTweak" || internal_key) * G
* @dev Uses BIP341 library for standardized Taproot key tweaking
* @param internalPubKeyX The x-only internal public key
* @return The x-only tweaked output key
*/
function taprootTweakPubKey(bytes32 internalPubKeyX) internal pure returns (bytes32) {
// Use BIP341.computeOutputKey for key-path only spending (empty merkle root)
(bytes32 outputKey,) = BIP341.computeOutputKey(internalPubKeyX, "");
return outputKey;
}
/**
* @notice Calculate BIP-340 tagged hash for BIP-322
* @dev Implements: sha256(sha256(tag) || sha256(tag) || msg)
* @param message The message to hash
* @return The tagged hash
*/
function getBIP340TaggedHash(bytes memory message) internal pure returns (bytes32) {
bytes32 tagHash = sha256(abi.encodePacked("BIP0322-signed-message"));
return sha256(abi.encodePacked(tagHash, tagHash, message));
}
/**
* @notice Convert internal public key to P2TR scriptPubKey
* @param bip340PubKeyX The x-only internal public key
* @return The P2TR scriptPubKey
*/
function pubKeyToP2TRScriptPubKey(bytes32 bip340PubKeyX) internal pure returns (bytes memory) {
// P2TR: OP_1 OP_PUSHBYTES_32 <taproot_output_key>
// For key-path only spending (no script tree), we must use the TWEAKED output key
bytes32 tweakedOutputKey = taprootTweakPubKey(bip340PubKeyX);
return abi.encodePacked(uint8(0x51), uint8(0x20), tweakedOutputKey);
}
/**
* @notice Build to_spend transaction and return its txid
* @param messageHash The BIP-340 tagged hash of the message
* @param scriptPubKey The scriptPubKey for the output
* @return The transaction ID
*/
function buildToSpendTx(bytes32 messageHash, bytes memory scriptPubKey) internal pure returns (bytes32) {
if (scriptPubKey.length > MAX_SINGLE_BYTE_COMPACT_SIZE) revert ScriptPubKeyTooLong();
// to_spend transaction structure per BIP-322:
// version: 4 bytes (0x00000000)
// input count: 1 byte (0x01)
// input:
// - txid: 32 bytes (0x00...00)
// - vout: 4 bytes (0xffffffff)
// - scriptSig: varint + OP_0 OP_PUSHBYTES_32 <messageHash>
// - sequence: 4 bytes (0x00000000)
// output count: 1 byte (0x01)
// output:
// - value: 8 bytes (0x0000000000000000)
// - scriptPubKey: varint + scriptPubKey
// locktime: 4 bytes (0x00000000)
bytes memory scriptSig = abi.encodePacked(uint8(0x00), uint8(0x20), messageHash);
uint8 scriptSigLen = uint8(scriptSig.length);
// NOTE: All integers must be in little-endian byte order per Bitcoin protocol
bytes memory btcTx = abi.encodePacked(
hex"00000000", // version
uint8(0x01), // input count
bytes32(0), // input txid (all zeros)
hex"ffffffff", // input vout (0xffffffff, LE)
scriptSigLen, // scriptSig length
scriptSig, // scriptSig
hex"00000000", // sequence
uint8(0x01), // output count
hex"0000000000000000", // output value
uint8(scriptPubKey.length), // scriptPubKey length
scriptPubKey, // scriptPubKey
hex"00000000" // locktime
);
// Return double SHA-256 (Bitcoin txid)
return sha256(abi.encodePacked(sha256(btcTx)));
}
/**
* @notice Calculate BIP-341 Taproot sighash for BIP-322 context
* @dev This function is specifically designed for BIP-322 signature verification
* @dev It makes BIP-322-specific assumptions about transaction structure (e.g., sequence = 0, OP_RETURN output)
* @dev This is NOT a generic BIP-341 sighash implementation - use only for BIP-322 verification
* @dev with support for SIGHASH_DEFAULT (0x00) and SIGHASH_ALL (0x01) for wallet compatibility
* @param toSpendTxid The txid being spent
* @param scriptPubKey The scriptPubKey being spent
* @param hashType The sighash type (0x00 for SIGHASH_DEFAULT, 0x01 for SIGHASH_ALL)
* @return The sighash
*/
function calculateTaprootSigHash(bytes32 toSpendTxid, bytes memory scriptPubKey, uint8 hashType)
internal
pure
returns (bytes32)
{
// BIP-341 signature message format (SIGHASH_ALL or SIGHASH_DEFAULT):
// epoch (1) + hash_type (1) + version (4) + locktime (4) +
// sha_prevouts (32) + sha_amounts (32) + sha_scriptpubkeys (32) + sha_sequences (32) + sha_outputs (32) +
// spend_type (1) + input_index (4)
//
// NOTE: SIGHASH_ALL (0x01) and SIGHASH_DEFAULT (0x00) commit to ALL prevouts
// NOTE: For BIP-322, we support both SIGHASH_DEFAULT (0x00) and SIGHASH_ALL (0x01)
// NOTE: BIP-341 requires compact size prefixes for scriptPubKey serialization in sha_scriptpubkeys
// NOTE: BIP-322 toSign transaction uses sequence 0
// Validate sighash type: only SIGHASH_DEFAULT (0x00) and SIGHASH_ALL (0x01) are supported
require(hashType == 0x00 || hashType == 0x01, "Invalid sighash type");
if (scriptPubKey.length > MAX_SINGLE_BYTE_COMPACT_SIZE) revert ScriptPubKeyTooLong();
bytes memory sigMsg = abi.encodePacked(
uint8(0x00), // epoch
hashType, // hash_type (SIGHASH_DEFAULT = 0x00 or SIGHASH_ALL = 0x01)
hex"00000000", // nVersion
hex"00000000", // nLockTime
sha256(abi.encodePacked(toSpendTxid, hex"00000000")), // sha_prevouts
sha256(abi.encodePacked(hex"0000000000000000")), // sha_amounts
sha256(abi.encodePacked(uint8(scriptPubKey.length), scriptPubKey)), // sha_scriptpubkeys (with compact size)
sha256(abi.encodePacked(hex"00000000")), // sha_sequences (sequence is 0)
sha256(abi.encodePacked(hex"0000000000000000", uint8(1), uint8(0x6a))), // sha_outputs (value || OP_RETURN)
uint8(0x00), // spend_type (key-path, no annex)
hex"00000000" // input_index (always 0)
);
// Return tagged hash "TapSighash"
bytes32 tagHash = sha256(abi.encodePacked("TapSighash"));
return sha256(abi.encodePacked(tagHash, tagHash, sigMsg));
}
/**
* @notice Calculate BIP-143 SegWit v0 sighash for P2WPKH in BIP-322 context
* @dev This function is specifically designed for BIP-322 signature verification
* @dev It makes BIP-322-specific assumptions about transaction structure (e.g., sequence = 0, OP_RETURN output)
* @dev This is NOT a generic BIP-143 sighash implementation - use only for BIP-322 verification
* @param toSpendTxid The txid being spent
* @param scriptPubKey The scriptPubKey being spent (P2WPKH witness program: OP_0 <20-byte-hash>)
* @return The sighash
*/
function calculateSegwitSigHash(bytes32 toSpendTxid, bytes memory scriptPubKey) internal pure returns (bytes32) {
// BIP-143 sighash for witness v0 (P2WPKH)
// https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki
//
// IMPORTANT: For P2WPKH, the scriptCode is not the witness program itself,
// but a P2PKH-style script: OP_DUP OP_HASH160 <20-byte-hash> OP_EQUALVERIFY OP_CHECKSIG
// Extract the 20-byte hash from scriptPubKey (skip OP_0 and length byte)
// scriptPubKey format: [OP_0 (0x00)] [0x14] [20-byte-hash]
require(scriptPubKey.length == 22, "Invalid P2WPKH scriptPubKey length");
require(uint8(scriptPubKey[0]) == 0x00 && uint8(scriptPubKey[1]) == 0x14, "Invalid P2WPKH scriptPubKey format");
bytes20 pubKeyHash;
assembly {
pubKeyHash := mload(add(scriptPubKey, 34)) // 32 (length prefix) + 2 (OP_0 + 0x14)
}
// Build P2PKH-style scriptCode: OP_DUP OP_HASH160 <20-byte-hash> OP_EQUALVERIFY OP_CHECKSIG
bytes memory scriptCode = abi.encodePacked(
uint8(0x76), // OP_DUP
uint8(0xa9), // OP_HASH160
uint8(0x14), // Push 20 bytes
pubKeyHash,
uint8(0x88), // OP_EQUALVERIFY
uint8(0xac) // OP_CHECKSIG
);
// Build BIP-143 sighash in parts to avoid stack too deep
// NOTE: BIP-143 uses double SHA256 for hashPrevouts, hashSequence, and hashOutputs
// NOTE: All integers must be in little-endian byte order per Bitcoin protocol
bytes32 hashPrevouts = sha256(
abi.encodePacked(
sha256(
abi.encodePacked(
toSpendTxid,
hex"00000000" // outpoint index
)
)
)
);
bytes32 hashSequence = sha256(
abi.encodePacked(
sha256(
abi.encodePacked(
hex"00000000" // sequence
)
)
)
);
bytes32 hashOutputs = sha256(
abi.encodePacked(
sha256(
abi.encodePacked(
hex"0000000000000000", // value
uint8(1), // scriptPubKey length
uint8(0x6a) // OP_RETURN
)
)
)
);
bytes memory part1 = abi.encodePacked(
hex"00000000", // nVersion
hashPrevouts, // hashPrevouts (double SHA256)
hashSequence, // hashSequence (double SHA256)
toSpendTxid, // outpoint hash
hex"00000000", // outpoint index
uint8(scriptCode.length), // scriptCode length
scriptCode // scriptCode (P2PKH format)
);
bytes memory part2 = abi.encodePacked(
hex"0000000000000000", // value
hex"00000000", // nSequence
hashOutputs, // hashOutputs (double SHA256)
hex"00000000", // nLockTime
hex"01000000" // sighash type (SIGHASH_ALL = 1, LE)
);
bytes memory sigMsg = abi.encodePacked(part1, part2);
return sha256(abi.encodePacked(sha256(sigMsg)));
}
/**
* @notice Calculate BIP-322 sighash for P2TR address
* @param message The message being signed
* @param bip340PubKeyX The x-only public key
* @param hashType The sighash type (0x00 for SIGHASH_DEFAULT, 0x01 for SIGHASH_ALL)
* @return The sighash to verify
*/
function calculateBIP322SigHashP2TR(bytes memory message, bytes32 bip340PubKeyX, uint8 hashType)
internal
pure
returns (bytes32)
{
// Get the BIP-340 tagged hash of the message
bytes32 messageHash = getBIP340TaggedHash(message);
// Build the scriptPubKey from the public key
bytes memory scriptPubKey = pubKeyToP2TRScriptPubKey(bip340PubKeyX);
// Build to_spend transaction
bytes32 toSpendTxid = buildToSpendTx(messageHash, scriptPubKey);
// Calculate BIP-341 sighash for the to_sign transaction
return calculateTaprootSigHash(toSpendTxid, scriptPubKey, hashType);
}
/**
* @notice Calculate BIP-322 sighash for P2WPKH address using compressed public key
* @param message The message being signed
* @param compressedPubKey The 33-byte compressed public key from witness
* @return The sighash to verify
*/
function calculateBIP322SigHashP2WPKH(bytes memory message, bytes memory compressedPubKey)
internal
pure
returns (bytes32)
{
require(compressedPubKey.length == 33, "Invalid compressed public key length");
// Get the BIP-340 tagged hash of the message
bytes32 messageHash = getBIP340TaggedHash(message);
// Build the scriptPubKey from the compressed public key
// P2WPKH: OP_0 OP_PUSHBYTES_20 <HASH160(pubkey)>
bytes32 sha = sha256(compressedPubKey);
bytes20 hash160 = ripemd160(abi.encodePacked(sha));
bytes memory scriptPubKey = abi.encodePacked(uint8(0x00), uint8(0x14), hash160);
// Build to_spend transaction
bytes32 toSpendTxid = buildToSpendTx(messageHash, scriptPubKey);
// Calculate BIP-143 sighash for the to_sign transaction
return calculateSegwitSigHash(toSpendTxid, scriptPubKey);
}
}
lib/vault-contracts/src/protocol/lib/helpers/BIP340Utils.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {EllipticCurve} from "../../../../lib/elliptic-curve-solidity/contracts/EllipticCurve.sol";
import {Secp256k1} from "./Secp256k1.sol";
/**
* @title BIP340Utils
* @notice Library for BIP-340 Schnorr signature verification on secp256k1
* @dev Uses an ecrecover optimization technique for efficient verification
*/
// Based on https://hackmd.io/@nZ-twauPRISEa6G9zg3XRw/SyjJzSLt9
library BIP340Utils {
/**
* @notice Verify a BIP-340 Schnorr signature
* @dev Uses the ecrecover hack to verify a schnorr signature more efficiently
* @param px The x-coordinate of the public key
* @param rx The x-coordinate of the R point in the signature
* @param s The s value of the signature
* @param m The message hash
* @return True if the signature is valid
*/
function verify(uint256 px, uint256 rx, uint256 s, bytes32 m) public pure returns (bool) {
// Check pubkey, rx, and s are in-range.
if (px >= Secp256k1.P || rx >= Secp256k1.P || s >= Secp256k1.N) {
return false;
}
(address exp, bool ok) = convToFakeAddr(rx);
if (!ok) {
return false;
}
uint256 e = computeChallenge(bytes32(rx), bytes32(px), m);
bytes32 sp = bytes32(Secp256k1.N - mulmod(s, px, Secp256k1.N));
bytes32 ep = bytes32(Secp256k1.N - mulmod(e, px, Secp256k1.N));
// 27 apparently used to signal even parity (which it will always have).
address rvh = ecrecover(sp, 27, bytes32(px), ep);
return rvh == exp; // if recovery fails we fail anyways
}
/**
* @notice Compute BIP-340 challenge value
* @dev Computes e = int(hashBIP0340/challenge(bytes(r) || bytes(P) || m)) mod n
* @param rx The x-coordinate of the R point as bytes32
* @param px The x-coordinate of the public key as bytes32
* @param m The message hash
* @return The challenge value modulo curve order
*/
function computeChallenge(bytes32 rx, bytes32 px, bytes32 m) internal pure returns (uint256) {
// Precomputed `sha256("BIP0340/challenge")`.
//
// Saves ~10k gas, mostly from byte shuffling to prepare the call.
//bytes32 tag = sha256("BIP0340/challenge");
bytes32 tag = 0x7bb52d7a9fef58323eb1bf7a407db382d2f3f2d81bb1224f49fe518f6d48d37c;
// Let e = int(hashBIP0340/challenge(bytes(r) || bytes(P) || m)) mod n.
return uint256(sha256(abi.encodePacked(tag, tag, rx, px, m))) % Secp256k1.N;
}
/**
* @notice Lift x-coordinate to full point on secp256k1 curve
* @dev Given an x coordinate, returns the y coordinate of an even point on the secp256k1 curve
* @param _x The x-coordinate to lift
* @return y The y-coordinate of the even point
* @return success True if the operation was successful
*/
function liftX(uint256 _x) internal pure returns (uint256, bool) {
uint256 _pp = Secp256k1.P;
uint256 _aa = Secp256k1.A;
uint256 _bb = Secp256k1.B;
if (_x >= _pp) {
return (0, false);
}
// Use EllipticCurve library to derive y-coordinate (0x02 for even y)
uint256 y = EllipticCurve.deriveY(0x02, _x, _aa, _bb, _pp);
if (!EllipticCurve.isOnCurve(_x, y, _aa, _bb, _pp)) {
return (0, false);
}
return (y, true);
}
/**
* @notice Convert Jacobian x-coordinate to affine coordinates
* @dev Internal function for doing the affine conversion for only the x coordinate
* @param _x The x-coordinate in Jacobian form
* @param _z The z-coordinate in Jacobian form
* @param _pp The prime modulus
* @return The x-coordinate in affine form
*/
function xToAffine(uint256 _x, uint256 _z, uint256 _pp) internal pure returns (uint256) {
uint256 zInv = EllipticCurve.invMod(_z, _pp);
uint256 zInv2 = mulmod(zInv, zInv, _pp);
return mulmod(_x, zInv2, _pp);
}
/**
* @notice Convert BIP-340 public key x-coordinate to Ethereum address format
* @dev Converts a BIP340 pubkey X coord to what it would look like as an Ethereum address
* @param px The x-coordinate of the BIP-340 public key
* @return addr The pseudo-Ethereum address
* @return success True if the conversion was successful
*/
function convToFakeAddr(uint256 px) internal pure returns (address, bool) {
(uint256 py, bool ok) = liftX(px);
if (!ok) {
return (address(0), false);
}
bytes32 h = keccak256(abi.encodePacked(bytes32(px), bytes32(py)));
return (address(uint160(uint256(h))), true);
}
}
lib/vault-contracts/src/protocol/lib/helpers/CompactSize.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;
/**
* @title CompactSize
* @notice Bitcoin CompactSize integer encoding/decoding utilities
* @dev Implements Bitcoin's variable-length integer format used in transaction serialization
* @dev Reference: https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
*/
library CompactSize {
error InvalidCompactSize(uint256 offset, uint8 prefix, uint64 value, uint64 minValue);
error BufferTooShort(uint256 offset, uint256 requiredLength, uint256 availableLength);
// ============ Encoding Functions ============
/**
* @notice Encode an integer as Bitcoin CompactSize format
* @param value The integer to encode (uint64)
* @return Encoded bytes in CompactSize format
* @dev Format:
* - value < 0xFD: [value] (1 byte)
* - value <= 0xFFFF: [0xFD][value as LE uint16] (3 bytes)
* - value <= 0xFFFFFFFF: [0xFE][value as LE uint32] (5 bytes)
* - value > 0xFFFFFFFF: [0xFF][value as LE uint64] (9 bytes)
*/
function encode(uint64 value) internal pure returns (bytes memory) {
if (value < 0xFD) {
// Single byte
return abi.encodePacked(uint8(value));
} else if (value <= 0xFFFF) {
// 0xFD + 2 bytes (little-endian uint16)
return abi.encodePacked(uint8(0xFD), uint8(value), uint8((value >> 8)));
} else if (value <= 0xFFFFFFFF) {
// 0xFE + 4 bytes (little-endian uint32)
return abi.encodePacked(
uint8(0xFE), uint8(value), uint8((value >> 8)), uint8((value >> 16)), uint8((value >> 24))
);
} else {
// 0xFF + 8 bytes (little-endian uint64)
return abi.encodePacked(
uint8(0xFF),
uint8(value),
uint8((value >> 8)),
uint8((value >> 16)),
uint8((value >> 24)),
uint8((value >> 32)),
uint8((value >> 40)),
uint8((value >> 48)),
uint8((value >> 56))
);
}
}
/**
* @notice Get the encoded length for a given value
* @param value The value to measure
* @return Length in bytes of the CompactSize encoding
*/
function encodedLength(uint64 value) internal pure returns (uint8) {
if (value < 0xFD) return 1;
if (value <= 0xFFFF) return 3;
if (value <= 0xFFFFFFFF) return 5;
return 9;
}
// ============ Decoding Functions ============
/**
* @notice Decode CompactSize integer from bytes
* @param data The bytes to decode from
* @param offset Starting position in the data
* @return value The decoded uint64 value
* @return newOffset Position immediately after the decoded CompactSize
* @dev Reverts if data is malformed or insufficient
*/
function decode(bytes memory data, uint256 offset) internal pure returns (uint64 value, uint256 newOffset) {
if (offset >= data.length) revert BufferTooShort(offset, offset + 1, data.length);
uint8 firstByte = uint8(data[offset]);
if (firstByte < 0xFD) {
// Single byte value
return (uint64(firstByte), offset + 1);
} else if (firstByte == 0xFD) {
// 2-byte value (uint16)
if (offset + 3 > data.length) revert BufferTooShort(offset, offset + 3, data.length);
value = readUint16LE(data, offset + 1);
if (value < 0xFD) revert InvalidCompactSize(offset, firstByte, value, 0xFD); // Non-canonical encoding
return (value, offset + 3);
} else if (firstByte == 0xFE) {
// 4-byte value (uint32)
if (offset + 5 > data.length) revert BufferTooShort(offset, offset + 5, data.length);
value = readUint32LE(data, offset + 1);
if (value <= 0xFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x10000); // Non-canonical encoding
return (value, offset + 5);
} else {
// 8-byte value (uint64)
if (offset + 9 > data.length) revert BufferTooShort(offset, offset + 9, data.length);
value = readUint64LE(data, offset + 1);
if (value <= 0xFFFFFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x100000000); // Non-canonical encoding
return (value, offset + 9);
}
}
/**
* @notice Decode CompactSize from calldata
* @param data The calldata to decode from
* @param offset Starting position
* @return value The decoded uint64 value
* @return newOffset Position immediately after the decoded CompactSize
*/
function decodeCalldata(bytes calldata data, uint256 offset)
internal
pure
returns (uint64 value, uint256 newOffset)
{
if (offset >= data.length) {
revert BufferTooShort(offset, offset + 1, data.length);
}
uint8 firstByte = uint8(data[offset]);
if (firstByte < 0xFD) {
return (uint64(firstByte), offset + 1);
} else if (firstByte == 0xFD) {
if (offset + 3 > data.length) revert BufferTooShort(offset, offset + 3, data.length);
value = readUint16LECalldata(data, offset + 1);
if (value < 0xFD) revert InvalidCompactSize(offset, firstByte, value, 0xFD);
return (value, offset + 3);
} else if (firstByte == 0xFE) {
if (offset + 5 > data.length) revert BufferTooShort(offset, offset + 5, data.length);
value = readUint32LECalldata(data, offset + 1);
if (value <= 0xFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x10000);
return (value, offset + 5);
} else {
if (offset + 9 > data.length) revert BufferTooShort(offset, offset + 9, data.length);
value = readUint64LECalldata(data, offset + 1);
if (value <= 0xFFFFFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x100000000);
return (value, offset + 9);
}
}
// ============ Little-Endian Reading Helpers ============
/**
* @notice Read little-endian uint16 from bytes
*/
function readUint16LE(bytes memory data, uint256 offset) internal pure returns (uint64) {
return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8);
}
/**
* @notice Read little-endian uint32 from bytes
*/
function readUint32LE(bytes memory data, uint256 offset) internal pure returns (uint64) {
return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
| (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24);
}
/**
* @notice Read little-endian uint64 from bytes
*/
function readUint64LE(bytes memory data, uint256 offset) internal pure returns (uint64) {
return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
| (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24)
| (uint64(uint8(data[offset + 4])) << 32) | (uint64(uint8(data[offset + 5])) << 40)
| (uint64(uint8(data[offset + 6])) << 48) | (uint64(uint8(data[offset + 7])) << 56);
}
/**
* @notice Read little-endian uint16 from calldata
*/
function readUint16LECalldata(bytes calldata data, uint256 offset) internal pure returns (uint64) {
return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8);
}
/**
* @notice Read little-endian uint32 from calldata
*/
function readUint32LECalldata(bytes calldata data, uint256 offset) internal pure returns (uint64) {
return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
| (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24);
}
/**
* @notice Read little-endian uint64 from calldata
*/
function readUint64LECalldata(bytes calldata data, uint256 offset) internal pure returns (uint64) {
return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
| (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24)
| (uint64(uint8(data[offset + 4])) << 32) | (uint64(uint8(data[offset + 5])) << 40)
| (uint64(uint8(data[offset + 6])) << 48) | (uint64(uint8(data[offset + 7])) << 56);
}
}
lib/vault-contracts/src/protocol/lib/helpers/Secp256k1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {EllipticCurve} from "../../../../lib/elliptic-curve-solidity/contracts/EllipticCurve.sol";
/**
* @title Secp256k1 public key recovery Library
* @dev Library providing arithmetic operations to recover the signer public key EC point from secp256k1 signed messages in Solidity
*/
library Secp256k1 {
// Curve Constants (secp256k1)
uint256 internal constant A = 0;
uint256 internal constant B = 7;
uint256 internal constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint256 internal constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
uint256 internal constant P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 internal constant N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
/// @notice secp256k1 curve order divided by 2 (for BIP-62 compliance)
bytes32 internal constant N_DIV_2 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0;
/// @dev recovers signer public key point value.
/// @param digest hashed message
/// @param v recovery id (0 or 1)
/// @param r first 32 bytes of signature
/// @param s last 32 bytes of signature
/// @return (x, y) EC point coordinates of the recovered public key
function recover(uint256 digest, uint8 v, uint256 r, uint256 s) internal pure returns (uint256, uint256) {
// Validate scalar ranges and recovery id up front. We restrict v to
// {0, 1}, which means the standard ECDSA x = r + (v >> 1) * N (mod P)
// collapses to x = r. Since N < P and r >= N is rejected, r already
// satisfies r < P, so no further reduction is required.
if (r == 0 || r >= N || s == 0 || s >= N || v > 1) {
return (0, 0);
}
uint256 x = r;
uint256 rInv = EllipticCurve.invMod(r, N);
// v encodes the parity of y directly: 0 -> 0x02 (even), 1 -> 0x03 (odd).
uint256 y = EllipticCurve.deriveY(uint8(0x02 + v), x, A, B, P);
// deriveY returns a value for any x via the (p+1)/4 shortcut, even when
// x lives on the twist rather than secp256k1. Reject off-curve points so
// downstream arithmetic only operates on secp256k1 group elements.
if (!EllipticCurve.isOnCurve(x, y, A, B, P)) {
return (0, 0);
}
// Q = rInv * (s * R - digest * G)
// Compute s * R
(uint256 qx, uint256 qy, uint256 qz) = EllipticCurve.jacMul(mulmod(rInv, s, N), x, y, 1, A, P);
// Compute -digest * G
uint256 digestModN = digest % N;
(uint256 qx2, uint256 qy2, uint256 qz2) = EllipticCurve.jacMul(mulmod(rInv, N - digestModN, N), GX, GY, 1, A, P);
// Add the two points
(uint256 qx3, uint256 qy3, uint256 qz3) = EllipticCurve.jacAdd(qx, qy, qz, qx2, qy2, qz2, P);
return EllipticCurve.toAffine(qx3, qy3, qz3, P);
}
/**
* @notice Validate that a signature S value is normalized (BIP-62)
* @param s The s value from the signature
* @return True if s is in the lower half of the curve order
*/
function isNormalizedSignature(bytes32 s) internal pure returns (bool) {
return uint256(s) <= uint256(N_DIV_2);
}
}
lib/vault-contracts/src/protocol/lib/taproot/BIP341.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;
import {EllipticCurve} from "../../../../lib/elliptic-curve-solidity/contracts/EllipticCurve.sol";
import {TaprootConstants} from "./TaprootConstants.sol";
import {CompactSize} from "../helpers/CompactSize.sol";
/**
* @title BIP341
* @notice BIP341 Taproot cryptographic primitives
* @dev Implements tagged hashing, x-only public key operations, and Taproot output key computation
* @dev Reference: https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki
*/
library BIP341 {
error InvalidPoint(uint256 x, uint256 y);
error InvalidXOnlyKey(bytes32 xOnly);
error InvalidControlBlock(uint256 length, uint256 remainder);
error InvalidBase(uint256 base, uint256 modulus);
/// @dev Control-block byte 0 packs the leaf version in the high 7 bits and
/// the output-key y-parity in the low bit.
uint8 internal constant PARITY_MASK = 0x01;
uint8 internal constant LEAF_VERSION_MASK = 0xfe;
// ============ Tagged Hash Functions ============
/**
* @notice Compute BIP340-style tagged hash: SHA256(SHA256(tag) || SHA256(tag) || data)
* @param tag The domain separation tag as raw UTF-8 bytes (not padded)
* @param data The data to hash
* @return The 32-byte tagged hash
* @dev This prevents collision between different hash contexts
* @dev Reference: BIP-340 tagged hashes use raw tag bytes, not padded to 32 bytes
*/
function taggedHash(bytes memory tag, bytes memory data) internal pure returns (bytes32) {
bytes32 tagHash = sha256(tag);
return sha256(abi.encodePacked(tagHash, tagHash, data));
}
/**
* @notice Compute TapTweak tagged hash for Taproot output key computation
* @param internalPubKey The 32-byte x-only internal public key
* @param merkleRoot The merkle root of the TapTree (empty bytes for key-path only, 32 bytes for script-path)
* @return The tagged hash used for tweaking
* @dev Per BIP-341: For key-path only (no scripts), pass empty bytes. For script-path, pass 32-byte merkle root.
*/
function tapTweakHash(bytes32 internalPubKey, bytes memory merkleRoot) internal pure returns (bytes32) {
return taggedHash(TaprootConstants.TAG_TAPTWEAK, abi.encodePacked(internalPubKey, merkleRoot));
}
/**
* @notice Compute TapLeaf tagged hash for a script leaf
* @param leafVersion The leaf version byte (0xC0 for Tapscript v0)
* @param script The script bytes
* @return The leaf hash
* @dev Format: TapLeaf || leaf_version || compact_size(script_len) || script
*/
function tapLeafHash(uint8 leafVersion, bytes memory script) internal pure returns (bytes32) {
// Encode script length using Bitcoin's CompactSize format (little-endian)
bytes memory scriptLength = CompactSize.encode(uint64(script.length));
return taggedHash(TaprootConstants.TAG_TAPLEAF, abi.encodePacked(leafVersion, scriptLength, script));
}
/**
* @notice Compute TapBranch tagged hash for merkle tree internal node
* @param left Left child hash
* @param right Right child hash
* @return The branch hash with lexicographic sorting applied
* @dev Hashes are sorted to ensure deterministic tree construction
*/
function tapBranchHash(bytes32 left, bytes32 right) internal pure returns (bytes32) {
// Lexicographic ordering: compare as big-endian integers
if (uint256(left) < uint256(right)) {
return taggedHash(TaprootConstants.TAG_TAPBRANCH, abi.encodePacked(left, right));
} else {
return taggedHash(TaprootConstants.TAG_TAPBRANCH, abi.encodePacked(right, left));
}
}
// ============ X-Only Public Key Operations ============
/**
* @notice Lift x-only public key to full (x, y) curve point
* @param xOnly The 32-byte x-coordinate
* @return x The x-coordinate (same as input)
* @return y The y-coordinate (even parity, i.e., y mod 2 == 0)
* @dev Uses secp256k1 curve equation: y^2 = x^3 + b (b = TaprootConstants.BB)
* @dev Always returns the even y-coordinate per BIP340 convention
*/
function liftX(bytes32 xOnly) internal pure returns (uint256 x, uint256 y) {
x = uint256(xOnly);
// Derive y from x using EllipticCurve library (0x02 = even parity per BIP340)
y = EllipticCurve.deriveY(
0x02, // even parity prefix
x,
TaprootConstants.AA,
TaprootConstants.BB,
TaprootConstants.PP
);
// Verify point is on curve
if (!EllipticCurve.isOnCurve(x, y, TaprootConstants.AA, TaprootConstants.BB, TaprootConstants.PP)) {
revert InvalidXOnlyKey(xOnly);
}
return (x, y);
}
/**
* @notice Check if a point's y-coordinate is even (quadratic residue)
* @param y The y-coordinate
* @return True if y is even (y mod 2 == 0)
*/
function hasEvenY(uint256 y) internal pure returns (bool) {
return (y & 1) == 0;
}
/**
* @notice Validate if an x-only public key represents a valid secp256k1 curve point
* @param xOnly The 32-byte x-coordinate to validate
* @return True if the x-coordinate has a corresponding valid y-coordinate on the curve
* @dev This ensures the key can be lifted to a full curve point without reverting
* @dev Uses inline computation to check if y^2 = x^3 + b (b = TaprootConstants.BB) has a valid square root
*/
function isValidXOnlyKey(bytes32 xOnly) internal pure returns (bool) {
uint256 x = uint256(xOnly);
uint256 pp = TaprootConstants.PP;
// x must be a canonical secp256k1 field element that lifts to a curve point
if (x == 0 || x >= pp) return false;
// Compute y^2 = x^3 + b (mod p), b = TaprootConstants.BB
uint256 y2 = addmod(
mulmod(x, mulmod(x, x, pp), pp),
TaprootConstants.BB, // secp256k1 curve parameter b
pp
);
// Check if y2 is a quadratic residue (has a square root) using Euler's criterion
// For prime p, y2 is a QR iff y2^((p-1)/2) ≡ 1 (mod p)
// For secp256k1, (p-1)/2 can be computed
uint256 euler = expPod(y2, TaprootConstants.PP_S1D2, pp);
// If Euler's criterion returns 1, then y2 has a square root
return euler == 1;
}
/**
* @notice Modular exponentiation helper
* @param base The base
* @param exponent The exponent
* @param modulus The modulus
* @return result base^exponent mod modulus
*/
function expPod(uint256 base, uint256 exponent, uint256 modulus) internal pure returns (uint256 result) {
if (base >= modulus) revert InvalidBase(base, modulus);
result = 1;
while (exponent > 0) {
if (exponent % 2 == 1) {
result = mulmod(result, base, modulus);
}
exponent = exponent >> 1;
base = mulmod(base, base, modulus);
}
}
/**
* @notice Extract x-only public key from point
* @param x The x-coordinate
* @param y The y-coordinate
* @return The 32-byte x-only public key
*/
function toXOnly(uint256 x, uint256 y) internal pure returns (bytes32) {
// Unused y parameter - included for API clarity
y; // silence compiler warning
return bytes32(x);
}
// ============ Taproot Output Key Computation ============
/**
* @notice Compute Taproot output key P from internal key Q and merkle root
* @param internalPubKey The 32-byte x-only internal public key Q
* @param merkleRoot The merkle root h (empty bytes for key-path only, 32 bytes for script-path)
* @return outputKey The 32-byte x-only output public key P
* @return outputKeyYIsOdd True if the output key's y-coordinate is odd
* @dev Formula: P = Q + int(hash_TapTweak(Q || h)) * G
* @dev Reference: BIP341 "Constructing and spending Taproot outputs"
* @dev Per BIP-341: For key-path only (no scripts), pass empty bytes. For script-path, pass 32-byte merkle root.
*/
function computeOutputKey(bytes32 internalPubKey, bytes memory merkleRoot)
internal
pure
returns (bytes32 outputKey, bool outputKeyYIsOdd)
{
// 1. Lift internal key Q to curve point
(uint256 qx, uint256 qy) = liftX(internalPubKey);
// 2. Compute tweak t = int(hash_TapTweak(Q || h)) mod n
// Note: Following btcd implementation which automatically
// performs modulo N reduction rather than failing on overflow.
bytes32 tweakHash = tapTweakHash(internalPubKey, merkleRoot);
uint256 t = uint256(tweakHash) % TaprootConstants.NN;
// 3. Compute t*G (scalar multiplication of generator by tweak)
(uint256 tGx, uint256 tGy) =
EllipticCurve.ecMul(t, TaprootConstants.GX, TaprootConstants.GY, TaprootConstants.AA, TaprootConstants.PP);
// 4. Compute P = Q + t*G (point addition)
(uint256 px, uint256 py) = EllipticCurve.ecAdd(qx, qy, tGx, tGy, TaprootConstants.AA, TaprootConstants.PP);
// Verify result is valid point
if (px == 0 && py == 0) {
revert InvalidPoint(px, py);
}
// 5. Return x-only representation of P and its y-coordinate parity
return (toXOnly(px, py), !hasEvenY(py));
}
/**
* @notice Verify a Taproot output key matches expected internal key and merkle root
* @param outputKey The claimed x-only output key
* @param internalPubKey The internal public key
* @param merkleRoot The merkle root (empty bytes for key-path only, 32 bytes for script-path)
* @return True if outputKey == computeOutputKey(internalPubKey, merkleRoot)
*/
function verifyOutputKey(bytes32 outputKey, bytes32 internalPubKey, bytes memory merkleRoot)
internal
pure
returns (bool)
{
(bytes32 computed,) = computeOutputKey(internalPubKey, merkleRoot);
return outputKey == computed;
}
// ============ Taproot Leaf Commitment Verification ============
/**
* @notice Verify that a script is committed in a Taproot output via control block
* @param controlBlock The control block containing: leafVersion, parity, internalKey, merkleProof
* @param witnessProgram The 32-byte output key from the scriptPubKey (P)
* @param script The script to verify
* @return True if script is committed in the Taproot output
* @dev This is the core Taproot verification matching Bitcoin's txscript.VerifyTaprootLeafCommitment
* @dev Control block format: [leafVersion + parity (1 byte)] [internalKey (32 bytes)] [merkleProof (0 or more 32-byte hashes)]
* @dev Reference: https://github.com/btcsuite/btcd/blob/v0.24.2/txscript/taproot.go#L363
*/
function verifyTaprootLeafCommitment(bytes memory controlBlock, bytes32 witnessProgram, bytes memory script)
internal
pure
returns (bool)
{
// 1. Parse control block
if (controlBlock.length < 33) revert InvalidControlBlock(controlBlock.length, controlBlock.length);
if ((controlBlock.length - 33) % 32 != 0) {
revert InvalidControlBlock(controlBlock.length, (controlBlock.length - 33) % 32);
}
uint8 leafVersionAndParity = uint8(controlBlock[0]);
uint8 leafVersion = leafVersionAndParity & LEAF_VERSION_MASK; // Mask out parity bit
uint8 outputKeyParity = leafVersionAndParity & PARITY_MASK;
bytes32 internalKey;
assembly {
internalKey := mload(add(controlBlock, 33)) // Skip length (32) + first byte (1)
}
// 2. Compute leaf hash
bytes32 leafHash = tapLeafHash(leafVersion, script);
// 3. Compute merkle root by processing the merkle proof
bytes32 merkleRoot = leafHash;
uint256 proofLength = (controlBlock.length - 33) >> 5;
for (uint256 i = 0; i < proofLength; i++) {
bytes32 proofElement;
assembly {
// Read proof element at offset: 32 (length) + 1 (version/parity) + 32 (internalKey) + i*32
proofElement := mload(add(controlBlock, add(65, mul(i, 32))))
}
merkleRoot = tapBranchHash(merkleRoot, proofElement);
}
// 4. Compute expected output key P = Q + hash(Q || merkleRoot) * G
(bytes32 expectedOutputKey, bool computedYIsOdd) = computeOutputKey(internalKey, abi.encodePacked(merkleRoot));
// 5. Verify witness program matches expected output key (x-coordinate)
if (witnessProgram != expectedOutputKey) {
return false;
}
// 6. Verify the parity of the y-coordinate matches the control block
// Per BIP341 and Bitcoin consensus rules
bool expectedYIsOdd = (outputKeyParity == 1);
if (computedYIsOdd != expectedYIsOdd) {
return false;
}
return true;
}
/**
* @notice Parse control block into components
* @param controlBlock The control block bytes
* @return leafVersion The leaf version (0xC0 for Tapscript v0)
* @return outputKeyParity The parity bit of the output key
* @return internalKey The 32-byte internal public key
* @return merkleProof Array of 32-byte merkle proof hashes
*/
function parseControlBlock(bytes memory controlBlock)
internal
pure
returns (uint8 leafVersion, uint8 outputKeyParity, bytes32 internalKey, bytes32[] memory merkleProof)
{
if (controlBlock.length < 33) revert InvalidControlBlock(controlBlock.length, controlBlock.length);
if ((controlBlock.length - 33) % 32 != 0) {
revert InvalidControlBlock(controlBlock.length, (controlBlock.length - 33) % 32);
}
uint8 leafVersionAndParity = uint8(controlBlock[0]);
leafVersion = leafVersionAndParity & LEAF_VERSION_MASK;
outputKeyParity = leafVersionAndParity & PARITY_MASK;
assembly {
internalKey := mload(add(controlBlock, 33))
}
uint256 proofLength = (controlBlock.length - 33) >> 5;
merkleProof = new bytes32[](proofLength);
for (uint256 i = 0; i < proofLength; i++) {
assembly {
let proofElement := mload(add(controlBlock, add(65, mul(i, 32))))
mstore(add(add(merkleProof, 32), mul(i, 32)), proofElement)
}
}
return (leafVersion, outputKeyParity, internalKey, merkleProof);
}
/**
* @notice Build control block from components
* @param leafVersion The leaf version (0xC0 for Tapscript v0)
* @param outputKeyParity The parity bit (0 or 1)
* @param internalKey The internal public key
* @param merkleProof Array of merkle proof hashes
* @return The encoded control block
*/
function buildControlBlock(
uint8 leafVersion,
uint8 outputKeyParity,
bytes32 internalKey,
bytes32[] memory merkleProof
) internal pure returns (bytes memory) {
uint8 leafVersionAndParity = leafVersion | (outputKeyParity & PARITY_MASK);
bytes memory controlBlock = abi.encodePacked(leafVersionAndParity, internalKey);
for (uint256 i = 0; i < merkleProof.length; i++) {
controlBlock = abi.encodePacked(controlBlock, merkleProof[i]);
}
return controlBlock;
}
}
lib/vault-contracts/src/protocol/lib/taproot/TaprootConstants.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;
/**
* @title TaprootConstants
* @notice Constants for BIP341 Taproot verification
* @dev Provides internal key Q, curve parameters, and BIP340 tagged hash tags
*/
library TaprootConstants {
// ============ Internal Key Q ============
// The x-only internal public key (32 bytes) used for all vaults
// BIP341 recommends using a nothing-up-my-sleeve (NUMS) point to disable keypath spending
// This is the recommended unspendable key from BIP341:
// lift_x(0x50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0)
bytes32 constant INTERNAL_KEY_Q = 0x50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0;
// ============ Secp256k1 Curve Parameters ============
// Generator point coordinates
uint256 constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint256 constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
// Curve equation: y^2 = x^3 + ax + b
uint256 constant AA = 0; // a coefficient
uint256 constant BB = 7; // b coefficient
// Prime field modulus
uint256 constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 constant PP_S1D2 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFE17;
// Curve order (for scalar operations)
uint256 constant NN = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
// ============ BIP340/341/342 Tagged Hash Tags ============
// BIP340 tag for Taproot tweaking (raw UTF-8 bytes, not padded)
bytes constant TAG_TAPTWEAK = bytes("TapTweak");
// BIP341 tag for leaf hashing (raw UTF-8 bytes, not padded)
bytes constant TAG_TAPLEAF = bytes("TapLeaf");
// BIP341 tag for branch hashing (raw UTF-8 bytes, not padded)
bytes constant TAG_TAPBRANCH = bytes("TapBranch");
// BIP340 tag for signature challenges (for future use)
bytes constant TAG_TAPBIP0340CHALLENGE = bytes("BIP0340/challenge");
// ============ Tapscript Constants ============
// Leaf version for Tapscript v0 (BIP342)
uint8 constant TAPSCRIPT_LEAF_VERSION = 0xC0;
// Taproot witness version
uint8 constant TAPROOT_WITNESS_VERSION = 0x01;
// Taproot output key size (x-only pubkey)
uint8 constant TAPROOT_PUBKEY_SIZE = 32;
}
Compiler settingsShow
{
"viaIR": true,
"libraries": {
"lib/vault-contracts/src/protocol/lib/BTCProofOfPossession.sol": {
"BIP340Utils": "0xb87040ca72a41c52bddf7a3ee203a27212ec67cc"
}
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.