Skip to content
Verified contractPartialMIT

UserActivator

Address0xdc738b2f70e72904f365bd97e694d56b53430aa3
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.27

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.27+commit.40a35a09
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
23,045,877
Creation transaction
0x6cd53d4c13…e06d395d28
Libraries
lib/blockchain-tools/src/BitcoinUtils.sol:BitcoinUtils0x09ca…79b531

src/lib/UserActivator.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.27;

import {Ownable} from "openzeppelin-contracts/contracts/access/Ownable.sol";
import {BTCDepositAddressDeriver} from "blockchain-tools/src/BTCDepositAddressDeriver.sol";
import {BitcoinNetworkEncoder} from "blockchain-tools/src/BitcoinNetworkEncoder.sol";

contract UserActivator is BTCDepositAddressDeriver, Ownable {
    event UserAddressActivated(address userETHAddress);

    // Mapping of activated addresses.
    mapping(address => bool) public activatedAddresses;

    constructor() BTCDepositAddressDeriver() Ownable(msg.sender) {}

    /**
     * @dev Activates a user by setting their address as activated.
     * @param _userAddress The address of the user to be activated.
     * Emits a `UserAddressActivated` event with the user address and their BTC deposit address.
     * Reverts if the user address is already activated.
     */
    function activateUser(address _userAddress) public {
        require(activatedAddresses[_userAddress] == false, "User is already activated");
        require(wasSeedSet, "Seed must be set before activating users");

        activatedAddresses[_userAddress] = true;

        emit UserAddressActivated(_userAddress);
    }

    /**
     * @dev Sets the seed for the BTC deposit address deriver.
     * @param _btcAddr1 The first BTC taproot address.
     * @param _btcAddr2 The second BTC taproot address.
     * @param _network The network of the BTC addresses.
     */
    function setSeed(string calldata _btcAddr1, string calldata _btcAddr2, BitcoinNetworkEncoder.Network _network)
        public
        override
        onlyOwner
    {
        BTCDepositAddressDeriver.setSeed(_btcAddr1, _btcAddr2, _network);
    }

    function getBTCDepositAddress(address ethAddress) public view override returns (string memory) {
        if (!activatedAddresses[ethAddress]) {
            revert("User is not activated");
        }
        return BTCDepositAddressDeriver.getBTCDepositAddress(ethAddress);
    }
}

lib/blockchain-tools/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/blockchain-tools/src/BTCDepositAddressDeriver.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.27;

import {Deriver} from "./Deriver.sol";
import {Bech32m} from "./Bech32m.sol";
import {BitcoinNetworkEncoder} from "./BitcoinNetworkEncoder.sol";

error SeedWasNotSetYet();
error UnsupportedBtcAddress(string btcAddress);
error CannotParseBtcAddress(
    string btcAddress,
    string hrp,
    Bech32m.DecodeError err
);

// Types of Bitcoin Network

contract BTCDepositAddressDeriver {

    event SeedChanged(string btcAddr1, string btcAddr2, string hrp);

    bool public wasSeedSet;

    // Validators' joint pubkeys in format of taproot addresses
    string public btcAddr1;
    string public btcAddr2;

    // Bitcoin address's network prefix
    string public networkHrp;

    // Validators' pubkey both coordinates deconstructed from taproot addresses
    uint256 public p1x;
    uint256 public p1y;
    uint256 public p2x;
    uint256 public p2y;

    constructor() {
        wasSeedSet = false;
    }

    // Set Validators' joint pubkeys and network prefix, must be called after contract deployment
    function setSeed(
        string calldata _btcAddr1,
        string calldata _btcAddr2,
        BitcoinNetworkEncoder.Network _network
    ) public virtual {
        string memory _hrp = BitcoinNetworkEncoder.getNetworkPrefix(_network);

        networkHrp = _hrp;

        (p1x, p1y) = parseBTCTaprootAddress(_hrp, _btcAddr1);
        (p2x, p2y) = parseBTCTaprootAddress(_hrp, _btcAddr2);

        btcAddr1 = _btcAddr1;
        btcAddr2 = _btcAddr2;

        wasSeedSet = true;
        emit SeedChanged(_btcAddr1, _btcAddr2, _hrp);
    }

    // Derive pubkey's (x,y) coordinates from taproot address
    function parseBTCTaprootAddress(
        string memory _hrp,
        string calldata _bitcoinAddress
    ) public pure returns (uint256, uint256) {

        (uint8 witVer, bytes memory witProg, Bech32m.DecodeError err) = Bech32m
            .decodeSegwitAddress(bytes(_hrp), bytes(_bitcoinAddress));

        if (err != Bech32m.DecodeError.NoError) {
            revert CannotParseBtcAddress(_bitcoinAddress, _hrp, err);
        }
        if (witVer != 1 || witProg.length != 32) {
            revert UnsupportedBtcAddress(_bitcoinAddress);
        }

        uint256 x = uint256(bytes32(witProg));

        if (x == 0 || x >= Deriver.PP) {
            revert UnsupportedBtcAddress(_bitcoinAddress);
        }

        uint256 y = Deriver.liftX(x);

        return (x, y);
    }

    // Get users' Bitcoin deposit address from user's Ethereum address
    function getBTCDepositAddress(
        address ethAddr
    ) public virtual view returns (string memory) {

        if (!wasSeedSet) {
            revert SeedWasNotSetYet();
        }

        return
            Deriver.getBtcAddressTaprootNoScriptFromEth(
                p1x,
                p1y,
                p2x,
                p2y,
                bytes(networkHrp),
                ethAddr
            );
    }
}

