I used to think that I understood how Bitcoin mining works, but after reading this thread I've changed my mind. Firstly I'm going to show what I thought it was to mine a block.
1. A miner validates the the very last block previously mined by someone else, in order to build a new block on top of it.
2. Miner constructs an empty block which contains a block header with the hash of the previous block, Version and a Time stamp.
3. Then the miner starts adding transactions to the block. The first one is the coinbase transaction which assigns the mining reward to the miner. Then miner picks up a few hundred transactions from the mempool, preferring those with the highest satoshis/byte ratio and adds them to the block too.
4. Miner makes a Merkle root by hashing the hashes of all the transactions in the block, and adds it(the Merkle root) to the block header.
5. Then the miner starts hashing the block, changing the nonce each time until it ends up with a hash which starts with a certain amount of zeros(18 zeros currently), or rather which is less than or equal to the target value, as @achow101 pointed out.
6.Then it is shared with other mining nodes and if it is validated, Voila!, the block reward is yours (along with all the fees associated with the txs in the block, and that's why transactions with the highest fees are preferred).
Now, what have I understood after reading this thread(sorry, it took so long to get to the point). Various articles and videos I watched on the subject have made an impression that only
in some cases it is necessary to change something in the block and start hashing all over again, while in reality this is
always the case.
In reality, a miner never finds the right hash with the very first block assembled, and always has to try various combinations numerous times, because
... an ASIC machine can hash 12 trillion times PER SECOND. and our nonce is 2,097,181,953. so that means winning miner spent only fraction of a second to calculate 2 billions hashes.
~
Do I understand it correctly this time?