Python bitcoin.core.CMutableTxOut() Examples

The following are 14 code examples of bitcoin.core.CMutableTxOut(). 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: transaction.py    From clove with GNU General Public License v3.0 6 votes vote down vote up
def build_outputs(self):
        if not self.secret_hash:
            self.generate_hash()
            self.set_locktime(number_of_hours=self.init_hours)
        else:
            self.set_locktime(number_of_hours=self.participate_hours)

        self.build_atomic_swap_contract()

        contract_p2sh = self.contract.to_p2sh_scriptPubKey()

        self.tx_out_list = [CMutableTxOut(to_base_units(self.value), contract_p2sh), ]
        if self.utxo_value > self.value:
            change = self.utxo_value - self.value
            self.tx_out_list.append(
                CMutableTxOut(to_base_units(change), CBitcoinAddress(self.sender_address).to_scriptPubKey())
            ) 
Example #2
Source File: tx_utils.py    From cert-issuer with MIT License 6 votes vote down vote up
def create_trx(op_return_val, issuing_transaction_fee, issuing_address, tx_outs, tx_inputs):
    """

    :param op_return_val:
    :param issuing_transaction_fee:
    :param issuing_address:
    :param tx_outs:
    :param tx_input:
    :return:
    """
    cert_out = CMutableTxOut(0, CScript([OP_RETURN, op_return_val]))
    tx_ins = []
    value_in = 0
    for tx_input in tx_inputs:
        tx_ins.append(CTxIn(COutPoint(tx_input.tx_hash, tx_input.tx_out_index)))
        value_in += tx_input.coin_value

    # send change back to our address
    amount = value_in - issuing_transaction_fee
    if amount > 0:
        change_out = create_transaction_output(issuing_address, amount)
        tx_outs = tx_outs + [change_out]
    tx_outs = tx_outs + [cert_out]
    transaction = CMutableTransaction(tx_ins, tx_outs)
    return transaction 
Example #3
Source File: channel.py    From Lightning with MIT License 6 votes vote down vote up
def select_coins(amount):
    """Get a txin set and change to spend amount."""
    coins = g.bit.listunspent()
    out = []
    for coin in coins:
        if not coin['spendable']:
            continue
        out.append(CMutableTxIn(coin['outpoint']))
        amount -= coin['amount']
        if amount <= 0:
            break
    if amount > 0:
        raise Exception("Not enough money")
    change = CMutableTxOut(
        -amount, g.bit.getrawchangeaddress().to_scriptPubKey())
    return out, change 
Example #4
Source File: transaction.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def build_outputs(self):
        self.tx_out_list = [
            CMutableTxOut(to_base_units(self.value), CBitcoinAddress(self.recipient_address).to_scriptPubKey())
        ] 
Example #5
Source File: transactions.py    From OpenBazaar-Server with MIT License 5 votes vote down vote up
def make_unsigned(cls, outpoints, outputs, tx_fee=TRANSACTION_FEE, testnet=False, out_value=None):
        """
        Build an unsigned transaction.

        Args:
            outpoints: A `list` of `dict` objects which contain a txid, vout, value, and scriptPubkey.
            outputs: If a single address the full value of the inputs (minus the tx fee) will be sent there.
                Otherwise it should be a `list` of `dict` objects containing address and value.
            tx_fee: The Bitcoin network fee to be paid on this transaction.
            testnet: Should this transaction be built for testnet?
            out_value: used if you want to specify a specific output value otherwise the full value
                of the inputs (minus the tx fee) will be used.
        """
        # build the inputs from the outpoints object
        SelectParams("testnet" if testnet else "mainnet")
        txins = []
        in_value = 0
        for outpoint in outpoints:
            in_value += outpoint["value"]
            txin = CMutableTxIn(COutPoint(lx(outpoint["txid"]), outpoint["vout"]))
            txin.scriptSig = CScript(x(outpoint["scriptPubKey"]))
            txins.append(txin)

        # build the outputs
        txouts = []
        if isinstance(outputs, list):
            for output in outputs:
                value = output["value"]
                address = output["address"]
                txouts.append(CMutableTxOut(value, CBitcoinAddress(address).to_scriptPubKey()))
        else:
            value = out_value if out_value is not None else (in_value - tx_fee)
            txouts.append(CMutableTxOut(value, CBitcoinAddress(outputs).to_scriptPubKey()))

        # make the transaction
        tx = CMutableTransaction(txins, txouts)

        return BitcoinTransaction(tx) 
Example #6
Source File: tx_utils.py    From cert-issuer with MIT License 5 votes vote down vote up
def create_transaction_output(address, output_value):
    """
    Create a single transaction output
    :param address:
    :param output_value:
    :return:
    """
    bitcoin_address = CBitcoinAddress(address)
    tx_out = CMutableTxOut(output_value, bitcoin_address.to_scriptPubKey())
    return tx_out 
Example #7
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 #8
Source File: channel.py    From Lightning with MIT License 5 votes vote down vote up
def commitment(self, ours=False):
        """Return an unsigned commitment transaction."""
        first = CMutableTxOut(self.our_balance, self.our_addr.to_scriptPubKey())
        second = CMutableTxOut(self.their_balance, self.their_addr.to_scriptPubKey())
        if not ours:
            first, second = second, first
        return CMutableTransaction([CMutableTxIn(self.anchor_point)],
                                   [first, second]) 
