From ef827533c1d10fdcc620c39205259239fd6d6627 Mon Sep 17 00:00:00 2001 From: Tomasz Slabon Date: Tue, 26 Sep 2023 18:25:50 +0200 Subject: [PATCH] Updated calculating of deposit script hash --- typescript/src/bitcoin.ts | 12 ++++++++++++ typescript/src/deposit.ts | 16 +++++++++------- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/typescript/src/bitcoin.ts b/typescript/src/bitcoin.ts index 63936a464..75b0f4163 100644 --- a/typescript/src/bitcoin.ts +++ b/typescript/src/bitcoin.ts @@ -524,6 +524,7 @@ export function createKeyRing( * @param text - Text the HASH160 is computed for. * @returns Hash as a 20-byte un-prefixed hex string. */ +// TODO: Make it use Hex for input and return values. export function computeHash160(text: string): string { const sha256Hash = utils.sha256( Hex.from(Buffer.from(text, "hex")).toPrefixedString() @@ -533,6 +534,17 @@ export function computeHash160(text: string): string { return Hex.from(hash160).toString() } +/** + * Computes the single SHA256 for the given text. + * @param text - Text the single SHA256 is computed for. + * @returns Hash as a 32-byte un-prefixed hex string. + */ +// TODO: Consider adding unit tests. +export function computeSha256(text: Hex): Hex { + const hash = utils.sha256(text.toPrefixedString()) + return Hex.from(hash) +} + /** * Computes the double SHA256 for the given text. * @param text - Text the double SHA256 is computed for. diff --git a/typescript/src/deposit.ts b/typescript/src/deposit.ts index c95726283..b3b38441e 100644 --- a/typescript/src/deposit.ts +++ b/typescript/src/deposit.ts @@ -9,11 +9,11 @@ import { UnspentTransactionOutput, TransactionHash, isPublicKeyHashLength, + computeSha256, + computeHash256, + computeHash160, } from "./bitcoin" -import { - BitcoinNetwork, - toBitcoinJsLibNetwork, -} from "./bitcoin-network" +import { BitcoinNetwork, toBitcoinJsLibNetwork } from "./bitcoin-network" import { Bridge, Event, Identifier } from "./chain" import { Hex } from "./hex" @@ -343,11 +343,13 @@ export async function calculateDepositScriptHash( witness: boolean ): Promise { const script = await assembleDepositScript(deposit) - // Parse the script from HEX string. - const parsedScript = bcoin.Script.fromRaw(Buffer.from(script, "hex")) // If witness script hash should be produced, SHA256 should be used. // Legacy script hash needs HASH160. - return witness ? parsedScript.sha256() : parsedScript.hash160() + if (witness) { + return computeSha256(Hex.from(script)).toBuffer() + } + + return Buffer.from(computeHash160(script), "hex") } /**