Skip to content

Commit a098920

Browse files
client: save private rlpx key to disk
1 parent 474c859 commit a098920

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

packages/client/lib/config.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,4 +282,11 @@ export class Config {
282282
if (option !== undefined) return option
283283
return this.chainCommon.chainName() === 'mainnet'
284284
}
285+
286+
getNetworkDir(): string {
287+
const networkDirName = this.common.chainName()
288+
const dataDir = `${this.datadir}/${networkDirName}`
289+
290+
return dataDir
291+
}
285292
}

packages/client/lib/net/server/rlpxserver.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { randomBytes } from 'crypto'
22
import { RLPx as Devp2pRLPx, Peer as Devp2pRLPxPeer, DPT as Devp2pDPT } from '@ethereumjs/devp2p'
33
import { RlpxPeer } from '../peer/rlpxpeer'
44
import { Server, ServerOptions } from './server'
5+
import fs from 'fs'
56

67
export interface RlpxServerOptions extends ServerOptions {
78
/* Local port to listen on (default: 30303) */
@@ -64,6 +65,20 @@ export class RlpxServer extends Server {
6465
constructor(options: RlpxServerOptions) {
6566
super(options)
6667

68+
if (this.key === undefined) {
69+
const dataDir = this.config.getNetworkDir()
70+
const fileName = dataDir + '/nodekey'
71+
if (fs.existsSync(fileName)) {
72+
this.key = Buffer.from(fs.readFileSync(fileName, { encoding: 'binary' }), 'binary')
73+
} else {
74+
const key = randomBytes(32)
75+
this.key = key
76+
fs.writeFileSync(fileName, key.toString('binary'), {
77+
encoding: 'binary',
78+
})
79+
}
80+
}
81+
6782
// TODO: get the external ip from the upnp service
6883
this.ip = '::'
6984
this.port = options.port ?? 30303

0 commit comments

Comments
 (0)