Exemplo n.º 1
0
def get_transport(transport_string, path, **kwargs):
    if transport_string == 'usb':
        from keepkeylib.transport_hid import HidTransport

        if path == '':
            try:
                path = list_usb()[0][0]
            except IndexError:
                raise Exception("No KeepKey found on USB")

        for d in HidTransport.enumerate():
            # Two-tuple of (normal_interface, debug_interface)
            if path in d:
                return HidTransport(d, **kwargs)

        raise Exception("Device not found")
 
    if transport_string == 'serial':
        from keepkeylib.transport_serial import SerialTransport
        return SerialTransport(path, **kwargs)

    if transport_string == 'pipe':
        from keepkeylib.transport_pipe import PipeTransport
        return PipeTransport(path, is_device=False, **kwargs)
    
    if transport_string == 'socket':
        from keepkeylib.transport_socket import SocketTransportClient
        return SocketTransportClient(path, **kwargs)
    
    if transport_string == 'fake':
        from keepkeylib.transport_fake import FakeTransport
        return FakeTransport(path, **kwargs)

    raise NotImplementedError("Unknown transport")
Exemplo n.º 2
0
def main():
    # List all connected KeepKeys on USB
    devices = HidTransport.enumerate()

    # Check whether we found any
    if len(devices) == 0:
        print('No KeepKey found')
        return

    # Use first connected device
    transport = HidTransport(devices[0])

    # Creates object for manipulating KeepKey
    client = KeepKeyClient(transport)

    # Print out KeepKey's features and settings
    print(client.features)

    # Get the first address of first BIP44 account
    # (should be the same address as shown in KeepKey wallet Chrome extension)
    bip32_path = client.expand_path("44'/0'/0'/0/0")
    address = client.get_address('morningstar', bip32_path)
    print('morningstar address:', address)

    client.close()
Exemplo n.º 3
0
def find_device():
    """Returns first WebUSB or HID transport."""
    for d in WebUsbTransport.enumerate():
        return WebUsbTransport(d)

    for d in HidTransport.enumerate():
        return HidTransport(d)
Exemplo n.º 4
0
def main():
    # List all connected KeepKeys on USB
    devices = HidTransport.enumerate()

    # Check whether we found any
    if len(devices) == 0:
        print('No KeepKey found')
        return

    # Use first connected device
    transport = HidTransport(devices[0])

    # Creates object for manipulating KeepKey
    client = KeepKeyClient(transport)

    # Print out KeepKey's features and settings
    print(client.features)

    # Get the first address of first BIP44 account
    # (should be the same address as shown in KeepKey wallet Chrome extension)
    mpath = "44'/0'/0'/0"
    bip32_path = client.expand_path(mpath)

    print bip32.serialize(client.get_public_node(bip32_path).node, 0x043587CF)

    for i in range(11):
        child_path = '%s%s' % ("44'/0'/0'/0/", str(i))
        address = client.get_address('tDash', client.expand_path(child_path))
        print 'tDASH address:', child_path, address

    client.close()
 def get_transport():
     from keepkeylib.transport_hid import HidTransport
     count = len(HidTransport.enumerate())
     if not count:
         logging.warning('Number of Keepkey devices: 0')
     for d in HidTransport.enumerate():
         transport = HidTransport(d)
         return transport
Exemplo n.º 6
0
    def __init__(self, path, password=''):
        super(KeepkeyClient, self).__init__(path, password)
        devices = HidTransport.enumerate()
        transport = HidTransport((path.encode(), None))
        self.client = KeepKey(transport)

        # if it wasn't able to find a client, throw an error
        if not self.client:
            raise IOError("no Device")

        self.password = password
        os.environ['PASSPHRASE'] = password
