@taquito/utils 17.3.2 → 17.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,922 +4,918 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.taquitoUtils = {}, global.buffer, global.ed25519, global.blake2b, global.blake, global.bs58check, global.core, global.BigNumber, global.elliptic, global.toBuffer));
5
5
  })(this, (function (exports, buffer, ed25519, blake2b, blake, bs58check, core, BigNumber, elliptic, toBuffer) { 'use strict';
6
6
 
7
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
-
9
- var blake__default = /*#__PURE__*/_interopDefaultLegacy(blake);
10
- var bs58check__default = /*#__PURE__*/_interopDefaultLegacy(bs58check);
11
- var BigNumber__default = /*#__PURE__*/_interopDefaultLegacy(BigNumber);
12
- var elliptic__default = /*#__PURE__*/_interopDefaultLegacy(elliptic);
13
- var toBuffer__default = /*#__PURE__*/_interopDefaultLegacy(toBuffer);
14
-
15
- exports.Prefix = void 0;
16
- (function (Prefix) {
17
- Prefix["TZ1"] = "tz1";
18
- Prefix["TZ2"] = "tz2";
19
- Prefix["TZ3"] = "tz3";
20
- Prefix["TZ4"] = "tz4";
21
- Prefix["KT"] = "KT";
22
- Prefix["KT1"] = "KT1";
23
- Prefix["EDSK2"] = "edsk2";
24
- Prefix["SPSK"] = "spsk";
25
- Prefix["P2SK"] = "p2sk";
26
- Prefix["EDPK"] = "edpk";
27
- Prefix["SPPK"] = "sppk";
28
- Prefix["P2PK"] = "p2pk";
29
- Prefix["BLPK"] = "BLpk";
30
- Prefix["EDESK"] = "edesk";
31
- Prefix["SPESK"] = "spesk";
32
- Prefix["P2ESK"] = "p2esk";
33
- Prefix["EDSK"] = "edsk";
34
- Prefix["EDSIG"] = "edsig";
35
- Prefix["SPSIG"] = "spsig";
36
- Prefix["P2SIG"] = "p2sig";
37
- Prefix["SIG"] = "sig";
38
- Prefix["NET"] = "Net";
39
- Prefix["NCE"] = "nce";
40
- Prefix["B"] = "B";
41
- Prefix["O"] = "o";
42
- Prefix["LO"] = "Lo";
43
- Prefix["LLO"] = "LLo";
44
- Prefix["P"] = "P";
45
- Prefix["CO"] = "Co";
46
- Prefix["ID"] = "id";
47
- Prefix["EXPR"] = "expr";
48
- Prefix["TZ"] = "TZ";
49
- Prefix["VH"] = "vh";
50
- Prefix["SASK"] = "sask";
51
- Prefix["ZET1"] = "zet1";
52
- //rollups
53
- Prefix["TXR1"] = "txr1";
54
- Prefix["TXI"] = "txi";
55
- Prefix["TXM"] = "txm";
56
- Prefix["TXC"] = "txc";
57
- Prefix["TXMR"] = "txmr";
58
- Prefix["TXRL"] = "txM";
59
- Prefix["TXW"] = "txw";
60
- Prefix["SR1"] = "sr1";
61
- Prefix["SRC1"] = "src1";
62
- })(exports.Prefix || (exports.Prefix = {}));
63
- const prefix = {
64
- [exports.Prefix.TZ1]: new Uint8Array([6, 161, 159]),
65
- [exports.Prefix.TZ2]: new Uint8Array([6, 161, 161]),
66
- [exports.Prefix.TZ3]: new Uint8Array([6, 161, 164]),
67
- [exports.Prefix.TZ4]: new Uint8Array([6, 161, 166]),
68
- [exports.Prefix.KT]: new Uint8Array([2, 90, 121]),
69
- [exports.Prefix.KT1]: new Uint8Array([2, 90, 121]),
70
- [exports.Prefix.EDSK]: new Uint8Array([43, 246, 78, 7]),
71
- [exports.Prefix.EDSK2]: new Uint8Array([13, 15, 58, 7]),
72
- [exports.Prefix.SPSK]: new Uint8Array([17, 162, 224, 201]),
73
- [exports.Prefix.P2SK]: new Uint8Array([16, 81, 238, 189]),
74
- [exports.Prefix.EDPK]: new Uint8Array([13, 15, 37, 217]),
75
- [exports.Prefix.SPPK]: new Uint8Array([3, 254, 226, 86]),
76
- [exports.Prefix.P2PK]: new Uint8Array([3, 178, 139, 127]),
77
- [exports.Prefix.BLPK]: new Uint8Array([6, 149, 135, 204]),
78
- [exports.Prefix.EDESK]: new Uint8Array([7, 90, 60, 179, 41]),
79
- [exports.Prefix.SPESK]: new Uint8Array([0x09, 0xed, 0xf1, 0xae, 0x96]),
80
- [exports.Prefix.P2ESK]: new Uint8Array([0x09, 0x30, 0x39, 0x73, 0xab]),
81
- [exports.Prefix.EDSIG]: new Uint8Array([9, 245, 205, 134, 18]),
82
- [exports.Prefix.SPSIG]: new Uint8Array([13, 115, 101, 19, 63]),
83
- [exports.Prefix.P2SIG]: new Uint8Array([54, 240, 44, 52]),
84
- [exports.Prefix.SIG]: new Uint8Array([4, 130, 43]),
85
- [exports.Prefix.NET]: new Uint8Array([87, 82, 0]),
86
- [exports.Prefix.NCE]: new Uint8Array([69, 220, 169]),
87
- [exports.Prefix.B]: new Uint8Array([1, 52]),
88
- [exports.Prefix.O]: new Uint8Array([5, 116]),
89
- [exports.Prefix.LO]: new Uint8Array([133, 233]),
90
- [exports.Prefix.LLO]: new Uint8Array([29, 159, 109]),
91
- [exports.Prefix.P]: new Uint8Array([2, 170]),
92
- [exports.Prefix.CO]: new Uint8Array([79, 179]),
93
- [exports.Prefix.ID]: new Uint8Array([153, 103]),
94
- [exports.Prefix.EXPR]: new Uint8Array([13, 44, 64, 27]),
95
- // Legacy prefix
96
- [exports.Prefix.TZ]: new Uint8Array([2, 90, 121]),
97
- [exports.Prefix.VH]: new Uint8Array([1, 106, 242]),
98
- [exports.Prefix.SASK]: new Uint8Array([11, 237, 20, 92]),
99
- [exports.Prefix.ZET1]: new Uint8Array([18, 71, 40, 223]),
100
- [exports.Prefix.TXR1]: new Uint8Array([1, 128, 120, 31]),
101
- [exports.Prefix.TXI]: new Uint8Array([79, 148, 196]),
102
- [exports.Prefix.TXM]: new Uint8Array([79, 149, 30]),
103
- [exports.Prefix.TXC]: new Uint8Array([79, 148, 17]),
104
- [exports.Prefix.TXMR]: new Uint8Array([18, 7, 206, 87]),
105
- [exports.Prefix.TXRL]: new Uint8Array([79, 146, 82]),
106
- [exports.Prefix.TXW]: new Uint8Array([79, 150, 72]),
107
- [exports.Prefix.SR1]: new Uint8Array([6, 124, 117]),
108
- [exports.Prefix.SRC1]: new Uint8Array([17, 165, 134, 138]),
109
- };
110
- const prefixLength = {
111
- [exports.Prefix.TZ1]: 20,
112
- [exports.Prefix.TZ2]: 20,
113
- [exports.Prefix.TZ3]: 20,
114
- [exports.Prefix.TZ4]: 20,
115
- [exports.Prefix.KT]: 20,
116
- [exports.Prefix.KT1]: 20,
117
- [exports.Prefix.EDPK]: 32,
118
- [exports.Prefix.SPPK]: 33,
119
- [exports.Prefix.P2PK]: 33,
120
- //working with value in comment for base58.ml line 445 but not consistent with the three above
121
- [exports.Prefix.BLPK]: 48,
122
- [exports.Prefix.EDSIG]: 64,
123
- [exports.Prefix.SPSIG]: 64,
124
- [exports.Prefix.P2SIG]: 64,
125
- [exports.Prefix.SIG]: 64,
126
- [exports.Prefix.NET]: 4,
127
- [exports.Prefix.B]: 32,
128
- [exports.Prefix.P]: 32,
129
- [exports.Prefix.O]: 32,
130
- [exports.Prefix.VH]: 32,
131
- [exports.Prefix.SASK]: 169,
132
- [exports.Prefix.ZET1]: 43,
133
- [exports.Prefix.TXR1]: 20,
134
- [exports.Prefix.TXI]: 32,
135
- [exports.Prefix.TXM]: 32,
136
- [exports.Prefix.TXC]: 32,
137
- [exports.Prefix.TXMR]: 32,
138
- [exports.Prefix.TXRL]: 32,
139
- [exports.Prefix.TXW]: 32,
140
- [exports.Prefix.SR1]: 20,
141
- [exports.Prefix.SRC1]: 32,
7
+ exports.Prefix = void 0;
8
+ (function (Prefix) {
9
+ Prefix["TZ1"] = "tz1";
10
+ Prefix["TZ2"] = "tz2";
11
+ Prefix["TZ3"] = "tz3";
12
+ Prefix["TZ4"] = "tz4";
13
+ Prefix["KT"] = "KT";
14
+ Prefix["KT1"] = "KT1";
15
+ Prefix["EDSK2"] = "edsk2";
16
+ Prefix["SPSK"] = "spsk";
17
+ Prefix["P2SK"] = "p2sk";
18
+ Prefix["EDPK"] = "edpk";
19
+ Prefix["SPPK"] = "sppk";
20
+ Prefix["P2PK"] = "p2pk";
21
+ Prefix["BLPK"] = "BLpk";
22
+ Prefix["EDESK"] = "edesk";
23
+ Prefix["SPESK"] = "spesk";
24
+ Prefix["P2ESK"] = "p2esk";
25
+ Prefix["EDSK"] = "edsk";
26
+ Prefix["EDSIG"] = "edsig";
27
+ Prefix["SPSIG"] = "spsig";
28
+ Prefix["P2SIG"] = "p2sig";
29
+ Prefix["SIG"] = "sig";
30
+ Prefix["NET"] = "Net";
31
+ Prefix["NCE"] = "nce";
32
+ Prefix["B"] = "B";
33
+ Prefix["O"] = "o";
34
+ Prefix["LO"] = "Lo";
35
+ Prefix["LLO"] = "LLo";
36
+ Prefix["P"] = "P";
37
+ Prefix["CO"] = "Co";
38
+ Prefix["ID"] = "id";
39
+ Prefix["EXPR"] = "expr";
40
+ Prefix["TZ"] = "TZ";
41
+ Prefix["VH"] = "vh";
42
+ Prefix["SASK"] = "sask";
43
+ Prefix["ZET1"] = "zet1";
44
+ //rollups
45
+ Prefix["TXR1"] = "txr1";
46
+ Prefix["TXI"] = "txi";
47
+ Prefix["TXM"] = "txm";
48
+ Prefix["TXC"] = "txc";
49
+ Prefix["TXMR"] = "txmr";
50
+ Prefix["TXRL"] = "txM";
51
+ Prefix["TXW"] = "txw";
52
+ Prefix["SR1"] = "sr1";
53
+ Prefix["SRC1"] = "src1";
54
+ })(exports.Prefix || (exports.Prefix = {}));
55
+ const prefix = {
56
+ [exports.Prefix.TZ1]: new Uint8Array([6, 161, 159]),
57
+ [exports.Prefix.TZ2]: new Uint8Array([6, 161, 161]),
58
+ [exports.Prefix.TZ3]: new Uint8Array([6, 161, 164]),
59
+ [exports.Prefix.TZ4]: new Uint8Array([6, 161, 166]),
60
+ [exports.Prefix.KT]: new Uint8Array([2, 90, 121]),
61
+ [exports.Prefix.KT1]: new Uint8Array([2, 90, 121]),
62
+ [exports.Prefix.EDSK]: new Uint8Array([43, 246, 78, 7]),
63
+ [exports.Prefix.EDSK2]: new Uint8Array([13, 15, 58, 7]),
64
+ [exports.Prefix.SPSK]: new Uint8Array([17, 162, 224, 201]),
65
+ [exports.Prefix.P2SK]: new Uint8Array([16, 81, 238, 189]),
66
+ [exports.Prefix.EDPK]: new Uint8Array([13, 15, 37, 217]),
67
+ [exports.Prefix.SPPK]: new Uint8Array([3, 254, 226, 86]),
68
+ [exports.Prefix.P2PK]: new Uint8Array([3, 178, 139, 127]),
69
+ [exports.Prefix.BLPK]: new Uint8Array([6, 149, 135, 204]),
70
+ [exports.Prefix.EDESK]: new Uint8Array([7, 90, 60, 179, 41]),
71
+ [exports.Prefix.SPESK]: new Uint8Array([0x09, 0xed, 0xf1, 0xae, 0x96]),
72
+ [exports.Prefix.P2ESK]: new Uint8Array([0x09, 0x30, 0x39, 0x73, 0xab]),
73
+ [exports.Prefix.EDSIG]: new Uint8Array([9, 245, 205, 134, 18]),
74
+ [exports.Prefix.SPSIG]: new Uint8Array([13, 115, 101, 19, 63]),
75
+ [exports.Prefix.P2SIG]: new Uint8Array([54, 240, 44, 52]),
76
+ [exports.Prefix.SIG]: new Uint8Array([4, 130, 43]),
77
+ [exports.Prefix.NET]: new Uint8Array([87, 82, 0]),
78
+ [exports.Prefix.NCE]: new Uint8Array([69, 220, 169]),
79
+ [exports.Prefix.B]: new Uint8Array([1, 52]),
80
+ [exports.Prefix.O]: new Uint8Array([5, 116]),
81
+ [exports.Prefix.LO]: new Uint8Array([133, 233]),
82
+ [exports.Prefix.LLO]: new Uint8Array([29, 159, 109]),
83
+ [exports.Prefix.P]: new Uint8Array([2, 170]),
84
+ [exports.Prefix.CO]: new Uint8Array([79, 179]),
85
+ [exports.Prefix.ID]: new Uint8Array([153, 103]),
86
+ [exports.Prefix.EXPR]: new Uint8Array([13, 44, 64, 27]),
87
+ // Legacy prefix
88
+ [exports.Prefix.TZ]: new Uint8Array([2, 90, 121]),
89
+ [exports.Prefix.VH]: new Uint8Array([1, 106, 242]),
90
+ [exports.Prefix.SASK]: new Uint8Array([11, 237, 20, 92]),
91
+ [exports.Prefix.ZET1]: new Uint8Array([18, 71, 40, 223]),
92
+ [exports.Prefix.TXR1]: new Uint8Array([1, 128, 120, 31]),
93
+ [exports.Prefix.TXI]: new Uint8Array([79, 148, 196]),
94
+ [exports.Prefix.TXM]: new Uint8Array([79, 149, 30]),
95
+ [exports.Prefix.TXC]: new Uint8Array([79, 148, 17]),
96
+ [exports.Prefix.TXMR]: new Uint8Array([18, 7, 206, 87]),
97
+ [exports.Prefix.TXRL]: new Uint8Array([79, 146, 82]),
98
+ [exports.Prefix.TXW]: new Uint8Array([79, 150, 72]),
99
+ [exports.Prefix.SR1]: new Uint8Array([6, 124, 117]),
100
+ [exports.Prefix.SRC1]: new Uint8Array([17, 165, 134, 138]),
101
+ };
102
+ const prefixLength = {
103
+ [exports.Prefix.TZ1]: 20,
104
+ [exports.Prefix.TZ2]: 20,
105
+ [exports.Prefix.TZ3]: 20,
106
+ [exports.Prefix.TZ4]: 20,
107
+ [exports.Prefix.KT]: 20,
108
+ [exports.Prefix.KT1]: 20,
109
+ [exports.Prefix.EDPK]: 32,
110
+ [exports.Prefix.SPPK]: 33,
111
+ [exports.Prefix.P2PK]: 33,
112
+ //working with value in comment for base58.ml line 445 but not consistent with the three above
113
+ [exports.Prefix.BLPK]: 48,
114
+ [exports.Prefix.EDSIG]: 64,
115
+ [exports.Prefix.SPSIG]: 64,
116
+ [exports.Prefix.P2SIG]: 64,
117
+ [exports.Prefix.SIG]: 64,
118
+ [exports.Prefix.NET]: 4,
119
+ [exports.Prefix.B]: 32,
120
+ [exports.Prefix.P]: 32,
121
+ [exports.Prefix.O]: 32,
122
+ [exports.Prefix.VH]: 32,
123
+ [exports.Prefix.SASK]: 169,
124
+ [exports.Prefix.ZET1]: 43,
125
+ [exports.Prefix.TXR1]: 20,
126
+ [exports.Prefix.TXI]: 32,
127
+ [exports.Prefix.TXM]: 32,
128
+ [exports.Prefix.TXC]: 32,
129
+ [exports.Prefix.TXMR]: 32,
130
+ [exports.Prefix.TXRL]: 32,
131
+ [exports.Prefix.TXW]: 32,
132
+ [exports.Prefix.SR1]: 20,
133
+ [exports.Prefix.SRC1]: 32,
142
134
  };
143
135
 
144
- /**
145
- * @description Verify signature of a payload
146
- *
147
- * @param messageBytes The forged message including the magic byte (11 for block,
148
- * 12 for preendorsement, 13 for endorsement, 3 for generic, 5 for the PACK format of michelson)
149
- * @param publicKey The public key to verify the signature against
150
- * @param signature The signature to verify
151
- * @returns A boolean indicating if the signature matches
152
- * @throws {@link InvalidPublicKeyError} | {@link InvalidSignatureError} | {@link InvalidMessageError}
153
- * @example
154
- * ```
155
- * const message = '03d0c10e3ed11d7c6e3357f6ef335bab9e8f2bd54d0ce20c482e241191a6e4b8ce6c01be917311d9ac46959750e405d57e268e2ed9e174a80794fbd504e12a4a000141eb3781afed2f69679ff2bbe1c5375950b0e40d00ff000000005e05050505050507070100000024747a32526773486e74516b72794670707352466261313652546656503539684b72654a4d07070100000024747a315a6672455263414c42776d4171776f6e525859565142445439426a4e6a42484a750001';
156
- * const pk = 'sppk7c7hkPj47yjYFEHX85q46sFJGw6RBrqoVSHwAJAT4e14KJwzoey';
157
- * const sig = 'spsig1cdLkp1RLgUHAp13aRFkZ6MQDPp7xCnjAExGL3MBSdMDmT6JgQSX8cufyDgJRM3sinFtiCzLbsyP6d365EHoNevxhT47nx'
158
- *
159
- * const response = verifySignature(message, pk, sig);
160
- * ```
161
- *
162
- */
163
- function verifySignature(messageBytes, publicKey, signature, watermark) {
164
- const pkPrefix = validatePkAndExtractPrefix(publicKey);
165
- const sigPrefix = validateSigAndExtractPrefix(signature);
166
- const decodedPublicKey = b58cdecode(publicKey, prefix[pkPrefix]);
167
- const decodedSig = b58cdecode(signature, prefix[sigPrefix]);
168
- let messageBuf = hex2buf(validateMessageNotEmpty(messageBytes));
169
- if (typeof watermark !== 'undefined') {
170
- messageBuf = mergebuf(watermark, messageBuf);
171
- }
172
- const bytesHash = blake2b.hash(messageBuf, 32);
173
- if (pkPrefix === exports.Prefix.EDPK) {
174
- return verifyEdSignature(decodedSig, bytesHash, decodedPublicKey);
175
- }
176
- else if (pkPrefix === exports.Prefix.SPPK) {
177
- return verifySpSignature(decodedSig, bytesHash, decodedPublicKey);
178
- }
179
- else if (pkPrefix === exports.Prefix.P2PK) {
180
- return verifyP2Signature(decodedSig, bytesHash, decodedPublicKey);
181
- }
182
- else {
183
- return false;
184
- }
185
- }
186
- function validateMessageNotEmpty(message) {
187
- if (message === '') {
188
- throw new core.InvalidMessageError(message, `can't be empty`);
189
- }
190
- return message;
191
- }
192
- function validatePkAndExtractPrefix(publicKey) {
193
- if (publicKey === '') {
194
- throw new core.InvalidPublicKeyError(publicKey, `can't be empty`);
195
- }
196
- const pkPrefix = publicKey.substring(0, 4);
197
- const publicKeyValidation = validatePublicKey(publicKey);
198
- if (publicKeyValidation !== exports.ValidationResult.VALID) {
199
- throw new core.InvalidPublicKeyError(publicKey, invalidDetail(publicKeyValidation));
200
- }
201
- return pkPrefix;
202
- }
203
- function validateSigAndExtractPrefix(signature) {
204
- const signaturePrefix = signature.startsWith('sig')
205
- ? signature.substring(0, 3)
206
- : signature.substring(0, 5);
207
- const validation = validateSignature(signature);
208
- if (validation !== exports.ValidationResult.VALID) {
209
- throw new core.InvalidSignatureError(signature, invalidDetail(validation));
210
- }
211
- return signaturePrefix;
212
- }
213
- function verifyEdSignature(decodedSig, bytesHash, decodedPublicKey) {
214
- try {
215
- return ed25519.verify(decodedPublicKey, bytesHash, decodedSig);
216
- }
217
- catch (e) {
218
- return false;
219
- }
220
- }
221
- function verifySpSignature(decodedSig, bytesHash, decodedPublicKey) {
222
- const key = new elliptic__default["default"].ec('secp256k1').keyFromPublic(decodedPublicKey);
223
- return verifySpOrP2Sig(decodedSig, bytesHash, key);
224
- }
225
- function verifyP2Signature(decodedSig, bytesHash, decodedPublicKey) {
226
- const key = new elliptic__default["default"].ec('p256').keyFromPublic(decodedPublicKey);
227
- return verifySpOrP2Sig(decodedSig, bytesHash, key);
228
- }
229
- function verifySpOrP2Sig(decodedSig, bytesHash, key) {
230
- const hexSig = buf2hex(toBuffer__default["default"](decodedSig));
231
- const match = hexSig.match(/([a-f\d]{64})/gi);
232
- if (match) {
233
- try {
234
- const [r, s] = match;
235
- return key.verify(bytesHash, { r, s });
236
- }
237
- catch (e) {
238
- return false;
239
- }
240
- }
241
- return false;
136
+ /**
137
+ * @description Verify signature of a payload
138
+ *
139
+ * @param messageBytes The forged message including the magic byte (11 for block,
140
+ * 12 for preendorsement, 13 for endorsement, 3 for generic, 5 for the PACK format of michelson)
141
+ * @param publicKey The public key to verify the signature against
142
+ * @param signature The signature to verify
143
+ * @returns A boolean indicating if the signature matches
144
+ * @throws {@link InvalidPublicKeyError} | {@link InvalidSignatureError} | {@link InvalidMessageError}
145
+ * @example
146
+ * ```
147
+ * const message = '03d0c10e3ed11d7c6e3357f6ef335bab9e8f2bd54d0ce20c482e241191a6e4b8ce6c01be917311d9ac46959750e405d57e268e2ed9e174a80794fbd504e12a4a000141eb3781afed2f69679ff2bbe1c5375950b0e40d00ff000000005e05050505050507070100000024747a32526773486e74516b72794670707352466261313652546656503539684b72654a4d07070100000024747a315a6672455263414c42776d4171776f6e525859565142445439426a4e6a42484a750001';
148
+ * const pk = 'sppk7c7hkPj47yjYFEHX85q46sFJGw6RBrqoVSHwAJAT4e14KJwzoey';
149
+ * const sig = 'spsig1cdLkp1RLgUHAp13aRFkZ6MQDPp7xCnjAExGL3MBSdMDmT6JgQSX8cufyDgJRM3sinFtiCzLbsyP6d365EHoNevxhT47nx'
150
+ *
151
+ * const response = verifySignature(message, pk, sig);
152
+ * ```
153
+ *
154
+ */
155
+ function verifySignature(messageBytes, publicKey, signature, watermark) {
156
+ const pkPrefix = validatePkAndExtractPrefix(publicKey);
157
+ const sigPrefix = validateSigAndExtractPrefix(signature);
158
+ const decodedPublicKey = b58cdecode(publicKey, prefix[pkPrefix]);
159
+ const decodedSig = b58cdecode(signature, prefix[sigPrefix]);
160
+ let messageBuf = hex2buf(validateMessageNotEmpty(messageBytes));
161
+ if (typeof watermark !== 'undefined') {
162
+ messageBuf = mergebuf(watermark, messageBuf);
163
+ }
164
+ const bytesHash = blake2b.hash(messageBuf, 32);
165
+ if (pkPrefix === exports.Prefix.EDPK) {
166
+ return verifyEdSignature(decodedSig, bytesHash, decodedPublicKey);
167
+ }
168
+ else if (pkPrefix === exports.Prefix.SPPK) {
169
+ return verifySpSignature(decodedSig, bytesHash, decodedPublicKey);
170
+ }
171
+ else if (pkPrefix === exports.Prefix.P2PK) {
172
+ return verifyP2Signature(decodedSig, bytesHash, decodedPublicKey);
173
+ }
174
+ else {
175
+ return false;
176
+ }
177
+ }
178
+ function validateMessageNotEmpty(message) {
179
+ if (message === '') {
180
+ throw new core.InvalidMessageError(message, `can't be empty`);
181
+ }
182
+ return message;
183
+ }
184
+ function validatePkAndExtractPrefix(publicKey) {
185
+ if (publicKey === '') {
186
+ throw new core.InvalidPublicKeyError(publicKey, `can't be empty`);
187
+ }
188
+ const pkPrefix = publicKey.substring(0, 4);
189
+ const publicKeyValidation = validatePublicKey(publicKey);
190
+ if (publicKeyValidation !== exports.ValidationResult.VALID) {
191
+ throw new core.InvalidPublicKeyError(publicKey, invalidDetail(publicKeyValidation));
192
+ }
193
+ return pkPrefix;
194
+ }
195
+ function validateSigAndExtractPrefix(signature) {
196
+ const signaturePrefix = signature.startsWith('sig')
197
+ ? signature.substring(0, 3)
198
+ : signature.substring(0, 5);
199
+ const validation = validateSignature(signature);
200
+ if (validation !== exports.ValidationResult.VALID) {
201
+ throw new core.InvalidSignatureError(signature, invalidDetail(validation));
202
+ }
203
+ return signaturePrefix;
204
+ }
205
+ function verifyEdSignature(decodedSig, bytesHash, decodedPublicKey) {
206
+ try {
207
+ return ed25519.verify(decodedPublicKey, bytesHash, decodedSig);
208
+ }
209
+ catch (e) {
210
+ return false;
211
+ }
212
+ }
213
+ function verifySpSignature(decodedSig, bytesHash, decodedPublicKey) {
214
+ const key = new elliptic.ec('secp256k1').keyFromPublic(decodedPublicKey);
215
+ return verifySpOrP2Sig(decodedSig, bytesHash, key);
216
+ }
217
+ function verifyP2Signature(decodedSig, bytesHash, decodedPublicKey) {
218
+ const key = new elliptic.ec('p256').keyFromPublic(decodedPublicKey);
219
+ return verifySpOrP2Sig(decodedSig, bytesHash, key);
220
+ }
221
+ function verifySpOrP2Sig(decodedSig, bytesHash, key) {
222
+ const hexSig = buf2hex(toBuffer(decodedSig));
223
+ const match = hexSig.match(/([a-f\d]{64})/gi);
224
+ if (match) {
225
+ try {
226
+ const [r, s] = match;
227
+ return key.verify(bytesHash, { r, s });
228
+ }
229
+ catch (e) {
230
+ return false;
231
+ }
232
+ }
233
+ return false;
242
234
  }
243
235
 
244
- /**
245
- * @category Error
246
- * @description Error that indicates invalid protocol hash being passed or used
247
- */
248
- class InvalidProtocolHashError extends core.ParameterValidationError {
249
- constructor(protocolHash, errorDetails) {
250
- super();
251
- this.protocolHash = protocolHash;
252
- this.errorDetails = errorDetails;
253
- this.name = 'InvalidProtocolHashError';
254
- this.name = 'InvalidProtocolHashError';
255
- this.message = `The protocol hash '${protocolHash}' is invalid`;
256
- errorDetails ? (this.message += `: ${errorDetails}`) : null;
257
- }
258
- }
259
- /**
260
- * @category Error
261
- * @description Error that indicates unable to convert data type from one to another
262
- */
263
- class ValueConversionError extends core.UnsupportedActionError {
264
- constructor(value, desiredType) {
265
- super();
266
- this.value = value;
267
- this.desiredType = desiredType;
268
- this.name = 'ValueConversionError';
269
- this.message = `Unable to convert ${value} to a ${desiredType}`;
270
- }
236
+ /**
237
+ * @category Error
238
+ * @description Error that indicates invalid protocol hash being passed or used
239
+ */
240
+ class InvalidProtocolHashError extends core.ParameterValidationError {
241
+ constructor(protocolHash, errorDetails) {
242
+ super();
243
+ this.protocolHash = protocolHash;
244
+ this.errorDetails = errorDetails;
245
+ this.name = 'InvalidProtocolHashError';
246
+ this.name = 'InvalidProtocolHashError';
247
+ this.message = `The protocol hash '${protocolHash}' is invalid`;
248
+ errorDetails ? (this.message += `: ${errorDetails}`) : null;
249
+ }
250
+ }
251
+ /**
252
+ * @category Error
253
+ * @description Error that indicates unable to convert data type from one to another
254
+ */
255
+ class ValueConversionError extends core.UnsupportedActionError {
256
+ constructor(value, desiredType) {
257
+ super();
258
+ this.value = value;
259
+ this.desiredType = desiredType;
260
+ this.name = 'ValueConversionError';
261
+ this.message = `Unable to convert ${value} to a ${desiredType}`;
262
+ }
271
263
  }
272
264
 
273
- exports.ValidationResult = void 0;
274
- (function (ValidationResult) {
275
- ValidationResult[ValidationResult["NO_PREFIX_MATCHED"] = 0] = "NO_PREFIX_MATCHED";
276
- ValidationResult[ValidationResult["INVALID_CHECKSUM"] = 1] = "INVALID_CHECKSUM";
277
- ValidationResult[ValidationResult["INVALID_LENGTH"] = 2] = "INVALID_LENGTH";
278
- ValidationResult[ValidationResult["VALID"] = 3] = "VALID";
279
- })(exports.ValidationResult || (exports.ValidationResult = {}));
280
- function isValidPrefix(value) {
281
- if (typeof value !== 'string') {
282
- return false;
283
- }
284
- return value in prefix;
285
- }
286
- /**
287
- * @description This function is called by the validation functions ([[validateAddress]], [[validateChain]], [[validateContractAddress]], [[validateKeyHash]], [[validateSignature]], [[validatePublicKey]]).
288
- * Verify if the value has the right prefix or return `NO_PREFIX_MATCHED`,
289
- * decode the value using base58 and return `INVALID_CHECKSUM` if it fails,
290
- * check if the length of the value matches the prefix type or return `INVALID_LENGTH`.
291
- * If all checks pass, return `VALID`.
292
- *
293
- * @param value Value to validate
294
- * @param prefixes prefix the value should have
295
- */
296
- function validatePrefixedValue(value, prefixes) {
297
- const match = new RegExp(`^(${prefixes.join('|')})`).exec(value);
298
- if (!match || match.length === 0) {
299
- return exports.ValidationResult.NO_PREFIX_MATCHED;
300
- }
301
- const prefixKey = match[0];
302
- if (!isValidPrefix(prefixKey)) {
303
- return exports.ValidationResult.NO_PREFIX_MATCHED;
304
- }
305
- // Check whether annotation exist before starting validation
306
- if (value.includes('%')) {
307
- value = value.split('%')[0];
308
- }
309
- const kt1Regex = /^(KT1\w{33})$/;
310
- if (!kt1Regex.test(value) && prefixKey === 'KT1') {
311
- return exports.ValidationResult.INVALID_CHECKSUM;
312
- }
313
- // decodeUnsafe return undefined if decoding fail
314
- let decoded = bs58check__default["default"].decodeUnsafe(value);
315
- if (!decoded) {
316
- return exports.ValidationResult.INVALID_CHECKSUM;
317
- }
318
- decoded = decoded.slice(prefix[prefixKey].length);
319
- if (decoded.length !== prefixLength[prefixKey]) {
320
- return exports.ValidationResult.INVALID_LENGTH;
321
- }
322
- return exports.ValidationResult.VALID;
323
- }
324
- const implicitPrefix = [exports.Prefix.TZ1, exports.Prefix.TZ2, exports.Prefix.TZ3, exports.Prefix.TZ4];
325
- const contractPrefix = [exports.Prefix.KT1, exports.Prefix.TXR1];
326
- const signaturePrefix = [exports.Prefix.EDSIG, exports.Prefix.P2SIG, exports.Prefix.SPSIG, exports.Prefix.SIG];
327
- const pkPrefix = [exports.Prefix.EDPK, exports.Prefix.SPPK, exports.Prefix.P2PK, exports.Prefix.BLPK];
328
- const operationPrefix = [exports.Prefix.O];
329
- const protocolPrefix = [exports.Prefix.P];
330
- const blockPrefix = [exports.Prefix.B];
331
- const smartRollupPrefix = [exports.Prefix.SR1];
332
- /**
333
- * @description Used to check if an address or a contract address is valid.
334
- *
335
- * @returns
336
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
337
- *
338
- * @example
339
- * ```
340
- * import { validateAddress } from '@taquito/utils';
341
- * const pkh = 'tz1L9r8mWmRPndRhuvMCWESLGSVeFzQ9NAWx'
342
- * const validation = validateAddress(pkh)
343
- * console.log(validation)
344
- * // This example return 3 which correspond to VALID
345
- * ```
346
- */
347
- function validateAddress(value) {
348
- return validatePrefixedValue(value, [...implicitPrefix, ...contractPrefix, ...smartRollupPrefix]);
349
- }
350
- /**
351
- * @description Used to check if a chain id is valid.
352
- *
353
- * @returns
354
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
355
- *
356
- * @example
357
- * ```
358
- * import { validateChain } from '@taquito/utils';
359
- * const chainId = 'NetXdQprcVkpaWU'
360
- * const validation = validateChain(chainId)
361
- * console.log(validation)
362
- * // This example return 3 which correspond to VALID
363
- * ```
364
- */
365
- function validateChain(value) {
366
- return validatePrefixedValue(value, [exports.Prefix.NET]);
367
- }
368
- /**
369
- * @description Used to check if a contract address is valid.
370
- *
371
- * @returns
372
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
373
- *
374
- * @example
375
- * ```
376
- * import { validateContractAddress } from '@taquito/utils';
377
- * const contractAddress = 'KT1JVErLYTgtY8uGGZ4mso2npTSxqVLDRVbC'
378
- * const validation = validateContractAddress(contractAddress)
379
- * console.log(validation)
380
- * // This example return 3 which correspond to VALID
381
- * ```
382
- */
383
- function validateContractAddress(value) {
384
- return validatePrefixedValue(value, contractPrefix);
385
- }
386
- /**
387
- * @description Used to check if a key hash is valid.
388
- *
389
- * @returns
390
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
391
- *
392
- * @example
393
- * ```
394
- * import { validateKeyHash } from '@taquito/utils';
395
- * const keyHashWithoutPrefix = '1L9r8mWmRPndRhuvMCWESLGSVeFzQ9NAWx'
396
- * const validation = validateKeyHash(keyHashWithoutPrefix)
397
- * console.log(validation)
398
- * // This example return 0 which correspond to NO_PREFIX_MATCHED
399
- * ```
400
- */
401
- function validateKeyHash(value) {
402
- return validatePrefixedValue(value, implicitPrefix);
403
- }
404
- /**
405
- * @description Used to check if a signature is valid.
406
- *
407
- * @returns
408
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
409
- *
410
- * @example
411
- * ```
412
- * import { validateSignature } from '@taquito/utils';
413
- * const signature = 'edsigtkpiSSschcaCt9pUVrpNPf7TTcgvgDEDD6NCEHMy8NNQJCGnMfLZzYoQj74yLjo9wx6MPVV29CvVzgi7qEcEUok3k7AuMg'
414
- * const validation = validateSignature(signature)
415
- * console.log(validation)
416
- * // This example return 3 which correspond to VALID
417
- * ```
418
- */
419
- function validateSignature(value) {
420
- return validatePrefixedValue(value, signaturePrefix);
421
- }
422
- /**
423
- * @description Used to check if a public key is valid.
424
- *
425
- * @returns
426
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
427
- *
428
- * @example
429
- * ```
430
- * import { validatePublicKey } from '@taquito/utils';
431
- * const publicKey = 'edpkvS5QFv7KRGfa3b87gg9DBpxSm3NpSwnjhUjNBQrRUUR66F7C9g'
432
- * const validation = validatePublicKey(publicKey)
433
- * console.log(validation)
434
- * // This example return 3 which correspond to VALID
435
- * ```
436
- */
437
- function validatePublicKey(value) {
438
- return validatePrefixedValue(value, pkPrefix);
439
- }
440
- /**
441
- * @description Used to check if an operation hash is valid.
442
- *
443
- * @returns
444
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
445
- *
446
- * @example
447
- * ```
448
- * import { validateOperation } from '@taquito/utils';
449
- * const operationHash = 'oo6JPEAy8VuMRGaFuMmLNFFGdJgiaKfnmT1CpHJfKP3Ye5ZahiP'
450
- * const validation = validateOperation(operationHash)
451
- * console.log(validation)
452
- * // This example return 3 which correspond to VALID
453
- * ```
454
- */
455
- function validateOperation(value) {
456
- return validatePrefixedValue(value, operationPrefix);
457
- }
458
- /**
459
- * @description Used to check if a protocol hash is valid.
460
- *
461
- * @returns
462
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
463
- *
464
- * @example
465
- * ```
466
- * import { validateProtocol } from '@taquito/utils';
467
- * const protocolHash = 'PtHangz2aRngywmSRGGvrcTyMbbdpWdpFKuS4uMWxg2RaH9i1qx'
468
- * const validation = validateProtocol(protocolHash)
469
- * console.log(validation)
470
- * // This example return 3 which correspond to VALID
471
- * ```
472
- */
473
- function validateProtocol(value) {
474
- return validatePrefixedValue(value, protocolPrefix);
475
- }
476
- /**
477
- * @description Used to check if a block hash is valid.
478
- *
479
- * @returns
480
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
481
- *
482
- * @example
483
- * ```
484
- * import { validateBlock } from '@taquito/utils';
485
- * const blockHash = 'PtHangz2aRngywmSRGGvrcTyMbbdpWdpFKuS4uMWxg2RaH9i1qx'
486
- * const validation = validateBlock(blockHash)
487
- * console.log(validation)
488
- * // This example return 3 which correspond to VALID
489
- * ```
490
- */
491
- function validateBlock(value) {
492
- return validatePrefixedValue(value, blockPrefix);
493
- }
494
- /**
495
- * @description Used to check if a spending key is valid.
496
- * @returns 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
497
- *
498
- */
499
- function validateSpendingKey(value) {
500
- return validatePrefixedValue(value, [exports.Prefix.SASK]);
501
- }
502
- function invalidDetail(validation) {
503
- switch (validation) {
504
- case exports.ValidationResult.NO_PREFIX_MATCHED:
505
- return 'with unsupported prefix';
506
- case exports.ValidationResult.INVALID_CHECKSUM:
507
- return 'failed checksum';
508
- case exports.ValidationResult.INVALID_LENGTH:
509
- return 'with incorrect length';
510
- default:
511
- return '';
512
- }
513
- }
514
- function validateSmartRollupAddress(value) {
515
- return validatePrefixedValue(value, [...smartRollupPrefix]);
265
+ exports.ValidationResult = void 0;
266
+ (function (ValidationResult) {
267
+ ValidationResult[ValidationResult["NO_PREFIX_MATCHED"] = 0] = "NO_PREFIX_MATCHED";
268
+ ValidationResult[ValidationResult["INVALID_CHECKSUM"] = 1] = "INVALID_CHECKSUM";
269
+ ValidationResult[ValidationResult["INVALID_LENGTH"] = 2] = "INVALID_LENGTH";
270
+ ValidationResult[ValidationResult["VALID"] = 3] = "VALID";
271
+ })(exports.ValidationResult || (exports.ValidationResult = {}));
272
+ function isValidPrefix(value) {
273
+ if (typeof value !== 'string') {
274
+ return false;
275
+ }
276
+ return value in prefix;
277
+ }
278
+ /**
279
+ * @description This function is called by the validation functions ([[validateAddress]], [[validateChain]], [[validateContractAddress]], [[validateKeyHash]], [[validateSignature]], [[validatePublicKey]]).
280
+ * Verify if the value has the right prefix or return `NO_PREFIX_MATCHED`,
281
+ * decode the value using base58 and return `INVALID_CHECKSUM` if it fails,
282
+ * check if the length of the value matches the prefix type or return `INVALID_LENGTH`.
283
+ * If all checks pass, return `VALID`.
284
+ *
285
+ * @param value Value to validate
286
+ * @param prefixes prefix the value should have
287
+ */
288
+ function validatePrefixedValue(value, prefixes) {
289
+ const match = new RegExp(`^(${prefixes.join('|')})`).exec(value);
290
+ if (!match || match.length === 0) {
291
+ return exports.ValidationResult.NO_PREFIX_MATCHED;
292
+ }
293
+ const prefixKey = match[0];
294
+ if (!isValidPrefix(prefixKey)) {
295
+ return exports.ValidationResult.NO_PREFIX_MATCHED;
296
+ }
297
+ // Check whether annotation exist before starting validation
298
+ if (value.includes('%')) {
299
+ value = value.split('%')[0];
300
+ }
301
+ const kt1Regex = /^(KT1\w{33})$/;
302
+ if (!kt1Regex.test(value) && prefixKey === 'KT1') {
303
+ return exports.ValidationResult.INVALID_CHECKSUM;
304
+ }
305
+ // decodeUnsafe return undefined if decoding fail
306
+ let decoded = bs58check.decodeUnsafe(value);
307
+ if (!decoded) {
308
+ return exports.ValidationResult.INVALID_CHECKSUM;
309
+ }
310
+ decoded = decoded.slice(prefix[prefixKey].length);
311
+ if (decoded.length !== prefixLength[prefixKey]) {
312
+ return exports.ValidationResult.INVALID_LENGTH;
313
+ }
314
+ return exports.ValidationResult.VALID;
315
+ }
316
+ const implicitPrefix = [exports.Prefix.TZ1, exports.Prefix.TZ2, exports.Prefix.TZ3, exports.Prefix.TZ4];
317
+ const contractPrefix = [exports.Prefix.KT1, exports.Prefix.TXR1];
318
+ const signaturePrefix = [exports.Prefix.EDSIG, exports.Prefix.P2SIG, exports.Prefix.SPSIG, exports.Prefix.SIG];
319
+ const pkPrefix = [exports.Prefix.EDPK, exports.Prefix.SPPK, exports.Prefix.P2PK, exports.Prefix.BLPK];
320
+ const operationPrefix = [exports.Prefix.O];
321
+ const protocolPrefix = [exports.Prefix.P];
322
+ const blockPrefix = [exports.Prefix.B];
323
+ const smartRollupPrefix = [exports.Prefix.SR1];
324
+ /**
325
+ * @description Used to check if an address or a contract address is valid.
326
+ *
327
+ * @returns
328
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
329
+ *
330
+ * @example
331
+ * ```
332
+ * import { validateAddress } from '@taquito/utils';
333
+ * const pkh = 'tz1L9r8mWmRPndRhuvMCWESLGSVeFzQ9NAWx'
334
+ * const validation = validateAddress(pkh)
335
+ * console.log(validation)
336
+ * // This example return 3 which correspond to VALID
337
+ * ```
338
+ */
339
+ function validateAddress(value) {
340
+ return validatePrefixedValue(value, [...implicitPrefix, ...contractPrefix, ...smartRollupPrefix]);
341
+ }
342
+ /**
343
+ * @description Used to check if a chain id is valid.
344
+ *
345
+ * @returns
346
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
347
+ *
348
+ * @example
349
+ * ```
350
+ * import { validateChain } from '@taquito/utils';
351
+ * const chainId = 'NetXdQprcVkpaWU'
352
+ * const validation = validateChain(chainId)
353
+ * console.log(validation)
354
+ * // This example return 3 which correspond to VALID
355
+ * ```
356
+ */
357
+ function validateChain(value) {
358
+ return validatePrefixedValue(value, [exports.Prefix.NET]);
359
+ }
360
+ /**
361
+ * @description Used to check if a contract address is valid.
362
+ *
363
+ * @returns
364
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
365
+ *
366
+ * @example
367
+ * ```
368
+ * import { validateContractAddress } from '@taquito/utils';
369
+ * const contractAddress = 'KT1JVErLYTgtY8uGGZ4mso2npTSxqVLDRVbC'
370
+ * const validation = validateContractAddress(contractAddress)
371
+ * console.log(validation)
372
+ * // This example return 3 which correspond to VALID
373
+ * ```
374
+ */
375
+ function validateContractAddress(value) {
376
+ return validatePrefixedValue(value, contractPrefix);
377
+ }
378
+ /**
379
+ * @description Used to check if a key hash is valid.
380
+ *
381
+ * @returns
382
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
383
+ *
384
+ * @example
385
+ * ```
386
+ * import { validateKeyHash } from '@taquito/utils';
387
+ * const keyHashWithoutPrefix = '1L9r8mWmRPndRhuvMCWESLGSVeFzQ9NAWx'
388
+ * const validation = validateKeyHash(keyHashWithoutPrefix)
389
+ * console.log(validation)
390
+ * // This example return 0 which correspond to NO_PREFIX_MATCHED
391
+ * ```
392
+ */
393
+ function validateKeyHash(value) {
394
+ return validatePrefixedValue(value, implicitPrefix);
395
+ }
396
+ /**
397
+ * @description Used to check if a signature is valid.
398
+ *
399
+ * @returns
400
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
401
+ *
402
+ * @example
403
+ * ```
404
+ * import { validateSignature } from '@taquito/utils';
405
+ * const signature = 'edsigtkpiSSschcaCt9pUVrpNPf7TTcgvgDEDD6NCEHMy8NNQJCGnMfLZzYoQj74yLjo9wx6MPVV29CvVzgi7qEcEUok3k7AuMg'
406
+ * const validation = validateSignature(signature)
407
+ * console.log(validation)
408
+ * // This example return 3 which correspond to VALID
409
+ * ```
410
+ */
411
+ function validateSignature(value) {
412
+ return validatePrefixedValue(value, signaturePrefix);
413
+ }
414
+ /**
415
+ * @description Used to check if a public key is valid.
416
+ *
417
+ * @returns
418
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
419
+ *
420
+ * @example
421
+ * ```
422
+ * import { validatePublicKey } from '@taquito/utils';
423
+ * const publicKey = 'edpkvS5QFv7KRGfa3b87gg9DBpxSm3NpSwnjhUjNBQrRUUR66F7C9g'
424
+ * const validation = validatePublicKey(publicKey)
425
+ * console.log(validation)
426
+ * // This example return 3 which correspond to VALID
427
+ * ```
428
+ */
429
+ function validatePublicKey(value) {
430
+ return validatePrefixedValue(value, pkPrefix);
431
+ }
432
+ /**
433
+ * @description Used to check if an operation hash is valid.
434
+ *
435
+ * @returns
436
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
437
+ *
438
+ * @example
439
+ * ```
440
+ * import { validateOperation } from '@taquito/utils';
441
+ * const operationHash = 'oo6JPEAy8VuMRGaFuMmLNFFGdJgiaKfnmT1CpHJfKP3Ye5ZahiP'
442
+ * const validation = validateOperation(operationHash)
443
+ * console.log(validation)
444
+ * // This example return 3 which correspond to VALID
445
+ * ```
446
+ */
447
+ function validateOperation(value) {
448
+ return validatePrefixedValue(value, operationPrefix);
449
+ }
450
+ /**
451
+ * @description Used to check if a protocol hash is valid.
452
+ *
453
+ * @returns
454
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
455
+ *
456
+ * @example
457
+ * ```
458
+ * import { validateProtocol } from '@taquito/utils';
459
+ * const protocolHash = 'PtHangz2aRngywmSRGGvrcTyMbbdpWdpFKuS4uMWxg2RaH9i1qx'
460
+ * const validation = validateProtocol(protocolHash)
461
+ * console.log(validation)
462
+ * // This example return 3 which correspond to VALID
463
+ * ```
464
+ */
465
+ function validateProtocol(value) {
466
+ return validatePrefixedValue(value, protocolPrefix);
467
+ }
468
+ /**
469
+ * @description Used to check if a block hash is valid.
470
+ *
471
+ * @returns
472
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
473
+ *
474
+ * @example
475
+ * ```
476
+ * import { validateBlock } from '@taquito/utils';
477
+ * const blockHash = 'PtHangz2aRngywmSRGGvrcTyMbbdpWdpFKuS4uMWxg2RaH9i1qx'
478
+ * const validation = validateBlock(blockHash)
479
+ * console.log(validation)
480
+ * // This example return 3 which correspond to VALID
481
+ * ```
482
+ */
483
+ function validateBlock(value) {
484
+ return validatePrefixedValue(value, blockPrefix);
485
+ }
486
+ /**
487
+ * @description Used to check if a spending key is valid.
488
+ * @returns 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
489
+ *
490
+ */
491
+ function validateSpendingKey(value) {
492
+ return validatePrefixedValue(value, [exports.Prefix.SASK]);
493
+ }
494
+ function invalidDetail(validation) {
495
+ switch (validation) {
496
+ case exports.ValidationResult.NO_PREFIX_MATCHED:
497
+ return 'with unsupported prefix';
498
+ case exports.ValidationResult.INVALID_CHECKSUM:
499
+ return 'failed checksum';
500
+ case exports.ValidationResult.INVALID_LENGTH:
501
+ return 'with incorrect length';
502
+ default:
503
+ return '';
504
+ }
505
+ }
506
+ function validateSmartRollupAddress(value) {
507
+ return validatePrefixedValue(value, [...smartRollupPrefix]);
516
508
  }
517
509
 
518
- // IMPORTANT: THIS FILE IS AUTO GENERATED! DO NOT MANUALLY EDIT OR CHECKIN!
519
- const VERSION = {
520
- "commitHash": "a97e506efd61b86e39ae30db588401b8fda46553",
521
- "version": "17.3.2"
510
+ // IMPORTANT: THIS FILE IS AUTO GENERATED! DO NOT MANUALLY EDIT OR CHECKIN!
511
+ const VERSION = {
512
+ "commitHash": "a908ab176a8c52c025fd43e7acd452415396f54e",
513
+ "version": "17.4.0"
522
514
  };
523
515
 
524
- const TZ_DECIMALS = 6;
525
- const MTZ_DECIMALS = 3;
526
- function getDecimal(format) {
527
- switch (format) {
528
- case 'tz':
529
- return TZ_DECIMALS;
530
- case 'mtz':
531
- return MTZ_DECIMALS;
532
- case 'mutez':
533
- default:
534
- return 0;
535
- }
536
- }
537
- function format(from = 'mutez', to = 'mutez', amount) {
538
- const bigNum = new BigNumber__default["default"](amount);
539
- if (bigNum.isNaN()) {
540
- return amount;
541
- }
542
- return bigNum
543
- .multipliedBy(Math.pow(10, getDecimal(from)))
544
- .dividedBy(Math.pow(10, getDecimal(to)));
516
+ const TZ_DECIMALS = 6;
517
+ const MTZ_DECIMALS = 3;
518
+ function getDecimal(format) {
519
+ switch (format) {
520
+ case 'tz':
521
+ return TZ_DECIMALS;
522
+ case 'mtz':
523
+ return MTZ_DECIMALS;
524
+ case 'mutez':
525
+ default:
526
+ return 0;
527
+ }
528
+ }
529
+ function format(from = 'mutez', to = 'mutez', amount) {
530
+ const bigNum = new BigNumber(amount);
531
+ if (bigNum.isNaN()) {
532
+ return amount;
533
+ }
534
+ return bigNum
535
+ .multipliedBy(Math.pow(10, getDecimal(from)))
536
+ .dividedBy(Math.pow(10, getDecimal(to)));
545
537
  }
546
538
 
547
- /**
548
- * @packageDocumentation
549
- * @module @taquito/utils
550
- */
551
- /**
552
- *
553
- * @description Hash a string using the BLAKE2b algorithm, base58 encode the hash obtained and appends the prefix 'expr' to it
554
- *
555
- * @param value Value in hex
556
- */
557
- function encodeExpr(value) {
558
- const blakeHash = blake__default["default"].blake2b(hex2buf(value), undefined, 32);
559
- return b58cencode(blakeHash, prefix['expr']);
560
- }
561
- /**
562
- *
563
- * @description Return the operation hash of a signed operation
564
- * @param value Value in hex of a signed operation
565
- */
566
- function encodeOpHash(value) {
567
- const blakeHash = blake__default["default"].blake2b(hex2buf(value), undefined, 32);
568
- return b58cencode(blakeHash, prefix.o);
569
- }
570
- /**
571
- *
572
- * @description Base58 encode a string or a Uint8Array and append a prefix to it
573
- *
574
- * @param value Value to base58 encode
575
- * @param prefix prefix to append to the encoded string
576
- */
577
- function b58cencode(value, prefix) {
578
- const payloadAr = typeof value === 'string' ? Uint8Array.from(buffer.Buffer.from(value, 'hex')) : value;
579
- const n = new Uint8Array(prefix.length + payloadAr.length);
580
- n.set(prefix);
581
- n.set(payloadAr, prefix.length);
582
- return bs58check__default["default"].encode(buffer.Buffer.from(n.buffer));
583
- }
584
- /**
585
- *
586
- * @description Base58 decode a string and remove the prefix from it
587
- *
588
- * @param value Value to base58 decode
589
- * @param prefix prefix to remove from the decoded string
590
- */
591
- const b58cdecode = (enc, prefixArg) => bs58check__default["default"].decode(enc).slice(prefixArg.length);
592
- /**
593
- *
594
- * @description Base58 decode a string with predefined prefix
595
- *
596
- * @param value Value to base58 decode
597
- */
598
- function b58decode(payload) {
599
- const buf = bs58check__default["default"].decode(payload);
600
- const prefixMap = {
601
- [prefix.tz1.toString()]: '0000',
602
- [prefix.tz2.toString()]: '0001',
603
- [prefix.tz3.toString()]: '0002',
604
- };
605
- const rollupPrefMap = {
606
- [prefix.txr1.toString()]: '02',
607
- };
608
- const pref = prefixMap[new Uint8Array(buf.slice(0, 3)).toString()];
609
- const rollupPref = rollupPrefMap[new Uint8Array(buf.slice(0, 4)).toString()];
610
- if (pref) {
611
- // tz addresses
612
- const hex = buf2hex(buf.slice(3));
613
- return pref + hex;
614
- }
615
- else if (rollupPref) {
616
- const hex = buf2hex(buf.slice(4));
617
- return rollupPref + hex + '00';
618
- }
619
- else {
620
- // other (kt addresses)
621
- return '01' + buf2hex(buf.slice(3, 42)) + '00';
622
- }
623
- }
624
- /**
625
- *
626
- * @description b58 decode a string without predefined prefix
627
- * @param value
628
- * @returns string of bytes
629
- */
630
- function b58decodeL2Address(payload) {
631
- const buf = bs58check__default["default"].decode(payload);
632
- // tz4 address currently
633
- return buf2hex(buf.slice(3, 42));
634
- }
635
- /**
636
- *
637
- * @description Base58 encode an address using predefined prefix
638
- *
639
- * @param value Address to base58 encode (tz1, tz2, tz3 or KT1)
640
- */
641
- function encodePubKey(value) {
642
- if (value.substring(0, 2) === '00') {
643
- const pref = {
644
- '0000': prefix.tz1,
645
- '0001': prefix.tz2,
646
- '0002': prefix.tz3,
647
- };
648
- return b58cencode(value.substring(4), pref[value.substring(0, 4)]);
649
- }
650
- else if (value.substring(0, 2) === '02') {
651
- // 42 also works but the removes the 00 padding at the end
652
- return b58cencode(value.substring(2, value.length - 2), prefix.txr1);
653
- }
654
- return b58cencode(value.substring(2, 42), prefix.KT);
655
- }
656
- /**
657
- *
658
- * @description Base58 encode an address without predefined prefix
659
- * @param value Address to base58 encode (tz4) hex dec
660
- * @returns return address
661
- */
662
- function encodeL2Address(value) {
663
- return b58cencode(value, prefix.tz4);
664
- }
665
- /**
666
- *
667
- * @description Base58 encode a key according to its prefix
668
- *
669
- * @param value Key to base58 encode
670
- */
671
- function encodeKey(value) {
672
- if (value[0] === '0') {
673
- const pref = {
674
- '00': new Uint8Array([13, 15, 37, 217]),
675
- '01': new Uint8Array([3, 254, 226, 86]),
676
- '02': new Uint8Array([3, 178, 139, 127]),
677
- };
678
- return b58cencode(value.substring(2), pref[value.substring(0, 2)]);
679
- }
680
- }
681
- /**
682
- *
683
- * @description Base58 encode a key hash according to its prefix
684
- *
685
- * @param value Key hash to base58 encode
686
- */
687
- function encodeKeyHash(value) {
688
- if (value[0] === '0') {
689
- const pref = {
690
- '00': new Uint8Array([6, 161, 159]),
691
- '01': new Uint8Array([6, 161, 161]),
692
- '02': new Uint8Array([6, 161, 164]),
693
- };
694
- return b58cencode(value.substring(2), pref[value.substring(0, 2)]);
695
- }
696
- }
697
- /**
698
- *
699
- * @description Convert an hex string to a Uint8Array
700
- *
701
- * @param hex Hex string to convert
702
- * @throws {@link ValueConversionError}
703
- */
704
- const hex2buf = (hex) => {
705
- if (hex.length % 2 !== 0) {
706
- throw new core.InvalidHexStringError(hex, `: Expecting even number of characters`);
707
- }
708
- const hexDigits = stripHexPrefix(hex);
709
- if (!hexDigits.match(/^([\da-f]{2})*$/gi)) {
710
- throw new core.InvalidHexStringError(hex, `: Only characters 0-9, a-f and A-F are expected. Optionally, it can be prefixed with '0x'`);
711
- }
712
- const out = new Uint8Array(hexDigits.length / 2);
713
- let j = 0;
714
- for (let i = 0; i < hexDigits.length; i += 2) {
715
- const v = parseInt(hexDigits.slice(i, i + 2), 16);
716
- if (Number.isNaN(v)) {
717
- throw new ValueConversionError(hex, 'Uint8Array');
718
- }
719
- out[j++] = v;
720
- }
721
- return out;
722
- };
723
- /**
724
- *
725
- * @description Merge 2 buffers together
726
- *
727
- * @param b1 First buffer
728
- * @param b2 Second buffer
729
- */
730
- const mergebuf = (b1, b2) => {
731
- const r = new Uint8Array(b1.length + b2.length);
732
- r.set(b1);
733
- r.set(b2, b1.length);
734
- return r;
735
- };
736
- /**
737
- *
738
- * @description Flatten a michelson json representation to an array
739
- *
740
- * @param s michelson json
741
- */
742
- const mic2arr = function me2(s) {
743
- let ret = [];
744
- if (Object.prototype.hasOwnProperty.call(s, 'prim')) {
745
- if (s.prim === 'Pair') {
746
- ret.push(me2(s.args[0]));
747
- ret = ret.concat(me2(s.args[1]));
748
- }
749
- else if (s.prim === 'Elt') {
750
- ret = {
751
- key: me2(s.args[0]),
752
- val: me2(s.args[1]),
753
- };
754
- }
755
- else if (s.prim === 'True') {
756
- ret = true;
757
- }
758
- else if (s.prim === 'False') {
759
- ret = false;
760
- }
761
- }
762
- else if (Array.isArray(s)) {
763
- const sc = s.length;
764
- for (let i = 0; i < sc; i++) {
765
- const n = me2(s[i]);
766
- if (typeof n.key !== 'undefined') {
767
- if (Array.isArray(ret)) {
768
- ret = {
769
- keys: [],
770
- vals: [],
771
- };
772
- }
773
- ret.keys.push(n.key);
774
- ret.vals.push(n.val);
775
- }
776
- else {
777
- ret.push(n);
778
- }
779
- }
780
- }
781
- else if (Object.prototype.hasOwnProperty.call(s, 'string')) {
782
- ret = s.string;
783
- }
784
- else if (Object.prototype.hasOwnProperty.call(s, 'int')) {
785
- ret = parseInt(s.int, 10);
786
- }
787
- else {
788
- ret = s;
789
- }
790
- return ret;
791
- };
792
- /**
793
- *
794
- * @description Convert a buffer to an hex string
795
- *
796
- * @param buffer Buffer to convert
797
- */
798
- const buf2hex = (buffer) => {
799
- const byteArray = new Uint8Array(buffer);
800
- const hexParts = [];
801
- byteArray.forEach((byte) => {
802
- const hex = byte.toString(16);
803
- const paddedHex = `00${hex}`.slice(-2);
804
- hexParts.push(paddedHex);
805
- });
806
- return hexParts.join('');
807
- };
808
- /**
809
- *
810
- * @description Gets Tezos address (PKH) from Public Key
811
- *
812
- * @param publicKey Public Key
813
- * @returns A string of the Tezos address (PKH) that was derived from the given Public Key
814
- */
815
- const getPkhfromPk = (publicKey) => {
816
- let encodingPrefix;
817
- let prefixLen;
818
- const keyPrefix = validatePkAndExtractPrefix(publicKey);
819
- const decoded = b58cdecode(publicKey, prefix[keyPrefix]);
820
- switch (keyPrefix) {
821
- case exports.Prefix.EDPK:
822
- encodingPrefix = prefix[exports.Prefix.TZ1];
823
- prefixLen = prefixLength[exports.Prefix.TZ1];
824
- break;
825
- case exports.Prefix.SPPK:
826
- encodingPrefix = prefix[exports.Prefix.TZ2];
827
- prefixLen = prefixLength[exports.Prefix.TZ2];
828
- break;
829
- case exports.Prefix.P2PK:
830
- encodingPrefix = prefix[exports.Prefix.TZ3];
831
- prefixLen = prefixLength[exports.Prefix.TZ3];
832
- break;
833
- case exports.Prefix.BLPK:
834
- encodingPrefix = prefix[exports.Prefix.TZ4];
835
- prefixLen = prefixLength[exports.Prefix.TZ4];
836
- }
837
- const hashed = blake2b.hash(decoded, prefixLen);
838
- const result = b58cencode(hashed, encodingPrefix);
839
- return result;
840
- };
841
- /**
842
- *
843
- * @description Convert a string to bytes
844
- *
845
- * @param str String to convert
846
- */
847
- function char2Bytes(str) {
848
- return buffer.Buffer.from(str, 'utf8').toString('hex');
849
- }
850
- /**
851
- *
852
- * @description Convert bytes to a string
853
- *
854
- * @param str Bytes to convert
855
- */
856
- function bytes2Char(hex) {
857
- return buffer.Buffer.from(hex2buf(hex)).toString('utf8');
858
- }
859
- /**
860
- *
861
- * @description Convert hex string/UintArray/Buffer to bytes
862
- *
863
- * @param hex String value to convert to bytes
864
- */
865
- function hex2Bytes(hex) {
866
- const hexDigits = stripHexPrefix(hex);
867
- if (!hexDigits.match(/^(0x)?([\da-f]{2})*$/gi)) {
868
- throw new core.InvalidHexStringError(hex, `: Expecting even number of characters: 0-9, a-z, A-Z, optionally prefixed with 0x`);
869
- }
870
- return buffer.Buffer.from(hexDigits, 'hex');
871
- }
872
- /**
873
- *
874
- * @description Converts a number or Bignumber to hexadecimal string
875
- *
876
- * @param val The value that will be converted to a hexadecimal string value
877
- */
878
- function toHexBuf(val, bitLength = 8) {
879
- return buffer.Buffer.from(num2PaddedHex(val, bitLength), 'hex');
880
- }
881
- /**
882
- *
883
- * @description Converts a number or BigNumber to a padded hexadecimal string
884
- * @param val The value that will be converted into a padded hexadecimal string value
885
- * @param bitLength The length of bits
886
- *
887
- */
888
- function num2PaddedHex(val, bitLength = 8) {
889
- if (new BigNumber__default["default"](val).isPositive()) {
890
- const nibbleLength = Math.ceil(bitLength / 4);
891
- const hex = val.toString(16);
892
- // check whether nibble (4 bits) length is higher or lowerthan the current hex string length
893
- let targetLength = hex.length >= nibbleLength ? hex.length : nibbleLength;
894
- // make sure the hex string target length is even
895
- targetLength = targetLength % 2 == 0 ? targetLength : targetLength + 1;
896
- return padHexWithZero(hex, targetLength);
897
- }
898
- else {
899
- const twosCompliment = new BigNumber__default["default"](2)
900
- .pow(bitLength)
901
- .minus(new BigNumber__default["default"](val).abs());
902
- return twosCompliment.toString(16);
903
- }
904
- }
905
- function padHexWithZero(hex, targetLength) {
906
- const padString = '0';
907
- if (hex.length >= targetLength) {
908
- return hex;
909
- }
910
- else {
911
- const padLength = targetLength - hex.length;
912
- return padString.repeat(padLength) + hex;
913
- }
914
- }
915
- /**
916
- *
917
- * @description Strips the first 2 characters of a hex string (0x)
918
- *
919
- * @param hex string to strip prefix from
920
- */
921
- function stripHexPrefix(hex) {
922
- return hex.startsWith('0x') ? hex.slice(2) : hex;
539
+ /**
540
+ * @packageDocumentation
541
+ * @module @taquito/utils
542
+ */
543
+ /*
544
+ * Some code in this file is originally from sotez and eztz
545
+ * Copyright (c) 2018 Andrew Kishino
546
+ * Copyright (c) 2017 Stephen Andrews
547
+ */
548
+ /**
549
+ *
550
+ * @description Hash a string using the BLAKE2b algorithm, base58 encode the hash obtained and appends the prefix 'expr' to it
551
+ *
552
+ * @param value Value in hex
553
+ */
554
+ function encodeExpr(value) {
555
+ const blakeHash = blake.blake2b(hex2buf(value), undefined, 32);
556
+ return b58cencode(blakeHash, prefix['expr']);
557
+ }
558
+ /**
559
+ *
560
+ * @description Return the operation hash of a signed operation
561
+ * @param value Value in hex of a signed operation
562
+ */
563
+ function encodeOpHash(value) {
564
+ const blakeHash = blake.blake2b(hex2buf(value), undefined, 32);
565
+ return b58cencode(blakeHash, prefix.o);
566
+ }
567
+ /**
568
+ *
569
+ * @description Base58 encode a string or a Uint8Array and append a prefix to it
570
+ *
571
+ * @param value Value to base58 encode
572
+ * @param prefix prefix to append to the encoded string
573
+ */
574
+ function b58cencode(value, prefix) {
575
+ const payloadAr = typeof value === 'string' ? Uint8Array.from(buffer.Buffer.from(value, 'hex')) : value;
576
+ const n = new Uint8Array(prefix.length + payloadAr.length);
577
+ n.set(prefix);
578
+ n.set(payloadAr, prefix.length);
579
+ return bs58check.encode(buffer.Buffer.from(n.buffer));
580
+ }
581
+ /**
582
+ *
583
+ * @description Base58 decode a string and remove the prefix from it
584
+ *
585
+ * @param value Value to base58 decode
586
+ * @param prefix prefix to remove from the decoded string
587
+ */
588
+ const b58cdecode = (enc, prefixArg) => bs58check.decode(enc).slice(prefixArg.length);
589
+ /**
590
+ *
591
+ * @description Base58 decode a string with predefined prefix
592
+ *
593
+ * @param value Value to base58 decode
594
+ */
595
+ function b58decode(payload) {
596
+ const buf = bs58check.decode(payload);
597
+ const prefixMap = {
598
+ [prefix.tz1.toString()]: '0000',
599
+ [prefix.tz2.toString()]: '0001',
600
+ [prefix.tz3.toString()]: '0002',
601
+ };
602
+ const rollupPrefMap = {
603
+ [prefix.txr1.toString()]: '02',
604
+ };
605
+ const pref = prefixMap[new Uint8Array(buf.slice(0, 3)).toString()];
606
+ const rollupPref = rollupPrefMap[new Uint8Array(buf.slice(0, 4)).toString()];
607
+ if (pref) {
608
+ // tz addresses
609
+ const hex = buf2hex(buf.slice(3));
610
+ return pref + hex;
611
+ }
612
+ else if (rollupPref) {
613
+ const hex = buf2hex(buf.slice(4));
614
+ return rollupPref + hex + '00';
615
+ }
616
+ else {
617
+ // other (kt addresses)
618
+ return '01' + buf2hex(buf.slice(3, 42)) + '00';
619
+ }
620
+ }
621
+ /**
622
+ *
623
+ * @description b58 decode a string without predefined prefix
624
+ * @param value
625
+ * @returns string of bytes
626
+ */
627
+ function b58decodeL2Address(payload) {
628
+ const buf = bs58check.decode(payload);
629
+ // tz4 address currently
630
+ return buf2hex(buf.slice(3, 42));
631
+ }
632
+ /**
633
+ *
634
+ * @description Base58 encode an address using predefined prefix
635
+ *
636
+ * @param value Address to base58 encode (tz1, tz2, tz3 or KT1)
637
+ */
638
+ function encodePubKey(value) {
639
+ if (value.substring(0, 2) === '00') {
640
+ const pref = {
641
+ '0000': prefix.tz1,
642
+ '0001': prefix.tz2,
643
+ '0002': prefix.tz3,
644
+ };
645
+ return b58cencode(value.substring(4), pref[value.substring(0, 4)]);
646
+ }
647
+ else if (value.substring(0, 2) === '02') {
648
+ // 42 also works but the removes the 00 padding at the end
649
+ return b58cencode(value.substring(2, value.length - 2), prefix.txr1);
650
+ }
651
+ return b58cencode(value.substring(2, 42), prefix.KT);
652
+ }
653
+ /**
654
+ *
655
+ * @description Base58 encode an address without predefined prefix
656
+ * @param value Address to base58 encode (tz4) hex dec
657
+ * @returns return address
658
+ */
659
+ function encodeL2Address(value) {
660
+ return b58cencode(value, prefix.tz4);
661
+ }
662
+ /**
663
+ *
664
+ * @description Base58 encode a key according to its prefix
665
+ *
666
+ * @param value Key to base58 encode
667
+ */
668
+ function encodeKey(value) {
669
+ if (value[0] === '0') {
670
+ const pref = {
671
+ '00': new Uint8Array([13, 15, 37, 217]),
672
+ '01': new Uint8Array([3, 254, 226, 86]),
673
+ '02': new Uint8Array([3, 178, 139, 127]),
674
+ };
675
+ return b58cencode(value.substring(2), pref[value.substring(0, 2)]);
676
+ }
677
+ }
678
+ /**
679
+ *
680
+ * @description Base58 encode a key hash according to its prefix
681
+ *
682
+ * @param value Key hash to base58 encode
683
+ */
684
+ function encodeKeyHash(value) {
685
+ if (value[0] === '0') {
686
+ const pref = {
687
+ '00': new Uint8Array([6, 161, 159]),
688
+ '01': new Uint8Array([6, 161, 161]),
689
+ '02': new Uint8Array([6, 161, 164]),
690
+ };
691
+ return b58cencode(value.substring(2), pref[value.substring(0, 2)]);
692
+ }
693
+ }
694
+ /**
695
+ *
696
+ * @description Convert an hex string to a Uint8Array
697
+ *
698
+ * @param hex Hex string to convert
699
+ * @throws {@link ValueConversionError}
700
+ */
701
+ const hex2buf = (hex) => {
702
+ if (hex.length % 2 !== 0) {
703
+ throw new core.InvalidHexStringError(hex, `: Expecting even number of characters`);
704
+ }
705
+ const hexDigits = stripHexPrefix(hex);
706
+ if (!hexDigits.match(/^([\da-f]{2})*$/gi)) {
707
+ throw new core.InvalidHexStringError(hex, `: Only characters 0-9, a-f and A-F are expected. Optionally, it can be prefixed with '0x'`);
708
+ }
709
+ const out = new Uint8Array(hexDigits.length / 2);
710
+ let j = 0;
711
+ for (let i = 0; i < hexDigits.length; i += 2) {
712
+ const v = parseInt(hexDigits.slice(i, i + 2), 16);
713
+ if (Number.isNaN(v)) {
714
+ throw new ValueConversionError(hex, 'Uint8Array');
715
+ }
716
+ out[j++] = v;
717
+ }
718
+ return out;
719
+ };
720
+ /**
721
+ *
722
+ * @description Merge 2 buffers together
723
+ *
724
+ * @param b1 First buffer
725
+ * @param b2 Second buffer
726
+ */
727
+ const mergebuf = (b1, b2) => {
728
+ const r = new Uint8Array(b1.length + b2.length);
729
+ r.set(b1);
730
+ r.set(b2, b1.length);
731
+ return r;
732
+ };
733
+ /**
734
+ *
735
+ * @description Flatten a michelson json representation to an array
736
+ *
737
+ * @param s michelson json
738
+ */
739
+ const mic2arr = function me2(s) {
740
+ let ret = [];
741
+ if (Object.prototype.hasOwnProperty.call(s, 'prim')) {
742
+ if (s.prim === 'Pair') {
743
+ ret.push(me2(s.args[0]));
744
+ ret = ret.concat(me2(s.args[1]));
745
+ }
746
+ else if (s.prim === 'Elt') {
747
+ ret = {
748
+ key: me2(s.args[0]),
749
+ val: me2(s.args[1]),
750
+ };
751
+ }
752
+ else if (s.prim === 'True') {
753
+ ret = true;
754
+ }
755
+ else if (s.prim === 'False') {
756
+ ret = false;
757
+ }
758
+ }
759
+ else if (Array.isArray(s)) {
760
+ const sc = s.length;
761
+ for (let i = 0; i < sc; i++) {
762
+ const n = me2(s[i]);
763
+ if (typeof n.key !== 'undefined') {
764
+ if (Array.isArray(ret)) {
765
+ ret = {
766
+ keys: [],
767
+ vals: [],
768
+ };
769
+ }
770
+ ret.keys.push(n.key);
771
+ ret.vals.push(n.val);
772
+ }
773
+ else {
774
+ ret.push(n);
775
+ }
776
+ }
777
+ }
778
+ else if (Object.prototype.hasOwnProperty.call(s, 'string')) {
779
+ ret = s.string;
780
+ }
781
+ else if (Object.prototype.hasOwnProperty.call(s, 'int')) {
782
+ ret = parseInt(s.int, 10);
783
+ }
784
+ else {
785
+ ret = s;
786
+ }
787
+ return ret;
788
+ };
789
+ /**
790
+ *
791
+ * @description Convert a Uint8Array to an hex string
792
+ *
793
+ * @param buffer Uint8Array to convert
794
+ */
795
+ const buf2hex = (buffer) => {
796
+ const hexParts = [];
797
+ buffer.forEach((byte) => {
798
+ const hex = byte.toString(16);
799
+ const paddedHex = `00${hex}`.slice(-2);
800
+ hexParts.push(paddedHex);
801
+ });
802
+ return hexParts.join('');
803
+ };
804
+ /**
805
+ *
806
+ * @description Gets Tezos address (PKH) from Public Key
807
+ *
808
+ * @param publicKey Public Key
809
+ * @returns A string of the Tezos address (PKH) that was derived from the given Public Key
810
+ */
811
+ const getPkhfromPk = (publicKey) => {
812
+ let encodingPrefix;
813
+ let prefixLen;
814
+ const keyPrefix = validatePkAndExtractPrefix(publicKey);
815
+ const decoded = b58cdecode(publicKey, prefix[keyPrefix]);
816
+ switch (keyPrefix) {
817
+ case exports.Prefix.EDPK:
818
+ encodingPrefix = prefix[exports.Prefix.TZ1];
819
+ prefixLen = prefixLength[exports.Prefix.TZ1];
820
+ break;
821
+ case exports.Prefix.SPPK:
822
+ encodingPrefix = prefix[exports.Prefix.TZ2];
823
+ prefixLen = prefixLength[exports.Prefix.TZ2];
824
+ break;
825
+ case exports.Prefix.P2PK:
826
+ encodingPrefix = prefix[exports.Prefix.TZ3];
827
+ prefixLen = prefixLength[exports.Prefix.TZ3];
828
+ break;
829
+ case exports.Prefix.BLPK:
830
+ encodingPrefix = prefix[exports.Prefix.TZ4];
831
+ prefixLen = prefixLength[exports.Prefix.TZ4];
832
+ }
833
+ const hashed = blake2b.hash(decoded, prefixLen);
834
+ const result = b58cencode(hashed, encodingPrefix);
835
+ return result;
836
+ };
837
+ /**
838
+ *
839
+ * @description Convert a string to bytes
840
+ *
841
+ * @param str String to convert
842
+ */
843
+ function char2Bytes(str) {
844
+ return buffer.Buffer.from(str, 'utf8').toString('hex');
845
+ }
846
+ /**
847
+ *
848
+ * @description Convert bytes to a string
849
+ *
850
+ * @param str Bytes to convert
851
+ */
852
+ function bytes2Char(hex) {
853
+ return buffer.Buffer.from(hex2buf(hex)).toString('utf8');
854
+ }
855
+ /**
856
+ *
857
+ * @description Convert hex string/UintArray/Buffer to bytes
858
+ *
859
+ * @param hex String value to convert to bytes
860
+ */
861
+ function hex2Bytes(hex) {
862
+ const hexDigits = stripHexPrefix(hex);
863
+ if (!hexDigits.match(/^(0x)?([\da-f]{2})*$/gi)) {
864
+ throw new core.InvalidHexStringError(hex, `: Expecting even number of characters: 0-9, a-z, A-Z, optionally prefixed with 0x`);
865
+ }
866
+ return buffer.Buffer.from(hexDigits, 'hex');
867
+ }
868
+ /**
869
+ *
870
+ * @description Converts a number or Bignumber to hexadecimal string
871
+ *
872
+ * @param val The value that will be converted to a hexadecimal string value
873
+ */
874
+ function toHexBuf(val, bitLength = 8) {
875
+ return buffer.Buffer.from(num2PaddedHex(val, bitLength), 'hex');
876
+ }
877
+ /**
878
+ *
879
+ * @description Converts a number or BigNumber to a padded hexadecimal string
880
+ * @param val The value that will be converted into a padded hexadecimal string value
881
+ * @param bitLength The length of bits
882
+ *
883
+ */
884
+ function num2PaddedHex(val, bitLength = 8) {
885
+ if (new BigNumber(val).isPositive()) {
886
+ const nibbleLength = Math.ceil(bitLength / 4);
887
+ const hex = val.toString(16);
888
+ // check whether nibble (4 bits) length is higher or lower than the current hex string length
889
+ let targetLength = hex.length >= nibbleLength ? hex.length : nibbleLength;
890
+ // make sure the hex string target length is even
891
+ targetLength = targetLength % 2 == 0 ? targetLength : targetLength + 1;
892
+ return padHexWithZero(hex, targetLength);
893
+ }
894
+ else {
895
+ const twosCompliment = new BigNumber(2)
896
+ .pow(bitLength)
897
+ .minus(new BigNumber(val).abs());
898
+ return twosCompliment.toString(16);
899
+ }
900
+ }
901
+ function padHexWithZero(hex, targetLength) {
902
+ const padString = '0';
903
+ if (hex.length >= targetLength) {
904
+ return hex;
905
+ }
906
+ else {
907
+ const padLength = targetLength - hex.length;
908
+ return padString.repeat(padLength) + hex;
909
+ }
910
+ }
911
+ /**
912
+ *
913
+ * @description Strips the first 2 characters of a hex string (0x)
914
+ *
915
+ * @param hex string to strip prefix from
916
+ */
917
+ function stripHexPrefix(hex) {
918
+ return hex.startsWith('0x') ? hex.slice(2) : hex;
923
919
  }
924
920
 
925
921
  Object.defineProperty(exports, 'DeprecationError', {
@@ -1021,7 +1017,5 @@
1021
1017
  exports.validateSpendingKey = validateSpendingKey;
1022
1018
  exports.verifySignature = verifySignature;
1023
1019
 
1024
- Object.defineProperty(exports, '__esModule', { value: true });
1025
-
1026
1020
  }));
1027
1021
  //# sourceMappingURL=taquito-utils.umd.js.map