MetacoSA / NBitcoin

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

How to get Spent Coins from Raw Transaction? #1053

Closed gunpal5 closed 2 years ago

gunpal5 commented 3 years ago

I am trying to learn blockchain programming. I've trying to verify the the Raw Transaction with NBitcoin. But I can't really figure out how to get Spent coins from Raw Transaction to create the validator instance.

RPCClient client = new RPCClient(new RPCCredentialString() { UserPassword = new NetworkCredential("", ""), }, "", Network.Main);

` var rawTransaction = client.GetRawTransaction( new uint256("3d194b4ec19325bcf852cc239560fa0ab8e1f8a6207194d20263a2178edd72f6"));

        //How to get Spent Coins?
        var validator = rawTransaction.CreateValidator(spentCoins)`
NicolasDorier commented 3 years ago

To get the spent coins, you need to fetch the previous transaction, then take the output. In pseudo code it is something like

foreach(var input in tx.Inputs)
{
var prev =  rpc.GetRawTransaction(input.PrevOut.Hash);
var coin = prev.Outputs.AsCoins().ToList()[input.PrevOut.N];
spentCoins.Add(coin);
}

It works, but doing so would need you to get txindex on bitcoin core which take tons of space.

You can take a look at this server https://github.com/dgarage/NBXplorer/ which allows you to easily get the previous coins without the need of txindex (and work on pruned nodes)

There is an example of multisig here: https://github.com/dgarage/NBXplorer/blob/master/Examples/MultiSig/Program.cs

yahiheb commented 3 years ago

This might be helpful: https://programmingblockchain.gitbook.io/programmingblockchain/bitcoin_transfer/transaction