This repository has been archived by the owner on Oct 30, 2018. It is now read-only.
/
blacklist.js
83 lines (68 loc) · 1.79 KB
/
blacklist.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
'use strict';
var assert = require('assert');
var fs = require('fs');
var utils = require('../utils');
var path = require('path');
/**
* Manage a blacklist file containing an object with key value pairs of
* nodeids: timestamp
* @constructor
* @license LGPL-3.0
* @see https://github.com/storj/bridge
* @param {String} path - blacklist folder location
*/
function Blacklist(folder) {
if (!(this instanceof Blacklist)) {
return new Blacklist(folder);
}
assert.ok(utils.existsSync(folder), 'Invalid Blacklist Folder');
this.blacklistFile = path.join(folder,'.blacklist');
this.blacklist = this._loadFromDisk();
}
Blacklist.TTL = 86400000;
/**
* Push node to blacklist
* @param {String} nodeid - Node id to be added to blacklist
*/
Blacklist.prototype.push = function(nodeid) {
this.blacklist[nodeid] = Date.now();
this._saveToDisk();
};
/**
* Save blacklist to disk
* @private
*/
Blacklist.prototype._saveToDisk = function() {
fs.writeFileSync(this.blacklistFile, JSON.stringify(this.blacklist));
};
/**
* Read blacklist from disk and Reap old nodeids
* @private
*/
Blacklist.prototype._loadFromDisk = function() {
if (!utils.existsSync(this.blacklistFile)) {
fs.writeFileSync(this.blacklistFile, JSON.stringify([]));
}
return this._reap(JSON.parse(fs.readFileSync(this.blacklistFile)));
};
/**
* Reap old nodeids from blacklist
* @private
*/
Blacklist.prototype._reap = function(blacklist) {
var now = Date.now();
for (var nodeid in blacklist) {
if ((blacklist[nodeid] - now) > Blacklist.TTL) {
delete blacklist[nodeid];
}
}
this.blacklist = blacklist;
return blacklist;
};
/**
* Return list of blacklisted nodeids
*/
Blacklist.prototype.toObject = function() {
return Object.keys(this._reap(this.blacklist));
};
module.exports = Blacklist;