Esempio n. 1
0
def main():
    ### (Optional) Replace these addresses with others
    id_a = Id('e12048ff037a0f15bcf977c86181828f5e05dbfe6cf2efe9af6362c8d53a00b0') # addr: mwZ5RAPyv7NxHeeqq2zFo8xngHqWiB4Urb
    id_b = Id('e12048ff047a0f15bcf977c86171828f5e05dbfe6cf2efe9af6362c8d53a00b4') # addr: mgUd1ycGZ7GW66XqdjDFkhGNHmf38b6ATL

    ### Change these inputs to unspent transaction outputs, given the transaction id and the output index
    tx_in1 = TxInput('72ad77c50666676d0ca0a1f395a3ee4ba00acbaad9bcb281892c5ab2a78ff11c', 1) # A in ai
    tx_in2 = TxInput('f6e382f958dbf2e89303e16e4052185e8a30bd97517abc7d498f9c07260848bf', 0) # I in ai

    ### Change these values to carry the same amount as the outputs specified above
    val_a = 0.01
    val_b = 0.01985
    # Transaction fee
    fee = 0.00005

    # create channel between AB
    if lightning:
        print('TESTING LIGHTNING CHANNELS:')
        c_ab = Channel.from_inputs(id_a, id_b, tx_in1, tx_in2, val_a, val_b, fee, LIGHTNING_STATE)
    else:
        print('TESTING GENERALIZED CHANNELS:')
        c_ab = Channel.from_inputs(id_a, id_b, tx_in1, tx_in2, val_a, val_b, fee, GENERALIZED_STATE)
    print_tx(c_ab.ft, 'FT_AB')
    for name, tx in c_ab.state.get_state_transactions():
        print_tx(tx, name)

    c_ab.close(val_a, val_b)
    print_tx(c_ab.close_tx, 'FT_AB close')
Esempio n. 2
0
    def setUp(self):
        setup('testnet')
        self.txin = TxInput(
            "76464c2b9e2af4d63ef38a77964b3b77e629dddefc5cb9eb1a3645b1608b790f",
            0)
        self.from_addr = P2pkhAddress('n4bkvTyU1dVdzsrhWBqBw8fEMbHjJvtmJR')
        self.sk = PrivateKey(
            'cTALNpTpRbbxTCJ2A5Vq88UxT44w1PE2cYqiB3n4hRvzyCev1Wwo')
        self.p2pk_sk = PrivateKey(
            'cRvyLwCPLU88jsyj94L7iJjQX5C2f8koG4G2gevN4BeSGcEvfKe9')
        self.p2pk_redeem_script = Script(
            [self.p2pk_sk.get_public_key().to_hex(), 'OP_CHECKSIG'])
        self.txout = TxOutput(to_satoshis(0.09),
                              self.p2pk_redeem_script.to_p2sh_script_pub_key())
        self.create_p2sh_and_send_result = '02000000010f798b60b145361aebb95cfcdedd29e6773b4b96778af33ed6f42a9e2b4c4676000000006b483045022100fd3a3fd4aeec5db0f3f9c5c5ef7f60f37920be7464a80edacbc3b6b9d0624173022031ce309330e60b19d39cec8c5597460c840adcdd66f7dbbf896eef3ec42b472f012102d82c9860e36f15d7b72aa59e29347f951277c21cd4d34822acdeeadbcff8a546ffffffff01405489000000000017a9142910fc0b1b7ab6c9789c5a67c22c5bcde5b903908700000000'

        self.txin_spend = TxInput(
            '7db363d5a7fabb64ccce154e906588f1936f34481223ea8c1f2c935b0a0c945b',
            0)
        # self.p2pk_sk , self.p2pk_redeem_script from above
        self.to_addr = self.from_addr
        self.txout2 = TxOutput(to_satoshis(0.08),
                               self.to_addr.to_script_pub_key())
        self.spend_p2sh_result = '02000000015b940c0a5b932c1f8cea231248346f93f18865904e15cecc64bbfaa7d563b37d000000006c47304402204984c2089bf55d5e24851520ea43c431b0d79f90d464359899f27fb40a11fbd302201cc2099bfdc18c3a412afb2ef1625abad8a2c6b6ae0bf35887b787269a6f2d4d01232103a2fef1829e0742b89c218c51898d9e7cb9d51201ba2bf9d9e9214ebb6af32708acffffffff0100127a00000000001976a914fd337ad3bf81e086d96a68e1f8d6a0a510f8c24a88ac00000000'

        # P2SH(CSV+P2PKH)
        self.sk_csv_p2pkh = PrivateKey(
            'cRvyLwCPLU88jsyj94L7iJjQX5C2f8koG4G2gevN4BeSGcEvfKe9')
        self.seq = Sequence(TYPE_RELATIVE_TIMELOCK, 200)
        self.txin_seq = TxInput(
            'f557c623e55f0affc696b742630770df2342c4aac395e0ed470923247bc51b95',
            0,
            sequence=self.seq.for_input_sequence())
        self.another_addr = P2pkhAddress('n4bkvTyU1dVdzsrhWBqBw8fEMbHjJvtmJR')
        self.spend_p2sh_csv_p2pkh_result = '0200000001951bc57b24230947ede095c3aac44223df70076342b796c6ff0a5fe523c657f5000000008a483045022100c123775e69ec27094f7940facb9ad769c09f48a7fc88250a2fce67bd92c9b4cf02204ebdbed84af46e584fe6db9a23c420b7370879e883b555e119465f84bf34d82f012103a2fef1829e0742b89c218c51898d9e7cb9d51201ba2bf9d9e9214ebb6af327081e02c800b27576a914c3f8e5b0f8455a2b02c29c4488a550278209b66988acc80000000100ab9041000000001976a914fd337ad3bf81e086d96a68e1f8d6a0a510f8c24a88ac00000000'
Esempio n. 3
0
def main():
    # always remember to setup the network
    setup('testnet')

    # create transaction input from tx id of UTXO (contained 0.4 tBTC)
    txin = TxInput(
        'fb48f4e23bf6ddf606714141ac78c3e921c8c0bebeb7c8abb2c799e9ff96ce6c', 0)

    # create transaction output using P2PKH scriptPubKey (locking script)
    addr = P2pkhAddress('n4bkvTyU1dVdzsrhWBqBw8fEMbHjJvtmJR')
    txout = TxOutput(
        Decimal('0.1'),
        Script([
            'OP_DUP', 'OP_HASH160',
            addr.to_hash160(), 'OP_EQUALVERIFY', 'OP_CHECKSIG'
        ]))

    # create another output to get the change - remaining 0.01 is tx fees
    # note that this time we used to_script_pub_key() to create the P2PKH
    # script
    change_addr = P2pkhAddress('mmYNBho9BWQB2dSniP1NJvnPoj5EVWw89w')
    change_txout = TxOutput(Decimal('0.29'), change_addr.to_script_pub_key())
    #change_txout = TxOutput(Decimal('0.29'), Script(['OP_DUP', 'OP_HASH160',
    #                                     change_addr.to_hash160(),
    #                                     'OP_EQUALVERIFY', 'OP_CHECKSIG']))

    # create transaction from inputs/outputs -- default locktime is used
    tx = Transaction([txin], [txout, change_txout])

    # print raw transaction
    print("\nRaw unsigned transaction:\n" + tx.serialize())

    # use the private key corresponding to the address that contains the
    # UTXO we are trying to spend to sign the input
    sk = PrivateKey('cRvyLwCPLU88jsyj94L7iJjQX5C2f8koG4G2gevN4BeSGcEvfKe9')

    # note that we pass the scriptPubkey as one of the inputs of sign_input
    # because it is used to replace the scriptSig of the UTXO we are trying to
    # spend when creating the transaction digest
    from_addr = P2pkhAddress('myPAE9HwPeKHh8FjKwBNBaHnemApo3dw6e')
    sig = sk.sign_input(
        tx, 0,
        Script([
            'OP_DUP', 'OP_HASH160',
            from_addr.to_hash160(), 'OP_EQUALVERIFY', 'OP_CHECKSIG'
        ]))
    #print(sig)

    # get public key as hex
    pk = sk.get_public_key()
    pk = pk.to_hex()
    #print (pk)

    # set the scriptSig (unlocking script)
    txin.script_sig = Script([sig, pk])
    signed_tx = tx.serialize()

    # print raw signed transaction ready to be broadcasted
    print("\nRaw signed transaction:\n" + signed_tx)
