Libbitcoin Node

From Bitcoin Wiki
Revision as of 20:16, 8 March 2017 by Evoskuil (talk | contribs) (→‎Example: Update example for v3 release.)
Jump to navigation Jump to search

The libbitcoin-node library provides an abstraction over the low level networking calls required to implement a full node on the Bitcoin peer-to-peer network. It was originally contained within libbitcoin.

Example (Version3)

#include <future>
#include <iostream>
#include <bitcoin/node.hpp>

int main()
{
    std::cout << "Starting up..." << std::endl;

    bc::threadpool pool(1);
    bc::node::configuration settings(bc::config::settings::mainnet);
    bc::node::full_node node(settings);
    std::promise<bc::code> started;

    const auto handle_started = [&started](const bc::code& ec)
    {
        started.set_value(ec);
    };

    // To also "run" the node on the p2p nework next call node.run(...).
    node.start(handle_started);

    const auto ec = started.get_future().get();

    if (ec)
    {
        std::cout << "The node failed to start: " << ec.message() << std::endl;
        return 1;
    }

    const auto display_history = [](const bc::code& code,
        const bc::chain::history_compact::list& history)
    {
        if (code)
        {
            std::cout << "Error: " << code.message();
            return;
        }

        for (const auto& entry : history)
        {
            auto output = (entry.kind == bc::chain::point_kind::output);
            auto kind = (output ? "output" : "spend");
            auto height = entry.height;
            auto hash = bc::encode_hash(entry.point.hash());
            auto index = entry.point.index();

            // The value for a spend is the entry.point.checksum() of the
            // output. This allows the spends to be correlated to outputs.
            std::cout << "History..." << std::endl;
            std::cout << "Kind: " << kind << std::endl;
            std::cout << "Height: " << height << std::endl;
            std::cout << "Point: " << hash << ":" << index << std::endl;
            std::cout << "Value: " << entry.value << std::endl;
            std::cout << std::endl;
        }
    };

    while (true)
    {
        std::cout << "Type a bitcoin address or 'stop' to exit." << std::endl;

        std::string command;
        std::getline(std::cin, command);

        if (command == "stop")
            break;

        bc::wallet::payment_address address(command);

        if (!address)
        {
            std::cout << "Invalid address: " << command << std::endl;
            continue;
        }

        // Accept up to 1000 rows and search from block 0.
        node.chain().fetch_history(address, 1000, 0, display_history);
    }

    std::cout << "Shutting down..." << std::endl;

    return 0;
}

Console Application

The library is accompanied by the console application Bitcoin Node (bn).

Design

Dependencies (Version2)

Dependencies (Version3)

See Also

References