lib/blockchain-tools/src/Bech32m.sol

// SPDX-License-Identifier: MIT
// https://github.com/gregdhill/bech32-sol/blob/master/src/Bech32.sol
// based on https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki
// https://github.com/sipa/bech32/blob/master/ref/python/segwit_addr.py

pragma solidity 0.8.27;

error EncodingIsUnknown();

library Bech32m {

    enum BechEncoding {
        // Used is SegWit v.0
        BECH32,
        // Used in SegWit v.1, e.g. Taproot
        BECH32M,
        // Specifies an unknown encoding, usually it means some error
        UNKNOWN
    }

    enum DecodeError {
        NoError,
        IncorrectPadding,
        IncorrectLength,
        CharacterOutOfRange,
        MixedCase,
        //checksum does not match
        IncorrectChecksum,
        //checksum bytes length is too short
        TooShortChecksum,
        InputIsTooLong,
        NotBech32Character,
        // Network prefix is not set
        HRPIsEmpty,
        NoDelimiter,
        // decoded HRP is different from expected HRP
        HRPMismatch,
        EmptyData,
        // witness program should be at least 2 bytes
        WitnessProgramTooSmall,
        // witness program should be maximum 40 bytes
        WitnessProgramTooLarge,
        // segwit version should be from 0 to 16 (including). Got some larger number.
        SegwitVersionTooLarge,
        // Length of segwit v0 program should be either 20 or 32 bytes. 20 for PWKH, 32 for P2WSH
        IncorrectSegwitV0Program,
        // Segwit v0 should be encoded using Bech32
        IncorrectEncodingForSegwitV0,
        // Segwit with versions 1-16 should be encoded with Bech32m
        IncorrectEncodingForSegwitVn
    }

    function explainDecodeError(DecodeError err) internal pure returns (string memory) {
        if (err == DecodeError.NoError) {
            return string("No error");
        } else if (err == DecodeError.IncorrectPadding) {
            return string("Incorrect Padding");
        } else if (err == DecodeError.IncorrectLength) {
            return string("Incorrect address length");
        } else if (err == DecodeError.CharacterOutOfRange) {
            return string("Address contain character out of range");
        } else if (err == DecodeError.MixedCase) {
            return string("Address consists of both capital and small letters");
        } else if (err == DecodeError.IncorrectChecksum) {
            return string("Address checksum does not match");
        } else if (err == DecodeError.TooShortChecksum) {
            return string("Address checksum is too short");
        } else if (err == DecodeError.InputIsTooLong) {
            return string("Address is too long");
        } else if (err == DecodeError.NotBech32Character) {
            return string("Address contains character which is not in bech32 encoding");
        } else if (err == DecodeError.HRPIsEmpty) {
            return string("Network prefix is empty");
        } else if (err == DecodeError.NoDelimiter) {
            return string("No prefix delimiter in the address");
        } else if (err == DecodeError.HRPMismatch) {
            return string("Network prefix is different from expected");
        } else if (err == DecodeError.WitnessProgramTooSmall) {
            return string("Witness program should be at least 2 bytes");
        } else if (err == DecodeError.EmptyData) {
            return string("Witness program is empty");
        } else if (err == DecodeError.WitnessProgramTooLarge) {
            return string("Witness program should be maximum 40 bytes");
        } else if (err == DecodeError.SegwitVersionTooLarge) {
            return string("Segwit version should be from 0 to 16 (including). Got some larger number.");
        } else if (err == DecodeError.IncorrectSegwitV0Program) {
            return string("Length of segwit v0 program should be either 20 or 32 bytes");
        } else if (err == DecodeError.IncorrectEncodingForSegwitV0) {
            return string("Segwit v0 should be encoded using Bech32");
        } else if (err == DecodeError.IncorrectEncodingForSegwitVn) {
            return string("Segwit with versions 1-16 should be encoded with Bech32m");
        }
        return "";
    }

    // Possible characters for Bitcoin address
    bytes internal constant CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";

    // index is character code in ASCII
    // value is Bech32 character value
    // if value is 0x7f=127 then character is not in the Bech32 charset
    bytes internal constant REVERSE_CHARSET =
        hex"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f0f7f0a1115141a1e07057f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f1d7f180d190908177f12161f1b137f010003100b1c0c0e0604027f7f7f7f7f";

    // Bech32m constant
    uint256 internal constant BECH32M_CONST = 0x2bc830a3;

    // 1 byte for the separator
    bytes1 internal constant SEPARATOR = bytes1(0x31);

    // Internal function that computes the Bech32 checksum.
    function polymod(uint[] memory values) internal pure returns (uint) {

        // Generator constants
        uint32[5] memory GENERATOR = [
            0x3b6a57b2,
            0x26508e6d,
            0x1ea119fa,
            0x3d4233dd,
            0x2a1462b3
        ];

        uint chk = 1;
        uint valuesLength = values.length;
        for (uint p = 0; p < valuesLength; p++) {
            uint top = chk >> 25;
            chk = ((chk & 0x1ffffff) << 5) ^ values[p];
            for (uint i = 0; i < 5; ++i) {
                if ((top >> i) & 1 == 1) {
                    chk ^= GENERATOR[i];
                }
            }
        }
        return chk;
    }

    // Expand the HRP into values for checksum computation.
    // hrpExpand DOES NOT check the validity of the HRP
    function hrpExpand(bytes memory hrp) internal pure returns (bytes memory) {

        bytes memory a = new bytes(hrp.length + hrp.length + 1);
        uint256 hrpLength = hrp.length;
        for (uint i = 0; i < hrpLength; i += 1) {
            a[i] = hrp[i] >> 5;
            a[i + hrp.length + 1] = bytes1(uint8(hrp[i]) & 31);
        }
        a[hrp.length] = 0;
        return a;
    }

    // Compute the checksum values given HRP and data.
    function createChecksum(
        bytes memory hrp,
        bytes memory data,
        BechEncoding spec
    ) internal pure returns (bytes memory) {
        // Note: UNKNOWN encoding check is already implemented in bech32Encode function
        uint const = spec == BechEncoding.BECH32M ? BECH32M_CONST : 1;
        bytes memory hrpExpandBytes = hrpExpand(hrp);
        uint[] memory polymodArg = new uint[](
            hrpExpandBytes.length + data.length + 6
        );

        uint256 hrpExpandBytesLength = hrpExpandBytes.length;
        for (uint i = 0; i < hrpExpandBytesLength; i += 1) {
            polymodArg[i] = uint8(hrpExpandBytes[i]);
        }
        uint256 dataLength = data.length;
        for (uint i = 0; i < dataLength; i += 1) {
            polymodArg[i + hrpExpandBytes.length] = uint8(data[i]);
        }

        uint polymodVal = polymod(polymodArg) ^ const;

        bytes memory chk = new bytes(6);

        chk[0] = bytes1(uint8((polymodVal >> (5 * (5))) & 31));
        chk[1] = bytes1(uint8((polymodVal >> (5 * (4))) & 31));
        chk[2] = bytes1(uint8((polymodVal >> (5 * (3))) & 31));
        chk[3] = bytes1(uint8((polymodVal >> (5 * (2))) & 31));
        chk[4] = bytes1(uint8((polymodVal >> (5 * (1))) & 31));
        chk[5] = bytes1(uint8((polymodVal >> (5 * (0))) & 31));

        return chk;
    }

    // Verify a checksum given HRP and converted data characters.
    function verifyChecksum(
        bytes memory hrp,
        bytes memory data
    ) internal pure returns (BechEncoding) {

        bytes memory hrpExpandBytes = hrpExpand(hrp);

        uint[] memory polymodArg = new uint[](
            hrpExpandBytes.length + data.length
        );
        uint256 hrpExpandBytesLength = hrpExpandBytes.length;
        for (uint i = 0; i < hrpExpandBytesLength; i += 1) {
            polymodArg[i] = uint8(hrpExpandBytes[i]);
        }
        uint256 dataLength = data.length;
        for (uint i = 0; i < dataLength; i += 1) {
            polymodArg[i + hrpExpandBytes.length] = uint8(data[i]);
        }

        uint polymodVal = polymod(polymodArg);
        if (polymodVal == 1) {
            return BechEncoding.BECH32;
        }
        if (polymodVal == BECH32M_CONST) {
            return BechEncoding.BECH32M;
        }

        return BechEncoding.UNKNOWN;
    }

    // Compute a Bech32 string given HRP and data values.
    function bech32Encode(
        bytes memory hrp,
        bytes memory data,
        BechEncoding spec
    ) internal pure returns (bytes memory) {

        if (spec == BechEncoding.UNKNOWN) {
            revert EncodingIsUnknown();
        }
        // 6 bytes of the checksum in a 5-bit format
        bytes memory chk = createChecksum(hrp, data, spec);

        // <hrp> 1 <data-5bit-format> <6bytes of chk-5bit-format>

        // reuse data and chk arrays to modify data in place to save gas

        uint256 dataLength = data.length;
        for (uint i = 0; i < dataLength; i += 1) {
            // ret[i + hrp.length + 1] = CHARSET[uint8(data[i])];
            data[i] = CHARSET[uint8(data[i])];
        }

        for (uint i = 0; i < 6; i += 1) {
            // ret[startChk + i] = CHARSET[uint8(chk[i])];
            chk[i] = CHARSET[uint8(chk[i])];
        }

        return bytes.concat(hrp, SEPARATOR, data, chk);
    }

    // Convert 5 bytes to 8 groups of 5 bits, with padding
    function conver8To5(bytes memory a) internal pure returns (bytes memory) {
        // We group the data into 5-byte groups
        // Because 5-byte group has the bitlength 40
        // Thus it can be easily converted to 8 5-bit groups.
        uint nGroup40bit = a.length / 5;

        // Some input bytes may not get into 5-byte input group
        // so we need to process the remaining bytes
        uint nRemainInp8bit = a.length % 5;

        // 0: 0 -> 0
        // 1: 8 -> 2
        // 2: 16 -> 4
        // 3: 24 -> 5
        // 4: 32 -> 7
        // Number of additional 5-bits should be added
        uint nRemainOut5Bit = 0;
        // Number of padding bits should be added
        uint nPadBits = 0;
        if (nRemainInp8bit == 1) {
            nRemainOut5Bit = 2;
            nPadBits = 2;
        } else if (nRemainInp8bit == 2) {
            nRemainOut5Bit = 4;
            nPadBits = 4;
        } else if (nRemainInp8bit == 3) {
            nRemainOut5Bit = 5;
            nPadBits = 1;
        } else if (nRemainInp8bit == 4) {
            nRemainOut5Bit = 7;
            nPadBits = 3;
        }

        uint outLen = nGroup40bit * 8 + nRemainOut5Bit;
        bytes memory b = new bytes(outLen);

        for (uint ig = 0; ig < nGroup40bit; ig += 1) {
            uint i = ig * 5;
            uint j = ig * 8;
            uint w = 256 ** 4 *
                uint(uint8(a[i])) +
                256 ** 3 *
                uint(uint8(a[i + 1])) +
                256 ** 2 *
                uint(uint8(a[i + 2])) +
                256 *
                uint(uint8(a[i + 3])) +
                uint(uint8(a[i + 4]));
            b[j + 7] = bytes1(uint8(w & 31));
            b[j + 6] = bytes1(uint8((w >> 5) & 31));
            b[j + 5] = bytes1(uint8((w >> 10) & 31));
            b[j + 4] = bytes1(uint8((w >> 15) & 31));
            b[j + 3] = bytes1(uint8((w >> 20) & 31));
            b[j + 2] = bytes1(uint8((w >> 25) & 31));
            b[j + 1] = bytes1(uint8((w >> 30) & 31));
            b[j] = bytes1(uint8((w >> 35) & 31));
        }

        if (nRemainOut5Bit > 0) {
            uint w;
            uint aLength = a.length;
            for (uint i = nGroup40bit * 5; i < aLength; i += 1) {
                w = (w << 8) + uint(uint8(a[i]));
            }
            w <<= nPadBits;
            for (uint j = 0; j < nRemainOut5Bit; j += 1) {
                b[nGroup40bit * 8 + j] = bytes1(
                    uint8((w >> (5 * (nRemainOut5Bit - j - 1))) & 31)
                );
            }
        }

        return b;
    }

    function encodeSegwitAddress(
        bytes memory hrp,
        uint8 witVer,
        bytes memory witProg
    ) internal pure returns (bytes memory) {
        BechEncoding spec = witVer == 0
            ? BechEncoding.BECH32
            : BechEncoding.BECH32M;

        bytes memory witProg5bit = conver8To5(witProg);
        bytes memory encArg = bytes.concat(bytes1(witVer), witProg5bit);

        return bech32Encode(hrp, encArg, spec);
    }

    // Convert 8 groups of 5 bits to 5 bytes
    function convert5to8(
        bytes memory data5Bits
    ) internal pure returns (bytes memory, DecodeError) {
        uint vRest;
        uint nRest5Bits = data5Bits.length % 8;
        uint nRest8Bits;
        uint nGroups40Bits = data5Bits.length / 8;
        uint startRest5Bit = nGroups40Bits * 8;
        uint startRest8Bit = nGroups40Bits * 5;

        if (nRest5Bits == 1) {
            return (new bytes(0), DecodeError.IncorrectLength);
        } else if (nRest5Bits == 2) {
            if (uint8(data5Bits[data5Bits.length - 1]) & 3 == 0) {
                vRest =
                    (uint(uint8(data5Bits[startRest5Bit])) << 5) +
                    uint(uint8(data5Bits[startRest5Bit + 1]));
                vRest >>= 2;
                nRest8Bits = 1;
            } else {
                return (new bytes(0), DecodeError.IncorrectPadding);
            }
        } else if (nRest5Bits == 3) {
            return (new bytes(0), DecodeError.IncorrectLength);
        } else if (nRest5Bits == 4) {
            if (uint8(data5Bits[data5Bits.length - 1]) & 15 == 0) {
                vRest =
                    (uint(uint8(data5Bits[startRest5Bit])) << 15) +
                    (uint(uint8(data5Bits[startRest5Bit + 1])) << 10) +
                    (uint(uint8(data5Bits[startRest5Bit + 2])) << 5) +
                    uint(uint8(data5Bits[startRest5Bit + 3]));
                vRest >>= 4;
                nRest8Bits = 2;
            } else {
                return (new bytes(0), DecodeError.IncorrectPadding);
            }
        } else if (nRest5Bits == 5) {
            if (uint8(data5Bits[data5Bits.length - 1]) & 1 == 0) {
                vRest =
                    (uint(uint8(data5Bits[startRest5Bit])) << 20) +
                    (uint(uint8(data5Bits[startRest5Bit + 1])) << 15) +
                    (uint(uint8(data5Bits[startRest5Bit + 2])) << 10) +
                    (uint(uint8(data5Bits[startRest5Bit + 3])) << 5) +
                    (uint(uint8(data5Bits[startRest5Bit + 4])));
                vRest >>= 1;
                nRest8Bits = 3;
            } else {
                return (new bytes(0), DecodeError.IncorrectPadding);
            }
        } else if (nRest5Bits == 6) {
            return (new bytes(0), DecodeError.IncorrectLength);
        } else if (nRest5Bits == 7) {
            if (uint8(data5Bits[data5Bits.length - 1]) & 7 == 0) {
                vRest =
                    (uint(uint8(data5Bits[startRest5Bit])) << 30) +
                    (uint(uint8(data5Bits[startRest5Bit + 1])) << 25) +
                    (uint(uint8(data5Bits[startRest5Bit + 2])) << 20) +
                    (uint(uint8(data5Bits[startRest5Bit + 3])) << 15) +
                    (uint(uint8(data5Bits[startRest5Bit + 4])) << 10) +
                    (uint(uint8(data5Bits[startRest5Bit + 5])) << 5) +
                    uint(uint8(data5Bits[startRest5Bit + 6]));
                vRest >>= 3;
                nRest8Bits = 4;
            } else {
                return (new bytes(0), DecodeError.IncorrectPadding);
            }
        }

        bytes memory rez8Bits = new bytes(nGroups40Bits * 5 + nRest8Bits);

        for (uint ig = 0; ig < nGroups40Bits; ig += 1) {
            uint i = ig * 8;
            uint j = ig * 5;
            uint v = (uint(uint8(data5Bits[i])) << 35);
            v += (uint(uint8(data5Bits[i + 1])) << 30);
            v += (uint(uint8(data5Bits[i + 2])) << 25);
            v += (uint(uint8(data5Bits[i + 3])) << 20);
            v += (uint(uint8(data5Bits[i + 4])) << 15);
            v += (uint(uint8(data5Bits[i + 5])) << 10);
            v += (uint(uint8(data5Bits[i + 6])) << 5);
            v += uint(uint8(data5Bits[i + 7]));
            rez8Bits[j] = bytes1(uint8((v >> 32) & 255));
            rez8Bits[j + 1] = bytes1(uint8((v >> 24) & 255));
            rez8Bits[j + 2] = bytes1(uint8((v >> 16) & 255));
            rez8Bits[j + 3] = bytes1(uint8((v >> 8) & 255));
            rez8Bits[j + 4] = bytes1(uint8((v) & 255));
        }

        if (nRest8Bits == 1) {
            rez8Bits[startRest8Bit] = bytes1(uint8(vRest & 255));
        } else if (nRest8Bits == 2) {
            rez8Bits[startRest8Bit] = bytes1(uint8((vRest >> 8) & 255));
            rez8Bits[startRest8Bit + 1] = bytes1(uint8(vRest & 255));
        } else if (nRest8Bits == 3) {
            rez8Bits[startRest8Bit] = bytes1(uint8((vRest >> 16) & 255));
            rez8Bits[startRest8Bit + 1] = bytes1(uint8((vRest >> 8) & 255));
            rez8Bits[startRest8Bit + 2] = bytes1(uint8(vRest & 255));
        } else if (nRest8Bits == 4) {
            rez8Bits[startRest8Bit] = bytes1(uint8((vRest >> 24) & 255));
            rez8Bits[startRest8Bit + 1] = bytes1(uint8((vRest >> 16) & 255));
            rez8Bits[startRest8Bit + 2] = bytes1(uint8((vRest >> 8) & 255));
            rez8Bits[startRest8Bit + 3] = bytes1(uint8(vRest & 255));
        }

        return (rez8Bits, DecodeError.NoError);
    }

    // check that all characters are in the range 33-126 inclusive\
    function isValidCharacterRange(
        bytes memory bech
    ) internal pure returns (bool) {
        uint256 bechLength = bech.length;
        for (uint i = 0; i < bechLength; i += 1) {
            if (uint8(bech[i]) < 33 || uint8(bech[i]) > 126) {
                return false;
            }
        }
        return true;
    }

    function isMixedCase(bytes memory b) internal pure returns (bool) {
        bool hasLower = false;
        bool hasUpper = false;

        // The range of ASCII values for uppercase letters A-Z is 65-90,
        // and the range for lowercase letters a-z is 97-122.
        for (uint i = 0; i < b.length; i += 1) {
            if (uint8(b[i]) >= 97 && uint8(b[i]) <= 122) {
                hasLower = true;
            } else if (uint8(b[i]) >= 65 && uint8(b[i]) <= 90) {
                hasUpper = true;
            }
            if (hasLower && hasUpper) {
                return true;
            }
        }

        return false;
    }

    function toLower(bytes memory a) internal pure returns (bytes memory) {
        bytes memory b = new bytes(a.length);
        uint256 aLength = a.length;
        for (uint i = 0; i < aLength; i += 1) {
            if (uint8(a[i]) >= 65 && uint8(a[i]) <= 90) {
                b[i] = bytes1(uint8(a[i]) + 32);
            } else {
                b[i] = a[i];
            }
        }
        return b;
    }

    // start included
    // stop excluded
    function decodeCharactersBech32(
        bytes memory bech,
        uint start,
        uint stop
    ) internal pure returns (bytes memory, DecodeError) {
        bytes memory decoded = new bytes(stop - start);
        for (uint i = start; i < stop; i += 1) {
            uint8 c = uint8(bech[i]);
            if (c >= REVERSE_CHARSET.length || REVERSE_CHARSET[c] == 0x7f) {
                return (new bytes(0), DecodeError.NotBech32Character);
            }
            decoded[i - start] = REVERSE_CHARSET[c];
        }
        return (decoded, DecodeError.NoError);
    }

    function bech32Decode(
        bytes memory bech
    )
        internal
        pure
        returns (bytes memory, bytes memory, BechEncoding, DecodeError)
    {
        if (bech.length > 90) {
            return (
                new bytes(0),
                new bytes(0),
                BechEncoding.UNKNOWN,
                DecodeError.InputIsTooLong
            );
        }

        if (!isValidCharacterRange(bech)) {
            return (
                new bytes(0),
                new bytes(0),
                BechEncoding.UNKNOWN,
                DecodeError.CharacterOutOfRange
            );
        }

        if (isMixedCase(bech)) {
            return (
                new bytes(0),
                new bytes(0),
                BechEncoding.UNKNOWN,
                DecodeError.MixedCase
            );
        }

        bytes memory bechLow = toLower(bech);
        int delimiterPos = int256(bechLow.length) - 1;

        if (bechLow.length > 2 && bechLow[2] == 0x31) {
            delimiterPos = 2;
        } else {
            delimiterPos = int256(bechLow.length) - 1;
            while (true) {
                delimiterPos -= 1;
                if (delimiterPos < 0) {
                    return (
                        new bytes(0),
                        new bytes(0),
                        BechEncoding.UNKNOWN,
                        DecodeError.NoDelimiter
                    );
                }
                // 0x31 is '1'
                if (bechLow[uint256(delimiterPos)] == 0x31) {
                    break;
                }
            }
        }
        if (delimiterPos < 1) {
            return (
                new bytes(0),
                new bytes(0),
                BechEncoding.UNKNOWN,
                DecodeError.HRPIsEmpty
            );
        }
        if (delimiterPos + 7 > int(bechLow.length)) {
            return (
                new bytes(0),
                new bytes(0),
                BechEncoding.UNKNOWN,
                DecodeError.TooShortChecksum
            );
        }

        bytes memory hrp = new bytes(uint(delimiterPos));
        for (uint i = 0; i < uint(delimiterPos); i += 1) {
            hrp[i] = bechLow[i];
        }

        (bytes memory dataAll5Bit, DecodeError err) = decodeCharactersBech32(
            bechLow,
            uint(delimiterPos + 1),
            bechLow.length
        );
        if (err != DecodeError.NoError) {
            return (new bytes(0), new bytes(0), BechEncoding.UNKNOWN, err);
        }

        BechEncoding spec = verifyChecksum(hrp, dataAll5Bit);
        if (spec == BechEncoding.UNKNOWN) {
            return (
                new bytes(0),
                new bytes(0),
                BechEncoding.UNKNOWN,
                DecodeError.IncorrectChecksum
            );
        }

        bytes memory data5Bit = new bytes(dataAll5Bit.length - 6);
        uint256 data5BitLength = data5Bit.length;
        for (uint i = 0; i < data5BitLength; i += 1) {
            data5Bit[i] = dataAll5Bit[i];
        }

        return (hrp, data5Bit, spec, DecodeError.NoError);
    }

    function areBytesEqual(
        bytes memory a,
        bytes memory b
    ) internal pure returns (bool) {
        if (a.length != b.length) {
            return false;
        }
        uint256 aLength = a.length;
        for (uint i = 0; i < aLength; i += 1) {
            if (a[i] != b[i]) {
                return false;
            }
        }
        return true;
    }

    // Decode a segwit address
    function decodeSegwitAddress(
        bytes memory expectedHrp,
        bytes memory addr
    ) internal pure returns (uint8, bytes memory, DecodeError) {
        (
            bytes memory hrpGot,
            bytes memory data5Bit,
            BechEncoding spec,
            DecodeError err
        ) = bech32Decode(addr);
        if (err != DecodeError.NoError) {
            return (0, new bytes(0), err);
        }

        if (!areBytesEqual(expectedHrp, hrpGot)) {
            return (0, new bytes(0), DecodeError.HRPMismatch);
        }

        if (data5Bit.length == 0) {
            return (0, new bytes(0), DecodeError.EmptyData);
        }

        if (uint8(data5Bit[0]) > 16) {
            return (0, new bytes(0), DecodeError.SegwitVersionTooLarge);
        }

        bytes memory data5BitNoVer = new bytes(data5Bit.length - 1);
        uint256 data5BitNoVerLength = data5BitNoVer.length; 
        for (uint i = 0; i < data5BitNoVerLength; i += 1) {
            data5BitNoVer[i] = data5Bit[i + 1];
        }

        bytes memory data8Bit;
        (data8Bit, err) = convert5to8(data5BitNoVer);
        if (err != DecodeError.NoError) {
            return (0, new bytes(0), err);
        }

        if (data8Bit.length < 2) {
            return (0, new bytes(0), DecodeError.WitnessProgramTooSmall);
        }

        if (data8Bit.length > 40) {
            return (0, new bytes(0), DecodeError.WitnessProgramTooLarge);
        }

        if (
            uint8(data5Bit[0]) == 0 &&
            data8Bit.length != 20 &&
            data8Bit.length != 32
        ) {
            return (0, new bytes(0), DecodeError.IncorrectSegwitV0Program);
        }

        if (uint8(data5Bit[0]) == 0 && spec != BechEncoding.BECH32) {
            return (0, new bytes(0), DecodeError.IncorrectEncodingForSegwitV0);
        }

        if (uint8(data5Bit[0]) != 0 && spec != BechEncoding.BECH32M) {
            return (0, new bytes(0), DecodeError.IncorrectEncodingForSegwitVn);
        }

        return (uint8(data5Bit[0]), data8Bit, DecodeError.NoError);
    }
}

