Beispiel #1
0
    def on_receive(self, keyhash, message):
        self.print_error("signal arrived for", keyhash)
        for key, _hash, window in self.keys:
            if _hash == keyhash:
                break
        else:
            self.print_error("keyhash not found")
            return

        wallet = window.wallet
        if wallet.has_keystore_encryption():
            password = window.password_dialog('An encrypted transaction was retrieved from cosigning pool.\nPlease enter your password to decrypt it.')
            if not password:
                return
        else:
            password = None
            if not window.question(_("An encrypted transaction was retrieved from cosigning pool.\nDo you want to open it now?")):
                return

        xprv = wallet.keystore.get_master_private_key(password)
        if not xprv:
            return
        try:
            k = bh2u(bitcoin.deserialize_xprv(xprv)[-1])
            EC = bitcoin.EC_KEY(bfh(k))
            message = bh2u(EC.decrypt_message(message))
        except Exception as e:
            traceback.print_exc(file=sys.stdout)
            window.show_message(str(e))
            return

        self.listener.clear(keyhash)
        tx = transaction.Transaction(message)
        show_transaction(tx, window, prompt_if_unsaved=True)
Beispiel #2
0
 def mock_fork(self, bad_header):
     forkpoint = bad_header['block_height']
     b = blockchain.Blockchain(config=self.config,
                               forkpoint=forkpoint,
                               parent=None,
                               forkpoint_hash=bh2u(sha256(str(forkpoint))),
                               prev_hash=bh2u(sha256(str(forkpoint - 1))))
     return b
Beispiel #3
0
        def update(features):
            self.features = features
            set_label_enabled()
            bl_hash = bh2u(features.bootloader_hash)
            bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
            noyes = [_("No"), _("Yes")]
            endis = [_("Enable Passphrases"), _("Disable Passphrases")]
            disen = [_("Disabled"), _("Enabled")]
            setchange = [_("Set a PIN"), _("Change PIN")]

            version = "%d.%d.%d" % (features.major_version,
                                    features.minor_version,
                                    features.patch_version)
            coins = ", ".join(coin.coin_name for coin in features.coins)

            device_label.setText(features.label)
            pin_set_label.setText(noyes[features.pin_protection])
            passphrases_label.setText(disen[features.passphrase_protection])
            bl_hash_label.setText(bl_hash)
            label_edit.setText(features.label)
            device_id_label.setText(features.device_id)
            initialized_label.setText(noyes[features.initialized])
            version_label.setText(version)
            coins_label.setText(coins)
            clear_pin_button.setVisible(features.pin_protection)
            clear_pin_warning.setVisible(features.pin_protection)
            pin_button.setText(setchange[features.pin_protection])
            pin_msg.setVisible(not features.pin_protection)
            passphrase_button.setText(endis[features.passphrase_protection])
            language_label.setText(features.language)
 def test_mnemonic_to_seed_basic(self):
     # note: not a valid electrum seed
     seed = mnemonic.Mnemonic.mnemonic_to_seed(mnemonic='foobar',
                                               passphrase='none')
     self.assertEqual(
         '741b72fd15effece6bfe5a26a52184f66811bd2be363190e07a42cca442b1a5bb22b3ad0eb338197287e6d314866c7fba863ac65d3f156087a5052ebc7157fce',
         bh2u(seed))
Beispiel #5
0
 def update(self, window: 'ElectrumWindow'):
     wallet = window.wallet
     if type(wallet) != Multisig_Wallet:
         return
     assert isinstance(wallet,
                       Multisig_Wallet)  # only here for type-hints in IDE
     if self.listener is None:
         self.logger.info("starting listener")
         self.listener = Listener(self)
         self.listener.start()
     elif self.listener:
         self.logger.info("shutting down listener")
         self.listener.stop()
         self.listener = None
     self.keys = []
     self.cosigner_list = []
     for key, keystore in wallet.keystores.items():
         xpub = keystore.get_master_public_key()  # type: str
         pubkey = BIP32Node.from_xkey(xpub).eckey.get_public_key_bytes(
             compressed=True)
         _hash = bh2u(crypto.sha256d(pubkey))
         if not keystore.is_watching_only():
             self.keys.append((key, _hash, window))
         else:
             self.cosigner_list.append((window, xpub, pubkey, _hash))
     if self.listener:
         self.listener.set_keyhashes([t[1] for t in self.keys])
