@taquito/utils 23.0.0-beta.0 → 23.0.0-beta.1

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.
@@ -1,15 +1,19 @@
1
1
  import { Buffer } from 'buffer';
2
- import { verify } from '@stablelib/ed25519';
3
2
  import { hash } from '@stablelib/blake2b';
4
- import blake from 'blakejs';
5
3
  import bs58check from 'bs58check';
6
- import { InvalidMessageError, InvalidPublicKeyError, InvalidSignatureError, ParameterValidationError, UnsupportedActionError, InvalidHexStringError } from '@taquito/core';
7
- export { DeprecationError, InvalidAddressError, InvalidBlockHashError, InvalidChainIdError, InvalidContractAddressError, InvalidHexStringError, InvalidKeyError, InvalidKeyHashError, InvalidMessageError, InvalidOperationHashError, InvalidOperationKindError, InvalidPublicKeyError, InvalidSignatureError, ProhibitedActionError } from '@taquito/core';
8
4
  import BigNumber from 'bignumber.js';
9
- import elliptic from 'elliptic';
10
5
  import toBuffer from 'typedarray-to-buffer';
6
+ import { ValidationResult, ParameterValidationError, InvalidPublicKeyError, InvalidSignatureError, InvalidMessageError, UnsupportedActionError, InvalidKeyError, InvalidAddressError, InvalidHexStringError } from '@taquito/core';
7
+ export { DeprecationError, InvalidAddressError, InvalidBlockHashError, InvalidChainIdError, InvalidContractAddressError, InvalidHexStringError, InvalidKeyError, InvalidKeyHashError, InvalidMessageError, InvalidOperationHashError, InvalidOperationKindError, InvalidPublicKeyError, InvalidSignatureError, ProhibitedActionError, ValidationResult } from '@taquito/core';
8
+ import { verify } from '@stablelib/ed25519';
9
+ import elliptic from 'elliptic';
10
+ import { bls12_381 } from '@noble/curves/bls12-381';
11
11
 
12
12
  // ref https://gitlab.com/tezos/tezos/-/blob/master/src/lib_crypto/base58.ml
13
+ /**
14
+ * @deprecated use PrefixV2 instead, this enum will be removed in the next minor release
15
+ * @description base58 prefix definition enum
16
+ */
13
17
  var Prefix;
14
18
  (function (Prefix) {
15
19
  Prefix["TZ1"] = "tz1";
@@ -54,6 +58,10 @@ var Prefix;
54
58
  Prefix["SRC1"] = "src1";
55
59
  Prefix["SH"] = "sh";
56
60
  })(Prefix || (Prefix = {}));
61
+ /**
62
+ * @deprecated use prefixV2 instead this constant will be removed in the next minor release
63
+ * @description base58 prefix to bytes mapping
64
+ */
57
65
  const prefix = {
58
66
  [Prefix.TZ1]: new Uint8Array([6, 161, 159]),
59
67
  [Prefix.TZ2]: new Uint8Array([6, 161, 161]),
@@ -98,6 +106,10 @@ const prefix = {
98
106
  [Prefix.SRC1]: new Uint8Array([17, 165, 134, 138]),
99
107
  [Prefix.SH]: new Uint8Array([2, 116, 180]),
100
108
  };
109
+ /**
110
+ * @deprecated use payloadLength instead this constant will be removed in the next minor release
111
+ * @description base58 prefix to payload length mapping
112
+ */
101
113
  const prefixLength = {
102
114
  [Prefix.TZ1]: 20,
103
115
  [Prefix.TZ2]: 20,
@@ -125,200 +137,252 @@ const prefixLength = {
125
137
  [Prefix.SRC1]: 32,
126
138
  [Prefix.SH]: 48,
127
139
  };
128
-
129
140
  /**
130
- * @description Verify signature of a payload
131
- *
132
- * @param messageBytes The forged message including the magic byte (11 for block,
133
- * 12 for preattestation, 13 for attestation, 3 for generic, 5 for the PACK format of michelson)
134
- * @param publicKey The public key to verify the signature against
135
- * @param signature The signature to verify
136
- * @returns A boolean indicating if the signature matches
137
- * @throws {@link InvalidPublicKeyError} | {@link InvalidSignatureError} | {@link InvalidMessageError}
138
- * @example
139
- * ```
140
- * const message = '03d0c10e3ed11d7c6e3357f6ef335bab9e8f2bd54d0ce20c482e241191a6e4b8ce6c01be917311d9ac46959750e405d57e268e2ed9e174a80794fbd504e12a4a000141eb3781afed2f69679ff2bbe1c5375950b0e40d00ff000000005e05050505050507070100000024747a32526773486e74516b72794670707352466261313652546656503539684b72654a4d07070100000024747a315a6672455263414c42776d4171776f6e525859565142445439426a4e6a42484a750001';
141
- * const pk = 'sppk7c7hkPj47yjYFEHX85q46sFJGw6RBrqoVSHwAJAT4e14KJwzoey';
142
- * const sig = 'spsig1cdLkp1RLgUHAp13aRFkZ6MQDPp7xCnjAExGL3MBSdMDmT6JgQSX8cufyDgJRM3sinFtiCzLbsyP6d365EHoNevxhT47nx'
143
- *
144
- * const response = verifySignature(message, pk, sig);
145
- * ```
146
- *
141
+ * @description base58 name to prefix mapping
147
142
  */
148
- function verifySignature(messageBytes, publicKey, signature, watermark) {
149
- const pkPrefix = validatePkAndExtractPrefix(publicKey);
150
- const sigPrefix = validateSigAndExtractPrefix(signature);
151
- const decodedPublicKey = b58cdecode(publicKey, prefix[pkPrefix]);
152
- const decodedSig = b58cdecode(signature, prefix[sigPrefix]);
153
- let messageBuf = hex2buf(validateMessageNotEmpty(messageBytes));
154
- if (typeof watermark !== 'undefined') {
155
- messageBuf = mergebuf(watermark, messageBuf);
156
- }
157
- const bytesHash = hash(messageBuf, 32);
158
- if (pkPrefix === Prefix.EDPK) {
159
- return verifyEdSignature(decodedSig, bytesHash, decodedPublicKey);
160
- }
161
- else if (pkPrefix === Prefix.SPPK) {
162
- return verifySpSignature(decodedSig, bytesHash, decodedPublicKey);
163
- }
164
- else if (pkPrefix === Prefix.P2PK) {
165
- return verifyP2Signature(decodedSig, bytesHash, decodedPublicKey);
166
- }
167
- else {
168
- return false;
169
- }
170
- }
171
- function validateMessageNotEmpty(message) {
172
- if (message === '') {
173
- throw new InvalidMessageError(message, `can't be empty`);
174
- }
175
- return message;
176
- }
177
- function validatePkAndExtractPrefix(publicKey) {
178
- if (publicKey === '') {
179
- throw new InvalidPublicKeyError(publicKey, `can't be empty`);
180
- }
181
- const pkPrefix = publicKey.substring(0, 4);
182
- const publicKeyValidation = validatePublicKey(publicKey);
183
- if (publicKeyValidation !== ValidationResult.VALID) {
184
- throw new InvalidPublicKeyError(publicKey, invalidDetail(publicKeyValidation));
185
- }
186
- return pkPrefix;
187
- }
188
- function validateSigAndExtractPrefix(signature) {
189
- const signaturePrefix = signature.startsWith('sig')
190
- ? signature.substring(0, 3)
191
- : signature.substring(0, 5);
192
- const validation = validateSignature(signature);
193
- if (validation !== ValidationResult.VALID) {
194
- throw new InvalidSignatureError(signature, invalidDetail(validation));
195
- }
196
- return signaturePrefix;
197
- }
198
- function verifyEdSignature(decodedSig, bytesHash, decodedPublicKey) {
199
- try {
200
- return verify(decodedPublicKey, bytesHash, decodedSig);
201
- }
202
- catch (e) {
203
- return false;
204
- }
205
- }
206
- function verifySpSignature(decodedSig, bytesHash, decodedPublicKey) {
207
- const key = new elliptic.ec('secp256k1').keyFromPublic(decodedPublicKey);
208
- return verifySpOrP2Sig(decodedSig, bytesHash, key);
209
- }
210
- function verifyP2Signature(decodedSig, bytesHash, decodedPublicKey) {
211
- const key = new elliptic.ec('p256').keyFromPublic(decodedPublicKey);
212
- return verifySpOrP2Sig(decodedSig, bytesHash, key);
213
- }
214
- function verifySpOrP2Sig(decodedSig, bytesHash, key) {
215
- const hexSig = buf2hex(toBuffer(decodedSig));
216
- const match = hexSig.match(/([a-f\d]{64})/gi);
217
- if (match) {
218
- try {
219
- const [r, s] = match;
220
- return key.verify(bytesHash, { r, s });
221
- }
222
- catch (e) {
223
- return false;
224
- }
225
- }
226
- return false;
227
- }
228
-
143
+ var PrefixV2;
144
+ (function (PrefixV2) {
145
+ PrefixV2["BlockHash"] = "B";
146
+ PrefixV2["OperationHash"] = "o";
147
+ PrefixV2["OperationListHash"] = "Lo";
148
+ PrefixV2["OperationListListHash"] = "LLo";
149
+ PrefixV2["ProtocolHash"] = "P";
150
+ PrefixV2["ContextHash"] = "Co";
151
+ PrefixV2["BlockMetadataHash"] = "bm";
152
+ PrefixV2["OperationMetadataHash"] = "r";
153
+ PrefixV2["OperationMetadataListHash"] = "Lr";
154
+ PrefixV2["OperationMetadataListListHash"] = "LLr";
155
+ PrefixV2["Ed25519PublicKeyHash"] = "tz1";
156
+ PrefixV2["Secp256k1PublicKeyHash"] = "tz2";
157
+ PrefixV2["P256PublicKeyHash"] = "tz3";
158
+ PrefixV2["ContractHash"] = "KT1";
159
+ PrefixV2["BlindedPublicKeyHash"] = "btz1";
160
+ PrefixV2["BLS12_381PublicKeyHash"] = "tz4";
161
+ PrefixV2["TXRollupAddress"] = "txr1";
162
+ PrefixV2["ZkRollupHash"] = "epx1";
163
+ PrefixV2["ScRollupHash"] = "scr1";
164
+ PrefixV2["SmartRollupHash"] = "sr1";
165
+ PrefixV2["CryptoboxPublicKeyHash"] = "id";
166
+ PrefixV2["Ed25519Seed"] = "edsk";
167
+ PrefixV2["Ed25519PublicKey"] = "edpk";
168
+ PrefixV2["Secp256k1SecretKey"] = "spsk";
169
+ PrefixV2["P256SecretKey"] = "p2sk";
170
+ PrefixV2["BLS12_381SecretKey"] = "BLsk";
171
+ PrefixV2["ValueHash"] = "vh";
172
+ PrefixV2["CycleNonce"] = "nce";
173
+ PrefixV2["ScriptExpr"] = "expr";
174
+ PrefixV2["InboxHash"] = "txi";
175
+ PrefixV2["MessageHash"] = "txm";
176
+ PrefixV2["CommitmentHash"] = "txc";
177
+ PrefixV2["MessageResultHash"] = "txmr";
178
+ PrefixV2["MessageResultListHash"] = "txM";
179
+ PrefixV2["WithdrawListHash"] = "txw";
180
+ PrefixV2["ScRollupStateHash"] = "scs1";
181
+ PrefixV2["ScRollupCommitmentHash"] = "scc1";
182
+ PrefixV2["SmartRollupStateHash"] = "srs1";
183
+ PrefixV2["SmartRollupCommitmentHash"] = "src1";
184
+ PrefixV2["Ed25519EncryptedSeed"] = "edesk";
185
+ PrefixV2["Secp256k1EncryptedSecretKey"] = "spesk";
186
+ PrefixV2["P256EncryptedSecretKey"] = "p2esk";
187
+ PrefixV2["BLS12_381EncryptedSecretKey"] = "BLesk";
188
+ PrefixV2["Secp256k1EncryptedScalar"] = "seesk";
189
+ PrefixV2["Secp256k1PublicKey"] = "sppk";
190
+ PrefixV2["P256PublicKey"] = "p2pk";
191
+ PrefixV2["Secp256k1Scalar"] = "SSp";
192
+ PrefixV2["Secp256k1Element"] = "GSp";
193
+ PrefixV2["Ed25519SecretKey"] = "_edsk";
194
+ PrefixV2["Ed25519Signature"] = "edsig";
195
+ PrefixV2["Secp256k1Signature"] = "spsig1";
196
+ PrefixV2["P256Signature"] = "p2sig";
197
+ PrefixV2["GenericSignature"] = "sig";
198
+ PrefixV2["ChainID"] = "Net";
199
+ PrefixV2["SaplingSpendingKey"] = "sask";
200
+ PrefixV2["EncryptedSaplingSpendingKey"] = "_sask";
201
+ PrefixV2["SaplingAddress"] = "zet1";
202
+ PrefixV2["GenericAggregateSignature"] = "asig";
203
+ PrefixV2["BLS12_381Signature"] = "BLsig";
204
+ PrefixV2["BLS12_381PublicKey"] = "BLpk";
205
+ PrefixV2["SlotHeader"] = "sh";
206
+ })(PrefixV2 || (PrefixV2 = {}));
229
207
  /**
230
- * @category Error
231
- * @description Error that indicates invalid protocol hash being passed or used
208
+ * @description base58 prefix to bytes mapping
232
209
  */
233
- class InvalidProtocolHashError extends ParameterValidationError {
234
- constructor(protocolHash, errorDetails) {
235
- super();
236
- this.protocolHash = protocolHash;
237
- this.errorDetails = errorDetails;
238
- this.name = 'InvalidProtocolHashError';
239
- this.name = 'InvalidProtocolHashError';
240
- this.message = `The protocol hash '${protocolHash}' is invalid`;
241
- errorDetails ? (this.message += `: ${errorDetails}`) : null;
242
- }
243
- }
210
+ const prefixV2 = {
211
+ [PrefixV2.BlockHash]: new Uint8Array([1, 52]),
212
+ [PrefixV2.OperationHash]: new Uint8Array([5, 116]),
213
+ [PrefixV2.OperationListHash]: new Uint8Array([133, 233]),
214
+ [PrefixV2.OperationListListHash]: new Uint8Array([29, 159, 109]),
215
+ [PrefixV2.ProtocolHash]: new Uint8Array([2, 170]),
216
+ [PrefixV2.ContextHash]: new Uint8Array([79, 199]),
217
+ [PrefixV2.BlockMetadataHash]: new Uint8Array([234, 249]),
218
+ [PrefixV2.OperationMetadataHash]: new Uint8Array([5, 183]),
219
+ [PrefixV2.OperationMetadataListHash]: new Uint8Array([134, 39]),
220
+ [PrefixV2.OperationMetadataListListHash]: new Uint8Array([29, 159, 182]),
221
+ [PrefixV2.Ed25519PublicKeyHash]: new Uint8Array([6, 161, 159]),
222
+ [PrefixV2.Secp256k1PublicKeyHash]: new Uint8Array([6, 161, 161]),
223
+ [PrefixV2.P256PublicKeyHash]: new Uint8Array([6, 161, 164]),
224
+ [PrefixV2.ContractHash]: new Uint8Array([2, 90, 121]),
225
+ [PrefixV2.BlindedPublicKeyHash]: new Uint8Array([1, 2, 49, 223]),
226
+ [PrefixV2.BLS12_381PublicKeyHash]: new Uint8Array([6, 161, 166]),
227
+ [PrefixV2.TXRollupAddress]: new Uint8Array([1, 128, 120, 31]),
228
+ [PrefixV2.ZkRollupHash]: new Uint8Array([1, 23, 224, 125]),
229
+ [PrefixV2.ScRollupHash]: new Uint8Array([1, 118, 132, 217]),
230
+ [PrefixV2.SmartRollupHash]: new Uint8Array([6, 124, 117]),
231
+ [PrefixV2.CryptoboxPublicKeyHash]: new Uint8Array([153, 103]),
232
+ [PrefixV2.Ed25519Seed]: new Uint8Array([13, 15, 58, 7]),
233
+ [PrefixV2.Ed25519PublicKey]: new Uint8Array([13, 15, 37, 217]),
234
+ [PrefixV2.Secp256k1SecretKey]: new Uint8Array([17, 162, 224, 201]),
235
+ [PrefixV2.P256SecretKey]: new Uint8Array([16, 81, 238, 189]),
236
+ [PrefixV2.BLS12_381SecretKey]: new Uint8Array([3, 150, 192, 40]),
237
+ [PrefixV2.ValueHash]: new Uint8Array([1, 106, 242]),
238
+ [PrefixV2.CycleNonce]: new Uint8Array([69, 220, 169]),
239
+ [PrefixV2.ScriptExpr]: new Uint8Array([13, 44, 64, 27]),
240
+ [PrefixV2.InboxHash]: new Uint8Array([79, 148, 196]),
241
+ [PrefixV2.MessageHash]: new Uint8Array([79, 149, 30]),
242
+ [PrefixV2.CommitmentHash]: new Uint8Array([79, 148, 17]),
243
+ [PrefixV2.MessageResultHash]: new Uint8Array([18, 7, 206, 87]),
244
+ [PrefixV2.MessageResultListHash]: new Uint8Array([79, 146, 82]),
245
+ [PrefixV2.WithdrawListHash]: new Uint8Array([79, 150, 72]),
246
+ [PrefixV2.ScRollupStateHash]: new Uint8Array([17, 144, 122, 202]),
247
+ [PrefixV2.ScRollupCommitmentHash]: new Uint8Array([17, 144, 21, 100]),
248
+ [PrefixV2.SmartRollupStateHash]: new Uint8Array([17, 165, 235, 240]),
249
+ [PrefixV2.SmartRollupCommitmentHash]: new Uint8Array([17, 165, 134, 138]),
250
+ [PrefixV2.Ed25519EncryptedSeed]: new Uint8Array([7, 90, 60, 179, 41]),
251
+ [PrefixV2.Secp256k1EncryptedSecretKey]: new Uint8Array([9, 237, 241, 174, 150]),
252
+ [PrefixV2.P256EncryptedSecretKey]: new Uint8Array([9, 48, 57, 115, 171]),
253
+ [PrefixV2.BLS12_381EncryptedSecretKey]: new Uint8Array([2, 5, 30, 53, 25]),
254
+ [PrefixV2.Secp256k1EncryptedScalar]: new Uint8Array([1, 131, 36, 86, 248]),
255
+ [PrefixV2.Secp256k1PublicKey]: new Uint8Array([3, 254, 226, 86]),
256
+ [PrefixV2.P256PublicKey]: new Uint8Array([3, 178, 139, 127]),
257
+ [PrefixV2.Secp256k1Scalar]: new Uint8Array([38, 248, 136]),
258
+ [PrefixV2.Secp256k1Element]: new Uint8Array([5, 92, 0]),
259
+ [PrefixV2.Ed25519SecretKey]: new Uint8Array([43, 246, 78, 7]),
260
+ [PrefixV2.Ed25519Signature]: new Uint8Array([9, 245, 205, 134, 18]),
261
+ [PrefixV2.Secp256k1Signature]: new Uint8Array([13, 115, 101, 19, 63]),
262
+ [PrefixV2.P256Signature]: new Uint8Array([54, 240, 44, 52]),
263
+ [PrefixV2.GenericSignature]: new Uint8Array([4, 130, 43]),
264
+ [PrefixV2.ChainID]: new Uint8Array([87, 82, 0]),
265
+ [PrefixV2.SaplingSpendingKey]: new Uint8Array([11, 237, 20, 92]),
266
+ [PrefixV2.EncryptedSaplingSpendingKey]: new Uint8Array([11, 237, 20, 92]),
267
+ [PrefixV2.SaplingAddress]: new Uint8Array([18, 71, 40, 223]),
268
+ [PrefixV2.GenericAggregateSignature]: new Uint8Array([2, 75, 234, 101]),
269
+ [PrefixV2.BLS12_381Signature]: new Uint8Array([40, 171, 64, 207]),
270
+ [PrefixV2.BLS12_381PublicKey]: new Uint8Array([6, 149, 135, 204]),
271
+ [PrefixV2.SlotHeader]: new Uint8Array([2, 116, 180]),
272
+ };
244
273
  /**
245
- * @category Error
246
- * @description Error that indicates unable to convert data type from one to another
274
+ * @description base58 prefix to payload length mapping
247
275
  */
248
- class ValueConversionError extends UnsupportedActionError {
249
- constructor(value, desiredType) {
250
- super();
251
- this.value = value;
252
- this.desiredType = desiredType;
253
- this.name = 'ValueConversionError';
254
- this.message = `Unable to convert ${value} to a ${desiredType}`;
255
- }
256
- }
276
+ const payloadLength = {
277
+ [PrefixV2.BlockHash]: 32,
278
+ [PrefixV2.OperationHash]: 32,
279
+ [PrefixV2.OperationListHash]: 32,
280
+ [PrefixV2.OperationListListHash]: 32,
281
+ [PrefixV2.ProtocolHash]: 32,
282
+ [PrefixV2.ContextHash]: 32,
283
+ [PrefixV2.BlockMetadataHash]: 32,
284
+ [PrefixV2.OperationMetadataHash]: 32,
285
+ [PrefixV2.OperationMetadataListHash]: 32,
286
+ [PrefixV2.OperationMetadataListListHash]: 32,
287
+ [PrefixV2.Ed25519PublicKeyHash]: 20,
288
+ [PrefixV2.Secp256k1PublicKeyHash]: 20,
289
+ [PrefixV2.P256PublicKeyHash]: 20,
290
+ [PrefixV2.ContractHash]: 20,
291
+ [PrefixV2.BlindedPublicKeyHash]: 20,
292
+ [PrefixV2.BLS12_381PublicKeyHash]: 20,
293
+ [PrefixV2.TXRollupAddress]: 20,
294
+ [PrefixV2.ZkRollupHash]: 20,
295
+ [PrefixV2.ScRollupHash]: 20,
296
+ [PrefixV2.SmartRollupHash]: 20,
297
+ [PrefixV2.CryptoboxPublicKeyHash]: 16,
298
+ [PrefixV2.Ed25519Seed]: 32,
299
+ [PrefixV2.Ed25519PublicKey]: 32,
300
+ [PrefixV2.Secp256k1SecretKey]: 32,
301
+ [PrefixV2.P256SecretKey]: 32,
302
+ [PrefixV2.BLS12_381SecretKey]: 32,
303
+ [PrefixV2.ValueHash]: 32,
304
+ [PrefixV2.CycleNonce]: 32,
305
+ [PrefixV2.ScriptExpr]: 32,
306
+ [PrefixV2.InboxHash]: 32,
307
+ [PrefixV2.MessageHash]: 32,
308
+ [PrefixV2.CommitmentHash]: 32,
309
+ [PrefixV2.MessageResultHash]: 32,
310
+ [PrefixV2.MessageResultListHash]: 32,
311
+ [PrefixV2.WithdrawListHash]: 32,
312
+ [PrefixV2.ScRollupStateHash]: 32,
313
+ [PrefixV2.ScRollupCommitmentHash]: 32,
314
+ [PrefixV2.SmartRollupStateHash]: 32,
315
+ [PrefixV2.SmartRollupCommitmentHash]: 32,
316
+ [PrefixV2.Ed25519EncryptedSeed]: 56,
317
+ [PrefixV2.Secp256k1EncryptedSecretKey]: 56,
318
+ [PrefixV2.P256EncryptedSecretKey]: 56,
319
+ [PrefixV2.BLS12_381EncryptedSecretKey]: 56,
320
+ [PrefixV2.Secp256k1EncryptedScalar]: 60,
321
+ [PrefixV2.Secp256k1PublicKey]: 33,
322
+ [PrefixV2.P256PublicKey]: 33,
323
+ [PrefixV2.Secp256k1Scalar]: 33,
324
+ [PrefixV2.Secp256k1Element]: 33,
325
+ [PrefixV2.Ed25519SecretKey]: 64,
326
+ [PrefixV2.Ed25519Signature]: 64,
327
+ [PrefixV2.Secp256k1Signature]: 64,
328
+ [PrefixV2.P256Signature]: 64,
329
+ [PrefixV2.GenericSignature]: 64,
330
+ [PrefixV2.ChainID]: 4,
331
+ [PrefixV2.SaplingSpendingKey]: 169,
332
+ [PrefixV2.EncryptedSaplingSpendingKey]: 193,
333
+ [PrefixV2.SaplingAddress]: 43,
334
+ [PrefixV2.GenericAggregateSignature]: 96,
335
+ [PrefixV2.BLS12_381Signature]: 96,
336
+ [PrefixV2.BLS12_381PublicKey]: 48,
337
+ [PrefixV2.SlotHeader]: 48,
338
+ };
257
339
 
258
- var ValidationResult;
259
- (function (ValidationResult) {
260
- ValidationResult[ValidationResult["NO_PREFIX_MATCHED"] = 0] = "NO_PREFIX_MATCHED";
261
- ValidationResult[ValidationResult["INVALID_CHECKSUM"] = 1] = "INVALID_CHECKSUM";
262
- ValidationResult[ValidationResult["INVALID_LENGTH"] = 2] = "INVALID_LENGTH";
263
- ValidationResult[ValidationResult["VALID"] = 3] = "VALID";
264
- })(ValidationResult || (ValidationResult = {}));
265
- function isValidPrefix(value) {
266
- if (typeof value !== 'string') {
267
- return false;
268
- }
269
- return value in prefix;
340
+ /**
341
+ * @description Used to check if a value has one of the allowed prefixes.
342
+ * @returns true if the value has one of the allowed prefixes, false otherwise
343
+ * @example
344
+ * ```
345
+ * import { isValidPrefixedValue } from '@taquito/utils';
346
+ * const value = 'tz1L9r8mWmRPndRhuvMCWESLGSVeFzQ9NAWx'
347
+ * const isValid = isValidPrefixedValue(value, [PrefixV2.Ed25519PublicKeyHash])
348
+ * console.log(isValid) // true
349
+ * ```
350
+ */
351
+ function isValidPrefixedValue(value, prefixes) {
352
+ return validatePrefixedValue(value, prefixes) === ValidationResult.VALID;
270
353
  }
271
354
  /**
272
355
  * @description This function is called by the validation functions ([[validateAddress]], [[validateChain]], [[validateContractAddress]], [[validateKeyHash]], [[validateSignature]], [[validatePublicKey]]).
273
- * Verify if the value has the right prefix or return `NO_PREFIX_MATCHED`,
274
- * decode the value using base58 and return `INVALID_CHECKSUM` if it fails,
275
- * check if the length of the value matches the prefix type or return `INVALID_LENGTH`.
276
- * If all checks pass, return `VALID`.
277
- *
356
+ * Verify if the value can be decoded or return `1` (INVALID_CHECKSUM) / `5` (INVALID_ENCODING), then check if the prefix is valid or allowed or return `0` (NO_PREFIX_MATCHED) / `4` (PREFIX_NOT_ALLOWED)
357
+ * If all checks pass, return `3` (VALID).
278
358
  * @param value Value to validate
279
359
  * @param prefixes prefix the value should have
360
+ * @returns 0 = NO_PREFIX_MATCHED, 1 = INVALID_CHECKSUM, 2 = INVALID_LENGTH, 3 = VALID, 4 = PREFIX_NOT_ALLOWED, 5 = INVALID_ENCODING, 6 = OTHER,
361
+ * @example
362
+ * ```
363
+ * import { validatePrefixedValue } from '@taquito/utils';
364
+ * const value = 'tz1L9r8mWmRPndRhuvMCWESLGSVeFzQ9NAWx'
365
+ * const validation = validatePrefixedValue(value, [PrefixV2.Ed25519PublicKeyHash])
366
+ * console.log(validation) // 3
367
+ * ```
280
368
  */
281
369
  function validatePrefixedValue(value, prefixes) {
282
- const match = new RegExp(`^(${prefixes.join('|')})`).exec(value);
283
- if (!match || match.length === 0) {
284
- return ValidationResult.NO_PREFIX_MATCHED;
285
- }
286
- const prefixKey = match[0];
287
- if (!isValidPrefix(prefixKey)) {
288
- return ValidationResult.NO_PREFIX_MATCHED;
289
- }
290
- // Check whether annotation exist before starting validation
291
- if (value.includes('%')) {
292
- value = value.split('%')[0];
293
- }
294
- const kt1Regex = /^(KT1\w{33})$/;
295
- if (!kt1Regex.test(value) && prefixKey === 'KT1') {
296
- return ValidationResult.INVALID_CHECKSUM;
297
- }
298
- // decodeUnsafe return undefined if decoding fail
299
- let decoded = bs58check.decodeUnsafe(value);
300
- if (!decoded) {
301
- return ValidationResult.INVALID_CHECKSUM;
370
+ try {
371
+ b58DecodeAndCheckPrefix(value, prefixes);
302
372
  }
303
- decoded = decoded.slice(prefix[prefixKey].length);
304
- if (decoded.length !== prefixLength[prefixKey]) {
305
- return ValidationResult.INVALID_LENGTH;
373
+ catch (err) {
374
+ if (err instanceof ParameterValidationError && err.result !== undefined) {
375
+ return err.result;
376
+ }
377
+ return ValidationResult.OTHER;
306
378
  }
307
379
  return ValidationResult.VALID;
308
380
  }
309
- const implicitPrefix = [Prefix.TZ1, Prefix.TZ2, Prefix.TZ3, Prefix.TZ4];
310
- const contractPrefix = [Prefix.KT1];
311
- const signaturePrefix = [Prefix.EDSIG, Prefix.P2SIG, Prefix.SPSIG, Prefix.SIG];
312
- const pkPrefix = [Prefix.EDPK, Prefix.SPPK, Prefix.P2PK, Prefix.BLPK];
313
- const operationPrefix = [Prefix.O];
314
- const protocolPrefix = [Prefix.P];
315
- const blockPrefix = [Prefix.B];
316
- const smartRollupPrefix = [Prefix.SR1];
317
381
  /**
318
382
  * @description Used to check if an address or a contract address is valid.
319
383
  *
320
384
  * @returns
321
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
385
+ * 0 = NO_PREFIX_MATCHED, 1 = INVALID_CHECKSUM, 2 = INVALID_LENGTH, 3 = VALID, 4 = PREFIX_NOT_ALLOWED, 5 = INVALID_ENCODING, 6 = OTHER,
322
386
  *
323
387
  * @example
324
388
  * ```
@@ -330,13 +394,14 @@ const smartRollupPrefix = [Prefix.SR1];
330
394
  * ```
331
395
  */
332
396
  function validateAddress(value) {
333
- return validatePrefixedValue(value, [...implicitPrefix, ...contractPrefix, ...smartRollupPrefix]);
397
+ const [addr] = splitAddress(value !== null && value !== void 0 ? value : '');
398
+ return validatePrefixedValue(addr, addressPrefixes);
334
399
  }
335
400
  /**
336
401
  * @description Used to check if a chain id is valid.
337
402
  *
338
403
  * @returns
339
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
404
+ * 0 = NO_PREFIX_MATCHED, 1 = INVALID_CHECKSUM, 2 = INVALID_LENGTH, 3 = VALID, 4 = PREFIX_NOT_ALLOWED, 5 = INVALID_ENCODING, 6 = OTHER,
340
405
  *
341
406
  * @example
342
407
  * ```
@@ -348,13 +413,13 @@ function validateAddress(value) {
348
413
  * ```
349
414
  */
350
415
  function validateChain(value) {
351
- return validatePrefixedValue(value, [Prefix.NET]);
416
+ return validatePrefixedValue(value, [PrefixV2.ChainID]);
352
417
  }
353
418
  /**
354
419
  * @description Used to check if a contract address is valid.
355
420
  *
356
421
  * @returns
357
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
422
+ * 0 = NO_PREFIX_MATCHED, 1 = INVALID_CHECKSUM, 2 = INVALID_LENGTH, 3 = VALID, 4 = PREFIX_NOT_ALLOWED, 5 = INVALID_ENCODING, 6 = OTHER,
358
423
  *
359
424
  * @example
360
425
  * ```
@@ -366,13 +431,13 @@ function validateChain(value) {
366
431
  * ```
367
432
  */
368
433
  function validateContractAddress(value) {
369
- return validatePrefixedValue(value, contractPrefix);
434
+ return validatePrefixedValue(value, [PrefixV2.ContractHash]);
370
435
  }
371
436
  /**
372
437
  * @description Used to check if a key hash is valid.
373
438
  *
374
439
  * @returns
375
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
440
+ * 0 = NO_PREFIX_MATCHED, 1 = INVALID_CHECKSUM, 2 = INVALID_LENGTH, 3 = VALID, 4 = PREFIX_NOT_ALLOWED, 5 = INVALID_ENCODING, 6 = OTHER,
376
441
  *
377
442
  * @example
378
443
  * ```
@@ -384,13 +449,13 @@ function validateContractAddress(value) {
384
449
  * ```
385
450
  */
386
451
  function validateKeyHash(value) {
387
- return validatePrefixedValue(value, implicitPrefix);
452
+ return validatePrefixedValue(value, publicKeyHashPrefixes);
388
453
  }
389
454
  /**
390
455
  * @description Used to check if a signature is valid.
391
456
  *
392
457
  * @returns
393
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
458
+ * 0 = NO_PREFIX_MATCHED, 1 = INVALID_CHECKSUM, 2 = INVALID_LENGTH, 3 = VALID, 4 = PREFIX_NOT_ALLOWED, 5 = INVALID_ENCODING, 6 = OTHER,
394
459
  *
395
460
  * @example
396
461
  * ```
@@ -402,13 +467,13 @@ function validateKeyHash(value) {
402
467
  * ```
403
468
  */
404
469
  function validateSignature(value) {
405
- return validatePrefixedValue(value, signaturePrefix);
470
+ return validatePrefixedValue(value, signaturePrefixes);
406
471
  }
407
472
  /**
408
473
  * @description Used to check if a public key is valid.
409
474
  *
410
475
  * @returns
411
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
476
+ * 0 = NO_PREFIX_MATCHED, 1 = INVALID_CHECKSUM, 2 = INVALID_LENGTH, 3 = VALID, 4 = PREFIX_NOT_ALLOWED, 5 = INVALID_ENCODING, 6 = OTHER,
412
477
  *
413
478
  * @example
414
479
  * ```
@@ -420,13 +485,13 @@ function validateSignature(value) {
420
485
  * ```
421
486
  */
422
487
  function validatePublicKey(value) {
423
- return validatePrefixedValue(value, pkPrefix);
488
+ return validatePrefixedValue(value, publicKeyPrefixes);
424
489
  }
425
490
  /**
426
491
  * @description Used to check if an operation hash is valid.
427
492
  *
428
493
  * @returns
429
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
494
+ * 0 = NO_PREFIX_MATCHED, 1 = INVALID_CHECKSUM, 2 = INVALID_LENGTH, 3 = VALID, 4 = PREFIX_NOT_ALLOWED, 5 = INVALID_ENCODING, 6 = OTHER,
430
495
  *
431
496
  * @example
432
497
  * ```
@@ -438,13 +503,13 @@ function validatePublicKey(value) {
438
503
  * ```
439
504
  */
440
505
  function validateOperation(value) {
441
- return validatePrefixedValue(value, operationPrefix);
506
+ return validatePrefixedValue(value, [PrefixV2.OperationHash]);
442
507
  }
443
508
  /**
444
509
  * @description Used to check if a protocol hash is valid.
445
510
  *
446
511
  * @returns
447
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
512
+ * 0 = NO_PREFIX_MATCHED, 1 = INVALID_CHECKSUM, 2 = INVALID_LENGTH, 3 = VALID, 4 = PREFIX_NOT_ALLOWED, 5 = INVALID_ENCODING, 6 = OTHER,
448
513
  *
449
514
  * @example
450
515
  * ```
@@ -456,13 +521,13 @@ function validateOperation(value) {
456
521
  * ```
457
522
  */
458
523
  function validateProtocol(value) {
459
- return validatePrefixedValue(value, protocolPrefix);
524
+ return validatePrefixedValue(value, [PrefixV2.ProtocolHash]);
460
525
  }
461
526
  /**
462
527
  * @description Used to check if a block hash is valid.
463
528
  *
464
529
  * @returns
465
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
530
+ * 0 = NO_PREFIX_MATCHED, 1 = INVALID_CHECKSUM, 2 = INVALID_LENGTH, 3 = VALID, 4 = PREFIX_NOT_ALLOWED, 5 = INVALID_ENCODING, 6 = OTHER,
466
531
  *
467
532
  * @example
468
533
  * ```
@@ -474,16 +539,12 @@ function validateProtocol(value) {
474
539
  * ```
475
540
  */
476
541
  function validateBlock(value) {
477
- return validatePrefixedValue(value, blockPrefix);
542
+ return validatePrefixedValue(value, [PrefixV2.BlockHash]);
478
543
  }
479
544
  /**
480
- * @description Used to check if a spending key is valid.
481
- * @returns 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
482
- *
545
+ * @deprecated this function will be removed in the next minor release
546
+ * @description generates a readable error string from a validation result
483
547
  */
484
- function validateSpendingKey(value) {
485
- return validatePrefixedValue(value, [Prefix.SASK]);
486
- }
487
548
  function invalidDetail(validation) {
488
549
  switch (validation) {
489
550
  case ValidationResult.NO_PREFIX_MATCHED:
@@ -496,16 +557,191 @@ function invalidDetail(validation) {
496
557
  return '';
497
558
  }
498
559
  }
560
+ /**
561
+ * @description Used to check if a spending key is valid.
562
+ * @returns
563
+ * 0 = NO_PREFIX_MATCHED, 1 = INVALID_CHECKSUM, 2 = INVALID_LENGTH, 3 = VALID, 4 = PREFIX_NOT_ALLOWED, 5 = INVALID_ENCODING, 6 = OTHER,
564
+ *
565
+ */
566
+ function validateSpendingKey(value) {
567
+ return validatePrefixedValue(value, [PrefixV2.SaplingSpendingKey]);
568
+ }
499
569
  function validateSmartRollupAddress(value) {
500
- return validatePrefixedValue(value, [...smartRollupPrefix]);
570
+ return validatePrefixedValue(value, [PrefixV2.SmartRollupHash]);
501
571
  }
502
572
 
503
573
  // IMPORTANT: THIS FILE IS AUTO GENERATED! DO NOT MANUALLY EDIT OR CHECKIN!
504
574
  const VERSION = {
505
- "commitHash": "7af2138a9e5c5b230c4b4c726f35c2f2e67b721c",
506
- "version": "23.0.0-beta.0"
575
+ "commitHash": "10b3de10de15ae68d47b1fca922d3129d2f79641",
576
+ "version": "23.0.0-beta.1"
507
577
  };
508
578
 
579
+ const BLS12_381_DST = 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_';
580
+ const POP_DST = 'BLS_POP_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_';
581
+ /**
582
+ * @description Verify signature of a payload
583
+ * @param message The forged message including the magic byte (11 for block, 12 for preattestation, 13 for attestation, 3 for generic, 5 for the PACK format of michelson) in string or Uint8Array
584
+ * @param publicKey The public key to verify the signature against
585
+ * @param signature The signature to verify
586
+ * @param watermark Optional if not included in the message
587
+ * @param pop Optional if verifying proof of possession signature
588
+ * @returns A boolean indicating if the signature matches
589
+ * @throws {@link InvalidPublicKeyError} | {@link InvalidSignatureError} | {@link InvalidMessageError}
590
+ * @example
591
+ * ```
592
+ * const message = '03d0c10e3ed11d7c6e3357f6ef335bab9e8f2bd54d0ce20c482e241191a6e4b8ce6c01be917311d9ac46959750e405d57e268e2ed9e174a80794fbd504e12a4a000141eb3781afed2f69679ff2bbe1c5375950b0e40d00ff000000005e05050505050507070100000024747a32526773486e74516b72794670707352466261313652546656503539684b72654a4d07070100000024747a315a6672455263414c42776d4171776f6e525859565142445439426a4e6a42484a750001';
593
+ * const pk = 'sppk7c7hkPj47yjYFEHX85q46sFJGw6RBrqoVSHwAJAT4e14KJwzoey';
594
+ * const sig = 'spsig1cdLkp1RLgUHAp13aRFkZ6MQDPp7xCnjAExGL3MBSdMDmT6JgQSX8cufyDgJRM3sinFtiCzLbsyP6d365EHoNevxhT47nx'
595
+ *
596
+ * const response = verifySignature(message, pk, sig);
597
+ * ```
598
+ *
599
+ */
600
+ function verifySignature(message, publicKey, signature, watermark, pop) {
601
+ const [pk, pre] = (() => {
602
+ try {
603
+ return b58DecodeAndCheckPrefix(publicKey, publicKeyPrefixes);
604
+ }
605
+ catch (err) {
606
+ if (err instanceof ParameterValidationError) {
607
+ throw new InvalidPublicKeyError(publicKey, err.result);
608
+ }
609
+ else {
610
+ throw err;
611
+ }
612
+ }
613
+ })();
614
+ const sig = (() => {
615
+ try {
616
+ const [sig] = b58DecodeAndCheckPrefix(signature, signaturePrefixes);
617
+ return sig;
618
+ }
619
+ catch (err) {
620
+ if (err instanceof ParameterValidationError) {
621
+ throw new InvalidSignatureError(signature, err.result);
622
+ }
623
+ else {
624
+ throw err;
625
+ }
626
+ }
627
+ })();
628
+ let msg;
629
+ if (typeof message === 'string') {
630
+ msg = hex2buf(message);
631
+ }
632
+ else {
633
+ msg = message;
634
+ }
635
+ if (msg.length === 0) {
636
+ throw new InvalidMessageError(buf2hex(msg), `can't be empty`);
637
+ }
638
+ if (typeof watermark !== 'undefined') {
639
+ msg = mergebuf(watermark, msg);
640
+ }
641
+ if (pop) {
642
+ return verifyBLSPopSignature(sig, msg, pk);
643
+ }
644
+ else {
645
+ switch (pre) {
646
+ case PrefixV2.P256PublicKey:
647
+ return verifyP2Signature(sig, msg, pk);
648
+ case PrefixV2.Secp256k1PublicKey:
649
+ return verifySpSignature(sig, msg, pk);
650
+ case PrefixV2.Ed25519PublicKey:
651
+ return verifyEdSignature(sig, msg, pk);
652
+ default:
653
+ return verifyBLSSignature(sig, msg, pk);
654
+ }
655
+ }
656
+ }
657
+ /**
658
+ * @deprecated use b58DecodeAndCheckPrefix instead, this function will be removed in the next minor release
659
+ * @description validates a public key and extracts the prefix
660
+ */
661
+ function validatePkAndExtractPrefix(publicKey) {
662
+ if (publicKey === '') {
663
+ throw new InvalidPublicKeyError(publicKey, `can't be empty`);
664
+ }
665
+ const pkPrefix = publicKey.substring(0, 4);
666
+ const publicKeyValidation = validatePublicKey(publicKey);
667
+ if (publicKeyValidation !== ValidationResult.VALID) {
668
+ throw new InvalidPublicKeyError(publicKey, invalidDetail(publicKeyValidation));
669
+ }
670
+ return pkPrefix;
671
+ }
672
+ function verifyEdSignature(sig, msg, publicKey) {
673
+ const hash$1 = hash(msg, 32);
674
+ try {
675
+ return verify(publicKey, hash$1, sig);
676
+ }
677
+ catch (_a) {
678
+ return false;
679
+ }
680
+ }
681
+ function verifySpSignature(sig, msg, publicKey) {
682
+ const key = new elliptic.ec('secp256k1').keyFromPublic(publicKey);
683
+ return verifySpOrP2Sig(sig, msg, key);
684
+ }
685
+ function verifyP2Signature(sig, msg, publicKey) {
686
+ const key = new elliptic.ec('p256').keyFromPublic(publicKey);
687
+ return verifySpOrP2Sig(sig, msg, key);
688
+ }
689
+ function verifySpOrP2Sig(sig, msg, key) {
690
+ const r = sig.slice(0, 32);
691
+ const s = sig.slice(32);
692
+ const hash$1 = hash(msg, 32);
693
+ try {
694
+ return key.verify(hash$1, { r, s });
695
+ }
696
+ catch (_a) {
697
+ return false;
698
+ }
699
+ }
700
+ const bls = bls12_381.longSignatures; // AKA MinPK
701
+ function verifyBLSSignature(sig, msg, publicKey) {
702
+ try {
703
+ const point = bls.hash(msg, BLS12_381_DST);
704
+ return bls.verify(sig, point, publicKey);
705
+ }
706
+ catch (_a) {
707
+ return false;
708
+ }
709
+ }
710
+ function verifyBLSPopSignature(sig, msg, publicKey) {
711
+ try {
712
+ const point = bls.hash(msg, POP_DST);
713
+ return bls.verify(sig, point, publicKey);
714
+ }
715
+ catch (_a) {
716
+ return false;
717
+ }
718
+ }
719
+
720
+ /**
721
+ * @category Error
722
+ * @description Error that indicates invalid protocol hash being passed or used
723
+ */
724
+ class InvalidProtocolHashError extends ParameterValidationError {
725
+ constructor(protocolHash, errorDetails) {
726
+ super(`The protocol hash '${protocolHash}' is invalid`, errorDetails);
727
+ this.protocolHash = protocolHash;
728
+ this.name = 'InvalidProtocolHashError';
729
+ this.name = this.constructor.name;
730
+ }
731
+ }
732
+ /**
733
+ * @category Error
734
+ * @description Error that indicates unable to convert data type from one to another
735
+ */
736
+ class ValueConversionError extends UnsupportedActionError {
737
+ constructor(value, desiredType) {
738
+ super(`Unable to convert ${value} to a ${desiredType}`);
739
+ this.value = value;
740
+ this.desiredType = desiredType;
741
+ this.name = this.constructor.name;
742
+ }
743
+ }
744
+
509
745
  const TZ_DECIMALS = 6;
510
746
  const MTZ_DECIMALS = 3;
511
747
  function getDecimal(format) {
@@ -539,222 +775,421 @@ function format(from = 'mutez', to = 'mutez', amount) {
539
775
  * Copyright (c) 2017 Stephen Andrews
540
776
  */
541
777
  /**
542
- *
543
- * @description Hash a string using the BLAKE2b algorithm, base58 encode the hash obtained and appends the prefix 'expr' to it
544
- *
545
- * @param value Value in hex
778
+ * @description list of prefixes that can be used to decode an address
546
779
  */
547
- function encodeExpr(value) {
548
- const blakeHash = blake.blake2b(hex2buf(value), undefined, 32);
549
- return b58cencode(blakeHash, prefix['expr']);
550
- }
780
+ const addressPrefixes = [
781
+ PrefixV2.P256PublicKeyHash,
782
+ PrefixV2.Secp256k1PublicKeyHash,
783
+ PrefixV2.Ed25519PublicKeyHash,
784
+ PrefixV2.BLS12_381PublicKeyHash,
785
+ PrefixV2.ContractHash,
786
+ PrefixV2.SmartRollupHash,
787
+ // PrefixV2.ZkRollupHash,
788
+ ];
551
789
  /**
552
- *
553
- * @description Return the operation hash of a signed operation
554
- * @param value Value in hex of a signed operation
790
+ * @description list of prefixes that can be used to decode a public key
555
791
  */
556
- function encodeOpHash(value) {
557
- const blakeHash = blake.blake2b(hex2buf(value), undefined, 32);
558
- return b58cencode(blakeHash, prefix.o);
792
+ const publicKeyPrefixes = [
793
+ PrefixV2.P256PublicKey,
794
+ PrefixV2.Secp256k1PublicKey,
795
+ PrefixV2.Ed25519PublicKey,
796
+ PrefixV2.BLS12_381PublicKey,
797
+ ];
798
+ /**
799
+ * @description list of prefixes that can be used to decode a public key hash
800
+ */
801
+ const publicKeyHashPrefixes = [
802
+ PrefixV2.P256PublicKeyHash,
803
+ PrefixV2.Secp256k1PublicKeyHash,
804
+ PrefixV2.Ed25519PublicKeyHash,
805
+ PrefixV2.BLS12_381PublicKeyHash,
806
+ ];
807
+ /**
808
+ * @description list of prefixes that can be used to decode a signature
809
+ */
810
+ const signaturePrefixes = [
811
+ PrefixV2.P256Signature,
812
+ PrefixV2.Secp256k1Signature,
813
+ PrefixV2.Ed25519Signature,
814
+ PrefixV2.BLS12_381Signature,
815
+ PrefixV2.GenericSignature,
816
+ ];
817
+ function b58DecodeAndCheckPrefix(src, allowed, payloadOnly) {
818
+ const buf = (() => {
819
+ try {
820
+ return bs58check.decode(src);
821
+ }
822
+ catch (err) {
823
+ if (err instanceof Error) {
824
+ if (err.message.includes('checksum')) {
825
+ throw new ParameterValidationError(ValidationResult.INVALID_CHECKSUM);
826
+ }
827
+ else {
828
+ throw new ParameterValidationError(ValidationResult.INVALID_ENCODING);
829
+ }
830
+ }
831
+ else {
832
+ throw err;
833
+ }
834
+ }
835
+ })();
836
+ let key;
837
+ for (key in PrefixV2) {
838
+ const p = PrefixV2[key];
839
+ const pre = prefixV2[p];
840
+ if (buf.length === pre.length + payloadLength[p] &&
841
+ buf.slice(0, pre.length).every((v, i) => v == pre[i])) {
842
+ if (allowed !== undefined && allowed.indexOf(p) < 0) {
843
+ throw new ParameterValidationError(ValidationResult.PREFIX_NOT_ALLOWED);
844
+ }
845
+ if (payloadOnly) {
846
+ return buf.slice(pre.length);
847
+ }
848
+ else {
849
+ return [buf.slice(pre.length), p];
850
+ }
851
+ }
852
+ }
853
+ throw new ParameterValidationError(ValidationResult.NO_PREFIX_MATCHED);
854
+ }
855
+ function b58DecodePublicKey(value, fmt) {
856
+ const [data, pre] = b58DecodeAndCheckPrefix(value, publicKeyPrefixes);
857
+ let tag;
858
+ switch (pre) {
859
+ case PrefixV2.Ed25519PublicKey:
860
+ tag = 0;
861
+ break;
862
+ case PrefixV2.Secp256k1PublicKey:
863
+ tag = 1;
864
+ break;
865
+ case PrefixV2.P256PublicKey:
866
+ tag = 2;
867
+ break;
868
+ case PrefixV2.BLS12_381PublicKey:
869
+ tag = 3;
870
+ break;
871
+ default:
872
+ throw new InvalidKeyError(ValidationResult.NO_PREFIX_MATCHED);
873
+ }
874
+ const buf = new Uint8Array(data.length + 1);
875
+ buf[0] = tag;
876
+ buf.set(data, 1);
877
+ if (fmt !== undefined && fmt === 'array') {
878
+ return buf;
879
+ }
880
+ else {
881
+ return buf2hex(buf);
882
+ }
883
+ }
884
+ function b58DecodePublicKeyHash(value, fmt) {
885
+ const [data, pre] = b58DecodeAndCheckPrefix(value, publicKeyHashPrefixes);
886
+ const buf = new Uint8Array(21);
887
+ let tag;
888
+ switch (pre) {
889
+ case PrefixV2.Ed25519PublicKeyHash:
890
+ tag = 0;
891
+ break;
892
+ case PrefixV2.Secp256k1PublicKeyHash:
893
+ tag = 1;
894
+ break;
895
+ case PrefixV2.P256PublicKeyHash:
896
+ tag = 2;
897
+ break;
898
+ case PrefixV2.BLS12_381PublicKeyHash:
899
+ tag = 3;
900
+ break;
901
+ default:
902
+ throw new InvalidAddressError(value, ValidationResult.NO_PREFIX_MATCHED);
903
+ }
904
+ buf[0] = tag;
905
+ buf.set(data, 1);
906
+ if (fmt !== undefined && fmt === 'array') {
907
+ return buf;
908
+ }
909
+ else {
910
+ return buf2hex(buf);
911
+ }
912
+ }
913
+ function b58DecodeBlsAddress(value, fmt) {
914
+ const [buf, pre] = b58DecodeAndCheckPrefix(value);
915
+ if (pre !== PrefixV2.BLS12_381PublicKeyHash) {
916
+ throw new InvalidKeyError(ValidationResult.NO_PREFIX_MATCHED);
917
+ }
918
+ if (fmt !== undefined && fmt === 'array') {
919
+ return buf;
920
+ }
921
+ else {
922
+ return buf2hex(buf);
923
+ }
924
+ }
925
+ function b58DecodeAddress(value, fmt) {
926
+ const i = value.indexOf('%');
927
+ if (i >= 0) {
928
+ value = value.slice(0, i);
929
+ }
930
+ const [data, pre] = b58DecodeAndCheckPrefix(value, addressPrefixes);
931
+ const buf = new Uint8Array(22);
932
+ if (pre === PrefixV2.ContractHash ||
933
+ pre === PrefixV2.SmartRollupHash ||
934
+ pre === PrefixV2.ZkRollupHash) {
935
+ let tag;
936
+ switch (pre) {
937
+ case PrefixV2.ContractHash:
938
+ tag = 1;
939
+ break;
940
+ case PrefixV2.SmartRollupHash:
941
+ tag = 3;
942
+ break;
943
+ case PrefixV2.ZkRollupHash:
944
+ tag = 4;
945
+ break;
946
+ }
947
+ buf[0] = tag;
948
+ buf.set(data, 1);
949
+ }
950
+ else {
951
+ let tag;
952
+ switch (pre) {
953
+ case PrefixV2.Ed25519PublicKeyHash:
954
+ tag = 0;
955
+ break;
956
+ case PrefixV2.Secp256k1PublicKeyHash:
957
+ tag = 1;
958
+ break;
959
+ case PrefixV2.P256PublicKeyHash:
960
+ tag = 2;
961
+ break;
962
+ case PrefixV2.BLS12_381PublicKeyHash:
963
+ tag = 3;
964
+ break;
965
+ default:
966
+ throw new InvalidAddressError(value, ValidationResult.NO_PREFIX_MATCHED);
967
+ }
968
+ buf[0] = 0;
969
+ buf[1] = tag;
970
+ buf.set(data, 2);
971
+ }
972
+ if (fmt !== undefined && fmt === 'array') {
973
+ return buf;
974
+ }
975
+ else {
976
+ return buf2hex(buf);
977
+ }
559
978
  }
560
979
  /**
561
- *
562
- * @description Base58 encode a string or a Uint8Array and append a prefix to it
563
- *
564
- * @param value Value to base58 encode
565
- * @param prefix prefix to append to the encoded string
980
+ * @description Gets Tezos address (PKH) from Public Key
981
+ * @param publicKey Base58 Public Key
982
+ * @returns A string of the Tezos address (PKH) that was derived from the given Public Key
983
+ * @example getPkhfromPk('edpkuNjKKT48xBoT5asPrWdmuM1Yw8D93MwgFgVvtca8jb5pstzaCh') // return 'tz2MVED1t9Jery77Bwm1m5YhUx8Wp5KWWRQe'
566
984
  */
567
- function b58cencode(value, prefix) {
568
- const payloadAr = typeof value === 'string' ? Uint8Array.from(Buffer.from(value, 'hex')) : value;
569
- const n = new Uint8Array(prefix.length + payloadAr.length);
570
- n.set(prefix);
571
- n.set(payloadAr, prefix.length);
572
- return bs58check.encode(Buffer.from(n.buffer));
985
+ function getPkhfromPk(publicKey) {
986
+ const [key, pre] = b58DecodeAndCheckPrefix(publicKey);
987
+ let pkhPre;
988
+ switch (pre) {
989
+ case PrefixV2.P256PublicKey:
990
+ pkhPre = PrefixV2.P256PublicKeyHash;
991
+ break;
992
+ case PrefixV2.Secp256k1PublicKey:
993
+ pkhPre = PrefixV2.Secp256k1PublicKeyHash;
994
+ break;
995
+ case PrefixV2.Ed25519PublicKey:
996
+ pkhPre = PrefixV2.Ed25519PublicKeyHash;
997
+ break;
998
+ case PrefixV2.BLS12_381PublicKey:
999
+ pkhPre = PrefixV2.BLS12_381PublicKeyHash;
1000
+ break;
1001
+ default:
1002
+ throw new InvalidPublicKeyError(publicKey, ValidationResult.NO_PREFIX_MATCHED);
1003
+ }
1004
+ const hashed = hash(key, 20);
1005
+ return b58Encode(hashed, pkhPre);
573
1006
  }
574
1007
  /**
575
- *
576
- * @description Base58 decode a string and remove the prefix from it
577
- *
578
- * @param value Value to base58 decode
579
- * @param prefix prefix to remove from the decoded string
1008
+ * @description Add the prefix to a hex string or Uint8Array and Base58 encode it
1009
+ * @param value Value to Base58 encode
1010
+ * @param pre prefix ID to append to the encoded string
1011
+ * @example b58Encode('e96b9f8b19af9c7ffa0c0480e1977b295850961f', PrefixV2.Ed25519PublicKeyHash) // returns 'tz1gvF4cD2dDtqitL3ZTraggSR1Mju2BKFEM'
580
1012
  */
581
- const b58cdecode = (enc, prefixArg) => bs58check.decode(enc).slice(prefixArg.length);
1013
+ function b58Encode(value, pre) {
1014
+ const data = typeof value === 'string' ? hex2buf(value) : value;
1015
+ const p = prefixV2[pre];
1016
+ const n = new Uint8Array(p.length + data.length);
1017
+ n.set(p);
1018
+ n.set(data, p.length);
1019
+ return bs58check.encode(toBuffer(n));
1020
+ }
582
1021
  /**
583
- *
584
- * @description Base58 decode a string with predefined prefix
585
- *
586
- * @param value Value to base58 decode
1022
+ * @description Parse binary public key and return Base58 representation
1023
+ * @param value Binary key data
1024
+ * @returns return prefixed public key
1025
+ * @example encodeKey('02033aba7da4a2e7b5dd9f074555c118829aff16213ea1b65859686bd5fcfeaf3616') // return 'p2pk66xmhjiN7LpfrDGFwpxPtJxkLtPjQ6HUxJbKmRbxSR7RMpamDwi'
587
1026
  */
588
- function b58decode(payload) {
589
- const buf = bs58check.decode(payload);
590
- const prefixMap = {
591
- [prefix.tz1.toString()]: '0000',
592
- [prefix.tz2.toString()]: '0001',
593
- [prefix.tz3.toString()]: '0002',
594
- [prefix.tz4.toString()]: '0003',
595
- };
596
- const pref = prefixMap[new Uint8Array(buf.slice(0, 3)).toString()];
597
- if (pref) {
598
- // tz addresses
599
- const hex = buf2hex(buf.slice(3));
600
- return pref + hex;
1027
+ function encodeKey(value) {
1028
+ let buf;
1029
+ if (typeof value === 'string') {
1030
+ buf = hex2buf(value);
601
1031
  }
602
1032
  else {
603
- // other (kt addresses)
604
- return '01' + buf2hex(buf.slice(3, 42)) + '00';
1033
+ buf = value;
605
1034
  }
1035
+ let pre;
1036
+ switch (buf[0]) {
1037
+ case 0:
1038
+ pre = PrefixV2.Ed25519PublicKey;
1039
+ break;
1040
+ case 1:
1041
+ pre = PrefixV2.Secp256k1PublicKey;
1042
+ break;
1043
+ case 2:
1044
+ pre = PrefixV2.P256PublicKey;
1045
+ break;
1046
+ case 3:
1047
+ pre = PrefixV2.BLS12_381PublicKey;
1048
+ break;
1049
+ default:
1050
+ throw new Error('invalid address format');
1051
+ }
1052
+ return b58Encode(buf.slice(1), pre);
606
1053
  }
607
1054
  /**
608
- *
609
- * @description b58 decode a string without predefined prefix
610
- * @param value
611
- * @returns string of bytes
612
- * @deprecated use b58decode instead
613
- */
614
- function b58decodeL2Address(payload) {
615
- const buf = bs58check.decode(payload);
616
- // tz4 address currently
617
- return buf2hex(buf.slice(3, 42));
618
- }
619
- /**
620
- *
621
- * @description Base58 encode an address using predefined prefix
622
- *
623
- * @param value Address to base58 encode (tz1, tz2, tz3 or KT1)
624
- * @deprecated use encodeAddress instead, same functionality with a more descriptive name
1055
+ * @description Parse binary public key hash and return Base58 representation
1056
+ * @param value Key hash to parse
1057
+ * @returns return prefixed public key hash
1058
+ * @example encodeKeyHash('0001907d6a7e9f084df840d6e67ffa8db5464f87d4d1') // return 'tz2MVED1t9Jery77Bwm1m5YhUx8Wp5KWWRQe'
625
1059
  */
626
- function encodePubKey(value) {
627
- if (value.substring(0, 2) === '00') {
628
- const pref = {
629
- '0000': prefix.tz1,
630
- '0001': prefix.tz2,
631
- '0002': prefix.tz3,
632
- '0003': prefix.tz4,
633
- };
634
- return b58cencode(value.substring(4), pref[value.substring(0, 4)]);
1060
+ function encodeKeyHash(value) {
1061
+ let buf;
1062
+ if (typeof value === 'string') {
1063
+ buf = hex2buf(value);
1064
+ }
1065
+ else {
1066
+ buf = value;
1067
+ }
1068
+ let pre;
1069
+ switch (buf[0]) {
1070
+ case 0:
1071
+ pre = PrefixV2.Ed25519PublicKeyHash;
1072
+ break;
1073
+ case 1:
1074
+ pre = PrefixV2.Secp256k1PublicKeyHash;
1075
+ break;
1076
+ case 2:
1077
+ pre = PrefixV2.P256PublicKeyHash;
1078
+ break;
1079
+ case 3:
1080
+ pre = PrefixV2.BLS12_381PublicKeyHash;
1081
+ break;
1082
+ default:
1083
+ throw new Error('invalid address format');
635
1084
  }
636
- return b58cencode(value.substring(2, 42), prefix.KT);
1085
+ return b58Encode(buf.slice(1, 21), pre);
637
1086
  }
638
1087
  /**
639
- *
640
- * @description Base58 encode an address using predefined prefix (tz1, tz2, tz3, or KT1 without annotation)
641
- *
642
- * @param value Address to base58 encode (tz1, tz2, tz3 or KT1). Supports value with or without '0x' prefix
1088
+ * @description Parse binary Contract ID and return Base58 representation
1089
+ * @param value Address to parse (tz1, tz2, tz3, KT1, or sr1).
1090
+ * @example encodeAddress('0000e96b9f8b19af9c7ffa0c0480e1977b295850961f') // return 'tz1gvF4cD2dDtqitL3ZTraggSR1Mju2BKFEM'
643
1091
  */
644
1092
  function encodeAddress(value) {
645
- if (value.substring(0, 2) === '0x') {
646
- value = value.slice(2);
1093
+ let buf;
1094
+ if (typeof value === 'string') {
1095
+ buf = hex2buf(value);
1096
+ }
1097
+ else {
1098
+ buf = value;
647
1099
  }
648
- if (value.substring(0, 2) === '00') {
649
- const pref = {
650
- '0000': prefix.tz1,
651
- '0001': prefix.tz2,
652
- '0002': prefix.tz3,
653
- '0003': prefix.tz4,
654
- };
655
- return b58cencode(value.substring(4), pref[value.substring(0, 4)]);
1100
+ switch (buf[0]) {
1101
+ case 0: // implicit
1102
+ return encodeKeyHash(buf.slice(1));
1103
+ case 1: // contract hash
1104
+ return b58Encode(buf.slice(1, 21), PrefixV2.ContractHash);
1105
+ case 3: // smart rollup hash
1106
+ return b58Encode(buf.slice(1, 21), PrefixV2.SmartRollupHash);
1107
+ case 4: // zk rollup hash
1108
+ return b58Encode(buf.slice(1, 21), PrefixV2.ZkRollupHash);
1109
+ default:
1110
+ throw new Error('invalid address format');
656
1111
  }
657
- return b58cencode(value.substring(2, 42), prefix.KT);
658
1112
  }
659
1113
  /**
660
- *
661
1114
  * @description Base58 encode an address without predefined prefix
662
1115
  * @param value Address to base58 encode (tz4) hex dec
663
1116
  * @returns return address
664
- * @deprecated use encodeAddress instead
1117
+ * @example encodeBlsAddress('af2dc3c40667abc0e89c0ef40171d22aed08d5eb') // return 'tz4QyWfEiv56CVDATV3DT3CDVhPaMKif2Ce8'
665
1118
  */
666
- function encodeL2Address(value) {
667
- return b58cencode(value, prefix.tz4);
1119
+ function encodeBlsAddress(value) {
1120
+ return b58Encode(value, PrefixV2.BLS12_381PublicKeyHash);
668
1121
  }
669
1122
  /**
670
- *
671
- * @description Base58 encode a key according to its prefix
672
- *
673
- * @param value Key to base58 encode
1123
+ * @description convert a fragment of Michelson code in hex string to an 'expr' prefix + base58 encoded BLAKE2b hash string
1124
+ * @param value a fragment of Michelson code in hex string
1125
+ * @returns return 'expr' prefix + base58 encoded BLAKE2b hash
1126
+ * @example encodeExpr('050a000000160000b2e19a9e74440d86c59f13dab8a18ff873e889ea') // return 'exprv6UsC1sN3Fk2XfgcJCL8NCerP5rCGy1PRESZAqr7L2JdzX55EN'
674
1127
  */
675
- function encodeKey(value) {
676
- if (value[0] === '0') {
677
- const pref = {
678
- '00': new Uint8Array([13, 15, 37, 217]),
679
- '01': new Uint8Array([3, 254, 226, 86]),
680
- '02': new Uint8Array([3, 178, 139, 127]),
681
- };
682
- return b58cencode(value.substring(2), pref[value.substring(0, 2)]);
683
- }
1128
+ function encodeExpr(value) {
1129
+ const blakeHash = hash(hex2buf(value), 32);
1130
+ return b58Encode(blakeHash, PrefixV2.ScriptExpr);
684
1131
  }
685
1132
  /**
686
- *
687
- * @description Base58 encode a key hash according to its prefix
688
- *
689
- * @param value Key hash to base58 encode
1133
+ * @description convert a signed operation in hex string to an 'op' prefix + base58 encoded BLAKE2b hash string
1134
+ * @param value signed operation in hex string
1135
+ * @returns return 'op' prefix + base58 encoded BLAKE2b hash
1136
+ * @example encodeOpHash('0f185d8a30061e8134c162dbb7a6c3ab8f5fdb153363ccd6149b49a33481156a6c00b2e19a9e74440d86c59f13dab8a18ff873e889eaa304ab05da13000001f1585a7384f36e45fb43dc37e8ce172bced3e05700ff0000000002002110c033f3a990c2e46a3d6054ecc2f74072aae7a34b5ac4d9ce9edc11c2410a97695682108951786f05b361da03b97245dc9897e1955e08b5b8d9e153b0bdeb0d') // return 'opapqvVXmebRTCFd2GQFydr4tJj3V5QocQuTmuhbatcHm4Seo2t'
690
1137
  */
691
- function encodeKeyHash(value) {
692
- if (value[0] === '0') {
693
- const pref = {
694
- '00': new Uint8Array([6, 161, 159]),
695
- '01': new Uint8Array([6, 161, 161]),
696
- '02': new Uint8Array([6, 161, 164]),
697
- '03': new Uint8Array([6, 161, 167]),
698
- };
699
- return b58cencode(value.substring(2), pref[value.substring(0, 2)]);
700
- }
1138
+ function encodeOpHash(value) {
1139
+ const blakeHash = hash(hex2buf(value), 32);
1140
+ return b58Encode(blakeHash, PrefixV2.OperationHash);
701
1141
  }
702
1142
  /**
703
- *
704
1143
  * @description Convert an hex string to a Uint8Array
705
- *
706
1144
  * @param hex Hex string to convert
707
1145
  * @throws {@link ValueConversionError}
708
1146
  */
709
- const hex2buf = (hex) => {
1147
+ function hex2buf(hex) {
1148
+ hex = hex.startsWith('0x') ? hex.slice(2) : hex;
710
1149
  if (hex.length % 2 !== 0) {
711
- throw new InvalidHexStringError(hex, `: Expecting even number of characters`);
1150
+ throw new InvalidHexStringError(hex, `Expecting even number of characters`);
712
1151
  }
713
- const hexDigits = stripHexPrefix(hex);
714
- if (!hexDigits.match(/^([\da-f]{2})*$/gi)) {
715
- throw new InvalidHexStringError(hex, `: Only characters 0-9, a-f and A-F are expected. Optionally, it can be prefixed with '0x'`);
1152
+ if (!hex.match(/^([\da-f]{2})*$/gi)) {
1153
+ throw new InvalidHexStringError(hex, `Only characters 0-9, a-f and A-F are expected. Optionally, it can be prefixed with '0x'`);
716
1154
  }
717
- const out = new Uint8Array(hexDigits.length / 2);
1155
+ const res = new Uint8Array(hex.length / 2);
718
1156
  let j = 0;
719
- for (let i = 0; i < hexDigits.length; i += 2) {
720
- const v = parseInt(hexDigits.slice(i, i + 2), 16);
721
- if (Number.isNaN(v)) {
722
- throw new ValueConversionError(hex, 'Uint8Array');
1157
+ for (let i = 0; i < hex.length; i += 2) {
1158
+ const ss = hex.slice(i, i + 2);
1159
+ const x = parseInt(ss, 16);
1160
+ if (Number.isNaN(x)) {
1161
+ throw new InvalidHexStringError(hex, `Only characters 0-9, a-f and A-F are expected. Optionally, it can be prefixed with '0x'`);
723
1162
  }
724
- out[j++] = v;
1163
+ res[j++] = x;
725
1164
  }
726
- return out;
727
- };
1165
+ return res;
1166
+ }
728
1167
  /**
729
- *
730
1168
  * @description Merge 2 buffers together
731
- *
732
1169
  * @param b1 First buffer
733
1170
  * @param b2 Second buffer
734
1171
  */
735
- const mergebuf = (b1, b2) => {
1172
+ function mergebuf(b1, b2) {
736
1173
  const r = new Uint8Array(b1.length + b2.length);
737
1174
  r.set(b1);
738
1175
  r.set(b2, b1.length);
739
1176
  return r;
740
- };
1177
+ }
741
1178
  /**
742
- *
743
1179
  * @description Flatten a michelson json representation to an array
744
- *
745
1180
  * @param s michelson json
746
1181
  */
747
- const mic2arr = function me2(s) {
1182
+ function mic2arr(s) {
748
1183
  let ret = [];
749
1184
  if (Object.prototype.hasOwnProperty.call(s, 'prim')) {
750
1185
  if (s.prim === 'Pair') {
751
- ret.push(me2(s.args[0]));
752
- ret = ret.concat(me2(s.args[1]));
1186
+ ret.push(mic2arr(s.args[0]));
1187
+ ret = ret.concat(mic2arr(s.args[1]));
753
1188
  }
754
1189
  else if (s.prim === 'Elt') {
755
1190
  ret = {
756
- key: me2(s.args[0]),
757
- val: me2(s.args[1]),
1191
+ key: mic2arr(s.args[0]),
1192
+ val: mic2arr(s.args[1]),
758
1193
  };
759
1194
  }
760
1195
  else if (s.prim === 'True') {
@@ -767,7 +1202,7 @@ const mic2arr = function me2(s) {
767
1202
  else if (Array.isArray(s)) {
768
1203
  const sc = s.length;
769
1204
  for (let i = 0; i < sc; i++) {
770
- const n = me2(s[i]);
1205
+ const n = mic2arr(s[i]);
771
1206
  if (typeof n.key !== 'undefined') {
772
1207
  if (Array.isArray(ret)) {
773
1208
  ret = {
@@ -793,110 +1228,43 @@ const mic2arr = function me2(s) {
793
1228
  ret = s;
794
1229
  }
795
1230
  return ret;
796
- };
1231
+ }
797
1232
  /**
798
- *
799
1233
  * @description Convert a Uint8Array to an hex string
800
- *
801
1234
  * @param buffer Uint8Array to convert
802
1235
  */
803
- const buf2hex = (buffer) => {
804
- const hexParts = [];
805
- buffer.forEach((byte) => {
806
- const hex = byte.toString(16);
807
- const paddedHex = `00${hex}`.slice(-2);
808
- hexParts.push(paddedHex);
809
- });
810
- return hexParts.join('');
811
- };
812
- /**
813
- *
814
- * @description Gets Tezos address (PKH) from Public Key
815
- *
816
- * @param publicKey Public Key
817
- * @returns A string of the Tezos address (PKH) that was derived from the given Public Key
818
- */
819
- const getPkhfromPk = (publicKey) => {
820
- let encodingPrefix;
821
- let prefixLen;
822
- const keyPrefix = validatePkAndExtractPrefix(publicKey);
823
- const decoded = b58cdecode(publicKey, prefix[keyPrefix]);
824
- switch (keyPrefix) {
825
- case Prefix.EDPK:
826
- encodingPrefix = prefix[Prefix.TZ1];
827
- prefixLen = prefixLength[Prefix.TZ1];
828
- break;
829
- case Prefix.SPPK:
830
- encodingPrefix = prefix[Prefix.TZ2];
831
- prefixLen = prefixLength[Prefix.TZ2];
832
- break;
833
- case Prefix.P2PK:
834
- encodingPrefix = prefix[Prefix.TZ3];
835
- prefixLen = prefixLength[Prefix.TZ3];
836
- break;
837
- case Prefix.BLPK:
838
- encodingPrefix = prefix[Prefix.TZ4];
839
- prefixLen = prefixLength[Prefix.TZ4];
840
- }
841
- const hashed = hash(decoded, prefixLen);
842
- const result = b58cencode(hashed, encodingPrefix);
843
- return result;
844
- };
845
- /**
846
- *
847
- * @description Convert a string to bytes
848
- *
849
- * @param str String to convert
850
- * @deprecated use stringToBytes instead, same functionality with a more descriptive name
851
- */
852
- function char2Bytes(str) {
853
- return Buffer.from(str, 'utf8').toString('hex');
1236
+ function buf2hex(bytes) {
1237
+ return Array.from(bytes)
1238
+ .map((x) => ((x >> 4) & 0xf).toString(16) + (x & 0xf).toString(16))
1239
+ .join('');
854
1240
  }
855
1241
  /**
856
- *
857
1242
  * @description Convert a string to a byte string representation
858
- *
859
1243
  * @param str String to convert
860
1244
  */
861
1245
  function stringToBytes(str) {
862
1246
  return Buffer.from(str, 'utf8').toString('hex');
863
1247
  }
864
1248
  /**
865
- *
866
- * @description Convert bytes to a string
867
- *
868
- * @param str Bytes to convert
869
- * @deprecated use hexStringToBytes instead, same functionality with a more descriptive name
870
- */
871
- function bytes2Char(hex) {
872
- return Buffer.from(hex2buf(hex)).toString('utf8');
873
- }
874
- /**
875
- *
876
1249
  * @description Convert byte string representation to string
877
- *
878
- * @param str byte string to convert
1250
+ * @param hex byte string to convert
879
1251
  */
880
1252
  function bytesToString(hex) {
881
1253
  return Buffer.from(hex2buf(hex)).toString('utf8');
882
1254
  }
883
1255
  /**
884
- *
885
1256
  * @description Convert hex string/UintArray/Buffer to bytes
886
- *
887
1257
  * @param hex String value to convert to bytes
888
1258
  */
889
1259
  function hex2Bytes(hex) {
890
1260
  const hexDigits = stripHexPrefix(hex);
891
1261
  if (!hexDigits.match(/^(0x)?([\da-f]{2})*$/gi)) {
892
- throw new InvalidHexStringError(hex, `: Expecting even number of characters: 0-9, a-z, A-Z, optionally prefixed with 0x`);
1262
+ throw new InvalidHexStringError(hex, `Expecting even number of characters: 0-9, a-z, A-Z, optionally prefixed with 0x`);
893
1263
  }
894
1264
  return Buffer.from(hexDigits, 'hex');
895
1265
  }
896
1266
  /**
897
- *
898
1267
  * @description Converts a number or Bignumber to hexadecimal string
899
- *
900
1268
  * @param val The value that will be converted to a hexadecimal string value
901
1269
  */
902
1270
  function toHexBuf(val, bitLength = 8) {
@@ -906,7 +1274,6 @@ function numToHexBuffer(val, bitLength = 8) {
906
1274
  return Buffer.from(num2PaddedHex(val, bitLength), 'hex');
907
1275
  }
908
1276
  /**
909
- *
910
1277
  * @description Converts a number or BigNumber to a padded hexadecimal string
911
1278
  * @param val The value that will be converted into a padded hexadecimal string value
912
1279
  * @param bitLength The length of bits
@@ -948,6 +1315,113 @@ function padHexWithZero(hex, targetLength) {
948
1315
  function stripHexPrefix(hex) {
949
1316
  return hex.startsWith('0x') ? hex.slice(2) : hex;
950
1317
  }
1318
+ function splitAddress(addr) {
1319
+ const i = addr.indexOf('%');
1320
+ if (i >= 0) {
1321
+ return [addr.slice(0, i), addr.slice(i)];
1322
+ }
1323
+ else {
1324
+ return [addr, null];
1325
+ }
1326
+ }
1327
+ function compareArrays(a, b) {
1328
+ let i = 0;
1329
+ while (i < a.length && i < b.length && a[i] === b[i])
1330
+ i++;
1331
+ const aa = i < a.length ? a[i] : 0;
1332
+ const bb = i < b.length ? b[i] : 0;
1333
+ return aa < bb ? -1 : aa > bb ? 1 : 0;
1334
+ }
1335
+ /**
1336
+ * @deprecated use b58DecodeAndCheckPrefix instead, this function will be removed in the next minor release
1337
+ * @description Base58 decode a string and remove the prefix from it
1338
+ * @param enc Value to base58 decode
1339
+ * @param prefixArg prefix to remove from the decoded string
1340
+ */
1341
+ function b58cdecode(enc, prefixArg) {
1342
+ return bs58check.decode(enc).slice(prefixArg.length);
1343
+ }
1344
+ /**
1345
+ * @deprecated use b58Encode instead, this function will be removed in the next minor release
1346
+ * @description Base58 encode a string or a Uint8Array and append a prefix to it
1347
+ * @param value Value to base58 encode
1348
+ * @param prefix prefix to append to the encoded string
1349
+ */
1350
+ function b58cencode(value, prefix) {
1351
+ const payloadAr = typeof value === 'string' ? hex2buf(value) : value;
1352
+ const n = new Uint8Array(prefix.length + payloadAr.length);
1353
+ n.set(prefix);
1354
+ n.set(payloadAr, prefix.length);
1355
+ return bs58check.encode(toBuffer(n));
1356
+ }
1357
+ /**
1358
+ * @deprecated use b58DecodeAndCheckPrefix instead, this function will be removed in the next minor release
1359
+ * @description Base58 decode a string with predefined prefix
1360
+ * @param payload Value to base58 decode
1361
+ */
1362
+ function b58decode(payload) {
1363
+ const buf = bs58check.decode(payload);
1364
+ const prefixMap = {
1365
+ [prefix.tz1.toString()]: '0000',
1366
+ [prefix.tz2.toString()]: '0001',
1367
+ [prefix.tz3.toString()]: '0002',
1368
+ [prefix.tz4.toString()]: '0003',
1369
+ };
1370
+ const pref = prefixMap[new Uint8Array(buf.slice(0, 3)).toString()];
1371
+ if (pref) {
1372
+ // tz addresses
1373
+ const hex = buf2hex(buf.slice(3));
1374
+ return pref + hex;
1375
+ }
1376
+ else {
1377
+ // other (kt addresses)
1378
+ return '01' + buf2hex(buf.slice(3, 42)) + '00';
1379
+ }
1380
+ }
1381
+ /**
1382
+ * @deprecated use b58DecodeBlsAddress instead, this function will be removed in the next minor release
1383
+ * @description b58 decode a string without predefined prefix
1384
+ * @param payload Value to base58 decode
1385
+ * @returns string of bytes
1386
+ */
1387
+ function b58decodeL2Address(payload) {
1388
+ const buf = bs58check.decode(payload);
1389
+ // tz4 address currently
1390
+ return buf2hex(buf.slice(3, 42));
1391
+ }
1392
+ /**
1393
+ * @deprecated use encodeAddress instead, this function will be removed in the next minor release
1394
+ * @description Base58 encode an address using predefined prefix
1395
+ * @param value Address to base58 encode (tz1, tz2, tz3 or KT1)
1396
+ */
1397
+ function encodePubKey(value) {
1398
+ return encodeAddress(value);
1399
+ }
1400
+ /**
1401
+ * @deprecated use encodeBlsAddress instead, this function will be removed in the next minor release
1402
+ * @description Base58 encode an address without predefined prefix
1403
+ * @param value Address to base58 encode (tz4) hex dec
1404
+ * @returns return address
1405
+ */
1406
+ function encodeL2Address(value) {
1407
+ return b58cencode(value, prefix.tz4);
1408
+ }
1409
+ /**
1410
+ * @deprecated use stringToBytes instead, this function will be removed in the next minor release
1411
+ * @description Convert a string to bytes
1412
+ * @param str String to convert
1413
+ */
1414
+ function char2Bytes(str) {
1415
+ return Buffer.from(str, 'utf8').toString('hex');
1416
+ }
1417
+ /**
1418
+ * @deprecated use bytesToString instead, this function will be removed in the next minor release
1419
+ * @description Convert bytes to a string
1420
+ * @param hex Bytes to convert
1421
+ */
1422
+ function bytes2Char(hex) {
1423
+ return Buffer.from(hex2buf(hex)).toString('utf8');
1424
+ }
951
1425
 
952
- export { InvalidProtocolHashError, Prefix, VERSION, ValidationResult, ValueConversionError, b58cdecode, b58cencode, b58decode, b58decodeL2Address, buf2hex, bytes2Char, bytesToString, char2Bytes, encodeAddress, encodeExpr, encodeKey, encodeKeyHash, encodeL2Address, encodeOpHash, encodePubKey, format, getPkhfromPk, hex2Bytes, hex2buf, invalidDetail, isValidPrefix, mergebuf, mic2arr, num2PaddedHex, numToHexBuffer, prefix, prefixLength, stringToBytes, stripHexPrefix, toHexBuf, validateAddress, validateBlock, validateChain, validateContractAddress, validateKeyHash, validateOperation, validatePkAndExtractPrefix, validateProtocol, validatePublicKey, validateSignature, validateSmartRollupAddress, validateSpendingKey, verifySignature };
1426
+ export { BLS12_381_DST, InvalidProtocolHashError, POP_DST, Prefix, PrefixV2, VERSION, ValueConversionError, addressPrefixes, b58DecodeAddress, b58DecodeAndCheckPrefix, b58DecodeBlsAddress, b58DecodePublicKey, b58DecodePublicKeyHash, b58Encode, b58cdecode, b58cencode, b58decode, b58decodeL2Address, buf2hex, bytes2Char, bytesToString, char2Bytes, compareArrays, encodeAddress, encodeBlsAddress, encodeExpr, encodeKey, encodeKeyHash, encodeL2Address, encodeOpHash, encodePubKey, format, getPkhfromPk, hex2Bytes, hex2buf, invalidDetail, isValidPrefixedValue, mergebuf, mic2arr, num2PaddedHex, numToHexBuffer, payloadLength, prefix, prefixLength, publicKeyHashPrefixes, publicKeyPrefixes, signaturePrefixes, splitAddress, stringToBytes, stripHexPrefix, toHexBuf, validateAddress, validateBlock, validateChain, validateContractAddress, validateKeyHash, validateOperation, validatePkAndExtractPrefix, validateProtocol, validatePublicKey, validateSignature, validateSmartRollupAddress, validateSpendingKey, verifySignature };
953
1427
  //# sourceMappingURL=taquito-utils.es6.js.map