At least in some jurisdictions, arrangements solely for the purpose of avoiding taxes (barring explicit carve-outs) are not permitted.
https://www.canada.ca/en/revenue-agency/programs/about-canad...
TLDR: if the only reason for a transaction is tax avoidance, it may not be "illegal", but it may be disallowed (and presumably incorporated in subsequent legislation).
Similar is "wash sale" legislation: for example, selling a security for a tax loss and
- buying it back within 30 days
- buying a call option on that security.
I will guess that the former might get you just a reassessment (the first time). The latter... well, you're smart enough to know about options and tax-loss sale, now you need to demonstrate that you didn't do it for tax avoidance.
Not sure what US law (federal and gazillion states) has on this.