Skip to content

Commit

Permalink
Reused nonce verification code in ProofOfWork library
Browse files Browse the repository at this point in the history
  • Loading branch information
thehenrytsai committed Jan 4, 2024
1 parent ae0885e commit ba3376a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 13 deletions.
35 changes: 23 additions & 12 deletions src/registered-tenant-gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import type { Express } from 'express';
import type { Dialect } from 'kysely';
import { Kysely } from 'kysely';

import type { DwnServerError } from './dwn-error.js';
import { DwnServerErrorCode } from './dwn-error.js';
import { ProofOfWork } from './registration/proof-of-work.js';

const recentChallenges: { [challenge: string]: number } = {};
const CHALLENGE_TIMEOUT = 5 * 60 * 1000; // challenges are valid this long after issuance
const COMPLEXITY_LOOKBACK = 5 * 60 * 1000; // complexity is based on number of successful registrations in this time frame
Expand Down Expand Up @@ -161,19 +165,26 @@ export class RegisteredTenantGate implements TenantGate {
return;
}

const hash = createHash('sha256');
hash.update(body.challenge);
hash.update(body.response);

const complexity = await this.getComplexity();
const digest = hash.digest('hex');
if (!digest.startsWith('0'.repeat(complexity))) {
res.status(401).json({
success: false,
reason: 'insufficiently complex',
requiredComplexity: complexity,
try {
ProofOfWork.verifyChallengeResponse({
challenge: body.challenge,
responseNonce: body.response,
requiredLeadingZerosInResultingHash: await this.getComplexity(),
});
return;
} catch (error) {
const dwnServerError = error as DwnServerError;

if (
dwnServerError.code ===
DwnServerErrorCode.ProofOfWorkInsufficientLeadingZeros
) {
res.status(401).json({
success: false,
reason: dwnServerError.message,
});

return;
}
}

try {
Expand Down
2 changes: 1 addition & 1 deletion src/registration/proof-of-work.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export class ProofOfWork {
requiredLeadingZerosInResultingHash: number;
challenge: string;
responseNonce: string;
requestData: string;
requestData?: string;
}): void {
const computedHash = this.computeHash(input);

Expand Down

0 comments on commit ba3376a

Please sign in to comment.