2021-10-20 12:18:01 +02:00
|
|
|
import * as createHash from 'create-hash';
|
2014-04-08 14:13:03 +02:00
|
|
|
|
2019-03-03 15:07:49 +01:00
|
|
|
export function ripemd160(buffer: Buffer): Buffer {
|
2019-04-02 11:57:07 +02:00
|
|
|
try {
|
|
|
|
return createHash('rmd160')
|
|
|
|
.update(buffer)
|
|
|
|
.digest();
|
|
|
|
} catch (err) {
|
|
|
|
return createHash('ripemd160')
|
|
|
|
.update(buffer)
|
|
|
|
.digest();
|
|
|
|
}
|
2014-06-26 11:26:21 +02:00
|
|
|
}
|
|
|
|
|
2019-03-03 15:07:49 +01:00
|
|
|
export function sha1(buffer: Buffer): Buffer {
|
|
|
|
return createHash('sha1')
|
|
|
|
.update(buffer)
|
|
|
|
.digest();
|
2014-04-08 14:13:03 +02:00
|
|
|
}
|
|
|
|
|
2019-03-03 15:07:49 +01:00
|
|
|
export function sha256(buffer: Buffer): Buffer {
|
|
|
|
return createHash('sha256')
|
|
|
|
.update(buffer)
|
|
|
|
.digest();
|
2014-04-08 14:13:03 +02:00
|
|
|
}
|
|
|
|
|
2019-03-03 15:07:49 +01:00
|
|
|
export function hash160(buffer: Buffer): Buffer {
|
|
|
|
return ripemd160(sha256(buffer));
|
2016-09-28 00:44:21 +02:00
|
|
|
}
|
|
|
|
|
2019-03-03 15:07:49 +01:00
|
|
|
export function hash256(buffer: Buffer): Buffer {
|
|
|
|
return sha256(sha256(buffer));
|
2016-09-28 00:44:21 +02:00
|
|
|
}
|
2021-11-12 00:33:18 +01:00
|
|
|
|
|
|
|
const TAGS = [
|
|
|
|
'BIP0340/challenge',
|
|
|
|
'BIP0340/aux',
|
|
|
|
'BIP0340/nonce',
|
|
|
|
'TapLeaf',
|
|
|
|
'TapBranch',
|
|
|
|
'TapSighash',
|
|
|
|
'TapTweak',
|
|
|
|
'KeyAgg list',
|
|
|
|
'KeyAgg coefficient',
|
|
|
|
] as const;
|
|
|
|
export type TaggedHashPrefix = typeof TAGS[number];
|
|
|
|
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
|
|
|
|
const TAGGED_HASH_PREFIXES = Object.fromEntries(
|
|
|
|
TAGS.map(tag => {
|
|
|
|
const tagHash = sha256(Buffer.from(tag));
|
|
|
|
return [tag, Buffer.concat([tagHash, tagHash])];
|
|
|
|
}),
|
|
|
|
) as { [k in TaggedHashPrefix]: Buffer };
|
|
|
|
|
|
|
|
export function taggedHash(prefix: TaggedHashPrefix, data: Buffer): Buffer {
|
|
|
|
return sha256(Buffer.concat([TAGGED_HASH_PREFIXES[prefix], data]));
|
|
|
|
}
|