Debian Codegraph @

tests/coinkite-cosigning/testSignDev.js

raw
1 """
2 *******************************************************************************
3 * BTChip Bitcoin Hardware Wallet Python API
4 * (c) 2014 BTChip - 1BTChip7VfTnrPra5jqci7ejnMguuHogTn
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 ********************************************************************************
18 """
19
20 # Coinkite co-signer signing
21 # To be run with the dongle in developer mode, PIN verified
22 # Pass the JSON request to sign as parameter
23
24 # TODO : verify Coinkite signature in the request
25
26 import hashlib
27 import sys
28 import json
29 from btchip.btchip import *
30 from btchip.btchipUtils import *
31 from base64 import b64encode
32
33 # Replace with your own seed (preferably import it and store it), key path, and Testnet flag
34 SEED = bytearray("fe721b95503a18a14d93914e02ff153f924737c336b01f98f2ff39395f630187".decode('hex'))
35 KEYPATH = "0'/2/0"
36 TESTNET = True
37
38
39 # From Electrum
40
41 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
42 __b58base = len(__b58chars)
43
44 def b58encode(v):
45 """ encode v, which is a string of bytes, to base58."""
46
47 long_value = 0L
48 for (i, c) in enumerate(v[::-1]):
49 long_value += (256**i) * ord(c)
50
51 result = ''
52 while long_value >= __b58base:
53 div, mod = divmod(long_value, __b58base)
54 result = __b58chars[mod] + result
55 long_value = div
56 result = __b58chars[long_value] + result
57
58 # Bitcoin does a little leading-zero-compression:
59 # leading 0-bytes in the input become leading-1s
60 nPad = 0
61 for c in v:
62 if c == '\0': nPad += 1
63 else: break
64
65 return (__b58chars[0]*nPad) + result
66
67 def EncodeBase58Check(vchIn):
68 hash = Hash(vchIn)
69 return b58encode(vchIn + hash[0:4])
70
71 def sha256(x):
72 return hashlib.sha256(x).digest()
73
74 def hash_160(public_key):
75 try:
76 md = hashlib.new('ripemd160')
77 md.update(sha256(public_key))
78 return md.digest()
79 except Exception:
80 import ripemd
81 md = ripemd.new(sha256(public_key))
82 return md.digest()
83
84 def Hash(x):
85 if type(x) is unicode: x=x.encode('utf-8')
86 return sha256(sha256(x))
87
88 def i4b(self, x):
89 return pack('>I', x)
90
91
92 # /from Electrum
93
94 def getXpub(publicKeyData, testnet=False):
95 header = ("043587CF" if testnet else "0488B21E")
96 result = header.decode('hex') + chr(publicKeyData['depth']) + str(publicKeyData['parentFingerprint']) + str(publicKeyData['childNumber']) + str(publicKeyData['chainCode']) + str(compress_public_key(publicKeyData['publicKey']))
97 return EncodeBase58Check(result)
98
99 def getPub(publicKeyData, testnet=False):
100 header = ("6F" if testnet else "00")
101 keyData = hash_160(str(compress_public_key(publicKeyData)))
102 return EncodeBase58Check(header.decode('hex') + keyData)
103
104 def signMessage(encodedPrivateKey, data):
105 messageData = bytearray("\x18Bitcoin Signed Message:\n")
106 writeVarint(len(data), messageData)
107 messageData.extend(data)
108 messageHash = Hash(messageData)
109 signature = app.signImmediate(encodedPrivateKey, messageHash)
110
111 # Parse the ASN.1 signature
112
113 rLength = signature[3]
114 r = signature[4 : 4 + rLength]
115 sLength = signature[4 + rLength + 1]
116 s = signature[4 + rLength + 2:]
117 if rLength == 33:
118 r = r[1:]
119 if sLength == 33:
120 s = s[1:]
121 r = str(r)
122 s = str(s)
123
124 # And convert it
125
126 return b64encode(chr(27 + 4 + (signature[0] & 0x01)) + r + s)
127
128
129 f = open(sys.argv[1], 'r')
130 signData = json.load(f)
131 requestData = json.loads(signData['contents'])
132
133 result = {}
134 result['cosigner'] = requestData['cosigner']
135 result['request'] = requestData['request']
136 result['signatures'] = []
137
138 dongle = getDongle(True)
139 app = btchip(dongle)
140 seed = app.importPrivateKey(SEED, TESTNET)
141 privateKey = app.deriveBip32Key(seed, KEYPATH)
142 publicKeyData = app.getPublicKey(privateKey)
143
144 wallets = {}
145 for key in requestData['req_keys'].keys():
146 privateKeyDiv = app.deriveBip32Key(privateKey, key)
147 publicKeyDataDiv = app.getPublicKey(privateKeyDiv)
148 if getPub(publicKeyDataDiv['publicKey'], TESTNET) == requestData['req_keys'][key][0]:
149 wallets[key] = privateKeyDiv
150 else:
151 raise "Invalid wallet, could not match key"
152
153 for signInput in requestData['inputs']:
154 sigHash = signInput[1].decode('hex')
155 signature = "\x30" + str(app.signImmediate(wallets[signInput[0]], sigHash)[1:])
156 signature = signature + "\x01"
157 result['signatures'].append([signature.encode('hex'), sigHash.encode('hex'), signInput[0]])
158
159 body = {}
160 body['_humans'] = "Upload this set of signatures to Coinkite."
161 body['content'] = json.dumps(result)
162 body['signature'] = signMessage(privateKey, body['content'])
163 body['signed_by'] = getPub(publicKeyData['publicKey'], False) # Bug, should use network
164
165 print json.dumps(body)
166
167 dongle.close()
168