Exemple #1
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
 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)
Exemple #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)
Exemple #4
0
 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))
Exemple #5
0
 def update(self, window):
     wallet = window.wallet
     if type(wallet) != Multisig_Wallet:
         return
     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()
         pubkey = BIP32Node.from_xkey(xpub).eckey.get_public_key_bytes(compressed=True)
         _hash = bh2u(crypto.sha256d(pubkey))
         self.logger.info(_hash)
         if not keystore.is_watching_only():
             self.keys.append((key, _hash, window))
             server.xpub(_hash)
         else:
             self.cosigner_list.append((window, xpub, pubkey, _hash))
             server.cosigners().append(_hash)
     for key in self.keys:
         self.logger.info(f'xpub: {key[1]}')
     for cosigner in self.cosigner_list:
         self.logger.info(f'cosigners: {cosigner[3]}')
     self.wallet_hash = server.wallet_hash()
     self.logger.info(self.wallet_hash)
     if self.listener:
         self.listener.set_keyhashes([t[1] for t in self.keys])
         self.listener.set_wallet_hash(self.wallet_hash)
Exemple #6
0
 def update(self, window):
     wallet = window.wallet
     self.window = window
     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 = bip32.deserialize_xpub(xpub)[-1]
         _hash = bh2u(crypto.sha256d(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])
Exemple #7
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())
Exemple #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)
     outputs = self.tx_outputs(keystore.get_derivation(), tx)
     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)
 def sign_transaction(self, keystore, tx, prev_tx, xpub_path):
     prev_tx = {
         bfh(txhash): self.electrum_tx_to_txtype(tx, xpub_path)
         for txhash, tx in prev_tx.items()
     }
     client = self.get_client(keystore)
     inputs = self.tx_inputs(tx, xpub_path, True)
     outputs = self.tx_outputs(keystore.get_derivation(), tx)
     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)
Exemple #10
0
    def sign_transaction(self, tx, password):
        # Build a PSBT in memory, upload it for signing.
        # - we can also work offline (without paired device present)
        if tx.is_complete():
            return

        client = self.get_client()

        assert client.dev.master_fingerprint == self.ckcc_xfp

        raw_psbt = self.build_psbt(tx)

        #open('debug.psbt', 'wb').write(out_fd.getvalue())

        try:
            try:
                self.handler.show_message("Authorize Transaction...")

                client.sign_transaction_start(raw_psbt, True)

                while 1:
                    # How to kill some time, without locking UI?
                    time.sleep(0.250)

                    resp = client.sign_transaction_poll()
                    if resp is not None:
                        break

                rlen, rsha = resp

                # download the resulting txn.
                new_raw = client.download_file(rlen, rsha)

            finally:
                self.handler.finished()

        except (CCUserRefused, CCBusyError) as exc:
            self.logger.info(f'Did not sign: {exc}')
            self.handler.show_error(str(exc))
            return
        except BaseException as e:
            self.logger.exception('')
            self.give_error(e, True)
            return

        # trust the coldcard to re-searilize final product right?
        tx.update(bh2u(new_raw))
 def test_push_script(self):
     # https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#push-operators
     self.assertEqual(push_script(''), bh2u(bytes([opcodes.OP_0])))
     self.assertEqual(push_script('07'), bh2u(bytes([opcodes.OP_7])))
     self.assertEqual(push_script('10'), bh2u(bytes([opcodes.OP_16])))
     self.assertEqual(push_script('81'), bh2u(bytes([opcodes.OP_1NEGATE])))
     self.assertEqual(push_script('11'), '0111')
     self.assertEqual(push_script(75 * '42'), '4b' + 75 * '42')
     self.assertEqual(
         push_script(76 * '42'),
         bh2u(bytes([opcodes.OP_PUSHDATA1]) + bfh('4c' + 76 * '42')))
     self.assertEqual(
         push_script(100 * '42'),
         bh2u(bytes([opcodes.OP_PUSHDATA1]) + bfh('64' + 100 * '42')))
     self.assertEqual(
         push_script(255 * '42'),
         bh2u(bytes([opcodes.OP_PUSHDATA1]) + bfh('ff' + 255 * '42')))
     self.assertEqual(
         push_script(256 * '42'),
         bh2u(bytes([opcodes.OP_PUSHDATA2]) + bfh('0001' + 256 * '42')))
     self.assertEqual(
         push_script(520 * '42'),
         bh2u(bytes([opcodes.OP_PUSHDATA2]) + bfh('0802' + 520 * '42')))