Exemplo n.º 7
0
    def __init__(self, device, path):
        super(KeepKeyClient, self).__init__(device)
        device.close()
        devices = HidTransport.enumerate()
        self.client = None
        for d in devices:
            if d[0] == path:
                transport = HidTransport(d)
                self.client = KeepKey(transport)
                break

        # if it wasn't able to find a client, throw an error
        if not self.client:
            raise IOError("no Device")
Exemplo n.º 8
0
    def _get_transport(self, device):
        self.logger.debug("Trying to connect over USB...")

        if device.path.startswith('web_usb'):
            for d in self._enumerate_web_usb():
                if self._web_usb_path(d) == device.path:
                    from keepkeylib.transport_webusb import WebUsbTransport
                    return WebUsbTransport(d)
        else:
            for d in self._enumerate_hid():
                if str(d[0]) == device.path:
                    from keepkeylib.transport_hid import HidTransport
                    return HidTransport(d)

        raise RuntimeError(f'device {device} not found')
Exemplo n.º 9
0
    def get_client() -> Optional[MyKeepkeyClient]:
        from keepkeylib.transport_hid import HidTransport

        count = len(HidTransport.enumerate())
        if not count:
            logging.warning('Number of Keepkey devices: 0')

        for d in HidTransport.enumerate():
            transport = HidTransport(d)
            client = MyKeepkeyClient(transport, ask_for_pin_callback, ask_for_pass_callback)
            if not device_id or client.features.device_id == device_id:
                return client
            else:
                client.clear_session()
                client.close()
        return None
Exemplo n.º 10
0
def connect_keepkey(ask_for_pin_fun, ask_for_pass_fun):
    try:
        from keepkeylib.transport_hid import HidTransport

        transport = None
        for d in HidTransport.enumerate():
            transport = HidTransport(d)
            break

        if transport:
            client = MyKeepkeyClient(transport, ask_for_pin_fun, ask_for_pass_fun)
            return client
        else:
            return None

    except Exception as e:
        raise
Exemplo n.º 11
0
    def get_client(self):
        if not KEEPKEY:
            give_error('please install github.com/keepkey/python-keepkey')

        if not self.client or self.client.bad:
            d = HidTransport.enumerate()
            if not d:
                give_error('Could not connect to your KeepKey. Please verify the cable is connected and that no other app is using it.')
            self.transport = HidTransport(d[0])
            self.client = QtGuiKeepKeyClient(self.transport)
            self.client.handler = self.handler
            self.client.set_tx_api(self)
            self.client.bad = False
            if not self.atleast_version(1, 0, 0):
                self.client = None
                give_error('Outdated KeepKey firmware. Please update the firmware from https://www.keepkey.com')
        return self.client
Exemplo n.º 12
0
     enumerateStatus = True
     signal.alarm(0)
   except:
     print("Enumerate failed, continuing next pass")
     time.sleep(0.5)
     if enumerateCount == 3:
       break
     enumerateCount += 1
     continue
 if enumerateStatus is False:
   print("Enumerate hard failed, power cycling")
   continue
 print("Fetching path...")
 for d in HidTransport.enumerate():
   if path in d:
     transport = HidTransport(d)
     break
 print("Transport locked, continuing...")
 phy.set_capture_size(1025)
 client = KeepKeyClient(transport)
 print("KeepKeyClient OK, arming glitcher...")
 scope.arm()
 phy.arm()
 print("Arm OK")
 if oneshot:
   input("Hit enter to fire glitch event...")
 try:
   signal.alarm(10)
   data = client.ping("HelloHelloHelloHelloHello")
   print(data)
   if data != "HelloHelloHelloHelloHello":
