27
27
import math
28
28
import rlp
29
29
30
- def intToBytes (i : int ) -> bytes :
31
- if i == 0 :
32
- return b"\x00 "
33
- return i .to_bytes (math .ceil (i .bit_length () / 8 ), 'big' )
30
+
31
+
32
+ def der_encode (value ):
33
+ value_bytes = value .to_bytes (max (1 , (value .bit_length () + 7 ) // 8 ), 'big' )
34
+ if value >= 0x80 :
35
+ value_bytes = (0x80 | len (value_bytes )).to_bytes (1 , 'big' ) + value_bytes
36
+ return value_bytes
37
+
38
+ def tlv_encode (tag , value ):
39
+ return der_encode (tag ) + der_encode (len (value )) + value
34
40
35
41
def parse_bip32_path (path ):
36
42
if len (path ) == 0 :
@@ -39,6 +45,7 @@ def parse_bip32_path(path):
39
45
elements = path .split ('/' )
40
46
for pathElement in elements :
41
47
element = pathElement .split ('\' ' )
48
+ result = result + der_encode (0x01 ) + der_encode (0x04 )
42
49
if len (element ) == 1 :
43
50
result = result + struct .pack (">I" , int (element [0 ]))
44
51
else :
@@ -56,17 +63,18 @@ def parse_bip32_path(path):
56
63
if args .path == None :
57
64
args .path = "44'/60'/0'/0/0"
58
65
66
+ tmp = tlv_encode (0x00 , struct .pack (">B" , 0x01 ))
67
+ tmp += parse_bip32_path (args .path )
59
68
data = binascii .unhexlify (args .delegate [2 :])
60
- tmp = intToBytes (args .chainid )
61
- data += struct .pack (">B" , len (tmp )) + tmp
62
- tmp = intToBytes (args .nonce )
63
- data += struct .pack (">B" , len (tmp )) + tmp
69
+ tmp += tlv_encode (0x02 , data )
70
+ tmp += tlv_encode (0x03 , struct .pack (">Q" , args .chainid ))
71
+ tmp += tlv_encode (0x04 , struct .pack (">Q" , args .nonce ))
64
72
65
- donglePath = parse_bip32_path ( args . path )
66
- apdu = bytearray . fromhex ( "e0320000" )
67
- apdu += struct . pack ( ">B" , len ( donglePath ) + 1 + len ( data ) )
68
- apdu += struct .pack (">B" , len (donglePath ) // 4 )
69
- apdu += donglePath + data
73
+ tmp = struct . pack ( ">H" , len ( tmp )) + tmp
74
+
75
+ apdu = bytearray . fromhex ( "e0340100" )
76
+ apdu += struct .pack (">B" , len (tmp ) )
77
+ apdu += tmp
70
78
71
79
dongle = getDongle (True )
72
80
result = dongle .exchange (bytes (apdu ))
@@ -81,4 +89,3 @@ def parse_bip32_path(path):
81
89
82
90
rlpData = [ args .chainid , binascii .unhexlify (args .delegate [2 :]), args .nonce , v , r , s ]
83
91
print (binascii .hexlify (rlp .encode (rlpData )).decode ('utf-8' ))
84
-
0 commit comments