UNPKG

@skalenetwork/bite

Version:

TS Library to interact with BITE protocol

291 lines (283 loc) 9.26 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { BITE: () => BITE, BITEMockup: () => BITEMockup }); module.exports = __toCommonJS(src_exports); // src/core/encrypt.ts var import_t_encrypt = require("@skalenetwork/t-encrypt"); // src/utils/constants.ts var EPOCH_ID_SIZE_BYTES = 8; var BITE_ADDRESS = "0x42495445204D452049274d20454e435259505444"; var NODE_ENV = "production"; // src/utils/helper.ts function remove0xPrefixIfNeeded(str) { return str.startsWith("0x") ? str.slice(2) : str; } function intTo8BytesHex(num) { if (typeof num !== "number" && typeof num !== "bigint") { throw new TypeError("Input must be a number or bigint"); } return BigInt(num).toString(16).padStart(2 * EPOCH_ID_SIZE_BYTES, "0"); } function validateUrl(url) { try { new URL(url); } catch { throw new Error(`Invalid provider URL: ${url}`); } } function validateHexString(str) { if (!/^[0-9a-fA-F]*$/.test(str)) { throw new Error("Invalid input: Must contain only hexadecimal characters"); } if (str.length % 2 !== 0) { throw new Error("Invalid input: Must have an even length"); } } // src/utils/logger.ts var import_tslog = require("tslog"); var isDev = NODE_ENV === "development"; var logger = new import_tslog.Logger({ name: "bite", minLevel: isDev ? "info" : 9 }); // src/core/biteRpc.ts async function getDecryptedTransactionData(endpoint, transactionHash) { try { validateUrl(endpoint); const requestBody = { jsonrpc: "2.0", method: "bite_getDecryptedTransactionData", params: [transactionHash], id: 1 }; const result = await sendRpcRequest(endpoint, requestBody); return result; } catch (error) { logger.error("Error fetching decrypted transaction data:", error); throw error; } } async function getCommonPublicKey(endpoint) { try { const requestBody = { jsonrpc: "2.0", method: "bite_getCommonPublicKey", params: [], id: 1 }; const result = await sendRpcRequest(endpoint, requestBody); if (typeof result !== "string") { throw new Error("Result is not a string"); } if (!/^[0-9a-fA-F]{256}$/.test(result)) { throw new Error("Result is not a valid 256-character hexadecimal string"); } return result; } catch (error) { logger.error("Error fetching BITE common public key:", error); throw error; } } async function sendRpcRequest(endpoint, requestBody) { try { validateUrl(endpoint); const response = await fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(requestBody) }); if (response.status !== 200) { throw new Error(`Received status code: ${response.status}`); } const data = await response.json(); if ("error" in data) { throw new Error(`Error from server: ${data.error.message}`); } return data.result; } catch (error) { logger.error("Error sending RPC request:", error); throw error; } } // src/core/encrypt.ts async function encryptTransaction(tx, endpoint) { try { const validatedTx = validateAndExtractTransactionFields(tx); const txTo = validatedTx.to; let txData = validatedTx.data; txData += txTo; tx.data = await encryptMessage(txData, endpoint); tx.to = BITE_ADDRESS; return tx; } catch (error) { logger.error("Error encrypting transaction:", error); throw error; } } async function encryptTransactionMockup(tx) { try { const validatedTx = validateAndExtractTransactionFields(tx); const txTo = validatedTx.to; let txData = validatedTx.data; txData += txTo; tx.data = await encryptMessageMockup(txData); tx.to = BITE_ADDRESS; return tx; } catch (error) { logger.error("Error encrypting transaction (mockup):", error); throw error; } } async function encryptMessage(message, endpoint) { try { const data = remove0xPrefixIfNeeded(message); validateHexString(data); const BLS_PUBLIC_KEY = await getCommonPublicKey(endpoint); const encryptedRawMessage = await (0, import_t_encrypt.encryptMessage)(data, BLS_PUBLIC_KEY); const epochIDHex = intTo8BytesHex(0); return `0x${epochIDHex}${encryptedRawMessage}`; } catch (error) { logger.error("Error encrypting message:", error); throw error; } } async function encryptMessageMockup(message) { try { const data = remove0xPrefixIfNeeded(message); if (!/^[0-9a-fA-F]*$/.test(data) || data.length % 2 !== 0) { throw new Error("Invalid input: message must be valid hex and even length"); } const encryptedRawMessage = await (0, import_t_encrypt.encryptMessageMockup)(data); const epochIDHex = intTo8BytesHex(0); return `0x${epochIDHex}${encryptedRawMessage}`; } catch (error) { logger.error("Error encrypting message:", error); throw error; } } function validateAndExtractTransactionFields(tx) { const isValid = tx && typeof tx === "object" && tx.data && tx.to && typeof tx.data === "string" && typeof tx.to === "string"; if (!isValid) { throw new Error("Invalid input: Must be an object with 'data' and 'to' fields of type string"); } const txData = remove0xPrefixIfNeeded(tx.data); const txTo = remove0xPrefixIfNeeded(tx.to); validateHexString(txData); validateHexString(txTo); if (txTo.length !== 40) { throw new Error("Invalid input: 'to' field must be exactly 20 bytes (40 hex characters) long"); } return { data: txData, to: txTo }; } // src/core/bite.ts var BITE = class { constructor(providerURL) { this.providerURL = providerURL; } /** * Encrypt a hex-encoded message using BLS public key. * @param message - Hex string (with or without 0x). */ async encryptMessage(message) { return encryptMessage(message, this.providerURL); } /** * Encrypt a transaction object using BLS public key. * @param tx - The transaction to encrypt. */ async encryptTransaction(tx) { return encryptTransaction(tx, this.providerURL); } /** * Fetch the common BLS public key from the configured endpoint. */ async getCommonPublicKey() { return getCommonPublicKey(this.providerURL); } /** * Get decrypted transaction data using the configured endpoint. * @param transactionHash - The hash of the transaction. */ async getDecryptedTransactionData(transactionHash) { return getDecryptedTransactionData(this.providerURL, transactionHash); } }; var BITEMockup = class { /** * Simulates encryption of a hex-encoded message * * @param message - Hex string (with or without 0x). */ async encryptMessage(message) { return encryptMessageMockup(message); } /** * Simulates encryption of a transaction object * * @param tx - The transaction to encrypt. */ async encryptTransaction(tx) { return encryptTransactionMockup(tx); } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { BITE, BITEMockup }); /** * @license * SKALE bite.ts * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ /** * @license * SKALE libte-ts * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ //# sourceMappingURL=index.js.map