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

Commit

Permalink
upgrade deps (config 2.0, monorepo betas, typedoc)
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanio committed Oct 27, 2020
1 parent a4393ac commit ce4d733
Show file tree
Hide file tree
Showing 34 changed files with 339 additions and 351 deletions.
10 changes: 10 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = {
extends: '@ethereumjs/eslint-config-defaults',
parserOptions: {
project: ['./tsconfig.json']
},
rules: {
'@typescript-eslint/no-floating-promises': 'off',
'no-redeclare': 'off'
}
}
2 changes: 1 addition & 1 deletion .nycrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"extends": "@ethereumjs/config-nyc"
"extends": "@ethereumjs/config-coverage"
}
1 change: 0 additions & 1 deletion definitions/Header.d.ts

This file was deleted.

27 changes: 0 additions & 27 deletions definitions/ethereumjs-block.d.ts

This file was deleted.

2 changes: 0 additions & 2 deletions definitions/keccak.d.ts

This file was deleted.

3 changes: 0 additions & 3 deletions definitions/rlp-encoding.d.ts

This file was deleted.

93 changes: 46 additions & 47 deletions examples/peer-communication-les.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
import * as devp2p from '../src/index'
import { LES, Peer } from '../src/index'
import Tx from 'ethereumjs-tx'
import Block from 'ethereumjs-block'
import Common from '@ethereumjs/common'
import { Transaction } from '@ethereumjs/tx'
import { Block, BlockHeader } from '@ethereumjs/block'
import ms from 'ms'
import chalk from 'chalk'
import assert from 'assert'
import { randomBytes } from 'crypto'

type Header = Block.Header

const PRIVATE_KEY = randomBytes(32)

const CHAIN_ID = 4 // Rinkeby
const GENESIS_TD = 1
const GENESIS_HASH = Buffer.from(
'6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177',
'hex',
'hex'
)

const Common = require('ethereumjs-common').default
const config = new Common('mainnet')
const config = new Common({ chain: 'mainnet' })
const bootstrapNodes = config.bootstrapNodes()
const BOOTNODES = bootstrapNodes
.filter((node: any) => {
Expand All @@ -29,7 +27,7 @@ const BOOTNODES = bootstrapNodes
return {
address: node.ip,
udpPort: node.port,
tcpPort: node.port,
tcpPort: node.port
}
})
const REMOTE_CLIENTID_FILTER = [
Expand All @@ -42,7 +40,7 @@ const REMOTE_CLIENTID_FILTER = [
'ubiq',
'gmc',
'gwhale',
'prichain',
'prichain'
]

const getPeerAddr = (peer: Peer) => `${peer._socket.remoteAddress}:${peer._socket.remotePort}`
Expand All @@ -53,76 +51,82 @@ const dpt = new devp2p.DPT(PRIVATE_KEY, {
endpoint: {
address: '0.0.0.0',
udpPort: null,
tcpPort: null,
},
tcpPort: null
}
})

/* eslint-disable no-console */
dpt.on('error', err => console.error(chalk.red(`DPT error: ${err}`)))

/* eslint-disable @typescript-eslint/no-use-before-define */

// RLPx
const rlpx = new devp2p.RLPx(PRIVATE_KEY, {
dpt: dpt,
maxPeers: 25,
capabilities: [devp2p.LES.les2],
remoteClientIdFilter: REMOTE_CLIENTID_FILTER,
listenPort: null,
listenPort: null
})

rlpx.on('error', err => console.error(chalk.red(`RLPx error: ${err.stack || err}`)))

rlpx.on('peer:added', peer => {
const addr = getPeerAddr(peer)
const les = peer.getProtocols()[0]
const requests: { headers: Header[]; bodies: any[] } = { headers: [], bodies: [] }
const requests: { headers: BlockHeader[]; bodies: any[] } = { headers: [], bodies: [] }

const clientId = peer.getHelloMessage().clientId
console.log(
chalk.green(
`Add peer: ${addr} ${clientId} (les${les.getVersion()}) (total: ${rlpx.getPeers().length})`,
),
`Add peer: ${addr} ${clientId} (les${les.getVersion()}) (total: ${rlpx.getPeers().length})`
)
)

les.sendStatus({
networkId: CHAIN_ID,
headTd: devp2p.int2buffer(GENESIS_TD),
headHash: GENESIS_HASH,
headNum: Buffer.from([]),
genesisHash: GENESIS_HASH,
genesisHash: GENESIS_HASH
})

les.once('status', (status: LES.Status) => {
let msg = [devp2p.buffer2int(status['headNum']), 1, 0, 1]
const msg = [devp2p.buffer2int(status['headNum']), 1, 0, 1]
les.sendMessage(devp2p.LES.MESSAGE_CODES.GET_BLOCK_HEADERS, 1, msg)
})

les.on('message', async (code: LES.MESSAGE_CODES, payload: any) => {
switch (code) {
case devp2p.LES.MESSAGE_CODES.BLOCK_HEADERS:
case devp2p.LES.MESSAGE_CODES.BLOCK_HEADERS: {
if (payload[2].length > 1) {
console.log(
`${addr} not more than one block header expected (received: ${payload[2].length})`,
`${addr} not more than one block header expected (received: ${payload[2].length})`
)
break
}
let header: Block.Header = new Block.Header(payload[2][0])
const header = BlockHeader.fromValuesArray(payload[2][0], {})

setTimeout(() => {
les.sendMessage(devp2p.LES.MESSAGE_CODES.GET_BLOCK_BODIES, 2, [header.hash()])
requests.bodies.push(header)
}, ms('0.1s'))
break
}

case devp2p.LES.MESSAGE_CODES.BLOCK_BODIES:
case devp2p.LES.MESSAGE_CODES.BLOCK_BODIES: {
if (payload[2].length !== 1) {
console.log(
`${addr} not more than one block body expected (received: ${payload[2].length})`,
`${addr} not more than one block body expected (received: ${payload[2].length})`
)
break
}

let header2 = requests.bodies.shift()
let block = new Block([header2.raw, payload[2][0][0], payload[2][0][1]])
let isValid = await isValidBlock(block)
const header2 = requests.bodies.shift()
const txs = payload[2][0][0]
const uncleHeaders = payload[2][0][1]
const block = Block.fromValuesArray([header2.raw(), txs, uncleHeaders])
const isValid = await isValidBlock(block)
let isValidPayload = false
if (isValid) {
isValidPayload = true
Expand All @@ -134,6 +138,7 @@ rlpx.on('peer:added', peer => {
console.log(`${addr} received wrong block body`)
}
break
}
}
})
})
Expand All @@ -144,9 +149,9 @@ rlpx.on('peer:removed', (peer, reasonCode, disconnectWe) => {
console.log(
chalk.yellow(
`Remove peer: ${getPeerAddr(peer)} - ${who}, reason: ${peer.getDisconnectPrefix(
reasonCode,
)} (${String(reasonCode)}) (total: ${total})`,
),
reasonCode
)} (${String(reasonCode)}) (total: ${total})`
)
)
})

Expand All @@ -168,7 +173,7 @@ rlpx.on('peer:error', (peer, err) => {
// rlpx.listen(30303, '0.0.0.0')
// dpt.bind(30303, '0.0.0.0')

for (let bootnode of BOOTNODES) {
for (const bootnode of BOOTNODES) {
dpt.bootstrap(bootnode).catch(err => {
console.error(chalk.bold.red(`DPT bootstrap error: ${err.stack || err}`))
})
Expand All @@ -188,33 +193,27 @@ dpt.addPeer({ address: '127.0.0.1', udpPort: 30303, tcpPort: 30303 })

function onNewBlock(block: Block, peer: Peer) {
const blockHashHex = block.hash().toString('hex')
const blockNumber = devp2p.buffer2int(block.header.number)
const blockNumber = block.header.number.toNumber()

console.log(
`----------------------------------------------------------------------------------------------------------`,
`----------------------------------------------------------------------------------------------------------`
)
console.log(`block ${blockNumber} received: ${blockHashHex} (from ${getPeerAddr(peer)})`)
console.log(
`----------------------------------------------------------------------------------------------------------`,
`----------------------------------------------------------------------------------------------------------`
)
}

function isValidTx(tx: Tx) {
return tx.validate(false)
function isValidTx(tx: Transaction) {
return tx.validate()
}

async function isValidBlock(block: Block) {
if (!block.validateUnclesHash()) return false
if (!block.transactions.every(isValidTx)) return false
return new Promise((resolve, reject) => {
block.genTxTrie(() => {
try {
resolve(block.validateTransactionsTrie())
} catch (err) {
reject(err)
}
})
})
return (
block.validateUnclesHash() &&
block.transactions.every(isValidTx) &&
block.validateTransactionsTrie()
)
}

setInterval(() => {
Expand All @@ -225,7 +224,7 @@ setInterval(() => {

console.log(
chalk.yellow(
`Total nodes in DPT: ${peersCount}, open slots: ${openSlots}, queue: ${queueLength} / ${queueLength2}`,
),
`Total nodes in DPT: ${peersCount}, open slots: ${openSlots}, queue: ${queueLength} / ${queueLength2}`
)
)
}, ms('30s'))
Loading

0 comments on commit ce4d733

Please sign in to comment.