Created
March 11, 2020 00:22
-
-
Save johnoke/178c9a30c335d8a477e48efbb2cf1d7a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var client = new QBitNinjaClient("http://api.qbit.ninja/", Network.Main); | |
var transactionId = uint256.Parse("sourceTransactionId"); | |
var transactionResponse = client.GetTransaction(transactionId).Result; | |
Console.WriteLine(transactionResponse.TransactionId); // | |
Console.WriteLine(transactionResponse.Block.Confirmations); | |
BitcoinSecret sender = new BitcoinSecret("senderPrivateKey"); | |
var receivedCoins = transactionResponse.ReceivedCoins; | |
OutPoint outPointToSpend = null; | |
foreach (var coin in receivedCoins) | |
{ | |
if (coin.TxOut.ScriptPubKey == sender.GetAddress(ScriptPubKeyType.Legacy).ScriptPubKey) | |
{ | |
outPointToSpend = coin.Outpoint; | |
} | |
} | |
if (outPointToSpend == null) | |
throw new Exception("TxOut doesn't contain our ScriptPubKey"); | |
Console.WriteLine("We want to spend {0}. outpoint:", outPointToSpend.N + 1); | |
var transaction = Transaction.Create(Network.Main); | |
transaction.Inputs.Add(new TxIn() | |
{ | |
PrevOut = outPointToSpend | |
}); | |
var destinationAddress = new BitcoinPubKeyAddress("senderPublicKey", Network.Main); | |
var destinationAmount = new Money(0.001m, MoneyUnit.BTC); | |
var minerFee = new Money(0.0001m, MoneyUnit.BTC); | |
var txInAmount = (Money)receivedCoins[(int)outPointToSpend.N].Amount; | |
var changeAmount = txInAmount - destinationAmount - minerFee; | |
transaction.Outputs.Add(destinationAmount, destinationAddress.ScriptPubKey); | |
// Send the change back | |
transaction.Outputs.Add(changeAmount, sender.GetAddress(ScriptPubKeyType.Legacy).ScriptPubKey); | |
var message = "John's transaction is on the block"; | |
var bytes = Encoding.UTF8.GetBytes(message); | |
transaction.Outputs.Add(Money.Zero, TxNullDataTemplate.Instance.GenerateScriptPubKey(bytes)); | |
transaction.Inputs[0].ScriptSig = sender.GetAddress(ScriptPubKeyType.Legacy).ScriptPubKey; | |
BroadcastResponse broadcastResponse = client.Broadcast(transaction).Result; | |
if (!broadcastResponse.Success) | |
{ | |
Console.Error.WriteLine("ErrorCode: " + broadcastResponse.Error.ErrorCode); | |
Console.Error.WriteLine("Error message: " + broadcastResponse.Error.Reason); | |
} | |
else | |
{ | |
Console.WriteLine("Success! You can check out the hash of the transaciton in any block explorer:"); | |
Console.WriteLine(transaction.GetHash()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment