## How can i send bitcoin using c# and the nbitcoin library?

6

3

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 ?

1

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.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
.SendFees("0.001")
.BuildTransaction(true);
Assert(txBuilder.Verify(tx)); //check fully signed


Thank you for your answer, In that example in codeproject they are sending colored coins, I did try the example and when I send it to the blockchain I get an error message saying - malformed transaction. – gideonlouw – 2016-04-05T11:04:34.410

The link takes you directly to a simple example (with a heading starting with "P2PK, P2PKH, Multi Sig payment"). The colored coins example is much further down. I edited my answer to include the example that I was referring to. If that is the one you tried and didn't work I might try later to run the example myself. – karask – 2016-04-05T11:30:42.657

ok for the variable aliceFunding, should I load my txn of the latest transaction for "Alice" ?

e.g.

var blockr = new BlockrTransactionRepository(); Transaction aliceFunding = blockr.Get("4ebf7f7ca0a5dafd10b9bd74d8cb93a6eb0831bcb637fec8e8aabf842f1c2688"); – gideonlouw – 2016-04-05T12:09:09.720

Yes. By the way, another resource that could be useful (in case you don't know it already) can be found in this ebook.

0

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