Add pow metrics

This commit is contained in:
2024-04-04 17:43:27 -06:00
parent 2eed36bdd7
commit 6084054590
6 changed files with 146 additions and 7 deletions

View File

@@ -1,5 +1,6 @@
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Inject, Injectable, Logger } from '@nestjs/common';
import { InjectMetric } from '@willsoto/nestjs-prometheus';
import { Cache } from 'cache-manager';
import { randomBytes, createHash } from 'crypto';
@@ -11,7 +12,14 @@ export class PowService {
constructor(
@Inject(CACHE_MANAGER) private cacheManager: Cache,
) { }
@InjectMetric('challenges_generated') private challengesGenerated: any,
@InjectMetric('challenges_completed') private challengesCompleted: any,
@InjectMetric('successful_verifies') private successfulVerifies: any,
@InjectMetric('failed_verifies') private failedVerifies: any,
@InjectMetric('difficulty') private powDifficulty: any,
) {
this.powDifficulty.set(this.difficulty);
}
/**
* Generate a proof of work challenge, stored to redis for verification within
@@ -19,7 +27,8 @@ export class PowService {
*/
async generateChallenge() {
const challenge = this.generateRandom256BitString();
console.log(challenge)
this.logger.verbose(`Generated challenge: ${challenge}`);
this.challengesGenerated.inc();
await this.cacheManager.set(challenge, true, 60 * 1000);
return challenge;
}
@@ -44,10 +53,17 @@ export class PowService {
*/
async verifyChallenge(challenge: string, proof: string): Promise<boolean> {
const expected = await this.cacheManager.get<boolean>(challenge);
return expected ? this.hashAndCheck(proof + challenge) : false;
const success = expected ? this.hashAndCheck(proof + challenge) : false;
if (success) {
this.successfulVerifies.inc();
} else {
this.failedVerifies.inc();
}
return success;
}
async markChallengeAsComplete(challenge: string) {
this.challengesCompleted.inc();
await this.cacheManager.del(challenge);
}
@@ -76,6 +92,7 @@ export class PowService {
*/
setDifficulty(difficulty: number) {
this.difficulty = difficulty;
this.powDifficulty.set(this.difficulty);
}
/**