2

I am using the NBitcoin Library to program a simple Bitcoin Transfer Program in C#.

The Program will take the coins from a Transaction ID and then Transfer it to a Destination Wallet Address

The Code to this program can be found from the Book - "Programming the BlockChain in C# - ( Community Edition )" on Pages 37 to 43

I have included the C# Code to this Thread as below.

I have created a TestNet Test Wallet and is using the Wallet Address to Receive the Program's Bitcoins.

The TestNet Test Wallet can be created at -

http://testnetwallet.com/wallet

To get the TestNet Test Wallet's Address, I log into my TestNet Wallet and click on the Receive "Button". A window pops up and in it is the TestNet Wallet's Receiving Address.

I am trying to send my Bitcoins to this Receiving Address and some how the Bitcoins just does not get into the Wallet.

The Program says that the Transactions is successful and it even returns a Transaction ID.

But upon checking the TestNet Wallet, I do not find any Transactions at all, nor do I find any newly deposited Bitcoins ?

Can some kind soul please kindly look through the C# code attached below to see what is wrong ?

I am using the NBitCoin C# Library with Visual Studio 2015.

The Below Code is included into a "Visual C# Console Program" in Visual Studio 2015.

// ReSharper disable All
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NBitcoin;
using NBitcoin.Protocol;
using QBitNinja.Client;
using QBitNinja.Client.Models;

namespace SpendYourCoins
{
    class Program
    {
        static void Main()
        {

            /*
            #region CREATE NEW PRIVKEY
            //var network = Network.TestNet;
            //Key privateKey = new Key();
            //var bitcoinPrivateKey = privateKey.GetWif(network);
            #endregion

            */

            #region IMPORT PRIVKEY
            var bitcoinPrivateKey = new BitcoinSecret("cTNoQtcdj9ZRV9XRNDFVisbif2XMSbxEbtP5WZTGJ2sGW9gSRr7Q");
            var network = bitcoinPrivateKey.Network;
            #endregion

            var address = bitcoinPrivateKey.GetAddress();

            Console.WriteLine(bitcoinPrivateKey); // cSZjE4aJNPpBtU6xvJ6J4iBzDgTmzTjbq8w2kqnYvAprBCyTsG4x
            Console.WriteLine(address); // mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv
            Console.WriteLine();



            var client = new QBitNinjaClient(Network.TestNet);
            var transactionId = uint256.Parse("12e548ababf06160486f91bfa2a406f131631258b2db025eb36bcd5230a70524");
            var transactionResponse = client.GetTransaction(transactionId).Result;

            Console.WriteLine(transactionResponse.TransactionId); // e44587cf08b4f03b0e8b4ae7562217796ec47b8c91666681d71329b764add2e3
            Console.WriteLine(transactionResponse.Block.Confirmations);
            Console.WriteLine();

            var receivedCoins = transactionResponse.ReceivedCoins;
            OutPoint outPointToSpend = null;
            foreach (var coin in receivedCoins)
            {
                if (coin.TxOut.ScriptPubKey == bitcoinPrivateKey.ScriptPubKey)
                {
                    outPointToSpend = coin.Outpoint;
                }
            }
            if(outPointToSpend == null)
                throw new Exception("TxOut doesn't contain our ScriptPubKey");
            Console.WriteLine("We want to spend {0}. outpoint:", outPointToSpend.N + 1);

            var transaction = new Transaction();
            transaction.Inputs.Add(new TxIn()
            {
                PrevOut = outPointToSpend
            });

            // var hallOfTheMakersAddress = new BitcoinPubKeyAddress("1KF8kUVHK42XzgcmJF4Lxz4wcL5WDL97PB");
            //var hallOfTheMakersAddress = new BitcoinPubKeyAddress("2MsNF9f3nsdkEMV6un9u3pMVKcTNJPauqaU");


            var hallOfTheMakersAddress = new BitcoinScriptAddress("2MtBDuoyhPa8athzErp8nj4NXMKgUQ2qGq8", Network.TestNet);


            // How much you want to TO
            var hallOfTheMakersAmount = new Money((decimal)0.5, MoneyUnit.BTC);
            /* At the time of writing the mining fee is 0.05usd
             * Depending on the market price and
             * On the currently advised mining fee,
             * You may consider to increase or decrease it
            */
            var minerFee = new Money((decimal)0.0001, MoneyUnit.BTC);
            // How much you want to spend FROM
            var txInAmount = (Money)receivedCoins[(int) outPointToSpend.N].Amount;
            Money changeBackAmount = txInAmount - hallOfTheMakersAmount - minerFee;

            TxOut hallOfTheMakersTxOut = new TxOut()
            {
                Value = hallOfTheMakersAmount,
                ScriptPubKey = hallOfTheMakersAddress.ScriptPubKey
            };

            TxOut changeBackTxOut = new TxOut()
            {
                Value = changeBackAmount,
                ScriptPubKey = bitcoinPrivateKey.ScriptPubKey
            };

            transaction.Outputs.Add(hallOfTheMakersTxOut);
            transaction.Outputs.Add(changeBackTxOut);

            var message = "nopara73 loves NBitcoin!";
            var bytes = Encoding.UTF8.GetBytes(message);
            transaction.Outputs.Add(new TxOut()
            {
                Value = Money.Zero,
                ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(bytes)
            });

            //Console.WriteLine(transaction);

            //var address = new BitcoinPubKeyAddress("mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv");
            //transaction.Inputs[0].ScriptSig = address.ScriptPubKey;

            // It is also OK:
            transaction.Inputs[0].ScriptSig =  bitcoinPrivateKey.ScriptPubKey;
            transaction.Sign(bitcoinPrivateKey, false);

            BroadcastResponse broadcastResponse = client.Broadcast(transaction).Result;

            if (!broadcastResponse.Success)
            {
                Console.WriteLine(string.Format("ErrorCode: {0}", broadcastResponse.Error.ErrorCode));
                Console.WriteLine("Error message: " + broadcastResponse.Error.Reason);
            }
            else
            {
                Console.WriteLine("Success! You can check out the hash of the transaciton in any block explorer:");
                Console.WriteLine(transaction.GetHash());
            }

            //using (var node = Node.ConnectToLocal(network)) //Connect to the node
            //{
            //    node.VersionHandshake(); //Say hello
            //                             //Advertize your transaction (send just the hash)
            //    node.SendMessage(new InvPayload(InventoryType.MSG_TX, transaction.GetHash()));
            //    //Send it
            //    node.SendMessage(new TxPayload(transaction));
            //    Thread.Sleep(500); //Wait a bit
            //}


            Console.ReadLine();
        }
    }
}

