Signed-off-by: James Zuccon <zuccon@gmail.com>
This commit is contained in:
James Zuccon
2024-09-06 10:59:30 +10:00
parent b9a53659ce
commit f189c4643b
12 changed files with 311 additions and 13 deletions
+106
View File
@@ -0,0 +1,106 @@
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;
}
}