[Python-modules-commits] [python-keepkey] 01/03: Import python-keepkey_0.7.3.orig.tar.gz

Tristan Seligmann mithrandi at moszumanska.debian.org
Sun Jul 3 22:36:13 UTC 2016


This is an automated email from the git hooks/post-receive script.

mithrandi pushed a commit to branch master
in repository python-keepkey.

commit 3dbf29c469ba27af8cc3bce84e7ee82e9f9c6754
Author: Tristan Seligmann <mithrandi at debian.org>
Date:   Mon Jul 4 00:30:48 2016 +0200

    Import python-keepkey_0.7.3.orig.tar.gz
---
 MANIFEST.in                             |   1 +
 PKG-INFO                                |   2 +-
 README.rst                              |   6 +-
 keepkey.egg-info/PKG-INFO               |   2 +-
 keepkey.egg-info/SOURCES.txt            |  40 ++-
 keepkey.egg-info/requires.txt           |   4 +-
 keepkeyctl                              |  73 ++--
 keepkeylib/ckd_public.py                |  10 +-
 keepkeylib/client.py                    |  81 ++---
 keepkeylib/debuglink.py                 |  28 +-
 keepkeylib/mapping.py                   |   4 +-
 keepkeylib/qt/pinmatrix.py              |  11 +-
 keepkeylib/tools.py                     |  10 +-
 keepkeylib/transport.py                 |  43 ++-
 keepkeylib/transport_fake.py            |  12 +-
 keepkeylib/transport_hid.py             |  74 ++--
 keepkeylib/transport_pipe.py            |  39 ++-
 keepkeylib/transport_serial.py          |  19 +-
 keepkeylib/transport_socket.py          |  44 +--
 keepkeylib/tx_api.py                    |  64 +++-
 keepkeylib/types_pb2.py                 | 170 +++++++--
 setup.py                                |   4 +-
 tests/common.py                         |  71 ++++
 tests/config.py                         |  51 +++
 tests/run-jenkins.sh                    |  55 +++
 tests/run-separate.sh                   |   5 +
 tests/run.sh                            |   3 +
 tests/test_basic.py                     |  36 ++
 tests/test_bip32_speed.py               |  57 +++
 tests/test_bootloader.py                | 140 ++++++++
 tests/test_debuglink.py                 |  40 +++
 tests/test_ecies.py                     | 134 +++++++
 tests/test_msg_applysettings.py         |  63 ++++
 tests/test_msg_changepin.py             | 212 +++++++++++
 tests/test_msg_cipherkeyvalue.py        |  74 ++++
 tests/test_msg_clearsession.py          |  39 +++
 tests/test_msg_estimatetxsize.py        |  34 ++
 tests/test_msg_getaddress.py            |  44 +++
 tests/test_msg_getaddress_show.py       |  49 +++
 tests/test_msg_getentropy.py            |  34 ++
 tests/test_msg_getpublickey.py          |  28 ++
 tests/test_msg_loaddevice.py            |  88 +++++
 tests/test_msg_ping.py                  |  50 +++
 tests/test_msg_recoverydevice.py        | 158 +++++++++
 tests/test_msg_recoverydevice_cipher.py | 272 +++++++++++++++
 tests/test_msg_resetdevice.py           | 188 ++++++++++
 tests/test_msg_signidentity.py          |  73 ++++
 tests/test_msg_signmessage.py           |  45 +++
 tests/test_msg_signtx.py                | 598 ++++++++++++++++++++++++++++++++
 tests/test_msg_signtx_xfer.py           | 326 +++++++++++++++++
 tests/test_msg_simplesigntx.py          | 360 +++++++++++++++++++
 tests/test_msg_verifymessage.py         | 132 +++++++
 tests/test_msg_wipedevice.py            |  25 ++
 tests/test_multisig.py                  | 224 ++++++++++++
 tests/test_multisig_change.py           | 355 +++++++++++++++++++
 tests/test_op_return.py                 |  92 +++++
 tests/test_protect_call.py              | 121 +++++++
 tests/test_protection_levels.py         | 201 +++++++++++
 tests/test_zerosig.py                   |  88 +++++
 59 files changed, 5032 insertions(+), 274 deletions(-)

diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..dcb861c
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1 @@
+recursive-include tests *.py *.sh
diff --git a/PKG-INFO b/PKG-INFO
index 9d02d00..be15af3 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
 Metadata-Version: 1.1
 Name: keepkey
-Version: 0.7.0
+Version: 0.7.3
 Summary: Python library for communicating with KeepKey Hardware Wallet
 Home-page: https://github.com/keepkey/python-keepkey
 Author: Bitcoin TREZOR and KeepKey
