Esempio n. 1
0
    def __init__(self, path, password=''):
        super(TrezorClient, self).__init__(path, password)
        if path.startswith('udp'):
            logging.debug('Simulator found, using DebugLink')
            transport = get_transport(path)
            self.client = TrezorClientDebugLink(transport=transport)
        else:
            self.client = Trezor(transport=get_transport(path), ui=ClickUI())

        # 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
Esempio n. 2
0
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
Esempio n. 3
0
 def _connect(self):
     self.wirelink = get_transport(self.path)
     self.client = (
         TrezorClientDebugLink(self.wirelink)
         if self.debug
         else TrezorClient(self.wirelink, ui=ui.ClickUI())
     )
Esempio n. 4
0
    def __enter__(self):
        args = [self.executable]
        env = ENV
        if self.gen == "core":
            args += ["-m", "main"]
            # for firmware 2.1.2 and newer
            env["TREZOR_PROFILE_DIR"] = self.workdir.name
            # for firmware 2.1.1 and older
            env["TREZOR_PROFILE"] = self.workdir.name
        self.process = subprocess.Popen(args,
                                        cwd=self.workdir.name,
                                        env=env,
                                        stdout=open(os.devnull, "w"))
        # wait until emulator is listening
        for _ in range(300):
            try:
                time.sleep(0.1)
                transport = get_transport("udp:127.0.0.1:21324")
                break
            except TransportException:
                pass
            if self.process.poll() is not None:
                self._cleanup()
                raise RuntimeError("Emulator proces died")
        else:
            # could not connect after 300 attempts * 0.1s = 30s of waiting
            self._cleanup()
            raise RuntimeError("Can't connect to emulator")

        self.client = TrezorClientDebugLink(transport)
        self.client.open()
        check_version(self.tag, self.client.version)
        return self
Esempio n. 5
0
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
Esempio n. 6
0
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()
Esempio n. 7
0
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 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
Esempio n. 9
0
    def _get_transport(self, path=None):
        """Reimplemented trezorlib.transport.get_transport for old trezorlib.
        Remove this when we start to require trezorlib 0.9.2
        """
        try:
            from trezorlib.transport import get_transport
        except ImportError:
            # compat for trezorlib < 0.9.2
            def get_transport(path=None, prefix_search=False):
                if path is None:
                    try:
                        return self._enumerate_devices()[0]
                    except IndexError:
                        raise Exception("No TREZOR device found") from None

                def match_prefix(a, b):
                    return a.startswith(b) or b.startswith(a)

                transports = [
                    t for t in self._all_transports()
                    if match_prefix(path, t.PATH_PREFIX)
                ]
                if transports:
                    return transports[0].find_by_path(path)
                raise Exception("Unknown path prefix '%s'" % path)

        return get_transport(path)
Esempio n. 10
0
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()
Esempio n. 11
0
    def __init__(self, device, path):
        super(TrezorClient, self).__init__(device)
        device.close()
        self.client = Trezor(transport=get_transport("hid:" + path.decode()))

        # if it wasn't able to find a client, throw an error
        if not self.client:
            raise IOError("no Device")
Esempio n. 12
0
def find_device():
    """Selects a transport based on `TREZOR_PATH` environment variable.

    If unset, picks first connected device.
    """
    try:
        return get_transport(os.environ.get("TREZOR_PATH"))
    except Exception as e:  # pylint: disable=broad-except
        log.debug("Failed to find a Trezor device: %s", e)
Esempio n. 13
0
def get_device():
    path = os.environ.get("TREZOR_PATH")
    if path:
        return get_transport(path)
    else:
        devices = enumerate_devices()
        for d in devices:
            if hasattr(d, "find_debug"):
                return d
        raise RuntimeError("No debuggable device found")
Esempio n. 14
0
def get_device():
    path = os.environ.get("TREZOR_PATH")
    if path:
        return get_transport(path)
    else:
        devices = enumerate_devices()
        for device in devices:
            if hasattr(device, "find_debug"):
                return device
        raise RuntimeError("No debuggable device found")
Esempio n. 15
0
    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
Esempio n. 16
0
    def unlock_trezor(self, device_path, derivation_path):
        """Unlock a Trezor for signing transactions to this network.

        :param device_path: Device path of the Trezor
        :param derivation_path: Derivation path of the key to use
        :return: True if success, else False
        """
        try:
            device = get_transport(device_path, prefix_search=False)
        except Exception:
            try:
                device = get_transport(device_path, prefix_search=True)
            except Exception:
                logger.exception('Failed to find Trezor device on path %s',
                                 device_path)
                return False

        self.trezor = TrezorClient(transport=device, ui=ClickUI())

        self.address_n = parse_path(derivation_path)
        self.address = self.normalize_address(
            trezoreth.get_address(self.trezor, self.address_n).hex())
        return True
Esempio n. 17
0
def main():
    try:
        transport = get_transport()
    except Exception as e:
        print(e)
        return

    client = TrezorClient(transport=transport, ui=ui.ClickUI())

    print()
    print('Confirm operation on TREZOR')
    print()

    masterKey = getMasterKey(client)
    # print('master key:', masterKey)

    fileName = getFileEncKey(masterKey)[0]
    # print('file name:', fileName)

    home = os.path.expanduser('~')
    path = os.path.join(home, 'Dropbox', 'Apps', 'TREZOR Password Manager')
    # print('path to file:', path)

    encKey = getFileEncKey(masterKey)[2]
    # print('enckey:', encKey)

    full_path = os.path.join(path, fileName)
    parsed_json = decryptStorage(full_path, encKey)

    # list entries
    entries = parsed_json['entries']
    printEntries(entries)

    entry_id = input('Select entry number to decrypt: ')
    entry_id = str(entry_id)

    plain_nonce = getDecryptedNonce(client, entries[entry_id])

    pwdArr = entries[entry_id]['password']['data']
    pwdHex = ''.join([hex(x)[2:].zfill(2) for x in pwdArr])
    print('password: '******'safe_note']['data']
    safeNoteHex = ''.join([hex(x)[2:].zfill(2) for x in safeNoteArr])
    print('safe_note:',
          decryptEntryValue(plain_nonce, bytes.fromhex(safeNoteHex)))

    return
Esempio n. 18
0
def main():
    try:
        transport = get_transport()
    except Exception as e:
        print(e)
        return

    client = TrezorClient(transport=transport, ui=ui.ClickUI())

    print()
    print('Confirm operation on TREZOR')
    print()

    masterKey = getMasterKey(client)
    # print('master key:', masterKey)

    fileName = getFileEncKey(masterKey)[0]
    # print('file name:', fileName)

    home = os.path.expanduser('~')
    path = os.path.join(home, 'Dropbox', 'Apps', 'TREZOR Password Manager')
    # print('path to file:', path)

    encKey = getFileEncKey(masterKey)[2]
    # print('enckey:', encKey)

    full_path = os.path.join(path, fileName)
    parsed_json = decryptStorage(full_path, encKey)

    # list entries
    entries = parsed_json['entries']
    printEntries(entries)

    entry_id = input('Select entry number to decrypt: ')
    entry_id = str(entry_id)

    plain_nonce = getDecryptedNonce(client, entries[entry_id])

    pwdArr = entries[entry_id]['password']['data']
    pwdHex = ''.join([hex(x)[2:].zfill(2) for x in pwdArr])
    print('password: '******'safe_note']['data']
    safeNoteHex = ''.join([hex(x)[2:].zfill(2) for x in safeNoteArr])
    print('safe_note:', decryptEntryValue(plain_nonce, bytes.fromhex(safeNoteHex)))

    return
def main():
    try:
        client = TrezorClient(get_transport(), ui=ui.ClickUI())
    except Exception as e:
        print(e)
        return

    arg1 = sys.argv[1]                     # output file
    arg2 = int(sys.argv[2], 10)            # total number of how many bytes of entropy to read
    step = 1024 if arg2 >= 1024 else arg2  # trezor will only return 1KB at a time

    with io.open(arg1, 'wb') as f:
        for i in range(0, arg2, step):
            entropy = misc.get_entropy(client, step)
            f.write(entropy)

    client.close()
