def get_all_clients(ui_factory=None): if ui_factory is None: ui_factory = ClickUI return [ TrezorClient(device, ui_factory()) for device in enumerate_devices() ]
def main(): # List all connected TREZORs on USB devices = HidTransport.enumerate() # Check whether we found any if len(devices) == 0: print('No TREZOR found') return # Use first connected device transport = HidTransport(devices[0]) # Creates object for manipulating TREZOR client = TrezorClient(transport) # Print out TREZOR's features and settings print(client.features) # Get the first address of first BIP44 account # (should be the same address as shown in wallet.trezor.io) bip32_path = client.expand_path("44'/42'/0'/0/0") address = client.get_address('Decred', bip32_path) print('Decred address:', address) address_n = client.expand_path("0") xpub = client.get_public_node('Decred', address_n) print('xpub: ', xpub) client.close()
def setUp(self): transport = config.TRANSPORT(*config.TRANSPORT_ARGS, **config.TRANSPORT_KWARGS) if hasattr(config, 'DEBUG_TRANSPORT'): debug_transport = config.DEBUG_TRANSPORT( *config.DEBUG_TRANSPORT_ARGS, **config.DEBUG_TRANSPORT_KWARGS) self.client = TrezorDebugClient(transport) self.client.set_debuglink(debug_transport) else: self.client = TrezorClient(transport) self.client.set_tx_api(tx_api.TxApiBitcoin) # self.client.set_buttonwait(3) # 1 2 3 4 5 6 7 8 9 10 11 12 self.mnemonic12 = 'alcohol woman abuse must during monitor noble actual mixed trade anger aisle' self.mnemonic18 = 'owner little vague addict embark decide pink prosper true fork panda embody mixture exchange choose canoe electric jewel' self.mnemonic24 = 'dignity pass list indicate nasty swamp pool script soccer toe leaf photo multiply desk host tomato cradle drill spread actor shine dismiss champion exotic' self.mnemonic_all = ' '.join(['all'] * 12) self.pin4 = '1234' self.pin6 = '789456' self.pin8 = '45678978' self.client.wipe_device() print("Setup finished") print("--------------")
def Create_wallet_file(): # create the clinet object devices = Wait_for_devices() transport = Choose_device(devices) client = TrezorClient(transport) # Label your wallet, something like 'lumen'. print('Please provide label for new drive: ') label = input() print('Computer asked TREZOR for new strong password.\n') print('Please confirm action on your device.\n') trezor_entropy = client.get_entropy(32) urandom_entropy = os.urandom(32) passw = hashlib.sha256(trezor_entropy + urandom_entropy).digest() if len(passw) != 32: raise Exception("32 bytes password expected") bip32_path = [10, 0] passw_encrypted = client.encrypt_keyvalue(bip32_path, label, passw, False, True) wallet_info = {'label': label, 'bip32_path': bip32_path, 'password_encrypted_hex': binascii.hexlify(passw_encrypted).decode(), 'Address':Keypair.from_raw_seed(passw).address().decode()} #Store the wallet Information with open('Stellar_wallet.json', 'w') as fp: json.dump(wallet_info, fp) print('Please disconnect your Trezor hardware wallet.')
def Choose_device(devices): if not len(devices): raise Exception("No TREZOR connected!") if len(devices) == 1: try: return HidTransport(devices[0]) except OSError: raise Exception("Device is currently in use, try reconnect the device") i = 0 print("----------------------------\n") print("Available devices:\n") for d in devices: try: client = TrezorClient(d) except OSError: sys.stderr.write("[-] <device is currently in use>\n") continue if client.features.label: print("[%d] %s\n" % (i, client.features.label)) else: print("[%d] <no label>\n" % i) client.close() i += 1 print("----------------------------\n") try: device_id = int(input("Please choose device to use:")) return HidTransport(devices[device_id]) except: raise Exception("Invalid choice, exiting...")
def main(): # List all connected TREZORs on USB devices = HidTransport.enumerate() # Check whether we found any if len(devices) == 0: print 'No TREZOR found' return # Use first connected device transport = HidTransport(devices[0]) # Creates object for manipulating TREZOR client = TrezorClient(transport) # Print out TREZOR's features and settings print client.features # Get the first address of first BIP44 account # (should be the same address as shown in mytrezor.com) bip32_path = client.expand_path("44'/0'/0'/0/0") address = client.get_address('Bitcoin', bip32_path) print 'Bitcoin address:', address client.close()
def main(): client = TrezorClient(UdpTransport()) masterKey = getMasterKey(client) # print('master key:', masterKey) fileName = getFileEncKey(masterKey)[0] # print('file name:', fileName) path = os.path.expanduser('~/Dropbox/Apps/TREZOR Password Manager/') # print('path to file:', path) encKey = getFileEncKey(masterKey)[2] # print('enckey:', encKey) jsonraw = decryptStorageRaw(sys.stdin, encKey) #sys.stdout.write(jsonraw) #return parsed_json = json.loads(jsonraw) entries = parsed_json['entries'] decodeEntries(entries, client) sys.stdout.write(json.dumps(parsed_json, separators=(',', ':'))) return
def get_tz_priv(coin, path): session_id = bytes.fromhex(environ.get('TZ_SESSIONID', '')) if trezor and len(session_id) == 32: device = get_transport() client = TrezorClient(transport=device, ui=ClickUI(), session_id=session_id) n_path = parse_path( "m/10065'/0'") # Logical path for BIP0065 operation info = get_public_node(client, n_path, coin_name=coin) side, pubkey = (info.node.public_key[0], info.node.public_key[1:]) left = True if side == 2 else False print("seed", b2x(pubkey), side) priv = encrypt_keyvalue(client, n_path, path, pubkey, ask_on_decrypt=side, ask_on_encrypt=False) client.close() print("priv", b2x(priv), left) is_valid(priv) return CBitcoinSecret.from_secret_bytes(priv) else: print("trezorlib must be available") print("see: https://pypi.org/project/trezor/") print("TZ_SESSIONID enviroinment variable required") print("See: trezorctl get-session --help") sys.exit(2)
def main(): try: # List all connected TREZORs on USB devices = HidTransport.enumerate() # Check whether we found any if len(devices) == 0: input('No TREZOR found. Press any key...') return # Use first connected device transport = HidTransport(devices[0]) # Creates object for manipulating TREZOR client = TrezorClient(transport) # Print out TREZOR's features and settings print(client.features) # # Get the first address of first BIP44 account # # (should be the same address as shown in wallet.trezor.io) # bip32_path = client.expand_path("44'/0'/0'/0/0") # address = client.get_address('Bitcoin', bip32_path) # print('Bitcoin address:', address) client.close() input('Press any key...') except Exception as e: print(str(e)) traceback.print_exc(file=sys.stdout) input('Press any key...')
def initDevice(self): printDbg("Initializing Trezor") with self.lock: self.status = 0 devices = enumerate_devices() if not len(devices): # No device connected return # Use the first device for now d = devices[0] ui = TrezorUi() try: self.client = TrezorClient(d, ui) except IOError: raise Exception("TREZOR device is currently in use") printOK("Trezor HW device connected [v. %s.%s.%s]" % (self.client.features.major_version, self.client.features.minor_version, self.client.features.patch_version)) self.status = 1 model = self.client.features.model or "1" if not self.checkModel(model): self.status = 3 self.messages[ 3] = "Wrong device model (%s) detected.\nLooking for model %s." % ( HW_devices[self.model][0], model) return required_version = MINIMUM_FIRMWARE_VERSION[model] printDbg("Current version is %s (minimum required: %s)" % (str(self.client.version), str(required_version))) # Check device is unlocked bip32_path = parse_path(MPATH + "%d'/0/%d" % (0, 0)) _ = btc.get_address(self.client, 'PIVX', bip32_path, False) self.status = 2
def decrypt(type, domain, secret): transport = get_transport() client = TrezorClient(transport, ClickUI()) dom = type.upper() + ": " + domain dec = decrypt_keyvalue(client, BIP32_PATH, dom, secret, False, True) client.close() return dec
def main(): # List all debuggable TREZORs devices = [device for device in enumerate_devices() if hasattr(device, 'find_debug')] # Check whether we found any if len(devices) == 0: print('No TREZOR found') return # Use first connected device transport = devices[0] debug_transport = devices[0].find_debug() # Creates object for manipulating TREZOR client = TrezorClient(transport) debug = DebugLink(debug_transport) sector = int(sys.argv[1]) f = open(sys.argv[2], "rb") content = f.read(sectorlens[sector]) if (len(content) != sectorlens[sector]): print("Not enough bytes in file") return debug.flash_erase(sector) step = 0x400 for offset in range(0, sectorlens[sector], step): debug.memory_write(sectoraddrs[sector] + offset, content[offset:offset + step], flash=True) client.close()
def _connect(self): self.wirelink = get_transport(self.path) self.client = ( TrezorClientDebugLink(self.wirelink) if self.debug else TrezorClient(self.wirelink, ui=ui.ClickUI()) )
def choose_device(devices): if not len(devices): raise RuntimeError("No TREZOR connected!") if len(devices) == 1: try: return devices[0] except IOError: raise RuntimeError("Device is currently in use") i = 0 sys.stderr.write("----------------------------\n") sys.stderr.write("Available devices:\n") for d in devices: try: client = TrezorClient(d) except IOError: sys.stderr.write("[-] <device is currently in use>\n") continue if client.features.label: sys.stderr.write("[%d] %s\n" % (i, client.features.label)) else: sys.stderr.write("[%d] <no label>\n" % i) client.close() i += 1 sys.stderr.write("----------------------------\n") sys.stderr.write("Please choose device to use:") try: device_id = int(input()) return devices[device_id] except: raise ValueError("Invalid choice, exiting...")
def main(): args = parse_args(Commands) if args.cmd == 'list': devices = list_usb() if args.json: print json.dumps(devices) else: for dev in devices: if dev[1] != None: print "%s - debuglink enabled" % dev[0] else: print dev[0] return transport = get_transport(args.transport, args.path) if args.verbose: client = TrezorClientDebug(transport) else: client = TrezorClient(transport) client.set_tx_api(TXAPIBitcoin()) cmds = Commands(client) res = args.func(cmds, args) if args.json: print json.dumps(res, sort_keys=True, indent=4) else: print res
def get_trezor_client() -> TrezorClient: """ Wrapper to open connection to Trezor One Returns: TrezorClient object """ # List all connected TREZORs on USB devices = enumerate_devices() # Check whether we found any if len(devices) == 0: raise ConnectionError('No TREZOR found') # Use first connected device #transport = devices[0] transport = get_transport() ui = ClickUI() # Creates object for manipulating TREZOR client = TrezorClient(transport, ui) return client
def choose_device(devices: Sequence["Transport"]) -> "Transport": if not len(devices): raise RuntimeError("No Trezor connected!") if len(devices) == 1: try: return devices[0] except IOError: raise RuntimeError("Device is currently in use") i = 0 sys.stderr.write("----------------------------\n") sys.stderr.write("Available devices:\n") for d in devices: try: client = TrezorClient(d, ui=ClickUI()) except IOError: sys.stderr.write("[-] <device is currently in use>\n") continue if client.features.label: sys.stderr.write(f"[{i}] {client.features.label}\n") else: sys.stderr.write(f"[{i}] <no label>\n") client.close() i += 1 sys.stderr.write("----------------------------\n") sys.stderr.write("Please choose device to use:") try: device_id = int(input()) return devices[device_id] except Exception: raise ValueError("Invalid choice, exiting...")
def main(): client = TrezorClient(UdpTransport()) print() print('Confirm operation on TREZOR') print() masterKey = getMasterKey(client) # print('master key:', masterKey) fileName = getFileEncKey(masterKey)[0] # print('file name:', fileName) path = os.path.expanduser('~/Dropbox/Apps/TREZOR Password Manager/') # print('path to file:', path) encKey = getFileEncKey(masterKey)[2] # print('enckey:', encKey) full_path = path + fileName parsed_json = decryptStorage(full_path, encKey) # list entries entries = parsed_json['entries'] printEntries(entries, client) return
def main(): if "encfs_root" not in os.environ: sys.stderr.write( "\nThis is not a standalone script and is not meant to be run independently.\n" ) sys.stderr.write( "\nUsage: encfs --standard --extpass=./encfs_aes_getpass.py ~/.crypt ~/crypt\n" ) sys.exit(1) devices = wait_for_devices() transport = choose_device(devices) client = TrezorClient(transport, ui=ClickUI()) rootdir = os.environ["encfs_root"] # Read "man encfs" for more passw_file = os.path.join(rootdir, "password.dat") if not os.path.exists(passw_file): # New encfs drive, let's generate password sys.stderr.write("Please provide label for new drive: ") label = input() sys.stderr.write("Computer asked Trezor for new strong password.\n") # 32 bytes, good for AES trezor_entropy = trezorlib.misc.get_entropy(client, 32) urandom_entropy = os.urandom(32) passw = hashlib.sha256(trezor_entropy + urandom_entropy).digest() if len(passw) != 32: raise ValueError("32 bytes password expected") bip32_path = [10, 0] passw_encrypted = trezorlib.misc.encrypt_keyvalue( client, bip32_path, label, passw, False, True ) data = { "label": label, "bip32_path": bip32_path, "password_encrypted_hex": passw_encrypted.hex(), } json.dump(data, open(passw_file, "w")) # Let's load password data = json.load(open(passw_file, "r")) passw = trezorlib.misc.decrypt_keyvalue( client, data["bip32_path"], data["label"], bytes.fromhex(data["password_encrypted_hex"]), False, True, ) print(passw)
def main(): # List all connected TREZORs on USB devices = HidTransport.enumerate() # Check whether we found any if len(devices) == 0: print('No TREZOR found') return # Use first connected device transport = devices[0] debug_transport = devices[0].find_debug() # Creates object for manipulating TREZOR client = TrezorClient(transport) debug = DebugLink(debug_transport) arg1 = int(sys.argv[1], 16) arg2 = int(sys.argv[2], 16) step = 0x400 if arg2 >= 0x400 else arg2 f = open('memory.dat', 'wb') for addr in range(arg1, arg1 + arg2, step): mem = debug.memory_read(addr, step) f.write(mem) f.close() client.close()
def get_client(): devices = HidTransport.enumerate() # list all connected TREZORs on USB if len(devices) == 0: # check whether we found any return None transport = HidTransport(devices[0]) # use first connected device return TrezorClient( transport) # creates object for communicating with TREZOR
def main(): if 'encfs_root' not in os.environ: sys.stderr.write( '\nThis is not a standalone script and is not meant to be run independently.\n' ) sys.stderr.write( '\nUsage: encfs --standard --extpass=./encfs_aes_getpass.py ~/.crypt ~/crypt\n' ) sys.exit(1) devices = wait_for_devices() transport = choose_device(devices) client = TrezorClient(transport) rootdir = os.environ['encfs_root'] # Read "man encfs" for more passw_file = os.path.join(rootdir, 'password.dat') if not os.path.exists(passw_file): # New encfs drive, let's generate password sys.stderr.write('Please provide label for new drive: ') label = input() sys.stderr.write('Computer asked TREZOR for new strong password.\n') sys.stderr.write('Please confirm the action on your device ...\n') # 32 bytes, good for AES trezor_entropy = client.get_entropy(32) urandom_entropy = os.urandom(32) passw = hashlib.sha256(trezor_entropy + urandom_entropy).digest() if len(passw) != 32: raise ValueError("32 bytes password expected") bip32_path = [10, 0] passw_encrypted = client.encrypt_keyvalue(bip32_path, label, passw, False, True) data = { 'label': label, 'bip32_path': bip32_path, 'password_encrypted_hex': binascii.hexlify(passw_encrypted).decode('ascii') } json.dump(data, open(passw_file, 'w')) # Let's load password data = json.load(open(passw_file, 'r')) sys.stderr.write('Please confirm the action on your device ...\n') passw = client.decrypt_keyvalue( data['bip32_path'], data['label'], binascii.unhexlify(data['password_encrypted_hex']), False, True) print(passw)
def __init__(self, w3, index): self.w3 = w3 self.client = TrezorClient(HidTransport.enumerate()[0]) self.index = index self.address = self.w3.toChecksumAddress("0x" + bytes( self.client.ethereum_get_address( [44 + BIP32_HARDEN, 60 + BIP32_HARDEN, BIP32_HARDEN, 0, index])).hex())
def encrypt(type, domain, secret): transport = get_transport() client = TrezorClient(transport, ClickUI()) dom = type.upper() + ": " + domain enc = encrypt_keyvalue(client, BIP32_PATH, dom, secret.encode(), False, True) client.close() return enc.hex()
def get_trezor_client(): devices = HidTransport.enumerate() if len(devices) == 0: worklog.error('could not find any trezor device connected') return None transport = HidTransport(devices[0]) client = TrezorClient(transport) return client
def device_version(): device = common.get_device() if not device: raise RuntimeError() client = TrezorClient(device) if client.features.model == "T": return 2 else: return 1
def _connect(self): self.wirelink = get_transport(self.path) self.client = (TrezorClientDebugLink(self.wirelink) if self.debug else TrezorClient(self.wirelink)) if self.debug: try: self.debuglink = self.wirelink.find_debug() self.client.set_debuglink(self.debuglink) except Exception as e: pass
def find_trezor(self): u"""Selects a trezor device and initialize the client.""" devices = TrezorDevice.enumerate() if len(devices) == 0: raise NoTrezorFoundError('No Trezor device was found. Make sure it' ' is plugged.') transport = devices[0] trezor = TrezorClient(transport, ui=ui.ClickUI()) return trezor
def __init__(self, transport, handler, plugin): self.client = TrezorClient(transport, ui=self) self.plugin = plugin self.device = plugin.device self.handler = handler self.msg = None self.creating_wallet = False self.in_flow = False self.used()
def client(): # pylint: disable=import-error from trezorlib.client import TrezorClient from trezorlib.transport_hid import HidTransport from trezorlib.messages_pb2 import PassphraseAck devices = list(HidTransport.enumerate()) if len(devices) != 1: msg = '{:d} Trezor devices found'.format(len(devices)) raise IOError(msg) t = TrezorClient(HidTransport(devices[0])) t.callback_PassphraseRequest = lambda msg: PassphraseAck(passphrase='') return t