Example #1
0
def abe_parse_raw_tx(res):
    version = int(res.get('ver'))
    locktime = int(res.get('lock_time'))
    vin = []
    vout = []
    for i in res.get('in'):
        prev_txid = i['prev_out']['hash']
        prev_n = int(i['prev_out']['n'])
        tx_outpoint = COutPoint(lx(prev_txid), prev_n)

        scriptSig = Script(x( i['raw_scriptSig'] ))
        sequence = int(i['sequence'])
        
        tx_input = CTxIn(tx_outpoint, x(scriptSig.get_hex()), sequence)
        vin.append(tx_input)

    for o in res.get('out'):
        value = float(o['value'])
        value = int(value * pow(10, 8))

        script = Script(x( o['raw_scriptPubKey'] ))
        tx_output = CTxOut(value, x(script.get_hex()))
        vout.append(tx_output)

    tx = Transaction(vin, vout, locktime, version)
    return b2x(tx.serialize())
Example #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)
Example #3
0
def insight_parse_raw_tx(res):
    version = int(res.get('version'))
    locktime = int(res.get('locktime'))
    vin = []
    vout = []
    for i in res.get('vin'):
        prev_txid = i['txid']
        prev_n = int(i['n'])

        seq = int(i['sequence'])
        script_asm = i['scriptSig']['asm']
        script = Script.from_human(script_asm)

        tx_outpoint = COutPoint(lx(prev_txid), prev_n)
        tx_input = CTxIn(tx_outpoint, x(script.get_hex()), seq)
        vin.append(tx_input)

    for o in res.get('vout'):
        value = float(o['value'])
        value = int(value * pow(10, 8))

        script_asm = o['scriptPubKey']['asm']
        script = Script.from_human(script_asm)

        tx_output = CTxOut(value, x(script.get_hex()))
        vout.append(tx_output)

    tx = Transaction(vin, vout, locktime, version)
    return b2x(tx.serialize())
Example #4
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)
Example #5
0
    def test_is_template_script(self):
        template = self.templates['Pay-To-Public-Key-Hash Output']
        scr = Script.from_human('OP_DUP OP_HASH160 0x0000000000000000000000000000000000000000 OP_EQUALVERIFY OP_CHECKSIG')
        self.assertTrue(script_gen.is_template_script(scr, template))

        scr = Script.from_human('OP_DUP OP_HASH160 0x0000000000000000000000000000000000000000 OP_EQUAL OP_CHECKSIG')
        self.assertFalse(script_gen.is_template_script(scr, template))

        scr = Script.from_human('OP_DUP OP_HASH160 0x00000000000000000000000000000000000000 OP_EQUALVERIFY OP_CHECKSIG')
        self.assertFalse(script_gen.is_template_script(scr, template))
Example #6
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
Example #7
0
 def coerce_item(cls, data):
     if not isinstance(data, Script):
         try:
             data = Script.from_human(data)
         except Exception:
             return None
     for i in known_templates:
         if is_template_script(data, i):
             return cls(data, i)
Example #8
0
 def coerce_item(cls, data):
     if not isinstance(data, Script):
         try:
             data = Script.from_human(data)
         except Exception:
             return None
     for i in known_templates:
         if is_template_script(data, i):
             return cls(data, i)
Example #9
0
def replace_outputs(tx, hash160):
    """Replace unsigned outputs in tx."""
    if not is_hex(hash160) and len(hash160.replace('0x', '')) == 40:
        raise ValueError('hash160 must be 40 hex digits.')
    out_script = Script.from_human('OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG' % hash160)

    unsigned_outputs = get_unsigned_outputs(tx)
    if not unsigned_outputs:
        return tx
    new_tx = Transaction.from_tx(tx)
    for o in unsigned_outputs:
        new_tx.vout[o].scriptPubKey = out_script
    return new_tx
Example #10
0
 def do_evaluate(self):
     self.clear_execution()
     try:
         scr = Script(str(self.tx_script.toPlainText()).decode('hex'))
     except Exception as e:
         self.error('Error decoding script: %s' % str(e))
         return
     exec_data = None
     if not self.block_height_edit.property('hasError').toBool() and not self.block_time_edit.property('hasError').toBool():
         exec_data = ExecutionData(self.block_height_edit.get_amount(), self.block_time_edit.get_amount())
     self.execution_widget.evaluate(scr, self.tx, self.inIdx, execution_data=exec_data)
     passed = True if self.execution_widget.execution.script_passed else False
     verified = self.execution_widget.execution.script_verified
     self.script_passed.setChecked(passed)
     self.script_verified.setChecked(verified)
     for widget in [self.script_passed, self.script_verified]:
         widget.setProperty('hasSuccess', widget.isChecked())
         self.style().polish(widget)
Example #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
Example #12
0
    def test_is_template_script(self):
        template = self.templates['Pay-To-Public-Key-Hash Output']
        scr = Script.from_human('OP_DUP OP_HASH160 0x0000000000000000000000000000000000000000 OP_EQUALVERIFY OP_CHECKSIG')
        self.assertTrue(script_gen.is_template_script(scr, template))

        scr = Script.from_human('OP_DUP OP_HASH160 0x0000000000000000000000000000000000000000 OP_EQUAL OP_CHECKSIG')
        self.assertFalse(script_gen.is_template_script(scr, template))

        scr = Script.from_human('OP_DUP OP_HASH160 0x00000000000000000000000000000000000000 OP_EQUALVERIFY OP_CHECKSIG')
        self.assertFalse(script_gen.is_template_script(scr, template))

        scr = Script.from_human('0x03569988948d05ddf970d610bc52f0d47fb21ec307a35d3cbeba6d11accfcd3c6a OP_CHECKSIG')
        self.assertTrue(script_gen.is_template_script(scr, self.templates['Pay-To-Public-Key']))

        scr = Script.from_human('0x3045022100f89cffc794d3c43bbaec99f61d0bb2eb72ea1df4be407f375e98f7039caab83d02204b24170189348f82d9af3049aadc1160904e7ef0ba3bc96f3fd241053f0b6de101 0x028f917ac4353d2027ef1be2d02b4dd657ef2ecf67191760c957e79f198b3579c6')
        self.assertTrue(script_gen.is_template_script(scr, self.templates['Signature Script']))

        scr = Script.from_human('0x304402200a156e3e5617cc1d795dfe0c02a5c7dab3941820f194eabd6107f81f25e0519102204d8c585635e03c9137b239893701dc280e25b162011e6474d0c9297d2650b46901 0x51210208b5b58fd9bf58f1d71682887182e7abd428756264442eec230dd021c193f8d9210245af4f2b1ae21c9310a3211f8d5debb296175e20b3a14b173ff30428e03d502d52ae')
        self.assertTrue(script_gen.is_template_script(scr, self.templates['Pay-To-Script-Hash Signature Script']))

        scr = Script.from_human('OP_0 0x304402200a156e3e5617cc1d795dfe0c02a5c7dab3941820f194eabd6107f81f25e0519102204d8c585635e03c9137b239893701dc280e25b162011e6474d0c9297d2650b46901 0x51210208b5b58fd9bf58f1d71682887182e7abd428756264442eec230dd021c193f8d9210245af4f2b1ae21c9310a3211f8d5debb296175e20b3a14b173ff30428e03d502d52ae')
        self.assertTrue(script_gen.is_template_script(scr, self.templates['Pay-To-Script-Hash Multisig Signature Script']))