C# parse bitcoin blockchain to get balance of an address



Is there a way to scan the Bitcoin blockchain in C# without using an external API? I am looking for the amount of spendable money of a Bitcoin address.

I am using NBitcoin.

// create new key pair based on private key
NBitcoin.Key key = new NBitcoin.Key(privateKey, privateKey.Length, false);

// parse blk*.dat
// get balance for address key.PubKey.Hash
// How to do that?

Pa Ddy

Posted 2015-06-15T21:32:03.330

Reputation: 71

Yes, this is certainly possible to do. The blockchain contains all the information needed. – Greg Hewgill – 2015-06-15T22:16:56.843

@GregHewgill how he will query blockchain with NBitcoin? – Igor Barinov – 2015-06-16T01:18:54.207

I'm afraid I don't know anything about how to use NBitcoin specifically. However, I've done exactly this with Python (for the blockchain of a different coin, but the structure is largely the same), so it's certainly possible. – Greg Hewgill – 2015-06-16T01:20:34.160

http://www.codeproject.com/Articles/784519/NBitcoin-How-to-scan-the-Blockchain – Sebastian Xawery Wiśniowiecki – 2015-07-26T11:58:12.213



How about running a QBitNinja server locally?

var client = new QBitNinjaClient(baseAddress:"specify host here, you probably want localhost", Network.TestNet);
var balanceModel = client.GetBalance(dest: [Add any IDestination here, like new BitcoinAddress("mivD5GHroixrzgjv6Ww73pV5R55PcL8JdM", Network.TestNet)], unspentOnly: true).Result;
if (balanceModel.Operations.Count == 0) 
    throw new Exception("No coins to spend");
var unspentCoins = new List<Coin>();
foreach (var operation in balanceModel.Operations)
            unspentCoins.AddRange(operation.ReceivedCoins.Select(coin => coin as Coin)); 
var balance = unspentCoins.Sum(x => x.Amount.ToDecimal(MoneyUnit.BTC));


Posted 2015-06-15T21:32:03.330

Reputation: 642


You can always use http://blockchainsql.io to SQL query the Bitcoin blockchain.

Disclaimer: I am the developer.

Herman Schoenfeld

Posted 2015-06-15T21:32:03.330

Reputation: 131

Just a note: when I click on GitHub/Twitter/Facebook or any contact link nothing happens. – nopara73 – 2017-10-26T14:58:31.477