How to use the bitcoinlib.keys.BKeyError function in bitcoinlib

To help you get started, we’ve selected a few bitcoinlib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github 1200wd / bitcoinlib / bitcoinlib / keys.py View on Github external
is_private = False
                        key = bkey[45:78]
                    else:
                        key = bkey[46:78]
                    depth = ord(bkey[4:5])
                    parent_fingerprint = bkey[5:9]
                    child_index = int(change_base(bkey[9:13], 256, 10))
                    chain = bkey[13:45]
                    # chk = bkey[78:82]
                elif kf['format'] == 'address':
                    da = deserialize_address(import_key)
                    key = da['public_key_hash']
                    network = Network(da['network'])
                    is_private = False
                elif kf['format'] == 'mnemonic':
                    raise BKeyError("Use HDKey.from_passphrase() method to parse a passphrase")
                else:
                    key = import_key
                    chain = b'\0' * 32
                    key_type = 'private'

        if witness_type is None:
            witness_type = DEFAULT_WITNESS_TYPE

        Key.__init__(self, key, network, compressed, passphrase, is_private)

        self.encoding = encoding
        self.witness_type = witness_type
        self.multisig = multisig

        self.chain = chain
        self.depth = depth
github 1200wd / bitcoinlib / bitcoinlib / keys.py View on Github external
def wif(self, prefix=None):
        """
        Get Private Key in Wallet Import Format, steps:
        # Convert to Binary and add 0x80 hex
        # Calculate Double SHA256 and add as checksum to end of key

        :param prefix: Specify versionbyte prefix in hexstring or bytes. Normally doesn't need to be specified, method uses default prefix from network settings
        :type prefix: str, bytes

        :return str: Base58Check encoded Private Key WIF
        """
        if not self.secret:
            raise BKeyError("WIF format not supported for public key")
        if prefix is None:
            versionbyte = self.network.prefix_wif
        else:
            if not isinstance(prefix, (bytes, bytearray)):
                versionbyte = binascii.unhexlify(prefix)
            else:
                versionbyte = prefix

        if self._wif and self._wif_prefix == versionbyte:
            return self._wif

        key = versionbyte + change_base(self.secret, 10, 256, 32)
        if self.compressed:
            key += b'\1'
        key += double_sha256(key)[:4]
        self._wif = change_base(key, 256, 58)
github 1200wd / bitcoinlib / bitcoinlib / keys.py View on Github external
:param public_key: Public key as HDKey or Key object or any other string accepted by HDKey object
        :type public_key: HDKey, Key, str, hexstring, bytes
        
        :return Signature: 
        """

        der_signature = ''
        signature = to_bytes(signature)
        if len(signature) > 64 and signature.startswith(b'\x30'):
            der_signature = signature
            if der_signature.endswith(b'\x01'):
                der_signature = der_signature[:-1]
            signature = convert_der_sig(signature[:-1], as_hex=False)
        signature = to_hexstring(signature)
        if len(signature) != 128:
            raise BKeyError("Signature length must be 64 bytes or 128 character hexstring")
        r = int(signature[:64], 16)
        s = int(signature[64:], 16)
        return Signature(r, s, signature=signature, der_signature=der_signature, public_key=public_key)
github 1200wd / bitcoinlib / bitcoinlib / keys.py View on Github external
:param der_signature: DER encoded signature
        :type der_signature: str, bytes
        :param public_key: Provide public key P if known
        :type public_key: HDKey, Key, str, hexstring, bytes
        :param k: k value used for signature
        :type k: int
        """

        self.r = int(r)
        self.s = int(s)
        self.x = None
        self.y = None
        if 1 > self.r >= secp256k1_n:
            raise BKeyError('Invalid Signature: r is not a positive integer smaller than the curve order')
        elif 1 > self.s >= secp256k1_n:
            raise BKeyError('Invalid Signature: s is not a positive integer smaller than the curve order')
        self._tx_hash = None
        self.tx_hash = tx_hash
        self.secret = None if not secret else int(secret)
        self._der_encoded = to_bytes(der_signature)
        self._signature = to_bytes(signature)
        self._public_key = None
        self.public_key = public_key
        self.k = k
