forked from Emurgo/cip14-js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
58 lines (45 loc) · 1.4 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import blake2b from "blake2b";
import { bech32 } from "bech32";
/// note: this function can't be inverted due to the hash
const DATA = "asset";
export default class AssetFingerprint {
readonly hashBuf: Uint8Array;
private constructor(hashBuf: Uint8Array) {
this.hashBuf = hashBuf;
}
static fromHash(hash: Uint8Array): AssetFingerprint {
return new AssetFingerprint(hash);
}
static fromParts(
policyId: Uint8Array,
assetName: Uint8Array
): AssetFingerprint {
// see https://github.com/cardano-foundation/CIPs/pull/64
const hashBuf = blake2b(20)
.update(new Uint8Array([...policyId, ...assetName]))
.digest("binary");
return AssetFingerprint.fromHash(hashBuf);
}
static fromBech32(fingerprint: string): AssetFingerprint {
const { prefix, words } = bech32.decode(fingerprint);
if (prefix !== DATA) {
throw new Error("Invalid asset fingerprint");
}
const hashBuf = Buffer.from(bech32.fromWords(words));
return AssetFingerprint.fromHash(hashBuf);
}
fingerprint(): string {
const words = bech32.toWords(this.hashBuf);
return bech32.encode(DATA, words);
}
hash(): string {
return Buffer.from(this.hashBuf).toString("hex");
}
prefix(): string {
return DATA;
}
// The last six characters of the data part form a checksum and contain no information
checksum(): string {
return this.fingerprint().slice(-6);
}
}