[Python-modules-commits] [btchip-python] 02/10: Import btchip-python_0.1.16.orig.tar.gz

Tristan Seligmann mithrandi at moszumanska.debian.org
Sun May 29 14:49:55 UTC 2016


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

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

commit 71015899222176bfbe80a10cec8a206658d38d19
Author: Tristan Seligmann <mithrandi at mithrandi.net>
Date:   Sun May 29 16:38:42 2016 +0200

    Import btchip-python_0.1.16.orig.tar.gz
---
 .gitignore                                      |   2 +
 .gitmodules                                     |   0
 LICENSE                                         | 202 ++++++++
 README.md                                       |  33 ++
 btchip/__init__.py                              |  19 +
 btchip/bitcoinTransaction.py                    | 145 ++++++
 btchip/bitcoinVarint.py                         |  63 +++
 btchip/btchip.py                                | 588 ++++++++++++++++++++++++
 btchip/btchipComm.py                            | 207 +++++++++
 btchip/btchipException.py                       |  28 ++
 btchip/btchipFirmwareWizard.py                  |  24 +
 btchip/btchipHelpers.py                         |  85 ++++
 btchip/btchipKeyRecovery.py                     |  57 +++
 btchip/btchipPersoWizard.py                     | 376 +++++++++++++++
 btchip/btchipUtils.py                           |  95 ++++
 btchip/ledgerWrapper.py                         |  92 ++++
 btchip/msqr.py                                  |  94 ++++
 btchip/ui/__init__.py                           |  19 +
 btchip/ui/personalization00start.py             |  55 +++
 btchip/ui/personalization01seed.py              |  77 ++++
 btchip/ui/personalization02security.py          |  96 ++++
 btchip/ui/personalization03config.py            |  68 +++
 btchip/ui/personalization04finalize.py          |  63 +++
 btchip/ui/personalizationseedbackup01.py        |  71 +++
 btchip/ui/personalizationseedbackup02.py        |  46 ++
 btchip/ui/personalizationseedbackup03.py        |  76 +++
 btchip/ui/personalizationseedbackup04.py        |  50 ++
 samples/getFirmwareVersion.py                   |  26 ++
 samples/runScript.py                            |  53 +++
 setup.py                                        |  29 ++
 tests/coinkite-cosigning/testGetPublicKeyDev.js | 115 +++++
 tests/coinkite-cosigning/testSignDev.js         | 168 +++++++
 tests/testConnectivity.py                       |  34 ++
 tests/testMessageSignature.py                   |  56 +++
 tests/testMultisigArmory.py                     | 194 ++++++++
 tests/testMultisigArmoryNo2FA.py                | 169 +++++++
 tests/testSimpleTransaction.py                  |  78 ++++
 ui/make.sh                                      |  12 +
 ui/personalization-00-start.ui                  |  98 ++++
 ui/personalization-01-seed.ui                   | 160 +++++++
 ui/personalization-02-security.ui               | 226 +++++++++
 ui/personalization-03-config.ui                 | 136 ++++++
 ui/personalization-04-finalize.ui               | 122 +++++
 ui/personalization-seedbackup-01.ui             | 138 ++++++
 ui/personalization-seedbackup-02.ui             |  69 +++
 ui/personalization-seedbackup-03.ui             | 165 +++++++
 ui/personalization-seedbackup-04.ui             |  82 ++++
 47 files changed, 4861 insertions(+)

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..2f78cf5
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+*.pyc
+
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000..e69de29
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..3067775
--- /dev/null
+++ b/README.md
@@ -0,0 +1,33 @@
+btchip-python
+=============
+
+Python samples for BTChip - work in progress
+
+Requirements
+-------------
+
+This API requires cython-hidapi version 0.7.99 (at least).
+
+To install cython-hidapi, refer to the instructions on https://github.com/trezor/cython-hidapi until a packaged version is available. Interim Debian packages have been built by Richard Ulrich at https://launchpad.net/~richi-paraeasy/+archive/ubuntu/bitcoin/ (btchip-python, hidapi and python-hidapi)
+
+For optional BIP 39 support during dongle setup, also install https://github.com/trezor/python-mnemonic - also available as a Debian package at the previous link (python-mnemonic)
+
+Building on Windows
+--------------------
+
+  - Download and install Python from https://www.python.org/ftp/python/2.7.8/python-2.7.8.msi
+  - Download and install Python QT from http://downloads.sourceforge.net/project/pyqt/PyQt4/PyQt-4.11.1/PyQt4-4.11.1-gpl-Py2.7-Qt4.8.6-x32.exe
+  - Download and install PyWin32 from http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/pywin32-218.win32-py2.7.exe/download
+  - Download MinGW setup from http://sourceforge.net/projects/mingw/files/Installer/mingw-get-setup.exe/download
+  - Install mingw32-gcc-g++ and mingw32-libz (dev and dll)
+  - Create a /Lib/disutils/distutils.cfg file in your Python installation directory (typically /Python27) containing the following content
+
+```
+[build]
+compliler=mingw32
+```
+
+  - Install distribute from https://gist.githubusercontent.com/anonymous/947191a4635cd7b7f79a/raw/36054b7f8d7b0c4c172628fd9bd16f46e53bb34b/distribute_setup.py
+  - Install the dependencies by running /Python27/Scripts/easy_install.exe cython hidapi 
+
+
diff --git a/btchip/__init__.py b/btchip/__init__.py
new file mode 100644
index 0000000..598eef9
--- /dev/null
+++ b/btchip/__init__.py
@@ -0,0 +1,19 @@
+"""
+*******************************************************************************
+*   BTChip Bitcoin Hardware Wallet Python API
+*   (c) 2014 BTChip - 1BTChip7VfTnrPra5jqci7ejnMguuHogTn
+*
+*  Licensed under the Apache License, Version 2.0 (the "License");
+*  you may not use this file except in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+*   Unless required by applicable law or agreed to in writing, software
+*   distributed under the License is distributed on an "AS IS" BASIS,
+*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+*  See the License for the specific language governing permissions and
+*   limitations under the License.
+********************************************************************************
+"""
+
diff --git a/btchip/bitcoinTransaction.py b/btchip/bitcoinTransaction.py
new file mode 100644
index 0000000..1da49bd
--- /dev/null
+++ b/btchip/bitcoinTransaction.py
@@ -0,0 +1,145 @@
+"""
+*******************************************************************************
+*   BTChip Bitcoin Hardware Wallet Python API
+*   (c) 2014 BTChip - 1BTChip7VfTnrPra5jqci7ejnMguuHogTn
+*
+*  Licensed under the Apache License, Version 2.0 (the "License");
+*  you may not use this file except in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+*   Unless required by applicable law or agreed to in writing, software
+*   distributed under the License is distributed on an "AS IS" BASIS,
+*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+*  See the License for the specific language governing permissions and
+*   limitations under the License.
+********************************************************************************
+"""
+
+from bitcoinVarint import *
+from binascii import hexlify
+
+class bitcoinInput:
+
+	def __init__(self, bufferOffset=None):
+		self.prevOut = ""
+		self.script = ""
+		self.sequence = ""
+		if bufferOffset is not None:
+			buf = bufferOffset['buffer']
+			offset = bufferOffset['offset']
+			self.prevOut = buf[offset:offset + 36]
+			offset += 36
+			scriptSize = readVarint(buf, offset)
+			offset += scriptSize['size']
+			self.script = buf[offset:offset + scriptSize['value']]
+			offset += scriptSize['value']
+			self.sequence = buf[offset:offset + 4]
+			offset += 4
+			bufferOffset['offset'] = offset
+
+	def serialize(self):
+		result = []
+		result.extend(self.prevOut)
+		writeVarint(len(self.script), result)
+		result.extend(self.script)
+		result.extend(self.sequence)
+		return result
+
+	def __str__(self):
+		buf =  "Prevout : " + hexlify(self.prevOut) + "\r\n"
+		buf += "Script : " + hexlify(self.script) + "\r\n"
+		buf += "Sequence : " + hexlify(self.sequence) + "\r\n"
+		return buf
+
+class bitcoinOutput:
+
+	def __init__(self, bufferOffset=None):
+		self.amount = ""
+		self.script = ""
+		if bufferOffset is not None:
+			buf = bufferOffset['buffer']
+			offset = bufferOffset['offset']
+			self.amount = buf[offset:offset + 8]
+			offset += 8
+			scriptSize = readVarint(buf, offset)
+			offset += scriptSize['size']
+			self.script = buf[offset:offset + scriptSize['value']]
+			offset += scriptSize['value']
+			bufferOffset['offset'] = offset
+
+	def serialize(self):
+		result = []
+		result.extend(self.amount)
+		writeVarint(len(self.script), result)
+		result.extend(self.script)
+		return result
+
+	def __str__(self):
+		buf =  "Amount : " + hexlify(self.amount) + "\r\n"
+		buf += "Script : " + hexlify(self.script) + "\r\n"
+		return buf
+
+
+class bitcoinTransaction:
+
+	def __init__(self, data=None):
+		self.version = ""
+		self.inputs = []
+		self.outputs = []
+		self.lockTime = ""
+		if data is not None:
+			offset = 0
+			self.version = data[offset:offset + 4]
+			offset += 4
+			inputSize = readVarint(data, offset)
+			offset += inputSize['size']
+			numInputs = inputSize['value']
+			for i in range(numInputs):
+				tmp = { 'buffer': data, 'offset' : offset}
+				self.inputs.append(bitcoinInput(tmp))
+				offset = tmp['offset']
+			outputSize = readVarint(data, offset)
+			offset += outputSize['size']
+			numOutputs = outputSize['value']
+			for i in range(numOutputs):
+				tmp = { 'buffer': data, 'offset' : offset}
+				self.outputs.append(bitcoinOutput(tmp))
+				offset = tmp['offset']
+			self.lockTime = data[offset:offset + 4]
+
+	def serialize(self, skipOutputLocktime=None):
+		result = []
+		result.extend(self.version)
+		writeVarint(len(self.inputs), result)
+		for trinput in self.inputs:
+			result.extend(trinput.serialize())
+		if not skipOutputLocktime:
+			writeVarint(len(self.outputs), result)
+			for troutput in self.outputs:
+				result.extend(troutput.serialize())
+			result.extend(self.lockTime)
+		return result
+
+	def serializeOutputs(self):
+		result = []
+		writeVarint(len(self.outputs), result)
+		for troutput in self.outputs:
+			result.extend(troutput.serialize())
+		return result
+
+	def __str__(self):
+		buf =  "Version : " + hexlify(self.version) + "\r\n"
+		index = 1
+		for trinput in self.inputs:
+			buf += "Input #" + str(index) + "\r\n"
+			buf += str(trinput)
+			index+=1
+		index = 1
+		for troutput in self.outputs:
+			buf += "Output #" + str(index) + "\r\n"
+			buf += str(troutput)
+			index+=1
+		buf += "Locktime : " + hexlify(self.lockTime) + "\r\n"
+		return buf
diff --git a/btchip/bitcoinVarint.py b/btchip/bitcoinVarint.py
new file mode 100644
index 0000000..9c61afd
--- /dev/null
+++ b/btchip/bitcoinVarint.py
@@ -0,0 +1,63 @@
+"""
+*******************************************************************************
+*   BTChip Bitcoin Hardware Wallet Python API
+*   (c) 2014 BTChip - 1BTChip7VfTnrPra5jqci7ejnMguuHogTn
+*
+*  Licensed under the Apache License, Version 2.0 (the "License");
+*  you may not use this file except in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+*   Unless required by applicable law or agreed to in writing, software
+*   distributed under the License is distributed on an "AS IS" BASIS,
+*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+*  See the License for the specific language governing permissions and
+*   limitations under the License.
+********************************************************************************
+"""
+
+from btchipException import BTChipException
+
+def readVarint(buffer, offset):
+	varintSize = 0
+	value = 0
+	if (buffer[offset] < 0xfd):
+		value = buffer[offset]
+		varintSize = 1
+	elif (buffer[offset] == 0xfd):
+		value = (buffer[offset + 2] << 8) | (buffer[offset + 1])
+		varintSize = 3
+	elif (buffer[offset] == 0xfe):
+		value = (buffer[offset + 4] << 24) | (buffer[offset + 3] << 16) | (buffer[offset + 2] << 8) | (buffer[offset + 1])
+		varintSize = 5
+	else:
+		raise BTChipException("unsupported varint")
+	return { "value": value, "size": varintSize }
+
+def writeVarint(value, buffer):
+	if (value < 0xfd):
+		buffer.append(value)
+	elif (value <= 0xffff):
+		buffer.append(0xfd)
+		buffer.append(value & 0xff)
+		buffer.append((value >> 8) & 0xff)
+	elif (value <= 0xffffffff):
+		buffer.append(0xfe)
+		buffer.append(value & 0xff)
+		buffer.append((value >> 8) & 0xff)
+		buffer.append((value >> 16) & 0xff)
+		buffer.append((value >> 24) & 0xff)
+	else:
+		raise BTChipException("unsupported encoding")
+	return buffer
+
+def getVarintSize(value):
+	if (value < 0xfd):
+		return 1
+	elif (value <= 0xffff):
+		return 3
+	elif (value <= 0xffffffff):
+		return 5
+	else:
+		raise BTChipException("unsupported encoding")
diff --git a/btchip/btchip.py b/btchip/btchip.py
new file mode 100644
index 0000000..5630bf6
--- /dev/null
+++ b/btchip/btchip.py
@@ -0,0 +1,588 @@
+"""
+*******************************************************************************
+*   BTChip Bitcoin Hardware Wallet Python API
+*   (c) 2014 BTChip - 1BTChip7VfTnrPra5jqci7ejnMguuHogTn
+*
+*  Licensed under the Apache License, Version 2.0 (the "License");
+*  you may not use this file except in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+*   Unless required by applicable law or agreed to in writing, software
+*   distributed under the License is distributed on an "AS IS" BASIS,
+*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+*  See the License for the specific language governing permissions and
+*   limitations under the License.
+********************************************************************************
+"""
+
+from btchipComm import *
+from bitcoinTransaction import *
+from bitcoinVarint import *
+from btchipException import *
+from btchipHelpers import *
+from btchipKeyRecovery import *
+from binascii import hexlify
+
+class btchip:
+	BTCHIP_CLA = 0xe0
+	BTCHIP_JC_EXT_CLA = 0xf0
+
+	BTCHIP_INS_SET_ALTERNATE_COIN_VERSION = 0x14
+	BTCHIP_INS_SETUP = 0x20
+	BTCHIP_INS_VERIFY_PIN = 0x22
+	BTCHIP_INS_GET_OPERATION_MODE = 0x24
+	BTCHIP_INS_SET_OPERATION_MODE = 0x26
+	BTCHIP_INS_SET_KEYMAP = 0x28
+	BTCHIP_INS_SET_COMM_PROTOCOL = 0x2a
+	BTCHIP_INS_GET_WALLET_PUBLIC_KEY = 0x40
+	BTCHIP_INS_GET_TRUSTED_INPUT = 0x42
+	BTCHIP_INS_HASH_INPUT_START = 0x44
+	BTCHIP_INS_HASH_INPUT_FINALIZE = 0x46
+	BTCHIP_INS_HASH_SIGN = 0x48
+	BTCHIP_INS_HASH_INPUT_FINALIZE_FULL = 0x4a
+	BTCHIP_INS_GET_INTERNAL_CHAIN_INDEX = 0x4c
+	BTCHIP_INS_SIGN_MESSAGE = 0x4e
+	BTCHIP_INS_GET_TRANSACTION_LIMIT = 0xa0
+	BTCHIP_INS_SET_TRANSACTION_LIMIT = 0xa2
+	BTCHIP_INS_IMPORT_PRIVATE_KEY = 0xb0
+	BTCHIP_INS_GET_PUBLIC_KEY = 0xb2
+	BTCHIP_INS_DERIVE_BIP32_KEY = 0xb4
+	BTCHIP_INS_SIGNVERIFY_IMMEDIATE = 0xb6
+	BTCHIP_INS_GET_RANDOM = 0xc0
+	BTCHIP_INS_GET_ATTESTATION = 0xc2
+	BTCHIP_INS_GET_FIRMWARE_VERSION = 0xc4
+	BTCHIP_INS_COMPOSE_MOFN_ADDRESS = 0xc6
+	BTCHIP_INS_GET_POS_SEED = 0xca
+
+	BTCHIP_INS_EXT_GET_HALF_PUBLIC_KEY = 0x20
+	BTCHIP_INS_EXT_CACHE_PUT_PUBLIC_KEY = 0x22
+	BTCHIP_INS_EXT_CACHE_HAS_PUBLIC_KEY = 0x24
+	BTCHIP_INS_EXT_CACHE_GET_FEATURES = 0x26
+
+	OPERATION_MODE_WALLET = 0x01
+	OPERATION_MODE_RELAXED_WALLET = 0x02
+	OPERATION_MODE_SERVER = 0x04
+	OPERATION_MODE_DEVELOPER = 0x08
+
+	FEATURE_UNCOMPRESSED_KEYS = 0x01
+	FEATURE_RFC6979 = 0x02
+	FEATURE_FREE_SIGHASHTYPE = 0x04
+	FEATURE_NO_2FA_P2SH = 0x08
+
+	QWERTY_KEYMAP = bytearray("000000000000000000000000760f00d4ffffffc7000000782c1e3420212224342627252e362d3738271e1f202122232425263333362e37381f0405060708090a0b0c0d0e0f101112131415161718191a1b1c1d2f3130232d350405060708090a0b0c0d0e0f101112131415161718191a1b1c1d2f313035".decode('hex'))
+	QWERTZ_KEYMAP = bytearray("000000000000000000000000760f00d4ffffffc7000000782c1e3420212224342627252e362d3738271e1f202122232425263333362e37381f0405060708090a0b0c0d0e0f101112131415161718191a1b1d1c2f3130232d350405060708090a0b0c0d0e0f101112131415161718191a1b1d1c2f313035".decode('hex'))
+	AZERTY_KEYMAP = bytearray("08000000010000200100007820c8ffc3feffff07000000002c38202030341e21222d352e102e3637271e1f202122232425263736362e37101f1405060708090a0b0c0d0e0f331112130415161718191d1b1c1a2f64302f2d351405060708090a0b0c0d0e0f331112130415161718191d1b1c1a2f643035".decode('hex'))
+
+	def __init__(self, dongle):
+		self.dongle = dongle
+		self.needKeyCache = False
+		try:
+			result = self.getJCExtendedFeatures()
+			self.needKeyCache = (result['proprietaryApi'] == False)
+		except:
+			pass
+
+	def setAlternateCoinVersion(self, versionRegular, versionP2SH):
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_SET_ALTERNATE_COIN_VERSION, 0x00, 0x00, 0x02, versionRegular, versionP2SH]
+		self.dongle.exchange(bytearray(apdu))
+
+	def verifyPin(self, pin):
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_VERIFY_PIN, 0x00, 0x00, len(pin) ]
+		apdu.extend(bytearray(pin))
+		self.dongle.exchange(bytearray(apdu))
+
+	def getVerifyPinRemainingAttempts(self):
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_VERIFY_PIN, 0x80, 0x00, 0x01 ]
+		apdu.extend(bytearray("0"))
+		try:
+			self.dongle.exchange(bytearray(apdu))
+		except BTChipException, e:
+			if ((e.sw & 0xfff0) == 0x63c0):
+				return e.sw - 0x63c0
+			raise e
+
+	def getWalletPublicKey(self, path):
+		result = {}
+		donglePath = parse_bip32_path(path)
+		if self.needKeyCache:
+			self.resolvePublicKeysInPath(path)			
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_GET_WALLET_PUBLIC_KEY, 0x00, 0x00, len(donglePath) ]
+		apdu.extend(donglePath)
+		response = self.dongle.exchange(bytearray(apdu))
+		offset = 0
+		result['publicKey'] = response[offset + 1 : offset + 1 + response[offset]]
+		offset = offset + 1 + response[offset]
+		result['address'] = str(response[offset + 1 : offset + 1 + response[offset]])
+		offset = offset + 1 + response[offset]
+		result['chainCode'] = response[offset : offset + 32]
+		return result
+
+	def getTrustedInput(self, transaction, index):
+		result = {}
+		# Header
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_GET_TRUSTED_INPUT, 0x00, 0x00 ]
+		params = bytearray(("%.8x" % (index)).decode('hex'))
+		params.extend(transaction.version)
+		writeVarint(len(transaction.inputs), params)
+		apdu.append(len(params))
+		apdu.extend(params)
+		self.dongle.exchange(bytearray(apdu))
+		# Each input
+		for trinput in transaction.inputs:
+			apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_GET_TRUSTED_INPUT, 0x80, 0x00 ]
+			params = bytearray(trinput.prevOut)
+			writeVarint(len(trinput.script), params)
+			apdu.append(len(params))
+			apdu.extend(params)
+			self.dongle.exchange(bytearray(apdu))
+			offset = 0
+			while (offset < len(trinput.script)):
+				blockLength = 251
+				if ((offset + blockLength) < len(trinput.script)):
+					dataLength = blockLength
+				else:
+					dataLength = len(trinput.script) - offset
+				params = trinput.script[offset : offset + dataLength]
+				if ((offset + dataLength) == len(trinput.script)):
+					params.extend(trinput.sequence)
+				apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_GET_TRUSTED_INPUT, 0x80, 0x00, len(params) ]
+				apdu.extend(params)
+				self.dongle.exchange(bytearray(apdu))
+				offset += dataLength
+		# Number of outputs
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_GET_TRUSTED_INPUT, 0x80, 0x00 ]
+		params = []
+		writeVarint(len(transaction.outputs), params)
+		apdu.append(len(params))
+		apdu.extend(params)
+		self.dongle.exchange(bytearray(apdu))
+		# Each output
+		for troutput in transaction.outputs:
+			apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_GET_TRUSTED_INPUT, 0x80, 0x00 ]
+			params = bytearray(troutput.amount)
+			writeVarint(len(troutput.script), params)
+			apdu.append(len(params))
+			apdu.extend(params)
+			self.dongle.exchange(bytearray(apdu))
+			offset = 0
+			while (offset < len(troutput.script)):
+				blockLength = 255
+				if ((offset + blockLength) < len(troutput.script)):
+					dataLength = blockLength
+				else:
+					dataLength = len(troutput.script) - offset
+				apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_GET_TRUSTED_INPUT, 0x80, 0x00, dataLength ]
+				apdu.extend(troutput.script[offset : offset + dataLength])
+				self.dongle.exchange(bytearray(apdu))
+				offset += dataLength
+		# Locktime
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_GET_TRUSTED_INPUT, 0x80, 0x00, len(transaction.lockTime) ]
+		apdu.extend(transaction.lockTime)
+		response = self.dongle.exchange(bytearray(apdu))
+		result['trustedInput'] = True
+		result['value'] = response
+		return result
+
+	def startUntrustedTransaction(self, newTransaction, inputIndex, outputList, redeemScript):
+		# Start building a fake transaction with the passed inputs
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_HASH_INPUT_START, 0x00, (0x00 if newTransaction else 0x80) ]
+		params = bytearray([0x01, 0x00, 0x00, 0x00]) # default version
+		writeVarint(len(outputList), params)
+		apdu.append(len(params))
+		apdu.extend(params)
+		self.dongle.exchange(bytearray(apdu))
+		# Loop for each input
+		currentIndex = 0
+		for passedOutput in outputList:
+			apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_HASH_INPUT_START, 0x80, 0x00 ]
+			params = []
+			script = redeemScript
+			if passedOutput['trustedInput']:
+				params.append(0x01)
+			else:
+				params.append(0x00)
+			if passedOutput['trustedInput']:
+				params.append(len(passedOutput['value']))
+			params.extend(passedOutput['value'])
+			if currentIndex <> inputIndex:
+				script = bytearray()
+			writeVarint(len(script), params)
+			if len(script) == 0:
+				params.extend(bytearray([0xFF, 0xFF, 0xFF, 0xFF])) # default sequence
+			apdu.append(len(params))
+			apdu.extend(params)
+			self.dongle.exchange(bytearray(apdu))
+			offset = 0
+			while(offset < len(script)):
+				blockLength = 255
+				if ((offset + blockLength) < len(script)):
+					dataLength = blockLength
+				else:
+					dataLength = len(script) - offset
+				params = script[offset : offset + dataLength]
+				if ((offset + dataLength) == len(script)):
+					params.extend(bytearray([0xFF, 0xFF, 0xFF, 0xFF])) # default sequence
+				apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_HASH_INPUT_START, 0x80, 0x00, len(params) ]
+				apdu.extend(params)
+				self.dongle.exchange(bytearray(apdu))
+				offset += blockLength
+			currentIndex += 1
+
+	def finalizeInput(self, outputAddress, amount, fees, changePath, rawTx=None):
+		alternateEncoding = False
+		donglePath = parse_bip32_path(changePath)
+		if self.needKeyCache:
+			self.resolvePublicKeysInPath(changePath)		
+		result = {}
+		if rawTx is not None:
+			try:
+				fullTx = bitcoinTransaction(bytearray(rawTx))
+				outputs = fullTx.serializeOutputs()
+				if len(donglePath) <> 0:
+					apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_HASH_INPUT_FINALIZE_FULL, 0xFF, 0x00 ]
+					params = []
+					params.extend(donglePath)
+					apdu.append(len(params))
+					apdu.extend(params)
+					response = self.dongle.exchange(bytearray(apdu))
+				apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_HASH_INPUT_FINALIZE_FULL, 0x80, 0x00 ]
+				params = []
+				params.extend(outputs)
+				apdu.append(len(params))
+				apdu.extend(params)
+				response = self.dongle.exchange(bytearray(apdu))
+				alternateEncoding = True
+			except:
+				pass
+		if not alternateEncoding:
+			apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_HASH_INPUT_FINALIZE, 0x02, 0x00 ]
+			params = []
+			params.append(len(outputAddress))
+			params.extend(bytearray(outputAddress))
+			writeHexAmountBE(btc_to_satoshi(str(amount)), params)
+			writeHexAmountBE(btc_to_satoshi(str(fees)), params)
+			params.extend(donglePath)
+			apdu.append(len(params))
+			apdu.extend(params)
+			response = self.dongle.exchange(bytearray(apdu))
+		result['confirmationNeeded'] = response[1 + response[0]] <> 0x00
+		result['confirmationType'] = response[1 + response[0]]
+		if result['confirmationType'] == 0x02:
+			result['keycardData'] = response[1 + response[0] + 1:]
+		if result['confirmationType'] == 0x03:
+			offset = 1 + response[0] + 1 
+			keycardDataLength = response[offset]
+			offset = offset + 1
+			result['keycardData'] = response[offset : offset + keycardDataLength]
+			offset = offset + keycardDataLength
+			result['secureScreenData'] = response[offset:]
+		result['outputData'] = response[1 : 1 + response[0]]
+		return result
+
+	def finalizeInputFull(self, outputData):
+		result = {}
+		offset = 0
+		encryptedOutputData = ""
+		while (offset < len(outputData)):
+			blockLength = 255
+			if ((offset + blockLength) < len(outputData)):
+				dataLength = blockLength
+				p1 = 0x00
+			else:
+				dataLength = len(outputData) - offset
+				p1 = 0x80
+			apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_HASH_INPUT_FINALIZE_FULL, \
+			p1, 0x00, dataLength ]
+			apdu.extend(outputData[offset : offset + dataLength])
+			response = self.dongle.exchange(bytearray(apdu))
+			encryptedOutputData = encryptedOutputData + response[1 : 1 + response[0]]
+			offset += dataLength
+                result['confirmationNeeded'] = response[1 + response[0]] <> 0x00
+                result['confirmationType'] = response[1 + response[0]]
+                if result['confirmationType'] == 0x02:
+			offset = 1 + response[0] + 1
+			keycardDataLength = response[offset]
+                        result['keycardData'] = response[offset : offset + keycardDataLength]
+                if result['confirmationType'] == 0x03:
+                        offset = 1 + response[0] + 1
+                        keycardDataLength = response[offset]
+                        offset = offset + 1
+                        result['keycardData'] = response[offset : offset + keycardDataLength]
+                        offset = offset + keycardDataLength
+                        result['secureScreenData'] = response[offset:]
+                result['encryptedOutputData'] = encryptedOutputData 
+		return result
+
+	def untrustedHashSign(self, path, pin="", lockTime=0, sighashType=0x01):
+		donglePath = parse_bip32_path(path)
+		if self.needKeyCache:
+			self.resolvePublicKeysInPath(path)		
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_HASH_SIGN, 0x00, 0x00 ]
+		params = []
+		params.extend(donglePath)
+		params.append(len(pin))
+		params.extend(bytearray(pin))
+		writeUint32BE(lockTime, params)
+		params.append(sighashType)
+		apdu.append(len(params))
+		apdu.extend(params)
+		result = self.dongle.exchange(bytearray(apdu))
+		result[0] = 0x30
+		return result
+
+	def signMessagePrepare(self, path, message):
+		donglePath = parse_bip32_path(path)
+		if self.needKeyCache:
+			self.resolvePublicKeysInPath(path)		
+		result = {}
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_SIGN_MESSAGE, 0x00, 0x00 ]
+		params = []
+		params.extend(donglePath)
+		params.append(len(message))
+		params.extend(bytearray(message))
+		apdu.append(len(params))
+		apdu.extend(params)
+		response = self.dongle.exchange(bytearray(apdu))
+		result['confirmationNeeded'] = response[0] <> 0x00
+		result['confirmationType'] = response[0]
+                if result['confirmationType'] == 0x02:
+                        result['keycardData'] = response[1:]
+                if result['confirmationType'] == 0x03:
+                        result['secureScreenData'] = response[1:]
+		return result
+
+	def signMessageSign(self, pin=""):
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_SIGN_MESSAGE, 0x80, 0x00 ]
+		params = []
+		if pin is not None:
+			params.append(len(pin))
+			params.extend(bytearray(pin))
+		else:
+			params.append(0x00)
+		apdu.append(len(params))
+		apdu.extend(params)
+		response = self.dongle.exchange(bytearray(apdu))
+		return response
+
+	def setup(self, operationModeFlags, featuresFlag, keyVersion, keyVersionP2SH, userPin, wipePin, keymapEncoding, seed=None, developerKey=None):
+		result = {}
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_SETUP, 0x00, 0x00 ]
+		params = [ operationModeFlags, featuresFlag, keyVersion, keyVersionP2SH ]
+		params.append(len(userPin))
+		params.extend(bytearray(userPin))
+		if wipePin is not None:
+			params.append(len(wipePin))
+			params.extend(bytearray(wipePin))
+		else:
+			params.append(0x00)
+		if seed is not None:
+			if len(seed) < 32 or len(seed) > 64:
+				raise BTChipException("Invalid seed length")
+			params.append(len(seed))
+			params.extend(seed)
+		else:
+			params.append(0x00)
+		if developerKey is not None:
+			params.append(len(developerKey))
+			params.extend(developerKey)
+		else:
+			params.append(0x00)
+		apdu.append(len(params))
+		apdu.extend(params)
+		response = self.dongle.exchange(bytearray(apdu))
+		result['trustedInputKey'] = response[0:16]
+		result['developerKey'] = response[16:]
+		self.setKeymapEncoding(keymapEncoding)
+		try:
+			self.setTypingBehaviour(0xff, 0xff, 0xff, 0x10)	
+                except BTChipException as e:
+                        if (e.sw == 0x6700): # Old firmware version, command not supported
+                                pass
+                        else:
+                                raise
+		return result
+
+	def setKeymapEncoding(self, keymapEncoding):
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_SET_KEYMAP, 0x00, 0x00 ]
+		apdu.append(len(keymapEncoding))
+		apdu.extend(keymapEncoding)
+		self.dongle.exchange(bytearray(apdu))
+
+	def setTypingBehaviour(self, unitDelayStart, delayStart, unitDelayKey, delayKey):
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_SET_KEYMAP, 0x01, 0x00 ]
+		params = []
+		writeUint32BE(unitDelayStart, params)
+		writeUint32BE(delayStart, params)
+		writeUint32BE(unitDelayKey, params)
+		writeUint32BE(delayKey, params)
+		apdu.append(len(params))
+		apdu.extend(params)
+		self.dongle.exchange(bytearray(apdu))
+
+	def getOperationMode(self):
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_GET_OPERATION_MODE, 0x00, 0x00, 0x00]
+		response = self.dongle.exchange(bytearray(apdu))
+		return response[0]
+
+	def setOperationMode(self, operationMode):
+		if operationMode <> btchip.OPERATION_MODE_WALLET \
+			and operationMode <> btchip.OPERATION_MODE_RELAXED_WALLET \
+			and operationMode <> btchip.OPERATION_MODE_SERVER \
+			and operationMode <> btchip.OPERATION_MODE_DEVELOPER:
+			raise BTChipException("Invalid operation mode")
+		apdu = [ self.BTCHIP_CLA, self.BTCHIP_INS_SET_OPERATION_MODE, 0x00, 0x00, 0x01, operationMode ]
+		self.dongle.exchange(bytearray(apdu))
... 4195 lines suppressed ...

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



More information about the Python-modules-commits mailing list