github 1200wd / bitcoinlib / bitcoinlib / keys.py View on Github external
:return dict: Dictionary with format, network and is_private
    """
    if not key:
        raise BKeyError("Key empty, please specify a valid key")
    key_format = ""
    networks = None
    script_types = []
    witness_types = ['legacy']
    multisig = [False]

    if isinstance(key, (bytes, bytearray)) and len(key) in [128, 130]:
        key = to_hexstring(key)

    if not (is_private is None or isinstance(is_private, bool)):
        raise BKeyError("Attribute 'is_private' must be False or True")
    elif isinstance(key, numbers.Number):
        key_format = 'decimal'
        is_private = True
    elif isinstance(key, (bytes, bytearray)) and len(key) in [33, 65] and key[:1] in [b'\2', b'\3']:
        key_format = 'bin_compressed'
        is_private = False
    elif isinstance(key, (bytes, bytearray)) and (len(key) in [33, 65] and key[:1] == b'\4'):
        key_format = 'bin'
        is_private = False
    elif isinstance(key, (bytes, bytearray)) and len(key) == 33 and key[-1:] == b'\1':
        key_format = 'bin_compressed'
        is_private = True
    elif isinstance(key, (bytes, bytearray)) and len(key) == 32:
        key_format = 'bin'
        is_private = True
    elif len(key) == 130 and key[:2] == '04' and not is_private:
github 1200wd / bitcoinlib / bitcoinlib / keys.py View on Github external
if self.depth == 3 and purpose == 44:
            return self
        elif self.depth == 4 and purpose == 45:
            return self
        elif self.depth != 0:
            raise BKeyError("Need a master key to generate account key")

        path = ["%s" % 'm' if self.is_private else 'M', "%d'" % purpose]
        if purpose == 45:
            return self.subkey_for_path(path)
        elif purpose == 48:
            path += ["%d'" % self.network.bip44_cointype, "%d'" % account_id, "%d'" % script_type]
            return self.subkey_for_path(path)
        else:
            raise BKeyError("Unknown purpose %d, cannot determine wallet public cosigner key" % purpose)
github 1200wd / bitcoinlib / bitcoinlib / keys.py View on Github external
def _key_derivation(self, seed):
        """
        Derive extended private key with key and chain part from seed

        :param seed:
        :type seed: bytes

        :return tuple: key and chain bytes
        """
        chain = hasattr(self, 'chain') and self.chain or b"Bitcoin seed"
        i = hmac.new(chain, seed, hashlib.sha512).digest()
        key = i[:32]
        chain = i[32:]
        key_int = change_base(key, 256, 10)
        if key_int >= secp256k1_n:
            raise BKeyError("Key cannot be greater than secp256k1_n. Try another index number.")
        return key, chain
github 1200wd / bitcoinlib / bitcoinlib / keys.py View on Github external
path = path[1:]
        elif path[0] == 'M':  # Use Public master key
            path = path[1:]
            first_public = True
        if path:
            if len(path) > 1:
                _logger.info("Path length > 1 can be slow for larger paths, use Wallet Class to generate keys paths")
            for item in path:
                if not item:
                    raise BKeyError("Could not parse path. Index is empty.")
                hardened = item[-1] in "'HhPp"
                if hardened:
                    item = item[:-1]
                index = int(item)
                if index < 0:
                    raise BKeyError("Could not parse path. Index must be a positive integer.")
                if first_public or not key.is_private:
                    key = key.child_public(index=index, network=network)  # TODO hardened=hardened key?
                    first_public = False
                else:
                    key = key.child_private(index=index, hardened=hardened, network=network)
        return key
github 1200wd / bitcoinlib / bitcoinlib / keys.py View on Github external
:return str: Base58 encoded address
        """
        if (self.compressed and compressed is None) or compressed:
            data = self.public_byte
            self.compressed = True
        else:
            data = self.public_uncompressed_byte
            self.compressed = False
        if encoding is None:
            if self._address_obj:
                encoding = self._address_obj.encoding
            else:
                encoding = 'base58'
        if not self.compressed and encoding == 'bech32':
            raise BKeyError("Uncompressed keys are non-standard for segwit/bech32 encoded addresses")
        if self._address_obj and script_type is None:
            script_type = self._address_obj.script_type
        if not(self._address_obj and self._address_obj.prefix == prefix and self._address_obj.encoding == encoding):
            self._address_obj = Address(data, prefix=prefix, network=self.network, script_type=script_type,
                                        encoding=encoding, compressed=compressed)
        return self._address_obj.address