@leofcoin/chain 1.4.21 → 1.4.22

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.
Files changed (78) hide show
  1. package/CHANGELOG.md +14 -14
  2. package/LICENSE +88 -88
  3. package/README.md +4 -4
  4. package/demo/index.html +25 -25
  5. package/examples/contracts/token.js +7 -7
  6. package/package.json +71 -75
  7. package/plugins/bundle.js +18 -18
  8. package/src/{chain.ts → chain.js} +716 -710
  9. package/src/config/config.js +14 -14
  10. package/src/config/main.js +4 -4
  11. package/src/config/protocol.js +5 -5
  12. package/src/contract.js +51 -51
  13. package/src/fee/config.js +3 -3
  14. package/src/machine.js +215 -215
  15. package/src/{node.ts → node.js} +24 -24
  16. package/src/protocol.js +3 -3
  17. package/src/state.js +31 -31
  18. package/src/{transaction.ts → transaction.js} +233 -181
  19. package/src/type.index.d.ts +20 -20
  20. package/src/typer.js +19 -19
  21. package/test/chain.js +120 -150
  22. package/test/contracts/token.js +40 -40
  23. package/test/create-genesis.js +66 -66
  24. package/tsconfig.js +15 -0
  25. package/workers/block-worker.js +40 -40
  26. package/workers/machine-worker.js +218 -218
  27. package/workers/pool-worker.js +28 -28
  28. package/workers/transaction-worker.js +19 -19
  29. package/workers/workers.js +8 -8
  30. package/block-worker.js +0 -1
  31. package/demo/865.browser.js +0 -10
  32. package/demo/chain.browser.js +0 -66842
  33. package/demo/generate-account.browser.js +0 -50
  34. package/demo/messages.browser.js +0 -328
  35. package/demo/multi-wallet.browser.js +0 -15
  36. package/demo/node.browser.js +0 -9858
  37. package/demo/pako.browser.js +0 -6900
  38. package/demo/peernet-swarm.browser.js +0 -839
  39. package/demo/storage.browser.js +0 -3724
  40. package/demo/workers/865.js +0 -10
  41. package/demo/workers/block-worker.js +0 -13175
  42. package/demo/workers/machine-worker.js +0 -13385
  43. package/demo/workers/pool-worker.js +0 -8503
  44. package/demo/workers/transaction-worker.js +0 -8495
  45. package/demo/wrtc.browser.js +0 -28
  46. package/dist/browser/workers/865.js +0 -10
  47. package/dist/browser/workers/block-worker.js +0 -9460
  48. package/dist/browser/workers/machine-worker.js +0 -9670
  49. package/dist/browser/workers/pool-worker.js +0 -4608
  50. package/dist/browser/workers/transaction-worker.js +0 -4600
  51. package/dist/chain.js +0 -10128
  52. package/dist/client-80bc8156.js +0 -491
  53. package/dist/commonjs-7fe3c381.js +0 -270
  54. package/dist/contracts/factory.js +0 -1
  55. package/dist/contracts/name-service.js +0 -1
  56. package/dist/contracts/native-token.js +0 -1
  57. package/dist/contracts/validators.js +0 -1
  58. package/dist/generate-account-445db122.js +0 -46
  59. package/dist/index-57f93805.js +0 -718
  60. package/dist/messages-bce1b91d-81af3b00.js +0 -315
  61. package/dist/module/chain.js +0 -10091
  62. package/dist/module/client-8031ec88.js +0 -489
  63. package/dist/module/commonjs-9005d5c0.js +0 -268
  64. package/dist/module/generate-account-489552b6.js +0 -44
  65. package/dist/module/index-ac2285c4.js +0 -688
  66. package/dist/module/messages-bce1b91d-eaf75d83.js +0 -302
  67. package/dist/module/node.js +0 -7049
  68. package/dist/module/workers/block-worker.js +0 -94
  69. package/dist/module/workers/machine-worker.js +0 -304
  70. package/dist/module/workers/pool-worker.js +0 -55
  71. package/dist/module/workers/transaction-worker.js +0 -47
  72. package/dist/node.js +0 -7061
  73. package/dist/standards/token.js +0 -1
  74. package/dist/workers/machine-worker.js +0 -1
  75. package/dist/workers/pool-worker.js +0 -1
  76. package/dist/workers/transaction-worker.js +0 -1
  77. package/rollup.config.js +0 -15
  78. package/tsconfig.json +0 -17
@@ -1,489 +0,0 @@
1
- var SocketClient = require('socket-request-client');
2
- require('@vandeurenglenn/debug');
3
-
4
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
5
-
6
- function _interopNamespace(e) {
7
- if (e && e.__esModule) return e;
8
- var n = Object.create(null);
9
- if (e) {
10
- Object.keys(e).forEach(function (k) {
11
- if (k !== 'default') {
12
- var d = Object.getOwnPropertyDescriptor(e, k);
13
- Object.defineProperty(n, k, d.get ? d : {
14
- enumerable: true,
15
- get: function () { return e[k]; }
16
- });
17
- }
18
- });
19
- }
20
- n["default"] = e;
21
- return Object.freeze(n);
22
- }
23
-
24
- var SocketClient__default = /*#__PURE__*/_interopDefaultLegacy(SocketClient);
25
-
26
- class Peer {
27
- #connection
28
- #connected = false
29
- #messageQue = []
30
- #chunksQue = {}
31
- #channel
32
- #peerId
33
- #channelName
34
- #chunkSize = 16 * 1024 // 16384
35
- #queRunning = false
36
- #MAX_BUFFERED_AMOUNT = 16 * 1024 * 1024
37
-
38
- get connection() {
39
- return this.#connection
40
- }
41
-
42
- get connected() {
43
- return this.#connected
44
- }
45
-
46
- get readyState() {
47
- return this.#channel?.readyState
48
- }
49
-
50
- /**
51
- * @params {Object} options
52
- * @params {string} options.channelName - this peerid : otherpeer id
53
- */
54
- constructor(options = {}) {
55
- this._in = this._in.bind(this);
56
- this.offerOptions = options.offerOptions;
57
- this.initiator = options.initiator;
58
- this.streams = options.streams;
59
- this.socketClient = options.socketClient;
60
- this.id = options.id;
61
- this.to = options.to;
62
- this.bw = {
63
- up: 0,
64
- down: 0
65
- };
66
-
67
- this.#channelName = options.channelName;
68
-
69
- this.#peerId = options.peerId;
70
- this.options = options;
71
- return this.#init()
72
- }
73
-
74
- get peerId() {
75
- return this.#peerId
76
- }
77
-
78
- set socketClient(value) {
79
- // this.socketClient?.pubsub.unsubscribe('signal', this._in)
80
- this._socketClient = value;
81
- this._socketClient.pubsub.subscribe('signal', this._in);
82
- }
83
-
84
- get socketClient() {
85
- return this._socketClient
86
- }
87
-
88
- splitMessage(message) {
89
- const chunks = [];
90
- message = pako.deflate(message);
91
- const size = message.byteLength || message.length;
92
- let offset = 0;
93
- return new Promise((resolve, reject) => {
94
- const splitMessage = () => {
95
- const chunk = message.slice(offset, offset + this.#chunkSize > size ? size : offset + this.#chunkSize);
96
- offset += this.#chunkSize;
97
- chunks.push(chunk);
98
- if (offset < size) return splitMessage()
99
- else resolve({chunks, size});
100
- };
101
-
102
- splitMessage();
103
- })
104
- }
105
-
106
- async #runQue() {
107
- this.#queRunning = true;
108
- if (this.#messageQue.length > 0 && this.#channel?.bufferedAmount + this.#messageQue[0]?.length < this.#MAX_BUFFERED_AMOUNT) {
109
- const message = this.#messageQue.shift();
110
-
111
- switch (this.#channel?.readyState) {
112
- case 'open':
113
- await this.#channel.send(message);
114
- if (this.#messageQue.length > 0) return this.#runQue()
115
- else this.#queRunning = false;
116
- break;
117
- case 'closed':
118
- case 'closing':
119
- this.#messageQue = [];
120
- this.#queRunning = false;
121
- debug('channel already closed, this usually means a bad implementation, try checking the readyState or check if the peer is connected before sending');
122
- break;
123
- case undefined:
124
- this.#messageQue = [];
125
- this.#queRunning = false;
126
- debug(`trying to send before a channel is created`);
127
- break;
128
- }
129
-
130
-
131
- } else {
132
- return setTimeout(() => this.#runQue(), 50)
133
- }
134
- }
135
-
136
- #trySend({ size, id, chunks }) {
137
- let offset = 0;
138
-
139
- for (const chunk of chunks) {
140
- const start = offset;
141
- const end = offset + chunk.length;
142
-
143
- const message = new TextEncoder().encode(JSON.stringify({ size, id, chunk, start, end }));
144
- this.#messageQue.push(message);
145
- }
146
-
147
- if (!this.queRunning) return this.#runQue()
148
- }
149
-
150
- async send(message, id) {
151
- const { chunks, size } = await this.splitMessage(message);
152
- return this.#trySend({ size, id, chunks })
153
- }
154
-
155
- request(data) {
156
- return new Promise((resolve, reject) => {
157
- const id = Math.random().toString(36).slice(-12);
158
-
159
- const _onData = message => {
160
- if (message.id === id) {
161
- resolve(message.data);
162
- pubsub.unsubscribe(`peer:data`, _onData);
163
- }
164
- };
165
-
166
- pubsub.subscribe(`peer:data`, _onData);
167
-
168
- // cleanup subscriptions
169
- // setTimeout(() => {
170
- // pubsub.unsubscribe(`peer:data-request-${id}`, _onData)
171
- // }, 5000);
172
-
173
- this.send(data, id);
174
- })
175
- }
176
-
177
- async #init() {
178
- try {
179
-
180
- if (!globalThis.pako) {
181
- const importee = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(/* webpackChunkName: "pako" */ 'pako')); });
182
- globalThis.pako = importee.default;
183
- }
184
-
185
- const iceServers = [{
186
- urls: 'stun:stun.l.google.com:19302' // Google's public STUN server
187
- }, {
188
- urls: "stun:openrelay.metered.ca:80",
189
- }, {
190
- urls: "turn:openrelay.metered.ca:443",
191
- username: "openrelayproject",
192
- credential: "openrelayproject",
193
- }, {
194
- urls: "turn:openrelay.metered.ca:443?transport=tcp",
195
- username: "openrelayproject",
196
- credential: "openrelayproject",
197
- }];
198
-
199
- this.#connection = new wrtc.RTCPeerConnection({iceServers});
200
-
201
- this.#connection.onicecandidate = ({ candidate }) => {
202
- if (candidate) {
203
- this.address = candidate.address;
204
- this.port = candidate.port;
205
- this.protocol = candidate.protocol;
206
- this.ipFamily = this.address.includes('::') ? 'ipv6': 'ipv4';
207
- this._sendMessage({candidate});
208
- }
209
- };
210
- // if (this.initiator) this.#connection.onnegotiationneeded = () => {
211
- // console.log('create offer');
212
- this.#connection.ondatachannel = (message) => {
213
- message.channel.onopen = () => {
214
- this.#connected = true;
215
- // debug(`peer:connected ${this}`)
216
- pubsub.publish('peer:connected', this);
217
- };
218
- message.channel.onclose = () => this.close.bind(this);
219
-
220
- message.channel.onmessage = (message) => {
221
- this._handleMessage(this.id, message);
222
- };
223
- this.#channel = message.channel;
224
- };
225
- if (this.initiator) {
226
-
227
- this.#channel = this.#connection.createDataChannel('messageChannel');
228
- this.#channel.onopen = () => {
229
- this.#connected = true;
230
- pubsub.publish('peer:connected', this);
231
- // this.#channel.send('hi')
232
- };
233
- this.#channel.onclose = () => this.close.bind(this);
234
-
235
- this.#channel.onmessage = (message) => {
236
- this._handleMessage(this.peerId, message);
237
- };
238
-
239
- const offer = await this.#connection.createOffer();
240
- await this.#connection.setLocalDescription(offer);
241
-
242
- this._sendMessage({'sdp': this.#connection.localDescription});
243
- }
244
- } catch (e) {
245
- console.log(e);
246
- }
247
-
248
- return this
249
- }
250
-
251
- _handleMessage(peerId, message) {
252
- // debug(`incoming message from ${peerId}`)
253
-
254
- message = JSON.parse(new TextDecoder().decode(message.data));
255
- // allow sharding (multiple peers share data)
256
- pubsub.publish('peernet:shard', message);
257
- const { id } = message;
258
-
259
- if (!this.#chunksQue[id]) this.#chunksQue[id] = [];
260
-
261
- if (message.size > this.#chunksQue[id].length || message.size === this.#chunksQue[id].length) {
262
- for (const value of Object.values(message.chunk)) {
263
- this.#chunksQue[id].push(value);
264
- }
265
- }
266
-
267
- if (message.size === this.#chunksQue[id].length) {
268
- let data = new Uint8Array(Object.values(this.#chunksQue[id]));
269
- delete this.#chunksQue[id];
270
- data = pako.inflate(data);
271
- pubsub.publish('peer:data', { id, data, from: this.peerId });
272
- }
273
- this.bw.down += message.byteLength || message.length;
274
- }
275
-
276
- _sendMessage(message) {
277
- this.socketClient.send({url: 'signal', params: {
278
- to: this.to,
279
- from: this.id,
280
- channelName: this.options.channelName,
281
- ...message
282
- }});
283
- }
284
-
285
- async _in(message, data) {
286
- // message = JSON.parse(message);
287
- if (!this.#connection || message.to !== this.id || message.from !== this.#peerId) return
288
- // if (data.videocall) return this._startStream(true, false); // start video and audio stream
289
- // if (data.call) return this._startStream(true, true); // start audio stream
290
- if (this.#connection?.signalinState === 'stable' && this.#connection?.remoteDescription !== null && this.#connection?.localDescription !== null) return
291
-
292
-
293
- if (message.candidate) {
294
- // debug(`incoming candidate ${this.#channelName}`)
295
- // debug(message.candidate.candidate)
296
- this.remoteAddress = message.candidate.address;
297
- this.remotePort = message.candidate.port;
298
- this.remoteProtocol = message.candidate.protocol;
299
- this.remoteIpFamily = this.remoteAddress?.includes('::') ? 'ipv6': 'ipv4';
300
- return this.#connection.addIceCandidate(new wrtc.RTCIceCandidate(message.candidate));
301
- }
302
- try {
303
- if (message.sdp) {
304
- if (message.sdp.type === 'offer') {
305
- // debug(`incoming offer ${this.#channelName}`)
306
- await this.#connection.setRemoteDescription(new wrtc.RTCSessionDescription(message.sdp));
307
- const answer = await this.#connection.createAnswer();
308
- await this.#connection.setLocalDescription(answer);
309
- this._sendMessage({'sdp': this.#connection.localDescription});
310
- }
311
- if (message.sdp.type === 'answer') {
312
- // debug(`incoming answer ${this.#channelName}`)
313
- await this.#connection.setRemoteDescription(new wrtc.RTCSessionDescription(message.sdp));
314
- }
315
- }
316
- } catch (e) {
317
- console.log(e);
318
- }
319
- }
320
-
321
- close() {
322
- // debug(`closing ${this.peerId}`)
323
- this.#connected = false;
324
- this.#channel?.close();
325
- this.#connection?.close();
326
-
327
- this.socketClient.pubsub.unsubscribe('signal', this._in);
328
- }
329
- }
330
-
331
- class Client {
332
- #peerConnection
333
- #connections = {}
334
- #stars = {}
335
-
336
- get connections() {
337
- return { ...this.#connections }
338
- }
339
-
340
- get peers() {
341
- return Object.entries(this.#connections)
342
- }
343
-
344
- constructor(id, networkVersion = 'peach', stars = ['wss://peach.leofcoin.org']) {
345
- this.id = id || Math.random().toString(36).slice(-12);
346
- this.peerJoined = this.peerJoined.bind(this);
347
- this.peerLeft = this.peerLeft.bind(this);
348
- this.starLeft = this.starLeft.bind(this);
349
- this.starJoined = this.starJoined.bind(this);
350
- this.networkVersion = networkVersion;
351
-
352
- this._init(stars);
353
- }
354
-
355
- async _init(stars = []) {
356
- this.starsConfig = stars;
357
- // reconnectJob()
358
-
359
- if (!globalThis.RTCPeerConnection) globalThis.wrtc = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(/* webpackChunkName: "wrtc" */ '@koush/wrtc')); });
360
- else globalThis.wrtc = {
361
- RTCPeerConnection,
362
- RTCSessionDescription,
363
- RTCIceCandidate
364
- };
365
-
366
- for (const star of stars) {
367
- try {
368
- this.socketClient = await SocketClient__default["default"](star, this.networkVersion);
369
- const id = await this.socketClient.request({url: 'id', params: {from: this.id}});
370
- this.socketClient.peerId = id;
371
- this.#stars[id] = this.socketClient;
372
- } catch (e) {
373
- if (stars.indexOf(star) === stars.length -1 && !this.socketClient) throw new Error(`No star available to connect`);
374
- }
375
- }
376
- const peers = await this.socketClient.peernet.join({id: this.id});
377
- for (const id of peers) {
378
- if (id !== this.id && !this.#connections[id]) this.#connections[id] = await new Peer({channelName: `${id}:${this.id}`, socketClient: this.socketClient, id: this.id, to: id, peerId: id});
379
- }
380
- this.setupListeners();
381
- }
382
-
383
- setupListeners() {
384
- this.socketClient.subscribe('peer:joined', this.peerJoined);
385
- this.socketClient.subscribe('peer:left', this.peerLeft);
386
- this.socketClient.subscribe('star:left', this.starLeft);
387
- }
388
-
389
- starJoined(id) {
390
- if (this.#stars[id]) {
391
- this.#stars[id].close();
392
- delete this.#stars[id];
393
- }
394
- console.log(`star ${id} joined`);
395
- }
396
-
397
- async starLeft(id) {
398
- if (this.#stars[id]) {
399
- this.#stars[id].close();
400
- delete this.#stars[id];
401
- }
402
- if (this.socketClient?.peerId === id) {
403
-
404
- this.socketClient.unsubscribe('peer:joined', this.peerJoined);
405
- this.socketClient.unsubscribe('peer:left', this.peerLeft);
406
- this.socketClient.unsubscribe('star:left', this.starLeft);
407
- this.socketClient.close();
408
- this.socketClient = undefined;
409
-
410
- for (const star of this.starsConfig) {
411
- try {
412
- this.socketClient = await SocketClient__default["default"](star, this.networkVersion);
413
- if (!this.socketClient?.client?._connection.connected) return
414
- const id = await this.socketClient.request({url: 'id', params: {from: this.id}});
415
- this.#stars[id] = this.socketClient;
416
-
417
- this.socketClient.peerId = id;
418
-
419
- const peers = await this.socketClient.peernet.join({id: this.id});
420
- this.setupListeners();
421
- for (const id of peers) {
422
- if (id !== this.id) {
423
- // close connection
424
- if (this.#connections[id]) {
425
- if (this.#connections[id].connected) await this.#connections[id].close();
426
- delete this.#connections[id];
427
- }
428
- // reconnect
429
- if (id !== this.id) this.#connections[id] = await new Peer({channelName: `${id}:${this.id}`, socketClient: this.socketClient, id: this.id, to: id, peerId: id});
430
- }
431
-
432
- }
433
- } catch (e) {
434
- console.log(e);
435
- if (this.starsConfig.indexOf(star) === this.starsConfig.length -1 && !this.socketClient) throw new Error(`No star available to connect`);
436
- }
437
- }
438
- }
439
- debug(`star ${id} left`);
440
- }
441
-
442
- peerLeft(peer) {
443
- const id = peer.peerId || peer;
444
- if (this.#connections[id]) {
445
- this.#connections[id].close();
446
- delete this.#connections[id];
447
- }
448
- debug(`peer ${id} left`);
449
- }
450
-
451
- async peerJoined(peer, signal) {
452
- const id = peer.peerId || peer;
453
- if (this.#connections[id]) {
454
- if (this.#connections[id].connected) this.#connections[id].close();
455
- delete this.#connections[id];
456
- }
457
- // RTCPeerConnection
458
- this.#connections[id] = await new Peer({initiator: true, channelName: `${this.id}:${id}`, socketClient: this.socketClient, id: this.id, to: id, peerId: id});
459
- debug(`peer ${id} joined`);
460
- }
461
-
462
- removePeer(peer) {
463
- const id = peer.peerId || peer;
464
- if (this.#connections[id]) {
465
- this.#connections[id].connected && this.#connections[id].close();
466
- delete this.#connections[id];
467
- }
468
- debug(`peer ${id} removed`);
469
- }
470
-
471
- async close() {
472
-
473
- this.socketClient.unsubscribe('peer:joined', this.peerJoined);
474
- this.socketClient.unsubscribe('peer:left', this.peerLeft);
475
- this.socketClient.unsubscribe('star:left', this.starLeft);
476
-
477
- const promises = [
478
- Object.values(this.#connections).map(connection => connection.close()),
479
- Object.values(this.#stars).map(connection => connection.close()),
480
- this.socketClient.close()
481
- ];
482
-
483
- return Promise.allSettled(promises)
484
-
485
- }
486
-
487
- }
488
-
489
- module.exports = Client;