Python bitcoin.core.b2x() Examples

The following are 30 code examples of bitcoin.core.b2x(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bitcoin.core , or try the search function .
Example #1
Source File: test_script.py    From checklocktimeverify-demos with GNU General Public License v3.0 6 votes vote down vote up
def test_to_p2sh_scriptPubKey(self):
        def T(redeemScript, expected_hex_bytes):
            redeemScript = CScript(redeemScript)
            actual_script = redeemScript.to_p2sh_scriptPubKey()
            self.assertEqual(b2x(actual_script), expected_hex_bytes)

        T([],
          'a914b472a266d0bd89c13706a4132ccfb16f7c3b9fcb87')

        T([1,x('029b6d2c97b8b7c718c325d7be3ac30f7c9d67651bce0c929f55ee77ce58efcf84'),1,OP_CHECKMULTISIG],
          'a91419a7d869032368fd1f1e26e5e73a4ad0e474960e87')

        T([b'\xff'*517],
          'a9140da7fa40ebf248dfbca363c79921bdd665fed5ba87')

        with self.assertRaises(ValueError):
            CScript([b'a' * 518]).to_p2sh_scriptPubKey() 
Example #2
Source File: test_script.py    From checklocktimeverify-demos with GNU General Public License v3.0 6 votes vote down vote up
def test_to_p2sh_scriptPubKey(self):
        def T(redeemScript, expected_hex_bytes):
            redeemScript = CScript(redeemScript)
            actual_script = redeemScript.to_p2sh_scriptPubKey()
            self.assertEqual(b2x(actual_script), expected_hex_bytes)

        T([],
          'a914b472a266d0bd89c13706a4132ccfb16f7c3b9fcb87')

        T([1,x('029b6d2c97b8b7c718c325d7be3ac30f7c9d67651bce0c929f55ee77ce58efcf84'),1,OP_CHECKMULTISIG],
          'a91419a7d869032368fd1f1e26e5e73a4ad0e474960e87')

        T([b'\xff'*517],
          'a9140da7fa40ebf248dfbca363c79921bdd665fed5ba87')

        with self.assertRaises(ValueError):
            CScript([b'a' * 518]).to_p2sh_scriptPubKey() 
Example #3
Source File: test_script.py    From replace-by-fee-tools with GNU General Public License v3.0 6 votes vote down vote up
def test_to_p2sh_scriptPubKey(self):
        def T(redeemScript, expected_hex_bytes):
            redeemScript = CScript(redeemScript)
            actual_script = redeemScript.to_p2sh_scriptPubKey()
            self.assertEqual(b2x(actual_script), expected_hex_bytes)

        T([],
          'a914b472a266d0bd89c13706a4132ccfb16f7c3b9fcb87')

        T([1,x('029b6d2c97b8b7c718c325d7be3ac30f7c9d67651bce0c929f55ee77ce58efcf84'),1,OP_CHECKMULTISIG],
          'a91419a7d869032368fd1f1e26e5e73a4ad0e474960e87')

        T([b'\xff'*517],
          'a9140da7fa40ebf248dfbca363c79921bdd665fed5ba87')

        with self.assertRaises(ValueError):
            CScript([b'a' * 518]).to_p2sh_scriptPubKey() 
Example #4
Source File: test_script.py    From replace-by-fee-tools with GNU General Public License v3.0 6 votes vote down vote up
def test_to_p2sh_scriptPubKey(self):
        def T(redeemScript, expected_hex_bytes):
            redeemScript = CScript(redeemScript)
            actual_script = redeemScript.to_p2sh_scriptPubKey()
            self.assertEqual(b2x(actual_script), expected_hex_bytes)

        T([],
          'a914b472a266d0bd89c13706a4132ccfb16f7c3b9fcb87')

        T([1,x('029b6d2c97b8b7c718c325d7be3ac30f7c9d67651bce0c929f55ee77ce58efcf84'),1,OP_CHECKMULTISIG],
          'a91419a7d869032368fd1f1e26e5e73a4ad0e474960e87')

        T([b'\xff'*517],
          'a9140da7fa40ebf248dfbca363c79921bdd665fed5ba87')

        with self.assertRaises(ValueError):
            CScript([b'a' * 518]).to_p2sh_scriptPubKey() 
Example #5
Source File: tx_builder.py    From hashmal with GNU General Public License v3.0 6 votes vote down vote up
def set_fields(self, script=None, txTo=None, inIdx=None, hashType=None):
        """Populate model.

        Args:
            script (str): Human-readable script.
            txTo (Transaction): Transaction.
            inIdx (int): Input index.
            hashType (int): SigHash type.

        """
        if script is not None:
            self.setData(self.index(0, 0), QVariant(script))
        if txTo is not None:
            self.setData(self.index(0, 1), QVariant(b2x(txTo.serialize())))
        if inIdx is not None:
            self.setData(self.index(0, 2), QVariant(inIdx))
        if hashType is not None:
            self.setData(self.index(0, 3), QVariant(hashType & 0x1f), RawRole)
            self.setData(self.index(0, 4), QVariant(hashType & SIGHASH_ANYONECANPAY)) 
Example #6
Source File: block_analyzer.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def txs_context_menu(self, position):
        try:
            selected = self.block_widget.txs_widget.view.selectedIndexes()[0]
        except IndexError:
            return
        menu = QMenu()
        if self.block:
            r = selected.row()
            tx = self.block.vtx[r]
            raw_tx = b2x(tx.serialize())
            self.handler.add_plugin_actions(self, menu, raw_tx)

        menu.exec_(self.block_widget.txs_widget.view.viewport().mapToGlobal(position)) 
Example #7
Source File: item_types.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def raw(self):
        return b2x(self.value.serialize()) 
Example #8
Source File: addr_encoder.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def raw(self):
        return b2x(self.value.to_bytes()) 
Example #9
Source File: addr_encoder.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def decode_address(self):
        txt = str(self.address_line.text())
        try:
            addr_bytes, version = decode_address(txt)
        except Exception:
            self.hash_line.setText('Could not decode address.')
            self.addr_version.setValue(0)
            return

        self.hash_line.setText(b2x(addr_bytes))
        self.addr_version.setValue(version) 
Example #10
Source File: tx_builder.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def data(self, index, role = Qt.DisplayRole):
        if not index.isValid():
            return None

        if role not in [Qt.DisplayRole, Qt.ToolTipRole, Qt.EditRole]:
            return None

        data = None
        c = index.column()
        if c == 0:
            if self.utxo_script:
                data = self.utxo_script.get_human()
        elif c == 1:
            if self.tx:
                data = b2x(self.tx.serialize())
        elif c == 2:
            data = self.inIdx
        elif c == 3:
            data = sighash_types_by_value[self.sighash_type]
        elif c == 4:
            if role == Qt.CheckStateRole:
                data = Qt.Checked if self.anyone_can_pay else Qt.Unchecked
            else:
                data = self.anyone_can_pay
        elif c == self.SigHashName:
            data = sig_hash_name(self.sighash_type | SIGHASH_ANYONECANPAY if self.anyone_can_pay else self.sighash_type)
        elif c == self.SigHashExplanation:
            data = sig_hash_explanation(self.sighash_type | SIGHASH_ANYONECANPAY if self.anyone_can_pay else self.sighash_type)

        return data 
Example #11
Source File: tx_builder.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def set_tx(self, tx):
        self.setData(self.index(0, 1), QVariant(b2x(tx.serialize()))) 
Example #12
Source File: tx_builder.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
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))) 
Example #13
Source File: item_types.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def raw(self):
        return b2x(self.value.serialize()) 
