epic_explorer/server/controllers/BlockchainBlock.ts

2048 lines
74 KiB
TypeScript
Raw Normal View History

2019-07-09 09:22:36 +00:00
import express from 'express';
2019-08-14 10:55:23 +00:00
import { Global } from "../global";
2019-07-09 09:22:36 +00:00
import { Request, Response, NextFunction } from 'express';
import { getRepository, getConnection } from 'typeorm';
2019-08-21 06:16:14 +00:00
import { validationMiddleware, redisMiddleware } from '../middlewares';
2019-07-09 09:22:36 +00:00
import {
InternalServerErrorException,
NoDataFoundException,
IntegerValidationException,
} from '../exceptions';
import {
BlockchainBlock,
BlockchainInput,
BlockchainOutput,
BlockchainKernel,
} from '../entities';
import {
BlockchainBlockCreateDto,
BlockchainBlockSingleViewDto,
BlockchainBlockUpdateDto,
BlockchainBlockPaginationDto,
TotalDifficultyNBlockDto,
} from '../dtos';
import { Paginate } from '../utils';
2019-09-04 09:17:26 +00:00
import {latestBlockDetails} from '../utils/common';
2019-07-09 09:22:36 +00:00
var moment = require('moment');
2019-08-08 09:15:05 +00:00
moment.updateLocale('en', {
relativeTime: {
future: "in %s",
past: "%s ago",
s: "seconds",
m: "1 minute",
mm: "%d minutes",
h: "1 hour",
hh: "%d hours",
d: "1 day",
dd: "%d days",
M: "1 month",
MM: "%d months",
y: "1 year",
yy: "%d years"
}
});
2019-07-09 09:22:36 +00:00
export class BlockchainBlockController {
public path = '/blockchain_block';
public router = express.Router();
constructor() {
this.IntializeRoutes();
}
nanoEpic(fee) {
if (fee == 0) {
return this.epic(0);
} else if (fee < 1000) {
return fee / 1000000000;
} else {
return this.microEpic(parseFloat(fee) / 1000);
}
}
microEpic(fee) {
if (fee == 0) {
return this.epic(0);
} else if (fee < 1000) {
return (fee * 1000000) / 1000000000;
} else {
return this.milliEpic(parseFloat(fee) / 1000);
}
}
milliEpic(fee) {
if (fee == 0) {
return this.epic(0);
} else if (fee < 1000) {
return (fee * 1000) / 1000000000;
} else {
return this.epic(parseFloat(fee) / 1000);
}
}
epic(fee) {
return fee;
}
2019-08-09 07:59:55 +00:00
dateDiff(date2, insec = false) {
2019-07-09 09:22:36 +00:00
var current_date = new Date();
// var current_date = new Date("Sat Apr 2 2018 15:04:00 GMT+0530 (IST)");
var enddaydif =
Math.abs(date2.getTime() - current_date.getTime()) /
(1000 * 60 * 60 * 24);
var enddayrnd = Math.round(enddaydif);
// if(enddayrnd < 1) {
var time = this.convertMinsToHrmin(
2019-08-09 07:59:55 +00:00
Math.abs(date2.getTime() - current_date.getTime()),insec
2019-07-09 09:22:36 +00:00
);
return time;
// } else if(enddayrnd == 1) {
// return 'Ends in ' + enddayrnd + ' day';
// }else {
// return 'Ends in ' + enddayrnd + ' days';
// }
}
// convertMinsToHrmin(millseconds) {
// var seconds = Math.floor(millseconds / 1000);
// var days = Math.floor(seconds / 86400);
// var hours = Math.floor((seconds % 86400) / 3600);
// var minutes = Math.floor(((seconds % 86400) % 3600) / 60);
// var dateTimeDurationString = '';
// if ((days > 0) && (hours === 0 && minutes === 0)) dateTimeDurationString += (days > 1) ? (days + ' days ') : (days + ' day ');
// if ((days > 0) && (hours > 0 || minutes > 0)) dateTimeDurationString += (days > 1) ? (days + ' days, ') : (days + ' day, ');
// if ((hours > 0) && (minutes > 0)) dateTimeDurationString += (hours > 1) ? (hours + ' hours, ') : (hours + ' hour, ');
// if ((hours > 0) && (minutes === 0)) dateTimeDurationString += (hours > 1) ? (hours + ' hours ') : (hours + ' hour ');
// if (minutes > 0) dateTimeDurationString += (minutes > 1) ? (minutes + ' minutes ') : (minutes + ' minute ');
// if (seconds > 0) dateTimeDurationString += (seconds > 1) ? (minutes + ' seconds ') : (minutes + ' second ');
// return dateTimeDurationString;
// }
2019-08-09 07:59:55 +00:00
convertMinsToHrmin(millseconds,insec) {
2019-07-09 09:22:36 +00:00
var seconds = Math.floor(millseconds / 1000);
2019-08-09 07:59:55 +00:00
if(insec){
let sec = Math.floor(millseconds / 1000);
return sec;
}
2019-07-09 09:22:36 +00:00
var days = Math.floor(seconds / 86400);
var hours = Math.floor((seconds % 86400) / 3600);
var minutes = Math.floor(((seconds % 86400) % 3600) / 60);
seconds = seconds % 60;
var dateTimeDurationString = '';
if (days > 0 && (hours === 0 && minutes === 0))
dateTimeDurationString += days > 1 ? days + 'd ' : days + 'd ';
if (days > 0 && (hours > 0 || minutes > 0))
dateTimeDurationString += days > 1 ? days + 'd ' : days + 'd ';
if (hours > 0 && minutes > 0)
dateTimeDurationString += hours > 1 ? hours + 'h ' : hours + 'h ';
if (hours > 0 && minutes === 0)
dateTimeDurationString += hours > 1 ? hours + 'h ' : hours + 'h ';
if (minutes > 0)
dateTimeDurationString += minutes > 1 ? minutes + 'm ' : minutes + 'm ';
if (seconds > 0)
dateTimeDurationString += seconds > 1 ? seconds + 's ' : seconds + 's ';
return dateTimeDurationString;
}
public IntializeRoutes() {
/**
* @swagger
* /epic_explorer/v1/blockchain_block:
* post:
* tags:
* - name: BLOCKCHAIN_BLOCK | BLOCKCHAIN_BLOCK CONTROLLER
* summary: create a blockchain_block
* description: create a blockchain_block
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: BlockchainBlock
* description: create a blockchain_block
* in: body
* required: true
* schema:
* $ref: '#/definitions/BlockchainBlockDto'
* responses:
* 200:
* description: blockchain_block created successfully
* definitions:
* BlockchainBlockDto:
* description: Dto
* properties:
* Hash:
* type: string
* Version:
* type: integer
* Height:
* type: integer
* Timestamp:
* type: string
* OutputRoot:
* type: string
* RangeProofRoot:
* type: string
* KernelRoot:
* type: string
* Nonce:
* type: string
* TotalDifficulty:
* type: string
* Previous:
* type: string
* TotalKernelOffset:
* type: string
* EdgeBits:
* type: integer
* CuckooSolution:
* type: string
* PrevRoot:
* type: string
* SecondaryScaling:
* type: integer
*/
this.router.post(
`${this.path}`,
validationMiddleware(BlockchainBlockCreateDto),
2019-08-21 06:16:14 +00:00
redisMiddleware(process.env.REDIS_EXPIRY),
2019-07-09 09:22:36 +00:00
this.BlockchainBlockCreate,
);
/**
* @swagger
2019-08-06 13:10:10 +00:00
* /epic_explorer/v1/blockchain_block/totaldiff:
2019-07-09 09:22:36 +00:00
* get:
* tags:
* - name: BLOCKCHAIN_BLOCK | BLOCKCHAIN_BLOCK CONTROLLER
* description: To get Total Difficulty and Number of Blocks
* summary: To get Total Difficulty and Number of Blocks
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: FromDate
* description: Enter the From date
* in: query
* type: string
* - name: ToDate
* description: Enter the To date
* in: query
* type: string
* - name: Interval
* description: Try to give Intevals such as 1 week/ 15 days/ 30 days/ 60 days/ 3 months
* in: query
* type: string
2019-08-06 14:28:31 +00:00
* - name: Type
* description: Enter the Algorithm Type
* in: query
* type: string
2019-08-07 08:09:41 +00:00
* - name: Difftype
* description: Enter the Difficulty Type
* in: query
* type: string
2019-07-09 09:22:36 +00:00
* responses:
* 200:
2019-08-06 13:10:10 +00:00
* description: Total Difficulty fetched successfully
2019-07-09 09:22:36 +00:00
*/
this.router.get(
2019-08-06 13:10:10 +00:00
`${this.path}/totaldiff`,
2019-07-09 09:22:36 +00:00
validationMiddleware(TotalDifficultyNBlockDto, true),
2019-08-21 06:16:14 +00:00
redisMiddleware(process.env.REDIS_EXPIRY),
2019-07-09 09:22:36 +00:00
this.TotalDifficultyNBlock,
);
2019-08-06 14:28:31 +00:00
2019-08-06 13:10:10 +00:00
/**
* @swagger
* /epic_explorer/v1/blockchain_block/blockcount:
* get:
* tags:
* - name: BLOCKCHAIN_BLOCK | BLOCKCHAIN_BLOCK CONTROLLER
* description: To get Total Difficulty and Number of Blocks
* summary: To get Total Difficulty and Number of Blocks
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: FromDate
* description: Enter the From date
* in: query
* type: string
* - name: ToDate
* description: Enter the To date
* in: query
* type: string
* - name: Interval
* description: Try to give Intevals such as 1 week/ 15 days/ 30 days/ 60 days/ 3 months
* in: query
* type: string
* responses:
* 200:
* description: Total Difficulty fetched successfully
*/
this.router.get(
`${this.path}/blockcount`,
validationMiddleware(TotalDifficultyNBlockDto, true),
2019-08-21 06:16:14 +00:00
redisMiddleware(process.env.REDIS_EXPIRY),
2019-08-06 13:10:10 +00:00
this.BlockCount,
);
2019-07-09 09:22:36 +00:00
2019-08-14 14:10:01 +00:00
/**
* @swagger
* /epic_explorer/v1/blockchain_block/blockinterval:
* get:
* tags:
* - name: BLOCKCHAIN_BLOCK | BLOCKCHAIN_BLOCK CONTROLLER
* description: To get Block Interval
* summary: To get Block Interval
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: Interval
2019-08-16 11:43:15 +00:00
* description: try to get Date
2019-08-14 14:10:01 +00:00
* in: query
* type: string
* responses:
* 200:
* description: Block Interval fetched successfully
*/
this.router.get(
`${this.path}/blockinterval`,
validationMiddleware(TotalDifficultyNBlockDto, true),
2019-08-21 06:16:14 +00:00
redisMiddleware(process.env.REDIS_EXPIRY),
2019-08-14 14:10:01 +00:00
this.BlockInterval,
);
2019-07-29 10:59:06 +00:00
/**
* @swagger
* /epic_explorer/v1/blockchain_block/stackblock:
* get:
* tags:
* - name: STACK_BLOCK | STACK_BLOCK CONTROLLER
* description: To get Total Difficulty and Number of Blocks
* summary: To get Total Difficulty and Number of Blocks
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: FromDate
* description: Enter the From date
* in: query
* type: string
* - name: ToDate
* description: Enter the To date
* in: query
* type: string
* - name: Interval
* description: Try to give Intevals such as 1 week/ 15 days/ 30 days/ 60 days/ 3 months
* in: query
* type: string
* responses:
* 200:
* description: Total Difficulty and No. of blocks fetched successfully
*/
this.router.get(
`${this.path}/stackblock`,
validationMiddleware(TotalDifficultyNBlockDto, true),
2019-08-21 06:16:14 +00:00
redisMiddleware(process.env.REDIS_EXPIRY),
2019-07-29 10:59:06 +00:00
this.StackBlock,
);
2019-07-30 07:43:44 +00:00
/**
* @swagger
* /epic_explorer/v1/blockchain_block/blockpiechart:
* get:
* tags:
* - name: STACK_BLOCK | STACK_BLOCK CONTROLLER
* description: To get Total Difficulty and Number of Blocks
* summary: To get Total Difficulty and Number of Blocks
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: FromDate
* description: Enter the From date
* in: query
* type: string
* - name: ToDate
* description: Enter the To date
* in: query
* type: string
* - name: Interval
* description: Try to give Intevals such as 1 week/ 15 days/ 30 days/ 60 days/ 3 months
* in: query
* type: string
* responses:
* 200:
* description: Total Difficulty and No. of blocks fetched successfully
*/
this.router.get(
`${this.path}/blockpiechart`,
validationMiddleware(TotalDifficultyNBlockDto, true),
2019-08-21 06:16:14 +00:00
redisMiddleware(process.env.REDIS_EXPIRY),
2019-07-30 07:43:44 +00:00
this.BlockPieChart,
);
2019-08-06 14:28:31 +00:00
2019-08-28 05:50:16 +00:00
// /**
// * @swagger
// * /epic_explorer/v1/blockchain_block/hashrate:
// * get:
// * tags:
// * - name: BLOCKCHAIN_BLOCK | BLOCKCHAIN_BLOCK CONTROLLER
// * description: To get Hash Rate of AR29 abd AT31
// * summary: To get Hash Rate of AR29 abd AT31
// * consumes:
// * - application/json
// * produces:
// * - application/json
// * parameters:
// * - name: FromDate
// * description: Enter the From date
// * in: query
// * type: string
// * - name: ToDate
// * description: Enter the To date
// * in: query
// * type: string
// * - name: Interval
// * description: Try to give Intevals such as 1 week/ 15 days/ 30 days/ 60 days/ 3 months
// * in: query
// * type: string
// * responses:
// * 200:
// * description: Hash Rate of AR29 abd AT31 fetched successfully
// */
// this.router.get(
// `${this.path}/hashrate`,
// validationMiddleware(TotalDifficultyNBlockDto, true),
// redisMiddleware(process.env.REDIS_EXPIRY),
// this.HashRate,
// );
2019-07-09 09:22:36 +00:00
/**
* @swagger
* /epic_explorer/v1/blockchain_block/latesblockdetails:
* get:
* tags:
* - name: BLOCKCHAIN_BLOCK | BLOCKCHAIN_BLOCK CONTROLLER
* description: To get Latest Block Height and Coin in Existence
* summary: To get Latest Block Height and Coin in Existence
* consumes:
* - application/json
* produces:
* - application/json
* responses:
* 200:
* description: Total Difficulty and No. of blocks fetched successfully
*/
this.router.get(
`${this.path}/latesblockdetails`,
validationMiddleware(TotalDifficultyNBlockDto, true),
2019-08-21 06:16:14 +00:00
redisMiddleware(process.env.REDIS_EXPIRY),
2019-07-09 09:22:36 +00:00
this.LatestDifficultyNBlock,
);
/**
* @swagger
* /epic_explorer/v1/blockchain_block/blockspersec:
* get:
* tags:
* - name: BLOCKCHAIN_BLOCK | BLOCKCHAIN_BLOCK CONTROLLER
* description: period of blocks generation per unit(second)
* summary: period of blocks generation per unit(second)
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: FromDate
* description: Enter the From date
* in: query
* type: string
* - name: ToDate
* description: Enter the To date
* in: query
* type: string
* - name: Interval
* description: Try to give Intevals such as 1 week/ 15 days/ 30 days/ 60 days/ 3 months
* in: query
* type: string
* responses:
* 200:
* description: period of blocks generation per second fetched Successfully
*/
this.router.get(
`${this.path}/blockspersec`,
validationMiddleware(TotalDifficultyNBlockDto, true),
2019-08-21 06:16:14 +00:00
redisMiddleware(process.env.REDIS_EXPIRY),
2019-07-09 09:22:36 +00:00
this.BlockchainBlockPerSecond,
);
/**
* @swagger
* /epic_explorer/v1/blockchain_block/supplygrowth:
* get:
* tags:
* - name: BLOCKCHAIN_BLOCK | BLOCKCHAIN_BLOCK CONTROLLER
* description: Supply growth
* summary: Supply growth
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: FromDate
* description: Enter the From date
* in: query
* type: string
* - name: ToDate
* description: Enter the To date
* in: query
* type: string
* - name: Interval
* description: Try to give Intevals such as 1 week/ 15 days/ 30 days/ 60 days/ 3 months
* in: query
* type: string
* responses:
* 200:
* description: period of blocks generation per second fetched Successfully
*/
this.router.get(
`${this.path}/supplygrowth`,
validationMiddleware(TotalDifficultyNBlockDto, true),
2019-08-21 06:16:14 +00:00
redisMiddleware(process.env.REDIS_EXPIRY),
2019-07-09 09:22:36 +00:00
this.SupplyGrowth,
);
/**
* @swagger
* /epic_explorer/v1/blockchain_block/blockminedchart:
* get:
* tags:
* - name: BLOCKCHAIN_BLOCK | BLOCKCHAIN_BLOCK CONTROLLER
* description: To get Total Difficulty and Number of Blocks
* summary: To get Block Mined
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: FromDate
* description: Enter the From date
* in: query
* type: string
* - name: ToDate
* description: Enter the To date
* in: query
* type: string
* - name: Interval
* description: Try to give Intevals such as 1 week/ 15 days/ 30 days/ 60 days/ 3 months
* in: query
* type: string
* responses:
* 200:
* description: Block Mined chart data fetched successfully
*/
this.router.get(
`${this.path}/blockminedchart`,
validationMiddleware(TotalDifficultyNBlockDto, true),
2019-08-21 06:16:14 +00:00
redisMiddleware(process.env.REDIS_EXPIRY),
2019-07-09 09:22:36 +00:00
this.BlockMineChart,
);
/**
* @swagger
* /epic_explorer/v1/blockchain_block/list:
* get:
* tags:
* - name: BLOCKCHAIN_BLOCK | BLOCKCHAIN_BLOCK CONTROLLER
* description: pagination blockchain_block
* summary: pagination blockchain_block
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: CurrentPage
* description: current page specification
* in: query
* type: integer
* required: true
* - name: PageSize
* description: page size specification
* in: query
* type: integer
* required: true
* responses:
* 200:
* description: blockchain_block list fetched successfully
*/
this.router.get(
`${this.path}/list`,
validationMiddleware(BlockchainBlockPaginationDto),
2019-08-21 06:16:14 +00:00
redisMiddleware(process.env.REDIS_EXPIRY),
2019-07-09 09:22:36 +00:00
this.BlockchainBlockPagination,
);
/**
* @swagger
* /epic_explorer/v1/blockchain_block/{hash}:
* get:
* tags:
* - name: BLOCKCHAIN_BLOCK | BLOCKCHAIN_BLOCK CONTROLLER
* summary: get single blockchain_block
* description: get single blockchain_block
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: hash
* in: path
* description: blockchain_block hash
* required: true
* type: string
* responses:
* 200:
* description: blockchain_block successfully fetched for given hash..
*/
this.router.get(
`${this.path}/:hash`,
validationMiddleware(BlockchainBlockSingleViewDto, true),
2019-08-21 06:16:14 +00:00
redisMiddleware(process.env.REDIS_EXPIRY),
2019-07-09 09:22:36 +00:00
this.BlockchainBlockFetch,
);
/**
* @swagger
* /epic_explorer/v1/blockchain_block:
* patch:
* tags:
* - name: BLOCKCHAIN_BLOCK | BLOCKCHAIN_BLOCK CONTROLLER
* summary: update a blockchain_block
* description: update a blockchain_block
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: blockchain_block
* description:
* in: body
* required: true
* schema:
* $ref: '#/definitions/BlockchainBlockDto'
* responses:
* 200:
* description: blockchain_block updated successfully
*/
this.router.patch(
`${this.path}`,
validationMiddleware(BlockchainBlockUpdateDto),
2019-08-21 06:16:14 +00:00
redisMiddleware(process.env.REDIS_EXPIRY),
2019-07-09 09:22:36 +00:00
this.BlockchainBlockUpdate,
);
/**
* @swagger
* /epic_explorer/v1/blockchain_block/hash:
* delete:
* tags:
* - name: BLOCKCHAIN_BLOCK | BLOCKCHAIN_BLOCK CONTROLLER
* summary: delete a blockchain_block
* description: delete a blockchain_block
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: Hash
* in: path
* description: blockchain_block hash
* required: true
* type: string
* responses:
* 200:
* description: blockchain_block successfully deleted for given hash..
*/
this.router.delete(
`${this.path}/:hash`,
validationMiddleware(BlockchainBlockSingleViewDto),
2019-08-21 06:16:14 +00:00
redisMiddleware(process.env.REDIS_EXPIRY),
2019-07-09 09:22:36 +00:00
this.BlockchainBlockDelete,
);
}
private BlockchainBlockCreate = async (
request: Request,
response: Response,
next: NextFunction,
) => {
try {
const BlockchainBlockRequestData: BlockchainBlockCreateDto = request.body;
2019-08-14 10:55:23 +00:00
const BlockchainBlockCreateQuery = await getConnection(Global.network).getRepository(
2019-07-09 09:22:36 +00:00
BlockchainBlock,
).save(BlockchainBlockRequestData);
response.status(200).json({
status: 200,
timestamp: Date.now(),
message: 'blockchain_block created successfully',
response: BlockchainBlockCreateQuery,
});
} catch (error) {
next(new InternalServerErrorException(error));
}
2019-08-14 10:55:23 +00:00
};
2019-07-09 09:22:36 +00:00
private BlockchainBlockFetch = async (
request: Request,
response: Response,
next: NextFunction,
) => {
try {
2019-09-10 10:08:28 +00:00
var BlockchainOutputFetchQuery = await getConnection(Global.network).getRepository(
BlockchainOutput,
2019-07-09 09:22:36 +00:00
).findOne({
select: [
2019-09-10 10:08:28 +00:00
'BlockId'
2019-07-09 09:22:36 +00:00
],
2019-09-10 10:08:28 +00:00
where: { Commit : request.params.hash },
2019-07-09 09:22:36 +00:00
});
2019-09-10 10:08:28 +00:00
if(BlockchainOutputFetchQuery){
var BlockchainBlockFetchQuery = await getConnection(Global.network).getRepository(
BlockchainBlock,
).findOne({
select: [
'Hash',
'Height',
'Timestamp',
'TotalDifficultyCuckaroo',
'TotalDifficultyCuckatoo',
'TotalDifficultyProgpow',
'TotalDifficultyRandomx',
'PreviousId',
'EdgeBits',
'SecondaryScaling',
'Proof',
],
where: { Hash: BlockchainOutputFetchQuery.BlockId },
});
}else{
var BlockchainBlockFetchQuery = await getConnection(Global.network).getRepository(
BlockchainBlock,
).findOne({
select: [
'Hash',
'Height',
'Timestamp',
'TotalDifficultyCuckaroo',
'TotalDifficultyCuckatoo',
'TotalDifficultyProgpow',
'TotalDifficultyRandomx',
'PreviousId',
'EdgeBits',
'SecondaryScaling',
'Proof',
],
where: { Hash: request.params.hash },
});
}
2019-07-09 09:22:36 +00:00
let paramVal = request.params.hash;
2019-07-16 06:17:19 +00:00
if (
!BlockchainBlockFetchQuery &&
!isNaN(paramVal) &&
paramVal.length <= 10 &&
paramVal <= 2147483647
) {
2019-08-14 10:55:23 +00:00
var BlockchainBlockFetchQuery = await getConnection(Global.network).getRepository(
2019-07-09 09:22:36 +00:00
BlockchainBlock,
).findOne({
select: [
'Hash',
'Height',
'Timestamp',
2019-07-29 14:01:27 +00:00
'TotalDifficultyCuckaroo',
'TotalDifficultyCuckatoo',
'TotalDifficultyProgpow',
'TotalDifficultyRandomx',
2019-07-09 09:22:36 +00:00
'PreviousId',
'EdgeBits',
'SecondaryScaling',
2019-07-29 14:01:27 +00:00
'Proof',
2019-07-09 09:22:36 +00:00
],
where: { Height: paramVal },
2019-07-09 09:22:36 +00:00
});
}
if (!BlockchainBlockFetchQuery) {
next(new NoDataFoundException());
2019-08-09 08:47:13 +00:00
}else{
2019-08-14 10:55:23 +00:00
const BlockchainBlockInputFetchQuery = await getConnection(Global.network).getRepository(
2019-07-09 09:22:36 +00:00
BlockchainInput,
).find({
select: ['Data'],
where: { BlockId: BlockchainBlockFetchQuery.Hash },
});
2019-08-14 10:55:23 +00:00
const BlockchainBlockOutputFetchQuery = await getConnection(Global.network).getRepository(
2019-07-09 09:22:36 +00:00
BlockchainOutput,
).find({
2019-09-10 10:08:28 +00:00
select: ['OutputType', 'Commit', 'Spent', 'MerkleProof', 'MmrIndex', 'ProofHash', 'Proof'],
2019-07-09 09:22:36 +00:00
where: { BlockId: BlockchainBlockFetchQuery.Hash },
});
2019-08-14 10:55:23 +00:00
const BlockchainBlockKernalFetchQuery = await getConnection(Global.network).getRepository(
2019-07-09 09:22:36 +00:00
BlockchainKernel,
).find({
select: ['Features', 'Fee', 'LockHeight'],
where: { BlockId: BlockchainBlockFetchQuery.Hash },
});
2019-07-29 14:01:27 +00:00
// if (BlockchainBlockFetchQuery.EdgeBits == 29) {
// BlockchainBlockFetchQuery['PoWAlgorithm'] = 'CuckARoo29';
// } else {
// BlockchainBlockFetchQuery['PoWAlgorithm'] = 'CuckAToo31';
// }
2019-08-06 14:28:31 +00:00
BlockchainBlockFetchQuery['TotalCuckoo']=parseInt(BlockchainBlockFetchQuery.TotalDifficultyCuckaroo) +
2019-08-04 00:40:13 +00:00
parseInt(BlockchainBlockFetchQuery.TotalDifficultyCuckatoo);
2019-08-12 13:55:18 +00:00
var coin_existence;
let DAY_HEIGHT = 1440
/// Height of the first epic block emission era
const BLOCK_ERA_1 = DAY_HEIGHT * 334;
/// Height of the second epic block emission era
const BLOCK_ERA_2 = BLOCK_ERA_1 + (DAY_HEIGHT * 470);
/// Height of the third epic block emission era
const BLOCK_ERA_3 = BLOCK_ERA_2 + (DAY_HEIGHT * 601);
/// Height of the fourth epic block emission era
const BLOCK_ERA_4 = BLOCK_ERA_3 + (DAY_HEIGHT * 800);
/// Height of the fifth epic block emission era
const BLOCK_ERA_5 = BLOCK_ERA_4 + (DAY_HEIGHT * 1019);
/// After the epic block emission era 6, each era will last 4 years (approximately 1460 days)
const BLOCK_ERA_6_ONWARDS = DAY_HEIGHT * 1460;
/// Block Reward that will be assigned after we change from era 5 to era 6.
const BASE_REWARD_ERA_6_ONWARDS = 0.15625;
/// Compute the total reward generated by each block in a given height.
if(BlockchainBlockFetchQuery.Height == 0) {
BlockchainBlockFetchQuery['BlockReward'] = 0;
}else if (BlockchainBlockFetchQuery.Height <= BLOCK_ERA_1) {
2019-08-12 13:55:18 +00:00
BlockchainBlockFetchQuery['BlockReward'] = 16;
} else if (BlockchainBlockFetchQuery.Height <= BLOCK_ERA_2) {
BlockchainBlockFetchQuery['BlockReward'] = 8;
} else if (BlockchainBlockFetchQuery.Height <= BLOCK_ERA_3) {
BlockchainBlockFetchQuery['BlockReward'] = 4;
} else if (BlockchainBlockFetchQuery.Height <= BLOCK_ERA_4) {
BlockchainBlockFetchQuery['BlockReward'] = 2;
} else if (BlockchainBlockFetchQuery.Height <= BLOCK_ERA_5) {
BlockchainBlockFetchQuery['BlockReward'] = 1;
} else {
// After the era 6, we reduce the block rewards by half each 1460 days.
// Minus 1 to include multiples in the same index
// (i.e changes greater than to greater or equals to)
let height_with_offset = BlockchainBlockFetchQuery.Height - (BLOCK_ERA_5 - 1);
let exp = height_with_offset / BLOCK_ERA_6_ONWARDS;
BlockchainBlockFetchQuery['BlockReward'] = BASE_REWARD_ERA_6_ONWARDS / (1 << exp);
}
// if (BlockchainBlockFetchQuery.Height <= 1440) {
// BlockchainBlockFetchQuery['BlockReward'] = 200;
// } else if (BlockchainBlockFetchQuery.Height <= 2880) {
// BlockchainBlockFetchQuery['BlockReward'] = 180;
// } else if (BlockchainBlockFetchQuery.Height <= 4320) {
// BlockchainBlockFetchQuery['BlockReward'] = 160;
// } else if (BlockchainBlockFetchQuery.Height <= 5760) {
// BlockchainBlockFetchQuery['BlockReward'] = 140;
// } else if (BlockchainBlockFetchQuery.Height <= 7200) {
// BlockchainBlockFetchQuery['BlockReward'] = 120;
// } else if (BlockchainBlockFetchQuery.Height <= 8640) {
// BlockchainBlockFetchQuery['BlockReward'] = 100;
// } else if (BlockchainBlockFetchQuery.Height <= 10080) {
// BlockchainBlockFetchQuery['BlockReward'] = 80;
// } else if (BlockchainBlockFetchQuery.Height <= 11520) {
// BlockchainBlockFetchQuery['BlockReward'] = 60;
// } else if (BlockchainBlockFetchQuery.Height <= 12960) {
// BlockchainBlockFetchQuery['BlockReward'] = 50;
// } else {
// BlockchainBlockFetchQuery['BlockReward'] = 25;
// }
2019-07-09 09:22:36 +00:00
if (BlockchainBlockFetchQuery.PreviousId) {
2019-08-14 10:55:23 +00:00
const BlockchainPreviousBlockFetchQuery = await getConnection(Global.network).getRepository(
2019-07-09 09:22:36 +00:00
BlockchainBlock,
).findOne({
2019-07-30 05:12:23 +00:00
select: ['TotalDifficultyCuckaroo', 'TotalDifficultyCuckatoo', 'TotalDifficultyProgpow', 'TotalDifficultyRandomx'],
2019-07-09 09:22:36 +00:00
where: { Hash: BlockchainBlockFetchQuery.PreviousId },
});
2019-07-29 14:01:27 +00:00
BlockchainBlockFetchQuery['TargetDifficultyCuckaroo'] =
parseInt(BlockchainBlockFetchQuery.TotalDifficultyCuckaroo) -
parseInt(BlockchainPreviousBlockFetchQuery.TotalDifficultyCuckaroo);
2019-07-30 05:12:23 +00:00
BlockchainBlockFetchQuery['TargetDifficultyCuckatoo'] =
2019-07-29 14:01:27 +00:00
parseInt(BlockchainBlockFetchQuery.TotalDifficultyCuckatoo) -
parseInt(BlockchainPreviousBlockFetchQuery.TotalDifficultyCuckatoo);
2019-07-30 05:12:23 +00:00
BlockchainBlockFetchQuery['TargetDifficultyProgpow'] =
2019-07-29 14:01:27 +00:00
parseInt(BlockchainBlockFetchQuery.TotalDifficultyProgpow) -
parseInt(BlockchainPreviousBlockFetchQuery.TotalDifficultyProgpow);
2019-07-30 05:12:23 +00:00
BlockchainBlockFetchQuery['TargetDifficultyRandomx'] =
2019-07-29 14:01:27 +00:00
parseInt(BlockchainBlockFetchQuery.TotalDifficultyRandomx) -
parseInt(BlockchainPreviousBlockFetchQuery.TotalDifficultyRandomx);
2019-07-09 09:22:36 +00:00
} else {
2019-07-29 14:01:27 +00:00
BlockchainBlockFetchQuery['TargetDifficultyCuckaroo'] = 'NULL';
BlockchainBlockFetchQuery['TargetDifficultyCuckatoo'] = 'NULL';
BlockchainBlockFetchQuery['TargetDifficultyProgpow'] = 'NULL';
BlockchainBlockFetchQuery['TargetDifficultyRandomx'] = 'NULL';
2019-07-09 09:22:36 +00:00
}
var Epicfee = 0;
BlockchainBlockKernalFetchQuery.forEach(e => {
e.Fee = this.nanoEpic(e.Fee);
Epicfee = Epicfee + e.Fee;
});
BlockchainBlockFetchQuery['Fee'] = Epicfee;
BlockchainBlockFetchQuery['Timestamp'] = moment
.utc(BlockchainBlockFetchQuery['Timestamp'])
.utc()
2019-08-14 14:10:01 +00:00
.format('MM-DD-YYYY, HH:MM:SS UTC');
2019-07-09 09:22:36 +00:00
BlockchainBlockFetchQuery['hashstart'] = BlockchainBlockFetchQuery[
'Hash'
].slice(0, 2);
BlockchainBlockFetchQuery['hashend'] = BlockchainBlockFetchQuery[
'Hash'
].slice(62, 64);
let balance = BlockchainBlockFetchQuery['Hash'].substring(2, 62);
let arr = balance.match(/.{1,6}/g);
BlockchainBlockFetchQuery['hasharray'] = arr.map(i => '#' + i);
2019-09-10 10:08:28 +00:00
var viewType = BlockchainOutputFetchQuery ? 'Commit' : 'HashHeight';
2019-07-09 09:22:36 +00:00
BlockchainBlockFetchQuery
? response.status(200).json({
2019-07-30 05:12:23 +00:00
status: 200,
timestamp: Date.now(),
message: 'blockchain_blocksuccessfully fetched for given id.',
response: {
BlockchainBlockFetchQuery: BlockchainBlockFetchQuery,
BlockchainBlockInputFetchQuery: BlockchainBlockInputFetchQuery,
BlockchainBlockOutputFetchQuery: BlockchainBlockOutputFetchQuery,
BlockchainBlockKernalFetchQuery: BlockchainBlockKernalFetchQuery,
2019-09-10 10:08:28 +00:00
viewType: viewType
2019-07-30 05:12:23 +00:00
},
})
2019-07-09 09:22:36 +00:00
: next(new NoDataFoundException());
2019-08-09 08:47:13 +00:00
}
2019-07-09 09:22:36 +00:00
} catch (error) {
2019-07-30 05:12:23 +00:00
console.log('error', error);
2019-07-09 09:22:36 +00:00
next(new InternalServerErrorException(error));
}
2019-08-12 12:50:12 +00:00
2019-07-09 09:22:36 +00:00
};
private BlockchainBlockUpdate = async (
request: Request,
response: Response,
next: NextFunction,
) => {
try {
const BlockchainBlockRequestData: BlockchainBlockUpdateDto = request.body;
2019-08-14 10:55:23 +00:00
const BlockchainBlockUpdateQuery = await getConnection(Global.network).getRepository(
2019-07-09 09:22:36 +00:00
BlockchainBlock,
).update(BlockchainBlockRequestData.Hash, BlockchainBlockRequestData);
response.status(200).json({
status: 200,
timestamp: Date.now(),
message: 'blockchain_block updated succesfully',
response: { ...BlockchainBlockUpdateQuery },
});
} catch (error) {
next(new InternalServerErrorException(error));
}
};
private BlockchainBlockDelete = async (
request: Request,
response: Response,
next: NextFunction,
) => {
try {
2019-08-14 10:55:23 +00:00
const BlockchainBlockDeleteQuery = await getConnection(Global.network).getRepository(
2019-07-09 09:22:36 +00:00
BlockchainBlock,
).delete(request.params.Hash);
BlockchainBlockDeleteQuery
? response.status(200).json({
2019-07-30 05:12:23 +00:00
status: 200,
timestamp: Date.now(),
message: 'blockchain_block successfully deleted for given hash.',
response: { ...BlockchainBlockDeleteQuery },
})
2019-07-09 09:22:36 +00:00
: next(new NoDataFoundException());
} catch (error) {
next(new InternalServerErrorException(error));
}
};
private BlockchainBlockPagination = async (
request: Request,
response: Response,
next: NextFunction,
) => {
try {
const {
CurrentPage,
// MaxPages,
PageSize,
}: BlockchainBlockPaginationDto = request.query;
2019-09-11 12:11:46 +00:00
console.log("Page size",PageSize);
2019-07-09 09:22:36 +00:00
if (parseInt(CurrentPage) == NaN) {
next(new IntegerValidationException('CurrentPage'));
} else if (parseInt(PageSize) == NaN) {
next(new IntegerValidationException('PageSize'));
}
// else if (parseInt(MaxPages) == NaN) {
// next(new IntegerValidationException('MaxPages'));
// }
else {
2019-08-14 10:55:23 +00:00
const BlockchainBlockCountQuery = await getConnection(Global.network).getRepository(BlockchainBlock)
2019-07-09 09:22:36 +00:00
.createQueryBuilder()
.getCount();
if (BlockchainBlockCountQuery) {
const PaginationReponseData = Paginate(
BlockchainBlockCountQuery,
parseInt(CurrentPage),
parseInt(PageSize),
// parseInt(MaxPages),
);
// const BlockchainBlockPaginationQuery = await getRepository(
// BlockchainBlock,
// ).find({
// skip: PaginationReponseData.startIndex,
// take: PaginationReponseData.pageSize,
// order: {
// Hash: 'DESC',
// },
// });
2019-08-14 10:55:23 +00:00
const BlockchainBlockPaginationQuery = await getConnection(Global.network).getRepository(
2019-07-09 09:22:36 +00:00
BlockchainBlock,
)
.createQueryBuilder('blockchain_block')
.select([
'blockchain_block.Hash',
'blockchain_block.Timestamp',
2019-08-04 00:40:13 +00:00
'(blockchain_block.TotalDifficultyCuckaroo + blockchain_block.TotalDifficultyCuckatoo) as TotalCuckoo',
2019-07-29 14:01:27 +00:00
'blockchain_block.TotalDifficultyCuckaroo',
'blockchain_block.TotalDifficultyCuckatoo',
'blockchain_block.TotalDifficultyProgpow',
'blockchain_block.TotalDifficultyRandomx',
2019-07-09 09:22:36 +00:00
'blockchain_block.previous_id',
2019-09-10 12:10:22 +00:00
'EXTRACT(EPOCH FROM (blockchain_block.timestamp - LAG(blockchain_block.timestamp) OVER (ORDER BY blockchain_block.timestamp))) as timetaken',
2019-07-29 14:01:27 +00:00
'blockchain_block.total_difficulty_cuckaroo - LAG(blockchain_block.total_difficulty_cuckaroo) OVER (ORDER BY blockchain_block.total_difficulty_cuckaroo) AS target_difficulty_cuckaroo',
'blockchain_block.total_difficulty_cuckatoo - LAG(blockchain_block.total_difficulty_cuckatoo) OVER (ORDER BY blockchain_block.total_difficulty_cuckatoo) AS target_difficulty_cuckatoo',
'blockchain_block.total_difficulty_progpow - LAG(blockchain_block.total_difficulty_progpow) OVER (ORDER BY blockchain_block.total_difficulty_progpow) AS target_difficulty_progpow',
'blockchain_block.total_difficulty_randomx - LAG(blockchain_block.total_difficulty_randomx) OVER (ORDER BY blockchain_block.total_difficulty_randomx) AS target_difficulty_randomx',
2019-07-09 09:22:36 +00:00
'blockchain_block.Height',
'blockchain_block.EdgeBits',
'COUNT(DISTINCT(blockchain_input.block_id)) AS input_count',
'COUNT(DISTINCT(blockchain_kernel.block_id)) AS kernal_count',
'COUNT(DISTINCT(blockchain_output.block_id)) AS output_count',
2019-07-29 14:01:27 +00:00
'blockchain_block.Proof As PoWAlgo',
2019-07-09 09:22:36 +00:00
])
2019-07-29 14:01:27 +00:00
// .addSelect(
// `CASE
// WHEN blockchain_block.EdgeBits = 29 THEN 'CuckARoo29'
// WHEN blockchain_block.EdgeBits = 31 THEN 'CuckAToo31'
// END`,
// 'PoWAlgo',
// )
2019-07-09 09:22:36 +00:00
.leftJoin('blockchain_block.BlockchainInputs', 'blockchain_input')
.leftJoin('blockchain_block.BlockchainKernels', 'blockchain_kernel')
.leftJoin('blockchain_block.BlockchainOutputs', 'blockchain_output')
.skip(PaginationReponseData.startIndex)
2019-09-11 12:11:46 +00:00
.take(PaginationReponseData.pageSize+1)
2019-07-09 09:22:36 +00:00
.orderBy('blockchain_block.Timestamp', 'DESC')
.groupBy('blockchain_block.Hash')
.getRawAndEntities();
2019-09-11 12:11:46 +00:00
console.log("page.size", PaginationReponseData.pageSize + 1);
2019-07-09 09:22:36 +00:00
let BlockchainBlockResult = BlockchainBlockPaginationQuery.raw;
2019-09-11 12:11:46 +00:00
BlockchainBlockResult.splice(-1,1);
2019-07-09 09:22:36 +00:00
let lastElemt =
BlockchainBlockResult[BlockchainBlockResult.length - 1];
2019-08-14 10:55:23 +00:00
const BlockchainPreviousBlockFetchQuery = await getConnection(Global.network).getRepository(
2019-07-09 09:22:36 +00:00
BlockchainBlock,
).findOne({
2019-07-30 05:12:23 +00:00
select: ['TotalDifficultyCuckaroo', 'TotalDifficultyCuckatoo', 'TotalDifficultyProgpow', 'TotalDifficultyRandomx'],
2019-07-09 09:22:36 +00:00
where: { Hash: lastElemt.previous_id },
});
BlockchainBlockResult[BlockchainBlockResult.length - 1][
2019-07-29 14:01:27 +00:00
'target_difficulty_cuckaroo'
2019-07-30 05:12:23 +00:00
] = BlockchainPreviousBlockFetchQuery &&
BlockchainPreviousBlockFetchQuery != undefined ?
(parseInt(lastElemt.blockchain_block_total_difficulty_cuckaroo)
? parseInt(lastElemt.blockchain_block_total_difficulty_cuckaroo)
: 0) -
(parseInt(BlockchainPreviousBlockFetchQuery.TotalDifficultyCuckaroo) ? parseInt(BlockchainPreviousBlockFetchQuery.TotalDifficultyCuckaroo) : 0)
: 0;
BlockchainBlockResult[BlockchainBlockResult.length - 1][
'target_difficulty_cuckatoo'
] = BlockchainPreviousBlockFetchQuery &&
BlockchainPreviousBlockFetchQuery != undefined ?
2019-07-29 14:01:27 +00:00
(parseInt(lastElemt.blockchain_block_total_difficulty_cuckatoo)
? parseInt(lastElemt.blockchain_block_total_difficulty_cuckatoo)
: 0) -
2019-07-30 05:12:23 +00:00
(parseInt(BlockchainPreviousBlockFetchQuery.TotalDifficultyCuckatoo) ? parseInt(BlockchainPreviousBlockFetchQuery.TotalDifficultyCuckatoo) : 0)
: 0;
BlockchainBlockResult[BlockchainBlockResult.length - 1][
'target_difficulty_progpow'
] = BlockchainPreviousBlockFetchQuery &&
BlockchainPreviousBlockFetchQuery != undefined ?
(parseInt(lastElemt.blockchain_block_total_difficulty_progpow)
? parseInt(lastElemt.blockchain_block_total_difficulty_progpow)
: 0) -
(parseInt(BlockchainPreviousBlockFetchQuery.TotalDifficultyProgpow) ? parseInt(BlockchainPreviousBlockFetchQuery.TotalDifficultyProgpow) : 0)
: 0;
BlockchainBlockResult[BlockchainBlockResult.length - 1][
'target_difficulty_randomx'
] = BlockchainPreviousBlockFetchQuery &&
BlockchainPreviousBlockFetchQuery != undefined ?
(parseInt(lastElemt.blockchain_block_total_difficulty_randomx)
? parseInt(lastElemt.blockchain_block_total_difficulty_randomx)
: 0) -
(parseInt(BlockchainPreviousBlockFetchQuery.TotalDifficultyRandomx) ? parseInt(BlockchainPreviousBlockFetchQuery.TotalDifficultyRandomx) : 0)
: 0;
2019-07-09 09:22:36 +00:00
BlockchainBlockResult.forEach(e => {
var latest_block = this.dateDiff(e.blockchain_block_timestamp);
e['hashstart'] = e.blockchain_block_hash.slice(0, 2);
e['hashend'] = e.blockchain_block_hash.slice(62, 64);
let balance = e.blockchain_block_hash.substring(2, 62);
let arr = balance.match(/.{1,6}/g);
e['hasharray'] = arr.map(i => '#' + i);
e['age'] = latest_block;
});
//console.log(BlockchainBlockPaginationQueryRawResult);
response.status(200).json({
status: 200,
timestamp: Date.now(),
message: 'blockchain_block list fetched successfully',
response: {
...PaginationReponseData,
BlockchainBlockResult,
},
});
} else {
next(new NoDataFoundException());
}
}
} catch (error) {
2019-07-30 05:12:23 +00:00
console.log('error', error);
2019-07-09 09:22:36 +00:00
next(new InternalServerErrorException(error));
}
};
2019-08-06 14:28:31 +00:00
2019-08-06 13:10:10 +00:00
private BlockCount = async (
2019-07-09 09:22:36 +00:00
request: Request,
response: Response,
next: NextFunction,
) => {
try {
const TotalDifficultyNBlockRequestData: TotalDifficultyNBlockDto =
request.query;
if (TotalDifficultyNBlockRequestData.Interval) {
var timeIntervalQry =
"timestamp at time zone '" +
process.env.TIME_ZONE +
"' > current_date - interval '" +
TotalDifficultyNBlockRequestData.Interval +
"'";
} else if (
TotalDifficultyNBlockRequestData.FromDate ||
TotalDifficultyNBlockRequestData.ToDate
) {
let fromdate = moment(TotalDifficultyNBlockRequestData.FromDate)
.utc()
.format('YYYY-MM-DD');
let todate = moment(TotalDifficultyNBlockRequestData.ToDate)
.utc()
.format('YYYY-MM-DD');
var timeIntervalQry =
"timestamp at time zone '" +
process.env.TIME_ZONE +
"' BETWEEN SYMMETRIC '" +
fromdate +
"' AND '" +
todate +
"'";
} else {
2019-08-06 13:10:10 +00:00
var timeIntervalQry =
2019-07-09 09:22:36 +00:00
"timestamp at time zone '" +
process.env.TIME_ZONE +
2019-08-09 07:59:55 +00:00
"' > current_date - interval '1 day'";
2019-07-09 09:22:36 +00:00
}
2019-08-14 10:55:23 +00:00
const BlockQuery = await getConnection(Global.network)
2019-07-09 09:22:36 +00:00
.query(
2019-07-30 07:13:24 +00:00
"select 1 as hash, max(total_difficulty_cuckaroo) as total_difficulty_cuckaroo, \
max(total_difficulty_cuckatoo) as total_difficulty_cuckatoo, \
max(total_difficulty_progpow) as total_difficulty_progpow, \
max(total_difficulty_randomx) as total_difficulty_randomx, date(DATE_TRUNC('day', timestamp at time zone '" +
2019-07-30 05:12:23 +00:00
process.env.TIME_ZONE +
2019-09-04 09:17:26 +00:00
"')) as date, count(DISTINCT hash) as blocks \
2019-07-09 09:22:36 +00:00
from blockchain_block where " +
2019-08-06 13:10:10 +00:00
timeIntervalQry +
2019-07-30 05:12:23 +00:00
"group by DATE_TRUNC('day', timestamp at time zone '" +
process.env.TIME_ZONE +
"') order by date",
2019-07-09 09:22:36 +00:00
)
.catch(err_msg => {
next(err_msg);
});
2019-08-06 13:10:10 +00:00
let date = [],
blockDate = [],
blocks = [];
BlockQuery.forEach(e => {
blockDate.push(moment(e.date).format('YYYY-MM-DD'));
blocks.push(parseInt(e.blocks));
});
2019-08-19 08:03:05 +00:00
2019-08-19 08:15:19 +00:00
if(blockDate.length == 0){
2019-08-19 08:03:05 +00:00
date = [moment(Date.now()).format('YYYY-MM-DD')];
blockDate = [moment(Date.now()).format('YYYY-MM-DD')];
blocks = [0];
}
2019-08-06 13:10:10 +00:00
response.status(200).json({
status: 200,
timestamp: Date.now(),
message: 'Total Difficulty and Blocks Data fetched Successfully',
response: {
Date: date,
Blocks: blocks,
blockDate:blockDate
},
});
} catch (error) {
next(new InternalServerErrorException(error));
}
};
2019-08-14 14:10:01 +00:00
private BlockInterval = async (
request: Request,
response: Response,
next: NextFunction,
) => {
try {
const TotalDifficultyNBlockRequestData: TotalDifficultyNBlockDto =
request.query;
if (TotalDifficultyNBlockRequestData.Interval) {
2019-08-16 11:43:15 +00:00
var IntervalDate = TotalDifficultyNBlockRequestData.Interval;
}else {
var current_date = Date.now();
var IntervalDate = "";
IntervalDate = moment(current_date).format('YYYY-MM-DD');
}
2019-08-14 14:10:01 +00:00
const BlockQuery = await getConnection(Global.network)
.query(
2019-08-22 13:01:01 +00:00
"SELECT bb.height, coalesce(max(bb.alter), 0) as alter, bb.timestamp FROM (SELECT height, EXTRACT(EPOCH FROM (timestamp - LAG(timestamp) OVER (ORDER BY timestamp))) AS alter, timestamp FROM blockchain_block where timestamp::date = date '"+IntervalDate+"' AND height != 0 order by height asc) as bb group by bb.height , bb.timestamp;",
2019-08-14 14:10:01 +00:00
)
.catch(err_msg => {
next(err_msg);
});
let date = [],
2019-08-16 11:43:15 +00:00
alter = [],
2019-08-14 14:10:01 +00:00
blocks = [];
BlockQuery.forEach(e => {
2019-08-16 11:43:15 +00:00
//date.push(moment(e.timestamp).format('YYYY-MM-DD HH:MM:SS'));
alter.push(parseInt(e.alter));
blocks.push(parseInt(e.height));
2019-08-14 14:10:01 +00:00
});
response.status(200).json({
status: 200,
timestamp: Date.now(),
message: 'Block Interval Data fetched Successfully',
response: {
2019-08-16 11:43:15 +00:00
//Date: date,
2019-08-14 14:10:01 +00:00
Blocks: blocks,
2019-08-16 11:43:15 +00:00
alter:alter
2019-08-14 14:10:01 +00:00
},
});
} catch (error) {
next(new InternalServerErrorException(error));
}
};
2019-08-06 13:10:10 +00:00
private TotalDifficultyNBlock = async (
request: Request,
response: Response,
next: NextFunction,
) => {
try {
const TotalDifficultyNBlockRequestData: TotalDifficultyNBlockDto =
request.query;
if (TotalDifficultyNBlockRequestData.Interval) {
var timeIntervalQry =
"timestamp at time zone '" +
process.env.TIME_ZONE +
"' > current_date - interval '" +
TotalDifficultyNBlockRequestData.Interval +
"'";
} else if (
TotalDifficultyNBlockRequestData.FromDate ||
TotalDifficultyNBlockRequestData.ToDate
) {
let fromdate = moment(TotalDifficultyNBlockRequestData.FromDate)
.utc()
.format('YYYY-MM-DD');
let todate = moment(TotalDifficultyNBlockRequestData.ToDate)
.utc()
.format('YYYY-MM-DD');
var timeIntervalQry =
"timestamp at time zone '" +
process.env.TIME_ZONE +
"' BETWEEN SYMMETRIC '" +
fromdate +
"' AND '" +
todate +
"'";
} else {
var timeIntervalQry =
"timestamp at time zone '" +
process.env.TIME_ZONE +
"' > current_date - interval '1 day'";
2019-08-06 14:28:31 +00:00
2019-08-06 13:10:10 +00:00
}
2019-08-06 14:28:31 +00:00
var alog_type = TotalDifficultyNBlockRequestData.Type;
2019-08-07 08:09:41 +00:00
var Difftype = TotalDifficultyNBlockRequestData.Difftype;
if (TotalDifficultyNBlockRequestData.Interval && TotalDifficultyNBlockRequestData.Interval != '1 day') {
2019-08-08 06:36:56 +00:00
var dateFormat = 'YYYY-MM-DD HH:mm:ss';
var tickFormat = '%m-%d';
2019-08-07 08:09:41 +00:00
}else{
2019-08-08 06:36:56 +00:00
var dateFormat = 'YYYY-MM-DD HH:mm:ss';
var tickFormat = '%H-%M';
2019-08-07 08:09:41 +00:00
}
2019-08-12 12:50:12 +00:00
if(Difftype == "target"){
2019-08-14 10:55:23 +00:00
var TotalDifficultyNBlockQuery = await getConnection(Global.network)
2019-08-07 08:09:41 +00:00
.query(
2019-08-12 12:50:12 +00:00
"SELECT a.hash, a.total_difficulty_randomx, a.total_difficulty_cuckatoo,a.total_difficulty_progpow, a.date FROM(select 1 as hash, (total_difficulty_cuckatoo - LAG(total_difficulty_cuckatoo) OVER (ORDER BY total_difficulty_cuckatoo)) AS total_difficulty_cuckatoo, \
(total_difficulty_progpow - LAG(total_difficulty_progpow) OVER (ORDER BY total_difficulty_progpow)) AS total_difficulty_progpow , \
(total_difficulty_randomx - LAG(total_difficulty_randomx) OVER (ORDER BY total_difficulty_randomx)) AS total_difficulty_randomx, \
2019-08-07 08:09:41 +00:00
DATE_TRUNC('minute', timestamp at time zone '" +
process.env.TIME_ZONE +
"') as date \
from blockchain_block where " +
timeIntervalQry +
2019-08-12 12:50:12 +00:00
" order by height) as a WHERE a.total_difficulty_randomx IS NOT NULL AND a.total_difficulty_progpow IS NOT NULL AND a.total_difficulty_cuckatoo IS NOT NULL AND a.total_difficulty_cuckatoo != '0' AND a.total_difficulty_randomx != '0' AND a.total_difficulty_progpow != '0'",
2019-08-07 08:09:41 +00:00
)
.catch(err_msg => {
next(err_msg);
});
}else if(Difftype == "total"){
2019-08-14 10:55:23 +00:00
var TotalDifficultyNBlockQuery = await getConnection(Global.network)
2019-08-07 08:09:41 +00:00
.query(
2019-08-12 12:50:12 +00:00
"select 1 as hash, total_difficulty_cuckatoo,total_difficulty_progpow,total_difficulty_randomx, \
2019-08-07 08:09:41 +00:00
DATE_TRUNC('minute', timestamp at time zone '" +
process.env.TIME_ZONE +
"') as date \
from blockchain_block where " +
timeIntervalQry +
" order by height",
)
.catch(err_msg => {
next(err_msg);
});
}
2019-08-13 10:37:53 +00:00
// let date = [],
// DifficultyCuckatoo = [],
// DifficultyProgpow = [],
// DifficultyRandomx = [];
2019-08-06 13:10:10 +00:00
2019-08-13 10:37:53 +00:00
var DifficultyCuckatoo = TotalDifficultyNBlockQuery.map(function (e) {
return parseInt(e.total_difficulty_cuckatoo);
2019-07-31 14:13:06 +00:00
});
2019-08-13 10:37:53 +00:00
var DifficultyProgpow = TotalDifficultyNBlockQuery.map(function (e) {
return parseInt(e.total_difficulty_progpow);
});
var DifficultyRandomx = TotalDifficultyNBlockQuery.map(function (e) {
return parseInt(e.total_difficulty_randomx);
});
var date = TotalDifficultyNBlockQuery.map(function (e) {
return moment(e.date).format(dateFormat);
});
2019-08-19 08:03:05 +00:00
if(date.length == 0){
date = [moment(Date.now()).format(dateFormat)];
DifficultyCuckatoo = [0];
DifficultyProgpow = [0];
DifficultyRandomx = [0];
}
2019-08-13 10:37:53 +00:00
// TotalDifficultyNBlockQuery.forEach(e => {
// date.push(moment(e.date).format(dateFormat));
// DifficultyCuckatoo.push(parseInt(e.total_difficulty_cuckatoo));
// DifficultyProgpow.push(parseInt(e.total_difficulty_progpow));
// DifficultyRandomx.push(parseInt(e.total_difficulty_randomx));
// });
// var Maxrange;
// var Minrange;
// if(alog_type == "cuckatoo"){
// Maxrange = Math.max.apply(Math, DifficultyCuckatoo);
// Minrange = Math.min.apply(Math, DifficultyCuckatoo);
// if(Minrange != 0){
// Minrange = (Minrange - (Minrange * 0.2));
// }
// Maxrange = (Maxrange + (Maxrange * 0.2));
// }else if(alog_type == "progpow"){
// Maxrange = Math.max.apply(Math, DifficultyProgpow);
// Minrange = Math.min.apply(Math, DifficultyProgpow);
// if(Minrange != 0){
// Minrange = (Minrange - (Minrange * 0.2));
// }
// Maxrange = (Maxrange + (Maxrange * 0.2));
// }else if(alog_type == "randomx"){
// Maxrange = Math.max.apply(Math, DifficultyRandomx);
// Minrange = Math.min.apply(Math, DifficultyRandomx);
// if(Minrange != 0){
// Minrange = (Minrange - (Minrange * 0.2));
// }
// Maxrange = (Maxrange + (Maxrange * 0.2));
// }else{
// var Maxrange1 = Math.max.apply(Math, TotalDifficultyNBlockQuery.map(function(o) { return o.total_difficulty_cuckatoo; }));
// var Minrange1 = Math.min.apply(Math, TotalDifficultyNBlockQuery.map(function(o) { return o.total_difficulty_cuckatoo; }));
// var Maxrange2 = Math.max.apply(Math, TotalDifficultyNBlockQuery.map(function(o) { return o.total_difficulty_progpow; }));
// var Minrange2 = Math.min.apply(Math, TotalDifficultyNBlockQuery.map(function(o) { return o.total_difficulty_progpow; }));
// var Maxrange3 = Math.max.apply(Math, TotalDifficultyNBlockQuery.map(function(o) { return o.total_difficulty_randomx; }));
// var Minrange3 = Math.min.apply(Math, TotalDifficultyNBlockQuery.map(function(o) { return o.total_difficulty_randomx; }));
// Maxrange = Math.max(Maxrange1, Maxrange2, Maxrange3);
// Minrange = Math.min(Minrange1, Minrange2, Minrange3);
// if(Minrange != 0){
// Minrange = (Minrange - (Minrange * 0.2));
// }
// Maxrange = (Maxrange + (Maxrange * 0.2));
// }
2019-08-08 12:47:55 +00:00
2019-08-07 12:28:41 +00:00
// Minrange = parseInt(Minrange);
// var Minrange2 = parseInt(Minrange * 0.3);
2019-07-09 09:22:36 +00:00
response.status(200).json({
status: 200,
timestamp: Date.now(),
2019-08-07 08:14:06 +00:00
message: 'Difficulty and Blocks Data fetched Successfully',
2019-07-09 09:22:36 +00:00
response: {
Date: date,
2019-08-12 12:50:12 +00:00
DifficultyCuckatoo: DifficultyCuckatoo,
DifficultyRandomx: DifficultyRandomx,
DifficultyProgpow: DifficultyProgpow,
2019-08-13 10:37:53 +00:00
//Maxrange: Maxrange,
//Minrange: Minrange,
2019-08-08 06:36:56 +00:00
tickFormat: tickFormat
2019-07-09 09:22:36 +00:00
},
});
} catch (error) {
next(new InternalServerErrorException(error));
}
};
2019-07-29 10:59:06 +00:00
private StackBlock = async (
request: Request,
response: Response,
next: NextFunction,
) => {
try {
const TotalDifficultyNBlockRequestData: TotalDifficultyNBlockDto =
request.query;
if (TotalDifficultyNBlockRequestData.Interval) {
var timeIntervalQry =
"timestamp at time zone '" +
process.env.TIME_ZONE +
"' > current_date - interval '" +
TotalDifficultyNBlockRequestData.Interval +
"'";
} else if (
TotalDifficultyNBlockRequestData.FromDate ||
TotalDifficultyNBlockRequestData.ToDate
) {
let fromdate = moment(TotalDifficultyNBlockRequestData.FromDate)
.utc()
.format('YYYY-MM-DD');
let todate = moment(TotalDifficultyNBlockRequestData.ToDate)
.utc()
.format('YYYY-MM-DD');
var timeIntervalQry =
"timestamp at time zone '" +
process.env.TIME_ZONE +
"' BETWEEN SYMMETRIC '" +
fromdate +
"' AND '" +
todate +
"'";
} else {
var timeIntervalQry =
"timestamp at time zone '" +
process.env.TIME_ZONE +
"' > current_date - interval '30 days'";
}
2019-08-14 10:55:23 +00:00
const stackNBlockQuery = await getConnection(Global.network)
2019-07-29 10:59:06 +00:00
.query(
2019-07-30 07:13:24 +00:00
"select 1 as hash, date(DATE_TRUNC('day', timestamp at time zone '" +
2019-07-30 05:12:23 +00:00
process.env.TIME_ZONE +
"')) as date, Count( CASE WHEN proof = 'RandomX' THEN 1 ELSE NULL END) AS RandomX, \
2019-08-01 07:38:45 +00:00
Count( CASE WHEN proof = 'Cuckoo' THEN 1 ELSE NULL END) AS Cuckoo,\
2019-07-29 10:59:06 +00:00
Count( CASE WHEN proof = 'ProgPow' THEN 1 ELSE NULL END) AS ProgPow \
from blockchain_block where " +
2019-07-30 05:12:23 +00:00
timeIntervalQry +
"group by DATE_TRUNC('day', timestamp at time zone '" +
process.env.TIME_ZONE +
"') order by date",
2019-07-29 10:59:06 +00:00
)
.catch(err_msg => {
next(err_msg);
});
let date = [],
2019-07-30 07:13:24 +00:00
Blocks = [],
2019-08-01 07:38:45 +00:00
Cuckoo = [],
2019-07-30 07:13:24 +00:00
ProgPow = [],
RandomX = [];
2019-07-30 05:12:23 +00:00
stackNBlockQuery.forEach(e => {
2019-07-29 10:59:06 +00:00
date.push(moment(e.date).format('YYYY-MM-DD'));
2019-07-30 10:48:20 +00:00
// Blocks.push({Cuckaroo: parseInt(e.cuckaroo), Cuckatoo : parseInt(e.cuckatoo), ProgPow : parseInt(e.progpow), RandomX : parseInt(e.randomx)})
2019-08-01 07:38:45 +00:00
Cuckoo.push(parseInt(e.cuckoo));
2019-07-30 07:13:24 +00:00
ProgPow.push(parseInt(e.progpow));
RandomX.push(parseInt(e.randomx));
2019-07-09 09:22:36 +00:00
});
2019-08-19 08:03:05 +00:00
if(date.length == 0){
date = [moment(Date.now()).format('YYYY-MM-DD')];
Cuckoo = [0];
ProgPow = [0];
RandomX = [0];
}
2019-07-09 09:22:36 +00:00
response.status(200).json({
status: 200,
timestamp: Date.now(),
2019-07-30 10:48:20 +00:00
message: 'Stack Data fetched Successfully',
2019-07-09 09:22:36 +00:00
response: {
Date: date,
2019-08-01 07:38:45 +00:00
Cuckoo:Cuckoo,
2019-07-30 10:48:20 +00:00
ProgPow:ProgPow,
RandomX:RandomX
2019-07-09 09:22:36 +00:00
},
});
} catch (error) {
next(new InternalServerErrorException(error));
}
};
2019-07-30 07:43:44 +00:00
private BlockPieChart = async (
request: Request,
response: Response,
next: NextFunction,
) => {
try {
const TotalDifficultyNBlockRequestData: TotalDifficultyNBlockDto =
request.query;
if (TotalDifficultyNBlockRequestData.Interval) {
var timeIntervalQry =
"timestamp at time zone '" +
process.env.TIME_ZONE +
"' > current_date - interval '" +
TotalDifficultyNBlockRequestData.Interval +
"'";
} else if (
TotalDifficultyNBlockRequestData.FromDate ||
TotalDifficultyNBlockRequestData.ToDate
) {
let fromdate = moment(TotalDifficultyNBlockRequestData.FromDate)
.utc()
.format('YYYY-MM-DD');
let todate = moment(TotalDifficultyNBlockRequestData.ToDate)
.utc()
.format('YYYY-MM-DD');
var timeIntervalQry =
"timestamp at time zone '" +
process.env.TIME_ZONE +
"' BETWEEN SYMMETRIC '" +
fromdate +
"' AND '" +
todate +
"'";
} else {
var timeIntervalQry =
"timestamp at time zone '" +
process.env.TIME_ZONE +
"' > current_date - interval '30 days'";
}
2019-08-14 10:55:23 +00:00
const stackNBlockQuery = await getConnection(Global.network)
2019-07-30 07:43:44 +00:00
.query(
2019-08-01 07:38:45 +00:00
"SELECT hash,total_edge_bits, RandomX, Cuckoo, ProgPow, Round(RandomX * 100.0 / total_edge_bits,2) AS RandomXper, Round(Cuckoo * 100.0 / total_edge_bits,2) AS Cuckooper, Round(ProgPow * 100.0 / total_edge_bits,2) AS ProgPowper from (select 1 as hash, COUNT(edge_bits) AS total_edge_bits, \
2019-07-30 07:43:44 +00:00
Count( CASE WHEN proof = 'RandomX' THEN 1 ELSE NULL END) AS RandomX,\
2019-08-01 07:38:45 +00:00
Count( CASE WHEN proof = 'Cuckoo' THEN 1 ELSE NULL END) AS Cuckoo,\
2019-07-30 07:43:44 +00:00
Count( CASE WHEN proof = 'ProgPow' THEN 1 ELSE NULL END) AS ProgPow \
from blockchain_block where " +
timeIntervalQry +
")t"
)
.catch(err_msg => {
next(err_msg);
});
2019-07-30 10:48:20 +00:00
let label = [],
value = [];
stackNBlockQuery.forEach(e => {
2019-08-01 07:38:45 +00:00
label.push("Cuckoo","ProgPow","RandomX");
value.push(parseInt(e.cuckoo),parseInt(e.progpow),parseInt(e.randomx));
2019-07-30 10:48:20 +00:00
});
2019-07-30 07:43:44 +00:00
response.status(200).json({
status: 200,
timestamp: Date.now(),
message: 'Piechart for block is fetched Successfully',
response: {
2019-07-30 10:48:20 +00:00
label,
value
2019-07-30 07:43:44 +00:00
},
});
} catch (error) {
next(new InternalServerErrorException(error));
}
};
2019-07-09 09:22:36 +00:00
private HashRate = async (
request: Request,
response: Response,
next: NextFunction,
) => {
try {
const TotalDifficultyNBlockRequestData: TotalDifficultyNBlockDto =
request.query;
if (TotalDifficultyNBlockRequestData.Interval) {
var timeIntervalQry =
"timestamp > current_date - interval '" +
TotalDifficultyNBlockRequestData.Interval +
"'";
var seriesquery =
"now() - interval '" +
TotalDifficultyNBlockRequestData.Interval +
"', now()";
} else if (
TotalDifficultyNBlockRequestData.FromDate ||
TotalDifficultyNBlockRequestData.ToDate
) {
let fromdate = moment(TotalDifficultyNBlockRequestData.FromDate)
.utc()
.format('YYYY-MM-DD');
let todate = moment(TotalDifficultyNBlockRequestData.ToDate)
.utc()
.format('YYYY-MM-DD');
var timeIntervalQry =
'timestamp BETWEEN SYMMETRIC ' + fromdate + ' AND ' + todate;
var seriesquery = "'" + fromdate + "'::timestamp, '" + todate + "'";
} else {
var timeIntervalQry = "timestamp > current_date - interval '30 days'";
var seriesquery = "now() - interval '30 days', now()";
}
2019-08-14 10:55:23 +00:00
const HashRateQueryAR29 = await getConnection(Global.network)
2019-07-09 09:22:36 +00:00
.query(
'with hours as ( SELECT hour::date from generate_series(' +
2019-07-30 05:12:23 +00:00
seriesquery +
", '1 day') as hour),tblDifference AS(select ROW_NUMBER() OVER(ORDER BY DATE_TRUNC('day', timestamp)) AS RowNumber, max(total_difficulty) as total_difficulty, date(DATE_TRUNC('day', timestamp)) as date, count(hash) as blocks from blockchain_block where " +
timeIntervalQry +
" and edge_bits=29 group by DATE_TRUNC('day', timestamp) order by date) select coalesce(max(t1.total_difficulty), 0) as total_difficulty, coalesce(max(t1.difficulty), 0) as difficulty, hours.hour, coalesce(max(t1.blocks), 0) as blocks, coalesce(max(t1.hashrate), 0) as hashrate from hours left join(SELECT cur.total_difficulty, cur.total_difficulty - previous.total_difficulty as difficulty, cur.date, cur.blocks, ((cast(cur.blocks as decimal) / 1440) * (cur.total_difficulty - previous.total_difficulty) * (2^32 / 60)) as hashrate FROM tblDifference cur LEFT OUTER JOIN tblDifference previous ON cur.RowNumber = previous.RowNumber + 1) as t1 on t1.date = hours.hour group by hours.hour order by hours.hour",
2019-07-09 09:22:36 +00:00
)
.catch(err_msg => {
next(err_msg);
});
2019-08-14 10:55:23 +00:00
const HashRateQueryAT31 = await getConnection(Global.network)
2019-07-09 09:22:36 +00:00
.query(
'with hours as ( SELECT hour::date from generate_series(' +
2019-07-30 05:12:23 +00:00
seriesquery +
", '1 day') as hour),tblDifference AS(select ROW_NUMBER() OVER(ORDER BY DATE_TRUNC('day', timestamp)) AS RowNumber, max(total_difficulty) as total_difficulty, date(DATE_TRUNC('day', timestamp)) as date, count(hash) as blocks from blockchain_block where " +
timeIntervalQry +
" and edge_bits=31 group by DATE_TRUNC('day', timestamp) order by date) select coalesce(max(t1.total_difficulty), 0) as total_difficulty , coalesce(max(t1.difficulty), 0) as difficulty, hours.hour, coalesce(max(t1.blocks), 0) as blocks, coalesce(max(t1.hashrate), 0) as hashrate from hours left join(SELECT cur.total_difficulty, cur.total_difficulty - previous.total_difficulty as difficulty, cur.date, cur.blocks, ((cast(cur.blocks as decimal) / 1440) * (cur.total_difficulty - previous.total_difficulty) * (2^32 / 60)) as hashrate FROM tblDifference cur LEFT OUTER JOIN tblDifference previous ON cur.RowNumber = previous.RowNumber + 1) as t1 on t1.date = hours.hour group by hours.hour order by hours.hour",
2019-07-09 09:22:36 +00:00
)
.catch(err_msg => {
next(err_msg);
});
let date = [],
hashrate29 = [],
hashrate31 = [];
2019-07-30 05:12:23 +00:00
HashRateQueryAR29.forEach(function (e, index) {
2019-07-09 09:22:36 +00:00
if (index > 0) {
date.push(moment(e.hour).format('YYYY-MM-DD'));
hashrate29.push(
Math.round((parseInt(e.hashrate) / 1000000000) * 100) / 100,
);
}
});
2019-07-30 05:12:23 +00:00
HashRateQueryAT31.forEach(function (e, index) {
2019-07-09 09:22:36 +00:00
if (index > 0) {
hashrate31.push(
Math.round((parseInt(e.hashrate) / 1000000000) * 100) / 100,
);
}
});
response.status(200).json({
status: 200,
timestamp: Date.now(),
message: 'Total Difficulty and Blocks Data fetched Successfully',
response: {
date,
hashrate29,
hashrate31,
},
});
} catch (error) {
next(new InternalServerErrorException(error));
}
};
2019-09-04 09:17:26 +00:00
2019-07-09 09:22:36 +00:00
private LatestDifficultyNBlock = async (
request: Request,
response: Response,
next: NextFunction,
) => {
try {
2019-09-04 09:17:26 +00:00
let result = await latestBlockDetails()
2019-07-09 09:22:36 +00:00
response.status(200).json({
status: 200,
timestamp: Date.now(),
message: 'Latest Block Details fetched Successfully',
response: {
2019-09-04 09:17:26 +00:00
...result
2019-07-09 09:22:36 +00:00
},
});
} catch (error) {
next(new InternalServerErrorException(error));
}
};
private BlockchainBlockPerSecond = async (
request: Request,
response: Response,
next: NextFunction,
) => {
try {
const BlockchainBlockPerSecondData: TotalDifficultyNBlockDto =
request.query;
if (BlockchainBlockPerSecondData.Interval) {
var timeIntervalQry =
2019-09-09 09:38:36 +00:00
"timestamp > current_date - interval '" +
2019-07-09 09:22:36 +00:00
BlockchainBlockPerSecondData.Interval +
"'";
} else if (
BlockchainBlockPerSecondData.FromDate ||
BlockchainBlockPerSecondData.ToDate
) {
let fromdate = moment(BlockchainBlockPerSecondData.FromDate)
.utc()
.format('YYYY-MM-DD');
let todate = moment(BlockchainBlockPerSecondData.ToDate)
.utc()
.format('YYYY-MM-DD');
var timeIntervalQry =
'timestamp BETWEEN SYMMETRIC ' + fromdate + ' AND ' + todate;
} else {
2019-09-09 09:38:36 +00:00
var timeIntervalQry = "timestamp > current_date - interval '30 days'";
2019-07-09 09:22:36 +00:00
}
2019-08-14 10:55:23 +00:00
const BlockchainBlockPerSecondQuery = await getConnection(Global.network)
2019-07-09 09:22:36 +00:00
.query(
"select date(DATE_TRUNC('day', timestamp)) as date, count(hash) as blocks, 86400/count(hash) as period \
from blockchain_block where " +
2019-07-30 05:12:23 +00:00
timeIntervalQry +
2019-09-09 09:38:36 +00:00
"AND height != 0 AND timestamp < current_date group by DATE_TRUNC('day', timestamp) order by date",
2019-07-09 09:22:36 +00:00
)
.catch(err_msg => {
next(err_msg);
});
let date = [],
period = [];
BlockchainBlockPerSecondQuery.forEach(e => {
date.push(moment(e.date).format('YYYY-MM-DD'));
period.push(parseInt(e.period));
});
2019-08-19 08:03:05 +00:00
if(date.length == 0){
date = [moment(Date.now()).format('YYYY-MM-DD')];
period = [0];
}
2019-07-09 09:22:36 +00:00
response.status(200).json({
status: 200,
timestamp: Date.now(),
message: 'period of blocks generation per second fetched Successfully',
response: {
date,
period,
},
});
} catch (error) {
next(new InternalServerErrorException(error));
}
};
private SupplyGrowth = async (
request: Request,
response: Response,
next: NextFunction,
) => {
try {
const BlockchainBlockPerSecondData: TotalDifficultyNBlockDto =
request.query;
if (BlockchainBlockPerSecondData.Interval) {
var timeIntervalQry =
"timestamp > current_date - interval '" +
BlockchainBlockPerSecondData.Interval +
"'";
} else if (
BlockchainBlockPerSecondData.FromDate ||
BlockchainBlockPerSecondData.ToDate
) {
let fromdate = moment(BlockchainBlockPerSecondData.FromDate)
.utc()
.format('YYYY-MM-DD');
let todate = moment(BlockchainBlockPerSecondData.ToDate)
.utc()
.format('YYYY-MM-DD');
var timeIntervalQry =
'timestamp BETWEEN SYMMETRIC ' + fromdate + ' AND ' + todate;
} else {
var timeIntervalQry = "timestamp > current_date - interval '30 days'";
}
let DAY_HEIGHT = 1440
/// Height of the first epic block emission era
const BLOCK_ERA_1 = DAY_HEIGHT * 334;
/// Height of the second epic block emission era
const BLOCK_ERA_2 = BLOCK_ERA_1 + (DAY_HEIGHT * 470);
/// Height of the third epic block emission era
const BLOCK_ERA_3 = BLOCK_ERA_2 + (DAY_HEIGHT * 601);
/// Height of the fourth epic block emission era
const BLOCK_ERA_4 = BLOCK_ERA_3 + (DAY_HEIGHT * 800);
/// Height of the fifth epic block emission era
const BLOCK_ERA_5 = BLOCK_ERA_4 + (DAY_HEIGHT * 1019);
/// After the epic block emission era 6, each era will last 4 years (approximately 1460 days)
const BLOCK_ERA_6_ONWARDS = DAY_HEIGHT * 1460;
/// Block Reward that will be assigned after we change from era 5 to era 6.
const BASE_REWARD_ERA_6_ONWARDS = 0.15625;
2019-08-14 10:55:23 +00:00
const BlockchainBlockPerSecondQuery = await getConnection(Global.network)
2019-07-09 09:22:36 +00:00
.query(
2019-08-13 07:24:01 +00:00
'select x.timestamp, SUM(x.reward) as total_reward_per_day \
2019-08-13 07:50:34 +00:00
from (SELECT DISTINCT height, hash, CAST(timestamp AS DATE), \
2019-07-09 09:22:36 +00:00
CASE \
WHEN height <= '+BLOCK_ERA_1+' THEN 16 \
WHEN height <= '+BLOCK_ERA_2+' THEN 8 \
WHEN height <= '+BLOCK_ERA_3+' THEN 4 \
WHEN height <= '+BLOCK_ERA_4+' THEN 2 \
WHEN height <= '+BLOCK_ERA_5+' THEN 1 \
ELSE '+BASE_REWARD_ERA_6_ONWARDS+' / (1 << ((height - ('+BLOCK_ERA_5+'- 1))/'+BLOCK_ERA_6_ONWARDS+'))\
2019-07-09 09:22:36 +00:00
END AS reward \
FROM blockchain_block where height > 0 AND ' +
2019-07-30 05:12:23 +00:00
timeIntervalQry +
') as x group by x.timestamp Order by x.timestamp ASC',
2019-07-09 09:22:36 +00:00
)
.catch(err_msg => {
next(err_msg);
});
/// Compute the total reward generated by each block in a given height.
// if (BlockchainBlockFetchQuery.Height <= BLOCK_ERA_1) {
// BlockchainBlockFetchQuery['BlockReward'] = 16;
// } else if (BlockchainBlockFetchQuery.Height <= BLOCK_ERA_2) {
// BlockchainBlockFetchQuery['BlockReward'] = 8;
// } else if (BlockchainBlockFetchQuery.Height <= BLOCK_ERA_3) {
// BlockchainBlockFetchQuery['BlockReward'] = 4;
// } else if (BlockchainBlockFetchQuery.Height <= BLOCK_ERA_4) {
// BlockchainBlockFetchQuery['BlockReward'] = 2;
// } else if (BlockchainBlockFetchQuery.Height <= BLOCK_ERA_5) {
// BlockchainBlockFetchQuery['BlockReward'] = 1;
// } else {
// // After the era 6, we reduce the block rewards by half each 1460 days.
// // Minus 1 to include multiples in the same index
// // (i.e changes greater than to greater or equals to)
// let height_with_offset = BlockchainBlockFetchQuery.Height - (BLOCK_ERA_5 - 1);
// let exp = height_with_offset / BLOCK_ERA_6_ONWARDS;
// BlockchainBlockFetchQuery['BlockReward'] = BASE_REWARD_ERA_6_ONWARDS / (1 << exp);
// }
2019-07-09 09:22:36 +00:00
let date = [],
total_reward_per_day = [],
addedreward = [],
prev_value = 0;
BlockchainBlockPerSecondQuery.forEach(e => {
date.push(moment(e.timestamp).format('YYYY-MM-DD'));
total_reward_per_day.push(parseInt(e.total_reward_per_day));
addedreward.push(prev_value + parseInt(e.total_reward_per_day));
prev_value = prev_value + parseInt(e.total_reward_per_day);
});
2019-08-19 08:03:05 +00:00
if(date.length == 0){
date = [moment(Date.now()).format('YYYY-MM-DD')];
total_reward_per_day = [0];
addedreward = [0];
}
2019-07-09 09:22:36 +00:00
response.status(200).json({
status: 200,
timestamp: Date.now(),
message: 'period of blocks generation per second fetched Successfully',
response: {
date,
total_reward_per_day,
addedreward,
},
});
} catch (error) {
next(new InternalServerErrorException(error));
}
};
private BlockMineChart = async (
request: Request,
response: Response,
next: NextFunction,
) => {
try {
const BlockchainBlockPerSecondData: TotalDifficultyNBlockDto =
request.query;
if (BlockchainBlockPerSecondData.Interval) {
var timeIntervalQry =
"timestamp at time zone '" +
process.env.TIME_ZONE +
"' > current_date - interval '" +
BlockchainBlockPerSecondData.Interval +
"'";
} else if (
BlockchainBlockPerSecondData.FromDate ||
BlockchainBlockPerSecondData.ToDate
) {
let fromdate = moment(BlockchainBlockPerSecondData.FromDate)
.utc()
.format('YYYY-MM-DD');
let todate = moment(BlockchainBlockPerSecondData.ToDate)
.utc()
.format('YYYY-MM-DD');
var timeIntervalQry =
"timestamp at time zone '" +
process.env.TIME_ZONE +
"' BETWEEN SYMMETRIC '" +
fromdate +
"' AND '" +
todate +
"'";
} else {
var timeIntervalQry =
"timestamp at time zone '" +
process.env.TIME_ZONE +
"' > current_date - interval '30 days'";
}
2019-08-14 10:55:23 +00:00
const BlockMineChartQuery = await getConnection(Global.network)
2019-07-30 05:12:23 +00:00
.query(
2019-08-01 07:38:45 +00:00
"SELECT hash, date , total_edge_bits, RandomX, Cuckoo, ProgPow, Round(RandomX * 100.0 / total_edge_bits,2) AS RandomXper, Round(Cuckoo * 100.0 / total_edge_bits,2) AS Cuckooper, Round(ProgPow * 100.0 / total_edge_bits,2) AS ProgPowper \
2019-07-29 06:01:50 +00:00
FROM (SELECT 1 as hash, \
date(DATE_TRUNC('day', timestamp at time zone '" +
process.env.TIME_ZONE +
"')) as date, \
COUNT(edge_bits) AS total_edge_bits, \
Count( CASE WHEN proof = 'RandomX' THEN 1 ELSE NULL END) AS RandomX, \
2019-08-01 07:38:45 +00:00
Count( CASE WHEN proof = 'Cuckoo' THEN 1 ELSE NULL END) AS Cuckoo,\
2019-07-29 06:01:50 +00:00
Count( CASE WHEN proof = 'ProgPow' THEN 1 ELSE NULL END) AS ProgPow \
FROM blockchain_block \
where " +
timeIntervalQry +
"GROUP BY DATE_TRUNC('day', timestamp at time zone '" +
process.env.TIME_ZONE +
"')) t order by date",
2019-07-30 05:12:23 +00:00
)
.catch(err_msg => {
next(err_msg);
});
let date = [],
RandomXper = [],
2019-08-01 07:38:45 +00:00
Cuckooper = [],
2019-07-30 05:12:23 +00:00
ProgPowper = [],
RandomX = [],
2019-08-01 07:38:45 +00:00
Cuckoo = [],
2019-07-30 05:12:23 +00:00
ProgPow = [];
BlockMineChartQuery.forEach(e => {
date.push(moment(e.date).format('YYYY-MM-DD'));
RandomXper.push(parseFloat(e.randomxper));
2019-08-01 09:51:43 +00:00
Cuckooper.push(parseFloat(e.cuckooper));
2019-07-30 05:12:23 +00:00
ProgPowper.push(parseFloat(e.progpowper));
RandomX.push(parseInt(e.randomx));
2019-08-14 10:55:23 +00:00
Cuckoo.push(parseInt(e.cuckoo));
2019-07-30 05:12:23 +00:00
ProgPow.push(parseInt(e.progpow));
2019-07-09 09:22:36 +00:00
});
2019-07-30 05:12:23 +00:00
2019-08-19 08:03:05 +00:00
if(date.length == 0){
date = [moment(Date.now()).format('YYYY-MM-DD')];
RandomXper = [0];
Cuckooper = [0];
ProgPowper = [0];
RandomX = [0];
Cuckoo = [0];
ProgPow = [0];
}
2019-07-30 05:12:23 +00:00
response.status(200).json({
status: 200,
timestamp: Date.now(),
message: 'period of blocks generation per second fetched Successfully',
response: {
date,
RandomXper,
2019-08-01 07:38:45 +00:00
Cuckooper,
2019-07-30 05:12:23 +00:00
ProgPowper,
RandomX,
2019-08-01 07:38:45 +00:00
Cuckoo,
ProgPow
2019-07-30 05:12:23 +00:00
},
});
} catch (error) {
next(new InternalServerErrorException(error));
}
};
2019-07-09 09:22:36 +00:00
}