-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathscript-data-hash.ts
More file actions
62 lines (58 loc) · 2.58 KB
/
script-data-hash.ts
File metadata and controls
62 lines (58 loc) · 2.58 KB
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
59
60
61
62
/* eslint-disable unicorn/number-literal-case */
import blake2b from "blake2b";
import { Cardano, Serialization } from "@cardano-sdk/core";
import { Hash32ByteBase16 } from "@cardano-sdk/crypto";
import { HexBlob } from "@cardano-sdk/util";
import { PlutusData } from "../types";
const CBOR_EMPTY_MAP = new Uint8Array([0xa0]);
/**
* Computes the hash of script data in a transaction, including redeemers, datums, and cost models.
*
* This function takes arrays of redeemers and datums, along with cost models, and encodes
* them in a CBOR (Concise Binary Object Representation) format. The encoded data is then
* hashed using the Blake2b hashing algorithm to produce a 32-byte hash. This hash is
* representative of the script data in a transaction on the Cardano blockchain.
*
* @param costModels The cost models for script execution.
* @param redemeers The redeemers in the transaction. If not present or empty, the function may return undefined.
* @param datums The datums in the transaction.
* @returns The hashed script data, or undefined if no redeemers are provided.
*/
export const hashScriptData = (
costModels: Serialization.Costmdls,
redemeers?: Serialization.Redeemers,
datums?: Serialization.CborSet<Cardano.PlutusData, PlutusData>,
): Hash32ByteBase16 | undefined => {
const writer = new Serialization.CborWriter();
if (datums && datums.size() > 0 && (!redemeers || redemeers.size() === 0)) {
/*
; Note that in the case that a transaction includes datums but does not
; include any redeemers, the script data format becomes (in hex):
; [ A0 | datums | A0 ]
; corresponding to a CBOR empty list and an empty map).
*/
writer.writeEncodedValue(CBOR_EMPTY_MAP);
writer.writeEncodedValue(Buffer.from(datums.toCbor(), "hex"));
writer.writeEncodedValue(CBOR_EMPTY_MAP);
} else {
if (!redemeers || redemeers.size() === 0) return undefined;
/*
; script data format:
; [ redeemers | datums | language views ]
; The redeemers are exactly the data present in the transaction witness set.
; Similarly for the datums, if present. If no datums are provided, the middle
; field is an empty string.
*/
writer.writeEncodedValue(Buffer.from(redemeers.toCbor(), "hex"));
if (datums && datums.size() > 0) {
writer.writeEncodedValue(Buffer.from(datums.toCbor(), "hex"));
}
writer.writeEncodedValue(
Buffer.from(costModels.languageViewsEncoding(), "hex"),
);
}
const hashHex = blake2b(32)
.update(Buffer.from(writer.encode()))
.digest("hex");
return Hash32ByteBase16.fromHexBlob(HexBlob(hashHex));
};