Esempio n. 20
0
def main():
    try:
        client = TrezorClient(get_transport())
    except Exception as e:
        print(e)
        return

    arg1 = sys.argv[1]                     # output file
    arg2 = int(sys.argv[2], 10)            # total number of how many bytes of entropy to read
    step = 1024 if arg2 >= 1024 else arg2  # trezor will only return 1KB at a time

    with io.open(arg1, 'wb') as f:
        for i in range(0, arg2, step):
            entropy = client.get_entropy(step)
            f.write(entropy)

    client.close()
Esempio n. 21
0
def main():
    # Use first connected device
    transport = get_transport()

    # 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()
Esempio n. 22
0
def main() -> None:
    try:
        transport = get_transport()
    except Exception as e:
        print(e)
        return

    client = TrezorClient(transport=transport, ui=ui.ClickUI())

    print()
    print("Confirm operation on Trezor")
    print()

    masterKey = getMasterKey(client)
    # print('master key:', masterKey)

    fileName = getFileEncKey(masterKey)[0]
    # print('file name:', fileName)

    home = os.path.expanduser("~")
    path = os.path.join(home, "Dropbox", "Apps", "TREZOR Password Manager")
    # print('path to file:', path)

    encKey = getFileEncKey(masterKey)[2]
    # print('enckey:', encKey)

    full_path = os.path.join(path, fileName)
    parsed_json = decryptStorage(full_path, encKey)

    # list entries
    entries = parsed_json["entries"]
    printEntries(entries)

    entry_id = input("Select entry number to decrypt: ")
    entry_id = str(entry_id)

    plain_nonce = getDecryptedNonce(client, entries[entry_id])

    pwdArr = entries[entry_id]["password"]["data"]
    pwdHex = "".join([hex(x)[2:].zfill(2) for x in pwdArr])
    print("password: "******"safe_note"]["data"]
    safeNoteHex = "".join([hex(x)[2:].zfill(2) for x in safeNoteArr])
    print("safe_note:", decryptEntryValue(plain_nonce, bytes.fromhex(safeNoteHex)))
Esempio n. 23
0
    def open(cls):
        #pdb.set_trace()
        try:
            cls.transport = get_transport(None, prefix_search=False)
        except StopIteration as e:
            debug()
            pdb.set_trace()

        init_msg = proto.Initialize()

        if cls.state is not None:
            init_msg.state = cls.state

        try:
            cls.features = cls.call_raw(init_msg)
            logging.info("call_raw transport.write(msg): %s", init_msg)
        except (TransportException, USBErrorBusy):
            raise OpenCredstickError("Error opening Trezor")
Esempio n. 24
0
def get_device():
    path = os.environ.get("TREZOR_PATH")
    interact = int(os.environ.get("INTERACT", 0))
    if path:
        try:
            transport = get_transport(path)
            return TrezorClientDebugLink(transport, auto_interact=not interact)
        except Exception as e:
            raise RuntimeError("Failed to open debuglink for {}".format(path)) from e

    else:
        devices = enumerate_devices()
        for device in devices:
            try:
                return TrezorClientDebugLink(device, auto_interact=not interact)
            except Exception:
                pass
        else:
            raise RuntimeError("No debuggable device found")
Esempio n. 25
0
def get_device():
    path = os.environ.get("TREZOR_PATH")
    if path:
        transport = get_transport(path)
    else:
        devices = enumerate_devices()
        for device in devices:
            if hasattr(device, "find_debug"):
                transport = device
                break
        else:
            raise RuntimeError("No debuggable device found")
    env_interactive = int(os.environ.get("INTERACT", 0))
    try:
        return TrezorClientDebugLink(transport,
                                     auto_interact=not env_interactive)
    except Exception as e:
        raise RuntimeError("Failed to open debuglink for {}".format(
            transport.get_path())) from e
Esempio n. 26
0
def main():
    transport = get_transport(os.environ.get("TREZOR_PATH"))
    identity_proto = IdentityType(proto='gpg', host='foo@bar')
    client = TrezorClient(transport=transport, ui=ClickUI(), state=None)

    digest = sys.stdin.buffer.read()
    assert len(digest) == 64, len(digest)

    result = sign_identity(client=client,
                           identity=identity_proto,
                           challenge_hidden=digest,
                           challenge_visual='',
                           ecdsa_curve_name='ed25519')

    assert len(result.signature) == 65, result
    assert result.signature[:1] == b'\x00'
    sig = bytes(result.signature[1:])

    sys.stdout.buffer.write(sig)