1 Answer 1

1

I have found your transaction here: 12e548ababf06160486f91bfa2a406f131631258b2db025eb36bcd5230a70524

It was successfully created, signed and submitted. I can also see a message that you added in.

There are a few things I picked up that are different when I look into the transaction vs how you built it up.

  1. The address that is derived from that private key is either: mj36bqZz5DcQFhKysoanLirq9f6MNfT1oJ

    or

    mweqjRVBWVTmiV8fqLYqWfWAmqzxCWYwJd (compressed)

    whereas you're noting that down as "mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv". You can validate that here bitaddress - testnet

  2. Is there any reason why you're using BitcoinScriptAddress

    Like:

    var hallOfTheMakersAddress = new BitcoinScriptAddress("2MtBDuoyhPa8athzErp8nj4NXMKgUQ2qGq8", Network.TestNet);
    

    Instead of something like:

    var hallOfTheMakersAddress = new BitcoinAddress("mweqjRVBWVTmiV8fqLYqWfWAmqzxCWYwJd", Network.TestNet);
    
4
  • Thank you for the quick reply. I tried that, and I get an error: Error CS0144 Cannot create an instance of the abstract class or interface 'BitcoinAddress' Can you please kindly take another look and help me with this? Mar 6, 2017 at 9:34
  • My mistake, sorry. Try: BitcoinAddress hallOfTheMakersAddress = BitcoinAddress.Create("mweqjRVBWVTmiV8fqLYqWfWAmqzxCWYwJd", Network.TestNet); Mar 6, 2017 at 9:41
  • I changed the program like you asked. The program runs successfully and even returns a Transaction ID. However, I do not see any Bitcoins coming into the Testnet Wallet... Can some kind soul please kindly take another look at the code and help out? I'm using var hallOfTheMakersAddress = BitcoinAddress.Create("2NBzSQBwACBnMNbTR8QjZQKYwW61RZMd777", Network.TestNet); Mar 6, 2017 at 9:51
  • I'm not very familiar with that wallet and why it keeps giving you Script Addresses instead of just normal Bitcoin Addresses. If you're starting out with Bitcoin I would recommend that you install Copay (copay.io) and create a testnet wallet in there. Your results will be far more predictable and easier to follow. It's what I'm currently using for testing purposes. Mar 6, 2017 at 9:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.