Skip to content

Commit

Permalink
Updated calculating of deposit script hash
Browse files Browse the repository at this point in the history
  • Loading branch information
tomaszslabon committed Sep 26, 2023
1 parent 6fe7cea commit ef82753
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
12 changes: 12 additions & 0 deletions typescript/src/bitcoin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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.
Expand Down
16 changes: 9 additions & 7 deletions typescript/src/deposit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ import {
UnspentTransactionOutput,
TransactionHash,
isPublicKeyHashLength,
computeSha256,
computeHash256,

Check failure on line 13 in typescript/src/deposit.ts

View workflow job for this annotation

GitHub Actions / typescript-format

'computeHash256' is defined but never used
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"

Expand Down Expand Up @@ -343,11 +343,13 @@ export async function calculateDepositScriptHash(
witness: boolean
): Promise<Buffer> {
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")
}

/**
Expand Down

0 comments on commit ef82753

Please sign in to comment.