Sending Transactions with NBitcoin and .NET

Sending Transactions with NBitcoin and .NET block-height 850458 02 Jul 2024

Sending to a Legacy Address from NBitcoin

This is more of a curiosity than anything. I have been dotnet developer for a few years and love C#. I’ve actually looked at the library for interacting with the Bitcoin network before but never really did anything with it. So this will likely be part one of a series on working with it. I have use bitcoinjs n the past but find that NBitcoin is more supported at least as far as more recent commits and is what is used in BTCPay Server. At this point I will be using Regtest and likely move to using some TestNet coins that I have. For the github gist

Getting Setup?

Send some amount of coins to a legacy address that I have created. This can be done using NBitcoin like so:

Network network = Network.RegTest;
Key bitcoinPrivateKey = new Key().GetBitcoinSecret(network);
var legacyAddress = bitcoinPrivateKey.PubKey.GetAddress(ScriptPubKeyType.Legacy, network);
Console.WriteLine(legacyAddress); //mtdFu4Qb8why1t71zpUpKkXpsCfjbYbUKj
BitcoinSecret bitcoinSecret = bitcoinPrivateKey.GetWif(Network.RegTest);
Console.WriteLine(bitcoinSecret); // cU6GUowDkCVQPhy3dsD6RwkoyBeHk41rYMYExhs5VZH8URabKFyv make sure to save this you'll need it later...

In my instance this led an address like so mtdFu4Qb8why1t71zpUpKkXpsCfjbYbUKj and I simply sent some regtest coins to it. alt text

Get the transaction Id and in your console/cli get the hex value for the transaction. Save that in the var transaction = Transaction.Parse("0200000004...", network); as we will parse that to get our outputs for the new inputs to send again to our other address.


getrawtransaction 7243d2760388821371b39ef98212d24c7d43d3541790294213b407bf9ffdf3ab



Complete Code Sample

If you have gotten this far you should be able to paste in your saved WIF secret (Wallet Import Format) and another address to send coins to. I did this using Bitcoin Core, but you could do the same as above. Something else to note, is that the miner fee is purely an excercise here. I imagine that in most situations you would want to do this with better estimation, and same with the coins. I am simply parsing the transaction hex for the prior address I know I have coins in to spend from again. Also, this does not take into account change back. Like I said I was mostly doing this for my own edification. But anyways, hope someone finds it helpful.

using NBitcoin;
using NBitcoin.Protocol;

public class LegacyPayToAddress
    public static void Run()
        //We will send the coins from this address mtdFu4Qb8why1t71zpUpKkXpsCfjbYbUKj to the one below and has the available output from 
        //the transaction with the hash 597ca9461b98b541f4d63e4679381947df7698c26750b1ad611bf08e947be2ac
        Network network = Network.RegTest;
        //Key bitcoinPrivateKey = new Key();
        //var legacyAddress = bitcoinPrivateKey.PubKey.GetAddress(ScriptPubKeyType.Legacy, network); 
        //Console.WriteLine(legacyAddress); //mtdFu4Qb8why1t71zpUpKkXpsCfjbYbUKj
        //BitcoinSecret bitcoinSecret = bitcoinPrivateKey.GetWif(Network.RegTest); 
        // Console.WriteLine(bitcoinSecret); // cU6GUowDkCVQPhy3dsD6RwkoyBeHk41rYMYExhs5VZH8URabKFyv
        var bitcoinSecret = new BitcoinSecret("cU6GUowDkCVQPhy3dsD6RwkoyBeHk41rYMYExhs5VZH8URabKFyv", network);
        var addressToSendTo = new BitcoinPubKeyAddress("n2WmqedHyr8j6kTh6VCZ4Yu3gwoCRmH8jo", network);
        var transaction = Transaction.Parse("0200000004691fb673...,network);

        Coin coin = new Coin();
        Money totalToSend = new Money(0, MoneyUnit.BTC);

        TxOutList outputs = transaction.Outputs;

        foreach (TxOut output in outputs)
            var paymentScript = output.ScriptPubKey;
            var address1 = paymentScript.GetDestinationAddress(network);
            if(address1 == bitcoinSecret.PubKey.GetAddress(ScriptPubKeyType.Legacy, network)) //Check if the address is the same as the one we have the private key for (a bit naive, but it works for this example)
                Console.WriteLine("This is your money");
                var minerFee = new Money(0.00007m, MoneyUnit.BTC); //Need to set a fee to get it mined by the network
                coin = new Coin(transaction,output);
                var outputValue = new Money(output.Value, MoneyUnit.Satoshi);
                totalToSend = outputValue - minerFee; //We will send all the money, minus the fee
        using (var node = Node.ConnectToLocal(network)) //Connect to the node
            var transactionToSend = Transaction.Create(network);
            transactionToSend.Inputs.Add(new TxIn()
                PrevOut = coin.Outpoint, ScriptSig = bitcoinSecret.PubKey.ScriptPubKey

            transactionToSend.Outputs.Add(totalToSend, addressToSendTo.ScriptPubKey);


            transactionToSend.Sign(bitcoinSecret, coin);
            node.SendMessage(new InvPayload(InventoryType.MSG_TX, transactionToSend.GetHash()));
            node.SendMessage(new TxPayload(transactionToSend));


Note also that I am using the node here and not sure exactly how that is working as I am only using Regtest and not sure if is interacting with the node as a peer? Or if it’s some RPC methods being called. I need to find out more.

If All Goes Well

You should see another transaction and your coins, minus the fee have moved to that other address. And will be spendable again as a new UTXO (unspent transaction output). alt text