I have been reading about transaction malleability a lot still doesn't make sense to me. Is there a script I can use to test it out ? If the transaction that is malleable is changed by the attack, how is it possible that the two transaction are still in the blockchain and the miners still pick the attackers TXID over the legitimate one? Why our legitimate transaction not seen by the miners?
The transaction that you submitted and the transaction that was malleated in-flight or by a miner are both legitimate (valid) transactions. Transaction malleability means that a valid transaction can be modified in-flight, without invalidating it and without access to the relevant private keys. Even if changing the components of the transaction doesn't make it invalid, it changes the
txid of the transaction. So if you plan on creating two transactions together, where the second spends the outputs of the first transaction, then you can be a victim of transaction malleability. This is especially important in Lightning Network where you create commitment transaction prior to signing the funding transaction.
Is there a script I can use to test it out?
The easiest one to try out is ECDSA signatures as ECDSA signatures are by themselves malleable. You can just change the
S component of the signature to
-S and it will still produce a valid signature verification check. This was fixed by SegWit by moving the signatures from
scriptSig to a separate witness component. Although the signatures are still malleable, the
txid calculation does not include hashing the witness component (
wtxid includes the witness component and hence is malleable).
If the transaction that is malleable is changed by the attack, how is it possible that the two transaction are still in the blockchain and the miners still pick the attackers TXID over the legitimate one? Why our legitimate transaction not seen by the miners?
Many miners still follow a first seen policy which means they will use the transaction that they see first. Bitcoin operates a gossip network with best effort basis. If you broadcast your transaction to nodes directly connected with you then it might possible that one of them malleates your transaction and is able to send that directly to a miner before the honest nodes are able to do it. Thus the miner will keep the first transaction received and discard the second transaction as a double spend. The miner has no way of knowing which transaction was the one that was directly relayed by you. Only one of them will enter the blockchain, not both after the miner mines the block. It might also be the case that it is the miner you malleates your transaction.