Exemplo n.º 13
0
def check_hw_wallet():
    printdbg('checking hw wallet')
    #client = None

    client = None
    signing = False

    if TYPE_HW_WALLET.lower().startswith("keepkey"):
        from keepkeylib.client import KeepKeyClient
        from keepkeylib.transport_hid import HidTransport
        import keepkeylib.ckd_public as bip32

        try:
            devices = HidTransport.enumerate()

        except Exception as e:
            err_msg = str(e.args)
            print_err_exit(get_caller_name(), get_function_name(), err_msg)

        if len(devices) == 0:
            print('===> No HW Wallet found')
            signing = False

        else:

            try:
                print('===> keepkey HW Wallet found')
                transport = HidTransport(devices[0])
                client = KeepKeyClient(transport)
                signing = True

            except Exception as e:
                err_msg = str(e.args)
                print_err_exit(get_caller_name(), get_function_name(), err_msg)

    elif TYPE_HW_WALLET.lower().startswith("trezor"):
        from trezorlib.client import TrezorClient
        from trezorlib.transport_hid import HidTransport
        import trezorlib.ckd_public as bip32

        try:
            devices = HidTransport.enumerate()

        except Exception as e:
            err_msg = str(e.args)
            print_err_exit(get_caller_name(), get_function_name(), err_msg)

        if len(devices) == 0:
            print('===> No HW Wallet found')
            signing = False

        else:
            try:
                print('===> trezor HW Wallet found')
                transport = HidTransport(devices[0])
                client = TrezorClient(transport)
                signing = True

            except Exception as e:
                err_msg = str(e.args)
                print_err_exit(get_caller_name(), get_function_name(), err_msg)

    elif TYPE_HW_WALLET.lower().startswith("ledgernanos"):
        #from btchip.btchip import *
        #from btchip.btchipUtils import *

        try:
            devices = getDongle(False)

        except Exception as e:
            err_msg = str(e.args)
            print_err_exit(get_caller_name(), get_function_name(), err_msg)

        if not devices:
            print('===> No HW Wallet found')
            signing = False

        else:
            try:
                print('===> Ledger nano s HW Wallet found')
                client = btchip(devices)
                signing = True

            except Exception as e:
                err_msg = str(e.args)
                print_err_exit(get_caller_name(), get_function_name(), err_msg)

    if client is not None:

        if TYPE_HW_WALLET.lower().startswith("ledgernanos"):
            pass

        else:
            try:
                wallet_supported_coins = list_coins(client)

            except Exception as e:
                err_msg = str(e.args)
                print_err_exit(get_caller_name(), get_function_name(), err_msg)

            if coin_name not in wallet_supported_coins:
                err_msg = 'only following coins supported by wallet\n\t' + \
                    str(wallet_supported_coins)
                print_err_exit(get_caller_name(), get_function_name(), err_msg)

    else:
        err_msg = "Can't run florijncoinmnb without hw wallet"
        print_err_exit(get_caller_name(), get_function_name(), err_msg)

    if TYPE_HW_WALLET.lower().startswith("ledgernanos"):
        mpath = get_mpath()

        return client, signing, mpath

    else:
        try:
            mpath = get_mpath()
            bip32_path = client.expand_path(mpath)
            xpub = bip32.serialize(
                client.get_public_node(bip32_path).node,
                (0x0488B21E if MAINNET else 0x043587CF))

        except AssertionError as e:
            err_msg = str(e.args)
            print_err_exit(get_caller_name(), get_function_name(), err_msg)

        except Exception as e:
            err_msg = str(e.args)
            print_err_exit(get_caller_name(), get_function_name(), err_msg)

        except KeyboardInterrupt:
            print_err_exit(get_caller_name(), get_function_name(),
                           "KeyboardInterrupt")

    printdbg('check_hw_wallet : signing : %s' % signing)
    printdbg('check_hw_wallet : xpub[:7] : %s' % xpub[:7])
    printdbg('check_hw_wallet : xpub[-7:] : %s' % xpub[-7:])
    printdbg('check_hw_wallet : mpath : %s' % mpath)

    return client, signing, bip32, mpath, xpub
