Skip to content

Instantly share code, notes, and snippets.

@ljchuello
Created September 8, 2019 03:29
Show Gist options
  • Save ljchuello/8ad04b40e35f78803579a437c0b8e36a to your computer and use it in GitHub Desktop.
Save ljchuello/8ad04b40e35f78803579a437c0b8e36a to your computer and use it in GitHub Desktop.
problems sending money when the wallet has more than 1 transaction
public bool EnviarTodo(string llavePrivada, string destino, string mensaje)
{
Key privateKey = Key.Parse(llavePrivada);
BitcoinSecret bitcoinPrivateKey = new BitcoinSecret(llavePrivada);
BitcoinAddress address = bitcoinPrivateKey.GetAddress(ScriptPubKeyType.Legacy);
QBitNinjaClient client = new QBitNinjaClient(Network.Main);
uint256 transactionId = uint256.Parse("42119368712db98a8fb75763fd9158848dc37ff5b180413e30a5063113b4aaa1");
GetTransactionResponse transactionResponse = client.GetTransaction(transactionId).Result;
// Creamos el objeto Transaction
Transaction transaction = Transaction.Create(Network.Main);
List<ICoin> receivedCoins = transactionResponse.ReceivedCoins;
OutPoint outPointToSpend = null;
foreach (var coin in receivedCoins)
{
if (coin.TxOut.ScriptPubKey == privateKey.ScriptPubKey)
{
outPointToSpend = coin.Outpoint;
}
}
// Validamos si existe algun ScriptPubKey
if (outPointToSpend == null)
{
throw new Exception("TxOut doesn't contain our ScriptPubKey");
}
// Creamos la entrada
TxIn tEtrada = new TxIn();
tEtrada.PrevOut = outPointToSpend;
transaction.Inputs.Add(tEtrada);
// Salida principal
TxOut tSalidaPrincipal = new TxOut();
tSalidaPrincipal.Value = new Money(0.00060035m, MoneyUnit.BTC);
tSalidaPrincipal.ScriptPubKey = new BitcoinPubKeyAddress(destino).ScriptPubKey;
// Añadimos la salida principal a la transacción
transaction.Outputs.Add(tSalidaPrincipal);
// Mensaje
if (!Cadena.Vacia(mensaje))
{
TxOut tMensaje = new TxOut();
tMensaje.Value = Money.Zero;
tMensaje.ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(Encoding.UTF8.GetBytes(mensaje));
transaction.Outputs.Add(tMensaje);
}
transaction.Inputs[0].ScriptSig = address.ScriptPubKey;
// Firmamos la transacción
transaction.Sign(bitcoinPrivateKey, receivedCoins.ToArray());
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.Error.WriteLine("ErrorCode: " + broadcastResponse.Error.ErrorCode);
Console.Error.WriteLine("Error message: " + broadcastResponse.Error.Reason);
Console.WriteLine("Success! You can check out the hash of the transaciton in any block explorer:");
Console.WriteLine(transaction.GetHash());
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment