From c6660698893cdc8b17d977276ac420b0abd90e66 Mon Sep 17 00:00:00 2001 From: MiaoWoo Date: Wed, 24 Jul 2019 13:03:06 +0800 Subject: [PATCH] refactor: add more type define Signed-off-by: MiaoWoo --- public/index.js | 4 +- src/core/base.ts | 190 ++++++++++++++-------------- src/core/block-exchange.ts | 195 +++++++++++++++-------------- src/core/block-loader.ts | 160 ++++++++++++------------ src/core/code.ts | 28 ++--- src/core/connect.ts | 194 ++++++++++++++--------------- src/core/constant.ts | 4 +- src/core/db/block-db.ts | 114 ++++++++--------- src/core/library.ts | 6 + src/core/node.ts | 194 +++++++++++++++-------------- src/core/rest-loader.ts | 71 +++-------- src/core/server.ts | 107 ++++++++-------- src/core/terahashmining.ts | 11 +- src/core/transaction-validator.ts | 45 +++---- src/core/transfer-msg.ts | 40 +++--- src/global.d.ts | 9 +- src/interfaces/server.ts | 198 ++++++++++++++++++++++++++++++ src/process/main-process.ts | 8 +- 18 files changed, 896 insertions(+), 682 deletions(-) create mode 100644 src/interfaces/server.ts diff --git a/public/index.js b/public/index.js index dd6414b..18ae74d 100644 --- a/public/index.js +++ b/public/index.js @@ -42,11 +42,11 @@ function newcon(address) { } socket = io(address, { path: '/ws', - transports: ['websocket'] + transports: ['websocket'], + autoConnect: false, }); socket.on('connect', function() { term.writeln('connect') - socket.emit('webclient', {}) }); socket.on('message', function(data) { if (typeof data === "string") { diff --git a/src/core/base.ts b/src/core/base.ts index 819b50b..daca104 100644 --- a/src/core/base.ts +++ b/src/core/base.ts @@ -15,43 +15,46 @@ import "./terahashmining" import { RBTree } from './library' import * as crypto from 'crypto'; import * as os from 'os' +import CNode from "./node"; +import { Comparator } from "bintrees"; +import { SocketSendInfo } from "../interfaces/server"; global.glStopNode = false; const MAX_TIME_NETWORK_TRANSPORT = 1 * 1000; -var GlSumUser; -var GlSumSys; -var GlSumIdle; +var GlSumUser: number; +var GlSumSys: number; +var GlSumIdle: number; global.CountAllNode = 0; export default class CCommon { - VirtualMode - KeyPair - PubKeyType - addrArr - addrStr - HashDBArr - ServerSign - MetaMap1 - MetaMap2 - CheckName - NodesArr - CurrentBlockNum - BlockNumDB - constructor(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) { + VirtualMode: any + KeyPair: crypto.ECDH + PubKeyType: string + addrArr: string[] + addrStr: string + HashDBArr: any + ServerSign: any[] | Buffer + MetaMap1: any + MetaMap2: any + CheckName: any + NodesArr: any[] + CurrentBlockNum: number + BlockNumDB: number + constructor(SetKeyPair: crypto.ECDH, RunIP: string, RunPort: number, UseRNDHeader: boolean, bVirtual: boolean) { global.SERVER = this this.VirtualMode = bVirtual this.KeyPair = SetKeyPair - var PubKey = SetKeyPair.getPublicKey('', 'compressed'); + var PubKey: string[] = SetKeyPair.getPublicKey(undefined, 'compressed') as any; this.PubKeyType = PubKey[0] this.addrArr = PubKey.slice(1) this.addrStr = global.GetHexFromArr(this.addrArr) this.HashDBArr = global.shaarr2(this.KeyPair.getPrivateKey(), [0, 0, 0, 0, 0, 0, 0, 1]) this.ServerSign = [] } - SendF(Node, Info, Length?) { + SendF(Node: CNode, Info: SocketSendInfo, Length?: number) { throw new Error('Unsupport Action...') // defiend in server.ts } - AddCheckErrCount(Node, Count, StrErr) { + AddCheckErrCount(Node: CNode, Count: number, StrErr: string) { throw new Error('Unsupport Action...') // defiend in server.ts } @@ -59,7 +62,7 @@ export default class CCommon { throw new Error('Unsupport Action...') // defiend in server.ts } - ReadBlockHeaderDB(BlockNum): any { + ReadBlockHeaderDB(BlockNum: number): any { throw new Error('Unsupport Action...') // defiend in block-db.ts(CDB) } @@ -219,79 +222,79 @@ export default class CCommon { return crypto.randomBytes(32); } }; -class SMemBuffer { - MetaMap1 - MetaMap2 - CheckName - constructor(MaxTime, CheckName) { - this.MetaMap1 = {} - this.MetaMap2 = {} - this.CheckName = CheckName - setInterval(this.ShiftMapDirect.bind(this), MaxTime) - } - GetStrKey(Arr) { - if (typeof Arr === "number" || typeof Arr === "string") { - return Arr; - } else { - return global.GetHexFromAddres(Arr); - } - throw "NOT RET!"; - } - LoadValue(Arr, bStay) { - if (!Arr) - return undefined; - var Key = this.GetStrKey(Arr); - var Value = this.MetaMap1[Key]; - if (Value !== undefined) { - if (!bStay) - delete this.MetaMap1[Key] - return Value; - } - Value = this.MetaMap2[Key] - if (Value !== undefined) { - if (!bStay) - delete this.MetaMap2[Key] - } - return Value; - } - SaveValue(Arr, Value) { - var Key = this.GetStrKey(Arr); - if (Value !== undefined) - this.MetaMap1[Key] = Value - } - ShiftMapDirect() { - if (global.glStopNode) - return; - if (this.CheckName) { - var Count = 0; - for (var _ in this.MetaMap2) { - Count++ - } - if (Count) { - global.ADD_TO_STAT(this.CheckName, 1, 1) - } - } - this.MetaMap2 = this.MetaMap1 - this.MetaMap1 = {} - } - Clear() { - this.MetaMap2 = {} - this.MetaMap1 = {} - } -}; +// class SMemBuffer { +// MetaMap1: { [x: string]: any; } +// MetaMap2: { [x: string]: any; } +// CheckName: any +// constructor(MaxTime: number, CheckName: any) { +// this.MetaMap1 = {} +// this.MetaMap2 = {} +// this.CheckName = CheckName +// setInterval(this.ShiftMapDirect.bind(this), MaxTime) +// } +// GetStrKey(Arr: any) { +// if (typeof Arr === "number" || typeof Arr === "string") { +// return Arr; +// } else { +// return global.GetHexFromAddres(Arr); +// } +// throw "NOT RET!"; +// } +// LoadValue(Arr: any, bStay: any) { +// if (!Arr) +// return undefined; +// var Key = this.GetStrKey(Arr); +// var Value = this.MetaMap1[Key]; +// if (Value !== undefined) { +// if (!bStay) +// delete this.MetaMap1[Key] +// return Value; +// } +// Value = this.MetaMap2[Key] +// if (Value !== undefined) { +// if (!bStay) +// delete this.MetaMap2[Key] +// } +// return Value; +// } +// SaveValue(Arr, Value) { +// var Key = this.GetStrKey(Arr); +// if (Value !== undefined) +// this.MetaMap1[Key] = Value +// } +// ShiftMapDirect() { +// if (global.glStopNode) +// return; +// if (this.CheckName) { +// var Count = 0; +// for (var _ in this.MetaMap2) { +// Count++ +// } +// if (Count) { +// global.ADD_TO_STAT(this.CheckName, 1, 1) +// } +// } +// this.MetaMap2 = this.MetaMap1 +// this.MetaMap1 = {} +// } +// Clear() { +// this.MetaMap2 = {} +// this.MetaMap1 = {} +// } +// }; export class STreeBuffer { - KeyType - MetaTree1 - MetaTree2 - CheckName - constructor(MaxTime, CompareFunction?, KeyType?, CheckName?) { + KeyType: string + MetaTree1: RBTree + MetaTree2: RBTree + CheckName: string + constructor(MaxTime: number, CompareFunction?: Comparator, KeyType?: string, CheckName?: undefined) { this.KeyType = KeyType this.MetaTree1 = new RBTree(CompareFunction) this.MetaTree2 = new RBTree(CompareFunction) this.CheckName = CheckName setInterval(this.ShiftMapDirect.bind(this), MaxTime) } - LoadValue(Hash, bStay) { + LoadValue(Hash: string, bStay: number) { if (!Hash) return undefined; if (typeof Hash !== this.KeyType) @@ -310,7 +313,7 @@ export class STreeBuffer { } return undefined; } - SaveValue(Hash, Value) { + SaveValue(Hash: string, Value: { BlockNum: any; Power?: any; SumHash?: any; }) { if (typeof Hash !== this.KeyType) throw "MUST ONLY TYPE=" + this.KeyType + " in " + Hash; if (Value !== undefined) { @@ -341,7 +344,7 @@ export class STreeBuffer { } }; -function ReadHashFromBufDB(Map, BlockNum) { +function ReadHashFromBufDB(Map: { [x: string]: any; }, BlockNum: number) { var MyHash = Map[BlockNum]; if (!MyHash) { var Block = global.SERVER.ReadBlockHeaderDB(BlockNum); @@ -354,7 +357,7 @@ function ReadHashFromBufDB(Map, BlockNum) { return MyHash; }; -function GetCheckAccHash(Map, BlockNum, Hash) { +function GetCheckAccHash(Map: { [x: string]: any; }, BlockNum: number, Hash: Buffer) { var MyHash = Map[BlockNum]; if (!MyHash) { MyHash = global.DApps.Accounts.GetHashOrUndefined(BlockNum); @@ -367,8 +370,7 @@ function GetCheckAccHash(Map, BlockNum, Hash) { return "=ERR:BAD="; else return "=OK="; - } - else { + } else { if (!Hash) return "=OK=:NO"; else @@ -406,13 +408,13 @@ function TestCreateTr() { return { time1: deltaTime, time2: DeltaData }; }; -function CreateHashBody(body, Num, Nonce) { +function CreateHashBody(body: Buffer, Num: number, Nonce: number) { body.writeUIntLE(Num, body.length - 12, 6); body.writeUIntLE(Nonce, body.length - 6, 6); return global.shaarr(body); }; -function CreateHashBodyPOWInnerMinPower(arr, BlockNum, MinPow) { +function CreateHashBodyPOWInnerMinPower(arr: Buffer, BlockNum: number, MinPow: number) { var nonce = 0; while (1) { var arrhash = CreateHashBody(arr, BlockNum, nonce); diff --git a/src/core/block-exchange.ts b/src/core/block-exchange.ts index dfc7b3f..69eb84b 100644 --- a/src/core/block-exchange.ts +++ b/src/core/block-exchange.ts @@ -13,8 +13,10 @@ import CBlock from './block-loader' import { RBTree } from './library' import { STreeBuffer } from './base'; import { teraManager } from '../rpc/manager' -require('./library'); -require('./crypto-library'); +import * as crypto from 'crypto'; +import './crypto-library' +import { TeraBlock, SocketSendInfo, TeraJobTx, TeraTr, TeraPOW } from '../interfaces/server'; +import CNode from './node'; const TX_PROCESS_TIME = 100; const TX_DELTA_PROCESS_TIME = 300; global.CAN_START = false; @@ -43,14 +45,14 @@ var FORMAT_DATA_TRANSFER = "{\ }"; const WorkStructSend = {}; export default class CConsensus extends CBlock { - CurrentBlockNum - SendBlockID - RelayMode - TreeSendPacket - idBlockChainTimer - OwnBlockCount - LevelNodes - constructor(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) { + CurrentBlockNum: number + SendBlockID: number + RelayMode: boolean + TreeSendPacket: RBTree + idBlockChainTimer: NodeJS.Timeout + OwnBlockCount: number + LevelNodes: any[] + constructor(SetKeyPair: crypto.ECDH, RunIP: string, RunPort: number, UseRNDHeader: boolean, bVirtual: boolean) { super(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) this.CurrentBlockNum = 0 this.SendBlockID = 0 @@ -70,7 +72,7 @@ export default class CConsensus extends CBlock { var self = this; if (self.idBlockChainTimer) clearInterval(self.idBlockChainTimer) - self.idBlockChainTimer = 0 + self.idBlockChainTimer = undefined setTimeout(function() { self.idBlockChainTimer = setInterval(self.StartBlockChain.bind(self), global.CONSENSUS_PERIOD_TIME) self.OnStartSecond() @@ -144,7 +146,7 @@ export default class CConsensus extends CBlock { global.AddInfoBlock(Block0, "Was Active") } } - TrToInfo(Block, Array, StrInfo) { + TrToInfo(Block: TeraBlock, Array: any[], StrInfo: string) { var Str = ""; for (var i = 0; i < Array.length; i++) { var Item = Array[i]; @@ -153,7 +155,7 @@ export default class CConsensus extends CBlock { } global.AddInfoBlock(Block, "" + StrInfo + ": Arr=[" + Str + "]") } - TRANSFER(Info, CurTime) { + TRANSFER(Info: SocketSendInfo, CurTime: number) { var startTime = process.hrtime(); var Data = this.DataFromF(Info); var Node = Info.Node; @@ -186,7 +188,7 @@ export default class CConsensus extends CBlock { var WasNewAdd = 0; if (Data.TxArray.length) { for (var i = 0; i < Data.TxArray.length; i++) { - var Tr = Data.TxArray[i]; + let Tr = Data.TxArray[i]; var Res = this.AddTrToBlockQuote(Block, Tr); if (Res === 1) { WasNewAdd = 1 @@ -204,7 +206,7 @@ export default class CConsensus extends CBlock { } else { for (var i = 0; i < Data.TicketArray.length; i++) { - var Tr = this.AddTicketToBlockQuote(Block, Data.TicketArray[i]); + let Tr = this.AddTicketToBlockQuote(Block, Data.TicketArray[i]); if (Tr) { if (!Tr.NodesList) Tr.NodesList = [] @@ -290,7 +292,7 @@ export default class CConsensus extends CBlock { } } } - CheckEndExchange(Block) { + CheckEndExchange(Block: TeraBlock) { if (Block.EndExchange) return; if (!global.USE_TICKET) { @@ -307,7 +309,7 @@ export default class CConsensus extends CBlock { this.CreateTreeHash(Block) } } - SendDataTransfer(Transfer, ArrT, MaxPOWList, MaxSumList, Block) { + SendDataTransfer(Transfer: TeraJobTx, ArrT: any, MaxPOWList: any[], MaxSumList: any[], Block: TeraBlock) { for (var Addr in Transfer.TransferNodes) { var Item = Transfer.TransferNodes[Addr]; Transfer.SendCount++ @@ -354,10 +356,10 @@ export default class CConsensus extends CBlock { Block.JobListTX.push({ Node: Item.Node, TreeLevel: Item.TreeLevel, Time: Date.now() }) } } - Send(Node, Info, TypeData?) { + Send(Node: CNode, Info: SocketSendInfo, TypeData?: number) { // defiend in server.ts } - TRANSFERTX(Info, CurTime) { + TRANSFERTX(Info: SocketSendInfo, CurTime: number) { var Data = this.DataFromF(Info); var Node = Info.Node; var Block = this.GetBlockContext(Data.BlockNum); @@ -376,7 +378,7 @@ export default class CConsensus extends CBlock { static GETTRANSFERTX_F() { return "{BlockNum:uint, TicketArray:[{HashTicket:arr10}]}"; } - GETTRANSFERTX(Info, CurTime) { + GETTRANSFERTX(Info: SocketSendInfo, CurTime: number) { return; var Data = this.DataFromF(Info); var Node = Info.Node; @@ -389,7 +391,7 @@ export default class CConsensus extends CBlock { CanSendTest() { return 1; } - SendTrByTickets(Info, Node, Block, ArrTT, CountTrySend) { + SendTrByTickets(Info: SocketSendInfo, Node: CNode, Block: TeraBlock, ArrTT: any[], CountTrySend: number) { if (!Block.PowTxTree) return; var Arr = []; @@ -427,31 +429,31 @@ export default class CConsensus extends CBlock { static RETTRANSFERTX_F() { return "{BlockNum:uint,Array:[{body:tr}]}"; } - RETTRANSFERTX(Info, CurTime) { + RETTRANSFERTX(Info: SocketSendInfo, CurTime: number) { return; - var Data = this.DataFromF(Info); - var Node = Info.Node; - Node.TransferBlockNum = Data.BlockNum - var Block = this.GetBlockContext(Data.BlockNum); - if (!Block || !Block.PowTxTree) { - return; - } - if (global.DoTxLog) - global.ToLog("RETTRANSFERTX BlockNum:" + Block.BlockNum + " Array=" + Data.Array.length + " from " + global.NodeName(Node)) - for (var i = 0; i < Data.Array.length; i++) { - var Tr = Data.Array[i]; - this.CheckCreateTransactionObject(Tr) - var Tr0 = Block.PowTxTree.find(Tr); - if (Tr0) { - if (!Tr0.IsTx) { - Tr0.IsTx = 1 - Tr0.body = Tr.body - Tr0.HASH = Tr.HASH - } - } - } + // var Data = this.DataFromF(Info); + // var Node = Info.Node; + // Node.TransferBlockNum = Data.BlockNum + // var Block = this.GetBlockContext(Data.BlockNum); + // if (!Block || !Block.PowTxTree) { + // return; + // } + // if (global.DoTxLog) + // global.ToLog("RETTRANSFERTX BlockNum:" + Block.BlockNum + " Array=" + Data.Array.length + " from " + global.NodeName(Node)) + // for (var i = 0; i < Data.Array.length; i++) { + // var Tr = Data.Array[i]; + // this.CheckCreateTransactionObject(Tr) + // var Tr0 = Block.PowTxTree.find(Tr); + // if (Tr0) { + // if (!Tr0.IsTx) { + // Tr0.IsTx = 1 + // Tr0.body = Tr.body + // Tr0.HASH = Tr.HASH + // } + // } + // } } - DoJobListTX(Block) { + DoJobListTX(Block: TeraBlock) { if (Block.EndExchange || !Block.JobListTX || !Block.PowTicketTree) return; var ArrTx; @@ -460,7 +462,7 @@ export default class CConsensus extends CBlock { var JobItem = Block.JobListTX[i]; var Delta = CurTime - JobItem.Time; if (!JobItem.WasSend && Delta >= TX_DELTA_PROCESS_TIME) { - JobItem.WasSend = 1 + JobItem.WasSend = true if (!ArrTx) ArrTx = this.GetArrayFromTxTree(Block) var Arr = this.FilterArrForSendNode(Block, JobItem.Node, ArrTx); @@ -473,7 +475,7 @@ export default class CConsensus extends CBlock { } } } - FindNodeTicket(Block, Tr, Node, bTt) { + FindNodeTicket(Block: TeraBlock, Tr: TeraTr, Node: CNode, bTt: any) { var Ticket; if (bTt) Ticket = Tr @@ -489,7 +491,7 @@ export default class CConsensus extends CBlock { } return 0; } - FilterArrForSendNode(Block, Node, ArrTx, bTt?) { + FilterArrForSendNode(Block: TeraBlock, Node: CNode, ArrTx: any[], bTt?: number) { var Arr = []; for (var t = 0; t < ArrTx.length; t++) { var Tr = ArrTx[t]; @@ -499,7 +501,7 @@ export default class CConsensus extends CBlock { } return Arr; } - CheckEndExchange00(Block) { + CheckEndExchange00(Block: TeraBlock) { if (Block.EndExchange) return; var CurTime = Date.now(); @@ -530,7 +532,7 @@ export default class CConsensus extends CBlock { this.CheckTxExchange(Block, bSend) } } - CheckTxExchange(Block, b?) { + CheckTxExchange(Block: TeraBlock, b?: number) { return; if (Block.EndExchange) return; @@ -578,10 +580,10 @@ export default class CConsensus extends CBlock { this.SendF(ElArr.Node, SendData, ElArr.Arr.length * global.TR_TICKET_HASH_LENGTH + 1000) } } - GetMaxSumListFromID(Node, MaxSumID, BlockList) { + GetMaxSumListFromID(Node: CNode, MaxSumID: any[], BlockList: any[]) { var Str0 = "GETBL:" + Node.id; for (var i = 0; i < BlockList.length; i++) { - var elemBlockList = BlockList[i]; + let elemBlockList = BlockList[i]; global.TreeBlockBuf.SaveValue(Str0 + elemBlockList.ID, elemBlockList) } var MaxSum = []; @@ -601,7 +603,7 @@ export default class CConsensus extends CBlock { } return MaxSum; } - CreateTransferBuffer(ArrT, MaxPOWList, MaxSumList, Block, Node) { + CreateTransferBuffer(ArrT: any, MaxPOWList: TeraPOW[], MaxSumList: TeraPOW[], Block: TeraBlock, Node: CNode) { var Data; var MaxSumID = []; var BlockList = []; @@ -633,8 +635,17 @@ export default class CConsensus extends CBlock { ArrTx = ArrT } Data = { - "Version": 5, "BlockNum": Block.BlockNum, "Reserv1": 0, "MaxPOW": MaxPOWList, "Reserv2": 0, "BaseBlockNum": this.CurrentBlockNum - Block.BlockNum, - "MaxSumID": MaxSumID, "BlockList": BlockList, "TicketArray": ArrTt, "TxArray": ArrTx, "NoSendTx": Node.NoSendTx, + "Version": 5, + "BlockNum": Block.BlockNum, + "Reserv1": 0, + "MaxPOW": MaxPOWList, + "Reserv2": 0, + "BaseBlockNum": this.CurrentBlockNum - Block.BlockNum, + "MaxSumID": MaxSumID, + "BlockList": BlockList, + "TicketArray": ArrTt, + "TxArray": ArrTx, + "NoSendTx": Node.NoSendTx, } var BufWrite = global.BufLib.GetBufferFromObject(Data, FORMAT_DATA_TRANSFER, global.MAX_BLOCK_SIZE + 30000, WorkStructSend); return BufWrite; @@ -642,7 +653,7 @@ export default class CConsensus extends CBlock { static TRANSFER_F() { return FORMAT_DATA_TRANSFER; } - CheckingMaxPowOther(Block) { + CheckingMaxPowOther(Block: TeraBlock) { var POW = Block.MaxPOW; if (POW && POW.Hash && global.CompareArr(POW.PowHash, Block.PowHash) < 0) { var LoadBlockNum = Block.BlockNum; @@ -654,7 +665,7 @@ export default class CConsensus extends CBlock { } Block.CheckMaxPow = true } - AddToMaxPOW(Block, item, Node?) { + AddToMaxPOW(Block: TeraBlock, item: TeraPOW, Node?: CNode) { if (Block && item) { if (!Block.MaxPOW) Block.MaxPOW = {} @@ -692,7 +703,7 @@ export default class CConsensus extends CBlock { } } } - AddPOWToMaxTree(POW, item) { + AddPOWToMaxTree(POW: TeraPOW, item: TeraPOW) { if (!POW.MaxTree) { POW.MaxTree = new RBTree(function(a: any, b: any) { return global.CompareArr(a.PowHash, b.PowHash); @@ -725,7 +736,7 @@ export default class CConsensus extends CBlock { } return arr; } - ToMaxPOWList(Arr) { + ToMaxPOWList(Arr: any[]) { for (var i = 0; i < Arr.length; i++) { var item = Arr[i]; if (item && item.BlockNum >= this.CurrentBlockNum - global.BLOCK_PROCESSING_LENGTH && item.BlockNum < this.CurrentBlockNum) { @@ -734,7 +745,7 @@ export default class CConsensus extends CBlock { } } } - RecreateMaxPOW(Block) { + RecreateMaxPOW(Block: TeraBlock) { if (Block.MaxPOW && Block.MaxPOW.MaxTree) { var Tree = Block.MaxPOW.MaxTree; var it = Tree.iterator(), Item; @@ -749,7 +760,7 @@ export default class CConsensus extends CBlock { } Block.CheckMaxSum = false } - CheckMaxSum(Block) { + CheckMaxSum(Block: TeraBlock) { var POW = Block.MaxSum; var List = this.GetBlockList(Block.BlockNum); var SumPow = this.GetSumFromList(List, Block.BlockNum); @@ -762,7 +773,7 @@ export default class CConsensus extends CBlock { } Block.CheckMaxSum = true } - AddToMaxSum(Block, item) { + AddToMaxSum(Block: TeraBlock, item: TeraPOW) { if (Block && item) { if (!Block.MaxSum) Block.MaxSum = {} @@ -809,7 +820,7 @@ export default class CConsensus extends CBlock { } } } - GetBlockList(CurBlockNum) { + GetBlockList(CurBlockNum: number) { var arr = []; for (var b = CurBlockNum - global.SUM_LIST_LENGTH + 1; b <= CurBlockNum; b++) { var Block = this.GetBlock(b); @@ -823,7 +834,7 @@ export default class CConsensus extends CBlock { } return arr; } - GetSumFromList(arr, CurBlockNum) { + GetSumFromList(arr: TeraBlock[], CurBlockNum: number) { var SumPow = 0; if (arr.length !== global.SUM_LIST_LENGTH) return SumPow; @@ -835,15 +846,14 @@ export default class CConsensus extends CBlock { Item.BlockNum = BlockNumStart + i var Value = global.GetHashFromSeqAddr(Item.SeqHash, Item.AddrHash, Item.BlockNum, undefined, global.MINING_VERSION_NUM); SumPow += global.GetPowPower(Value.PowHash) - Item.Hash3 = Value.Hash - } - else { + Item.Hash = Value.Hash + } else { break; } } return SumPow; } - GetArrayFromTxTree(Block) { + GetArrayFromTxTree(Block: TeraBlock) { if (!Block.PowTxTree) return []; var BufLength = 0; @@ -857,7 +867,7 @@ export default class CConsensus extends CBlock { } return arr; } - GetArrayFromTicketTree(Block) { + GetArrayFromTicketTree(Block: TeraBlock) { if (!Block.PowTicketTree) return []; var arr = []; @@ -867,7 +877,7 @@ export default class CConsensus extends CBlock { } return arr; } - CheckPrioritetTx(Tr) { + CheckPrioritetTx(Tr: TeraTr) { if (Tr.Prioritet === undefined) { var Body = Tr.body; Tr.Prioritet = global.MAX_LENGTH_SENDER_MAP @@ -881,10 +891,11 @@ export default class CConsensus extends CBlock { } } } - GetSenderPrioritet(BlockNum, SenderNum) { + GetSenderPrioritet(BlockNum: number, SenderNum: number): number { + return 0; //defiend in transaction-validator.ts(CSmartContract) } - AddToQuote(Tree, Tr) { + AddToQuote(Tree: RBTree, Tr: TeraTr) { this.CheckPrioritetTx(Tr) var Tr0 = Tree.find(Tr); if (Tr0) { @@ -901,16 +912,16 @@ export default class CConsensus extends CBlock { return 1; } } - IsValidTicket(Tr, BlockNum): any { + IsValidTicket(Tr: TeraTr, BlockNum: number): any { // defiend in transaction-validator.ts(CSmartContract) } - IsValidTransaction(Tr, BlockNum): any { + IsValidTransaction(Tr: TeraTr, BlockNum: number): any { // defiend in transaction-validator.ts(CSmartContract) } - AddDAppTransactions(BlockNum, Arr) { + AddDAppTransactions(BlockNum: number, Arr: TeraTr[]) { // defiend in transaction-validator.ts(CSmartContract) } - AddTicketToBlockQuote(Block, Tr) { + AddTicketToBlockQuote(Block: TeraBlock, Tr: TeraTr) { if (Block.PowTicketTree) { var Res = this.IsValidTicket(Tr, Block.BlockNum); if (Res >= 1) { @@ -921,7 +932,7 @@ export default class CConsensus extends CBlock { return null; } } - AddTrToBlockQuote(Block, Tr, bTTAdd?) { + AddTrToBlockQuote(Block: TeraBlock, Tr: TeraTr, bTTAdd?) { if (Block.PowTxTree) { var Res = this.IsValidTransaction(Tr, Block.BlockNum); if (Res >= 1) { @@ -935,7 +946,7 @@ export default class CConsensus extends CBlock { return Res; } } - GetBlockContext(BlockNum) { + GetBlockContext(BlockNum: number) { if (BlockNum === undefined || !this.IsCorrectBlockNum(BlockNum)) return undefined; var Context = this.GetBlock(BlockNum); @@ -952,10 +963,10 @@ export default class CConsensus extends CBlock { } return Context; } - StartBlock(Block) { + StartBlock(Block: TeraBlock) { Block.Active = true } - IsCorrectBlockNum(BlockNum) { + IsCorrectBlockNum(BlockNum: number) { var start = this.CurrentBlockNum - global.BLOCK_PROCESSING_LENGTH; var finish = this.GetLastCorrectBlockNum(); if (BlockNum < start || BlockNum > finish) { @@ -966,7 +977,7 @@ export default class CConsensus extends CBlock { GetLastCorrectBlockNum() { return this.CurrentBlockNum + 4; } - GetStrSendCount(Block) { + GetStrSendCount(Block: TeraBlock) { if (!Block) return ""; var Str = ""; @@ -979,7 +990,7 @@ export default class CConsensus extends CBlock { } return "" + Count + ":[" + Str.substr(1) + "]"; } - GetStrGetCount(Block) { + GetStrGetCount(Block: TeraBlock) { if (!Block) return ""; var Str = ""; @@ -991,7 +1002,7 @@ export default class CConsensus extends CBlock { } return "" + Count + ":[" + Str.substr(1) + "]"; } - ToStrBlocks(DopStr) { + ToStrBlocks(DopStr: string) { var num = Math.floor(this.CurrentBlockNum / 3) * 3; var start = num - global.BLOCK_PROCESSING_LENGTH2 + 2; var finish = this.CurrentBlockNum; @@ -1017,9 +1028,9 @@ export default class CConsensus extends CBlock { Str = Str.substr(1) global.ToInfo("" + finish + " -> " + Str + " " + DopStr) } - PreparePOWHash(Block) { + PreparePOWHash(Block: TeraBlock) { if (!Block.TreeHash) - Block.TreeHash = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + Block.TreeHash = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) var PrevHash = this.GetPrevHash(Block); if (!PrevHash) { global.AddInfoBlock(Block, "-err prev hash-") @@ -1036,7 +1047,7 @@ export default class CConsensus extends CBlock { } return true; } - CalcTreeHashFromArrTr(BlockNum, arrTr) { + CalcTreeHashFromArrTr(BlockNum: number, arrTr: TeraTr[]) { var arrHASH = []; for (var i = 0; i < arrTr.length; i++) { var Tr = arrTr[i]; @@ -1045,7 +1056,7 @@ export default class CConsensus extends CBlock { var Tree = global.CalcMerklFromArray(BlockNum, arrHASH); return Tree.Root; } - CreateTreeHash(Block) { + CreateTreeHash(Block: TeraBlock) { if (Block.EndExchange) return; Block.EndExchange = true @@ -1071,7 +1082,7 @@ export default class CConsensus extends CBlock { Block.arrContent = arrContent Block.TrCount = Block.arrContent.length } - WatchdogSaved(BlockNum) { + WatchdogSaved(BlockNum: number) { var Block = this.GetBlock(BlockNum); if (!Block) { global.ToLog("#1 WatchdogSaved: no BlockNum=" + BlockNum) @@ -1128,7 +1139,7 @@ export default class CConsensus extends CBlock { var CURRENTBLOCKNUM = this.CurrentBlockNum; if (global.GrayConnect()) { if (!this.LoadHistoryMode) - this.StartSyncBlockchain(undefined, 1) + this.StartSyncBlockchain(undefined, true) return; } if (this.LoadHistoryMode) @@ -1307,7 +1318,7 @@ export default class CConsensus extends CBlock { this.RelayMode = !bWasSave this.FREE_MEM_BLOCKS(CURRENTBLOCKNUM - global.BLOCK_COUNT_IN_MEMORY) } - GetAvgPowBlock(StartNum, CountNum) { + GetAvgPowBlock(StartNum: number, CountNum: number) { var Count = 0; var SumPow = 0; for (var Num = StartNum; Num < StartNum + CountNum; Num++) { @@ -1323,13 +1334,13 @@ export default class CConsensus extends CBlock { else return SumPow / Count; } - CreatePOWNew(Block) { + CreatePOWNew(Block: TeraBlock) { global.CreateHashMinimal(Block, global.GENERATE_BLOCK_ACCOUNT) this.AddToMaxPOW(Block, { SeqHash: Block.SeqHash, AddrHash: Block.AddrHash, PrevHash: Block.PrevHash, TreeHash: Block.TreeHash, }) } - SetNoPOW(BlockNumFrom, bReload, RefBlockNum) { + SetNoPOW(BlockNumFrom: number, bReload: number, RefBlockNum: string) { var CurNum = BlockNumFrom; var finish = this.GetLastCorrectBlockNum(); while (true) { @@ -1349,7 +1360,7 @@ export default class CConsensus extends CBlock { CurNum++ } } - MiningProcess(msg) { + MiningProcess(msg: TeraBlock) { var BlockMining = this.GetBlock(msg.BlockNum); if (!BlockMining) { teraManager.SendToWebClient({ diff --git a/src/core/block-loader.ts b/src/core/block-loader.ts index bf97c88..5519a26 100644 --- a/src/core/block-loader.ts +++ b/src/core/block-loader.ts @@ -15,29 +15,31 @@ import { TYPE_TRANSACTION } from '../constant/account'; import { STreeBuffer } from './base'; import { RBTree } from './library'; import { DB_FORMAT } from '../constant/db-format'; -//import * as crypto from 'crypto'; -require('./block-loader-const'); +import * as crypto from 'crypto'; +import CNode from './node'; +import { LoadContext, TeraBlock, ContextTask, TeraChain, SocketSendInfo } from '../interfaces/server'; +import './block-loader-const' const STAT_BLOCK_LOAD_PERIOD = global.CONSENSUS_PERIOD_TIME / 5; export default class CBlock extends CRest { - MapMapLoaded - BlockChain - ChainID - BlockID - TaskNodeIndex - LoadedChainList - LastChainLoad - StartLoadBlockTime - LoadHistoryMode - MapBlockBodyLoad - BlockNumDB - RelayMode - LoadHistoryMessage - LastLoadedBlockNum - LoadHistoryContext - LoadBlockStatNum - BADHashCount - ActualNodes - constructor(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) { + MapMapLoaded: {} + BlockChain: { [x: string]: any; } + ChainID: number + BlockID: number + TaskNodeIndex: number + LoadedChainList: any[] + LastChainLoad: any + StartLoadBlockTime: number + LoadHistoryMode: boolean + MapBlockBodyLoad: { [x: string]: any; } + BlockNumDB: number + RelayMode: boolean + LoadHistoryMessage: boolean + LastLoadedBlockNum: number + LoadHistoryContext: LoadContext + LoadBlockStatNum: number + BADHashCount: number + ActualNodes: RBTree + constructor(SetKeyPair: crypto.ECDH, RunIP: string, RunPort: number, UseRNDHeader: boolean, bVirtual: boolean) { super(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) this.MapMapLoaded = {} this.BlockChain = {} @@ -62,7 +64,7 @@ export default class CBlock extends CRest { StopNode() { global.glStopNode = true } - GenesisBlockHeaderDB(Num) { + GenesisBlockHeaderDB(Num: number) { if (Num < 0) return undefined; var Block: any = { @@ -115,7 +117,7 @@ export default class CBlock extends CRest { } return PrevArr; } - GetPrevHash(Block) { + GetPrevHash(Block: TeraBlock) { var startPrev = Block.BlockNum - global.BLOCK_PROCESSING_LENGTH2; var Sum = 0; var arr = []; @@ -132,7 +134,7 @@ export default class CBlock extends CRest { var PrevHash = global.CalcHashFromArray(arr, true); return PrevHash; } - GetPrevHashDB(Block) { + GetPrevHashDB(Block: TeraBlock) { var startPrev = Block.BlockNum - global.BLOCK_PROCESSING_LENGTH2; var arr = []; for (var i = 0; i < global.BLOCK_PROCESSING_LENGTH; i++) { @@ -147,10 +149,10 @@ export default class CBlock extends CRest { var PrevHash = global.CalcHashFromArray(arr, true); return PrevHash; } - StartSyncBlockchain(Node?, bSilent?, bCheckPoint?, PrevStartedBlockNum?) { + StartSyncBlockchain(Node?: CNode, bSilent?: boolean, bCheckPoint?: boolean, PrevStartedBlockNum?: number) { this.FREE_ALL_MEM_CHAINS() if (global.NO_HISTORY_MODE) { - this.LoadHistoryMode = 0 + this.LoadHistoryMode = false return; } if (global.CREATE_ON_START && !global.LOCAL_RUN) @@ -243,7 +245,7 @@ export default class CBlock extends CRest { this.SendF(Node, { "Method": "GETBLOCKHEADER", "Context": Context, "Data": { Foward: 1, BlockNum: Context.BlockNum, Hash: BlockDB.SumHash } }) } } - StartLoadBlockHeader(LoadHash, Num, StrInfo, bIsSum) { + StartLoadBlockHeader(LoadHash: Buffer, Num: number, StrInfo: string, bIsSum: boolean) { if (this.LoadHistoryMode) return; if (global.NO_HISTORY_MODE) @@ -345,7 +347,7 @@ export default class CBlock extends CRest { global.ToLog("Timeout - stop load chain with id=" + chain.id + " (" + chain.BlockNum + "-" + chain.BlockNumMax + ")") chain.StopSend = true chain.AddInfo("Stop load #2") - this.ClearChains(chain, 0) + this.ClearChains(chain, false) } } } @@ -377,7 +379,7 @@ export default class CBlock extends CRest { this.FREE_ALL_MEM_CHAINS() } } - GetNextNode(task, keyid?, checktime?, BlockNum?) { + GetNextNode(task: ContextTask, keyid?: string | number, checktime?: number | boolean, BlockNum?: number) { var CurTime = global.GetCurrentTime(0) - 0; if (checktime && task.time) { var Delta = CurTime - task.time; @@ -445,16 +447,21 @@ export default class CBlock extends CRest { } return { Result: false, timewait: timewait }; } - SendChainNext(chain, checktime) { + SendChainNext(chain: any, checktime: boolean) { var Ret = this.GetNextNode(chain, chain.BlockNum, checktime); if (Ret.Result) { if (!chain.Context) chain.Context = { Chain: chain } var Node = Ret.Node; this.SendF(Node, { - "Method": "GETBLOCKHEADER", "Context": chain.Context, "Data": { - Foward: 0, BlockNum: chain.BlockNum, Hash: chain.Hash, - IsSum: chain.IsSum, Count: chain.Count + "Method": "GETBLOCKHEADER", + "Context": chain.Context, + "Data": { + Foward: 0, + BlockNum: chain.BlockNum, + Hash: chain.Hash, + IsSum: chain.IsSum, + Count: chain.Count } }) var DopStr = ""; @@ -481,13 +488,13 @@ export default class CBlock extends CRest { Count:uint\ }"; } - GetBlockArrFromBuffer_Load(BufRead, Info) { + GetBlockArrFromBuffer_Load(BufRead: Buffer, Info: SocketSendInfo) { var BlockArr = global.GetBlockArrFromBuffer(BufRead, Info); if (BlockArr.length > 0 && BlockArr[0].BlockNum === global.BLOCK_PROCESSING_LENGTH2) BlockArr.unshift(this.ReadBlockHeaderDB(global.BLOCK_PROCESSING_LENGTH2 - 1)) return BlockArr; } - RETBLOCKHEADER_FOWARD(Info, CurTime) { + RETBLOCKHEADER_FOWARD(Info: SocketSendInfo, CurTime: number) { if (!Info.Context.Foward) return; var Context = this.LoadHistoryContext; @@ -528,8 +535,8 @@ export default class CBlock extends CRest { } } if (arr2.length > 1) { - Context.WasLoadNum = 1 - var chain = { id: 0, StopSend: 1, WriteToDBAfterLoad: 1 }; + Context.WasLoadNum = true + var chain = { id: 0, StopSend: true, WriteToDBAfterLoad: true }; this.ChainBindMethods(chain) this.SetChainNum(chain) this.PrepareTransactionsForLoad(chain, arr2) @@ -552,7 +559,7 @@ export default class CBlock extends CRest { } } } - RETBLOCKHEADER(Info, CurTime) { + RETBLOCKHEADER(Info: SocketSendInfo, CurTime: number) { Info.Node.NextPing = global.MIN_PERIOD_PING if (Info.Context.Foward) return this.RETBLOCKHEADER_FOWARD(Info, CurTime); @@ -656,7 +663,7 @@ export default class CBlock extends CRest { this.CheckToStartLoadBlockData(chain) } } - BlockChainLoad(Block) { + BlockChainLoad(Block: TeraBlock) { var chain = Block.chain; Block.Send = undefined chain.BlockNum = Block.BlockNum @@ -668,7 +675,7 @@ export default class CBlock extends CRest { chain.ParentChain = undefined chain.AddInfo("SetChainSend:" + chain.BlockNum) } - CheckToStartLoadBlockData(chain) { + CheckToStartLoadBlockData(chain: TeraChain) { if (chain.Deleted) return; var arr = this.GetArrFromChain(chain); @@ -693,7 +700,7 @@ export default class CBlock extends CRest { chain.AddInfo(Str) this.PrepareTransactionsForLoad(chain, arr) } - GetArrFromChain(chain) { + GetArrFromChain(chain: TeraChain) { var arr = []; var Block = chain.BlockHead; while (Block) { @@ -705,7 +712,7 @@ export default class CBlock extends CRest { } return arr; } - PrepareTransactionsForLoad(chain, arr, bNoSlice?) { + PrepareTransactionsForLoad(chain: TeraChain, arr: any[], bNoSlice?: boolean) { if (!bNoSlice) arr = arr.slice(1) chain.arr = arr @@ -759,7 +766,7 @@ export default class CBlock extends CRest { } } } - CheckAndWriteLoadedChain(chain) { + CheckAndWriteLoadedChain(chain: TeraChain) { if (chain.CurNumArrLoad >= chain.arr.length) { var Block = chain.arr[chain.arr.length - 1]; if (chain.WriteToDBAfterLoad || Block.BlockNum >= this.CurrentBlockNum + global.TIME_START_SAVE - 2) { @@ -790,7 +797,7 @@ export default class CBlock extends CRest { } } } - WriteLoadedBlockArr(arr) { + WriteLoadedBlockArr(arr: TeraBlock[]) { if (!arr.length) return; var startTime = process.hrtime(); @@ -853,10 +860,10 @@ export default class CBlock extends CRest { this.FREE_ALL_MEM_CHAINS() global.ADD_TO_STAT_TIME("WRITECHAIN_TO_DB_TIME", startTime) } - SetNoPOW(BlockNumFrom, bReload, RefBlockNum) { + SetNoPOW(BlockNumFrom: number, bReload: number, RefBlockNum: any) { //defiend in block-exchange.js } - CopyBlock(Block, BlockDst) { + CopyBlock(Block: TeraBlock, BlockDst: TeraBlock) { BlockDst.BlockNum = Block.BlockNum BlockDst.TreeHash = Block.TreeHash BlockDst.AddrHash = Block.AddrHash @@ -872,7 +879,7 @@ export default class CBlock extends CRest { BlockDst.arrContent = Block.arrContent BlockDst.bSave = Block.bSave } - CopyBlockToMem(Block) { + CopyBlockToMem(Block: TeraBlock) { var BlockMem = this.BlockChain[Block.BlockNum]; if (BlockMem) { this.CopyBlock(Block, BlockMem) @@ -882,10 +889,10 @@ export default class CBlock extends CRest { } this.AddToStatBlockConfirmation(Block) } - RecreateMaxPOW(Block) { + RecreateMaxPOW(Block: TeraBlock) { //defiend in block-exchange.js } - ClearMaxInBlock(Block) { + ClearMaxInBlock(Block: TeraBlock) { Block.MaxPOW = {} var POW = Block.MaxPOW; POW.SeqHash = Block.SeqHash @@ -906,7 +913,7 @@ export default class CBlock extends CRest { POW.SumHash = Block.SumHash POW.SumPow = Block.SumPow } - AddToStatBlockConfirmation(Block) { + AddToStatBlockConfirmation(Block: TeraBlock) { if (Block.BlockNum > global.START_BLOCK_RUN + global.BLOCK_PROCESSING_LENGTH2) { var TimeDelta = this.CurrentBlockNum - Block.BlockNum; global.ADD_TO_STAT("MAX:BlockConfirmation", TimeDelta) @@ -915,7 +922,7 @@ export default class CBlock extends CRest { global.ADD_TO_STAT("MAX:BlockConfirmation", global.BLOCK_PROCESSING_LENGTH) } } - SendBlockNext(Block) { + SendBlockNext(Block: TeraBlock & ContextTask) { var SendResult = 0; var Key = global.GetHexFromArr(Block.TreeHash); while (true) { @@ -940,7 +947,7 @@ export default class CBlock extends CRest { } return SendResult; } - ClearChains(DeleteChain, bShow?) { + ClearChains(DeleteChain: TeraChain, bShow?: boolean) { if (!DeleteChain) { this.FREE_ALL_MEM_CHAINS() return this.LoadedChainList.length; @@ -1005,14 +1012,13 @@ export default class CBlock extends CRest { global.ADD_TO_STAT("NODE_CAN_GET:" + global.NodeName(Node), Node.CanGetBlocks, 1) } } - static - GETBLOCK_F() { + static GETBLOCK_F() { return "{\ BlockNum:uint,\ TreeHash:hash,\ }"; } - RETGETBLOCK(Info, CurTime) { + RETGETBLOCK(Info: SocketSendInfo, CurTime: number) { Info.Node.NextPing = global.MIN_PERIOD_PING var Block = Info.Context.Block; if (Block && !Block.TreeEq) { @@ -1075,7 +1081,7 @@ export default class CBlock extends CRest { } } } - SendCanBlock(Node, Block) { + SendCanBlock(Node: CNode, Block: TeraBlock) { Node.SendBlockCount++ if (!Node.INFO.BlockNumDB) return; @@ -1086,23 +1092,23 @@ export default class CBlock extends CRest { static CANBLOCK_F() { return "{BlockNum:uint}"; } - CANBLOCK(Info, CurTime) { + CANBLOCK(Info: SocketSendInfo, CurTime: number) { var Data = this.DataFromF(Info); this.SendF(Info.Node, { "Method": "RETCANBLOCK", "Data": { Result: 1 } }) } static RETCANBLOCK_F() { return "{Result:byte}"; } - RETCANBLOCK(Info, CurTime) { + RETCANBLOCK(Info: SocketSendInfo, CurTime: number) { var Data = this.DataFromF(Info); if (Data.Result === 1) { Info.Node.LoadBlockCount++ } } - DataFromF(Info, bSendFormat?): any { + DataFromF(Info: SocketSendInfo, bSendFormat?: boolean): any { //defiend in server.js } - SetBlockNOSendToNode(Block, Node, Str) { + SetBlockNOSendToNode(Block: TeraBlock, Node: CNode, Str) { var Str = global.GetHexFromArr(Block.TreeHash); var Str2 = this.GetStrFromHashShort(Block.TreeHash); var keysend = "" + Node.addrStr + ":" + Str; @@ -1110,7 +1116,7 @@ export default class CBlock extends CRest { if (Block.chain) Block.chain.AddInfo("" + Block.BlockNum + " " + Str2 + "<-" + global.GetNodeStrPort(Node)) } - FindBlockInLoadedChain(BlockNum, TreeHash) { + FindBlockInLoadedChain(BlockNum: number, TreeHash: Buffer) { var StrTreeHash = global.GetHexFromArr(TreeHash); var MapBlockLoaded = this.GetMapLoaded(BlockNum); var BlockFind = MapBlockLoaded["TH:" + StrTreeHash]; @@ -1119,7 +1125,7 @@ export default class CBlock extends CRest { else return undefined; } - CheckSeqHashDB(Block, StrError) { + CheckSeqHashDB(Block: TeraBlock, StrError: string) { if (Block.BlockNum < global.BLOCK_PROCESSING_LENGTH2) return true; var TreeHashTest = global.CalcTreeHashFromArrBody(Block.BlockNum, Block.arrContent); @@ -1147,7 +1153,7 @@ export default class CBlock extends CRest { } return true; } - ToLogBlock(Block, StrInfo, arr) { + ToLogBlock(Block: TeraBlock, StrInfo: string, arr: any[]) { global.ToLog("-------------" + StrInfo) global.ToLog("BlockNum=" + (Block.BlockNum)) global.ToLog("Hash=" + global.GetHexFromArr(Block.Hash)) @@ -1161,7 +1167,7 @@ export default class CBlock extends CRest { global.ToLog("arr[" + i + "]=" + global.GetHexFromArr(arr[i])) } } - GetBlock(num, bToMem?, bReadBody?) { + GetBlock(num: number, bToMem?: boolean, bReadBody?: boolean) { if (bToMem === undefined) bToMem = true if (num < this.CurrentBlockNum - global.BLOCK_COUNT_IN_MEMORY) @@ -1178,7 +1184,7 @@ export default class CBlock extends CRest { } return Block; } - GetMapLoaded(num) { + GetMapLoaded(num: number) { if (num < 0) num = 0 var index = Math.floor(num / global.BLOCK_COUNT_IN_MEMORY); @@ -1189,10 +1195,10 @@ export default class CBlock extends CRest { } return map; } - GetMapLoadedFromChain(chain) { + GetMapLoadedFromChain(chain: TeraChain) { return this.GetMapLoaded(chain.BlockNumStart); } - FREE_MEM_BLOCKS(NumMax) { + FREE_MEM_BLOCKS(NumMax: number) { for (var key in this.BlockChain) { var Block = this.BlockChain[key]; if (!Block || Block.BlockNum < NumMax) { @@ -1200,7 +1206,7 @@ export default class CBlock extends CRest { } } } - FREE_MEM_CHAINS(NumMax) { + FREE_MEM_CHAINS(NumMax: number) { this.FREE_MEM_BLOCKS(NumMax - global.BLOCK_COUNT_IN_MEMORY) var maxArrMap = Math.floor(NumMax / global.BLOCK_COUNT_IN_MEMORY) - 1; if (maxArrMap >= 0) { @@ -1232,7 +1238,7 @@ export default class CBlock extends CRest { //@ts-ignore gc() } - AddValueToHistory(typedata, val) { + AddValueToHistory(typedata: string, val: any) { var Arr = global.HistoryBlockBuf.LoadValue(typedata, 1); if (!Arr) { Arr = [] @@ -1240,7 +1246,7 @@ export default class CBlock extends CRest { } Arr.push(val) } - GetHistoryTree(typedata) { + GetHistoryTree(typedata: string) { var Tree = global.HistoryBlockBuf.LoadValue(typedata, 1); if (!Tree) { Tree = new RBTree(global.CompareItemHash) @@ -1248,7 +1254,7 @@ export default class CBlock extends CRest { } return Tree; } - ChainBindMethods(chain) { + ChainBindMethods(chain: TeraChain) { function GetRootChain() { var Count = 0; @@ -1276,22 +1282,22 @@ export default class CBlock extends CRest { chain.GetFindDB = GetFindDB.bind(chain) chain.AddInfo = global.AddInfoChain.bind(chain) } - GetMemoryStamp(Str) { + GetMemoryStamp(Str: string) { return Str + ":##:" + Math.floor(this.CurrentBlockNum / global.BLOCK_COUNT_IN_MEMORY); } - GetStrFromHashShort(Hash) { + GetStrFromHashShort(Hash: Buffer) { var Str = global.GetHexFromArr(Hash); if (typeof Str === "string") return Str.substr(0, 6); else return ""; } - ToLogTime(startTime, Str) { + ToLogTime(startTime: [number, number], Str: string) { const Time = process.hrtime(startTime); var deltaTime = (Time[0] * 1000 + Time[1] / 1e6); global.ToLog(Str + " : " + deltaTime + "ms") } - AddBlockToLoadBody(Block) { + AddBlockToLoadBody(Block: TeraBlock) { if (!this.MapBlockBodyLoad[Block.BlockNum]) { this.MapBlockBodyLoad[Block.BlockNum] = Block } @@ -1308,10 +1314,10 @@ export default class CBlock extends CRest { this.MapBlockBodyLoad = {} if (!arr.length) return; - var chain = { StopSend: 1, WriteToDBAfterLoad: 1, BodyLoad: 1 }; + var chain = { StopSend: true, WriteToDBAfterLoad: true, BodyLoad: true }; this.ChainBindMethods(chain) this.SetChainNum(chain) - this.PrepareTransactionsForLoad(chain, arr, 1) + this.PrepareTransactionsForLoad(chain, arr, true) } }; global.LoadBlockFromNetwork = function(Params, F) { diff --git a/src/core/code.ts b/src/core/code.ts index 5eaff31..f698e00 100644 --- a/src/core/code.ts +++ b/src/core/code.ts @@ -11,11 +11,14 @@ "use strict"; import * as fs from 'fs' import { secp256k1 } from '../core/library' +import * as crypto from 'crypto' const FORMAT_EVAL_SEND = "{MaxBlockNum:uint,Code:str,Sign:arr64}"; import CCommon from './base' +import CNode from './node'; +import { SocketSendInfo } from '../interfaces/server'; export default class CCode extends CCommon { - LastEvalCodeNum - constructor(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) { + LastEvalCodeNum: number + constructor(SetKeyPair: crypto.ECDH, RunIP: string, RunPort: number, UseRNDHeader: boolean, bVirtual: boolean) { super(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) if (!global.ADDRLIST_MODE && !this.VirtualMode) { setInterval(this.CheckLoadCodeTime.bind(this), 10 * 1000) @@ -37,7 +40,7 @@ export default class CCode extends CCommon { global.START_LOAD_CODE.StartLoadVersionNum = 0 global.START_LOAD_CODE.StartLoadVersionNumTime = 0 } - StartLoadCode(Node, CodeVersion) { + StartLoadCode(Node: CNode, CodeVersion: { VersionNum: any; }) { var VersionNum = CodeVersion.VersionNum; global.START_LOAD_CODE.StartLoad = CodeVersion global.START_LOAD_CODE.StartLoadNode = Node @@ -51,11 +54,10 @@ export default class CCode extends CCommon { var Context = { "VersionNum": VersionNum }; this.SendF(Node, { "Method": "GETCODE", "Context": Context, "Data": VersionNum }) } - static - GETCODE_F() { + static GETCODE_F() { return "uint"; } - RETCODE(Info) { + RETCODE(Info: SocketSendInfo) { var VersionNum = Info.Context.VersionNum; if (!VersionNum || !global.START_LOAD_CODE.StartLoad) return; @@ -67,15 +69,14 @@ export default class CCode extends CCommon { fs.writeSync(file_handle, Info.Data, 0, Info.Data.length) fs.closeSync(file_handle) this.UseCode(VersionNum, global.USE_AUTO_UPDATE) - } - else { + } else { global.ToError("Error check hash of version code :" + global.START_LOAD_CODE.StartLoadVersionNum + " from node: " + Info.Node.ip + ":" + Info.Node.port) this.ClearLoadCode() this.AddCheckErrCount(Info.Node, 1, "Error check hash of version code") } } } - UseCode(VersionNum, bUpdate) { + UseCode(VersionNum: string, bUpdate: boolean) { if (bUpdate) { UpdateCodeFiles(VersionNum) } @@ -102,8 +103,7 @@ export default class CCode extends CCommon { global.CODE_VERSION.Hash = Hash global.CODE_VERSION.Sign = Sign return "OK Set new code version=" + Data.VersionNum; - } - else { + } else { return "File not exist: " + fname; } } @@ -134,12 +134,10 @@ function UpdateCodeFiles(StartNum) { UnpackCodeFile(Path); if (StartNum % 2 === 0) { global.RestartNode(1); - } - else { + } else { } return 1; - } - else { + } else { global.ToLog("Delete old file update:" + Name); fs.unlinkSync(Path); } diff --git a/src/core/connect.ts b/src/core/connect.ts index f444016..843a2fa 100644 --- a/src/core/connect.ts +++ b/src/core/connect.ts @@ -33,31 +33,32 @@ global.MAX_WAIT_PERIOD_FOR_HOT = 4 * global.CONSENSUS_PERIOD_TIME; const PERIOD_FOR_START_CHECK_TIME = 300; const CAN_START_TIME_AVG = 200; import CMessages from './transfer-msg' +import { TeraBlock, SocketSendInfo } from '../interfaces/server'; export default class CConnect extends CMessages { - ip - port - StartTime - WasNodesSort - LevelNodes - NodesArr - NodesArrUnSort - NodesMap - NodesIPMap - PerioadAfterCanStart - КодДляРазработчикаХекс - CommonKey - KeyToNode - NameToNode - BlockNumDB - idTimerSetConst - SignCurrentTimeDev - StopDetectGrayMode - LastNotZeroNodesTime - TransferTree - СтатБлок - BusyLevel - SendTrafficFree - constructor(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) { + ip: string + port: number | string + StartTime: number + WasNodesSort: boolean + LevelNodes: any[] + NodesArr: CNode[] + NodesArrUnSort: CNode[] + NodesMap: { [x: string]: CNode; } + NodesIPMap: { [x: string]: any; } + PerioadAfterCanStart: number + КодДляРазработчикаХекс: string + CommonKey: string + KeyToNode: Buffer + NameToNode: any + BlockNumDB: number + idTimerSetConst: NodeJS.Timeout + SignCurrentTimeDev: Buffer + StopDetectGrayMode: number + LastNotZeroNodesTime: number + TransferTree: any[] + СтатБлок: { SeqHash: any; BlockNum: any; AddrHash: any; } + BusyLevel: number + SendTrafficFree: number + constructor(SetKeyPair: crypto.ECDH, RunIP: string, RunPort: number, UseRNDHeader: boolean, bVirtual: boolean) { super(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) this.StartTime = Date.now() this.WasNodesSort = false @@ -91,14 +92,14 @@ export default class CConnect extends CMessages { } return Массив; } - ДоступенКлючРазработчика(Node) { + ДоступенКлючРазработчика(Node: CNode) { if (Node.PubKey && global.WALLET.WalletOpen !== false && global.IsDeveloperAccount(global.WALLET.PubKeyArr)) { return 1; } return 0; } - БлокИзДанных(Node, Arr) { - var Block: any = {}; + БлокИзДанных(Node: CNode, Arr: any) { + var Block: TeraBlock = {}; if (this.ДоступенКлючРазработчика(Node) && !global.IsZeroArr(Arr)) { var Data = global.BufLib.GetObjectFromBuffer(Arr, "{BlockNum:arr6,SeqHash:arr32,AddrHash:arr32}", {}); Block.BlockNum = this.ValueFromXORDevelop(Node, "Stat:BlockNum", Data.BlockNum, "uint") @@ -107,7 +108,7 @@ export default class CConnect extends CMessages { } return Block; } - StartConnectTry(Node) { + StartConnectTry(Node: CNode) { var Delta = Date.now() - Node.StartTimeConnect; if (Delta >= Node.NextConnectDelta && this.IsCanConnect(Node)) { if (!global.GetSocketStatus(Node.Socket)) { @@ -120,7 +121,7 @@ export default class CConnect extends CMessages { } } } - FindRunNodeContext(addrArr, ip, port, bUpdate) { + FindRunNodeContext(addrArr: Buffer, ip: string, port: number, bUpdate: boolean) { var Node, addrStr; addrStr = global.GetHexFromAddres(addrArr) Node = this.NodesMap[addrStr] @@ -142,7 +143,7 @@ export default class CConnect extends CMessages { Node.port = port return Node; } - CheckNodeMap(Node) { + CheckNodeMap(Node: CNode) { if (Node.addrStrTemp && Node.addrStrTemp !== Node.addrStr) { delete this.NodesMap[Node.addrStrTemp] var Node2 = this.NodesMap[Node.addrStr]; @@ -155,7 +156,7 @@ export default class CConnect extends CMessages { Node.addrStrTemp = undefined } } - StartHandshake(Node) { + StartHandshake(Node: CNode) { return this.StartConnectTry(Node); } StartPingPong() { @@ -187,7 +188,7 @@ export default class CConnect extends CMessages { } } } - GetPingData(Node) { + GetPingData(Node: CNode) { var GrayAddres = 0; if (global.GrayConnect()) GrayAddres = 1 @@ -275,14 +276,14 @@ export default class CConnect extends CMessages { NetConstant:{Num:uint,BlockNum:uint,MaxTrasactionLimit:uint,Reserv1:uint,Reserv2:uint,Reserv3:uint,Reserv4:uint,Reserv5:uint,Sign:arr64},\ }"; } - static PONG_F(bSend) { + static PONG_F(bSend: boolean) { return CConnect.PING_F(bSend); } - PING(Info, CurTime) { + PING(Info: SocketSendInfo, CurTime: number) { this.DoPingData(Info, 1) this.SendF(Info.Node, { "Method": "PONG", "Context": Info.Context, "Data": this.GetPingData(Info.Node) }) } - DoPingData(Info, bCheckPoint) { + DoPingData(Info: SocketSendInfo, bCheckPoint: number) { var Node = Info.Node; var Data = this.DataFromF(Info); Info.Node.VERSIONMAX = Data.VERSIONMAX @@ -295,7 +296,7 @@ export default class CConnect extends CMessages { Node.Name = "" } Node.INFO = Data - Node.INFO.WasPing = 1 + Node.INFO.WasPing = true Node.LevelCount = Data.LevelCount Node.LoadHistoryMode = Data.LoadHistoryMode Node.LastTime = global.GetCurrentTime() - 0 @@ -308,7 +309,7 @@ export default class CConnect extends CMessages { this.CheckDeltaTime(Data, Info.Node) } } - PONG(Info, CurTime) { + PONG(Info: SocketSendInfo, CurTime: number) { var Data = this.DataFromF(Info); var Node = Info.Node; if (!Info.Context) @@ -372,7 +373,7 @@ export default class CConnect extends CMessages { } this.CheckDeltaTime(Data, Info.Node) } - CheckCheckPoint(Data, Node) { + CheckCheckPoint(Data: { CheckPoint: { BlockNum: string | number; Hash: any; Sign: any; }; }, Node: CNode) { if (global.CREATE_ON_START) return; if (Data.CheckPoint.BlockNum && Data.CheckPoint.BlockNum > global.CHECK_POINT.BlockNum) { @@ -386,7 +387,7 @@ export default class CConnect extends CMessages { if (Block && global.CompareArr(Block.Hash, global.CHECK_POINT.Hash) !== 0) { this.BlockNumDB = global.CHECK_POINT.BlockNum - 1 this.TruncateBlockDB(this.BlockNumDB) - this.StartSyncBlockchain(Node, 0, 1) + this.StartSyncBlockchain(Node, false, true) } } else { Node.NextConnectDelta = 60 * 1000 @@ -395,7 +396,7 @@ export default class CConnect extends CMessages { } } } - CheckDeltaTime(Data, Node) { + CheckDeltaTime(Data: { CheckDeltaTime: { Num: string | number; Sign: any; }; }, Node: CNode) { if (global.AUTO_CORRECT_TIME) if (global.CAN_START && !global.CREATE_ON_START) { if (Data.CheckDeltaTime.Num > global.CHECK_DELTA_TIME.Num) { @@ -410,7 +411,7 @@ export default class CConnect extends CMessages { } } } - CheckNetConstant(Data, Node) { + CheckNetConstant(Data: { NetConstant: { Num: string | number; Sign: any; BlockNum: number; }; }, Node: CNode) { if (Data.NetConstant.Num > global.NET_CONSTANT.Num) { var SignArr = this.GetSignCheckNetConstant(Data.NetConstant); if (global.CheckDevelopSign(SignArr, Data.NetConstant.Sign)) { @@ -438,7 +439,7 @@ export default class CConnect extends CMessages { DoNetConst() { global.MAX_TRANSACTION_LIMIT = global.NET_CONSTANT.MaxTrasactionLimit } - CheckCodeVersion(Data, Node) { + CheckCodeVersion(Data: { CodeVersion: any; CheckPoint: { BlockNum: any; Hash: any[] | Buffer; }; }, Node: CNode) { var CodeVersion = Data.CodeVersion; Node.VersionNum = CodeVersion.VersionNum if (CodeVersion.VersionNum >= global.MIN_CODE_VERSION_NUM) { @@ -487,12 +488,12 @@ export default class CConnect extends CMessages { } } } - GetSignCheckNetConstant(Data) { + GetSignCheckNetConstant(Data: { Num: string | number; Sign: any; BlockNum: number; }) { var Buf = global.BufLib.GetBufferFromObject(Data, "{Num:uint,BlockNum:uint,MaxTrasactionLimit:uint,Reserv1:uint,Reserv2:uint,Reserv3:uint,Reserv4:uint,Reserv5:uint}", 1000, {}); return global.shaarr(Buf); } - GetSignCheckDeltaTime(Data) { + GetSignCheckDeltaTime(Data: { Num: string | number; Sign: any; }) { var Buf = global.BufLib.GetBufferFromObject(Data, "{Num:uint,bUse:byte,StartBlockNum:uint,EndBlockNum:uint,bAddTime:byte,DeltaTime:uint}", 1000, {}); return global.shaarr(Buf); @@ -505,7 +506,7 @@ export default class CConnect extends CMessages { Node2.NextPing = 5 * 1000 } } - StartDisconnectHot(Node, StrError, bDeleteHot?) { + StartDisconnectHot(Node: CNode, StrError: string, bDeleteHot?: boolean) { global.AddNodeInfo(Node, "DisconnectHot:" + StrError) if (Node.Active && Node.Hot) { global.AddNodeInfo(Node, "SEND DISCONNECTHOT") @@ -513,12 +514,12 @@ export default class CConnect extends CMessages { } this.DeleteNodeFromHot(Node) } - DISCONNECTHOT(Info, CurTime) { + DISCONNECTHOT(Info: { Node: any; Data: string; }, CurTime: any) { this.DeleteNodeFromHot(Info.Node) global.ADD_TO_STAT("DISCONNECTHOT") global.AddNodeInfo(Info.Node, "GET DISCONNECTHOT:" + Info.Data) } - StartGetNodes(Node) { + StartGetNodes(Node: CNode) { if (global.glStopNode) return; var Delta = Date.now() - Node.StartTimeGetNodes; @@ -530,10 +531,12 @@ export default class CConnect extends CMessages { this.Send(Node, { "Method": "GETNODES", "Context": {}, "Data": undefined }) } } - GETNODES(Info, CurTime) { + GETNODES(Info: { Node: CNode; Context: any; }, CurTime: number) { this.SendF(Info.Node, { - "Method": "RETGETNODES", "Context": Info.Context, "Data": { - arr: this.GetDirectNodesArray(false, 0, 1), IsAddrList: global.ADDRLIST_MODE, + "Method": "RETGETNODES", + "Context": Info.Context, "Data": { + arr: this.GetDirectNodesArray(false, 0, 1), + IsAddrList: global.ADDRLIST_MODE, } }, global.MAX_NODES_RETURN * 250 + 300) } @@ -551,7 +554,7 @@ export default class CConnect extends CMessages { ],\ IsAddrList:byte}"; } - RETGETNODES(Info, CurTime) { + RETGETNODES(Info: SocketSendInfo, CurTime: number) { var Data = this.DataFromF(Info); var arr = Data.arr; if (arr && arr.length > 0) { @@ -565,7 +568,7 @@ export default class CConnect extends CMessages { Info.Node.IsAddrList = Data.IsAddrList global.AddNodeInfo(Info.Node, "RETGETNODES length=" + arr.length) } - GetNewNode(ip, port, addrStr?) { + GetNewNode(ip: string, port: number, addrStr?: string) { var bTemp; if (!addrStr) { bTemp = 1 @@ -577,7 +580,7 @@ export default class CConnect extends CMessages { Node.addrStrTemp = addrStr return Node; } - AddNode(Str) { + AddNode(Str: string) { var ip, port; var Index = Str.indexOf(":"); if (Index > 0) { @@ -595,7 +598,7 @@ export default class CConnect extends CMessages { this.GetNewNode(ip, port) return "AddNode " + ip + ":" + port; } - IsCanConnect(Node) { + IsCanConnect(Node: CNode) { if (Node.addrStr === this.addrStr || this.NodeInBan(Node) || Node.Delete || Node.Self || Node.DoubleConnection) return false; if (Node.ip === this.ip && Node.port === this.port) @@ -604,10 +607,10 @@ export default class CConnect extends CMessages { return false; return true; } - NodeInBan(Node) { + NodeInBan(Node: CNode) { //defiend in } - GetDirectNodesArray(bAll, bWebPort?, bGetAddrArr?) { + GetDirectNodesArray(bAll: boolean, bWebPort?: number, bGetAddrArr?: number) { var ret = []; var Value: any = { addrStr: this.addrStr, ip: this.ip, port: this.port, LastTime: 0, DeltaTime: 0, Hot: true, BlockProcessCount: 0, portweb: global.HTTP_HOSTING_PORT, @@ -657,7 +660,7 @@ export default class CConnect extends CMessages { } return ret; } - AddToArrNodes(Item, b?) { + AddToArrNodes(Item: CNode, b?: boolean) { if (Item.addrStr === "" || Item.addrStr === this.addrStr) return; var Node; @@ -669,8 +672,10 @@ export default class CConnect extends CMessages { if (!Node) { if (Item instanceof CNode) Node = Item - else - Node = new CNode(Item.addrStr, Item.ip, Item.port) + else { + let item = Item as { addrStr: string, ip: string, port: number } + Node = new CNode(item.addrStr, item.ip, item.port) + } Node.id = this.NodesArr.length Node.addrArr = global.GetAddresFromHex(Node.addrStr) this.NodesMap[Node.addrStr] = Node @@ -714,7 +719,7 @@ export default class CConnect extends CMessages { this.AddToArrNodes(arr[i], true) } } - GetLevelEnum(Node) { + GetLevelEnum(Node: CNode) { var Level = this.AddrLevelNode(Node); var arr0 = this.LevelNodes[Level]; if (!arr0) { @@ -747,14 +752,12 @@ export default class CConnect extends CMessages { if (Node.Active && Node.CanHot) this.SendF(Node, { "Method": "ADDLEVELCONNECT", "Context": {}, "Data": this.GetLevelEnum(Node) }) } - static - ADDLEVELCONNECT_F() { + static ADDLEVELCONNECT_F() { return "uint"; } ADDLEVELCONNECT(Info, CurTime) { Info.Node.LevelCount = this.DataFromF(Info) var ret; - var Count; if (!global.CAN_START) return; if (Info.Node.GrayConnect || global.GrayConnect()) @@ -763,14 +766,13 @@ export default class CConnect extends CMessages { var bAdd = this.AddLevelConnect(Info.Node); if (bAdd) { ret = { result: 1, Count: Count } - } - else { + } else { ret = { result: 0, Count: Count } } global.AddNodeInfo(Info.Node, "GET ADDLEVELCONNECT, DO bAdd=" + bAdd) this.SendF(Info.Node, { "Method": "RETADDLEVELCONNECT", "Context": Info.Context, "Data": ret }) } - AddLevelConnect(Node) { + AddLevelConnect(Node: CNode) { if (!global.CAN_START) return false; var Level = this.AddrLevelNode(Node); @@ -802,22 +804,20 @@ export default class CConnect extends CMessages { global.AddNodeInfo(Node, "Add Level connect") return true; } - static - RETADDLEVELCONNECT_F() { + static RETADDLEVELCONNECT_F() { return "{result:byte,Count:uint}"; } - RETADDLEVELCONNECT(Info, CurTime) { + RETADDLEVELCONNECT(Info: SocketSendInfo, CurTime: number) { var Data = this.DataFromF(Info); global.AddNodeInfo(Info.Node, "GET RETADDLEVELCONNECT: " + Data.result) if (Data.result === 1) { this.AddLevelConnect(Info.Node) - } - else { + } else { this.AddCheckErrCount(Info.Node, 1) } Info.Node.LevelCount = Data.Count } - AddCheckErrCount(Node, Count, StrErr?) { + AddCheckErrCount(Node: CNode, Count: number, StrErr?: string) { //defiend in server.ts } DeleteBadConnectingByTimer() { @@ -837,7 +837,7 @@ export default class CConnect extends CMessages { } } } - CheckDisconnectHot(Level) { + CheckDisconnectHot(Level: number) { var CurTime = global.GetCurrentTime() - 0; var MaxCountChilds; if (Level < 3) @@ -879,7 +879,7 @@ export default class CConnect extends CMessages { } } } - SetTime(NewTime) { + SetTime(NewTime: number) { global.ToLog("Set new time: " + NewTime) if (NewTime) { global.DELTA_CURRENT_TIME = NewTime - (global.GetCurrentTime(0) - 0) @@ -889,7 +889,7 @@ export default class CConnect extends CMessages { static TIME_F() { return "{Time:uint, Sign:arr64}"; } - SendTimeDev(Node) { + SendTimeDev(Node: CNode) { if (!global.WALLET.WalletOpen) { global.ToLog("Error Wallet not open") return 0; @@ -914,7 +914,7 @@ export default class CConnect extends CMessages { } return Count; } - TIME(Info, CurTime) { + TIME(Info: SocketSendInfo, CurTime: number) { if (global.AUTO_CORRECT_TIME) { var Node = Info.Node; var Data = this.DataFromF(Info); @@ -1062,7 +1062,7 @@ export default class CConnect extends CMessages { } } } - SetNodePrioritet(Node, Prioritet) { + SetNodePrioritet(Node: CNode, Prioritet: number) { if (Node.Prioritet === Prioritet) return; if (Node.addrArr) { @@ -1075,7 +1075,7 @@ export default class CConnect extends CMessages { } Node.Prioritet = Prioritet } - AddNodeToActive(Node) { + AddNodeToActive(Node: CNode) { if (Node.addrArr) { if (global.CompareArr(Node.addrArr, this.addrArr) === 0) { return; @@ -1092,10 +1092,10 @@ export default class CConnect extends CMessages { } global.ADD_TO_STAT("AddToActive") } - DeleteNodeFromActive(Node) { + DeleteNodeFromActive(Node: CNode) { Node.Active = false if (Node.Hot) - this.StartDisconnectHot(Node, "NotActive", 1) + this.StartDisconnectHot(Node, "NotActive", true) Node.Hot = false this.ActualNodes.remove(Node) global.CloseSocket(Node.Socket, "DeleteNodeFromActive") @@ -1120,13 +1120,13 @@ export default class CConnect extends CMessages { } } } - IsLocalIP(addr) { + IsLocalIP(addr: string) { if (addr.substr(0, 7) === "192.168" || addr.substr(0, 3) === "10.") return 1; else return 0; } - GetActualsServerIP(bFlag) { + GetActualsServerIP(bFlag: boolean) { var arr = this.GetActualNodes(); var Str = ""; arr.sort(function(a, b) { @@ -1145,7 +1145,7 @@ export default class CConnect extends CMessages { } return Str.substr(0, Str.length - 2); } - AddrLevelNode(Node) { + AddrLevelNode(Node: CNode) { if (Node.GrayConnect) return global.MAX_LEVEL_SPECIALIZATION - 1; return global.AddrLevelArr(this.addrArr, Node.addrArr); @@ -1172,7 +1172,7 @@ export default class CConnect extends CMessages { } return ArrNodes; } - DeleteNodeFromHot(Node) { + DeleteNodeFromHot(Node: CNode) { if (Node.Hot) { Node.Hot = false } @@ -1188,14 +1188,14 @@ export default class CConnect extends CMessages { } } } - DeleteAllNodesFromHot(Str) { + DeleteAllNodesFromHot(Str: string) { for (var i = 0; i < this.LevelNodes.length; i++) { var arr = this.LevelNodes[i]; for (var n = 0; arr && n < arr.length; n++) { var Node = arr[n]; if (Node.Hot) { global.ADD_TO_STAT("DeleteAllNodesFromHot") - this.StartDisconnectHot(Node, Str, 1) + this.StartDisconnectHot(Node, Str, true) } } } @@ -1203,7 +1203,7 @@ export default class CConnect extends CMessages { GetTransferTree() { var HotArr = []; for (var Level = 0; Level < this.LevelNodes.length; Level++) { - var arr = this.LevelNodes[Level]; + let arr = this.LevelNodes[Level]; HotArr[Level] = [] for (var n = 0; arr && n < arr.length; n++) { var Node = arr[n]; @@ -1214,9 +1214,9 @@ export default class CConnect extends CMessages { } } } - var arr = this.NodesArr; + let arr = this.NodesArr; for (var n = 0; arr && n < arr.length; n++) { - var Node = arr[n]; + let Node = arr[n]; if (!Node) continue; if (Node.Hot) @@ -1293,7 +1293,7 @@ export default class CConnect extends CMessages { } else { this.DetectGrayMode() for (var Level = 0; Level < ArrTree.length; Level++) { - var arr = ArrTree[Level]; + let arr = ArrTree[Level]; if (!arr) continue; arr.sort(SortNodeBlockProcessCount) @@ -1301,7 +1301,7 @@ export default class CConnect extends CMessages { var WasDoHot = 0; var length = Math.min(arr.length, 10); for (var n = 0; n < length; n++) { - var Node = arr[n]; + let Node = arr[n]; var DeltaTime = CurTime - Node.StartTimeConnect; if (!Node.Active && WasDoConnect < 5 && !Node.WasAddToConnect && DeltaTime >= Node.NextConnectDelta) { global.AddNodeInfo(Node, "To connect") @@ -1324,18 +1324,18 @@ export default class CConnect extends CMessages { } } } - ValueToXOR(StrType, Str) { + ValueToXOR(StrType: string, Str: string) { var Arr1 = global.toUTF8Array(Str); var Arr2 = global.shaarr(this.CommonKey + ":" + this.addrStr + ":" + StrType); return global.WALLET.XORHash(Arr1, Arr2, 32); } - ValueFromXOR(Node, StrType, Arr1) { + ValueFromXOR(Node: CNode, StrType: string, Arr1: any) { var Arr2 = global.shaarr(this.CommonKey + ":" + Node.addrStr + ":" + StrType); var Arr = global.WALLET.XORHash(Arr1, Arr2, 32); var Str = global.Utf8ArrayToStr(Arr); return Str; } - ValueToXORDevelop(StrName, Data, Type) { + ValueToXORDevelop(StrName: string, Data: any, Type: string) { var Arr1; if (Type === "uint") { Arr1 = [] @@ -1352,7 +1352,7 @@ export default class CConnect extends CMessages { var Arr2 = global.shaarr(this.КодДляРазработчикаХекс + ":" + StrName); return global.WALLET.XORHash(Arr1, Arr2, Arr1.length); } - ValueFromXORDevelop(Node, StrName, Arr1, Type) { + ValueFromXORDevelop(Node: CNode, StrName: string, Arr1: { length: any; }, Type: string) { if (!Node.КодДляРазработчикаХекс) { Node.КодДляРазработчикаХекс = global.GetHexFromArr(global.WALLET.KeyPair.computeSecret(Node.PubKey, null)) } @@ -1370,7 +1370,7 @@ export default class CConnect extends CMessages { } }; -function SortNodeBlockProcessCount(a, b) { +function SortNodeBlockProcessCount(a: CNode, b: CNode) { if (b.BlockProcessCount !== a.BlockProcessCount) return b.BlockProcessCount - a.BlockProcessCount; if (a.DeltaTime !== b.DeltaTime) @@ -1378,7 +1378,7 @@ function SortNodeBlockProcessCount(a, b) { return a.id - b.id; }; -function SortNodeBlockProcessCountGray(a, b) { +function SortNodeBlockProcessCountGray(a: CNode, b: CNode) { if (a.StartFindList !== b.StartFindList) return a.StartFindList - b.StartFindList; if (b.BlockProcessCount !== a.BlockProcessCount) diff --git a/src/core/constant.ts b/src/core/constant.ts index e9a20ea..63197bd 100644 --- a/src/core/constant.ts +++ b/src/core/constant.ts @@ -263,7 +263,7 @@ if (global.HTTP_PORT_PASSWORD === undefined) if (global.HTTP_IP_CONNECT === undefined) global.HTTP_IP_CONNECT = ""; if (global.USE_AUTO_UPDATE === undefined) - global.USE_AUTO_UPDATE = 1; + global.USE_AUTO_UPDATE = true; if (global.USE_PARAM_JS === undefined) global.USE_PARAM_JS = 1; if (global.DATA_PATH === undefined) @@ -337,7 +337,7 @@ function InitParamsArg() { global.LOCAL_RUN = 0; break; case "NOAUTOUPDATE": - global.USE_AUTO_UPDATE = 0; + global.USE_AUTO_UPDATE = false; break; case "NOPARAMJS": global.USE_PARAM_JS = 0; diff --git a/src/core/db/block-db.ts b/src/core/db/block-db.ts index 7498ac4..68579ae 100644 --- a/src/core/db/block-db.ts +++ b/src/core/db/block-db.ts @@ -12,6 +12,7 @@ import * as fs from 'fs' import DBLib from './db' import DBRow from './db-row' +import * as crypto from 'crypto' global.BlockDB = new DBLib(); global.BLOCK_HEADER_SIZE = 150; const FILE_NAME_HEADER = "block-header"; @@ -34,17 +35,19 @@ const FILE_NAME_HEADER2 = "block-header2"; const WorkStructHeader2 = {}; const DEFAULT_DB_VERSION = 2; import CCode from '../code' +import { TeraBlock, TeraTr } from '../../interfaces/server'; +import CNode from '../node'; export default class CDB extends CCode { DBHeader100: DBRow BlockNumDB: number BlockNumDBMin: number - CurrentBlockNum - CheckOnStartComplete - UseTruncateBlockDB - MapHeader - StatMap - PrevBlockChainArr - constructor(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) { + CurrentBlockNum: number + CheckOnStartComplete: number + UseTruncateBlockDB: number + MapHeader: { [x: string]: any; } + StatMap: { [x: string]: any; StartPos: any; StartBlockNum: any; Length: any; ArrPower: any; ArrPowerMy: any; CaclBlockNum?: any; CalcMinLength?: any; } + PrevBlockChainArr: any[] + constructor(SetKeyPair: crypto.ECDH, RunIP: string, RunPort: number, UseRNDHeader: boolean, bVirtual: boolean) { super(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) var bWriteMode = (global.PROCESS_NAME === "MAIN"); global.DB_VERSION = DEFAULT_DB_VERSION @@ -70,7 +73,7 @@ export default class CDB extends CCode { this.BlockNumDBMin = StateTX.BlockNumMin } } - GetBlock(num, bToMem, bReadBody): any { + GetBlock(num: number, bToMem: boolean, bReadBody: boolean): any { //defiend in block-loader.ts(CBlock) } LoadMemBlocksOnStart() { @@ -99,20 +102,20 @@ export default class CDB extends CCode { this.ReadStateTX() var BlockNum = this.GetMaxNumBlockDB(); if (global.NO_CHECK_BLOCKNUM_ONSTART) { - this.BlockNumDB = this.CheckBlocksOnStartFoward(BlockNum - 2, 0) + this.BlockNumDB = this.CheckBlocksOnStartFoward(BlockNum - 2, false) global.ToLog("START_BLOCK_NUM:" + this.BlockNumDB, 2) return; } BlockNum = this.CheckBlocksOnStartReverse(BlockNum) - this.BlockNumDB = this.CheckBlocksOnStartFoward(BlockNum - 2000, 0) - this.BlockNumDB = this.CheckBlocksOnStartFoward(this.BlockNumDB - 100, 1) + this.BlockNumDB = this.CheckBlocksOnStartFoward(BlockNum - 2000, false) + this.BlockNumDB = this.CheckBlocksOnStartFoward(this.BlockNumDB - 100, true) if (this.BlockNumDB >= global.BLOCK_PROCESSING_LENGTH2) { this.TruncateBlockDB(this.BlockNumDB) } global.ToLog("START_BLOCK_NUM:" + this.BlockNumDB, 2) this.CheckOnStartComplete = 1 } - CheckBlocksOnStartReverse(StartNum) { + CheckBlocksOnStartReverse(StartNum: number) { var delta = 1; var Count = 0; var PrevBlock; @@ -142,7 +145,7 @@ export default class CDB extends CCode { } return 0; } - CheckBlocksOnStartFoward(StartNum, bCheckBody) { + CheckBlocksOnStartFoward(StartNum: number, bCheckBody: boolean) { var PrevBlock; if (StartNum < this.BlockNumDBMin + global.BLOCK_PROCESSING_LENGTH2) StartNum = this.BlockNumDBMin + global.BLOCK_PROCESSING_LENGTH2 @@ -198,7 +201,7 @@ export default class CDB extends CCode { } return num > 0 ? num - 1 : 0; } - WriteBlockDB(Block) { + WriteBlockDB(Block: TeraBlock) { var startTime = process.hrtime(); if (Block.TrCount === 0 && !global.IsZeroArr(Block.TreeHash)) { global.ToLogTrace("ERROR WRITE TrCount BLOCK:" + Block.BlockNum) @@ -212,7 +215,7 @@ export default class CDB extends CCode { global.ADD_TO_STAT_TIME("WriteBlockDB", startTime) return Ret; } - WriteBlockDBFinaly(Block) { + WriteBlockDBFinaly(Block: TeraBlock) { var Ret = this.WriteBlockHeaderDB(Block); if (Ret) { if (Block.TrDataLen === 0 && !global.IsZeroArr(Block.TreeHash)) { @@ -226,17 +229,17 @@ export default class CDB extends CCode { } return Ret; } - OnWriteBlock(Block) { + OnWriteBlock(Block: TeraBlock) { //defiend in transaction-validator.ts(CSmartContract) } - PreSaveDataTreeToDB(Block) { + PreSaveDataTreeToDB(Block: TeraBlock) { var Ret = this.WriteBodyDB(Block); if (Ret) { - Ret = this.WriteBlockHeaderDB(Block, 1) + Ret = this.WriteBlockHeaderDB(Block, true) } return Ret; } - WriteBodyResultDB(Block) { + WriteBodyResultDB(Block: TeraBlock) { var arrTr = Block.arrContentResult; if (Block.TrDataPos && Block.TrDataLen && Block.VersionBody && arrTr && arrTr.length) { var FileItem = global.BlockDB.OpenDBFile(FILE_NAME_BODY, 1); @@ -259,7 +262,7 @@ export default class CDB extends CCode { } return true; } - WriteBodyDB(Block) { + WriteBodyDB(Block: TeraBlock) { var FileItem = global.BlockDB.OpenDBFile(FILE_NAME_BODY, 1); var FD = FileItem.fd; var Position = FileItem.size; @@ -296,10 +299,10 @@ export default class CDB extends CCode { Block.TrDataLen = TrDataLen return true; } - CheckSeqHashDB(Block, StrError): any { + CheckSeqHashDB(Block: TeraBlock, StrError: string): any { //defiend in block-loader.ts(CBlock) } - WriteBlockHeaderDB(Block, bPreSave?) { + WriteBlockHeaderDB(Block: TeraBlock, bPreSave?: boolean) { if (!bPreSave && Block.BlockNum > this.BlockNumDBMin + global.BLOCK_PROCESSING_LENGTH2) { if (global.USE_CHECK_SAVE_DB) if (!this.CheckSeqHashDB(Block, "WriteBlockHeaderDB")) @@ -324,7 +327,7 @@ export default class CDB extends CCode { var Res = this.WriteBufHeaderToFile1(BufWrite, Block.BlockNum); return Res; } - WriteBlockHeaderToFile2(Block) { + WriteBlockHeaderToFile2(Block: TeraBlock) { var BufWrite, FileItem, written; var BlockNum = Math.trunc(Block.BlockNum); this.TruncateBufMap(BlockNum) @@ -359,7 +362,7 @@ export default class CDB extends CCode { return true; } } - WriteBufHeaderToFile1(BufWrite, BlockNum) { + WriteBufHeaderToFile1(BufWrite: Buffer, BlockNum: number) { BlockNum = Math.trunc(BlockNum) this.TruncateBufMap(BlockNum) var FileItem = global.BlockDB.OpenDBFile(FILE_NAME_HEADER, 1); @@ -376,7 +379,7 @@ export default class CDB extends CCode { return true; } } - WriteBlockHeader100(Block) { + WriteBlockHeader100(Block: TeraBlock) { return; if (Block.BlockNum % 100 !== 0) return; @@ -400,11 +403,11 @@ export default class CDB extends CCode { } this.DBHeader100.Write({ Num: Num, Hash100: Hash100, Hash: Block.Hash }) } - TruncateBlockDBInner100(LastBlock) { + TruncateBlockDBInner100(LastBlock: TeraBlock) { return; this.DBHeader100.Truncate(Math.trunc(LastBlock.BlockNum / 100)) } - ReadBlockDB(Num) { + ReadBlockDB(Num: number) { if (!Num) Num = 0 Num = Math.trunc(Num) @@ -422,7 +425,7 @@ export default class CDB extends CCode { } return Block; } - ReadBlockBodyDB(Block) { + ReadBlockBodyDB(Block: TeraBlock) { var FileItem = global.BlockDB.OpenDBFile(FILE_NAME_BODY); if (Block.TrDataLen > global.MAX_BLOCK_SIZE * 2) { global.ToLogTrace("Error value TrDataLen, BlockNum=" + Block.BlockNum) @@ -457,7 +460,7 @@ export default class CDB extends CCode { Block.TrCount = Block.arrContent.length return true; } - ReadBlockHeaderDB(BlockNum) { + ReadBlockHeaderDB(BlockNum: number) { if (global.DB_VERSION === 2) { return this.ReadBlockHeaderDB2(BlockNum); } @@ -479,7 +482,7 @@ export default class CDB extends CCode { } return Block; } - ReadBlockHeaderDB2(BlockNum) { + ReadBlockHeaderDB2(BlockNum: number) { var Block, BufRead, FileItem, bytesRead, Position; if (BlockNum < 0) { return undefined; @@ -512,14 +515,14 @@ export default class CDB extends CCode { ClearBufMap() { this.MapHeader = {} } - TruncateBufMap(BlockNum) { + TruncateBufMap(BlockNum: number) { if (BlockNum % 10000 === 0) this.ClearBufMap() else { delete this.MapHeader[BlockNum] } } - ReadBlockHeaderFromMapDB(BlockNum) { + ReadBlockHeaderFromMapDB(BlockNum: number) { var Block = this.MapHeader[BlockNum]; if (!Block) { Block = this.ReadBlockHeaderDB(BlockNum) @@ -529,7 +532,7 @@ export default class CDB extends CCode { } return Block; } - SetTruncateBlockDB(BlockNum) { + SetTruncateBlockDB(BlockNum: number) { BlockNum = Math.trunc(BlockNum) if (BlockNum < global.BLOCK_PROCESSING_LENGTH2) BlockNum = global.BLOCK_PROCESSING_LENGTH2 @@ -541,7 +544,7 @@ export default class CDB extends CCode { this.UseTruncateBlockDB = BlockNum } } - TruncateBlockDB(LastBlockNum) { + TruncateBlockDB(LastBlockNum: number) { this.UseTruncateBlockDB = undefined var Block = this.ReadBlockDB(LastBlockNum); if (!Block) { @@ -550,7 +553,7 @@ export default class CDB extends CCode { } this.WriteBlockDB(Block) } - TruncateBlockDBInner(LastBlock) { + TruncateBlockDBInner(LastBlock: TeraBlock) { var FItem1, size; if (global.DB_VERSION === 2) { FItem1 = global.BlockDB.OpenDBFile(FILE_NAME_HEADER2, 1) @@ -613,7 +616,7 @@ export default class CDB extends CCode { } return 0; } - BlockHeaderToBuf(BufWrite, Block) { + BlockHeaderToBuf(BufWrite: Buffer, Block: TeraBlock) { Block.Reserv500 = 0 var len = BufWrite.len; BufWrite.Write(Block.TreeHash, "hash") @@ -626,7 +629,7 @@ export default class CDB extends CCode { BufWrite.Write(Block.TrDataLen, "uint32") BufWrite.len = len + global.BLOCK_HEADER_SIZE } - BufToBlockHeader(BufRead, Num) { + BufToBlockHeader(BufRead: Buffer, Num: number) { var Block: any = {}; var len = BufRead.len; Block.TreeHash = BufRead.Read("hash") @@ -641,15 +644,14 @@ export default class CDB extends CCode { BufRead.len = len + global.BLOCK_HEADER_SIZE return this.PrepareBlockFields(Block, Num); } - PrepareBlockFields(Block, Num) { + PrepareBlockFields(Block: TeraBlock, Num: number) { Block.AddInfo = global.AddInfoBlock.bind(Block) Block.Info = "" Block.BlockNum = Num Block.SeqHash = this.GetSeqHash(Block.BlockNum, Block.PrevHash, Block.TreeHash) if (Block.BlockNum >= global.BLOCK_PROCESSING_LENGTH2) { global.CalcHashBlockFromSeqAddr(Block) - } - else { + } else { Block.Hash = this.GetHashGenesis(Block.BlockNum) Block.PowHash = Block.Hash } @@ -658,7 +660,7 @@ export default class CDB extends CCode { return undefined; return Block; } - GetRows(start, count, Filter, bMinerName) { + GetRows(start: number, count: number, Filter: string, bMinerName: boolean) { if (Filter) { Filter = Filter.trim() Filter = Filter.toUpperCase() @@ -709,7 +711,7 @@ export default class CDB extends CCode { } return arr; } - GetTrRows(BlockNum, start, count) { + GetTrRows(BlockNum: number, start: number, count: number) { var arr = []; var Block = this.ReadBlockDB(BlockNum); if (Block && Block.arrContent) @@ -759,7 +761,7 @@ export default class CDB extends CCode { StartPos: 0, StartBlockNum: 0, Length: 0, "ArrPower": new Float64Array(MAX_ARR_PERIOD), "ArrPowerMy": new Float64Array(MAX_ARR_PERIOD), } } - TruncateStat(LastBlockNum) { + TruncateStat(LastBlockNum: number) { if (this.StatMap) { var LastNumStat = this.StatMap.StartBlockNum + this.StatMap.Length; var Delta = LastNumStat - LastBlockNum; @@ -771,7 +773,7 @@ export default class CDB extends CCode { this.StatMap.CaclBlockNum = 0 } } - GetStatBlockchainPeriod(Param) { + GetStatBlockchainPeriod(Param: { BlockNum: any; Count: number; Miner: number; Adviser: number; bMinerLess: any; bNonce: any; }) { var StartNum = Param.BlockNum; if (!Param.Count || Param.Count < 0) Param.Count = 1000 @@ -833,7 +835,7 @@ export default class CDB extends CCode { } return { ArrList: ArrList, AvgValue: AvgValue, steptime: StepTime }; } - GetStatBlockchain(name, MinLength) { + GetStatBlockchain(name: string, MinLength: number) { if (!MinLength) return []; var MAX_ARR_PERIOD = global.MAX_STAT_PERIOD * 2 + 10; @@ -903,15 +905,15 @@ export default class CDB extends CCode { } return arr; } - GetHashGenesis(Num) { - return [Num + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Num + 1]; + GetHashGenesis(Num: number): Buffer { + return Buffer.from([Num + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Num + 1]); } - GetSeqHash(BlockNum, PrevHash, TreeHash) { + GetSeqHash(BlockNum: number, PrevHash: Buffer, TreeHash: Buffer) { var arr = [global.GetArrFromValue(BlockNum), PrevHash, TreeHash]; var SeqHash = global.CalcHashFromArray(arr, true); return SeqHash; } - CheckCreateTicketObject(Tr, BlockNum?, SetTxID?) { + CheckCreateTicketObject(Tr: TeraTr, BlockNum?: any, SetTxID?: number) { if (!Tr.HashPow && Tr.HashTicket) { Tr.num = BlockNum var FullHashTicket = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; @@ -925,7 +927,7 @@ export default class CDB extends CCode { Tr.TxID = global.GetHexFromArr(FullHashTicket.slice(0, global.TR_TICKET_HASH_LENGTH + 6)) } } - CheckCreateTransactionObject(Tr, SetTxID?, NotPrioritet?) { + CheckCreateTransactionObject(Tr: TeraTr, SetTxID?: number, NotPrioritet?: number) { if (!Tr.HashPow) { var Body = Tr.body; Tr.IsTx = 1 @@ -938,7 +940,7 @@ export default class CDB extends CCode { this.CheckCreateTicketObject(Tr, Tr.num, SetTxID) } } - BlockChainToBuf(WriteNum, StartNum, EndBlockNum) { + BlockChainToBuf(WriteNum: number, StartNum: number, EndBlockNum: number) { if (StartNum === undefined) return global.BufLib.GetNewBuffer(10); var GetLength = EndBlockNum - StartNum + 1; @@ -975,7 +977,7 @@ export default class CDB extends CCode { this.PrevBlockChainArr = arr return this.ArrHeaderToBuf(WriteNum, arr); } - ArrHeaderToBuf(StartNum, arr) { + ArrHeaderToBuf(StartNum: number, arr: any[]) { var CountSend = arr.length - global.BLOCK_PROCESSING_LENGTH2; var BufWrite; if (CountSend <= 0) { @@ -1005,7 +1007,7 @@ export default class CDB extends CCode { } }; -function AddInfo(Block, Str, BlockNumStart) { +function AddInfo(Block: TeraBlock, Str: string, BlockNumStart: number) { if (!global.STAT_MODE) return; if (!Block.Info) @@ -1019,19 +1021,19 @@ function AddInfo(Block, Str, BlockNumStart) { Block.Info += "\n" + Str; } }; -global.AddInfoChain = function(Str) { +global.AddInfoChain = function(Str: string) { if (!global.STAT_MODE) return; if (this.BlockNumStart > global.GetCurrentBlockNumByTime() - global.HISTORY_BLOCK_COUNT) AddInfo(this, Str, this.BlockNumStart); }; -global.AddInfoBlock = function(Block, Str) { +global.AddInfoBlock = function(Block: TeraBlock, Str: string) { if (!global.STAT_MODE) return; if (Block && Block.BlockNum && Block.BlockNum > global.GetCurrentBlockNumByTime() - global.HISTORY_BLOCK_COUNT) AddInfo(Block, Str, Block.BlockNum); }; -global.GetNodeStrPort = function(Node) { +global.GetNodeStrPort = function(Node: CNode) { if (!Node) return ""; if (global.LOCAL_RUN) diff --git a/src/core/library.ts b/src/core/library.ts index f12d608..6832a78 100644 --- a/src/core/library.ts +++ b/src/core/library.ts @@ -294,6 +294,12 @@ function CheckGlobalTime() { global.DELTA_CURRENT_TIME = global.DELTA_CURRENT_TIME * -1; setTimeout(() => { global.DELTA_CURRENT_TIME = global.DELTA_CURRENT_TIME * -1 + // if (!global.CAN_START) { + // global.DELTA_CURRENT_TIME = global.DELTA_CURRENT_TIME + 3000; + // setTimeout(() => { + // global.DELTA_CURRENT_TIME = global.DELTA_CURRENT_TIME - 3000; + // }, 3000) + // } }, 3000) }, 5000) global.SAVE_CONST(); diff --git a/src/core/node.ts b/src/core/node.ts index be81365..ff112b3 100644 --- a/src/core/node.ts +++ b/src/core/node.ts @@ -12,100 +12,116 @@ import "./library" import * as net from "net" import { secp256k1, RBTree } from '../core/library' +import { TeraSocket, SocketSendInfo } from "../interfaces/server"; var ConnectIDCount = 1; -export class TeraSocket extends net.Socket { - ConnectToServer: boolean; - Node: CNode; - ConnectID: string; - WasClose: number; - SocketStatus: number; - Buf: Buffer; - SocketNum: number; - SocketPrioritet: number; - HashRND: Buffer; -} + export default class CNode { - addrStr - ip - port - StartFindList - WhiteConnect - GrayConnect - POW - FirstTime - FirstTimeStr - LastTime - LastTimeError - LastTimeTransfer - FromIP - FromPort - Active - Hot - CanHot - CountChildConnect - BlockProcessCount - VersionOK - VersionNum - Delete - DeltaBan - Name - Info - PrevInfo - StartTimeHot - NextHotDelta - LastTimeGetNode - DeltaGlobTime - CountDeltaTime - DeltaTime - SumDeltaTime - TransferCount - StopGetBlock - LevelCount - LevelEnum - TimeMap - bInit - INFO - DoubleConnectCount - StartTimeConnect - NextConnectDelta - StartTimeGetNodes - NextGetNodesDelta - PingStart - NextPing - SendBlockArr - LoadBlockArr - SendBlockCount - LoadBlockCount - SendBlockCountAll - LoadBlockCountAll - WantHardTrafficArr - WantHardTraffic - CanHardTraffic - BufWriteLength - BufWrite - SendPacket: RBTree - ConnectCount - TrafficArr - SendTrafficCurrent - SendTrafficLimit - ErrCount - ErrCountAll - SendPacketNum + id: number; + addrStr: string + ip: string + port: number + StartFindList: number + WhiteConnect: number + GrayConnect: number + POW: number + FirstTime: number + FirstTimeStr: string + LastTime: number + LastTimeError: number + LastTimeTransfer: number + FromIP: any + FromPort: any + Active: boolean + Hot: boolean + CanHot: boolean + CountChildConnect: number + BlockProcessCount: number + VersionOK: boolean + VersionNum: number + Delete: number + DeltaBan: number + Name: string + Info: string + PrevInfo: string + StartTimeHot: number + NextHotDelta: number + LastTimeGetNode: number + DeltaGlobTime: number + CountDeltaTime: number + DeltaTime: number + SumDeltaTime: number + TransferCount: number + StopGetBlock: number + LevelCount: number + LevelEnum: number + TimeMap: {} + bInit: number + INFO: { + BlockNumDB?: number; + WasPing?: boolean; + LoadHistoryMode?: boolean; + portweb?: number + } + DoubleConnectCount: number + StartTimeConnect: number + NextConnectDelta: number + StartTimeGetNodes: number + NextGetNodesDelta: number + PingStart: number + NextPing: number + SendBlockArr: any[] + LoadBlockArr: any[] + SendBlockCount: number + LoadBlockCount: number + SendBlockCountAll: number + LoadBlockCountAll: number + WantHardTrafficArr: any[] + WantHardTraffic: number + CanHardTraffic: number + BufWriteLength: number + BufWrite: Buffer | Uint8Array + SendPacket: RBTree + ConnectCount: number + TrafficArr: any[] + SendTrafficCurrent: number + SendTrafficLimit: number + ErrCount: number + ErrCountAll: number + SendPacketNum: number Socket: TeraSocket Socket2: TeraSocket - ReconnectFromServer - SecretForReconnect + ReconnectFromServer: number + SecretForReconnect: any[] | Buffer Self: boolean - addrStrTemp - DoubleConnection - PubKey - addrArr - SocketStart - WaitConnectFromServer - WaitConnectIP - Prioritet - WasAddToReconnect - constructor(addrStr, ip, port) { + addrStrTemp: any + DoubleConnection: boolean + PubKey: Buffer + addrArr: any[] + SocketStart: number + WaitConnectFromServer: number + WaitConnectIP: string + Prioritet: any + WasAddToReconnect: number + WasAddToConnect: number + Level: number + SendRestGetHeader: number + TransferBlockNum: number; + CurBlockNum: number; + NoSendTx: any; + VERSIONMAX: any; + LoadHistoryMode: boolean; + portweb: number; + PingNumber: number; + DeltaTimeM: number; + Times: { Arr: number[] }; + AvgDelta: number; + IsAddrList: boolean; + КодДляРазработчикаХекс: any; + ip_arrival: string; + port_arrival: number; + TransferSize: number; + TransferBlockNumFix: number; + constructor(addrStr: string, ip: string, port: number) { this.addrStr = addrStr this.ip = ip.trim() this.port = port diff --git a/src/core/rest-loader.ts b/src/core/rest-loader.ts index 81507d2..faaec23 100644 --- a/src/core/rest-loader.ts +++ b/src/core/rest-loader.ts @@ -12,6 +12,8 @@ import CDB from './db/block-db' import { TYPE_TRANSACTION } from '../constant/account'; import { DB_FORMAT } from '../constant/db-format'; +import * as crypto from 'crypto' +import { LoadContext, ContextTask, TeraBlock, SocketSendInfo } from '../interfaces/server'; import CNode from './node'; var MIN_POW_CHAINS = 2; global.COUNT_NODE_PROOF = 6; @@ -19,44 +21,15 @@ if (global.TEST_NETWORK) { MIN_POW_CHAINS = 1; global.COUNT_NODE_PROOF = 1; } -interface ContextTask { - StartNum?: number - Count?: number - Time?: number - Node?: CNode - MapSend?: {} - OK?: boolean -} -interface LoadContext { - Mode?: number, - BlockNum?: number, - BlockNumRest?: number, - WasDelta?: number, - BlockNumProof?: number, - CountProof?: number, - StartTimeHistory?: number, - MaxTimeOut?: number, - LoopSyncRest?: number, - SendGetHeaderCount?: number, - ReceiveHeaderCount?: number, - ArrProof?: any[], - MapSend?: any, - BlockProof?, - TxProof?, - AccTaskList?: ContextTask[], - AccTaskFinished?: number, - SmartTaskList?: ContextTask[], - SmartTaskFinished?: number -} export default class CRest extends CDB { LoadRestContext: LoadContext LoadHistoryContext: LoadContext - BlockNumDB - BlockNumDBMin - UseTruncateBlockDB - ContextSendLoadToBegin - constructor(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) { + BlockNumDB: number + BlockNumDBMin: number + UseTruncateBlockDB: number + ContextSendLoadToBegin: { Time: number; MapSend: {}; BlockNum?: number; } + constructor(SetKeyPair: crypto.ECDH, RunIP: string, RunPort: number, UseRNDHeader: boolean, bVirtual: boolean) { super(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) } CheckSyncRest() { @@ -65,14 +38,11 @@ export default class CRest extends CDB { if (Delta > global.REST_START_COUNT + global.DELTA_BLOCK_ACCOUNT_HASH + 500) { var BlockNumRest = GetCurrentRestNum(global.REST_START_COUNT + global.DELTA_BLOCK_ACCOUNT_HASH + 500); if (this.BlockNumDB >= this.BlockNumDBMin && this.BlockNumDB <= this.BlockNumDBMin + global.BLOCK_PROCESSING_LENGTH2) { + } else if (BlockNumRest > this.BlockNumDB) { + } else { + this.LoadRestContext = undefined + return; } - else - if (BlockNumRest > this.BlockNumDB) { - } - else { - this.LoadRestContext = undefined - return; - } this.LoadRestContext = { Mode: 0, BlockNum: BlockNumRest, @@ -81,7 +51,7 @@ export default class CRest extends CDB { BlockNumProof: BlockNumRest + global.DELTA_BLOCK_ACCOUNT_HASH, CountProof: global.COUNT_BLOCKS_FOR_LOAD, StartTimeHistory: Date.now(), - MaxTimeOut: 600 * 1000, + MaxTimeOut: 3600 * 1000, LoopSyncRest: 1, SendGetHeaderCount: 0, ReceiveHeaderCount: 0, @@ -92,18 +62,17 @@ export default class CRest extends CDB { this.NodesArr[i].SendRestGetHeader = 0 } global.ToLog("**********START REST MODE: " + this.LoadRestContext.BlockNumProof) - } - else { + } else { this.LoadRestContext = undefined } } - GetNextNode(task, keyid, checktime?, BlockNum?): any { + GetNextNode(task, keyid: string | number, checktime?: number | boolean, BlockNum?: number): any { //defiend in block-loader.ts(CBlock) } - DataFromF(Info, bSendFormat?): any { + DataFromF(Info: SocketSendInfo, bSendFormat?: boolean): any { //defiend in block-loader.ts(CBlock) } - AddToBan(Node, Str) { + AddToBan(Node: CNode, Str: string) { //defiend in server.ts(CTransport) } LoopSyncRest() { @@ -181,7 +150,7 @@ export default class CRest extends CDB { if (global.TX_PROCESS && global.TX_PROCESS.RunRPC) { Context.Mode++ global.ToLog("Next mode: " + Context.Mode, 2) - var Block = { BlockNum: Context.BlockNumRest }; + var Block = { BlockNum: Context.BlockNumRest } as TeraBlock; this.BlockNumDB = Block.BlockNum this.BlockNumDBMin = Block.BlockNum this.WriteBlockHeaderDB(Block) @@ -435,10 +404,10 @@ export default class CRest extends CDB { break; } } - GetBlockArrFromBuffer_Load(BufRead, Info?): any { + GetBlockArrFromBuffer_Load(BufRead: Buffer, Info?: SocketSendInfo): any { //defiend in block-loader.ts(CBlock) } - RETBLOCKHEADER_REST(Info, CurTime) { + RETBLOCKHEADER_REST(Info: SocketSendInfo, CurTime: number) { if (Info.Node.SendRestGetHeader === 2) return; Info.Node.SendRestGetHeader = 2 @@ -509,7 +478,7 @@ export default class CRest extends CDB { } }; -function CheckHashSmarts(LastSumHash) { +function CheckHashSmarts(LastSumHash: Buffer) { global.DApps.Smart.Close(); var MaxNum = global.DApps.Smart.GetMaxNum(); var Item = global.DApps.Smart.DBSmart.Read(MaxNum); diff --git a/src/core/server.ts b/src/core/server.ts index c0de8dd..0964ca8 100644 --- a/src/core/server.ts +++ b/src/core/server.ts @@ -16,7 +16,8 @@ import { secp256k1, RBTree } from "./library" import "./crypto-library" import CConnect from './connect' import { STreeBuffer } from './base'; -import CNode, { TeraSocket } from './node'; +import CNode from './node'; +import { SocketSendInfo, TeraSocket } from '../interfaces/server'; const HARD_PACKET_PERIOD = 20; global.BUF_TYPE = 1; global.STR_TYPE = 2; @@ -61,26 +62,25 @@ const FORMAT_PACKET_SEND_TCP = "{\ Data:data,\ }"; export default class CTransport extends CConnect { - UseRNDHeader - BAN_IP - CanSend - SendFormatMap - ActualNodes - SendTrafficFree - LoadedPacketNum - LoadedSocketNum - LoadBufSocketList - BusyLevel - LastTimeHard - LastTimeHardOK - HardPacketForSend - MethodTiming - CurrentTimeStart - CurrentTimeValues - SendStatNum - Server - ServerSign - constructor(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) { + UseRNDHeader: any + BAN_IP: { [x: string]: { TimeTo: any; }; } + CanSend: number + SendFormatMap: { [x: string]: any; } + ActualNodes: RBTree + SendTrafficFree: number + LoadedPacketNum: number + LoadedSocketNum: number + LoadBufSocketList: RBTree + LastTimeHard: number + LastTimeHardOK: number + HardPacketForSend: RBTree + MethodTiming: { [x: string]: any; } + CurrentTimeStart: number + CurrentTimeValues: { [x: string]: any; } + SendStatNum: number + Server: net.Server + ServerSign: Buffer + constructor(SetKeyPair: crypto.ECDH, RunIP: string, RunPort: number, UseRNDHeader: boolean, bVirtual: boolean) { super(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) this.UseRNDHeader = UseRNDHeader this.BAN_IP = {} @@ -150,7 +150,7 @@ export default class CTransport extends CConnect { this.CurrentTimeValues = {} this.LoadNodesFromFile() } - GetF(Method, bSend) { + GetF(Method: string, bSend: boolean) { var name = Method + "-" + bSend; var format = this.SendFormatMap[name]; if (!format) { @@ -165,14 +165,14 @@ export default class CTransport extends CConnect { } return format; } - SendF(Node, Info, Length) { + SendF(Node: CNode, Info: SocketSendInfo, Length: number) { var format = this.GetF(Info.Method, true); if (!Length) Length = format.length Info.Data = global.BufLib.GetBufferFromObject(Info.Data, format.struct, Length, format.wrk) this.Send(Node, Info, 1) } - DataFromF(Info, bSendFormat?) { + DataFromF(Info: SocketSendInfo, bSendFormat?: boolean) { var format = this.GetF(Info.Method, bSendFormat); try { var Data = global.BufLib.GetObjectFromBuffer(Info.Data, format.struct, format.wrk); @@ -183,7 +183,7 @@ export default class CTransport extends CConnect { return {}; } } - ADD_CURRENT_STAT_TIME(Key, Value) { + ADD_CURRENT_STAT_TIME(Key: string, Value: number) { var TimeNum = Math.floor(Date.now() / global.STAT_PERIOD); if (this.CurrentTimeStart !== TimeNum) this.CurrentTimeValues = {} @@ -192,7 +192,7 @@ export default class CTransport extends CConnect { this.CurrentTimeValues[Key] = 0 this.CurrentTimeValues[Key] += Value } - GET_CURRENT_STAT_TIME(Key) { + GET_CURRENT_STAT_TIME(Key: string) { var TimeNum = Math.floor(Date.now() / global.STAT_PERIOD); if (this.CurrentTimeStart === TimeNum) { var Value = this.CurrentTimeValues[Key]; @@ -237,7 +237,7 @@ export default class CTransport extends CConnect { this.SendTrafficFree += TRAFIC_LIMIT_NODE global.ADD_TO_STAT("SEND_TRAFFIC_FREE", this.SendTrafficFree / 1024) } - OnGetMethod(Info, CurTime) { + OnGetMethod(Info: SocketSendInfo, CurTime: number) { if (global.DEBUG_MODE) { var Str = ""; if (Info.Data && Info.Data.Length) @@ -276,22 +276,21 @@ export default class CTransport extends CConnect { } return Arr; } - NodeIp(Node) { + NodeIp(Node: CNode) { if (Node.ip_arrival) { return { ip: Node.ip_arrival, port: Node.port_arrival }; - } - else { + } else { return { ip: Node.ip, port: Node.port }; } } - SetXORHeader(buf, bForce) { + SetXORHeader(buf: Buffer, bForce: boolean) { if (this.UseRNDHeader || bForce) { var HashHashSign = global.shaarr(buf.slice(buf.length - 32, buf.length)); for (var i = 0; i < 32; i++) buf[i] = HashHashSign[i] ^ buf[i] } } - WasBanIP(rinfo) { + WasBanIP(rinfo: { address: any; }) { if (!rinfo || !rinfo.address) return false; var Key = "" + rinfo.address.trim(); @@ -302,10 +301,10 @@ export default class CTransport extends CConnect { } return false; } - NodeInBan(Node) { + NodeInBan(Node: CNode) { return this.WasBanIP({ address: Node.ip }); } - DeleteNodeFromActiveByIP(ip) { + DeleteNodeFromActiveByIP(ip: string) { var Arr = this.GetActualNodes(); for (var i = 0; i < Arr.length; i++) { var Node = Arr[i]; @@ -314,7 +313,7 @@ export default class CTransport extends CConnect { } } } - AddToBan(Node, Str) { + AddToBan(Node: CNode, Str: string) { if (global.NeedRestart) return; this.DeleteNodeFromActive(Node) @@ -332,7 +331,7 @@ export default class CTransport extends CConnect { this.DeleteNodeFromActiveByIP(Node.ip) global.ADD_TO_STAT("AddToBan") } - AddToBanIP(ip, Str, Period?) { + AddToBanIP(ip: string, Str: string, Period?: number) { if (!Period) Period = 600 * 1000 var Key = "" + ip.trim(); @@ -341,7 +340,7 @@ export default class CTransport extends CConnect { global.ToLog("ADD TO BAN:: " + Key + " " + Str) global.ADD_TO_STAT("AddToBanIP") } - OnPacketTCP(Meta) { + OnPacketTCP(Meta: SocketSendInfo) { var startTime = process.hrtime(); global.ADD_TO_STAT("USEPACKET") var CurTime = global.GetCurrentTime(); @@ -357,7 +356,7 @@ export default class CTransport extends CConnect { global.ADD_TO_STAT_TIME("TIME_USE_PACKET", startTime) global.ADD_TO_STAT_TIME("MAX:TIME_USE_PACKET:" + Meta.Method, startTime) } - GetBufFromData(Method, Data, TypeData, ContextID?) { + GetBufFromData(Method: string, Data: any, TypeData: number, ContextID?: Buffer) { var BufData; if (TypeData === global.BUF_TYPE) { BufData = Data @@ -388,7 +387,7 @@ export default class CTransport extends CConnect { global.BufLib.Write(BufWrite, BufWrite.length, "uint") return BufWrite; } - GetDataFromBuf(buf) { + GetDataFromBuf(buf: Buffer) { try { var Meta = global.BufLib.GetObjectFromBuffer(buf, FORMAT_PACKET_SEND_TCP, WorkStructPacketSend); } catch (e) { @@ -406,10 +405,10 @@ export default class CTransport extends CConnect { } return Meta; } - GetHashFromData(Info) { + GetHashFromData(Info: SocketSendInfo) { return global.shaarr(Info.Method + Info.Length + "-" + (Info.NodeTime - 0)); } - OnGetFromTCP(Node: CNode, Socket: TeraSocket, Buf) { + OnGetFromTCP(Node: CNode, Socket: TeraSocket, Buf: Buffer) { if (!Node) return; if (!Node.Socket) @@ -455,7 +454,7 @@ export default class CTransport extends CConnect { break; } } - DoDataFromTCP(Socket, buf) { + DoDataFromTCP(Socket: TeraSocket, buf: Buffer) { this.LoadedPacketNum++ var Node = Socket.Node; if (!Node) @@ -513,7 +512,7 @@ export default class CTransport extends CConnect { global.ADD_TO_STAT_TIME("MAX:TIMEDOGETDATA", startTime) return 1; } - StopDoSendPacket(Param, Node, Name) { + StopDoSendPacket(Param: { Hot: any; Period: number; LowVersion: any; Hard: number; }, Node: CNode, Name: string) { var CurTime = global.GetCurrentTime(0) - 0; if (!Param) { global.ADD_TO_STAT("STOP_METHOD") @@ -575,7 +574,7 @@ export default class CTransport extends CConnect { global.ADD_TO_STAT("HARD_PACKET_PERIOD") this.DoHardPacketForSendNext() } - RiseBusyLevelByInfo(Info) { + RiseBusyLevelByInfo(Info: CNode) { if (!Info) return; if (!this.BusyLevel) @@ -585,7 +584,7 @@ export default class CTransport extends CConnect { if (this.BusyLevel <= 0) this.BusyLevel = 1 } - DropBusyLevelByInfo(Info) { + DropBusyLevelByInfo(Info: CNode) { if (!Info) return; if (this.BusyLevel > Info.BlockProcessCount) @@ -631,7 +630,7 @@ export default class CTransport extends CConnect { break; } } - Send(Node: CNode, Info, TypeData) { + Send(Node: CNode, Info: SocketSendInfo, TypeData: number) { if (!Node.Socket) { this.DeleteNodeFromActive(Node) return; @@ -644,7 +643,7 @@ export default class CTransport extends CConnect { } global.ContextPackets.SaveValue(Info.ContextID, Info.Context) } else { - Info.ContextID = [] + Info.ContextID = Buffer.alloc(0) } Node.SendPacketNum++ Info.Node = Node @@ -736,11 +735,10 @@ export default class CTransport extends CConnect { global.ADD_TO_STAT("SENDDATA(KB):" + global.NodeName(Node), Value, 1) } } - CheckPOWTicketConnect(Socket: TeraSocket, data) { + CheckPOWTicketConnect(Socket: TeraSocket, data: any) { try { var Info = global.BufLib.GetObjectFromBuffer(data, global.FORMAT_POW_TO_SERVER, {}); - } - catch (e) { + } catch (e) { this.SendCloseSocket(Socket, "FORMAT_POW_TO_SERVER") return; } @@ -786,8 +784,7 @@ export default class CTransport extends CConnect { Socket.end(this.GetBufFromData("POW_CONNEC11", "ERROR_RECONNECT", 2)) global.CloseSocket(Socket, "ERROR_RECONNECT") return; - } - else { + } else { if (power < global.MIN_POWER_POW_HANDSHAKE) { global.ToLog("END: MIN_POWER_POW_HANDSHAKE") global.AddNodeInfo(Node, "SERV: ERR MIN_POWER_POW_HANDSHAKE") @@ -927,7 +924,7 @@ export default class CTransport extends CConnect { }) this.Server.on('close', function() { }) - this.Server.on('error', function(err) { + this.Server.on('error', function(err: TeraError) { if (err.code === 'EADDRINUSE') { global.ToLogClient('Port ' + SELF.port + ' in use, retrying...') if (SELF.Server) @@ -954,12 +951,12 @@ export default class CTransport extends CConnect { let SELF = this; SELF.port = global.START_PORT_NUMBER global.ToLogClient("Prepare to run TCP server on " + global.LISTEN_IP + ":" + SELF.port) - this.Server.listen(SELF.port, global.LISTEN_IP, function() { + this.Server.listen(SELF.port as number, global.LISTEN_IP, function() { if (SELF.CanSend < 2) global.ToLogClient("Run TCP server on " + SELF.ip + ":" + SELF.port) SELF.CanSend++ var Hash = global.sha3(SELF.addrStr) - SELF.ServerSign = secp256k1.sign(Buffer.from(Hash), SELF.KeyPair.getPrivateKey('')).signature + SELF.ServerSign = secp256k1.sign(Buffer.from(Hash), SELF.KeyPair.getPrivateKey()).signature }) } FindInternetIP() { diff --git a/src/core/terahashmining.ts b/src/core/terahashmining.ts index a08ad0d..4d84684 100644 --- a/src/core/terahashmining.ts +++ b/src/core/terahashmining.ts @@ -36,9 +36,9 @@ function CreateHashMinimal(Block, MinerID) { global.WriteUint32ToArrOnPos(Block.AddrHash, PrevHashNum, 28); return true; }; -var MAX_MEMORY3 = 0, SHIFT_MASKA3; -var BufferNonce3, BufferBlockNum3; -var bWasInitVer3, bWasInitVerOK3; +var MAX_MEMORY3 = 0, SHIFT_MASKA3: number; +var BufferNonce3: Uint32Array, BufferBlockNum3: Uint32Array; +var bWasInitVer3: number, bWasInitVerOK3: number; function InitVer3(Block) { bWasInitVer3 = 1; @@ -100,7 +100,7 @@ let CreatePOWVersionX = function CreatePOWVersion3(Block, bHashPump?) { var BlockNum = Block.BlockNum; var Miner = Block.MinerID; var StartNonceRnd = DELTA_NONCE + Block.LastNonce + Math.trunc(3000000000 * Math.random()); - var List = global.GetNonceHashArr(BlockNum, Miner, StartNonceRnd, RunCount); + var List = GetNonceHashArr(BlockNum, Miner, StartNonceRnd, RunCount); for (var n = 0; n < RunCount; n++) { var Nonce = List.ArrNonce[n]; var HashNum = List.ArrHash[n] >>> SHIFT_MASKA3; @@ -188,7 +188,7 @@ function ReadIndexFromArr(arr) { value = value >>> SHIFT_MASKA3; return value; }; -global.GetNonceHashArr = function(BlockNum, Miner, StartNonceRnd, CountNonce) { +function GetNonceHashArr(BlockNum, Miner, StartNonceRnd, CountNonce) { var ArrNonce = []; var ArrHash = []; for (var n = 0; n < CountNonce; n++) { @@ -200,6 +200,7 @@ global.GetNonceHashArr = function(BlockNum, Miner, StartNonceRnd, CountNonce) { } return { ArrNonce: ArrNonce, ArrHash: ArrHash }; }; +global.GetNonceHashArr = GetNonceHashArr export { InitVer3, diff --git a/src/core/transaction-validator.ts b/src/core/transaction-validator.ts index bdf33ee..714e262 100644 --- a/src/core/transaction-validator.ts +++ b/src/core/transaction-validator.ts @@ -10,7 +10,7 @@ "use strict"; import { TYPE_TRANSACTION } from '../constant/account'; -import { RBTree } from './library'; +import * as crypto from 'crypto' import "../system/dapp" import "../system/accounts" import "../system/smart" @@ -21,14 +21,15 @@ if (global.PROCESS_NAME === "MAIN") { require("./wallet"); } import CConsensus from './block-exchange' +import { TeraRBTree, TeraBlock, TeraTr } from '../interfaces/server'; export default class CSmartContract extends CConsensus { - BufHashTree - SenderBlockHashMap - SenderMap - WasReloadSenderMapFromDB - constructor(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) { + BufHashTree: TeraRBTree + SenderBlockHashMap: { [x: string]: any; } + SenderMap: { [x: string]: any; } + WasReloadSenderMapFromDB: number + constructor(SetKeyPair: crypto.ECDH, RunIP: string, RunPort: number, UseRNDHeader: boolean, bVirtual: boolean) { super(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) - this.BufHashTree = new RBTree(global.CompareArr) + this.BufHashTree = new TeraRBTree(global.CompareArr) this.BufHashTree.LastAddNum = 0 this.SenderMap = {} this.SenderBlockHashMap = {} @@ -36,7 +37,7 @@ export default class CSmartContract extends CConsensus { setInterval(this.ClearOldSenderMapItem.bind(this), 10000) } } - AddBlockToHashTree(Block) { + AddBlockToHashTree(Block: TeraBlock) { this.BufHashTree.LastAddNum = Block.BlockNum var arr = Block.arrContent; if (arr) { @@ -46,7 +47,7 @@ export default class CSmartContract extends CConsensus { } } } - DeleteBlockFromHashTree(Block) { + DeleteBlockFromHashTree(Block: TeraBlock) { var arr = Block.arrContent; if (arr) { for (var i = 0; i < arr.length; i++) { @@ -55,12 +56,12 @@ export default class CSmartContract extends CConsensus { } } } - OnWriteBlock(Block) { + OnWriteBlock(Block: TeraBlock) { this.AddToSenderMap(Block) } - OnDelete(Block) { + OnDelete(Block: TeraBlock) { } - BlockProcessTX(Block) { + BlockProcessTX(Block: TeraBlock) { if (Block.BlockNum < 1) return; var COUNT_MEM_BLOCKS = 0; @@ -156,13 +157,13 @@ export default class CSmartContract extends CConsensus { global.DApps[key].OnWriteBlockFinish(Block) } } - BlockDeleteTX(Block) { + BlockDeleteTX(Block: TeraBlock) { this.BufHashTree.LastAddNum = 0 for (var key in global.DApps) { global.DApps[key].OnDeleteBlock(Block) } } - IsValidTicket(Tr, BlockNum) { + IsValidTicket(Tr: TeraTr, BlockNum: number) { this.CheckCreateTicketObject(Tr, BlockNum) if (Tr.power < global.MIN_POWER_POW_TR) return - 2; @@ -170,7 +171,7 @@ export default class CSmartContract extends CConsensus { return - 3; return 1; } - IsValidTransaction(Tr, BlockNum) { + IsValidTransaction(Tr: TeraTr, BlockNum: number) { if (!Tr.body || Tr.body.length < global.MIN_TRANSACTION_SIZE || Tr.body.length > global.MAX_TRANSACTION_SIZE) return - 1; this.CheckCreateTransactionObject(Tr) @@ -182,7 +183,7 @@ export default class CSmartContract extends CConsensus { return - 4; return 1; } - ReWriteDAppTransactions(Length) { + ReWriteDAppTransactions(Length: number) { if (!global.TX_PROCESS.Worker) return 0; if (!Length) @@ -200,7 +201,7 @@ export default class CSmartContract extends CConsensus { global.TX_PROCESS.RunRPC("ReWriteDAppTransactions", { StartNum: StartNum, EndNum: EndNum }) return 1; } - AddDAppTransactions(BlockNum, Arr) { + AddDAppTransactions(BlockNum: number, Arr: TeraTr[]) { if (BlockNum % global.PERIOD_ACCOUNT_HASH !== 0) return; var BlockNumHash = BlockNum - global.DELTA_BLOCK_ACCOUNT_HASH; @@ -223,17 +224,17 @@ export default class CSmartContract extends CConsensus { Arr.unshift(Tr) } } - AddTransactionOwn(Tr) { + AddTransactionOwn(Tr: TeraTr) { if (!global.TX_PROCESS.Worker) return - 6; var StrHex = global.GetHexFromArr(global.sha3(Tr.body)); global.TX_PROCESS.Worker.send({ cmd: "FindTX", TX: StrHex }) - return this.AddTransaction(Tr, 1); + return this.AddTransaction(Tr, true); } - AddTransaction(Tr, ToAll) { + AddTransaction(Tr: TeraTr, ToAll: boolean) { // transfer-msg.ts(CMessages) } - AddToSenderMap(Block) { + AddToSenderMap(Block: TeraBlock) { if (!global.START_SERVER) return; var BlockNum = Block.BlockNum; @@ -259,7 +260,7 @@ export default class CSmartContract extends CConsensus { } } } - GetSenderPrioritet(BlockNum, SenderNum) { + GetSenderPrioritet(BlockNum: number, SenderNum: number): number { if (!this.WasReloadSenderMapFromDB) this.ReloadSenderMapFromDB() if (SenderNum < 0) diff --git a/src/core/transfer-msg.ts b/src/core/transfer-msg.ts index 901f321..a5b268b 100644 --- a/src/core/transfer-msg.ts +++ b/src/core/transfer-msg.ts @@ -10,17 +10,20 @@ "use strict"; import { RBTree } from './library'; +import * as crypto from 'crypto' const MAX_MESSAGE_COUNT = 1000; import CSmartContract from './transaction-validator' +import { TeraTr, SocketSendInfo } from '../interfaces/server'; +import CNode from './node'; export default class CMessages extends CSmartContract { - MemPoolMsg - constructor(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) { + MemPoolMsg: RBTree[] + constructor(SetKeyPair: crypto.ECDH, RunIP: string, RunPort: number, UseRNDHeader: boolean, bVirtual: boolean) { super(SetKeyPair, RunIP, RunPort, UseRNDHeader, bVirtual) this.MemPoolMsg = [] for (var i = 0; i <= global.MAX_LEVEL_SPECIALIZATION; i++) this.MemPoolMsg[i] = new RBTree(global.CompareItemTimePow) } - AddMsgToQuote(Msg) { + AddMsgToQuote(Msg: TeraTr) { var Tree = this.MemPoolMsg[Msg.Level]; if (Tree) { if (Tree.insert(Msg)) { @@ -38,7 +41,7 @@ export default class CMessages extends CSmartContract { } return 0; } - IsValidMsg(Msg) { + IsValidMsg(Msg: TeraTr) { this.CheckCreateMsgHASH(Msg) if (Msg.power < global.MIN_POWER_POW_MSG) return - 1; @@ -46,7 +49,7 @@ export default class CMessages extends CSmartContract { return - 1; return 1; } - CheckCreateMsgHASH(Msg) { + CheckCreateMsgHASH(Msg: TeraTr) { if (!Msg.HashPow) { Msg.HASH = global.sha3(Msg.body) Msg.HashPow = global.GetHashWithValues(Msg.HASH, Msg.nonce, Msg.time) @@ -57,16 +60,19 @@ export default class CMessages extends CSmartContract { Msg.Level = global.MAX_LEVEL_SPECIALIZATION } } - CreateMsgFromBody(Body, ToAddr) { + CreateMsgFromBody(Body: any, ToAddr: any) { var HASH = global.sha3(Body); var Msg = { - HASH: HASH, body: Body, addrArr: ToAddr, nonce: global.CreateNoncePOWExtern(HASH, this.CurrentBlockNum, 3 * (1 << global.MIN_POWER_POW_MSG)), + HASH: HASH, + body: Body, + addrArr: ToAddr, + nonce: global.CreateNoncePOWExtern(HASH, this.CurrentBlockNum, 3 * (1 << global.MIN_POWER_POW_MSG)), time: this.CurrentBlockNum, }; this.CheckCreateMsgHASH(Msg) return Msg; } - SendMessage(Body, ToAddr) { + SendMessage(Body: any, ToAddr: any) { var Msg = this.CreateMsgFromBody(Body, ToAddr); this.SendMessageNext(Msg) } @@ -91,7 +97,7 @@ export default class CMessages extends CSmartContract { static MESSAGE_F() { return "{Arr:[{addrArr:hash,body:tr,nonce:uint,time:uint}]}"; } - MESSAGE(Info, CurTime) { + MESSAGE(Info: SocketSendInfo, CurTime: number) { var Data = this.DataFromF(Info); var arr = Data.Arr; for (var i = 0; i < arr.length; i++) { @@ -112,11 +118,11 @@ export default class CMessages extends CSmartContract { } } } - SendGetMessage(Node) { + SendGetMessage(Node: CNode) { var Context = { "SendGetMessage": 1 }; this.Send(Node, { "Method": "GETMESSAGE", "Context": Context, "Data": undefined }) } - GETMESSAGE(Info, CurTime) { + GETMESSAGE(Info: SocketSendInfo, CurTime: number) { var arr = []; var BufLength = 300; var Level = global.AddrLevelArr(this.addrArr, Info.Node.addrArr); @@ -132,7 +138,7 @@ export default class CMessages extends CSmartContract { } this.SendF(Info.Node, { "Method": "MESSAGE", "Context": Info.Context, "Data": { Arr: arr } }, BufLength) } - AddTransaction(Tr, ToAll?) { + AddTransaction(Tr: TeraTr, ToAll?: boolean) { Tr.ToAll = ToAll var Res = this.IsValidTransaction(Tr, this.CurrentBlockNum); if (Res <= 0 && Res !== - 3) @@ -168,7 +174,7 @@ export default class CMessages extends CSmartContract { ToLogContext("#1 Add " + TrName(Tr) + " for Block: " + Tr.num + " Res=" + Res) return Res; } - SendTransaction(Tr) { + SendTransaction(Tr: TeraTr) { if (!Tr.ToAll) return; var CurTime = global.GetCurrentTime(0) - 0; @@ -201,17 +207,17 @@ export default class CMessages extends CSmartContract { static TRANSACTION_F() { return "{body:tr}"; } - TRANSACTION(Info, CurTime) { + TRANSACTION(Info: SocketSendInfo, CurTime: number) { var Tr = this.DataFromF(Info); ToLogContext("Receive " + TrName(Tr) + " from " + global.NodeName(Info.Node)) - this.AddTransaction(Tr, 0) + this.AddTransaction(Tr, false) } }; -function ToLogContext(Str) { +function ToLogContext(Str: string) { }; -function TrName(Tr) { +function TrName(Tr: TeraTr) { if (!Tr.HASH) global.SERVER.CheckCreateTransactionObject(Tr); var Str = global.GetHexFromArr(Tr.HASH); diff --git a/src/global.d.ts b/src/global.d.ts index aa767fd..9f02290 100644 --- a/src/global.d.ts +++ b/src/global.d.ts @@ -5,6 +5,7 @@ import CSmartContract from './core/transaction-validator' import CConsensus from './core/block-exchange' import CTransport from './core/server' import * as BufLib from './core/buffer' +import { Comparator } from 'bintrees'; declare global { var nw: any; @@ -174,7 +175,7 @@ declare global { LISTEN_IP: string; HTTP_PORT_PASSWORD: string; HTTP_IP_CONNECT: string; - USE_AUTO_UPDATE: number; + USE_AUTO_UPDATE: boolean; USE_PARAM_JS: number; CREATE_ON_START: boolean | number; DEBUG_MODE: number; @@ -254,9 +255,9 @@ declare global { FinishTime: Function; CompareItemBufFD: Function; CompareArr33: Function; - CompareItemHashSimple: Function; + CompareItemHashSimple: Comparator; CompareItemHash: any; - CompareItemHash32: Function; + CompareItemHash32: Comparator; CompareItemHASH32: Function; CompareItemHash33: Function; CompareItemHashPow: Function; @@ -539,7 +540,7 @@ declare global { CopyObjValue: Function; CopyArr: Function; ParseNum: Function; - CompareArr: (a: any[], b: any[]) => number; + CompareArr: (a: any[] | Buffer, b: any[] | Buffer) => number; CompareArrL: Function; shaarr2: Function; sha3arr2: Function; diff --git a/src/interfaces/server.ts b/src/interfaces/server.ts new file mode 100644 index 0000000..162226b --- /dev/null +++ b/src/interfaces/server.ts @@ -0,0 +1,198 @@ +import CNode from "../core/node"; +import { RBTree } from "bintrees"; +import * as net from "net" + +export interface ContextTask { + RestartGetNextNode?: number; + LastTimeRestartGetNextNode?: number; + time?: number; + StartNum?: number + Count?: number + Time?: number + Node?: CNode + MapSend?: {} + OK?: boolean +} + +export interface LoadContext { + Mode?: number; + Node?: CNode; + BlockNum?: number; + BlockNumRest?: number; + WasDelta?: number; + BlockNumProof?: number; + CountProof?: number; + StartTimeHistory?: number; + MaxTimeOut?: number; + LoopSyncRest?: number; + SendGetHeaderCount?: number; + ReceiveHeaderCount?: number; + Foward?: number; + Pause?: number; + DeltaBlockNum?: number; + ArrProof?: any[]; + MapSend?: any; + BlockProof?: any; + TxProof?: any; + AccTaskList?: ContextTask[]; + AccTaskFinished?: number; + SmartTaskList?: ContextTask[]; + SmartTaskFinished?: number; + PrevBlockNum?: number; + time?: number; + FindCheckPoint?: boolean; + WasLoadNum?: boolean; +} + +export class TeraSocket extends net.Socket { + ConnectToServer: boolean; + Node: CNode; + ConnectID: string; + WasClose: number; + SocketStatus: number; + Buf: Buffer; + SocketNum: number; + SocketPrioritet: number; + HashRND: Buffer; +} + +export interface SocketSendInfo { + TimeNum?: number; + PacketNum?: number; + Prioritet?: number; + TypeData?: number; + ContextID?: Buffer; + NodeTime?: number; + Length?: string; + MethodTiming?: any; + Node?: CNode; + Method: string; + Context?: any; + Data?: any; + Socket?: TeraSocket; +} + +export interface TeraPOW { + SumList?: any; + MaxTree?: any; + PowLocalHash?: Buffer; + LocalAddrHash?: Buffer; + LocalSeqHash?: Buffer; + BlockNum?: number; + SeqHash?: Buffer; + AddrHash?: Buffer; + PrevHash?: Buffer; + TreeHash?: Buffer; + Hash?: Buffer; + PowHash?: Buffer; + SumPow?: number; + SumHash?: Buffer; +} + +export interface TeraJobTx { + GetCount?: number; + WasSend?: boolean; + Node?: CNode; + TreeLevel?: any; + SendCount?: any; + TransferNodes?: TeraJobTx[]; + Time?: number +} + +export interface TeraBlock { + NodeNum?: number; + TransferNodesCount?: number; + StartMining?: boolean; + Prepared?: boolean; + LevelsTransfer?: TeraJobTx[]; + Active?: boolean; + CheckMaxSum?: boolean; + CheckMaxPow?: boolean; + PowTicketTree?: RBTree; + PowTxTree?: RBTree + EndExchangeTime?: number; + JobListTX?: TeraJobTx[]; + EndExchange?: boolean; + MapSend?: any; + MaxPOW?: TeraPOW; + MaxSum?: TeraPOW; + Send?: any; + Info?: any; + AddInfo?: any; + FilePos?: number; + VersionDB?: number; + BlockNumber?: number; + SumPow?: any; + SumHash?: Buffer; + arrContent?: any; + arrContentResult?: any; + VersionBody?: number; + TrDataPos?: number; + TrCount?: number; + + SeqHash?: Buffer; + TreeHash?: Buffer; + AddrHash?: Buffer; + PrevHash?: Buffer; + PowHash?: Buffer; + Power?: number; + Hash?: Buffer; + Reserv500?: number; + + BlockNum?: number; + TrDataLen?: number; + bSave?: boolean; + + chain?: TeraChain + Context?: { Block: TeraBlock } +} + +export interface TeraTr { + ToAll?: boolean; + addrArr?: Buffer; + nonce?: number; + time?: number; + Level?: any; + NodesList?: CNode[]; + SenderNum?: number; + Prioritet?: number; + HASH?: any; + IsTx?: number; + body?: any; + HashPow?: Buffer; + HashTicket?: number[]; + num?: number; + power?: number; + TimePow?: number; + TxID?: string; +} + +export interface TeraChain { + id?: number; + arr?: any[]; + CurNumArrLoad?: number; + LoadDBFinaly?: boolean; + AddToLoad?: boolean; + BlockHead?: TeraChain; + BlockDown?: TeraChain; + Deleted?: boolean; + ParentChain?: TeraChain; + RootChain?: TeraChain; + FindBlockDB?: boolean; + StopSend?: boolean; + IsSum?: boolean; + Hash?: Buffer; + BlockNum?: number; + BlockNumStart?: number; + + WriteToDBAfterLoad?: boolean + BodyLoad?: boolean + + AddInfo?(arg0: string); + GetFindDB?(): any; + GetRootChain?(): any; +} + +export class TeraRBTree extends RBTree { + LastAddNum: number +} \ No newline at end of file diff --git a/src/process/main-process.ts b/src/process/main-process.ts index c82fedb..02f3bd2 100644 --- a/src/process/main-process.ts +++ b/src/process/main-process.ts @@ -93,7 +93,7 @@ var WebProcess: TeraProcess = { idInterval2: 0, LastAlive: Date.now(), Worker: undefined, - Path: "./process/web-process.js", + Path: "./process/web-process", OnMessage: OnMessageWeb, PeriodAlive: 10 * 1000 }; @@ -165,7 +165,7 @@ global.STATIC_PROCESS = { idInterval2: 0, LastAlive: Date.now(), Worker: undefined, - Path: "./process/static-process.js", + Path: "./process/static-process", OnMessage: OnMessageStatic, PeriodAlive: 50000 }; @@ -191,7 +191,7 @@ global.TX_PROCESS = { idInterval2: 0, LastAlive: Date.now(), Worker: undefined, - Path: "./process/tx-process.js", + Path: "./process/tx-process", OnMessage: OnMessageTX, PeriodAlive: 100 * 1000 }; @@ -661,7 +661,7 @@ function RunServer() { } } KeyPair.setPrivateKey(Buffer.from(ServerPrivKey)); - new CServer(KeyPair, global.START_IP, global.START_PORT_NUMBER, false, false); + new CServer(KeyPair, global.START_IP, global.START_PORT_NUMBER as number, false, false); DoStartFindList(); };