Mosquitoes spread pathogenic arboviruses while themselves tolerate infection. We here characterize an immunity pathway providing long-term antiviral protection and define how this pathway discriminates between self and non-self. Mosquitoes use viral RNAs to create viral derived cDNAs (vDNAs) central to the antiviral response. vDNA molecules are acquired through a process of reverse-transcription and recombination directed by endogenous retrotransposons. These vDNAs are thought to integrate in the host genome as endogenous viral elements (EVEs). Sequencing of pre-integrated vDNA revealed that the acquisition process exquisitely distinguishes viral from host RNA, providing one layer of self-nonself discrimination. Importantly, we show EVE-derived piRNAs have antiviral activity and are loaded onto Piwi4 to inhibit virus replication. In a second layer of self-non-self discrimination, Piwi4 preferentially loads EVE-derived piRNAs, discriminating against transposon-targeting piRNAs. Our findings define a fundamental virus-specific immunity pathway in mosquitoes that uses EVEs as a potent and specific antiviral transgenerational mechanism.