C++ code for traverse though all the blocks in blockchain?

2

1

In my project for one particular functionality, I want to traverse through all the Transactions. For that purpose I want to traverse through all the blocks in blockchain.

Rasela Don

Posted 2014-10-28T10:31:42.353

Reputation: 319

Answers

3

If you are intent on doing it with c++, there is a blockchain parsing library that may help you here https://code.google.com/p/blockchain/.

Depending on your application, though, I might recommend just writing a terminal script to use the daemon. It probably won't be as fast, but I bet it would be easier to get up quickly. These commands can be called to get you the info you need:

// Gets the block at index index
./bitcoin-cli getblockhash {index}

// Gets the block using the result of the first statement
./bitcoind-cli getblock {hash} 

// The block has an array of transactions in it
for (Tx tx : block.tx) {
    ./bitcoind-cli getrawtransaction {tx} 1
}

morsecoder

Posted 2014-10-28T10:31:42.353

Reputation: 12 624

What language is that? Or is it pseudocode?Nick ODell 2014-10-28T17:22:23.027

Oh, and you have to use ./bitcoin-cli now.Nick ODell 2014-10-28T17:23:32.987

Pseudo code. Yeah, you're right, I'll change.morsecoder 2014-10-28T17:25:36.940

1Also make sure you enable txindex=1 in your bitcoin.conf and run build the transaction index (bitcoind -reindex) before you iterate all (=also non-wallet) transactions.behas 2014-10-29T08:34:13.223

Thank you very much for the answer. It is really helpful Stephen. By the way, Is there any method to retrieve the last index of the block received? If so it would be helpful for me to run a for loop to get all the blockhashes.Rasela Don 2014-10-29T15:26:25.810

Glad it helped! you probably want to do something like while $(./bitcoin-cli getblockhash(i)) != null,error, because the best block when you start running this code won't be the best block when you finish running it. If you just want the height of your blockchain, look in $(./bitcoin-cli getinfo)morsecoder 2014-10-29T15:37:55.960