diff --git a/lib/utils/ens-cache.js b/lib/utils/ens-cache.js index 6cdcf8261..603d2b795 100644 --- a/lib/utils/ens-cache.js +++ b/lib/utils/ens-cache.js @@ -1,121 +1,148 @@ // @flow import namehash from 'eth-ens-namehash'; const cacheTimeout = 24 * 60 * 60 * 1000; // one day export type EthersProvider = { +lookupAddress: (address: string) => Promise, +resolveName: (name: string) => Promise, ... }; type ENSNameQueryCacheEntry = { // We normalize ETH addresses to lowercase characters +normalizedETHAddress: string, +cacheInsertionTime: number, // We normalize ENS names using eth-ens-namehash +normalizedENSName: ?string, }; type ENSAddressQueryCacheEntry = { +normalizedENSName: string, +cacheInsertionTime: number, +normalizedETHAddress: ?string, }; // We have a need for querying ENS names from both clients as well as from // keyserver code. On the client side, we could use wagmi's caching behavior, // but that doesn't work for keyserver since it's React-specific. To keep // caching behavior consistent across platforms, we instead introduce this // vanilla JS class that handles querying and caching ENS for all cases. class ENSCache { provider: EthersProvider; // Maps from normalized ETH address to a cache entry for that address nameQueryCache: Map = new Map(); // Maps from normalized ETH name to a cache entry for that name addressQueryCache: Map = new Map(); constructor(provider: EthersProvider) { this.provider = provider; } // Getting a name for an ETH address is referred to as "reverse resolution". // 1. Since any address can set a reverse resolution to an arbitrary ENS name // (without permission from the owner), this function will also perform a // "forward resolution" to confirm that the owner of the ENS name has // mapped it to this address. // 2. We only consider an ENS name valid if it's equal to its normalized // version via eth-ens-namehash. This is to protect against homograph // attacks. See https://docs.ens.domains/dapp-developer-guide/resolving-names#reverse-resolution // If we fail to find an ENS name for an address, fail to confirm a matching // forward resolution, or if the ENS name does not equal its normalized // version, we will return undefined. async getNameForAddress(ethAddress: string): Promise { const normalizedETHAddress = ethAddress.toLowerCase(); - const cacheResult = this.nameQueryCache.get(normalizedETHAddress); + const cacheResult = this.getCachedNameForAddress(normalizedETHAddress); if (cacheResult) { - const { cacheInsertionTime, normalizedENSName } = cacheResult; - if (cacheInsertionTime + cacheTimeout > Date.now()) { - return normalizedENSName; - } else { - this.nameQueryCache.delete(normalizedETHAddress); - } + return cacheResult; } const cacheAndReturnResult = (result: ?string) => { this.nameQueryCache.set(normalizedETHAddress, { normalizedETHAddress, cacheInsertionTime: Date.now(), normalizedENSName: result, }); return result; }; // ethers.js handles checking forward resolution (point 1 above) for us const ensName = await this.provider.lookupAddress(normalizedETHAddress); if (!ensName) { return cacheAndReturnResult(undefined); } const normalizedENSName = namehash.normalize(ensName); if (normalizedENSName !== ensName) { return cacheAndReturnResult(undefined); } return cacheAndReturnResult(normalizedENSName); } + getCachedNameForAddress(ethAddress: string): ?string { + const normalizedETHAddress = ethAddress.toLowerCase(); + + const cacheResult = this.nameQueryCache.get(normalizedETHAddress); + if (!cacheResult) { + return undefined; + } + + const { cacheInsertionTime, normalizedENSName } = cacheResult; + if (cacheInsertionTime + cacheTimeout <= Date.now()) { + this.nameQueryCache.delete(normalizedETHAddress); + return undefined; + } + + return normalizedENSName; + } + async getAddressForName(ensName: string): Promise { const normalizedENSName = namehash.normalize(ensName); if (normalizedENSName !== ensName) { return undefined; } - const cacheResult = this.addressQueryCache.get(normalizedENSName); + const cacheResult = this.getCachedAddressForName(normalizedENSName); if (cacheResult) { - const { cacheInsertionTime, normalizedETHAddress } = cacheResult; - if (cacheInsertionTime + cacheTimeout > Date.now()) { - return normalizedETHAddress; - } else { - this.addressQueryCache.delete(normalizedENSName); - } + return cacheResult; } const cacheAndReturnResult = (result: ?string) => { this.addressQueryCache.set(normalizedENSName, { normalizedENSName, cacheInsertionTime: Date.now(), normalizedETHAddress: result, }); return result; }; const ethAddress = await this.provider.resolveName(normalizedENSName); if (!ethAddress) { return cacheAndReturnResult(undefined); } return cacheAndReturnResult(ethAddress.toLowerCase()); } + + getCachedAddressForName(ensName: string): ?string { + const normalizedENSName = namehash.normalize(ensName); + if (normalizedENSName !== ensName) { + return undefined; + } + + const cacheResult = this.addressQueryCache.get(normalizedENSName); + if (!cacheResult) { + return undefined; + } + + const { cacheInsertionTime, normalizedETHAddress } = cacheResult; + if (cacheInsertionTime + cacheTimeout <= Date.now()) { + this.addressQueryCache.delete(normalizedENSName); + return undefined; + } + + return normalizedETHAddress; + } } export { ENSCache }; diff --git a/lib/utils/ens-cache.test.js b/lib/utils/ens-cache.test.js index 20b25bacf..2fbda32a0 100644 --- a/lib/utils/ens-cache.test.js +++ b/lib/utils/ens-cache.test.js @@ -1,75 +1,107 @@ // @flow import { ethers } from 'ethers'; import { ENSCache } from './ens-cache'; const provider = new ethers.providers.AlchemyProvider( 'mainnet', process.env.ALCHEMY_API_KEY, ); const ensCache = new ENSCache(provider); const baseLookupAddress = provider.lookupAddress.bind(provider); let timesLookupAddressCalled = 0; provider.lookupAddress = (ethAddress: string) => { timesLookupAddressCalled++; return baseLookupAddress(ethAddress); }; const baseResolveName = provider.resolveName.bind(provider); let timesResolveNameCalled = 0; provider.resolveName = (ensName: string) => { timesResolveNameCalled++; return baseResolveName(ensName); }; if (!process.env.ALCHEMY_API_KEY) { // Test only works if we can query blockchain console.log( 'skipped running ENSCache tests because of missing ALCHEMY_API_KEY ' + 'environmental variable', ); } describe('getNameForAddress', () => { + it('should fail to return ashoat.eth if not in cache', async () => { + if (!process.env.ALCHEMY_API_KEY) { + return; + } + const obviouslyAshoatEth = ensCache.getCachedNameForAddress( + '0x911413ef4127910d79303483f7470d095f399ca9', + ); + expect(obviouslyAshoatEth).toBe(undefined); + }); it('should return ashoat.eth', async () => { if (!process.env.ALCHEMY_API_KEY) { return; } const obviouslyAshoatEth = await ensCache.getNameForAddress( '0x911413ef4127910d79303483f7470d095f399ca9', ); expect(obviouslyAshoatEth).toBe('ashoat.eth'); }); + it('should return ashoat.eth if in cache', async () => { + if (!process.env.ALCHEMY_API_KEY) { + return; + } + const obviouslyAshoatEth = ensCache.getCachedNameForAddress( + '0x911413ef4127910d79303483f7470d095f399ca9', + ); + expect(obviouslyAshoatEth).toBe('ashoat.eth'); + }); it('should have ashoat.eth cached', async () => { if (!process.env.ALCHEMY_API_KEY) { return; } const timesLookupAddressCalledBefore = timesLookupAddressCalled; const obviouslyAshoatEth = await ensCache.getNameForAddress( '0x911413ef4127910d79303483f7470d095f399ca9', ); expect(obviouslyAshoatEth).toBe('ashoat.eth'); expect(timesLookupAddressCalled).toBe(timesLookupAddressCalledBefore); }); }); describe('getAddressForName', () => { + it("should fail to return ashoat.eth's address if not in cache", async () => { + if (!process.env.ALCHEMY_API_KEY) { + return; + } + const ashoatAddr = ensCache.getCachedAddressForName('ashoat.eth'); + expect(ashoatAddr).toBe(undefined); + }); it("should return ashoat.eth's address", async () => { if (!process.env.ALCHEMY_API_KEY) { return; } const ashoatAddr = await ensCache.getAddressForName('ashoat.eth'); expect(ashoatAddr).toBe('0x911413ef4127910d79303483f7470d095f399ca9'); }); + it("should return ashoat.eth's address if in cache", async () => { + if (!process.env.ALCHEMY_API_KEY) { + return; + } + const ashoatAddr = ensCache.getCachedAddressForName('ashoat.eth'); + expect(ashoatAddr).toBe('0x911413ef4127910d79303483f7470d095f399ca9'); + }); it("should have ashoat.eth's address cached", async () => { if (!process.env.ALCHEMY_API_KEY) { return; } const timesResolveNameCalledBefore = timesResolveNameCalled; const ashoatAddr = await ensCache.getAddressForName('ashoat.eth'); expect(ashoatAddr).toBe('0x911413ef4127910d79303483f7470d095f399ca9'); expect(timesResolveNameCalled).toBe(timesResolveNameCalledBefore); }); });