Esempio n. 27
0
def get_device():
    path = os.environ.get("TREZOR_PATH")
    if path:
        transport = get_transport(path)
    else:
        devices = enumerate_devices()
        for device in devices:
            if hasattr(device, "find_debug"):
                transport = device
                break
        else:
            raise RuntimeError("No debuggable device found")
    env_interactive = int(os.environ.get("INTERACT", 0))
    try:
        return TrezorClientDebugLink(transport, auto_interact=not env_interactive)
    except Exception as e:
        raise RuntimeError(
            "Failed to open debuglink for {}".format(transport.get_path())
        ) from e
Esempio n. 28
0
def _raw_client(request: pytest.FixtureRequest) -> Client:
    path = os.environ.get("TREZOR_PATH")
    interact = int(os.environ.get("INTERACT", 0))
    if path:
        try:
            transport = get_transport(path)
            return Client(transport, auto_interact=not interact)
        except Exception as e:
            request.session.shouldstop = "Failed to communicate with Trezor"
            raise RuntimeError(f"Failed to open debuglink for {path}") from e

    else:
        devices = enumerate_devices()
        for device in devices:
            try:
                return Client(device, auto_interact=not interact)
            except Exception:
                pass

        request.session.shouldstop = "Failed to communicate with Trezor"
        raise RuntimeError("No debuggable device found")
 def __enter__(self):
     if self.tag.startswith("/"):  # full path+filename provided
         args = [self.tag]
     else:  # only gen+tag provided
         args = ["%s/trezor-emu-%s-%s" % (BINDIR, self.gen, self.tag)]
     env = ENV
     if self.gen == "core":
         args += ["-m", "main"]
         env["TREZOR_PROFILE_DIR"] = self.workdir.name
     self.process = subprocess.Popen(
         args, cwd=self.workdir.name, env=ENV, stdout=open(os.devnull, "w")
     )
     # wait until emulator is started
     while True:
         try:
             self.transport = get_transport("udp:127.0.0.1:21324")
         except TransportException:
             time.sleep(0.1)
             continue
         break
     self.client = TrezorClientDebugLink(self.transport)
     self.client.open()
     return self
Esempio n. 30
0
# ########## Constants
coin = "Testnet"
path = "m/84'/1'/0'/0/0"
nLockTime = 1602572140  # 10/13/2020 @ 6:55am (UTC)
# ########## Constants


def is_valid(priv):
    n = 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141'
    priv = int(b2x(priv), 16)
    n = int(n.replace(' ', ''), 16)
    assert priv > 0
    assert priv < n


device = get_transport()
client = TrezorClient(transport=device, ui=ClickUI())

n_path = parse_path(path)
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 = decrypt_keyvalue(client,
                        n_path,
                        path,
                        pubkey,
                        ask_on_decrypt=False,
                        ask_on_encrypt=side)
is_valid(priv)
print("priv", b2x(priv), left)
Esempio n. 31
0
    "alcohol woman abuse must during monitor noble actual mixed trade anger aisle"
)
mnemonic24 = "permit universe parent weapon amused modify essay borrow tobacco budget walnut " "lunch consider gallery ride amazing frog forget treat market chapter velvet useless topple"

debug_mode = args.debug
if args.trezor_path:
    path = args.trezor_path
elif args.trezor_idx:
    path = "bridge:web01" if args.trezor_idx == "usb" else "udp:127.0.0.1:21324"
else:
    path = os.environ.get("TREZOR_PATH", "bridge:web01")

mnemonic = mnemonic24 if args.mnemonic == 1 else mnemonic12


wirelink = get_transport(path)
client = TrezorClientDebugLink(wirelink) if debug_mode else TrezorClient(wirelink)
if debug_mode:
    debuglink = wirelink.find_debug()
    client.set_debuglink(debuglink)

client.transport.session_begin()

