Exemplo n.º 1
0
    def test_script_from_hex(self):
        s = Script('6a0105'.decode('hex'))
        self.assertEqual(s.get_human(), 'OP_RETURN 0x05')

        s = Script(
            '76a914000000000000000000000000000000000000000088ac'.decode('hex'))
        self.assertEqual(
            s.get_human(),
            'OP_DUP OP_HASH160 0x0000000000000000000000000000000000000000 OP_EQUALVERIFY OP_CHECKSIG'
        )
Exemplo n.º 2
0
    def test_script_from_hex_to_human(self):
        i = ScriptItem('6a0105', 'OP_RETURN 0x05')
        s = Script(i.hex.decode('hex'))
        self.assertEqual(s.get_human(), i.human)

        i = ScriptItem('6a01010131', 'OP_RETURN 0x01 "1"')
        s = Script(i.hex.decode('hex'))
        self.assertEqual(s.get_human(), i.human)

        i = ScriptItem(
            '76a914000000000000000000000000000000000000000088ac',
            'OP_DUP OP_HASH160 0x0000000000000000000000000000000000000000 OP_EQUALVERIFY OP_CHECKSIG'
        )
        s = Script(i.hex.decode('hex'))
        self.assertEqual(s.get_human(), i.human)
Exemplo n.º 3
0
    def setup_data(self, execution, parent):
        self.beginResetModel()
        for count, step in enumerate(execution.steps):
            step_item = TopLevelScriptItem((count, step.last_op, step.stack, step.log), parent)
            # Loop through stack items.
            scr = Script(step.stack).get_human().split()
            sub_level_item_data = []
            for i, data in enumerate(step.stack):
                human = scr[i]
                # Variable name
                if self.plugin_handler:
                    key = self.plugin_handler.get_plugin('Variables').ui.key_for_value(human, strict=False)
                    if key:
                        human = '$' + key

                stack_data = data
                try:
                    stack_data = stack_data.encode('hex')
                except Exception:
                    stack_data = str(stack_data)
                sub_level_item_data.append([i, '', stack_data, human])
            # Reverse items for a more visually-accurate stack.
            sub_level_item_data.reverse()
            for sub in sub_level_item_data:
                data_item = SubLevelScriptItem(sub, step_item)
                step_item.appendChild(data_item)
            parent.appendChild(step_item)
        self.endResetModel()
Exemplo n.º 4
0
def build_spending_tx(script_sig, credit_tx):
    tx = Transaction(version=1, locktime=0)
    txin = CMutableTxIn(CMutableOutPoint(credit_tx.GetHash(), 0), script_sig)
    tx.vin = [txin]
    txout = CMutableTxOut(0, Script())
    tx.vout = [txout]
    return tx
Exemplo n.º 5
0
 def __init__(self, parent=None):
     super(ScriptEdit, self).__init__(parent)
     self.current_format = 'Human'
     self.script = Script()
     self.textChanged.connect(self.on_text_changed)
     self.setFont(monospace_font)
     # For tooltips
     self.context = []
Exemplo n.º 6
0
 def add_input(self, i):
     in_script = Script(i.scriptSig)
     item = map(lambda x: QStandardItem(x),
                [str(i.prevout),
                 in_script.get_human(),
                 str(i.nSequence)])
     # Raw scriptSig is stored as RawRole.
     item[1].setData(QtCore.QVariant(in_script.get_hex()), RawRole)
     self.model.appendRow(item)
Exemplo n.º 7
0
 def add_output(self, o):
     out_script = Script(o.scriptPubKey)
     value = Amount(o.nValue)
     item = map(lambda x: QStandardItem(x),
                [value.get_str(), out_script.get_human()])
     # Value in satoshis is stored as RawRole.
     item[0].setData(QtCore.QVariant(value.satoshis), RawRole)
     # Raw scriptPubKey is stored as RawRole.
     item[1].setData(QtCore.QVariant(out_script.get_hex()), RawRole)
     self.model.appendRow(item)
Exemplo n.º 8
0
 def set_data(self, text, fmt):
     script = None
     if fmt == 'Hex' and len(text) % 2 == 0:
         try:
             script = Script(text.decode('hex'))
         except Exception:
             pass
     elif fmt == 'Human':
         txt, self.context = transform_human(text)
         script = Script.from_human(txt)
     self.script = script
Exemplo n.º 9
0
    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid() or not self.tx: return QVariant(None)
        if role not in [Qt.DisplayRole, Qt.ToolTipRole, Qt.EditRole, RawRole]:
            return None
        tx_input = self.tx.vin[index.row()]
        col = index.column()
        data = None
        if col == 0:
            data = b2lx(tx_input.prevout.hash)
        elif col == 1:
            data = tx_input.prevout.n
        elif col == 2:
            if role == RawRole:
                data = Script(tx_input.scriptSig).get_hex()
            else:
                data = Script(tx_input.scriptSig).get_human()
        elif col == 3:
            data = tx_input.nSequence

        return QVariant(data)
Exemplo n.º 10
0
    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid() or not self.vout: return QVariant(None)
        if role not in [Qt.DisplayRole, Qt.ToolTipRole, Qt.EditRole, RawRole]:
            return None
        tx_out = self.vout[index.row()]
        col = index.column()
        data = None
        if col == 0:
            if role in [Qt.EditRole, RawRole]:
                data = tx_out.nValue
            elif role in [Qt.ToolTipRole]:
                data = ' '.join([str(tx_out.nValue), 'satoshis'])
            else:
                data = self.format_amount(tx_out.nValue)
        elif col == 1:
            if role == RawRole:
                data = Script(tx_out.scriptPubKey).get_hex()
            else:
                data = Script(tx_out.scriptPubKey).get_human()

        return QVariant(data)
Exemplo n.º 11
0
 def get_outputs(self):
     vout = []
     for i in range(self.model.rowCount()):
         value, ok = self.model.item(i, 0).data(RawRole).toInt()
         if not ok:
             raise Exception('Could not get satoshis for output %d' % i)
             return
         out_script = Script(
             str(self.model.item(i,
                                 1).data(RawRole).toString()).decode('hex'))
         i_output = CTxOut(value, out_script.get_hex().decode('hex'))
         vout.append(i_output)
     return vout
Exemplo n.º 12
0
 def set_tx(self, tx):
     self.beginResetModel()
     self.inputs = []
     for i in tx.vin:
         hash_type = 0
         try:
             s = Script(i.scriptSig).get_human().split()[-2]
             # Loose sanity check to ensure the data is long enough.
             if len(s) >= 120:
                 hash_type = int(s[-2:], 16)
         except Exception:
             pass
         self.inputs.append([False, hash_type])
     self.endResetModel()
Exemplo n.º 13
0
    def __init__(self, data, parent=None):
        super(TopLevelScriptItem, self).__init__(data, parent)
        self.stack_data = Script(self.item_data[2]).get_human()
        # Convert log data representations to human-readable ones.
        log_data = self.item_data[3].split()
        for i, word in enumerate(log_data):
            # Try to put the data in human-readable form.
            try:
                hex_word = format_hex_string(word, with_prefix=False)
                if all(ord(c) < 128 and ord(c) > 31 for c in hex_word.decode('hex')):
                    log_data[i] = ''.join(['"', hex_word.decode('hex'), '"'])
            except Exception:
                pass
        self.log_data = ' '.join(log_data)

        self.op_name = opcodes.opcode_names.get(self.item_data[1], 'PUSHDATA')
Exemplo n.º 14
0
    def sign_transaction(self):
        """Sign the transaction."""
        script, txTo, inIdx, hash_type = self.model.get_fields()
        if inIdx >= len(txTo.vin):
            self.set_result_message('Nonexistent input specified for signing.',
                                    error=True)
            return
        if not script:
            self.set_result_message('Invalid output script.', error=True)
            return
        privkey = self.get_private_key()
        if not privkey:
            self.set_result_message('Could not parse private key.', error=True)
            return
        sig_hash = chainparams.signature_hash(script, txTo, inIdx, hash_type)

        sig = privkey.sign(sig_hash)
        hash_type_hex = format_hex_string(hex(hash_type),
                                          with_prefix=False).decode('hex')
        sig = sig + hash_type_hex
        txTo.vin[inIdx].scriptSig = Script([sig, privkey.pub])

        if self.verify_script.isChecked():
            # Try verify
            try:
                VerifyScript(txTo.vin[inIdx].scriptSig, script, txTo, inIdx,
                             (SCRIPT_VERIFY_P2SH, ))
            except Exception as e:
                self.set_result_message('Error when verifying: %s' % str(e),
                                        error=True)
                return

        self.dock.deserialize_raw(b2x(txTo.serialize()))
        # Deserializing a tx clears the model, so re-populate.
        self.model.set_fields(script=script.get_human(),
                              inIdx=inIdx,
                              hashType=hash_type)
        self.set_result_message(
            'Successfully set scriptSig for input %d (SigHash type: %s).' %
            (inIdx, sig_hash_name(hash_type)))
Exemplo n.º 15
0
 def test_compatibility_with_cscript(self):
     cs = CScript(['01'.decode('hex'), OP_DUP, OP_HASH160])
     s = Script(cs)
     self.assertEqual(s.get_human(), '0x01 OP_DUP OP_HASH160')
Exemplo n.º 16
0
 def __init__(self, *args):
     super(StackWidget, self).__init__(*args)
     self.setAlternatingRowColors(True)
     self.script = Script()