lib/blockchain-tools/src/BitcoinNetworkEncoder.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.27;

library BitcoinNetworkEncoder {

    bytes constant BTC_BECH32_MAINNET_BYTES = hex"626331"; // prefix = bc1
    bytes constant BTC_BECH32_TESTNET_BYTES = hex"746231"; // prefix = tb1
    bytes constant BTC_BECH32_REGTEST_BYTES = hex"6263727431"; // prefix = bcrt1
    bytes constant BTC_BECH32_SIMNET_BYTES = hex"736231"; // prefix = sb1

    string constant BTC_BECH32_MAINNET = 'bc';
    string constant BTC_BECH32_TESTNET = 'tb';
    string constant BTC_BECH32_REGTEST = 'bcrt';
    string constant BTC_BECH32_SIMNET = 'sb';

    bytes constant BTC_P2PKH_MAINNET = hex"31"; // prefix = 1
    bytes constant BTC_P2SH_MAINNET = hex"33"; // prefix = 3
    bytes constant BTC_P2PKH_TESTNET = hex"32"; // prefix = 2
    bytes constant BTC_P2SH_TESTNET = hex"6d"; // prefix = m
    bytes constant BTC_P2PKH_REGTEST = hex"32"; // prefix = 2
    bytes constant BTC_P2SH_REGTEST = hex"6d"; // prefix = m
    bytes constant BTC_P2PKH_SIMNET = hex"53"; // prefix = S
    bytes constant BTC_P2SH_SIMNET = hex"73"; // prefix = s

    //NB: don't forget to update `lnbtc_ext.go` when changing this enum!
    enum Network {
        Mainnet,
        Testnet,
        Regtest,
        Simnet
    }

    function getBtcBech32Prefix(Network _network) internal pure returns (bytes memory) {
        if (_network == Network.Mainnet) {
            return BTC_BECH32_MAINNET_BYTES;
        } else if (_network == Network.Regtest) {
            return BTC_BECH32_REGTEST_BYTES;
        } else if (_network == Network.Testnet) {
            return BTC_BECH32_TESTNET_BYTES;
        } else if (_network == Network.Simnet) {
            return BTC_BECH32_SIMNET_BYTES;
        } else {
            revert("Unknown network type");
        }
    }

    function getNetworkPrefix(Network _network) internal pure returns (string memory) {
        if (_network == Network.Mainnet) {
            return BTC_BECH32_MAINNET;
        } else if (_network == Network.Testnet) {
            return BTC_BECH32_TESTNET;
        } else if (_network == Network.Regtest) {
            return BTC_BECH32_REGTEST;
        } else if (_network == Network.Simnet) {
            return BTC_BECH32_SIMNET;
        } else {
            revert("Unknown network type");
        }
    }

    function getBtcBase58_P2PKH(BitcoinNetworkEncoder.Network network) internal pure returns (bytes memory) {
        if (network == BitcoinNetworkEncoder.Network.Mainnet) {
            return BTC_P2PKH_MAINNET;
        } else if (network == BitcoinNetworkEncoder.Network.Regtest) {
            return BTC_P2PKH_REGTEST;
        } else if (network == BitcoinNetworkEncoder.Network.Testnet) {
            return BTC_P2PKH_TESTNET;
        } else if (network == BitcoinNetworkEncoder.Network.Simnet) {
            return BTC_P2PKH_SIMNET;
        } else {
            revert("Unknown network type");
        }
    }

    function getBtcBase58_P2SH(BitcoinNetworkEncoder.Network network) internal pure returns (bytes memory) {
        if (network == BitcoinNetworkEncoder.Network.Mainnet) {
            return BTC_P2SH_MAINNET;
        } else if (network == BitcoinNetworkEncoder.Network.Regtest) {
            return BTC_P2SH_REGTEST;
        } else if (network == BitcoinNetworkEncoder.Network.Testnet) {
            return BTC_P2SH_TESTNET;
        } else if (network == BitcoinNetworkEncoder.Network.Simnet) {
            return BTC_P2SH_SIMNET;
        } else {
            revert("Unknown network type");
        }
    }
}