Example #14
Source File: test_wallet.py    From replace-by-fee-tools with GNU General Public License v3.0 5 votes vote down vote up
def test_to_scriptPubKey(self):
        """CBitcoinAddress.to_scriptPubKey() works"""
        def T(str_addr, expected_scriptPubKey_hexbytes):
            addr = CBitcoinAddress(str_addr)

            actual_scriptPubKey = addr.to_scriptPubKey()
            self.assertEqual(b2x(actual_scriptPubKey), expected_scriptPubKey_hexbytes)

        T('31h1vYVSYuKP6AhS86fbRdMw9XHieotbST',
          'a914000000000000000000000000000000000000000087')

        T('1111111111111111111114oLvT2',
          '76a914000000000000000000000000000000000000000088ac') 
Example #15
Source File: test_wallet.py    From replace-by-fee-tools with GNU General Public License v3.0 5 votes vote down vote up
def test(self):
        def T(base58_privkey, expected_hex_pubkey, expected_is_compressed_value):
            key = CBitcoinSecret(base58_privkey)
            self.assertEqual(b2x(key.pub), expected_hex_pubkey)
            self.assertEqual(key.is_compressed, expected_is_compressed_value)

        T('5KJvsngHeMpm884wtkJNzQGaCErckhHJBGFsvd3VyK5qMZXj3hS',
          '0478d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71a1518063243acd4dfe96b66e3f2ec8013c8e072cd09b3834a19f81f659cc3455',
          False)
        T('L3p8oAcQTtuokSCRHQ7i4MhjWc9zornvpJLfmg62sYpLRJF9woSu',
          '0378d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71',
          True) 
