@leofcoin/messages 1.0.3 → 1.1.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.
package/dist/messages.js CHANGED
@@ -1,567 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var protons = require('protons');
4
- var bs32 = require('@vandeurenglenn/base32');
5
- var bs58 = require('@vandeurenglenn/base58');
6
- var isHex = require('@vandeurenglenn/is-hex');
7
- var varint = require('varint');
8
- var createKeccakHash = require('keccak');
3
+ Object.defineProperty(exports, '__esModule', { value: true });
9
4
 
10
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
5
+ var codecFormatInterface = require('@leofcoin/codec-format-interface');
11
6
 
12
- var protons__default = /*#__PURE__*/_interopDefaultLegacy(protons);
13
- var bs32__default = /*#__PURE__*/_interopDefaultLegacy(bs32);
14
- var bs58__default = /*#__PURE__*/_interopDefaultLegacy(bs58);
15
- var isHex__default = /*#__PURE__*/_interopDefaultLegacy(isHex);
16
- var varint__default = /*#__PURE__*/_interopDefaultLegacy(varint);
17
- var createKeccakHash__default = /*#__PURE__*/_interopDefaultLegacy(createKeccakHash);
18
-
19
- var proto$4 = `
20
- message ContractMessage {
21
- required string creator = 1;
22
- required bytes contract = 2;
23
- repeated string constructorParameters = 3;
24
- }
25
- `;
26
-
27
- class BasicInterface {
28
- #handleDecode() {
29
- if (!this.decode) throw new Error('bad implementation: needs decode func')
30
- this.decode();
31
- }
32
-
33
- #handleEncode() {
34
- if (!this.encode) throw new Error('bad implementation: needs encode func')
35
- this.encode();
36
- }
37
- isHex(string) {
38
- return isHex__default['default'](string)
39
- }
40
- isBase32(string) {
41
- return base32.isBase32(string)
42
- }
43
- isBase58(string) {
44
- return base58.isBase32(string)
45
- }
46
- /**
47
- * @param {String} encoded
48
- */
49
- fromBs32(encoded) {
50
- this.encoded = bs32__default['default'].decode(encoded);
51
- return this.#handleDecode()
52
- }
53
-
54
- /**
55
- * @param {String} encoded
56
- */
57
- fromBs58(encoded) {
58
- this.encoded = bs58__default['default'].decode(encoded);
59
- return this.#handleDecode()
60
- }
61
-
62
- async toArray() {
63
- const array = [];
64
- for await (const value of this.encoded.values()) {
65
- array.push(value);
66
- }
67
- return array
68
- }
69
-
70
- fromString(string) {
71
- this.encoded = new Uint8Array(string.split(','));
72
- return this.#handleDecode()
73
- }
74
-
75
- fromArray(array) {
76
- this.encoded = new Uint8Array([...array]);
77
- return this.#handleDecode()
78
- }
79
-
80
- /**
81
- * @param {Buffer} encoded
82
- */
83
- fromEncoded(encoded) {
84
- this.encoded = encoded;
85
- return this.#handleDecode()
86
- }
87
-
88
- /**
89
- * @param {String} encoded
90
- */
91
- fromHex(encoded) {
92
- this.encoded = Buffer.from(encoded, 'hex');
93
- return this.#handleDecode()
94
- }
95
-
96
- toString(encoding = 'utf8') {
97
- if (!this.encoded) this.#handleEncode();
98
- return this.encoded.toString(encoding)
99
- }
100
-
101
- /**
102
- * @return {String} encoded
103
- */
104
- toHex() {
105
- return this.toString('hex')
106
- }
107
-
108
- /**
109
- * @return {String} encoded
110
- */
111
- toBs32() {
112
- if (!this.encoded) this.#handleEncode();
113
- return bs32__default['default'].encode(this.encoded)
114
- }
115
-
116
- /**
117
- * @return {String} encoded
118
- */
119
- toBs58() {
120
- if (!this.encoded) this.#handleEncode();
121
- return bs58__default['default'].encode(this.encoded)
122
- }
123
-
124
- /**
125
- * @param {Object} data
126
- */
127
- create(data) {
128
- const decoded = {};
129
- if (this.keys?.length > 0) {
130
- for (const key of this.keys) {
131
- Object.defineProperties(decoded, {
132
- [key]: {
133
- enumerable: true,
134
- configurable: true,
135
- set: (val) => value = data[key],
136
- get: () => data[key]
137
- }
138
- });
139
- }
140
-
141
- this.decoded = decoded;
142
- this.encode();
143
- }
144
- }
145
- }
146
-
147
- var codecs = {
148
- // just a hash
149
- 'disco-hash': {
150
- codec: parseInt('30', 16),
151
- hashAlg: 'dbl-keccak-256', // ,
152
- // testnet: 'olivia'
153
- },
154
- 'peernet-peer-response': {
155
- codec: parseInt('707072', 16),
156
- hashAlg: 'keccak-256',
157
- },
158
- 'peernet-peer': {
159
- codec: parseInt('7070', 16),
160
- hashAlg: 'keccak-256',
161
- },
162
- 'peernet-dht': {
163
- codec: parseInt('706468', 16),
164
- hashAlg: 'keccak-256',
165
- },
166
- 'peernet-dht-response': {
167
- codec: parseInt('706472', 16),
168
- hashAlg: 'keccak-256',
169
- },
170
- // data
171
- 'peernet-data': {
172
- codec: parseInt('706461', 16),
173
- hashAlg: 'keccak-256',
174
- },
175
- 'peernet-data-response': {
176
- codec: parseInt('70646172', 16),
177
- hashAlg: 'keccak-256',
178
- },
179
- // message
180
- 'peernet-message': {
181
- codec: parseInt('706d65', 16),
182
- hashAlg: 'keccak-256',
183
- },
184
- // pubsub
185
- 'peernet-ps': {
186
- codec: parseInt('707073', 16),
187
- hashAlg: 'keccak-256',
188
- },
189
- 'peernet-response': {
190
- codec: parseInt('7072', 16),
191
- hashAlg: 'keccak-256',
192
- },
193
- 'peernet-request': {
194
- codec: parseInt('707271', 16),
195
- hashAlg: 'keccak-256',
196
- },
197
- // normal block
198
- 'leofcoin-block': {
199
- codec: parseInt('6c62', 16),
200
- hashAlg: 'dbl-keccak-512', // ,
201
- // testnet: 'olivia'
202
- },
203
- 'leofcoin-tx': {
204
- codec: parseInt('6c74', 16),
205
- hashAlg: 'dbl-keccak-512', // ,
206
- // testnet: 'olivia'
207
- },
208
- // itx
209
- 'leofcoin-itx': {
210
- codec: parseInt('6c69', 16),
211
- hashAlg: 'keccak-512', // ,
212
- // testnet: 'olivia'
213
- },
214
- // peer reputation
215
- 'leofcoin-pr': {
216
- codec: parseInt('6c70', 16),
217
- hashAlg: 'keccak-256', // ,
218
- // testnet: 'olivia'
219
- },
220
- // chat message
221
- 'chat-message': {
222
- codec: parseInt('636d', 16),
223
- hashAlg: 'dbl-keccak-256',
224
- },
225
- };
226
-
227
- class PeernetCodec extends BasicInterface {
228
- get codecs() {
229
- return {...globalThis.peernet.codecs, ...codecs}
230
- }
231
- constructor(buffer) {
232
- super();
233
- if (buffer) {
234
- if (buffer instanceof Uint8Array) {
235
- const codec = varint__default['default'].decode(buffer);
236
- const name = this.getCodecName(codec);
237
- if (name) {
238
- this.name = name;
239
- this.encoded = buffer;
240
- this.decode(buffer);
241
- } else {
242
- this.encode(buffer);
243
- }
244
- } else if (buffer instanceof ArrayBuffer) {
245
- const encoded = new Uint8Array(buffer.byteLength);
246
-
247
- for (let i = 0; i < buffer.byteLength; i++) {
248
- encoded[i] = buffer[i];
249
- }
250
- this.encoded = encoded;
251
- // this.encoded = new Uint8Array(buffer, buffer.byteOffset, buffer.byteLength)
252
- this.decode(buffer);
253
- return
254
- }
255
- if (typeof buffer === 'string') {
256
- if (this.codecs[buffer]) this.fromName(buffer);
257
- else if (this.isHex(buffer)) this.fromHex(buffer);
258
- else if (this.isBase32(buffer)) this.fromBs32(buffer);
259
- else if (this.isBase58(buffer)) this.fromBs58(buffer);
260
- else throw new Error(`unsupported string ${buffer}`)
261
- }
262
- if (!isNaN(buffer)) if (this.codecs[this.getCodecName(buffer)]) this.fromCodec(buffer);
263
- }
264
- }
265
-
266
- fromEncoded(encoded) {
267
- const codec = varint__default['default'].decode(encoded);
268
- const name = this.getCodecName(codec);
269
- this.name = name;
270
- this.encoded = encoded;
271
- this.decode(encoded);
272
- }
273
-
274
- getCodec(name) {
275
- return this.codecs[name].codec
276
- }
277
-
278
- getCodecName(codec) {
279
- return Object.keys(this.codecs).reduce((p, c) => {
280
- const item = this.codecs[c];
281
- if (item.codec === codec) return c;
282
- else return p;
283
- }, undefined)
284
- }
285
-
286
- getHashAlg(name) {
287
- return this.codecs[name].hashAlg
288
- }
289
-
290
- fromCodec(codec) {
291
- this.name = this.getCodecName(codec);
292
- this.hashAlg = this.getHashAlg(this.name);
293
-
294
- this.codec = this.getCodec(this.name);
295
- this.codecBuffer = varint__default['default'].encode(codec);
296
- }
297
-
298
- fromName(name) {
299
- const codec = this.getCodec(name);
300
- this.name = name;
301
- this.codec = codec;
302
- this.hashAlg = this.getHashAlg(name);
303
- this.codecBuffer = varint__default['default'].encode(codec);
304
- }
305
-
306
- decode() {
307
- const codec = varint__default['default'].decode(this.encoded);
308
- this.fromCodec(codec);
309
- }
310
-
311
- encode() {
312
- const codec = varint__default['default'].encode(this.decoded);
313
- this.encoded = codec;
314
- return this.encoded
315
- }
316
- }
317
-
318
- class CodecHash extends BasicInterface {
319
- constructor(buffer, options = {}) {
320
- super();
321
- if (options.name) this.name = options.name;
322
- else this.name = 'disco-hash';
323
- if (options.codecs) this.codecs = options.codecs;
324
- if (buffer) {
325
- if (buffer instanceof Uint8Array) {
326
- this.discoCodec = new PeernetCodec(buffer, this.codecs);
327
- const name = this.discoCodec.name;
328
-
329
- if (name) {
330
- this.name = name;
331
- this.decode(buffer);
332
- } else {
333
- this.encode(buffer);
334
- }
335
- }
336
-
337
- if (typeof buffer === 'string') {
338
- if (this.isHex(buffer)) this.fromHex(buffer);
339
- if (this.isBase32(buffer)) this.fromBs32(buffer);
340
- else if (this.isBase58(buffer)) this.fromBs58(buffer);
341
- else throw new Error(`unsupported string ${buffer}`)
342
- } else if (typeof buffer === 'object') this.fromJSON(buffer);
343
- }
344
- }
345
-
346
- get prefix() {
347
- const length = this.length;
348
- const uint8Array = new Uint8Array(length.length + this.discoCodec.codecBuffer.length);
349
- uint8Array.set(length);
350
- uint8Array.set(this.discoCodec.codecBuffer, length.length);
351
-
352
- return uint8Array
353
- }
354
-
355
- get length() {
356
- return varint__default['default'].encode(this.size)
357
- }
358
-
359
- get buffer() {
360
- return this.encoded
361
- }
362
-
363
- get hash() {
364
- return this.encoded
365
- }
366
-
367
- fromJSON(json) {
368
- return this.encode(Buffer.from(JSON.stringify(json)))
369
- }
370
-
371
- encode(buffer, name) {
372
- if (!this.name && name) this.name = name;
373
- if (!buffer) buffer = this.buffer;
374
- this.discoCodec = new PeernetCodec(this.name, this.codecs);
375
- this.discoCodec.fromName(this.name);
376
- let hashAlg = this.discoCodec.hashAlg;
377
- if (hashAlg.includes('dbl')) {
378
- hashAlg = hashAlg.replace('dbl-', '');
379
- buffer = createKeccakHash__default['default'](hashAlg.replace('-', '')).update(buffer).digest();
380
- }
381
- this.digest = createKeccakHash__default['default'](hashAlg.replace('-', '')).update(buffer).digest();
382
- this.size = this.digest.length;
383
-
384
- this.codec = this.discoCodec.encode();
385
- this.codec = this.discoCodec.codecBuffer;
386
- const uint8Array = new Uint8Array(this.digest.length + this.prefix.length);
387
- uint8Array.set(this.prefix);
388
- uint8Array.set(this.digest, this.prefix.length);
389
-
390
- this.encoded = uint8Array;
391
-
392
- return this.encoded
393
- }
394
-
395
- validate(buffer) {
396
- if (Buffer.isBuffer(buffer)) {
397
- const codec = varint__default['default'].decode(buffer);
398
- if (this.codecs[codec]) {
399
- this.decode(buffer);
400
- } else {
401
- this.encode(buffer);
402
- }
403
- }
404
- if (typeof buffer === 'string') {
405
- if (this.isHex(buffer)) this.fromHex(buffer);
406
- if (this.isBase32(buffer)) this.fromBs32(buffer);
407
- }
408
- if (typeof buffer === 'object') this.fromJSON(buffer);
409
- }
410
-
411
- decode(buffer) {
412
- this.encoded = buffer;
413
- const codec = varint__default['default'].decode(buffer);
414
-
415
- this.discoCodec = new PeernetCodec(codec, this.codecs);
416
- // TODO: validate codec
417
- buffer = buffer.slice(varint__default['default'].decode.bytes);
418
- this.size = varint__default['default'].decode(buffer);
419
- this.digest = buffer.slice(varint__default['default'].decode.bytes);
420
- if (this.digest.length !== this.size) {
421
- throw new Error(`hash length inconsistent: 0x${this.encoded.toString('hex')}`)
422
- }
423
-
424
- // const discoCodec = new Codec(codec, this.codecs)
425
-
426
- this.name = this.discoCodec.name;
427
-
428
-
429
- this.size = this.digest.length;
430
-
431
- return {
432
- codec: this.codec,
433
- name: this.name,
434
- size: this.size,
435
- length: this.length,
436
- digest: this.digest,
437
- }
438
- }
439
- }
440
-
441
- class FormatInterface extends BasicInterface {
442
- /**
443
- * @param {Buffer|String|Object} buffer - data - The data needed to create the desired message
444
- * @param {Object} proto - {encode, decode}
445
- * @param {Object} options - {hashFormat, name}
446
- */
447
- constructor(buffer, proto, options = {}) {
448
- super();
449
- this.protoEncode = proto.encode;
450
- this.protoDecode = proto.decode;
451
- this.hashFormat = options.hashFormat || 'bs32';
452
- if (options.name) this.name = options.name;
453
- if (buffer instanceof Uint8Array) this.fromUint8Array(buffer);
454
- else if (buffer instanceof ArrayBuffer) this.fromArrayBuffer(buffer);
455
- else if (buffer.name === options.name) return buffer
456
- else if (buffer instanceof String) {
457
- if (this.isHex(buffer)) this.fromHex(buffer);
458
- else if (this.isBase32(buffer)) this.fromBs32(buffer);
459
- else if (this.isBase58(buffer)) this.fromBs58(buffer);
460
- else throw new Error(`unsupported string ${buffer}`)
461
- } else {
462
- this.create(buffer);
463
- }
464
- }
465
-
466
- /**
467
- * @return {PeernetHash}
468
- */
469
- get peernetHash() {
470
- return new CodecHash(this.decoded, {name: this.name})
471
- }
472
-
473
- /**
474
- * @return {peernetHash}
475
- */
476
- get hash() {
477
- const upper = this.hashFormat.charAt(0).toUpperCase();
478
- const format = `${upper}${this.hashFormat.substring(1, this.hashFormat.length)}`;
479
- return this.peernetHash[`to${format}`]()
480
- }
481
-
482
- /**
483
- * @return {Object}
484
- */
485
- decode() {
486
- let encoded = this.encoded;
487
- const discoCodec = new PeernetCodec(this.encoded);
488
- encoded = encoded.slice(discoCodec.codecBuffer.length);
489
- this.name = discoCodec.name;
490
- this.decoded = this.protoDecode(encoded);
491
- return this.decoded
492
- }
493
-
494
- /**
495
- * @return {Buffer}
496
- */
497
- encode(decoded) {
498
- if (!decoded) decoded = this.decoded;
499
- const codec = new PeernetCodec(this.name);
500
- const encoded = this.protoEncode(decoded);
501
- const uint8Array = new Uint8Array(encoded.length + codec.codecBuffer.length);
502
- uint8Array.set(codec.codecBuffer);
503
- uint8Array.set(encoded, codec.codecBuffer.length);
504
- this.encoded = uint8Array;
505
- return this.encoded
506
- }
507
-
508
- hasCodec() {
509
- if (!this.encoded) return false
510
- const codec = new PeernetCodec(this.encoded);
511
- if (codec.name) return true
512
- }
513
-
514
- fromUint8Array(buffer) {
515
- this.encoded = buffer;
516
- if (!this.hasCodec()) this.create(
517
- JSON.parse(new TextDecoder().decode(this.encoded))
518
- );
519
- else this.decode();
520
- }
521
-
522
- fromArrayBuffer(buffer) {
523
- this.encoded = new Uint8Array(buffer, buffer.byteOffset, buffer.byteLength);
524
- if (!this.hasCodec()) this.create(
525
- JSON.parse(new TextDecoder().decode(this.encoded))
526
- );
527
- else this.decode();
528
- }
529
- }
530
-
531
- class ContractMessage extends FormatInterface {
532
- get keys() {
533
- return ['creator', 'contract', 'constructorParameters']
534
- }
535
-
536
- constructor(buffer) {
537
- super(buffer, protons__default['default'](proto$4).ContractMessage, {name: 'contract-message'});
538
- }
539
- }
540
-
541
- var proto$3 = `
542
-
543
- message TransactionMessage {
544
- required uint64 timestamp = 1;
545
- required string from = 2;
546
- required string to = 3;
547
- required uint64 nonce = 4;
548
- required string method = 5;
549
- repeated string params = 6;
550
- }
551
- `;
552
-
553
- class TransactionMessage extends FormatInterface {
554
- get keys() {
555
- return ['timestamp', 'from', 'to', 'nonce', 'method', 'params']
556
- }
557
-
558
- constructor(buffer) {
559
- const name = 'transaction-message';
560
- super(buffer, protons__default['default'](proto$3).TransactionMessage, {name});
561
- }
562
- }
563
-
564
- var proto$2 = `
7
+ var proto = `
565
8
  message ValidatorMessage {
566
9
  required string address = 1;
567
10
  required string reward = 2;
@@ -588,59 +31,107 @@ message BlockMessage {
588
31
  }
589
32
  `;
590
33
 
591
- class BlockMessage extends FormatInterface {
34
+ class ContractMessage extends codecFormatInterface.FormatInterface {
35
+ get keys() {
36
+ return ['creator', 'contract', 'constructorParameters']
37
+ }
38
+
39
+ get messageName() {
40
+ return 'ContractMessage'
41
+ }
42
+
43
+ constructor(buffer) {
44
+ super(buffer, proto, {name: 'contract-message'});
45
+ }
46
+ }
47
+
48
+ var contract = /*#__PURE__*/Object.freeze({
49
+ __proto__: null,
50
+ 'default': ContractMessage
51
+ });
52
+
53
+ class TransactionMessage extends codecFormatInterface.FormatInterface {
54
+ get keys() {
55
+ return ['timestamp', 'from', 'to', 'nonce', 'method', 'params']
56
+ }
57
+
58
+ get messageName() {
59
+ return 'TransactionMessage'
60
+ }
61
+
62
+ constructor(buffer) {
63
+ const name = 'transaction-message';
64
+ super(buffer, proto, {name});
65
+ }
66
+ }
67
+
68
+ var transaction = /*#__PURE__*/Object.freeze({
69
+ __proto__: null,
70
+ 'default': TransactionMessage
71
+ });
72
+
73
+ class BlockMessage extends codecFormatInterface.FormatInterface {
592
74
  get keys() {
593
75
  return ['index', 'previousHash', 'timestamp', 'reward', 'fees', 'transactions', 'validators']
594
76
  }
595
77
 
78
+ get messageName() {
79
+ return 'BlockMessage'
80
+ }
81
+
596
82
  constructor(buffer) {
597
83
  const name = 'block-message';
598
- super(buffer, protons__default['default'](proto$2).BlockMessage, {name});
84
+ super(buffer, proto, {name});
599
85
  }
600
86
  }
601
87
 
602
- var proto$1 = `
603
-
604
- message BWMessage {
605
- required uint64 up = 1;
606
- required uint64 down = 2;
607
- }
608
- `;
88
+ var block = /*#__PURE__*/Object.freeze({
89
+ __proto__: null,
90
+ 'default': BlockMessage
91
+ });
609
92
 
610
- class BWMessage extends FormatInterface {
93
+ class BWMessage extends codecFormatInterface.FormatInterface {
611
94
  get keys() {
612
95
  return ['up', 'down']
613
96
  }
614
97
 
98
+ get messageName() {
99
+ return 'BWMessage'
100
+ }
101
+
615
102
  constructor(buffer) {
616
103
  const name = 'bw-message';
617
- super(buffer, protons__default['default'](proto$1).BWMessage, {name});
104
+ super(buffer, proto, {name});
618
105
  }
619
106
  }
620
107
 
621
- var proto = `
622
-
623
- message BWRequestMessage {
624
- }
625
- `;
108
+ var bw = /*#__PURE__*/Object.freeze({
109
+ __proto__: null,
110
+ 'default': BWMessage
111
+ });
626
112
 
627
- class BWRequestMessage extends FormatInterface {
113
+ class BWRequestMessage extends codecFormatInterface.FormatInterface {
628
114
  get keys() {
629
115
  return []
630
116
  }
631
117
 
118
+ get messageName() {
119
+ return 'BWRequestMessage'
120
+ }
121
+
632
122
  constructor(buffer) {
633
123
  const name = 'bw-request-message';
634
- super(buffer, protons__default['default'](proto).BWRequestMessage, {name});
124
+ super(buffer, proto, {name});
635
125
  }
636
126
  }
637
127
 
638
- var messages = {
639
- ContractMessage,
640
- TransactionMessage,
641
- BlockMessage,
642
- BWMessage,
643
- BWRequestMessage
644
- };
128
+ var bwRequest = /*#__PURE__*/Object.freeze({
129
+ __proto__: null,
130
+ 'default': BWRequestMessage
131
+ });
645
132
 
646
- module.exports = messages;
133
+ exports.BWMessage = bw;
134
+ exports.BWRequestMessage = bwRequest;
135
+ exports.BlockMessage = block;
136
+ exports.ContractMessage = contract;
137
+ exports.TransactionMessage = transaction;