What piece of code would allow me to check if a block has been found then run an operation?

0

I am relatively new to C++ and I was wondering if anybody could help me out. I am looking piece of code that will loop until a block is found by a node and then when one is found print a simple output like "Block found".

Thanks!

Cheese

Posted 2014-03-24T20:45:22.813

Reputation: 61

Is C++ really a requirement for this? I'm an avid C++ programmer myself and I would not want to do this in C++. And alternative would be python or even bash. Also, what OS are you targeting?Tyler 2014-04-23T21:19:41.020

Answers

1

You could simply record the value of bitcoind getblockcount somewhere and see when that changes by calling getblockcount repeatedly.

Luca Matteis

Posted 2014-03-24T20:45:22.813

Reputation: 4 784

1If I was running bitcoind, personally I would enable the blocknotify config setting and do away with the repetitive polling.ChrisW 2014-04-23T22:22:23.337

-1

#include <string>
#include <iostream>
#include <stdio.h>

std::string exec(char* cmd) {
    FILE* pipe = popen(cmd, "r");
    if (!pipe) return "ERROR";
    char buffer[128];
    std::string result = "";
    while(!feof(pipe)) {
        if(fgets(buffer, 128, pipe) != NULL)
            result += buffer;
    }
    pclose(pipe);
    return result;
}

int main(){
    int count;
    count = stoi(exec("bitcoind getblockcount"));
    for(;;){
        int new_count = stoi(exec("bitcoind getblockcount"));
        while(count < new_count){
            std::cout << "Block found." << std::endl;
            count++;
        }
        system("sleep 1"); // There are other ways of sleeping. This is the quick and dirty way.
    }
    return 0;
}

To be fair, this is a rip off of Luca's idea and https://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c.

Tyler

Posted 2014-03-24T20:45:22.813

Reputation: 591