Ejemplo n.º 1
0
def is_valid_variable_value(value, variable_type):
    """Returns whether value is valid."""
    if variable_type == "address":
        v = format_hex_string(value, with_prefix=False)
        if len(v) == 40:
            return True
    return False
Ejemplo n.º 2
0
    def __init__(self, value, template=''):
        super(ScriptTemplateItem, self).__init__(value)
        self.template = template
        # Populate variables dict.
        variables = {}
        iterator = self.value.human_iter()
        text = self.template.text.split()
        index = 0
        while 1:
            try:
                s = next(iterator)
                txt = text[index]
                if txt.startswith('<') and txt.endswith('>'):
                    variables[txt[1:-1]] = s
                index += 1
            except Exception:
                break
        self.variables = variables

        # Actions for copying all variables.
        for k, v in self.variables.items():
            # Special case for scripts.
            # Two actions: Copy X and Copy X (hex)
            if self.template.variables[k] == 'script':
                scr = Script(format_hex_string(v, with_prefix=False).decode('hex'))
                label = ' '.join(['Copy', k])
                self.add_copy_action(label, scr.get_human())
                k = ' '.join([k, '(hex)'])
            label = ' '.join(['Copy', k])
            self.add_copy_action(label, v)
Ejemplo n.º 3
0
    def __init__(self, value, template=''):
        super(ScriptTemplateItem, self).__init__(value)
        self.template = template
        # Populate variables dict.
        variables = {}
        iterator = self.value.human_iter()
        text = self.template.text.split()
        index = 0
        while 1:
            try:
                s = next(iterator)
                txt = text[index]
                if txt.startswith('<') and txt.endswith('>'):
                    variables[txt[1:-1]] = s
                index += 1
            except Exception:
                break
        self.variables = variables

        # Actions for copying all variables.
        for k, v in self.variables.items():
            # Special case for scripts.
            # Two actions: Copy X and Copy X (hex)
            if self.template.variables[k] == 'script':
                scr = Script(
                    format_hex_string(v, with_prefix=False).decode('hex'))
                label = ' '.join(['Copy', k])
                self.add_copy_action(label, scr.get_human())
                k = ' '.join([k, '(hex)'])
            label = ' '.join(['Copy', k])
            self.add_copy_action(label, v)
Ejemplo n.º 4
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)))
Ejemplo n.º 5
0
 def test_format_hex_string(self):
     format_tests = (
         ('0x0', True, '0x00'),
         ('0x0', False, '00'),
         ('ff', True, '0xff'),
         ('ff', False, 'ff'),
         ('0x000', True, '0x0000'),
         ('0x000', False, '0000'),
     )
     for value, with_prefix, expected in format_tests:
         self.assertEqual(expected, utils.format_hex_string(value, with_prefix=with_prefix))
Ejemplo n.º 6
0
    def get_private_key(self):
        """Attempt to parse the private key that was input."""
        txt = str(self.privkey_edit.text())
        privkey = None
        if is_hex(txt):
            txt = format_hex_string(txt, with_prefix=False)

        try:
            privkey = CBitcoinSecret.from_secret_bytes(x(txt))
        except Exception:
            pass

        return privkey
Ejemplo n.º 7
0
    def encode_data(self):
        payload = str(self.payload_edit.toPlainText())
        if not payload:
            self.error('No data was input.')

        if is_hex(payload):
            payload = format_hex_string(payload, with_prefix=False).decode('hex')

        try:
            msg = base58.encode(payload)
            self.encoded_edit.setPlainText(msg)
        except Exception as e:
            self.error(str(e))
Ejemplo n.º 8
0
 def test_format_hex_string(self):
     format_tests = (
         ('0x0', True, '0x00'),
         ('0x0', False, '00'),
         ('ff', True, '0xff'),
         ('ff', False, 'ff'),
         ('0x000', True, '0x0000'),
         ('0x000', False, '0000'),
     )
     for value, with_prefix, expected in format_tests:
         self.assertEqual(
             expected,
             utils.format_hex_string(value, with_prefix=with_prefix))