lib/blockchain-tools/src/Deriver.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.27;

import {EllipticCurve} from "../lib/elliptic-curve-solidity/contracts/EllipticCurve.sol";

import {Bech32m} from "./Bech32m.sol";

library Deriver {
    // BEGIN SECP256k1 CONSTANTS
    uint256 public constant GX =
        0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
    uint256 public constant GY =
        0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
    uint256 public constant AA = 0;
    uint256 public constant BB = 7;
    uint256 public constant PP =
        0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
    // END SECP256k1 CONSTANTS

    // sha256("TapTweak")
    bytes32 public constant SHA256_TAP_TWEAK =
        hex"e80fe1639c9ca050e3af1b39c143c63e429cbceb15d940fbb5c5a1f4af57c5e9";
    
    // Note: Tagged hashes are not needed here as this function:
    // 1. Has clearly typed inputs
    // 2. Is used only for internal coefficient derivation
    // 3. Does not interact directly with Bitcoin protocol
    function getCoefficient(
        uint256 x1,
        uint256 y1,
        address a
    ) internal pure returns (uint256) {
        uint256 c = uint256(sha256(abi.encode(x1, y1, a)));
        return c;
    }

    // pubkey add operation
    function addPubkeys(
        uint256 x1,
        uint256 y1,
        uint256 x2,
        uint256 y2
    ) internal pure returns (uint256, uint256) {
        return EllipticCurve.ecAdd(x1, y1, x2, y2, AA, PP);
    }

    // pubkey multiplication by scalar operation
    function mulPubkey(
        uint256 x,
        uint256 y,
        uint256 scalar
    ) internal pure returns (uint256, uint256) {
        return EllipticCurve.ecMul(scalar, x, y, AA, PP);
    }

    // linear combination of two pubkeys
    // Note: resulting point may have odd y coordinate(not compatible with BIP-340), however
    // if it is used for address derivation which requires only x coordinate, it is not a problem.
    // But if you use this pubkey for other purposes, you should check y coordinate and negate the point if necessary.
    function getCombinedPubkey(
        uint256 p1x,
        uint256 p1y,
        uint256 p2x,
        uint256 p2y,
        uint256 c1,
        uint256 c2
    ) internal pure returns (uint256, uint256) {
        (uint256 x1, uint256 y1) = mulPubkey(p1x, p1y, c1);
        (uint256 x2, uint256 y2) = mulPubkey(p2x, p2y, c2);

        (uint256 x3, uint256 y3) = addPubkeys(x1, y1, x2, y2);
       
        // Note: y-coordinate parity check is handled in getBtcAddressTaprootNoScriptFromEth
        // where it's actually needed for BIP-340 compatibility
        
        return (x3, y3);
    }

    // derive pubkey from Validators' pubkeys and user's Ethereum address
    function getPubkeyFromAddress(
        uint256 p1x,
        uint256 p1y,
        uint256 p2x,
        uint256 p2y,
        address addr
    ) internal pure returns (uint256, uint256) {
        uint256 c1 = getCoefficient(p1x, p1y, addr);
        uint256 c2 = getCoefficient(p2x, p2y, addr);
        return getCombinedPubkey(p1x, p1y, p2x, p2y, c1, c2);
    }

    // derive Bitcoin address from pubkey
    // only x coordinate is used for address generation
    function getBtcTaprootAddrFromPubkey(
        uint256 x,
        bytes memory hrp
    ) internal pure returns (string memory) {
        return string(Bech32m.encodeSegwitAddress(hrp, 1, abi.encodePacked(x)));
    }

    // calculate y coordinate from x coordinate
    function liftX(uint256 x) internal pure returns (uint256) {
        return EllipticCurve.deriveY(0x02, x, AA, BB, PP);
    }

    // tweaks pubkey with a no script path
    // According to BIP 341: "If the spending conditions do not require a script path,
    // the output key should commit to an unspendable script path instead of having no script path"
    // Note: resulting point may have odd y coordinate(not compatible with BIP-340), however
    // it is used for address derivation which requires only x coordinate.
    function computeTaprootKeyNoScript(
        uint256 x,
        uint256 y
    ) internal pure returns (uint256, uint256) {
        // Calculate TaggedHash("TapTweak", x)
        uint256 h = uint256(
            sha256(abi.encode(SHA256_TAP_TWEAK, SHA256_TAP_TWEAK, x))
        );

        (uint256 x1, uint256 y1) = mulPubkey(GX, GY, h);

        (uint256 x2, uint256 y2) = addPubkeys(x, y, x1, y1);

        return (x2, y2);
    }

    // derive Bitcoin address from user's Ethereum address and validators' pubkeys
    // It generate taproot address with taproot commitment and no script path(preferred way according to BIP-341)
    // Better to use this function instead of getBtcAddressFromEth
    function getBtcAddressTaprootNoScriptFromEth(
        uint256 p1x,
        uint256 p1y,
        uint256 p2x,
        uint256 p2y,
        bytes memory hrp,
        address ethAddr
    ) internal pure returns (string memory) {
        (uint256 x, uint256 y) = getPubkeyFromAddress(
            p1x,
            p1y,
            p2x,
            p2y,
            ethAddr
        );

        // BIP-340 requires even y-coordinate for public keys
        if (y % 2 == 1) {
            y = PP - y;
        }

        (uint256 xTweaked,) = computeTaprootKeyNoScript(x, y);

        return getBtcTaprootAddrFromPubkey(xTweaked, hrp);
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {
    "lib/blockchain-tools/src/BitcoinUtils.sol": {
      "BitcoinUtils": "0x09ca580E60fd02fBA24384EcC947A22aD379B531"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris",
  "remappings": [
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
    "bip340-solidity/=lib/bip340-solidity/",
    "blockchain-tools/=lib/blockchain-tools/",
    "ds-test/=lib/blockchain-tools/forge-std/lib/ds-test/src/",
    "elliptic-curve-solidity/=lib/blockchain-tools/lib/elliptic-curve-solidity/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "foundry-devops/=lib/blockchain-tools/lib/foundry-devops/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "safe-contracts/=lib/safe-contracts/",
    "@safe-global/safe-contracts/=lib/safe-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.