import * as crypto from 'crypto' ; import config from 'shared/config' ; import { SECOND } from 'core/util/const' ; import { Delegate } from 'shared/model/delegate' ; import { Timestamp } from 'shared/model/types' ; import { Slot , Slots } from 'shared/model/round' ; import { sortHashListFunc } from 'core/util/slot' ; type EpochTime = number ; class SlotService { returns { number } private beginEpochTime ( ) { return new Date ( config . CONSTANTS . EPOCH_TIME ) ; } param { number | undefined } time private getEpochTime ( time = Date . now ( ) ) { const d = this . beginEpochTime ( ) ; const t = d . getTime ( ) ; return Math . floor ( ( time - t ) / SECOND ) ; } method param { number } time return { number } public getTime ( time ? ) { return this . getEpochTime ( time ) ; } method param { number } epochTime return { number } public getRealTime ( epochTime = this . getTime ( ) ) { return this . beginEpochTime ( ) . getTime ( ) + epochTime * SECOND ; } method param { number } epochTime return { number } public getSlotNumber ( epochTime = this . getTime ( ) ) { return Math . floor ( epochTime / config . CONSTANTS . FORGING . SLOT_INTERVAL ) ; } method param { number } slot return { number } public getSlotTime ( slot ) { return slot * config . CONSTANTS . FORGING . SLOT_INTERVAL ; } public getSlotRealTime ( slot ) { const slotTime = slot * config . CONSTANTS . FORGING . SLOT_INTERVAL ; return this . getRealTime ( slotTime ) ; } public generateSlots ( blockId , delegates , firstSlotNumber ) { const hashedDelegates = delegates . map ( ( delegate ) => { const { publicKey } = delegate . account ; const hash = crypto . createHash ( 'md5' ) . update ( publicKey + blockId ) . digest ( 'hex' ) ; return { hash , generatorPublicKey : publicKey } ; } ) ; const sortedDelegates = hashedDelegates . sort ( sortHashListFunc ) ; const slots = { } ; sortedDelegates . forEach ( ( delegate , index ) => { slots [ delegate . generatorPublicKey ] = new Slot ( firstSlotNumber + index ) ; } ) ; return slots ; } public getTruncTime ( ) { return Math . floor ( this . getTime ( ) / config . CONSTANTS . FORGING . SLOT_INTERVAL ) * config . CONSTANTS . FORGING . SLOT_INTERVAL ; } } export default new SlotService ( ) ;