Exemplo n.º 1
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()
Exemplo n.º 2
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.º 3
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.º 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)
    bip32_path = client.expand_path("44'/0'/0'/0/0")
    address = client.get_address('morningstar', bip32_path)
    print('morningstar address:', 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 wait_for_devices():
    devices = HidTransport.enumerate()
    while not len(devices):
        sys.stderr.write("Please connect KeepKey to computer and press Enter...")
        raw_input()
        devices = HidTransport.enumerate()

    return devices
Exemplo n.º 7
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.º 8
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.º 9
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('Bitcoin', bip32_path)
    print('Bitcoin address:', address)

    client.close()
Exemplo n.º 10
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.º 11
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.º 12
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.º 13
0
def enumerate_hid():
    global TRANSPORT, TRANSPORT_ARGS, TRANSPORT_KWARGS, DEBUG_TRANSPORT, DEBUG_TRANSPORT_ARGS, DEBUG_TRANSPORT_KWARGS

    devices = HidTransport.enumerate()

    if len(devices) > 0:
        if devices[0][1] != None:
            TRANSPORT = HidTransport
            TRANSPORT_ARGS = (devices[0],)
            TRANSPORT_KWARGS = {'debug_link': False}
            DEBUG_TRANSPORT = HidTransport
            DEBUG_TRANSPORT_ARGS = (devices[0],)
            DEBUG_TRANSPORT_KWARGS = {'debug_link': True}
Exemplo n.º 14
0
def enumerate_hid():
    global TRANSPORT, TRANSPORT_ARGS, TRANSPORT_KWARGS, DEBUG_TRANSPORT, DEBUG_TRANSPORT_ARGS, DEBUG_TRANSPORT_KWARGS

    devices = HidTransport.enumerate()

    if len(devices) > 0:
        if devices[0][1] != None:
            TRANSPORT = HidTransport
            TRANSPORT_ARGS = (devices[0], )
            TRANSPORT_KWARGS = {'debug_link': False}
            DEBUG_TRANSPORT = HidTransport
            DEBUG_TRANSPORT_ARGS = (devices[0], )
            DEBUG_TRANSPORT_KWARGS = {'debug_link': True}
Exemplo n.º 15
0
def choose_device(devices):
    if not len(devices):
        raise Exception("No KeepKey connected!")

    if len(devices) == 1:
        try:
            return HidTransport(devices[0])
        except IOError:
            raise Exception("Device is currently in use")

    i = 0
    sys.stderr.write("----------------------------\n")
    sys.stderr.write("Available devices:\n")
    for d in devices:
        try:
            t = HidTransport(d)
        except IOError:
            sys.stderr.write("[-] <device is currently in use>\n")
            continue

        client = KeepKeyClient(t)

        if client.features.label:
            sys.stderr.write("[%d] %s\n" % (i, client.features.label))
        else:
            sys.stderr.write("[%d] <no label>\n" % i)
        t.close()
        i += 1

    sys.stderr.write("----------------------------\n")
    sys.stderr.write("Please choose device to use: ")

    try:
        device_id = int(raw_input())
        return HidTransport(devices[device_id])
    except:
        raise Exception("Invalid choice, exiting...")
Exemplo n.º 16
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.º 17
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.º 18
0
def enumerate_hid():
    global TRANSPORT, TRANSPORT_ARGS, TRANSPORT_KWARGS, DEBUG_TRANSPORT, DEBUG_TRANSPORT_ARGS, DEBUG_TRANSPORT_KWARGS

    try:
        devices = HidTransport.enumerate()
    except Exception:
        print("Error loading HID. HID devices not enumerated.")
        devices = []

    if len(devices) > 0:
        if devices[0][1] != None:
            TRANSPORT = HidTransport
            TRANSPORT_ARGS = (devices[0],)
            TRANSPORT_KWARGS = {'debug_link': False}
            DEBUG_TRANSPORT = HidTransport
            DEBUG_TRANSPORT_ARGS = (devices[0],)
            DEBUG_TRANSPORT_KWARGS = {'debug_link': True}
Exemplo n.º 19
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 == 'bridge':
        from keepkeylib.transport_bridge import BridgeTransport
        return BridgeTransport(path, **kwargs)
    
    if transport_string == 'fake':
        from keepkeylib.transport_fake import FakeTransport
        return FakeTransport(path, **kwargs)
    
    raise NotImplemented("Unknown transport")
Exemplo n.º 20
0
def enumerate(password=''):
    results = []
    for d in HidTransport.enumerate():
        d_data = {}

        path = d[0].decode()
        d_data['type'] = 'keepkey'
        d_data['path'] = path

        try:
            client = KeepkeyClient(path, password)
            if client.client.features.initialized:
                master_xpub = client.get_pubkey_at_path('m/0h')['xpub']
                d_data['fingerprint'] = get_xpub_fingerprint_hex(master_xpub)
            else:
                d_data['error'] = 'Not initialized'
            client.close()
        except Exception as e:
            d_data[
                'error'] = "Could not open client or get fingerprint information: " + str(
                    e)

        results.append(d_data)
    return results
Exemplo n.º 21
0
import sys
import binascii
import itertools
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,
)
Exemplo n.º 22
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.º 23
0
def enumerate_transports():
    """Returns USB HID transports."""
    return [HidTransport(p) for p in HidTransport.enumerate()]
