sdk_20220214095424.js 6.71 KB
'use strict';

const Service = require('egg').Service;
const request = require('request');
class DdnService extends Service {

  // 根据前端传过来的地址查询链上数据
  async getDDNDataByUrl(url) {
    const { config } = this;
    const result = await new Promise((resolve, reject) => {
      request({
        url,
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          version: '',
          nethash: config.nethash,
        },
      }, (error, response, body) => {
        if (error) {
          reject(error);
        } else {
          resolve(JSON.parse(body));
        }
      });
    });
    return result;
  }
  async getPeers() {
    const { config } = this;
    const peer_host = await this.getPeerHost();
    const url = `${peer_host}/api/peers`;
    const result = await new Promise(resolve => {
      request({
        url,
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          version: '',
          nethash: config.nethash,
        },
      }, (error, response, body) => {
        resolve(JSON.parse(body));
      });
    });
    return result;
  }
  // 区块高度
  async getHeight() {
    const { config } = this;
    const peer_host = await this.getPeerHost();
    const url = `${peer_host}/api/blocks/getHeight`;
    const result = await new Promise(resolve => {
      request({
        url,
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          version: '',
          nethash: config.nethash,
        },
      }, (error, response, body) => {
        resolve(JSON.parse(body));
      });
    });
    return result;
  }
  // 交易详情
  async getTransaction(id) {
    const { config } = this;
    const peer_host = await this.getPeerHost();
    const url = `${peer_host}/api/transactions/get?id=${id}`;
    const result = await new Promise(resolve => {
      request({
        url,
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          version: '',
          nethash: config.nethash,
        },
      }, (error, response, body) => {
        resolve(JSON.parse(body));
      });
    });
    return result;
  }
  // 交易列表
  async getTransactions(con, page = 1, per_page = 10) {
    const { config } = this;
    const peer_host = await this.getPeerHost();
    const conditions = [];
    if (con.sender_id) {
      conditions.push('senderId=' + con.sender_id);
    }
    if (con.recipient_id) {
      conditions.push('recipientId=' + con.recipient_id);
    }
    conditions.push('limit=' + Number(per_page));
    conditions.push('offset=' + (Number(page) - 1) * Number(per_page));
    const url = `${peer_host}/api/transactions?${conditions.join('&')}`;
    const result = await new Promise(resolve => {
      request({
        url,
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          version: '',
          nethash: config.nethash,
        },
      }, (error, response, body) => {
        resolve(JSON.parse(body));
      });
    });
    return result;
  }

  // 账户信息
  async getAccount(address) {
    const { config } = this;
    const peer_host = await this.getPeerHost();
    const url = `${peer_host}/api/accounts?address=${address}`;
    const result = await new Promise((resolve, reject) => {
      request({
        url,
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          version: '',
          nethash: config.nethash,
        },
      }, (error, response, body) => {
        if (error) {
          reject(error);
        }
        resolve(JSON.parse(body));
      });
    });
    return result;
  }

  // 交易上链
  async pushTransaction(trs) {
    const { config } = this;
    const peer_host = await this.getPeerHost();
    const url = `${peer_host}/peer/transactions`;
    let ddn_result = await new Promise(resolve => {
      request({
        url,
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          version: '',
          nethash: config.nethash,
        },
        body: trs,
      }, (error, response, body) => {
        resolve(body);
      });
    });
    ddn_result = JSON.parse(ddn_result);
    return ddn_result;
  }

  // 获取结点地址
  async getPeerHost() {
    // const peer_host = await this.service.sdk.redis.get('peer_host');
    // if (!peer_host) {
    const res = await this.checkPeerHost();
    return res;
    // }
    // return peer_host.host;
  }

  // 检查结点并指定可用结点
  async checkPeerHost() {
    const { config } = this;
    // const peers = this.config.peer_list;
    // const peers = [ 'http://120.24.69.99:8003' ];
    const peers = [ 'http://localhost:8001' ];
    const peers_height = {};
    let max_height = null;
    let min_height = null;
    let best_peer = null;
    for (let i = 0; i < peers.length; i++) {
      const url = `${peers[i]}/api/blocks/getstatus`;
      const result = await new Promise(resolve => {
        request({
          url,
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            version: '',
            nethash: config.nethash,
          },
        }, (error, response, body) => {
          if (error) {
            resolve({ success: false });
          } else {
            resolve(JSON.parse(body));
          }
        });
      });
      if (result.success) {
        peers_height[peers[i]] = result.height;
        if (!max_height || Number(result.height) > Number(max_height)) {
          max_height = result.height;
        }
        if (!min_height || Number(result.height) < Number(min_height)) {
          min_height = result.height;
        }
        if (!best_peer || Number(result.height) === Number(max_height)) {
          best_peer = peers[i];
        }
      } else {
        // 节点不可达,报警

        // has_error = true;
        // this.service.sdk.alisms.peerWarning(peers[i].split(/\.|\:/)[4] + 'lost', config.admin_phone);
      }
    }
    // // 高度相差3个,就报警
    // if (max_height - min_height > 3) {
    //   console.log('高度相差3个,报警');
    //   has_error = true;
    //   this.service.sdk.alisms.peerWarning('HeighGt3', config.admin_phone);
    // }
    // if (!best_peer) {
    //   has_error = true;
    //   this.service.sdk.alisms.peerWarning('noPeer', config.admin_phone);
    // }
    // // 如果没有异常了,就再次打开监控通知,开始监控和通知
    // if (!has_error) {
    //   await this.service.sdk.redis.set('peer_warning', { status: 'on' });
    // }
    // await this.service.sdk.redis.set('peer_host', { host: best_peer });
    // await this.service.sdk.redis.set('peers_height', peers_height);
    return best_peer;
  }


}

module.exports = DdnService;