Esempio n. 4
0
def main():
    # always remember to setup the network
    setup('testnet')

    #
    # This script creates a P2SH address containing a P2PK script and sends
    # some funds to it
    #

    # create transaction input from tx id of UTXO (contained 0.1 tBTC)
    txin = TxInput(
        '76464c2b9e2af4d63ef38a77964b3b77e629dddefc5cb9eb1a3645b1608b790f', 0)

    # address we are spending from
    from_addr = P2pkhAddress('n4bkvTyU1dVdzsrhWBqBw8fEMbHjJvtmJR')

    # secret key of address that we are trying to spent
    sk = PrivateKey('cTALNpTpRbbxTCJ2A5Vq88UxT44w1PE2cYqiB3n4hRvzyCev1Wwo')

    #
    # create transaction output using P2SH scriptPubKey (locking script)
    # (the recipient will give us the final address  but for now we create it
    # for demonstration purposes)
    #

    # secret key corresponding to the pubkey needed for the P2SH (P2PK) transaction
    p2pk_sk = PrivateKey(
        'cRvyLwCPLU88jsyj94L7iJjQX5C2f8koG4G2gevN4BeSGcEvfKe9')
    p2pk_pk = p2pk_sk.get_public_key().to_hex()
    redeem_script = Script([p2pk_pk, 'OP_CHECKSIG'])
    txout = TxOutput(Decimal('0.09'), redeem_script.to_p2sh_script_pub_key())

    # no change address - the remaining 0.01 tBTC will go to miners)

    # create transaction from inputs/outputs -- default locktime is used
    tx = Transaction([txin], [txout])

    # print raw transaction
    print("\nRaw unsigned transaction:\n" + tx.serialize())

    # use the private key corresponding to the address that contains the
    # UTXO we are trying to spend to create the signature for the txin
    sig = sk.sign_input(tx, 0, from_addr.to_script_pub_key())
    #print(sig)

    # get public key as hex
    pk = sk.get_public_key()
    pk = pk.to_hex()
    #print (pk)

    # set the scriptSig (unlocking script)
    txin.script_sig = Script([sig, pk])
    signed_tx = tx.serialize()

    # print raw signed transaction ready to be broadcasted
    print("\nRaw signed transaction:\n" + signed_tx)
    print("\nTxId:", tx.get_txid())
Esempio n. 5
0
    def create_ft(self, input_l: TxInput, input_r: TxInput, val_l: float, val_r: float) -> Transaction:
        txs_in = [input_l, input_r]
        tx_out = TxOutput(val_l + val_r - self.fee, scripts.get_script_ft_output(self.id_l, self.id_r))
        tx = Transaction(txs_in, [tx_out])

        sig_l = self.id_l.sk.sign_input(tx, 0 , self.id_l.p2pkh)
        sig_r = self.id_r.sk.sign_input(tx, 1 , self.id_r.p2pkh)

        input_l.script_sig = Script([sig_l, self.id_l.pk.to_hex()])
        input_r.script_sig = Script([sig_r, self.id_r.pk.to_hex()])
        return tx
Esempio n. 6
0
    def create_close_tx(self, valA: float, valB: float) -> Transaction:
        tx_in = TxInput(self.ft.get_txid(), 0)
        tx_out_l = TxOutput(valA - self.fee, self.id_l.p2pkh)
        tx_out_r = TxOutput(valB - self.fee, self.id_r.p2pkh)

        tx = Transaction([tx_in], [tx_out_l, tx_out_r])

        sig_l = self.id_l.sk.sign_input(tx, 0 , scripts.get_script_ft_output(self.id_l, self.id_r))
        sig_r = self.id_r.sk.sign_input(tx, 0 , scripts.get_script_ft_output(self.id_l, self.id_r))

        tx_in.script_sig = Script([sig_r, sig_l])
        return tx
def main():
    # always remember to setup the network
    setup('testnet')  # same params as regest, which the node should run

    # create transaction input from tx id of UTXO (contained 0.4 tBTC)
    txin = TxInput(
        'e2d08a63a540000222d6a92440436375d8b1bc89a2638dc5366833804287c83f', 1)

    # create transaction output using P2PKH scriptPubKey (locking script)
    addr = P2pkhAddress('msXP94TBncQ9usP6oZNpGweE24biWjJs2d')
    # locking script expects 2 numbers that when added equal 5 (silly example)
    txout = TxOutput(0.9, Script(['OP_ADD', 'OP_5', 'OP_EQUAL']))

    # create another output to get the change - remaining 0.01 is tx fees
    # note that this time we used to_script_pub_key() to create the P2PKH
    # script
    change_addr = P2pkhAddress('mrCDrCybB6J1vRfbwM5hemdJz73FwDBC8r')
    change_txout = TxOutput(2, change_addr.to_script_pub_key())

    # create transaction from inputs/outputs -- default locktime is used
    tx = Transaction([txin], [txout, change_txout])

    # print raw transaction
    print("\nRaw unsigned transaction:\n" + tx.serialize())

    # use the private key corresponding to the address that contains the
    # UTXO we are trying to spend to sign the input
    sk = PrivateKey('cMahea7zqjxrtgAbB7LSGbcQUr1uX1ojuat9jZodMN87JcbXMTcA')

    # note that we pass the scriptPubkey as one of the inputs of sign_input
    # because it is used to replace the scriptSig of the UTXO we are trying to
    # spend when creating the transaction digest
    from_addr = P2pkhAddress('mrCDrCybB6J1vRfbwM5hemdJz73FwDBC8r')
    sig = sk.sign_input(
        tx, 0,
        Script([
            'OP_DUP', 'OP_HASH160',
            from_addr.to_hash160(), 'OP_EQUALVERIFY', 'OP_CHECKSIG'
        ]))
    #print(sig)

    # get public key as hex
    pk = sk.get_public_key()
    pk = pk.to_hex()
    #print (pk)

    # set the scriptSig (unlocking script)
    txin.script_sig = Script([sig, pk])
    signed_tx = tx.serialize()

    # print raw signed transaction ready to be broadcasted
    print("\nRaw signed transaction:\n" + signed_tx)
Esempio n. 8
0
def get_gen_punish_tx(tx_in: TxInput, payee: Id, script: Script, id_as: Id, secret_rev, val: int, fee: float, l: bool) -> Transaction:
    tx_out = TxOutput(val-fee, payee.p2pkh)
    tx = Transaction([tx_in], [tx_out])

    sig = payee.sk.sign_input(tx, 0, Script(script))
    sig_as = id_as.sk.sign_input(tx, 0, Script(script))

    if l:
        tx_in.script_sig = Script([secret_rev, sig_as, 0x0, sig])
    else:
        tx_in.script_sig = Script([secret_rev, sig_as, sig, 0x0])

    return tx
