Пример #1
0
    def gettransaction(self, tx_id):
        res = self.compose_request('dashboards/transaction/', data=tx_id)

        tx = res['data'][tx_id]['transaction']
        confirmations = res['context']['state'] - tx['block_id']
        status = 'unconfirmed'
        if confirmations:
            status = 'confirmed'
        witness_type = 'legacy'
        if tx['has_witness']:
            witness_type = 'segwit'
        input_total = tx['input_total']
        if tx['is_coinbase']:
            input_total = tx['output_total']
        t = Transaction(locktime=tx['lock_time'], version=tx['version'], network=self.network,
                        fee=tx['fee'], size=tx['size'], hash=tx['hash'],
                        date=datetime.strptime(tx['time'], "%Y-%m-%d %H:%M:%S"),
                        confirmations=confirmations, block_height=tx['block_id'], status=status,
                        input_total=input_total, coinbase=tx['is_coinbase'],
                        output_total=tx['output_total'], witness_type=witness_type)
        index_n = 0
        for ti in res['data'][tx_id]['inputs']:
            t.add_input(prev_hash=ti['transaction_hash'], output_n=ti['index'],
                        unlocking_script_unsigned=ti['script_hex'], index_n=index_n, value=ti['value'],
                        address=ti['recipient'], unlocking_script=ti['spending_signature_hex'])
            index_n += 1
        for to in res['data'][tx_id]['outputs']:
            try:
                deserialize_address(to['recipient'], network=self.network.name)
                addr = to['recipient']
            except EncodingError:
                addr = ''
            t.add_output(value=to['value'], address=addr, lock_script=to['script_hex'],
                         spent=to['is_spent'], output_n=to['index'])
        return t
Пример #2
0
    def gettransaction(self, tx_id):
        res = self.compose_request('dashboards/transaction/', data=tx_id)

        tx = res['data'][tx_id]['transaction']
        confirmations = 0 if tx['block_id'] <= 0 else res['context']['state'] - tx['block_id']
        status = 'unconfirmed'
        if confirmations:
            status = 'confirmed'
        witness_type = 'legacy'
        if tx['has_witness']:
            witness_type = 'segwit'
        input_total = tx['input_total']
        t = Transaction(locktime=tx['lock_time'], version=tx['version'], network=self.network,
                        fee=tx['fee'], size=tx['size'], txid=tx['hash'],
                        date=None if not confirmations else datetime.strptime(tx['time'], "%Y-%m-%d %H:%M:%S"),
                        confirmations=confirmations, block_height=tx['block_id'] if tx['block_id'] > 0 else None,
                        status=status, input_total=input_total, coinbase=tx['is_coinbase'],
                        output_total=tx['output_total'], witness_type=witness_type)
        index_n = 0
        if not res['data'][tx_id]['inputs']:
            # This is a coinbase transaction, add input
            t.add_input(prev_txid=b'\00' * 32, output_n=0, value=0)

        for ti in res['data'][tx_id]['inputs']:
            if ti['spending_witness']:
                # witnesses = b"".join([varstr(bytes.fromhex(x)) for x in ti['spending_witness'].split(",")])
                witnesses = ti['spending_witness'].split(",")
                address = Address.parse(ti['recipient'])
                if address.script_type == 'p2sh':
                    witness_type = 'p2sh-segwit'
                else:
                    witness_type = 'segwit'
                t.add_input(prev_txid=ti['transaction_hash'], output_n=ti['index'],
                            unlocking_script=ti['spending_signature_hex'],
                            witnesses=witnesses, index_n=index_n, value=ti['value'],
                            address=address, witness_type=witness_type, sequence=ti['spending_sequence'], strict=False)
            else:
                t.add_input(prev_txid=ti['transaction_hash'], output_n=ti['index'],
                            unlocking_script=ti['spending_signature_hex'], index_n=index_n, value=ti['value'],
                            address=ti['recipient'], unlocking_script_unsigned=ti['script_hex'],
                            sequence=ti['spending_sequence'], strict=False)
            index_n += 1
        for to in res['data'][tx_id]['outputs']:
            try:
                deserialize_address(to['recipient'], network=self.network.name)
                addr = to['recipient']
            except EncodingError:
                addr = ''
            t.add_output(value=to['value'], address=addr, lock_script=to['script_hex'],
                         spent=to['is_spent'], output_n=to['index'], spending_txid=to['spending_transaction_hash'],
                         spending_index_n=to['spending_index'], strict=False)
        return t
Пример #3
0
index = 1000
pub_with_pubparent = K.child_public(index).address()
pub_with_privparent = k.child_private(index).address()
if pub_with_privparent != pub_with_pubparent:
    print("Error index %4d: pub-child %s, priv-child %s" %
          (index, pub_with_privparent, pub_with_pubparent))
