Skip to content
This repository was archived by the owner on Dec 10, 2020. It is now read-only.

Commit 1b226e2

Browse files
holgerd77ryanio
authored andcommitted
Added Config -> transports as the main entry point for transport configuration, made Config.servers private, new getTransportServers() method, adopted test setup
1 parent b9dbd91 commit 1b226e2

32 files changed

+217
-141
lines changed

bin/cli.ts

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
#!/usr/bin/env node
22

33
const chains = require('@ethereumjs/common/dist/chains').chains
4-
const { getLogger } = require('../lib/logging')
5-
const { parseParams, parseTransports } = require('../lib/util')
6-
const { fromName: serverFromName } = require('../lib/net/server')
4+
import { getLogger } from '../lib/logging'
5+
import { parseParams } from '../lib/util'
76
import Node from '../lib/node'
87
import { Server as RPCServer } from 'jayson'
98
import { Config } from '../lib/config'
@@ -42,7 +41,7 @@ const args = require('yargs')
4241
},
4342
transports: {
4443
describe: 'Network transports',
45-
default: ['rlpx:port=30303', 'libp2p'],
44+
default: Config.TRANSPORTS_DEFAULT,
4645
array: true,
4746
},
4847
rpc: {
@@ -128,6 +127,7 @@ async function run() {
128127
logger,
129128
syncmode: args.syncmode,
130129
lightserv: args.lightserv,
130+
transports: args.transports,
131131
minPeers: args.minPeers,
132132
maxPeers: args.maxPeers,
133133
})
@@ -136,16 +136,6 @@ async function run() {
136136
// eslint-disable-next-line @typescript-eslint/no-unused-vars
137137
const chainParams = args.params ? await parseParams(args.params) : args.network
138138

139-
const servers = parseTransports(args.transports).map((t: any) => {
140-
const Server = serverFromName(t.name)
141-
if (t.name === 'rlpx') {
142-
t.options.bootnodes = t.options.bootnodes || config.common.bootstrapNodes()
143-
}
144-
return new Server({ config, ...t.options })
145-
})
146-
147-
config.servers = servers
148-
149139
const syncDataDir = config.getSyncDataDirectory()
150140
fs.ensureDirSync(syncDataDir)
151141
logger.info(`Sync data directory: ${syncDataDir}`)

lib/config.ts

Lines changed: 49 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@ import Common from '@ethereumjs/common'
33
import { Logger } from 'winston'
44
import { defaultLogger } from './logging'
55
import { Libp2pServer, RlpxServer } from './net/server'
6+
import { parseTransports } from './util'
67

78
export interface Options {
89
/**
910
* Specify the chain and hardfork by passing a Common instance.
1011
*
11-
* Default: chain `mainnet` and hardfork `chainstart`
12+
* Default: chain 'mainnet' and hardfork 'chainstart'
1213
*/
1314
common?: Common
1415
/**
@@ -17,12 +18,6 @@ export interface Options {
1718
* Default: Logger with loglevel 'debug'
1819
*/
1920
logger?: Logger
20-
/**
21-
* Transport servers (RLPx or Libp2p)
22-
*
23-
* Default: []
24-
*/
25-
servers?: (RlpxServer | Libp2pServer)[]
2621
/**
2722
* Synchronization mode ('fast' or 'light')
2823
*
@@ -32,45 +27,60 @@ export interface Options {
3227
/**
3328
* Serve light peer requests
3429
*
35-
* Default: false
30+
* Default: `false`
3631
*/
3732
lightserv?: boolean
3833
/**
3934
* Root data directory for the blockchain
4035
*/
4136
datadir?: string
37+
/**
38+
* Network transports ('rlpx' and/or 'libp2p')
39+
*
40+
* Default: `['rlpx:port=30303', 'libp2p']`
41+
*/
42+
transports?: string[]
43+
/**
44+
* Transport servers (RLPx or Libp2p)
45+
* Use `transports` option, only used for testing purposes
46+
*
47+
* Default: servers created from `transports` option
48+
*/
49+
servers?: (RlpxServer | Libp2pServer)[]
4250
/**
4351
* Number of peers needed before syncing
4452
*
45-
* Default: 2
53+
* Default: `2`
4654
*/
4755
minPeers?: number
4856
/**
4957
* Maximum peers allowed
5058
*
51-
* Default: 25
59+
* Default: `25`
5260
*/
5361
maxPeers?: number
5462
}
5563

5664
export class Config {
65+
public static readonly COMMON_DEFAULT = new Common({ chain: 'mainnet', hardfork: 'chainstart' })
66+
public static readonly LOGGER_DEFAULT = defaultLogger
67+
public static readonly SYNCMODE_DEFAULT = 'fast'
68+
public static readonly LIGHTSERV_DEFAULT = false
69+
public static readonly DATADIR_DEFAULT = `${os.homedir()}/Library/Ethereum`
70+
public static readonly TRANSPORTS_DEFAULT = ['rlpx:port=30303', 'libp2p']
71+
public static readonly MINPEERS_DEFAULT = 2
72+
public static readonly MAXPEERS_DEFAULT = 25
73+
5774
public common: Common
5875
public logger: Logger
59-
public servers: (RlpxServer | Libp2pServer)[]
6076
public syncmode: string
6177
public lightserv: boolean
6278
public datadir: string
79+
public transports: string[]
6380
public minPeers: number
6481
public maxPeers: number
6582

66-
public static readonly COMMON_DEFAULT = new Common({ chain: 'mainnet', hardfork: 'chainstart' })
67-
public static readonly LOGGER_DEFAULT = defaultLogger
68-
public static readonly SERVERS_DEFAULT = []
69-
public static readonly SYNCMODE_DEFAULT = 'fast'
70-
public static readonly LIGHTSERV_DEFAULT = false
71-
public static readonly DATADIR_DEFAULT = `${os.homedir()}/Library/Ethereum`
72-
public static readonly MINPEERS_DEFAULT = 2
73-
public static readonly MAXPEERS_DEFAULT = 25
83+
private servers: (RlpxServer | Libp2pServer)[] = []
7484

7585
constructor(options: Options = {}) {
7686
// Initialize Common with an explicit 'chainstart' HF set until
@@ -80,12 +90,14 @@ export class Config {
8090
// TODO: map chainParams (and lib/util.parseParams) to new Common format
8191
this.common = options.common ?? Config.COMMON_DEFAULT
8292
this.logger = options.logger ?? Config.LOGGER_DEFAULT
83-
this.servers = options.servers ?? Config.SERVERS_DEFAULT
8493
this.syncmode = options.syncmode ?? Config.SYNCMODE_DEFAULT
8594
this.lightserv = options.lightserv ?? Config.LIGHTSERV_DEFAULT
95+
this.transports = options.transports ?? Config.TRANSPORTS_DEFAULT
8696
this.datadir = options.datadir ?? Config.DATADIR_DEFAULT
8797
this.minPeers = options.minPeers ?? Config.MINPEERS_DEFAULT
8898
this.maxPeers = options.maxPeers ?? Config.MAXPEERS_DEFAULT
99+
100+
this.servers = options.servers ? options.servers : this.getTransportServers()
89101
}
90102

91103
/**
@@ -100,4 +112,21 @@ export class Config {
100112
const dataDir = `${this.datadir}/${networkDirName}ethereumjs/${syncDirName}`
101113
return dataDir
102114
}
115+
116+
/**
117+
* Returns the transport servers created from the `transports` option
118+
*/
119+
getTransportServers(): (RlpxServer | Libp2pServer)[] {
120+
if (this.servers.length === 0) {
121+
this.servers = parseTransports(this.transports).map((t) => {
122+
if (t.name === 'rlpx') {
123+
t.options.bootnodes = t.options.bootnodes || this.common.bootstrapNodes()
124+
return new RlpxServer({ config: this, ...t.options })
125+
} else {
126+
return new Libp2pServer({ config: this, ...t.options })
127+
}
128+
})
129+
}
130+
return this.servers
131+
}
103132
}

lib/net/peerpool.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,11 @@ export class PeerPool extends EventEmitter {
5555
if (this.opened) {
5656
return false
5757
}
58-
this.config.servers.map((server) => {
59-
server.on('connected', (peer: Peer) => {
58+
this.config.getTransportServers().map((s) => {
59+
s.on('connected', (peer: Peer) => {
6060
this.connected(peer)
6161
})
62-
server.on('disconnected', (peer: Peer) => {
62+
s.on('disconnected', (peer: Peer) => {
6363
this.disconnected(peer)
6464
})
6565
})
@@ -196,7 +196,7 @@ export class PeerPool extends EventEmitter {
196196
if (this.size === 0) {
197197
this.noPeerPeriods += 1
198198
if (this.noPeerPeriods >= 3) {
199-
const promises = this.config.servers.map(async (server: any) => {
199+
const promises = this.config.getTransportServers().map(async (server: any) => {
200200
if (server.bootstrap) {
201201
this.config.logger.info('Retriggering bootstrap.')
202202
await server.bootstrap()

lib/net/server/index.ts

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,6 @@ export { Server } from './server'
22
export { RlpxServer } from './rlpxserver'
33
export { Libp2pServer } from './libp2pserver'
44

5-
import { RlpxServer } from './rlpxserver'
6-
import { Libp2pServer } from './libp2pserver'
7-
85
/**
96
* @module net/server
107
*/
11-
12-
const servers: any = {
13-
rlpx: RlpxServer,
14-
libp2p: Libp2pServer,
15-
}
16-
17-
export const fromName = function (name: string) {
18-
return servers[name]
19-
}

lib/service/service.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ export class Service extends events.EventEmitter {
6969
return false
7070
}
7171
const protocols = this.protocols
72-
this.config.servers.map((s) => s.addProtocols(protocols))
72+
this.config.getTransportServers().map((s) => s.addProtocols(protocols))
7373
if (this.pool) {
7474
this.pool.on('banned', (peer: Peer) => this.config.logger.debug(`Peer banned: ${peer}`))
7575
this.pool.on('error', (error: Error) => this.emit('error', error))
@@ -100,7 +100,7 @@ export class Service extends events.EventEmitter {
100100
if (this.running) {
101101
return false
102102
}
103-
await Promise.all(this.config.servers.map((s) => s.start()))
103+
await Promise.all(this.config.getTransportServers().map((s) => s.start()))
104104
this.running = true
105105
this.config.logger.info(`Started ${this.name} service.`)
106106
}

lib/util/parse.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ export function parseBootnodes(string: string) {
2121
}
2222
}
2323

24-
export function parseTransports(transports: any[]) {
24+
export function parseTransports(transports: string[]) {
2525
return transports.map((t) => {
2626
const options: any = {}
2727
const [name, ...pairs] = t.split(':')

test/integration/fastethereumservice.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ tape('[Integration:FastEthereumService]', async (t) => {
1212
const server = new MockServer()
1313
const chain = new MockChain()
1414
const service = new FastEthereumService({
15-
//@ts-ignore
15+
//@ts-ignore allow Config instantiation with MockServer
1616
config: new Config({ servers: [server], lightserv: true }),
1717
chain,
1818
})

test/integration/fastsync.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,10 @@ tape('[Integration:FastSync]', async (t) => {
1414
async function setup(options: any = {}): Promise<any[]> {
1515
const server = new MockServer({ location: options.location })
1616
const chain = new MockChain({ height: options.height })
17+
//@ts-ignore allow Config instantiation with MockServer
18+
const config = new Config({ servers: [server], minPeers: 1 })
1719
const service = new FastEthereumService({
18-
//@ts-ignore allow Config instantiation with MockServer
19-
config: new Config({ servers: [server], minPeers: 1 }),
20+
config,
2021
interval: options.interval || 10,
2122
timeout: 500,
2223
chain,

test/integration/lightethereumservice.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,9 @@ tape('[Integration:LightEthereumService]', async (t) => {
1010
async function setup() {
1111
const server = new MockServer()
1212
const chain = new MockChain()
13-
const service = new LightEthereumService({
14-
//@ts-ignore allow Config instantiation with MockServer
15-
config: new Config({ servers: [server] }),
16-
chain,
17-
})
13+
//@ts-ignore allow Config instantiation with MockServer
14+
const config = new Config({ servers: [server] })
15+
const service = new LightEthereumService({ config, chain })
1816
await service.open()
1917
await server.start()
2018
await service.start()

test/integration/mocks/mockchain.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export default class MockChain extends Chain {
1111
public height: any
1212

1313
constructor(options: any = {}) {
14-
super({ config: new Config(), ...options })
14+
super({ config: new Config({ transports: [] }), ...options })
1515
options = { ...defaultOptions, ...options }
1616
this.height = options.height
1717
}

0 commit comments

Comments
 (0)