const crypto = require('crypto');
function secureRandomInt(min, max) {
if (min > max) {
throw new Error('Min must be less than or equal to max');
}
const range = max - min + 1;
const bytesNeeded = Math.ceil(Math.log2(range) / 8);
const randomBytes = crypto.randomBytes(bytesNeeded);
let randomValue = 0;
for (let i = 0; i < bytesNeeded; i++) {
randomValue = (randomValue << 8) | randomBytes[i];
}
return (randomValue % range) + min;
}
function secureRandomFloat() {
const randomBytes = crypto.randomBytes(8);
const randomValue = randomBytes.readUInt32LE(0) / 0x100000000;
return randomValue;
}
function secureRandomBytes(length) {
return crypto.randomBytes(length);
}
function secureRandomHex(length) {
if (length % 2 !== 0) {
throw new Error('Length must be an even number');
}
return crypto.randomBytes(length / 2).toString('hex');
}
function generateWalletEntropy(strength = 256) {
const validStrengths = [128, 160, 192, 224, 256];
if (!validStrengths.includes(strength)) {
throw new Error(`Invalid entropy strength. Valid values: ${validStrengths.join(', ')}`);
}
return crypto.randomBytes(strength / 8);
}
function secureShuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = secureRandomInt(0, i);
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
function generateSecureNonce() {
return crypto.randomBytes(32);
}
function generateSeedPhrase(wordCount = 12) {
const validWordCounts = [12, 15, 18, 21, 24];
if (!validWordCounts.includes(wordCount)) {
throw new Error(`Invalid word count. Valid values: ${validWordCounts.join(', ')}`);
}
const wordlist = [
'abandon', 'ability', 'able', 'about', 'above', 'absent', 'absorb', 'abstract',
'absurd', 'abuse', 'access', 'accident', 'account', 'accuse', 'achieve', 'acid',
];
const entropyBits = {
12: 128, 15: 160, 18: 192, 21: 224, 24: 256
}[wordCount];
const entropy = generateWalletEntropy(entropyBits);
const seedWords = [];
for (let i = 0; i < wordCount; i++) {
const randomIndex = secureRandomInt(0, wordlist.length - 1);
seedWords.push(wordlist[randomIndex]);
}
return seedWords.join(' ');
}
module.exports = {
secureRandomInt,
secureRandomFloat,
secureRandomBytes,
secureRandomHex,
generateWalletEntropy,
secureShuffleArray,
generateSecureNonce,
generateSeedPhrase,
};