I am using NBitcoin library to create my private keys and addresses, but I can't find an example of how to send Bitcoin.
Does anyone have a c# example code to send Bitcoin using the NBitcoin library ?
I am using NBitcoin library to create my private keys and addresses, but I can't find an example of how to send Bitcoin.
Does anyone have a c# example code to send Bitcoin using the NBitcoin library ?
You can find an example here.
Specifically, see the first example where Alice sends bitcoins to Satoshi:
Transaction aliceFunding = new Transaction()
{
Outputs =
{
new TxOut("0.45", alice.GetAddress()),
new TxOut("0.8", alice.Key.PubKey)
}
};
Coin[] aliceCoins = aliceFunding
.Outputs
.Select((o, i) => new Coin(new OutPoint(aliceFunding.GetHash(), i), o))
.ToArray();
Notice the outputs (Alice's initial coins). The first uses GetAddress() to get the bitcoin address corresponding to Alice's private key (i.e. P2PKH) while the second uses Alice's public key (i.e. P2PK).
And the transaction is constructed here:
var txBuilder = new TransactionBuilder();
var tx = txBuilder
.AddCoins(aliceCoins)
.AddKeys(alice.Key)
.Send(satoshi.GetAddress(), "1.00")
.SendFees("0.001")
.SetChange(alice.GetAddress())
.BuildTransaction(true);
Assert(txBuilder.Verify(tx)); //check fully signed
ok I updated the code:
//Load latest transaction:
var blockr = new BlockrTransactionRepository();
NBitcoin.uint256 check = new NBitcoin.uint256("4ebf7f7ca0a5dafd10b9bd74d8cb93a6eb0831bcb637fec8e8aabf842f1c2688");
Transaction aliceFunding = blockr.Get(check);
Coin[] aliceCoins = aliceFunding
.Outputs
.Select((o, i) => new Coin(new OutPoint(aliceFunding.GetHash(), i), o))
.ToArray();
txBuilder = new TransactionBuilder();
tx = txBuilder
.AddCoins(aliceCoins)
.AddKeys(alice.Key)
.Send(satoshi.GetAddress(), "0.05")
.SendFees("0.001")
.SetChange(alice.GetAddress())
.BuildTransaction(true);
Assert(txBuilder.Verify(tx));