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