Aedes aegypti transmit pathogenic arboviruses while the mosquito itself tolerates the infection. We examine a piRNA-based immunity that relies on the acquisition of viral derived cDNA (vDNA) and how this pathway discriminates between self and non-self. The piRNAs derived from these vDNAs are essential for virus control and Piwi4 has a central role in the pathway. Piwi4 binds preferentially to virus-derived piRNAs but not to transposon-targeting piRNAs. Analysis of episomal vDNA from infected cells reveals that vDNA molecules are acquired through a discriminatory process of reverse-transcription and recombination directed by endogenous retrotransposons. Using a high-resolution Ae. aegypti genomic sequence, we found that vDNAs integrated in the host genome as endogenous viral elements (EVEs), produce antisense piRNAs that are preferentially loaded onto Piwi4. Importantly, EVE-derived piRNAs are specifically loaded onto Piwi4 to inhibit virus replication. Thus, Ae. aegypti employs a sophisticated antiviral mechanism that promotes viral persistence and generates long-lasting adaptive immunity.