diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000000..95299e5d67 --- /dev/null +++ b/.flake8 @@ -0,0 +1,16 @@ +[flake8] +exclude = + .tox/, + build/, + dist/, + tools/signtest.py, + trezorlib/*_pb2.py +ignore = + # F821 undefined name 'unicode', + F821, + # F401: module imported but unused + F401, + # E402: module level import not at top of file + E402, + # E501: line too long + E501 diff --git a/.travis.yml b/.travis.yml index d63a1e332b..2bf8eea3e6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -25,9 +25,11 @@ install: - pip install "pip>=7.0" wheel - pip install "setuptools>=19.0" - pip install tox-travis + - pip install flake8 script: - python setup.py install + - flake8 - tox notifications: diff --git a/setup.py b/setup.py index f68f18ec38..6ccd2c0625 100755 --- a/setup.py +++ b/setup.py @@ -39,7 +39,7 @@ setup( 'trezorlib.tx_api', 'trezorlib.types_pb2', ], - scripts = ['trezorctl'], + scripts=['trezorctl'], install_requires=install_requires, include_package_data=True, zip_safe=False, diff --git a/tests/device_tests/config.py b/tests/device_tests/config.py index cac3139ee7..ae7a2e602a 100644 --- a/tests/device_tests/config.py +++ b/tests/device_tests/config.py @@ -45,7 +45,8 @@ except Exception as e: def pipe_exists(path): - import os, stat + import os + import stat try: return stat.S_ISFIFO(os.stat(path).st_mode) except: diff --git a/tests/device_tests/test_basic.py b/tests/device_tests/test_basic.py index c1c5fb70dc..a5d79b5cdc 100644 --- a/tests/device_tests/test_basic.py +++ b/tests/device_tests/test_basic.py @@ -21,6 +21,7 @@ import common from trezorlib import messages_pb2 as messages + class TestBasic(common.TrezorTest): def test_features(self): @@ -50,5 +51,6 @@ class TestBasic(common.TrezorTest): # Device ID must be fresh after every reset self.assertNotEqual(id1, id2) + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_bip32_speed.py b/tests/device_tests/test_bip32_speed.py index 168f763060..ce6d4246d2 100644 --- a/tests/device_tests/test_bip32_speed.py +++ b/tests/device_tests/test_bip32_speed.py @@ -21,7 +21,7 @@ from __future__ import print_function import unittest import common import time -from trezorlib import tools + class TestBip32Speed(common.TrezorTest): @@ -70,5 +70,6 @@ class TestBip32Speed(common.TrezorTest): # Cached time expected to be at least 2x faster self.assertLessEqual(cache_time, nocache_time / 2.) + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_debuglink.py b/tests/device_tests/test_debuglink.py index d84f5959ae..df41b3aa59 100644 --- a/tests/device_tests/test_debuglink.py +++ b/tests/device_tests/test_debuglink.py @@ -16,14 +16,11 @@ # You should have received a copy of the GNU Lesser General Public License # along with this library. If not, see . -import time import unittest import common -import binascii from trezorlib import messages_pb2 as proto -from trezorlib import types_pb2 as types -from trezorlib.client import PinException + class TestDebugLink(common.TrezorTest): @@ -56,5 +53,6 @@ class TestDebugLink(common.TrezorTest): resp = self.client.call_raw(proto.PinMatrixAck(pin=pin_encoded)) self.assertIsInstance(resp, proto.Success) + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_applysettings.py b/tests/device_tests/test_msg_applysettings.py index 2302a3d926..83ee6ce87e 100644 --- a/tests/device_tests/test_msg_applysettings.py +++ b/tests/device_tests/test_msg_applysettings.py @@ -16,12 +16,12 @@ # You should have received a copy of the GNU Lesser General Public License # along with this library. If not, see . -import time import unittest import common from trezorlib import messages_pb2 as proto + class TestMsgApplysettings(common.TrezorTest): def test_apply_settings(self): @@ -92,5 +92,6 @@ class TestMsgApplysettings(common.TrezorTest): proto.Features()]) self.client.apply_settings(homescreen=img) + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_changepin.py b/tests/device_tests/test_msg_changepin.py index 33cd949f42..fbb331048c 100644 --- a/tests/device_tests/test_msg_changepin.py +++ b/tests/device_tests/test_msg_changepin.py @@ -16,12 +16,11 @@ # You should have received a copy of the GNU Lesser General Public License # along with this library. If not, see . -import time import unittest import common from trezorlib import messages_pb2 as proto -from trezorlib import types_pb2 as proto_types + class TestMsgChangepin(common.TrezorTest): @@ -218,5 +217,6 @@ class TestMsgChangepin(common.TrezorTest): self.assertTrue(features.pin_protection) self.assertEqual(self.client.debug.read_pin()[0], self.pin4) + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_cipherkeyvalue.py b/tests/device_tests/test_msg_cipherkeyvalue.py index 441dfa9017..c2156ff3e6 100644 --- a/tests/device_tests/test_msg_cipherkeyvalue.py +++ b/tests/device_tests/test_msg_cipherkeyvalue.py @@ -20,7 +20,6 @@ import unittest import common import binascii -from trezorlib.client import CallException class TestMsgCipherkeyvalue(common.TrezorTest): @@ -88,5 +87,6 @@ class TestMsgCipherkeyvalue(common.TrezorTest): self.setup_mnemonic_nopin_nopassphrase() self.assertRaises(Exception, self.client.decrypt_keyvalue, [0, 1, 2], b"test", b"testing") + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_clearsession.py b/tests/device_tests/test_msg_clearsession.py index 755b970531..33ea42c681 100644 --- a/tests/device_tests/test_msg_clearsession.py +++ b/tests/device_tests/test_msg_clearsession.py @@ -16,13 +16,13 @@ # You should have received a copy of the GNU Lesser General Public License # along with this library. If not, see . -import time import unittest import common from trezorlib import messages_pb2 as proto from trezorlib import types_pb2 as proto_types + class TestMsgClearsession(common.TrezorTest): def test_clearsession(self): @@ -53,5 +53,6 @@ class TestMsgClearsession(common.TrezorTest): res = self.client.ping('random data', button_protection=True, pin_protection=True, passphrase_protection=True) self.assertEqual(res, 'random data') + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_estimatetxsize.py b/tests/device_tests/test_msg_estimatetxsize.py index b8a5a069c7..340c8a5334 100644 --- a/tests/device_tests/test_msg_estimatetxsize.py +++ b/tests/device_tests/test_msg_estimatetxsize.py @@ -17,28 +17,28 @@ # along with this library. If not, see . import unittest -import common import binascii +import common -import trezorlib.messages_pb2 as proto import trezorlib.types_pb2 as proto_types -from trezorlib.client import CallException + class TestMsgEstimatetxsize(common.TrezorTest): def test_estimate_size(self): self.setup_mnemonic_nopin_nopassphrase() - inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e - # amount=390000, - prev_hash=binascii.unhexlify('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882'), - prev_index=0, - ) - - out1 = proto_types.TxOutputType(address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1', - amount=390000 - 10000, - script_type=proto_types.PAYTOADDRESS, - ) + inp1 = proto_types.TxInputType( + address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e + # amount=390000, + prev_hash=binascii.unhexlify('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882'), + prev_index=0, + ) + out1 = proto_types.TxOutputType( + address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1', + amount=390000 - 10000, + script_type=proto_types.PAYTOADDRESS, + ) est_size = self.client.estimate_tx_size('Bitcoin', [inp1, ], [out1, ]) self.assertEqual(est_size, 194) @@ -48,5 +48,6 @@ class TestMsgEstimatetxsize(common.TrezorTest): self.assertGreaterEqual(est_size, real_size) + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_ethereum_getaddress.py b/tests/device_tests/test_msg_ethereum_getaddress.py index 55ad039eaa..afa4a8025a 100644 --- a/tests/device_tests/test_msg_ethereum_getaddress.py +++ b/tests/device_tests/test_msg_ethereum_getaddress.py @@ -18,9 +18,9 @@ import unittest import common -import trezorlib.ckd_public as bip32 import binascii + class TestMsgEthereumGetaddress(common.TrezorTest): def test_ethereum_getaddress(self): @@ -31,5 +31,6 @@ class TestMsgEthereumGetaddress(common.TrezorTest): self.assertEqual(binascii.hexlify(self.client.ethereum_get_address([-9, 0])), b'f68804ac9eca9483ab4241d3e4751590d2c05102') self.assertEqual(binascii.hexlify(self.client.ethereum_get_address([0, 9999999])), b'7a6366ecfcaf0d5dcc1539c171696c6cdd1eb8ed') + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_ethereum_signtx.py b/tests/device_tests/test_msg_ethereum_signtx.py index 0cb2a895c0..9116b448ec 100644 --- a/tests/device_tests/test_msg_ethereum_signtx.py +++ b/tests/device_tests/test_msg_ethereum_signtx.py @@ -20,10 +20,6 @@ import unittest import common import binascii -import trezorlib.messages_pb2 as proto -import trezorlib.types_pb2 as proto_types - -from rlp.utils import int_to_big_endian class TestMsgEthereumSigntx(common.TrezorTest): @@ -94,18 +90,20 @@ class TestMsgEthereumSigntx(common.TrezorTest): self.assertEqual(binascii.hexlify(sig_r), '070e9dafda4d9e733fa7b6747a75f8a4916459560efb85e3e73cd39f31aa160d') self.assertEqual(binascii.hexlify(sig_s), '7842db33ef15c27049ed52741db41fe3238a6fa3a6a0888fcfb74d6917600e41') - def test_ethereum_signtx_newcontract(self): self.setup_mnemonic_nopin_nopassphrase() # contract creation without data should fail. - self.assertRaises(Exception, self.client.ethereum_sign_tx, + self.assertRaises( + Exception, + self.client.ethereum_sign_tx, n=[0, 0], nonce=123456, gas_price=20000, gas_limit=20000, to='', - value=12345678901234567890) + value=12345678901234567890 + ) sig_v, sig_r, sig_s = self.client.ethereum_sign_tx( n=[0, 0], @@ -121,37 +119,49 @@ class TestMsgEthereumSigntx(common.TrezorTest): def test_ethereum_sanity_checks(self): # gas overflow - self.assertRaises(Exception, self.client.ethereum_sign_tx, + self.assertRaises( + Exception, + self.client.ethereum_sign_tx, n=[0, 0], nonce=123456, gas_price=0xffffffffffffffffffffffffffffffff, gas_limit=0xffffffffffffffffffffffffffffff, to=binascii.unhexlify('1d1c328764a41bda0492b66baa30c4a339ff85ef'), - value=12345678901234567890) + value=12345678901234567890 + ) # no gas price - self.assertRaises(Exception, self.client.ethereum_sign_tx, + self.assertRaises( + Exception, + self.client.ethereum_sign_tx, n=[0, 0], nonce=123456, gas_limit=10000, to=binascii.unhexlify('1d1c328764a41bda0492b66baa30c4a339ff85ef'), - value=12345678901234567890) + value=12345678901234567890 + ) # no gas limit - self.assertRaises(Exception, self.client.ethereum_sign_tx, + self.assertRaises( + Exception, + self.client.ethereum_sign_tx, n=[0, 0], nonce=123456, gas_price=10000, to=binascii.unhexlify('1d1c328764a41bda0492b66baa30c4a339ff85ef'), - value=12345678901234567890) + value=12345678901234567890 + ) # no nonce - self.assertRaises(Exception, self.client.ethereum_sign_tx, + self.assertRaises( + Exception, + self.client.ethereum_sign_tx, n=[0, 0], gas_price=10000, gas_limit=123456, to=binascii.unhexlify('1d1c328764a41bda0492b66baa30c4a339ff85ef'), - value=12345678901234567890) + value=12345678901234567890 + ) def test_ethereum_signtx_nodata_eip155(self): self.setup_mnemonic_allallall() @@ -235,5 +245,6 @@ class TestMsgEthereumSigntx(common.TrezorTest): self.assertEqual(binascii.hexlify(sig_r), 'f7505f709d5999343aea3c384034c62d0514336ff6c6af65582006f708f81503') self.assertEqual(binascii.hexlify(sig_s), '44e09e29a4b6247000b46ddc94fe391e94deb2b39ad6ac6398e6db5bec095ba9') + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_getaddress.py b/tests/device_tests/test_msg_getaddress.py index e100c84cdc..ba848e5af7 100644 --- a/tests/device_tests/test_msg_getaddress.py +++ b/tests/device_tests/test_msg_getaddress.py @@ -20,6 +20,7 @@ import unittest import common import trezorlib.ckd_public as bip32 + class TestMsgGetaddress(common.TrezorTest): def test_btc(self): @@ -58,5 +59,6 @@ class TestMsgGetaddress(common.TrezorTest): self.assertEqual(address2, '1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb') self.assertEqual(address1, address2) + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_getaddress_segwit.py b/tests/device_tests/test_msg_getaddress_segwit.py index 7b799e801f..5ff3f7780b 100644 --- a/tests/device_tests/test_msg_getaddress_segwit.py +++ b/tests/device_tests/test_msg_getaddress_segwit.py @@ -2,7 +2,7 @@ import unittest import common import trezorlib.ckd_public as bip32 import trezorlib.types_pb2 as proto_types -import binascii + class TestMsgGetaddressSegwit(common.TrezorTest): @@ -23,21 +23,21 @@ class TestMsgGetaddressSegwit(common.TrezorTest): def test_show_multisig_3(self): self.setup_mnemonic_allallall() - nodes = map(lambda index : self.client.get_public_node(self.client.expand_path("999'/1'/%d'" % index)), range(1,4)) + nodes = map(lambda index: self.client.get_public_node(self.client.expand_path("999'/1'/%d'" % index)), range(1, 4)) multisig1 = proto_types.MultisigRedeemScriptType( - pubkeys=map(lambda n : proto_types.HDNodePathType(node=bip32.deserialize(n.xpub), address_n=[2,0]), nodes), - signatures=[b'', b'', b''], - m=2, - ) - multisig2 = proto_types.MultisigRedeemScriptType( - pubkeys=map(lambda n : proto_types.HDNodePathType(node=bip32.deserialize(n.xpub), address_n=[2,1]), nodes), + pubkeys=map(lambda n: proto_types.HDNodePathType(node=bip32.deserialize(n.xpub), address_n=[2, 0]), nodes), signatures=[b'', b'', b''], m=2, ) + # multisig2 = proto_types.MultisigRedeemScriptType( + # pubkeys=map(lambda n: proto_types.HDNodePathType(node=bip32.deserialize(n.xpub), address_n=[2, 1]), nodes), + # signatures=[b'', b'', b''], + # m=2, + # ) for i in [1, 2, 3]: self.assertEqual(self.client.get_address("Testnet", self.client.expand_path("999'/1'/%d'/2/0" % i), False, multisig1, script_type=proto_types.SPENDP2SHWITNESS), - '2N2MxyAfifVhb3AMagisxaj3uij8bfXqf4Y'); + '2N2MxyAfifVhb3AMagisxaj3uij8bfXqf4Y') if __name__ == '__main__': diff --git a/tests/device_tests/test_msg_getaddress_segwit_native.py b/tests/device_tests/test_msg_getaddress_segwit_native.py index 50469dddd7..77e065e537 100644 --- a/tests/device_tests/test_msg_getaddress_segwit_native.py +++ b/tests/device_tests/test_msg_getaddress_segwit_native.py @@ -2,7 +2,7 @@ import unittest import common import trezorlib.ckd_public as bip32 import trezorlib.types_pb2 as proto_types -import binascii + class TestMsgGetaddressSegwitNative(common.TrezorTest): @@ -23,14 +23,14 @@ class TestMsgGetaddressSegwitNative(common.TrezorTest): def test_show_multisig_3(self): self.setup_mnemonic_allallall() - nodes = map(lambda index : self.client.get_public_node(self.client.expand_path("999'/1'/%d'" % index)), range(1,4)) + nodes = map(lambda index: self.client.get_public_node(self.client.expand_path("999'/1'/%d'" % index)), range(1, 4)) multisig1 = proto_types.MultisigRedeemScriptType( - pubkeys=map(lambda n : proto_types.HDNodePathType(node=bip32.deserialize(n.xpub), address_n=[2,0]), nodes), + pubkeys=map(lambda n: proto_types.HDNodePathType(node=bip32.deserialize(n.xpub), address_n=[2, 0]), nodes), signatures=[b'', b'', b''], m=2, ) multisig2 = proto_types.MultisigRedeemScriptType( - pubkeys=map(lambda n : proto_types.HDNodePathType(node=bip32.deserialize(n.xpub), address_n=[2,1]), nodes), + pubkeys=map(lambda n: proto_types.HDNodePathType(node=bip32.deserialize(n.xpub), address_n=[2, 1]), nodes), signatures=[b'', b'', b''], m=2, ) diff --git a/tests/device_tests/test_msg_getaddress_show.py b/tests/device_tests/test_msg_getaddress_show.py index 0e1c1a38e2..a88fce3f25 100644 --- a/tests/device_tests/test_msg_getaddress_show.py +++ b/tests/device_tests/test_msg_getaddress_show.py @@ -20,7 +20,7 @@ import unittest import common import trezorlib.ckd_public as bip32 import trezorlib.types_pb2 as proto_types -import binascii + class TestMsgGetaddress(common.TrezorTest): @@ -35,12 +35,14 @@ class TestMsgGetaddress(common.TrezorTest): node = bip32.deserialize('xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy') multisig = proto_types.MultisigRedeemScriptType( - pubkeys=[proto_types.HDNodePathType(node=node, address_n=[1]), - proto_types.HDNodePathType(node=node, address_n=[2]), - proto_types.HDNodePathType(node=node, address_n=[3])], - signatures=[b'', b'', b''], - m=2, - ) + pubkeys=[ + proto_types.HDNodePathType(node=node, address_n=[1]), + proto_types.HDNodePathType(node=node, address_n=[2]), + proto_types.HDNodePathType(node=node, address_n=[3]) + ], + signatures=[b'', b'', b''], + m=2, + ) for i in [1, 2, 3]: self.assertEqual(self.client.get_address('Bitcoin', [i], show_display=True, multisig=multisig), '3E7GDtuHqnqPmDgwH59pVC7AvySiSkbibz') @@ -55,13 +57,14 @@ class TestMsgGetaddress(common.TrezorTest): pubs.append(proto_types.HDNodePathType(node=node, address_n=[x])) multisig = proto_types.MultisigRedeemScriptType( - pubkeys=pubs, - signatures=[b''] * 15, - m=15, - ) + pubkeys=pubs, + signatures=[b''] * 15, + m=15, + ) for i in range(15): self.assertEqual(self.client.get_address('Bitcoin', [i], show_display=True, multisig=multisig), '3QaKF8zobqcqY8aS6nxCD5ZYdiRfL3RCmU') + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_getentropy.py b/tests/device_tests/test_msg_getentropy.py index d8351bd1a3..a29f80d5bc 100644 --- a/tests/device_tests/test_msg_getentropy.py +++ b/tests/device_tests/test_msg_getentropy.py @@ -19,12 +19,13 @@ from __future__ import print_function import unittest -import common import math +import common import trezorlib.messages_pb2 as proto import trezorlib.types_pb2 as proto_types + def entropy(data): counts = {} for c in data: @@ -38,6 +39,7 @@ def entropy(data): e -= p * math.log(p, 256) return e + class TestMsgGetentropy(common.TrezorTest): def test_entropy(self): @@ -48,5 +50,6 @@ class TestMsgGetentropy(common.TrezorTest): self.assertTrue(len(ent) == l) print('entropy = ', entropy(ent)) + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_getpublickey.py b/tests/device_tests/test_msg_getpublickey.py index e5a27ee041..685fd6abbc 100644 --- a/tests/device_tests/test_msg_getpublickey.py +++ b/tests/device_tests/test_msg_getpublickey.py @@ -20,6 +20,7 @@ import unittest import common import trezorlib.ckd_public as bip32 + class TestMsgGetpublic_key(common.TrezorTest): def test_btc(self): @@ -42,5 +43,6 @@ class TestMsgGetpublic_key(common.TrezorTest): self.setup_mnemonic_nopin_nopassphrase() self.assertEqual(bip32.serialize(self.client.get_public_node([111, 42]).node, 0x043587CF), 'tpubDAgixSyai5PWbc8N1mBkHDR5nLgAnHFtY7r4y5EzxqAxrt9YUDpZL3kaRoHVvCfrcwNo31c2isBP2uTHcZxEosuKbyJhCAbrvGoPuLUZ7Mz') + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_loaddevice.py b/tests/device_tests/test_msg_loaddevice.py index d8a6b4005a..3a714d3d1c 100644 --- a/tests/device_tests/test_msg_loaddevice.py +++ b/tests/device_tests/test_msg_loaddevice.py @@ -19,7 +19,6 @@ import unittest import common -from trezorlib import messages_pb2 as messages class TestDeviceLoad(common.TrezorTest): @@ -89,5 +88,6 @@ class TestDeviceLoad(common.TrezorTest): self.assertEqual(address_nfkd, address_nfkc) self.assertEqual(address_nfkd, address_nfd) + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_loaddevice_xprv.py b/tests/device_tests/test_msg_loaddevice_xprv.py index cc76c68757..bc84c905a5 100644 --- a/tests/device_tests/test_msg_loaddevice_xprv.py +++ b/tests/device_tests/test_msg_loaddevice_xprv.py @@ -19,7 +19,6 @@ import unittest import common -from trezorlib import messages_pb2 as messages class TestDeviceLoadXprv(common.TrezorTest): @@ -43,5 +42,6 @@ class TestDeviceLoadXprv(common.TrezorTest): address = self.client.get_address('Bitcoin', []) self.assertEqual(address, '1CHUbFa4wTTPYgkYaw2LHSd5D4qJjMU8ri') + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_ping.py b/tests/device_tests/test_msg_ping.py index 00c64fb7d4..9321cf467d 100644 --- a/tests/device_tests/test_msg_ping.py +++ b/tests/device_tests/test_msg_ping.py @@ -16,13 +16,13 @@ # You should have received a copy of the GNU Lesser General Public License # along with this library. If not, see . -import time import unittest import common from trezorlib import messages_pb2 as proto from trezorlib import types_pb2 as proto_types + class TestPing(common.TrezorTest): def test_ping(self): @@ -62,5 +62,6 @@ class TestPing(common.TrezorTest): res = self.client.ping('random data', button_protection=True, pin_protection=True, passphrase_protection=True) self.assertEqual(res, 'random data') + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_recoverydevice.py b/tests/device_tests/test_msg_recoverydevice.py index 32f174cf1c..9f5825b9a4 100644 --- a/tests/device_tests/test_msg_recoverydevice.py +++ b/tests/device_tests/test_msg_recoverydevice.py @@ -23,6 +23,7 @@ import common from trezorlib import messages_pb2 as proto + class TestDeviceRecovery(common.TrezorTest): def test_pin_passphrase(self): mnemonic = self.mnemonic12.split(' ') @@ -171,5 +172,6 @@ class TestDeviceRecovery(common.TrezorTest): self.setup_mnemonic_nopin_nopassphrase() self.assertRaises(Exception, self.client.recovery_device, 12, False, False, 'label', 'english') + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_resetdevice.py b/tests/device_tests/test_msg_resetdevice.py index e75d40a630..5dfe8a989c 100644 --- a/tests/device_tests/test_msg_resetdevice.py +++ b/tests/device_tests/test_msg_resetdevice.py @@ -17,12 +17,13 @@ # along with this library. If not, see . import unittest -import common import hashlib +import common from trezorlib import messages_pb2 as proto from mnemonic import Mnemonic + def generate_entropy(strength, internal_entropy, external_entropy): ''' strength - length of produced seed. One of 128, 192, 256 @@ -51,18 +52,21 @@ def generate_entropy(strength, internal_entropy, external_entropy): return entropy_stripped + class TestDeviceReset(common.TrezorTest): def test_reset_device(self): # No PIN, no passphrase external_entropy = b'zlutoucky kun upel divoke ody' * 2 strength = 128 - ret = self.client.call_raw(proto.ResetDevice(display_random=False, - strength=strength, - passphrase_protection=False, - pin_protection=False, - language='english', - label='test')) + ret = self.client.call_raw(proto.ResetDevice( + display_random=False, + strength=strength, + passphrase_protection=False, + pin_protection=False, + language='english', + label='test' + )) # Provide entropy self.assertIsInstance(ret, proto.EntropyRequest) @@ -74,7 +78,7 @@ class TestDeviceReset(common.TrezorTest): expected_mnemonic = Mnemonic('english').to_mnemonic(entropy) mnemonic = [] - for _ in range(strength//32*3): + for _ in range(strength // 32 * 3): self.assertIsInstance(ret, proto.ButtonRequest) mnemonic.append(self.client.debug.read_reset_word()) self.client.debug.press_yes() @@ -86,7 +90,7 @@ class TestDeviceReset(common.TrezorTest): self.assertEqual(mnemonic, expected_mnemonic) mnemonic = [] - for _ in range(strength//32*3): + for _ in range(strength // 32 * 3): self.assertIsInstance(ret, proto.ButtonRequest) mnemonic.append(self.client.debug.read_reset_word()) self.client.debug.press_yes() @@ -116,12 +120,14 @@ class TestDeviceReset(common.TrezorTest): external_entropy = b'zlutoucky kun upel divoke ody' * 2 strength = 128 - ret = self.client.call_raw(proto.ResetDevice(display_random=True, - strength=strength, - passphrase_protection=True, - pin_protection=True, - language='english', - label='test')) + ret = self.client.call_raw(proto.ResetDevice( + display_random=True, + strength=strength, + passphrase_protection=True, + pin_protection=True, + language='english', + label='test' + )) self.assertIsInstance(ret, proto.ButtonRequest) self.client.debug.press_yes() @@ -148,7 +154,7 @@ class TestDeviceReset(common.TrezorTest): expected_mnemonic = Mnemonic('english').to_mnemonic(entropy) mnemonic = [] - for _ in range(strength//32*3): + for _ in range(strength // 32 * 3): self.assertIsInstance(ret, proto.ButtonRequest) mnemonic.append(self.client.debug.read_reset_word()) self.client.debug.press_yes() @@ -160,7 +166,7 @@ class TestDeviceReset(common.TrezorTest): self.assertEqual(mnemonic, expected_mnemonic) mnemonic = [] - for _ in range(strength//32*3): + for _ in range(strength // 32 * 3): self.assertIsInstance(ret, proto.ButtonRequest) mnemonic.append(self.client.debug.read_reset_word()) self.client.debug.press_yes() @@ -189,15 +195,17 @@ class TestDeviceReset(common.TrezorTest): self.client.call_raw(proto.Cancel()) def test_failed_pin(self): - external_entropy = b'zlutoucky kun upel divoke ody' * 2 + # external_entropy = b'zlutoucky kun upel divoke ody' * 2 strength = 128 - ret = self.client.call_raw(proto.ResetDevice(display_random=True, - strength=strength, - passphrase_protection=True, - pin_protection=True, - language='english', - label='test')) + ret = self.client.call_raw(proto.ResetDevice( + display_random=True, + strength=strength, + passphrase_protection=True, + pin_protection=True, + language='english', + label='test' + )) self.assertIsInstance(ret, proto.ButtonRequest) self.client.debug.press_yes() @@ -220,5 +228,6 @@ class TestDeviceReset(common.TrezorTest): self.setup_mnemonic_nopin_nopassphrase() self.assertRaises(Exception, self.client.reset_device, False, 128, True, True, 'label', 'english') + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_msg_signidentity.py b/tests/device_tests/test_msg_signidentity.py index 0cd9de7779..0eb3950d92 100644 --- a/tests/device_tests/test_msg_signidentity.py +++ b/tests/device_tests/test_msg_signidentity.py @@ -19,29 +19,35 @@ from __future__ import print_function import unittest -import common import binascii import hashlib import struct +import common -from trezorlib.client import CallException import trezorlib.types_pb2 as proto_types + def check_path(identity): m = hashlib.sha256() m.update(struct.pack(" 038caebd6f753bbbd2bb1f3346a43cd32140648583673a31d62f2dfb56ad0ab9e3 # ext1 + ext2 + int - # redeemscript (2 of 3): 522102c0d0c5fee952620757c6128dbf327c996cd72ed3358d15d6518a1186099bc15e210388460dc439f4c8f5bcfc268c36e11b4375cad5c3535c336cfdf8c32c3afad5c1210338d78612e990f2eea0c426b5e48a8db70b9d7ed66282b3b26511e0b1c75515a653ae - # multisig address: 3Gj7y1FdTppx2JEDqYqAEZFnKCA4GRysKF - # tx: d1d08ea63255af4ad16b098e9885a252632086fa6be53301521d05253ce8a73d - # input 0: 0.001 BTC + # redeemscript (2 of 3): 522102c0d0c5fee952620757c6128dbf327c996cd72ed3358d15d6518a1186099bc15e210388460dc439f4c8f5bcfc268c36e11b4375cad5c3535c336cfdf8c32c3afad5c1210338d78612e990f2eea0c426b5e48a8db70b9d7ed66282b3b26511e0b1c75515a653ae + # multisig address: 3Gj7y1FdTppx2JEDqYqAEZFnKCA4GRysKF + # tx: d1d08ea63255af4ad16b098e9885a252632086fa6be53301521d05253ce8a73d + # input 0: 0.001 BTC # ext1 + int + ext2 - # redeemscript (2 of 3): 522102c0d0c5fee952620757c6128dbf327c996cd72ed3358d15d6518a1186099bc15e210338d78612e990f2eea0c426b5e48a8db70b9d7ed66282b3b26511e0b1c75515a6210388460dc439f4c8f5bcfc268c36e11b4375cad5c3535c336cfdf8c32c3afad5c153ae - # multisig address: 3QsvfB6d1LzYcpm8xyhS1N1HBRrzHTgLHB - # tx: a6e2829d089cee47e481b1a753a53081b40738cc87e38f1d9b23ab57d9ad4396 - # input 0: 0.001 BTC + # redeemscript (2 of 3): 522102c0d0c5fee952620757c6128dbf327c996cd72ed3358d15d6518a1186099bc15e210338d78612e990f2eea0c426b5e48a8db70b9d7ed66282b3b26511e0b1c75515a6210388460dc439f4c8f5bcfc268c36e11b4375cad5c3535c336cfdf8c32c3afad5c153ae + # multisig address: 3QsvfB6d1LzYcpm8xyhS1N1HBRrzHTgLHB + # tx: a6e2829d089cee47e481b1a753a53081b40738cc87e38f1d9b23ab57d9ad4396 + # input 0: 0.001 BTC # ext1 + ext3 + int - # redeemscript (2 of 3): 522102c0d0c5fee952620757c6128dbf327c996cd72ed3358d15d6518a1186099bc15e2102e0c21e2a7cf00b94c5421725acff97f9826598b91f2340c5ddda730caca7d648210338d78612e990f2eea0c426b5e48a8db70b9d7ed66282b3b26511e0b1c75515a653ae - # multisig address: 37LvC1Q5CyKbMbKMncEJdXxqGhHxrBEgPE - # tx: e4bc1ae5e5007a08f2b3926fe11c66612e8f73c6b00c69c7027213b84d259be3 - # input 1: 0.001 BTC + # redeemscript (2 of 3): 522102c0d0c5fee952620757c6128dbf327c996cd72ed3358d15d6518a1186099bc15e2102e0c21e2a7cf00b94c5421725acff97f9826598b91f2340c5ddda730caca7d648210338d78612e990f2eea0c426b5e48a8db70b9d7ed66282b3b26511e0b1c75515a653ae + # multisig address: 37LvC1Q5CyKbMbKMncEJdXxqGhHxrBEgPE + # tx: e4bc1ae5e5007a08f2b3926fe11c66612e8f73c6b00c69c7027213b84d259be3 + # input 1: 0.001 BTC multisig_in1 = proto_types.MultisigRedeemScriptType( - pubkeys=[proto_types.HDNodePathType(node=node_ext1, address_n=[1]), - proto_types.HDNodePathType(node=node_ext2, address_n=[1]), - proto_types.HDNodePathType(node=node_int, address_n=[1])], - signatures=[b'', b'', b''], - m=2, - ) + pubkeys=[ + proto_types.HDNodePathType(node=node_ext1, address_n=[1]), + proto_types.HDNodePathType(node=node_ext2, address_n=[1]), + proto_types.HDNodePathType(node=node_int, address_n=[1]) + ], + signatures=[b'', b'', b''], + m=2, + ) multisig_in2 = proto_types.MultisigRedeemScriptType( - pubkeys=[proto_types.HDNodePathType(node=node_ext1, address_n=[1]), - proto_types.HDNodePathType(node=node_int, address_n=[1]), - proto_types.HDNodePathType(node=node_ext2, address_n=[1])], - signatures=[b'', b'', b''], - m=2, - ) + pubkeys=[ + proto_types.HDNodePathType(node=node_ext1, address_n=[1]), + proto_types.HDNodePathType(node=node_int, address_n=[1]), + proto_types.HDNodePathType(node=node_ext2, address_n=[1]) + ], + signatures=[b'', b'', b''], + m=2, + ) multisig_in3 = proto_types.MultisigRedeemScriptType( - pubkeys=[proto_types.HDNodePathType(node=node_ext1, address_n=[1]), - proto_types.HDNodePathType(node=node_ext3, address_n=[1]), - proto_types.HDNodePathType(node=node_int, address_n=[1])], - signatures=[b'', b'', b''], - m=2, - ) + pubkeys=[ + proto_types.HDNodePathType(node=node_ext1, address_n=[1]), + proto_types.HDNodePathType(node=node_ext3, address_n=[1]), + proto_types.HDNodePathType(node=node_int, address_n=[1]) + ], + signatures=[b'', b'', b''], + m=2, + ) - inp1 = proto_types.TxInputType(address_n=[1], - prev_hash=binascii.unhexlify('d1d08ea63255af4ad16b098e9885a252632086fa6be53301521d05253ce8a73d'), - prev_index=0, - script_type=proto_types.SPENDMULTISIG, - multisig=multisig_in1, - ) + inp1 = proto_types.TxInputType( + address_n=[1], + prev_hash=binascii.unhexlify('d1d08ea63255af4ad16b098e9885a252632086fa6be53301521d05253ce8a73d'), + prev_index=0, + script_type=proto_types.SPENDMULTISIG, + multisig=multisig_in1, + ) - inp2 = proto_types.TxInputType(address_n=[1], - prev_hash=binascii.unhexlify('a6e2829d089cee47e481b1a753a53081b40738cc87e38f1d9b23ab57d9ad4396'), - prev_index=0, - script_type=proto_types.SPENDMULTISIG, - multisig=multisig_in2, - ) + inp2 = proto_types.TxInputType( + address_n=[1], + prev_hash=binascii.unhexlify('a6e2829d089cee47e481b1a753a53081b40738cc87e38f1d9b23ab57d9ad4396'), + prev_index=0, + script_type=proto_types.SPENDMULTISIG, + multisig=multisig_in2, + ) - inp3 = proto_types.TxInputType(address_n=[1], - prev_hash=binascii.unhexlify('e4bc1ae5e5007a08f2b3926fe11c66612e8f73c6b00c69c7027213b84d259be3'), - prev_index=1, - script_type=proto_types.SPENDMULTISIG, - multisig=multisig_in3, - ) + inp3 = proto_types.TxInputType( + address_n=[1], + prev_hash=binascii.unhexlify('e4bc1ae5e5007a08f2b3926fe11c66612e8f73c6b00c69c7027213b84d259be3'), + prev_index=1, + script_type=proto_types.SPENDMULTISIG, + multisig=multisig_in3, + ) def _responses(self, inp1, inp2, change=0): resp = [ @@ -152,13 +160,17 @@ class TestMultisigChange(common.TrezorTest): def test_external_external(self): self.setup_mnemonic_nopin_nopassphrase() - out1 = proto_types.TxOutputType(address='12iyMbUb4R2K3gre4dHSrbu5azG5KaqVss', - amount=100000, - script_type=proto_types.PAYTOADDRESS) + out1 = proto_types.TxOutputType( + address='12iyMbUb4R2K3gre4dHSrbu5azG5KaqVss', + amount=100000, + script_type=proto_types.PAYTOADDRESS + ) - out2 = proto_types.TxOutputType(address='17kTB7qSk3MupQxWdiv5ZU3zcrZc2Azes1', - amount=100000, - script_type=proto_types.PAYTOADDRESS) + out2 = proto_types.TxOutputType( + address='17kTB7qSk3MupQxWdiv5ZU3zcrZc2Azes1', + amount=100000, + script_type=proto_types.PAYTOADDRESS + ) with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp2)) @@ -170,13 +182,17 @@ class TestMultisigChange(common.TrezorTest): def test_external_internal(self): self.setup_mnemonic_nopin_nopassphrase() - out1 = proto_types.TxOutputType(address='12iyMbUb4R2K3gre4dHSrbu5azG5KaqVss', - amount=100000, - script_type=proto_types.PAYTOADDRESS) + out1 = proto_types.TxOutputType( + address='12iyMbUb4R2K3gre4dHSrbu5azG5KaqVss', + amount=100000, + script_type=proto_types.PAYTOADDRESS + ) - out2 = proto_types.TxOutputType(address_n=[4], - amount=100000, - script_type=proto_types.PAYTOADDRESS) + out2 = proto_types.TxOutputType( + address_n=[4], + amount=100000, + script_type=proto_types.PAYTOADDRESS + ) with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp2, change=2)) @@ -188,13 +204,17 @@ class TestMultisigChange(common.TrezorTest): def test_internal_external(self): self.setup_mnemonic_nopin_nopassphrase() - out1 = proto_types.TxOutputType(address_n=[4], - amount=100000, - script_type=proto_types.PAYTOADDRESS) + out1 = proto_types.TxOutputType( + address_n=[4], + amount=100000, + script_type=proto_types.PAYTOADDRESS + ) - out2 = proto_types.TxOutputType(address='17kTB7qSk3MupQxWdiv5ZU3zcrZc2Azes1', - amount=100000, - script_type=proto_types.PAYTOADDRESS) + out2 = proto_types.TxOutputType( + address='17kTB7qSk3MupQxWdiv5ZU3zcrZc2Azes1', + amount=100000, + script_type=proto_types.PAYTOADDRESS + ) with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp2, change=1)) @@ -206,13 +226,17 @@ class TestMultisigChange(common.TrezorTest): def test_multisig_external_external(self): self.setup_mnemonic_nopin_nopassphrase() - out1 = proto_types.TxOutputType(address='3796Q9jVirg2KY1WQRqtmHKXCoSk8MB7Td', - amount=100000, - script_type=proto_types.PAYTOADDRESS) + out1 = proto_types.TxOutputType( + address='3796Q9jVirg2KY1WQRqtmHKXCoSk8MB7Td', + amount=100000, + script_type=proto_types.PAYTOADDRESS + ) - out2 = proto_types.TxOutputType(address='3CTPCg3ksh59jWt9zQpTPHCSQDCdJoQQ9d', - amount=100000, - script_type=proto_types.PAYTOADDRESS) + out2 = proto_types.TxOutputType( + address='3CTPCg3ksh59jWt9zQpTPHCSQDCdJoQQ9d', + amount=100000, + script_type=proto_types.PAYTOADDRESS + ) with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp2)) @@ -225,21 +249,27 @@ class TestMultisigChange(common.TrezorTest): self.setup_mnemonic_nopin_nopassphrase() multisig_out1 = proto_types.MultisigRedeemScriptType( - pubkeys=[proto_types.HDNodePathType(node=self.node_int, address_n=[1]), - proto_types.HDNodePathType(node=self.node_ext1, address_n=[1]), - proto_types.HDNodePathType(node=self.node_ext2, address_n=[1])], - signatures=[b'', b'', b''], - m=2, - ) + pubkeys=[ + proto_types.HDNodePathType(node=self.node_int, address_n=[1]), + proto_types.HDNodePathType(node=self.node_ext1, address_n=[1]), + proto_types.HDNodePathType(node=self.node_ext2, address_n=[1]) + ], + signatures=[b'', b'', b''], + m=2, + ) - out1 = proto_types.TxOutputType(address_n=[1], - multisig=multisig_out1, - amount=100000, - script_type=proto_types.PAYTOMULTISIG) + out1 = proto_types.TxOutputType( + address_n=[1], + multisig=multisig_out1, + amount=100000, + script_type=proto_types.PAYTOMULTISIG + ) - out2 = proto_types.TxOutputType(address='3CTPCg3ksh59jWt9zQpTPHCSQDCdJoQQ9d', - amount=100000, - script_type=proto_types.PAYTOADDRESS) + out2 = proto_types.TxOutputType( + address='3CTPCg3ksh59jWt9zQpTPHCSQDCdJoQQ9d', + amount=100000, + script_type=proto_types.PAYTOADDRESS + ) with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp2, change=1)) @@ -252,21 +282,27 @@ class TestMultisigChange(common.TrezorTest): self.setup_mnemonic_nopin_nopassphrase() multisig_out2 = proto_types.MultisigRedeemScriptType( - pubkeys=[proto_types.HDNodePathType(node=self.node_int, address_n=[2]), - proto_types.HDNodePathType(node=self.node_ext1, address_n=[2]), - proto_types.HDNodePathType(node=self.node_ext2, address_n=[2])], - signatures=[b'', b'', b''], - m=2, - ) + pubkeys=[ + proto_types.HDNodePathType(node=self.node_int, address_n=[2]), + proto_types.HDNodePathType(node=self.node_ext1, address_n=[2]), + proto_types.HDNodePathType(node=self.node_ext2, address_n=[2]) + ], + signatures=[b'', b'', b''], + m=2, + ) - out1 = proto_types.TxOutputType(address='37Wf955dcCaFSJmiNaGpacczMwj7iC8JMx', - amount=100000, - script_type=proto_types.PAYTOADDRESS) + out1 = proto_types.TxOutputType( + address='37Wf955dcCaFSJmiNaGpacczMwj7iC8JMx', + amount=100000, + script_type=proto_types.PAYTOADDRESS + ) - out2 = proto_types.TxOutputType(address_n=[2], - multisig=multisig_out2, - amount=100000, - script_type=proto_types.PAYTOMULTISIG) + out2 = proto_types.TxOutputType( + address_n=[2], + multisig=multisig_out2, + amount=100000, + script_type=proto_types.PAYTOMULTISIG + ) with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp2, change=2)) @@ -279,21 +315,27 @@ class TestMultisigChange(common.TrezorTest): self.setup_mnemonic_nopin_nopassphrase() multisig_out2 = proto_types.MultisigRedeemScriptType( - pubkeys=[proto_types.HDNodePathType(node=self.node_int, address_n=[2]), - proto_types.HDNodePathType(node=self.node_ext1, address_n=[2]), - proto_types.HDNodePathType(node=self.node_ext3, address_n=[2])], - signatures=[b'', b'', b''], - m=2, - ) + pubkeys=[ + proto_types.HDNodePathType(node=self.node_int, address_n=[2]), + proto_types.HDNodePathType(node=self.node_ext1, address_n=[2]), + proto_types.HDNodePathType(node=self.node_ext3, address_n=[2]) + ], + signatures=[b'', b'', b''], + m=2, + ) - out1 = proto_types.TxOutputType(address='3796Q9jVirg2KY1WQRqtmHKXCoSk8MB7Td', - amount=100000, - script_type=proto_types.PAYTOADDRESS) + out1 = proto_types.TxOutputType( + address='3796Q9jVirg2KY1WQRqtmHKXCoSk8MB7Td', + amount=100000, + script_type=proto_types.PAYTOADDRESS + ) - out2 = proto_types.TxOutputType(address_n=[2], - multisig=multisig_out2, - amount=100000, - script_type=proto_types.PAYTOMULTISIG) + out2 = proto_types.TxOutputType( + address_n=[2], + multisig=multisig_out2, + amount=100000, + script_type=proto_types.PAYTOMULTISIG + ) with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp2)) @@ -306,21 +348,27 @@ class TestMultisigChange(common.TrezorTest): self.setup_mnemonic_nopin_nopassphrase() multisig_out1 = proto_types.MultisigRedeemScriptType( - pubkeys=[proto_types.HDNodePathType(node=self.node_ext1, address_n=[1]), - proto_types.HDNodePathType(node=self.node_ext2, address_n=[1]), - proto_types.HDNodePathType(node=self.node_int, address_n=[1])], - signatures=[b'', b'', b''], - m=2, - ) + pubkeys=[ + proto_types.HDNodePathType(node=self.node_ext1, address_n=[1]), + proto_types.HDNodePathType(node=self.node_ext2, address_n=[1]), + proto_types.HDNodePathType(node=self.node_int, address_n=[1]) + ], + signatures=[b'', b'', b''], + m=2, + ) - out1 = proto_types.TxOutputType(address_n=[1], - multisig=multisig_out1, - amount=100000, - script_type=proto_types.PAYTOMULTISIG) + out1 = proto_types.TxOutputType( + address_n=[1], + multisig=multisig_out1, + amount=100000, + script_type=proto_types.PAYTOMULTISIG + ) - out2 = proto_types.TxOutputType(address='3CTPCg3ksh59jWt9zQpTPHCSQDCdJoQQ9d', - amount=100000, - script_type=proto_types.PAYTOADDRESS) + out2 = proto_types.TxOutputType( + address='3CTPCg3ksh59jWt9zQpTPHCSQDCdJoQQ9d', + amount=100000, + script_type=proto_types.PAYTOADDRESS + ) with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp3)) @@ -328,5 +376,6 @@ class TestMultisigChange(common.TrezorTest): self.assertEqual(binascii.hexlify(serialized_tx), b'01000000023da7e83c25051d520133e56bfa86206352a285988e096bd14aaf5532a68ed0d100000000b40047304402204b7d6c7e9feef91209cbdf4deaf855696dc22a40e57bd3eafd5e00b0ee41d9de0220262c5a05d0b46ef98fddfef3831b3ebb6841ffbeb10666f8fb6f8d2e3023e30d014c69522102c0d0c5fee952620757c6128dbf327c996cd72ed3358d15d6518a1186099bc15e210388460dc439f4c8f5bcfc268c36e11b4375cad5c3535c336cfdf8c32c3afad5c1210338d78612e990f2eea0c426b5e48a8db70b9d7ed66282b3b26511e0b1c75515a653aeffffffffe39b254db8137202c7690cb0c6738f2e61661ce16f92b3f2087a00e5e51abce401000000b500483045022100bb2118da21c8a84f115b655f640f269a40be77ae2c0af9c5ffd8260a85dbfc7702202e7b5b6c05b8f50bd879dbee88828e80e85448d686b63a1a50e99d921923f6f5014c69522102c0d0c5fee952620757c6128dbf327c996cd72ed3358d15d6518a1186099bc15e2102e0c21e2a7cf00b94c5421725acff97f9826598b91f2340c5ddda730caca7d648210338d78612e990f2eea0c426b5e48a8db70b9d7ed66282b3b26511e0b1c75515a653aeffffffff02a08601000000000017a914a4efc33d43d7a8a0040182c76ab624ff862f50d287a08601000000000017a9147615527d78854293edadf83682ea26937f8a51bb8700000000') + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_op_return.py b/tests/device_tests/test_op_return.py index 00d592ea80..cc6c27c0bb 100644 --- a/tests/device_tests/test_op_return.py +++ b/tests/device_tests/test_op_return.py @@ -17,9 +17,8 @@ # along with this library. If not, see . import unittest -import common import binascii -import itertools +import common import trezorlib.messages_pb2 as proto import trezorlib.types_pb2 as proto_types @@ -37,21 +36,24 @@ class TestOpReturn(common.TrezorTest): # tx: d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882 # input 0: 0.0039 BTC - inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e - # amount=390000, - prev_hash=TXHASH_d5f65e, - prev_index=0, - ) + inp1 = proto_types.TxInputType( + address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e + # amount=390000, + prev_hash=TXHASH_d5f65e, + prev_index=0, + ) - out1 = proto_types.TxOutputType(address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1', - amount=390000 - 10000, - script_type=proto_types.PAYTOADDRESS, - ) + out1 = proto_types.TxOutputType( + address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1', + amount=390000 - 10000, + script_type=proto_types.PAYTOADDRESS, + ) - out2 = proto_types.TxOutputType(op_return_data=b'test of the op_return data', - amount=0, - script_type=proto_types.PAYTOOPRETURN, - ) + out2 = proto_types.TxOutputType( + op_return_data=b'test of the op_return data', + amount=0, + script_type=proto_types.PAYTOOPRETURN, + ) with self.client: self.client.set_expected_responses([ @@ -81,21 +83,24 @@ class TestOpReturn(common.TrezorTest): # tx: d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882 # input 0: 0.0039 BTC - inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e - # amount=390000, - prev_hash=TXHASH_d5f65e, - prev_index=0, - ) + inp1 = proto_types.TxInputType( + address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e + # amount=390000, + prev_hash=TXHASH_d5f65e, + prev_index=0, + ) - out1 = proto_types.TxOutputType(address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1', - amount=390000 - 10000 - 10000, - script_type=proto_types.PAYTOADDRESS, - ) + out1 = proto_types.TxOutputType( + address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1', + amount=390000 - 10000 - 10000, + script_type=proto_types.PAYTOADDRESS, + ) - out1 = proto_types.TxOutputType(op_return_data=b'test of the op_return data', - amount=10000, - script_type=proto_types.PAYTOOPRETURN, - ) + out1 = proto_types.TxOutputType( + op_return_data=b'test of the op_return data', + amount=10000, + script_type=proto_types.PAYTOOPRETURN, + ) with self.client: self.client.set_expected_responses([ @@ -109,5 +114,6 @@ class TestOpReturn(common.TrezorTest): ]) self.assertRaises(CallException, self.client.sign_tx, 'Bitcoin', [inp1, ], [out1, ]) + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_protect_call.py b/tests/device_tests/test_protect_call.py index 4a18690e5a..d7f5eb17cf 100644 --- a/tests/device_tests/test_protect_call.py +++ b/tests/device_tests/test_protect_call.py @@ -23,19 +23,21 @@ import unittest import common from trezorlib import messages_pb2 as proto -from trezorlib import types_pb2 as types -from trezorlib.client import PinException, CallException +from trezorlib.client import PinException # FIXME TODO Add passphrase tests + class TestProtectCall(common.TrezorTest): def _some_protected_call(self, button, pin, passphrase): # This method perform any call which have protection in the device - res = self.client.ping('random data', - button_protection=button, - pin_protection=pin, - passphrase_protection=passphrase) + res = self.client.ping( + 'random data', + button_protection=button, + pin_protection=pin, + passphrase_protection=passphrase + ) self.assertEqual(res, 'random data') """ @@ -131,5 +133,6 @@ class TestProtectCall(common.TrezorTest): self.assertRaises(PinException, self._some_protected_call, False, True, False) test_backoff(attempt, start) + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_protection_levels.py b/tests/device_tests/test_protection_levels.py index b8c8e5a957..c70270baf0 100644 --- a/tests/device_tests/test_protection_levels.py +++ b/tests/device_tests/test_protection_levels.py @@ -38,61 +38,75 @@ class TestProtectionLevels(common.TrezorTest): def test_apply_settings(self): with self.client: self.setup_mnemonic_pin_passphrase() - self.client.set_expected_responses([proto.PinMatrixRequest(), - proto.ButtonRequest(), - proto.Success(), - proto.Features()]) # TrezorClient reinitializes device + self.client.set_expected_responses([ + proto.PinMatrixRequest(), + proto.ButtonRequest(), + proto.Success(), + proto.Features() + ]) # TrezorClient reinitializes device self.client.apply_settings(label='nazdar') def test_change_pin(self): with self.client: self.setup_mnemonic_pin_passphrase() - self.client.set_expected_responses([proto.ButtonRequest(), - proto.PinMatrixRequest(), - proto.PinMatrixRequest(), - proto.PinMatrixRequest(), - proto.Success(), - proto.Features()]) + self.client.set_expected_responses([ + proto.ButtonRequest(), + proto.PinMatrixRequest(), + proto.PinMatrixRequest(), + proto.PinMatrixRequest(), + proto.Success(), + proto.Features() + ]) self.client.change_pin() def test_ping(self): with self.client: self.setup_mnemonic_pin_passphrase() - self.client.set_expected_responses([proto.ButtonRequest(), - proto.PinMatrixRequest(), - proto.PassphraseRequest(), - proto.Success()]) + self.client.set_expected_responses([ + proto.ButtonRequest(), + proto.PinMatrixRequest(), + proto.PassphraseRequest(), + proto.Success() + ]) self.client.ping('msg', True, True, True) def test_get_entropy(self): with self.client: self.setup_mnemonic_pin_passphrase() - self.client.set_expected_responses([proto.ButtonRequest(), - proto.Entropy()]) + self.client.set_expected_responses([ + proto.ButtonRequest(), + proto.Entropy() + ]) self.client.get_entropy(10) def test_get_public_key(self): with self.client: self.setup_mnemonic_pin_passphrase() - self.client.set_expected_responses([proto.PinMatrixRequest(), - proto.PassphraseRequest(), - proto.PublicKey()]) + self.client.set_expected_responses([ + proto.PinMatrixRequest(), + proto.PassphraseRequest(), + proto.PublicKey() + ]) self.client.get_public_node([]) def test_get_address(self): with self.client: self.setup_mnemonic_pin_passphrase() - self.client.set_expected_responses([proto.PinMatrixRequest(), - proto.PassphraseRequest(), - proto.Address()]) + self.client.set_expected_responses([ + proto.PinMatrixRequest(), + proto.PassphraseRequest(), + proto.Address() + ]) self.client.get_address('Bitcoin', []) def test_wipe_device(self): with self.client: self.setup_mnemonic_pin_passphrase() - self.client.set_expected_responses([proto.ButtonRequest(), - proto.Success(), - proto.Features()]) + self.client.set_expected_responses([ + proto.ButtonRequest(), + proto.Success(), + proto.Features() + ]) self.client.wipe_device() def test_load_device(self): @@ -108,10 +122,7 @@ class TestProtectionLevels(common.TrezorTest): def test_reset_device(self): with self.client: - self.client.set_expected_responses([proto.EntropyRequest()] + \ - [proto.ButtonRequest()] * 24 + \ - [proto.Success(), - proto.Features()]) + self.client.set_expected_responses([proto.EntropyRequest()] + [proto.ButtonRequest()] * 24 + [proto.Success(), proto.Features()]) self.client.reset_device(False, 128, True, False, 'label', 'english') # This must fail, because device is already initialized @@ -120,9 +131,7 @@ class TestProtectionLevels(common.TrezorTest): def test_recovery_device(self): with self.client: self.client.set_mnemonic(self.mnemonic12) - self.client.set_expected_responses([proto.WordRequest()] * 24 + \ - [proto.Success(), - proto.Features()]) + self.client.set_expected_responses([proto.WordRequest()] * 24 + [proto.Success(), proto.Features()]) self.client.recovery_device(12, False, False, 'label', 'english') # This must fail, because device is already initialized @@ -131,16 +140,18 @@ class TestProtectionLevels(common.TrezorTest): def test_sign_message(self): with self.client: self.setup_mnemonic_pin_passphrase() - self.client.set_expected_responses([proto.ButtonRequest(), - proto.PinMatrixRequest(), - proto.PassphraseRequest(), - proto.MessageSignature()]) + self.client.set_expected_responses([ + proto.ButtonRequest(), + proto.PinMatrixRequest(), + proto.PassphraseRequest(), + proto.MessageSignature() + ]) self.client.sign_message('Bitcoin', [], 'testing message') def test_verify_message(self): with self.client: self.setup_mnemonic_pin_passphrase() - self.client.set_expected_responses([proto.ButtonRequest(),proto.Success()]) + self.client.set_expected_responses([proto.ButtonRequest(), proto.Success()]) self.client.verify_message( 'Bitcoin', '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e', @@ -179,15 +190,17 @@ class TestProtectionLevels(common.TrezorTest): def test_signtx(self): self.setup_mnemonic_pin_passphrase() - inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e - prev_hash=TXHASH_d5f65e, - prev_index=0, - ) + inp1 = proto_types.TxInputType( + address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e + prev_hash=TXHASH_d5f65e, + prev_index=0, + ) - out1 = proto_types.TxOutputType(address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1', - amount=390000 - 10000, - script_type=proto_types.PAYTOADDRESS, - ) + out1 = proto_types.TxOutputType( + address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1', + amount=390000 - 10000, + script_type=proto_types.PAYTOADDRESS, + ) with self.client: @@ -215,5 +228,6 @@ class TestProtectionLevels(common.TrezorTest): # def test_firmware_upload(self): # pass + if __name__ == '__main__': unittest.main() diff --git a/tests/device_tests/test_zerosig.py b/tests/device_tests/test_zerosig.py index 9f29920593..a6e043f36a 100644 --- a/tests/device_tests/test_zerosig.py +++ b/tests/device_tests/test_zerosig.py @@ -19,18 +19,18 @@ from __future__ import print_function import unittest -import common import binascii import sys +import common -import trezorlib.messages_pb2 as proto import trezorlib.types_pb2 as proto_types if sys.version_info < (3,): def byteindex(data, index): return ord(data[index]) else: - byteindex = lambda data, index: data[index] + def byteindex(data, index): + return data[index] TXHASH_d5f65e = binascii.unhexlify(b'd5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882') @@ -74,17 +74,19 @@ class TestZeroSig(common.TrezorTest): def test_one_zero_signature(self): self.setup_mnemonic_nopin_nopassphrase() - inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e - # amount=390000, - prev_hash=TXHASH_d5f65e, - prev_index=0, - ) + inp1 = proto_types.TxInputType( + address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e + # amount=390000, + prev_hash=TXHASH_d5f65e, + prev_index=0, + ) # Following address_n has been mined by 'test_mine_zero_signature' - out1 = proto_types.TxOutputType(address_n=[177], - amount=390000 - 10000, - script_type=proto_types.PAYTOADDRESS, - ) + out1 = proto_types.TxOutputType( + address_n=[177], + amount=390000 - 10000, + script_type=proto_types.PAYTOADDRESS, + ) (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) siglen = byteindex(serialized_tx, 44) @@ -95,17 +97,19 @@ class TestZeroSig(common.TrezorTest): def test_two_zero_signature(self): self.setup_mnemonic_nopin_nopassphrase() - inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e - # amount=390000, - prev_hash=TXHASH_d5f65e, - prev_index=0, - ) + inp1 = proto_types.TxInputType( + address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e + # amount=390000, + prev_hash=TXHASH_d5f65e, + prev_index=0, + ) # Following address_n has been mined by 'test_mine_zero_signature' - out1 = proto_types.TxOutputType(address_n=[16518], - amount=390000 - 10000, - script_type=proto_types.PAYTOADDRESS, - ) + out1 = proto_types.TxOutputType( + address_n=[16518], + amount=390000 - 10000, + script_type=proto_types.PAYTOADDRESS, + ) (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) siglen = byteindex(serialized_tx, 44) @@ -113,5 +117,6 @@ class TestZeroSig(common.TrezorTest): # TREZOR must strip leading zero from signature self.assertEqual(siglen, 66) + if __name__ == '__main__': unittest.main() diff --git a/tests/unit_tests/test_protobuf_json.py b/tests/unit_tests/test_protobuf_json.py index 6ccda3a00b..b382ec21ba 100644 --- a/tests/unit_tests/test_protobuf_json.py +++ b/tests/unit_tests/test_protobuf_json.py @@ -19,7 +19,7 @@ import common import unittest -from trezorlib.protobuf_json import json2pb, pb2json +from trezorlib.protobuf_json import pb2json import trezorlib.messages_pb2 as msg @@ -29,7 +29,7 @@ class TestProtobufJson(unittest.TestCase): m = msg.Features() m.device_id = '1234' j = pb2json(m) - self.assertEqual(j, {'device_id': u'1234'} ) + self.assertEqual(j, {'device_id': u'1234'}) if __name__ == '__main__': diff --git a/tests/unit_tests/test_tx_api.py b/tests/unit_tests/test_tx_api.py index e60fc2feef..cbc795b49a 100644 --- a/tests/unit_tests/test_tx_api.py +++ b/tests/unit_tests/test_tx_api.py @@ -25,20 +25,20 @@ from trezorlib.tx_api import TxApiBitcoin, TxApiTestnet class TestTxApi(unittest.TestCase): def test_get(self): - tx = TxApiBitcoin.get_tx('39a29e954977662ab3879c66fb251ef753e0912223a83d1dcb009111d28265e5') - tx = TxApiBitcoin.get_tx('54aa5680dea781f45ebb536e53dffc526d68c0eb5c00547e323b2c32382dfba3') - tx = TxApiBitcoin.get_tx('58497a7757224d1ff1941488d23087071103e5bf855f4c1c44e5c8d9d82ca46e') - tx = TxApiBitcoin.get_tx('6189e3febb5a21cee8b725aa1ef04ffce7e609448446d3a8d6f483c634ef5315') - tx = TxApiBitcoin.get_tx('a6e2829d089cee47e481b1a753a53081b40738cc87e38f1d9b23ab57d9ad4396') - tx = TxApiBitcoin.get_tx('c6091adf4c0c23982a35899a6e58ae11e703eacd7954f588ed4b9cdefc4dba52') - tx = TxApiBitcoin.get_tx('c63e24ed820c5851b60c54613fbc4bcb37df6cd49b4c96143e99580a472f79fb') - tx = TxApiBitcoin.get_tx('c6be22d34946593bcad1d2b013e12f74159e69574ffea21581dad115572e031c') - tx = TxApiBitcoin.get_tx('d1d08ea63255af4ad16b098e9885a252632086fa6be53301521d05253ce8a73d') - tx = TxApiBitcoin.get_tx('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882') - tx = TxApiBitcoin.get_tx('e4bc1ae5e5007a08f2b3926fe11c66612e8f73c6b00c69c7027213b84d259be3') + TxApiBitcoin.get_tx('39a29e954977662ab3879c66fb251ef753e0912223a83d1dcb009111d28265e5') + TxApiBitcoin.get_tx('54aa5680dea781f45ebb536e53dffc526d68c0eb5c00547e323b2c32382dfba3') + TxApiBitcoin.get_tx('58497a7757224d1ff1941488d23087071103e5bf855f4c1c44e5c8d9d82ca46e') + TxApiBitcoin.get_tx('6189e3febb5a21cee8b725aa1ef04ffce7e609448446d3a8d6f483c634ef5315') + TxApiBitcoin.get_tx('a6e2829d089cee47e481b1a753a53081b40738cc87e38f1d9b23ab57d9ad4396') + TxApiBitcoin.get_tx('c6091adf4c0c23982a35899a6e58ae11e703eacd7954f588ed4b9cdefc4dba52') + TxApiBitcoin.get_tx('c63e24ed820c5851b60c54613fbc4bcb37df6cd49b4c96143e99580a472f79fb') + TxApiBitcoin.get_tx('c6be22d34946593bcad1d2b013e12f74159e69574ffea21581dad115572e031c') + TxApiBitcoin.get_tx('d1d08ea63255af4ad16b098e9885a252632086fa6be53301521d05253ce8a73d') + TxApiBitcoin.get_tx('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882') + TxApiBitcoin.get_tx('e4bc1ae5e5007a08f2b3926fe11c66612e8f73c6b00c69c7027213b84d259be3') - tx = TxApiTestnet.get_tx('6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54') - tx = TxApiTestnet.get_tx('d6da21677d7cca5f42fbc7631d062c9ae918a0254f7c6c22de8e8cb7fd5b8236') + TxApiTestnet.get_tx('6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54') + TxApiTestnet.get_tx('d6da21677d7cca5f42fbc7631d062c9ae918a0254f7c6c22de8e8cb7fd5b8236') if __name__ == '__main__': diff --git a/tools/encfs_aes_getpass.py b/tools/encfs_aes_getpass.py index 03e0400d2c..8fab67ff15 100755 --- a/tools/encfs_aes_getpass.py +++ b/tools/encfs_aes_getpass.py @@ -15,7 +15,7 @@ import json import hashlib import binascii -from trezorlib.client import TrezorClient, TrezorClientDebug +from trezorlib.client import TrezorClient from trezorlib.transport_hid import HidTransport # Python2 vs Python3 @@ -24,6 +24,7 @@ try: except NameError: pass + def wait_for_devices(): devices = HidTransport.enumerate() while not len(devices): @@ -33,6 +34,7 @@ def wait_for_devices(): return devices + def choose_device(devices): if not len(devices): raise Exception("No TREZOR connected!") @@ -71,9 +73,10 @@ def choose_device(devices): except: raise Exception("Invalid choice, exiting...") + def main(): - if not 'encfs_root' in os.environ: + 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) @@ -122,5 +125,6 @@ def main(): print(passw) + if __name__ == '__main__': main() diff --git a/tools/helloworld.py b/tools/helloworld.py index 9afcb57eb7..ea3b7a7e58 100755 --- a/tools/helloworld.py +++ b/tools/helloworld.py @@ -4,6 +4,7 @@ from __future__ import print_function from trezorlib.client import TrezorClient from trezorlib.transport_hid import HidTransport + def main(): # List all connected TREZORs on USB devices = HidTransport.enumerate() @@ -30,5 +31,6 @@ def main(): client.close() + if __name__ == '__main__': main() diff --git a/tools/mem_read.py b/tools/mem_read.py index 0e30fddb4f..e8c1c0d5ca 100755 --- a/tools/mem_read.py +++ b/tools/mem_read.py @@ -2,9 +2,8 @@ from __future__ import print_function from trezorlib.debuglink import DebugLink -from trezorlib.client import TrezorClient, TrezorDebugClient +from trezorlib.client import TrezorClient from trezorlib.transport_hid import HidTransport -import binascii import sys # usage examples @@ -15,6 +14,7 @@ import sys # note that in order for this to work, your trezor device must # be running a firmware that was built with debug link enabled + def main(): # List all connected TREZORs on USB devices = HidTransport.enumerate() @@ -39,12 +39,13 @@ def main(): f = open('memory.dat', 'w') for addr in range(arg1, arg1 + arg2, step): - mem = debug.memory_read(addr, step) - f.write(mem) + mem = debug.memory_read(addr, step) + f.write(mem) f.close() client.close() + if __name__ == '__main__': main() diff --git a/tools/mem_write.py b/tools/mem_write.py index a9393128ad..94aa47af27 100755 --- a/tools/mem_write.py +++ b/tools/mem_write.py @@ -2,11 +2,12 @@ from __future__ import print_function from trezorlib.debuglink import DebugLink -from trezorlib.client import TrezorClient, TrezorDebugClient +from trezorlib.client import TrezorClient from trezorlib.transport_hid import HidTransport import binascii import sys + def main(): # List all connected TREZORs on USB devices = HidTransport.enumerate() @@ -24,8 +25,9 @@ def main(): client = TrezorClient(transport) debug = DebugLink(debug_transport) - mem = debug.memory_write(int(sys.argv[1],16), binascii.unhexlify(sys.argv[2]), flash=True) + debug.memory_write(int(sys.argv[1], 16), binascii.unhexlify(sys.argv[2]), flash=True) client.close() + if __name__ == '__main__': main() diff --git a/tools/mnemonic_check.py b/tools/mnemonic_check.py index 3d18d2fe6c..9a6c655542 100755 --- a/tools/mnemonic_check.py +++ b/tools/mnemonic_check.py @@ -22,6 +22,7 @@ try: except NameError: pass + def generate_entropy(strength, internal_entropy, external_entropy): ''' strength - length of produced seed. One of 128, 192, 256 @@ -50,6 +51,7 @@ def generate_entropy(strength, internal_entropy, external_entropy): return entropy_stripped + def main(): print(__doc__) @@ -72,5 +74,6 @@ def main(): print("Generated mnemonic is:", words) + if __name__ == '__main__': main() diff --git a/tools/rng_entropy_collector.py b/tools/rng_entropy_collector.py index 889146738f..e610cd7d34 100755 --- a/tools/rng_entropy_collector.py +++ b/tools/rng_entropy_collector.py @@ -5,18 +5,19 @@ # push confirmation from __future__ import print_function -import binascii import io import sys from trezorlib.client import TrezorClient from trezorlib.transport_hid import HidTransport + def get_client(): - devices = HidTransport.enumerate() # List all connected TREZORs on USB - if len(devices) == 0: # Check whether we found any + 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 + transport = HidTransport(devices[0]) # use first connected device + return TrezorClient(transport) # creates object for communicating with TREZOR + def main(): client = get_client() @@ -24,9 +25,9 @@ def main(): print('No TREZOR connected') 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 + 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 xrange(0, arg2, step): @@ -35,5 +36,6 @@ def main(): client.close() + if __name__ == '__main__': main() diff --git a/tools/tx_sign_tool.py b/tools/tx_sign_tool.py index 51431e72ab..081060c21d 100755 --- a/tools/tx_sign_tool.py +++ b/tools/tx_sign_tool.py @@ -20,20 +20,26 @@ from __future__ import print_function import binascii from trezorlib.client import TrezorClient from trezorlib.transport_hid import HidTransport -from trezorlib.tx_api import * +from trezorlib.tx_api import TxApiBitcoin, TxApiTestnet, TxApiLitecoin from trezorlib import types_pb2 as types +# Python2 vs Python3 +try: + input = raw_input +except NameError: + pass + def get_client(): - devices = HidTransport.enumerate() # List all connected TREZORs on USB - if len(devices) == 0: # Check whether we found any + 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 + transport = HidTransport(devices[0]) # use first connected device + return TrezorClient(transport) # creates object for communicating with TREZOR def get_txapi(): - coin = raw_input('Which coin {Bitcoin, Testnet, Litecoin}? ').strip() + coin = input('Which coin {Bitcoin, Testnet, Litecoin}? ').strip() if coin not in {'Bitcoin', 'Testnet', 'Litecoin'}: return None, None txapi_lookup = { @@ -66,29 +72,29 @@ def main(): while True: print() - prev_in_hash = raw_input('Previous input hash (empty to move on): ').strip() + prev_in_hash = input('Previous input hash (empty to move on): ').strip() if prev_in_hash == '': break - prev_in_vout = raw_input('Previous input index: ').strip() - addrn = raw_input("Node path to sign with (e.g.- %s/0'/0/0): " % coin).strip() + prev_in_vout = input('Previous input index: ').strip() + addrn = input("Node path to sign with (e.g.- %s/0'/0/0): " % coin).strip() inputs.append(types.TxInputType( - prev_hash = binascii.unhexlify(prev_in_hash), - prev_index = int(prev_in_vout, 10), - address_n = client.expand_path(addrn) + prev_hash=binascii.unhexlify(prev_in_hash), + prev_index=int(prev_in_vout, 10), + address_n=client.expand_path(addrn) )) outputs = [] while True: print() - out_addr = raw_input('Pay to address (empty to move on): ').strip() + out_addr = input('Pay to address (empty to move on): ').strip() if out_addr == '': break - out_amount = raw_input('Amount (in satoshis): ').strip() + out_amount = input('Amount (in satoshis): ').strip() outputs.append(types.TxOutputType( - amount = int(out_amount, 10), - script_type = types.PAYTOADDRESS, - address = out_addr + amount=int(out_amount, 10), + script_type=types.PAYTOADDRESS, + address=out_addr )) (signatures, serialized_tx) = client.sign_tx(coin, inputs, outputs) diff --git a/tox.ini b/tox.ini index e08c793252..7ff2d0248a 100644 --- a/tox.ini +++ b/tox.ini @@ -10,4 +10,4 @@ deps = -rrequirements.txt commands = python -m compileall trezorlib/ - python trezorctl + python trezorctl --help diff --git a/trezorlib/ckd_public.py b/trezorlib/ckd_public.py index 3d48f63a52..c6243d441e 100644 --- a/trezorlib/ckd_public.py +++ b/trezorlib/ckd_public.py @@ -36,7 +36,8 @@ if sys.version_info < (3,): def byteindex(data, index): return ord(data[index]) else: - byteindex = lambda data, index: data[index] + def byteindex(data, index): + return data[index] def point_to_pubkey(point): @@ -46,6 +47,7 @@ def point_to_pubkey(point): vk = x_str + y_str return struct.pack('B', (byteindex(vk, 63) & 1) + 2) + vk[0:32] # To compressed key + def sec_to_public_pair(pubkey): """Convert a public key in sec binary format to a public pair.""" x = string_to_number(pubkey[1:33]) @@ -64,15 +66,19 @@ def sec_to_public_pair(pubkey): return public_pair_for_x(ecdsa.ecdsa.generator_secp256k1, x, is_even=(sec0 == b'\2')) + def is_prime(n): return (bool)(n & PRIME_DERIVATION_FLAG) + def fingerprint(pubkey): return string_to_number(tools.hash_160(pubkey)[:4]) + def get_address(public_node, address_type): return tools.public_key_to_bc_address(public_node.public_key, address_type) + def public_ckd(public_node, n): if not isinstance(n, list): raise Exception('Parameter must be a list') @@ -85,6 +91,7 @@ def public_ckd(public_node, n): return node + def get_subnode(node, i): # Public Child key derivation (CKD) algorithm of BIP32 i_as_bytes = struct.pack(">L", i) @@ -106,8 +113,7 @@ def get_subnode(node, i): # BIP32 magic converts old public key to new public point x, y = sec_to_public_pair(node.public_key) - point = I_left_as_exponent * SECP256k1.generator + \ - Point(SECP256k1.curve, x, y, SECP256k1.order) + point = I_left_as_exponent * SECP256k1.generator + Point(SECP256k1.curve, x, y, SECP256k1.order) if point == INFINITY: raise Exception("Point cannot be INFINITY") @@ -117,6 +123,7 @@ def get_subnode(node, i): return node_out + def serialize(node, version=0x0488B21E): s = b'' s += struct.pack('>I', version) @@ -131,6 +138,7 @@ def serialize(node, version=0x0488B21E): s += tools.Hash(s)[:4] return tools.b58encode(s) + def deserialize(xpub): data = tools.b58decode(xpub, None) diff --git a/trezorlib/client.py b/trezorlib/client.py index e93cbd9ec7..bddf6c1cca 100644 --- a/trezorlib/client.py +++ b/trezorlib/client.py @@ -25,17 +25,24 @@ import time import binascii import hashlib import unicodedata -import json +# import json import getpass from mnemonic import Mnemonic from . import tools -from . import mapping +# from . import mapping from . import messages_pb2 as proto from . import types_pb2 as types from .debuglink import DebugLink +# Python2 vs Python3 +try: + input = raw_input +except NameError: + pass + + # try: # from PIL import Image # SCREENSHOT = True @@ -59,7 +66,9 @@ def getch(): return msvcrt.getch() # POSIX system. Create and return a getch that manipulates the tty. - import sys, tty + import sys + import tty + def _getch(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) @@ -72,9 +81,11 @@ def getch(): return _getch() + def get_buttonrequest_value(code): # Converts integer code to its string representation of ButtonRequestType - return [ k for k, v in types.ButtonRequestType.items() if v == code][0] + return [k for k, v in types.ButtonRequestType.items() if v == code][0] + def pprint(msg): msg_class = msg.__class__.__name__ @@ -89,19 +100,23 @@ def pprint(msg): else: return "<%s> (%d bytes):\n%s" % (msg_class, msg_size, msg) + def log(msg): sys.stderr.write(str(msg)) sys.stderr.write('\n') sys.stderr.flush() + class CallException(Exception): def __init__(self, code, message): super(CallException, self).__init__() self.args = [code, message] + class PinException(CallException): pass + class field(object): # Decorator extracts single value from # protobuf object. If the field is not @@ -116,6 +131,7 @@ class field(object): return getattr(ret, self.field) return wrapped_f + class expect(object): # Decorator checks if the method # returned one of expected protobuf messages @@ -131,6 +147,7 @@ class expect(object): return ret return wrapped_f + def session(f): # Decorator wraps a BaseClient method # with session activation / deactivation @@ -143,6 +160,7 @@ def session(f): client.transport.session_end() return wrapped_f + def normalize_nfc(txt): if sys.version_info[0] < 3: if isinstance(txt, unicode): @@ -157,6 +175,7 @@ def normalize_nfc(txt): raise Exception('unicode/str or bytes/str expected') + class BaseClient(object): # Implements very basic layer of sending raw protobuf # messages to device and getting its response back. @@ -178,9 +197,9 @@ class BaseClient(object): handler_name = "callback_%s" % resp.__class__.__name__ handler = getattr(self, handler_name, None) - if handler != None: + if handler is not None: msg = handler(resp) - if msg == None: + if msg is None: raise Exception("Callback %s must return protobuf message, not None" % handler) resp = self.call(msg) @@ -188,7 +207,7 @@ class BaseClient(object): def callback_Failure(self, msg): if msg.code in (types.Failure_PinInvalid, - types.Failure_PinCancelled, types.Failure_PinExpected): + types.Failure_PinCancelled, types.Failure_PinExpected): raise PinException(msg.code, msg.message) raise CallException(msg.code, msg.message) @@ -196,6 +215,7 @@ class BaseClient(object): def close(self): self.transport.close() + class DebugWireMixin(object): def call_raw(self, msg): log("SENDING " + pprint(msg)) @@ -203,6 +223,7 @@ class DebugWireMixin(object): log("RECEIVED " + pprint(resp)) return resp + class TextUIMixin(object): # This class demonstrates easy test-based UI # integration between the device and wallet. @@ -233,8 +254,7 @@ class TextUIMixin(object): return proto.WordAck(word='\x08') # ignore middle column if only 6 keys requested. - if (msg.type == types.WordRequestType_Matrix6 and - character in ('2', '5', '8')): + if (isinstance(msg.type, types.WordRequestType_Matrix6) and character in ('2', '5', '8')): continue if (ord(character) >= ord('1') and ord(character) <= ord('9')): @@ -274,14 +294,12 @@ class TextUIMixin(object): types.WordRequestType_Matrix6): return self.callback_RecoveryMatrix(msg) log("Enter one word of mnemonic: ") - try: - word = raw_input() - except NameError: - word = input() # Python 3 + word = input() if self.expand: word = self.mnemonic_wordlist.expand_word(word) return proto.WordAck(word=word) + class DebugLinkMixin(object): # This class implements automatic responses # and other functionality for unit tests @@ -328,15 +346,15 @@ class DebugLinkMixin(object): def __exit__(self, _type, value, traceback): self.in_with_statement -= 1 - if _type != None: + if _type is not None: # Another exception raised return False # return isinstance(value, TypeError) # Evaluate missed responses in 'with' statement - if self.expected_responses != None and len(self.expected_responses): - raise Exception("Some of expected responses didn't come from device: %s" % \ - [ pprint(x) for x in self.expected_responses ]) + if self.expected_responses is not None and len(self.expected_responses): + raise Exception("Some of expected responses didn't come from device: %s" % + [pprint(x) for x in self.expected_responses]) # Cleanup self.expected_responses = None @@ -376,22 +394,22 @@ class DebugLinkMixin(object): return resp def _check_request(self, msg): - if self.expected_responses != None: + if self.expected_responses is not None: try: expected = self.expected_responses.pop(0) except IndexError: raise CallException(types.Failure_UnexpectedMessage, - "Got %s, but no message has been expected" % pprint(msg)) + "Got %s, but no message has been expected" % pprint(msg)) if msg.__class__ != expected.__class__: raise CallException(types.Failure_UnexpectedMessage, - "Expected %s, got %s" % (pprint(expected), pprint(msg))) + "Expected %s, got %s" % (pprint(expected), pprint(msg))) fields = expected.ListFields() # only filled (including extensions) for field, value in fields: if not msg.HasField(field.name) or getattr(msg, field.name) != value: raise CallException(types.Failure_UnexpectedMessage, - "Expected %s, got %s" % (pprint(expected), pprint(msg))) + "Expected %s, got %s" % (pprint(expected), pprint(msg))) def callback_ButtonRequest(self, msg): log("ButtonRequest code: " + get_buttonrequest_value(msg.code)) @@ -423,6 +441,7 @@ class DebugLinkMixin(object): raise Exception("Unexpected call") + class ProtocolMixin(object): PRIME_DERIVATION_FLAG = 0x80000000 VENDORS = ('bitcointrezor.com', 'trezor.io') @@ -445,7 +464,7 @@ class ProtocolMixin(object): def _convert_prime(self, n): # Convert minus signs to uint32 with flag - return [ int(abs(x) | self.PRIME_DERIVATION_FLAG) if x < 0 else x for x in n ] + return [int(abs(x) | self.PRIME_DERIVATION_FLAG) if x < 0 else x for x in n] @staticmethod def expand_path(n): @@ -474,7 +493,7 @@ class ProtocolMixin(object): "Decred": 42 } if n[0] in coins: - n = ["44'", "%d'" % coins[n[0]] ] + n[1:] + n = ["44'", "%d'" % coins[n[0]]] + n[1:] path = [] for x in n: @@ -498,7 +517,7 @@ class ProtocolMixin(object): def get_public_node(self, n, ecdsa_curve_name=DEFAULT_CURVE, show_display=False, coin_name=None): n = self._convert_prime(n) if not ecdsa_curve_name: - ecdsa_curve_name=DEFAULT_CURVE + ecdsa_curve_name = DEFAULT_CURVE return self.call(proto.GetPublicKey(address_n=n, ecdsa_curve_name=ecdsa_curve_name, show_display=show_display, coin_name=coin_name)) @field('address') @@ -553,7 +572,6 @@ class ProtocolMixin(object): return response.signature_v, response.signature_r, response.signature_s - @field('entropy') @expect(proto.Entropy) def get_entropy(self, size): @@ -575,13 +593,13 @@ class ProtocolMixin(object): @expect(proto.Success) def apply_settings(self, label=None, language=None, use_passphrase=None, homescreen=None): settings = proto.ApplySettings() - if label != None: + if label is not None: settings.label = label if language: settings.language = language - if use_passphrase != None: + if use_passphrase is not None: settings.use_passphrase = use_passphrase - if homescreen != None: + if homescreen is not None: settings.homescreen = homescreen out = self.call(settings) @@ -618,7 +636,7 @@ class ProtocolMixin(object): @field('message') @expect(proto.Success) def set_u2f_counter(self, u2f_counter): - ret = self.call(proto.SetU2FCounter(u2f_counter = u2f_counter)) + ret = self.call(proto.SetU2FCounter(u2f_counter=u2f_counter)) return ret def verify_message(self, coin_name, address, signature, message): @@ -760,7 +778,7 @@ class ProtocolMixin(object): serialized_tx += res.serialized.serialized_tx if res.HasField('serialized') and res.serialized.HasField('signature_index'): - if signatures[res.serialized.signature_index] != None: + if signatures[res.serialized.signature_index] is not None: raise Exception("Signature for index %d already filled" % res.serialized.signature_index) signatures[res.serialized.signature_index] = res.serialized.signature @@ -797,7 +815,7 @@ class ProtocolMixin(object): else: msg.outputs.extend([current_tx.outputs[res.details.request_index], ]) - if debug_processor != None: + if debug_processor is not None: # If debug_processor function is provided, # pass thru it the request and prepared response. # This is useful for unit tests, see test_msg_signtx @@ -816,8 +834,8 @@ class ProtocolMixin(object): if None in signatures: raise Exception("Some signatures are missing!") - log("SIGNED IN %.03f SECONDS, CALLED %d MESSAGES, %d BYTES" % \ - (time.time() - start, counter, len(serialized_tx))) + log("SIGNED IN %.03f SECONDS, CALLED %d MESSAGES, %d BYTES" % + (time.time() - start, counter, len(serialized_tx))) return (signatures, serialized_tx) @@ -844,14 +862,15 @@ class ProtocolMixin(object): # optimization to load the wordlist once, instead of for each recovery word self.mnemonic_wordlist = Mnemonic('english') - res = self.call(proto.RecoveryDevice(word_count=int(word_count), - passphrase_protection=bool(passphrase_protection), - pin_protection=bool(pin_protection), - label=label, - language=language, - enforce_wordlist=True, - type=type, - dry_run=dry_run)) + res = self.call(proto.RecoveryDevice( + word_count=int(word_count), + passphrase_protection=bool(passphrase_protection), + pin_protection=bool(pin_protection), + label=label, + language=language, + enforce_wordlist=True, + type=type, + dry_run=dry_run)) self.init_device() return res @@ -963,7 +982,7 @@ class ProtocolMixin(object): @session def firmware_update(self, fp): - if self.features.bootloader_mode == False: + if self.features.bootloader_mode is False: raise Exception("Device must be in bootloader mode") data = fp.read() @@ -1000,11 +1019,14 @@ class ProtocolMixin(object): raise Exception("Unexpected message %s" % resp) + class TrezorClient(ProtocolMixin, TextUIMixin, BaseClient): pass + class TrezorClientDebug(ProtocolMixin, TextUIMixin, DebugWireMixin, BaseClient): pass + class TrezorDebugClient(ProtocolMixin, DebugLinkMixin, DebugWireMixin, BaseClient): pass diff --git a/trezorlib/debuglink.py b/trezorlib/debuglink.py index 152e4bf421..2e91a34574 100644 --- a/trezorlib/debuglink.py +++ b/trezorlib/debuglink.py @@ -19,17 +19,20 @@ from __future__ import print_function from . import messages_pb2 as proto -from .transport import NotImplementedException + def pin_info(pin): print("Device asks for PIN %s" % pin) + def button_press(yes_no): print("User pressed", '"y"' if yes_no else '"n"') + def pprint(msg): return "<%s> (%d bytes):\n%s" % (msg.__class__.__name__, msg.ByteSize(), msg) + class DebugLink(object): def __init__(self, transport, pin_func=pin_info, button_func=button_press): self.transport = transport @@ -126,4 +129,4 @@ class DebugLink(object): self._call(proto.DebugLinkMemoryWrite(address=address, memory=memory, flash=flash), nowait=True) def flash_erase(self, sector): - obj = self._call(proto.DebugLinkFlashErase(sector=sector), nowait=True) + self._call(proto.DebugLinkFlashErase(sector=sector), nowait=True) diff --git a/trezorlib/mapping.py b/trezorlib/mapping.py index a1f2854d8b..217aa51101 100644 --- a/trezorlib/mapping.py +++ b/trezorlib/mapping.py @@ -21,6 +21,7 @@ from . import messages_pb2 as proto map_type_to_class = {} map_class_to_type = {} + def build_map(): for msg_type, i in proto.MessageType.items(): msg_name = msg_type.replace('MessageType_', '') @@ -29,6 +30,7 @@ def build_map(): map_type_to_class[i] = msg_class map_class_to_type[msg_class] = i + def get_type(msg): return map_class_to_type[msg.__class__] @@ -36,6 +38,7 @@ def get_type(msg): def get_class(t): return map_type_to_class[t] + def check_missing(): from google.protobuf import reflection @@ -47,5 +50,6 @@ def check_missing(): if len(missing): raise Exception("Following protobuf messages are not defined in mapping: %s" % missing) + build_map() check_missing() diff --git a/trezorlib/protobuf_json.py b/trezorlib/protobuf_json.py index 7d2b1be0f9..ccc0d6a378 100644 --- a/trezorlib/protobuf_json.py +++ b/trezorlib/protobuf_json.py @@ -37,15 +37,16 @@ Provide serialization and de-serialization of Google's protobuf Messages into/fr # Note that preservation of unknown fields is currently not available for Python (c) google docs # extensions is not supported from 0.0.5 (due to gpb2.3 changes) -__version__='0.0.6' -__author__='Paul Dovbush ' +__version__ = '0.0.6' +__author__ = 'Paul Dovbush ' -import json # py2.6+ TODO: add support for other JSON serialization modules from google.protobuf.descriptor import FieldDescriptor as FD from functools import partial -class ParseError(Exception): pass + +class ParseError(Exception): + pass def json2pb(pb, js, useFieldNumber=False): @@ -79,13 +80,12 @@ def json2pb(pb, js, useFieldNumber=False): return pb - def pb2json(pb, useFieldNumber=False): ''' convert google.protobuf.descriptor instance to JSON string ''' js = {} - # fields = pb.DESCRIPTOR.fields #all fields - fields = pb.ListFields() #only filled (including extensions) - for field,value in fields: + # fields = pb.DESCRIPTOR.fields # all fields + fields = pb.ListFields() # only filled (including extensions) + for field, value in fields: if useFieldNumber: key = field.number else: @@ -94,7 +94,8 @@ def pb2json(pb, useFieldNumber=False): ftype = partial(pb2json, useFieldNumber=useFieldNumber) # ---- monkey patching ---- elif field.type == FD.TYPE_ENUM: - ftype = lambda x: field.enum_type.values[x].name + def ftype(x): + return field.enum_type.values[x].name # ---- end of monkey patching ---- elif field.type in _ftype2js: ftype = _ftype2js[field.type] @@ -120,7 +121,7 @@ _ftype2js = { FD.TYPE_FIXED32: float, FD.TYPE_BOOL: bool, FD.TYPE_STRING: str, - #FD.TYPE_MESSAGE: pb2json, #handled specially + # FD.TYPE_MESSAGE: pb2json, #handled specially FD.TYPE_BYTES: lambda x: x.encode('string_escape'), FD.TYPE_UINT32: int, FD.TYPE_ENUM: int, @@ -140,7 +141,7 @@ _js2ftype = { FD.TYPE_FIXED32: float, FD.TYPE_BOOL: bool, FD.TYPE_STRING: str, - # FD.TYPE_MESSAGE: json2pb, #handled specially + # FD.TYPE_MESSAGE: json2pb, # handled specially FD.TYPE_BYTES: lambda x: x.decode('string_escape'), FD.TYPE_UINT32: int, FD.TYPE_ENUM: int, @@ -156,7 +157,7 @@ import binascii from . import types_pb2 as types _ftype2js[FD.TYPE_BYTES] = lambda x: binascii.hexlify(x) -del _ftype2js[FD.TYPE_ENUM] # handled specially +del _ftype2js[FD.TYPE_ENUM] # handled specially _js2ftype[FD.TYPE_BYTES] = lambda x: binascii.unhexlify(x) _js2ftype[FD.TYPE_ENUM] = lambda x: getattr(types, x) diff --git a/trezorlib/qt/pinmatrix.py b/trezorlib/qt/pinmatrix.py index 768f6b59a3..add67fb029 100644 --- a/trezorlib/qt/pinmatrix.py +++ b/trezorlib/qt/pinmatrix.py @@ -13,6 +13,7 @@ except: from PyQt5.QtCore import QRegExp, Qt from PyQt5.Qt import QT_VERSION_STR + class PinButton(QPushButton): def __init__(self, password, encoded_value): super(PinButton, self).__init__('?') @@ -30,6 +31,7 @@ class PinButton(QPushButton): self.password.setText(self.password.text() + str(self.encoded_value)) self.password.setFocus() + class PinMatrixWidget(QWidget): ''' Displays widget with nine blank buttons and password box. @@ -101,6 +103,7 @@ class PinMatrixWidget(QWidget): def get_value(self): return self.password.text() + if __name__ == '__main__': ''' Demo application showing PinMatrix widget in action diff --git a/trezorlib/tools.py b/trezorlib/tools.py index 154cf70802..572f00ea4d 100644 --- a/trezorlib/tools.py +++ b/trezorlib/tools.py @@ -25,13 +25,18 @@ import sys if sys.version_info < (3,): def byteindex(data, index): return ord(data[index]) + def iterbytes(data): - return (ord (char) for char in data) + return (ord(char) for char in data) else: - byteindex = lambda data, index: data[index] + def byteindex(data, index): + return data[index] iterbytes = iter -Hash = lambda x: hashlib.sha256(hashlib.sha256(x).digest()).digest() + +def Hash(data): + return hashlib.sha256(hashlib.sha256(data).digest()).digest() + def hash_160(public_key): md = hashlib.new('ripemd160') @@ -45,11 +50,13 @@ def hash_160_to_bc_address(h160, address_type): addr = vh160 + h[0:4] return b58encode(addr) + def compress_pubkey(public_key): if byteindex(public_key, 0) == 4: return bytes((byteindex(public_key, 64) & 1) + 2) + public_key[1:33] raise Exception("Pubkey is already compressed") + def public_key_to_bc_address(public_key, address_type, compress=True): if public_key[0] == '\x04' and compress: public_key = compress_pubkey(public_key) @@ -57,9 +64,11 @@ def public_key_to_bc_address(public_key, address_type, compress=True): h160 = hash_160(public_key) return hash_160_to_bc_address(h160, address_type) + __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' __b58base = len(__b58chars) + def b58encode(v): """ encode v, which is a string of bytes, to base58.""" @@ -85,6 +94,7 @@ def b58encode(v): return (__b58chars[0] * nPad) + result + def b58decode(v, length): """ decode v into a string of len bytes.""" long_value = 0 @@ -111,6 +121,7 @@ def b58decode(v, length): return result + def monkeypatch_google_protobuf_text_format(): # monkeypatching: text formatting of protobuf messages import google.protobuf.text_format @@ -125,4 +136,3 @@ def monkeypatch_google_protobuf_text_format(): _oldPrintFieldValue(field, value, out, indent, as_utf8, as_one_line) google.protobuf.text_format.PrintFieldValue = _customPrintFieldValue - diff --git a/trezorlib/transport.py b/trezorlib/transport.py index d1d5e28367..837227a021 100644 --- a/trezorlib/transport.py +++ b/trezorlib/transport.py @@ -19,15 +19,18 @@ from __future__ import absolute_import import struct -from . import mapping import binascii +from . import mapping + class NotImplementedException(Exception): pass + class ConnectionError(Exception): pass + class Transport(object): def __init__(self, device, *args, **kwargs): self.device = device @@ -84,7 +87,7 @@ class Transport(object): """ while True: data = self._read() - if data != None: + if data is not None: break return self._parse_message(data) @@ -129,6 +132,7 @@ class Transport(object): def _session_end(self): pass + class TransportV1(Transport): def write(self, msg): ser = msg.SerializeToString() @@ -172,6 +176,7 @@ class TransportV1(Transport): return chunk[1:] + class TransportV2(Transport): def write(self, msg): if not self.session_id: diff --git a/trezorlib/transport_bridge.py b/trezorlib/transport_bridge.py index 044a8184ec..a777258da6 100644 --- a/trezorlib/transport_bridge.py +++ b/trezorlib/transport_bridge.py @@ -28,9 +28,11 @@ from .transport import TransportV1 TREZORD_HOST = 'https://localback.net:21324' CONFIG_URL = 'https://wallet.trezor.io/data/config_signed.bin' + def get_error(resp): return ' (error=%d str=%s)' % (resp.status_code, resp.json()['error']) + class BridgeTransport(TransportV1): CONFIGURED = False @@ -47,7 +49,8 @@ class BridgeTransport(TransportV1): @staticmethod def configure(): - if BridgeTransport.CONFIGURED: return + if BridgeTransport.CONFIGURED: + return r = requests.get(CONFIG_URL, verify=False) if r.status_code != 200: raise Exception('Could not fetch config from %s' % CONFIG_URL) @@ -88,7 +91,7 @@ class BridgeTransport(TransportV1): self.session = None def _ready_to_read(self): - return self.response != None + return self.response is not None def write(self, protobuf_msg): # Override main 'write' method, HTTP transport cannot be diff --git a/trezorlib/transport_hid.py b/trezorlib/transport_hid.py index 8259b7da8b..5714bfe9ab 100644 --- a/trezorlib/transport_hid.py +++ b/trezorlib/transport_hid.py @@ -18,10 +18,11 @@ '''USB HID implementation of Transport.''' -import hid import time +import hid from .transport import TransportV1, TransportV2, ConnectionError + def enumerate(): """ Return a list of available TREZOR devices. @@ -46,9 +47,10 @@ def enumerate(): # List of two-tuples (path_normal, path_debuglink) return sorted(devices.values()) + def path_to_transport(path): try: - device = [ d for d in hid.enumerate(0, 0) if d['path'] == path ][0] + device = [d for d in hid.enumerate(0, 0) if d['path'] == path][0] except IndexError: raise ConnectionError("Connection failed") @@ -56,10 +58,11 @@ def path_to_transport(path): try: transport = DEVICE_TRANSPORTS[(device['vendor_id'], device['product_id'])] except IndexError: - raise Exception("Unknown transport for VID:PID %04x:%04x" % (vid, pid)) + raise Exception("Unknown transport for VID:PID %04x:%04x" % (device['vendor_id'], device['product_id'])) return transport + class _HidTransport(object): def __init__(self, device, *args, **kwargs): self.hid = None @@ -134,12 +137,15 @@ class _HidTransport(object): return bytearray(data) + class HidTransportV1(_HidTransport, TransportV1): pass + class HidTransportV2(_HidTransport, TransportV2): pass + DEVICE_IDS = [ (0x534c, 0x0001), # TREZOR (0x1209, 0x53c0), # TREZORv2 Bootloader @@ -152,11 +158,13 @@ DEVICE_TRANSPORTS = { (0x1209, 0x53c1): HidTransportV2, # TREZORv2 } + # Backward compatible wrapper, decides for proper transport # based on VID/PID of given path def HidTransport(device, *args, **kwargs): transport = path_to_transport(device[0]) return transport(device, *args, **kwargs) + # Backward compatibility hack; HidTransport is a function, not a class like before HidTransport.enumerate = enumerate diff --git a/trezorlib/transport_pipe.py b/trezorlib/transport_pipe.py index 624d567837..6566d29cb7 100644 --- a/trezorlib/transport_pipe.py +++ b/trezorlib/transport_pipe.py @@ -18,36 +18,39 @@ from __future__ import print_function import os +import time from select import select + from .transport import TransportV1 """PipeTransport implements fake wire transport over local named pipe. Use this transport for talking with trezor simulator.""" + class PipeTransport(TransportV1): def __init__(self, device, is_device, *args, **kwargs): - self.is_device = is_device # Set True if act as device + self.is_device = is_device # set True if act as device super(PipeTransport, self).__init__(device, *args, **kwargs) def _open(self): if self.is_device: - self.filename_read = self.device+'.to' - self.filename_write = self.device+'.from' + self.filename_read = self.device + '.to' + self.filename_write = self.device + '.from' os.mkfifo(self.filename_read, 0o600) os.mkfifo(self.filename_write, 0o600) else: - self.filename_read = self.device+'.from' - self.filename_write = self.device+'.to' + self.filename_read = self.device + '.from' + self.filename_write = self.device + '.to' if not os.path.exists(self.filename_write): raise Exception("Not connected") - self.write_fd = os.open(self.filename_write, os.O_RDWR)#|os.O_NONBLOCK) + self.write_fd = os.open(self.filename_write, os.O_RDWR) # |os.O_NONBLOCK) self.write_f = os.fdopen(self.write_fd, 'w+b', 0) - self.read_fd = os.open(self.filename_read, os.O_RDWR)#|os.O_NONBLOCK) + self.read_fd = os.open(self.filename_read, os.O_RDWR) # |os.O_NONBLOCK) self.read_f = os.fdopen(self.read_fd, 'rb', 0) def _close(self): diff --git a/trezorlib/transport_udp.py b/trezorlib/transport_udp.py index 7ef3d2dd51..4a4b930779 100644 --- a/trezorlib/transport_udp.py +++ b/trezorlib/transport_udp.py @@ -20,7 +20,8 @@ import socket from select import select -from .transport import TransportV2, ConnectionError +from .transport import TransportV2 + class UdpTransport(TransportV2): def __init__(self, device, *args, **kwargs): diff --git a/trezorlib/tx_api.py b/trezorlib/tx_api.py index 6c12451489..6acb208d5b 100644 --- a/trezorlib/tx_api.py +++ b/trezorlib/tx_api.py @@ -25,6 +25,7 @@ from . import types_pb2 as proto_types cache_dir = None + class TxApi(object): def __init__(self, network, url): @@ -35,7 +36,7 @@ class TxApi(object): global cache_dir if cache_dir: cache_file = '%s/%s_%s_%s.json' % (cache_dir, self.network, resource, resourceid) - try: # looking into cache first + try: # looking into cache first j = json.load(open(cache_file)) return j except: @@ -47,7 +48,7 @@ class TxApi(object): except: raise Exception('URL error: %s' % url) if cache_dir and cache_file: - try: # saving into cache + try: # saving into cache json.dump(j, open(cache_file, 'w')) except: pass @@ -74,8 +75,8 @@ class TxApiInsight(TxApi): for vin in data['vin']: i = t.inputs.add() if 'coinbase' in vin.keys(): - i.prev_hash = b"\0"*32 - i.prev_index = 0xffffffff # signed int -1 + i.prev_hash = b"\0" * 32 + i.prev_index = 0xffffffff # signed int -1 i.script_sig = binascii.unhexlify(vin['coinbase']) i.sequence = vin['sequence'] @@ -94,7 +95,7 @@ class TxApiInsight(TxApi): if t.version == 2: joinsplit_cnt = len(data['vjoinsplit']) if joinsplit_cnt == 0: - t.extra_data =b'\x00' + t.extra_data = b'\x00' else: if joinsplit_cnt >= 253: # we assume cnt < 253, so we can treat varIntLen(cnt) as 1 @@ -122,8 +123,8 @@ class TxApiSmartbit(TxApi): for vin in data['inputs']: i = t.inputs.add() if 'coinbase' in vin.keys(): - i.prev_hash = b"\0"*32 - i.prev_index = 0xffffffff # signed int -1 + i.prev_hash = b"\0" * 32 + i.prev_index = 0xffffffff # signed int -1 i.script_sig = binascii.unhexlify(vin['coinbase']) i.sequence = vin['sequence'] @@ -154,8 +155,8 @@ class TxApiBlockCypher(TxApi): for vin in data['inputs']: i = t.inputs.add() if 'prev_hash' not in vin: - i.prev_hash = b"\0"*32 - i.prev_index = 0xffffffff # signed int -1 + i.prev_hash = b"\0" * 32 + i.prev_index = 0xffffffff # signed int -1 i.script_sig = binascii.unhexlify(vin['script']) i.sequence = vin['sequence'] else: @@ -177,4 +178,3 @@ TxApiTestnet = TxApiInsight(network='insight_testnet', url='https://test-insight TxApiLitecoin = TxApiBlockCypher(network='blockcypher_litecoin', url='https://api.blockcypher.com/v1/ltc/main/') TxApiSegnet = TxApiSmartbit(network='smartbit_segnet', url='https://segnet-api.smartbit.com.au/v1/blockchain/') TxApiZcashTestnet = TxApiInsight(network='insight_zcashtestnet', url='https://explorer.testnet.z.cash/api/', zcash=True) -