@leofcoin/chain 1.10.13 → 1.10.15

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 (33) hide show
  1. package/exports/beacon-envelope.js +2 -2
  2. package/exports/beacon-epoch.js +1 -1
  3. package/exports/beacon-lifecycle.js +2 -2
  4. package/exports/beacon-round.js +1 -1
  5. package/exports/beacon.js +1 -1
  6. package/exports/browser/beacon-envelope.js +79 -3
  7. package/exports/browser/beacon-epoch.js +2 -1
  8. package/exports/browser/beacon-lifecycle.js +3 -2
  9. package/exports/browser/beacon-round.js +2 -1
  10. package/exports/browser/beacon-wire.js +3 -3
  11. package/exports/browser/beacon.js +3 -2
  12. package/exports/browser/{browser-DvU1xNFS-sdlKNCJc.js → browser-DvU1xNFS-DmmNUdE-.js} +4 -4
  13. package/exports/browser/{proposal.proto-BcUgd885.js → browser-crypto-B9N9KlL4.js} +35 -6
  14. package/exports/browser/chain.js +16 -295
  15. package/exports/browser/{client-B-jyclOB-CsNYfj4Z.js → client-DDC8C510-3uaB70KL.js} +36 -12
  16. package/exports/browser/connection-monitor-GPztgSSJ.js +454 -0
  17. package/exports/browser/hkdf-CnZvwpZ9.js +222 -0
  18. package/exports/browser/{index-Bxr5Iztg-C6xBk0rK.js → index-Bxr5Iztg-WbFIosyf.js} +4 -4
  19. package/exports/browser/{index-CFBGfpG1.js → index-Ccn5sExe.js} +1 -2
  20. package/exports/browser/{messages-FMRAS8QX-CvlZBzy5.js → messages-DH0tgNM9-C2CtyLsf.js} +4 -4
  21. package/exports/browser/{node-browser-xlqSBOaN.js → node-browser-BYi7D_oa.js} +6 -6
  22. package/exports/browser/node-browser.js +4 -4
  23. package/exports/browser/sha2-piimb6xL.js +614 -0
  24. package/exports/browser/{weierstrass-C-jX_jly.js → weierstrass-Q0QND1ZT.js} +1 -1
  25. package/exports/browser/workers/machine-worker.js +412 -135
  26. package/exports/chain.js +13 -291
  27. package/exports/connection-monitor.js +324 -0
  28. package/exports/node.js +7 -0
  29. package/exports/workers/machine-worker.js +412 -135
  30. package/package.json +8 -4
  31. package/exports/browser/browser-CWeoyGUw-BabtHowB.js +0 -57
  32. package/exports/browser/constants-Cv0p224A.js +0 -130
  33. package/exports/browser/hkdf-DhdhLAAv.js +0 -147
@@ -1,6 +1,6 @@
1
1
  import { secp256k1 } from '@noble/curves/secp256k1';
2
- import { hkdf } from '@noble/hashes/hkdf';
3
- import { sha256 } from '@noble/hashes/sha256';
2
+ import { hkdf } from '@noble/hashes/hkdf.js';
3
+ import { sha256 } from '@noble/hashes/sha2.js';
4
4
 
5
5
  const encoder = new TextEncoder();
6
6
  const SCALAR_BYTES = 32;
@@ -1,4 +1,4 @@
1
- import { sha256 } from '@noble/hashes/sha256';
1
+ import { sha256 } from '@noble/hashes/sha2.js';
2
2
  import { toBase58, fromBase58 } from '@vandeurenglenn/typed-array-utils';
3
3
  import { deriveBeaconGroupPublicKey } from './beacon.js';
4
4
  import { q as quorumThreshold } from './quorum-S_qdgiAY.js';
@@ -1,5 +1,5 @@
1
- import { hkdf } from '@noble/hashes/hkdf';
2
- import { sha256 } from '@noble/hashes/sha256';
1
+ import { hkdf } from '@noble/hashes/hkdf.js';
2
+ import { sha256 } from '@noble/hashes/sha2.js';
3
3
  import { canonicalBeaconEpochConfig, beaconEpochDigest } from './beacon-epoch.js';
4
4
  import '@vandeurenglenn/typed-array-utils';
5
5
  import './beacon.js';
@@ -2,7 +2,7 @@ import { fromBase58, toBase58 } from '@vandeurenglenn/typed-array-utils';
2
2
  import { beaconMessage, deriveBeaconPublicShare, verifyBeaconSignatureShare, reconstructBeaconSignature, verifyBeaconProof, beaconRandomness } from './beacon.js';