Ejemplo n.º 9
0
    def get_private_key(self):
        """Attempt to parse the private key that was input."""
        txt = str(self.privkey_edit.text())
        privkey = None
        if is_hex(txt):
            txt = format_hex_string(txt, with_prefix=False)

        try:
            privkey = CBitcoinSecret.from_secret_bytes(x(txt))
        except Exception:
            pass

        return privkey
Ejemplo n.º 10
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')
Ejemplo n.º 11
0
def format_variable_value(value, var_type):
    """Returns a 2-tuple of (is_valid, formatted_value)."""
    if var_type == 'address':
        try:
            h160 = CBase58Data(value).to_bytes()
        except Exception:
            # Check if value is a hash160.
            if is_hex(value) and len(
                    format_hex_string(value, with_prefix=False)) == 40:
                h160 = format_hex_string(value,
                                         with_prefix=False).decode('hex')
            else:
                return False, 'Error: Could not decode address.'
        return True, '0x' + h160.encode('hex')
    elif var_type == 'pubkey':
        if not is_hex(value):
            return False, 'Error: Pubkey must be hex.'
        key_hex = format_hex_string(value, with_prefix=False)
        pub = CPubKey(key_hex.decode('hex'))
        if not pub.is_fullyvalid:
            return False, 'Error: Pubkey is invalid.'
        return True, '0x' + key_hex
    elif var_type == 'text':
        try:
            return True, '0x' + value.encode('hex')
        except Exception as e:
            return False, 'Error: ' + str(e)
    elif var_type == 'signature':
        if not is_hex(value):
            return False, 'Error: Signature must be hex.'
        # We remain algorithm-agnostic by not checking the length.
        return True, format_hex_string(value, with_prefix=True)
    elif var_type == 'script':
        if not is_hex(value):
            try:
                scr = Script.from_human(value)
                return True, format_hex_string(scr.get_hex(), with_prefix=True)
            except Exception:
                return False, 'Error: Cannot parse human-readable script.'
        try:
            scr = Script(
                format_hex_string(value, with_prefix=False).decode('hex'))
            return True, format_hex_string(value, with_prefix=True)
        except Exception:
            return False, 'Error: Cannot parse script.'

    return True, value
Ejemplo n.º 12
0
def format_variable_value(value, var_type):
    """Returns a 2-tuple of (is_valid, formatted_value)."""
    if var_type == 'address':
        try:
            h160 = CBase58Data(value).to_bytes()
        except Exception:
            # Check if value is a hash160.
            if is_hex(value) and len(format_hex_string(value, with_prefix=False)) == 40:
                h160 = format_hex_string(value, with_prefix=False).decode('hex')
            else:
                return False, 'Error: Could not decode address.'
        return True, '0x' + h160.encode('hex')
    elif var_type == 'pubkey':
        if not is_hex(value):
            return False, 'Error: Pubkey must be hex.'
        key_hex = format_hex_string(value, with_prefix=False)
        pub = CPubKey(key_hex.decode('hex'))
        if not pub.is_fullyvalid:
            return False, 'Error: Pubkey is invalid.'
        return True, '0x' + key_hex
    elif var_type == 'text':
        try:
            return True, '0x' + value.encode('hex')
        except Exception as e:
            return False, 'Error: ' + str(e)
    elif var_type == 'signature':
        if not is_hex(value):
            return False, 'Error: Signature must be hex.'
        # We remain algorithm-agnostic by not checking the length.
        return True, format_hex_string(value, with_prefix=True)
    elif var_type == 'script':
        if not is_hex(value):
            try:
                scr = Script.from_human(value)
                return True, format_hex_string(scr.get_hex(), with_prefix=True)
            except Exception:
                return False, 'Error: Cannot parse human-readable script.'
        try:
            scr = Script(format_hex_string(value, with_prefix=False).decode('hex'))
            return True, format_hex_string(value, with_prefix=True)
        except Exception:
            return False, 'Error: Cannot parse script.'

    return True, value
Ejemplo n.º 13
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)))