Beispiel #6
0
 def gen_random_versioned_seed(cls):
     version = cls.LATEST_VERSION
     hex_seed = bh2u(os.urandom(16))
     checksum = cls.code_hashid(version + hex_seed)
     return VersionedSeed(version=version.upper(),
                          seed=hex_seed.upper(),
                          checksum=checksum.upper())
Beispiel #7
0
 def sign_transaction(self, keystore, tx, prev_tx, xpub_path):
     self.prev_tx = prev_tx
     self.xpub_path = xpub_path
     client = self.get_client(keystore)
     inputs = self.tx_inputs(tx, True, keystore.get_script_gen())
     outputs = self.tx_outputs(keystore.get_derivation(), tx, keystore.get_script_gen())
     signed_tx = client.sign_tx(self.get_coin_name(), inputs, outputs, lock_time=tx.locktime)[1]
     raw = bh2u(signed_tx)
     tx.update_signatures(raw)
Beispiel #8
0
 def sign_transaction(self, keystore, tx, prev_tx, xpub_path):
     self.prev_tx = prev_tx
     self.xpub_path = xpub_path
     client = self.get_client(keystore)
     inputs = self.tx_inputs(tx, True, keystore.get_script_gen())
     outputs = self.tx_outputs(keystore.get_derivation(), tx, keystore.get_script_gen())
     signed_tx = client.sign_tx(self.get_coin_name(), inputs, outputs, version=4, lock_time=tx.locktime, overwintered=True, version_group_id=2301567109, branch_id=1991772603)[1]
     raw = bh2u(signed_tx)
     tx.update_signatures(raw, True)
 def test_mnemonic_to_seed(self):
     for test_name, test in SEED_TEST_CASES.items():
         if test.words_hex is not None:
             self.assertEqual(test.words_hex,
                              bh2u(test.words.encode('utf8')),
                              msg=test_name)
         self.assertTrue(is_new_seed(test.words, prefix=test.seed_version),
                         msg=test_name)
         m = mnemonic.Mnemonic(lang=test.lang)
         if test.entropy is not None:
             self.assertEqual(test.entropy,
                              m.mnemonic_decode(test.words),
                              msg=test_name)
         if test.passphrase_hex is not None:
             self.assertEqual(test.passphrase_hex,
                              bh2u(test.passphrase.encode('utf8')),
                              msg=test_name)
         seed = mnemonic.Mnemonic.mnemonic_to_seed(
             mnemonic=test.words, passphrase=test.passphrase)
         self.assertEqual(test.bip32_seed, bh2u(seed), msg=test_name)
Beispiel #10
0
 def sign_transaction(self, keystore, tx: PartialTransaction, prev_tx):
     self.prev_tx = prev_tx
     client = self.get_client(keystore)
     inputs = self.tx_inputs(tx, for_sig=True, keystore=keystore)
     outputs = self.tx_outputs(tx, keystore=keystore)
     signatures = client.sign_tx(self.get_coin_name(),
                                 inputs,
                                 outputs,
                                 lock_time=tx.locktime,
                                 version=tx.version)[0]
     signatures = [(bh2u(x) + '01') for x in signatures]
     tx.update_signatures(signatures)
Beispiel #11
0
 def do_send(self, tx):
     for window, xpub, K, _hash in self.cosigner_list:
         if not self.cosigner_can_sign(tx, xpub):
             continue
         raw_tx_bytes = bfh(str(tx))
         message = bitcoin.encrypt_message(raw_tx_bytes, bh2u(K)).decode('ascii')
         try:
             server.put(_hash, message)
         except Exception as e:
             traceback.print_exc(file=sys.stdout)
             window.show_message("Failed to send transaction to cosigning pool.")
             return
         window.show_message("Your transaction was sent to the cosigning pool.\nOpen your cosigner wallet to retrieve it.")
