Use crypto.randomBytes instead of Math.random

This commit is contained in:
Elijah R 2024-06-01 17:35:05 -04:00
parent 60d41c2ef8
commit 7473a2f724

View file

@ -4,6 +4,7 @@ import { createSVGWindow } from 'svgdom'
import { SVG, registerWindow } from '@svgdotjs/svg.js' import { SVG, registerWindow } from '@svgdotjs/svg.js'
import * as fs from "node:fs/promises"; import * as fs from "node:fs/promises";
import sharp from "sharp"; import sharp from "sharp";
import crypto from "crypto";
const BASE_SVG = await fs.readFile("assets/ElectoralCollege2024.svg", "utf-8"); const BASE_SVG = await fs.readFile("assets/ElectoralCollege2024.svg", "utf-8");
@ -17,8 +18,8 @@ export function MakePrediction(bias: number, gopcandidate : string, demcandidate
var demVotes = 0; var demVotes = 0;
var draw = SVG(window.document.documentElement); var draw = SVG(window.document.documentElement);
draw.svg(BASE_SVG); draw.svg(BASE_SVG);
Object.keys(ELECTORAL_COLLEGE).forEach(state => { for (const state of Object.keys(ELECTORAL_COLLEGE)) {
if ((GOP_WIN_ODDS as any)[state] >= bias + Math.random()) { if ((GOP_WIN_ODDS as any)[state] >= bias + await betterRandom()) {
election[state] = "R"; election[state] = "R";
gopVotes += (ELECTORAL_COLLEGE as any)[state]; gopVotes += (ELECTORAL_COLLEGE as any)[state];
// @ts-ignore // @ts-ignore
@ -30,7 +31,7 @@ export function MakePrediction(bias: number, gopcandidate : string, demcandidate
// @ts-ignore // @ts-ignore
draw.find(`#${state}`).fill("#1C408C"); draw.find(`#${state}`).fill("#1C408C");
} }
}); };
var s = sharp(Buffer.from(draw.svg())); var s = sharp(Buffer.from(draw.svg()));
var png = await s.png().toBuffer(); var png = await s.png().toBuffer();
res({ res({
@ -53,4 +54,12 @@ export interface Prediction {
winner: string, winner: string,
svg: string, svg: string,
png: Buffer, png: Buffer,
}
export function betterRandom() : Promise<number> {
return new Promise(res => {
crypto.randomBytes(4, (err, buf) => {
res(buf.readUInt32BE(0) / 0x100000000);
});
});
} }