UNPKG

@bsv/sdk

Version:

BSV Blockchain Software Development Kit

81 lines 2.72 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isValidURL = exports.getHashFromURL = exports.getURLForFile = exports.getURLForHash = exports.normalizeURL = void 0; const utils_js_1 = require("../primitives/utils.js"); const index_js_1 = require("../primitives/index.js"); /** * Takes a UHRP URL and removes any prefixes. * @param {string} URL - The UHRP URL. * @returns {string} - Normalized URL. */ const normalizeURL = (URL) => { if (URL.toLowerCase().startsWith('uhrp:')) URL = URL.slice(5); if (URL.startsWith('//')) URL = URL.slice(2); return URL; }; exports.normalizeURL = normalizeURL; /** * Generates a UHRP URL from a given SHA-256 hash. * @param {number[]} hash - 32-byte SHA-256 hash. * @returns {string} - Base58Check encoded URL. */ const getURLForHash = (hash) => { if (hash.length !== 32) { throw new Error('Hash length must be 32 bytes (sha256)'); } return (0, utils_js_1.toBase58Check)(hash, (0, utils_js_1.toArray)('ce00', 'hex')); }; exports.getURLForHash = getURLForHash; /** * Generates a UHRP URL for a given file. * Uses a streaming hash to avoid excessive memory usage with large files. * @param {Uint8Array | number[]} file - File content as a typed array or number array. * @returns {string} - Base58Check encoded URL. */ const getURLForFile = (file) => { const data = file instanceof Uint8Array ? file : Uint8Array.from(file); const hasher = new index_js_1.Hash.SHA256(); const chunkSize = 1024 * 1024; for (let i = 0; i < data.length; i += chunkSize) { const chunk = data.subarray(i, i + chunkSize); hasher.update(Array.from(chunk)); } const hash = hasher.digest(); return (0, exports.getURLForHash)(hash); }; exports.getURLForFile = getURLForFile; /** * Extracts the hash from a UHRP URL. * @param {string} URL - UHRP URL. * @returns {number[]} - Extracted SHA-256 hash. */ const getHashFromURL = (URL) => { URL = (0, exports.normalizeURL)(URL); const { data, prefix } = (0, utils_js_1.fromBase58Check)(URL, undefined, 2); if (data.length !== 32) { throw new Error('Invalid length!'); } if ((0, utils_js_1.toHex)(prefix) !== 'ce00') { throw new Error('Bad prefix'); } return data; }; exports.getHashFromURL = getHashFromURL; /** * Checks if a URL is a valid UHRP URL. * @param {string} URL - The URL to validate. * @returns {boolean} - True if valid, false otherwise. */ const isValidURL = (URL) => { try { (0, exports.getHashFromURL)(URL); return true; } catch (e) { return false; } }; exports.isValidURL = isValidURL; //# sourceMappingURL=StorageUtils.js.map