2727import math
2828import rlp
2929
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
3440
3541def parse_bip32_path (path ):
3642 if len (path ) == 0 :
@@ -39,6 +45,7 @@ def parse_bip32_path(path):
3945 elements = path .split ('/' )
4046 for pathElement in elements :
4147 element = pathElement .split ('\' ' )
48+ result = result + der_encode (0x01 ) + der_encode (0x04 )
4249 if len (element ) == 1 :
4350 result = result + struct .pack (">I" , int (element [0 ]))
4451 else :
@@ -56,17 +63,18 @@ def parse_bip32_path(path):
5663if args .path == None :
5764 args .path = "44'/60'/0'/0/0"
5865
66+ tmp = tlv_encode (0x00 , struct .pack (">B" , 0x01 ))
67+ tmp += parse_bip32_path (args .path )
5968data = 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 ))
6472
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
7078
7179dongle = getDongle (True )
7280result = dongle .exchange (bytes (apdu ))
@@ -81,4 +89,3 @@ def parse_bip32_path(path):
8189
8290rlpData = [ args .chainid , binascii .unhexlify (args .delegate [2 :]), args .nonce , v , r , s ]
8391print (binascii .hexlify (rlp .encode (rlpData )).decode ('utf-8' ))
84-
0 commit comments