Skip to content

Commit

Permalink
initial pow work
Browse files Browse the repository at this point in the history
  • Loading branch information
finn-block committed Oct 31, 2023
1 parent 3f5b3c5 commit bc51fe3
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 8 deletions.
54 changes: 46 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"@tbd54566975/dwn-sdk-js": "0.2.4",
"@tbd54566975/dwn-sql-store": "0.2.1",
"better-sqlite3": "^8.5.0",
"body-parser": "^1.20.2",
"bytes": "3.1.2",
"cors": "2.8.5",
"express": "4.18.2",
Expand Down
5 changes: 5 additions & 0 deletions src/http-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {

import { jsonRpcApi } from './json-rpc-api.js';
import { requestCounter, responseHistogram } from './metrics.js';
import { getChallenge, verifyChallenge } from './pow.js';

export class HttpApi {
#api: Express;
Expand All @@ -47,6 +48,7 @@ export class HttpApi {

#setupMiddleware(): void {
this.#api.use(cors({ exposedHeaders: 'dwn-response' }));
this.#api.use(express.json());

this.#api.use(
responseTime((req: Request, res: Response, time) => {
Expand Down Expand Up @@ -181,6 +183,9 @@ export class HttpApi {
return res.json(jsonRpcResponse);
}
});

this.#api.get('/register', getChallenge);
this.#api.post('/register', verifyChallenge);
}

#listen(port: number, callback?: () => void): void {
Expand Down
40 changes: 40 additions & 0 deletions src/pow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { createHash } from 'crypto';
import type { Request, Response } from 'express';

const outstandingHashes: { [challenge: string]: Date } = {};

export async function getChallenge(
_req: Request,
res: Response,
): Promise<void> {
// sign a JWT with an expiration date shortly in the future (1-2 min) and a complexity
// make the complexity go up when get challenge requests increase in frequency

res.status(500).json({ error: 'unimplemented' });
}

export async function verifyChallenge(
req: Request,
res: Response,
): Promise<void> {
console.log(req.body);
const body: {
challenge: string;
response: string;
} = req.body;

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

const hex = hash.digest('hex');
const complexity = Object.keys(outstandingHashes).length;
for (let i = 0; i < complexity; i++) {
if (hex[i] != '0') {
res.status(401).json({ success: false });
return;
}
}

res.json({ success: true });
}

0 comments on commit bc51fe3

Please sign in to comment.