-
-
Save martincik/fd583e966b63df399a57dbb463d3ceca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { env } from '@/env'; | |
import { calculateChecksumBE } from '@/checksum'; | |
import * as Sentry from "@sentry/node"; | |
import { nodeProfilingIntegration } from '@sentry/profiling-node'; | |
Sentry.init({ | |
dsn: "https://", | |
integrations: [ | |
nodeProfilingIntegration(), | |
], | |
// Performance Monitoring | |
tracesSampleRate: 1.0, // Capture 100% of the transactions | |
// Set sampling rate for profiling - this is relative to tracesSampleRate | |
profilesSampleRate: 1.0, | |
}); | |
import express, { Application, Request, Response } from 'express'; | |
import cors from 'cors'; | |
import multer from "multer"; | |
import fs from "fs"; | |
import Irys from '@irys/sdk'; | |
import axios from 'axios'; | |
const app: Application = express(); | |
// The error handler must be registered before any other error middleware and after all controllers | |
Sentry.setupExpressErrorHandler(app); | |
const upload = multer({ dest: './uploads' }) | |
app.use(cors()); | |
app.use(express.json({ limit: '305mb' })); | |
app.use(express.urlencoded({ extended: true, limit: '305mb' })); | |
app.get('/health', (_req: Request, res: Response) => { | |
res.send('OK'); | |
}); | |
app.get('/sentry-test', (_req: Request, res: Response) => { | |
Sentry.captureMessage('Testing sentry'); | |
res.send('Testing sentry'); | |
}); | |
app.post('/upload', upload.single('file'), async (req: Request, res: Response) => { | |
const file = req.file; | |
if (!file) { | |
res.status(403).send('No file uploaded.'); | |
console.error('No file uploaded.'); | |
Sentry.captureException({ | |
"message": "No file uploaded", | |
}); | |
return; | |
} | |
console.log('Request body:', req.body); | |
const checksum = req.body.checksum; | |
console.log('Received checksum:', checksum); | |
if (!checksum) { | |
res.status(400).send('Checksum is missing from the request.'); | |
console.error('Checksum is missing from the request.'); | |
Sentry.captureException({ | |
"message": "Checksum is missing from the request", | |
}); | |
return; | |
} | |
const realChecksum = await calculateChecksumBE(file.path); | |
console.log('Backend calculated checksum:', realChecksum); | |
if (checksum !== realChecksum) { | |
res.status(403).send('Checksum does not match.'); | |
console.error('Checksum does not match.'); | |
Sentry.captureException({ | |
"message": "Backend checksum does not match the frontend checksum", | |
"fe_checksum": checksum, | |
"be_checksum": realChecksum, | |
}); | |
return; | |
} | |
let tempFilePath: string | null = null; | |
try { | |
const irys = new Irys({ | |
network: "mainnet", // "mainnet" || "devnet" | |
token: "aptos", | |
key: env.PRIVATE_KEY_STRING | |
}); | |
const fileStream = fs.createReadStream(file.path); | |
const price = await irys.getPrice(file.size); | |
console.log(`Uploading Image to Arweave: ${file.path} - Size: ${file.size} - Price: ${price}`); | |
await irys.fund(price); | |
const receipt = await irys.upload(fileStream, { | |
tags: [{ name: "Content-Type", value: file.mimetype }], | |
}); | |
console.log(`Receipt: ${JSON.stringify(receipt)}`); | |
const imgUri = `https://arweave.net/${receipt.id}` | |
// Download and check the checksum | |
tempFilePath = `./temp_${receipt.id}`; | |
const writer = fs.createWriteStream(tempFilePath); | |
console.log('Downloading the image to verify the checksum...'); | |
const response = await axios({ | |
url: imgUri, | |
method: 'GET', | |
responseType: 'stream' | |
}); | |
response.data.pipe(writer); | |
await new Promise((resolve, reject) => { | |
writer.on('finish', resolve); | |
writer.on('error', reject); | |
}); | |
console.log("Downloaded image successfully. Verifying checksum...") | |
const downloadedChecksum = await calculateChecksumBE(tempFilePath); | |
if (downloadedChecksum !== realChecksum) { | |
throw new Error(`Downloaded file checksum does not match the original file. Real checksum: ${realChecksum}, Downloaded checksum: ${downloadedChecksum}`); | |
} | |
console.log('Checksum verification successful.'); | |
console.log(`Image URI: ${imgUri}`); | |
res.send(imgUri); | |
} catch (e) { | |
console.error('Downloaded file checksum does not match the original file.'); | |
Sentry.captureException(e); | |
console.error(e); | |
res.status(500).send(e instanceof Error ? `Error: ${e.message}` : 'Something went wrong'); | |
} finally { | |
try { | |
if (file && file.path) { | |
await fs.promises.unlink(file.path); | |
} | |
// Also delete the temporary downloaded file if it exists | |
if (tempFilePath && fs.existsSync(tempFilePath)) { | |
await fs.promises.unlink(tempFilePath); | |
} | |
} catch (err) { | |
console.error(`Error while deleting the file: ${err}`); | |
} | |
} | |
}); | |
app.listen(env.PORT, function () { | |
console.log(`Sketch API is listening on port ${env.PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment