Bitcoin Forum
November 21, 2017, 10:51:59 AM *
News: Latest stable version of Bitcoin Core: 0.15.1  [Torrent].
 
   Home   Help Search Donate Login Register  
Pages: [1]
  Print  
Author Topic: How to create transaction using NBitcoin in C#.  (Read 514 times)
Billion Dollar Boy
Newbie
*
Offline Offline

Activity: 2


View Profile
September 04, 2017, 02:36:27 PM
 #1

Hi,
I am creating an online wallet & I am using C# (WebAPI) as my backed scripting language.
I am also using NBitcoin & QBitninja NuGet packages developed by NicolasDorier.
Some how I created a verified transaction but network is not able to broadcast that transaction.

Command:- bitcoin-cli signrawtransaction 010000000001012be
973e52a7f8efbc91ef9c397a81df05c047e8138c76920fd9225df19aaea360000000000ffffffff 0
2a4c0e400000000001976a9140ecd86fcda32df67e7cbd989eddd38d00bb2504f88ac40420f0000 0
000001976a9145da61fbc2b8de68bbe1b666b4e84bec9d2e3edae88ac02473044022061199488e5 a
5fe9c3db4678eadc08b92de1d0881dd13ac3af5b39b15543ae4c202205ff7aeead9ba8c3f4bc89a c
0614802ae19f781be8bfa8c74fb01bd50b96c7cf4012103e970de664249bb560ec1501ea8a98571 d
a983c899ee02888d6e41aaab2ff56b300000000



 Err. :-  
{
  "hex": "010000000001012be973e52a7f8efbc91ef9c397a81df05c047e8138c76920fd9225df
19aaea360000000000ffffffff02a4c0e400000000001976a9140ecd86fcda32df67e7cbd989edd d
38d00bb2504f88ac40420f00000000001976a9145da61fbc2b8de68bbe1b666b4e84bec9d2e3eda e
88ac02473044022061199488e5a5fe9c3db4678eadc08b92de1d0881dd13ac3af5b39b15543ae4c 2
02205ff7aeead9ba8c3f4bc89ac0614802ae19f781be8bfa8c74fb01bd50b96c7cf4012103e970d e
664249bb560ec1501ea8a98571da983c899ee02888d6e41aaab2ff56b300000000",
  "complete": false,
  "errors": [
    {
      "txid": "36eaaa19df2592fd2069c738817e045cf01da897c3f91ec9fb8e7f2ae573e92b"
,
      "vout": 0,
      "scriptSig": "",
      "sequence": 4294967295,
      "error": "Input not found or already spent"
    }
  ]
}


Demo Code :-

public string SendBitCoins(int userId, int walletID, string destinationAddress, decimal amount)
        {
            try
            {
                var masterKey = new GetMasterWallet(userId);
                var privateKey = masterKey.PrivateKey;
                Money fee = Money.Satoshis(8476);
                Money transactionAmount = Money.Satoshis(Convert.ToInt64(amount * 100000000));
                var transaction = CreateTransaction(userId, walletID, privateKey.PubKey,transactionAmount,fee, masterKey);
                var transactionhex = BuildTransaction(transaction,privateKey, destinationAddress, amount, fee);
                return transactionhex;
            }
            catch (Exception)
            {

                throw;
            }
        }


public Transaction CreateTransaction(int userID,int userWalletID, PubKey sourcePublicKey, Money amount, Money fee, ExtKey masterwallet)
        {
            try
            {
                var init = new Transaction();
                if (userWalletID != 0)
                {
                    var client = new QBitNinjaClient(Network.TestNet);
                    var totalAmount = amount + fee;
                    long transactionAmount = 0;
                    var userRequestAddress = _unitOfWork.UserRequestAddressRepository
                        .GetManyQueryable(x => x.UserID == userID &&
                        x.UserWalletID == userWalletID && x.Amount > 0 && !x.IsActive);
                    var userPrivateWalletKey = new UserWalletChainService(_unitOfWork).GetUserWalletKey(userWalletID, masterwallet);
                    var userPublicWalletKey = userPrivateWalletKey.Neuter();
                    

                    userRequestAddress.ToList().ForEach(x => {
                        var extPubKey = userPublicWalletKey.Derive(
                                        new KeyPath(Convert.ToString(x.ChainDerivationKey)));
                        //var extPrivateKey = userPrivateWalletKey.Derive(
                        //                new KeyPath(Convert.ToString(x.ChainDerivationKey)));
                        client.GetBalance(extPubKey.PubKey.Hash.GetAddress(Network.TestNet), true)
                        .Result.Operations.ToList().ForEach(z => {
                            z.ReceivedCoins.ForEach(l => {
                                if (totalAmount.Satoshi > transactionAmount)
                                    //init.Outputs.Add(new TxOut(Money.Coins(1m), GetP2WPKH(sourcePublicKey)));
                                    init.Outputs.Add(new TxOut(Money.Coins(Convert.ToDecimal((l.Amount as Money).Satoshi) / 100000000), GetP2WPKH(sourcePublicKey)));
                                //init.Outputs.Add(new TxOut(Money.Coins(Convert.ToDecimal((l.Amount as Money).Satoshi) / 100000000), GetP2WPKH(userPrivateWalletKey.PrivateKey.PubKey)));

                                transactionAmount += (l.Amount as Money).Satoshi;
                            });
                        });
                    });
                }
                //init.Outputs.Add(new TxOut(Money.Coins(1m), GetP2WPKH(sourcePublicKey)));
                return init;
            }
            catch (Exception)
            {

                throw;
            }
        }


