network.ts 1.38 KB
Newer Older
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
import {AbstractController} from "./AbstractController"
import {BMAConstants} from "../constants"

const _                = require('underscore');
const http2raw         = require('../http2raw');

export class NetworkBinding extends AbstractController {

  async peer() {
    const p = await this.PeeringService.peer();
    if (!p) {
      throw BMAConstants.ERRORS.SELF_PEER_NOT_FOUND;
    }
    return p.json();
  }

  async peersGet(req:any) {
    let merkle = await this.server.dal.merkleForPeers();
    return await this.MerkleService(req, merkle, async (hashes:string[]) => {
      try {
        let peers = await this.server.dal.findPeersWhoseHashIsIn(hashes);
        const map:any = {};
        peers.forEach((peer:any) => {
          map[peer.hash] = peer;
        });
        if (peers.length == 0) {
          throw BMAConstants.ERRORS.PEER_NOT_FOUND;
        }
        return map;
      } catch (e) {
        throw e;
      }
    })
  }

  peersPost(req:any) {
    return this.pushEntity(req, http2raw.peer, BMAConstants.ENTITY_PEER)
  }

  async peers() {
    let peers = await this.server.dal.listAllPeers();
    return {
      peers: peers.map((p:any) => {
        return _.pick(p,
          'version',
          'currency',
          'status',
          'first_down',
          'last_try',
          'pubkey',
          'block',
          'signature',
          'endpoints');
      })
    };
  }
}