Blog

Filter posts by Category Or Tag of the Blog section!

singing and broadcasting the bitcoin wallet in with the latest version of Nbitcoin

Monday, 09 May 2022

As an update to my previous post about creating the Bitcoin wallet by using the Nbitcoin library, for those who are using the newer versions of the library I created a separate method for singing and broadcasting with the new changes.


 

  private static bool SingAndBroadcast(string secret, string toAddress, decimal amount, string fundingTransactionHash)
        {
            Network bitcoinNetwork = Network.Main;
            var bitcoinPrivateKey = new BitcoinSecret(secret, bitcoinNetwork);
            var address = bitcoinPrivateKey.GetAddress(ScriptPubKeyType.Legacy);

            var client = new QBitNinjaClient(bitcoinNetwork);
            var transactionId = uint256.Parse(fundingTransactionHash);
            var transactionResponse = client.GetTransaction(transactionId).Result;

            var receivedCoins = transactionResponse.ReceivedCoins;

            OutPoint outPointToSpend = null;
            foreach (var coin in receivedCoins)
            {
                if (coin.TxOut.ScriptPubKey == bitcoinPrivateKey.GetAddress(ScriptPubKeyType.Legacy).ScriptPubKey)
                {
                    outPointToSpend = coin.Outpoint;
                }
            }

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

            var receiverAddress = BitcoinAddress.Create(toAddress, bitcoinNetwork);


            var txOutAmount = new Money(amount, MoneyUnit.BTC);

            // Tx fee
            var minerFee = new Money(0.0005m, MoneyUnit.BTC);

            // Change
            var txInAmount = (Money)receivedCoins[(int)outPointToSpend.N].Amount;
            var changeAmount = txInAmount - txOutAmount - minerFee;

            transaction.Outputs.Add(txOutAmount, receiverAddress.ScriptPubKey);
            transaction.Outputs.Add(changeAmount, bitcoinPrivateKey.GetAddress(ScriptPubKeyType.Legacy).ScriptPubKey);


            transaction.Inputs[0].ScriptSig = address.ScriptPubKey;

            //Sign Tx
            transaction.Sign(bitcoinPrivateKey, receivedCoins.ToArray());

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

            return broadcastResponse.Success;
        }

The method first creates a BitcoinSecret object using the secret and the Bitcoin network (mainnet or testnet). Then, it gets the Bitcoin address of the sender using the BitcoinSecret object. The method then uses the QBitNinjaClient to get the transaction details of the funding transaction using the transaction ID. The receivedCoins variable contains the list of coins received by the sender's Bitcoin address in the funding transaction.

The method then searches for the received coins that match the sender's Bitcoin address and sets the outPointToSpend variable to the OutPoint of the matching coin. It then creates a new transaction object, adds the matching coin as an input to the transaction, and adds two outputs: one for the recipient's Bitcoin address and one for the change (if any). The method calculates the transaction fee and sets the script signature of the input to the sender's Bitcoin address.

Finally, the method signs the transaction using the private key of the sender's Bitcoin address and broadcasts the transaction to the Bitcoin network using the QBitNinjaClient. If the transaction is successfully broadcasted, the method returns true.

comments powered by Disqus