@btc-vision/transaction
Version:
OPNet transaction library allows you to create and sign transactions for the OPNet network.
57 lines • 1.94 kB
JavaScript
import { createHash } from 'crypto';
import { toHex } from '@btc-vision/bitcoin';
const hexPattern = /^[0-9a-fA-F]+$/;
/**
* Utility class for Bitcoin related functions
*/
export class BitcoinUtils {
/**
* Converts satoshi to BTC
* @param {number} btc - The amount in BTC
* @returns {bigint} The amount in satoshi
*/
static btcToSatoshi(btc) {
return BigInt(btc * 100000000);
}
/**
* Generates random bytes.
* @public
* @returns {Uint8Array} The random bytes
*/
static rndBytes() {
return BitcoinUtils.getSafeRandomValues(64);
}
static getSafeRandomValues(length) {
if (typeof globalThis.window !== 'undefined' &&
globalThis.window.crypto &&
typeof globalThis.window.crypto.getRandomValues === 'function') {
const array = new Uint8Array(length);
window.crypto.getRandomValues(array);
return array;
}
else if (globalThis.crypto && typeof globalThis.crypto.getRandomValues === 'function') {
const array = new Uint8Array(length);
globalThis.crypto.getRandomValues(array);
return array;
}
else {
console.log(`No secure random number generator available. Please upgrade your environment.`, globalThis.window.crypto, globalThis.crypto);
throw new Error('No secure random number generator available. Please upgrade your environment.');
}
}
static isValidHex(hex) {
return hexPattern.test(hex);
}
/**
* Hashes the given data
* @param {Uint8Array} data - The data to hash
* @returns {string} The hashed data
*/
static opnetHash(data) {
const hashed = createHash('sha512');
hashed.update(data);
const hash = hashed.digest();
return `0x${toHex(new Uint8Array(hash))}`;
}
}
//# sourceMappingURL=BitcoinUtils.js.map