MetacoSA / NBitcoin

Comprehensive Bitcoin library for the .NET framework.
MIT License
1.88k stars 848 forks source link

TransactionBuilder removes coins #1049

Open starkdm opened 3 years ago

starkdm commented 3 years ago

Code:

Console.Write("COINS:");
foreach (var coin in unspentCoins) Console.Write(" " + coin.Amount.Satoshi);
Console.WriteLine();

TransactionBuilder builder = Network.CreateTransactionBuilder();
builder.AddCoins(unspentCoins);
foreach (var sender in senders) builder.AddKeys(sender.PrivateKey);
builder.SendFees(new Money((long)bitcoinFees));
builder.SetChange(changeAddress.Address.ScriptPubKey);

Console.WriteLine("RECIPIENTS:");
foreach (var recipient in recipients) {
     Console.WriteLine(recipient.Address + " -> " + recipient.Amount);
     builder.Send(recipient.Address, new Money((long)recipient.Amount));
}

Transaction transaction = builder.BuildTransaction(true);
Console.WriteLine("TX HEX: " + transaction.ToHex());

Output:

COINS: 4000 4000 RECIPIENTS: tb1qkhfr4wns4sn8n6cpcnu8kg08l6phjnysvqv9m6 -> 1000 TX HEX: 010000000001016352b5e9da35c6ba12d045788b94b6fd2751f7009ae05adeaf217eb6d32704f80300000000ffffffff02e803000000000000160014b5d23aba70ac2679eb01c4f87b21e7fe83794c90d007000000000000160014c8c3bd2ecf22762c9181c97b09ec0557f06768740247304402205059409e24563c463a25e49989b8f8eb46d4691850c94e6d981f5b2f2a277ef60220080625aa120b5b691825c0b411d449df9181d2b01aa29de316007358df461d9801210378acb444cf6392047feba9c2d1f8d5733c2426d2a97b3ff1e7dd625305cebc0200000000

Why the resulting transaction contains only one input, although I indicated 2. I need the funds from 2 addresses to be fully spent. At each address 1 coin of 4000 satoshes.

NicolasDorier commented 3 years ago

@starkdm the coins added to the transactionbuilder are the available coins. It is not guarantee all get spent.

However, you can call txbuilder.SendAllRemainingToChange() to make sure all the coins get spent and sent to change.