Ejemplo n.º 1
0
    def output_index_for_address(self, address_or_hash160):
        """ Returns the index of the output in this transaction
            that pays to the provided address.

        Args:
            address_or_hash160 (str or bytes): If a string, a
                Base58Check encoded address. If bytes, the hash160
                of the public key.

        Returns:
            int: The index of the corresponding output or None.
        """
        if isinstance(address_or_hash160, str):
            ver, h160_bytes = address_to_key_hash(address_or_hash160)
            h160 = bytes_to_str(h160_bytes)
        elif isinstance(address_or_hash160, bytes):
            h160 = bytes_to_str(address_or_hash160)
        else:
            raise TypeError("address_or_hash160 can only be bytes or str")

        rv = None
        for i, o in enumerate(self.outputs):
            scr = o.script
            if scr.is_p2pkh() or scr.is_p2sh():
                if scr.get_hash160()[2:] == h160:
                    rv = i
                    break

        return rv
Ejemplo n.º 2
0
    def broadcast_transaction(self, transaction):
        """ Broadcasts a transaction to the Bitcoin network

        Args:
            transaction (bytes or str): serialized, signed transaction

        Returns:
            str: The transaction ID
        """
        if isinstance(transaction, bytes):
            signed_hex = bytes_to_str(transaction)
        elif isinstance(transaction, Transaction):
            signed_hex = bytes_to_str(bytes(transaction))
        elif isinstance(transaction, str):
            signed_hex = transaction
        else:
            raise TypeError(
                "transaction must be one of: bytes, str, Transaction.")

        data = {"signed_hex": signed_hex}
        r = self._request("POST", "transactions/send", json=data)
        if r.status_code == 200:
            j = r.json()
            return j["transaction_hash"]
        elif r.status_code == 400:
            j = r.json()

            # TODO: Change this to some more meaningful exception type
            raise exceptions.TransactionBroadcastError(j['message'])
        else:
            # Some other status code... should never happen.
            raise exceptions.TransactionBroadcastError(
                "Unexpected response: %r" % r.status_code)
Ejemplo n.º 3
0
    def broadcast_transaction(self, transaction):
        """ Broadcasts a transaction to the Bitcoin network

        Args:
            transaction (bytes or str): serialized, signed transaction

        Returns:
            str: The transaction ID
        """
        if isinstance(transaction, bytes):
            signed_hex = bytes_to_str(transaction)
        elif isinstance(transaction, Transaction):
            signed_hex = bytes_to_str(bytes(transaction))
        elif isinstance(transaction, str):
            signed_hex = transaction
        else:
            raise TypeError(
                "transaction must be one of: bytes, str, Transaction.")

        data = {"signed_hex": signed_hex}
        r = self._request("POST", "transactions/send", json=data)
        if r.status_code == 200:
            j = r.json()
            return j["transaction_hash"]
        elif r.status_code == 400:
            j = r.json()

            # TODO: Change this to some more meaningful exception type
            raise exceptions.TransactionBroadcastError(j['message'])
        else:
            # Some other status code... should never happen.
            raise exceptions.TransactionBroadcastError(
                "Unexpected response: %r" % r.status_code)
Ejemplo n.º 4
0
    def build_push_str(s):
        """ Creates a script to push s onto the stack.

        Args:
            s (bytes): bytes to be pushed onto the stack.

        Returns:
            b (bytes): Serialized bytes containing the appropriate PUSHDATA
                       op for s.
        """
        ls = len(s)
        hexstr = bytes_to_str(s)
        pd_index = 0

        if ls < Script.BTC_OPCODE_TABLE['OP_PUSHDATA1']:
            return bytes([ls]) + s
        # Determine how many bytes are required for the length
        elif ls < 0xff:
            pd_index = 1
        elif ls < 0xffff:
            pd_index = 2
        else:
            pd_index = 4

        p = bytes([Script.BTC_OPCODE_TABLE['OP_PUSHDATA%d' % (pd_index)]])
        p += bytes([ls]) + s
        return p
Ejemplo n.º 5
0
    def post(self):
        """Initialize the payment channel handshake.

        Params (query):
            refund_tx (string): half-signed serialized refund transaction

        Response (json) 2xx:
            refund_tx (string): fully-signed serialized refund transaction
        """
        try:
            params = request.values.to_dict()
            # Validate parameters
            if 'refund_tx' not in params:
                raise BadParametersError('No refund provided.')

            # Initialize the payment channel
            refund_tx = Transaction.from_hex(params['refund_tx'])
            self.server.initialize_handshake(refund_tx)

            # Respond with the fully-signed refund transaction
            success = {'refund_tx': bytes_to_str(bytes(refund_tx))}
            return jsonify(success)
        except Exception as e:
            # Catch payment exceptions and send error response to client
            raise BadRequest(str(e))
