forked from ping-pub/faucet
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathchecker.js
48 lines (42 loc) · 1.49 KB
/
checker.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
import { Level } from "level";
const WINDOW = 86400 * 1000 // milliseconds in a day
// const WINDOW = 20 * 1000 // 20s for test
export class FrequencyChecker {
constructor(conf) {
this.conf = conf
this.db = new Level(conf.db.path, { valueEncoding: 'json' });
}
async check(key, limit) {
return new Promise((resolve) => {
this.db.get(key, function (err, value) {
const now = Date.now()
if (err || value && value.filter(x => now - x < WINDOW).length < limit) {
resolve(true)
// console.log(key, limit, value, true)
} else {
resolve(false)
// console.log(key, limit, false)
}
});
})
}
async checkIp(ip, chain) {
const chainLimit = this.conf.blockchains.find(x => x.name === chain)
return chainLimit ? this.check(ip, chainLimit.limit.ip ) : Promise.resolve(false)
}
async checkAddress(address, chain) {
const chainLimit = this.conf.blockchains.find(x => x.name === chain)
return chainLimit ? this.check(address, chainLimit.limit.address ) : Promise.resolve(false)
}
async update(key) {
const db = this.db
db.get(key, function (err, history) {
if (err) {
db.put(key, [Date.now()])
} else {
history.push(Date.now())
db.put(key, history)
}
});
}
}