What exactly causes the output containing OP_RETURN to be unspendable? And why do I have to use the byes after OP_RETURN for keeping data in the blockchain and I can't use bytes before OP_RETURN?
What does exactly cause the output containing OP_RETURN to be unspendable?
Simply the fact that no input can possibly unlock coins which are encumbered with such an OP_RETURN-containing script. Whenever the script interpreter encounters an OP_RETURN instruction, it instantly aborts and cause the entire script to fail.
However, OP_RETURN does more than make a script unspendable. It makes it noticably and provably unspendable, and triggers special logic. For example, creating an output that pay to a normal P2WPKH address for a key you generated, and then throwing away the key, also makes the coin unspendable. However, it isn't obvious to the network that it is unspendable, and you can't prove to anyone that is.
This is different with OP_RETURN: any script that starts with OP_RETURN is obviously unspendable, and at least the Bitcoin Core software notices this as a special case, and will avoid storing such outputs in its database, because it is known that they cannot be spent. Attempts to spend it will trigger a "coin not found" rather than "script validation" error, but the result is the same: the transaction won't be allowed to proceed.
And why do I have to use the byes after OP_RETURN for keeping data in the blockchain and I can't use bytes before OP_RETURN?
For two reasons:
- By putting the OP_RETURN at the front, the special certainly-can't-be-spent-so-can-be-forgotten-about logic will trigger, which is lighter on all future full nodes that implement this logic.
- Standard relay policies implemented in most network nodes only permit a certain limited number of output templates. These include payments to typical addresses, and also scripts up to a certain size that start with OP_RETURN. If you'd try to create an output that put the data before the opcode, it would be considered a non-standard output type and not relayed by most nodes.