비트코인 네트워크에 접속하기 위해서 Libbitcoin 라이브러리 패키지에서 추가 라이브러리를 설치하도록 하겠습니다.
하기 2개의 라이브러리를 추가로 설치하시기 바랍니다.
https://github.com/libbitcoin/libbitcoin-protocol.git
https://github.com/libbitcoin/libbitcoin-client.git
Libbitcoin 라이브러리는 비트코인 P2P 네트워크에 접속하기 위한 하이레벨 API를 제공합니다.
비동기 API를 지원하기 때문에 API를 호출할때에 콜백을 등록해야 합니다.
다음 코드는 하기 Tutorial을 참고로 하고 있습니다.
http://aaronjaramillo.org/libbitcoin-connecting-to-the-network
그리고 작성된 코드는 다음의 github에서 다운로드 받을수 있습니다.
https://github.com/ihpark92/Libbitcoin_Tutorial/
먼저 다음과 같이 client.hpp 를 추가로 include 하고 HelloBlockChain.cpp 로 저장을 합니다.
#include <bitcoin/bitcoin.hpp>#include <bitcoin/client.hpp>#include <string.h>#include <iostream>#include <cstdint>using namespace bc;
그리고 다음과 같이 connection 객체를 선언한후에 retry 횟수와 timeout값, 그리고 비트코인 메인넷 주소와 포트번호를 명시합니다.
int main(){client::connection_type connection = {};connection.retries = 3;connection.timeout_seconds = 8;connection.server = config::endpoint("tcp://mainnet.libbitcoin.net:9091");
비동기 API를 호출하기 위해 다음과 같이 2개의 콜백함수를 정의합니다.
on_reply 함수는 정상적으로 접속된 경우 블록의 갯수를 반환하고, on_error는 에러발생시 에러코드를 반환합니다.
const auto on_reply = [](size_t blockHeight){std::cout << "Height: " << blockHeight << std::endl;};static const auto on_error = [](const code& ec){std::cout << "Error Code: " << ec.message() << std::endl;};
콜백함수 정의후에 다음과 같이 비트코인 네트워크에 접속후 결과를 출력합니다.
client::obelisk_client client(connection);if(!client.connect(connection)){std::cout << "Fail" << std::endl;} else {std::cout << "Connection Succeeded" << std::endl;}
접속이 완료되면 다음과 같이 마지막 블록높이를 반환하는 쿼리를 호출하고, 비동기 호출이 실행되도록 wait 함수를 호출합니다.
client.blockchain_fetch_last_height(on_error, on_reply);client.wait();
저장후에 다음과 같이 빌드합니다.
$ g++ -std=c++11 -o height HelloBlockChain.cpp $(pkg-config --cflags libbitcoin --libs libbitcoin libbitcoin-client)
실행결과는 다음과 같습니다.
비트코인 메인넷의 블록높이는 515677 임을 출력하고 있습니다.
실제 메인넷의 블록높이를 확인시에 가장 마지막블록의 번호가 515676이기 때문에 블록의 높이는 515677 임을 확인할수 있습니다.
(0번 블록이 최초의 제네시스 블록)
'비트코인 > Libbitcoin 프로그래밍' 카테고리의 다른 글
Libbitcoin 라이브러리를 사용하여 Bitcoin testnet에 raw transaction 전송하기 (0) | 2018.04.04 |
---|---|
Libbitcoin 라이브러리를 사용하여 주소의 잔액 확인하기 (0) | 2018.03.29 |
Libbitcoin 라이브러리를 사용하여 raw transaction 생성하기 (0) | 2018.03.29 |
Libbitcoin 라이브러리를 사용하여 Multisig 스크립트 생성하기 (0) | 2018.03.27 |
Libbitcoin 라이브러리를 사용하여 대화형 HD 키생성 지갑 만들기 [2/2] (0) | 2018.03.24 |