diff --git a/README.rst b/README.rst
index f940b43..8b330ec 100644
--- a/README.rst
+++ b/README.rst
@@ -28,7 +28,7 @@ also found in ``helloworld.py``
 
       # Check whether we found any
       if len(devices) == 0:
-          print 'No KeepKey found'
+          print('No KeepKey found')
           return
 
       # Use first connected device
@@ -38,13 +38,13 @@ also found in ``helloworld.py``
       client = KeepKeyClient(transport)
 
       # Print out KeepKey's features and settings
-      print client.features
+      print(client.features)
 
       # Get the first address of first BIP44 account
       # (should be the same address as shown in KeepKey wallet Chrome extension)
       bip32_path = client.expand_path("44'/0'/0'/0/0")
       address = client.get_address('Bitcoin', bip32_path)
-      print 'Bitcoin address:', address
+      print('Bitcoin address:', address)
 
       client.close()
 
diff --git a/keepkey.egg-info/PKG-INFO b/keepkey.egg-info/PKG-INFO
index 9d02d00..be15af3 100644
--- a/keepkey.egg-info/PKG-INFO
+++ b/keepkey.egg-info/PKG-INFO
@@ -1,6 +1,6 @@
 Metadata-Version: 1.1
 Name: keepkey
-Version: 0.7.0
+Version: 0.7.3
 Summary: Python library for communicating with KeepKey Hardware Wallet
 Home-page: https://github.com/keepkey/python-keepkey
 Author: Bitcoin TREZOR and KeepKey
diff --git a/keepkey.egg-info/SOURCES.txt b/keepkey.egg-info/SOURCES.txt
index 05e1923..56929ea 100644
--- a/keepkey.egg-info/SOURCES.txt
+++ b/keepkey.egg-info/SOURCES.txt
@@ -1,3 +1,4 @@
+MANIFEST.in
 README.rst
 keepkeyctl
 setup.py
@@ -24,4 +25,41 @@ keepkeylib/transport_socket.py
 keepkeylib/tx_api.py
 keepkeylib/types_pb2.py
 keepkeylib/qt/__init__.py
-keepkeylib/qt/pinmatrix.py
\ No newline at end of file
+keepkeylib/qt/pinmatrix.py
+tests/common.py
+tests/config.py
+tests/run-jenkins.sh
+tests/run-separate.sh
+tests/run.sh
+tests/test_basic.py
+tests/test_bip32_speed.py
+tests/test_bootloader.py
+tests/test_debuglink.py
+tests/test_ecies.py
+tests/test_msg_applysettings.py
+tests/test_msg_changepin.py
+tests/test_msg_cipherkeyvalue.py
+tests/test_msg_clearsession.py
+tests/test_msg_estimatetxsize.py
+tests/test_msg_getaddress.py
+tests/test_msg_getaddress_show.py
+tests/test_msg_getentropy.py
+tests/test_msg_getpublickey.py
+tests/test_msg_loaddevice.py
+tests/test_msg_ping.py
+tests/test_msg_recoverydevice.py
+tests/test_msg_recoverydevice_cipher.py
+tests/test_msg_resetdevice.py
+tests/test_msg_signidentity.py
+tests/test_msg_signmessage.py
+tests/test_msg_signtx.py
+tests/test_msg_signtx_xfer.py
+tests/test_msg_simplesigntx.py
+tests/test_msg_verifymessage.py
+tests/test_msg_wipedevice.py
+tests/test_multisig.py
+tests/test_multisig_change.py
+tests/test_op_return.py
+tests/test_protect_call.py
+tests/test_protection_levels.py
+tests/test_zerosig.py
\ No newline at end of file
diff --git a/keepkey.egg-info/requires.txt b/keepkey.egg-info/requires.txt
index c587b67..14e6929 100644
--- a/keepkey.egg-info/requires.txt
+++ b/keepkey.egg-info/requires.txt
@@ -1,4 +1,4 @@
 ecdsa>=0.9
-protobuf==2.6.1
+protobuf>=2.6.1
 mnemonic>=0.8
-hidapi>=0.7.99
\ No newline at end of file
+hidapi==0.7.99.post15
\ No newline at end of file
diff --git a/keepkeyctl b/keepkeyctl
index 8c23be2..cfbbbf2 100755
--- a/keepkeyctl
+++ b/keepkeyctl
@@ -1,4 +1,5 @@
 #!/usr/bin/env python
+from __future__ import print_function
 import os
 import binascii
 import argparse
