Skip to content

Instantly share code, notes, and snippets.

@FrqSalah
Created January 16, 2023 10:06
Show Gist options
  • Save FrqSalah/6364e074389b47bdb3550e27aa92ec2f to your computer and use it in GitHub Desktop.
Save FrqSalah/6364e074389b47bdb3550e27aa92ec2f to your computer and use it in GitHub Desktop.
Example using BitcoinRpc in C#
using BitcoinRpc.Protocol;
using BitcoinRpc.Protocol.Methods;
using BitcoinRpc.Protocol.Models;
// Connect to the Bitcoin RPC
var rpc = new BitcoinRpcClient("http://user:[email protected]:8332/");
// Get the private key of the sender
var privateKey = "5J3mBbAH58CpQ3Y5RNJpUKPE62SQ5tfcvU2JpbnkeyhfsYB1Jcn";
// Get the public address from the private key
var fromAddress = rpc.GetNewAddress().Result;
Console.WriteLine("Sender address: " + fromAddress);
// Create a new transaction
var tx = new CreateRawTransaction();
// 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 = rpc.SignRawTransactionWithKey(tx, new[] { privateKey }).Result;
// Broadcast the transaction to the network
var broadcastResponse = rpc.SendRawTransaction(signedTx.Hex).Result;
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