how does node create UTXO from blockchain for the first time? Let's say I am a new node.
I try to synch with the full node to grab the whole blockchain. Now, I synced with it .It's time for my node to create UTXO database ..
How does it do this exactly so that it knows which one to put in UTXO database ? since it will need to know which one is unspent. By looking at the blockchain, it can't quickly figure out which one is unspent for the following Reason: 1st height block contains output which has 5btc sent to me. I only spend this in the 400,000th block. This kind of thing happens for every other output. So how does bitcoin build UTXO in an effective way ?
It would also be great if there could be any code from bitcoind or something so i can take a look. Couldn't find it myself.
The UTXO set is updated every time a block is connected to the chain. So if you imagine during initial sync, you download block #1 and verify it, then add one UTXO to the database (the coinbase output). Block #2 gets downloaded and verified, and you add one more UTXO to the set and so on. Eventually you download block #1000 which contains a transaction that spends the coinbase output from block #1. If everything is valid, you delete that block #1 coinbase output from the UTXO set and replace it with whatever new coins are created by the transaction in block #1000.
So your assumption that &quot;Now, I synced with it. It's time for my node to create UTXO database&quot; is incorrect - the UTXO database is always under constant maintenance from the moment you launch bitcoind.
To start digging through the code, note this call to UpdateCoins() in the function ConnectBlock(). This will eventually call AddCoins() and you can see the UTXO are actually added to a cache first (which is eventually flushed to disk). But this is the mechanism you are looking for.
You can see where coins are removed from the UTXO cache in SpendCoin()