Broadcasting a transaction with libbitcoin is as simple as making function call, not unlike checking an addresses balance.
This makes it easy for us to append this functionality to our existing raw transaction script. If you haven’t already read about creating a raw transaction, click here.
Now all we have to do is add the connection settings to our script and write two callback handlers. Both will have the same functionality, returning an error code’s message, this will let us know if the broadcast succeeded.
Like So:
client::connection_type connection = {}; connection.retries = 3; connection.timeout_seconds = 8; connection.server = config::endpoint("tcp://testnet.libbitcoin.net:19091"); client::obelisk_client client(connection); if(!client.connect(connection)) { std::cout << "Fail" << std::endl; } else { std::cout << "Connection Succeeded" << std::endl; } static const auto on_done = [](const code& ec) { std::cout << "Success: " << ec.message() << std::endl; }; static const auto on_error2 = [](const code& ec) { std::cout << "Error Code: " << ec.message() << std::endl; };
Now, we simply need to call the client’s broadcast function and pass both our handlers and the transaction object that was formed by our script. Followed by the wait function.
client.transaction_pool_broadcast(on_error2, on_done, tx); client.wait();
As usual we can compile this with g++ and run it.
alpha$ g++ -std=c++11 -o rawTX rawTX.cpp HD_WalletTESTNET.cpp $(pkg-config --cflags libbitcoin --libs libbitcoin libbitcoin-client) alpha$ ./rawTX
The output should look similar to this. Our transaction can also be verified by checking the block explorer at blockcypher.com
As always, the sample code in its entirety can be found on github.