Ejemplo n.º 6
0
    def __str__(self):
        """ Gives the hex-encoded serialization of the header.

        Returns:
            str: hex-encoded string.
        """
        return bytes_to_str(bytes(self))
Ejemplo n.º 7
0
    def to_hex(self):
        """ Generates a hex encoding of the serialized transaction.

        Returns:
            str: Hex-encoded serialization.
        """
        return bytes_to_str(bytes(self))
Ejemplo n.º 8
0
    def to_hex(self):
        """ Generates a hex encoding of the serialized transaction.

        Returns:
            str: Hex-encoded serialization.
        """
        return bytes_to_str(bytes(self))
Ejemplo n.º 9
0
    def __str__(self):
        """ Gives the hex-encoded serialization of the header.

        Returns:
            str: hex-encoded string.
        """
        return bytes_to_str(bytes(self))
Ejemplo n.º 10
0
    def create(self, request, format='json'):
        """Initialize the payment channel handshake.

        Params (query):
            refund_tx (string): half-signed serialized refund transaction

        Response (json) 2xx:
            refund_tx (string): fully-signed serialized refund transaction
        """
        try:
            params = request.data
            # Validate parameters
            if 'refund_tx' not in params:
                raise BadParametersError('No refund provided.')

            # Initialize the payment channel
            refund_tx = Transaction.from_hex(params['refund_tx'])
            payment_server.initialize_handshake(refund_tx)

            # Respond with the fully-signed refund transaction
            success = {'refund_tx': bytes_to_str(bytes(refund_tx))}
            return Response(success)
        except Exception as e:
            error = {'error': str(e)}
            return Response(error, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 11
0
    def __str__(self):
        """ Returns a human readable formatting of this input.

        Returns:
            s (str): A string containing the human readable input.
        """
        return ("CoinbaseInput(" + "Outpoint: %s " % (self.outpoint) +
                "Outpoint Index: 0x%08x " % (self.outpoint_index) +
                "Script: %s " % (bytes_to_str(self.script)) +
                "Sequence: 0x%08x)" % (self.sequence_num))
Ejemplo n.º 12
0
    def __str__(self):
        """ Returns a human readable formatting of this input.

        Returns:
            s (str): A string containing the human readable input.
        """
        return (
            "CoinbaseInput(" +
            "Outpoint: %s " % (self.outpoint) +
            "Outpoint Index: 0x%08x " % (self.outpoint_index) +
            "Script: %s " % (bytes_to_str(self.script)) +
            "Sequence: 0x%08x)" % (self.sequence_num))
Ejemplo n.º 13
0
    def build_p2pkh(hash160_key):
        """ Builds a Pay-to-Public-Key-Hash script.

        Args:
            hash160_key (bytes): the RIPEMD-160 hash of the public key
                in internal byte order.

        Returns:
            scr (Script): a serializable Script object containing the
                p2pkh script.
        """
        return Script('OP_DUP OP_HASH160 0x%s OP_EQUALVERIFY OP_CHECKSIG' %
                      bytes_to_str(hash160_key))
Ejemplo n.º 14
0
    def build_p2sh(hash160_key):
        """ Builds a Pay-to-Script-Hash script.

        Args:
            hash160_key (bytes): the RIPEMD-160 hash of the script in
                internal byte order.

        Returns:
            scr (Script): a serializable Script object containing the
                p2sh script.
        """

        return Script('OP_HASH160 0x%s OP_EQUAL' % bytes_to_str(hash160_key))
Ejemplo n.º 15
0
    def _disassemble(self, raw):
        """ Disassembles a raw script (in bytes) to human-readable text
            using the opcodes in BTC_OPCODE_TABLE. The disassembled string
            is stored in self.script.

        Args:
            raw (bytes): A byte stream containing the script to be
                disassembled.
        """
        script = []
        while raw:
            op, raw = raw[0], raw[1:]
            if op == 0x00:
                script.append('OP_0')
            elif op < 0x4b:
                script.append('0x%s' % (bytes_to_str(raw[0:op])))
                raw = raw[op:]
            else:
                opcode = Script.BTC_OPCODE_REV_TABLE[op]
                if opcode in ['OP_PUSHDATA1', 'OP_PUSHDATA2', 'OP_PUSHDATA4']:
                    pushlen = int(opcode[-1])
                    datalen = 0
                    if pushlen == 1:
                        datalen, raw = raw[0], raw[1:]
                    elif pushlen == 2:
                        datalen, raw = struct.unpack("<H", raw[0:2])[0], raw[2:]
                    elif pushlen == 4:
                        datalen, raw = struct.unpack("<I", raw[0:4])[0], raw[4:]

                    script.append('OP_PUSHDATA%d 0x%x 0x%s' %
                                  (pushlen,
                                   datalen,
                                   bytes_to_str(raw[:datalen])))
                    raw = raw[datalen:]
                else:
                    script.append(opcode)

        self.script = " ".join(script)
Ejemplo n.º 16
0
    def broadcast_transaction(self, transaction):
        """ Broadcasts a transaction to the Bitcoin network

        Args:
            transaction (bytes or str): serialized, signed transaction

        Returns:
            str: The transaction ID
        """
        if isinstance(transaction, bytes):
            signed_hex = bytes_to_str(transaction)
        elif isinstance(transaction, Transaction):
            signed_hex = bytes_to_str(bytes(transaction))
        elif isinstance(transaction, str):
            signed_hex = transaction
        else:
            raise TypeError(
                "transaction must be one of: bytes, str, Transaction.")

        data = {"tx": signed_hex}
        r = self._request("POST", "/txs/push", True, json=data)
        j = r.json()
        return j["tx"]["hash"]
Ejemplo n.º 17
0
    def broadcast_transaction(self, transaction):
        """ Broadcasts a transaction to the Bitcoin network

        Args:
            transaction (bytes or str): serialized, signed transaction

        Returns:
            str: The transaction ID
        """
        if isinstance(transaction, bytes):
            signed_hex = bytes_to_str(transaction)
        elif isinstance(transaction, Transaction):
            signed_hex = bytes_to_str(bytes(transaction))
        elif isinstance(transaction, str):
            signed_hex = transaction
        else:
            raise TypeError(
                "transaction must be one of: bytes, str, Transaction.")

        data = {"tx": signed_hex}
        r = self._request("POST", "/txs/push", True, json=data)
        j = r.json()
        return j["tx"]["hash"]
Ejemplo n.º 18
0
    def __str__(self):
        """ Creates a human-readable string representation of the script.

        Returns:
            s (str): String representation of the script
        """
        script = ""
        self._check_tokenized()
        for t in self._tokens:
            if isinstance(t, bytes):
                script += "0x%s " % bytes_to_str(t)
            else:
                script += t + " "

        return script.rstrip()
Ejemplo n.º 19
0
    def __str__(self):
        """ Creates a human-readable string representation of the script.

        Returns:
            s (str): String representation of the script
        """
        script = ""
        self._check_tokenized()
        for t in self._tokens:
            if isinstance(t, bytes):
                script += "0x%s " % bytes_to_str(t)
            else:
                script += t + " "

        return script.rstrip()
Ejemplo n.º 20
0
 def __str__(self):
     """ Returns a hex string in RPC order
     """
     return bytes_to_str(self._bytes[::-1])
Ejemplo n.º 21
0
from two1.lib.bitcoin.txn import TransactionOutput
from two1.lib.bitcoin.script import Script
from two1.lib.bitcoin.utils import address_to_key_hash
from two1.lib.bitcoin.utils import bytes_to_str

address = '137KzxStaf6vw5yGujViK3Tkigoix9N3v7'
_, hash160 = address_to_key_hash(address)
out_script = Script.build_p2pkh(hash160)
out1 = TransactionOutput(value=100000, script=out_script)

# Print the script
print("%s" % (out_script))

# Print the address
print("Addresses = %r" % (out1.get_addresses()))

# Print the value
print("Value: %d" % (out1.value))

# Serialize
out1_bytes = bytes(out1)
print(bytes_to_str(out1_bytes))
Ejemplo n.º 22
0
 def __str__(self):
     """ Returns a hex string in RPC order
     """
     return bytes_to_str(self._bytes[::-1])
Ejemplo n.º 23
0
from two1.lib.bitcoin.crypto import PublicKey
from two1.lib.wallet import Wallet
from two1.lib.bitcoin.utils import bytes_to_str

wallet = Wallet()
pubkey = wallet.get_payout_public_key()
compressed = pubkey.compressed_bytes
str = bytes_to_str(pubkey.compressed_bytes).upper()

print("Payout public key: %s" % (str))