Why block height is required in coinbase? While reading bitcoin source I found this short comment:

// Height first in coinbase required for block.version=2


(From https://github.com/bitcoin/bitcoin/blob/master/src/miner.cpp#L338).

Why this is required? Does it prevent some misuse or attack?

I found that this change was introduced in BIP-0034. In relevant pull request it is justified by following points:


  Putting the height in the coinbase is desired for at least two reasons:
  
  
  It guarantees that every subsequent block and transaction hash is unique.
  It can be used to better reason about plausible difficulty for not-yet-connected blocks.
  


But for me this explains nothing: I don't see how adding height guarantees unique block hashes and I don't understand what is "plausible difficulty for not-yet-connected blocks".
In his comment @amaclin pointed to BIP-30 which provides motivation for BIP-34.

I still don't understand what is "to better reason about plausible difficulty for not-yet-connected blocks" but it seems that the sole point of BIP-34 is to prevent intentional creation of duplicate coinbase transactions.

According BIP-30 they can be used in several attacks:


  Recently, an attack that exploits the reference implementation's dealing with duplicate transactions was described and demonstrated. It allows reverting fully-confirmed transactions to a single confirmation, making them vulnerable to become unspendable entirely. Another attack is possible that allows forking the block chain for a subset of the network.


This answer by Pieter Wuille explains blockchain forking in more detail.



Contrary to the explanation in BIP-34 pull request, adding block height to coinbase does not guarantee that every subsequent transaction hash is unique. It only makes harder to create transactions with same hash intentionally. There is still possibility that some unrelated transactions will clash.