Esempio n. 9
0
    def setUp(self):
        setup('testnet')
        # values for testing create non std tx
        self.txin = TxInput("e2d08a63a540000222d6a92440436375d8b1bc89a2638dc5366833804287c83f", 1)
        self.to_addr = P2pkhAddress('msXP94TBncQ9usP6oZNpGweE24biWjJs2d')
        self.sk = PrivateKey('cMahea7zqjxrtgAbB7LSGbcQUr1uX1ojuat9jZodMN87JcbXMTcA')
        self.txout = TxOutput( 0.9, Script(['OP_ADD', 'OP_5', 'OP_EQUAL']) )
        self.change_addr = P2pkhAddress('mrCDrCybB6J1vRfbwM5hemdJz73FwDBC8r')
        self.change_txout = TxOutput( 2, self.change_addr.to_script_pub_key())
        self.create_non_std_tx_result = '02000000013fc8874280336836c58d63a289bcb1d87563434024a9d622020040a5638ad0e2010000006a47304402201febc032331342baaece4b88c7ab42d7148c586b9a48944cbebde95636ac7424022018f0911a4ba664ac8cc21457a58e3a1214ba92b84cb60e57f4119fe655b3a78901210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798ffffffff02804a5d05000000000393558700c2eb0b000000001976a914751e76e8199196d454941c45d1b3a323f1433bd688ac00000000'

        # values for testing create non std tx
        self.txin_spend = TxInput("4d9a6baf45d4b57c875fe83d5e0834568eae4b5ef6e61d13720ef6685168e663", 0)
        self.txin_spend.script_sig = Script(['OP_2', 'OP_3'])
        self.txout_spend = TxOutput( 0.8, self.change_addr.to_script_pub_key())
        self.spend_non_std_tx_result = '020000000163e6685168f60e72131de6f65e4bae8e5634085e3de85f877cb5d445af6b9a4d00000000025253ffffffff0100b4c404000000001976a914751e76e8199196d454941c45d1b3a323f1433bd688ac00000000'
Esempio n. 10
0
def createTxPayAndSign(tx_state_input: TxInput, id_state_pay_right: Id,
                       tx_state_lock_script: Script, id_pay_receiver: Id,
                       lock_coins: float, fee: float) -> Transaction:
    """
    Right can spend locked coins after time T wherever he wants

    :param tx_state_input: tx_state locked output reference
    :param id_state_pay_right: id for signing spend of tx_state.out_lock by right user
    :param tx_state_lock_script: lock script of tx_state.out_lock (for creating a signature)
    :param id_pay_receiver: id that will own coins if transaction will be published
    :param lock_coins: coins locked in tx_state
    :param fee: coins paid to miners
    :return: transaction for pay to right user, valid after time T
    """

    out_pay = TxOutput(lock_coins - fee, id_pay_receiver.p2pkh)
    tx_pay = Transaction([tx_state_input], [out_pay])

    signature = id_state_pay_right.private_key.sign_input(
        tx_pay, 0, tx_state_lock_script)
    tx_state_input.script_sig = Script([
        signature,
        id_state_pay_right.public_key.to_hex(), 'OP_0', 'OP_0', 'OP_0', 'OP_0',
        'OP_0', 'OP_0'
    ])

    return tx_pay
Esempio n. 11
0
def main():
    # always remember to setup the network
    setup('testnet')

    priv1 = PrivateKey("cN1XE3ESGgdvr4fWsB7L3BcqXncUauF8Fo8zzv4Sm6WrkiGrsxrG")
    priv2 = PrivateKey("cR8AkcbL2pgBswrHp28AftEznHPPLA86HiTog8MpNCibxwrsUcZ4")
    
    p2sh_redeem_script = Script(
        ['OP_1', priv1.get_public_key().to_hex(), priv2.get_public_key().to_hex(),'OP_2', 'OP_CHECKMULTISIG'])

    fromAddress = P2wshAddress.from_script(p2sh_redeem_script)

    toAddress = P2wpkhAddress.from_address("tb1qtstf97nhk2gycz7vl37esddjpxwt3ut30qp5pn")

    # set values
    txid = '2042195c40a92353f2ffe30cd0df8d177698560e81807e8bf9174a9c0e98e6c2'
    vout = 0
    amount = 0.01

    # create transaction input from tx id of UTXO
    txin = TxInput(txid, vout)

    txOut1 = TxOutput(0.0001, toAddress.to_script_pub_key())
    txOut2 = TxOutput(0.0098, fromAddress.to_script_pub_key())

    tx = Transaction([txin], [txOut1, txOut2], has_segwit=True)

    sig1 = priv1.sign_segwit_input(tx, 0, p2sh_redeem_script, amount)
    tx.witnesses.append(Script(['OP_0', sig1, p2sh_redeem_script.to_hex()]))

    # print raw signed transaction ready to be broadcasted
    print("\nRaw signed transaction:\n" + tx.serialize())
    print("\nTxId:", tx.get_txid())
Esempio n. 12
0
def createTxRefund(tx_er_input: TxInput, tx_state_input: TxInput, id_er: Id,
                   id_state_ref_left: Id, tx_state_lock_script: Script,
                   id_refund: Id, lock_coins: float, fee: float, eps: float,
                   rel_lock: int) -> (Transaction, str):
    """
    Left user creates transaction for refund based on tx_state and tx_er, and signs it

    :param tx_er_input: enable-refund transaction output reference
    :param tx_state_input: tx_state locked output reference
    :param id_er: id that owns output of enable-refund transaction
    :param id_state_ref_left: id for signing spend of tx_state.out_lock by left user
    :param tx_state_lock_script: lock script of tx_state.out_lock (for creating a signature)
    :param id_refund: id that will own coins if transaction will be published
    :param lock_coins: coins locked in tx_state
    :param fee: coins paid to miners
    :param eps: coins from enable-refund transaction
    :param rel_lock: relative lock on tx_er_input (for creating a signature)
    :return: tx_refund, signed by left user
    """

    out_refund = TxOutput(lock_coins + eps - fee, id_refund.p2pkh)

    tx_refund = Transaction([tx_er_input, tx_state_input], [out_refund])

    er_in_lock_script = getEnableTxOutputLockScript(id_er.public_key, rel_lock)
    sig_er_in = id_er.private_key.sign_input(tx_refund, 0, er_in_lock_script)
    tx_er_input.script_sig = Script([sig_er_in, id_er.public_key.to_hex()])

    # should be also signed by right for 2/2 multisig
    sig_state_left = id_state_ref_left.private_key.sign_input(
        tx_refund, 1, tx_state_lock_script)

    return tx_refund, sig_state_left
Esempio n. 13
0
def get_input_trx_from_utxo(priv_key_from_obj, p2sh_addr_to, seq_number_in_hex,
                            redeem_script):
    """
    Looks back up to HISTORY_TRANSACTIONS_BACK with listtransactions to find UTXO

    Returns tuple, 0: Total Amount To Spend, 1: List of created TrxIn initialized objects
    from UTXO.
    """
    trx_set = btc_call('listtransactions "*"' + HISTORY_TRANSACTIONS_BACK +
                       '0 "true"')
    json_trx_set = json.loads(trx_set)
    utxo_set = []
    total_amount = 0.0
    print("For the P2SH address: " + p2sh_addr_to + " found these UTXOs:\n")
    for trx in json_trx_set:
        if trx['address'] == p2sh_addr_to:
            # Nested if helps helps out with debugging
            if int(
                    trx['confirmations']
            ) >= MIN_CONFIRMATIONS_TO_SEARCH_FOR and trx['category'] == 'send':
                txin = TxInput(txid=trx['txid'],
                               txout_index=trx['vout'],
                               sequence=seq_number_in_hex)

                print("Trx id: " + str(trx['txid']) + ", vout: " +
                      str(trx['vout']) + " amount: " + str(-trx['amount']))

                utxo_set.append(txin)
                total_amount = total_amount + (-trx['amount'])
    print("\n")
    return (total_amount, utxo_set)
def main():
    # always remember to setup the network
    setup('testnet')

    #
    # This script spends from a P2SH address containing a P2PK script
    #

    # create transaction input from tx id of UTXO (contained 0.1 tBTC)
    txin = TxInput(
        '7db363d5a7fabb64ccce154e906588f1936f34481223ea8c1f2c935b0a0c945b', 0)

    # secret key needed to spend P2PK that is wrapped by P2SH
    p2pk_sk = PrivateKey(
        'cRvyLwCPLU88jsyj94L7iJjQX5C2f8koG4G2gevN4BeSGcEvfKe9')
    p2pk_pk = p2pk_sk.get_public_key().to_hex()
    # create the redeem script - needed to sign the transaction
    redeem_script = Script([p2pk_pk, 'OP_CHECKSIG'])

    #TODELETE
    #txin_script_pub_key = redeem_script.to_p2sh_script_pub_key()

    to_addr = P2pkhAddress('n4bkvTyU1dVdzsrhWBqBw8fEMbHjJvtmJR')
    txout = TxOutput(Decimal('0.08'), to_addr.to_script_pub_key())

    # no change address - the remaining 0.01 tBTC will go to miners)

    # create transaction from inputs/outputs -- default locktime is used
    tx = Transaction([txin], [txout])

    # print raw transaction
    print("\nRaw unsigned transaction:\n" + tx.serialize())

    # use the private key corresponding to the address that contains the
    # UTXO we are trying to spend to create the signature for the txin -
    # note that the redeem script is passed to replace the scriptSig
    sig = p2pk_sk.sign_input(tx, 0, redeem_script)
    #print(sig)

    # set the scriptSig (unlocking script)
    txin.script_sig = Script([sig, redeem_script.to_hex()])
    signed_tx = tx.serialize()

    # print raw signed transaction ready to be broadcasted
    print("\nRaw signed transaction:\n" + signed_tx)
    print("\nTxId:", tx.get_txid())
