How to create and broadcast tx with multiple inputs in python bitcoinlib?

1.1k views Asked by At

I'm trying to create a transaction with multiple inputs in bitcoinlib. I pasted an example from examples in bitcoinlib repo:

from bitcoinlib.transactions import *
from bitcoinlib.services.services import *
import requests

amount = 19605 # in satoshis
t = Transaction(fee=5000, outputs=[Output(amount, address="to address")])
transaction_inputs = [
    ("b0514d3d47bffdf588e14e0324c88e4934a36423f011d634b4e379b3a65c5207", 0, "wif private key"),
    ("4e831f9221470f93cc0cd2e0ef0e2f731c5bbfde0e8fc2ae430b31149ffd25bb", 1, "wif private key")
]
for ti in transaction_inputs:
    ki = Key(ti[2])
    t.add_input(prev_txid=ti[0], output_n=ti[1], keys=ki.public())
icount = 0
for ti in transaction_inputs:
    ki = Key(ti[2])
    t.sign(ki.private_byte, icount)
    icount += 1

print(t.verify())
rawhextx = t.raw_hex()
tx = Service().sendrawtransaction(rawhextx)
print(tx)

sendrawtransaction returns False. t.verify() is True. Also I tried to broadcast tx by myself with POST request to blockchain.info:

>>> resp = requests.post("https://blockchain.info/pushtx", data={"tx": rawhextx})
>>> resp.text
'Code: -25, Error: bad-txns-inputs-missingorspent'

As far as I understood, this error means that my UTXOs are already spent, but they aren't (i specified txs with my UTXOs above). I would like to use this library, but I am open to suggestions of alternatives, if this library isn't suitable for my task.

1

There are 1 answers

0
phonkuser On BEST ANSWER

I solved it. "output_n" is index of output, related to sender address in "prev_txid" tx, not an index of tx inputs. Changing all second values in tuples to 0 helped, as outputs to its addresses had first indexes.

from bitcoinlib.transactions import *
from bitcoinlib.services.services import *
import requests

amount = 19605 # in satoshis
t = Transaction(fee=5000, outputs=[Output(amount, address="to address")])
transaction_inputs = [
    ("b0514d3d47bffdf588e14e0324c88e4934a36423f011d634b4e379b3a65c5207", 0, "wif private key"),
    ("4e831f9221470f93cc0cd2e0ef0e2f731c5bbfde0e8fc2ae430b31149ffd25bb", 0, "wif private key")
]
for ti in transaction_inputs:
    ki = Key(ti[2])
    t.add_input(prev_txid=ti[0], output_n=ti[1], keys=ki.public())
icount = 0
for ti in transaction_inputs:
    ki = Key(ti[2])
    t.sign(ki.private_byte, icount)
    icount += 1

print(t.verify())
rawhextx = t.raw_hex()
tx = Service().sendrawtransaction(rawhextx)
print(tx)