Wtxid relay was introduced in BIP339, where you'll find more details on the rationale and design.
Whenever a node supports BIP339, it will advertize that to its peers, through the wtxidrelay
negotiations message. When those peers support BIP339 as well, they may choose to advertize transactions through their wtxid instead of their txid.
Every transaction is only advertized once (using the txid for normal peers, and using the wtxid for BIP339 peers) on each connection. That's not the code you posted though; that code is for populating the relay pool: the set of recent transactions which is used to answer getdata
requests sent in response to transactions advertized by inv
s. Because some peers may request using the txid, and some may requests using the wtxid (mostly matching their BIP339 support, but even BIP339 peers will in some cases request using txids), both are added to the relay pool.
- Why the node send these two ids, what are the benefits?
Wtxid based relay is better, but is not available to pre-BIP339 peers, so both have to remain supported.
- Suppose a transaction's txid is A, and its wtxid is B. Nodes will relay A and B inv to peers. After a client received A first, will the client mark this transaction "fAlreadyHave" when receiving B later?
Generally the same transaction is only advertized once per connection, but it is possible that a node hears a txid A first, and the wtxid B later from another peer. If the actual transaction was received already (by fetching tx using txid A), then both txid A and wtxid B will be considered "AlreadyHave".
Before the actual transaction is received, the node has no idea that advertisements for A and for B refer to the same transaction. To avoid duplicate requests, Bitcoin Core introduces a 2s delay before fetching transactions advertised using txids, to give wtxid peers a chance to advertize it first.