fst – Rev 1

Subversion Repositories:
Rev:
const geoip = require('geoip-lite')
const moment = require('moment')
const SyncData = require('./SyncData.js')

var Metrics = function () {
    // Public
    this.peers = []
    this.attacked_peers = {}
    this.attackers = {}
    this.geo = {}
    this.ports = {}

    // Update the metrics using a message.
    this.update = function (syncMessage) {
        if (!(syncMessage instanceof SyncData))
            throw 'Argument exception'

        var peer = syncMessage.peer
        var ip = syncMessage.ip
        var port = syncMessage.port

        // Update peers.
        if (!this.peers.includes(peer)) {
            this.peers.push(peer)
        }

        // Update attacks.
        if (!(peer in this.attacked_peers)) {
            this.attacked_peers[peer] = {}
            this.attacked_peers[peer].count = 1
            this.attacked_peers[peer].stamp = moment()
        }
        else {
            ++this.attacked_peers[peer].count
            this.attacked_peers[peer].stamp = moment()
        }

        // Update the list of attackers.
        if (!(ip in this.attackers)) {
            this.attackers[ip] = {}
            this.attackers[ip].count = 1
            this.attackers[ip].stamp = moment()
        }
        else {
            ++this.attackers[ip].count
            this.attackers[ip].stamp = moment()
        }

        // Update ports.
        if(!(port in this.ports)) {
            this.ports[port] = 1
        }
        else {
            ++this.ports[port]
        }

        // Update geoip.
        var geo = geoip.lookup(ip)
        if (!(geo.country in this.geo)) {
            this.geo[geo.country] = 1
        } else {
            ++this.geo[geo.country]
        }
    }
}

// Deserialize metrics from JSON.
Metrics.fromJSON = function (data) {
    const payload = JSON.parse(data)

    if (payload === null || typeof payload === undefined)
        throw 'Deserialization failed'

    for (var key in new Metrics()) {
        if (typeof Metrics[key] !== 'undefined' && !payload.hasOwnProperty(key)) {
            throw 'Deserialization failed'
        }
    }

    var metrics = new Metrics()
    metrics.peers = payload.peers
    metrics.attacked_peers = payload.attacked_peers
    metrics.attackers = payload.attackers
    metrics.geo = payload.geo
    metrics.ports = payload.ports

    return metrics
}

module.exports = Metrics