Beispiel #12
0
 def sign_transaction(self, keystore, tx: PartialTransaction, prev_tx):
     prev_tx = {
         bfh(txhash): self.electrum_tx_to_txtype(tx)
         for txhash, tx in prev_tx.items()
     }
     client = self.get_client(keystore)
     inputs = self.tx_inputs(tx, for_sig=True, keystore=keystore)
     outputs = self.tx_outputs(tx, keystore=keystore)
     details = SignTx(lock_time=tx.locktime, version=tx.version)
     signatures, _ = client.sign_tx(self.get_coin_name(),
                                    inputs,
                                    outputs,
                                    details=details,
                                    prev_txes=prev_tx)
     signatures = [(bh2u(x) + '01') for x in signatures]
     tx.update_signatures(signatures)
 def on_qr(self, data):
     from electrum_zcash.bitcoin import base_decode, is_address
     data = data.strip()
     if is_address(data):
         self.set_URI(data)
         return
     if data.startswith('ciphscoin:'):
         self.set_URI(data)
         return
     # try to decode transaction
     from electrum_zcash.transaction import Transaction
     from electrum_zcash.util import bh2u
     try:
         text = bh2u(base_decode(data, None, base=43))
         tx = Transaction(text)
         tx.deserialize()
     except:
         tx = None
     if tx:
         self.tx_dialog(tx)
         return
     # show error
     self.show_error("Unable to decode QR data")
Beispiel #14
0
 def update(self, window):
     wallet = window.wallet
     if type(wallet) != Multisig_Wallet:
         return
     if self.listener is None:
         self.print_error("starting listener")
         self.listener = Listener(self)
         self.listener.start()
     elif self.listener:
         self.print_error("shutting down listener")
         self.listener.stop()
         self.listener = None
     self.keys = []
     self.cosigner_list = []
     for key, keystore in wallet.keystores.items():
         xpub = keystore.get_master_public_key()
         K = bitcoin.deserialize_xpub(xpub)[-1]
         _hash = bh2u(bitcoin.Hash(K))
         if not keystore.is_watching_only():
             self.keys.append((key, _hash, window))
         else:
             self.cosigner_list.append((window, xpub, K, _hash))
     if self.listener:
         self.listener.set_keyhashes([t[1] for t in self.keys])
Beispiel #15
0
    def sign_transaction(self, tx, password):
        if tx.is_complete():
            return
        client = self.get_client()
        inputs = []
        inputsPaths = []
        pubKeys = []
        chipInputs = []
        redeemScripts = []
        signatures = []
        preparedTrustedInputs = []
        changePath = ""
        changeAmount = None
        output = None
        outputAmount = None
        p2shTransaction = False
        pin = ""
        self.get_client(
        )  # prompt for the PIN before displaying the dialog if necessary

        if tx.overwintered:
            if not self.get_client_electrum().supports_overwinter():
                self.give_error(MSG_NEEDS_FW_UPDATE_OVERWINTER)
        # Fetch inputs of the transaction to sign
        derivations = self.get_tx_derivations(tx)
        for txin in tx.inputs():
            if txin['type'] == 'coinbase':
                self.give_error(
                    "Coinbase not supported")  # should never happen

            if txin['type'] in ['p2sh']:
                p2shTransaction = True

            pubkeys, x_pubkeys = tx.get_sorted_pubkeys(txin)
            for i, x_pubkey in enumerate(x_pubkeys):
                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

            redeemScript = Transaction.get_preimage_script(txin)
            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))
            inputs.append([
                txin['prev_tx'].raw, txin['prevout_n'], redeemScript,
                txin['prevout_hash'], signingPos,
                txin.get('sequence', 0xffffffff - 1)
            ])
            inputsPaths.append(hwAddress)
            pubKeys.append(pubkeys)

        # Sanity check
        if p2shTransaction:
            for txin in tx.inputs():
                if txin['type'] != 'p2sh':
                    self.give_error(
                        "P2SH / regular input mixed in same transaction not supported"
                    )  # should never happen

        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)
            txOutput += var_int(len(script) // 2)
            txOutput += script
        txOutput = bfh(txOutput)

        # Recognize outputs - only one output and one change is authorized
        if not p2shTransaction:
            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")
            for _type, address, amount in tx.outputs():
                assert _type == TYPE_ADDRESS
                info = tx.output_info.get(address)
                if (info is not None) and len(tx.outputs()) > 1 \
                        and info[0][0] == 1:  # "is on 'change' branch"
                    index, xpubs, m = info
                    changePath = self.get_derivation()[2:] + "/%d/%d" % index
                    changeAmount = amount
                else:
                    output = address
                    if not self.get_client_electrum().canAlternateCoinVersions:
                        v, h = b58_address_to_hash160(address)
                        if v == constants.net.ADDRTYPE_P2PKH:
                            output = hash160_to_b58_address(h, 0)
                    outputAmount = amount

        self.handler.show_message(
            _("Confirm Transaction on your Ledger device..."))
        try:
            # Get trusted inputs from the original transactions
            for utxo in inputs:
                sequence = int_to_hex(utxo[5], 4)
                if tx.overwintered:
                    txtmp = zcashTransaction(bfh(utxo[0]))
                    tmp = bfh(utxo[3])[::-1]
                    tmp += bfh(int_to_hex(utxo[1], 4))
                    tmp += txtmp.outputs[utxo[1]].amount
                    chipInputs.append({'value': tmp, 'sequence': sequence})
                    redeemScripts.append(bfh(utxo[2]))
                elif not p2shTransaction:
                    txtmp = zcashTransaction(bfh(utxo[0]))
                    trustedInput = self.get_client().getTrustedInput(
                        txtmp, utxo[1])
                    trustedInput['sequence'] = sequence
                    chipInputs.append(trustedInput)
                    redeemScripts.append(txtmp.outputs[utxo[1]].script)
                else:
                    tmp = bfh(utxo[3])[::-1]
                    tmp += bfh(int_to_hex(utxo[1], 4))
                    chipInputs.append({'value': tmp, 'sequence': sequence})
                    redeemScripts.append(bfh(utxo[2]))

            # Sign all inputs
            firstTransaction = True
            inputIndex = 0
            rawTx = tx.serialize()
            self.get_client().enableAlternate2fa(False)
            if tx.overwintered:
                self.get_client().startUntrustedTransaction(
                    True,
                    inputIndex,
                    chipInputs,
                    redeemScripts[inputIndex],
                    version=tx.version,
                    overwintered=tx.overwintered)
                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)

                if tx.overwintered:
                    inputSignature = self.get_client().untrustedHashSign(
                        '',
                        pin,
                        lockTime=tx.locktime,
                        overwintered=tx.overwintered)
                outputData['outputData'] = txOutput
                transactionOutput = outputData['outputData']
                if outputData['confirmationNeeded']:
                    outputData['address'] = output
                    self.handler.finished()
                    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..."))
                while inputIndex < len(inputs):
                    singleInput = [chipInputs[inputIndex]]
                    self.get_client().startUntrustedTransaction(
                        False,
                        0,
                        singleInput,
                        redeemScripts[inputIndex],
                        version=tx.version,
                        overwintered=tx.overwintered)
                    inputSignature = self.get_client().untrustedHashSign(
                        inputsPaths[inputIndex],
                        pin,
                        lockTime=tx.locktime,
                        overwintered=tx.overwintered)
                    inputSignature[0] = 0x30  # force for 1.4.9+
                    signatures.append(inputSignature)
                    inputIndex = inputIndex + 1
            else:
                while inputIndex < len(inputs):
                    self.get_client().startUntrustedTransaction(
                        firstTransaction, inputIndex, chipInputs,
                        redeemScripts[inputIndex])
                    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)
                    outputData['outputData'] = txOutput
                    if firstTransaction:
                        transactionOutput = outputData['outputData']
                    if outputData['confirmationNeeded']:
                        outputData['address'] = output
                        self.handler.finished()
                        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..."))
                    else:
                        # Sign input with the provided PIN
                        inputSignature = self.get_client().untrustedHashSign(
                            inputsPaths[inputIndex], pin, lockTime=tx.locktime)
                        inputSignature[0] = 0x30  # force for 1.4.9+
                        signatures.append(inputSignature)
                        inputIndex = inputIndex + 1
                    if pin != 'paired':
                        firstTransaction = False
        except UserWarning:
            self.handler.show_error(_('Cancelled by user'))
            return
        except BTChipException as e:
            if e.sw == 0x6985:  # cancelled by user
                return
            else:
                traceback.print_exc(file=sys.stderr)
                self.give_error(e, True)
        except BaseException as e:
            traceback.print_exc(file=sys.stdout)
            self.give_error(e, True)
        finally:
            self.handler.finished()

        for i, txin in enumerate(tx.inputs()):
            signingPos = inputs[i][4]
            txin['signatures'][signingPos] = bh2u(signatures[i])
        tx.raw = tx.serialize()