Skip to content

Instantly share code, notes, and snippets.

@nopara73
Last active July 12, 2017 06:12
Show Gist options
  • Save nopara73/a1fb4b89baca67a51a4fe26a0567459f to your computer and use it in GitHub Desktop.
Save nopara73/a1fb4b89baca67a51a4fe26a0567459f to your computer and use it in GitHub Desktop.
Build basic transaction
using NBitcoin;
using NBitcoin.Policy;
using QBitNinja.Client;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using static System.Console;
namespace HTumbleBitProofOfConcept
{
class Program
{
private static readonly Network _network = Network.TestNet;
private static readonly BitcoinExtKey _seed = new BitcoinExtKey("tprv8ZgxMBicQKsPeGSjHbcTdpBxmVvRmySiUkQFBLruRTrn2dXAtn2rqApjVUgqsFkhfJZLYy8kXgRaEgZh7M3zdxyabF1TcwoxZsgpmAnHYyH");
private static readonly QBitNinjaClient _qBitClient = new QBitNinjaClient(_network);
static void Main(string[] args)
{
BuildBasicTransactionAsync().Wait();
ReadKey();
}
private static async Task BuildBasicTransactionAsync(CancellationToken ctsToken = default(CancellationToken))
{
ExtKey _fundingExtKey = _seed.ExtKey.Derive(0, hardened: false);
BitcoinAddress fundingAddress = _fundingExtKey.ScriptPubKey.GetDestinationAddress(_network); // mkvRuHAv3qek4mP3ipjqFnaFXj4d2kKit3
WriteLine($"{nameof(fundingAddress)}: {fundingAddress}");
uint256 txIdToSpend = (await _qBitClient.GetBalance(fundingAddress, unspentOnly: false).ConfigureAwait(false)).Operations.First().TransactionId;
ctsToken.ThrowIfCancellationRequested();
Transaction txToSpend = (await _qBitClient.GetTransaction(txIdToSpend).ConfigureAwait(false)).Transaction;
ctsToken.ThrowIfCancellationRequested();
ExtKey destinationExtKey = _seed.ExtKey.Derive(1, false);
BitcoinAddress destinationAddress = destinationExtKey.ScriptPubKey.GetDestinationAddress(_network); // mk1soVb7Se1t99v7APGqiXofr2pKVS7hN5
WriteLine($"{nameof(destinationAddress)}: {destinationAddress}");
var fee = new Money(0.001m, MoneyUnit.BTC);
var builder = new TransactionBuilder();
Transaction txThatSpends = builder
.AddCoins(txToSpend)
.AddKeys(_fundingExtKey)
.SendFees(fee)
.Send(destinationAddress, txToSpend.Outputs.First().Value - fee)
.BuildTransaction(sign: true);
TransactionPolicyError[] errors = builder.Check(txThatSpends);
ReportIfErrors(txName: nameof(txThatSpends), errors: builder.Check(txThatSpends));
if (errors.Count() == 0) ReportTransaction(txName: nameof(txThatSpends), transaction: txThatSpends);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment