@leofcoin/chain 1.0.4 → 1.0.7

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