# Path: bit/constants.py
# BTC = 10 ** 8
# 
# Path: bit/network/rates.py
# @classmethod
# def currency_to_satoshi(cls, currency):
#     headers = {"x-accept-version": "2.0.0", "Accept": "application/json"}
#     r = requests.get(cls.SINGLE_RATE + currency, headers=headers)
#     r.raise_for_status()
#     rate = r.json()['data']['rate']
#     return int(ONE / Decimal(rate) * BTC)
# 
# Path: bit/network/meta.py
# class Unspent:
#     """Represents an unspent transaction output (UTXO)."""
# 
#     __slots__ = ('amount', 'confirmations', 'script', 'txid', 'txindex', 'type', 'vsize', 'segwit', 'sequence')
# 
#     def __init__(self, amount, confirmations, script, txid, txindex, type='p2pkh', vsize=None, segwit=None,
#                  sequence=int.from_bytes(SEQUENCE, byteorder='little')):
#         self.amount = amount
#         self.confirmations = confirmations
#         self.script = script
#         self.txid = txid
#         self.txindex = txindex
#         self.type = type if type in UNSPENT_TYPES else 'unknown'
#         self.vsize = vsize if vsize else UNSPENT_TYPES[self.type]['vsize']
#         self.segwit = UNSPENT_TYPES[self.type]['segwit']
#         self.sequence = sequence
# 
#     def to_dict(self):
#         return {attr: getattr(self, attr) for attr in Unspent.__slots__}
# 
#     @classmethod
#     def from_dict(cls, d):
#         return Unspent(**{attr: d[attr] for attr in Unspent.__slots__})
# 
#     def __eq__(self, other):
#         return (
#             self.amount == other.amount
#             and self.script == other.script
#             and self.txid == other.txid
#             and self.txindex == other.txindex
#             and self.segwit == other.segwit
#             and self.sequence == other.sequence
#         )
# 
#     def __repr__(self):
#         return 'Unspent(amount={}, confirmations={}, script={}, txid={}, txindex={}, segwit={}, sequence={})'.format(
#             repr(self.amount),
#             repr(self.confirmations),
#             repr(self.script),
#             repr(self.txid),
#             repr(self.txindex),
#             repr(self.segwit),
#             repr(self.sequence)
#         )
# 
#     def set_type(self, type, vsize=0):
#         self.type = type if type in UNSPENT_TYPES else 'unknown'
#         self.vsize = vsize if vsize else UNSPENT_TYPES[self.type]['vsize']
#         self.segwit = UNSPENT_TYPES[self.type]['segwit']
#         return self
# 
#     def opt_in_for_RBF(self):
#         if self.sequence > 4294967293:
#             self.sequence = 4294967293
# 
# Path: bit/exceptions.py
# class BitcoinNodeException(Exception):
#     pass
# 
# class ExcessiveAddress(Exception):
#     pass
# 
# Path: bit/transaction.py
# def address_to_scriptpubkey(address):
#     # Raise ValueError if we cannot identify the address.
#     get_version(address)
#     try:
#         version = b58decode_check(address)[:1]
#     except ValueError:
#         witver, data = segwit_decode(address)
#         return segwit_scriptpubkey(witver, data)
# 
#     if version == MAIN_PUBKEY_HASH or version == TEST_PUBKEY_HASH:
#         return OP_DUP + OP_HASH160 + OP_PUSH_20 + address_to_public_key_hash(address) + OP_EQUALVERIFY + OP_CHECKSIG
#     elif version == MAIN_SCRIPT_HASH or version == TEST_SCRIPT_HASH:
#         return OP_HASH160 + OP_PUSH_20 + address_to_public_key_hash(address) + OP_EQUAL
# 
# Path: bit/utils.py
# def bytes_to_hex(bytestr, upper=False):
#     hexed = hexlify(bytestr).decode()
#     return hexed.upper() if upper else hexed


import requests
import json
import logging
from decimal import Decimal, getcontext
from bit.constants import BTC
from bit.network import currency_to_satoshi
from bit.network.meta import Unspent
from bit.exceptions import BitcoinNodeException, ExcessiveAddress
from bit.transaction import address_to_scriptpubkey
from bit.utils import bytes_to_hex

        return sorted(
            [
                Unspent(
                    tx["value"],
                    block_height - tx["status"]["block_height"] + 1 if tx["status"]["confirmed"] else 0,
                    script_pubkey,
                    tx["txid"],
                    tx["vout"],
                )
                for tx in r.json()
            ],
            key=lambda u: u.confirmations,
        )

    @classmethod
    def get_unspent_testnet(cls, address):
        # Get current block height:
        r_block = requests.get(cls.TEST_ENDPOINT + 'blocks/tip/height', timeout=DEFAULT_TIMEOUT)
        if r_block.status_code != 200:  # pragma: no cover
            raise ConnectionError
        block_height = int(r_block.text)

        r = requests.get(cls.TEST_UNSPENT_API.format(address), timeout=DEFAULT_TIMEOUT)

        if r.status_code == 400:  # pragma: no cover
            return []
        elif r.status_code != 200:  # pragma: no cover
            raise ConnectionError


# Path: bit/constants.py
# BTC = 10 ** 8
# 
# Path: bit/network/rates.py
# @classmethod
# def currency_to_satoshi(cls, currency):
#     headers = {"x-accept-version": "2.0.0", "Accept": "application/json"}
#     r = requests.get(cls.SINGLE_RATE + currency, headers=headers)
#     r.raise_for_status()
#     rate = r.json()['data']['rate']
#     return int(ONE / Decimal(rate) * BTC)
# 
# Path: bit/network/meta.py
# class Unspent:
#     """Represents an unspent transaction output (UTXO)."""
# 
#     __slots__ = ('amount', 'confirmations', 'script', 'txid', 'txindex', 'type', 'vsize', 'segwit', 'sequence')
# 
#     def __init__(self, amount, confirmations, script, txid, txindex, type='p2pkh', vsize=None, segwit=None,
#                  sequence=int.from_bytes(SEQUENCE, byteorder='little')):
#         self.amount = amount
#         self.confirmations = confirmations
#         self.script = script
#         self.txid = txid
#         self.txindex = txindex
#         self.type = type if type in UNSPENT_TYPES else 'unknown'
#         self.vsize = vsize if vsize else UNSPENT_TYPES[self.type]['vsize']
#         self.segwit = UNSPENT_TYPES[self.type]['segwit']
#         self.sequence = sequence
# 
#     def to_dict(self):
#         return {attr: getattr(self, attr) for attr in Unspent.__slots__}
# 
#     @classmethod
#     def from_dict(cls, d):
#         return Unspent(**{attr: d[attr] for attr in Unspent.__slots__})
# 
#     def __eq__(self, other):
#         return (
#             self.amount == other.amount
#             and self.script == other.script
#             and self.txid == other.txid
#             and self.txindex == other.txindex
#             and self.segwit == other.segwit
#             and self.sequence == other.sequence
#         )
# 
#     def __repr__(self):
#         return 'Unspent(amount={}, confirmations={}, script={}, txid={}, txindex={}, segwit={}, sequence={})'.format(
#             repr(self.amount),
#             repr(self.confirmations),
#             repr(self.script),
#             repr(self.txid),
#             repr(self.txindex),
#             repr(self.segwit),
#             repr(self.sequence)
#         )
# 
#     def set_type(self, type, vsize=0):
#         self.type = type if type in UNSPENT_TYPES else 'unknown'
#         self.vsize = vsize if vsize else UNSPENT_TYPES[self.type]['vsize']
#         self.segwit = UNSPENT_TYPES[self.type]['segwit']
#         return self
# 
#     def opt_in_for_RBF(self):
#         if self.sequence > 4294967293:
#             self.sequence = 4294967293
# 
# Path: bit/exceptions.py
# class BitcoinNodeException(Exception):
#     pass
# 
# class ExcessiveAddress(Exception):
#     pass
# 
# Path: bit/transaction.py
# def address_to_scriptpubkey(address):
#     # Raise ValueError if we cannot identify the address.
#     get_version(address)
#     try:
#         version = b58decode_check(address)[:1]
#     except ValueError:
#         witver, data = segwit_decode(address)
#         return segwit_scriptpubkey(witver, data)
# 
#     if version == MAIN_PUBKEY_HASH or version == TEST_PUBKEY_HASH:
#         return OP_DUP + OP_HASH160 + OP_PUSH_20 + address_to_public_key_hash(address) + OP_EQUALVERIFY + OP_CHECKSIG
#     elif version == MAIN_SCRIPT_HASH or version == TEST_SCRIPT_HASH:
#         return OP_HASH160 + OP_PUSH_20 + address_to_public_key_hash(address) + OP_EQUAL
# 
# Path: bit/utils.py
# def bytes_to_hex(bytestr, upper=False):
#     hexed = hexlify(bytestr).decode()
#     return hexed.upper() if upper else hexed


# Path: bit/network/services.py
import requests
import json
import logging
from decimal import Decimal, getcontext
from bit.constants import BTC
from bit.network import currency_to_satoshi
from bit.network.meta import Unspent
from bit.exceptions import BitcoinNodeException, ExcessiveAddress
from bit.transaction import address_to_scriptpubkey
from bit.utils import bytes_to_hex


        return sorted(
            [
                Unspent(
                    tx["value"],
                    block_height - tx["status"]["block_height"] + 1 if tx["status"]["confirmed"] else 0,
                    script_pubkey,
                    tx["txid"],
                    tx["vout"],
                )
                for tx in r.json()
            ],
            key=lambda u: u.confirmations,
        )

    @classmethod
    def get_unspent_testnet(cls, address):
        # Get current block height:
        r_block = requests.get(cls.TEST_ENDPOINT + 'blocks/tip/height', timeout=DEFAULT_TIMEOUT)
        if r_block.status_code != 200:  # pragma: no cover
            raise ConnectionError
        block_height = int(r_block.text)

        r = requests.get(cls.TEST_UNSPENT_API.format(address), timeout=DEFAULT_TIMEOUT)

        if r.status_code == 400:  # pragma: no cover
            return []
        elif r.status_code != 200:  # pragma: no cover
            raise ConnectionError


        script_pubkey = bytes_to_hex(address_to_scriptpubkey(address))