Bitcoin Forum
May 04, 2024, 12:24:51 PM *
News: Latest Bitcoin Core release: 27.0 [Torrent]
 
   Home   Help Search Login Register More  
Pages: [1]
  Print  
Author Topic: How to create transaction using NBitcoin in C#.  (Read 773 times)
Billion Dollar Boy (OP)
Newbie
*
Offline Offline

Activity: 2
Merit: 0


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.
If you see garbage posts (off-topic, trolling, spam, no point, etc.), use the "report to moderator" links. All reports are investigated, though you will rarely be contacted about your reports.
Advertised sites are not endorsed by the Bitcoin Forum. They may be unsafe, untrustworthy, or illegal in your jurisdiction.
wavelengthsf
Full Member
***
Offline Offline

Activity: 658
Merit: 118


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 (OP)
Newbie
*
Offline Offline

Activity: 2
Merit: 0


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
Legendary
*
Offline Offline

Activity: 1039
Merit: 2783


Bitcoin and C♯ Enthusiast


View Profile WWW
September 06, 2017, 05:57:48 PM
Merited by ABCbits (1)
 #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
Donate: 1Q9s or bc1q
|
|
|
FinderOuter(0.19.1)Ann-git
Denovo(0.7.0)Ann-git
Bitcoin.Net(0.26.0)Ann-git
|
|
|
BitcoinTransactionTool(0.11.0)Ann-git
WatchOnlyBitcoinWallet(3.2.1)Ann-git
SharpPusher(0.12.0)Ann-git
Pages: [1]
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.19 | SMF © 2006-2009, Simple Machines Valid XHTML 1.0! Valid CSS!