Exemplo n.º 24
0
 def _enumerate_hid(self):
     if self.libraries_available:
         from keepkeylib.transport_hid import HidTransport
         return HidTransport.enumerate()
     return []
Exemplo n.º 25
0
def list_usb():
    from keepkeylib.transport_hid import HidTransport
    return HidTransport.enumerate()
Exemplo n.º 26
0
from __future__ import print_function

import sys
sys.path = [
    '../',
] + sys.path

from keepkeylib.transport_pipe import PipeTransport
from keepkeylib.transport_hid import HidTransport
from keepkeylib.transport_socket import SocketTransportClient

devices = HidTransport.enumerate()

if len(devices) > 0:
    if devices[0][1] != None:
        print('Using TREZOR')
        TRANSPORT = HidTransport
        TRANSPORT_ARGS = (devices[0], )
        TRANSPORT_KWARGS = {'debug_link': False}
        DEBUG_TRANSPORT = HidTransport
        DEBUG_TRANSPORT_ARGS = (devices[0], )
        DEBUG_TRANSPORT_KWARGS = {'debug_link': True}
    else:
        print('Using Raspberry Pi')
        TRANSPORT = HidTransport
        TRANSPORT_ARGS = (devices[0], )
        TRANSPORT_KWARGS = {'debug_link': False}
        DEBUG_TRANSPORT = SocketTransportClient
        DEBUG_TRANSPORT_ARGS = ('trezor.bo:2000', )
        DEBUG_TRANSPORT_KWARGS = {}
else:
Exemplo n.º 27
0
 def _enumerate_hid(self):
     if KEEPKEYLIB:
         from keepkeylib.transport_hid import HidTransport
         return HidTransport.enumerate()
     return []
Exemplo n.º 28
0
def list_usb():
    from keepkeylib.transport_hid import HidTransport
    return HidTransport.enumerate()
Exemplo n.º 29
0
 # try_repeat = random.randint(27,32)
 try_repeat = random.randint(37,38)
 scope.glitch.repeat = try_repeat
 print("Preparing for attempt %d, glitch at %f, %d width" % (i,delay,try_repeat))
 phy.set_power_source("off")
 # phy.set_usb_mode(mode="LS")
 time.sleep(0.5)
 phy.set_power_source("host")
 time.sleep(3.0)
 enumerateStatus = False
 enumerateCount = 0
 while enumerateStatus is False:
   try:
     signal.alarm(10)
     print("Attempting enumeration...")
     path = HidTransport.enumerate()[0][0]
     print("Path OK!")
     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():
Exemplo n.º 30
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.º 31
0
import sys
sys.path = ['../',] + sys.path

from keepkeylib.transport_pipe import PipeTransport
from keepkeylib.transport_hid import HidTransport
from keepkeylib.transport_socket import SocketTransportClient
from keepkeylib.transport_bridge import BridgeTransport

devices = HidTransport.enumerate()

if len(devices) > 0:
    if devices[0][1] != None:
        print 'Using TREZOR'
        TRANSPORT = HidTransport
        TRANSPORT_ARGS = (devices[0],)
        TRANSPORT_KWARGS = {'debug_link': False}
        DEBUG_TRANSPORT = HidTransport
        DEBUG_TRANSPORT_ARGS = (devices[0],)
        DEBUG_TRANSPORT_KWARGS = {'debug_link': True}
    else:
        print 'Using Raspberry Pi'
        TRANSPORT = HidTransport
        TRANSPORT_ARGS = (devices[0],)
        TRANSPORT_KWARGS = {'debug_link': False}
        DEBUG_TRANSPORT = SocketTransportClient
        DEBUG_TRANSPORT_ARGS = ('trezor.bo:2000',)
        DEBUG_TRANSPORT_KWARGS = {}
else:
    print 'Using Emulator'
    TRANSPORT = PipeTransport
    TRANSPORT_ARGS = ('/tmp/pipe.trezor', False)
Exemplo n.º 32
0
 def hid_transport(self, pair):
     from keepkeylib.transport_hid import HidTransport
     return HidTransport(pair)
Exemplo n.º 33
0
def find_device():
    """Returns first USB HID transport."""
    return next(HidTransport(p) for p in HidTransport.enumerate())