@@ -20,22 +21,22 @@ def parse_args(commands):
 #    parser.add_argument('-d', '--debug', dest='debug', action='store_true', help='Enable low-level debugging')
 
     cmdparser = parser.add_subparsers(title='Available commands')
-    
+
     for cmd in commands._list_commands():
         func = object.__getattribute__(commands, cmd)
-            
+
         try:
             arguments = func.arguments
         except AttributeError:
             arguments = ((('params',), {'nargs': '*'}),)
-        
+
         item = cmdparser.add_parser(cmd, help=func.help)
         for arg in arguments:
             item.add_argument(*arg[0], **arg[1])
-            
+
         item.set_defaults(func=func)
         item.set_defaults(cmd=cmd)
-    
+
     return parser.parse_args()
 
 def get_transport(transport_string, path, **kwargs):
@@ -70,25 +71,25 @@ def get_transport(transport_string, path, **kwargs):
     if transport_string == 'fake':
         from keepkeylib.transport_fake import FakeTransport
         return FakeTransport(path, **kwargs)
-    
-    raise NotImplemented("Unknown transport")
+
+    raise NotImplementedError("Unknown transport")
 
 class Commands(object):
     def __init__(self, client):
         self.client = client
-        
+
     @classmethod
     def _list_commands(cls):
-        return [ x for x in dir(cls) if not x.startswith('_') ]
-  
+        return [x for x in dir(cls) if not x.startswith('_')]
+
     def list(self, args):
         # Fake method for advertising 'list' command
         pass
- 
+
     def get_address(self, args):
         address_n = self.client.expand_path(args.n)
         return self.client.get_address(args.coin, address_n, args.show_display)
-    
+
     def get_entropy(self, args):
         return binascii.hexlify(self.client.get_entropy(args.size))
 
@@ -96,14 +97,14 @@ class Commands(object):
         return self.client.features
 
     def list_coins(self, args):
-        return [ coin.coin_name for coin in self.client.features.coins ]
+        return [coin.coin_name for coin in self.client.features.coins]
 
     def ping(self, args):
         return self.client.ping(args.msg, button_protection=args.button_protection, pin_protection=args.pin_protection, passphrase_protection=args.passphrase_protection)
 
     def get_public_node(self, args):
         address_n = self.client.expand_path(args.n)
-        return self.client.get_public_node(address_n, args.ecdsa_curve_name, args.show_display)
+        return self.client.get_public_node(address_n, ecdsa_curve_name=args.curve, show_display=args.show_display)
 
     def set_label(self, args):
         return self.client.apply_settings(label=args.label)
@@ -128,11 +129,13 @@ class Commands(object):
         if args.mnemonic:
             mnemonic = ' '.join(args.mnemonic)
             return self.client.load_device_by_mnemonic(mnemonic, args.pin,
-                        args.passphrase_protection, args.label, 'english', args.skip_checksum)
-
+                                                       args.passphrase_protection,
+                                                       args.label, 'english',
+                                                       args.skip_checksum)
         else:
             return self.client.load_device_by_xprv(args.xprv, args.pin,
-                        args.passphrase_protection, args.label, 'english')
+                                                   args.passphrase_protection,
+                                                   args.label, 'english')
 
     def reset_device(self, args):
         return self.client.reset_device(True, args.strength, args.passphrase_protection,
@@ -188,13 +191,13 @@ class Commands(object):
         if args.file:
             fp = open(args.file, 'r')
         elif args.url:
-            print "Downloading from", args.url
+            print("Downloading from", args.url)
             resp = urllib.urlretrieve(args.url)
             fp = open(resp[0], 'r')
             urllib.urlcleanup() # We still keep file pointer open
 
         if fp.read(8) == '54525a52':
-            print "Converting firmware to binary"
+            print("Converting firmware to binary")
 
             fp.seek(0)
             fp_old = fp
@@ -208,7 +211,7 @@ class Commands(object):
         if fp.read(4) != 'KPKY':
             raise Exception("KeepKey firmware header expected")
 
-        print "Please confirm action on device..."
+        print("Please confirm action on device...")
 
         fp.seek(0)
         return self.client.firmware_update(fp=fp)
@@ -240,7 +243,7 @@ class Commands(object):
         (('-n', '-address'), {'type': str}),
         (('-d', '--show-display'), {'action': 'store_true', 'default': False}),
     )
-    
+
     get_entropy.arguments = (
         (('size',), {'type': int}),
     )
@@ -255,16 +258,16 @@ class Commands(object):
         (('-p', '--pin-protection'), {'action': 'store_true', 'default': False}),
         (('-r', '--passphrase-protection'), {'action': 'store_true', 'default': False}),
     )
-    
+
     set_label.arguments = (
         (('-l', '--label',), {'type': str, 'default': ''}),
-#        (('-c', '--clear'), {'action': 'store_true', 'default': False})
+        # (('-c', '--clear'), {'action': 'store_true', 'default': False})
     )
 
     change_pin.arguments = (
-         (('-r', '--remove'), {'action': 'store_true', 'default': False}),
+        (('-r', '--remove'), {'action': 'store_true', 'default': False}),
     )
-    
+
     wipe_device.arguments = ()
 
     recovery_device.arguments = (
@@ -330,7 +333,7 @@ class Commands(object):
 
     get_public_node.arguments = (
         (('-n', '-address'), {'type': str}),
-        (('-e', '--ecdsa-curve-name'), {'type': str}),
+        (('-e', '--curve'), {'type': str}),
         (('-d', '--show-display'), {'action': 'store_true', 'default': False}),
     )
 
@@ -397,20 +400,20 @@ def qt_pin_func(input_text, message=None):
         # let's fallback to default pin_func implementation
         return pin_func(input_text, message)
 '''
-    
+
 def main():
     args = parse_args(Commands)
 
     if args.cmd == 'list':
         devices = list_usb()
         if args.json:
-            print json.dumps(devices)
+            print(json.dumps(devices))
         else:
             for dev in devices:
                 if dev[1] != None:
-                    print "%s - debuglink enabled" % dev[0]
+                    print("%s - debuglink enabled" % dev[0])
                 else:
-                    print dev[0]
+                    print(dev[0])
         return
 
     transport = get_transport(args.transport, args.path)
@@ -420,13 +423,13 @@ def main():
         client = KeepKeyClient(transport)
 
     cmds = Commands(client)
-    
+
     res = args.func(cmds, args)
-    
+
     if args.json:
-        print json.dumps(res, sort_keys=True, indent=4)
+        print(json.dumps(res, sort_keys=True, indent=4))
     else:
-        print res
-    
+        print(res)
+
 if __name__ == '__main__':
     main()
diff --git a/keepkeylib/ckd_public.py b/keepkeylib/ckd_public.py
index 64787b7..7f49d28 100644
--- a/keepkeylib/ckd_public.py
+++ b/keepkeylib/ckd_public.py
@@ -7,8 +7,8 @@ from ecdsa.util import string_to_number, number_to_string
 from ecdsa.curves import SECP256k1
 from ecdsa.ellipticcurve import Point, INFINITY
 
-import tools
-import types_pb2 as proto_types
+from . import tools
+from . import types_pb2 as proto_types
 
 PRIME_DERIVATION_FLAG = 0x80000000
 
@@ -17,7 +17,7 @@ def point_to_pubkey(point):
     x_str = number_to_string(point.x(), order)
     y_str = number_to_string(point.y(), order)
     vk = x_str + y_str
-    return chr((ord(vk[63]) & 1) + 2) + vk[0:32]  # To compressed key 
+    return chr((ord(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."""
@@ -99,7 +99,7 @@ def serialize(node, version=0x0488B21E):
     s += node.chain_code
     if node.private_key:
         s += '\x00' + node.private_key
-    else :
+    else:
         s += node.public_key
     s += tools.Hash(s)[:4]
     return tools.b58encode(s)
@@ -115,7 +115,7 @@ def deserialize(xpub):
     node.fingerprint = struct.unpack('>I', data[5:9])[0]
     node.child_num = struct.unpack('>I', data[9:13])[0]
     node.chain_code = data[13:45]
-    
+
     key = data[45:-4]
     if key[0] == '\x00':
         node.private_key = key[1:]
diff --git a/keepkeylib/client.py b/keepkeylib/client.py
index 98b8c6a..7c75a43 100644
--- a/keepkeylib/client.py
+++ b/keepkeylib/client.py
@@ -1,20 +1,21 @@
+from __future__ import print_function
+
 import os
 import sys
 import time
 import binascii
 import hashlib
 import unicodedata
-import mapping
 import json
 import getpass
 
-import tools
-import messages_pb2 as proto
-import types_pb2 as types
-import protobuf_json
-from keepkeylib.debuglink import DebugLink
 from mnemonic import Mnemonic
 
+from . import tools
+from . import mapping
+from . import messages_pb2 as proto
+from . import types_pb2 as types
+from .debuglink import DebugLink
 
 # try:
 #     from PIL import Image
@@ -113,7 +114,7 @@ class expect(object):
     # or raises an exception
     def __init__(self, *expected):
         self.expected = expected
-        
+
     def __call__(self, f):
         def wrapped_f(*args, **kwargs):
             ret = f(*args, **kwargs)
@@ -123,15 +124,18 @@ class expect(object):
         return wrapped_f
 
 def normalize_nfc(txt):
-    # Normalize string to UTF8 NFC for sign_message
-    if isinstance(txt, str):
-        utxt = txt.decode('utf8')
-    elif isinstance(txt, unicode):
-        utxt = txt
+    if sys.version_info[0] < 3:
+        if isinstance(txt, unicode):
+            return unicodedata.normalize('NFC', txt).encode('utf-8')
+        if isinstance(txt, str):
+            return unicodedata.normalize('NFC', txt.decode('utf-8')).encode('utf-8')
     else:
-        raise Exception("String value expected")
+        if isinstance(txt, bytes):
+            return unicodedata.normalize('NFC', txt.decode('utf-8')).encode('utf-8')
+        if isinstance(txt, str):
+            return unicodedata.normalize('NFC', txt).encode('utf-8')
 
-    return unicodedata.normalize('NFC', utxt)
+    raise Exception('unicode/str or bytes/str expected')
 
 class BaseClient(object):
     # Implements very basic layer of sending raw protobuf
@@ -229,7 +233,7 @@ class TextUIMixin(object):
         passphrase = getpass.getpass('')
         log("Confirm your Passphrase: ")
         if passphrase == getpass.getpass(''):
-            passphrase = unicode(str(bytearray(passphrase, 'utf-8')), 'utf-8')
+            passphrase = normalize_nfc(passphrase)
             return proto.PassphraseAck(passphrase=passphrase)
         else:
             log("Passphrase did not match! ")
@@ -237,7 +241,10 @@ class TextUIMixin(object):
 
     def callback_WordRequest(self, msg):
         log("Enter one word of mnemonic: ")
-        word = raw_input()
+        try:
+            word = raw_input()
+        except NameError:
+            word = input() # Python 3
         return proto.WordAck(word=word)
 
     def callback_CharacterRequest(self, msg):
@@ -272,7 +279,7 @@ class TextUIMixin(object):
                 # capture spaces
                 return proto.CharacterAck(character=' ')
 
-            elif character_ascii == 127 \
+            elif character_ascii == 8 or character_ascii == 127 \
             and (msg.word_pos > 0 or msg.character_pos > 0):
                 # capture backspaces
                 return proto.CharacterAck(delete=True)
@@ -302,7 +309,7 @@ class DebugLinkMixin(object):
 
         # Always press Yes and provide correct pin
         self.setup_debuglink(True, True)
-        
+
         # Do not expect any specific response from device
         self.expected_responses = None
 
@@ -352,7 +359,7 @@ class DebugLinkMixin(object):
         self.pin_correct = pin_correct
 
     def set_passphrase(self, passphrase):
-        self.passphrase = unicode(str(bytearray(Mnemonic.normalize_string(passphrase), 'utf-8')), 'utf-8')
+        self.passphrase = normalize_nfc(passphrase)
 
     def set_mnemonic(self, mnemonic):
         self.mnemonic = unicode(str(bytearray(Mnemonic.normalize_string(mnemonic), 'utf-8')), 'utf-8').split(' ')
@@ -374,7 +381,7 @@ class DebugLinkMixin(object):
         resp = super(DebugLinkMixin, self).call_raw(msg)
         self._check_request(resp)
         return resp
-        
+
     def _check_request(self, msg):
         if self.expected_responses != None:
             try:
@@ -392,7 +399,7 @@ class DebugLinkMixin(object):
                 if not msg.HasField(field.name) or getattr(msg, field.name) != value:
                     raise CallException(types.Failure_Other,
                             "Expected %s, got %s" % (pprint(expected), pprint(msg)))
-            
+
     def callback_ButtonRequest(self, msg):
         log("ButtonRequest code: " + get_buttonrequest_value(msg.code))
 
@@ -447,7 +454,8 @@ class ProtocolMixin(object):
         # Convert minus signs to uint32 with flag
         return [ int(abs(x) | self.PRIME_DERIVATION_FLAG) if x < 0 else x for x in n ]
 
-    def expand_path(self, n):
+    @staticmethod
+    def expand_path(n):
         # Convert string of bip32 path to list of uint32 integers with prime flags
         # 0/-1/1' -> [0, 0x80000001, 0x80000001]
         if not n:
@@ -466,7 +474,7 @@ class ProtocolMixin(object):
             x = abs(int(x))
 
             if prime:
-                x |= self.PRIME_DERIVATION_FLAG
+                x |= ProtocolMixin.PRIME_DERIVATION_FLAG
 
             path.append(x)
 
@@ -507,7 +515,7 @@ class ProtocolMixin(object):
 
     @field('message')
     @expect(proto.Success)
-    def apply_settings(self, label=None, language=None, use_passphrase=None):
+    def apply_settings(self, label=None, language=None, use_passphrase=None, homescreen=None):
         settings = proto.ApplySettings()
         if label != None:
             settings.label = label
@@ -535,15 +543,8 @@ class ProtocolMixin(object):
     @expect(proto.MessageSignature)
     def sign_message(self, coin_name, n, message):
         n = self._convert_prime(n)
-
-        try:
-            # Convert message to UTF8 NFC (seems to be a bitcoin-qt standard)
-            message = normalize_nfc(message)
-            # Convert message to ASCII stream
-            message = str(bytearray(message, 'utf-8'))
-        except:
-            pass # it was not UTF8 string
-
+        # Convert message to UTF8 NFC (seems to be a bitcoin-qt standard)
+        message = normalize_nfc(message)
         return self.call(proto.SignMessage(coin_name=coin_name, address_n=n, message=message))
 
     @expect(proto.SignedIdentity)
@@ -551,14 +552,8 @@ class ProtocolMixin(object):
         return self.call(proto.SignIdentity(identity=identity, challenge_hidden=challenge_hidden, challenge_visual=challenge_visual, ecdsa_curve_name=ecdsa_curve_name))
 
     def verify_message(self, address, signature, message):
-        try:
-            # Convert message to UTF8 NFC (seems to be a bitcoin-qt standard)
-            message = normalize_nfc(message)
-        # Convert message to ASCII stream
-            message = str(bytearray(message, 'utf-8'))
-        except:
-            pass # it was not UTF8 string
-
+        # Convert message to UTF8 NFC (seems to be a bitcoin-qt standard)
+        message = normalize_nfc(message)
         try:
             if address:
                 resp = self.call(proto.VerifyMessage(address=address, signature=signature, message=message))
@@ -816,7 +811,7 @@ class ProtocolMixin(object):
         mnemonic = Mnemonic.normalize_string(mnemonic)
 
         # Convert mnemonic to ASCII stream
-        mnemonic = unicode(str(bytearray(mnemonic, 'utf-8')), 'utf-8')
+        mnemonic = normalize_nfc(mnemonic)
 
         if self.features.initialized:
             raise Exception("Device is initialized already. Call wipe_device() and try again.")
@@ -842,7 +837,7 @@ class ProtocolMixin(object):
             raise Exception("Invalid length of xprv")
 
         node = types.HDNodeType()
-        data = tools.b58decode(xprv, None).encode('hex')
+        data = binascii.hexlify(tools.b58decode(xprv, None))
 
         if data[90:92] != '00':
             raise Exception("Contain invalid private key")
diff --git a/keepkeylib/debuglink.py b/keepkeylib/debuglink.py
index 07dee84..917b9bf 100644
--- a/keepkeylib/debuglink.py
+++ b/keepkeylib/debuglink.py
@@ -1,11 +1,13 @@
-import messages_pb2 as proto
-from transport import NotImplementedException
+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
+    print("Device asks for PIN %s" % pin)
 
 def button_press(yes_no):
-    print "User pressed", '"y"' if yes_no else '"n"'
+    print("User pressed", '"y"' if yes_no else '"n"')
 
 def pprint(msg):
     return "<%s> (%d bytes):\n%s" % (msg.__class__.__name__, msg.ByteSize(), msg)
@@ -19,20 +21,20 @@ class DebugLink(object):
 
     def close(self):
         self.transport.close()
-        
+
     def _call(self, msg, nowait=False):
-        print "DEBUGLINK SEND", pprint(msg)
+        print("DEBUGLINK SEND", pprint(msg))
         self.transport.write(msg)
         if nowait:
             return
         ret = self.transport.read_blocking()
-        print "DEBUGLINK RECV", pprint(ret)
+        print("DEBUGLINK RECV", pprint(ret))
         return ret
 
     def read_pin(self):
         obj = self._call(proto.DebugLinkGetState())
-        print "Read PIN:", obj.pin
-        print "Read matrix:", obj.matrix
+        print("Read PIN:", obj.pin)
+        print("Read matrix:", obj.matrix)
 
         return (obj.pin, obj.matrix)
 
@@ -49,11 +51,11 @@ class DebugLink(object):
         # We have to encode that into encoded pin,
         # because application must send back positions
         # on keypad, not a real PIN.
-        pin_encoded = ''.join([ str(matrix.index(p) + 1) for p in pin])
+        pin_encoded = ''.join([str(matrix.index(p) + 1) for p in pin])
 
-        print "Encoded PIN:", pin_encoded
+        print("Encoded PIN:", pin_encoded)
         return pin_encoded
-        
+
     def read_layout(self):
         obj = self._call(proto.DebugLinkGetState())
         return obj.layout
@@ -98,7 +100,7 @@ class DebugLink(object):
          self._call(proto.DebugLinkFillConfig(), nowait=True)
 
     def press_button(self, yes_no):
-        print "Pressing", yes_no
+        print("Pressing", yes_no)
         self.button_func(yes_no)
         self._call(proto.DebugLinkDecision(yes_no=yes_no), nowait=True)
 
diff --git a/keepkeylib/mapping.py b/keepkeylib/mapping.py
index f631ed0..3496d8a 100644
--- a/keepkeylib/mapping.py
+++ b/keepkeylib/mapping.py
@@ -1,4 +1,4 @@
-import messages_pb2 as proto
+from . import messages_pb2 as proto
 
 map_type_to_class = {}
 map_class_to_type = {}
@@ -10,7 +10,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__]
 
diff --git a/keepkeylib/qt/pinmatrix.py b/keepkeylib/qt/pinmatrix.py
index 1d2a5f8..306f5b1 100644
--- a/keepkeylib/qt/pinmatrix.py
+++ b/keepkeylib/qt/pinmatrix.py
@@ -1,8 +1,9 @@
+from __future__ import print_function
 import sys
 import math
 import operator
-from PyQt4.Qt import QApplication, QWidget, QGridLayout, QVBoxLayout, QHBoxLayout
-from PyQt4.QtGui import QPushButton, QLineEdit, QSizePolicy, QRegExpValidator, QLabel
+from PyQt4.QtGui import (QPushButton, QLineEdit, QSizePolicy, QRegExpValidator, QLabel,
+                         QApplication, QWidget, QGridLayout, QVBoxLayout, QHBoxLayout)
 from PyQt4.QtCore import QObject, SIGNAL, QRegExp, Qt
 
 class PinButton(QPushButton):
@@ -27,7 +28,7 @@ class PinMatrixWidget(QWidget):
     '''
     def __init__(self, show_strength=True, parent=None):
         super(PinMatrixWidget, self).__init__(parent)
-        
+
         self.password = QLineEdit()
         self.password.setValidator(QRegExpValidator(QRegExp('[1-9]+'), None))
         self.password.setEchoMode(QLineEdit.Password)
@@ -91,8 +92,8 @@ if __name__ == '__main__':
     matrix = PinMatrixWidget()
 
     def clicked():
-        print "PinMatrix value is", matrix.get_value()
-        print "Possible button combinations:", matrix.get_strength()
+        print("PinMatrix value is", matrix.get_value())
+        print("Possible button combinations:", matrix.get_strength())
         sys.exit()
 
     ok = QPushButton('OK')
diff --git a/keepkeylib/tools.py b/keepkeylib/tools.py
index e01a887..fe40541 100644
--- a/keepkeylib/tools.py
+++ b/keepkeylib/tools.py
@@ -1,5 +1,6 @@
 import hashlib
 import binascii
+import sys
 
 Hash = lambda x: hashlib.sha256(hashlib.sha256(x).digest()).digest()
 
@@ -33,7 +34,7 @@ __b58base = len(__b58chars)
 def b58encode(v):
     """ encode v, which is a string of bytes, to base58."""
 
-    long_value = 0L
+    long_value = 0
     for (i, c) in enumerate(v[::-1]):
         long_value += (256 ** i) * ord(c)
 
@@ -57,7 +58,7 @@ def b58encode(v):
 
 def b58decode(v, length):
     """ decode v into a string of len bytes."""
-    long_value = 0L
+    long_value = 0
     for (i, c) in enumerate(v[::-1]):
         long_value += __b58chars.find(c) * (__b58base ** i)
 
@@ -79,7 +80,10 @@ def b58decode(v, length):
     if length is not None and len(result) != length:
         return None
 
-    return result
+    if sys.version_info[0] < 3:
+        return result
+    else:
+        return str.encode(result)
 
 def monkeypatch_google_protobuf_text_format():
     # monkeypatching: text formatting of protobuf messages
diff --git a/keepkeylib/transport.py b/keepkeylib/transport.py
index 71160f0..9ff25df 100644
--- a/keepkeylib/transport.py
+++ b/keepkeylib/transport.py
@@ -1,5 +1,5 @@
 import struct
-import mapping
+from . import mapping
 
 class NotImplementedException(Exception):
     pass
@@ -12,31 +12,31 @@ class Transport(object):
         self.device = device
         self.session_depth = 0
         self._open()
-    
+
     def _open(self):
         raise NotImplementedException("Not implemented")
-    
+
     def _close(self):
         raise NotImplementedException("Not implemented")
-    
+
     def _write(self, msg, protobuf_msg):
         raise NotImplementedException("Not implemented")
-    
+
     def _read(self):
         raise NotImplementedException("Not implemented")
-    
+
     def _session_begin(self):
         pass
-    
+
     def _session_end(self):
         pass
-    
+
     def ready_to_read(self):
         """
         Returns True if there is data to be read from the transport.  Otherwise, False.
         """
         raise NotImplementedException("Not implemented")
-    
+
     def session_begin(self):
         """
         Apply a lock to the device in order to preform synchronous multistep "conversations" with the device.  For example, before entering the transaction signing workflow, one begins a session.  After the transaction is complete, the session may be ended.
@@ -44,7 +44,7 @@ class Transport(object):
         if self.session_depth == 0:
             self._session_begin()
         self.session_depth += 1
-    
+
     def session_end(self):
         """
         End a session.  Se session_begin for an in depth description of TREZOR sessions.
@@ -53,20 +53,20 @@ class Transport(object):
         self.session_depth = max(0, self.session_depth)
         if self.session_depth == 0:
             self._session_end()
-        
+
     def close(self):
         """
         Close the connection to the physical device or file descriptor represented by the Transport.
         """
         self._close()
-        
+
     def write(self, msg):
         """
         Write mesage to tansport.  msg should be a member of a valid `protobuf class <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_ with a SerializeToString() method.
         """
         ser = msg.SerializeToString()
         header = struct.pack(">HL", mapping.get_type(msg), len(ser))
-        self._write("##%s%s" % (header, ser), msg)
+        self._write(b"##" + header + ser, msg)
 
     def read(self):
         """
@@ -77,11 +77,11 @@ class Transport(object):
             return None
 
         data = self._read()
-        if data == None:
+        if data is None:
             return None
-        
+
         return self._parse_message(data)
-        
+
     def read_blocking(self):
         """
         Same as read, except blocks untill data is available to be read.
@@ -90,7 +90,7 @@ class Transport(object):
             data = self._read()
             if data != None:
                 break
-        
+
         return self._parse_message(data)
 
     def _parse_message(self, data):
@@ -101,7 +101,7 @@ class Transport(object):
             inst = mapping.get_class(msg_type)()
             inst.ParseFromString(data)
             return inst
-    
+
     def _read_headers(self, read_f):
         # Try to read headers until some sane value are detected
         is_ok = False
@@ -110,15 +110,14 @@ class Transport(object):
             # Align cursor to the beginning of the header ("##")
             c = read_f.read(1)
             i = 0
-            while c != '#':
+            while c != b"#":
                 i += 1
                 if i >= 64:
                     # timeout
                     raise Exception("Timed out while waiting for the magic character")
-                #print "Aligning to magic characters"
                 c = read_f.read(1)
 
-            if read_f.read(1) != "#":
+            if read_f.read(1) != b"#":
                 # Second character must be # to be valid header
                 raise Exception("Second magic character is broken")
 
@@ -129,5 +128,5 @@ class Transport(object):
                 break
             except:
                 raise Exception("Cannot parse header length")
-       
+
         return (msg_type, datalen)
diff --git a/keepkeylib/transport_fake.py b/keepkeylib/transport_fake.py
index 6ceb3f2..d50bec7 100644
--- a/keepkeylib/transport_fake.py
+++ b/keepkeylib/transport_fake.py
@@ -2,23 +2,23 @@
 
 # Local serial port loopback: socat PTY,link=COM8 PTY,link=COM9
 
-from transport import Transport, NotImplementedException
+from .transport import Transport, NotImplementedException
 
 class FakeTransport(Transport):
     def __init__(self, device, *args, **kwargs):
         super(FakeTransport, self).__init__(device, *args, **kwargs)
-        
+
     def _open(self):
         pass
-    
+
     def _close(self):
         pass
-    
+
     def ready_to_read(self):
         return False
-    
... 5617 lines suppressed ...

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/python-keepkey.git



More information about the Python-modules-commits mailing list