client.wipe_device()
client.load_device_by_mnemonic(
    mnemonic=mnemonic,
    pin="",
    passphrase_protection=False,
    label="ph4test",
    language="english",
)
Esempio n. 32
0
from trezorlib.client import TrezorClient
from trezorlib.transport import get_transport

client = TrezorClient(get_transport())

bip32_path = client.expand_path("44'/0'/0'/0/0")
print(client.get_address('Bitcoin', bip32_path))

bip32_path = client.expand_path("44'/0'/0'/0/1")
print(client.get_address('Bitcoin', bip32_path))
Esempio n. 33
0
async def amain():
    parser = argparse.ArgumentParser(description="Trezor address loader")

    parser.add_argument("--trezor-path",
                        dest="trezor_path",
                        default=None,
                        help="Trezor device path")
    parser.add_argument("--trezor-idx",
                        dest="trezor_idx",
                        default=None,
                        help="Trezor path idx")
    parser.add_argument("--pin",
                        dest="pin",
                        default="",
                        help="Trezor PIN protection")
    parser.add_argument(
        "--passphrase",
        dest="passphrase",
        default=False,
        action="store_const",
        const=True,
        help="Enable passphrase",
    )
    parser.add_argument(
        "--debug",
        dest="debug",
        default=False,
        action="store_const",
        const=True,
        help="Debug",
    )
    parser.add_argument(
        "--debug-link",
        dest="debug_link",
        default=False,
        action="store_const",
        const=True,
        help=
        "Debug link with Trezor. May skip some dialogs (e.g., passphrase entry)",
    )
    args = parser.parse_args()

    try:
        if args.debug:
            coloredlogs.install(level=logging.DEBUG, use_chroot=False)
        else:
            coloredlogs.install(level=logging.INFO, use_chroot=False)
    except Exception as e:
        pass

    debug_mode = args.debug_link
    if args.trezor_path:
        path = args.trezor_path
    elif args.trezor_idx:
        path = "bridge:web01" if args.trezor_idx == "usb" else "udp:127.0.0.1:21324"
    else:
        path = os.environ.get("TREZOR_PATH", "bridge:web01")

    wirelink = get_transport(path)
    client = (TrezorClientDebugLink(wirelink)
              if debug_mode else TrezorClient(wirelink, ui=ui.ClickUI()))

    # client.transport.session_begin()
    trezor_proxy = tmanager.Trezor(path=path, debug=args.debug_link)
    network_type = NetworkTypes.MAINNET
    agent = agent_lite.Agent(trezor_proxy, network_type=network_type)
    res = await agent.get_address()
    print(res)

    # client.transport.session_end()
    client.close()
    sys.exit(0)
Esempio n. 34
0
def main():
    numinputs = 100
    sizeinputtx = 10

    # Use first connected device
    try:
        transport = get_transport()
    except Exception as e:
        print(e)
        return

    print(transport)

    txstore = MyTxApiBitcoin()

    # Creates object for manipulating TREZOR
    client = TrezorClient(transport)
    # client.set_tx_api(TxApiTestnet)
    txstore.set_client(client)
    txstore.set_publickey(
        client.get_public_node(client.expand_path("44'/0'/0'")))
    print("creating input txs")
    txstore.create_inputs(numinputs, sizeinputtx)
    print("go")
    client.set_tx_api(txstore)
    # client.set_tx_api(MyTxApiBitcoin())

    # 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)

    outputs = [
        proto_types.TxOutputType(
            amount=0,
            script_type=proto_types.PAYTOADDRESS,
            address='p2xtZoXeX5X8BP8JfFhQK2nD3emtjch7UeFm'
            # op_return_data=binascii.unhexlify('2890770995194662774cd192ee383b805e9a066e6a456be037727649228fb7f6')
            # address_n=client.expand_path("44'/0'/0'/0/35"),
            # address='3PUxV6Cc4udQZQsJhArVUzvvVoKC8ohkAj',
        ),
        # proto_types.TxOutputType(
        #     amount=0,
        #     script_type=proto_types.PAYTOOPRETURN,
        #     op_return_data=binascii.unhexlify('2890770995194662774cd192ee383b805e9a066e6a456be037727649228fb7f6')
        # ),
        # proto_types.TxOutputType(
        #     amount= 8120,
        #     script_type=proto_types.PAYTOADDRESS,
        #     address_n=client.expand_path("44'/1'/0'/1/0"),
        #     address='1PtCkQgyN6xHmXWzLmFFrDNA5vYhYLeNFZ',
        #     address='14KRxYgFc7Se8j7MDdrK5PTNv8meq4GivK',
        # ),
        # proto_types.TxOutputType(
        # amount= 18684 - 2000,
        # script_type=proto_types.PAYTOADDRESS,
        # address_n=client.expand_path("44'/0'/0'/0/7"),
        # # address='1PtCkQgyN6xHmXWzLmFFrDNA5vYhYLeNFZ',
        # # address='1s9TSqr3PHZdXGrYws59Uaf5SPqavH43z',
        # ),
        # proto_types.TxOutputType(
        # amount= 1000,
        # script_type=proto_types.PAYTOADDRESS,
        # # address_n=client.expand_path("44'/0'/0'/0/18"),
        # # address='1PtCkQgyN6xHmXWzLmFFrDNA5vYhYLeNFZ',
        # # address='1NcMqUvyWv1K3Zxwmx5sqfj7ZEmPCSdJFM',
        # ),
    ]

    #    (signatures, serialized_tx) = client.sign_tx('Testnet', inputs, outputs)
    (signatures, serialized_tx) = client.sign_tx('Bitcoin',
                                                 txstore.get_inputs(),
                                                 txstore.get_outputs())
    print('Transaction:', binascii.hexlify(serialized_tx))

    client.close()