Exemplo n.º 14
0
from keepkeylib.client import KeepKeyClient
from keepkeylib.transport_hid import HidTransport
import keepkeylib.types_pb2 as proto_types
from keepkeylib import tx_api
from keepkeylib.tx_api import TXAPIDashTestnet

tx_api.rpcuser = '******'
tx_api.rpcpassword = '******'

devices = HidTransport.enumerate()

if len(devices) == 0:
    print('No KeepKey found')
    sys.exit()

transport = HidTransport(devices[0])
client = KeepKeyClient(transport)
client.set_tx_api(TXAPIDashTestnet())

inp1 = proto_types.TxInputType(
    address_n=[44 | 0x80000000, 165 | 0x80000000, 0 | 0x80000000, 0,
               0],  # yjJUQ42u8Z86s9LiUmNgvS9dSzhunWbuQR
    # amount=500000000
    prev_hash=binascii.unhexlify(
        '4a1f3f89d95dd162e30399386dd7748c7fa02ec958320f4542923cf3a63fde48'),
    prev_index=1,
)

out1 = proto_types.TxOutputType(
    address='yV7G6wcfkqfjw3SyykJzYnsL3fqJByqXYG',
    amount=500000000 - 10000,
Exemplo n.º 15
0
def enumerate_transports():
    """Returns USB HID transports."""
    return [HidTransport(p) for p in HidTransport.enumerate()]
Exemplo n.º 16
0
def get_device_list(return_clients: bool = True, passphrase_encoding: Optional[str] = 'NFC',
                    allow_bootloader_mode: bool = False) \
        -> Tuple[List[Dict], List[Exception]]:
    """
    :return: Tuple[List[Dict <{'client': MyTrezorClient, 'device_id': str, 'desc',: str, 'model': str}>],
                   List[Exception]]
    """
    from keepkeylib.transport_hid import HidTransport

    ret_list = []
    exceptions: List[Exception] = []
    device_ids = []
    was_bootloader_mode = False

    for d in HidTransport.enumerate():
        try:
            transport = HidTransport(d)
            client = MyKeepkeyClient(transport, ask_for_pin_callback, ask_for_pass_callback, passphrase_encoding)

            if client.features.bootloader_mode:
                if was_bootloader_mode:
                    # in bootloader mode the device_id attribute isn't available, so for a given client object
                    # we are unable to distinguish between being the same device reached with the different
                    # transport and being another device
                    # for that reason, to avoid returning duplicate clients for the same device, we don't return
                    # more than one instance of a device in bootloader mod
                    client.close()
                    continue
                was_bootloader_mode = True

            if (not client.features.bootloader_mode or allow_bootloader_mode) and \
                (client.features.device_id not in device_ids or client.features.bootloader_mode):

                version = f'{client.features.major_version}.{client.features.minor_version}.' \
                          f'{client.features.patch_version}'
                if client.features.label:
                    desc = client.features.label
                else:
                    desc = '[UNNAMED]'
                desc = f'{desc} (ver: {version}, id: {client.features.device_id})'

                c = {
                    'client': client,
                    'device_id': client.features.device_id,
                    'desc': desc,
                    'model': client.features.model,
                    'bootloader_mode': client.features.bootloader_mode
                }

                ret_list.append(c)
                device_ids.append(client.features.device_id)  # beware: it's empty in bootloader mode
            else:
                # the same device is already connected using different connection medium
                client.close()
        except Exception as e:
            logging.warning(
                f'Cannot create Keepkey client ({d.__class__.__name__}) due to the following error: ' + str(e))
            exceptions.append(e)

    if not return_clients:
        for cli in ret_list:
            cli['client'].close()
            cli['client'] = None

    return ret_list, exceptions
Exemplo n.º 17
0
 def hid_transport(self, pair):
     from keepkeylib.transport_hid import HidTransport
     return HidTransport(pair)
Exemplo n.º 18
0
def find_device():
    """Returns first USB HID transport."""
    return next(HidTransport(p) for p in HidTransport.enumerate())