MetacoSA / NBitcoin

Comprehensive Bitcoin library for the .NET framework.
MIT License
1.86k stars 840 forks source link

NBitcoin Unable to create transaction #1117

Open starkdm opened 1 year ago

starkdm commented 1 year ago

The following code creates a bitcoin transaction with 1 input and 1 output. The sender and recipient addresses are the same. fundingTx - existing transaction with 1 unspent output, senderAddresses - NBitcoin.BitcoinAddress array with 1 element - sender address (including private key), coin - fundingTx output with index 0 (first and only), recipient - recipient (NBitcoin.BitcoinAddress, that same address as the sender), fees - transaction fee (correct value in satoshies).

Transaction tx1 = Transaction.Parse(fundingTxHexString, Network.Main);
Coin coin = new Coin(tx1, 0);

TransactionBuilder builder = Network.CreateTransactionBuilder();
builder.AddCoins(new[] { coin });
builder.AddKeys(senderAddresses.Select((sender) => sender.PrivateKey).ToArray());
builder.SendFees(new Money(fees));
builder.SetChange(changeAddress.Address.ScriptPubKey);
builder.SendAllRemainingToChange();
builder.Send(recipient, value);

Transaction transaction = builder.BuildTransaction(true);

As a result, sometimes I get this nonsense:

{
    "addresses": [
        "bc1qmystncn6phsrtex5hchtulwvwrqj7gl79qe2zk"
    ],
    "block_height": -1,
    "block_index": -1,
    "confirmations": 0,
    "double_spend": false,
    "fees": 0,
    "hash": "f6ef6ddbb30eedde0695a4a6967c1bb97742e58f22007906783d3c20b102f215",
    "inputs": [
        {
            "age": 0,
            "output_index": 0,
            "prev_hash": "b4111fb1bf6ec9ca3875b468eb02bb47c433a77e459a498b643e63fa1633fa66",
            "script_type": "empty",
            "sequence": 4294967295
        }
    ],
    "outputs": [
        {
            "addresses": [
                "bc1qmystncn6phsrtex5hchtulwvwrqj7gl79qe2zk"
            ],
            "script": "0014d920b9e27a0de035e4d4be2ebe7dcc70c12f23fe",
            "script_type": "pay-to-witness-pubkey-hash",
            "value": 1595000
        }
    ],
    "preference": "low",
    "received": "2022-07-13T22:52:24.566309859Z",
    "relayed_by": "44.200.190.150",
    "size": 191,
    "total": 1595000,
    "ver": 1,
    "vin_sz": 1,
    "vout_sz": 1,
    "vsize": 110
}

That is, the problem is with how coin is processed. In this case, builder.Verify returns true, that is, the transaction was formed "correctly". Tell me how to fix it?