HASH_TYPE = 0x01 .to_bytes(4, byteorder='little') class InsufficientFunds(Exception):
    pass 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 class TxIn:
    __slots__ = ('script_sig', 'script_sig_len', 'txid', 'txindex', 'witness', 'amount', 'sequence', 'segwit_input')

    def __init__(self, script_sig, txid, txindex, witness=b'', amount=None, sequence=SEQUENCE, segwit_input=False):

        self.script_sig = script_sig
        self.script_sig_len = int_to_varint(len(script_sig))
        self.txid = txid
        self.txindex = txindex
        self.witness = witness
        self.amount = amount
        self.sequence = sequence
        self.segwit_input = segwit_input

    def __eq__(self, other):
        return (
            self.script_sig == other.script_sig
            and self.script_sig_len == other.script_sig_len
            and self.txid == other.txid
            and self.txindex == other.txindex
            and self.witness == other.witness
            and self.amount == other.amount
            and self.sequence == other.sequence
            and self.segwit_input == other.segwit_input
        )

    def __repr__(self):
        if self.is_segwit():
            return 'TxIn({}, {}, {}, {}, {}, {}, {})'.format(
                repr(self.script_sig),
                repr(self.script_sig_len),
                repr(self.txid),
                repr(self.txindex),
                repr(self.witness),
                repr(self.amount),
                repr(self.sequence),
            )
        return 'TxIn({}, {}, {}, {}, {})'.format(
            repr(self.script_sig), repr(self.script_sig_len), repr(self.txid), repr(self.txindex), repr(self.sequence)
        )

    def __bytes__(self):
        return b''.join([self.txid, self.txindex, self.script_sig_len, self.script_sig, self.sequence])

    def is_segwit(self):
        return self.segwit_input or self.witness class TxOut:
    __slots__ = ('amount', 'script_pubkey_len', 'script_pubkey')

    def __init__(self, amount, script_pubkey):
        self.amount = amount
        self.script_pubkey = script_pubkey
        self.script_pubkey_len = int_to_varint(len(script_pubkey))

    def __eq__(self, other):
        return (
            self.amount == other.amount
            and self.script_pubkey == other.script_pubkey
            and self.script_pubkey_len == other.script_pubkey_len
        )

    def __repr__(self):
        return 'TxOut({}, {}, {})'.format(repr(self.amount), repr(self.script_pubkey), repr(self.script_pubkey_len))

    def __bytes__(self):
        return b''.join([self.amount, self.script_pubkey_len, self.script_pubkey]) class TxObj:
    __slots__ = ('version', 'TxIn', 'TxOut', 'locktime')

    def __init__(self, version, TxIn, TxOut, locktime):
        segwit_tx = any([i.segwit_input or i.witness for i in TxIn])
        self.version = version
        self.TxIn = TxIn
        if segwit_tx:
            for i in self.TxIn:
                i.witness = i.witness if i.witness else b'\x00'
        self.TxOut = TxOut
        self.locktime = locktime

    def __eq__(self, other):
        return (
            self.version == other.version
            and self.TxIn == other.TxIn
            and self.TxOut == other.TxOut
            and self.locktime == other.locktime
        )

    def __repr__(self):
        return 'TxObj({}, {}, {}, {})'.format(
            repr(self.version), repr(self.TxIn), repr(self.TxOut), repr(self.locktime)
        )

    def __bytes__(self):
        inp = int_to_varint(len(self.TxIn)) + b''.join(map(bytes, self.TxIn))
        out = int_to_varint(len(self.TxOut)) + b''.join(map(bytes, self.TxOut))
        wit = b''.join([w.witness for w in self.TxIn])
        return b''.join([self.version, MARKER if wit else b'', FLAG if wit else b'', inp, out, wit, self.locktime])

    def legacy_repr(self):
        inp = int_to_varint(len(self.TxIn)) + b''.join(map(bytes, self.TxIn))
        out = int_to_varint(len(self.TxOut)) + b''.join(map(bytes, self.TxOut))
        return b''.join([self.version, inp, out, self.locktime])

    def to_hex(self):
        return bytes_to_hex(bytes(self))

    @classmethod
    def is_segwit(cls, tx):
        if isinstance(tx, cls):
            tx = bytes(tx)
        elif not isinstance(tx, bytes):
            tx = hex_to_bytes(tx)
        return tx[4:6] == MARKER + FLAG def calc_txid(tx_hex):
    tx_obj = deserialize(tx_hex)
    return bytes_to_hex(double_sha256(tx_obj.legacy_repr())[::-1]) def create_new_transaction(private_key, unspents, outputs):

    version = VERSION_1
    lock_time = LOCK_TIME
    outputs = construct_outputs(outputs)

    # Optimize for speed, not memory, by pre-computing values.
    inputs = []
    for unspent in unspents:
        script_sig = b''  # empty scriptSig for new unsigned transaction.
        txid = hex_to_bytes(unspent.txid)[::-1]
        txindex = unspent.txindex.to_bytes(4, byteorder='little')
        amount = int(unspent.amount).to_bytes(8, byteorder='little')
        sequence = unspent.sequence.to_bytes(4, byteorder='little')
        inputs.append(TxIn(script_sig, txid, txindex, amount=amount, segwit_input=unspent.segwit,
                           sequence=sequence))

    tx_unsigned = TxObj(version, inputs, outputs, lock_time)

    tx = sign_tx(private_key, tx_unsigned, unspents=unspents)
    return tx def construct_outputs(outputs):
    outputs_obj = []

    for data in outputs:
        dest, amount = data

        # P2PKH/P2SH/Bech32
        if amount:
            script_pubkey = address_to_scriptpubkey(dest)

            amount = amount.to_bytes(8, byteorder='little')

        # Blockchain storage
        else:
            script_pubkey = OP_RETURN + len(dest).to_bytes(1, byteorder='little') + dest

            amount = b'\x00\x00\x00\x00\x00\x00\x00\x00'

        outputs_obj.append(TxOut(amount, script_pubkey))

    return outputs_obj def deserialize(tx):
    if isinstance(tx, str) and re.match('^[0-9a-fA-F]*$', tx):
        return deserialize(hex_to_bytes(tx))

    segwit_tx = TxObj.is_segwit(tx)

    version, tx = read_bytes(tx, 4)

    if segwit_tx:
        _, tx = read_bytes(tx, 1)  # ``marker`` is nulled
        _, tx = read_bytes(tx, 1)  # ``flag`` is nulled

    ins, tx = read_var_int(tx)
    inputs = []
    for i in range(ins):
        txid, tx = read_bytes(tx, 32)
        txindex, tx = read_bytes(tx, 4)
        script_sig, tx = read_var_string(tx)
        sequence, tx = read_bytes(tx, 4)
        inputs.append(TxIn(script_sig, txid, txindex, sequence=sequence))

    outs, tx = read_var_int(tx)
    outputs = []
    for _ in range(outs):
        amount, tx = read_bytes(tx, 8)
        script_pubkey, tx = read_var_string(tx)
        outputs.append(TxOut(amount, script_pubkey))

    if segwit_tx:
        for i in range(ins):
            wnum, tx = read_var_int(tx)
            witness = int_to_varint(wnum)
            for _ in range(wnum):
                w, tx = read_segwit_string(tx)
                witness += w
            inputs[i].witness = witness

    locktime, _ = read_bytes(tx, 4)

    txobj = TxObj(version, inputs, outputs, locktime)

    return txobj def estimate_tx_fee(in_size, n_in, out_size, n_out, satoshis, segwit=False):

    if not satoshis:
        return 0

    estimated_size = math.ceil(
        in_size
        + len(int_to_unknown_bytes(n_in, byteorder='little'))
        + out_size
        + len(int_to_unknown_bytes(n_out, byteorder='little'))
        + 8
        # Accounting for magic header vBytes ('0001') 
        + (0.5 if segwit else 0)
    )

    estimated_fee = estimated_size * satoshis

    logging.debug('Estimated fee: {} satoshis for {} bytes'.format(estimated_fee, estimated_size))

    return estimated_fee def sanitize_tx_data(
    unspents,
    outputs,
    fee,
    leftover,
    combine=True,
    message=None,
    compressed=True,
    absolute_fee=False,
    min_change=0,
    version='main',
    message_is_hex=False,
    replace_by_fee=False
):
    """
    sanitize_tx_data()

    fee is in satoshis per byte.
    """

    outputs = outputs.copy()

    for i, output in enumerate(outputs):
        dest, amount, currency = output
        outputs[i] = (dest, currency_to_satoshi_cached(amount, currency))

    if not unspents:
        raise ValueError('Transactions must have at least one unspent.')

    # Temporary storage so all outputs precede messages.
    messages = []

    if message:
        if message_is_hex:
            message_chunks = chunk_data(message, MESSAGE_LIMIT)
        else:
            message_chunks = chunk_data(message.encode('utf-8'), MESSAGE_LIMIT)

        for message in message_chunks:
            messages.append((message, 0))

    # Include return address in output count.
    # Calculate output size as a list (including return address).
    output_size = [len(address_to_scriptpubkey(o[0])) + 9 for o in outputs]
    output_size.append(len(messages) * (MESSAGE_LIMIT + 9))
    output_size.append(len(address_to_scriptpubkey(leftover)) + 9)
    sum_outputs = sum(out[1] for out in outputs)

    # Use Branch-and-Bound for coin selection:
    unspents[:], remaining = select_coins(
        sum_outputs,
        fee,
        output_size,
        min_change=min_change,
        absolute_fee=absolute_fee,
        consolidate=combine,
        unspents=unspents,
    )

    if replace_by_fee:
        for unspent in unspents:
            unspent.opt_in_for_RBF()

    if remaining > 0:
        outputs.append((leftover, remaining))

    # Sanity check: If spending from main-/testnet, then all output addresses must also be for main-/testnet.
    for output in outputs:
        dest, amount = output
        vs = get_version(dest)
        if vs and vs != version:
            raise ValueError('Cannot send to ' + vs + 'net address when spending from a ' + version + 'net address.')

    outputs.extend(messages)

    return unspents, outputs def select_coins(target, fee, output_size, min_change, *, absolute_fee=False, consolidate=False, unspents):
    '''
    Implementation of Branch-and-Bound coin selection defined in Erhart's
    Master's thesis An Evaluation of Coin Selection Strategies here:
    http://murch.one/wp-content/uploads/2016/11/erhardt2016coinselection.pdf

    :param target: The total amount of the outputs in a transaction for which
                   we try to select the inputs to spend.
    :type target: ``int``
    :param fee: The number of satoshi per byte for the fee of the transaction.
    :type fee: ``int``
    :param output_size: A list containing as int the sizes of each output.
    :type output_size: ``list`` of ``int`
    :param min_change: The minimum amount of satoshis allowed for the
                       return/change address if there is no perfect match.
    :type min_change: ``int``
    :param absolute_fee: Whether or not the parameter ``fee`` should be
                         repurposed to denote the exact fee amount.
    :type absolute_fee: ``bool``
    :param consolidate: Whether or not the Branch-and-Bound process for finding
                        a perfect match should be skipped and all unspents
                        used directly.
    :type consolidate: ``bool``
    :param unspents: The UTXOs to use as inputs.
    :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
    :raises InsufficientFunds: If ``unspents`` does not contain enough balance
                               to allow spending matching the target.
    '''

    # The maximum number of tries for Branch-and-Bound:
    BNB_TRIES = 1000000

    # COST_OF_OVERHEAD excludes the return address of output_size (last element).
    COST_OF_OVERHEAD = (8 + sum(output_size[:-1]) + 1) * fee

    def branch_and_bound(d, selected_coins, effective_value, target, fee, sorted_unspents):  # pragma: no cover

        nonlocal COST_OF_OVERHEAD, BNB_TRIES
        BNB_TRIES -= 1
        COST_PER_INPUT = 148 * fee  # Just typical estimate values
        COST_PER_OUTPUT = 34 * fee

        # The target we want to match includes cost of overhead for transaction
        target_to_match = target + COST_OF_OVERHEAD
        # Allowing to pay fee for a whole input and output is rationally
        # correct, but increases the fee-rate dramatically for only few inputs.
        match_range = COST_PER_INPUT + COST_PER_OUTPUT
        # We could allow to spend up to X% more on the fees if we can find a
        # perfect match:
        # match_range += int(0.1 * fee * sum(u.vsize for u in selected_coins))

        # Check for solution and cut criteria:
        if effective_value > target_to_match + match_range:
            return []
        elif effective_value >= target_to_match:
            return selected_coins
        elif BNB_TRIES <= 0:
            return []
        elif d >= len(sorted_unspents):
            return []
        else:
            # Randomly explore next branch:
            binary_random = randint(0, 1)
            if binary_random:
                # Explore inclusion branch first, else omission branch:
                effective_value_new = effective_value + sorted_unspents[d].amount - fee * sorted_unspents[d].vsize

                with_this = branch_and_bound(
                    d + 1, selected_coins + [sorted_unspents[d]], effective_value_new, target, fee, sorted_unspents
                )

                if with_this != []:
                    return with_this
                else:
                    without_this = branch_and_bound(
                        d + 1, selected_coins, effective_value, target, fee, sorted_unspents
                    )

                    return without_this

            else:
                # As above but explore omission branch first:
                without_this = branch_and_bound(d + 1, selected_coins, effective_value, target, fee, sorted_unspents)

                if without_this != []:
                    return without_this
                else:
                    effective_value_new = effective_value + sorted_unspents[d].amount - fee * sorted_unspents[d].vsize

                    with_this = branch_and_bound(
                        d + 1, selected_coins + [sorted_unspents[d]], effective_value_new, target, fee, sorted_unspents
                    )

                    return with_this

    sorted_unspents = sorted(unspents, key=lambda u: u.amount, reverse=True)
    selected_coins = []

    if not consolidate and not absolute_fee:
        # Trying to find a perfect match using Branch-and-Bound:
        selected_coins = branch_and_bound(
            d=0, selected_coins=[], effective_value=0, target=target, fee=fee, sorted_unspents=sorted_unspents
        )
        remaining = 0

    # Fallback: If no match, Single Random Draw with return address:
    if selected_coins == []:
        unspents = unspents.copy()
        # Since we have no information on the user's spending habit it is
        # best practice to randomly select UTXOs until we have enough.
        if not consolidate:
            # To have a deterministic way of inserting inputs when
            # consolidating, we only shuffle the unspents otherwise.
            shuffle(unspents)
        while unspents:
            selected_coins.append(unspents.pop(0))
            estimated_fee = estimate_tx_fee(
                sum(u.vsize for u in selected_coins), len(selected_coins), sum(output_size), len(output_size), fee, any(u.segwit for u in selected_coins)
            )
            estimated_fee = fee if absolute_fee else estimated_fee
            remaining = sum(u.amount for u in selected_coins) - target - estimated_fee
            if remaining >= min_change and (not consolidate or len(unspents) == 0):
                break
        else:
            raise InsufficientFunds(
                'Balance {} is less than {} (including '
                'fee).'.format(sum(u.amount for u in selected_coins), target + min_change + estimated_fee)
            )

    return selected_coins, remaining 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 def calculate_preimages(tx_obj, inputs_parameters):
    """Calculates preimages for provided transaction structure and input
    values.

    :param tx_obj: The transaction object used to calculate preimage from using
                   a transaction digest algorithm, such as BIP-143 for Segwit
                   inputs. This transaction object must hence have scriptCodes
                   filled into the corresponding scriptSigs in the inputs.
    :type tx_obj: :object:`~bit.transaction.TxObj`
    :param inputs_parameters: A list of tuples with input index as integer,
                              hash type as integer and a boolean flag to denote
                              if the input is spending from a Segwit output.
                              For example: [(0, 1, True), (2, 1, False), (...)]
    :type inputs_parameters: A `list` of `tuple`
    """

    # Tx object data:
    input_count = int_to_varint(len(tx_obj.TxIn))
    output_count = int_to_varint(len(tx_obj.TxOut))
    output_block = b''.join([bytes(o) for o in tx_obj.TxOut])

    hashPrevouts = double_sha256(b''.join([i.txid + i.txindex for i in tx_obj.TxIn]))
    hashSequence = double_sha256(b''.join([i.sequence for i in tx_obj.TxIn]))
    hashOutputs = double_sha256(output_block)

    preimages = []
    for input_index, hash_type, segwit_input in inputs_parameters:
        # We can only handle hashType == 1:
        if hash_type != HASH_TYPE:
            raise ValueError('Bit only support hashType of value 1.')
        # Calculate prehashes:
        if segwit_input:
            # BIP-143 preimage:
            hashed = sha256(
                tx_obj.version
                + hashPrevouts
                + hashSequence
                + tx_obj.TxIn[input_index].txid
                + tx_obj.TxIn[input_index].txindex
                + tx_obj.TxIn[input_index].script_sig_len
                + tx_obj.TxIn[input_index].script_sig  # scriptCode length
                + tx_obj.TxIn[input_index].sequence  # scriptCode (includes amount)
                + hashOutputs
                + tx_obj.locktime
                + hash_type
            )
        else:
            hashed = sha256(
                tx_obj.version
                + input_count
                + b''.join(ti.txid + ti.txindex + OP_0 + ti.sequence for ti in islice(tx_obj.TxIn, input_index))
                + tx_obj.TxIn[input_index].txid
                + tx_obj.TxIn[input_index].txindex
                + tx_obj.TxIn[input_index].script_sig_len
                + tx_obj.TxIn[input_index].script_sig  # scriptCode length
                + tx_obj.TxIn[input_index].sequence  # scriptCode
                + b''.join(
                    ti.txid + ti.txindex + OP_0 + ti.sequence for ti in islice(tx_obj.TxIn, input_index + 1, None)
                )
                + output_count
                + output_block
                + tx_obj.locktime
                + hash_type
            )
        preimages.append(hashed)
    return preimages def sign_tx(private_key, tx, *, unspents):
    """Signs inputs in provided transaction object for which unspents
    are provided and can be signed by the private key.

    :param private_key: Private key
    :type private_key: ``PrivateKey`` or ``MultiSig``
    :param tx: Transaction object
    :type tx: ``TxObj``
    :param unspents: For inputs to be signed their corresponding Unspent objects
                     must be provided.
    :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
    :returns: The signed transaction as hex.
    :rtype: ``str``
    """

    # input_dict contains those unspents that can be signed by private_key,
    # providing additional information for segwit-inputs (the amount to spend)
    input_dict = {}
    try:
        for unspent in unspents:
            if not private_key.can_sign_unspent(unspent):
                continue
            tx_input = hex_to_bytes(unspent.txid)[::-1] + unspent.txindex.to_bytes(4, byteorder='little')
            input_dict[tx_input] = unspent.to_dict()
    except TypeError:
        raise TypeError(
            'Please provide as unspents at least all inputs to be signed with the function call in a list.'
        )

    # Determine input indices to sign from input_dict (allows for transaction batching)
    sign_inputs = [j for j, i in enumerate(tx.TxIn) if i.txid + i.txindex in input_dict]

    segwit_tx = TxObj.is_segwit(tx)
    public_key = private_key.public_key
    public_key_push = script_push(len(public_key))
    hash_type = HASH_TYPE

    # Make input parameters for preimage calculation
    inputs_parameters = []

    # The TxObj in `tx` will below be modified to contain the scriptCodes used
    # for the transaction structure to be signed

    # `input_script_field` copies the scriptSigs for partially signed
    # transactions to later extract signatures from it:
    input_script_field = [tx.TxIn[i].script_sig for i in range(len(tx.TxIn))]

    for i in sign_inputs:
        # Create transaction object for preimage calculation
        tx_input = tx.TxIn[i].txid + tx.TxIn[i].txindex
        segwit_input = input_dict[tx_input]['segwit']
        tx.TxIn[i].segwit_input = segwit_input

        script_code = private_key.scriptcode
        script_code_len = int_to_varint(len(script_code))

        # Use scriptCode for preimage calculation of transaction object:
        tx.TxIn[i].script_sig = script_code
        tx.TxIn[i].script_sig_len = script_code_len

        if segwit_input:
            try:
                tx.TxIn[i].script_sig += input_dict[tx_input]['amount'].to_bytes(8, byteorder='little')

                # For partially signed Segwit transactions the signatures must
                # be extracted from the witnessScript field:
                input_script_field[i] = tx.TxIn[i].witness
            except AttributeError:
                raise ValueError(
                    'Cannot sign a segwit input when the input\'s amount is '
                    'unknown. Maybe no network connection or the input is '
                    'already spent? Then please provide all inputs to sign as '
                    '`Unspent` objects to the function call.'
                )

        inputs_parameters.append([i, hash_type, segwit_input])
    preimages = calculate_preimages(tx, inputs_parameters)

    # Calculate signature scripts:
    for hash, (i, _, segwit_input) in zip(preimages, inputs_parameters):
        signature = private_key.sign(hash) + b'\x01'

        # ------------------------------------------------------------------
        if private_key.instance == 'MultiSig' or private_key.instance == 'MultiSigTestnet':
            # P2(W)SH input

            script_blob = b''
            sigs = {}
            # Initial number of witness items (OP_0 + one signature + redeemscript).
            witness_count = 3
            if input_script_field[i]:
                sig_list = get_signatures_from_script(input_script_field[i])
                # Bitcoin Core convention: Every missing signature is denoted
                # by 0x00. Only used for already partially-signed scriptSigs:
                script_blob += b'\x00' * (private_key.m - len(sig_list) - 1)
                # Total number of witness items when partially or fully signed:
                witness_count = private_key.m + 2
                # For a partially signed input make a dictionary containing
                # all the provided signatures with public-keys as keys:
                for sig in sig_list:
                    for pub in private_key.public_keys:
                        if verify_sig(sig[:-1], hash, pub):
                            # If we already found a valid signature for pubkey
                            # we just overwrite it and don't care.
                            sigs[pub] = sig
                if len(sigs) >= private_key.m:
                    raise ValueError('Transaction is already signed with sufficiently needed signatures.')

            sigs[public_key] = signature

            witness = b''
            # Sort ingthe signatures according to the public-key list:
            for pub in private_key.public_keys:
                if pub in sigs:
                    sig = sigs[pub]
                    length = int_to_varint(len(sig)) if segwit_input else script_push(len(sig))
                    witness += length + sig

            script_sig = b'\x22' + private_key.segwit_scriptcode

            witness = (int_to_varint(witness_count) if segwit_input else b'') + b'\x00' + witness + script_blob
            witness += (
                int_to_varint(len(private_key.redeemscript))
                if segwit_input
                else script_push(len(private_key.redeemscript))
            ) + private_key.redeemscript

            script_sig = script_sig if segwit_input else witness
            witness = witness if segwit_input else b'\x00' if segwit_tx else b''

        # ------------------------------------------------------------------
        else:
            # P2(W)PKH input

            script_sig = b'\x16' + private_key.segwit_scriptcode

            witness = (
                (b'\x02' if segwit_input else b'')
                + len(signature).to_bytes(1, byteorder='little')  # witness counter
                + signature
                + public_key_push
                + public_key
            )

            script_sig = script_sig if segwit_input else witness
            witness = witness if segwit_input else b'\x00' if segwit_tx else b''

        # Providing the signature(s) to the input
        tx.TxIn[i].script_sig = script_sig
        tx.TxIn[i].script_sig_len = int_to_varint(len(script_sig))
        tx.TxIn[i].witness = witness

    return tx.to_hex() def hex_to_bytes(hexed):

    if len(hexed) & 1:
        hexed = '0' + hexed

    return bytes.fromhex(hexed) def get_signatures_from_script(script):
    """Returns a list of signatures retrieved from the provided (partially)
    signed multisig scriptSig.

    :param script: The partially-signed multisig scriptSig.
    :type script: ``bytes``
    :returns: A list of retrieved signature from the provided scriptSig.
    :rtype: A ``list`` of ``bytes`` signatures
    """

    script = script[1:]  # remove the first OP_0
    sigs = []
    while len(script) > 0:
        # Consume script while extracting possible signatures:
        val, script = read_var_int(script)
        potential_sig, script = read_bytes(script, val)
        try:
            # Raises ValueError if argument to `der_to_cdata` is not a
            # DER-encoding of a signature (without the appended SIGHASH).
            der_to_cdata(potential_sig[:-1])
            # We only add if DER-encoded signature:
            sigs.append(potential_sig)
        except ValueError:
            pass
    return sigs class PrivateKey(BaseKey):
    """This class represents a Bitcoin private key. ``Key`` is an alias.

    :param wif: A private key serialized to the Wallet Import Format. If the
                argument is not supplied, a new private key will be created.
                The WIF compression flag will be adhered to, but the version
                byte is disregarded. Compression will be used by all new keys.
    :type wif: ``str``
    :raises TypeError: If ``wif`` is not a ``str``.
    """

    def __init__(self, wif=None):
        super().__init__(wif=wif)

        self.version = 'main'
        self.instance = 'PrivateKey'

        self._address = None
        self._segwit_address = None
        self._scriptcode = None
        self._segwit_scriptcode = None

        self.balance = 0
        self.unspents = []
        self.transactions = []

    @property
    def address(self):
        """The public address you share with others to receive funds."""
        if self._address is None:
            self._address = public_key_to_address(self._public_key, version=self.version)
        return self._address

    @property
    def segwit_address(self):
        """The public segwit nested in P2SH address you share with others to
        receive funds."""
        # Only make segwit address if public key is compressed
        if self._segwit_address is None and self.is_compressed():
            self._segwit_address = public_key_to_segwit_address(self._public_key, version=self.version)
        return self._segwit_address

    @property
    def scriptcode(self):
        self._scriptcode = address_to_scriptpubkey(self.address)
        return self._scriptcode

    @property
    def segwit_scriptcode(self):
        self._segwit_scriptcode = OP_0 + OP_PUSH_20 + ripemd160_sha256(self.public_key)
        return self._segwit_scriptcode

    def can_sign_unspent(self, unspent):
        script = bytes_to_hex(address_to_scriptpubkey(self.address))
        if self.segwit_address:
            segwit_script = bytes_to_hex(address_to_scriptpubkey(self.segwit_address))
            return unspent.script == script or unspent.script == segwit_script
        else:
            return unspent.script == script

    def to_wif(self):
        return bytes_to_wif(self._pk.secret, version=self.version, compressed=self.is_compressed())

    def balance_as(self, currency):
        """Returns your balance as a formatted string in a particular currency.

        :param currency: One of the :ref:`supported currencies`.
        :type currency: ``str``
        :rtype: ``str``
        """
        return satoshi_to_currency_cached(self.balance, currency)

    def get_balance(self, currency='satoshi'):
        """Fetches the current balance by calling
        :func:`~bit.PrivateKey.get_unspents` and returns it using
        :func:`~bit.PrivateKey.balance_as`.

        :param currency: One of the :ref:`supported currencies`.
        :type currency: ``str``
        :rtype: ``str``
        """
        self.get_unspents()
        return self.balance_as(currency)

    def get_unspents(self):
        """Fetches all available unspent transaction outputs.

        :rtype: ``list`` of :class:`~bit.network.meta.Unspent`
        """
        self.unspents[:] = list(
            map(
                lambda u: u.set_type('p2pkh' if self.is_compressed() else 'p2pkh-uncompressed'),
                NetworkAPI.get_unspent(self.address),
            )
        )
        if self.segwit_address:
            self.unspents += list(map(lambda u: u.set_type('np2wkh'), NetworkAPI.get_unspent(self.segwit_address)))
        self.balance = sum(unspent.amount for unspent in self.unspents)
        return self.unspents

    def get_transactions(self):
        """Fetches transaction history.

        :rtype: ``list`` of ``str`` transaction IDs
        """
        self.transactions[:] = NetworkAPI.get_transactions(self.address)
        if self.segwit_address:
            self.transactions += NetworkAPI.get_transactions(self.segwit_address)
        return self.transactions

    def create_transaction(
        self,
        outputs,
        fee=None,
        absolute_fee=False,
        leftover=None,
        combine=True,
        message=None,
        unspents=None,
        message_is_hex=False,
        replace_by_fee=False
    ):  # pragma: no cover
        """Creates a signed P2PKH transaction.

        :param outputs: A sequence of outputs you wish to send in the form
                        ``(destination, amount, currency)``. The amount can
                        be either an int, float, or string as long as it is
                        a valid input to ``decimal.Decimal``. The currency
                        must be :ref:`supported <supported currencies>`.
        :type outputs: ``list`` of ``tuple``
        :param fee: The number of satoshi per byte to pay to miners. By default
                    Bit will poll `<https://bitcoinfees.earn.com>`_ and use a fee
                    that will allow your transaction to be confirmed as soon as
                    possible.
        :type fee: ``int``
        :param leftover: The destination that will receive any change from the
                         transaction. By default Bit will send any change to
                         the same address you sent from.
        :type leftover: ``str``
        :param combine: Whether or not Bit should use all available UTXOs to
                        make future transactions smaller and therefore reduce
                        fees. By default Bit will consolidate UTXOs. Note: When
                        setting :param absolute_fee: this is ignored.
        :type combine: ``bool``
        :param message: A message to include in the transaction. This will be
                        stored in the blockchain forever. Due to size limits,
                        each message will be stored in chunks of 40 bytes.
        :type message: ``str``
        :param unspents: The UTXOs to use as the inputs. By default Bit will
                         communicate with the blockchain itself.
        :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
        :param replace_by_fee: Whether to opt-in for replace-by-fee (BIP 125).
        :type replace_by_fee: ``bool``
        :returns: The signed transaction as hex.
        :rtype: ``str``
        """
        try:
            unspents = unspents or self.get_unspents()
        except ConnectionError:
            raise ConnectionError('All APIs are unreachable. Please provide the unspents to spend from directly.')

        # If at least one input is from segwit the return address is for segwit
        return_address = self.segwit_address if any([u.segwit for u in unspents]) else self.address

        unspents, outputs = sanitize_tx_data(
            unspents,
            outputs,
            fee or get_fee_cached(),
            leftover or return_address,
            combine=combine,
            message=message,
            absolute_fee=absolute_fee,
            version=self.version,
            message_is_hex=message_is_hex,
            replace_by_fee=replace_by_fee
        )

        return create_new_transaction(self, unspents, outputs)

    def send(
        self,
        outputs,
        fee=None,
        absolute_fee=False,
        leftover=None,
        combine=True,
        message=None,
        unspents=None,
        message_is_hex=False,
        replace_by_fee=False
    ):  # pragma: no cover
        """Creates a signed P2PKH transaction and attempts to broadcast it on
        the blockchain. This accepts the same arguments as
        :func:`~bit.PrivateKey.create_transaction`.

        :param outputs: A sequence of outputs you wish to send in the form
                        ``(destination, amount, currency)``. The amount can
                        be either an int, float, or string as long as it is
                        a valid input to ``decimal.Decimal``. The currency
                        must be :ref:`supported <supported currencies>`.
        :type outputs: ``list`` of ``tuple``
        :param fee: The number of satoshi per byte to pay to miners. By default
                    Bit will poll `<https://bitcoinfees.earn.com>`_ and use a fee
                    that will allow your transaction to be confirmed as soon as
                    possible.
        :type fee: ``int``
        :param leftover: The destination that will receive any change from the
                         transaction. By default Bit will send any change to
                         the same address you sent from.
        :type leftover: ``str``
        :param combine: Whether or not Bit should use all available UTXOs to
                        make future transactions smaller and therefore reduce
                        fees. By default Bit will consolidate UTXOs. Note: When
                        setting :param absolute_fee: this is ignored.
        :type combine: ``bool``
        :param message: A message to include in the transaction. This will be
                        stored in the blockchain forever. Due to size limits,
                        each message will be stored in chunks of 40 bytes.
        :type message: ``str``
        :param unspents: The UTXOs to use as the inputs. By default Bit will
                         communicate with the blockchain itself.
        :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
        :param replace_by_fee: Whether to opt-in for replace-by-fee (BIP 125).
        :type replace_by_fee: ``bool``
        :returns: The transaction ID.
        :rtype: ``str``
        """

        tx_hex = self.create_transaction(
            outputs,
            fee=fee,
            absolute_fee=absolute_fee,
            leftover=leftover,
            combine=combine,
            message=message,
            unspents=unspents,
            message_is_hex=message_is_hex,
            replace_by_fee=replace_by_fee
        )

        NetworkAPI.broadcast_tx(tx_hex)

        return calc_txid(tx_hex)

    @classmethod
    def prepare_transaction(
        cls,
        address,
        outputs,
        compressed=True,
        fee=None,
        absolute_fee=False,
        leftover=None,
        combine=True,
        message=None,
        unspents=None,
        message_is_hex=False,
        replace_by_fee=False
    ):  # pragma: no cover
        """Prepares a P2PKH transaction for offline signing.

        :param address: The address the funds will be sent from.
        :type address: ``str``
        :param outputs: A sequence of outputs you wish to send in the form
                        ``(destination, amount, currency)``. The amount can
                        be either an int, float, or string as long as it is
                        a valid input to ``decimal.Decimal``. The currency
                        must be :ref:`supported <supported currencies>`.
        :type outputs: ``list`` of ``tuple``
        :param compressed: Whether or not the ``address`` corresponds to a
                           compressed public key. This influences the fee.
        :type compressed: ``bool``
        :param fee: The number of satoshi per byte to pay to miners. By default
                    Bit will poll `<https://bitcoinfees.earn.com>`_ and use a fee
                    that will allow your transaction to be confirmed as soon as
                    possible.
        :type fee: ``int``
        :param leftover: The destination that will receive any change from the
                         transaction. By default Bit will send any change to
                         the same address you sent from.
        :type leftover: ``str``
        :param combine: Whether or not Bit should use all available UTXOs to
                        make future transactions smaller and therefore reduce
                        fees. By default Bit will consolidate UTXOs. Note: When
                        setting :param absolute_fee: this is ignored.
        :type combine: ``bool``
        :param message: A message to include in the transaction. This will be
                        stored in the blockchain forever. Due to size limits,
                        each message will be stored in chunks of 40 bytes.
        :type message: ``str``
        :param unspents: The UTXOs to use as the inputs. By default Bit will
                         communicate with the blockchain itself.
        :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
        :param replace_by_fee: Whether to opt-in for replace-by-fee (BIP 125).
        :type replace_by_fee: ``bool``
        :returns: JSON storing data required to create an offline transaction.
        :rtype: ``str``
        """
        unspents, outputs = sanitize_tx_data(
            unspents or NetworkAPI.get_unspent(address),
            outputs,
            fee or get_fee_cached(),
            leftover or address,
            combine=combine,
            message=message,
            absolute_fee=absolute_fee,
            version='main',
            message_is_hex=message_is_hex,
            replace_by_fee=replace_by_fee
        )

        data = {'unspents': [unspent.to_dict() for unspent in unspents], 'outputs': outputs}

        return json.dumps(data, separators=(',', ':'))

    def sign_transaction(self, tx_data, unspents=None):  # pragma: no cover
        """Creates a signed P2PKH transaction using previously prepared
        transaction data.

        :param tx_data: Hex-encoded transaction or output of :func:`~bit.Key.prepare_transaction`.
        :type tx_data: ``str``
        :param unspents: The UTXOs to use as the inputs. By default Bit will
                         communicate with the blockchain itself.
        :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
        :returns: The signed transaction as hex.
        :rtype: ``str``
        """
        try:  # Json-tx-data from :func:`~bit.Key.prepare_transaction`
            data = json.loads(tx_data)
            assert unspents is None

            unspents = [Unspent.from_dict(unspent) for unspent in data['unspents']]
            outputs = data['outputs']

            return create_new_transaction(self, unspents, outputs)
        except:  # May be hex-encoded transaction using batching:
            try:
                unspents = unspents or self.get_unspents()
            except ConnectionError:
                raise ConnectionError(
                    'All APIs are unreachable. Please provide the unspent '
                    'inputs as unspents directly to sign this transaction.'
                )

            tx_data = deserialize(tx_data)
            return sign_tx(self, tx_data, unspents=unspents)

    @classmethod
    def from_hex(cls, hexed):
        """
        :param hexed: A private key previously encoded as hex.
        :type hexed: ``str``
        :rtype: :class:`~bit.PrivateKey`
        """
        return PrivateKey(ECPrivateKey.from_hex(hexed))

    @classmethod
    def from_bytes(cls, bytestr):
        """
        :param bytestr: A private key previously encoded as hex.
        :type bytestr: ``bytes``
        :rtype: :class:`~bit.PrivateKey`
        """
        return PrivateKey(ECPrivateKey(bytestr))

    @classmethod
    def from_der(cls, der):
        """
        :param der: A private key previously encoded as DER.
        :type der: ``bytes``
        :rtype: :class:`~bit.PrivateKey`
        """
        return PrivateKey(ECPrivateKey.from_der(der))

    @classmethod
    def from_pem(cls, pem):
        """
        :param pem: A private key previously encoded as PEM.
        :type pem: ``bytes``
        :rtype: :class:`~bit.PrivateKey`
        """
        return PrivateKey(ECPrivateKey.from_pem(pem))

    @classmethod
    def from_int(cls, num):
        """
        :param num: A private key in raw integer form.
        :type num: ``int``
        :rtype: :class:`~bit.PrivateKey`
        """
        return PrivateKey(ECPrivateKey.from_int(num))

    def __repr__(self):
        return '<PrivateKey: {}>'.format(self.address) class PrivateKeyTestnet(BaseKey):
    """This class represents a testnet Bitcoin private key. **Note:** coins
    on the test network have no monetary value!

    :param wif: A private key serialized to the Wallet Import Format. If the
                argument is not supplied, a new private key will be created.
                The WIF compression flag will be adhered to, but the version
                byte is disregarded. Compression will be used by all new keys.
    :type wif: ``str``
    :raises TypeError: If ``wif`` is not a ``str``.
    """

    def __init__(self, wif=None):
        super().__init__(wif=wif)

        self.version = 'test'
        self.instance = 'PrivateKeyTestnet'

        self._address = None
        self._segwit_address = None
        self._scriptcode = None
        self._segwit_scriptcode = None

        self.balance = 0
        self.unspents = []
        self.transactions = []

    @property
    def address(self):
        """The public address you share with others to receive funds."""
        if self._address is None:
            self._address = public_key_to_address(self._public_key, version=self.version)
        return self._address

    @property
    def segwit_address(self):
        """The public segwit nested in P2SH address you share with others to
        receive funds."""
        # Only make segwit address if public key is compressed
        if self._segwit_address is None and self.is_compressed():
            self._segwit_address = public_key_to_segwit_address(self._public_key, version=self.version)
        return self._segwit_address

    @property
    def scriptcode(self):
        self._scriptcode = address_to_scriptpubkey(self.address)
        return self._scriptcode

    @property
    def segwit_scriptcode(self):
        self._segwit_scriptcode = OP_0 + OP_PUSH_20 + ripemd160_sha256(self.public_key)
        return self._segwit_scriptcode

    def can_sign_unspent(self, unspent):
        script = bytes_to_hex(address_to_scriptpubkey(self.address))
        if self.segwit_address:
            segwit_script = bytes_to_hex(address_to_scriptpubkey(self.segwit_address))
            return unspent.script == script or unspent.script == segwit_script
        else:
            return unspent.script == script

    def to_wif(self):
        return bytes_to_wif(self._pk.secret, version=self.version, compressed=self.is_compressed())

    def balance_as(self, currency):
        """Returns your balance as a formatted string in a particular currency.

        :param currency: One of the :ref:`supported currencies`.
        :type currency: ``str``
        :rtype: ``str``
        """
        return satoshi_to_currency_cached(self.balance, currency)

    def get_balance(self, currency='satoshi'):
        """Fetches the current balance by calling
        :func:`~bit.PrivateKeyTestnet.get_unspents` and returns it using
        :func:`~bit.PrivateKeyTestnet.balance_as`.

        :param currency: One of the :ref:`supported currencies`.
        :type currency: ``str``
        :rtype: ``str``
        """
        self.get_unspents()
        return self.balance_as(currency)

    def get_unspents(self):
        """Fetches all available unspent transaction outputs.

        :rtype: ``list`` of :class:`~bit.network.meta.Unspent`
        """
        self.unspents[:] = list(
            map(
                lambda u: u.set_type('p2pkh' if self.is_compressed() else 'p2pkh-uncompressed'),
                NetworkAPI.get_unspent_testnet(self.address),
            )
        )
        if self.segwit_address:
            self.unspents += list(
                map(lambda u: u.set_type('np2wkh'), NetworkAPI.get_unspent_testnet(self.segwit_address))
            )
        self.balance = sum(unspent.amount for unspent in self.unspents)
        return self.unspents

    def get_transactions(self):
        """Fetches transaction history.

        :rtype: ``list`` of ``str`` transaction IDs
        """
        self.transactions[:] = NetworkAPI.get_transactions_testnet(self.address)
        if self.segwit_address:
            self.transactions += NetworkAPI.get_transactions_testnet(self.segwit_address)
        return self.transactions

    def create_transaction(
        self,
        outputs,
        fee=None,
        absolute_fee=False,
        leftover=None,
        combine=True,
        message=None,
        unspents=None,
        message_is_hex=False,
        replace_by_fee=False
    ):  # pragma: no cover
        """Creates a signed P2PKH transaction.

        :param outputs: A sequence of outputs you wish to send in the form
                        ``(destination, amount, currency)``. The amount can
                        be either an int, float, or string as long as it is
                        a valid input to ``decimal.Decimal``. The currency
                        must be :ref:`supported <supported currencies>`.
        :type outputs: ``list`` of ``tuple``
        :param fee: The number of satoshi per byte to pay to miners. By default
                    Bit will poll `<https://bitcoinfees.earn.com>`_ and use a fee
                    that will allow your transaction to be confirmed as soon as
                    possible.
        :type fee: ``int``
        :param leftover: The destination that will receive any change from the
                         transaction. By default Bit will send any change to
                         the same address you sent from.
        :type leftover: ``str``
        :param combine: Whether or not Bit should use all available UTXOs to
                        make future transactions smaller and therefore reduce
                        fees. By default Bit will consolidate UTXOs. Note: When
                        setting :param absolute_fee: this is ignored.
        :type combine: ``bool``
        :param message: A message to include in the transaction. This will be
                        stored in the blockchain forever. Due to size limits,
                        each message will be stored in chunks of 40 bytes.
        :type message: ``str``
        :param unspents: The UTXOs to use as the inputs. By default Bit will
                         communicate with the testnet blockchain itself.
        :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
        :param replace_by_fee: Whether to opt-in for replace-by-fee (BIP 125).
        :type replace_by_fee: ``bool``
        :returns: The signed transaction as hex.
        :rtype: ``str``
        """
        try:
            unspents = unspents or self.get_unspents()
        except ConnectionError:
            raise ConnectionError('All APIs are unreachable. Please provide the unspents to spend from directly.')

        # If at least one input is from segwit the return address is for segwit
        return_address = self.segwit_address if any([u.segwit for u in unspents]) else self.address

        unspents, outputs = sanitize_tx_data(
            unspents,
            outputs,
            fee or get_fee_cached(),
            leftover or return_address,
            combine=combine,
            message=message,
            absolute_fee=absolute_fee,
            version=self.version,
            message_is_hex=message_is_hex,
            replace_by_fee=replace_by_fee
        )

        return create_new_transaction(self, unspents, outputs)

    def send(
        self,
        outputs,
        fee=None,
        absolute_fee=False,
        leftover=None,
        combine=True,
        message=None,
        unspents=None,
        message_is_hex=False,
        replace_by_fee=False
    ):  # pragma: no cover
        """Creates a signed P2PKH transaction and attempts to broadcast it on
        the testnet blockchain. This accepts the same arguments as
        :func:`~bit.PrivateKeyTestnet.create_transaction`.

        :param outputs: A sequence of outputs you wish to send in the form
                        ``(destination, amount, currency)``. The amount can
                        be either an int, float, or string as long as it is
                        a valid input to ``decimal.Decimal``. The currency
                        must be :ref:`supported <supported currencies>`.
        :type outputs: ``list`` of ``tuple``
        :param fee: The number of satoshi per byte to pay to miners. By default
                    Bit will poll `<https://bitcoinfees.earn.com>`_ and use a fee
                    that will allow your transaction to be confirmed as soon as
                    possible.
        :type fee: ``int``
        :param leftover: The destination that will receive any change from the
                         transaction. By default Bit will send any change to
                         the same address you sent from.
        :type leftover: ``str``
        :param combine: Whether or not Bit should use all available UTXOs to
                        make future transactions smaller and therefore reduce
                        fees. By default Bit will consolidate UTXOs. Note: When
                        setting :param absolute_fee: this is ignored.
        :type combine: ``bool``
        :param message: A message to include in the transaction. This will be
                        stored in the blockchain forever. Due to size limits,
                        each message will be stored in chunks of 40 bytes.
        :type message: ``str``
        :param unspents: The UTXOs to use as the inputs. By default Bit will
                         communicate with the testnet blockchain itself.
        :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
        :param replace_by_fee: Whether to opt-in for replace-by-fee (BIP 125).
        :type replace_by_fee: ``bool``
        :returns: The transaction ID.
        :rtype: ``str``
        """

        tx_hex = self.create_transaction(
            outputs,
            fee=fee,
            absolute_fee=absolute_fee,
            leftover=leftover,
            combine=combine,
            message=message,
            unspents=unspents,
            message_is_hex=message_is_hex,
            replace_by_fee=replace_by_fee
        )

        NetworkAPI.broadcast_tx_testnet(tx_hex)

        return calc_txid(tx_hex)

    @classmethod
    def prepare_transaction(
        cls,
        address,
        outputs,
        compressed=True,
        fee=None,
        absolute_fee=False,
        leftover=None,
        combine=True,
        message=None,
        unspents=None,
        message_is_hex=False,
        replace_by_fee=False
    ):  # pragma: no cover
        """Prepares a P2PKH transaction for offline signing.

        :param address: The address the funds will be sent from.
        :type address: ``str``
        :param outputs: A sequence of outputs you wish to send in the form
                        ``(destination, amount, currency)``. The amount can
                        be either an int, float, or string as long as it is
                        a valid input to ``decimal.Decimal``. The currency
                        must be :ref:`supported <supported currencies>`.
        :type outputs: ``list`` of ``tuple``
        :param compressed: Whether or not the ``address`` corresponds to a
                           compressed public key. This influences the fee.
        :type compressed: ``bool``
        :param fee: The number of satoshi per byte to pay to miners. By default
                    Bit will poll `<https://bitcoinfees.earn.com>`_ and use a fee
                    that will allow your transaction to be confirmed as soon as
                    possible.
        :type fee: ``int``
        :param leftover: The destination that will receive any change from the
                         transaction. By default Bit will send any change to
                         the same address you sent from.
        :type leftover: ``str``
        :param combine: Whether or not Bit should use all available UTXOs to
                        make future transactions smaller and therefore reduce
                        fees. By default Bit will consolidate UTXOs. Note: When
                        setting :param absolute_fee: this is ignored.
        :type combine: ``bool``
        :param message: A message to include in the transaction. This will be
                        stored in the blockchain forever. Due to size limits,
                        each message will be stored in chunks of 40 bytes.
        :type message: ``str``
        :param unspents: The UTXOs to use as the inputs. By default Bit will
                         communicate with the blockchain itself.
        :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
        :param replace_by_fee: Whether to opt-in for replace-by-fee (BIP 125).
        :type replace_by_fee: ``bool``
        :returns: JSON storing data required to create an offline transaction.
        :rtype: ``str``
        """
        unspents, outputs = sanitize_tx_data(
            unspents or NetworkAPI.get_unspent_testnet(address),
            outputs,
            fee or get_fee_cached(),
            leftover or address,
            combine=combine,
            message=message,
            absolute_fee=absolute_fee,
            version='test',
            message_is_hex=message_is_hex,
            replace_by_fee=replace_by_fee
        )

        data = {'unspents': [unspent.to_dict() for unspent in unspents], 'outputs': outputs}

        return json.dumps(data, separators=(',', ':'))

    def sign_transaction(self, tx_data, unspents=None):  # pragma: no cover
        """Creates a signed P2PKH transaction using previously prepared
        transaction data.

        :param tx_data: Hex-encoded transaction or output of :func:`~bit.Key.prepare_transaction`.
        :type tx_data: ``str``
        :param unspents: The UTXOs to use as the inputs. By default Bit will
                         communicate with the blockchain itself.
        :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
        :returns: The signed transaction as hex.
        :rtype: ``str``
        """
        try:  # Json-tx-data from :func:`~bit.Key.prepare_transaction`
            data = json.loads(tx_data)
            assert unspents is None

            unspents = [Unspent.from_dict(unspent) for unspent in data['unspents']]
            outputs = data['outputs']

            return create_new_transaction(self, unspents, outputs)
        except:  # May be hex-encoded transaction using batching:
            try:
                unspents = unspents or self.get_unspents()
            except ConnectionError:
                raise ConnectionError(
                    'All APIs are unreachable. Please provide the unspent '
                    'inputs as unspents directly to sign this transaction.'
                )

            tx_data = deserialize(tx_data)
            return sign_tx(self, tx_data, unspents=unspents)

    @classmethod
    def from_hex(cls, hexed):
        """
        :param hexed: A private key previously encoded as hex.
        :type hexed: ``str``
        :rtype: :class:`~bit.PrivateKeyTestnet`
        """
        return PrivateKeyTestnet(ECPrivateKey.from_hex(hexed))

    @classmethod
    def from_bytes(cls, bytestr):
        """
        :param bytestr: A private key previously encoded as hex.
        :type bytestr: ``bytes``
        :rtype: :class:`~bit.PrivateKeyTestnet`
        """
        return PrivateKeyTestnet(ECPrivateKey(bytestr))

    @classmethod
    def from_der(cls, der):
        """
        :param der: A private key previously encoded as DER.
        :type der: ``bytes``
        :rtype: :class:`~bit.PrivateKeyTestnet`
        """
        return PrivateKeyTestnet(ECPrivateKey.from_der(der))

    @classmethod
    def from_pem(cls, pem):
        """
        :param pem: A private key previously encoded as PEM.
        :type pem: ``bytes``
        :rtype: :class:`~bit.PrivateKeyTestnet`
        """
        return PrivateKeyTestnet(ECPrivateKey.from_pem(pem))

    @classmethod
    def from_int(cls, num):
        """
        :param num: A private key in raw integer form.
        :type num: ``int``
        :rtype: :class:`~bit.PrivateKeyTestnet`
        """
        return PrivateKeyTestnet(ECPrivateKey.from_int(num))

    def __repr__(self):
        return '<PrivateKeyTestnet: {}>'.format(self.address) class MultiSigTestnet:
    """This class represents a testnet Bitcoin multisignature contract.
    **Note:** coins on the test network have no monetary value!

    :param private_key: A class representing a testnet private key.
    :type private_key: ``PrivateKeyTestnet``
    :raises TypeError: If ``private_key`` is not a ``PrivateKeyTestnet``.
    :param public_keys: A list or set of public keys encoded as hex or bytes
                        assigned to the multi-signature contract. If using a
                        list, then the order of the public keys will be used in
                        the contract. If using a set, then Bit will order the
                        public keys according to lexicographical order.
    :type public_keys: ``list`` or ``set`` of ``str`` or ``bytes``
    :raises TypeError: When the list ``public_keys`` does not include the public
                       key corresponding to the private key used in this class.
    :param m: The number of required signatures to spend from this multi-
              signature contract.
    :type m: ``int``
    """

    def __init__(self, private_key, public_keys, m):

        if private_key.instance != 'PrivateKeyTestnet':
            raise TypeError('MultiSigTesnet only accepts PrivateKeyTestnet class to assign a private key.')

        if bytes_to_hex(private_key.public_key) not in public_keys and private_key.public_key not in public_keys:
            raise ValueError('Private key does not match any provided public key.')

        if type(public_keys) not in (list, set):
            raise TypeError('The public keys must be provided in a list or set.')

        self.version = 'test'
        self.instance = 'MultiSigTestnet'

        self._pk = private_key
        self.public_key = private_key.public_key
        if type(public_keys) == set:
            public_keys = sorted(public_keys)
        self.public_keys = list(map(lambda k: k if type(k) == bytes else hex_to_bytes(k), public_keys))
        self.m = m
        self.redeemscript = multisig_to_redeemscript(self.public_keys, self.m)
        self.is_compressed = all(len(p) == 33 for p in self.public_keys)

        self._address = None
        self._segwit_address = None
        self._scriptcode = None
        self._segwit_scriptcode = None

        self.balance = 0
        self.unspents = []
        self.transactions = []

    @property
    def address(self):
        """The public address you share with others to receive funds."""
        if self._address is None:
            self._address = multisig_to_address(self.public_keys, self.m, version=self.version)
        return self._address

    @property
    def segwit_address(self):
        """The public segwit nested in P2SH address you share with others to
        receive funds."""
        # Only make segwit-address if all public keys are compressed
        if self._segwit_address is None and self.is_compressed is True:
            self._segwit_address = multisig_to_segwit_address(self.public_keys, self.m, version=self.version)
        return self._segwit_address

    @property
    def scriptcode(self):
        self._scriptcode = self.redeemscript
        return self._scriptcode

    @property
    def segwit_scriptcode(self):
        self._segwit_scriptcode = OP_0 + OP_PUSH_32 + sha256(self.redeemscript)
        return self._segwit_scriptcode

    def can_sign_unspent(self, unspent):
        script = bytes_to_hex(address_to_scriptpubkey(self.address))
        if self.segwit_address:
            segwit_script = bytes_to_hex(address_to_scriptpubkey(self.segwit_address))
            return unspent.script == script or unspent.script == segwit_script
        else:
            return unspent.script == script

    def sign(self, data):  # pragma: no cover
        """Signs some data which can be verified later by others using
        the public key.

        :param data: The message to sign.
        :type data: ``bytes``
        :returns: A signature compliant with BIP-62.
        :rtype: ``bytes``
        """
        return self._pk.sign(data)

    def balance_as(self, currency):
        """Returns your balance as a formatted string in a particular currency.

        :param currency: One of the :ref:`supported currencies`.
        :type currency: ``str``
        :rtype: ``str``
        """
        return satoshi_to_currency_cached(self.balance, currency)

    def get_balance(self, currency='satoshi'):
        """Fetches the current balance by calling
        :func:`~bit.MultiSig.get_unspents` and returns it using
        :func:`~bit.MultiSig.balance_as`.

        :param currency: One of the :ref:`supported currencies`.
        :type currency: ``str``
        :rtype: ``str``
        """
        self.get_unspents()
        return self.balance_as(currency)

    def get_unspents(self):
        """Fetches all available unspent transaction outputs.

        :rtype: ``list`` of :class:`~bit.network.meta.Unspent`
        """
        # P2SH size: OP_00 + m * <SIG> + <redeemScript>:
        p2sh_size = 1 + self.m * 74 + len(int_to_varint(len(self.redeemscript))) + len(self.redeemscript)
        # Adding outpoint size, scriptSig size and sequence size:
        add_p2sh_vsize = 36 + len(int_to_varint(p2sh_size)) + p2sh_size + 4
        # Converting to vSize for Segwit: outpoint size + scriptSig size + witness vSize
        add_np2wsh_vsize = 36 + 40 + (1 + p2sh_size) / 4

        self.unspents[:] = list(
            map(lambda u: u.set_type('p2sh', add_p2sh_vsize), NetworkAPI.get_unspent_testnet(self.address))
        )
        if self.segwit_address:
            self.unspents += list(
                map(
                    lambda u: u.set_type('np2wsh', add_np2wsh_vsize),
                    NetworkAPI.get_unspent_testnet(self.segwit_address),
                )
            )
        self.balance = sum(unspent.amount for unspent in self.unspents)
        return self.unspents

    def get_transactions(self):
        """Fetches transaction history.

        :rtype: ``list`` of ``str`` transaction IDs
        """
        self.transactions[:] = NetworkAPI.get_transactions_testnet(self.address)
        if self.segwit_address:
            self.transactions += NetworkAPI.get_transactions_testnet(self.segwit_address)
        return self.transactions

    def create_transaction(
        self,
        outputs,
        fee=None,
        absolute_fee=False,
        leftover=None,
        combine=True,
        message=None,
        unspents=None,
        message_is_hex=False,
        replace_by_fee=False
    ):  # pragma: no cover
        """Creates a signed P2SH transaction.

        :param outputs: A sequence of outputs you wish to send in the form
                        ``(destination, amount, currency)``. The amount can
                        be either an int, float, or string as long as it is
                        a valid input to ``decimal.Decimal``. The currency
                        must be :ref:`supported <supported currencies>`.
        :type outputs: ``list`` of ``tuple``
        :param fee: The number of satoshi per byte to pay to miners. By default
                    Bit will poll `<https://bitcoinfees.21.co>`_ and use a fee
                    that will allow your transaction to be confirmed as soon as
                    possible.
        :type fee: ``int``
        :param leftover: The destination that will receive any change from the
                         transaction. By default Bit will send any change to
                         the same address you sent from.
        :type leftover: ``str``
        :param combine: Whether or not Bit should use all available UTXOs to
                        make future transactions smaller and therefore reduce
                        fees. By default Bit will consolidate UTXOs. Note: When
                        setting :param absolute_fee: this is ignored.
        :type combine: ``bool``
        :param message: A message to include in the transaction. This will be
                        stored in the blockchain forever. Due to size limits,
                        each message will be stored in chunks of 40 bytes.
        :type message: ``str``
        :param unspents: The UTXOs to use as the inputs. By default Bit will
                         communicate with the testnet blockchain itself.
        :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
        :param replace_by_fee: Whether to opt-in for replace-by-fee (BIP 125).
        :type replace_by_fee: ``bool``
        :returns: The signed transaction as hex.
        :rtype: ``str``
        """
        try:
            unspents = unspents or self.get_unspents()
        except ConnectionError:
            raise ConnectionError('All APIs are unreachable. Please provide the unspents to spend from directly.')

        # If at least one input is from segwit the return address is for segwit
        return_address = self.segwit_address if any([u.segwit for u in unspents]) else self.address

        unspents, outputs = sanitize_tx_data(
            unspents,
            outputs,
            fee or get_fee_cached(),
            leftover or return_address,
            combine=combine,
            message=message,
            absolute_fee=absolute_fee,
            version=self.version,
            message_is_hex=message_is_hex,
            replace_by_fee=replace_by_fee
        )

        return create_new_transaction(self, unspents, outputs)

    @classmethod
    def prepare_transaction(
        cls,
        address,
        outputs,
        compressed=True,
        fee=None,
        absolute_fee=False,
        leftover=None,
        combine=True,
        message=None,
        unspents=None,
        message_is_hex=False,
        replace_by_fee=False
    ):  # pragma: no cover
        """Prepares a P2SH transaction for offline signing.

        :param address: The address the funds will be sent from.
        :type address: ``str``
        :param outputs: A sequence of outputs you wish to send in the form
                        ``(destination, amount, currency)``. The amount can
                        be either an int, float, or string as long as it is
                        a valid input to ``decimal.Decimal``. The currency
                        must be :ref:`supported <supported currencies>`.
        :type outputs: ``list`` of ``tuple``
        :param compressed: Whether or not the ``address`` corresponds to a
                           compressed public key. This influences the fee.
        :type compressed: ``bool``
        :param fee: The number of satoshi per byte to pay to miners. By default
                    Bit will poll `<https://bitcoinfees.21.co>`_ and use a fee
                    that will allow your transaction to be confirmed as soon as
                    possible.
        :type fee: ``int``
        :param leftover: The destination that will receive any change from the
                         transaction. By default Bit will send any change to
                         the same address you sent from.
        :type leftover: ``str``
        :param combine: Whether or not Bit should use all available UTXOs to
                        make future transactions smaller and therefore reduce
                        fees. By default Bit will consolidate UTXOs. Note: When
                        setting :param absolute_fee: this is ignored.
        :type combine: ``bool``
        :param message: A message to include in the transaction. This will be
                        stored in the blockchain forever. Due to size limits,
                        each message will be stored in chunks of 40 bytes.
        :type message: ``str``
        :param unspents: The UTXOs to use as the inputs. By default Bit will
                         communicate with the blockchain itself.
        :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
        :param replace_by_fee: Whether to opt-in for replace-by-fee (BIP 125).
        :type replace_by_fee: ``bool``
        :returns: JSON storing data required to create an offline transaction.
        :rtype: ``str``
        """
        unspents, outputs = sanitize_tx_data(
            unspents or NetworkAPI.get_unspent_testnet(address),
            outputs,
            fee or get_fee_cached(),
            leftover or address,
            combine=combine,
            message=message,
            absolute_fee=absolute_fee,
            version='test',
            message_is_hex=message_is_hex,
            replace_by_fee=replace_by_fee
        )

        data = {'unspents': [unspent.to_dict() for unspent in unspents], 'outputs': outputs}

        return json.dumps(data, separators=(',', ':'))

    def sign_transaction(self, tx_data, unspents=None):  # pragma: no cover
        """Creates a signed P2SH transaction using previously prepared
        transaction data.

        :param tx_data: Hex-encoded transaction or output of :func:`~bit.Key.prepare_transaction`.
        :type tx_data: ``str``
        :param unspents: The UTXOs to use as the inputs. By default Bit will
                         communicate with the blockchain itself.
        :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
        :returns: The signed transaction as hex.
        :rtype: ``str``
        """
        try:  # Json-tx-data from :func:`~bit.Key.prepare_transaction`
            data = json.loads(tx_data)
            assert unspents is None

            unspents = [Unspent.from_dict(unspent) for unspent in data['unspents']]
            outputs = data['outputs']

            return create_new_transaction(self, unspents, outputs)
        except:  # May be hex-encoded partially-signed transaction or using batching:
            try:
                unspents = unspents or self.get_unspents()
            except ConnectionError:
                raise ConnectionError(
                    'All APIs are unreachable. Please provide the unspent '
                    'inputs as unspents directly to sign this transaction.'
                )

            tx_data = deserialize(tx_data)
            return sign_tx(self, tx_data, unspents=unspents)

    def __repr__(self):
        return '<MultiSigTestnet: {}>'.format(self.address) class MultiSig:
    """This class represents a Bitcoin multisignature contract.
    **Note:** coins on the test network have no monetary value!

    :param private_key: A class representing a private key.
    :type private_key: ``PrivateKey``
    :raises TypeError: If ``private_key`` is not a ``PrivateKey``.
    :param public_keys: A list or set of public keys encoded as hex or bytes
                        assigned to the multi-signature contract. If using a
                        list, then the order of the public keys will be used in
                        the contract. If using a set, then Bit will order the
                        public keys according to lexicographical order.
    :type public_keys: ``list`` or ``set`` of ``str`` or ``bytes``
    :raises TypeError: When the list ``public_keys`` does not include the public
                       key corresponding to the private key used in this class.
    :param m: The number of required signatures to spend from this multi-
              signature contract.
    :type m: ``int``
    """

    def __init__(self, private_key, public_keys, m):

        if private_key.instance != 'PrivateKey':
            raise TypeError('MultiSig only accepts a PrivateKey class to assign a private key.')

        if bytes_to_hex(private_key.public_key) not in public_keys and private_key.public_key not in public_keys:
            raise ValueError('Private key does not match any provided public key.')

        if type(public_keys) not in (list, set):
            raise TypeError('The public keys must be provided in a list or set.')

        self.version = 'main'
        self.instance = 'MultiSig'

        self._pk = private_key
        self.public_key = private_key.public_key
        if type(public_keys) == set:
            public_keys = sorted(public_keys)
        self.public_keys = list(map(lambda k: k if type(k) == bytes else hex_to_bytes(k), public_keys))
        self.m = m
        self.redeemscript = multisig_to_redeemscript(self.public_keys, self.m)
        self.is_compressed = all(len(p) == 33 for p in self.public_keys)

        self._address = None
        self._segwit_address = None
        self._scriptcode = None
        self._segwit_scriptcode = None

        self.balance = 0
        self.unspents = []
        self.transactions = []

    @property
    def address(self):
        """The public address you share with others to receive funds."""
        if self._address is None:
            self._address = multisig_to_address(self.public_keys, self.m, version=self.version)
        return self._address

    @property
    def segwit_address(self):
        """The public segwit nested in P2SH address you share with others to
        receive funds."""
        # Only make segwit-address if all public keys are compressed
        if self._segwit_address is None and self.is_compressed:
            self._segwit_address = multisig_to_segwit_address(self.public_keys, self.m, version=self.version)
        return self._segwit_address

    @property
    def scriptcode(self):
        self._scriptcode = self.redeemscript
        return self._scriptcode

    @property
    def segwit_scriptcode(self):
        self._segwit_scriptcode = OP_0 + OP_PUSH_32 + sha256(self.redeemscript)
        return self._segwit_scriptcode

    def can_sign_unspent(self, unspent):
        script = bytes_to_hex(address_to_scriptpubkey(self.address))
        if self.segwit_address:
            segwit_script = bytes_to_hex(address_to_scriptpubkey(self.segwit_address))
            return unspent.script == script or unspent.script == segwit_script
        else:
            return unspent.script == script

    def sign(self, data):  # pragma: no cover
        """Signs some data which can be verified later by others using
        the public key.

        :param data: The message to sign.
        :type data: ``bytes``
        :returns: A signature compliant with BIP-62.
        :rtype: ``bytes``
        """
        return self._pk.sign(data)

    def balance_as(self, currency):
        """Returns your balance as a formatted string in a particular currency.

        :param currency: One of the :ref:`supported currencies`.
        :type currency: ``str``
        :rtype: ``str``
        """
        return satoshi_to_currency_cached(self.balance, currency)

    def get_balance(self, currency='satoshi'):
        """Fetches the current balance by calling
        :func:`~bit.MultiSig.get_unspents` and returns it using
        :func:`~bit.MultiSig.balance_as`.

        :param currency: One of the :ref:`supported currencies`.
        :type currency: ``str``
        :rtype: ``str``
        """
        self.get_unspents()
        return self.balance_as(currency)

    def get_unspents(self):
        """Fetches all available unspent transaction outputs.

        :rtype: ``list`` of :class:`~bit.network.meta.Unspent`
        """
        # P2SH size: OP_00 + m * <SIG> + <redeemScript>:
        p2sh_size = 1 + self.m * 74 + len(int_to_varint(len(self.redeemscript))) + len(self.redeemscript)
        # Adding outpoint size, scriptSig size and sequence size:
        add_p2sh_vsize = 36 + len(int_to_varint(p2sh_size)) + p2sh_size + 4
        # Converting to vSize for Segwit: outpoint size + scriptSig size + witness vSize:
        add_np2wsh_vsize = 36 + 40 + (1 + p2sh_size) / 4

        self.unspents[:] = list(
            map(lambda u: u.set_type('p2sh', add_p2sh_vsize), NetworkAPI.get_unspent(self.address))
        )
        if self.segwit_address:
            self.unspents += list(
                map(lambda u: u.set_type('np2wsh', add_np2wsh_vsize), NetworkAPI.get_unspent(self.segwit_address))
            )
        self.balance = sum(unspent.amount for unspent in self.unspents)
        return self.unspents

    def get_transactions(self):
        """Fetches transaction history.

        :rtype: ``list`` of ``str`` transaction IDs
        """
        self.transactions[:] = NetworkAPI.get_transactions(self.address)
        if self.segwit_address:
            self.transactions += NetworkAPI.get_transactions(self.segwit_address)
        return self.transactions

    def create_transaction(
        self,
        outputs,
        fee=None,
        absolute_fee=False,
        leftover=None,
        combine=True,
        message=None,
        unspents=None,
        message_is_hex=False,
        replace_by_fee=False
    ):  # pragma: no cover
        """Creates a signed P2SH transaction.

        :param outputs: A sequence of outputs you wish to send in the form
                        ``(destination, amount, currency)``. The amount can
                        be either an int, float, or string as long as it is
                        a valid input to ``decimal.Decimal``. The currency
                        must be :ref:`supported <supported currencies>`.
        :type outputs: ``list`` of ``tuple``
        :param fee: The number of satoshi per byte to pay to miners. By default
                    Bit will poll `<https://bitcoinfees.21.co>`_ and use a fee
                    that will allow your transaction to be confirmed as soon as
                    possible.
        :type fee: ``int``
        :param leftover: The destination that will receive any change from the
                         transaction. By default Bit will send any change to
                         the same address you sent from.
        :type leftover: ``str``
        :param combine: Whether or not Bit should use all available UTXOs to
                        make future transactions smaller and therefore reduce
                        fees. By default Bit will consolidate UTXOs. Note: When
                        setting :param absolute_fee: this is ignored.
        :type combine: ``bool``
        :param message: A message to include in the transaction. This will be
                        stored in the blockchain forever. Due to size limits,
                        each message will be stored in chunks of 40 bytes.
        :type message: ``str``
        :param unspents: The UTXOs to use as the inputs. By default Bit will
                         communicate with the testnet blockchain itself.
        :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
        :param replace_by_fee: Whether to opt-in for replace-by-fee (BIP 125).
        :type replace_by_fee: ``bool``
        :returns: The signed transaction as hex.
        :rtype: ``str``
        """
        try:
            unspents = unspents or self.get_unspents()
        except ConnectionError:
            raise ConnectionError('All APIs are unreachable. Please provide the unspents to spend from directly.')

        # If at least one input is from segwit the return address is for segwit
        return_address = self.segwit_address if any([u.segwit for u in unspents]) else self.address

        unspents, outputs = sanitize_tx_data(
            unspents,
            outputs,
            fee or get_fee_cached(),
            leftover or return_address,
            combine=combine,
            message=message,
            absolute_fee=absolute_fee,
            version=self.version,
            message_is_hex=message_is_hex,
            replace_by_fee=replace_by_fee
        )

        return create_new_transaction(self, unspents, outputs)

    @classmethod
    def prepare_transaction(
        cls,
        address,
        outputs,
        compressed=True,
        fee=None,
        absolute_fee=False,
        leftover=None,
        combine=True,
        message=None,
        unspents=None,
        message_is_hex=False,
        replace_by_fee=False
    ):  # pragma: no cover
        """Prepares a P2SH transaction for offline signing.

        :param address: The address the funds will be sent from.
        :type address: ``str``
        :param outputs: A sequence of outputs you wish to send in the form
                        ``(destination, amount, currency)``. The amount can
                        be either an int, float, or string as long as it is
                        a valid input to ``decimal.Decimal``. The currency
                        must be :ref:`supported <supported currencies>`.
        :type outputs: ``list`` of ``tuple``
        :param compressed: Whether or not the ``address`` corresponds to a
                           compressed public key. This influences the fee.
        :type compressed: ``bool``
        :param fee: The number of satoshi per byte to pay to miners. By default
                    Bit will poll `<https://bitcoinfees.21.co>`_ and use a fee
                    that will allow your transaction to be confirmed as soon as
                    possible.
        :type fee: ``int``
        :param leftover: The destination that will receive any change from the
                         transaction. By default Bit will send any change to
                         the same address you sent from.
        :type leftover: ``str``
        :param combine: Whether or not Bit should use all available UTXOs to
                        make future transactions smaller and therefore reduce
                        fees. By default Bit will consolidate UTXOs. Note: When
                        setting :param absolute_fee: this is ignored.
        :type combine: ``bool``
        :param message: A message to include in the transaction. This will be
                        stored in the blockchain forever. Due to size limits,
                        each message will be stored in chunks of 40 bytes.
        :type message: ``str``
        :param unspents: The UTXOs to use as the inputs. By default Bit will
                         communicate with the blockchain itself.
        :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
        :param replace_by_fee: Whether to opt-in for replace-by-fee (BIP 125).
        :type replace_by_fee: ``bool``
        :returns: JSON storing data required to create an offline transaction.
        :rtype: ``str``
        """
        unspents, outputs = sanitize_tx_data(
            unspents or NetworkAPI.get_unspent(address),
            outputs,
            fee or get_fee_cached(),
            leftover or address,
            combine=combine,
            message=message,
            absolute_fee=absolute_fee,
            version='main',
            message_is_hex=message_is_hex,
            replace_by_fee=replace_by_fee
        )

        data = {'unspents': [unspent.to_dict() for unspent in unspents], 'outputs': outputs}

        return json.dumps(data, separators=(',', ':'))

    def sign_transaction(self, tx_data, unspents=None):  # pragma: no cover
        """Creates a signed P2SH transaction using previously prepared
        transaction data.

        :param tx_data: Hex-encoded transaction or output of :func:`~bit.Key.prepare_transaction`.
        :type tx_data: ``str``
        :param unspents: The UTXOs to use as the inputs. By default Bit will
                         communicate with the blockchain itself.
        :type unspents: ``list`` of :class:`~bit.network.meta.Unspent`
        :returns: The signed transaction as hex.
        :rtype: ``str``
        """
        try:  # Json-tx-data from :func:`~bit.Key.prepare_transaction`
            data = json.loads(tx_data)
            assert unspents is None

            unspents = [Unspent.from_dict(unspent) for unspent in data['unspents']]
            outputs = data['outputs']

            return create_new_transaction(self, unspents, outputs)
        except:  # May be hex-encoded partially-signed transaction or using batching:
            try:
                unspents = unspents or self.get_unspents()
            except ConnectionError:
                raise ConnectionError(
                    'All APIs are unreachable. Please provide the unspent '
                    'inputs as unspents directly to sign this transaction.'
                )

            tx_data = deserialize(tx_data)
            return sign_tx(self, tx_data, unspents=unspents)

    def __repr__(self):
        return '<MultiSig: {}>'.format(self.address) WALLET_FORMAT_MAIN = '5KHxtARu5yr1JECrYGEA2YpCPdh1i9ciEgQayAF8kcqApkGzT9s' WALLET_FORMAT_TEST_1 = 'KzDFE5K1Mb6cP2SAUySLUMx8F8KWn5RYiUFTFXcDMY5X22Jp1MvH' WALLET_FORMAT_TEST_2 = 'KxhDjpU1TWDbD2ukWpTcj9T55bkKVJsyn2hcDucCecpjApetCRG9' BITCOIN_ADDRESS = '1ELReFsTCUY2mfaDTy32qxYiT49z786eFg' BITCOIN_ADDRESS_TEST = 'mtrNwJxS1VyHYn3qBY1Qfsm3K3kh1mGRMS' BITCOIN_ADDRESS_PAY2SH = '39SrGQEfFXcTYJhBvjZeQja66Cpz82EEUn' BITCOIN_ADDRESS_TEST_PAY2SH = '2NFKbBHzzh32q5DcZJNgZE9sF7gYmtPbawk' BITCOIN_SEGWIT_ADDRESS = 'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq' BITCOIN_SEGWIT_ADDRESS_PAY2SH = 'bc1qc7slrfxkknqcq2jevvvkdgvrt8080852dfjewde450xdlk4ugp7szw5tk9' BITCOIN_SEGWIT_HASH = 'e8df018c7e326cc253faac7e46cdc51e68542c42' BITCOIN_SEGWIT_HASH_PAY2SH = 'c7a1f1a4d6b4c1802a59631966a18359de779e8a6a65973735a3ccdfdabc407d' BITCOIN_SEGWIT_ADDRESS_TEST = 'tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx' BITCOIN_SEGWIT_ADDRESS_TEST_PAY2SH = 'tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7' BITCOIN_SEGWIT_HASH_TEST = '751e76e8199196d454941c45d1b3a323f1433bd6' BITCOIN_SEGWIT_HASH_TEST_PAY2SH = '1863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262' PAY2SH_HASH = b'U\x13\x1e\xfbz\x0e\xddLv\xcc;\xbe\x83;\xfcY\xa6\xf7<k' PAY2SH_TEST_HASH = b'\xf2&\x1e\x95d\xc9\xdf\xff\xa8\x15\x05\xc1S\xfb\x95\xbf\x93\x99C\x08' BITCOIN_ADDRESS_COMPRESSED = '1ExJJsNLQDNVVM1s1sdyt1o5P3GC5r32UG' BITCOIN_ADDRESS_TEST_COMPRESSED = 'muUFbvTKDEokGTVUjScMhw1QF2rtv5hxCz'
import pytest
import copy
from bit.constants import HASH_TYPE
from bit.exceptions import InsufficientFunds
from bit.network.meta import Unspent
from bit.transaction import (
    TxIn,
    TxOut,
    TxObj,
    calc_txid,
    create_new_transaction,
    construct_outputs,
    deserialize,
    estimate_tx_fee,
    sanitize_tx_data,
    select_coins,
    address_to_scriptpubkey,
    calculate_preimages,
    sign_tx,
)
from bit.utils import hex_to_bytes, get_signatures_from_script
from bit.wallet import PrivateKey, PrivateKeyTestnet, MultiSigTestnet, MultiSig
from .samples import (
    WALLET_FORMAT_MAIN,
    WALLET_FORMAT_TEST_1,
    WALLET_FORMAT_TEST_2,
    BITCOIN_ADDRESS,
    BITCOIN_ADDRESS_TEST,
    BITCOIN_ADDRESS_PAY2SH,
    BITCOIN_ADDRESS_TEST_PAY2SH,
    BITCOIN_SEGWIT_ADDRESS,
    BITCOIN_SEGWIT_ADDRESS_PAY2SH,
    BITCOIN_SEGWIT_HASH,
    BITCOIN_SEGWIT_HASH_PAY2SH,
    BITCOIN_SEGWIT_ADDRESS_TEST,
    BITCOIN_SEGWIT_ADDRESS_TEST_PAY2SH,
    BITCOIN_SEGWIT_HASH_TEST,
    BITCOIN_SEGWIT_HASH_TEST_PAY2SH,
    PAY2SH_HASH,
    PAY2SH_TEST_HASH,
    BITCOIN_ADDRESS_COMPRESSED,
    BITCOIN_ADDRESS_TEST_COMPRESSED,
)
        tx2 = multi1.sign_transaction(tx1, unspents=UNSPENTS_BATCH[::-1])
        assert tx2 == FINAL_TX_BATCH

    def test_multisig_tx_many_inputs(self):
        key1 = PrivateKeyTestnet(WALLET_FORMAT_TEST_1)
        key2 = PrivateKeyTestnet(WALLET_FORMAT_TEST_2)
        p = [key1.public_key.hex(), key2.public_key.hex()]
        multi1 = MultiSigTestnet(key1, p, 2)
        multi2 = MultiSigTestnet(key2, p, 2)
        tx0 = create_new_transaction(
            multi1,
            UNSPENTS_MULTISIG_MANY,
            [
                ("bcrt1qpm3x3jrdqhefptw3hlymmlpejttct08zgzzd2t", 4000000000),
                ("2NCWeVbWmaUp92dSFP3RddPk6r3GTd6cDd6", 999971920),
            ],
        )
        tx1 = multi2.sign_transaction(tx0, unspents=UNSPENTS_MULTISIG_MANY)
        assert tx1 == FINAL_TX_MULTISIG_MANY


class TestDeserializeTransaction:
    def test_legacy_deserialize(self):
        txobj = deserialize(FINAL_TX_1)
        assert txobj.version == hex_to_bytes(FINAL_TX_1[:8])
        assert len(txobj.TxIn) == 1
        assert txobj.TxIn[0].txid == hex_to_bytes(FINAL_TX_1[10:74])
        assert txobj.TxIn[0].txindex == hex_to_bytes(FINAL_TX_1[74:82])
        assert txobj.TxIn[0].script_sig_len == hex_to_bytes(FINAL_TX_1[82:84])
        assert txobj.TxIn[0].script_sig == hex_to_bytes(FINAL_TX_1[84:360])
        assert txobj.TxIn[0].witness == b''
        assert txobj.TxIn[0].sequence == hex_to_bytes(FINAL_TX_1[360:368])
        assert len(txobj.TxOut) == 2
        assert txobj.TxOut[0].amount == hex_to_bytes(FINAL_TX_1[370:386])
        assert txobj.TxOut[0].script_pubkey_len == hex_to_bytes(FINAL_TX_1[386:388])
        assert txobj.TxOut[0].script_pubkey == hex_to_bytes(FINAL_TX_1[388:438])
        assert txobj.TxOut[1].amount == hex_to_bytes(FINAL_TX_1[438:454])
        assert txobj.TxOut[1].script_pubkey_len == hex_to_bytes(FINAL_TX_1[454:456])
        assert txobj.TxOut[1].script_pubkey == hex_to_bytes(FINAL_TX_1[456:506])
        assert txobj.locktime == hex_to_bytes(FINAL_TX_1[506:])

    def test_segwit_deserialize(self):
        txobj = deserialize(SEGWIT_TX_1)
        assert txobj.version == hex_to_bytes(SEGWIT_TX_1[:8])
        assert len(txobj.TxIn) == 2
        assert txobj.TxIn[0].txid == hex_to_bytes(SEGWIT_TX_1[14:78])
        assert txobj.TxIn[0].txindex == hex_to_bytes(SEGWIT_TX_1[78:86])
        assert txobj.TxIn[0].script_sig_len == hex_to_bytes(SEGWIT_TX_1[86:88])
        assert txobj.TxIn[0].script_sig == hex_to_bytes(SEGWIT_TX_1[88:300])
        assert txobj.TxIn[0].sequence == hex_to_bytes(SEGWIT_TX_1[300:308])
        assert txobj.TxIn[0].witness == hex_to_bytes(SEGWIT_TX_1[564:566])
        assert txobj.TxIn[1].txid == hex_to_bytes(SEGWIT_TX_1[308:372])
        assert txobj.TxIn[1].txindex == hex_to_bytes(SEGWIT_TX_1[372:380])
        assert txobj.TxIn[1].script_sig_len == hex_to_bytes(SEGWIT_TX_1[380:382])
        assert txobj.TxIn[1].script_sig == hex_to_bytes(SEGWIT_TX_1[382:428])
        assert txobj.TxIn[1].sequence == hex_to_bytes(SEGWIT_TX_1[428:436])
        assert txobj.TxIn[1].witness == hex_to_bytes(SEGWIT_TX_1[566:780])
        assert len(txobj.TxOut) == 2
        assert txobj.TxOut[0].amount == hex_to_bytes(SEGWIT_TX_1[438:454])
        assert txobj.TxOut[0].script_pubkey_len == hex_to_bytes(SEGWIT_TX_1[454:456])
        assert txobj.TxOut[0].script_pubkey == hex_to_bytes(SEGWIT_TX_1[456:500])
        assert txobj.TxOut[1].amount == hex_to_bytes(SEGWIT_TX_1[500:516])
        assert txobj.TxOut[1].script_pubkey_len == hex_to_bytes(SEGWIT_TX_1[516:518])
        assert txobj.TxOut[1].script_pubkey == hex_to_bytes(SEGWIT_TX_1[518:564])
        assert txobj.locktime == hex_to_bytes(SEGWIT_TX_1[780:])


