Elffuss BraidHub

kikocis/osiris public

1224e2ca50b7 · 2.5 KiBRawPermalink
1/**
2 * OFAC sanctioned crypto address lookup.
3 *
4 * Source: the community-maintained mirror at
5 * https://github.com/0xB10C/ofac-sanctioned-digital-currency-addresses, which
6 * tracks the Treasury SDN list additions/removals as flat per-chain JSON
7 * arrays. The raw lists are small (low-tens of KB) so we load them whole and
8 * keep a lowercased `Set` for O(1) membership checks.
9 *
10 * The cache is filled lazily on the first lookup per chain and refreshed
11 * every 24h. A second concurrent request that arrives while a fetch is in
12 * flight waits on the same promise (single-flight) to avoid duplicate work.
13 * If a refresh fails after the cache has gone stale we keep serving the
14 * previous snapshot rather than blinding the route — a false negative on
15 * brand-new sanctions is preferable to a sudden gap in coverage.
16 */
17
18const SOURCES: Record<string, string> = {
19 BTC: 'https://raw.githubusercontent.com/0xB10C/ofac-sanctioned-digital-currency-addresses/lists/sanctioned_addresses_BTC.json',
20 ETH: 'https://raw.githubusercontent.com/0xB10C/ofac-sanctioned-digital-currency-addresses/lists/sanctioned_addresses_ETH.json',
21};
22
23const TTL_MS = 24 * 60 * 60 * 1000;
24
25type ChainList = { fetchedAt: number; set: Set<string> };
26const cache: Record<string, ChainList> = {};
27const inflight: Record<string, Promise<ChainList> | undefined> = {};
28
29async function loadList(chain: 'BTC' | 'ETH'): Promise<ChainList> {
30 const cached = cache[chain];
31 if (cached && Date.now() - cached.fetchedAt < TTL_MS) return cached;
32 if (inflight[chain]) return inflight[chain]!;
33
34 inflight[chain] = (async () => {
35 try {
36 const res = await fetch(SOURCES[chain], { signal: AbortSignal.timeout(8000) });
37 if (!res.ok) throw new Error(`OFAC list ${chain} HTTP ${res.status}`);
38 const arr = (await res.json()) as string[];
39 const set = new Set(arr.map((a) => a.toLowerCase()));
40 const entry = { fetchedAt: Date.now(), set };
41 cache[chain] = entry;
42 return entry;
43 } catch (e) {
44 // On failure, keep stale data if any to avoid leaving the route blind.
45 if (cached) return cached;
46 throw e;
47 } finally {
48 inflight[chain] = undefined;
49 }
50 })();
51
52 return inflight[chain]!;
53}
54
55export async function isSanctioned(
56 address: string,
57 chain: 'BTC' | 'ETH'
58): Promise<{ sanctioned: boolean; source?: string }> {
59 try {
60 const list = await loadList(chain);
61 if (list.set.has(address.toLowerCase())) {
62 return { sanctioned: true, source: 'OFAC SDN' };
63 }
64 return { sanctioned: false };
65 } catch {
66 return { sanctioned: false };
67 }
68}