Exemple #12
0
    def test_compact_size(self):
        s = transaction.BCDataStream()
        values = [
            0, 1, 252, 253, 2**16 - 1, 2**16, 2**32 - 1, 2**32, 2**64 - 1
        ]
        for v in values:
            s.write_compact_size(v)

        with self.assertRaises(transaction.SerializationError):
            s.write_compact_size(-1)

        self.assertEqual(
            bh2u(s.input),
            '0001fcfdfd00fdfffffe00000100feffffffffff0000000001000000ffffffffffffffffff'
        )
        for v in values:
            self.assertEqual(s.read_compact_size(), v)

        with self.assertRaises(transaction.SerializationError):
            s.read_compact_size()
 def on_qr(self, data):
     from electrum_exos.bitcoin import base_decode, is_address
     data = data.strip()
     if is_address(data):
         self.set_URI(data)
         return
     if data.startswith('exos:'):
         self.set_URI(data)
         return
     # try to decode transaction
     from electrum_exos.transaction import Transaction
     from electrum_exos.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")
Exemple #14
0
    def __init__(self, tx, parent, desc, prompt_if_unsaved):
        '''Transactions in the wallet will show their description.
        Pass desc to give a description for txs not yet in the wallet.
        '''
        # We want to be a top-level window
        QDialog.__init__(self, parent=None)
        # Take a copy; it might get updated in the main window by
        # e.g. the FX plugin.  If this happens during or after a long
        # sign operation the signatures are lost.
        self.tx = tx = copy.deepcopy(tx)  # type: Transaction

        try:
            self.tx.deserialize()
        except BaseException as e:
            raise SerializationError(e)
        self.main_window = parent
        self.wallet = parent.wallet
        self.prompt_if_unsaved = prompt_if_unsaved
        self.saved = False
        self.desc = desc

        # store the keyhash and cosigners for current wallet
        self.keyhashes = set()
        self.cosigner_list = set()
        if type(self.wallet) == Multisig_Wallet:
            for key, keystore in self.wallet.keystores.items():
                xpub = keystore.get_master_public_key()
                K = bip32.deserialize_xpub(xpub)[-1]
                _hash = bh2u(crypto.sha256d(K))
                if not keystore.is_watching_only():
                    self.keyhashes.add(_hash)
                else:
                    self.cosigner_list.add(_hash)

        # if the wallet can populate the inputs with more info, do it now.
        # as a result, e.g. we might learn an imported address tx is segwit,
        # in which case it's ok to display txid
        tx.add_inputs_info(self.wallet)

        self.setMinimumWidth(950)
        self.setWindowTitle(_("Transaction"))

        vbox = QVBoxLayout()
        self.setLayout(vbox)

        vbox.addWidget(QLabel(_("Transaction ID:")))
        self.tx_hash_e = ButtonsLineEdit()
        qr_show = lambda: parent.show_qrcode(
            str(self.tx_hash_e.text()), 'Transaction ID', parent=self)
        qr_icon = "qrcode_white.png" if ColorScheme.dark_scheme else "qrcode.png"
        self.tx_hash_e.addButton(qr_icon, qr_show, _("Show as QR code"))
        self.tx_hash_e.setReadOnly(True)
        vbox.addWidget(self.tx_hash_e)
        self.tx_desc = QLabel()
        vbox.addWidget(self.tx_desc)
        self.status_label = QLabel()
        vbox.addWidget(self.status_label)
        self.date_label = QLabel()
        vbox.addWidget(self.date_label)
        self.amount_label = QLabel()
        vbox.addWidget(self.amount_label)
        self.size_label = QLabel()
        vbox.addWidget(self.size_label)
        self.fee_label = QLabel()
        vbox.addWidget(self.fee_label)

        self.add_io(vbox)

        self.sign_button = b = QPushButton(_("Sign"))
        b.clicked.connect(self.sign)

        self.broadcast_button = b = QPushButton(_("Broadcast"))
        b.clicked.connect(self.do_broadcast)

        self.save_button = b = QPushButton(_("Save"))
        save_button_disabled = not tx.is_complete()
        b.setDisabled(save_button_disabled)
        if save_button_disabled:
            b.setToolTip(SAVE_BUTTON_DISABLED_TOOLTIP)
        else:
            b.setToolTip(SAVE_BUTTON_ENABLED_TOOLTIP)
        b.clicked.connect(self.save)

        self.export_button = b = QPushButton(_("Export"))
        b.clicked.connect(self.export)

        self.cancel_button = b = QPushButton(_("Close"))
        b.clicked.connect(self.close)
        b.setDefault(True)

        self.qr_button = b = QPushButton()
        b.setIcon(read_QIcon(qr_icon))
        b.clicked.connect(self.show_qr)

        self.copy_button = CopyButton(lambda: str(self.tx), parent.app)

        # Action buttons
        self.buttons = [
            self.sign_button, self.broadcast_button, self.cancel_button
        ]
        # Transaction sharing buttons
        self.sharing_buttons = [
            self.copy_button, self.qr_button, self.export_button,
            self.save_button
        ]

        run_hook('transaction_dialog', self)

        hbox = QHBoxLayout()
        hbox.addLayout(Buttons(*self.sharing_buttons))
        hbox.addStretch(1)
        hbox.addLayout(Buttons(*self.buttons))
        vbox.addLayout(hbox)
        self.update()
    def sign_transaction(self, tx, password):
        if tx.is_complete():
            return
        client = self.get_client()
        inputs = []
        inputsPaths = []
        pubKeys = []
        chipInputs = []
        redeemScripts = []
        signatures = []
        changePath = ""
        output = None
        p2shTransaction = False
        segwitTransaction = False
        pin = ""
        self.get_client(
        )  # prompt for the PIN before displaying the dialog if necessary

        # 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

            if txin['type'] in ['p2wpkh-p2sh', 'p2wsh-p2sh']:
                if not self.get_client_electrum().supports_segwit():
                    self.give_error(MSG_NEEDS_FW_UPDATE_SEGWIT)
                segwitTransaction = True

            if txin['type'] in ['p2wpkh', 'p2wsh']:
                if not self.get_client_electrum().supports_native_segwit():
                    self.give_error(MSG_NEEDS_FW_UPDATE_SEGWIT)
                segwitTransaction = 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)
            txin_prev_tx = txin.get('prev_tx')
            if txin_prev_tx is None and not Transaction.is_segwit_input(txin):
                raise UserFacingException(
                    _('Offline signing with {} is not supported for legacy inputs.'
                      ).format(self.device))
            txin_prev_tx_raw = txin_prev_tx.raw if txin_prev_tx else None
            inputs.append([
                txin_prev_tx_raw, txin['prevout_n'], redeemScript,
                txin['prevout_hash'], signingPos,
                txin.get('sequence', 0xffffffff - 1),
                txin.get('value')
            ])
            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 o in tx.outputs():
            output_type, addr, amount = o.type, o.address, o.value
            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 (for hw.1 and nano)
        # - at most one output can bypass confirmation (~change) (for all)
        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")
            has_change = False
            any_output_on_change_branch = is_any_tx_output_on_change_branch(tx)
            for o in tx.outputs():
                assert o.type == TYPE_ADDRESS
                info = tx.output_info.get(o.address)
                if (info is not None) and len(tx.outputs()) > 1 \
                        and not has_change:
                    index = info.address_index
                    on_change_branch = index[0] == 1
                    # prioritise hiding outputs on the 'change' branch from user
                    # because no more than one change address allowed
                    if on_change_branch == any_output_on_change_branch:
                        changePath = self.get_derivation(
                        )[2:] + "/%d/%d" % index
                        has_change = True
                    else:
                        output = o.address
                else:
                    output = o.address

        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 segwitTransaction:
                    tmp = bfh(utxo[3])[::-1]
                    tmp += bfh(int_to_hex(utxo[1], 4))
                    tmp += bfh(int_to_hex(utxo[6], 8))  # txin['value']
                    chipInputs.append({
                        'value': tmp,
                        'witness': True,
                        'sequence': sequence
                    })
                    redeemScripts.append(bfh(utxo[2]))
                elif not p2shTransaction:
                    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)
                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_to_network()
            self.get_client().enableAlternate2fa(False)
            if segwitTransaction:
                self.get_client().startUntrustedTransaction(
                    True,
                    inputIndex,
                    chipInputs,
                    redeemScripts[inputIndex],
                    version=tx.version)
                # 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))
                outputData['outputData'] = txOutput
                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)
                    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
            else:
                while inputIndex < len(inputs):
                    self.get_client().startUntrustedTransaction(
                        firstTransaction,
                        inputIndex,
                        chipInputs,
                        redeemScripts[inputIndex],
                        version=tx.version)
                    # 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))
                    outputData['outputData'] = txOutput
                    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
            elif e.sw == 0x6982:
                raise  # pin lock. decorator will catch it
            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]
            tx.add_signature_to_txin(i, signingPos, bh2u(signatures[i]))
        tx.raw = tx.serialize()
    def __init__(self, tx, parent, desc, prompt_if_unsaved):
        '''Transactions in the wallet will show their description.
        Pass desc to give a description for txs not yet in the wallet.
        '''
        # We want to be a top-level window
        QDialog.__init__(self, parent=None)

        self.tx = tx = copy.deepcopy(tx)  # type: Transaction
        try:
            self.tx.deserialize()
        except BaseException as e:
            raise SerializationError(e)
        self.main_window = parent
        self.wallet = parent.wallet
        self.prompt_if_unsaved = prompt_if_unsaved
        self.saved = False
        self.desc = desc
        self.locks = {}
        self.currently_signing = None

        # Set timeout flag
        self.timed_out = False

        self.main_window = parent
        self.wallet = parent.wallet

        # store the keyhash and cosigners for current wallet
        self.keyhashes = set()
        self.cosigner_list = set()
        if type(self.wallet) == Multisig_Wallet:
            for key, keystore in self.wallet.keystores.items():
                xpub = keystore.get_master_public_key()
                pubkey = BIP32Node.from_xkey(xpub).eckey.get_public_key_bytes(
                    compressed=True)
                _hash = bh2u(crypto.sha256d(pubkey))
                if not keystore.is_watching_only():
                    self.keyhashes.add(_hash)
                else:
                    self.cosigner_list.add(_hash)
                    self.locks[_hash] = server.get(_hash + '_lock')
                    if self.locks[_hash]:
                        name = server.get(_hash + '_name')
                        if name:
                            self.currently_signing = name

        self.setMinimumWidth(200)
        self.setWindowTitle(_("Information"))

        vbox = QVBoxLayout()
        self.setLayout(vbox)
        self.warning = QLabel()
        vbox.addWidget(self.warning)
        warning_text = (_(
            'A transaction with the following information is currently being signed'
        ) + '\n' + _(
            'by a cosigner. A notification will appear within 30 seconds of either signing'
        ) + '\n' + _('or the transaction window expiring.'))
        self.warning.setText(warning_text)
        self.tx_desc = QLabel()
        vbox.addWidget(self.tx_desc)
        self.status_label = QLabel()
        vbox.addWidget(self.status_label)
        self.date_label = QLabel()
        vbox.addWidget(self.date_label)
        self.amount_label = QLabel()
        vbox.addWidget(self.amount_label)
        self.size_label = QLabel()
        vbox.addWidget(self.size_label)
        self.fee_label = QLabel()
        vbox.addWidget(self.fee_label)

        self.cancel_button = b = QPushButton(_("Close"))
        b.clicked.connect(self.close)
        b.setDefault(True)

        # Action buttons
        self.buttons = [self.cancel_button]

        # Add label for countdown timer
        self.time_out_label = QLabel()
        vbox.addWidget(self.time_out_label)

        run_hook('transaction_dialog', self)

        hbox = QHBoxLayout()
        hbox.addLayout(Buttons(*self.buttons))
        vbox.addLayout(hbox)

        self.time_left_int = int(DURATION_INT)
        for _hash, expire in self.locks.items():
            if expire:
                # Set time left to desired duration
                self.time_left_int = int(DURATION_INT -
                                         (int(server.get_current_time()) -
                                          int(expire)))

        self.timer_start()
        self.update()
