Created
January 16, 2023 10:03
-
-
Save FrqSalah/3060e4ee8d923d0d85f2ba3020d22074 to your computer and use it in GitHub Desktop.
Example of using NBitcoin in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using NBitcoin; | |
using NBitcoin.Protocol; | |
using NBitcoin.Protocol.Behaviors; | |
// Create a private key for the sender | |
var privateKey = new Key(); | |
// Get the public address from the private key | |
var fromAddress = privateKey.PubKey.GetAddress(Network.TestNet); | |
Console.WriteLine("Sender address: " + fromAddress); | |
// Create a new transaction | |
var tx = new Transaction(); | |
// Create a recipient address | |
var toAddress = new BitcoinPubKeyAddress("mwCwTceJvYV27KXBc3NJZys6CjsgsoeHmf"); | |
// Specify the amount to send | |
var amount = new Money(0.01m, MoneyUnit.BTC); | |
// Add an output to the transaction to send the specified amount to the recipient address | |
tx.Outputs.Add(amount, toAddress); | |
// Get the previous transaction where the sender's address received some bitcoins | |
var previousTx = new uint256("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.Inputs.Add(new TxIn(previousTx, outputIndex)); | |
// Sign the transaction using the private key of the sender | |
tx.Sign(privateKey, false); | |
// Create a node to connect to the Bitcoin network | |
var node = new Node(Network.TestNet); | |
// Start the node and connect to the network | |
node.Behaviors.Add(new TrackerBehavior()); | |
node.Connect(); | |
// Broadcast the transaction to the network | |
node.SendMessage(new InvPayload(tx)); | |
Console.WriteLine("Transaction broadcasted to the network with txid: " + tx.GetHash()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment