@leofcoin/codec-format-interface 1.5.3 → 1.6.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.
package/dist/index.js ADDED
@@ -0,0 +1,549 @@
1
+ import bs32 from '@vandeurenglenn/base32';
2
+ import base58 from '@vandeurenglenn/base58';
3
+ import proto from '@vandeurenglenn/proto-array';
4
+ import { fromBase58, fromHex, toHex, toBase32, toBase58 } from '@vandeurenglenn/typed-array-utils';
5
+ import { createKeccak } from 'hash-wasm';
6
+ import varint from 'varint';
7
+
8
+ /**
9
+ * @param {string}
10
+ */
11
+ var isHex = (function (string) { return /^[A-F0-9]+$/i.test(string); });
12
+
13
+ let BasicInterface$1 = class BasicInterface {
14
+ encoded;
15
+ decoded;
16
+ keys;
17
+ name;
18
+ // get Codec(): Codec {}
19
+ protoEncode(data) {
20
+ // check schema
21
+ return proto.encode(this.proto, data);
22
+ }
23
+ protoDecode(data) {
24
+ // check schema
25
+ return proto.decode(this.proto, data);
26
+ }
27
+ isHex(string) {
28
+ return isHex(string);
29
+ }
30
+ isBase32(string) {
31
+ return bs32.isBase32(string);
32
+ }
33
+ isBase58(string) {
34
+ return base58.isBase58(string);
35
+ }
36
+ fromBs32(encoded) {
37
+ this.encoded = bs32.decode(encoded);
38
+ return this.decode();
39
+ }
40
+ fromBs58(encoded) {
41
+ this.encoded = fromBase58(encoded);
42
+ return this.decode();
43
+ }
44
+ async toArray() {
45
+ const array = [];
46
+ for await (const value of this.encoded.values()) {
47
+ array.push(value);
48
+ }
49
+ return array;
50
+ }
51
+ fromString(string) {
52
+ const array = string.split(',');
53
+ const arrayLike = array.map(string => Number(string));
54
+ this.encoded = Uint8Array.from(arrayLike);
55
+ return this.decode();
56
+ }
57
+ fromHex(string) {
58
+ this.encoded = fromHex(string);
59
+ return this.decode();
60
+ }
61
+ fromArray(array) {
62
+ this.encoded = Uint8Array.from([...array]);
63
+ return this.decode();
64
+ }
65
+ fromEncoded(encoded) {
66
+ this.encoded = encoded;
67
+ return this.decode();
68
+ }
69
+ toString() {
70
+ if (!this.encoded)
71
+ this.encode();
72
+ return this.encoded.toString();
73
+ }
74
+ toHex() {
75
+ if (!this.encoded)
76
+ this.encode();
77
+ return toHex(this.encoded);
78
+ }
79
+ /**
80
+ * @return {String} encoded
81
+ */
82
+ toBs32() {
83
+ if (!this.encoded)
84
+ this.encode();
85
+ return toBase32(this.encoded);
86
+ }
87
+ /**
88
+ * @return {String} encoded
89
+ */
90
+ toBs58() {
91
+ if (!this.encoded)
92
+ this.encode();
93
+ return toBase58(this.encoded);
94
+ }
95
+ /**
96
+ * @param {Object} data
97
+ */
98
+ create(data) {
99
+ const decoded = {};
100
+ if (this.keys?.length > 0) {
101
+ for (const key of this.keys) {
102
+ Object.defineProperties(decoded, {
103
+ [key]: {
104
+ enumerable: true,
105
+ configurable: true,
106
+ set: (value) => data[key],
107
+ get: () => data[key]
108
+ }
109
+ });
110
+ }
111
+ this.decoded = decoded;
112
+ return this.encode();
113
+ }
114
+ }
115
+ };
116
+
117
+ var codecs = {
118
+ // just a hash
119
+ 'disco-hash': {
120
+ codec: parseInt('30', 16),
121
+ hashAlg: 'dbl-keccak-256', // ,
122
+ // testnet: 'olivia'
123
+ },
124
+ 'peernet-peer-response': {
125
+ codec: parseInt('707072', 16),
126
+ hashAlg: 'keccak-256',
127
+ },
128
+ 'peernet-peer': {
129
+ codec: parseInt('7070', 16),
130
+ hashAlg: 'keccak-256',
131
+ },
132
+ 'peernet-dht': {
133
+ codec: parseInt('706468', 16),
134
+ hashAlg: 'keccak-256',
135
+ },
136
+ 'peernet-dht-response': {
137
+ codec: parseInt('706472', 16),
138
+ hashAlg: 'keccak-256',
139
+ },
140
+ // data
141
+ 'peernet-data': {
142
+ codec: parseInt('706461', 16),
143
+ hashAlg: 'keccak-256',
144
+ },
145
+ 'peernet-data-response': {
146
+ codec: parseInt('70646172', 16),
147
+ hashAlg: 'keccak-256',
148
+ },
149
+ // message
150
+ 'peernet-message': {
151
+ codec: parseInt('706d65', 16),
152
+ hashAlg: 'keccak-256',
153
+ },
154
+ // pubsub
155
+ 'peernet-ps': {
156
+ codec: parseInt('707073', 16),
157
+ hashAlg: 'keccak-256',
158
+ },
159
+ 'peernet-response': {
160
+ codec: parseInt('7072', 16),
161
+ hashAlg: 'keccak-256',
162
+ },
163
+ 'peernet-request': {
164
+ codec: parseInt('707271', 16),
165
+ hashAlg: 'keccak-256',
166
+ },
167
+ // normal block
168
+ 'leofcoin-block': {
169
+ codec: parseInt('6c62', 16),
170
+ hashAlg: 'dbl-keccak-512', // ,
171
+ // testnet: 'olivia'
172
+ },
173
+ 'leofcoin-tx': {
174
+ codec: parseInt('6c74', 16),
175
+ hashAlg: 'dbl-keccak-512', // ,
176
+ // testnet: 'olivia'
177
+ },
178
+ // itx
179
+ 'leofcoin-itx': {
180
+ codec: parseInt('6c69', 16),
181
+ hashAlg: 'keccak-512', // ,
182
+ // testnet: 'olivia'
183
+ },
184
+ // peer reputation
185
+ 'leofcoin-pr': {
186
+ codec: parseInt('6c70', 16),
187
+ hashAlg: 'keccak-256', // ,
188
+ // testnet: 'olivia'
189
+ },
190
+ // chat message
191
+ 'chat-message': {
192
+ codec: parseInt('70636d', 16),
193
+ hashAlg: 'dbl-keccak-256',
194
+ },
195
+ 'peernet-file': {
196
+ codec: parseInt('7066', 16),
197
+ hashAlg: 'keccak-256',
198
+ },
199
+ 'peernet-file-response': {
200
+ codec: parseInt('706672', 16),
201
+ hashAlg: 'keccak-256',
202
+ }
203
+ };
204
+
205
+ var codecs$1 = /*#__PURE__*/Object.freeze({
206
+ __proto__: null,
207
+ default: codecs
208
+ });
209
+
210
+ let Codec$1 = class Codec extends BasicInterface$1 {
211
+ get codecs() {
212
+ return { ...globalThis.peernet.codecs, ...codecs };
213
+ }
214
+ constructor(buffer) {
215
+ super();
216
+ if (buffer) {
217
+ if (buffer instanceof Uint8Array) {
218
+ const codec = varint.decode(buffer);
219
+ const name = this.getCodecName(codec);
220
+ if (name) {
221
+ this.name = name;
222
+ this.encoded = buffer;
223
+ this.decode(buffer);
224
+ }
225
+ else {
226
+ this.encode(buffer);
227
+ }
228
+ }
229
+ else if (buffer instanceof ArrayBuffer) {
230
+ const encoded = new Uint8Array(buffer.byteLength);
231
+ for (let i = 0; i < buffer.byteLength; i++) {
232
+ encoded[i] = buffer[i];
233
+ }
234
+ this.encoded = encoded;
235
+ // this.encoded = new Uint8Array(buffer, buffer.byteOffset, buffer.byteLength)
236
+ this.decode(buffer);
237
+ return;
238
+ }
239
+ if (typeof buffer === 'string') {
240
+ if (this.codecs[buffer])
241
+ this.fromName(buffer);
242
+ else if (this.isHex(buffer))
243
+ this.fromHex(buffer);
244
+ else if (this.isBase32(buffer))
245
+ this.fromBs32(buffer);
246
+ else if (this.isBase58(buffer))
247
+ this.fromBs58(buffer);
248
+ else
249
+ throw new Error(`unsupported string ${buffer}`);
250
+ }
251
+ if (!isNaN(buffer))
252
+ if (this.codecs[this.getCodecName(buffer)])
253
+ this.fromCodec(buffer);
254
+ }
255
+ }
256
+ fromEncoded(encoded) {
257
+ const codec = varint.decode(encoded);
258
+ const name = this.getCodecName(codec);
259
+ this.name = name;
260
+ this.encoded = encoded;
261
+ this.decode(encoded);
262
+ }
263
+ getCodec(name) {
264
+ return this.codecs[name].codec;
265
+ }
266
+ getCodecName(codec) {
267
+ return Object.keys(this.codecs).reduce((p, c) => {
268
+ const item = this.codecs[c];
269
+ if (item.codec === codec)
270
+ return c;
271
+ else
272
+ return p;
273
+ }, undefined);
274
+ }
275
+ getHashAlg(name) {
276
+ return this.codecs[name].hashAlg;
277
+ }
278
+ fromCodec(codec) {
279
+ this.name = this.getCodecName(codec);
280
+ this.hashAlg = this.getHashAlg(this.name);
281
+ this.codec = this.getCodec(this.name);
282
+ this.codecBuffer = varint.encode(codec);
283
+ }
284
+ fromName(name) {
285
+ const codec = this.getCodec(name);
286
+ this.name = name;
287
+ this.codec = codec;
288
+ this.hashAlg = this.getHashAlg(name);
289
+ this.codecBuffer = varint.encode(codec);
290
+ }
291
+ decode() {
292
+ const codec = varint.decode(this.encoded);
293
+ this.fromCodec(codec);
294
+ }
295
+ encode() {
296
+ const codec = varint.encode(this.decoded);
297
+ this.encoded = codec;
298
+ return this.encoded;
299
+ }
300
+ };
301
+
302
+ let CodecHash$1 = class CodecHash extends BasicInterface$1 {
303
+ constructor(buffer, options = {}) {
304
+ super();
305
+ if (options.name)
306
+ this.name = options.name;
307
+ else
308
+ this.name = 'disco-hash';
309
+ if (options.codecs)
310
+ this.codecs = options.codecs;
311
+ return this.init(buffer);
312
+ }
313
+ async init(uint8Array) {
314
+ if (uint8Array) {
315
+ if (uint8Array instanceof Uint8Array) {
316
+ this.discoCodec = new Codec$1(uint8Array, this.codecs);
317
+ const name = this.discoCodec.name;
318
+ if (name) {
319
+ this.name = name;
320
+ this.decode(uint8Array);
321
+ }
322
+ else {
323
+ await this.encode(uint8Array);
324
+ }
325
+ }
326
+ if (typeof uint8Array === 'string') {
327
+ if (this.isHex(uint8Array))
328
+ await this.fromHex(uint8Array);
329
+ if (this.isBase32(uint8Array))
330
+ await this.fromBs32(uint8Array);
331
+ else if (this.isBase58(uint8Array))
332
+ await this.fromBs58(uint8Array);
333
+ else
334
+ throw new Error(`unsupported string ${uint8Array}`);
335
+ }
336
+ else if (typeof uint8Array === 'object')
337
+ await this.fromJSON(uint8Array);
338
+ }
339
+ return this;
340
+ }
341
+ get prefix() {
342
+ const length = this.length;
343
+ const uint8Array = new Uint8Array(length.length + this.discoCodec.codecBuffer.length);
344
+ uint8Array.set(length);
345
+ uint8Array.set(this.discoCodec.codecBuffer, length.length);
346
+ return uint8Array;
347
+ }
348
+ get length() {
349
+ return varint.encode(this.size);
350
+ }
351
+ get buffer() {
352
+ return this.encoded;
353
+ }
354
+ get hash() {
355
+ return this.encoded;
356
+ }
357
+ fromJSON(json) {
358
+ return this.encode(Buffer.from(JSON.stringify(json)));
359
+ }
360
+ async encode(buffer, name) {
361
+ if (!this.name && name)
362
+ this.name = name;
363
+ if (!buffer)
364
+ buffer = this.buffer;
365
+ this.discoCodec = new Codec$1(this.name, this.codecs);
366
+ this.discoCodec.fromName(this.name);
367
+ let hashAlg = this.discoCodec.hashAlg;
368
+ const hashVariant = Number(hashAlg.split('-')[hashAlg.split('-').length - 1]);
369
+ if (hashAlg.includes('dbl')) {
370
+ hashAlg = hashAlg.replace('dbl-', '');
371
+ const hasher = await createKeccak(hashVariant);
372
+ await hasher.init();
373
+ hasher.update(buffer);
374
+ buffer = hasher.digest('binary');
375
+ }
376
+ const hasher = await createKeccak(hashVariant);
377
+ await hasher.init();
378
+ hasher.update(buffer);
379
+ this.digest = hasher.digest('binary');
380
+ this.size = this.digest.length;
381
+ this.codec = this.discoCodec.encode();
382
+ this.codec = this.discoCodec.codecBuffer;
383
+ const uint8Array = new Uint8Array(this.digest.length + this.prefix.length);
384
+ uint8Array.set(this.prefix);
385
+ uint8Array.set(this.digest, this.prefix.length);
386
+ this.encoded = uint8Array;
387
+ return this.encoded;
388
+ }
389
+ async validate(buffer) {
390
+ if (Buffer.isBuffer(buffer)) {
391
+ const codec = varint.decode(buffer);
392
+ if (this.codecs[codec]) {
393
+ this.decode(buffer);
394
+ }
395
+ else {
396
+ await this.encode(buffer);
397
+ }
398
+ }
399
+ if (typeof buffer === 'string') {
400
+ if (this.isHex(buffer))
401
+ this.fromHex(buffer);
402
+ if (this.isBase32(buffer))
403
+ this.fromBs32(buffer);
404
+ }
405
+ if (typeof buffer === 'object')
406
+ this.fromJSON(buffer);
407
+ }
408
+ decode(buffer) {
409
+ this.encoded = buffer;
410
+ const codec = varint.decode(buffer);
411
+ this.discoCodec = new Codec$1(codec, this.codecs);
412
+ // TODO: validate codec
413
+ buffer = buffer.slice(varint.decode.bytes);
414
+ this.size = varint.decode(buffer);
415
+ this.digest = buffer.slice(varint.decode.bytes);
416
+ if (this.digest.length !== this.size) {
417
+ throw new Error(`hash length inconsistent: 0x${this.encoded.toString('hex')}`);
418
+ }
419
+ // const discoCodec = new Codec(codec, this.codecs)
420
+ this.name = this.discoCodec.name;
421
+ this.size = this.digest.length;
422
+ return {
423
+ codec: this.codec,
424
+ name: this.name,
425
+ size: this.size,
426
+ length: this.length,
427
+ digest: this.digest,
428
+ };
429
+ }
430
+ };
431
+
432
+ let FormatInterface$1 = class FormatInterface extends BasicInterface$1 {
433
+ set proto(value) {
434
+ this._proto = value;
435
+ this.keys = Object.keys(this._proto);
436
+ }
437
+ get proto() {
438
+ return this._proto;
439
+ }
440
+ init(buffer) {
441
+ if (buffer instanceof Uint8Array)
442
+ this.fromUint8Array(buffer);
443
+ else if (buffer instanceof ArrayBuffer)
444
+ this.fromArrayBuffer(buffer);
445
+ else if (buffer?.name === this.name)
446
+ return buffer;
447
+ else if (buffer instanceof String) {
448
+ if (this.isHex(buffer))
449
+ this.fromHex(buffer);
450
+ else if (this.isBase58(buffer))
451
+ this.fromBs58(buffer);
452
+ else if (this.isBase32(buffer))
453
+ this.fromBs32(buffer);
454
+ else
455
+ throw new Error(`unsupported ${buffer}`);
456
+ }
457
+ else {
458
+ this.create(buffer);
459
+ }
460
+ return this;
461
+ }
462
+ hasCodec() {
463
+ if (!this.encoded)
464
+ return false;
465
+ const codec = new Codec$1(this.encoded);
466
+ if (codec.name)
467
+ return true;
468
+ }
469
+ decode() {
470
+ let encoded = this.encoded;
471
+ const codec = new Codec$1(this.encoded);
472
+ if (codec.codecBuffer) {
473
+ encoded = encoded.slice(codec.codecBuffer.length);
474
+ this.name = codec.name;
475
+ this.decoded = this.protoDecode(encoded);
476
+ try {
477
+ this.decoded = JSON.parse(this.decoded);
478
+ }
479
+ catch {
480
+ }
481
+ }
482
+ else {
483
+ throw new Error(`no codec found`);
484
+ }
485
+ return this.decoded;
486
+ }
487
+ encode(decoded) {
488
+ let encoded;
489
+ if (!decoded)
490
+ decoded = this.decoded;
491
+ const codec = new Codec$1(this.name);
492
+ if (decoded instanceof Uint8Array)
493
+ encoded = decoded;
494
+ else
495
+ encoded = this.protoEncode(decoded);
496
+ if (codec.codecBuffer) {
497
+ const uint8Array = new Uint8Array(encoded.length + codec.codecBuffer.length);
498
+ uint8Array.set(codec.codecBuffer);
499
+ uint8Array.set(encoded, codec.codecBuffer.length);
500
+ this.encoded = uint8Array;
501
+ }
502
+ else {
503
+ throw new Error(`invalid codec`);
504
+ }
505
+ return this.encoded;
506
+ }
507
+ /**
508
+ * @param {Buffer|String|Object} buffer - data - The data needed to create the desired message
509
+ * @param {Object} proto - {protoObject}
510
+ * @param {Object} options - {hashFormat, name}
511
+ */
512
+ constructor(buffer, proto, options = {}) {
513
+ super();
514
+ this.proto = proto;
515
+ this.hashFormat = options.hashFormat || 'bs32';
516
+ if (options.name)
517
+ this.name = options.name;
518
+ this.init(buffer);
519
+ }
520
+ /**
521
+ * @return {PeernetHash}
522
+ */
523
+ get peernetHash() {
524
+ return new CodecHash$1(this.decoded, { name: this.name });
525
+ }
526
+ /**
527
+ * @return {peernetHash}
528
+ */
529
+ async hash() {
530
+ const upper = this.hashFormat.charAt(0).toUpperCase();
531
+ const format = `${upper}${this.hashFormat.substring(1, this.hashFormat.length)}`;
532
+ return (await this.peernetHash)[`to${format}`]();
533
+ }
534
+ fromUint8Array(buffer) {
535
+ this.encoded = buffer;
536
+ return this.hasCodec() ? this.decode() : this.create(JSON.parse(new TextDecoder().decode(this.encoded)));
537
+ }
538
+ fromArrayBuffer(buffer) {
539
+ this.encoded = new Uint8Array(buffer, buffer.byteOffset, buffer.byteLength);
540
+ return this.hasCodec() ? this.decode() : this.create(JSON.parse(new TextDecoder().decode(this.encoded)));
541
+ }
542
+ };
543
+
544
+ const BasicInterface = BasicInterface$1;
545
+ const FormatInterface = FormatInterface$1;
546
+ const CodecHash = CodecHash$1;
547
+ const Codec = Codec$1;
548
+
549
+ export { BasicInterface, Codec, CodecHash, FormatInterface, codecs$1 as codecs };
package/package.json CHANGED
@@ -1,11 +1,14 @@
1
1
  {
2
2
  "name": "@leofcoin/codec-format-interface",
3
- "version": "1.5.3",
3
+ "version": "1.6.1",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": "./dist/index.js"
8
8
  },
