2016-08-28 07:38:30 -07:00
from struct import pack , unpack
2016-01-30 01:00:51 -08:00
import hashlib
2016-09-22 01:25:03 -07:00
import sys
import traceback
2014-08-24 10:44:26 -07:00
2019-02-28 13:26:15 -08:00
from electrum_zclassic import bitcoin
from electrum_zclassic import constants
from electrum_zclassic . bitcoin import ( TYPE_ADDRESS , int_to_hex , var_int ,
2018-03-11 03:34:03 -07:00
b58_address_to_hash160 ,
2018-06-02 09:40:29 -07:00
hash160_to_b58_address )
2019-02-28 13:26:15 -08:00
from electrum_zclassic . i18n import _
from electrum_zclassic . plugins import BasePlugin
from electrum_zclassic . keystore import Hardware_KeyStore
from electrum_zclassic . transaction import Transaction
2016-01-30 01:33:54 -08:00
from . . hw_wallet import HW_PluginBase
2019-02-28 13:26:15 -08:00
from electrum_zclassic . util import print_error , is_verbose , bfh , bh2u , versiontuple
2018-03-11 03:34:03 -07:00
def setAlternateCoinVersions ( self , regular , p2sh ) :
apdu = [ self . BTCHIP_CLA , 0x14 , 0x00 , 0x00 , 0x02 , regular , p2sh ]
self . dongle . exchange ( bytearray ( apdu ) )
2016-01-29 22:46:19 -08:00
2014-08-24 10:44:26 -07:00
try :
2016-08-28 07:38:30 -07:00
import hid
from btchip . btchipComm import HIDDongleHIDAPI , DongleWait
2014-08-24 10:44:26 -07:00
from btchip . btchip import btchip
2016-08-28 07:38:30 -07:00
from btchip . btchipUtils import compress_public_key , format_transaction , get_regular_input_script , get_p2sh_input_script
2014-08-24 10:44:26 -07:00
from btchip . bitcoinTransaction import bitcoinTransaction
2014-09-19 07:02:09 -07:00
from btchip . btchipFirmwareWizard import checkFirmware , updateFirmware
2014-08-27 14:19:14 -07:00
from btchip . btchipException import BTChipException
2018-03-11 03:34:03 -07:00
btchip . setAlternateCoinVersions = setAlternateCoinVersions
2014-08-24 10:44:26 -07:00
BTCHIP = True
2017-01-24 16:34:35 -08:00
BTCHIP_DEBUG = is_verbose
2014-08-24 10:44:26 -07:00
except ImportError :
BTCHIP = False
2018-04-05 16:42:04 -07:00
MSG_NEEDS_FW_UPDATE_GENERIC = _ ( ' Firmware version too old. Please update at ' ) + \
' https://www.ledgerwallet.com '
2018-06-02 09:40:29 -07:00
MULTI_OUTPUT_SUPPORT = ' 1.1.4 '
ALTERNATIVE_COIN_VERSION = ' 1.0.1 '
2018-04-05 16:42:04 -07:00
2016-08-28 07:38:30 -07:00
class Ledger_Client ( ) :
def __init__ ( self , hidDevice ) :
self . dongleObject = btchip ( hidDevice )
self . preflightDone = False
def is_pairable ( self ) :
return True
def close ( self ) :
self . dongleObject . dongle . close ( )
def timeout ( self , cutoff ) :
pass
def is_initialized ( self ) :
return True
def label ( self ) :
return " "
def i4b ( self , x ) :
2018-04-05 16:42:04 -07:00
return pack ( ' >I ' , x )
2016-08-28 07:38:30 -07:00
2018-06-02 09:40:29 -07:00
def has_usable_connection_with_device ( self ) :
try :
self . dongleObject . getFirmwareVersion ( )
except BaseException :
return False
return True
2018-04-05 16:42:04 -07:00
def test_pin_unlocked ( func ) :
""" Function decorator to test the Ledger for being unlocked, and if not,
raise a human - readable exception .
"""
def catch_exception ( self , * args , * * kwargs ) :
try :
return func ( self , * args , * * kwargs )
except BTChipException as e :
if e . sw == 0x6982 :
raise Exception ( _ ( ' Your Ledger is locked. Please unlock it. ' ) )
else :
raise
return catch_exception
@test_pin_unlocked
2017-10-31 03:45:25 -07:00
def get_xpub ( self , bip32_path , xtype ) :
2016-08-28 07:38:30 -07:00
self . checkDevice ( )
2019-02-28 14:04:05 -08:00
# bip32_path is of the form 44'/147'/0'
2016-08-28 07:38:30 -07:00
# S-L-O-W - we don't handle the fingerprint directly, so compute
# it manually from the previous node
# This only happens once so it's bearable
#self.get_client() # prompt for the PIN before displaying the dialog if necessary
#self.handler.show_message("Computing master public key")
2017-11-03 02:32:16 -07:00
splitPath = bip32_path . split ( ' / ' )
if splitPath [ 0 ] == ' m ' :
splitPath = splitPath [ 1 : ]
bip32_path = bip32_path [ 2 : ]
fingerprint = 0
if len ( splitPath ) > 1 :
prevPath = " / " . join ( splitPath [ 0 : len ( splitPath ) - 1 ] )
nodeData = self . dongleObject . getWalletPublicKey ( prevPath )
2018-04-05 16:42:04 -07:00
publicKey = compress_public_key ( nodeData [ ' publicKey ' ] )
2017-11-03 02:32:16 -07:00
h = hashlib . new ( ' ripemd160 ' )
h . update ( hashlib . sha256 ( publicKey ) . digest ( ) )
fingerprint = unpack ( " >I " , h . digest ( ) [ 0 : 4 ] ) [ 0 ]
nodeData = self . dongleObject . getWalletPublicKey ( bip32_path )
publicKey = compress_public_key ( nodeData [ ' publicKey ' ] )
depth = len ( splitPath )
lastChild = splitPath [ len ( splitPath ) - 1 ] . split ( ' \' ' )
childnum = int ( lastChild [ 0 ] ) if len ( lastChild ) == 1 else 0x80000000 | int ( lastChild [ 0 ] )
xpub = bitcoin . serialize_xpub ( xtype , nodeData [ ' chainCode ' ] , publicKey , depth , self . i4b ( fingerprint ) , self . i4b ( childnum ) )
return xpub
2016-08-28 07:38:30 -07:00
def has_detached_pin_support ( self , client ) :
try :
client . getVerifyPinRemainingAttempts ( )
return True
2017-02-16 01:54:24 -08:00
except BTChipException as e :
2016-08-28 07:38:30 -07:00
if e . sw == 0x6d00 :
return False
raise e
def is_pin_validated ( self , client ) :
try :
# Invalid SET OPERATION MODE to verify the PIN status
client . dongle . exchange ( bytearray ( [ 0xe0 , 0x26 , 0x00 , 0x00 , 0x01 , 0xAB ] ) )
2017-02-16 01:54:24 -08:00
except BTChipException as e :
2016-08-28 07:38:30 -07:00
if ( e . sw == 0x6982 ) :
return False
if ( e . sw == 0x6A80 ) :
return True
raise e
2017-01-24 16:34:35 -08:00
def supports_multi_output ( self ) :
return self . multiOutputSupported
2016-08-28 07:38:30 -07:00
def perform_hw1_preflight ( self ) :
try :
2017-09-17 09:34:38 -07:00
firmwareInfo = self . dongleObject . getFirmwareVersion ( )
2018-06-02 09:40:29 -07:00
firmware = firmwareInfo [ ' version ' ]
self . multiOutputSupported = versiontuple ( firmware ) > = versiontuple ( MULTI_OUTPUT_SUPPORT )
self . canAlternateCoinVersions = ( versiontuple ( firmware ) > = versiontuple ( ALTERNATIVE_COIN_VERSION )
and firmwareInfo [ ' specialVersion ' ] > = 0x20 )
2017-09-17 09:34:38 -07:00
2018-06-02 09:40:29 -07:00
if not checkFirmware ( firmwareInfo ) :
2016-10-24 06:45:54 -07:00
self . dongleObject . dongle . close ( )
2018-04-05 16:42:04 -07:00
raise Exception ( MSG_NEEDS_FW_UPDATE_GENERIC )
2016-08-28 07:38:30 -07:00
try :
self . dongleObject . getOperationMode ( )
2017-02-16 01:54:24 -08:00
except BTChipException as e :
2016-08-28 07:38:30 -07:00
if ( e . sw == 0x6985 ) :
2016-10-24 06:45:54 -07:00
self . dongleObject . dongle . close ( )
2016-12-20 21:52:54 -08:00
self . handler . get_setup ( )
2016-08-28 07:38:30 -07:00
# Acquire the new client on the next run
else :
raise e
2017-02-16 01:54:24 -08:00
if self . has_detached_pin_support ( self . dongleObject ) and not self . is_pin_validated ( self . dongleObject ) and ( self . handler is not None ) :
2016-08-28 07:38:30 -07:00
remaining_attempts = self . dongleObject . getVerifyPinRemainingAttempts ( )
2017-02-16 01:54:24 -08:00
if remaining_attempts != 1 :
2016-08-28 07:38:30 -07:00
msg = " Enter your Ledger PIN - remaining attempts : " + str ( remaining_attempts )
else :
msg = " Enter your Ledger PIN - WARNING : LAST ATTEMPT. If the PIN is not correct, the dongle will be wiped. "
confirmed , p , pin = self . password_dialog ( msg )
if not confirmed :
raise Exception ( ' Aborted by user - please unplug the dongle and plug it again before retrying ' )
pin = pin . encode ( )
self . dongleObject . verifyPin ( pin )
2018-03-11 03:34:03 -07:00
if self . canAlternateCoinVersions :
2018-06-02 09:40:29 -07:00
self . dongleObject . setAlternateCoinVersions ( constants . net . ADDRTYPE_P2PKH ,
constants . net . ADDRTYPE_P2SH )
2017-02-16 01:54:24 -08:00
except BTChipException as e :
2016-08-28 07:38:30 -07:00
if ( e . sw == 0x6faa ) :
raise Exception ( " Dongle is temporarily locked - please unplug it and replug it again " )
if ( ( e . sw & 0xFFF0 ) == 0x63c0 ) :
raise Exception ( " Invalid PIN - please unplug the dongle and plug it again before retrying " )
2018-06-02 09:40:29 -07:00
if e . sw == 0x6f00 and e . message == ' Invalid channel ' :
# based on docs 0x6f00 might be a more general error, hence we also compare message to be sure
raise Exception ( " Invalid channel. \n "
" Please make sure that ' Browser support ' is disabled on your device. " )
2016-08-28 07:38:30 -07:00
raise e
def checkDevice ( self ) :
if not self . preflightDone :
2016-10-19 23:38:13 -07:00
try :
self . perform_hw1_preflight ( )
except BTChipException as e :
2018-06-02 09:40:29 -07:00
if ( e . sw == 0x6d00 or e . sw == 0x6700 ) :
2019-02-28 13:26:15 -08:00
raise Exception ( _ ( " Device not in Zclassic mode " ) ) from e
2016-10-19 23:38:13 -07:00
raise e
2016-08-28 07:38:30 -07:00
self . preflightDone = True
def password_dialog ( self , msg = None ) :
response = self . handler . get_word ( msg )
if response is None :
return False , None , None
return True , response , response
2014-08-24 10:44:26 -07:00
2016-08-18 02:34:37 -07:00
class Ledger_KeyStore ( Hardware_KeyStore ) :
2016-08-28 07:38:30 -07:00
hw_type = ' ledger '
2016-01-01 01:38:43 -08:00
device = ' Ledger '
2014-08-24 10:44:26 -07:00
2016-08-21 13:44:42 -07:00
def __init__ ( self , d ) :
Hardware_KeyStore . __init__ ( self , d )
2016-01-10 21:38:45 -08:00
# Errors and other user interaction is done through the wallet's
# handler. The handler is per-window and preserved across
# device reconnects
self . force_watching_only = False
2014-09-20 05:27:13 -07:00
self . signing = False
2016-12-20 21:52:54 -08:00
self . cfg = d . get ( ' cfg ' , { ' mode ' : 0 , ' pair ' : ' ' } )
2017-04-12 10:15:43 -07:00
2016-12-20 21:52:54 -08:00
def dump ( self ) :
obj = Hardware_KeyStore . dump ( self )
obj [ ' cfg ' ] = self . cfg
return obj
2016-08-18 02:34:37 -07:00
2016-08-28 07:38:30 -07:00
def get_derivation ( self ) :
2018-04-05 16:42:04 -07:00
return self . derivation
2014-08-24 10:44:26 -07:00
2016-08-28 07:38:30 -07:00
def get_client ( self ) :
2017-01-24 16:34:35 -08:00
return self . plugin . get_client ( self ) . dongleObject
2018-04-05 16:42:04 -07:00
2017-01-24 16:34:35 -08:00
def get_client_electrum ( self ) :
2016-08-28 07:38:30 -07:00
return self . plugin . get_client ( self )
2018-04-05 16:42:04 -07:00
2014-09-19 04:39:12 -07:00
def give_error ( self , message , clear_client = False ) :
2015-07-05 13:14:53 -07:00
print_error ( message )
2014-09-19 04:39:12 -07:00
if not self . signing :
2016-01-29 22:46:19 -08:00
self . handler . show_error ( message )
2014-09-19 04:39:12 -07:00
else :
self . signing = False
2016-01-10 22:08:12 -08:00
if clear_client :
2016-08-18 02:34:37 -07:00
self . client = None
2015-07-04 00:45:08 -07:00
raise Exception ( message )
2014-09-19 04:39:12 -07:00
2018-06-02 09:40:29 -07:00
def set_and_unset_signing ( func ) :
""" Function decorator to set and unset self.signing. """
def wrapper ( self , * args , * * kwargs ) :
try :
self . signing = True
return func ( self , * args , * * kwargs )
finally :
self . signing = False
return wrapper
2016-08-28 07:38:30 -07:00
def address_id_stripped ( self , address ) :
2016-01-10 02:53:28 -08:00
# Strip the leading "m/"
2016-08-28 07:38:30 -07:00
change , index = self . get_address_index ( address )
derivation = self . derivation
address_path = " %s / %d / %d " % ( derivation , change , index )
return address_path [ 2 : ]
2014-08-24 10:44:26 -07:00
def decrypt_message ( self , pubkey , message , password ) :
2018-06-02 09:40:29 -07:00
raise RuntimeError ( _ ( ' Encryption and decryption are currently not supported for {} ' ) . format ( self . device ) )
2014-08-24 10:44:26 -07:00
2018-06-02 09:40:29 -07:00
@set_and_unset_signing
2016-08-28 07:38:30 -07:00
def sign_message ( self , sequence , message , password ) :
2017-11-05 08:45:55 -08:00
message = message . encode ( ' utf8 ' )
2018-06-02 09:40:29 -07:00
message_hash = hashlib . sha256 ( message ) . hexdigest ( ) . upper ( )
2016-01-10 22:08:12 -08:00
# prompt for the PIN before displaying the dialog if necessary
client = self . get_client ( )
2016-08-28 07:38:30 -07:00
address_path = self . get_derivation ( ) [ 2 : ] + " / %d / %d " % sequence
2018-06-02 09:40:29 -07:00
self . handler . show_message ( " Signing message ... \r \n Message hash: " + message_hash )
2014-08-24 10:44:26 -07:00
try :
info = self . get_client ( ) . signMessagePrepare ( address_path , message )
pin = " "
2015-07-04 00:45:08 -07:00
if info [ ' confirmationNeeded ' ] :
2016-12-20 21:52:54 -08:00
pin = self . handler . get_auth ( info ) # does the authenticate dialog and returns pin
if not pin :
raise UserWarning ( _ ( ' Cancelled by user ' ) )
pin = str ( pin ) . encode ( )
2014-08-24 10:44:26 -07:00
signature = self . get_client ( ) . signMessageSign ( pin )
2017-02-16 01:54:24 -08:00
except BTChipException as e :
2015-01-31 17:29:21 -08:00
if e . sw == 0x6a80 :
2015-08-14 04:34:22 -07:00
self . give_error ( " Unfortunately, this message cannot be signed by the Ledger wallet. Only alphanumerical messages shorter than 140 characters are supported. Please remove any extra characters (tab, carriage return) and retry. " )
2018-06-02 09:40:29 -07:00
elif e . sw == 0x6985 : # cancelled by user
return b ' '
2015-07-04 00:45:08 -07:00
else :
self . give_error ( e , True )
2016-12-20 21:52:54 -08:00
except UserWarning :
self . handler . show_error ( _ ( ' Cancelled by user ' ) )
2018-06-02 09:40:29 -07:00
return b ' '
2017-02-16 01:54:24 -08:00
except Exception as e :
2015-02-23 07:30:33 -08:00
self . give_error ( e , True )
2014-08-24 10:44:26 -07:00
finally :
2017-11-17 19:09:15 -08:00
self . handler . finished ( )
2014-08-24 10:44:26 -07:00
# Parse the ASN.1 signature
rLength = signature [ 3 ]
r = signature [ 4 : 4 + rLength ]
sLength = signature [ 4 + rLength + 1 ]
s = signature [ 4 + rLength + 2 : ]
if rLength == 33 :
r = r [ 1 : ]
if sLength == 33 :
s = s [ 1 : ]
# And convert it
2017-11-05 08:45:55 -08:00
return bytes ( [ 27 + 4 + ( signature [ 0 ] & 0x01 ) ] ) + r + s
2018-06-02 09:40:29 -07:00
@set_and_unset_signing
2014-10-30 13:10:12 -07:00
def sign_transaction ( self , tx , password ) :
2014-10-24 01:53:09 -07:00
if tx . is_complete ( ) :
2014-09-19 04:39:12 -07:00
return
2016-01-27 11:47:49 -08:00
client = self . get_client ( )
2014-08-24 10:44:26 -07:00
inputs = [ ]
inputsPaths = [ ]
pubKeys = [ ]
2016-08-28 07:38:30 -07:00
chipInputs = [ ]
2015-07-04 00:45:08 -07:00
redeemScripts = [ ]
2014-08-24 10:44:26 -07:00
signatures = [ ]
preparedTrustedInputs = [ ]
2015-07-04 00:45:08 -07:00
changePath = " "
2014-08-24 10:44:26 -07:00
changeAmount = None
output = None
outputAmount = None
2016-08-28 07:38:30 -07:00
p2shTransaction = False
2014-08-27 14:19:14 -07:00
pin = " "
2016-08-28 07:38:30 -07:00
self . get_client ( ) # prompt for the PIN before displaying the dialog if necessary
2016-09-30 05:56:53 -07:00
2014-08-24 10:44:26 -07:00
# Fetch inputs of the transaction to sign
2016-09-30 05:56:53 -07:00
derivations = self . get_tx_derivations ( tx )
2016-09-22 01:25:03 -07:00
for txin in tx . inputs ( ) :
2017-03-21 01:08:16 -07:00
if txin [ ' type ' ] == ' coinbase ' :
2014-09-19 04:39:12 -07:00
self . give_error ( " Coinbase not supported " ) # should never happen
2016-09-22 01:25:03 -07:00
2017-03-01 23:38:06 -08:00
if txin [ ' type ' ] in [ ' p2sh ' ] :
2016-09-22 01:25:03 -07:00
p2shTransaction = True
2016-09-30 05:56:53 -07:00
2017-03-01 23:38:06 -08:00
pubkeys , x_pubkeys = tx . get_sorted_pubkeys ( txin )
for i , x_pubkey in enumerate ( x_pubkeys ) :
2016-09-30 05:56:53 -07:00
if x_pubkey in derivations :
signingPos = i
s = derivations . get ( x_pubkey )
hwAddress = " %s / %d / %d " % ( self . get_derivation ( ) [ 2 : ] , s [ 0 ] , s [ 1 ] )
break
else :
self . give_error ( " No matching x_key for sign_transaction " ) # should never happen
2016-08-28 07:38:30 -07:00
2017-04-18 02:12:46 -07:00
redeemScript = Transaction . get_preimage_script ( txin )
2018-06-02 09:40:29 -07:00
if txin . get ( ' prev_tx ' ) is None : # and not Transaction.is_segwit_input(txin):
# note: offline signing does not work atm even with segwit inputs for ledger
raise Exception ( _ ( ' Offline signing with {} is not supported. ' ) . format ( self . device ) )
2017-08-08 00:26:05 -07:00
inputs . append ( [ txin [ ' prev_tx ' ] . raw , txin [ ' prevout_n ' ] , redeemScript , txin [ ' prevout_hash ' ] , signingPos , txin . get ( ' sequence ' , 0xffffffff - 1 ) ] )
2016-08-28 07:38:30 -07:00
inputsPaths . append ( hwAddress )
2017-03-01 23:38:06 -08:00
pubKeys . append ( pubkeys )
2016-09-22 01:25:03 -07:00
2016-08-28 07:38:30 -07:00
# Sanity check
if p2shTransaction :
2017-03-01 23:38:06 -08:00
for txin in tx . inputs ( ) :
if txin [ ' type ' ] != ' p2sh ' :
2016-08-28 07:38:30 -07:00
self . give_error ( " P2SH / regular input mixed in same transaction not supported " ) # should never happen
2016-09-22 01:25:03 -07:00
txOutput = var_int ( len ( tx . outputs ( ) ) )
for txout in tx . outputs ( ) :
output_type , addr , amount = txout
txOutput + = int_to_hex ( amount , 8 )
script = tx . pay_script ( output_type , addr )
2017-08-13 03:00:33 -07:00
txOutput + = var_int ( len ( script ) / / 2 )
2016-09-22 01:25:03 -07:00
txOutput + = script
2017-08-13 03:00:33 -07:00
txOutput = bfh ( txOutput )
2014-08-24 10:44:26 -07:00
# Recognize outputs - only one output and one change is authorized
2016-08-28 07:38:30 -07:00
if not p2shTransaction :
2017-01-24 16:34:35 -08:00
if not self . get_client_electrum ( ) . supports_multi_output ( ) :
if len ( tx . outputs ( ) ) > 2 :
self . give_error ( " Transaction with more than 2 outputs not supported " )
2016-10-19 23:23:10 -07:00
for _type , address , amount in tx . outputs ( ) :
2016-08-28 07:38:30 -07:00
assert _type == TYPE_ADDRESS
2016-10-19 23:23:10 -07:00
info = tx . output_info . get ( address )
2018-06-02 09:40:29 -07:00
if ( info is not None ) and len ( tx . outputs ( ) ) > 1 \
and info [ 0 ] [ 0 ] == 1 : # "is on 'change' branch"
2016-10-19 23:23:10 -07:00
index , xpubs , m = info
changePath = self . get_derivation ( ) [ 2 : ] + " / %d / %d " % index
2016-08-28 07:38:30 -07:00
changeAmount = amount
else :
output = address
2018-03-11 03:34:03 -07:00
if not self . get_client_electrum ( ) . canAlternateCoinVersions :
v , h = b58_address_to_hash160 ( address )
2018-06-02 09:40:29 -07:00
if v == constants . net . ADDRTYPE_P2PKH :
2018-03-11 03:34:03 -07:00
output = hash160_to_b58_address ( h , 0 )
2016-08-28 07:38:30 -07:00
outputAmount = amount
2016-09-22 01:25:03 -07:00
2016-09-22 01:54:32 -07:00
self . handler . show_message ( _ ( " Confirm Transaction on your Ledger device... " ) )
2014-08-24 10:44:26 -07:00
try :
# Get trusted inputs from the original transactions
2018-04-05 16:42:04 -07:00
for utxo in inputs :
2017-04-12 10:35:00 -07:00
sequence = int_to_hex ( utxo [ 5 ] , 4 )
2018-03-10 15:40:56 -08:00
if not p2shTransaction :
2017-11-08 06:01:25 -08:00
txtmp = bitcoinTransaction ( bfh ( utxo [ 0 ] ) )
trustedInput = self . get_client ( ) . getTrustedInput ( txtmp , utxo [ 1 ] )
trustedInput [ ' sequence ' ] = sequence
chipInputs . append ( trustedInput )
redeemScripts . append ( txtmp . outputs [ utxo [ 1 ] ] . script )
2016-08-28 07:38:30 -07:00
else :
2017-08-13 03:00:33 -07:00
tmp = bfh ( utxo [ 3 ] ) [ : : - 1 ]
tmp + = bfh ( int_to_hex ( utxo [ 1 ] , 4 ) )
chipInputs . append ( { ' value ' : tmp , ' sequence ' : sequence } )
redeemScripts . append ( bfh ( utxo [ 2 ] ) )
2016-08-28 07:38:30 -07:00
2014-08-24 10:44:26 -07:00
# Sign all inputs
firstTransaction = True
inputIndex = 0
2016-10-09 00:20:32 -07:00
rawTx = tx . serialize ( )
2016-12-20 21:52:54 -08:00
self . get_client ( ) . enableAlternate2fa ( False )
2018-03-10 15:40:56 -08:00
while inputIndex < len ( inputs ) :
self . get_client ( ) . startUntrustedTransaction ( firstTransaction , inputIndex ,
chipInputs , redeemScripts [ inputIndex ] )
2018-06-02 09:40:29 -07:00
if changePath :
# we don't set meaningful outputAddress, amount and fees
# as we only care about the alternateEncoding==True branch
outputData = self . get_client ( ) . finalizeInput ( b ' ' , 0 , 0 , changePath , bfh ( rawTx ) )
else :
outputData = self . get_client ( ) . finalizeInputFull ( txOutput )
2017-04-12 10:15:43 -07:00
outputData [ ' outputData ' ] = txOutput
2018-03-10 15:40:56 -08:00
if firstTransaction :
transactionOutput = outputData [ ' outputData ' ]
2015-09-03 17:07:18 -07:00
if outputData [ ' confirmationNeeded ' ] :
2016-12-20 21:52:54 -08:00
outputData [ ' address ' ] = output
2017-11-17 19:09:15 -08:00
self . handler . finished ( )
2016-12-20 21:52:54 -08:00
pin = self . handler . get_auth ( outputData ) # does the authenticate dialog and returns pin
if not pin :
raise UserWarning ( )
if pin != ' paired ' :
self . handler . show_message ( _ ( " Confirmed. Signing Transaction... " ) )
2018-03-10 15:40:56 -08:00
else :
# Sign input with the provided PIN
2017-11-11 02:37:50 -08:00
inputSignature = self . get_client ( ) . untrustedHashSign ( inputsPaths [ inputIndex ] , pin , lockTime = tx . locktime )
2014-08-27 14:19:14 -07:00
inputSignature [ 0 ] = 0x30 # force for 1.4.9+
signatures . append ( inputSignature )
2014-08-24 10:44:26 -07:00
inputIndex = inputIndex + 1
2018-03-10 15:40:56 -08:00
if pin != ' paired ' :
firstTransaction = False
2016-12-20 21:52:54 -08:00
except UserWarning :
self . handler . show_error ( _ ( ' Cancelled by user ' ) )
return
2018-06-02 09:40:29 -07:00
except BTChipException as e :
if e . sw == 0x6985 : # cancelled by user
return
else :
traceback . print_exc ( file = sys . stderr )
self . give_error ( e , True )
2016-09-22 01:25:03 -07:00
except BaseException as e :
traceback . print_exc ( file = sys . stdout )
2014-09-19 04:39:12 -07:00
self . give_error ( e , True )
2014-08-24 10:44:26 -07:00
finally :
2017-11-17 19:09:15 -08:00
self . handler . finished ( )
2014-08-24 10:44:26 -07:00
2017-04-18 01:43:24 -07:00
for i , txin in enumerate ( tx . inputs ( ) ) :
signingPos = inputs [ i ] [ 4 ]
2017-08-13 03:00:33 -07:00
txin [ ' signatures ' ] [ signingPos ] = bh2u ( signatures [ i ] )
2017-04-18 01:43:24 -07:00
tx . raw = tx . serialize ( )
2014-08-24 10:44:26 -07:00
2018-06-02 09:40:29 -07:00
@set_and_unset_signing
def show_address ( self , sequence , txin_type ) :
client = self . get_client ( )
address_path = self . get_derivation ( ) [ 2 : ] + " / %d / %d " % sequence
self . handler . show_message ( _ ( " Showing address ... " ) )
try :
client . getWalletPublicKey ( address_path , showOnScreen = True )
except BTChipException as e :
if e . sw == 0x6985 : # cancelled by user
pass
else :
traceback . print_exc ( file = sys . stderr )
self . handler . show_error ( e )
except BaseException as e :
traceback . print_exc ( file = sys . stderr )
self . handler . show_error ( e )
finally :
self . handler . finished ( )
2016-08-21 13:44:42 -07:00
class LedgerPlugin ( HW_PluginBase ) :
libraries_available = BTCHIP
keystore_class = Ledger_KeyStore
client = None
2018-04-05 16:42:04 -07:00
DEVICE_IDS = [
2016-08-28 07:38:30 -07:00
( 0x2581 , 0x1807 ) , # HW.1 legacy btchip
( 0x2581 , 0x2b7c ) , # HW.1 transitional production
( 0x2581 , 0x3b7c ) , # HW.1 ledger production
( 0x2581 , 0x4b7c ) , # HW.1 ledger test
( 0x2c97 , 0x0000 ) , # Blue
( 0x2c97 , 0x0001 ) # Nano-S
]
def __init__ ( self , parent , config , name ) :
HW_PluginBase . __init__ ( self , parent , config , name )
if self . libraries_available :
self . device_manager ( ) . register_devices ( self . DEVICE_IDS )
2016-08-21 13:44:42 -07:00
2016-08-28 07:38:30 -07:00
def get_btchip_device ( self , device ) :
ledger = False
2018-06-02 09:40:29 -07:00
if device . product_key [ 0 ] == 0x2581 and device . product_key [ 1 ] == 0x3b7c :
ledger = True
if device . product_key [ 0 ] == 0x2581 and device . product_key [ 1 ] == 0x4b7c :
ledger = True
if device . product_key [ 0 ] == 0x2c97 :
if device . interface_number == 0 or device . usage_page == 0xffa0 :
ledger = True
else :
return None # non-compatible interface of a Nano S or Blue
2016-08-28 07:38:30 -07:00
dev = hid . device ( )
dev . open_path ( device . path )
dev . set_nonblocking ( True )
return HIDDongleHIDAPI ( dev , ledger , BTCHIP_DEBUG )
2018-04-05 16:42:04 -07:00
2016-08-28 07:38:30 -07:00
def create_client ( self , device , handler ) :
2018-06-02 09:40:29 -07:00
if handler :
self . handler = handler
2016-08-28 07:38:30 -07:00
client = self . get_btchip_device ( device )
2017-02-16 01:54:24 -08:00
if client is not None :
2016-08-28 07:38:30 -07:00
client = Ledger_Client ( client )
return client
2018-06-02 09:40:29 -07:00
def setup_device ( self , device_info , wizard , purpose ) :
2016-08-28 07:38:30 -07:00
devmgr = self . device_manager ( )
device_id = device_info . device . id_
client = devmgr . client_by_id ( device_id )
client . handler = self . create_handler ( wizard )
2019-02-28 13:26:31 -08:00
client . get_xpub ( " m/44 ' /147 ' " , ' standard ' ) # TODO replace by direct derivation once Nano S > 1.1
2016-08-28 07:38:30 -07:00
2017-10-31 03:45:25 -07:00
def get_xpub ( self , device_id , derivation , xtype , wizard ) :
2016-08-28 07:38:30 -07:00
devmgr = self . device_manager ( )
client = devmgr . client_by_id ( device_id )
client . handler = self . create_handler ( wizard )
client . checkDevice ( )
2017-10-31 03:45:25 -07:00
xpub = client . get_xpub ( derivation , xtype )
2016-08-28 07:38:30 -07:00
return xpub
def get_client ( self , keystore , force_pair = True ) :
# All client interaction should not be in the main GUI thread
devmgr = self . device_manager ( )
handler = keystore . handler
with devmgr . hid_lock :
2018-04-05 16:42:04 -07:00
client = devmgr . client_for_keystore ( self , handler , keystore , force_pair )
2016-08-28 07:38:30 -07:00
# returns the client for a given keystore. can use xpub
#if client:
# client.used()
2017-02-16 01:54:24 -08:00
if client is not None :
2018-04-05 16:42:04 -07:00
client . checkDevice ( )
2016-08-28 07:38:30 -07:00
return client
2018-06-02 09:40:29 -07:00
def show_address ( self , wallet , address ) :
sequence = wallet . get_address_index ( address )
txin_type = wallet . get_txin_type ( address )
wallet . get_keystore ( ) . show_address ( sequence , txin_type )