import { binToHex, hexToBin, hashTransaction, isHex } from '@bitauth/libauth'; /** * Transaction Hash Primitive. */ export class TransactionHash { public readonly bytes: Uint8Array; /** * Instantiates TransactionHash from a Transaction Hash's bytes. * * @param bytes {Uint8Array} The Transaction Hash's bytes. */ constructor(bytes: Uint8Array) { // If bytes is not exactly 32, then this is an invalid transaction hash... if (bytes.length !== 32) { throw new Error( `Invalid Transaction Hash: Expected 32 bytes but received ${bytes.length}`, ); } this.bytes = bytes; } /** * Instantiates TransactionHash from a hex string. * * @param hex {string} The hex string. * * @throws {Error} If hex is invalid. * * @returns {TransactionHash} Instance of TransactionHash. */ public static fromHex(hex: string): TransactionHash { if (!isHex(hex)) { throw new Error('Invalid hex provided'); } const bytes = hexToBin(hex); return new TransactionHash(bytes); } /** * Instantiates TransactionHash from a Transaction's bytes. * * @param transactionBytes {Uint8Array} The Transaction's bytes. * * @returns {TransactionHash} Instance of TransactionHash. */ public static fromTransactionBytes( transactionBytes: Uint8Array, ): TransactionHash { const transactionHash = hashTransaction(transactionBytes); return new TransactionHash(hexToBin(transactionHash)); } /** * Instantiates TransactionHash from a Transaction's bytes in hex. * * @param transactionHex {Uint8Array} The Transaction's bytes in hex. * * @throws {Error} If hex is invalid. * * @returns {TransactionHash} Instance of TransactionHash. */ public static fromTransactionHex(transactionHex: string): TransactionHash { if (!isHex(transactionHex)) { throw new Error('Invalid hex provided'); } const bytes = hexToBin(transactionHex); return TransactionHash.fromTransactionBytes(bytes); } /** * Returns transaction hash as a hex string. * * @returns {string} Hex string of the Transaction Hash. */ public toHex(): string { return binToHex(this.bytes); } /** * Returns transaction hash as a Uint8Array. * * @returns {Uint8Array} Uint8Array of the Transaction Hash. */ public toBytes(): Uint8Array { return this.bytes; } }