본문으로 바로가기

비트코인 특정주소의 잔액을 확인하는 프로그램을 작성해보도록 하겠습니다.


다음 코드는 하기 Tutorial을 참고로 하고 있습니다.

http://aaronjaramillo.org/libbitcoin-checking-an-address-balance


그리고 작성된 코드는 다음의 github에서 다운로드 받을수 있습니다.

https://github.com/ihpark92/Libbitcoin_Tutorial/


먼저 다음과 같이 client.hpp를 include 하도록 하고 Balance.cpp로 저장을 합니다.


#include <bitcoin/bitcoin.hpp>
#include <bitcoin/client.hpp>
#include <string.h>
#include <iostream>
using namespace bc;


그리고 다음과 같이 잔액을 확인하는 함수를 정의합니다.

구현부는 이전 포스팅의 비트코인 네트워크의 블록높이를 확인하는 코드와 동일합니다.


void getBalance(wallet::payment_address address)
{
client::connection_type connection = {};
connection.retries = 3;
connection.timeout_seconds = 8;
connection.server = config::endpoint("tcp://mainnet.libbitcoin.net:9091");
client::obelisk_client client(connection);


이어서 다음과 같이 쿼리 호출시에 정상접속의 경우와 에러발생시의 2개의 콜백함수를 정의합니다.

정상접속의 경우에는 하기에 balancer 함수를 호출하여 잔액을 계산합니다. balance 함수는 아래에서 다시 구현합니다.


static const auto on_done = [](const chain::history::list& rows)
{
uint64_t balance = balancer(rows);
std::cout<< encode_base10(balance, 8) << std::endl;
};
static const auto on_error2 = [](const code ec) {
std::cout << "Error Code: " << ec.message() << std::endl;
};


그리고 네트워크에 접속한후에 fetch history 함수를 콜백함수와 잔액조회를 원하는 주소를 인자로 하여 호출합니다.


if(!client.connect(connection))
{
std::cout << "Fail" << std::endl;
} else {
std::cout << "Connection Succeeded" << std::endl;
}
client.blockchain_fetch_history3(on_error2, on_done, address);
client.wait();


콜백에서 호출하는 balancer 함수는 다음과 같이 미사용한 tx의 hash 값을 확인하고 잔액을 증가하도록 계산하여 최종적으로 해당 주소의 총잔액을 계산합니다.


uint64_t balancer(const chain::history::list& rows)
{
uint64_t unspent_balance = 0;
for(const auto& row: rows)
{
// spend unconfirmed (or no spend attempted)
if (row.spend.hash() == null_hash)
unspent_balance += row.value;
}
return unspent_balance;
}


main 함수는 다음과 같이 특정 주소를 인자로 하여 잔액조회를 합니다.


int main()
{
wallet::payment_address addy("15QzCiznJXqihKmNTgcxwS8nf7sdSXBAE9");
getBalance(addy);
}


위의 주소의 잔액을 조회한 결과는 다음과 같습니다.



위의 주소의 실제잔액을 확인해보면 다음과 같습니다.