Esempio n. 35
0
def get_device():
    path = os.environ.get('TREZOR_PATH')
    return get_transport(path)
Esempio n. 36
0
def main():
    parser = argparse.ArgumentParser(description="Trezor initializer")

    parser.add_argument("--trezor-path",
                        dest="trezor_path",
                        default=None,
                        help="Trezor device path")
    parser.add_argument("--trezor-idx",
                        dest="trezor_idx",
                        default=None,
                        help="Trezor path idx")
    parser.add_argument("--mnemonic-idx",
                        dest="mnemonic_idx",
                        default=0,
                        type=int,
                        help="Trezor mnemonic index (testing indices)")
    parser.add_argument("--mnemonic",
                        dest="mnemonic",
                        default=None,
                        help="Trezor mnemonic")
    parser.add_argument("--pin",
                        dest="pin",
                        default="",
                        help="Trezor PIN protection")
    parser.add_argument("--label",
                        dest="label",
                        default="",
                        help="Trezor label - on display")
    parser.add_argument("--language",
                        dest="language",
                        default="english",
                        help="Seed language")
    parser.add_argument(
        "--passphrase",
        dest="passphrase",
        default=False,
        action="store_const",
        const=True,
        help="Enable passphrase",
    )
    parser.add_argument(
        "--debug",
        dest="debug",
        default=False,
        action="store_const",
        const=True,
        help="Debug",
    )
    args = parser.parse_args()

    mnemonic12 = (
        "alcohol woman abuse must during monitor noble actual mixed trade anger aisle"
    )
    mnemonic24 = (
        "permit universe parent weapon amused modify essay borrow tobacco budget walnut "
        "lunch consider gallery ride amazing frog forget treat market chapter velvet useless topple"
    )

    debug_mode = args.debug
    if args.trezor_path:
        path = args.trezor_path
    elif args.trezor_idx:
        path = "bridge:web01" if args.trezor_idx == "usb" else "udp:127.0.0.1:21324"
    else:
        path = os.environ.get("TREZOR_PATH", "bridge:web01")

    mnemonic = mnemonic24 if args.mnemonic_idx == 1 else mnemonic12
    if args.mnemonic:
        mnemonic = mnemonic

    wirelink = get_transport(path)
    client = (TrezorClientDebugLink(wirelink)
              if debug_mode else TrezorClient(wirelink, ui=ui.ClickUI))
    client.transport.session_begin()

    device.wipe(client)
    debuglink.load_device_by_mnemonic(
        client=client,
        mnemonic=mnemonic,
        pin=args.pin,
        passphrase_protection=args.passphrase,
        label=args.label,
        language=args.language,
    )

    client.transport.session_end()
    client.close()