sdk.js 7.01 KB
'use strict';

const Service = require('egg').Service;
const request = require('request');
const net = {
  oldNet: '',
  newNet: ''
}
class DdnService extends Service {

  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, peer_url) {
    const { config } = this;
    const peer_host = await this.getPeerHost();
    const url = peer_url ? `${peer_url}/api/accounts?address=${address}` : `${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);
        }
        console.log(url, body)
        resolve(JSON.parse(body));
      });
    });
    return result;
  }

  // 账户信息列表
  async getAccountList(page, per_page, peer_url) {
    const { config } = this;
    const peer_host = await this.getPeerHost();
    const offect = per_page * page
    const url = peer_url ? `${peer_url}/api/accounts/top?offect=${offect}&limit=${per_page}` : `${peer_host}/api/accounts/top?page=${page}&per_page=${per_page}`;
    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 getAccountCount(peer_url) {
    const { config } = this;
    const peer_host = await this.getPeerHost();
    const url = peer_url ? `${peer_url}/api/accounts/count` : `${peer_host}/api/accounts/count`;
    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, peer_url) {
    console.log(trs)
    const { config } = this;
    const peer_host = await this.getPeerHost();
    const url = peer_url ? `${peer_url}/peer/transactions` : `${peer_host}/api/transactions`;
    let ddn_result = await new Promise(resolve => {
      request({
        url,
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          version: '',
          nethash: config.ed25519NetHash,
        },
        body: trs,
      }, (error, response, body) => {
        console.log(error, 'body', body)
        resolve(JSON.parse(body));
      });
    });
    console.log('ddn_result', ddn_result)
    // ddn_result = JSON.parse(ddn_result);
    return ddn_result;// 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 {
      }
    }

    return best_peer;
  }


}

module.exports = DdnService;