else:
    print("Child Key Derivation for key %d worked!" % index)
    print("%s == %s" % (pub_with_pubparent, pub_with_privparent))

#
# Addresses
#
print("\n=== Deserialize address ===")
pprint(deserialize_address('12ooWd8Xag7hsgP9PBPnmyGe36VeUrpMSH'))

print("\n=== Deserialize bech32 address ===")
pprint(
    deserialize_address(
        'bc1qtlktwxgx3xu3r7fnt04q06e4gflpvmm70qw66rjckzyc0n54elxqsgqlpy'))

print("\n=== Create addreses from public key ===")
pk = HDKey().public_hex
print("Public key: %s" % pk)
print(Address(pk).address)
print(Address(pk, script_type='p2sh').address)
print(Address(pk, encoding='bech32').address)
print(Address(pk, script_type='p2sh', encoding='bech32').address)
print(Address(pk, encoding='bech32', network='litecoin').address)
print(Address(pk, encoding='bech32', network='dash').address)
Пример #4
0
    def __init__(self,
                 amount,
                 address='',
                 public_key_hash=b'',
                 public_key=b'',
                 lock_script=b'',
                 network=DEFAULT_NETWORK):
        """
        Create a new transaction output
        
        An transaction outputs locks the specified amount to a public key. Anyone with the private key can unlock
        this output.
        
        The transaction output class contains an amount and the destination which can be provided either as address, 
        public key, public key hash or a locking script. Only one needs to be provided as the they all can be derived 
        from each other, but you can provide as much attributes as you know to improve speed.
        
        :param amount: Amount of output in smallest denominator of currency, for example satoshi's for bitcoins
        :type amount: int
        :param address: Destination address of output. Leave empty to derive from other attributes you provide.
        :type address: str
        :param public_key_hash: Hash of public key
        :type public_key_hash: bytes, str
        :param public_key: Destination public key
        :type public_key: bytes, str
        :param lock_script: Locking script of output. If not provided a default unlocking script will be provided with a public key hash.
        :type lock_script: bytes, str
        :param network: Network, leave empty for default
        :type network: str
        """
        if not (address or public_key_hash or public_key or lock_script):
            raise TransactionError(
                "Please specify address, lock_script, public key or public key hash when "
                "creating output")

        self.amount = amount
        self.lock_script = to_bytes(lock_script)
        self.public_key_hash = to_bytes(public_key_hash)
        self.address = address
        self.public_key = to_bytes(public_key)
        self.network = Network(network)
        self.compressed = True
        self.k = None
        self.versionbyte = self.network.prefix_address
        self.script_type = 'p2pkh'

        if self.public_key:
            self.k = Key(binascii.hexlify(self.public_key).decode('utf-8'),
                         network=network)
            self.address = self.k.address()
            self.compressed = self.k.compressed
        if self.public_key_hash and not self.address:
            self.address = pubkeyhash_to_addr(public_key_hash,
                                              versionbyte=self.versionbyte)
        if self.address:
            address_dict = deserialize_address(self.address)
            if address_dict['script_type']:
                self.script_type = address_dict['script_type']
            else:
                raise TransactionError(
                    "Could not determine script type of address %s" %
                    self.address)
            self.public_key_hash = address_dict['public_key_hash_bytes']
            if address_dict[
                    'network'] and self.network.network_name != address_dict[
                        'network']:
                raise TransactionError(
                    "Address (%s) is from different network then defined %s" %
                    (address_dict['network'], self.network.network_name))
        if not self.public_key_hash and self.k:
            self.public_key_hash = self.k.hash160()

        if self.lock_script and not self.public_key_hash:
            ss = script_deserialize(self.lock_script)
            self.script_type = ss['script_type']
            if self.script_type == 'p2sh':
                self.versionbyte = self.network.prefix_address_p2sh
            if self.script_type in ['p2pkh', 'p2sh']:
                self.public_key_hash = ss['signatures'][0]
                self.address = pubkeyhash_to_addr(self.public_key_hash,
                                                  versionbyte=self.versionbyte)
            else:
                _logger.warning("Script type %s not supported" %
                                self.script_type)

        if self.lock_script == b'':
            if self.script_type == 'p2pkh':
                self.lock_script = b'\x76\xa9\x14' + self.public_key_hash + b'\x88\xac'
            elif self.script_type == 'p2sh':
                self.lock_script = b'\xa9\x14' + self.public_key_hash + b'\x87'
            else:
                raise TransactionError(
                    "Unknown output script type %s, please provide own locking script"
                    % self.script_type)