Example #16
Source File: test_wallet.py    From replace-by-fee-tools with GNU General Public License v3.0 5 votes vote down vote up
def test_to_scriptPubKey(self):
        """CBitcoinAddress.to_scriptPubKey() works"""
        def T(str_addr, expected_scriptPubKey_hexbytes):
            addr = CBitcoinAddress(str_addr)

            actual_scriptPubKey = addr.to_scriptPubKey()
            self.assertEqual(b2x(actual_scriptPubKey), expected_scriptPubKey_hexbytes)

        T('31h1vYVSYuKP6AhS86fbRdMw9XHieotbST',
          'a914000000000000000000000000000000000000000087')

        T('1111111111111111111114oLvT2',
          '76a914000000000000000000000000000000000000000088ac') 
Example #17
Source File: solvers.py    From GenesisZ with GNU General Public License v3.0 5 votes vote down vote up
def build_cmdline(self):
        return self.path + ['--nonces', str(self.rounds),
                '-i', b2x(self.header.serialize())] 
Example #18
Source File: solvers.py    From GenesisZ with GNU General Public License v3.0 5 votes vote down vote up
def build_cmdline(self):
        return self.path + ['-s', '-c',
                '-n', str(uint256_from_str(self.start_nonce)),
                '-r', str(self.rounds),
                '-t', str(self.threads),
                '-x', b2x(self.header.serialize())] 
Example #19
Source File: item_types.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def raw(self):
        return b2x(self.value.serialize()) 
Example #20
Source File: transaction.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def as_hex(self):
        return b2x(self.serialize())

# Known serializer classes 
Example #21
Source File: test_chainparams.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def test_clams_fields(self):
        chainparams.set_to_preset('Clams')
        blk = Block.deserialize(clams_raw_block)
        self.assertEqual(clams_raw_block.encode('hex'), blk.as_hex())
        self.assertEqual('3045022100b4e1b24eff6f0c7945c1cabc2d37ac88df861fe37f9bc22ac3c8594bac58f6f9022044e8dfde90dc28d06ba17d5c2b9b3a65ad1cdc03c3e0f8f5655d1f5b9c8cfa0b', b2x(blk.blockSig)) 
Example #22
Source File: tx.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def context_menu(self):
        menu = QMenu()
        copy = menu.addMenu('Copy')
        copy.addAction('Amount', self.copy_amount)
        copy.addAction('Output Script', self.copy_script)
        copy.addAction('Output Script (Hex)', self.copy_script_hex)
        def copy_serialized():
            row = self.view.selectedIndexes()[0].row()
            out = self.model.tx.vout[row]
            data = b2x(out.serialize())
            QApplication.clipboard().setText(data)
        copy.addAction('Serialized Output', copy_serialized)
        return menu 
Example #23
Source File: tx.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def context_menu(self):
        menu = QMenu()
        copy = menu.addMenu('Copy')
        copy.addAction('Previous Transaction ID', self.copy_prev_tx)
        copy.addAction('Input Script', self.copy_script)
        copy.addAction('Input Script (Hex)', self.copy_script_hex)

        def copy_serialized():
            row = self.view.selectedIndexes()[0].row()
            inp = self.model.tx.vin[row]
            data = b2x(inp.serialize())
            QApplication.clipboard().setText(data)
        copy.addAction('Serialized Input', copy_serialized)
        return menu 
Example #24
Source File: block.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def copy_serialized(self):
        data = b2x(self.model.header.serialize())
        QApplication.clipboard().setText(data) 
Example #25
Source File: txtenna.py    From txtenna-python with The Unlicense 5 votes vote down vote up
def do_mesh_sendtoaddress(self, rem) :
        """ 
        Create a signed transaction and broadcast it over the connected mesh device. The transaction 
        spends some amount of satoshis to the specified address from the local bitcoind wallet and selected network. 

        Usage: mesh_sendtoaddress ADDRESS SATS NETWORK(m|t)

        eg. txTenna> mesh_sendtoaddress 2N4BtwKZBU3kXkWT7ZBEcQLQ451AuDWiau2 13371337 t
        """
        try:

            proxy = bitcoin.rpc.Proxy()
            (addr, sats, network) = rem.split()

            # Create the txout. This time we create the scriptPubKey from a Bitcoin
            # address.
            txout = CMutableTxOut(sats, CBitcoinAddress(addr).to_scriptPubKey())

            # Create the unsigned transaction.
            unfunded_transaction = CMutableTransaction([], [txout])
            funded_transaction = proxy.fundrawtransaction(unfunded_transaction)
            signed_transaction = proxy.signrawtransaction(funded_transaction["tx"])
            txhex = b2x(signed_transaction["tx"].serialize())
            txid = b2lx(signed_transaction["tx"].GetTxid())
            print("sendtoaddress_mesh (tx, txid, network): " + txhex + ", " + txid, ", " + network)

            # broadcast over mesh
            self.do_mesh_broadcast_rawtx( txhex + " " + txid + " " + network)

        except Exception: # pylint: disable=broad-except
            traceback.print_exc()

        try :
            # lock UTXOs used to fund the tx if broadcast successful
            vin_outpoints = set()
            for txin in funded_transaction["tx"].vin:
                vin_outpoints.add(txin.prevout)
            ## json_outpoints = [{'txid':b2lx(outpoint.hash), 'vout':outpoint.n}
            ##              for outpoint in vin_outpoints]
            ## print(str(json_outpoints))
            proxy.lockunspent(False, vin_outpoints)
            
        except Exception: # pylint: disable=broad-except
            ## TODO: figure out why this is happening
            print("RPC timeout after calling lockunspent") 
Example #26
Source File: transactions.py    From OpenBazaar-Server with MIT License 5 votes vote down vote up
def to_raw_tx(self):
        """
        return the raw, serialized transaction
        """
        return b2x(self.tx.serialize()) 
Example #27
Source File: test_bitcoin_transfer.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def test_audit_contract_empty_transaction():
    btc_network = BitcoinTestNet()
    tx = b2x(CTransaction().serialize())

    with raises(
        ValueError, match='Given transaction has no outputs.'
    ):
        btc_network.audit_contract('', tx) 
Example #28
Source File: base.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def extract_secret(cls, raw_transaction: str=None, scriptsig: str=None) -> str:
        '''
        Extracting secret from Alice redeem transaction (first redeem in the Atomic Swao).

        Args:
            raw_transaction (str): raw transaction to extract secret from
            scriptSig (str): value of the scriptSig field from the first vin

        Returns:
            str: transaction secret

        Raises:
            ValueError: if something goes wrong

        Example:
            >>> from clove.network import Litecoin
            >>> network = Litecoin()
            >>> network.extract_secret(raw_transaction='0100000001aa25fd5f63cb41d6ee7dd495256046b4c3f17d4540a1b258a06bfefac30da60900000000fdff0047304402201c8869d359b5599ecffd51a96f0a8799392c98c4e15242762ba455e37b1f5d6302203f2974e9afc8d641f9363167df48e5a845a8deba1381bf5a1b549ac04718a1ac01410459cdb91eb7298bc2578dc4e7ac2109ac3cfd9dc9818795c5583e720d2114d540724bf26b4541f683ff51968db627a04eecd1f5cff615b6350dad5fb595f8adf420c480afb333623864901c968022a07dd93fe3c06f5684ea728b8113e17fa91bd9514c5163a61450314a793bf317665ecdc54c2e843bb106aeee158876a91485c0522f6e23beb11cc3d066cd20ed732648a4e66704926db75bb17576a914621f617c765c3caa5ce1bb67f6a3e51382b8da296888ac00000000015a7b0100000000001976a91485c0522f6e23beb11cc3d066cd20ed732648a4e688ac00000000')  # noqa: E501
            'c480afb333623864901c968022a07dd93fe3c06f5684ea728b8113e17fa91bd9'

            >>> network.extract_secret(scriptsig='0c480afb333623864901c968022a07dd93fe3c06f5684ea728b8113e17fa91bd9514c5163a61450314a793bf317665ecdc54c2e843bb106aeee158876a91485c0522f6e23beb11cc3d066cd20')  # noqa: E501
            'c480afb333623864901c968022a07dd93fe3c06f5684ea728b8113e17fa91bd9'
        '''
        if not raw_transaction and not scriptsig:
            raise ValueError('raw_transaction or scriptsig have to be provided.')

        if raw_transaction:
            tx = cls.deserialize_raw_transaction(raw_transaction)

            if not tx.vin:
                raise ValueError('Given transaction has no inputs.')

            secret_tx_in = tx.vin[0]
            script_ops = list(secret_tx_in.scriptSig)
        else:
            script_ops = list(script.CScript.fromhex(scriptsig))

        if script_ops[-2] == 1:
            return b2x(script_ops[-3])

        raise ValueError('Unable to extract secret.') 
Example #29
Source File: transaction.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def raw_transaction(self):
        return b2x(self.tx.serialize()) 
Example #30
Source File: test_wallet.py    From checklocktimeverify-demos with GNU General Public License v3.0 5 votes vote down vote up
def test_to_scriptPubKey(self):
        """CBitcoinAddress.to_scriptPubKey() works"""
        def T(str_addr, expected_scriptPubKey_hexbytes):
            addr = CBitcoinAddress(str_addr)

            actual_scriptPubKey = addr.to_scriptPubKey()
            self.assertEqual(b2x(actual_scriptPubKey), expected_scriptPubKey_hexbytes)

        T('31h1vYVSYuKP6AhS86fbRdMw9XHieotbST',
          'a914000000000000000000000000000000000000000087')

        T('1111111111111111111114oLvT2',
          '76a914000000000000000000000000000000000000000088ac')