def btc_payment(source_address, outputs, fee_satoshi_kb, network='mainnet'):
    try:
        setup(network)
        outputs_list = []
        p2sh_num = 0
        p2pkh_num = 0
        total_amount_to_spend = _calculate_total_amount(outputs)
        print(total_amount_to_spend)
        txin = []
        utxo_amount = 0

        for address, value in outputs.items():
            addr_type = _check_address_type(address)
            addr = ''
            if addr_type is P2PKH_ADDRESS:
                addr = P2pkhAddress(address)
                txout = TxOutput(
                    Decimal(value) / Decimal(SATOSHIS_PER_BITCOIN),
                    Script([
                        'OP_DUP', 'OP_HASH160',
                        addr.to_hash160(), 'OP_EQUALVERIFY', 'OP_CHECKSIG'
                    ]))
                outputs_list.append(txout)
                p2pkh_num += 1
            elif addr_type is P2SH_ADDRESS:
                addr = P2shAddress(address)
                txout = TxOutput(
                    Decimal(value) / Decimal(SATOSHIS_PER_BITCOIN),
                    Script(['OP_HASH160',
                            addr.to_hash160(), 'OP_EQUAL']))
                outputs_list.append(txout)
                p2sh_num += 1

        utxo_set, fee = _get_unspent_transactions(source_address,
                                                  total_amount_to_spend,
                                                  p2pkh_num, p2sh_num,
                                                  fee_satoshi_kb)

        for utxo in utxo_set:
            txin.append(TxInput(utxo['txid'], utxo['vout']))
            utxo_amount += utxo['amount']

        change = utxo_amount - fee - total_amount_to_spend
        change_addr = P2pkhAddress(source_address)
        change_txout = TxOutput(
            Decimal(change) / Decimal(SATOSHIS_PER_BITCOIN),
            Script([
                'OP_DUP', 'OP_HASH160',
                change_addr.to_hash160(), 'OP_EQUALVERIFY', 'OP_CHECKSIG'
            ]))
        outputs_list.append(change_txout)
        tx = Transaction(txin, outputs_list)

        return tx.serialize(), utxo_set
    except UnspentTransactionsError:
        raise UnspentTransactionsError
    except:
        raise BtcPaymentError("Problem during creation of raw transaction")
    def setUp(self):
        setup('testnet')
        # values for testing unsigned tx, signed tx all, signed tx with low s,
        # sighash none
        self.txin = TxInput('fb48f4e23bf6ddf606714141ac78c3e921c8c0bebeb7c8abb2c799e9ff96ce6c', 0)
        self.addr = P2pkhAddress('n4bkvTyU1dVdzsrhWBqBw8fEMbHjJvtmJR')
        self.txout = TxOutput(Decimal('0.1'), Script(['OP_DUP', 'OP_HASH160', self.addr.to_hash160(),
                                           'OP_EQUALVERIFY', 'OP_CHECKSIG']) )
        self.change_addr = P2pkhAddress('mytmhndz4UbEMeoSZorXXrLpPfeoFUDzEp')
        self.change_txout = TxOutput(Decimal('0.29'), self.change_addr.to_script_pub_key())
        self.change_low_s_addr = P2pkhAddress('mmYNBho9BWQB2dSniP1NJvnPoj5EVWw89w')
        self.change_low_s_txout = TxOutput(Decimal('0.29'), self.change_low_s_addr.to_script_pub_key())
        self.sk = PrivateKey('cRvyLwCPLU88jsyj94L7iJjQX5C2f8koG4G2gevN4BeSGcEvfKe9')
        self.from_addr = P2pkhAddress('myPAE9HwPeKHh8FjKwBNBaHnemApo3dw6e')

        self.core_tx_result = '02000000016cce96ffe999c7b2abc8b7bebec0c821e9c378ac41417106f6ddf63be2f448fb0000000000ffffffff0280969800000000001976a914fd337ad3bf81e086d96a68e1f8d6a0a510f8c24a88ac4081ba01000000001976a914c992931350c9ba48538003706953831402ea34ea88ac00000000'
        self.core_tx_signed_result = '02000000016cce96ffe999c7b2abc8b7bebec0c821e9c378ac41417106f6ddf63be2f448fb000000006a473044022079dad1afef077fa36dcd3488708dd05ef37888ef550b45eb00cdb04ba3fc980e02207a19f6261e69b604a92e2bffdf6ddbed0c64f55d5003e9dfb58b874b07aef3d7012103a2fef1829e0742b89c218c51898d9e7cb9d51201ba2bf9d9e9214ebb6af32708ffffffff0280969800000000001976a914fd337ad3bf81e086d96a68e1f8d6a0a510f8c24a88ac4081ba01000000001976a914c992931350c9ba48538003706953831402ea34ea88ac00000000'
        self.core_tx_signed_low_s_SIGALL_result = '02000000016cce96ffe999c7b2abc8b7bebec0c821e9c378ac41417106f6ddf63be2f448fb000000006a473044022044ef433a24c6010a90af14f7739e7c60ce2c5bc3eab96eaee9fbccfdbb3e272202205372a617cb235d0a0ec2889dbfcadf15e10890500d184c8dda90794ecdf79492012103a2fef1829e0742b89c218c51898d9e7cb9d51201ba2bf9d9e9214ebb6af32708ffffffff0280969800000000001976a914fd337ad3bf81e086d96a68e1f8d6a0a510f8c24a88ac4081ba01000000001976a91442151d0c21442c2b038af0ad5ee64b9d6f4f4e4988ac00000000'
        self.core_tx_signed_low_s_SIGNONE_result = '02000000016cce96ffe999c7b2abc8b7bebec0c821e9c378ac41417106f6ddf63be2f448fb000000006b483045022100b4ef8ec12b39b21c4b5d57ce82c0c8762a8e9fbe5322a0f00bd5de0dba5152fe02203edb3128b6df0c891770e377fdc8be5b46a2eab16c63bf57507d075a98557236022103a2fef1829e0742b89c218c51898d9e7cb9d51201ba2bf9d9e9214ebb6af32708ffffffff0280969800000000001976a914fd337ad3bf81e086d96a68e1f8d6a0a510f8c24a88ac4081ba01000000001976a91442151d0c21442c2b038af0ad5ee64b9d6f4f4e4988ac00000000'
        self.core_tx_signed_low_s_SIGNONE_txid = '76464c2b9e2af4d63ef38a77964b3b77e629dddefc5cb9eb1a3645b1608b790f'

        # values for testing sighash single and sighash all/none/single with
        # anyonecanpay
        self.sig_txin1 = TxInput("76464c2b9e2af4d63ef38a77964b3b77e629dddefc5cb9eb1a3645b1608b790f", 0)
        self.sig_txin2 = TxInput('76464c2b9e2af4d63ef38a77964b3b77e629dddefc5cb9eb1a3645b1608b790f', 1)
        self.sig_from_addr1 = P2pkhAddress('n4bkvTyU1dVdzsrhWBqBw8fEMbHjJvtmJR')
        self.sig_from_addr2 = P2pkhAddress('mmYNBho9BWQB2dSniP1NJvnPoj5EVWw89w')
        self.sig_sk1 = PrivateKey('cTALNpTpRbbxTCJ2A5Vq88UxT44w1PE2cYqiB3n4hRvzyCev1Wwo')
        self.sig_sk2 = PrivateKey('cVf3kGh6552jU2rLaKwXTKq5APHPoZqCP4GQzQirWGHFoHQ9rEVt')
        self.sig_to_addr1 = P2pkhAddress('myPAE9HwPeKHh8FjKwBNBaHnemApo3dw6e')
        self.sig_txout1 = TxOutput(Decimal('0.09'), Script(['OP_DUP', 'OP_HASH160',
                                                 self.sig_to_addr1.to_hash160(),
                                                 'OP_EQUALVERIFY',
                                                 'OP_CHECKSIG']) )
        self.sig_to_addr2 = P2pkhAddress('mmYNBho9BWQB2dSniP1NJvnPoj5EVWw89w')
        self.sig_txout2 = TxOutput(Decimal('0.009'), Script(['OP_DUP', 'OP_HASH160',
                                                   self.sig_to_addr2.to_hash160(),
                                                   'OP_EQUALVERIFY',
                                                   'OP_CHECKSIG']) )
        self.sig_sighash_single_result = '02000000010f798b60b145361aebb95cfcdedd29e6773b4b96778af33ed6f42a9e2b4c4676000000006a47304402202cfd7077fe8adfc5a65fb3953fa3482cad1413c28b53f12941c1082898d4935102201d393772c47f0699592268febb5b4f64dabe260f440d5d0f96dae5bc2b53e11e032102d82c9860e36f15d7b72aa59e29347f951277c21cd4d34822acdeeadbcff8a546ffffffff0240548900000000001976a914c3f8e5b0f8455a2b02c29c4488a550278209b66988aca0bb0d00000000001976a91442151d0c21442c2b038af0ad5ee64b9d6f4f4e4988ac00000000'
        self.sign_sighash_all_2in_2out_result = '02000000020f798b60b145361aebb95cfcdedd29e6773b4b96778af33ed6f42a9e2b4c4676000000006b483045022100e30383d4006ef8b796ed397a81d2c55e6db3c05b370cb26179110816e57356e6022068fcd18a2a6984839a1fa7670693ed5c787da96589cd0f5ca81e3f11e613bd11012102d82c9860e36f15d7b72aa59e29347f951277c21cd4d34822acdeeadbcff8a546ffffffff0f798b60b145361aebb95cfcdedd29e6773b4b96778af33ed6f42a9e2b4c4676010000006a47304402206b728374b8879fd7a10cbd4f347934d583f4301aa5d592211487732c235b85b6022030acdc07761f227c27010bd022df4b22eb9875c65a59e8e8a5722229bc7362f4012102364d6f04487a71b5966eae3e14a4dc6f00dbe8e55e61bedd0b880766bfe72b5dffffffff0240548900000000001976a914c3f8e5b0f8455a2b02c29c4488a550278209b66988aca0bb0d00000000001976a91442151d0c21442c2b038af0ad5ee64b9d6f4f4e4988ac00000000'
        self.sign_sighash_none_2in_2out_result = '02000000020f798b60b145361aebb95cfcdedd29e6773b4b96778af33ed6f42a9e2b4c4676000000006a47304402202a2804048b7f84f2dd7641ec05bbaf3da9ae0d2a9f9ad476d376adfd8bf5033302205170fee2ab7b955d72ae2beac3bae15679d75584c37d78d82b07df5402605bab022102d82c9860e36f15d7b72aa59e29347f951277c21cd4d34822acdeeadbcff8a546ffffffff0f798b60b145361aebb95cfcdedd29e6773b4b96778af33ed6f42a9e2b4c4676010000006a473044022021a82914b002bd02090fbdb37e2e739e9ba97367e74db5e1de834bbab9431a2f02203a11f49a3f6ac03b1550ee04f9d84deee2045bc038cb8c3e70869470126a064d022102364d6f04487a71b5966eae3e14a4dc6f00dbe8e55e61bedd0b880766bfe72b5dffffffff0240548900000000001976a914c3f8e5b0f8455a2b02c29c4488a550278209b66988aca0bb0d00000000001976a91442151d0c21442c2b038af0ad5ee64b9d6f4f4e4988ac00000000'
        self.sign_sighash_single_2in_2out_result = '02000000020f798b60b145361aebb95cfcdedd29e6773b4b96778af33ed6f42a9e2b4c4676000000006a47304402206118d21952932deb8608f772017fe76827ccdc8b750ead0f5636429ab5883a6802207f6ded77e22785b0e6c682c05260c2e073d1e1522d4c02fb78df6cdd2862e853032102d82c9860e36f15d7b72aa59e29347f951277c21cd4d34822acdeeadbcff8a546ffffffff0f798b60b145361aebb95cfcdedd29e6773b4b96778af33ed6f42a9e2b4c4676010000006a47304402205012090ddf07ee2e7767020f09224001360243f8dbe05c5011c54eed9fb90d4802203358e227c891f609c3baf98d975d9ee72666fb511c808419d24ec5cccaf3938e032102364d6f04487a71b5966eae3e14a4dc6f00dbe8e55e61bedd0b880766bfe72b5dffffffff0240548900000000001976a914c3f8e5b0f8455a2b02c29c4488a550278209b66988aca0bb0d00000000001976a91442151d0c21442c2b038af0ad5ee64b9d6f4f4e4988ac00000000'
        self.sign_sighash_all_single_anyone_2in_2out_result = '02000000020f798b60b145361aebb95cfcdedd29e6773b4b96778af33ed6f42a9e2b4c4676000000006b4830450221008837e1300f41566cbcd9649ea21a6c1574cce7bf4bc288b878b545e9370041ab022040d0abdd2a0945463b85553922f27a755492e4e2ba89ae68cb14079103072dbb812102d82c9860e36f15d7b72aa59e29347f951277c21cd4d34822acdeeadbcff8a546ffffffff0f798b60b145361aebb95cfcdedd29e6773b4b96778af33ed6f42a9e2b4c4676010000006a473044022067943abe9fa7584ba9816fc9bf002b043f7f97e11de59155d66e0411a679ba2c02200a13462236fa520b80b4ed85c7ded363b4c9264eb7b2d9746200be48f2b6f4cb832102364d6f04487a71b5966eae3e14a4dc6f00dbe8e55e61bedd0b880766bfe72b5dffffffff0240548900000000001976a914c3f8e5b0f8455a2b02c29c4488a550278209b66988aca0bb0d00000000001976a91442151d0c21442c2b038af0ad5ee64b9d6f4f4e4988ac00000000'
Esempio n. 17
0
def main():
    # always remember to setup the network
    setup('testnet')

    # the key that corresponds to the P2WPKH address
    priv = PrivateKey('cNho8fw3bPfLKT4jPzpANTsxTsP8aTdVBD6cXksBEXt4KhBN7uVk')
    pub = priv.get_public_key()

    # the p2sh script and the corresponding address
    redeem_script = pub.get_segwit_address().to_script_pub_key()
    p2sh_addr = P2shAddress.from_script(redeem_script)

    # the UTXO of the P2SH-P2WPKH that we are trying to spend
    inp = TxInput('95c5cac558a8b47436a3306ba300c8d7af4cd1d1523d35da3874153c66d99b09', 0)

    # exact amount of UTXO we try to spent
    amount = 0.0014

    # the address to send funds to
    to_addr = P2pkhAddress('mvBGdiYC8jLumpJ142ghePYuY8kecQgeqS')

    # the output sending 0.001 -- 0.0004 goes to miners as fee -- no change
    out = TxOutput(to_satoshis(0.001), to_addr.to_script_pub_key())

    # create a tx with at least one segwit input
    tx = Transaction([inp], [out], has_segwit=True)

    # script code is the script that is evaluated for a witness program type; each
    # witness program type has a specific template for the script code
    # script code that corresponds to P2WPKH (it is the classic P2PKH)
    script_code = pub.get_address().to_script_pub_key()

    # calculate signature using the appropriate script code
    # remember to include the original amount of the UTXO
    sig = priv.sign_segwit_input(tx, 0, script_code, to_satoshis(amount))

    # script_sig is the redeem script passed as a single element
    inp.script_sig = Script([redeem_script.to_hex()])

    # finally, the unlocking script is added as a witness
    tx.witnesses.append(Script([sig, pub.to_hex()]))

    # print raw signed transaction ready to be broadcasted
    print("\nRaw signed transaction:\n" + tx.serialize())
    def setUp(self):
        setup('testnet')
        self.sk1 = PrivateKey.from_wif("cTALNpTpRbbxTCJ2A5Vq88UxT44w1PE2cYqiB3n4hRvzyCev1Wwo")
        self.sk2 = PrivateKey.from_wif("cRvyLwCPLU88jsyj94L7iJjQX5C2f8koG4G2gevN4BeSGcEvfKe9")

        # 2-2 Multi-sign Script
        self.p2wsh_script = Script(['OP_2', self.sk1.get_public_key().to_hex(), self.sk2.get_public_key().to_hex(),
                                    'OP_2', 'OP_CHECKMULTISIG'])

        # tb1q89t0jucv7un4qq85u0a0tkc9qkepvg3vra72r00msx58wqplewfsfrlunx
        self.p2wsh_addr = P2wshAddress.from_script(self.p2wsh_script)

        # n4bkvTyU1dVdzsrhWBqBw8fEMbHjJvtmJR
        self.p2pkh_addr = self.sk1.get_public_key().get_address()

        # P2PKH to P2WSH
        self.txin1 = TxInput("6e9a0692ed4b3328909d66d41531854988dc39edba5df186affaefda91824e69", 0)
        self.txout1 = TxOutput(to_satoshis(0.0097), self.p2wsh_addr.to_script_pub_key())

        # P2WSH to P2PKH
        self.txin_spend = TxInput("6233aca9f2d6165da2d7b4e35d73b039a22b53f58ce5af87dddee7682be937ea", 0)
        self.txin_spend_amount = to_satoshis(0.0097)
        self.txout2 = TxOutput(to_satoshis(0.0096), self.p2pkh_addr.to_script_pub_key())
        self.p2wsh_redeem_script = self.p2wsh_script

        # Multiple input multiple output
        # P2PKH UTXO
        self.txin1_multiple = TxInput("24d949f8c77d7fc0cd09c8d5fccf7a0249178c16170c738da19f6c4b176c9f4b", 0)
        self.txin1_multiple_amount = to_satoshis(0.005)
        # P2WSH UTXO
        self.txin2_multiple = TxInput("65f4d69c91a8de54dc11096eaa315e84ef91a389d1d1c17a691b72095100a3a4", 0)
        self.txin2_multiple_amount = to_satoshis(0.0069)
        # P2WPKH UTXO
        self.txin3_multiple = TxInput("6c8fc6453a2a3039c2b5b55dcc59587e8b0afa52f92607385b5f4c7e84f38aa2", 0)
        self.txin3_multiple_amount = to_satoshis(0.0079)

        self.output1_multiple = TxOutput(to_satoshis(0.001), self.p2wsh_addr.to_script_pub_key())
        self.output2_multiple = TxOutput(to_satoshis(0.001), self.sk1.get_public_key().get_segwit_address().to_script_pub_key())
        self.output3_multiple = TxOutput(to_satoshis(0.0177), self.p2pkh_addr.to_script_pub_key())

        # result
        self.create_send_to_p2pkh_result = "0200000001694e8291daeffaaf86f15dbaed39dc8849853115d4669d9028334bed92069a6e000000006a473044022038516db4e67c9217b871c690c09f60a57235084f888e23b8ac77ba01d0cba7ae022027a811be50cf54718fc6b88ea900bfa9c8d3e218208fef0e185163e3a47d9a08012102d82c9860e36f15d7b72aa59e29347f951277c21cd4d34822acdeeadbcff8a546ffffffff0110cd0e00000000002200203956f9730cf7275000f4e3faf5db0505b216222c1f7ca1bdfb81a877003fcb9300000000"
        self.spend_p2pkh_result = "02000000000101ea37e92b68e7dedd87afe58cf5532ba239b0735de3b4d7a25d16d6f2a9ac33620000000000ffffffff0100a60e00000000001976a914fd337ad3bf81e086d96a68e1f8d6a0a510f8c24a88ac040047304402205c88b6c247c6b59e1cc48493b66629b6c011d97b99ecf991b595e891542cf1a802204fa0e3c238818a65adc87a0b2511ba780e4b57ff6c1ba6b27815b1dca7b72c1c01483045022100cec7df71d36a37b979b693c9408ddc1f63325654566fd1b4ee7b6fc18ec601e502203ed5a2c68096d403686cf60b6c1d740b8ae254ec94fc4c35d54f70e4c59a28340147522102d82c9860e36f15d7b72aa59e29347f951277c21cd4d34822acdeeadbcff8a5462103a2fef1829e0742b89c218c51898d9e7cb9d51201ba2bf9d9e9214ebb6af3270852ae00000000"
        self.multiple_input_multiple_ouput_result = "020000000001034b9f6c174b6c9fa18d730c17168c1749027acffcd5c809cdc07f7dc7f849d924000000006a47304402206932c93458a6ebb85f9fd6f69666cd383a3b8c8d517a096501438840d90493070220544d996a737ca9affda3573635b09e215be1ffddbee9b1260fc3d85d61d90ae5012102d82c9860e36f15d7b72aa59e29347f951277c21cd4d34822acdeeadbcff8a546ffffffffa4a3005109721b697ac1d1d189a391ef845e31aa6e0911dc54dea8919cd6f4650000000000ffffffffa28af3847e4c5f5b380726f952fa0a8b7e5859cc5db5b5c239302a3a45c68f6c0000000000ffffffff03a0860100000000002200203956f9730cf7275000f4e3faf5db0505b216222c1f7ca1bdfb81a877003fcb93a086010000000000160014fd337ad3bf81e086d96a68e1f8d6a0a510f8c24a10021b00000000001976a914fd337ad3bf81e086d96a68e1f8d6a0a510f8c24a88ac000400483045022100ff3d84fea8f9ed0f467a4451846a834f94ee00538c5f70637540b8d3ec762e8802204f35aadacaff8e3c5b7d9ba9bb068141f6950feb9da68707249a485f519cbd9d01483045022100b0e1a9f73cb4674d780e24e0a1a7dc96719ce119eb2df2804653990ae2ca32e402203398b490e9caa872463191ba7a4ae84845a94d3b4025ee845491a9f71ea623390147522102d82c9860e36f15d7b72aa59e29347f951277c21cd4d34822acdeeadbcff8a5462103a2fef1829e0742b89c218c51898d9e7cb9d51201ba2bf9d9e9214ebb6af3270852ae024730440220733fcbd21517a1559e9561668e480ffd0a24b62520cfa16ca7689b20f7f82be402204f053a27f19e0bd1346676c74c65e9e452515bc6510ab307ac3a3fb6d3c89ca7012102d82c9860e36f15d7b72aa59e29347f951277c21cd4d34822acdeeadbcff8a54600000000"
Esempio n. 19
0
def get_standard_ct_punish(tx_in: TxInput, payee: Id, script_ct: Script, secret, val: float, fee: float)-> Transaction:

    tx_out = TxOutput(val-fee, payee.p2pkh)
    tx = Transaction([tx_in], [tx_out])
    
    sig = payee.sk.sign_input(tx, 0 , Script(script_ct))

    tx_in.script_sig = Script([secret, sig])
    
    return tx
Esempio n. 20
0
def main():
    # always remember to setup the network
    setup('testnet')

    # create transaction input from tx id of UTXO (contained 0.4 tBTC)
    txin = TxInput(
        '41c0c1b9aff5d2608a00dd458120b86b38b26a19bb80a4085e0e868e4be0941a', 0)

    # create transaction output using P2PKH scriptPubKey (locking scrip
    addr = P2pkhAddress('2NCpHygg5xJ4FJr3p8gpEzyZtX6R8JxNbZF')
Esempio n. 21
0
def spend_all():
    """ creates & broadcasts a transactions that spend all UTXOs from the P2SH"""
    # loads script data (Script, p2sh_addr)
    script, p2sh_addr = csv_script(recreate=True)

    # load transaction data(PrivateKey, timelock, P2pkhAddresses) from data.json
    data = tools.load_data_json(priv=True, timelock_tx=True, p2pk=True)
    priv_key = data['priv_key']
    tx_lock = data['timelock_tx'] 
    p2pkh_addr = data['p2pk_addr']

    # query cli to detect transactions send to the p2sh adddress
    # gathers txid, vout, and amount of p2sh's UTXOs to create TxInputs
    p2sh_utxos, p2sh_balance = [], 0
    wallet_txs = tools.talk_to_cli('bitcoin-cli listtransactions * 900', True)
    for tx in json.loads(wallet_txs):
        if tx['address'] == p2sh_addr and tx['category'] == 'send':
            p2sh_utxos.append(TxInput(tx['txid'], tx['vout'], sequence=tx_lock))
            p2sh_balance += (-tx['amount'])
    # confirm that bitcoin-cli was able to locate transactions to p2sh address
    if not p2sh_utxos:
        errors.missing_utxos()  # prints error msg & raises systemExit

    # check current network fees and compute fee estimate
    resp = requests.get('https://api.blockcypher.com/v1/btc/test3').json()
    fee_per_kb = resp['medium_fee_per_kb']
    # per Output: 34 bytes | per Input: 200 bytes (estimate)
    script_size = 1 * 34 + len(p2sh_utxos) * 200
    fee = (script_size * fee_per_kb) / 100000000
    if fee >= p2sh_balance:
        fee = tools.user_custom_fee(fee, p2sh_balance)        

    # create and sign transaction
    tx_out = TxOutput((p2sh_balance-fee), p2pkh_addr.to_script_pub_key())
    # no change address, spending entire balance
    tx = Transaction(p2sh_utxos, [tx_out])
    pub_key = priv_key.get_public_key().to_hex()
    for i, txin in enumerate(p2sh_utxos):
        sig = priv_key.sign_input(tx, i, script)
        txin.script_sig = Script([sig, pub_key, script.to_hex()])
    tx_signed, tx_id = tx.serialize(), tx.get_txid()

    # writes tx_id into data.json and displays tx_signed (+details) to the user
    tools.update_data_json(outputs={'tx_id': tx_id, 'tx_signed': tx_signed})
    print('\nSpending from P2SH transaction')
    print(' -> to_addr:', p2pkh_addr.to_address())
    print(' -> amount:', p2sh_balance-fee)
    print(' -> fee:', fee)
    print(' -> tx_id:', tx_id)
    print(' -> tx_signed:',tx_signed, '\n')

    # broadcast signed transaction over bitcoin-cli
    r = tools.talk_to_cli(f'bitcoin-cli sendrawtransaction {tx_signed}', True)
    if len(r) == 64:
        print('\nTransaction broadcasted via bitcoin-cli successfully\n')
Esempio n. 22
0
def get_gen_split_tx(tx_in: TxInput, id_l: Id, id_r: Id, script: Script, val_l: int, val_r, fee: float) -> Transaction:
    tx_out0 = TxOutput(val_l-0.5*fee, id_l.p2pkh)
    tx_out1 = TxOutput(val_r-0.5*fee, id_r.p2pkh)
    tx = Transaction([tx_in], [tx_out0, tx_out1])

    sig_l = id_l.sk.sign_input(tx, 0, Script(script))
    sig_r = id_r.sk.sign_input(tx, 0, Script(script))

    tx_in.script_sig = Script([sig_r, sig_l])

    return tx
def main():
    # always remember to setup the network
    setup('regtest')

    # create transaction input from tx id of UTXO (contained 0.4 tBTC)
    txin = TxInput('4d9a6baf45d4b57c875fe83d5e0834568eae4b5ef6e61d13720ef6685168e663', 0)
    # provide unlocking script
    # note that no signing is required to unlock: OP_ADD OP_5 OP_EQUAL
    txin.script_sig = Script(['OP_2', 'OP_3'])

    # create transaction output using P2PKH scriptPubKey (locking script)
    addr = P2pkhAddress('mrCDrCybB6J1vRfbwM5hemdJz73FwDBC8r')
    # locking script expects 2 numbers that when added equal 5 (silly example)
    txout = TxOutput( 0.8, addr.to_script_pub_key() )

    # create transaction from inputs/outputs -- default locktime is used
    tx = Transaction([txin], [txout])

    # print raw transaction
    print("\nRaw transaction:\n" + tx.serialize())
Esempio n. 24
0
    def _tx_encf(self, vk_p, ct_c, sk_u, txin_id, txin_index):
        # create transaction input from tx id of UTXO
        txin = TxInput(txin_id, txin_index)

        # having the vk_p from the shared key generate the corresponding address for decoder to use to respond
        vk_p = PublicKey(vk_p)
        addr_p = vk_p.get_address().to_string()

        # create transaction output using P2PKH scriptPubKey for paying address
        paying_addr = P2pkhAddress(addr_p)
        paying_txout = TxOutput(0.00002, paying_addr.to_script_pub_key())

        # create an output where the address is the ciphertext
        cipher_txout = TxOutput(0.00001,
                                Script(['OP_HASH160', ct_c, 'OP_EQUAL']))

        # create transaction from inputs/outputs -- default locktime is used
        tx = Transaction([txin], [paying_txout, cipher_txout])
        #print("\nRaw unsigned transaction:\n" + tx.serialize())

        # use private key corresponding to the address that contains the UTXO we are trying to spend to sign the input
        vk_u = sk_u.get_public_key()
        addr_u = vk_u.get_address().to_string()

        # note that we pass the scriptPubkey as one of the inputs of sign_input because it is used to replace
        # the scriptSig of the UTXO we are trying to spend when creating the transaction digest
        from_addr = P2pkhAddress(addr_u)
        sig = sk_u.sign_input(
            tx, 0,
            from_addr.to_script_pub_key())  # 0 is for the index of the input

        # set the scriptSig (unlocking script)
        vk_u = vk_u.to_hex()
        txin.script_sig = Script([sig, vk_u])
        signed_tx = tx.serialize()

        print("Users input address: ", addr_u)
        print("Decoder paying address: ", addr_p)
        print("\nRaw signed transaction:\n" + signed_tx)

        return signed_tx
Esempio n. 25
0
def get_htlc(tx_in: TxInput, id_l: Id, id_r: Id, secret, hashed_secret, val_l: float, val_r: float, fee: float, l: bool, timelock) -> Transaction:
    tx_out = TxOutput(val_l-fee/2, scripts.get_script_lightning_locked(id_l, id_r, hashed_secret, timelock)) # output to l

    tx = Transaction([tx_in], [tx_out])

    scriptFToutput = scripts.get_script_ft_output(id_l, id_r)

    sig = id_l.sk.sign_input(tx, 0, scriptFToutput) # referenced tx is ft

    tx_in.script_sig = Script([sig, secret])

    return tx
Esempio n. 26
0
def get_gen_ct_tx(tx_in: TxInput, id_l: Id, id_r: Id, id_as_l: Id, hashed_secret_rev_l, id_as_r: Id, hashed_secret_rev_r, val: float, fee: float, timelock: int) -> Transaction:
    timelock = 0x2
    tx_out = TxOutput(val-fee, scripts.get_script_split(id_l, id_r, id_as_l, hashed_secret_rev_l, id_as_r, hashed_secret_rev_r, timelock))
    tx = Transaction([tx_in], [tx_out])

    scriptFToutput = scripts.get_script_ft_output(id_l, id_r)

    sig_l = id_l.sk.sign_input(tx, 0 , scriptFToutput)
    sig_r = id_r.sk.sign_input(tx, 0 , scriptFToutput)

    tx_in.script_sig = Script([sig_r, sig_l])

    return tx
Esempio n. 27
0
 def getInputs():
     inputs = []
     count = 0
     for utxo in all_utxos:
         #create inputs and append them into an array
         #First, create an input
         utxo = all_utxos[count]
         txin = TxInput(utxo["txid"],
                        utxo["vout"],
                        sequence=seq.for_input_sequence())
         #then, append it to the array
         inputs.append(txin)
         ++count
     return inputs
Esempio n. 28
0
    def _tx_encb(self, sk_s, ct_r, txin_id, txin_index):
        # create transaction input from tx id of UTXO
        txin = TxInput(txin_id, txin_index)

        # create an output where the address is the ciphertext[0:20]
        cipher1_txout = TxOutput(
            0.000001,
            Script([
                'OP_DUP', 'OP_HASH160', ct_r[:40], 'OP_EQUALVERIFY',
                'OP_CHECKSIG'
            ]))

        # create another output where the address is the ciphertext[20:40]
        cipher2_txout = TxOutput(0.000001,
                                 Script(['OP_HASH160', ct_r[40:], 'OP_EQUAL']))

        # create transaction from inputs/outputs -- default locktime is used
        tx = Transaction([txin], [cipher1_txout, cipher2_txout])
        #print("\nRaw unsigned transaction:\n" + tx.serialize())

        # use private key corresponding to the address that contains the UTXO we are trying to spend to sign the input
        vk_p = sk_s.get_public_key()
        addr_p = vk_p.get_address().to_string()

        # note that we pass the scriptPubkey as one of the inputs of sign_input because it is used to replace
        # the scriptSig of the UTXO we are trying to spend when creating the transaction digest
        from_addr = P2pkhAddress(addr_p)
        sig = sk_s.sign_input(tx, 0, from_addr.to_script_pub_key())

        # set the scriptSig (unlocking script)
        vk_p = vk_p.to_hex()
        txin.script_sig = Script([sig, vk_p])
        signed_tx = tx.serialize()

        print("\nRaw signed transaction:\n" + signed_tx)
        return signed_tx
Esempio n. 29
0
def main():
    # always remember to setup the network
    setup('testnet')

    # the key that corresponds to the P2WPKH address
    priv = PrivateKey("cVdte9ei2xsVjmZSPtyucG43YZgNkmKTqhwiUA8M4Fc3LdPJxPmZ")

    pub = priv.get_public_key()

    fromAddress = pub.get_segwit_address()
    print(fromAddress.to_string())

    # amount is needed to sign the segwit input
    fromAddressAmount = to_satoshis(0.01)

    # UTXO of fromAddress
    txid = '13d2d30eca974e8fa5da11b9608fa36905a22215e8df895e767fc903889367ff'
    vout = 0

    toAddress = P2pkhAddress('mrrKUpJnAjvQntPgz2Z4kkyr1gbtHmQv28')

    # create transaction input from tx id of UTXO
    txin = TxInput(txid, vout)

    # the script code required for signing for p2wpkh is the same as p2pkh
    script_code = Script([
        'OP_DUP', 'OP_HASH160',
        pub.to_hash160(), 'OP_EQUALVERIFY', 'OP_CHECKSIG'
    ])

    # create transaction output
    txOut = TxOutput(to_satoshis(0.009), toAddress.to_script_pub_key())

    # create transaction without change output - if at least a single input is
    # segwit we need to set has_segwit=True
    tx = Transaction([txin], [txOut], has_segwit=True)

    print("\nRaw transaction:\n" + tx.serialize())

    sig = priv.sign_segwit_input(tx, 0, script_code, fromAddressAmount)
    tx.witnesses.append(Script([sig, pub.to_hex()]))

    # print raw signed transaction ready to be broadcasted
    print("\nRaw signed transaction:\n" + tx.serialize())
    print("\nTxId:", tx.get_txid())
def main():
    # always remember to setup the network
    setup('testnet')

    priv0 = PrivateKey("cN1XE3ESGgdvr4fWsB7L3BcqXncUauF8Fo8zzv4Sm6WrkiGrsxrG")

    pub = priv0.get_public_key()
    fromAddress = pub.get_segwit_address()

    priv1 = PrivateKey("cN1XE3ESGgdvr4fWsB7L3BcqXncUauF8Fo8zzv4Sm6WrkiGrsxrG")

    # P2SH Script: OP_M <Public key 1> <Public key 2> ... OP_N OP_CHECKMULTISIG
    p2sh_redeem_script = Script(
        ['OP_1',
         priv1.get_public_key().to_hex(), 'OP_1', 'OP_CHECKMULTISIG'])

    toAddress = P2wshAddress.from_script(p2sh_redeem_script)

    # set values
    txid = 'd222d91e2da368ac38e84aa615c557e4caeacce02aa5dbca10d840fd460fc938'
    vout = 0
    amount = Decimal('0.01764912')

    # create transaction input from tx id of UTXO
    txin = TxInput(txid, vout)
    redeem_script1 = Script([
        'OP_DUP', 'OP_HASH160',
        priv0.get_public_key().to_hash160(), 'OP_EQUALVERIFY', 'OP_CHECKSIG'
    ])

    # create transaction output
    txOut1 = TxOutput(Decimal('0.0001'), toAddress.to_script_pub_key())
    txOut2 = TxOutput(Decimal('0.01744912'), fromAddress.to_script_pub_key())

    # create transaction
    tx = Transaction([txin], [txOut1, txOut2], has_segwit=True)

    print("\nRaw transaction:\n" + tx.serialize())

    sig1 = priv0.sign_segwit_input(tx, 0, redeem_script1, amount)
    tx.witnesses.append(Script([sig1, pub.to_hex()]))

    # print raw signed transaction ready to be broadcasted
    print("\nRaw signed transaction:\n" + tx.serialize())
    print("\nTxId:", tx.get_txid())