9
+ "files": [
10
+ "dist"
11
+ ],
9
12
  "typings": "dist/index.d.ts",
10
13
  "scripts": {
11
14
  "test": "echo \"Error: no test specified\" && exit 1",
package/.gitattributes DELETED
@@ -1,2 +0,0 @@
1
- # Auto detect text files and perform LF normalization
2
- * text=auto
package/rollup.config.js DELETED
@@ -1,13 +0,0 @@
1
- import typescript from '@rollup/plugin-typescript'
2
- import tsConfig from './tsconfig.json' assert { type: 'json' }
3
-
4
- export default [{
5
- input: ['src/index.ts'],
6
- output: [{
7
- file: 'dist/index.js',
8
- format: 'es'
9
- }],
10
- plugins: [
11
- typescript(tsConfig)
12
- ]
13
- }]
@@ -1,123 +0,0 @@
1
- import bs32 from '@vandeurenglenn/base32';
2
- import base58 from '@vandeurenglenn/base58';
3
- import isHex from '@vandeurenglenn/is-hex';
4
- import proto from '@vandeurenglenn/proto-array'
5
- import { fromBase32, fromBase58, fromString, fromHex, fromArrayLike, fromUintArrayString, toBase32, toBase58, toHex } from '@vandeurenglenn/typed-array-utils'
6
-
7
-
8
- export default class BasicInterface {
9
- encoded: Uint8Array;
10
- decoded: object | string;
11
- keys: string[]
12
- name: string
13
- // get Codec(): Codec {}
14
-
15
- protoEncode(data: object): Uint8Array {
16
- // check schema
17
-
18
- return proto.encode(this.proto, data)
19
- }
20
-
21
- protoDecode(data: Uint8Array): object {
22
- // check schema
23
- return proto.decode(this.proto, data)
24
- }
25
-
26
- isHex(string: any) {
27
- return isHex(string)
28
- }
29
- isBase32(string: any) {
30
- return bs32.isBase32(string)
31
- }
32
- isBase58(string: any) {
33
- return base58.isBase58(string)
34
- }
35
-
36
- fromBs32(encoded: base58String): object {
37
- this.encoded = bs32.decode(encoded)
38
- return this.decode()
39
- }
40
-
41
-
42
- fromBs58(encoded: any): object {
43
- this.encoded = fromBase58(encoded)
44
- return this.decode()
45
- }
46
-
47
- async toArray() {
48
- const array: number[] = []
49
- for await (const value of this.encoded.values()) {
50
- array.push(value)
51
- }
52
- return array
53
- }
54
-
55
- fromString(string: string): object {
56
- const array: string[] = string.split(',')
57
- const arrayLike = array.map(string => Number(string))
58
- this.encoded = Uint8Array.from(arrayLike)
59
- return this.decode()
60
- }
61
-
62
- fromHex(string) {
63
- this.encoded = fromHex(string)
64
- return this.decode()
65
- }
66
-
67
- fromArray(array: number[]): object {
68
- this.encoded = Uint8Array.from([...array])
69
- return this.decode()
70
- }
71
-
72
- fromEncoded(encoded: Uint8Array) {
73
- this.encoded = encoded
74
- return this.decode()
75
- }
76
-
77
- toString(): string {
78
- if (!this.encoded) this.encode()
79
- return this.encoded.toString()
80
- }
81
-
82
- toHex() {
83
- if (!this.encoded) this.encode()
84
- return toHex(this.encoded)
85
- }
86
-
87
- /**
88
- * @return {String} encoded
89
- */
90
- toBs32() {
91
- if (!this.encoded) this.encode()
92
- return toBase32(this.encoded)
93
- }
94
-
95
- /**
96
- * @return {String} encoded
97
- */
98
- toBs58() {
99
- if (!this.encoded) this.encode()
100
- return toBase58(this.encoded)
101
- }
102
-
103
- /**
104
- * @param {Object} data
105
- */
106
- create(data: object) {
107
- const decoded = {}
108
- if (this.keys?.length > 0) {
109
- for (const key of this.keys) {
110
- Object.defineProperties(decoded, {
111
- [key]: {
112
- enumerable: true,
113
- configurable: true,
114
- set: (value) => value = data[key],
115
- get: () => data[key]
116
- }
117
- })
118
- }
119
- this.decoded = decoded
120
- return this.encode()
121
- }
122
- }
123
- }