-
Notifications
You must be signed in to change notification settings - Fork 5
/
locations.js
executable file
·91 lines (80 loc) · 2.67 KB
/
locations.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const axios = require('axios');
const CachemanFile = require('cacheman-file');
const geoip = require('geoip-lite');
const cache = new CachemanFile({ tmpDir: '.cache', ttl: 24 * 3600 });
const getPeers = async () => {
try {
const params = {
"method": "getpeerinfo",
"params": [],
"id": "foo"
}
const res = await axios.post('http://user:[email protected]:3332/', params);
if (!res.data.result) throw new Error('Missing peers.');
console.log(`${res.data.result.length} Sumcoin peers found`);
return res.data.result.map(peer => {
const [ip,] = peer.addr.split(':');
return ip;
});
} catch (e) {
console.log('Can\'t get Sumcoin peers', e);
return [];
}
};
const getElectrumIPs = async () => {
try {
const res = await axios.get('http://164.92.74.251:5000/get-ips');
console.log(`${res.data.length} Electrum wallet IPs found`);
return res.data;
} catch (e) {
console.log('Can\'t get Electrum IPs', e);
return [];
}
};
const formatLocationData = (geoData) => {
if (!geoData) return null;
return {
country_name: geoData.country,
region_name: geoData.region,
city: geoData.city,
latitude: geoData.ll[0],
longitude: geoData.ll[1]
};
};
const getLocation = async (ip) => new Promise((resolve) => {
cache.get(ip, async (err, value) => {
if (value) {
return resolve(value);
}
try {
const geo = geoip.lookup(ip);
const formattedGeo = formatLocationData(geo);
cache.set(ip, formattedGeo, 24 * 3600);
resolve(formattedGeo);
} catch (e) {
console.log('Can\'t get location', e);
resolve(null); // Resolve with null if there's an error
}
});
});
const getLocations = async () => {
const sumcoinPeers = await getPeers();
const electrumIPs = await getElectrumIPs();
const allIPs = [...new Set([...sumcoinPeers, ...electrumIPs])]; // Combine and deduplicate IPs
const locations = await Promise.all(allIPs.map(getLocation));
console.log(`Total IPs (Sumcoin + Electrum): ${locations.length}`);
return locations.filter(location => location !== null); // Filter out null locations
};
const cacheLocations = async () => {
const locations = await getLocations();
cache.set('locations', JSON.stringify(locations), 100);
};
const getCachedLocations = () => new Promise((resolve) => {
cache.get('locations', (err, value) => {
resolve(value ? value : []);
});
});
module.exports = {
getCachedLocations,
cacheLocations,
};