Skip to content

Commit

Permalink
Merge pull request #145 from ethereumjs/typescript-transition-exports
Browse files Browse the repository at this point in the history
Typescript transition: ES6 import / export syntax
  • Loading branch information
holgerd77 authored Oct 7, 2020
2 parents dd25563 + 7010afa commit 53f65e8
Show file tree
Hide file tree
Showing 103 changed files with 1,213 additions and 1,188 deletions.
6 changes: 6 additions & 0 deletions .nycrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"extends": "@ethereumjs/config-nyc",
"include": [
"lib/**/*.ts"
]
}
10 changes: 5 additions & 5 deletions bin/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
const Common = require('ethereumjs-common').default
const chains = require('ethereumjs-common/dist/chains').chains
const { getLogger } = require('../lib/logging')
const { parse } = require('../lib/util')
const { parseParams, parseTransports } = require('../lib/util')
const { fromName: serverFromName } = require('../lib/net/server')
const EthereumNode = require('../lib/node')
import Node from '../lib/node'
import { Server as RPCServer } from 'jayson'
const RPCManager = require('../lib/rpc')
const level = require('level')
Expand Down Expand Up @@ -88,7 +88,7 @@ async function runNode (options: any) {
if (options.lightserv) {
logger.info(`Serving light peer requests`)
}
const node = new EthereumNode(options)
const node = new Node(options)
node.on('error', (err: any) => logger.error(err))
node.on('listening', (details: any) => {
logger.info(`Listener up transport=${details.transport} url=${details.url}`)
Expand Down Expand Up @@ -124,12 +124,12 @@ async function run () {
}
}
const networkDirName = args.network === 'mainnet' ? '' : `${args.network}/`
const chainParams = args.params ? await parse.params(args.params) : args.network
const chainParams = args.params ? await parseParams(args.params) : args.network
// Initialize Common with an explicit 'chainstart' HF set until
// hardfork awareness is implemented within the library
// Also a fix for https://github.com/ethereumjs/ethereumjs-vm/issues/757
const common = new Common(chainParams, 'chainstart')
const servers = parse.transports(args.transports).map((t: any) => {
const servers = parseTransports(args.transports).map((t: any) => {
const Server = serverFromName(t.name)
if (t.name === 'rlpx') {
t.options.bootnodes = t.options.bootnodes || common.bootstrapNodes()
Expand Down
92 changes: 39 additions & 53 deletions lib/blockchain/chain.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const { EventEmitter } = require('events')
import * as events from 'events'
import Common from 'ethereumjs-common'
const Block = require('ethereumjs-block')
const Blockchain = require('ethereumjs-blockchain')
import Blockchain from 'ethereumjs-blockchain'
import { BN } from 'ethereumjs-util'
const { defaultLogger } = require('../logging')
import { defaultLogger } from '../logging'
const promisify = require('util-promisify')

const defaultOptions = {
Expand All @@ -15,14 +15,14 @@ const defaultOptions = {
* Blockchain
* @memberof module:blockchain
*/
export = module.exports = class Chain extends EventEmitter {
export class Chain extends events.EventEmitter {

private logger: any
private common: Common
private db: any
private blockchain: any
public logger: any
public common: Common
public db: any
public blockchain: Blockchain

private opened = false
public opened = false

private _headers = {}
private _blocks = {}
Expand All @@ -42,7 +42,7 @@ export = module.exports = class Chain extends EventEmitter {
* @param {Common} [options.common] common parameters
* @param {Logger} [options.logger] Logger instance
*/
constructor (options: any) {
constructor (options?: any) {
super()
options = { ...defaultOptions, ...options }

Expand Down Expand Up @@ -84,17 +84,15 @@ export = module.exports = class Chain extends EventEmitter {

/**
* Network ID
* @type {number}
*/
get networkId () {
get networkId (): number {
return this.common.networkId()
}

/**
* Genesis block parameters
* @type {Object}
*/
get genesis () {
get genesis (): object {
const genesis = this.common.genesis()
Object.entries(genesis).forEach(([k, v]) => { genesis[k] = hexToBuffer(v as string) })
return genesis
Expand All @@ -104,27 +102,24 @@ export = module.exports = class Chain extends EventEmitter {
* Returns properties of the canonical headerchain. The ``latest`` property is
* the latest header in the chain, the ``td`` property is the total difficulty of
* headerchain, and the ``height`` is the height of the headerchain.
* @type {Object}
*/
get headers () {
get headers (): object {
return { ...this._headers }
}

/**
* Returns properties of the canonical blockchain. The ``latest`` property is
* the latest block in the chain, the ``td`` property is the total difficulty of
* blockchain, and the ``height`` is the height of the blockchain.
* @type {Object}
*/
get blocks () {
get blocks (): object {
return { ...this._blocks }
}

/**
* Open blockchain and wait for database to load
* @return {Promise}
*/
async open () {
async open (): Promise<boolean | void> {
if (this.opened) {
return false
}
Expand All @@ -136,9 +131,8 @@ export = module.exports = class Chain extends EventEmitter {

/**
* Close blockchain and database
* @return {Promise}
*/
async close () {
async close (): Promise<boolean | void> {
if (!this.opened) {
return false
}
Expand All @@ -151,20 +145,18 @@ export = module.exports = class Chain extends EventEmitter {
* Update blockchain properties (latest block, td, height, etc...)
* @return {Promise}
*/
async update () {
async update (): Promise<boolean | void> {
if (!this.opened) {
return false
}
const headers: any = {}
const blocks: any = {}
await Promise.all([
this.getLatestHeader(),
this.getLatestBlock()
]).then(latest => { [headers.latest, blocks.latest] = latest })
await Promise.all([
this.getTd(headers.latest.hash()),
this.getTd(blocks.latest.hash())
]).then(td => { [headers.td, blocks.td] = td })
headers.latest = await this.getLatestHeader()
blocks.latest = await this.getLatestBlock()

headers.td = await this.getTd(headers.latest.hash())
blocks.td = await this.getTd(blocks.latest.hash())

headers.height = new BN(headers.latest.number)
blocks.height = new BN(blocks.latest.header.number)
this._headers = headers
Expand All @@ -178,41 +170,38 @@ export = module.exports = class Chain extends EventEmitter {
* @param max maximum number of blocks to get
* @param skip number of blocks to skip
* @param reverse get blocks in reverse
* @return {Promise}
*/
async getBlocks (block: Buffer | BN, max: number, skip: number, reverse: boolean) {
async getBlocks (block: Buffer | BN, max: number, skip: number, reverse: boolean): Promise<any[]> {
if (!this.opened) {
await this.open()
}
if (!this._getBlocks) {
this._getBlocks = promisify(this.blockchain.getBlocks.bind(this.blockchain))
}
return (this._getBlocks as Function)(block, max, skip, reverse)
return await (this._getBlocks as Function)(block, max, skip, reverse)
}

/**
* Gets a block by its hash or number
* @param blocks block hash or number
* @return {Promise}
*/
async getBlock (block: Buffer | BN) {
async getBlock (block: Buffer | BN): Promise<any> {
if (!this.opened) {
await this.open()
}
if (!this._getBlock) {
this._getBlock = promisify(this.blockchain.getBlock.bind(this.blockchain))
}

return (this._getBlock as Function)(block)
return await (this._getBlock as Function)(block)
}

/**
* Insert new blocks into blockchain
* @method putBlocks
* @param {Block[]} blocks list of blocks to add
* @return {Promise}
*/
async putBlocks (blocks: object[]) {
async putBlocks (blocks: object[]): Promise<void> {
if (!this.opened) {
await this.open()
}
Expand All @@ -233,9 +222,8 @@ export = module.exports = class Chain extends EventEmitter {
* @param max maximum number of headers to get
* @param skip number of headers to skip
* @param reverse get headers in reverse
* @return {Promise}
*/
async getHeaders (block: Buffer | BN, max: number, skip: number, reverse: boolean) {
async getHeaders (block: Buffer | BN, max: number, skip: number, reverse: boolean): Promise<any[]> {
const blocks = await this.getBlocks(block, max, skip, reverse)
return blocks.map((b: any) => b.header)
}
Expand All @@ -244,9 +232,8 @@ export = module.exports = class Chain extends EventEmitter {
* Insert new headers into blockchain
* @method putHeaders
* @param headers list of headers to add
* @return {Promise}
*/
async putHeaders (headers: object[]) {
async putHeaders (headers: object[]): Promise<void> {
if (!this.opened) {
await this.open()
}
Expand All @@ -263,49 +250,48 @@ export = module.exports = class Chain extends EventEmitter {

/**
* Gets the latest header in the canonical chain
* @return {Promise}
*/
async getLatestHeader () {
async getLatestHeader (): Promise<any> {
if (!this.opened) {
await this.open()
}
if (!this._getLatestHeader) {
this._getLatestHeader = promisify(this.blockchain.getLatestHeader.bind(this.blockchain))
}
return (this._getLatestHeader as Function)()
const result: any = await (this._getLatestHeader as Function)()
return result
}

/**
* Gets the latest block in the canonical chain
* @return {Promise}
*/
async getLatestBlock () {
async getLatestBlock (): Promise<any> {
if (!this.opened) {
await this.open()
}
if (!this._getLatestBlock) {
this._getLatestBlock = promisify(this.blockchain.getLatestBlock.bind(this.blockchain))
}
return (this._getLatestBlock as Function)()
const result: any = await (this._getLatestBlock as Function)()
return result
}

/**
* Gets total difficulty for a block
* @param hash block hash
* @return {Promise}
*/
async getTd (hash: Buffer) {
async getTd (hash: Buffer): Promise<any> {
if (!this.opened) {
await this.open()
}
if (!this._getTd) {
this._getTd = promisify(this.blockchain._getTd.bind(this.blockchain))
}
return (this._getTd as Function)(hash)
return await (this._getTd as Function)(hash)
}
}

function hexToBuffer (hexString: string) {
function hexToBuffer (hexString: string): Buffer | string {
if (typeof (hexString) === 'string' && hexString.startsWith('0x')) {
return Buffer.from(hexString.slice(2), 'hex')
}
Expand Down
3 changes: 1 addition & 2 deletions lib/blockchain/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@
* @module blockchain
*/

exports.Chain = require('./chain')
export = exports
export * from './chain'
15 changes: 6 additions & 9 deletions lib/logging.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const chalk = require('chalk')
const winston = require('winston')
const { createLogger, format, transports } = winston
import chalk, { ColorSupport } from 'chalk'
import { createLogger, format, transports } from 'winston'
const { combine, timestamp, label, printf } = format

const levelColors: any = {
Expand All @@ -22,15 +21,16 @@ const errorFormat = format((info: any) => {

function logFormat () {
return printf((info: any) => {
const color = chalk[levelColors[info.level]].bind(chalk)
// @ts-ignore: implicitly has an 'any' TODO
const color = (chalk[levelColors[info.level]]).bind(chalk)
const level = color(info.level.toUpperCase())
const re = /(\w+)=(.+?)(?:\s|$)/g
info.message = info.message.replace(re, (_: any, tag: string, char: string) => `${color(tag)}=${char} `)
return `${level} [${info.timestamp}] ${info.message}`
})
}

function getLogger (options = { loglevel: 'info' }) {
export function getLogger (options = { loglevel: 'info' }) {
const logger = createLogger({
format: combine(
errorFormat(),
Expand All @@ -50,7 +50,4 @@ function getLogger (options = { loglevel: 'info' }) {
return logger
}

exports.defaultLogger = getLogger({ loglevel: 'debug' })
exports.getLogger = getLogger

export = exports
export const defaultLogger = getLogger({ loglevel: 'debug' });
10 changes: 4 additions & 6 deletions lib/net/peer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
* @module net/peer
*/

exports.Peer = require('./peer')
exports.RlpxPeer = require('./rlpxpeer')
exports.Libp2pPeer = require('./libp2ppeer')
exports.Libp2pNode = require('./libp2pnode')

export = exports
export * from './peer'
export * from './rlpxpeer'
export * from './libp2ppeer'
export * from './libp2pnode'
Loading

0 comments on commit 53f65e8

Please sign in to comment.