gun-eth 1.4.32 → 1.4.34

Sign up to get free protection for your applications and to get access to all the features.
@@ -3,11 +3,8 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var Gun = require('gun');
6
- var SEA = require('gun/sea.js');
7
6
  var ethers = require('ethers');
8
- var url = require('url');
9
- var path$1 = require('path');
10
- var fs = require('fs');
7
+ require('gun/sea.js');
11
8
 
12
9
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
13
10
  let contractAddresses$1 = {
@@ -434,37 +431,48 @@ const PROOF_OF_INTEGRITY_ABI = [
434
431
  }
435
432
  ];
436
433
 
437
- // =============================================
438
- // IMPORTS AND GLOBAL VARIABLES
439
- // =============================================
434
+ const SEA = Gun.SEA;
440
435
 
441
436
  let PROOF_CONTRACT_ADDRESS;
442
- let rpcUrl = "";
443
- let privateKey = "";
444
-
445
- const MESSAGE_TO_SIGN = "Access GunDB with Ethereum";
446
-
447
437
  let contractAddresses = {
448
- PROOF_OF_INTEGRITY_ADDRESS: CHAIN_CONFIG.optimismSepolia.PROOF_OF_INTEGRITY_ADDRESS,
449
- STEALTH_ANNOUNCER_ADDRESS: CHAIN_CONFIG.optimismSepolia.STEALTH_ANNOUNCER_ADDRESS
438
+ PROOF_OF_INTEGRITY_ADDRESS:
439
+ CHAIN_CONFIG.optimismSepolia.PROOF_OF_INTEGRITY_ADDRESS,
440
+ STEALTH_ANNOUNCER_ADDRESS:
441
+ CHAIN_CONFIG.optimismSepolia.STEALTH_ANNOUNCER_ADDRESS,
450
442
  };
451
443
 
452
- // Solo per Node.js
453
- if (typeof window === 'undefined') {
454
- try {
455
- const __filename = url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('gun-eth.cjs.js', document.baseURI).href)));
456
- const __dirname = path$1.dirname(__filename);
457
-
444
+ // Funzione di inizializzazione per Node.js
445
+ const initNodeEnvironment = async () => {
446
+ if (typeof window === "undefined") {
458
447
  try {
459
- const rawdata = fs.readFileSync(path.join(__dirname, 'contract-address.json'), 'utf8');
460
- contractAddresses = JSON.parse(rawdata);
461
- console.log('Loaded contract addresses:', contractAddresses);
462
- } catch (err) {
463
- console.warn('Warning: contract-address.json not found or invalid');
448
+ // Importazioni dinamiche
449
+ const { fileURLToPath } = await import('url');
450
+ const { dirname } = await import('path');
451
+ const { readFile } = await import('fs/promises');
452
+ const { join } = await import('path');
453
+
454
+ const __filename = fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('gun-eth.cjs.js', document.baseURI).href)));
455
+ const __dirname = dirname(__filename);
456
+
457
+ try {
458
+ const rawdata = await readFile(
459
+ join(__dirname, "contract-address.json"),
460
+ "utf8"
461
+ );
462
+ contractAddresses = JSON.parse(rawdata);
463
+ console.log("Loaded contract addresses:", contractAddresses);
464
+ } catch (err) {
465
+ console.warn("Warning: contract-address.json not found or invalid");
466
+ }
467
+ } catch (error) {
468
+ console.error("Error loading Node.js modules:", error);
464
469
  }
465
- } catch (error) {
466
- console.error('Error loading Node.js modules:', error);
467
470
  }
471
+ };
472
+
473
+ // Inizializza solo in ambiente Node.js
474
+ if (typeof window === "undefined") {
475
+ initNodeEnvironment();
468
476
  }
469
477
 
470
478
  // =============================================
@@ -537,7 +545,7 @@ const getSigner = async () => {
537
545
  if (rpcUrl && privateKey) {
538
546
  const provider = new ethers.ethers.JsonRpcProvider(rpcUrl, {
539
547
  chainId: LOCAL_CONFIG.CHAIN_ID,
540
- name: "localhost"
548
+ name: "localhost",
541
549
  });
542
550
  return new Wallet(privateKey, provider);
543
551
  } else if (
@@ -562,27 +570,24 @@ function deriveStealthAddress(sharedSecret, spendingPublicKey) {
562
570
  try {
563
571
  const sharedSecretBytes = ethers.ethers.toUtf8Bytes(sharedSecret);
564
572
  const spendingPublicKeyBytes = ethers.ethers.toUtf8Bytes(spendingPublicKey);
565
-
573
+
566
574
  const stealthPrivateKey = ethers.ethers.keccak256(
567
- ethers.ethers.concat([
568
- sharedSecretBytes,
569
- spendingPublicKeyBytes
570
- ])
575
+ ethers.ethers.concat([sharedSecretBytes, spendingPublicKeyBytes])
571
576
  );
572
-
577
+
573
578
  const stealthWallet = new Wallet(stealthPrivateKey);
574
579
 
575
580
  console.log("Debug deriveStealthAddress:", {
576
581
  sharedSecretHex: stealthPrivateKey,
577
582
  spendingPublicKey,
578
583
  stealthPrivateKey,
579
- stealthAddress: stealthWallet.address
584
+ stealthAddress: stealthWallet.address,
580
585
  });
581
586
 
582
587
  return {
583
588
  stealthPrivateKey,
584
589
  stealthAddress: stealthWallet.address,
585
- wallet: stealthWallet
590
+ wallet: stealthWallet,
586
591
  };
587
592
  } catch (error) {
588
593
  console.error("Error in deriveStealthAddress:", error);
@@ -684,17 +689,21 @@ Gun.chain.createAndStoreEncryptedPair = async function (address, signature) {
684
689
  const viewingAccount = gunToEthAccount(v_pair.priv);
685
690
  const spendingAccount = gunToEthAccount(s_pair.priv);
686
691
 
687
- gun.get("gun-eth").get("users").get(address).put({
688
- pair: encryptedPair,
689
- v_pair: encryptedV_pair,
690
- s_pair: encryptedS_pair,
691
- publicKeys: {
692
- viewingPublicKey: v_pair.epub, // Use SEA encryption public key
693
- viewingPublicKey: v_pair.epub, // Use SEA encryption public key
694
- spendingPublicKey: spendingAccount.publicKey, // Use Ethereum address
695
- ethViewingAddress: viewingAccount.publicKey // Also save Ethereum address
696
- }
697
- });
692
+ gun
693
+ .get("gun-eth")
694
+ .get("users")
695
+ .get(address)
696
+ .put({
697
+ pair: encryptedPair,
698
+ v_pair: encryptedV_pair,
699
+ s_pair: encryptedS_pair,
700
+ publicKeys: {
701
+ viewingPublicKey: v_pair.epub, // Use SEA encryption public key
702
+ viewingPublicKey: v_pair.epub, // Use SEA encryption public key
703
+ spendingPublicKey: spendingAccount.publicKey, // Use Ethereum address
704
+ ethViewingAddress: viewingAccount.publicKey, // Also save Ethereum address
705
+ },
706
+ });
698
707
 
699
708
  console.log("Encrypted pairs and public keys stored for:", address);
700
709
  } catch (error) {
@@ -752,9 +761,9 @@ Gun.chain.proof = function (chain, nodeId, data, callback) {
752
761
 
753
762
  try {
754
763
  // Se siamo in localhost e in development, usa automaticamente la chain locale
755
- const targetChain = isLocalEnvironment() ? 'localhost' : chain;
764
+ const targetChain = isLocalEnvironment() ? "localhost" : chain;
756
765
  const chainConfig = getAddressesForChain(targetChain);
757
-
766
+
758
767
  console.log(`Using ${targetChain} configuration:`, chainConfig);
759
768
 
760
769
  // Usa gli indirizzi dalla configurazione
@@ -790,10 +799,7 @@ Gun.chain.proof = function (chain, nodeId, data, callback) {
790
799
  PROOF_OF_INTEGRITY_ABI,
791
800
  signer
792
801
  );
793
- const tx = await contract.updateData(
794
- toUtf8Bytes(nodeId),
795
- contentHash
796
- );
802
+ const tx = await contract.updateData(toUtf8Bytes(nodeId), contentHash);
797
803
  console.log("Transaction sent:", tx.hash);
798
804
  const receipt = await tx.wait();
799
805
  console.log("Transaction confirmed:", receipt);
@@ -820,7 +826,6 @@ Gun.chain.proof = function (chain, nodeId, data, callback) {
820
826
  return { contentHash, timestamp, updater };
821
827
  };
822
828
 
823
-
824
829
  if (nodeId && !data) {
825
830
  // Case 1: User passes only node
826
831
  gun.get(nodeId).once(async (existingData) => {
@@ -836,7 +841,8 @@ Gun.chain.proof = function (chain, nodeId, data, callback) {
836
841
  console.log("contentHash", contentHash);
837
842
 
838
843
  if (!contentHash) {
839
- if (callback) callback({ err: "No content hash found for this node" });
844
+ if (callback)
845
+ callback({ err: "No content hash found for this node" });
840
846
  return;
841
847
  }
842
848
 
@@ -928,10 +934,13 @@ Gun.chain.gunToEthAccount = function (gunPrivateKey) {
928
934
  * @param {string} signature - The sender's signature to access their keys
929
935
  * @returns {Promise<Object>} Object containing stealth addresses and keys
930
936
  */
931
- Gun.chain.generateStealthAddress = async function (recipientAddress, signature) {
937
+ Gun.chain.generateStealthAddress = async function (
938
+ recipientAddress,
939
+ signature
940
+ ) {
932
941
  try {
933
942
  const gun = this;
934
-
943
+
935
944
  // Get recipient's public keys
936
945
  const recipientData = await gun
937
946
  .get("gun-eth")
@@ -940,14 +949,21 @@ Gun.chain.generateStealthAddress = async function (recipientAddress, signature)
940
949
  .get("publicKeys")
941
950
  .then();
942
951
 
943
- if (!recipientData || !recipientData.viewingPublicKey || !recipientData.spendingPublicKey) {
952
+ if (
953
+ !recipientData ||
954
+ !recipientData.viewingPublicKey ||
955
+ !recipientData.spendingPublicKey
956
+ ) {
944
957
  throw new Error("Recipient's public keys not found");
945
958
  }
946
959
 
947
960
  // Get sender's keys
948
- const senderAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);
961
+ const senderAddress = await this.verifySignature(
962
+ MESSAGE_TO_SIGN,
963
+ signature
964
+ );
949
965
  const password = generatePassword(signature);
950
-
966
+
951
967
  const senderData = await gun
952
968
  .get("gun-eth")
953
969
  .get("users")
@@ -962,16 +978,20 @@ Gun.chain.generateStealthAddress = async function (recipientAddress, signature)
962
978
  let spendingKeyPair;
963
979
  try {
964
980
  const decryptedData = await SEA.decrypt(senderData.s_pair, password);
965
- spendingKeyPair = typeof decryptedData === 'string' ?
966
- JSON.parse(decryptedData) :
967
- decryptedData;
981
+ spendingKeyPair =
982
+ typeof decryptedData === "string"
983
+ ? JSON.parse(decryptedData)
984
+ : decryptedData;
968
985
  } catch (error) {
969
986
  console.error("Error decrypting spending pair:", error);
970
987
  throw new Error("Unable to decrypt spending pair");
971
988
  }
972
989
 
973
990
  // Generate shared secret using SEA ECDH with encryption public key
974
- const sharedSecret = await SEA.secret(recipientData.viewingPublicKey, spendingKeyPair);
991
+ const sharedSecret = await SEA.secret(
992
+ recipientData.viewingPublicKey,
993
+ spendingKeyPair
994
+ );
975
995
 
976
996
  if (!sharedSecret) {
977
997
  throw new Error("Unable to generate shared secret");
@@ -987,9 +1007,8 @@ Gun.chain.generateStealthAddress = async function (recipientAddress, signature)
987
1007
  return {
988
1008
  stealthAddress,
989
1009
  senderPublicKey: spendingKeyPair.epub, // Use encryption public key
990
- spendingPublicKey: recipientData.spendingPublicKey
1010
+ spendingPublicKey: recipientData.spendingPublicKey,
991
1011
  };
992
-
993
1012
  } catch (error) {
994
1013
  console.error("Error generating stealth address:", error);
995
1014
  throw error;
@@ -1077,10 +1096,14 @@ Gun.chain.recoverStealthFunds = async function (
1077
1096
  // Decrypt viewing and spending pairs
1078
1097
  let viewingKeyPair;
1079
1098
  try {
1080
- const decryptedViewingData = await SEA.decrypt(encryptedData.v_pair, password);
1081
- viewingKeyPair = typeof decryptedViewingData === 'string' ?
1082
- JSON.parse(decryptedViewingData) :
1083
- decryptedViewingData;
1099
+ const decryptedViewingData = await SEA.decrypt(
1100
+ encryptedData.v_pair,
1101
+ password
1102
+ );
1103
+ viewingKeyPair =
1104
+ typeof decryptedViewingData === "string"
1105
+ ? JSON.parse(decryptedViewingData)
1106
+ : decryptedViewingData;
1084
1107
  } catch (error) {
1085
1108
  console.error("Error decrypting keys:", error);
1086
1109
  throw new Error("Unable to decrypt keys");
@@ -1105,7 +1128,7 @@ Gun.chain.recoverStealthFunds = async function (
1105
1128
  console.error("Mismatch:", {
1106
1129
  recovered: recoveredAddress,
1107
1130
  expected: stealthAddress,
1108
- sharedSecret
1131
+ sharedSecret,
1109
1132
  });
1110
1133
  throw new Error("Recovered stealth address does not match");
1111
1134
  }
@@ -1133,11 +1156,14 @@ Gun.chain.announceStealthPayment = async function (
1133
1156
  senderPublicKey,
1134
1157
  spendingPublicKey,
1135
1158
  signature,
1136
- options = { onChain: false, chain: 'optimismSepolia' }
1159
+ options = { onChain: false, chain: "optimismSepolia" }
1137
1160
  ) {
1138
1161
  try {
1139
1162
  const gun = this;
1140
- const senderAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);
1163
+ const senderAddress = await this.verifySignature(
1164
+ MESSAGE_TO_SIGN,
1165
+ signature
1166
+ );
1141
1167
 
1142
1168
  if (options.onChain) {
1143
1169
  // On-chain announcement
@@ -1164,24 +1190,21 @@ Gun.chain.announceStealthPayment = async function (
1164
1190
  stealthAddress,
1165
1191
  { value: devFee }
1166
1192
  );
1167
-
1193
+
1168
1194
  console.log("Transaction sent:", tx.hash);
1169
1195
  const receipt = await tx.wait();
1170
1196
  console.log("Transaction confirmed:", receipt.hash);
1171
-
1197
+
1172
1198
  console.log("Stealth payment announced on-chain (dev fee paid)");
1173
1199
  } else {
1174
1200
  // Off-chain announcement (GunDB)
1175
- gun
1176
- .get("gun-eth")
1177
- .get("stealth-payments")
1178
- .set({
1179
- stealthAddress,
1180
- senderAddress,
1181
- senderPublicKey,
1182
- spendingPublicKey,
1183
- timestamp: Date.now(),
1184
- });
1201
+ gun.get("gun-eth").get("stealth-payments").set({
1202
+ stealthAddress,
1203
+ senderAddress,
1204
+ senderPublicKey,
1205
+ spendingPublicKey,
1206
+ timestamp: Date.now(),
1207
+ });
1185
1208
  console.log("Stealth payment announced off-chain");
1186
1209
  }
1187
1210
  } catch (error) {
@@ -1196,13 +1219,18 @@ Gun.chain.announceStealthPayment = async function (
1196
1219
  * @param {string} signature - The signature to authenticate the user
1197
1220
  * @returns {Promise<Array>} List of stealth payments
1198
1221
  */
1199
- Gun.chain.getStealthPayments = async function (signature, options = { source: 'both' }) {
1222
+ Gun.chain.getStealthPayments = async function (
1223
+ signature,
1224
+ options = { source: "both" }
1225
+ ) {
1200
1226
  try {
1201
1227
  const payments = [];
1202
1228
 
1203
- if (options.source === 'onChain' || options.source === 'both') {
1229
+ if (options.source === "onChain" || options.source === "both") {
1204
1230
  const signer = await getSigner();
1205
- const chainConfig = getAddressesForChain(options.chain || 'optimismSepolia');
1231
+ const chainConfig = getAddressesForChain(
1232
+ options.chain || "optimismSepolia"
1233
+ );
1206
1234
  const contractAddress = chainConfig.STEALTH_ANNOUNCER_ADDRESS;
1207
1235
 
1208
1236
  const contract = new Contract(
@@ -1210,28 +1238,32 @@ Gun.chain.getStealthPayments = async function (signature, options = { source: 'b
1210
1238
  STEALTH_ANNOUNCER_ABI,
1211
1239
  signer
1212
1240
  );
1213
-
1241
+
1214
1242
  try {
1215
1243
  // Get total number of announcements
1216
1244
  const totalAnnouncements = await contract.getAnnouncementsCount();
1217
1245
  const totalCount = Number(totalAnnouncements.toString());
1218
1246
  console.log("Total on-chain announcements:", totalCount);
1219
-
1247
+
1220
1248
  if (totalCount > 0) {
1221
1249
  // Get announcements in batches of 100
1222
1250
  const batchSize = 100;
1223
1251
  const lastIndex = totalCount - 1;
1224
-
1225
- for(let i = 0; i <= lastIndex; i += batchSize) {
1252
+
1253
+ for (let i = 0; i <= lastIndex; i += batchSize) {
1226
1254
  const toIndex = Math.min(i + batchSize - 1, lastIndex);
1227
1255
  const batch = await contract.getAnnouncementsInRange(i, toIndex);
1228
-
1256
+
1229
1257
  // For each announcement, try to decrypt
1230
- for(const announcement of batch) {
1258
+ for (const announcement of batch) {
1231
1259
  try {
1232
1260
  // Verify announcement is valid
1233
- if (!announcement || !announcement.stealthAddress ||
1234
- !announcement.senderPublicKey || !announcement.spendingPublicKey) {
1261
+ if (
1262
+ !announcement ||
1263
+ !announcement.stealthAddress ||
1264
+ !announcement.senderPublicKey ||
1265
+ !announcement.spendingPublicKey
1266
+ ) {
1235
1267
  console.log("Invalid announcement:", announcement);
1236
1268
  continue;
1237
1269
  }
@@ -1243,20 +1275,21 @@ Gun.chain.getStealthPayments = async function (signature, options = { source: 'b
1243
1275
  signature,
1244
1276
  announcement.spendingPublicKey
1245
1277
  );
1246
-
1278
+
1247
1279
  // If no errors thrown, announcement is for us
1248
1280
  payments.push({
1249
1281
  stealthAddress: announcement.stealthAddress,
1250
1282
  senderPublicKey: announcement.senderPublicKey,
1251
1283
  spendingPublicKey: announcement.spendingPublicKey,
1252
1284
  timestamp: Number(announcement.timestamp),
1253
- source: 'onChain',
1254
- wallet: recoveredWallet
1285
+ source: "onChain",
1286
+ wallet: recoveredWallet,
1255
1287
  });
1256
-
1257
1288
  } catch (e) {
1258
1289
  // Not for us, continue
1259
- console.log(`Announcement not for us: ${announcement.stealthAddress}`);
1290
+ console.log(
1291
+ `Announcement not for us: ${announcement.stealthAddress}`
1292
+ );
1260
1293
  continue;
1261
1294
  }
1262
1295
  }
@@ -1267,7 +1300,7 @@ Gun.chain.getStealthPayments = async function (signature, options = { source: 'b
1267
1300
  }
1268
1301
  }
1269
1302
 
1270
- if (options.source === 'offChain' || options.source === 'both') {
1303
+ if (options.source === "offChain" || options.source === "both") {
1271
1304
  // Get off-chain payments
1272
1305
  const gun = this;
1273
1306
  const offChainPayments = await new Promise((resolve) => {
@@ -1279,12 +1312,12 @@ Gun.chain.getStealthPayments = async function (signature, options = { source: 'b
1279
1312
  .map()
1280
1313
  .once((payment, id) => {
1281
1314
  if (payment?.stealthAddress) {
1282
- p.push({ ...payment, id, source: 'offChain' });
1315
+ p.push({ ...payment, id, source: "offChain" });
1283
1316
  }
1284
1317
  });
1285
1318
  setTimeout(() => resolve(p), 2000);
1286
1319
  });
1287
-
1320
+
1288
1321
  payments.push(...offChainPayments);
1289
1322
  }
1290
1323
 
@@ -1301,7 +1334,7 @@ Gun.chain.getStealthPayments = async function (signature, options = { source: 'b
1301
1334
  * @param {string} recipientAddress - The recipient's address
1302
1335
  * @returns {Promise<void>}
1303
1336
  */
1304
- Gun.chain.cleanStealthPayments = async function(recipientAddress) {
1337
+ Gun.chain.cleanStealthPayments = async function (recipientAddress) {
1305
1338
  try {
1306
1339
  const gun = this;
1307
1340
  const payments = await gun
@@ -1316,7 +1349,12 @@ Gun.chain.cleanStealthPayments = async function(recipientAddress) {
1316
1349
  if (payments) {
1317
1350
  Object.keys(payments).forEach(async (key) => {
1318
1351
  const payment = payments[key];
1319
- if (!payment || !payment.stealthAddress || !payment.senderPublicKey || !payment.spendingPublicKey) {
1352
+ if (
1353
+ !payment ||
1354
+ !payment.stealthAddress ||
1355
+ !payment.senderPublicKey ||
1356
+ !payment.spendingPublicKey
1357
+ ) {
1320
1358
  await gun
1321
1359
  .get("gun-eth")
1322
1360
  .get("stealth-payments")
@@ -1343,7 +1381,7 @@ class GunEth {
1343
1381
  static gunToEthAccount = gunToEthAccount;
1344
1382
  static getSigner = getSigner;
1345
1383
  static deriveStealthAddress = deriveStealthAddress;
1346
-
1384
+
1347
1385
  // Chain methods
1348
1386
  static chainMethods = {
1349
1387
  setSigner: Gun.chain.setSigner,
@@ -1360,7 +1398,7 @@ class GunEth {
1360
1398
  recoverStealthFunds: Gun.chain.recoverStealthFunds,
1361
1399
  announceStealthPayment: Gun.chain.announceStealthPayment,
1362
1400
  getStealthPayments: Gun.chain.getStealthPayments,
1363
- cleanStealthPayments: Gun.chain.cleanStealthPayments
1401
+ cleanStealthPayments: Gun.chain.cleanStealthPayments,
1364
1402
  };
1365
1403
 
1366
1404
  // Constants
@@ -1369,12 +1407,12 @@ class GunEth {
1369
1407
  static LOCAL_CONFIG = LOCAL_CONFIG;
1370
1408
  }
1371
1409
 
1410
+ exports.Gun = Gun;
1372
1411
  exports.default = Gun;
1373
1412
  exports.GunEth = GunEth;
1374
- exports.MESSAGE_TO_SIGN = MESSAGE_TO_SIGN;
1375
1413
  exports.deriveStealthAddress = deriveStealthAddress;
1376
1414
  exports.generatePassword = generatePassword;
1377
1415
  exports.generateRandomId = generateRandomId;
1378
1416
  exports.getSigner = getSigner;
1379
1417
  exports.gunToEthAccount = gunToEthAccount;
1380
- //# sourceMappingURL=gun-eth.cjs.js.map
1418
+ exports.initNodeEnvironment = initNodeEnvironment;