public string BuildTransaction(Transaction transaction, Key sourcePriveatKey, string destinationAddress,decimal amount,Money fee)
        {
            TransactionBuilder builder = null;
            try
            {
                var destination = BitcoinAddress.Create(destinationAddress).ScriptPubKey;
                

                Coin[] coins = transaction.Outputs.AsCoins().ToArray();
                
                builder = new TransactionBuilder();
                Transaction tx = builder
                    .AddCoins(coins[0])
                    .AddKeys(sourcePriveatKey)
                    .Send(destination, Money.Coins(amount))
                    .SetChange(sourcePriveatKey)
                    .SendFees(fee)
                    .BuildTransaction(sign: true);
                if (builder.Verify(tx))
                    return tx.ToHex();
                else
                    return "";
            }
            catch (Exception)
            {

                throw;
            }
        }


please give me some suggestion is anybody knows what I am doing wrong.
1511261519
Hero Member
*
Offline Offline

Posts: 1511261519

View Profile Personal Message (Offline)

Ignore
1511261519
Reply with quote  #2

1511261519
Report to moderator
1511261519
Hero Member
*
Offline Offline

Posts: 1511261519

View Profile Personal Message (Offline)

Ignore
1511261519
Reply with quote  #2

1511261519
Report to moderator
Join ICO Now Coinlancer is Disrupting the Freelance marketplace!
Advertised sites are not endorsed by the Bitcoin Forum. They may be unsafe, untrustworthy, or illegal in your jurisdiction. Advertise here.
1511261519
Hero Member
*
Offline Offline

Posts: 1511261519

View Profile Personal Message (Offline)

Ignore
1511261519
Reply with quote  #2

1511261519
Report to moderator
1511261519
Hero Member
*
Offline Offline

Posts: 1511261519

View Profile Personal Message (Offline)

Ignore
1511261519
Reply with quote  #2

1511261519
Report to moderator
wavelengthsf
Full Member
***
Offline Offline

Activity: 126


View Profile
September 04, 2017, 02:44:09 PM
 #2

It appears that you're trying to send more Bitcoin than the address has, so the network is rejecting it. Make sure your units are correct in the amount you are sending.
Billion Dollar Boy
Newbie
*
Offline Offline

Activity: 2


View Profile
September 04, 2017, 05:06:36 PM
 #3

Hi,
My units are same.
I think the transaction which I created is not correct, there is very limited help in this topic specifically in C#.
Do you have such kind of precooked code that will be more helpful.

Thanks Smiley
Coding Enthusiast
Sr. Member
****
Offline Offline

Activity: 422


Novice C♯ Coder


View Profile WWW
September 06, 2017, 05:57:48 PM
 #4

Your transaction is wrong! More precisely your Tx_in_count is 0 where it should be something bigger and equal to 1

01000000 00 01012be973e52a7f8efbc91ef9c397a81df05c....

The bold part is your VarInt which should indicate the number of Transaction Outputs you are spending. it shows 0 here. Possibly you are making a mistake in creating your VarInt since what comes next is not a valid tx id.
If you are spending 1 output, which I am guessing you are, it should simply be "01"

BTW Nbitcoin has a (near) live chat here: https://gitter.im/MetacoSA/NBitcoin

Projects List+Suggestion box
Donation link using BIP21
BitcoinTransactionTool (0.9.2): Ann - Source Code
Watch Only Bitcoin Wallet (2.2.0): Ann - Source Code
SharpPusher-broadcast transactions (0.10.0): Ann - Source Code

Pages: [1]
  Print  
 
Jump to:  

Sponsored by , a Bitcoin-accepting VPN.
Powered by MySQL Powered by PHP Powered by SMF 1.1.19 | SMF © 2006-2009, Simple Machines Valid XHTML 1.0! Valid CSS!