Example #9
Source File: channel.py    From Lightning with MIT License 5 votes vote down vote up
def settlement(self):
        """Generate the settlement transaction."""
        # Put outputs in the order of the inputs, so that both versions are the same
        first = CMutableTxOut(self.our_balance,
                              self.our_addr.to_scriptPubKey())
        second = CMutableTxOut(self.their_balance,
                               self.their_addr.to_scriptPubKey())
        if self.anchor_index == 0:
            pass
        elif self.anchor_index == 1:
            first, second = second, first
        else:
            raise Exception("Unknown index", self.anchor_index)
        return CMutableTransaction([CMutableTxIn(self.anchor_point)],
                                   [first, second]) 
Example #10
Source File: channel.py    From Lightning with MIT License 5 votes vote down vote up
def open_channel(address, mymoney, theirmoney, fees, their_coins, their_change, their_pubkey, their_out_addr): # pylint: disable=too-many-arguments, line-too-long
    """Open a payment channel."""
    # Get inputs and change output
    coins, change = select_coins(mymoney + 2 * fees)
    # Make the anchor script
    anchor_output_script = anchor_script(get_pubkey(), their_pubkey)
    # Construct the anchor utxo
    payment = CMutableTxOut(mymoney + theirmoney + 2 * fees,
                            anchor_output_script.to_p2sh_scriptPubKey())
    # Anchor tx
    transaction = CMutableTransaction(
        their_coins + coins,
        [payment, change, their_change])
    # Half-sign
    transaction = g.bit.signrawtransaction(transaction)['tx']
    # Create channel in DB
    our_addr = g.bit.getnewaddress()
    channel = Channel(address=address,
                      anchor_point=COutPoint(transaction.GetHash(), 0),
                      anchor_index=0,
                      their_sig=b'',
                      anchor_redeem=anchor_output_script,
                      our_balance=mymoney,
                      our_addr=our_addr,
                      their_balance=theirmoney,
                      their_addr=their_out_addr,
                     )
    database.session.add(channel)
    database.session.commit()
    # Event: channel opened
    CHANNEL_OPENED.send('channel', address=address)
    return (transaction, anchor_output_script, our_addr) 
Example #11
Source File: test_jsonrpcproxy.py    From Lightning with MIT License 5 votes vote down vote up
def test_json_roundtrip(self):
        VALUES = [
            42, 0, -42, 2100000000000000, -2100000000000000,
            "basic string", "\u1111Unicode", "\U00010000Wide Unicode",
            "\x00\n\t\r\nEscape codes", "\"'\"Quotes", "",
            None,
            b"\x00\x01\xFFBinary data", b"",
            CBase58Data.from_bytes(b'\x00\x01\xFF', 42),
            P2SHBitcoinAddress.from_bytes(b'\x00\x01\xFF'),
            P2PKHBitcoinAddress.from_bytes(b'\x00\x01\xFF'),
            CMutableTxIn(COutPoint(b'\x00'*16+b'\xFF'*16, 42),
                         CScript(b'\x00\x01\xFF'),
                         42),
            CMutableTxOut(42, CScript(b'\x00\x01\xFF')),
            CMutableTransaction([CMutableTxIn(COutPoint(b'\x00'*32, 42),
                                              CScript(b'\x00\x01\xFF'),
                                              42),
                                 CMutableTxIn(COutPoint(b'\xFF'*32, 42),
                                              CScript(b'\xFF\x01\x00'),
                                              43)],
                                [CMutableTxOut(42, CScript(b'\x00\x01\xFF')),
                                 CMutableTxOut(43, CScript(b'\xFF\x01\x00'))],
                                42, 3),
            [1, b'\x00\x01\xFF', "List Test",],
            {'a':1, 'key':b'\xFF\x01\x00', 1:'Dictionary Test'},
            [{3: [0, 1, 2,],}, [[b'\xFFRecursion Test',],],],
        ]
        for value in VALUES:
            self.assertEqual(from_json(to_json(value)), value) 
Example #12
Source File: test_stack.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #13
Source File: test_stack.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def build_crediting_tx(script_pubkey):
    tx = Transaction(version=1, locktime=0)
    txin = CMutableTxIn()
    txin.scriptSig = Script.from_human('0x00 0x00')
    tx.vin = [txin]
    txout = CMutableTxOut(0, script_pubkey)
    tx.vout = [txout]
    return tx 
Example #14
Source File: tx_builder.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def create_outputs_tab(self):
        form = QFormLayout()
        self.outputs_tree = OutputsTree()
        self.outputs_tree.view.setWhatsThis('The outputs of your transaction are displayed here.')
        self.outputs_editor = OutputsEditor(self.handler.gui, self.outputs_tree)
        self.outputs_editor.setEnabled(False)

        def update_enabled_widgets():
            num_outputs = len(self.outputs_tree.get_outputs())
            self.outputs_editor.setEnabled(num_outputs > 0)

        def add_output():
            new_output = CMutableTxOut(0)
            self.outputs_tree.add_output(new_output)

            update_enabled_widgets()
            if len(self.outputs_tree.get_outputs()) > 0:
                self.outputs_tree.view.selectRow(self.outputs_tree.model.rowCount() - 1)

        update_enabled_widgets()

        add_output_button = QPushButton('New output')
        add_output_button.setToolTip('Add a new output')
        add_output_button.setWhatsThis('Clicking this button will add a new output to your transaction.')
        add_output_button.clicked.connect(add_output)

        form.addRow(self.outputs_tree)
        form.addRow(Separator())

        form.addRow(self.outputs_editor)

        form.addRow(Separator())
        form.addRow(floated_buttons([add_output_button]))

        w = QWidget()
        w.setLayout(form)
        return w