Skip to content

Instantly share code, notes, and snippets.

@FrqSalah
Created January 16, 2023 10:05
Show Gist options
  • Save FrqSalah/da46b4dded31202a5bbc80d246f4722e to your computer and use it in GitHub Desktop.
Save FrqSalah/da46b4dded31202a5bbc80d246f4722e to your computer and use it in GitHub Desktop.
Exemple using BitcoinLib in C#
using BitcoinLib.Services.Coins.Bitcoin;
using BitcoinLib.Responses;
using BitcoinLib.Responses.Bases;
using BitcoinLib.Responses.Shared;
// Create an instance of the BitcoinService class
var bitcoinService = new BitcoinService();
// Get the private key of the sender
var privateKey = "5J3mBbAH58CpQ3Y5RNJpUKPE62SQ5tfcvU2JpbnkeyhfsYB1Jcn";
// Get the public address from the private key
var fromAddress = bitcoinService.GetAddressFromPrivateKey(privateKey);
Console.WriteLine("Sender address: " + fromAddress);
// Create a new transaction
var tx = new CreateRawTransactionResponse();
// Create a recipient address
var toAddress = "mwCwTceJvYV27KXBc3NJZys6CjsgsoeHmf";
// Specify the amount to send
var amount = 0.01m;
// Add an output to the transaction to send the specified amount to the recipient address
tx.AddOutput(toAddress, amount);
// Get the previous transaction where the sender's address received some bitcoins
var previousTx = "d5d27987d2a3dfc724e359870c6644b40e497bdc0589a033220fe15429d88599";
// Get the index of the output of the previous transaction that the sender wants to spend
var outputIndex = 0;
// Add an input to the transaction to spend the bitcoins from the previous transaction
tx.AddInput(previousTx, outputIndex);
// Sign the transaction using the private key of the sender
var signedTx = bitcoinService.SignRawTransaction(tx.Hex, new[] { new SignRawTransactionInput() { TxId = previousTx, VOut = (uint)outputIndex, ScriptPubKey = bitcoinService.GetScriptPubKey(fromAddress) } }, new[] { privateKey });
// Broadcast the transaction to the network
var broadcastResponse = bitcoinService.SendRawTransaction(signedTx);
Console.WriteLine("Transaction broadcasted to the network with txid: " + broadcastResponse);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment