dgf-prototype/backend/index.js

71 lines
1.8 KiB
JavaScript
Raw Normal View History

2024-03-19 22:22:36 -05:00
const express = require('express');
const { Level } = require('level');
2024-03-20 16:30:27 -05:00
const { recoverPersonalSignature } = require('@metamask/eth-sig-util');
// const { ecrecover, fromRpcSig, pubToAddress } = require('@ethereumjs/util');
// const { Keccak } = require('sha3');
const objectHash = require('object-hash');
// const { createHash } = require('node:crypto');
2024-03-19 22:22:36 -05:00
require('dotenv').config();
const app = express();
const port = process.env.PORT || 3000;
const dataDir = process.env.DATA_DIR || 'data';
const db = new Level(`${dataDir}/forum`, { valueEncoding: 'json' });
2024-03-20 16:30:27 -05:00
// const keccak = Keccak(256);
2024-03-19 22:22:36 -05:00
app.use(express.json());
app.post('/write', async (req, res) => {
2024-03-20 16:30:27 -05:00
const { body: { author, content, signature } } = req;
// Check author signature
try {
const account = recoverPersonalSignature({ data: content, signature });
if (account !== author) {
console.log('error: author does not match signature');
res.status(403).end();
return;
}
} catch (e) {
console.log('error: failed to recover signature:', e.message);
res.status(400).end();
return;
}
2024-03-19 22:22:36 -05:00
// Compute content hash
2024-03-20 16:30:27 -05:00
const data = { author, content, signature };
const hash = objectHash(data);
2024-03-19 22:22:36 -05:00
console.log('write', hash);
// Store content
db.put(hash, data);
// Return hash
res.send(hash);
});
app.get('/read/:hash', async (req, res) => {
// Fetch content
const { hash } = req.params;
2024-03-20 09:41:06 -05:00
let data;
try {
data = await db.get(req.params.hash);
} catch (e) {
console.log('read error:', e.message, hash);
res.status(e.status).end();
return;
}
2024-03-19 22:22:36 -05:00
console.log('read', hash);
// Return content
res.json(data);
});
app.get('*', (req, res) => {
console.log(`req.path: ${req.path}`);
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});