Exemple #17
0
    def on_receive(self, keyhash, data):
        self.logger.info(f"signal arrived for {keyhash}")
        for key, _hash, window in self.keys:
            if _hash == keyhash:
                break
        else:
            self.logger.info("keyhash not found")
            return

        # convert data from string to json
        data = json.loads(data)

        signed = data.get('signed')
        txs = data.get('txs')

        # invalid JSON structure
        if not signed or not txs:
            self.logger.info("cosigner data malformed, missing entry")
            return
        
        # check if user has signed
        if keyhash in signed:
            self.logger.info("user has already signed")
            return

        message = txs[keyhash]

        wallet = window.wallet
        if isinstance(wallet.keystore, keystore.Hardware_KeyStore):
            window.show_warning(_('An encrypted transaction was retrieved from cosigning pool.') + '\n' +
                                _('However, hardware wallets do not support message decryption, '
                                  'which makes them not compatible with the current design of cosigner pool.'))
            return
        elif wallet.has_keystore_encryption():
            password = window.password_dialog(str(datetime.datetime.now().strftime("%a, %d %b %Y %H:%M:%S") + '\n\n' +
                                              _('An encrypted transaction was retrieved from cosigning pool.') + '\n' +
                                              _('Please enter your password to decrypt it. ')), parent=None)
            if not password:
                return
        else:
            password = None
            if not window.question(_("An encrypted transaction was retrieved from cosigning pool.") + '\n' +
                                   _("Do you want to open it now?")):
                return

        xprv = None
        try:
            xprv = wallet.keystore.get_master_private_key(password)
            if not xprv:
                return
        except InvalidPassword as e:
            self.logger.info("Incorrect Password")
            window.show_error(_("Incorrect Password"))
            return

        try:
            privkey = BIP32Node.from_xkey(xprv).eckey
            message = bh2u(privkey.decrypt_message(message))
        except Exception as e:
            self.logger.exception('')
            window.show_error(_('Error decrypting message') + ':\n' + str(e))
            return

        tx = transaction.Transaction(message)

        def calculate_wait_time(expire):
            # calculate wait time
            server_time = server.get_current_time()
            mins, secs = 0, 0
            if server_time is not None:
                wait_time = int((WAIT_TIME - (int(server_time) - int(expire))))
                mins, secs = divmod(wait_time, 60)
            return '{:02d}:{:02d}'.format(mins, secs)

        # check if lock has been placed for wallet
        lock = server.lock
        if lock:
            # calculate wait time based on lock expiry and server time
            timeformat = calculate_wait_time(lock['timestamp'])
            # display pop up
            window.show_warning(_("A cosigner is currently signing the transaction.") + '\n' +
                                _("Please wait {} until the signing has concluded.".format(timeformat)))

            xpub = lock['xpub']
            name = None
            try:
                name = server.get(xpub+'_name')
            except Exception as e:
                self.logger.exception(e)
                self.logger.error("Failed to get cosigner name from server")
            show_timeout_wait_dialog(tx, xpub, name, window, prompt_if_unsaved=True)
            return
        else:
            buffer = {'timestamp' : '', 'xpub' : ''}
            buffer['timestamp'] = str(server.get_current_time())
            buffer['xpub'] = keyhash
            server.lock = buffer
            time_until_expired = '10 minutes'

        window.show_warning(_("You have {} to conclude signing after which the dialog will".format(time_until_expired)) + '\n' +
                            _("automatically close."), parent=None)
            
        self.listener.clear(keyhash)
        show_transaction_timeout(tx, signed, window, prompt_if_unsaved=True)
Exemple #18
0
    def on_receive(self, keyhash, message):
        self.logger.info(f"signal arrived for {keyhash}")

        WAIT_TIME = 10 * 60

        if self.suppress_notifications:
            for window, xpub, K, _hash in self.cosigner_list:
                if server.get(_hash + '_lock'):
                    return
            self.suppress_notifications = False

        for key, _hash, window in self.keys:
            if _hash == keyhash:
                break
        else:
            self.logger.info("keyhash not found")
            return

        wallet = window.wallet
        if isinstance(wallet.keystore, keystore.Hardware_KeyStore):
            window.show_warning(
                _('An encrypted transaction was retrieved from cosigning pool.'
                  ) + '\n' +
                _('However, hardware wallets do not support message decryption, '
                  'which makes them not compatible with the current design of cosigner pool.'
                  ))
            return
        elif wallet.has_keystore_encryption():
            # set pick to false when opening password dialog
            server.put(keyhash + '_pick', 'False')
            password = window.password_dialog(
                _('An encrypted transaction was retrieved from cosigning pool.'
                  ) + '\n' + _('Please enter your password to decrypt it.'))
            if not password:
                # set pick back to true if password incorrect or omitted
                server.put(keyhash + '_pick', 'True')
                return
        else:
            password = None
            if not window.question(
                    _("An encrypted transaction was retrieved from cosigning pool."
                      ) + '\n' + _("Do you want to open it now?")):
                return

        xprv = wallet.keystore.get_master_private_key(password)
        if not xprv:
            return
        try:
            privkey = BIP32Node.from_xkey(xprv).eckey
            message = bh2u(privkey.decrypt_message(message))
        except Exception as e:
            self.logger.exception('')
            window.show_error(_('Error decrypting message') + ':\n' + str(e))
            return

        #self.listener.clear(keyhash)
        tx = transaction.Transaction(message)

        def calculate_wait_time(expire):
            # calculate wait time
            wait_time = int(
                (WAIT_TIME - (int(server.get_current_time()) - int(expire))))
            mins, secs = divmod(wait_time, 60)
            return '{:02d}:{:02d}'.format(mins, secs)

        # check if lock has been placed for any wallets
        for window, xpub, K, _hash in self.cosigner_list:
            expire = server.get(_hash + '_lock')
            if expire:
                # set pick back to true if user lock is present
                server.put(keyhash + '_pick', 'True')
                # suppress any further notifications
                self.suppress_notifications = True
                # calculate wait time based on lock expiry and server time
                timeformat = calculate_wait_time(expire)

                # display pop up
                window.show_warning(
                    _("A cosigner is currently signing the transaction.") +
                    '\n' +
                    _("Please wait {} until the signing has concluded.".format(
                        timeformat)))

                show_timeout_wait_dialog(tx, window, prompt_if_unsaved=True)

                return

        # test if wallet has previously placed a lock
        current_wallet_lock = server.get(keyhash + '_lock')
        if not current_wallet_lock:
            # no lock has been placed for current wallet => lock transaction dialog
            server.put(keyhash + '_lock', str(server.get_current_time()))
            time_until_expired = '10 minutes'
        else:
            time_until_expired = calculate_wait_time(current_wallet_lock)

        # place flag to test for graceful shutdown
        server.put(keyhash + '_shutdown', 'up')
        window.show_warning(
            _("You have {} to conclude signing after which the dialog will".
              format(time_until_expired)) + '\n' + _("automatically close."))

        show_transaction_timeout(tx, window, prompt_if_unsaved=True)