As you may know, smart contracts cannot send signed transactions, they can only react to them. Smart contract code is triggered by transactions originating from Externally Owned Accounts (EOA).
tx.origin
is the address of the EOA from which originates the transaction. While msg.sender
is the address of the account from which the current call is coming from which could be an EOA or a Contract Account (CA).
What is the purpose of it?
Ensuring that the current caller is an EOA, not a CA.
When should you add this code?
This could be a security mechanism to ensure that no contract could try to exploit a vulnerability if you later make a call on msg.sender. But It also locks out every CA from interacting with your contract... Not sure if there is another use to it.
What difference does it make if the msg.sender is not a tx.origin? And
in which cases are msg.sender and tx.origin not the same address?
If msg.sender
is not tx.origin
your direct caller is most definitely a smart contract.
If a user A sends a tx calling a smart contract B, msg.sender == tx.origin == user A address. If contract B makes an external call to contract C then msg.sender == contract B while tx.origin is still user A.
When could this pose a security risk?
I don't see a security risk here but maybe someone might know of one ? It's at least an extremely severe limitation. As you pointed out, any smart contract calling on your code would instantly revert since msg.sender would not equal to tx.origin.