class TestGetSignaturesFromScript:
    def test_get_signatures_1(self):
        script = hex_to_bytes(
            '0047304402200b526cf17f86891a62f4bd27745494005682d650c27dda87'
            '7f35b0161c38bc9002204674a0be6275ce948812c200251802d15eaa1953'
            '3d864d64b83b992c10b3ecf201'
            '483045022100a57ba5464a03343bd5ebf21ce0d3d49b84710c62a421b7d5'
            'b86de75ca10d8c7602206395d6a552fc0dbb31d3c0b1db34fa4a14cc29d6'
            '60c8c68172c7e513cb6a0ac901'
            '475221021816325d19fd34fd87a039e83e35fc9de3c9de64a501a6684b9b'
            'f9946364fbb721037d696886864509ed63044d8f1bcd53b8def1247bd2bbe'
            '056ff81b23e8c09280f52ae'
        )
        sigs = get_signatures_from_script(script)
        assert len(sigs) == 2
        assert sigs[0][:4] == hex_to_bytes('30440220')
        assert sigs[0][-4:] == hex_to_bytes('b3ecf201')
        assert sigs[1][:4] == hex_to_bytes('30450221')
        assert sigs[1][-4:] == hex_to_bytes('6a0ac901')

    def test_get_signatures_2(self):
        script = hex_to_bytes(
            '0047304402200b526cf17f86891a62f4bd27745494005682d650c27dda87'
            '7f35b0161c38bc9002204674a0be6275ce948812c200251802d15eaa1953'
            '3d864d64b83b992c10b3ecf201'
            '00'
            '695221021816325d19fd34fd87a039e83e35fc9de3c9de64a501a6684b9b'
            'f9946364fbb721037d696886864509ed63044d8f1bcd53b8def1247bd2bb'
            'e056ff81b23e8c09280f21033dc7fb58b701fc0af63ee3a8b72ebbeed04a'
            '1c006b50007f32ec6a33a56213f853ae0400483045022100f686296df668'
            '17198feead5fa24f3f04cb7e6780187e73fc8c531254fd002c13022044ef'
            'e2ea00f31de395376d83cb122bd708116d151bdf2de61107d77447b475c6'
            '0100695221021816325d19fd34fd87a039e83e35fc9de3c9de64a501a668'
            '4b9bf9946364fbb721037d696886864509ed63044d8f1bcd53b8def1247b'
            'd2bbe056ff81b23e8c09280f21033dc7fb58b701fc0af63ee3a8b72ebbee'
            'd04a1c006b50007f32ec6a33a56213f853ae'
        )
        sigs = get_signatures_from_script(script)
        assert len(sigs) == 1
        assert sigs[0][:4] == hex_to_bytes('30440220')
        assert sigs[0][-4:] == hex_to_bytes('b3ecf201')


class TestAddressToScriptPubKey:
    def test_address_to_scriptpubkey_legacy(self):
        want = b'v\xa9\x14\x92F\x1b\xdeb\x83\xb4a\xec\xe7\xdd\xf4\xdb\xf1\xe0\xa4\x8b\xd1\x13\xd8\x88\xac'
        assert address_to_scriptpubkey(BITCOIN_ADDRESS) == want

        want = b'v\xa9\x14\x99\x0e\xf6\rc\xb5\xb5\x96J\x1c"\x82\x06\x1a\xf4Q#\xe9?\xcb\x88\xac'
        assert address_to_scriptpubkey(BITCOIN_ADDRESS_COMPRESSED) == want

    def test_address_to_scriptpubkey_legacy_p2sh(self):
        want = b'\xa9\x14U\x13\x1e\xfbz\x0e\xddLv\xcc;\xbe\x83;\xfcY\xa6\xf7<k\x87'

        assert address_to_scriptpubkey(BITCOIN_ADDRESS_PAY2SH) == want