Skip to content

Commit 0041c53

Browse files
authored
Make logging consistent (#3654)
1 parent ef99a53 commit 0041c53

File tree

12 files changed

+391
-313
lines changed

12 files changed

+391
-313
lines changed

packages/blockchain/src/consensus/clique.ts

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,13 @@ export class CliqueConsensus implements Consensus {
114114
*/
115115
public _cliqueLatestBlockSigners: CliqueLatestBlockSigners = []
116116

117+
DEBUG: boolean // Guard for debug logs
117118
constructor() {
119+
// Skip DEBUG calls unless 'ethjs' included in environmental DEBUG variables
120+
// Additional window check is to prevent vite browser bundling (and potentially other) to break
121+
this.DEBUG =
122+
typeof window === 'undefined' ? (process?.env?.DEBUG?.includes('ethjs') ?? false) : false
123+
118124
this.algorithm = ConsensusAlgorithm.Clique
119125
}
120126

@@ -220,7 +226,7 @@ export class CliqueConsensus implements Consensus {
220226
cliqueEpochTransitionSigners(genesisBlock.header),
221227
]
222228
await this.cliqueUpdateSignerStates(genesisSignerState)
223-
debug(`[Block 0] Genesis block -> update signer states`)
229+
this.DEBUG && debug(`[Block 0] Genesis block -> update signer states`)
224230
await this.cliqueUpdateVotes()
225231
}
226232

@@ -270,7 +276,7 @@ export class CliqueConsensus implements Consensus {
270276
let i = 0
271277
try {
272278
for (const signer of this.cliqueActiveSigners(signerState[0])) {
273-
debug(`Clique signer [${i}]: ${signer} (block: ${signerState[0]})`)
279+
this.DEBUG && debug(`Clique signer [${i}]: ${signer} (block: ${signerState[0]})`)
274280
i++
275281
}
276282
// eslint-disable-next-line no-empty
@@ -344,7 +350,8 @@ export class CliqueConsensus implements Consensus {
344350
this._cliqueLatestVotes = this._cliqueLatestVotes.filter(
345351
(vote) => !vote[1][1].equals(beneficiary),
346352
)
347-
debug(`[Block ${header.number}] Clique majority consensus (AUTH ${beneficiary})`)
353+
this.DEBUG &&
354+
debug(`[Block ${header.number}] Clique majority consensus (AUTH ${beneficiary})`)
348355
}
349356
// DROP vote
350357
votes = this._cliqueLatestVotes.filter((vote) => {
@@ -378,27 +385,31 @@ export class CliqueConsensus implements Consensus {
378385
// Discard votes from removed signer and for removed signer
379386
(vote) => !vote[1][0].equals(beneficiary) && !vote[1][1].equals(beneficiary),
380387
)
381-
debug(`[Block ${header.number}] Clique majority consensus (DROP ${beneficiary})`)
388+
this.DEBUG &&
389+
debug(`[Block ${header.number}] Clique majority consensus (DROP ${beneficiary})`)
382390
}
383391
if (round === 1) {
384392
// Always add the latest vote to the history no matter if already voted
385393
// the same vote or not
386394
this._cliqueLatestVotes.push(latestVote)
387-
debug(
388-
`[Block ${header.number}] New clique vote: ${signer} -> ${beneficiary} ${
389-
equalsBytes(nonce, CLIQUE_NONCE_AUTH) ? 'AUTH' : 'DROP'
390-
}`,
391-
)
395+
this.DEBUG &&
396+
debug(
397+
`[Block ${header.number}] New clique vote: ${signer} -> ${beneficiary} ${
398+
equalsBytes(nonce, CLIQUE_NONCE_AUTH) ? 'AUTH' : 'DROP'
399+
}`,
400+
)
392401
}
393402
if (consensus) {
394403
if (round === 1) {
395-
debug(
396-
`[Block ${header.number}] Clique majority consensus on existing votes -> update signer states`,
397-
)
404+
this.DEBUG &&
405+
debug(
406+
`[Block ${header.number}] Clique majority consensus on existing votes -> update signer states`,
407+
)
398408
} else {
399-
debug(
400-
`[Block ${header.number}] Clique majority consensus on new vote -> update signer states`,
401-
)
409+
this.DEBUG &&
410+
debug(
411+
`[Block ${header.number}] Clique majority consensus on new vote -> update signer states`,
412+
)
402413
}
403414
const newSignerState: CliqueSignerState = [header.number, activeSigners]
404415
await this.cliqueUpdateSignerStates(newSignerState)

packages/client/src/sync/fetcher/accountfetcher.ts

Lines changed: 25 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -136,11 +136,12 @@ export class AccountFetcher extends Fetcher<JobTask, AccountData[], AccountData>
136136
const origin = this.getOrigin(syncRange)
137137
const limit = this.getLimit(syncRange)
138138

139-
this.debug(
140-
`Account fetcher instantiated root=${short(this.root)} origin=${short(origin)} limit=${short(
141-
limit,
142-
)} destroyWhenDone=${this.destroyWhenDone}`,
143-
)
139+
this.DEBUG &&
140+
this.debug(
141+
`Account fetcher instantiated root=${short(this.root)} origin=${short(origin)} limit=${short(
142+
limit,
143+
)} destroyWhenDone=${this.destroyWhenDone}`,
144+
)
144145
}
145146

146147
async blockingFetch(): Promise<boolean> {
@@ -302,11 +303,12 @@ export class AccountFetcher extends Fetcher<JobTask, AccountData[], AccountData>
302303
origin: Uint8Array,
303304
{ accounts, proof }: { accounts: AccountData[]; proof: Uint8Array[] },
304305
): Promise<boolean> {
305-
this.debug(
306-
`verifyRangeProof accounts:${accounts.length} first=${bytesToHex(
307-
accounts[0].hash,
308-
)} last=${short(accounts[accounts.length - 1].hash)}`,
309-
)
306+
this.DEBUG &&
307+
this.debug(
308+
`verifyRangeProof accounts:${accounts.length} first=${bytesToHex(
309+
accounts[0].hash,
310+
)} last=${short(accounts[accounts.length - 1].hash)}`,
311+
)
310312

311313
for (let i = 0; i < accounts.length - 1; i++) {
312314
// ensure the range is monotonically increasing
@@ -382,7 +384,7 @@ export class AccountFetcher extends Fetcher<JobTask, AccountData[], AccountData>
382384

383385
if (this.highestKnownHash && compareBytes(limit, this.highestKnownHash) < 0) {
384386
// skip this job and don't rerequest it if it's limit is lower than the highest known key hash
385-
this.debug(`skipping request with limit lower than highest known hash`)
387+
this.DEBUG && this.debug(`skipping request with limit lower than highest known hash`)
386388
return Object.assign([], [{ skipped: true }], { completed: true })
387389
}
388390

@@ -415,12 +417,12 @@ export class AccountFetcher extends Fetcher<JobTask, AccountData[], AccountData>
415417
// if proof is false, reject corrupt peer
416418
if (isMissingRightRange !== false) return undefined
417419
} catch (e) {
418-
this.debug(e)
420+
this.DEBUG && this.debug(e)
419421
// if proof is false, reject corrupt peer
420422
return undefined
421423
}
422424

423-
this.debug(`Data for last range has been received`)
425+
this.DEBUG && this.debug(`Data for last range has been received`)
424426
// response contains empty object so that task can be terminated in store phase and not reenqueued
425427
return Object.assign([], [Object.create(null)], { completed: true })
426428
}
@@ -436,11 +438,12 @@ export class AccountFetcher extends Fetcher<JobTask, AccountData[], AccountData>
436438
// Check if there is any pending data to be synced to the right
437439
let completed: boolean
438440
if (isMissingRightRange && this.isMissingRightRange(limit, rangeResult)) {
439-
this.debug(
440-
`Peer ${peerInfo} returned missing right range account=${bytesToHex(
441-
rangeResult.accounts[rangeResult.accounts.length - 1].hash,
442-
)} limit=${bytesToHex(limit)}`,
443-
)
441+
this.DEBUG &&
442+
this.debug(
443+
`Peer ${peerInfo} returned missing right range account=${bytesToHex(
444+
rangeResult.accounts[rangeResult.accounts.length - 1].hash,
445+
)} limit=${bytesToHex(limit)}`,
446+
)
444447
completed = false
445448
} else {
446449
completed = true
@@ -487,15 +490,15 @@ export class AccountFetcher extends Fetcher<JobTask, AccountData[], AccountData>
487490
* @param result fetch result
488491
*/
489492
async store(result: AccountData[]): Promise<void> {
490-
this.debug(`Stored ${result.length} accounts in account trie`)
493+
this.DEBUG && this.debug(`Stored ${result.length} accounts in account trie`)
491494

492495
if (JSON.stringify(result[0]) === JSON.stringify({ skipped: true })) {
493496
// return without storing to skip this task
494497
return
495498
}
496499
if (JSON.stringify(result[0]) === JSON.stringify(Object.create(null))) {
497500
// TODO fails to handle case where there is a proof of non existence and returned accounts for last requested range
498-
this.debug('Final range received with no elements remaining to the right')
501+
this.DEBUG && this.debug('Final range received with no elements remaining to the right')
499502

500503
await this.accountTrie.persistRoot()
501504
this.snapFetchersCompleted(AccountFetcher, this.accountTrie.root())
@@ -579,7 +582,7 @@ export class AccountFetcher extends Fetcher<JobTask, AccountData[], AccountData>
579582
debugStr += ` limit=${short(
580583
setLengthLeft(bigIntToBytes(startedWith + pushedCount - BIGINT_1), 32),
581584
)}`
582-
this.debug(`Created new tasks num=${tasks.length} ${debugStr}`)
585+
this.DEBUG && this.debug(`Created new tasks num=${tasks.length} ${debugStr}`)
583586
return tasks
584587
}
585588

@@ -602,7 +605,7 @@ export class AccountFetcher extends Fetcher<JobTask, AccountData[], AccountData>
602605
const origin = this.getOrigin(pendingRange)
603606
const limit = this.getLimit(pendingRange)
604607

605-
this.debug(`Fetcher pending with origin=${short(origin)} limit=${short(limit)}`)
608+
this.DEBUG && this.debug(`Fetcher pending with origin=${short(origin)} limit=${short(limit)}`)
606609
const tasks = this.tasks()
607610
for (const task of tasks) {
608611
this.enqueueTask(task)

packages/client/src/sync/fetcher/blockfetcher.ts

Lines changed: 28 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ export class BlockFetcher extends BlockFetcherBase<Block[], Block> {
5353
})
5454
if (!Array.isArray(headersResult) || headersResult[1].length === 0) {
5555
// Catch occasional null or empty responses
56-
this.debug(`Peer ${peerInfo} returned no headers for blocks=${blocksRange}`)
56+
this.DEBUG && this.debug(`Peer ${peerInfo} returned no headers for blocks=${blocksRange}`)
5757
return []
5858
}
5959
const headers = headersResult[1]
@@ -64,13 +64,14 @@ export class BlockFetcher extends BlockFetcherBase<Block[], Block> {
6464
bodiesResult[1].length === 0
6565
) {
6666
// Catch occasional null or empty responses
67-
this.debug(`Peer ${peerInfo} returned no bodies for blocks=${blocksRange}`)
67+
this.DEBUG && this.debug(`Peer ${peerInfo} returned no bodies for blocks=${blocksRange}`)
6868
return []
6969
}
7070
const bodies = bodiesResult[1]
71-
this.debug(
72-
`Requested blocks=${blocksRange} from ${peerInfo} (received: ${headers.length} headers / ${bodies.length} bodies)`,
73-
)
71+
this.DEBUG &&
72+
this.debug(
73+
`Requested blocks=${blocksRange} from ${peerInfo} (received: ${headers.length} headers / ${bodies.length} bodies)`,
74+
)
7475
const blocks: Block[] = []
7576
for (const [i, [txsData, unclesData, withdrawalsData]] of bodies.entries()) {
7677
const header = headers[i]
@@ -81,9 +82,10 @@ export class BlockFetcher extends BlockFetcherBase<Block[], Block> {
8182
!equalsBytes(header.withdrawalsRoot, KECCAK256_RLP) &&
8283
(withdrawalsData?.length ?? 0) === 0)
8384
) {
84-
this.debug(
85-
`Requested block=${headers[i].number}} from peer ${peerInfo} missing non-empty txs=${txsData.length} or uncles=${unclesData.length} or withdrawals=${withdrawalsData?.length}`,
86-
)
85+
this.DEBUG &&
86+
this.debug(
87+
`Requested block=${headers[i].number}} from peer ${peerInfo} missing non-empty txs=${txsData.length} or uncles=${unclesData.length} or withdrawals=${withdrawalsData?.length}`,
88+
)
8789
return []
8890
}
8991
const values: BlockBytes = [headers[i].raw(), txsData, unclesData]
@@ -99,9 +101,10 @@ export class BlockFetcher extends BlockFetcherBase<Block[], Block> {
99101
await block.validateData(false, false)
100102
blocks.push(block)
101103
}
102-
this.debug(
103-
`Returning blocks=${blocksRange} from ${peerInfo} (received: ${headers.length} headers / ${bodies.length} bodies)`,
104-
)
104+
this.DEBUG &&
105+
this.debug(
106+
`Returning blocks=${blocksRange} from ${peerInfo} (received: ${headers.length} headers / ${bodies.length} bodies)`,
107+
)
105108
return blocks
106109
}
107110

@@ -120,7 +123,8 @@ export class BlockFetcher extends BlockFetcherBase<Block[], Block> {
120123
} else if (result.length > 0 && result.length < job.task.count) {
121124
// Save partial result to re-request missing items.
122125
job.partialResult = result
123-
this.debug(`Partial result received=${result.length} expected=${job.task.count}`)
126+
this.DEBUG &&
127+
this.debug(`Partial result received=${result.length} expected=${job.task.count}`)
124128
}
125129
}
126130
return
@@ -133,18 +137,20 @@ export class BlockFetcher extends BlockFetcherBase<Block[], Block> {
133137
async store(blocks: Block[]) {
134138
try {
135139
const num = await this.chain.putBlocks(blocks)
136-
this.debug(
137-
`Fetcher results stored in blockchain (blocks num=${blocks.length} first=${
138-
blocks[0]?.header.number
139-
} last=${blocks[blocks.length - 1]?.header.number})`,
140-
)
140+
this.DEBUG &&
141+
this.debug(
142+
`Fetcher results stored in blockchain (blocks num=${blocks.length} first=${
143+
blocks[0]?.header.number
144+
} last=${blocks[blocks.length - 1]?.header.number})`,
145+
)
141146
this.config.events.emit(Event.SYNC_FETCHED_BLOCKS, blocks.slice(0, num))
142147
} catch (e: any) {
143-
this.debug(
144-
`Error storing fetcher results in blockchain (blocks num=${blocks.length} first=${
145-
blocks[0]?.header.number
146-
} last=${blocks[blocks.length - 1]?.header.number}): ${e}`,
147-
)
148+
this.DEBUG &&
149+
this.debug(
150+
`Error storing fetcher results in blockchain (blocks num=${blocks.length} first=${
151+
blocks[0]?.header.number
152+
} last=${blocks[blocks.length - 1]?.header.number}): ${e}`,
153+
)
148154
throw e
149155
}
150156
}

packages/client/src/sync/fetcher/blockfetcherbase.ts

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -44,20 +44,25 @@ export abstract class BlockFetcherBase<JobResult, StorageItem> extends Fetcher<
4444
count: bigint
4545

4646
protected reverse: boolean
47+
protected DEBUG: boolean
4748

4849
/**
4950
* Create new block fetcher
5051
*/
5152
constructor(options: BlockFetcherOptions) {
5253
super(options)
5354

55+
this.DEBUG =
56+
typeof window === 'undefined' ? (process?.env?.DEBUG?.includes('ethjs') ?? false) : false
57+
5458
this.chain = options.chain
5559
this.first = options.first
5660
this.count = options.count
5761
this.reverse = options.reverse ?? false
58-
this.debug(
59-
`Block fetcher instantiated interval=${this.interval} first=${this.first} count=${this.count} reverse=${this.reverse} destroyWhenDone=${this.destroyWhenDone}`,
60-
)
62+
this.DEBUG &&
63+
this.debug(
64+
`Block fetcher instantiated interval=${this.interval} first=${this.first} count=${this.count} reverse=${this.reverse} destroyWhenDone=${this.destroyWhenDone}`,
65+
)
6166
}
6267

6368
/**
@@ -92,7 +97,7 @@ export abstract class BlockFetcherBase<JobResult, StorageItem> extends Fetcher<
9297
}
9398

9499
debugStr += ` count=${pushedCount} reverse=${this.reverse}`
95-
this.debug(`Created new tasks num=${tasks.length} ${debugStr}`)
100+
this.DEBUG && this.debug(`Created new tasks num=${tasks.length} ${debugStr}`)
96101
return tasks
97102
}
98103

@@ -104,18 +109,20 @@ export abstract class BlockFetcherBase<JobResult, StorageItem> extends Fetcher<
104109
this.count > BIGINT_0 &&
105110
this.processed - this.finished < this.config.maxFetcherRequests
106111
) {
107-
this.debug(
108-
`Fetcher pending with first=${this.first} count=${this.count} reverse=${this.reverse}`,
109-
)
112+
this.DEBUG &&
113+
this.debug(
114+
`Fetcher pending with first=${this.first} count=${this.count} reverse=${this.reverse}`,
115+
)
110116
const tasks = this.tasks(this.first, this.count)
111117
for (const task of tasks) {
112118
this.enqueueTask(task)
113119
}
114-
this.debug(`Enqueued num=${tasks.length} tasks`)
120+
this.DEBUG && this.debug(`Enqueued num=${tasks.length} tasks`)
115121
} else {
116-
this.debug(
117-
`No new tasks enqueued in=${this.in.length} count=${this.count} processed=${this.processed} finished=${this.finished}`,
118-
)
122+
this.DEBUG &&
123+
this.debug(
124+
`No new tasks enqueued in=${this.in.length} count=${this.count} processed=${this.processed} finished=${this.finished}`,
125+
)
119126
}
120127
}
121128

@@ -198,9 +205,10 @@ export abstract class BlockFetcherBase<JobResult, StorageItem> extends Fetcher<
198205
)
199206
}
200207
}
201-
this.debug(
202-
`Enqueued tasks by number list num=${numberList.length} min=${min} bulkRequest=${bulkRequest} ${updateHeightStr}`,
203-
)
208+
this.DEBUG &&
209+
this.debug(
210+
`Enqueued tasks by number list num=${numberList.length} min=${min} bulkRequest=${bulkRequest} ${updateHeightStr}`,
211+
)
204212
if (this.in.length === 0) {
205213
this.nextTasks()
206214
}

0 commit comments

Comments
 (0)