getrawtransaction seems to only work for certain transactions

1

1

I am working through mastering bitcoin. I am confused by getrawtransaction. I would like to look at the first transaction in block 277316.

from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException

# rpc_user and rpc_password are set in the bitcoin.conf file
p = AuthServiceProxy("http://%s:%s@127.0.0.1:8332"%(username, pw))

# look at specific block 
blockheight = 277316

# get the hash of that block
block_hash = p.getblockhash(277316)

# get the block 
block = p.getblock(block_hash)

# get the transactions in the block
transactions = block['tx']
first_transaction = transactions[0]
print p.getrawtransaction(first_transaction)

Gives this error:

bitcoinrpc.authproxy.JSONRPCException: -5: No such mempool transaction. Use -txindex to enable blockchain transaction queries. Use gettransaction for wallet transactions.

It seems like it only wants to look in the mempool. How do I use the -txindex parameter it suggests?

If I run the below code, it works fine. This is also a transaction from the same block (64th transaction) and clearly not in the mempool. What is the difference between this and the how I get the transaction id in the above code?

print p.getrawtransaction('0627052b6f28912f2703066a912ea577f2ce4da4caa5a5fbd8a57286c345c2f2')

user2242044

Posted 2017-09-30T02:08:37.970

Reputation: 177

Answers

3

getrawtransaction is only guaranteed to work for mempool transactions, unless you're running with the -txindex command line flag, or txindex=1 in your bitcoin.conf file.

In practice it works for all transactions that have at least one unspent output remaining, but it's relatively slow, and functionality that may be removed at some point.

Pieter Wuille

Posted 2017-09-30T02:08:37.970

Reputation: 54 032

Thanks. Is there a better way of doing this since you mentioned this is slow?user2242044 2017-09-30T13:20:32.020

1Use a specialized indexing service, there are several projects doing that. Bitcoin Core's intention is validating blocks and transaction, with the least amount of resources. Maintaining an index to query arbitrary transactions does not fit into that.Pieter Wuille 2017-09-30T15:55:22.350