3
3
  import { canonicalBeaconEpochConfig, beaconParticipants, beaconEpochGroupPublicKey } from './beacon-epoch.js';
4
4
  import '@noble/curves/bls12-381';
5
- import '@noble/hashes/sha256';
5
+ import '@noble/hashes/sha2.js';
6
6
  import './quorum-S_qdgiAY.js';
7
7
 
8
8
  class BeaconRound {
package/exports/beacon.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { bls12_381 } from '@noble/curves/bls12-381';
2
- import { sha256 } from '@noble/hashes/sha256';
2
+ import { sha256 } from '@noble/hashes/sha2.js';
3
3
 
4
4
  const encoder = new TextEncoder();
5
5
  const Fr = bls12_381.fields.Fr;
@@ -1,5 +1,81 @@
1
- import { w as weierstrass, r as randomBytes, c as concatBytes, F as Field, m as mod, p as pow2, s as sha256 } from './weierstrass-C-jX_jly.js';
2
- import { h as hmac, a as hkdf } from './hkdf-DhdhLAAv.js';
1
+ import { H as Hash, h as hash, t as toBytes, e as exists, b as bytes, w as weierstrass, r as randomBytes, c as concatBytes, F as Field, m as mod, p as pow2, s as sha256 } from './weierstrass-Q0QND1ZT.js';
2
+ import { h as hkdf } from './hkdf-CnZvwpZ9.js';
3
+ import { s as sha256$1 } from './sha2-piimb6xL.js';
4
+
5
+ // HMAC (RFC 2104)
6
+ class HMAC extends Hash {
7
+ constructor(hash$1, _key) {
8
+ super();
9
+ this.finished = false;
10
+ this.destroyed = false;
11
+ hash(hash$1);
12
+ const key = toBytes(_key);
13
+ this.iHash = hash$1.create();
14
+ if (typeof this.iHash.update !== 'function')
15
+ throw new Error('Expected instance of class which extends utils.Hash');
16
+ this.blockLen = this.iHash.blockLen;
17
+ this.outputLen = this.iHash.outputLen;
18
+ const blockLen = this.blockLen;
19
+ const pad = new Uint8Array(blockLen);
20
+ // blockLen can be bigger than outputLen
21
+ pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
22
+ for (let i = 0; i < pad.length; i++)
23
+ pad[i] ^= 0x36;
24
+ this.iHash.update(pad);
25
+ // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
26
+ this.oHash = hash$1.create();
27
+ // Undo internal XOR && apply outer XOR
28
+ for (let i = 0; i < pad.length; i++)
29
+ pad[i] ^= 0x36 ^ 0x5c;
30
+ this.oHash.update(pad);
31
+ pad.fill(0);
32
+ }
33
+ update(buf) {
34
+ exists(this);
35
+ this.iHash.update(buf);
36
+ return this;
37
+ }
38
+ digestInto(out) {
39
+ exists(this);
40
+ bytes(out, this.outputLen);
41
+ this.finished = true;
42
+ this.iHash.digestInto(out);
43
+ this.oHash.update(out);
44
+ this.oHash.digestInto(out);
45
+ this.destroy();
46
+ }
47
+ digest() {
48
+ const out = new Uint8Array(this.oHash.outputLen);
49
+ this.digestInto(out);
50
+ return out;
51
+ }
52
+ _cloneInto(to) {
53
+ // Create new instance without calling constructor since key already in state and we don't know it.
54
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
55
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
56
+ to = to;
57
+ to.finished = finished;
58
+ to.destroyed = destroyed;
59
+ to.blockLen = blockLen;
60
+ to.outputLen = outputLen;
61
+ to.oHash = oHash._cloneInto(to.oHash);
62
+ to.iHash = iHash._cloneInto(to.iHash);
63
+ return to;
64
+ }
65
+ destroy() {
66
+ this.destroyed = true;
67
+ this.oHash.destroy();
68
+ this.iHash.destroy();
69
+ }
70
+ }
71
+ /**
72
+ * HMAC: RFC2104 message authentication code.
73
+ * @param hash - function that would be used e.g. sha256
74
+ * @param key - message key
75
+ * @param message - message data
76
+ */
77
+ const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
78
+ hmac.create = (hash, key) => new HMAC(hash, key);
3
79
 
4
80
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
5
81
  // connects noble-curves to noble-hashes
@@ -125,7 +201,7 @@ const bytesScalar = (bytes) => {
125
201
  const encryptionKey = (privateKey, publicKey, aad) => {
126
202
  if (!secp256k1.utils.isValidPrivateKey(privateKey)) throw new Error("invalid beacon encryption private key");
127
203
  const sharedSecret = secp256k1.getSharedSecret(privateKey, publicKey, true);
128
- return hkdf(sha256, sharedSecret, sha256(aad), aad, 32);
204
+ return hkdf(sha256$1, sharedSecret, sha256$1(aad), aad, 32);
129
205
  };
130
206
  const importAesKey = (key, usage) => globalThis.crypto.subtle.importKey("raw", key, { name: "AES-GCM" }, false, [usage]);
131
207
  const createBeaconEncryptionKey = (randomPrivateKey = () => secp256k1.utils.randomPrivateKey()) => {
@@ -1,7 +1,8 @@
1
- import { s as sha256 } from './weierstrass-C-jX_jly.js';
1
+ import { s as sha256 } from './sha2-piimb6xL.js';
2
2
  import { t as toBase58, f as fromBase58 } from './index-CvKt4UDE.js';
3
3
  import { deriveBeaconGroupPublicKey } from './beacon.js';
4
4
  import { q as quorumThreshold } from './quorum-S_qdgiAY.js';
5
+ import './weierstrass-Q0QND1ZT.js';
5
6
 
6
7
  const encoder = new TextEncoder();
7
8
  const lengthPrefix = (bytes) => {
@@ -1,8 +1,9 @@
1
- import { a as hkdf } from './hkdf-DhdhLAAv.js';
2
- import { s as sha256 } from './weierstrass-C-jX_jly.js';
1
+ import { h as hkdf } from './hkdf-CnZvwpZ9.js';
2
+ import { s as sha256 } from './sha2-piimb6xL.js';
3
3
  import { canonicalBeaconEpochConfig, beaconEpochDigest } from './beacon-epoch.js';
4
4
  import './index-CvKt4UDE.js';
5
5
  import './beacon.js';
6
+ import './weierstrass-Q0QND1ZT.js';
6
7
  import './quorum-S_qdgiAY.js';
7
8
 
8
9
  const encoder = new TextEncoder();
@@ -1,7 +1,8 @@
1
1
  import { f as fromBase58, t as toBase58 } from './index-CvKt4UDE.js';
2
2
  import { beaconMessage, deriveBeaconPublicShare, verifyBeaconSignatureShare, reconstructBeaconSignature, verifyBeaconProof, beaconRandomness } from './beacon.js';
3
3
  import { canonicalBeaconEpochConfig, beaconParticipants, beaconEpochGroupPublicKey } from './beacon-epoch.js';
4
- import './weierstrass-C-jX_jly.js';
4
+ import './weierstrass-Q0QND1ZT.js';
5
+ import './sha2-piimb6xL.js';
5
6
  import './quorum-S_qdgiAY.js';
6
7
 
7
8
  class BeaconRound {
@@ -1,7 +1,7 @@
1
- import { s as signTransaction, c as MultiWallet, d as createTransactionHash } from './index-CFBGfpG1.js';
1
+ import { s as signTransaction, c as MultiWallet, d as createTransactionHash } from './index-Ccn5sExe.js';
2
2
  import { f as fromBase58 } from './index-CvKt4UDE.js';
3
- import './proposal.proto-BcUgd885.js';
4
- import 'crypto';
3
+ import './browser-crypto-B9N9KlL4.js';
4
+ import './sha2-piimb6xL.js';
5
5
 
6
6
  const validInteger = (value, minimum = 0n) => {
7
7
  try {
@@ -1,4 +1,5 @@
1
- import { v as validateObject, m as mod, u as utf8ToBytes, a as concatBytes, d as bytesToNumberBE, f as bitLen, g as weierstrassPoints, i as getMinHashLength, j as mapHashToField, k as bitGet, l as ensureBytes, F as Field, s as sha256, o as FpInvertBatch, q as FpPow, x as bitMask, y as mapToCurveSimpleSWU, z as bitSet, r as randomBytes, A as bytesToHex, B as numberToBytesBE } from './weierstrass-C-jX_jly.js';
1
+ import { v as validateObject, m as mod, u as utf8ToBytes, a as concatBytes, d as bytesToNumberBE, f as bitLen, g as weierstrassPoints, i as getMinHashLength, j as mapHashToField, k as bitGet, l as ensureBytes, F as Field, s as sha256, n as FpInvertBatch, o as FpPow, q as bitMask, x as mapToCurveSimpleSWU, y as bitSet, r as randomBytes, z as bytesToHex, A as numberToBytesBE } from './weierstrass-Q0QND1ZT.js';
2
+ import { s as sha256$1 } from './sha2-piimb6xL.js';
2
3
 
3
4
  function validateDST(dst) {
4
5
  if (dst instanceof Uint8Array)
@@ -1700,7 +1701,7 @@ const verifyBeaconProof = (proof, message, groupPublicKey) => {
1700
1701
  };
1701
1702
  const beaconRandomness = (proof) => {
1702
1703
  if (proof.length !== 96) throw new Error("invalid BLS beacon proof length");
1703
- return sha256(proof);
1704
+ return sha256$1(proof);
1704
1705
  };
1705
1706
 
1706
1707
  export { beaconMessage, beaconRandomness, combineBeaconShares, createBeaconContribution, deriveBeaconGroupPublicKey, deriveBeaconPublicShare, reconstructBeaconSignature, signBeaconRound, verifyBeaconProof, verifyBeaconShare, verifyBeaconSignatureShare };
@@ -1,8 +1,8 @@
1
- import { g as getDefaultExportFromCjs } from './node-browser-xlqSBOaN.js';
2
- import 'crypto';
3
- import './constants-Cv0p224A.js';
4
- import './proposal.proto-BcUgd885.js';
1
+ import { g as getDefaultExportFromCjs } from './node-browser-BYi7D_oa.js';
2
+ import './browser-crypto-B9N9KlL4.js';
5
3
  import './index-CvKt4UDE.js';
4
+ import './sha2-piimb6xL.js';
5
+ import './connection-monitor-GPztgSSJ.js';
6
6
 
7
7
  function _mergeNamespaces$1(n, m) {
8
8
  m.forEach(function (e) {
@@ -1,4 +1,5 @@
1
1
  import { a as index$4, b as base58$1, i as index$5, f as fromBase58, c as fromHex, d as fromArrayLike, e as toBase32, t as toBase58, g as toHex } from './index-CvKt4UDE.js';
2
+ import { s as sha256 } from './sha2-piimb6xL.js';
2
3
 
3
4
  var isHex = string => /^[A-F0-9]+$/i.test(
4
5
  string.startsWith('0x') ?
@@ -7065,20 +7066,20 @@ const getTokens = (proto) => {
7065
7066
  return tokens;
7066
7067
  };
7067
7068
 
7068
- const encoder = new TextEncoder();
7069
+ const encoder$1 = new TextEncoder();
7069
7070
  const toType = (data) => {
7070
7071
  if (data instanceof Uint8Array)
7071
7072
  return data;
7072
7073
  if (data instanceof ArrayBuffer)
7073
7074
  return new Uint8Array(data);
7074
7075
  if (typeof data === 'bigint')
7075
- return encoder.encode(data.toString());
7076
+ return encoder$1.encode(data.toString());
7076
7077
  if (typeof data === 'string')
7077
- return encoder.encode(data);
7078
+ return encoder$1.encode(data);
7078
7079
  if (typeof data === 'object')
7079
- return encoder.encode(JSON.stringify(data, jsonStringifyBigInt$1));
7080
+ return encoder$1.encode(JSON.stringify(data, jsonStringifyBigInt$1));
7080
7081
  if (typeof data === 'number' || typeof data === 'boolean')
7081
- return encoder.encode(data.toString());
7082
+ return encoder$1.encode(data.toString());
7082
7083
  throw new Error(`unsuported type ${typeof data || data}`);
7083
7084
  };
7084
7085
  const encode = (proto, input, compress) => {
@@ -8861,4 +8862,32 @@ var proto = {
8861
8862
  signature: String()
8862
8863
  };
8863
8864
 
8864
- export { ContractMessage as C, FormatInterface as F, TransactionMessage as T, proto$1 as a, proto as b, jsonParseBigInt$1 as c, Codec as d, proto$3 as e, index$1 as f, createRIPEMD160 as g, createHMAC as h, index$2 as i, jsonStringifyBigInt$1 as j, createSHA512 as k, createKeccak as l, index$3 as m, proto$7 as n, proto$8 as o, proto$2 as p, proto$5 as q };
8865
+ const encoder = new TextEncoder();
8866
+ const normalizeInput = (value) => {
8867
+ if (typeof value === "string") return encoder.encode(value);
8868
+ if (value instanceof Uint8Array) return value;
8869
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
8870
+ return new Uint8Array(value);
8871
+ };
8872
+ const createHash = (algorithm) => {
8873
+ if (algorithm !== "sha256") throw new Error(`Unsupported hash algorithm: ${algorithm}`);
8874
+ const chunks = [];
8875
+ return {
8876
+ update(data) {
8877
+ chunks.push(normalizeInput(data));
8878
+ return this;
8879
+ },
8880
+ digest() {
8881
+ const length = chunks.reduce((total, chunk) => total + chunk.length, 0);
8882
+ const input = new Uint8Array(length);
8883
+ let offset = 0;
8884
+ for (const chunk of chunks) {
8885
+ input.set(chunk, offset);
8886
+ offset += chunk.length;
8887
+ }
8888
+ return sha256(input);
8889
+ }
8890
+ };
8891
+ };
8892
+
8893
+ export { ContractMessage as C, FormatInterface as F, TransactionMessage as T, proto$1 as a, proto as b, jsonParseBigInt$1 as c, Codec as d, proto$3 as e, index$1 as f, createRIPEMD160 as g, createHMAC as h, index$2 as i, jsonStringifyBigInt$1 as j, createSHA512 as k, createKeccak as l, index$3 as m, createHash as n, proto$7 as o, proto$2 as p, proto$8 as q, proto$5 as r };
@@ -1,9 +1,9 @@
1
- import { F as FormatInterface, p as proto, a as proto$1, b as proto$2, T as TransactionMessage, j as jsonStringifyBigInt, c as jsonParseBigInt, C as ContractMessage, d as Codec } from './proposal.proto-BcUgd885.js';
2
- import { B as BlockMessage, L as LastBlockMessage, P as PROTOCOL_VERSION, R as REACHED_ONE_ZERO_ZERO, a as BWMessage, S as StateMessage } from './constants-Cv0p224A.js';
3
- import { M as MAX_TRANSACTION_BYTES, a as MAX_BLOCK_TRANSACTION_BYTES, b as MAX_BLOCK_TRANSACTIONS, c as MultiWallet, d as createTransactionHash, e as calculateFee, f as createContractMessage, s as signTransaction, r as randombytes, g as distributeTransactionFee, h as supportsTransactionFees, i as supportsMonetaryPolicy, v as validateBlockResourceLimits, j as calculateMonetaryPolicy, k as distributeAmount, l as aggregateValidatorFees, m as MONETARY_POLICY_AUTHORITY, n as contractFactoryMessage, o as nativeTokenMessage, p as validatorsMessage, q as nameServiceMessage, t as parseUnits, u as formatUnits } from './index-CFBGfpG1.js';
1
+ import { F as FormatInterface, p as proto, a as proto$1, b as proto$2, T as TransactionMessage, j as jsonStringifyBigInt, c as jsonParseBigInt, C as ContractMessage, d as Codec } from './browser-crypto-B9N9KlL4.js';
2
+ import { B as BlockMessage, L as LastBlockMessage, P as PROTOCOL_VERSION, R as REACHED_ONE_ZERO_ZERO, C as ConnectionMonitor, a as BWMessage, S as StateMessage } from './connection-monitor-GPztgSSJ.js';
3
+ import { M as MAX_TRANSACTION_BYTES, a as MAX_BLOCK_TRANSACTION_BYTES, b as MAX_BLOCK_TRANSACTIONS, c as MultiWallet, d as createTransactionHash, e as calculateFee, f as createContractMessage, s as signTransaction, r as randombytes, g as distributeTransactionFee, h as supportsTransactionFees, i as supportsMonetaryPolicy, v as validateBlockResourceLimits, j as calculateMonetaryPolicy, k as distributeAmount, l as aggregateValidatorFees, m as MONETARY_POLICY_AUTHORITY, n as contractFactoryMessage, o as nativeTokenMessage, p as validatorsMessage, q as nameServiceMessage, t as parseUnits, u as formatUnits } from './index-Ccn5sExe.js';
4
4
  import { f as fromBase58 } from './index-CvKt4UDE.js';
5
5
  import { q as quorumThreshold } from './quorum-S_qdgiAY.js';
6
- import 'crypto';
6
+ import './sha2-piimb6xL.js';
7
7
 
8
8
  const getTargets = () => Array.from([]);
9
9
  const isEnabled = (target) => {
@@ -4692,6 +4692,12 @@ class State extends Contract {
4692
4692
  const localIndex = localBlock ? Number(localBlock.index) : -1;
4693
4693
  const remoteIndex = Number(lastBlock.index);
4694
4694
  const remoteBlockHash = lastBlock.hash;
4695
+ globalThis.pubsub.publish("sync-progress", {
4696
+ phase: "syncing",
4697
+ startIndex: localIndex,
4698
+ localIndex,
4699
+ targetIndex: remoteIndex
4700
+ });
4695
4701
  let localStateHash = "0x0";
4696
4702
  try {
4697
4703
  localStateHash = new TextDecoder().decode(await globalThis.chainStore.get("lastBlock"));
@@ -4751,6 +4757,12 @@ class State extends Contract {
4751
4757
  } else {
4752
4758
  debug$1(`Block already in local state. Remote hash: ${remoteBlockHash} matches local state`);
4753
4759
  }
4760
+ globalThis.pubsub.publish("sync-progress", {
4761
+ phase: "synced",
4762
+ startIndex: localIndex,
4763
+ localIndex: remoteIndex,
4764
+ targetIndex: remoteIndex
4765
+ });
4754
4766
  } catch (error) {
4755
4767
  console.log(error);
4756
4768
  throw error;
@@ -5037,297 +5049,6 @@ class VersionControl extends State {
5037
5049
  }
5038
5050
  }
5039
5051
 
5040
- class ConnectionMonitor {
5041
- #isMonitoring = false;
5042
- #checkInterval = null;
5043
- #reconnectDelay = 5e3;
5044
- #reconnectTimer = null;
5045
- #healthCheckInterval = 6e4;
5046
- #version;
5047
- #lastHealthCheckAt = 0;
5048
- #reconnecting = false;
5049
- // event handlers to remove later
5050
- #onOnline = null;
5051
- #onVisibilityChange = null;
5052
- #onSigcont = null;
5053
- #onPeerConnected = null;
5054
- get isMonitoring() {
5055
- return this.#isMonitoring;
5056
- }
5057
- get connectedPeers() {
5058
- return Object.values(globalThis.peernet?.connections || {}).filter((peer) => peer.connected);
5059
- }
5060
- get compatiblePeers() {
5061
- return this.connectedPeers.filter((peer) => {
5062
- if (!peer.version || !this.#version) return false;
5063
- const [peerMajor, peerMinor] = peer.version.split(".");
5064
- const [localMajor, localMinor] = this.#version.split(".");
5065
- return peerMajor === localMajor && peerMinor === localMinor;
5066
- });
5067
- }
5068
- get disconnectedPeers() {
5069
- return Object.values(globalThis.peernet?.connections || {}).filter((peer) => !peer.connected);
5070
- }
5071
- start(version) {
5072
- this.#version = version;
5073
- console.log(`\u{1F517} Connection Monitor initialized for version: ${this.#version}`);
5074
- if (this.#isMonitoring) return;
5075
- this.#isMonitoring = true;
5076
- console.log("\u{1F504} Starting connection monitor...");
5077
- if (typeof window !== "undefined" && typeof document !== "undefined") {
5078
- this.#onOnline = () => {
5079
- console.log("\u{1F310} Network online \u2014 attempting restore");
5080
- void this.#restoreNetwork();
5081
- };
5082
- window.addEventListener("online", this.#onOnline);
5083
- this.#onVisibilityChange = () => {
5084
- if (document.visibilityState === "visible") {
5085
- console.log("\u{1F4A1} Visibility regained");
5086
- if (this.connectedPeers.length === 0) {
5087
- console.log("\u{1F4A1} Visibility regained \u2014 attempting restore");
5088
- void this.#restoreNetwork();
5089
- }
5090
- }
5091
- };
5092
- document.addEventListener("visibilitychange", this.#onVisibilityChange);
5093
- }
5094
- if (typeof process !== "undefined" && typeof process.on === "function") {
5095
- this.#onSigcont = () => {
5096
- console.log("\u{1F514} Process resumed (SIGCONT) \u2014 attempting restore");
5097
- void this.#restoreNetwork();
5098
- };
5099
- try {
5100
- process.on("SIGCONT", this.#onSigcont);
5101
- } catch (e) {
5102
- }
5103
- }
5104
- this.#lastHealthCheckAt = Date.now();
5105
- this.#checkInterval = setInterval(() => {
5106
- this.#healthCheck();
5107
- }, this.#healthCheckInterval);
5108
- this.#onPeerConnected = () => {
5109
- if (this.#reconnectTimer) {
5110
- clearTimeout(this.#reconnectTimer);
5111
- this.#reconnectTimer = null;
5112
- }
5113
- this.#reconnecting = false;
5114
- this.#reconnectDelay = 5e3;
5115
- };
5116
- globalThis.pubsub?.subscribe("peer:connected", this.#onPeerConnected);
5117
- }
5118
- stop() {
5119
- if (!this.#isMonitoring) return;
5120
- this.#isMonitoring = false;
5121
- if (this.#checkInterval) {
5122
- clearInterval(this.#checkInterval);
5123
- this.#checkInterval = null;
5124
- }
5125
- if (typeof window !== "undefined") {
5126
- if (this.#onOnline) {
5127
- window.removeEventListener("online", this.#onOnline);
5128
- this.#onOnline = null;
5129
- }
5130
- if (this.#onVisibilityChange) {
5131
- document.removeEventListener("visibilitychange", this.#onVisibilityChange);
5132
- this.#onVisibilityChange = null;
5133
- }
5134
- }
5135
- if (typeof process !== "undefined" && typeof process.removeListener === "function" && this.#onSigcont) {
5136
- try {
5137
- process.removeListener("SIGCONT", this.#onSigcont);
5138
- } catch (e) {
5139
- }
5140
- this.#onSigcont = null;
5141
- }
5142
- if (this.#onPeerConnected) {
5143
- globalThis.pubsub?.unsubscribe("peer:connected", this.#onPeerConnected);
5144
- this.#onPeerConnected = null;
5145
- }
5146
- if (this.#reconnectTimer) {
5147
- clearTimeout(this.#reconnectTimer);
5148
- this.#reconnectTimer = null;
5149
- }
5150
- console.log("\u23F9\uFE0F Connection monitor stopped");
5151
- }
5152
- async #healthCheck() {
5153
- const now = Date.now();
5154
- const expectedNext = this.#lastHealthCheckAt + this.#healthCheckInterval;
5155
- const drift = now - expectedNext;
5156
- this.#lastHealthCheckAt = now;
5157
- if (drift > 5e3) {
5158
- console.log(`\u23F0 Detected timer drift of ${drift}ms (likely system sleep) \u2014 attempting restore`);
5159
- void this.#restoreNetwork();
5160
- }
5161
- const connectedPeers = this.connectedPeers;
5162
- const compatiblePeers = this.compatiblePeers;
5163
- const disconnectedPeers = this.disconnectedPeers;
5164
- console.log(
5165
- `\u{1F50D} Health check: ${connectedPeers.length} connected, ${compatiblePeers.length} compatible, ${disconnectedPeers.length} negotiating`
5166
- );
5167
- if (connectedPeers.length === 0 && disconnectedPeers.length === 0) {
5168
- console.warn("\u26A0\uFE0F No peer connections detected \u2014 attempting reconnection");
5169
- await this.#attemptReconnection();
5170
- } else if (compatiblePeers.length === 0 && connectedPeers.length > 0) {
5171
- console.warn("\u26A0\uFE0F No compatible peers found \u2014 attempting reconnection");
5172
- await this.#attemptReconnection();
5173
- }
5174
- globalThis.pubsub?.publish("connection-status", {
5175
- connected: connectedPeers.length,
5176
- compatible: compatiblePeers.length,
5177
- healthy: compatiblePeers.length > 0
5178
- });
5179
- }
5180
- // lightweight TCP probe to detect internet connectivity in Node.js
5181
- async #isOnLine(timeout = 1500) {
5182
- if (navigator?.onLine !== void 0) {
5183
- return navigator.onLine;
5184
- }
5185
- return new Promise(async (resolve) => {
5186
- try {
5187
- const net = await import('net');
5188
- const socket = new net.Socket();
5189
- let finished = false;
5190
- const finish = (val) => {
5191
- if (finished) return;
5192
- finished = true;
5193
- try {
5194
- socket.destroy();
5195
- } catch (e) {
5196
- }
5197
- resolve(val);
5198
- };
5199
- socket.setTimeout(timeout);
5200
- socket.once("connect", () => finish(true));
5201
- socket.once("error", () => finish(false));
5202
- socket.once("timeout", () => finish(false));
5203
- socket.connect(53, "1.1.1.1");
5204
- } catch (e) {
5205
- resolve(false);
5206
- }
5207
- });
5208
- }
5209
- // Called on visibility/online/resume events
5210
- async #restoreNetwork() {
5211
- if (this.#reconnecting) {
5212
- console.log("\u{1F501} Reconnection already in progress, skipping");
5213
- return;
5214
- }
5215
- this.#reconnecting = true;
5216
- if (this.connectedPeers.length > 0) {
5217
- console.log("\u2705 Already connected to peers, skipping restoration");
5218
- this.#reconnecting = false;
5219
- return;
5220
- }
5221
- console.log("\u{1F501} Restoring network");
5222
- try {
5223
- const online = await this.#isOnLine(1500);
5224
- if (!online) {
5225
- console.warn("\u26A0\uFE0F No internet detected, skipping restore");
5226
- this.#reconnecting = false;
5227
- return;
5228
- }
5229
- } catch (e) {
5230
- console.warn("\u26A0\uFE0F Online probe failed, proceeding with restore", e?.message || e);
5231
- }
5232
- try {
5233
- console.log("\u{1F504} Attempting network restoration...");
5234
- if (globalThis.peernet?.client?.reinit) {
5235
- console.log(" \u2192 Trying client.reinit()");
5236
- try {
5237
- await globalThis.peernet.client.reinit();
5238
- console.log(" \u2705 client.reinit() succeeded");
5239
- } catch (e) {
5240
- console.warn(" \u26A0\uFE0F client.reinit() failed:", e?.message || e);
5241
- }
5242
- }
5243
- if (globalThis.peernet?.start) {
5244
- console.log(" \u2192 Trying peernet.start()");
5245
- try {
5246
- await globalThis.peernet.start();
5247
- console.log(" \u2705 peernet.start() succeeded");
5248
- } catch (e) {
5249
- console.warn(" \u26A0\uFE0F peernet.start() failed:", e?.message || e);
5250
- }
5251
- }
5252
- try {
5253
- const networkName = globalThis.peernet?.network;
5254
- if (networkName && typeof networkName === "string") {
5255
- const { default: networks } = await import('./constants-Cv0p224A.js').then(function (n) { return n.n; });
5256
- const [mainKey, subKey] = networkName.split(":");
5257
- const networkConfig = networks?.[mainKey]?.[subKey];
5258
- if (networkConfig?.stars && Array.isArray(networkConfig.stars)) {
5259
- console.log(" \u2192 Attempting to dial star servers:", networkConfig.stars.join(", "));
5260
- for (const star of networkConfig.stars) {
5261
- try {
5262
- if (globalThis.peernet?.client && "dial" in globalThis.peernet.client) {
5263
- await globalThis.peernet.client.dial(star);
5264
- console.log(` \u2705 Connected to star server: ${star}`);
5265
- }
5266
- } catch (e) {
5267
- console.warn(` \u26A0\uFE0F Failed to dial ${star}:`, e?.message || e);
5268
- }
5269
- }
5270
- }
5271
- }
5272
- } catch (e) {
5273
- console.warn(" \u26A0\uFE0F Could not load or dial star servers:", e?.message || e);
5274
- }
5275
- await new Promise((resolve) => setTimeout(resolve, 2e3));
5276
- const connectedAfter = this.connectedPeers.length;
5277
- console.log(`\u{1F504} Restoration complete. Connected peers: ${connectedAfter}`);
5278
- } catch (error) {
5279
- console.error("\u274C Network restoration failed:", error?.message || error);
5280
- } finally {
5281
- this.#reconnecting = false;
5282
- }
5283
- }
5284
- async waitForPeers(timeoutMs = 3e4) {
5285
- return new Promise((resolve) => {
5286
- const startTime = Date.now();
5287
- const checkPeers = () => {
5288
- if (this.compatiblePeers.length > 0) {
5289
- resolve(true);
5290
- return;
5291
- }
5292
- if (Date.now() - startTime >= timeoutMs) {
5293
- resolve(false);
5294
- return;
5295
- }
5296
- setTimeout(checkPeers, 1e3);
5297
- };
5298
- checkPeers();
5299
- });
5300
- }
5301
- async #attemptReconnection() {
5302
- try {
5303
- await this.#restoreNetwork();
5304
- const hasConnections = this.connectedPeers.length > 0 || this.disconnectedPeers.length > 0;
5305
- if (hasConnections) {
5306
- console.log("\u2705 Reconnection successful, resetting backoff delay");
5307
- this.#reconnectDelay = 5e3;
5308
- } else {
5309
- console.warn("\u26A0\uFE0F Reconnection attempt completed but no peers connected");
5310
- if (this.#reconnectDelay >= 3e4) {
5311
- console.warn("\u26A0\uFE0F Reconnection delay reached maximum, resetting to 5 seconds");
5312
- this.#reconnectDelay = 5e3;
5313
- } else {
5314
- this.#reconnectDelay = Math.min(this.#reconnectDelay * 1.5, 3e4);
5315
- console.warn(`\u26A0\uFE0F Increasing reconnection delay to ${this.#reconnectDelay} ms`);
5316
- }
5317
- this.#reconnectTimer = setTimeout(() => this.#attemptReconnection(), this.#reconnectDelay);
5318
- }
5319
- } catch (error) {
5320
- console.error("\u274C Reconnection failed:", error?.message || error);
5321
- if (this.#reconnectDelay >= 3e4) {
5322
- this.#reconnectDelay = 5e3;
5323
- } else {
5324
- this.#reconnectDelay = Math.min(this.#reconnectDelay * 1.5, 3e4);
5325
- }
5326
- this.#reconnectTimer = setTimeout(() => this.#attemptReconnection(), this.#reconnectDelay);
5327
- }
5328
- }
5329
- }
5330
-
5331
5052
  const validateChainLink = (localTip, incoming) => {
5332
5053
  const localHash = localTip?.hash || "0x0";
5333
5054
  const localIndex = Number(localTip?.index ?? -1);