Commit 828fb271 828fb271589a861eebd48c295cf30f0a509af475 by wulianyou

first commit

0 parents
Showing 71 changed files with 4768 additions and 0 deletions
'use strict';
module.exports = {
write: true,
prefix: '^',
plugin: 'autod-egg',
test: [
'test',
'benchmark',
],
dep: [
'egg',
'egg-scripts',
],
devdep: [
'egg-ci',
'egg-bin',
'egg-mock',
'autod',
'autod-egg',
'eslint',
'eslint-config-egg',
],
exclude: [
'./test/fixtures',
'./dist',
],
};
module.exports = {
nethash: '0ab796cd'
}
\ No newline at end of file
{
"extends": "eslint-config-egg"
}
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
name: Node.js CI
on:
push:
branches:
- main
- master
pull_request:
branches:
- main
- master
schedule:
- cron: '0 2 * * *'
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
node-version: [10]
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- name: Checkout Git Source
uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Install Dependencies
run: npm i -g npminstall && npminstall
- name: Continuous Integration
run: npm run ci
- name: Code Coverage
uses: codecov/codecov-action@v1
with:
token: ${{ secrets.CODECOV_TOKEN }}
logs/
npm-debug.log
yarn-error.log
node_modules/
package-lock.json
yarn.lock
coverage/
.idea/
run/
.DS_Store
*.sw*
*.un~
typings/
.nyc_output/
'use strict';
const Controller = require('egg').Controller;
const nodeSdk = require('@ddn/node-sdk').default;
class TransferController extends Controller {
async postTransaction() {
const { ctx, config } = this;
const body = ctx.request.body;
const rule = {
secret: { type: 'string' },
amount: { type: 'string' },
transaction: { type: 'string' },
};
console.log(body);
try {
ctx.validate(rule);
} catch (error) {
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const oldNetTransaction = JSON.parse(body.transaction);
if (oldNetTransaction.recipientId !== config.ed25519Address) {
ctx.helper.err({
ctx,
err: '接收地址不正确,请使用正确的地址',
});
return;
}
// const oldNetTransaction = JSON.stringify(body.transaction);
// 旧网转出
const oldNetData = await this.service.sdk.pushTransaction(JSON.stringify({ transaction: oldNetTransaction }), config.ed25519Url);
console.log('就往转账', oldNetData, typeof oldNetData);
if (!oldNetData || !oldNetData.success) {
ctx.helper.err({
ctx,
data: oldNetData,
});
return;
}
const result = await ctx.model.Transfer.create({ toAddress: body.receiverAddress, amount: body.amount, transaction: body.transaction, address: body.senderAddress });
ctx.helper.success({
ctx,
data: result,
});
// const transaction = await nodeSdk.transaction.createTransaction(body.receiverAccount, body.amount, body.remark || '网络升级转账', config.naclSecret);
// const trs = JSON.stringify({ transaction });
// // 上链操作
// const data = await this.service.sdk.pushTransaction(trs);
// if (data.success) {
// ctx.helper.success({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: true });
// } else {
// ctx.helper.err({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: false });
// }
}
async getBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.ed25519Url);
ctx.helper.success({
ctx,
data,
});
}
async getTransaction() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.naclUrl);
ctx.helper.success({
ctx,
data,
});
}
async asyncAccount() {
const { ctx, config } = this;
const limit = 100;
let asyncCount = 0;
let errAsyncAccount = 0;
const data = await this.service.sdk.getAccountCount(config.ed25519Url);
if (data.success) {
const length = Math.ceil(data.count / 100);
for (let index = 0; index < length; index++) {
const acountList = await this.service.sdk.getAccountList(index + 1, limit, config.ed25519Url);
console.log(acountList)
if (acountList.success) {
for (let index = 0; index < acountList.accounts.length; index++) {
const element = acountList.accounts[index];
if (element.balance == 0) continue;
const result = await this.app.model.Accounts.create({ balance: element.balance, address: element.address, publicKey: element.publicKey });
if (!result) {
errAsyncAccount++;
this.ctx.logger.error(`存入账户数据出错 数据:${JSON.stringify(element)},地址:${config.ed25519Url},error: ${JSON.stringify(result)}`);
} else {
asyncCount++;
}
}
} else {
this.ctx.logger.error(`同步账户数据出错:页码:${index + 1},每页条数:${limit},地址:${config.ed25519Url}`);
}
}
} else {
this.ctx.logger.error(`同步账户数据请求账户数量出错:${config.ed25519Url}`);
}
ctx.helper.success({
ctx,
data: { 出错数量: errAsyncAccount, 同步数量: data.count, 已同步数量: asyncCount },
});
}
}
module.exports = TransferController;
'use strict';
const Controller = require('egg').Controller;
const nodeSdk = require('@ddn/node-sdk').default;
class TransferController extends Controller {
async postTransaction() {
const { ctx, config } = this;
const body = ctx.request.body;
const rule = {
secret: { type: 'string' },
amount: { type: 'string' },
transaction: { type: 'string' },
};
console.log(body);
try {
ctx.validate(rule);
} catch (error) {
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const oldNetTransaction = JSON.parse(body.transaction);
if (oldNetTransaction.recipientId !== config.ed25519Address) {
ctx.helper.err({
ctx,
err: '接收地址不正确,请使用正确的地址',
});
return;
}
// const oldNetTransaction = JSON.stringify(body.transaction);
// 旧网转出
const oldNetData = await this.service.sdk.pushTransaction(JSON.stringify({ transaction: oldNetTransaction }), config.ed25519Url);
console.log('就往转账', oldNetData, typeof oldNetData);
if (!oldNetData || !oldNetData.success) {
ctx.helper.err({
ctx,
data: oldNetData,
});
return;
}
const result = await ctx.model.Transfer.create({ toAddress: body.receiverAddress, amount: body.amount, transaction: body.transaction, address: body.senderAddress });
ctx.helper.success({
ctx,
data: result,
});
// const transaction = await nodeSdk.transaction.createTransaction(body.receiverAccount, body.amount, body.remark || '网络升级转账', config.naclSecret);
// const trs = JSON.stringify({ transaction });
// // 上链操作
// const data = await this.service.sdk.pushTransaction(trs);
// if (data.success) {
// ctx.helper.success({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: true });
// } else {
// ctx.helper.err({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: false });
// }
}
async getBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.ed25519Url);
ctx.helper.success({
ctx,
data,
});
}
async getTransaction() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.naclUrl);
ctx.helper.success({
ctx,
data,
});
}
async asyncAccount() {
const { ctx, config } = this;
const limit = 100;
let asyncCount = 0;
let errAsyncAccount = 0;
let balanceIsZero = 0;
const data = await this.service.sdk.getAccountCount(config.ed25519Url);
if (data.success) {
const length = Math.ceil(data.count / 100);
for (let index = 0; index < length; index++) {
const acountList = await this.service.sdk.getAccountList(index + 1, limit, config.ed25519Url);
console.log(acountList)
if (acountList.success) {
for (let index = 0; index < acountList.accounts.length; index++) {
const element = acountList.accounts[index];
if (element.balance == 0) {
balanceIsZero++
continue;
}
const result = await this.app.model.Accounts.create({ balance: element.balance, address: element.address, publicKey: element.publicKey });
if (!result) {
errAsyncAccount++;
this.ctx.logger.error(`存入账户数据出错 数据:${JSON.stringify(element)},地址:${config.ed25519Url},error: ${JSON.stringify(result)}`);
} else {
asyncCount++;
}
}
} else {
this.ctx.logger.error(`同步账户数据出错:页码:${index + 1},每页条数:${limit},地址:${config.ed25519Url}`);
}
}
} else {
this.ctx.logger.error(`同步账户数据请求账户数量出错:${config.ed25519Url}`);
}
ctx.helper.success({
ctx,
data: { 出错数量: errAsyncAccount, 同步数量: data.count, 已同步数量: asyncCount, 余额为零数量: balanceIsZero },
});
}
}
module.exports = TransferController;
'use strict';
const Controller = require('egg').Controller;
const nodeSdk = require('@ddn/node-sdk').default;
class TransferController extends Controller {
async postTransaction() {
const { ctx, config } = this;
const body = ctx.request.body;
const rule = {
secret: { type: 'string' },
amount: { type: 'string' },
transaction: { type: 'string' },
};
console.log(body);
try {
ctx.validate(rule);
} catch (error) {
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const oldNetTransaction = JSON.parse(body.transaction);
if (oldNetTransaction.recipientId !== config.ed25519Address) {
ctx.helper.err({
ctx,
err: '接收地址不正确,请使用正确的地址',
});
return;
}
// const oldNetTransaction = JSON.stringify(body.transaction);
// 旧网转出
const oldNetData = await this.service.sdk.pushTransaction(JSON.stringify({ transaction: oldNetTransaction }), config.ed25519Url);
console.log('就往转账', oldNetData, typeof oldNetData);
if (!oldNetData || !oldNetData.success) {
ctx.helper.err({
ctx,
data: oldNetData,
});
return;
}
const result = await ctx.model.Transfer.create({ toAddress: body.receiverAddress, amount: body.amount, transaction: body.transaction, address: body.senderAddress });
ctx.helper.success({
ctx,
data: result,
});
// const transaction = await nodeSdk.transaction.createTransaction(body.receiverAccount, body.amount, body.remark || '网络升级转账', config.naclSecret);
// const trs = JSON.stringify({ transaction });
// // 上链操作
// const data = await this.service.sdk.pushTransaction(trs);
// if (data.success) {
// ctx.helper.success({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: true });
// } else {
// ctx.helper.err({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: false });
// }
}
async getBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.ed25519Url);
ctx.helper.success({
ctx,
data,
});
}
async getTransaction() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.naclUrl);
ctx.helper.success({
ctx,
data,
});
}
async asyncAccount() {
const { ctx, config } = this;
const limit = 100;
let asyncCount = 0;
let errAsyncAccount = 0;
let balanceIsZero = 0;
const data = await this.service.sdk.getAccountCount(config.ed25519Url);
if (data.success) {
const length = Math.ceil(data.count / 100);
console.log(data.count)
for (let index = 0; index < length; index++) {
const acountList = await this.service.sdk.getAccountList(index + 1, limit, config.ed25519Url);
console.log(acountList)
if (acountList.success) {
for (let index = 0; index < acountList.accounts.length; index++) {
const element = acountList.accounts[index];
if (element.balance == 0) {
balanceIsZero++
continue;
}
const result = await this.app.model.Accounts.create({ balance: element.balance, address: element.address, publicKey: element.publicKey });
if (!result) {
errAsyncAccount++;
this.ctx.logger.error(`存入账户数据出错 数据:${JSON.stringify(element)},地址:${config.ed25519Url},error: ${JSON.stringify(result)}`);
} else {
asyncCount++;
}
}
} else {
this.ctx.logger.error(`同步账户数据出错:页码:${index + 1},每页条数:${limit},地址:${config.ed25519Url}`);
}
}
} else {
this.ctx.logger.error(`同步账户数据请求账户数量出错:${config.ed25519Url}`);
}
ctx.helper.success({
ctx,
data: { 出错数量: errAsyncAccount, 同步数量: data.count, 已同步数量: asyncCount, 余额为零数量: balanceIsZero },
});
}
}
module.exports = TransferController;
'use strict';
const Controller = require('egg').Controller;
const nodeSdk = require('@ddn/node-sdk').default;
const accountData=require('../../config/mem_accounts.json')
class TransferController extends Controller {
async postTransaction() {
const { ctx, config } = this;
const body = ctx.request.body;
const rule = {
secret: { type: 'string' },
amount: { type: 'string' },
transaction: { type: 'string' },
};
console.log(body);
try {
ctx.validate(rule);
} catch (error) {
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const oldNetTransaction = JSON.parse(body.transaction);
if (oldNetTransaction.recipientId !== config.ed25519Address) {
ctx.helper.err({
ctx,
err: '接收地址不正确,请使用正确的地址',
});
return;
}
// const oldNetTransaction = JSON.stringify(body.transaction);
// 旧网转出
const oldNetData = await this.service.sdk.pushTransaction(JSON.stringify({ transaction: oldNetTransaction }), config.ed25519Url);
console.log('就往转账', oldNetData, typeof oldNetData);
if (!oldNetData || !oldNetData.success) {
ctx.helper.err({
ctx,
data: oldNetData,
});
return;
}
const result = await ctx.model.Transfer.create({ toAddress: body.receiverAddress, amount: body.amount, transaction: body.transaction, address: body.senderAddress });
ctx.helper.success({
ctx,
data: result,
});
// const transaction = await nodeSdk.transaction.createTransaction(body.receiverAccount, body.amount, body.remark || '网络升级转账', config.naclSecret);
// const trs = JSON.stringify({ transaction });
// // 上链操作
// const data = await this.service.sdk.pushTransaction(trs);
// if (data.success) {
// ctx.helper.success({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: true });
// } else {
// ctx.helper.err({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: false });
// }
}
async getBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.ed25519Url);
ctx.helper.success({
ctx,
data,
});
}
async getTransaction() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.naclUrl);
ctx.helper.success({
ctx,
data,
});
}
async asyncAccount() {
const { ctx, config } = this;
const limit = 100;
let asyncCount = 0;
let errAsyncAccount = 0;
let balanceIsZero = 0;
const data = await this.service.sdk.getAccountCount(config.ed25519Url);
if (data.success) {
const length = Math.ceil(data.count / 100);
console.log(data.count)
for (let index = 0; index < length; index++) {
const acountList = await this.service.sdk.getAccountList(index + 1, limit, config.ed25519Url);
console.log(acountList)
if (acountList.success) {
for (let index = 0; index < acountList.accounts.length; index++) {
const element = acountList.accounts[index];
if (element.balance == 0) {
balanceIsZero++
continue;
}
const result = await this.app.model.Accounts.create({ balance: element.balance, address: element.address, publicKey: element.publicKey });
if (!result) {
errAsyncAccount++;
this.ctx.logger.error(`存入账户数据出错 数据:${JSON.stringify(element)},地址:${config.ed25519Url},error: ${JSON.stringify(result)}`);
} else {
asyncCount++;
}
}
} else {
this.ctx.logger.error(`同步账户数据出错:页码:${index + 1},每页条数:${limit},地址:${config.ed25519Url}`);
}
}
} else {
this.ctx.logger.error(`同步账户数据请求账户数量出错:${config.ed25519Url}`);
}
ctx.helper.success({
ctx,
data: { 出错数量: errAsyncAccount, 同步数量: data.count, 已同步数量: asyncCount, 余额为零数量: balanceIsZero },
});
}
}
module.exports = TransferController;
'use strict';
const Controller = require('egg').Controller;
const nodeSdk = require('@ddn/node-sdk').default;
const accountData=require('../../config/mem_accounts.json')
class TransferController extends Controller {
async postTransaction() {
const { ctx, config } = this;
const body = ctx.request.body;
const rule = {
secret: { type: 'string' },
amount: { type: 'string' },
transaction: { type: 'string' },
};
console.log(body);
try {
ctx.validate(rule);
} catch (error) {
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const oldNetTransaction = JSON.parse(body.transaction);
if (oldNetTransaction.recipientId !== config.ed25519Address) {
ctx.helper.err({
ctx,
err: '接收地址不正确,请使用正确的地址',
});
return;
}
// const oldNetTransaction = JSON.stringify(body.transaction);
// 旧网转出
const oldNetData = await this.service.sdk.pushTransaction(JSON.stringify({ transaction: oldNetTransaction }), config.ed25519Url);
console.log('就往转账', oldNetData, typeof oldNetData);
if (!oldNetData || !oldNetData.success) {
ctx.helper.err({
ctx,
data: oldNetData,
});
return;
}
const result = await ctx.model.Transfer.create({ toAddress: body.receiverAddress, amount: body.amount, transaction: body.transaction, address: body.senderAddress });
ctx.helper.success({
ctx,
data: result,
});
// const transaction = await nodeSdk.transaction.createTransaction(body.receiverAccount, body.amount, body.remark || '网络升级转账', config.naclSecret);
// const trs = JSON.stringify({ transaction });
// // 上链操作
// const data = await this.service.sdk.pushTransaction(trs);
// if (data.success) {
// ctx.helper.success({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: true });
// } else {
// ctx.helper.err({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: false });
// }
}
async getBalance() {
console.log(accountData)
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.ed25519Url);
ctx.helper.success({
ctx,
data,
});
}
async getTransaction() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.naclUrl);
ctx.helper.success({
ctx,
data,
});
}
async asyncAccount() {
const { ctx, config } = this;
const limit = 100;
let asyncCount = 0;
let errAsyncAccount = 0;
let balanceIsZero = 0;
const data = await this.service.sdk.getAccountCount(config.ed25519Url);
if (data.success) {
const length = Math.ceil(data.count / 100);
console.log(data.count)
for (let index = 0; index < length; index++) {
const acountList = await this.service.sdk.getAccountList(index + 1, limit, config.ed25519Url);
console.log(acountList)
if (acountList.success) {
for (let index = 0; index < acountList.accounts.length; index++) {
const element = acountList.accounts[index];
if (element.balance == 0) {
balanceIsZero++
continue;
}
const result = await this.app.model.Accounts.create({ balance: element.balance, address: element.address, publicKey: element.publicKey });
if (!result) {
errAsyncAccount++;
this.ctx.logger.error(`存入账户数据出错 数据:${JSON.stringify(element)},地址:${config.ed25519Url},error: ${JSON.stringify(result)}`);
} else {
asyncCount++;
}
}
} else {
this.ctx.logger.error(`同步账户数据出错:页码:${index + 1},每页条数:${limit},地址:${config.ed25519Url}`);
}
}
} else {
this.ctx.logger.error(`同步账户数据请求账户数量出错:${config.ed25519Url}`);
}
ctx.helper.success({
ctx,
data: { 出错数量: errAsyncAccount, 同步数量: data.count, 已同步数量: asyncCount, 余额为零数量: balanceIsZero },
});
}
}
module.exports = TransferController;
'use strict';
const Controller = require('egg').Controller;
const nodeSdk = require('@ddn/node-sdk').default;
const accountData=require('../../config/mem_accounts.json')
class TransferController extends Controller {
async postTransaction() {
const { ctx, config } = this;
const body = ctx.request.body;
const rule = {
secret: { type: 'string' },
amount: { type: 'string' },
transaction: { type: 'string' },
};
console.log(body);
try {
ctx.validate(rule);
} catch (error) {
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const oldNetTransaction = JSON.parse(body.transaction);
if (oldNetTransaction.recipientId !== config.ed25519Address) {
ctx.helper.err({
ctx,
err: '接收地址不正确,请使用正确的地址',
});
return;
}
// const oldNetTransaction = JSON.stringify(body.transaction);
// 旧网转出
const oldNetData = await this.service.sdk.pushTransaction(JSON.stringify({ transaction: oldNetTransaction }), config.ed25519Url);
console.log('就往转账', oldNetData, typeof oldNetData);
if (!oldNetData || !oldNetData.success) {
ctx.helper.err({
ctx,
data: oldNetData,
});
return;
}
const result = await ctx.model.Transfer.create({ toAddress: body.receiverAddress, amount: body.amount, transaction: body.transaction, address: body.senderAddress });
ctx.helper.success({
ctx,
data: result,
});
// const transaction = await nodeSdk.transaction.createTransaction(body.receiverAccount, body.amount, body.remark || '网络升级转账', config.naclSecret);
// const trs = JSON.stringify({ transaction });
// // 上链操作
// const data = await this.service.sdk.pushTransaction(trs);
// if (data.success) {
// ctx.helper.success({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: true });
// } else {
// ctx.helper.err({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: false });
// }
}
async getBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.ed25519Url);
ctx.helper.success({
ctx,
data,
});
}
async getTransaction() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.naclUrl);
ctx.helper.success({
ctx,
data,
});
}
async asyncAccount() {
const { ctx, config } = this;
const limit = 100;
let asyncCount = 0;
let errAsyncAccount = 0;
let balanceIsZero = 0;
const data = await this.service.sdk.getAccountCount(config.ed25519Url);
if (data.success) {
const length = Math.ceil(data.count / 100);
console.log(data.count)
for (let index = 0; index < length; index++) {
const acountList = await this.service.sdk.getAccountList(index + 1, limit, config.ed25519Url);
console.log(acountList)
if (acountList.success) {
for (let index = 0; index < acountList.accounts.length; index++) {
const element = acountList.accounts[index];
if (element.balance == 0) {
balanceIsZero++
continue;
}
const result = await this.app.model.Accounts.create({ balance: element.balance, address: element.address, publicKey: element.publicKey });
if (!result) {
errAsyncAccount++;
this.ctx.logger.error(`存入账户数据出错 数据:${JSON.stringify(element)},地址:${config.ed25519Url},error: ${JSON.stringify(result)}`);
} else {
asyncCount++;
}
}
} else {
this.ctx.logger.error(`同步账户数据出错:页码:${index + 1},每页条数:${limit},地址:${config.ed25519Url}`);
}
}
} else {
this.ctx.logger.error(`同步账户数据请求账户数量出错:${config.ed25519Url}`);
}
ctx.helper.success({
ctx,
data: { 出错数量: errAsyncAccount, 同步数量: data.count, 已同步数量: asyncCount, 余额为零数量: balanceIsZero },
});
}
}
module.exports = TransferController;
'use strict';
const Controller = require('egg').Controller;
const nodeSdk = require('@ddn/node-sdk').default;
const accountData = require('../../config/mem_accounts.json')
class TransferController extends Controller {
async postTransaction() {
const { ctx, config } = this;
const body = ctx.request.body;
const rule = {
secret: { type: 'string' },
amount: { type: 'string' },
transaction: { type: 'string' },
};
console.log(body);
try {
ctx.validate(rule);
} catch (error) {
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const oldNetTransaction = JSON.parse(body.transaction);
if (oldNetTransaction.recipientId !== config.ed25519Address) {
ctx.helper.err({
ctx,
err: '接收地址不正确,请使用正确的地址',
});
return;
}
// const oldNetTransaction = JSON.stringify(body.transaction);
// 旧网转出
const oldNetData = await this.service.sdk.pushTransaction(JSON.stringify({ transaction: oldNetTransaction }), config.ed25519Url);
console.log('就往转账', oldNetData, typeof oldNetData);
if (!oldNetData || !oldNetData.success) {
ctx.helper.err({
ctx,
data: oldNetData,
});
return;
}
const result = await ctx.model.Transfer.create({ toAddress: body.receiverAddress, amount: body.amount, transaction: body.transaction, address: body.senderAddress });
ctx.helper.success({
ctx,
data: result,
});
// const transaction = await nodeSdk.transaction.createTransaction(body.receiverAccount, body.amount, body.remark || '网络升级转账', config.naclSecret);
// const trs = JSON.stringify({ transaction });
// // 上链操作
// const data = await this.service.sdk.pushTransaction(trs);
// if (data.success) {
// ctx.helper.success({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: true });
// } else {
// ctx.helper.err({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: false });
// }
}
async getBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.ed25519Url);
ctx.helper.success({
ctx,
data,
});
}
async haveBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
let balance
const result = accountData.RECORDS.some(item => {
if (item.address === query.address && item.balance > 0) {
balance = item.balance
return true
}
})
ctx.helper.success({
ctx,
data: {
balance
},
});
}
async getTransaction() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.naclUrl);
ctx.helper.success({
ctx,
data,
});
}
async asyncAccount() {
const { ctx, config } = this;
const limit = 100;
let asyncCount = 0;
let errAsyncAccount = 0;
let balanceIsZero = 0;
const data = await this.service.sdk.getAccountCount(config.ed25519Url);
if (data.success) {
const length = Math.ceil(data.count / 100);
console.log(data.count)
for (let index = 0; index < length; index++) {
const acountList = await this.service.sdk.getAccountList(index + 1, limit, config.ed25519Url);
console.log(acountList)
if (acountList.success) {
for (let index = 0; index < acountList.accounts.length; index++) {
const element = acountList.accounts[index];
if (element.balance == 0) {
balanceIsZero++
continue;
}
const result = await this.app.model.Accounts.create({ balance: element.balance, address: element.address, publicKey: element.publicKey });
if (!result) {
errAsyncAccount++;
this.ctx.logger.error(`存入账户数据出错 数据:${JSON.stringify(element)},地址:${config.ed25519Url},error: ${JSON.stringify(result)}`);
} else {
asyncCount++;
}
}
} else {
this.ctx.logger.error(`同步账户数据出错:页码:${index + 1},每页条数:${limit},地址:${config.ed25519Url}`);
}
}
} else {
this.ctx.logger.error(`同步账户数据请求账户数量出错:${config.ed25519Url}`);
}
ctx.helper.success({
ctx,
data: { 出错数量: errAsyncAccount, 同步数量: data.count, 已同步数量: asyncCount, 余额为零数量: balanceIsZero },
});
}
}
module.exports = TransferController;
'use strict';
const Controller = require('egg').Controller;
const nodeSdk = require('@ddn/node-sdk').default;
const accountData = require('../../config/mem_accounts.json')
class TransferController extends Controller {
async postTransaction() {
const { ctx, config } = this;
const body = ctx.request.body;
const rule = {
secret: { type: 'string' },
amount: { type: 'string' },
transaction: { type: 'string' },
};
console.log(body);
try {
ctx.validate(rule);
} catch (error) {
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const oldNetTransaction = JSON.parse(body.transaction);
if (oldNetTransaction.recipientId !== config.ed25519Address) {
ctx.helper.err({
ctx,
err: '接收地址不正确,请使用正确的地址',
});
return;
}
// const oldNetTransaction = JSON.stringify(body.transaction);
// 旧网转出
const oldNetData = await this.service.sdk.pushTransaction(JSON.stringify({ transaction: oldNetTransaction }), config.ed25519Url);
console.log('就往转账', oldNetData, typeof oldNetData);
if (!oldNetData || !oldNetData.success) {
ctx.helper.err({
ctx,
data: oldNetData,
});
return;
}
const result = await ctx.model.Transfer.create({ toAddress: body.receiverAddress, amount: body.amount, transaction: body.transaction, address: body.senderAddress });
ctx.helper.success({
ctx,
data: result,
});
// const transaction = await nodeSdk.transaction.createTransaction(body.receiverAccount, body.amount, body.remark || '网络升级转账', config.naclSecret);
// const trs = JSON.stringify({ transaction });
// // 上链操作
// const data = await this.service.sdk.pushTransaction(trs);
// if (data.success) {
// ctx.helper.success({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: true });
// } else {
// ctx.helper.err({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: false });
// }
}
async getBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.ed25519Url);
ctx.helper.success({
ctx,
data,
});
}
async haveBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
let balance
const result = accountData.RECORDS.some(item => {
if (item.address === query.address && item.balance > 0) {
balance = item.balance
return true
}
})
if (result) {
ctx.helper.success({
ctx,
data: {
balance
},
});
} else {
ctx.helper.err({
ctx,
data: {
balance
},
});
}
}
async getTransaction() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.naclUrl);
ctx.helper.success({
ctx,
data,
});
}
async asyncAccount() {
const { ctx, config } = this;
const limit = 100;
let asyncCount = 0;
let errAsyncAccount = 0;
let balanceIsZero = 0;
const data = await this.service.sdk.getAccountCount(config.ed25519Url);
if (data.success) {
const length = Math.ceil(data.count / 100);
console.log(data.count)
for (let index = 0; index < length; index++) {
const acountList = await this.service.sdk.getAccountList(index + 1, limit, config.ed25519Url);
console.log(acountList)
if (acountList.success) {
for (let index = 0; index < acountList.accounts.length; index++) {
const element = acountList.accounts[index];
if (element.balance == 0) {
balanceIsZero++
continue;
}
const result = await this.app.model.Accounts.create({ balance: element.balance, address: element.address, publicKey: element.publicKey });
if (!result) {
errAsyncAccount++;
this.ctx.logger.error(`存入账户数据出错 数据:${JSON.stringify(element)},地址:${config.ed25519Url},error: ${JSON.stringify(result)}`);
} else {
asyncCount++;
}
}
} else {
this.ctx.logger.error(`同步账户数据出错:页码:${index + 1},每页条数:${limit},地址:${config.ed25519Url}`);
}
}
} else {
this.ctx.logger.error(`同步账户数据请求账户数量出错:${config.ed25519Url}`);
}
ctx.helper.success({
ctx,
data: { 出错数量: errAsyncAccount, 同步数量: data.count, 已同步数量: asyncCount, 余额为零数量: balanceIsZero },
});
}
}
module.exports = TransferController;
'use strict';
const Controller = require('egg').Controller;
const nodeSdk = require('@ddn/node-sdk').default;
const accountData = require('../../config/mem_accounts.json')
class TransferController extends Controller {
async postTransaction() {
const { ctx, config } = this;
const body = ctx.request.body;
const rule = {
secret: { type: 'string' },
amount: { type: 'string' },
transaction: { type: 'string' },
};
console.log(body);
try {
ctx.validate(rule);
} catch (error) {
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const oldNetTransaction = JSON.parse(body.transaction);
if (oldNetTransaction.recipientId !== config.ed25519Address) {
ctx.helper.err({
ctx,
err: '接收地址不正确,请使用正确的地址',
});
return;
}
// const oldNetTransaction = JSON.stringify(body.transaction);
// 旧网转出
const oldNetData = await this.service.sdk.pushTransaction(JSON.stringify({ transaction: oldNetTransaction }), config.ed25519Url);
console.log('就往转账', oldNetData, typeof oldNetData);
if (!oldNetData || !oldNetData.success) {
ctx.helper.err({
ctx,
data: oldNetData,
});
return;
}
const result = await ctx.model.Transfer.create({ toAddress: body.receiverAddress, amount: body.amount, transaction: body.transaction, address: body.senderAddress });
ctx.helper.success({
ctx,
data: result,
});
// const transaction = await nodeSdk.transaction.createTransaction(body.receiverAccount, body.amount, body.remark || '网络升级转账', config.naclSecret);
// const trs = JSON.stringify({ transaction });
// // 上链操作
// const data = await this.service.sdk.pushTransaction(trs);
// if (data.success) {
// ctx.helper.success({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: true });
// } else {
// ctx.helper.err({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: false });
// }
}
async getBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.ed25519Url);
ctx.helper.success({
ctx,
data,
});
}
async haveBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
let balance
const result = accountData.RECORDS.some(item => {
if (item.address === query.address && item.balance > 0) {
balance = item.balance
return true
}
})
ctx.helper.success({
ctx,
data: {
balance
},
});
}
async getTransaction() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.naclUrl);
ctx.helper.success({
ctx,
data,
});
}
async asyncAccount() {
const { ctx, config } = this;
const limit = 100;
let asyncCount = 0;
let errAsyncAccount = 0;
let balanceIsZero = 0;
const data = await this.service.sdk.getAccountCount(config.ed25519Url);
if (data.success) {
const length = Math.ceil(data.count / 100);
console.log(data.count)
for (let index = 0; index < length; index++) {
const acountList = await this.service.sdk.getAccountList(index + 1, limit, config.ed25519Url);
console.log(acountList)
if (acountList.success) {
for (let index = 0; index < acountList.accounts.length; index++) {
const element = acountList.accounts[index];
if (element.balance == 0) {
balanceIsZero++
continue;
}
const result = await this.app.model.Accounts.create({ balance: element.balance, address: element.address, publicKey: element.publicKey });
if (!result) {
errAsyncAccount++;
this.ctx.logger.error(`存入账户数据出错 数据:${JSON.stringify(element)},地址:${config.ed25519Url},error: ${JSON.stringify(result)}`);
} else {
asyncCount++;
}
}
} else {
this.ctx.logger.error(`同步账户数据出错:页码:${index + 1},每页条数:${limit},地址:${config.ed25519Url}`);
}
}
} else {
this.ctx.logger.error(`同步账户数据请求账户数量出错:${config.ed25519Url}`);
}
ctx.helper.success({
ctx,
data: { 出错数量: errAsyncAccount, 同步数量: data.count, 已同步数量: asyncCount, 余额为零数量: balanceIsZero },
});
}
}
module.exports = TransferController;
'use strict';
const Controller = require('egg').Controller;
const nodeSdk = require('@ddn/node-sdk').default;
const accountData = require('../../config/mem_accounts.json')
class TransferController extends Controller {
async postTransaction() {
const { ctx, config } = this;
const body = ctx.request.body;
const rule = {
secret: { type: 'string' },
amount: { type: 'string' },
transaction: { type: 'string' },
};
console.log(body);
try {
ctx.validate(rule);
} catch (error) {
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const oldNetTransaction = JSON.parse(body.transaction);
if (oldNetTransaction.recipientId !== config.ed25519Address) {
ctx.helper.err({
ctx,
err: '接收地址不正确,请使用正确的地址',
});
return;
}
// const oldNetTransaction = JSON.stringify(body.transaction);
// 旧网转出
const oldNetData = await this.service.sdk.pushTransaction(JSON.stringify({ transaction: oldNetTransaction }), config.ed25519Url);
console.log('就往转账', oldNetData, typeof oldNetData);
if (!oldNetData || !oldNetData.success) {
ctx.helper.err({
ctx,
data: oldNetData,
});
return;
}
const result = await ctx.model.Transfer.create({ toAddress: body.receiverAddress, amount: body.amount, transaction: body.transaction, address: body.senderAddress });
ctx.helper.success({
ctx,
data: result,
});
// const transaction = await nodeSdk.transaction.createTransaction(body.receiverAccount, body.amount, body.remark || '网络升级转账', config.naclSecret);
// const trs = JSON.stringify({ transaction });
// // 上链操作
// const data = await this.service.sdk.pushTransaction(trs);
// if (data.success) {
// ctx.helper.success({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: true });
// } else {
// ctx.helper.err({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: false });
// }
}
async haveBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.ed25519Url);
ctx.helper.success({
ctx,
data,
});
}
async getBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
let balance
const result = accountData.RECORDS.some(item => {
if (item.address === query.address && item.balance > 0) {
balance = item.balance
return true
}
})
ctx.helper.success({
ctx,
data: {
balance
},
});
}
async getTransaction() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.naclUrl);
ctx.helper.success({
ctx,
data,
});
}
async asyncAccount() {
const { ctx, config } = this;
const limit = 100;
let asyncCount = 0;
let errAsyncAccount = 0;
let balanceIsZero = 0;
const data = await this.service.sdk.getAccountCount(config.ed25519Url);
if (data.success) {
const length = Math.ceil(data.count / 100);
console.log(data.count)
for (let index = 0; index < length; index++) {
const acountList = await this.service.sdk.getAccountList(index + 1, limit, config.ed25519Url);
console.log(acountList)
if (acountList.success) {
for (let index = 0; index < acountList.accounts.length; index++) {
const element = acountList.accounts[index];
if (element.balance == 0) {
balanceIsZero++
continue;
}
const result = await this.app.model.Accounts.create({ balance: element.balance, address: element.address, publicKey: element.publicKey });
if (!result) {
errAsyncAccount++;
this.ctx.logger.error(`存入账户数据出错 数据:${JSON.stringify(element)},地址:${config.ed25519Url},error: ${JSON.stringify(result)}`);
} else {
asyncCount++;
}
}
} else {
this.ctx.logger.error(`同步账户数据出错:页码:${index + 1},每页条数:${limit},地址:${config.ed25519Url}`);
}
}
} else {
this.ctx.logger.error(`同步账户数据请求账户数量出错:${config.ed25519Url}`);
}
ctx.helper.success({
ctx,
data: { 出错数量: errAsyncAccount, 同步数量: data.count, 已同步数量: asyncCount, 余额为零数量: balanceIsZero },
});
}
}
module.exports = TransferController;
'use strict';
const Controller = require('egg').Controller;
const nodeSdk = require('@ddn/node-sdk').default;
const accountData = require('../../config/mem_accounts.json')
class TransferController extends Controller {
async postTransaction() {
const { ctx, config } = this;
const body = ctx.request.body;
const rule = {
secret: { type: 'string' },
amount: { type: 'string' },
transaction: { type: 'string' },
};
console.log(body);
try {
ctx.validate(rule);
} catch (error) {
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const oldNetTransaction = JSON.parse(body.transaction);
if (oldNetTransaction.recipientId !== config.ed25519Address) {
ctx.helper.err({
ctx,
err: '接收地址不正确,请使用正确的地址',
});
return;
}
// const oldNetTransaction = JSON.stringify(body.transaction);
// 旧网转出
const oldNetData = await this.service.sdk.pushTransaction(JSON.stringify({ transaction: oldNetTransaction }), config.ed25519Url);
console.log('就往转账', oldNetData, typeof oldNetData);
if (!oldNetData || !oldNetData.success) {
ctx.helper.err({
ctx,
data: oldNetData,
});
return;
}
const result = await ctx.model.Transfer.create({ toAddress: body.receiverAddress, amount: body.amount, transaction: body.transaction, address: body.senderAddress });
ctx.helper.success({
ctx,
data: result,
});
// const transaction = await nodeSdk.transaction.createTransaction(body.receiverAccount, body.amount, body.remark || '网络升级转账', config.naclSecret);
// const trs = JSON.stringify({ transaction });
// // 上链操作
// const data = await this.service.sdk.pushTransaction(trs);
// if (data.success) {
// ctx.helper.success({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: true });
// } else {
// ctx.helper.err({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: false });
// }
}
async haveBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.ed25519Url);
ctx.helper.success({
ctx,
data,
});
}
async getBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
let balance=0
const result = accountData.RECORDS.some(item => {
if (item.address === query.address && item.balance > 0) {
balance = item.balance
return true
}
})
ctx.helper.success({
ctx,
data: {
balance
},
});
}
async getTransaction() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.naclUrl);
ctx.helper.success({
ctx,
data,
});
}
async asyncAccount() {
const { ctx, config } = this;
const limit = 100;
let asyncCount = 0;
let errAsyncAccount = 0;
let balanceIsZero = 0;
const data = await this.service.sdk.getAccountCount(config.ed25519Url);
if (data.success) {
const length = Math.ceil(data.count / 100);
console.log(data.count)
for (let index = 0; index < length; index++) {
const acountList = await this.service.sdk.getAccountList(index + 1, limit, config.ed25519Url);
console.log(acountList)
if (acountList.success) {
for (let index = 0; index < acountList.accounts.length; index++) {
const element = acountList.accounts[index];
if (element.balance == 0) {
balanceIsZero++
continue;
}
const result = await this.app.model.Accounts.create({ balance: element.balance, address: element.address, publicKey: element.publicKey });
if (!result) {
errAsyncAccount++;
this.ctx.logger.error(`存入账户数据出错 数据:${JSON.stringify(element)},地址:${config.ed25519Url},error: ${JSON.stringify(result)}`);
} else {
asyncCount++;
}
}
} else {
this.ctx.logger.error(`同步账户数据出错:页码:${index + 1},每页条数:${limit},地址:${config.ed25519Url}`);
}
}
} else {
this.ctx.logger.error(`同步账户数据请求账户数量出错:${config.ed25519Url}`);
}
ctx.helper.success({
ctx,
data: { 出错数量: errAsyncAccount, 同步数量: data.count, 已同步数量: asyncCount, 余额为零数量: balanceIsZero },
});
}
}
module.exports = TransferController;
'use strict';
const Controller = require('egg').Controller;
const nodeSdk = require('@ddn/node-sdk').default;
const accountData = require('../../config/mem_accounts.json')
class TransferController extends Controller {
async postTransaction() {
const { ctx, config } = this;
const body = ctx.request.body;
const rule = {
secret: { type: 'string' },
amount: { type: 'string' },
transaction: { type: 'string' },
};
console.log(body);
try {
ctx.validate(rule);
} catch (error) {
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const oldNetTransaction = JSON.parse(body.transaction);
if (oldNetTransaction.recipientId !== config.ed25519Address) {
ctx.helper.err({
ctx,
err: '接收地址不正确,请使用正确的地址',
});
return;
}
// const oldNetTransaction = JSON.stringify(body.transaction);
// 旧网转出
const oldNetData = await this.service.sdk.pushTransaction(JSON.stringify({ transaction: oldNetTransaction }), config.ed25519Url);
console.log('就往转账', oldNetData, typeof oldNetData);
if (!oldNetData || !oldNetData.success) {
ctx.helper.err({
ctx,
data: oldNetData,
});
return;
}
const result = await ctx.model.Transfer.create({ toAddress: body.receiverAddress, amount: body.amount, transaction: body.transaction, address: body.senderAddress });
ctx.helper.success({
ctx,
data: result,
});
// const transaction = await nodeSdk.transaction.createTransaction(body.receiverAccount, body.amount, body.remark || '网络升级转账', config.naclSecret);
// const trs = JSON.stringify({ transaction });
// // 上链操作
// const data = await this.service.sdk.pushTransaction(trs);
// if (data.success) {
// ctx.helper.success({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: true });
// } else {
// ctx.helper.err({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: false });
// }
}
async haveBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.ed25519Url);
ctx.helper.success({
ctx,
data,
});
}
async getBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
let balance = 0
const result = accountData.RECORDS.some(item => {
if (item.address === query.address && item.balance > 0) {
balance = item.balance
return true
}
})
ctx.helper.success({
ctx,
data: {
account: { balance }
},
});
}
async getTransaction() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.naclUrl);
ctx.helper.success({
ctx,
data,
});
}
async asyncAccount() {
const { ctx, config } = this;
const limit = 100;
let asyncCount = 0;
let errAsyncAccount = 0;
let balanceIsZero = 0;
const data = await this.service.sdk.getAccountCount(config.ed25519Url);
if (data.success) {
const length = Math.ceil(data.count / 100);
console.log(data.count)
for (let index = 0; index < length; index++) {
const acountList = await this.service.sdk.getAccountList(index + 1, limit, config.ed25519Url);
console.log(acountList)
if (acountList.success) {
for (let index = 0; index < acountList.accounts.length; index++) {
const element = acountList.accounts[index];
if (element.balance == 0) {
balanceIsZero++
continue;
}
const result = await this.app.model.Accounts.create({ balance: element.balance, address: element.address, publicKey: element.publicKey });
if (!result) {
errAsyncAccount++;
this.ctx.logger.error(`存入账户数据出错 数据:${JSON.stringify(element)},地址:${config.ed25519Url},error: ${JSON.stringify(result)}`);
} else {
asyncCount++;
}
}
} else {
this.ctx.logger.error(`同步账户数据出错:页码:${index + 1},每页条数:${limit},地址:${config.ed25519Url}`);
}
}
} else {
this.ctx.logger.error(`同步账户数据请求账户数量出错:${config.ed25519Url}`);
}
ctx.helper.success({
ctx,
data: { 出错数量: errAsyncAccount, 同步数量: data.count, 已同步数量: asyncCount, 余额为零数量: balanceIsZero },
});
}
}
module.exports = TransferController;
'use strict';
const Controller = require('egg').Controller;
const nodeSdk = require('@ddn/node-sdk').default;
const accountData = require('../../config/mem_accounts.json')
class TransferController extends Controller {
async postTransaction() {
const { ctx, config } = this;
const body = ctx.request.body;
const rule = {
secret: { type: 'string' },
amount: { type: 'string' },
transaction: { type: 'string' },
};
console.log(body);
try {
ctx.validate(rule);
} catch (error) {
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const oldNetTransaction = JSON.parse(body.transaction);
if (oldNetTransaction.recipientId !== config.ed25519Address) {
ctx.helper.err({
ctx,
err: '接收地址不正确,请使用正确的地址',
});
return;
}
// const oldNetTransaction = JSON.stringify(body.transaction);
// 旧网转出
// const oldNetData = await this.service.sdk.pushTransaction(JSON.stringify({ transaction: oldNetTransaction }), config.ed25519Url);
// console.log('就往转账', oldNetData, typeof oldNetData);
// if (!oldNetData || !oldNetData.success) {
// ctx.helper.err({
// ctx,
// data: oldNetData,
// });
// return;
// }
const result = await ctx.model.Transfer.create({ toAddress: body.receiverAddress, amount: body.amount, transaction: body.transaction, address: body.senderAddress });
ctx.helper.success({
ctx,
data: result,
});
// const transaction = await nodeSdk.transaction.createTransaction(body.receiverAccount, body.amount, body.remark || '网络升级转账', config.naclSecret);
// const trs = JSON.stringify({ transaction });
// // 上链操作
// const data = await this.service.sdk.pushTransaction(trs);
// if (data.success) {
// ctx.helper.success({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: true });
// } else {
// ctx.helper.err({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: false });
// }
}
async haveBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.ed25519Url);
ctx.helper.success({
ctx,
data,
});
}
async getBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
let balance = 0
const result = accountData.RECORDS.some(item => {
if (item.address === query.address && item.balance > 0) {
balance = item.balance
return true
}
})
ctx.helper.success({
ctx,
data: {
account: { balance }
},
});
}
async getTransaction() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.naclUrl);
ctx.helper.success({
ctx,
data,
});
}
async asyncAccount() {
const { ctx, config } = this;
const limit = 100;
let asyncCount = 0;
let errAsyncAccount = 0;
let balanceIsZero = 0;
const data = await this.service.sdk.getAccountCount(config.ed25519Url);
if (data.success) {
const length = Math.ceil(data.count / 100);
console.log(data.count)
for (let index = 0; index < length; index++) {
const acountList = await this.service.sdk.getAccountList(index + 1, limit, config.ed25519Url);
console.log(acountList)
if (acountList.success) {
for (let index = 0; index < acountList.accounts.length; index++) {
const element = acountList.accounts[index];
if (element.balance == 0) {
balanceIsZero++
continue;
}
const result = await this.app.model.Accounts.create({ balance: element.balance, address: element.address, publicKey: element.publicKey });
if (!result) {
errAsyncAccount++;
this.ctx.logger.error(`存入账户数据出错 数据:${JSON.stringify(element)},地址:${config.ed25519Url},error: ${JSON.stringify(result)}`);
} else {
asyncCount++;
}
}
} else {
this.ctx.logger.error(`同步账户数据出错:页码:${index + 1},每页条数:${limit},地址:${config.ed25519Url}`);
}
}
} else {
this.ctx.logger.error(`同步账户数据请求账户数量出错:${config.ed25519Url}`);
}
ctx.helper.success({
ctx,
data: { 出错数量: errAsyncAccount, 同步数量: data.count, 已同步数量: asyncCount, 余额为零数量: balanceIsZero },
});
}
}
module.exports = TransferController;
'use strict';
const moment = require('moment');
module.exports = {
/**
* 对象拼接为字符串
* @param {object} object 待拼接的hash对象
*/
concatHash(object) {
const keys = Object.keys(object).sort();
let paramsStr = '';
for (let index = 0; index < keys.length; index++) {
const key = keys[index];
let value = object[key];
// object参数类型转换为string
if (typeof (value) === 'object') {
value = JSON.stringify(value);
}
paramsStr = paramsStr + `${key}${value}`;
}
return paramsStr;
},
err({ ctx, code, err, status }) {
ctx.body = {
success: false,
code: code || 1,
err,
};
ctx.status = status || 200;
},
// 优化错误信息可读性
errorReadable(e) {
switch (e.code) {
case 'invalid_param': { // 参数错误
const errorHash = {
missing_field: '缺失',
};
let msg = '';
for (let i = 0; i < e.errors.length; i++) {
msg += '参数' + e.errors[i].field + ' ' + (errorHash[e.errors[i].code] || e.errors[i].message) + ';';
}
return msg;
}
default:
console.log('未优化类型错误!');
return JSON.stringify(e);
}
},
success({ ctx, data, status }) {
ctx.body = {
success: true,
code: 0,
data,
};
ctx.status = status || 200;
},
async verifySign(ctx) {
const authorization = ctx.request.headers.authorization;
const timestamp = ctx.request.headers.timestamp;
const publicKey = ctx.request.headers.publickey;
if (!timestamp) {
this.err({
ctx,
err: 'hearder: timestamp不能为空',
});
return false;
}
if (!authorization) {
this.err({
ctx,
err: 'hearder: authorization不能为空',
});
return false;
}
if (!publicKey) {
this.err({
ctx,
err: 'hearder: publicKey不能为空',
});
return false;
}
// 验证时间不大于5秒
const time = moment().valueOf();
if (Math.abs(Number(timestamp) - time) > (ctx.app.config.timeEquation || 5000)) {
ctx.body = {
code: 1,
err: '签名超时',
};
return false;
}
// 验证签名
// 1. 获取请求者公钥
const platformKey = await ctx.model.PlatformKey.findOne({ where: { publicKey } });
if (!platformKey) {
ctx.body = {
code: 1,
err: 'publicKey不存在',
};
return false;
}
if (!platformKey.usable) {
ctx.body = {
code: 1,
err: '密钥对不可用',
};
return;
}
// 2. 对签名进行验证
// 2.1 合并参数并排序组合拼接
const allParams = { ...ctx.params, ...ctx.request.query, ...ctx.request.body, timestamp };
const paramsStr = this.concatHash(allParams);
const verify = this.service.sdk.gm.sm2VerifySign(paramsStr, authorization, publicKey);
// 3. 比对时间戳
if (!verify) {
ctx.body = {
code: 1,
err: '签名无效',
};
return false;
}
// 记录当前媒体平台
ctx.platformId = platformKey.platformId;
return true;
},
};
'use strict';
module.exports = app => {
const { STRING, DATE, UUID, UUIDV1, JSON } = app.Sequelize;
const Account = app.model.define('transfer', {
id: {
allowNull: false,
primaryKey: true,
type: UUID,
defaultValue: UUIDV1,
},
address: { type: STRING, comment: '地址' },
toAddress: { type: STRING, comment: '接收地址' },
amount: { type: STRING, comment: '金额' },
transaction: { type: JSON, comment: '交易体' },
createdAt: { type: DATE },
updatedAt: { type: DATE },
});
return Account;
};
'use strict';
module.exports = app => {
const { STRING, DATE, UUID, UUIDV1, JSON, BOOLEAN } = app.Sequelize;
const Account = app.model.define('transfer', {
id: {
allowNull: false,
primaryKey: true,
type: UUID,
defaultValue: UUIDV1,
},
address: { type: STRING, comment: '地址' },
toAddress: { type: STRING, comment: '接收地址' },
amount: { type: STRING, comment: '金额' },
transaction: { type: JSON, comment: '交易体' },
finish: { type: BOOLEAN, comment: '是否完成' },
createdAt: { type: DATE },
updatedAt: { type: DATE },
});
return Account;
};
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.post('/upgrade/transfer/postTransaction', controller.transfer.postTransaction);
router.get('/upgrade/transfer/getBanlance', controller.transfer.getBalance);
router.get('/upgrade/transfer/transaction', controller.transfer.getTransaction);
router.get('/upgrade/transfer/async', controller.transfer.asyncAccount);
};
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.post('/upgrade/transfer/postTransaction', controller.transfer.postTransaction);
router.get('/upgrade/transfer/getBanlance', controller.transfer.getBalance);
router.get('/upgrade/transfer/haveBalance', controller.transfer.haveBalance);
router.get('/upgrade/transfer/transaction', controller.transfer.getTransaction);
router.get('/upgrade/transfer/async', controller.transfer.asyncAccount);
};
// eslint-disable-next-line strict
const Subscription = require('egg').Subscription;
const nodeSdk = require('@ddn/node-sdk').default;
class Transfer extends Subscription {
static get schedule() {
return {
interval: '10s',
type: 'worker',
};
}
async subscribe() {
const { ctx, config } = this;
const trsData = await ctx.model.Transfer.findAll({ where: { finish: false } });
console.log(trsData)
trsData.map(async item => {
if (item.id != "e2475660-9942-11ec-b873-171b64126906") {
return
}
const transaction = await nodeSdk.transaction.createTransaction(item.toAddress, item.amount, item.remark || '网络升级转账', config.naclSecret);
const trs = JSON.stringify({ transaction });
// 上链操作
const data = await this.service.sdk.pushTransaction(trs);
if (data.success) {
ctx.model.Transfer.update({ finish: true }, { where: { id: item.id } });
} else {
ctx.model.Transfer.update({ finish: false }, { where: { id: item.id } });
}
});
}
}
module.exports = Transfer;
// eslint-disable-next-line strict
const Subscription = require('egg').Subscription;
const nodeSdk = require('@ddn/node-sdk').default;
class Transfer extends Subscription {
static get schedule() {
return {
interval: '10s',
type: 'worker',
};
}
async subscribe() {
const { ctx, config } = this;
const trsData = await ctx.model.Transfer.findAll({ where: { finish: false } });
console.log(trsData)
trsData.map(async item => {
// if (item.id != "e2475660-9942-11ec-b873-171b64126906") {
// return
// }
const transaction = await nodeSdk.transaction.createTransaction(item.toAddress, item.amount, item.remark || '网络升级转账', config.naclSecret);
const trs = JSON.stringify({ transaction });
// 上链操作
const data = await this.service.sdk.pushTransaction(trs);
if (data.success) {
ctx.model.Transfer.update({ finish: true }, { where: { id: item.id } });
} else {
ctx.model.Transfer.update({ finish: false }, { where: { id: item.id } });
}
});
}
}
module.exports = Transfer;
'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;
'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 {
}
}
return best_peer;
}
}
module.exports = DdnService;
'use strict';
const Service = require('egg').Service;
const request = require('request');
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) {
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 {
}
}
return best_peer;
}
}
module.exports = DdnService;
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1644800905769_2309';
// add your middleware config here
config.middleware = [];
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1644800905769_2309';
// add your middleware config here
config.middleware = [];
config.sequelize = {
host: 'localhost',
port: '5432',
username: 'postgres',
password: 'wawjr1314',
database: 'jh',
dialect: 'postgres',
pool: {
max: 5,
min: 0,
idle: 10000,
},
logging: true,
};
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1644800905769_2309';
// add your middleware config here
config.middleware = [];
config.sequelize = {
host: 'localhost',
port: '5432',
username: 'postgres',
password: 'wawjr1314',
database: 'ddn',
dialect: 'postgres',
pool: {
max: 5,
min: 0,
idle: 10000,
},
logging: true,
};
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1644800905769_2309';
// add your middleware config here
config.middleware = [];
config.sequelize = {
host: 'localhost',
port: '5432',
username: 'postgres',
password: 'wawjr1314',
database: 'ddn',
dialect: 'postgres',
pool: {
max: 5,
min: 0,
idle: 10000,
},
logging: true,
};
config.ed25519Address = '',
config.naclAddress = '',
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1644800905769_2309';
// add your middleware config here
config.middleware = [];
config.sequelize = {
host: 'localhost',
port: '5432',
username: 'postgres',
password: 'wawjr1314',
database: 'ddn',
dialect: 'postgres',
pool: {
max: 5,
min: 0,
idle: 10000,
},
logging: true,
};
config.ed25519Address = '';
config.naclAddress = '';
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1644800905769_2309';
// add your middleware config here
config.middleware = [];
config.sequelize = {
host: 'localhost',
port: '5432',
username: 'postgres',
password: 'wawjr1314',
database: 'ddn',
dialect: 'postgres',
pool: {
max: 5,
min: 0,
idle: 10000,
},
logging: true,
};
config.ed25519Address = '';
config.naclAddress = '';
config.naclSecret = '';
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
const config = exports = {};
config.ed25519Address = 'DFy6P2sN1KLDNtppnqLBPWcnH8GTJRouGj'; // 旧网接收钱包地址
// config.naclAddress = 'D3EFYncByWwzsSQvRsVbufBfmVstuf11QW'; // 新网转账钱包地址
config.naclSecret = 'predict upon can egg glare desk draw arm hub auction language upper'; // 新网转账钱包秘钥
config.ed25519Url = 'http://120.24.69.99:8001'; // 旧网节点地址
// config.naclUrl = 'http://8.142.20.158:9000'; // 新网节点地址
config.naclUrl = 'http://localhost:8001'; // 测试地址
config.ed25519NetHash = 'b11fa2f2';// 旧网nethash
config.naclNetHash = '0ab796cd'; // 新网nethash
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
const config = exports = {};
config.ed25519Address = 'DFy6P2sN1KLDNtppnqLBPWcnH8GTJRouGj'; // 旧网接收钱包地址
// config.naclAddress = 'D3EFYncByWwzsSQvRsVbufBfmVstuf11QW'; // 新网转账钱包地址
config.naclSecret = 'predict upon can egg glare desk draw arm hub auction language upper'; // 新网转账钱包秘钥
config.ed25519Url = 'http://120.24.69.99:8001'; // 旧网节点地址
config.naclUrl = 'http://8.142.20.158:8001'; // 新网节点地址
// config.naclUrl = 'http://localhost:8001'; // 测试地址
config.ed25519NetHash = 'b11fa2f2';// 旧网nethash
config.naclNetHash = '0ab796cd'; // 新网nethash
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};
'use strict';
/** @type Egg.EggPlugin */
module.exports = {
// had enabled by egg
// static: {
// enable: true,
// }
};
'use strict';
/** @type Egg.EggPlugin */
module.exports = {
// had enabled by egg
// static: {
// enable: true,
// }
cors: {
enable: true,
package: 'egg-cors',
},
sequelize: {
enable: true,
package: 'egg-sequelize',
},
validate: {
enable: true,
package: 'egg-validate',
},
};
'use strict';
/** @type Egg.EggPlugin */
module.exports = {
// had enabled by egg
// static: {
// enable: true,
// }
// cors: {
// enable: true,
// package: 'egg-cors',
// },
sequelize: {
enable: true,
package: 'egg-sequelize',
},
validate: {
enable: true,
package: 'egg-validate',
},
};
{
"name": "DDNTrs",
"version": "1.0.0",
"description": "DDN",
"private": true,
"egg": {
"declarations": true
},
"dependencies": {
"egg": "^2.15.1",
"egg-scripts": "^2.11.0"
},
"devDependencies": {
"autod": "^3.0.1",
"autod-egg": "^1.1.0",
"egg-bin": "^4.11.0",
"egg-ci": "^1.11.0",
"egg-mock": "^3.21.0",
"eslint": "^5.13.0",
"eslint-config-egg": "^7.1.0"
},
"engines": {
"node": ">=10.0.0"
},
"scripts": {
"start": "egg-scripts start --daemon --title=egg-server-DDNTrs",
"stop": "egg-scripts stop --title=egg-server-DDNTrs",
"dev": "egg-bin dev",
"debug": "egg-bin debug",
"test": "npm run lint -- --fix && npm run test-local",
"test-local": "egg-bin test",
"cov": "egg-bin cov",
"lint": "eslint .",
"ci": "npm run lint && npm run cov",
"autod": "autod"
},
"ci": {
"version": "10"
},
"repository": {
"type": "git",
"url": ""
},
"author": "creazy",
"license": "MIT"
}
{
"name": "DDNTrs",
"version": "1.0.0",
"description": "DDN upgrade server",
"private": true,
"egg": {
"declarations": true
},
"dependencies": {
"egg": "^2.15.1",
"egg-scripts": "^2.11.0"
},
"devDependencies": {
"autod": "^3.0.1",
"autod-egg": "^1.1.0",
"egg-bin": "^4.11.0",
"egg-ci": "^1.11.0",
"egg-mock": "^3.21.0",
"eslint": "^5.13.0",
"eslint-config-egg": "^7.1.0"
},
"engines": {
"node": ">=10.0.0"
},
"scripts": {
"start": "egg-scripts start --daemon --title=egg-server-DDNTrs",
"stop": "egg-scripts stop --title=egg-server-DDNTrs",
"dev": "egg-bin dev",
"debug": "egg-bin debug",
"test": "npm run lint -- --fix && npm run test-local",
"test-local": "egg-bin test",
"cov": "egg-bin cov",
"lint": "eslint .",
"ci": "npm run lint && npm run cov",
"autod": "autod"
},
"ci": {
"version": "10"
},
"repository": {
"type": "git",
"url": ""
},
"author": "creazy",
"license": "MIT"
}
{
"name": "DDNTrs",
"version": "1.0.0",
"description": "DDN upgrade server",
"private": true,
"egg": {
"declarations": true
},
"dependencies": {
"@ddn/node-sdk": "^2.1.2",
"egg": "^2.15.1",
"egg-scripts": "^2.11.0",
"egg-sequelize": "^6.0.0",
},
"devDependencies": {
"autod": "^3.0.1",
"autod-egg": "^1.1.0",
"egg-bin": "^4.11.0",
"egg-ci": "^1.11.0",
"egg-mock": "^3.21.0",
"eslint": "^5.13.0",
"eslint-config-egg": "^7.1.0"
},
"engines": {
"node": ">=10.0.0"
},
"scripts": {
"start": "egg-scripts start --daemon --title=egg-server-DDNTrs",
"stop": "egg-scripts stop --title=egg-server-DDNTrs",
"dev": "egg-bin dev",
"debug": "egg-bin debug",
"test": "npm run lint -- --fix && npm run test-local",
"test-local": "egg-bin test",
"cov": "egg-bin cov",
"lint": "eslint .",
"ci": "npm run lint && npm run cov",
"autod": "autod"
},
"ci": {
"version": "10"
},
"repository": {
"type": "git",
"url": ""
},
"author": "creazy",
"license": "MIT"
}
{
"name": "DDNTrs",
"version": "1.0.0",
"description": "DDN upgrade server",
"private": true,
"egg": {
"declarations": true
},
"dependencies": {
"@ddn/node-sdk": "^2.1.2",
"egg": "^2.15.1",
"egg-scripts": "^2.11.0",
"egg-sequelize": "^6.0.0"
},
"devDependencies": {
"autod": "^3.0.1",
"autod-egg": "^1.1.0",
"egg-bin": "^4.11.0",
"egg-ci": "^1.11.0",
"egg-mock": "^3.21.0",
"eslint": "^5.13.0",
"eslint-config-egg": "^7.1.0"
},
"engines": {
"node": ">=10.0.0"
},
"scripts": {
"start": "egg-scripts start --daemon --title=egg-server-DDNTrs",
"stop": "egg-scripts stop --title=egg-server-DDNTrs",
"dev": "egg-bin dev",
"debug": "egg-bin debug",
"test": "npm run lint -- --fix && npm run test-local",
"test-local": "egg-bin test",
"cov": "egg-bin cov",
"lint": "eslint .",
"ci": "npm run lint && npm run cov",
"autod": "autod"
},
"ci": {
"version": "10"
},
"repository": {
"type": "git",
"url": ""
},
"author": "creazy",
"license": "MIT"
}
'use strict';
const path = require('path');
module.exports = {
config: path.join(__dirname, 'database/config.json'),
'migrations-path': path.join(__dirname, 'database/migrations'),
'seeders-path': path.join(__dirname, 'database/seeders'),
'models-path': path.join(__dirname, 'app/model'),
};
\ No newline at end of file
language: node_js
node_js:
- '10'
before_install:
- npm i npminstall -g
install:
- npminstall
script:
- npm run ci
after_script:
- npminstall codecov && codecov
# DDNTrs
DDN
## QuickStart
<!-- add docs here for user -->
see [egg docs][egg] for more detail.
### Development
```bash
$ npm i
$ npm run dev
$ open http://localhost:7001/
```
### Deploy
```bash
$ npm start
$ npm stop
```
### npm scripts
- Use `npm run lint` to check code style.
- Use `npm test` to run unit test.
- Use `npm run autod` to auto detect dependencies upgrade, see [autod](https://www.npmjs.com/package/autod) for more detail.
[egg]: https://eggjs.org
\ No newline at end of file
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
const { ctx } = this;
ctx.body = 'hi, egg';
}
}
module.exports = HomeController;
'use strict';
const Controller = require('egg').Controller;
const nodeSdk = require('@ddn/node-sdk').default;
const accountData = require('../../config/mem_accounts.json')
class TransferController extends Controller {
async postTransaction() {
const { ctx, config } = this;
const body = ctx.request.body;
const rule = {
secret: { type: 'string' },
amount: { type: 'string' },
transaction: { type: 'string' },
};
console.log(body);
try {
ctx.validate(rule);
} catch (error) {
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const oldNetTransaction = JSON.parse(body.transaction);
if (oldNetTransaction.recipientId !== config.ed25519Address) {
ctx.helper.err({
ctx,
err: '接收地址不正确,请使用正确的地址',
});
return;
}
// const oldNetTransaction = JSON.stringify(body.transaction);
// 旧网转出
// const oldNetData = await this.service.sdk.pushTransaction(JSON.stringify({ transaction: oldNetTransaction }), config.ed25519Url);
// console.log('就往转账', oldNetData, typeof oldNetData);
// if (!oldNetData || !oldNetData.success) {
// ctx.helper.err({
// ctx,
// data: oldNetData,
// });
// return;
// }
const some = accountData.RECORDS.some(item => {
if (item.address === body.senderAddress) {
return body.amount * 10 ** 8 == item.balance;
}
});
// 加上手续费
body.amount = (body.amount + 0.1) * 10 ** 8;
if (!some) {
ctx.helper.err({
ctx,
err: '金额不正确,请联系社区工作人员',
});
return;
}
const result = await ctx.model.Transfer.create({ toAddress: body.receiverAddress, amount: body.amount, transaction: body.transaction, address: body.senderAddress });
ctx.helper.success({
ctx,
data: result,
});
// const transaction = await nodeSdk.transaction.createTransaction(body.receiverAccount, body.amount, body.remark || '网络升级转账', config.naclSecret);
// const trs = JSON.stringify({ transaction });
// // 上链操作
// const data = await this.service.sdk.pushTransaction(trs);
// if (data.success) {
// ctx.helper.success({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: true });
// } else {
// ctx.helper.err({
// ctx,
// data,
// });
// ctx.model.Transfer.update({ id: result.id }, { finish: false });
// }
}
// async haveBalance() {
// const { ctx, config } = this;
// const query = ctx.request.query;
// const rule = {
// address: { type: 'string' },
// };
// console.log(query);
// try {
// ctx.validate(rule, query);
// } catch (error) {
// console.log(error);
// ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
// return;
// }
// const data = await this.service.sdk.getAccount(query.address, config.ed25519Url);
// ctx.helper.success({
// ctx,
// data,
// });
// }
async getBalance() {
const { ctx, config } = this;
const query = ctx.request.query;
let balance = 0;
let total = 0
const rule = {
address: { type: 'string' },
};
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const transferCount = await this.ctx.model.Transfer.count({ address: query.address });
if (transferCount === 0) {
balance = 0;
} else {
accountData.RECORDS.some(item => {
if (item.address === query.address && item.balance > 0) {
balance = item.balance / (10 ** 8);
return true;
}
if (item.balance > 0) {
total += Number(item.balance)
}
});
}
console.log(total / (10 ** 8))
ctx.helper.success({
ctx,
data: {
account: { balance }
},
});
}
async getTransaction() {
const { ctx, config } = this;
const query = ctx.request.query;
const rule = {
address: { type: 'string' },
};
console.log(query);
try {
ctx.validate(rule, query);
} catch (error) {
console.log(error);
ctx.helper.err({ ctx, err: ctx.helper.errorReadable(error) });
return;
}
const data = await this.service.sdk.getAccount(query.address, config.naclUrl);
ctx.helper.success({
ctx,
data,
});
}
// async asyncAccount() {
// const { ctx, config } = this;
// const limit = 100;
// let asyncCount = 0;
// let errAsyncAccount = 0;
// let balanceIsZero = 0;
// const data = await this.service.sdk.getAccountCount(config.ed25519Url);
// if (data.success) {
// const length = Math.ceil(data.count / 100);
// console.log(data.count)
// for (let index = 0; index < length; index++) {
// const acountList = await this.service.sdk.getAccountList(index + 1, limit, config.ed25519Url);
// console.log(acountList)
// if (acountList.success) {
// for (let index = 0; index < acountList.accounts.length; index++) {
// const element = acountList.accounts[index];
// if (element.balance == 0) {
// balanceIsZero++
// continue;
// }
// const result = await this.app.model.Accounts.create({ balance: element.balance, address: element.address, publicKey: element.publicKey });
// if (!result) {
// errAsyncAccount++;
// this.ctx.logger.error(`存入账户数据出错 数据:${JSON.stringify(element)},地址:${config.ed25519Url},error: ${JSON.stringify(result)}`);
// } else {
// asyncCount++;
// }
// }
// } else {
// this.ctx.logger.error(`同步账户数据出错:页码:${index + 1},每页条数:${limit},地址:${config.ed25519Url}`);
// }
// }
// } else {
// this.ctx.logger.error(`同步账户数据请求账户数量出错:${config.ed25519Url}`);
// }
// ctx.helper.success({
// ctx,
// data: { 出错数量: errAsyncAccount, 同步数量: data.count, 已同步数量: asyncCount, 余额为零数量: balanceIsZero },
// });
// }
}
module.exports = TransferController;
'use strict';
const moment = require('moment');
module.exports = {
/**
* 对象拼接为字符串
* @param {object} object 待拼接的hash对象
*/
concatHash(object) {
const keys = Object.keys(object).sort();
let paramsStr = '';
for (let index = 0; index < keys.length; index++) {
const key = keys[index];
let value = object[key];
// object参数类型转换为string
if (typeof (value) === 'object') {
value = JSON.stringify(value);
}
paramsStr = paramsStr + `${key}${value}`;
}
return paramsStr;
},
err({ ctx, code, err, status }) {
ctx.body = {
success: false,
code: code || 1,
err,
};
ctx.status = status || 200;
},
// 优化错误信息可读性
errorReadable(e) {
switch (e.code) {
case 'invalid_param': { // 参数错误
const errorHash = {
missing_field: '缺失',
};
let msg = '';
for (let i = 0; i < e.errors.length; i++) {
msg += '参数' + e.errors[i].field + ' ' + (errorHash[e.errors[i].code] || e.errors[i].message) + ';';
}
return msg;
}
default:
console.log('未优化类型错误!');
return JSON.stringify(e);
}
},
success({ ctx, data, status }) {
ctx.body = {
success: true,
code: 0,
data,
};
ctx.status = status || 200;
},
async verifySign(ctx) {
const authorization = ctx.request.headers.authorization;
const timestamp = ctx.request.headers.timestamp;
const publicKey = ctx.request.headers.publickey;
if (!timestamp) {
this.err({
ctx,
err: 'hearder: timestamp不能为空',
});
return false;
}
if (!authorization) {
this.err({
ctx,
err: 'hearder: authorization不能为空',
});
return false;
}
if (!publicKey) {
this.err({
ctx,
err: 'hearder: publicKey不能为空',
});
return false;
}
// 验证时间不大于5秒
const time = moment().valueOf();
if (Math.abs(Number(timestamp) - time) > (ctx.app.config.timeEquation || 5000)) {
ctx.body = {
code: 1,
err: '签名超时',
};
return false;
}
// 验证签名
// 1. 获取请求者公钥
const platformKey = await ctx.model.PlatformKey.findOne({ where: { publicKey } });
if (!platformKey) {
ctx.body = {
code: 1,
err: 'publicKey不存在',
};
return false;
}
if (!platformKey.usable) {
ctx.body = {
code: 1,
err: '密钥对不可用',
};
return;
}
// 2. 对签名进行验证
// 2.1 合并参数并排序组合拼接
const allParams = { ...ctx.params, ...ctx.request.query, ...ctx.request.body, timestamp };
const paramsStr = this.concatHash(allParams);
const verify = this.service.sdk.gm.sm2VerifySign(paramsStr, authorization, publicKey);
// 3. 比对时间戳
if (!verify) {
ctx.body = {
code: 1,
err: '签名无效',
};
return false;
}
// 记录当前媒体平台
ctx.platformId = platformKey.platformId;
return true;
},
};
'use strict';
module.exports = app => {
const { STRING, DATE, UUID, UUIDV1, TEXT, BOOLEAN } = app.Sequelize;
const Account = app.model.define('account', {
id: {
allowNull: false,
primaryKey: true,
type: UUID,
defaultValue: UUIDV1,
},
address: { type: STRING, unique: true },
balance: { type: STRING },
publicKey: { type: STRING, unique: true },
created_at: { type: DATE },
updated_at: { type: DATE },
});
return Account;
};
'use strict';
module.exports = app => {
const { STRING, DATE, UUID, UUIDV1, TEXT, BOOLEAN } = app.Sequelize;
const Transfer = app.model.define('transfer', {
id: {
allowNull: false,
primaryKey: true,
type: UUID,
defaultValue: UUIDV1,
},
address: { type: STRING, comment: '地址' },
// sendTrsId: { type: STRING, comment: '发送交易成功的id' },
// toTrsId: { type: STRING, comment: '接收成功的交易id' },
toAddress: { type: STRING, comment: '接收地址' },
amount: { type: STRING, comment: '金额' },
transaction: { type: TEXT, comment: '交易体' },
finish: { type: BOOLEAN, comment: '是否完成', defaultValue: false },
createdAt: { type: DATE },
updatedAt: { type: DATE },
});
return Transfer;
};
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.post('/upgrade/transfer/postTransaction', controller.transfer.postTransaction);
router.get('/upgrade/transfer/getBanlance', controller.transfer.getBalance);
// router.get('/upgrade/transfer/haveBalance', controller.transfer.haveBalance);
router.get('/upgrade/transfer/transaction', controller.transfer.getTransaction);
// router.get('/upgrade/transfer/async', controller.transfer.asyncAccount);
};
// eslint-disable-next-line strict
const Subscription = require('egg').Subscription;
const nodeSdk = require('@ddn/node-sdk').default;
class Transfer extends Subscription {
static get schedule() {
return {
interval: '10s',
type: 'worker',
};
}
async subscribe() {
const { ctx, config } = this;
const trsData = await ctx.model.Transfer.findAll({ where: { finish: false } });
console.log(trsData)
trsData.map(async item => {
// if (item.id != "e2475660-9942-11ec-b873-171b64126906") {
// return
// }
const transaction = await nodeSdk.transaction.createTransaction(item.toAddress, item.amount, item.remark || '网络升级转账', config.naclSecret);
const trs = JSON.stringify({ transaction });
// 上链操作
const data = await this.service.sdk.pushTransaction(trs);
console.log('向新网地址转账结果',data)
if (data.success) {
ctx.model.Transfer.update({ finish: true }, { where: { id: item.id } });
} else {
ctx.model.Transfer.update({ finish: false }, { where: { id: item.id } });
}
});
}
}
module.exports = Transfer;
'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;
environment:
matrix:
- nodejs_version: '10'
install:
- ps: Install-Product node $env:nodejs_version
- npm i npminstall && node_modules\.bin\npminstall
test_script:
- node --version
- npm --version
- npm run test
build: off
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
config.cluster = {
listen: {
port: 7009,
},
};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1644800905769_2309';
// add your middleware config here
config.middleware = [];
config.security = {
csrf: {
enable: false,
ignoreJSON: true,
},
};
config.cors = {
origin: '*',
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH',
};
config.sequelize = {
host: 'localhost',
port: '5432',
username: 'postgres',
password: 'wawjr1314',
database: 'ddn',
dialect: 'postgres',
pool: {
max: 5,
min: 0,
idle: 10000,
},
logging: false,
};
// config.ed25519Address = 'DFy6P2sN1KLDNtppnqLBPWcnH8GTJRouGj'; // 旧网接收钱包地址 弃用
config.naclSecret = 'puzzle elite rescue gun blush top floor surge injury popular pole inquiry'; // 新网转账钱包秘钥
// config.ed25519Url = 'http://120.24.69.99:8001'; // 旧网节点地址 弃用
config.naclUrl = 'http://8.142.20.158:8001'; // 新网节点地址
// config.naclUrl = 'http://localhost:8001'; // 测试地址
config.ed25519NetHash = 'b11fa2f2';// 旧网nethash
config.naclNetHash = '0ab796cd'; // 新网nethash
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
const config = exports = {};
// config.ed25519Address = 'DFy6P2sN1KLDNtppnqLBPWcnH8GTJRouGj'; // 旧网接收钱包地址
// config.naclAddress = 'D3EFYncByWwzsSQvRsVbufBfmVstuf11QW'; // 新网转账钱包地址
config.naclSecret = 'puzzle elite rescue gun blush top floor surge injury popular pole inquiry'; // 新网转账钱包秘钥
// config.ed25519Url = 'http://120.24.69.99:8001'; // 旧网节点地址
config.naclUrl = 'http://8.142.20.158:8001'; // 新网节点地址
// config.naclUrl = 'http://localhost:8001'; // 测试地址
config.ed25519NetHash = 'b11fa2f2';// 旧网nethash
config.naclNetHash = '0ab796cd'; // 新网nethash
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};
/**
* Please use yourself constants file
* Note: Once the mainnet is online, this file can no longer be changed.
*/
module.exports = {
nethash: '0ab796cd', // 标定该链的版本
};
This diff could not be displayed because it is too large.
'use strict';
/** @type Egg.EggPlugin */
module.exports = {
// had enabled by egg
// static: {
// enable: true,
// }
cors: {
enable: true,
package: 'egg-cors',
},
sequelize: {
enable: true,
package: 'egg-sequelize',
},
validate: {
enable: true,
package: 'egg-validate',
},
};
{
"development": {
"username": "postgres",
"password": "wawjr1314",
"database": "ddn",
"host": "localhost",
"dialect": "postgres"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
const { UUID, DATE, STRING, TEXT, BOOLEAN, UUIDV1 } = Sequelize;
await queryInterface.createTable('transfers', {
id: {
allowNull: false,
primaryKey: true,
type: UUID,
defaultValue: UUIDV1,
},
address: { type: STRING },
to_address: { type: STRING },
amount: { type: STRING },
transaction: { type: TEXT },
finish: { type: BOOLEAN },
created_at: { type: DATE },
updated_at: { type: DATE },
});
},
async down(queryInterface, Sequelize) {
/**
* Add reverting commands here.
*
* Example:
* await queryInterface.dropTable('users');
*/
await queryInterface.dropTable('transfer');
}
};
'use strict';
module.exports = {
async up (queryInterface, Sequelize) {
const { UUID, DATE, STRING, TEXT, BOOLEAN, UUIDV1 } = Sequelize;
await queryInterface.createTable('accounts', {
id: {
allowNull: false,
primaryKey: true,
type: UUID,
defaultValue: UUIDV1,
},
address: { type: STRING, unique: true },
balance: { type: STRING },
publicKey: { type: STRING, unique: true },
created_at: { type: DATE },
updated_at: { type: DATE },
});
},
async down (queryInterface, Sequelize) {
/**
* Add reverting commands here.
*
* Example:
* await queryInterface.dropTable('users');
*/
await queryInterface.dropTable('accounts');
}
};
No preview for this file type
{
"include": [
"**/*"
]
}
\ No newline at end of file
{
"name": "DDNTrs",
"version": "1.0.0",
"description": "DDN upgrade server",
"private": true,
"egg": {
"declarations": true
},
"dependencies": {
"@ddn/node-sdk": "^2.2.0",
"egg": "^2.15.1",
"egg-cors": "^2.2.3",
"egg-scripts": "^2.11.0",
"egg-sequelize": "^6.0.0",
"egg-validate": "^2.0.2",
"pg": "^8.7.3"
},
"devDependencies": {
"autod": "^3.0.1",
"autod-egg": "^1.1.0",
"egg-bin": "^4.11.0",
"egg-ci": "^1.11.0",
"egg-mock": "^3.21.0",
"eslint": "^5.13.0",
"eslint-config-egg": "^7.1.0",
"sequelize-cli": "^6.4.1"
},
"engines": {
"node": ">=10.0.0"
},
"scripts": {
"start": "egg-scripts start --daemon --title=egg-server-DDNTrs",
"stop": "egg-scripts stop --title=egg-server-DDNTrs",
"dev": "egg-bin dev",
"debug": "egg-bin debug",
"test": "npm run lint -- --fix && npm run test-local",
"test-local": "egg-bin test",
"cov": "egg-bin cov",
"lint": "eslint .",
"ci": "npm run lint && npm run cov",
"autod": "autod",
"init":"npx sequelize db:migrate"
},
"ci": {
"version": "10"
},
"repository": {
"type": "git",
"url": ""
},
"author": "creazy",
"license": "MIT"
}
'use strict';
const { app, assert } = require('egg-mock/bootstrap');
describe('test/app/controller/home.test.js', () => {
it('should assert', () => {
const pkg = require('../../../package.json');
assert(app.config.keys.startsWith(pkg.name));
// const ctx = app.mockContext({});
// yield ctx.service.xx();
});
it('should GET /', () => {
return app.httpRequest()
.get('/')
.expect('hi, egg')
.expect(200);
});
});