gun-eth 1.4.22 → 1.4.23
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/gun-eth.cjs.js +1534 -68
- package/dist/gun-eth.cjs.js.map +1 -1
- package/dist/gun-eth.esm.js +1534 -68
- package/dist/gun-eth.esm.js.map +1 -1
- package/dist/gun-eth.min.js +2 -12
- package/dist/gun-eth.min.js.map +1 -1
- package/package.json +8 -6
- package/dist/gun-eth.js +0 -1382
- package/dist/gun-eth.js.map +0 -1
package/dist/gun-eth.min.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"gun-eth.min.js","sources":["../src/config/local.js","../src/abis/abis.js","../src/index.js"],"sourcesContent":["let contractAddresses = {\r\n PROOF_OF_INTEGRITY_ADDRESS: \"0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512\",\r\n STEALTH_ANNOUNCER_ADDRESS: \"0x5FbDB2315678afecb367f032d93F642f64180aa3\"\r\n};\r\n\r\nif (typeof window === 'undefined') {\r\n const { fileURLToPath } = require('url');\r\n const { dirname } = require('path');\r\n const { readFileSync } = require('fs');\r\n const { join } = require('path');\r\n\r\n try {\r\n const __filename = fileURLToPath(import.meta.url);\r\n const __dirname = dirname(__filename);\r\n const rawdata = readFileSync(join(__dirname, 'contract-address.json'), 'utf8');\r\n contractAddresses = JSON.parse(rawdata);\r\n console.log(\"Loaded contract addresses:\", contractAddresses);\r\n } catch (error) {\r\n console.warn(\"Warning: contract-address.json not found or invalid\");\r\n }\r\n}\r\n\r\nexport const LOCAL_CONFIG = {\r\n CHAIN_ID: 1337,\r\n PROOF_OF_INTEGRITY_ADDRESS: contractAddresses.PROOF_OF_INTEGRITY_ADDRESS,\r\n STEALTH_ANNOUNCER_ADDRESS: contractAddresses.STEALTH_ANNOUNCER_ADDRESS,\r\n RPC_URL: \"http://127.0.0.1:8545\",\r\n GUN_PEER: \"http://localhost:8765/gun\"\r\n}; ","import { LOCAL_CONFIG } from '../config/local.js';\r\n\r\n// Indirizzi di produzione per diverse chain\r\nexport const CHAIN_CONFIG = {\r\n optimismSepolia: {\r\n STEALTH_ANNOUNCER_ADDRESS: \"\",\r\n PROOF_OF_INTEGRITY_ADDRESS: \"\",\r\n RPC_URL: \"https://sepolia.optimism.io\",\r\n CHAIN_ID: 11155420\r\n },\r\n arbitrumSepolia: {\r\n STEALTH_ANNOUNCER_ADDRESS: \"\",\r\n PROOF_OF_INTEGRITY_ADDRESS: \"\",\r\n RPC_URL: \"https://sepolia-rollup.arbitrum.io/rpc\",\r\n CHAIN_ID: 421614\r\n },\r\n localhost: {\r\n RPC_URL: \"http://127.0.0.1:8545\",\r\n CHAIN_ID: 1337\r\n }\r\n};\r\n\r\n// Funzione per ottenere gli indirizzi corretti\r\nexport function getAddressesForChain(chainName) {\r\n let config;\r\n\r\n // Se è localhost, prova a caricare gli indirizzi locali\r\n if (chainName === 'localhost') {\r\n try {\r\n // Carica gli indirizzi dal file generato dal deploy locale\r\n const localAddresses = require('../config/contract-address.json');\r\n config = {\r\n ...CHAIN_CONFIG.localhost,\r\n ...localAddresses\r\n };\r\n console.log(\"Using local addresses:\", config);\r\n return config;\r\n } catch (err) {\r\n console.warn('No local addresses found');\r\n throw new Error('No local addresses found. Did you run local deployment?');\r\n }\r\n }\r\n\r\n // Altrimenti usa gli indirizzi di produzione\r\n config = CHAIN_CONFIG[chainName];\r\n if (!config) {\r\n throw new Error(`Chain ${chainName} not supported. Supported chains: ${Object.keys(CHAIN_CONFIG).join(', ')}`);\r\n }\r\n\r\n return config;\r\n}\r\n\r\n// Funzione helper per verificare se siamo in ambiente locale\r\nexport function isLocalEnvironment() {\r\n return process.env.NODE_ENV === 'development' && \r\n typeof window !== 'undefined' && \r\n window.location.hostname === 'localhost';\r\n}\r\n\r\nexport const STEALTH_ANNOUNCER_ABI = [\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"_devAddress\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"constructor\"\r\n },\r\n {\r\n \"anonymous\": false,\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"senderPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"spendingPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"stealthAddress\",\r\n \"type\": \"address\"\r\n },\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"timestamp\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"name\": \"StealthPaymentAnnounced\",\r\n \"type\": \"event\"\r\n },\r\n {\r\n \"anonymous\": false,\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"newAddress\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"name\": \"DevAddressUpdated\",\r\n \"type\": \"event\"\r\n },\r\n {\r\n \"anonymous\": false,\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"newFee\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"name\": \"DevFeeUpdated\",\r\n \"type\": \"event\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"senderPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"spendingPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"stealthAddress\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"name\": \"announcePayment\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"payable\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [],\r\n \"name\": \"devAddress\",\r\n \"outputs\": [\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [],\r\n \"name\": \"devFee\",\r\n \"outputs\": [\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [],\r\n \"name\": \"getAnnouncementsCount\",\r\n \"outputs\": [\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"fromIndex\",\r\n \"type\": \"uint256\"\r\n },\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"toIndex\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"name\": \"getAnnouncementsInRange\",\r\n \"outputs\": [\r\n {\r\n \"components\": [\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"senderPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"spendingPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"stealthAddress\",\r\n \"type\": \"address\"\r\n },\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"timestamp\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"internalType\": \"struct StealthAnnouncer.StealthAnnouncement[]\",\r\n \"name\": \"\",\r\n \"type\": \"tuple[]\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"_newFee\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"name\": \"updateDevFee\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"_newAddress\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"name\": \"updateDevAddress\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [],\r\n \"name\": \"withdrawStuckETH\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"function\"\r\n }\r\n];\r\n\r\nexport const PROOF_OF_INTEGRITY_ABI = [\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"bytes[]\",\r\n \"name\": \"nodeIds\",\r\n \"type\": \"bytes[]\"\r\n },\r\n {\r\n \"internalType\": \"bytes32[]\",\r\n \"name\": \"contentHashes\",\r\n \"type\": \"bytes32[]\"\r\n }\r\n ],\r\n \"name\": \"batchUpdateData\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"anonymous\": false,\r\n \"inputs\": [\r\n {\r\n \"indexed\": true,\r\n \"internalType\": \"bytes\",\r\n \"name\": \"nodeId\",\r\n \"type\": \"bytes\"\r\n },\r\n {\r\n \"indexed\": false,\r\n \"internalType\": \"bytes32\",\r\n \"name\": \"contentHash\",\r\n \"type\": \"bytes32\"\r\n },\r\n {\r\n \"indexed\": false,\r\n \"internalType\": \"address\",\r\n \"name\": \"updater\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"name\": \"DataUpdated\",\r\n \"type\": \"event\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"bytes\",\r\n \"name\": \"nodeId\",\r\n \"type\": \"bytes\"\r\n }\r\n ],\r\n \"name\": \"getLatestRecord\",\r\n \"outputs\": [\r\n {\r\n \"internalType\": \"bytes32\",\r\n \"name\": \"\",\r\n \"type\": \"bytes32\"\r\n },\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"\",\r\n \"type\": \"uint256\"\r\n },\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"bytes\",\r\n \"name\": \"nodeId\",\r\n \"type\": \"bytes\"\r\n },\r\n {\r\n \"internalType\": \"bytes32\",\r\n \"name\": \"contentHash\",\r\n \"type\": \"bytes32\"\r\n }\r\n ],\r\n \"name\": \"updateData\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"bytes\",\r\n \"name\": \"nodeId\",\r\n \"type\": \"bytes\"\r\n },\r\n {\r\n \"internalType\": \"bytes32\",\r\n \"name\": \"contentHash\",\r\n \"type\": \"bytes32\"\r\n }\r\n ],\r\n \"name\": \"verifyData\",\r\n \"outputs\": [\r\n {\r\n \"internalType\": \"bool\",\r\n \"name\": \"\",\r\n \"type\": \"bool\"\r\n },\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"\",\r\n \"type\": \"uint256\"\r\n },\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n }\r\n];\r\n","// =============================================\r\n// IMPORTS AND GLOBAL VARIABLES\r\n// =============================================\r\nimport Gun from \"gun\";\r\nimport SEA from \"gun/sea.js\";\r\nimport { ethers } from \"ethers\";\r\nimport { PROOF_OF_INTEGRITY_ABI, STEALTH_ANNOUNCER_ABI, getAddressesForChain } from \"./abis/abis.js\";\r\nimport { LOCAL_CONFIG } from \"./config/local.js\";\r\n\r\n// Ottieni gli indirizzi corretti per la chain\r\nconst chainConfig = getAddressesForChain('optimismSepolia'); // o la chain desiderata\r\nconst STEALTH_ANNOUNCER_ADDRESS = chainConfig.STEALTH_ANNOUNCER_ADDRESS;\r\nconst PROOF_OF_INTEGRITY_ADDRESS = chainConfig.PROOF_OF_INTEGRITY_ADDRESS;\r\n\r\nlet PROOF_CONTRACT_ADDRESS;\r\nlet rpcUrl = \"\";\r\nlet privateKey = \"\";\r\n\r\nexport const MESSAGE_TO_SIGN = \"Access GunDB with Ethereum\";\r\n\r\nlet contractAddresses = {\r\n PROOF_OF_INTEGRITY_ADDRESS: null,\r\n STEALTH_ANNOUNCER_ADDRESS: STEALTH_ANNOUNCER_ADDRESS\r\n};\r\n\r\n// Solo per Node.js\r\nif (typeof window === 'undefined') {\r\n const { fileURLToPath } = require('url');\r\n const { dirname } = require('path');\r\n const { readFileSync } = require('fs');\r\n const path = require('path');\r\n \r\n const __filename = fileURLToPath(import.meta.url);\r\n const __dirname = dirname(__filename);\r\n\r\n try {\r\n const rawdata = readFileSync(path.join(__dirname, 'contract-address.json'), 'utf8');\r\n contractAddresses = JSON.parse(rawdata);\r\n console.log('Loaded contract addresses:', contractAddresses);\r\n } catch (err) {\r\n console.warn('Warning: contract-address.json not found or invalid');\r\n }\r\n}\r\n\r\n// =============================================\r\n// UTILITY FUNCTIONS\r\n// =============================================\r\n/**\r\n * Generates a random node ID for GunDB\r\n * @returns {string} A random hexadecimal string\r\n */\r\nexport function generateRandomId() {\r\n return ethers.hexlify(ethers.randomBytes(32)).slice(2);\r\n}\r\n\r\n/**\r\n * Generates a password from a signature.\r\n * @param {string} signature - The signature to derive the password from.\r\n * @returns {string|null} The generated password or null if generation fails.\r\n */\r\nexport function generatePassword(signature) {\r\n try {\r\n const hexSignature = ethers.hexlify(signature);\r\n const hash = ethers.keccak256(hexSignature);\r\n console.log(\"Generated password:\", hash);\r\n return hash;\r\n } catch (error) {\r\n console.error(\"Error generating password:\", error);\r\n return null;\r\n }\r\n}\r\n\r\n/**\r\n * Converts a Gun private key to an Ethereum account.\r\n * @param {string} gunPrivateKey - The Gun private key in base64url format.\r\n * @returns {Object} An object containing the Ethereum account and public key.\r\n */\r\nexport function gunToEthAccount(gunPrivateKey) {\r\n // Function to convert base64url to hex\r\n const base64UrlToHex = (base64url) => {\r\n const padding = \"=\".repeat((4 - (base64url.length % 4)) % 4);\r\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\") + padding;\r\n const binary = atob(base64);\r\n return Array.from(binary, (char) =>\r\n char.charCodeAt(0).toString(16).padStart(2, \"0\")\r\n ).join(\"\");\r\n };\r\n\r\n // Convert Gun private key to hex format\r\n const hexPrivateKey = \"0x\" + base64UrlToHex(gunPrivateKey);\r\n\r\n // Create an Ethereum wallet from the private key\r\n const wallet = new ethers.Wallet(hexPrivateKey);\r\n\r\n // Get the public address (public key)\r\n const publicKey = wallet.address;\r\n\r\n return {\r\n account: wallet,\r\n publicKey: publicKey,\r\n privateKey: hexPrivateKey,\r\n };\r\n}\r\n\r\n/**\r\n * Gets an Ethereum signer based on current configuration\r\n * @returns {Promise<ethers.Signer>} The configured signer\r\n * @throws {Error} If no valid provider is found\r\n */\r\nexport const getSigner = async () => {\r\n if (rpcUrl && privateKey) {\r\n // Standalone mode with local provider\r\n const provider = new ethers.JsonRpcProvider(rpcUrl, {\r\n chainId: LOCAL_CONFIG.CHAIN_ID,\r\n name: \"localhost\"\r\n });\r\n return new ethers.Wallet(privateKey, provider);\r\n } else if (\r\n typeof window !== \"undefined\" &&\r\n typeof window.ethereum !== \"undefined\"\r\n ) {\r\n // Browser mode\r\n await window.ethereum.request({ method: \"eth_requestAccounts\" });\r\n const provider = new ethers.BrowserProvider(window.ethereum);\r\n return provider.getSigner();\r\n } else {\r\n throw new Error(\"No valid Ethereum provider found\");\r\n }\r\n};\r\n\r\n/**\r\n * Utility function to generate stealth address\r\n * @param {string} sharedSecret - The shared secret\r\n * @param {string} spendingPublicKey - The spending public key\r\n * @returns {Object} The stealth address and private key\r\n */\r\nexport function deriveStealthAddress(sharedSecret, spendingPublicKey) {\r\n try {\r\n // Convert shared secret to bytes\r\n const sharedSecretBytes = Buffer.from(sharedSecret, 'base64');\r\n \r\n // Generate stealth private key using shared secret and spending public key\r\n const stealthPrivateKey = ethers.keccak256(\r\n ethers.concat([\r\n sharedSecretBytes,\r\n ethers.getBytes(spendingPublicKey)\r\n ])\r\n );\r\n \r\n // Create stealth wallet\r\n const stealthWallet = new ethers.Wallet(stealthPrivateKey);\r\n\r\n console.log(\"Debug deriveStealthAddress:\", {\r\n sharedSecretHex: ethers.hexlify(sharedSecretBytes),\r\n spendingPublicKey,\r\n stealthPrivateKey,\r\n stealthAddress: stealthWallet.address\r\n });\r\n\r\n return {\r\n stealthPrivateKey,\r\n stealthAddress: stealthWallet.address,\r\n wallet: stealthWallet\r\n };\r\n } catch (error) {\r\n console.error(\"Error in deriveStealthAddress:\", error);\r\n throw error;\r\n }\r\n}\r\n\r\n// =============================================\r\n// BASIC GUN-ETH CHAIN METHODS\r\n// =============================================\r\n\r\n// Set the message to sign\r\nGun.chain.MESSAGE_TO_SIGN = MESSAGE_TO_SIGN;\r\n\r\n/**\r\n * Sets standalone configuration for Gun.\r\n * @param {string} newRpcUrl - The new RPC URL.\r\n * @param {string} newPrivateKey - The new private key.\r\n * @returns {Gun} The Gun instance for chaining.\r\n */\r\nGun.chain.setSigner = function (newRpcUrl, newPrivateKey) {\r\n rpcUrl = newRpcUrl;\r\n privateKey = newPrivateKey;\r\n console.log(\"Standalone configuration set\");\r\n return this;\r\n};\r\n\r\nGun.chain.getSigner = getSigner();\r\n\r\n/**\r\n * Verifies an Ethereum signature.\r\n * @param {string} message - The original message that was signed.\r\n * @param {string} signature - The signature to verify.\r\n * @returns {Promise<string|null>} The recovered address or null if verification fails.\r\n */\r\nGun.chain.verifySignature = async function (message, signature) {\r\n try {\r\n const recoveredAddress = ethers.verifyMessage(message, signature);\r\n return recoveredAddress;\r\n } catch (error) {\r\n console.error(\"Error verifying signature:\", error);\r\n return null;\r\n }\r\n};\r\n\r\n/**\r\n * Generates a password from a signature.\r\n * @param {string} signature - The signature to derive the password from.\r\n * @returns {string|null} The generated password or null if generation fails.\r\n */\r\nGun.chain.generatePassword = function (signature) {\r\n return generatePassword(signature);\r\n};\r\n\r\n/**\r\n * Creates an Ethereum signature for a given message.\r\n * @param {string} message - The message to sign.\r\n * @returns {Promise<string|null>} The signature or null if signing fails.\r\n */\r\nGun.chain.createSignature = async function (message) {\r\n try {\r\n // Check if message matches MESSAGE_TO_SIGN\r\n if (message !== MESSAGE_TO_SIGN) {\r\n throw new Error(\"Invalid message, valid message is: \" + MESSAGE_TO_SIGN);\r\n }\r\n const signer = await getSigner();\r\n const signature = await signer.signMessage(message);\r\n console.log(\"Signature created:\", signature);\r\n return signature;\r\n } catch (error) {\r\n console.error(\"Error creating signature:\", error);\r\n return null;\r\n }\r\n};\r\n\r\n// =============================================\r\n// KEY PAIR MANAGEMENT\r\n// =============================================\r\n/**\r\n * Creates and stores an encrypted key pair for a given address.\r\n * @param {string} address - The Ethereum address to associate with the key pair.\r\n * @param {string} signature - The signature to use for encryption.\r\n * @returns {Promise<void>}\r\n */\r\nGun.chain.createAndStoreEncryptedPair = async function (address, signature) {\r\n try {\r\n const gun = this;\r\n const pair = await SEA.pair();\r\n const v_pair = await SEA.pair();\r\n const s_pair = await SEA.pair();\r\n const password = generatePassword(signature);\r\n\r\n // Save original SEA pairs\r\n const encryptedPair = await SEA.encrypt(JSON.stringify(pair), password);\r\n const encryptedV_pair = await SEA.encrypt(JSON.stringify(v_pair), password);\r\n const encryptedS_pair = await SEA.encrypt(JSON.stringify(s_pair), password);\r\n\r\n // Convert only to get Ethereum addresses\r\n const viewingAccount = gunToEthAccount(v_pair.priv);\r\n const spendingAccount = gunToEthAccount(s_pair.priv);\r\n\r\n gun.get(\"gun-eth\").get(\"users\").get(address).put({\r\n pair: encryptedPair,\r\n v_pair: encryptedV_pair,\r\n s_pair: encryptedS_pair,\r\n publicKeys: {\r\n viewingPublicKey: v_pair.epub, // Use SEA encryption public key\r\n viewingPublicKey: v_pair.epub, // Use SEA encryption public key\r\n spendingPublicKey: spendingAccount.publicKey, // Use Ethereum address\r\n ethViewingAddress: viewingAccount.publicKey // Also save Ethereum address\r\n }\r\n });\r\n\r\n console.log(\"Encrypted pairs and public keys stored for:\", address);\r\n } catch (error) {\r\n console.error(\"Error creating and storing encrypted pair:\", error);\r\n throw error;\r\n }\r\n};\r\n\r\n/**\r\n * Retrieves and decrypts a stored key pair for a given address.\r\n * @param {string} address - The Ethereum address associated with the key pair.\r\n * @param {string} signature - The signature to use for decryption.\r\n * @returns {Promise<Object|null>} The decrypted key pair or null if retrieval fails.\r\n */\r\nGun.chain.getAndDecryptPair = async function (address, signature) {\r\n try {\r\n const gun = this;\r\n const encryptedData = await gun\r\n .get(\"gun-eth\")\r\n .get(\"users\")\r\n .get(address)\r\n .get(\"pair\")\r\n .then();\r\n if (!encryptedData) {\r\n throw new Error(\"No encrypted data found for this address\");\r\n }\r\n const password = generatePassword(signature);\r\n const decryptedPair = await SEA.decrypt(encryptedData, password);\r\n console.log(decryptedPair);\r\n return decryptedPair;\r\n } catch (error) {\r\n console.error(\"Error retrieving and decrypting pair:\", error);\r\n return null;\r\n }\r\n};\r\n\r\n// =============================================\r\n// PROOF OF INTEGRITY\r\n// =============================================\r\n/**\r\n * Proof of Integrity\r\n * @param {string} chain - The blockchain to use (e.g., \"optimismSepolia\").\r\n * @param {string} nodeId - The ID of the node to verify or write.\r\n * @param {Object} data - The data to write (if writing).\r\n * @param {Function} callback - Callback function to handle the result.\r\n * @returns {Gun} The Gun instance for chaining.\r\n */\r\nGun.chain.proof = function (chain, nodeId, data, callback) {\r\n console.log(\"Proof plugin called with:\", { chain, nodeId, data });\r\n\r\n if (typeof callback !== \"function\") {\r\n console.error(\"Callback must be a function\");\r\n return this;\r\n }\r\n\r\n try {\r\n // Se siamo in localhost e in development, usa automaticamente la chain locale\r\n const targetChain = isLocalEnvironment() ? 'localhost' : chain;\r\n const chainConfig = getAddressesForChain(targetChain);\r\n \r\n console.log(`Using ${targetChain} configuration:`, chainConfig);\r\n\r\n // Usa gli indirizzi dalla configurazione\r\n const contract = new ethers.Contract(\r\n chainConfig.PROOF_OF_INTEGRITY_ADDRESS,\r\n PROOF_OF_INTEGRITY_ABI,\r\n signer\r\n );\r\n\r\n // Funzione per verificare on-chain\r\n const verifyOnChain = async (nodeId, contentHash) => {\r\n console.log(\"Verifying on chain:\", { nodeId, contentHash });\r\n const signer = await getSigner();\r\n const contract = new ethers.Contract(\r\n PROOF_CONTRACT_ADDRESS,\r\n PROOF_OF_INTEGRITY_ABI,\r\n signer\r\n );\r\n const [isValid, timestamp, updater] = await contract.verifyData(\r\n ethers.toUtf8Bytes(nodeId),\r\n contentHash\r\n );\r\n console.log(\"Verification result:\", { isValid, timestamp, updater });\r\n return { isValid, timestamp, updater };\r\n };\r\n\r\n // Funzione per scrivere on-chain\r\n const writeOnChain = async (nodeId, contentHash) => {\r\n console.log(\"Writing on chain:\", { nodeId, contentHash });\r\n const signer = await getSigner();\r\n const contract = new ethers.Contract(\r\n PROOF_CONTRACT_ADDRESS,\r\n PROOF_OF_INTEGRITY_ABI,\r\n signer\r\n );\r\n const tx = await contract.updateData(\r\n ethers.toUtf8Bytes(nodeId),\r\n contentHash\r\n );\r\n console.log(\"Transaction sent:\", tx.hash);\r\n const receipt = await tx.wait();\r\n console.log(\"Transaction confirmed:\", receipt);\r\n return tx;\r\n };\r\n\r\n // Funzione per ottenere l'ultimo record\r\n const getLatestRecord = async (nodeId) => {\r\n const signer = await getSigner();\r\n const contract = new ethers.Contract(\r\n PROOF_CONTRACT_ADDRESS,\r\n PROOF_OF_INTEGRITY_ABI,\r\n signer\r\n );\r\n const [contentHash, timestamp, updater] = await contract.getLatestRecord(\r\n ethers.toUtf8Bytes(nodeId)\r\n );\r\n console.log(\"Latest record from blockchain:\", {\r\n nodeId,\r\n contentHash,\r\n timestamp,\r\n updater,\r\n });\r\n return { contentHash, timestamp, updater };\r\n };\r\n\r\n \r\n if (nodeId && !data) {\r\n // Case 1: User passes only node\r\n gun.get(nodeId).once(async (existingData) => {\r\n if (!existingData) {\r\n if (callback) callback({ err: \"Node not found in GunDB\" });\r\n return;\r\n }\r\n\r\n console.log(\"existingData\", existingData);\r\n\r\n // Use stored contentHash instead of recalculating\r\n const contentHash = existingData._contentHash;\r\n console.log(\"contentHash\", contentHash);\r\n\r\n if (!contentHash) {\r\n if (callback) callback({ err: \"No content hash found for this node\" });\r\n return;\r\n }\r\n\r\n try {\r\n const { isValid, timestamp, updater } = await verifyOnChain(\r\n nodeId,\r\n contentHash\r\n );\r\n const latestRecord = await getLatestRecord(nodeId);\r\n\r\n if (isValid) {\r\n if (callback)\r\n callback({\r\n ok: true,\r\n message: \"Data verified on blockchain\",\r\n timestamp,\r\n updater,\r\n latestRecord,\r\n });\r\n } else {\r\n if (callback)\r\n callback({\r\n ok: false,\r\n message: \"Data not verified on blockchain\",\r\n latestRecord,\r\n });\r\n }\r\n } catch (error) {\r\n if (callback) callback({ err: error.message });\r\n }\r\n });\r\n } else if (data && !nodeId) {\r\n // Case 2: User passes only text (data)\r\n const newNodeId = generateRandomId();\r\n const dataString = JSON.stringify(data);\r\n const contentHash = ethers.keccak256(ethers.toUtf8Bytes(dataString));\r\n\r\n gun\r\n .get(newNodeId)\r\n .put({ ...data, _contentHash: contentHash }, async (ack) => {\r\n console.log(\"ack\", ack);\r\n if (ack.err) {\r\n if (callback) callback({ err: \"Error saving data to GunDB\" });\r\n return;\r\n }\r\n\r\n try {\r\n const tx = await writeOnChain(newNodeId, contentHash);\r\n if (callback)\r\n callback({\r\n ok: true,\r\n message: \"Data written to GunDB and blockchain\",\r\n nodeId: newNodeId,\r\n txHash: tx.hash,\r\n });\r\n } catch (error) {\r\n if (callback) callback({ err: error.message });\r\n }\r\n });\r\n } else {\r\n if (callback)\r\n callback({\r\n err: \"Invalid input. Provide either nodeId or data, not both.\",\r\n });\r\n }\r\n\r\n return gun;\r\n } catch (error) {\r\n callback({ err: error.message });\r\n return this;\r\n }\r\n};\r\n\r\n// =============================================\r\n// STEALTH ADDRESS CORE FUNCTIONS\r\n// =============================================\r\n/**\r\n * Converts a Gun private key to an Ethereum account.\r\n * @param {string} gunPrivateKey - The Gun private key in base64url format.\r\n * @returns {Object} An object containing the Ethereum account and public key.\r\n */\r\nGun.chain.gunToEthAccount = function (gunPrivateKey) {\r\n return gunToEthAccount(gunPrivateKey);\r\n};\r\n\r\n/**\r\n * Generate a stealth key and related key pairs\r\n * @param {string} recipientAddress - The recipient's Ethereum address\r\n * @param {string} signature - The sender's signature to access their keys\r\n * @returns {Promise<Object>} Object containing stealth addresses and keys\r\n */\r\nGun.chain.generateStealthAddress = async function (recipientAddress, signature) {\r\n try {\r\n const gun = this;\r\n \r\n // Get recipient's public keys\r\n const recipientData = await gun\r\n .get(\"gun-eth\")\r\n .get(\"users\")\r\n .get(recipientAddress)\r\n .get(\"publicKeys\")\r\n .then();\r\n\r\n if (!recipientData || !recipientData.viewingPublicKey || !recipientData.spendingPublicKey) {\r\n throw new Error(\"Recipient's public keys not found\");\r\n }\r\n\r\n // Get sender's keys\r\n const senderAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);\r\n const password = generatePassword(signature);\r\n \r\n const senderData = await gun\r\n .get(\"gun-eth\")\r\n .get(\"users\")\r\n .get(senderAddress)\r\n .then();\r\n\r\n if (!senderData || !senderData.s_pair) {\r\n throw new Error(\"Sender's keys not found\");\r\n }\r\n\r\n // Decrypt sender's spending pair\r\n let spendingKeyPair;\r\n try {\r\n const decryptedData = await SEA.decrypt(senderData.s_pair, password);\r\n spendingKeyPair = typeof decryptedData === 'string' ? \r\n JSON.parse(decryptedData) : \r\n decryptedData;\r\n } catch (error) {\r\n console.error(\"Error decrypting spending pair:\", error);\r\n throw new Error(\"Unable to decrypt spending pair\");\r\n }\r\n\r\n // Generate shared secret using SEA ECDH with encryption public key\r\n const sharedSecret = await SEA.secret(recipientData.viewingPublicKey, spendingKeyPair);\r\n\r\n if (!sharedSecret) {\r\n throw new Error(\"Unable to generate shared secret\");\r\n }\r\n\r\n console.log(\"Generate shared secret:\", sharedSecret);\r\n\r\n const { stealthAddress } = deriveStealthAddress(\r\n sharedSecret,\r\n recipientData.spendingPublicKey\r\n );\r\n\r\n return {\r\n stealthAddress,\r\n senderPublicKey: spendingKeyPair.epub, // Use encryption public key\r\n spendingPublicKey: recipientData.spendingPublicKey\r\n };\r\n\r\n } catch (error) {\r\n console.error(\"Error generating stealth address:\", error);\r\n throw error;\r\n }\r\n};\r\n\r\n/**\r\n * Publish public keys needed to receive stealth payments\r\n * @param {string} signature - The signature to authenticate the user\r\n * @returns {Promise<void>}\r\n */\r\nGun.chain.publishStealthKeys = async function (signature) {\r\n try {\r\n const gun = this;\r\n const address = await this.verifySignature(MESSAGE_TO_SIGN, signature);\r\n const password = generatePassword(signature);\r\n\r\n // Get encrypted key pairs\r\n const encryptedData = await gun\r\n .get(\"gun-eth\")\r\n .get(\"users\")\r\n .get(address)\r\n .then();\r\n\r\n if (!encryptedData || !encryptedData.v_pair || !encryptedData.s_pair) {\r\n throw new Error(\"Keys not found\");\r\n }\r\n\r\n // Decrypt viewing and spending pairs\r\n const viewingKeyPair = JSON.parse(\r\n await SEA.decrypt(encryptedData.v_pair, password)\r\n );\r\n const spendingKeyPair = JSON.parse(\r\n await SEA.decrypt(encryptedData.s_pair, password)\r\n );\r\n\r\n const viewingAccount = gunToEthAccount(viewingKeyPair.priv);\r\n const spendingAccount = gunToEthAccount(spendingKeyPair.priv);\r\n\r\n // Publish only public keys\r\n gun.get(\"gun-eth\").get(\"users\").get(address).get(\"publicKeys\").put({\r\n viewingPublicKey: viewingAccount.publicKey,\r\n spendingPublicKey: spendingAccount.publicKey,\r\n });\r\n\r\n console.log(\"Stealth public keys published successfully\");\r\n } catch (error) {\r\n console.error(\"Error publishing stealth keys:\", error);\r\n throw error;\r\n }\r\n};\r\n\r\n// =============================================\r\n// STEALTH PAYMENT FUNCTIONS\r\n// =============================================\r\n/**\r\n * Recover funds from a stealth address\r\n * @param {string} stealthAddress - The stealth address to recover funds from\r\n * @param {string} senderPublicKey - The sender's public key used to generate the address\r\n * @param {string} signature - The signature to decrypt private keys\r\n * @returns {Promise<Object>} Object containing wallet to access funds\r\n */\r\nGun.chain.recoverStealthFunds = async function (\r\n stealthAddress,\r\n senderPublicKey,\r\n signature,\r\n spendingPublicKey\r\n) {\r\n try {\r\n const gun = this;\r\n const password = generatePassword(signature);\r\n\r\n // Get own key pairs\r\n const myAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);\r\n const encryptedData = await gun\r\n .get(\"gun-eth\")\r\n .get(\"users\")\r\n .get(myAddress)\r\n .then();\r\n\r\n if (!encryptedData || !encryptedData.v_pair || !encryptedData.s_pair) {\r\n throw new Error(\"Keys not found\");\r\n }\r\n\r\n // Decrypt viewing and spending pairs\r\n let viewingKeyPair;\r\n try {\r\n const decryptedViewingData = await SEA.decrypt(encryptedData.v_pair, password);\r\n viewingKeyPair = typeof decryptedViewingData === 'string' ? \r\n JSON.parse(decryptedViewingData) : \r\n decryptedViewingData;\r\n } catch (error) {\r\n console.error(\"Error decrypting keys:\", error);\r\n throw new Error(\"Unable to decrypt keys\");\r\n }\r\n\r\n // Generate shared secret using SEA ECDH\r\n const sharedSecret = await SEA.secret(senderPublicKey, viewingKeyPair);\r\n\r\n if (!sharedSecret) {\r\n throw new Error(\"Unable to generate shared secret\");\r\n }\r\n\r\n console.log(\"Recover shared secret:\", sharedSecret);\r\n\r\n const { wallet, stealthAddress: recoveredAddress } = deriveStealthAddress(\r\n sharedSecret,\r\n spendingPublicKey\r\n );\r\n\r\n // Verify address matches\r\n if (recoveredAddress.toLowerCase() !== stealthAddress.toLowerCase()) {\r\n console.error(\"Mismatch:\", {\r\n recovered: recoveredAddress,\r\n expected: stealthAddress,\r\n sharedSecret\r\n });\r\n throw new Error(\"Recovered stealth address does not match\");\r\n }\r\n\r\n return {\r\n wallet,\r\n address: recoveredAddress,\r\n };\r\n } catch (error) {\r\n console.error(\"Error recovering stealth funds:\", error);\r\n throw error;\r\n }\r\n};\r\n\r\n/**\r\n * Announce a stealth payment\r\n * @param {string} stealthAddress - The generated stealth address\r\n * @param {string} senderPublicKey - The sender's public key\r\n * @param {string} spendingPublicKey - The spending public key\r\n * @param {string} signature - The sender's signature\r\n * @returns {Promise<void>}\r\n */\r\nGun.chain.announceStealthPayment = async function (\r\n stealthAddress,\r\n senderPublicKey,\r\n spendingPublicKey,\r\n signature,\r\n options = { onChain: false, chain: 'optimismSepolia' }\r\n) {\r\n try {\r\n const gun = this;\r\n const senderAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);\r\n\r\n if (options.onChain) {\r\n // On-chain announcement\r\n const signer = await getSigner();\r\n const chainAddresses = getAddressesForChain(options.chain);\r\n const contractAddress = chainAddresses.STEALTH_ANNOUNCER_ADDRESS;\r\n\r\n console.log(\"Using contract address:\", contractAddress);\r\n\r\n const contract = new ethers.Contract(\r\n contractAddress,\r\n STEALTH_ANNOUNCER_ABI,\r\n signer\r\n );\r\n\r\n // Get dev fee from contract\r\n const devFee = await contract.devFee();\r\n console.log(\"Dev fee:\", devFee.toString());\r\n\r\n // Call contract\r\n const tx = await contract.announcePayment(\r\n senderPublicKey,\r\n spendingPublicKey,\r\n stealthAddress,\r\n { value: devFee }\r\n );\r\n \r\n console.log(\"Transaction sent:\", tx.hash);\r\n const receipt = await tx.wait();\r\n console.log(\"Transaction confirmed:\", receipt.hash);\r\n \r\n console.log(\"Stealth payment announced on-chain (dev fee paid)\");\r\n } else {\r\n // Off-chain announcement (GunDB)\r\n gun\r\n .get(\"gun-eth\")\r\n .get(\"stealth-payments\")\r\n .set({\r\n stealthAddress,\r\n senderAddress,\r\n senderPublicKey,\r\n spendingPublicKey,\r\n timestamp: Date.now(),\r\n });\r\n console.log(\"Stealth payment announced off-chain\");\r\n }\r\n } catch (error) {\r\n console.error(\"Error announcing stealth payment:\", error);\r\n console.error(\"Error details:\", error.stack);\r\n throw error;\r\n }\r\n};\r\n\r\n/**\r\n * Get all stealth payments for an address\r\n * @param {string} signature - The signature to authenticate the user\r\n * @returns {Promise<Array>} List of stealth payments\r\n */\r\nGun.chain.getStealthPayments = async function (signature, options = { source: 'both' }) {\r\n try {\r\n const payments = [];\r\n\r\n if (options.source === 'onChain' || options.source === 'both') {\r\n // Get on-chain payments\r\n const signer = await getSigner();\r\n const contractAddress = process.env.NODE_ENV === 'development' \r\n ? LOCAL_CONFIG.STEALTH_ANNOUNCER_ADDRESS \r\n : STEALTH_ANNOUNCER_ADDRESS;\r\n\r\n const contract = new ethers.Contract(\r\n contractAddress,\r\n STEALTH_ANNOUNCER_ABI,\r\n signer\r\n );\r\n \r\n try {\r\n // Get total number of announcements\r\n const totalAnnouncements = await contract.getAnnouncementsCount();\r\n const totalCount = Number(totalAnnouncements.toString());\r\n console.log(\"Total on-chain announcements:\", totalCount);\r\n \r\n if (totalCount > 0) {\r\n // Get announcements in batches of 100\r\n const batchSize = 100;\r\n const lastIndex = totalCount - 1;\r\n \r\n for(let i = 0; i <= lastIndex; i += batchSize) {\r\n const toIndex = Math.min(i + batchSize - 1, lastIndex);\r\n const batch = await contract.getAnnouncementsInRange(i, toIndex);\r\n \r\n // For each announcement, try to decrypt\r\n for(const announcement of batch) {\r\n try {\r\n // Verify announcement is valid\r\n if (!announcement || !announcement.stealthAddress || \r\n !announcement.senderPublicKey || !announcement.spendingPublicKey) {\r\n console.log(\"Invalid announcement:\", announcement);\r\n continue;\r\n }\r\n\r\n // Try to recover funds to verify if announcement is for us\r\n const recoveredWallet = await this.recoverStealthFunds(\r\n announcement.stealthAddress,\r\n announcement.senderPublicKey,\r\n signature,\r\n announcement.spendingPublicKey\r\n );\r\n \r\n // If no errors thrown, announcement is for us\r\n payments.push({\r\n stealthAddress: announcement.stealthAddress,\r\n senderPublicKey: announcement.senderPublicKey,\r\n spendingPublicKey: announcement.spendingPublicKey,\r\n timestamp: Number(announcement.timestamp),\r\n source: 'onChain',\r\n wallet: recoveredWallet\r\n });\r\n\r\n } catch (e) {\r\n // Not for us, continue\r\n console.log(`Announcement not for us: ${announcement.stealthAddress}`);\r\n continue;\r\n }\r\n }\r\n }\r\n }\r\n } catch (error) {\r\n console.error(\"Error retrieving on-chain announcements:\", error);\r\n }\r\n }\r\n\r\n if (options.source === 'offChain' || options.source === 'both') {\r\n // Get off-chain payments\r\n const gun = this;\r\n const offChainPayments = await new Promise((resolve) => {\r\n const p = [];\r\n gun\r\n .get(\"gun-eth\")\r\n .get(\"stealth-payments\")\r\n .get(recipientAddress)\r\n .map()\r\n .once((payment, id) => {\r\n if (payment?.stealthAddress) {\r\n p.push({ ...payment, id, source: 'offChain' });\r\n }\r\n });\r\n setTimeout(() => resolve(p), 2000);\r\n });\r\n \r\n payments.push(...offChainPayments);\r\n }\r\n\r\n console.log(`Found ${payments.length} stealth payments`);\r\n return payments;\r\n } catch (error) {\r\n console.error(\"Error retrieving stealth payments:\", error);\r\n throw error;\r\n }\r\n};\r\n\r\n/**\r\n * Clean up old stealth payments\r\n * @param {string} recipientAddress - The recipient's address\r\n * @returns {Promise<void>}\r\n */\r\nGun.chain.cleanStealthPayments = async function(recipientAddress) {\r\n try {\r\n const gun = this;\r\n const payments = await gun\r\n .get(\"gun-eth\")\r\n .get(\"stealth-payments\")\r\n .get(recipientAddress)\r\n .map()\r\n .once()\r\n .then();\r\n\r\n // Remove empty or invalid nodes\r\n if (payments) {\r\n Object.keys(payments).forEach(async (key) => {\r\n const payment = payments[key];\r\n if (!payment || !payment.stealthAddress || !payment.senderPublicKey || !payment.spendingPublicKey) {\r\n await gun\r\n .get(\"gun-eth\")\r\n .get(\"stealth-payments\")\r\n .get(recipientAddress)\r\n .get(key)\r\n .put(null);\r\n }\r\n });\r\n }\r\n } catch (error) {\r\n console.error(\"Error cleaning stealth payments:\", error);\r\n }\r\n};\r\n\r\n// =============================================\r\n// EXPORTS\r\n// =============================================\r\n\r\n// Crea una classe GunEth che contiene tutti i metodi e le utility\r\nexport class GunEth {\r\n // Static utility methods\r\n static generateRandomId = generateRandomId;\r\n static generatePassword = generatePassword;\r\n static gunToEthAccount = gunToEthAccount;\r\n static getSigner = getSigner;\r\n static deriveStealthAddress = deriveStealthAddress;\r\n \r\n // Chain methods\r\n static chainMethods = {\r\n setSigner: Gun.chain.setSigner,\r\n getSigner: Gun.chain.getSigner,\r\n verifySignature: Gun.chain.verifySignature,\r\n generatePassword: Gun.chain.generatePassword,\r\n createSignature: Gun.chain.createSignature,\r\n createAndStoreEncryptedPair: Gun.chain.createAndStoreEncryptedPair,\r\n getAndDecryptPair: Gun.chain.getAndDecryptPair,\r\n proof: Gun.chain.proof,\r\n gunToEthAccount: Gun.chain.gunToEthAccount,\r\n generateStealthAddress: Gun.chain.generateStealthAddress,\r\n publishStealthKeys: Gun.chain.publishStealthKeys,\r\n recoverStealthFunds: Gun.chain.recoverStealthFunds,\r\n announceStealthPayment: Gun.chain.announceStealthPayment,\r\n getStealthPayments: Gun.chain.getStealthPayments,\r\n cleanStealthPayments: Gun.chain.cleanStealthPayments\r\n };\r\n\r\n // Constants\r\n static MESSAGE_TO_SIGN = MESSAGE_TO_SIGN;\r\n static PROOF_CONTRACT_ADDRESS = PROOF_CONTRACT_ADDRESS;\r\n static LOCAL_CONFIG = LOCAL_CONFIG;\r\n}\r\n\r\n// Esporta Gun come default\r\nexport default Gun;\r\n"],"names":["contractAddresses","PROOF_OF_INTEGRITY_ADDRESS","STEALTH_ANNOUNCER_ADDRESS","window","fileURLToPath","require","dirname","readFileSync","join","__filename","document","location","pathToFileURL","href","_documentCurrentScript","tagName","toUpperCase","src","URL","baseURI","rawdata","JSON","parse","console","log","error","warn","LOCAL_CONFIG","CHAIN_ID","RPC_URL","GUN_PEER","CHAIN_CONFIG","optimismSepolia","arbitrumSepolia","localhost","getAddressesForChain","chainName","config","require$$0","err","Error","Object","keys","STEALTH_ANNOUNCER_ABI","inputs","internalType","name","type","stateMutability","anonymous","outputs","components","PROOF_OF_INTEGRITY_ABI","indexed","chainConfig","PROOF_CONTRACT_ADDRESS","rpcUrl","privateKey","MESSAGE_TO_SIGN","path","__dirname","generateRandomId","ethers","hexlify","randomBytes","slice","generatePassword","signature","hexSignature","hash","keccak256","gunToEthAccount","gunPrivateKey","hexPrivateKey","base64url","padding","repeat","length","base64","replace","binary","atob","Array","from","char","charCodeAt","toString","padStart","base64UrlToHex","wallet","Wallet","account","publicKey","address","getSigner","async","provider","JsonRpcProvider","chainId","ethereum","request","method","BrowserProvider","deriveStealthAddress","sharedSecret","spendingPublicKey","sharedSecretBytes","Buffer","stealthPrivateKey","concat","getBytes","stealthWallet","sharedSecretHex","stealthAddress","Gun","chain","setSigner","newRpcUrl","newPrivateKey","this","verifySignature","message","verifyMessage","createSignature","signer","signMessage","createAndStoreEncryptedPair","gun","pair","SEA","v_pair","s_pair","password","encryptedPair","encrypt","stringify","encryptedV_pair","encryptedS_pair","viewingAccount","priv","spendingAccount","get","put","publicKeys","viewingPublicKey","epub","ethViewingAddress","getAndDecryptPair","encryptedData","then","decryptedPair","decrypt","proof","nodeId","data","callback","targetChain","isLocalEnvironment","Contract","verifyOnChain","contentHash","contract","isValid","timestamp","updater","verifyData","toUtf8Bytes","writeOnChain","tx","updateData","receipt","wait","getLatestRecord","once","existingData","_contentHash","latestRecord","ok","newNodeId","dataString","ack","txHash","generateStealthAddress","recipientAddress","recipientData","senderAddress","senderData","spendingKeyPair","decryptedData","secret","senderPublicKey","publishStealthKeys","viewingKeyPair","recoverStealthFunds","myAddress","decryptedViewingData","recoveredAddress","toLowerCase","recovered","expected","announceStealthPayment","options","onChain","contractAddress","devFee","announcePayment","value","set","Date","now","stack","getStealthPayments","source","payments","process","env","NODE_ENV","totalAnnouncements","getAnnouncementsCount","totalCount","Number","batchSize","lastIndex","i","toIndex","Math","min","batch","getAnnouncementsInRange","announcement","recoveredWallet","push","e","offChainPayments","Promise","resolve","p","map","payment","id","setTimeout","cleanStealthPayments","forEach","key","GunEth","static"],"mappings":"0dAAA,IAAIA,EAAoB,CACtBC,2BAA4B,6CAC5BC,0BAA2B,8CAG7B,GAAsB,oBAAXC,OAAwB,CACjC,MAAMC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AAyB3L,EACzB2L,8BAAgC9L,EAChC8L,oBAAsB1N"}
|
1
|
+
{"version":3,"file":"gun-eth.min.js","sources":["../node_modules/gun/sea.js","../src/config/local.js","../src/abis/abis.js","../src/index.js"],"sourcesContent":[";(function(){\n\n /* UNBUILD */\n function USE(arg, req){\n return req? require(arg) : arg.slice? USE[R(arg)] : function(mod, path){\n arg(mod = {exports: {}});\n USE[R(path)] = mod.exports;\n }\n function R(p){\n return p.split('/').slice(-1).toString().replace('.js','');\n }\n }\n if(typeof module !== \"undefined\"){ var MODULE = module }\n /* UNBUILD */\n\n ;USE(function(module){\n // Security, Encryption, and Authorization: SEA.js\n // MANDATORY READING: https://gun.eco/explainers/data/security.html\n // IT IS IMPLEMENTED IN A POLYFILL/SHIM APPROACH.\n // THIS IS AN EARLY ALPHA!\n\n if(typeof self !== \"undefined\"){ module.window = self } // should be safe for at least browser/worker/nodejs, need to check other envs like RN etc.\n if(typeof window !== \"undefined\"){ module.window = window }\n\n var tmp = module.window || module, u;\n var SEA = tmp.SEA || {};\n\n if(SEA.window = module.window){ SEA.window.SEA = SEA }\n\n try{ if(u+'' !== typeof MODULE){ MODULE.exports = SEA } }catch(e){}\n module.exports = SEA;\n })(USE, './root');\n\n ;USE(function(module){\n var SEA = USE('./root');\n try{ if(SEA.window){\n if(location.protocol.indexOf('s') < 0\n && location.host.indexOf('localhost') < 0\n && ! /^127\\.\\d+\\.\\d+\\.\\d+$/.test(location.hostname)\n && location.protocol.indexOf('file:') < 0){\n console.warn('HTTPS needed for WebCrypto in SEA, redirecting...');\n location.protocol = 'https:'; // WebCrypto does NOT work without HTTPS!\n }\n } }catch(e){}\n })(USE, './https');\n\n ;USE(function(module){\n var u;\n if(u+''== typeof btoa){\n if(u+'' == typeof Buffer){\n try{ global.Buffer = USE(\"buffer\", 1).Buffer }catch(e){ console.log(\"Please `npm install buffer` or add it to your package.json !\") }\n }\n global.btoa = function(data){ return Buffer.from(data, \"binary\").toString(\"base64\") };\n global.atob = function(data){ return Buffer.from(data, \"base64\").toString(\"binary\") };\n }\n })(USE, './base64');\n\n ;USE(function(module){\n USE('./base64');\n // This is Array extended to have .toString(['utf8'|'hex'|'base64'])\n function SeaArray() {}\n Object.assign(SeaArray, { from: Array.from })\n SeaArray.prototype = Object.create(Array.prototype)\n SeaArray.prototype.toString = function(enc, start, end) { enc = enc || 'utf8'; start = start || 0;\n const length = this.length\n if (enc === 'hex') {\n const buf = new Uint8Array(this)\n return [ ...Array(((end && (end + 1)) || length) - start).keys()]\n .map((i) => buf[ i + start ].toString(16).padStart(2, '0')).join('')\n }\n if (enc === 'utf8') {\n return Array.from(\n { length: (end || length) - start },\n (_, i) => String.fromCharCode(this[ i + start])\n ).join('')\n }\n if (enc === 'base64') {\n return btoa(this)\n }\n }\n module.exports = SeaArray;\n })(USE, './array');\n\n ;USE(function(module){\n USE('./base64');\n // This is Buffer implementation used in SEA. Functionality is mostly\n // compatible with NodeJS 'safe-buffer' and is used for encoding conversions\n // between binary and 'hex' | 'utf8' | 'base64'\n // See documentation and validation for safe implementation in:\n // https://github.com/feross/safe-buffer#update\n var SeaArray = USE('./array');\n function SafeBuffer(...props) {\n console.warn('new SafeBuffer() is depreciated, please use SafeBuffer.from()')\n return SafeBuffer.from(...props)\n }\n SafeBuffer.prototype = Object.create(Array.prototype)\n Object.assign(SafeBuffer, {\n // (data, enc) where typeof data === 'string' then enc === 'utf8'|'hex'|'base64'\n from() {\n if (!Object.keys(arguments).length || arguments[0]==null) {\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n }\n const input = arguments[0]\n let buf\n if (typeof input === 'string') {\n const enc = arguments[1] || 'utf8'\n if (enc === 'hex') {\n const bytes = input.match(/([\\da-fA-F]{2})/g)\n .map((byte) => parseInt(byte, 16))\n if (!bytes || !bytes.length) {\n throw new TypeError('Invalid first argument for type \\'hex\\'.')\n }\n buf = SeaArray.from(bytes)\n } else if (enc === 'utf8' || 'binary' === enc) { // EDIT BY MARK: I think this is safe, tested it against a couple \"binary\" strings. This lets SafeBuffer match NodeJS Buffer behavior more where it safely btoas regular strings.\n const length = input.length\n const words = new Uint16Array(length)\n Array.from({ length: length }, (_, i) => words[i] = input.charCodeAt(i))\n buf = SeaArray.from(words)\n } else if (enc === 'base64') {\n const dec = atob(input)\n const length = dec.length\n const bytes = new Uint8Array(length)\n Array.from({ length: length }, (_, i) => bytes[i] = dec.charCodeAt(i))\n buf = SeaArray.from(bytes)\n } else if (enc === 'binary') { // deprecated by above comment\n buf = SeaArray.from(input) // some btoas were mishandled.\n } else {\n console.info('SafeBuffer.from unknown encoding: '+enc)\n }\n return buf\n }\n const byteLength = input.byteLength // what is going on here? FOR MARTTI\n const length = input.byteLength ? input.byteLength : input.length\n if (length) {\n let buf\n if (input instanceof ArrayBuffer) {\n buf = new Uint8Array(input)\n }\n return SeaArray.from(buf || input)\n }\n },\n // This is 'safe-buffer.alloc' sans encoding support\n alloc(length, fill = 0 /*, enc*/ ) {\n return SeaArray.from(new Uint8Array(Array.from({ length: length }, () => fill)))\n },\n // This is normal UNSAFE 'buffer.alloc' or 'new Buffer(length)' - don't use!\n allocUnsafe(length) {\n return SeaArray.from(new Uint8Array(Array.from({ length : length })))\n },\n // This puts together array of array like members\n concat(arr) { // octet array\n if (!Array.isArray(arr)) {\n throw new TypeError('First argument must be Array containing ArrayBuffer or Uint8Array instances.')\n }\n return SeaArray.from(arr.reduce((ret, item) => ret.concat(Array.from(item)), []))\n }\n })\n SafeBuffer.prototype.from = SafeBuffer.from\n SafeBuffer.prototype.toString = SeaArray.prototype.toString\n\n module.exports = SafeBuffer;\n })(USE, './buffer');\n\n ;USE(function(module){\n const SEA = USE('./root')\n const api = {Buffer: USE('./buffer')}\n var o = {}, u;\n\n // ideally we can move away from JSON entirely? unlikely due to compatibility issues... oh well.\n JSON.parseAsync = JSON.parseAsync || function(t,cb,r){ var u; try{ cb(u, JSON.parse(t,r)) }catch(e){ cb(e) } }\n JSON.stringifyAsync = JSON.stringifyAsync || function(v,cb,r,s){ var u; try{ cb(u, JSON.stringify(v,r,s)) }catch(e){ cb(e) } }\n\n api.parse = function(t,r){ return new Promise(function(res, rej){\n JSON.parseAsync(t,function(err, raw){ err? rej(err) : res(raw) },r);\n })}\n api.stringify = function(v,r,s){ return new Promise(function(res, rej){\n JSON.stringifyAsync(v,function(err, raw){ err? rej(err) : res(raw) },r,s);\n })}\n\n if(SEA.window){\n api.crypto = SEA.window.crypto || SEA.window.msCrypto\n api.subtle = (api.crypto||o).subtle || (api.crypto||o).webkitSubtle;\n api.TextEncoder = SEA.window.TextEncoder;\n api.TextDecoder = SEA.window.TextDecoder;\n api.random = (len) => api.Buffer.from(api.crypto.getRandomValues(new Uint8Array(api.Buffer.alloc(len))));\n }\n if(!api.TextDecoder)\n {\n const { TextEncoder, TextDecoder } = USE((u+'' == typeof MODULE?'.':'')+'./lib/text-encoding', 1);\n api.TextDecoder = TextDecoder;\n api.TextEncoder = TextEncoder;\n }\n if(!api.crypto)\n {\n try\n {\n var crypto = USE('crypto', 1);\n Object.assign(api, {\n crypto,\n random: (len) => api.Buffer.from(crypto.randomBytes(len))\n }); \n const { Crypto: WebCrypto } = USE('@peculiar/webcrypto', 1);\n api.ossl = api.subtle = new WebCrypto({directory: 'ossl'}).subtle // ECDH\n }\n catch(e){\n console.log(\"Please `npm install @peculiar/webcrypto` or add it to your package.json !\");\n }}\n\n module.exports = api\n })(USE, './shim');\n\n ;USE(function(module){\n var SEA = USE('./root');\n var shim = USE('./shim');\n var s = {};\n s.pbkdf2 = {hash: {name : 'SHA-256'}, iter: 100000, ks: 64};\n s.ecdsa = {\n pair: {name: 'ECDSA', namedCurve: 'P-256'},\n sign: {name: 'ECDSA', hash: {name: 'SHA-256'}}\n };\n s.ecdh = {name: 'ECDH', namedCurve: 'P-256'};\n\n // This creates Web Cryptography API compliant JWK for sign/verify purposes\n s.jwk = function(pub, d){ // d === priv\n pub = pub.split('.');\n var x = pub[0], y = pub[1];\n var jwk = {kty: \"EC\", crv: \"P-256\", x: x, y: y, ext: true};\n jwk.key_ops = d ? ['sign'] : ['verify'];\n if(d){ jwk.d = d }\n return jwk;\n };\n \n s.keyToJwk = function(keyBytes) {\n const keyB64 = keyBytes.toString('base64');\n const k = keyB64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/\\=/g, '');\n return { kty: 'oct', k: k, ext: false, alg: 'A256GCM' };\n }\n\n s.recall = {\n validity: 12 * 60 * 60, // internally in seconds : 12 hours\n hook: function(props){ return props } // { iat, exp, alias, remember } // or return new Promise((resolve, reject) => resolve(props)\n };\n\n s.check = function(t){ return (typeof t == 'string') && ('SEA{' === t.slice(0,4)) }\n s.parse = async function p(t){ try {\n var yes = (typeof t == 'string');\n if(yes && 'SEA{' === t.slice(0,4)){ t = t.slice(3) }\n return yes ? await shim.parse(t) : t;\n } catch (e) {}\n return t;\n }\n\n SEA.opt = s;\n module.exports = s\n })(USE, './settings');\n\n ;USE(function(module){\n var shim = USE('./shim');\n module.exports = async function(d, o){\n var t = (typeof d == 'string')? d : await shim.stringify(d);\n var hash = await shim.subtle.digest({name: o||'SHA-256'}, new shim.TextEncoder().encode(t));\n return shim.Buffer.from(hash);\n }\n })(USE, './sha256');\n\n ;USE(function(module){\n // This internal func returns SHA-1 hashed data for KeyID generation\n const __shim = USE('./shim')\n const subtle = __shim.subtle\n const ossl = __shim.ossl ? __shim.ossl : subtle\n const sha1hash = (b) => ossl.digest({name: 'SHA-1'}, new ArrayBuffer(b))\n module.exports = sha1hash\n })(USE, './sha1');\n\n ;USE(function(module){\n var SEA = USE('./root');\n var shim = USE('./shim');\n var S = USE('./settings');\n var sha = USE('./sha256');\n var u;\n\n SEA.work = SEA.work || (async (data, pair, cb, opt) => { try { // used to be named `proof`\n var salt = (pair||{}).epub || pair; // epub not recommended, salt should be random!\n opt = opt || {};\n if(salt instanceof Function){\n cb = salt;\n salt = u;\n }\n data = (typeof data == 'string')? data : await shim.stringify(data);\n if('sha' === (opt.name||'').toLowerCase().slice(0,3)){\n var rsha = shim.Buffer.from(await sha(data, opt.name), 'binary').toString(opt.encode || 'base64')\n if(cb){ try{ cb(rsha) }catch(e){console.log(e)} }\n return rsha;\n }\n salt = salt || shim.random(9);\n var key = await (shim.ossl || shim.subtle).importKey('raw', new shim.TextEncoder().encode(data), {name: opt.name || 'PBKDF2'}, false, ['deriveBits']);\n var work = await (shim.ossl || shim.subtle).deriveBits({\n name: opt.name || 'PBKDF2',\n iterations: opt.iterations || S.pbkdf2.iter,\n salt: new shim.TextEncoder().encode(opt.salt || salt),\n hash: opt.hash || S.pbkdf2.hash,\n }, key, opt.length || (S.pbkdf2.ks * 8))\n data = shim.random(data.length) // Erase data in case of passphrase\n var r = shim.Buffer.from(work, 'binary').toString(opt.encode || 'base64')\n if(cb){ try{ cb(r) }catch(e){console.log(e)} }\n return r;\n } catch(e) { \n console.log(e);\n SEA.err = e;\n if(SEA.throw){ throw e }\n if(cb){ cb() }\n return;\n }});\n\n module.exports = SEA.work;\n })(USE, './work');\n\n ;USE(function(module){\n var SEA = USE('./root');\n var shim = USE('./shim');\n var S = USE('./settings');\n\n SEA.name = SEA.name || (async (cb, opt) => { try {\n if(cb){ try{ cb() }catch(e){console.log(e)} }\n return;\n } catch(e) {\n console.log(e);\n SEA.err = e;\n if(SEA.throw){ throw e }\n if(cb){ cb() }\n return;\n }});\n\n //SEA.pair = async (data, proof, cb) => { try {\n SEA.pair = SEA.pair || (async (cb, opt) => { try {\n\n var ecdhSubtle = shim.ossl || shim.subtle;\n // First: ECDSA keys for signing/verifying...\n var sa = await shim.subtle.generateKey({name: 'ECDSA', namedCurve: 'P-256'}, true, [ 'sign', 'verify' ])\n .then(async (keys) => {\n // privateKey scope doesn't leak out from here!\n //const { d: priv } = await shim.subtle.exportKey('jwk', keys.privateKey)\n var key = {};\n key.priv = (await shim.subtle.exportKey('jwk', keys.privateKey)).d;\n var pub = await shim.subtle.exportKey('jwk', keys.publicKey);\n //const pub = Buff.from([ x, y ].join(':')).toString('base64') // old\n key.pub = pub.x+'.'+pub.y; // new\n // x and y are already base64\n // pub is UTF8 but filename/URL safe (https://www.ietf.org/rfc/rfc3986.txt)\n // but split on a non-base64 letter.\n return key;\n })\n \n // To include PGPv4 kind of keyId:\n // const pubId = await SEA.keyid(keys.pub)\n // Next: ECDH keys for encryption/decryption...\n\n try{\n var dh = await ecdhSubtle.generateKey({name: 'ECDH', namedCurve: 'P-256'}, true, ['deriveKey'])\n .then(async (keys) => {\n // privateKey scope doesn't leak out from here!\n var key = {};\n key.epriv = (await ecdhSubtle.exportKey('jwk', keys.privateKey)).d;\n var pub = await ecdhSubtle.exportKey('jwk', keys.publicKey);\n //const epub = Buff.from([ ex, ey ].join(':')).toString('base64') // old\n key.epub = pub.x+'.'+pub.y; // new\n // ex and ey are already base64\n // epub is UTF8 but filename/URL safe (https://www.ietf.org/rfc/rfc3986.txt)\n // but split on a non-base64 letter.\n return key;\n })\n }catch(e){\n if(SEA.window){ throw e }\n if(e == 'Error: ECDH is not a supported algorithm'){ console.log('Ignoring ECDH...') }\n else { throw e }\n } dh = dh || {};\n\n var r = { pub: sa.pub, priv: sa.priv, /* pubId, */ epub: dh.epub, epriv: dh.epriv }\n if(cb){ try{ cb(r) }catch(e){console.log(e)} }\n return r;\n } catch(e) {\n console.log(e);\n SEA.err = e;\n if(SEA.throw){ throw e }\n if(cb){ cb() }\n return;\n }});\n\n module.exports = SEA.pair;\n })(USE, './pair');\n\n ;USE(function(module){\n var SEA = USE('./root');\n var shim = USE('./shim');\n var S = USE('./settings');\n var sha = USE('./sha256');\n var u;\n\n SEA.sign = SEA.sign || (async (data, pair, cb, opt) => { try {\n opt = opt || {};\n if(!(pair||opt).priv){\n if(!SEA.I){ throw 'No signing key.' }\n pair = await SEA.I(null, {what: data, how: 'sign', why: opt.why});\n }\n if(u === data){ throw '`undefined` not allowed.' }\n var json = await S.parse(data);\n var check = opt.check = opt.check || json;\n if(SEA.verify && (SEA.opt.check(check) || (check && check.s && check.m))\n && u !== await SEA.verify(check, pair)){ // don't sign if we already signed it.\n var r = await S.parse(check);\n if(!opt.raw){ r = 'SEA' + await shim.stringify(r) }\n if(cb){ try{ cb(r) }catch(e){console.log(e)} }\n return r;\n }\n var pub = pair.pub;\n var priv = pair.priv;\n var jwk = S.jwk(pub, priv);\n var hash = await sha(json);\n var sig = await (shim.ossl || shim.subtle).importKey('jwk', jwk, {name: 'ECDSA', namedCurve: 'P-256'}, false, ['sign'])\n .then((key) => (shim.ossl || shim.subtle).sign({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, new Uint8Array(hash))) // privateKey scope doesn't leak out from here!\n var r = {m: json, s: shim.Buffer.from(sig, 'binary').toString(opt.encode || 'base64')}\n if(!opt.raw){ r = 'SEA' + await shim.stringify(r) }\n\n if(cb){ try{ cb(r) }catch(e){console.log(e)} }\n return r;\n } catch(e) {\n console.log(e);\n SEA.err = e;\n if(SEA.throw){ throw e }\n if(cb){ cb() }\n return;\n }});\n\n module.exports = SEA.sign;\n })(USE, './sign');\n\n ;USE(function(module){\n var SEA = USE('./root');\n var shim = USE('./shim');\n var S = USE('./settings');\n var sha = USE('./sha256');\n var u;\n\n SEA.verify = SEA.verify || (async (data, pair, cb, opt) => { try {\n var json = await S.parse(data);\n if(false === pair){ // don't verify!\n var raw = await S.parse(json.m);\n if(cb){ try{ cb(raw) }catch(e){console.log(e)} }\n return raw;\n }\n opt = opt || {};\n // SEA.I // verify is free! Requires no user permission.\n var pub = pair.pub || pair;\n var key = SEA.opt.slow_leak? await SEA.opt.slow_leak(pub) : await (shim.ossl || shim.subtle).importKey('jwk', S.jwk(pub), {name: 'ECDSA', namedCurve: 'P-256'}, false, ['verify']);\n var hash = await sha(json.m);\n var buf, sig, check, tmp; try{\n buf = shim.Buffer.from(json.s, opt.encode || 'base64'); // NEW DEFAULT!\n sig = new Uint8Array(buf);\n check = await (shim.ossl || shim.subtle).verify({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, sig, new Uint8Array(hash));\n if(!check){ throw \"Signature did not match.\" }\n }catch(e){\n if(SEA.opt.fallback){\n return await SEA.opt.fall_verify(data, pair, cb, opt);\n }\n }\n var r = check? await S.parse(json.m) : u;\n\n if(cb){ try{ cb(r) }catch(e){console.log(e)} }\n return r;\n } catch(e) {\n console.log(e); // mismatched owner FOR MARTTI\n SEA.err = e;\n if(SEA.throw){ throw e }\n if(cb){ cb() }\n return;\n }});\n\n module.exports = SEA.verify;\n // legacy & ossl memory leak mitigation:\n\n var knownKeys = {};\n var keyForPair = SEA.opt.slow_leak = pair => {\n if (knownKeys[pair]) return knownKeys[pair];\n var jwk = S.jwk(pair);\n knownKeys[pair] = (shim.ossl || shim.subtle).importKey(\"jwk\", jwk, {name: 'ECDSA', namedCurve: 'P-256'}, false, [\"verify\"]);\n return knownKeys[pair];\n };\n\n var O = SEA.opt;\n SEA.opt.fall_verify = async function(data, pair, cb, opt, f){\n if(f === SEA.opt.fallback){ throw \"Signature did not match\" } f = f || 1;\n var tmp = data||'';\n data = SEA.opt.unpack(data) || data;\n var json = await S.parse(data), pub = pair.pub || pair, key = await SEA.opt.slow_leak(pub);\n var hash = (f <= SEA.opt.fallback)? shim.Buffer.from(await shim.subtle.digest({name: 'SHA-256'}, new shim.TextEncoder().encode(await S.parse(json.m)))) : await sha(json.m); // this line is old bad buggy code but necessary for old compatibility.\n var buf; var sig; var check; try{\n buf = shim.Buffer.from(json.s, opt.encode || 'base64') // NEW DEFAULT!\n sig = new Uint8Array(buf)\n check = await (shim.ossl || shim.subtle).verify({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, sig, new Uint8Array(hash))\n if(!check){ throw \"Signature did not match.\" }\n }catch(e){ try{\n buf = shim.Buffer.from(json.s, 'utf8') // AUTO BACKWARD OLD UTF8 DATA!\n sig = new Uint8Array(buf)\n check = await (shim.ossl || shim.subtle).verify({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, sig, new Uint8Array(hash))\n }catch(e){\n if(!check){ throw \"Signature did not match.\" }\n }\n }\n var r = check? await S.parse(json.m) : u;\n O.fall_soul = tmp['#']; O.fall_key = tmp['.']; O.fall_val = data; O.fall_state = tmp['>'];\n if(cb){ try{ cb(r) }catch(e){console.log(e)} }\n return r;\n }\n SEA.opt.fallback = 2;\n\n })(USE, './verify');\n\n ;USE(function(module){\n var shim = USE('./shim');\n var S = USE('./settings');\n var sha256hash = USE('./sha256');\n\n const importGen = async (key, salt, opt) => {\n //const combo = shim.Buffer.concat([shim.Buffer.from(key, 'utf8'), salt || shim.random(8)]).toString('utf8') // old\n opt = opt || {};\n const combo = key + (salt || shim.random(8)).toString('utf8'); // new\n const hash = shim.Buffer.from(await sha256hash(combo), 'binary')\n \n const jwkKey = S.keyToJwk(hash) \n return await shim.subtle.importKey('jwk', jwkKey, {name:'AES-GCM'}, false, ['encrypt', 'decrypt'])\n }\n module.exports = importGen;\n })(USE, './aeskey');\n\n ;USE(function(module){\n var SEA = USE('./root');\n var shim = USE('./shim');\n var S = USE('./settings');\n var aeskey = USE('./aeskey');\n var u;\n\n SEA.encrypt = SEA.encrypt || (async (data, pair, cb, opt) => { try {\n opt = opt || {};\n var key = (pair||opt).epriv || pair;\n if(u === data){ throw '`undefined` not allowed.' }\n if(!key){\n if(!SEA.I){ throw 'No encryption key.' }\n pair = await SEA.I(null, {what: data, how: 'encrypt', why: opt.why});\n key = pair.epriv || pair;\n }\n var msg = (typeof data == 'string')? data : await shim.stringify(data);\n var rand = {s: shim.random(9), iv: shim.random(15)}; // consider making this 9 and 15 or 18 or 12 to reduce == padding.\n var ct = await aeskey(key, rand.s, opt).then((aes) => (/*shim.ossl ||*/ shim.subtle).encrypt({ // Keeping the AES key scope as private as possible...\n name: opt.name || 'AES-GCM', iv: new Uint8Array(rand.iv)\n }, aes, new shim.TextEncoder().encode(msg)));\n var r = {\n ct: shim.Buffer.from(ct, 'binary').toString(opt.encode || 'base64'),\n iv: rand.iv.toString(opt.encode || 'base64'),\n s: rand.s.toString(opt.encode || 'base64')\n }\n if(!opt.raw){ r = 'SEA' + await shim.stringify(r) }\n\n if(cb){ try{ cb(r) }catch(e){console.log(e)} }\n return r;\n } catch(e) { \n console.log(e);\n SEA.err = e;\n if(SEA.throw){ throw e }\n if(cb){ cb() }\n return;\n }});\n\n module.exports = SEA.encrypt;\n })(USE, './encrypt');\n\n ;USE(function(module){\n var SEA = USE('./root');\n var shim = USE('./shim');\n var S = USE('./settings');\n var aeskey = USE('./aeskey');\n\n SEA.decrypt = SEA.decrypt || (async (data, pair, cb, opt) => { try {\n opt = opt || {};\n var key = (pair||opt).epriv || pair;\n if(!key){\n if(!SEA.I){ throw 'No decryption key.' }\n pair = await SEA.I(null, {what: data, how: 'decrypt', why: opt.why});\n key = pair.epriv || pair;\n }\n var json = await S.parse(data);\n var buf, bufiv, bufct; try{\n buf = shim.Buffer.from(json.s, opt.encode || 'base64');\n bufiv = shim.Buffer.from(json.iv, opt.encode || 'base64');\n bufct = shim.Buffer.from(json.ct, opt.encode || 'base64');\n var ct = await aeskey(key, buf, opt).then((aes) => (/*shim.ossl ||*/ shim.subtle).decrypt({ // Keeping aesKey scope as private as possible...\n name: opt.name || 'AES-GCM', iv: new Uint8Array(bufiv), tagLength: 128\n }, aes, new Uint8Array(bufct)));\n }catch(e){\n if('utf8' === opt.encode){ throw \"Could not decrypt\" }\n if(SEA.opt.fallback){\n opt.encode = 'utf8';\n return await SEA.decrypt(data, pair, cb, opt);\n }\n }\n var r = await S.parse(new shim.TextDecoder('utf8').decode(ct));\n if(cb){ try{ cb(r) }catch(e){console.log(e)} }\n return r;\n } catch(e) { \n console.log(e);\n SEA.err = e;\n if(SEA.throw){ throw e }\n if(cb){ cb() }\n return;\n }});\n\n module.exports = SEA.decrypt;\n })(USE, './decrypt');\n\n ;USE(function(module){\n var SEA = USE('./root');\n var shim = USE('./shim');\n var S = USE('./settings');\n // Derive shared secret from other's pub and my epub/epriv \n SEA.secret = SEA.secret || (async (key, pair, cb, opt) => { try {\n opt = opt || {};\n if(!pair || !pair.epriv || !pair.epub){\n if(!SEA.I){ throw 'No secret mix.' }\n pair = await SEA.I(null, {what: key, how: 'secret', why: opt.why});\n }\n var pub = key.epub || key;\n var epub = pair.epub;\n var epriv = pair.epriv;\n var ecdhSubtle = shim.ossl || shim.subtle;\n var pubKeyData = keysToEcdhJwk(pub);\n var props = Object.assign({ public: await ecdhSubtle.importKey(...pubKeyData, true, []) },{name: 'ECDH', namedCurve: 'P-256'}); // Thanks to @sirpy !\n var privKeyData = keysToEcdhJwk(epub, epriv);\n var derived = await ecdhSubtle.importKey(...privKeyData, false, ['deriveBits']).then(async (privKey) => {\n // privateKey scope doesn't leak out from here!\n var derivedBits = await ecdhSubtle.deriveBits(props, privKey, 256);\n var rawBits = new Uint8Array(derivedBits);\n var derivedKey = await ecdhSubtle.importKey('raw', rawBits,{ name: 'AES-GCM', length: 256 }, true, [ 'encrypt', 'decrypt' ]);\n return ecdhSubtle.exportKey('jwk', derivedKey).then(({ k }) => k);\n })\n var r = derived;\n if(cb){ try{ cb(r) }catch(e){console.log(e)} }\n return r;\n } catch(e) {\n console.log(e);\n SEA.err = e;\n if(SEA.throw){ throw e }\n if(cb){ cb() }\n return;\n }});\n\n // can this be replaced with settings.jwk?\n var keysToEcdhJwk = (pub, d) => { // d === priv\n //var [ x, y ] = shim.Buffer.from(pub, 'base64').toString('utf8').split(':') // old\n var [ x, y ] = pub.split('.') // new\n var jwk = d ? { d: d } : {}\n return [ // Use with spread returned value...\n 'jwk',\n Object.assign(\n jwk,\n { x: x, y: y, kty: 'EC', crv: 'P-256', ext: true }\n ), // ??? refactor\n {name: 'ECDH', namedCurve: 'P-256'}\n ]\n }\n\n module.exports = SEA.secret;\n })(USE, './secret');\n\n ;USE(function(module){\n var SEA = USE('./root');\n // This is to certify that a group of \"certificants\" can \"put\" anything at a group of matched \"paths\" to the certificate authority's graph\n SEA.certify = SEA.certify || (async (certificants, policy = {}, authority, cb, opt = {}) => { try {\n /*\n The Certify Protocol was made out of love by a Vietnamese code enthusiast. Vietnamese people around the world deserve respect!\n IMPORTANT: A Certificate is like a Signature. No one knows who (authority) created/signed a cert until you put it into their graph.\n \"certificants\": '*' or a String (Bob.pub) || an Object that contains \"pub\" as a key || an array of [object || string]. These people will have the rights.\n \"policy\": A string ('inbox'), or a RAD/LEX object {'*': 'inbox'}, or an Array of RAD/LEX objects or strings. RAD/LEX object can contain key \"?\" with indexOf(\"*\") > -1 to force key equals certificant pub. This rule is used to check against soul+'/'+key using Gun.text.match or String.match.\n \"authority\": Key pair or priv of the certificate authority.\n \"cb\": A callback function after all things are done.\n \"opt\": If opt.expiry (a timestamp) is set, SEA won't sync data after opt.expiry. If opt.block is set, SEA will look for block before syncing.\n */\n console.log('SEA.certify() is an early experimental community supported method that may change API behavior without warning in any future version.')\n\n certificants = (() => {\n var data = []\n if (certificants) {\n if ((typeof certificants === 'string' || Array.isArray(certificants)) && certificants.indexOf('*') > -1) return '*'\n if (typeof certificants === 'string') return certificants\n if (Array.isArray(certificants)) {\n if (certificants.length === 1 && certificants[0]) return typeof certificants[0] === 'object' && certificants[0].pub ? certificants[0].pub : typeof certificants[0] === 'string' ? certificants[0] : null\n certificants.map(certificant => {\n if (typeof certificant ==='string') data.push(certificant)\n else if (typeof certificant === 'object' && certificant.pub) data.push(certificant.pub)\n })\n }\n\n if (typeof certificants === 'object' && certificants.pub) return certificants.pub\n return data.length > 0 ? data : null\n }\n return\n })()\n\n if (!certificants) return console.log(\"No certificant found.\")\n\n const expiry = opt.expiry && (typeof opt.expiry === 'number' || typeof opt.expiry === 'string') ? parseFloat(opt.expiry) : null\n const readPolicy = (policy || {}).read ? policy.read : null\n const writePolicy = (policy || {}).write ? policy.write : typeof policy === 'string' || Array.isArray(policy) || policy[\"+\"] || policy[\"#\"] || policy[\".\"] || policy[\"=\"] || policy[\"*\"] || policy[\">\"] || policy[\"<\"] ? policy : null\n // The \"blacklist\" feature is now renamed to \"block\". Why ? BECAUSE BLACK LIVES MATTER!\n // We can now use 3 keys: block, blacklist, ban\n const block = (opt || {}).block || (opt || {}).blacklist || (opt || {}).ban || {}\n const readBlock = block.read && (typeof block.read === 'string' || (block.read || {})['#']) ? block.read : null\n const writeBlock = typeof block === 'string' ? block : block.write && (typeof block.write === 'string' || block.write['#']) ? block.write : null\n\n if (!readPolicy && !writePolicy) return console.log(\"No policy found.\")\n\n // reserved keys: c, e, r, w, rb, wb\n const data = JSON.stringify({\n c: certificants,\n ...(expiry ? {e: expiry} : {}), // inject expiry if possible\n ...(readPolicy ? {r: readPolicy } : {}), // \"r\" stands for read, which means read permission.\n ...(writePolicy ? {w: writePolicy} : {}), // \"w\" stands for write, which means write permission.\n ...(readBlock ? {rb: readBlock} : {}), // inject READ block if possible\n ...(writeBlock ? {wb: writeBlock} : {}), // inject WRITE block if possible\n })\n\n const certificate = await SEA.sign(data, authority, null, {raw:1})\n\n var r = certificate\n if(!opt.raw){ r = 'SEA'+JSON.stringify(r) }\n if(cb){ try{ cb(r) }catch(e){console.log(e)} }\n return r;\n } catch(e) {\n SEA.err = e;\n if(SEA.throw){ throw e }\n if(cb){ cb() }\n return;\n }});\n\n module.exports = SEA.certify;\n })(USE, './certify');\n\n ;USE(function(module){\n var shim = USE('./shim');\n // Practical examples about usage found in tests.\n var SEA = USE('./root');\n SEA.work = USE('./work');\n SEA.sign = USE('./sign');\n SEA.verify = USE('./verify');\n SEA.encrypt = USE('./encrypt');\n SEA.decrypt = USE('./decrypt');\n SEA.certify = USE('./certify');\n //SEA.opt.aeskey = USE('./aeskey'); // not official! // this causes problems in latest WebCrypto.\n\n SEA.random = SEA.random || shim.random;\n\n // This is Buffer used in SEA and usable from Gun/SEA application also.\n // For documentation see https://nodejs.org/api/buffer.html\n SEA.Buffer = SEA.Buffer || USE('./buffer');\n\n // These SEA functions support now ony Promises or\n // async/await (compatible) code, use those like Promises.\n //\n // Creates a wrapper library around Web Crypto API\n // for various AES, ECDSA, PBKDF2 functions we called above.\n // Calculate public key KeyID aka PGPv4 (result: 8 bytes as hex string)\n SEA.keyid = SEA.keyid || (async (pub) => {\n try {\n // base64('base64(x):base64(y)') => shim.Buffer(xy)\n const pb = shim.Buffer.concat(\n pub.replace(/-/g, '+').replace(/_/g, '/').split('.')\n .map((t) => shim.Buffer.from(t, 'base64'))\n )\n // id is PGPv4 compliant raw key\n const id = shim.Buffer.concat([\n shim.Buffer.from([0x99, pb.length / 0x100, pb.length % 0x100]), pb\n ])\n const sha1 = await sha1hash(id)\n const hash = shim.Buffer.from(sha1, 'binary')\n return hash.toString('hex', hash.length - 8) // 16-bit ID as hex\n } catch (e) {\n console.log(e)\n throw e\n }\n });\n // all done!\n // Obviously it is missing MANY necessary features. This is only an alpha release.\n // Please experiment with it, audit what I've done so far, and complain about what needs to be added.\n // SEA should be a full suite that is easy and seamless to use.\n // Again, scroll naer the top, where I provide an EXAMPLE of how to create a user and sign in.\n // Once logged in, the rest of the code you just read handled automatically signing/validating data.\n // But all other behavior needs to be equally easy, like opinionated ways of\n // Adding friends (trusted public keys), sending private messages, etc.\n // Cheers! Tell me what you think.\n ((SEA.window||{}).GUN||{}).SEA = SEA;\n\n module.exports = SEA\n // -------------- END SEA MODULES --------------------\n // -- BEGIN SEA+GUN MODULES: BUNDLED BY DEFAULT UNTIL OTHERS USE SEA ON OWN -------\n })(USE, './sea');\n\n ;USE(function(module){\n var SEA = USE('./sea'), Gun, u;\n if(SEA.window){\n Gun = SEA.window.GUN || {chain:{}};\n } else {\n Gun = USE((u+'' == typeof MODULE?'.':'')+'./gun', 1);\n }\n SEA.GUN = Gun;\n\n function User(root){ \n this._ = {$: this};\n }\n User.prototype = (function(){ function F(){}; F.prototype = Gun.chain; return new F() }()) // Object.create polyfill\n User.prototype.constructor = User;\n\n // let's extend the gun chain with a `user` function.\n // only one user can be logged in at a time, per gun instance.\n Gun.chain.user = function(pub){\n var gun = this, root = gun.back(-1), user;\n if(pub){\n pub = SEA.opt.pub((pub._||'')['#']) || pub;\n return root.get('~'+pub);\n }\n if(user = root.back('user')){ return user }\n var root = (root._), at = root, uuid = at.opt.uuid || lex;\n (at = (user = at.user = gun.chain(new User))._).opt = {};\n at.opt.uuid = function(cb){\n var id = uuid(), pub = root.user;\n if(!pub || !(pub = pub.is) || !(pub = pub.pub)){ return id }\n id = '~' + pub + '/' + id;\n if(cb && cb.call){ cb(null, id) }\n return id;\n }\n return user;\n }\n function lex(){ return Gun.state().toString(36).replace('.','') }\n Gun.User = User;\n User.GUN = Gun;\n User.SEA = Gun.SEA = SEA;\n module.exports = User;\n })(USE, './user');\n\n ;USE(function(module){\n var u, Gun = (''+u != typeof GUN)? (GUN||{chain:{}}) : USE((''+u === typeof MODULE?'.':'')+'./gun', 1);\n Gun.chain.then = function(cb, opt){\n var gun = this, p = (new Promise(function(res, rej){\n gun.once(res, opt);\n }));\n return cb? p.then(cb) : p;\n }\n })(USE, './then');\n\n ;USE(function(module){\n var User = USE('./user'), SEA = User.SEA, Gun = User.GUN, noop = function(){};\n\n // Well first we have to actually create a user. That is what this function does.\n User.prototype.create = function(...args){\n var pair = typeof args[0] === 'object' && (args[0].pub || args[0].epub) ? args[0] : typeof args[1] === 'object' && (args[1].pub || args[1].epub) ? args[1] : null;\n var alias = pair && (pair.pub || pair.epub) ? pair.pub : typeof args[0] === 'string' ? args[0] : null;\n var pass = pair && (pair.pub || pair.epub) ? pair : alias && typeof args[1] === 'string' ? args[1] : null;\n var cb = args.filter(arg => typeof arg === 'function')[0] || null; // cb now can stand anywhere, after alias/pass or pair\n var opt = args && args.length > 1 && typeof args[args.length-1] === 'object' ? args[args.length-1] : {}; // opt is always the last parameter which typeof === 'object' and stands after cb\n \n var gun = this, cat = (gun._), root = gun.back(-1);\n cb = cb || noop;\n opt = opt || {};\n if(false !== opt.check){\n var err;\n if(!alias){ err = \"No user.\" }\n if((pass||'').length < 8){ err = \"Password too short!\" }\n if(err){\n cb({err: Gun.log(err)});\n return gun;\n }\n }\n if(cat.ing){\n (cb || noop)({err: Gun.log(\"User is already being created or authenticated!\"), wait: true});\n return gun;\n }\n cat.ing = true;\n var act = {}, u;\n act.a = function(pubs){\n act.pubs = pubs;\n if(pubs && !opt.already){\n // If we can enforce that a user name is already taken, it might be nice to try, but this is not guaranteed.\n var ack = {err: Gun.log('User already created!')};\n cat.ing = false;\n (cb || noop)(ack);\n gun.leave();\n return;\n }\n act.salt = String.random(64); // pseudo-randomly create a salt, then use PBKDF2 function to extend the password with it.\n SEA.work(pass, act.salt, act.b); // this will take some short amount of time to produce a proof, which slows brute force attacks.\n }\n act.b = function(proof){\n act.proof = proof;\n pair ? act.c(pair) : SEA.pair(act.c) // generate a brand new key pair or use the existing.\n }\n act.c = function(pair){\n var tmp\n act.pair = pair || {};\n if(tmp = cat.root.user){\n tmp._.sea = pair;\n tmp.is = {pub: pair.pub, epub: pair.epub, alias: alias};\n }\n // the user's public key doesn't need to be signed. But everything else needs to be signed with it! // we have now automated it! clean up these extra steps now!\n act.data = {pub: pair.pub};\n act.d();\n }\n act.d = function(){\n act.data.alias = alias;\n act.e();\n }\n act.e = function(){\n act.data.epub = act.pair.epub; \n SEA.encrypt({priv: act.pair.priv, epriv: act.pair.epriv}, act.proof, act.f, {raw:1}); // to keep the private key safe, we AES encrypt it with the proof of work!\n }\n act.f = function(auth){\n act.data.auth = JSON.stringify({ek: auth, s: act.salt}); \n act.g(act.data.auth);\n }\n act.g = function(auth){ var tmp;\n act.data.auth = act.data.auth || auth;\n root.get(tmp = '~'+act.pair.pub).put(act.data).on(act.h); // awesome, now we can actually save the user with their public key as their ID.\n var link = {}; link[tmp] = {'#': tmp}; root.get('~@'+alias).put(link).get(tmp).on(act.i); // next up, we want to associate the alias with the public key. So we add it to the alias list.\n }\n act.h = function(data, key, msg, eve){\n eve.off(); act.h.ok = 1; act.i();\n }\n act.i = function(data, key, msg, eve){\n if(eve){ act.i.ok = 1; eve.off() }\n if(!act.h.ok || !act.i.ok){ return }\n cat.ing = false;\n cb({ok: 0, pub: act.pair.pub}); // callback that the user has been created. (Note: ok = 0 because we didn't wait for disk to ack)\n if(noop === cb){ pair ? gun.auth(pair) : gun.auth(alias, pass) } // if no callback is passed, auto-login after signing up.\n }\n root.get('~@'+alias).once(act.a);\n return gun;\n }\n User.prototype.leave = function(opt, cb){\n var gun = this, user = (gun.back(-1)._).user;\n if(user){\n delete user.is;\n delete user._.is;\n delete user._.sea;\n }\n if(SEA.window){\n try{var sS = {};\n sS = SEA.window.sessionStorage;\n delete sS.recall;\n delete sS.pair;\n }catch(e){};\n }\n return gun;\n }\n })(USE, './create');\n\n ;USE(function(module){\n var User = USE('./user'), SEA = User.SEA, Gun = User.GUN, noop = function(){};\n // now that we have created a user, we want to authenticate them!\n User.prototype.auth = function(...args){ // TODO: this PR with arguments need to be cleaned up / refactored.\n var pair = typeof args[0] === 'object' && (args[0].pub || args[0].epub) ? args[0] : typeof args[1] === 'object' && (args[1].pub || args[1].epub) ? args[1] : null;\n var alias = !pair && typeof args[0] === 'string' ? args[0] : null;\n var pass = (alias || (pair && !(pair.priv && pair.epriv))) && typeof args[1] === 'string' ? args[1] : null;\n var cb = args.filter(arg => typeof arg === 'function')[0] || null; // cb now can stand anywhere, after alias/pass or pair\n var opt = args && args.length > 1 && typeof args[args.length-1] === 'object' ? args[args.length-1] : {}; // opt is always the last parameter which typeof === 'object' and stands after cb\n \n var gun = this, cat = (gun._), root = gun.back(-1);\n \n if(cat.ing){\n (cb || noop)({err: Gun.log(\"User is already being created or authenticated!\"), wait: true});\n return gun;\n }\n cat.ing = true;\n \n var act = {}, u, tries = 9;\n act.a = function(data){\n if(!data){ return act.b() }\n if(!data.pub){\n var tmp = []; Object.keys(data).forEach(function(k){ if('_'==k){ return } tmp.push(data[k]) })\n return act.b(tmp);\n }\n if(act.name){ return act.f(data) }\n act.c((act.data = data).auth);\n }\n act.b = function(list){\n var get = (act.list = (act.list||[]).concat(list||[])).shift();\n if(u === get){\n if(act.name){ return act.err('Your user account is not published for dApps to access, please consider syncing it online, or allowing local access by adding your device as a peer.') }\n if(alias && tries--){\n root.get('~@'+alias).once(act.a);\n return;\n }\n return act.err('Wrong user or password.') \n }\n root.get(get).once(act.a);\n }\n act.c = function(auth){\n if(u === auth){ return act.b() }\n if('string' == typeof auth){ return act.c(obj_ify(auth)) } // in case of legacy\n SEA.work(pass, (act.auth = auth).s, act.d, act.enc); // the proof of work is evidence that we've spent some time/effort trying to log in, this slows brute force.\n }\n act.d = function(proof){\n SEA.decrypt(act.auth.ek, proof, act.e, act.enc);\n }\n act.e = function(half){\n if(u === half){\n if(!act.enc){ // try old format\n act.enc = {encode: 'utf8'};\n return act.c(act.auth);\n } act.enc = null; // end backwards\n return act.b();\n }\n act.half = half;\n act.f(act.data);\n }\n act.f = function(pair){\n var half = act.half || {}, data = act.data || {};\n act.g(act.lol = {pub: pair.pub || data.pub, epub: pair.epub || data.epub, priv: pair.priv || half.priv, epriv: pair.epriv || half.epriv});\n }\n act.g = function(pair){\n if(!pair || !pair.pub || !pair.epub){ return act.b() }\n act.pair = pair;\n var user = (root._).user, at = (user._);\n var tmp = at.tag;\n var upt = at.opt;\n at = user._ = root.get('~'+pair.pub)._;\n at.opt = upt;\n // add our credentials in-memory only to our root user instance\n user.is = {pub: pair.pub, epub: pair.epub, alias: alias || pair.pub};\n at.sea = act.pair;\n cat.ing = false;\n try{if(pass && u == (obj_ify(cat.root.graph['~'+pair.pub].auth)||'')[':']){ opt.shuffle = opt.change = pass; } }catch(e){} // migrate UTF8 & Shuffle!\n opt.change? act.z() : (cb || noop)(at);\n if(SEA.window && ((gun.back('user')._).opt||opt).remember){\n // TODO: this needs to be modular.\n try{var sS = {};\n sS = SEA.window.sessionStorage; // TODO: FIX BUG putting on `.is`!\n sS.recall = true;\n sS.pair = JSON.stringify(pair); // auth using pair is more reliable than alias/pass\n }catch(e){}\n }\n try{\n if(root._.tag.auth){ // auth handle might not be registered yet\n (root._).on('auth', at) // TODO: Deprecate this, emit on user instead! Update docs when you do.\n } else { setTimeout(function(){ (root._).on('auth', at) },1) } // if not, hackily add a timeout.\n //at.on('auth', at) // Arrgh, this doesn't work without event \"merge\" code, but \"merge\" code causes stack overflow and crashes after logging in & trying to write data.\n }catch(e){\n Gun.log(\"Your 'auth' callback crashed with:\", e);\n }\n }\n act.h = function(data){\n if(!data){ return act.b() }\n alias = data.alias\n if(!alias)\n alias = data.alias = \"~\" + pair.pub \n if(!data.auth){\n return act.g(pair);\n }\n pair = null;\n act.c((act.data = data).auth);\n }\n act.z = function(){\n // password update so encrypt private key using new pwd + salt\n act.salt = String.random(64); // pseudo-random\n SEA.work(opt.change, act.salt, act.y);\n }\n act.y = function(proof){\n SEA.encrypt({priv: act.pair.priv, epriv: act.pair.epriv}, proof, act.x, {raw:1});\n }\n act.x = function(auth){\n act.w(JSON.stringify({ek: auth, s: act.salt}));\n }\n act.w = function(auth){\n if(opt.shuffle){ // delete in future!\n console.log('migrate core account from UTF8 & shuffle');\n var tmp = {}; Object.keys(act.data).forEach(function(k){ tmp[k] = act.data[k] });\n delete tmp._;\n tmp.auth = auth;\n root.get('~'+act.pair.pub).put(tmp);\n } // end delete\n root.get('~'+act.pair.pub).get('auth').put(auth, cb || noop);\n }\n act.err = function(e){\n var ack = {err: Gun.log(e || 'User cannot be found!')};\n cat.ing = false;\n (cb || noop)(ack);\n }\n act.plugin = function(name){\n if(!(act.name = name)){ return act.err() }\n var tmp = [name];\n if('~' !== name[0]){\n tmp[1] = '~'+name;\n tmp[2] = '~@'+name;\n }\n act.b(tmp);\n }\n if(pair){\n if(pair.priv && pair.epriv)\n act.g(pair);\n else\n root.get('~'+pair.pub).once(act.h);\n } else\n if(alias){\n root.get('~@'+alias).once(act.a);\n } else\n if(!alias && !pass){\n SEA.name(act.plugin);\n }\n return gun;\n }\n function obj_ify(o){\n if('string' != typeof o){ return o }\n try{o = JSON.parse(o);\n }catch(e){o={}};\n return o;\n }\n })(USE, './auth');\n\n ;USE(function(module){\n var User = USE('./user'), SEA = User.SEA, Gun = User.GUN;\n User.prototype.recall = function(opt, cb){\n var gun = this, root = gun.back(-1), tmp;\n opt = opt || {};\n if(opt && opt.sessionStorage){\n if(SEA.window){\n try{\n var sS = {};\n sS = SEA.window.sessionStorage; // TODO: FIX BUG putting on `.is`!\n if(sS){\n (root._).opt.remember = true;\n ((gun.back('user')._).opt||opt).remember = true;\n if(sS.recall || sS.pair) root.user().auth(JSON.parse(sS.pair), cb); // pair is more reliable than alias/pass\n }\n }catch(e){}\n }\n return gun;\n }\n /*\n TODO: copy mhelander's expiry code back in.\n Although, we should check with community,\n should expiry be core or a plugin?\n */\n return gun;\n }\n })(USE, './recall');\n\n ;USE(function(module){\n var User = USE('./user'), SEA = User.SEA, Gun = User.GUN, noop = function(){};\n User.prototype.pair = function(){\n var user = this, proxy; // undeprecated, hiding with proxies.\n try{ proxy = new Proxy({DANGER:'\\u2620'}, {get: function(t,p,r){\n if(!user.is || !(user._||'').sea){ return }\n return user._.sea[p];\n }})}catch(e){}\n return proxy;\n }\n // If authenticated user wants to delete his/her account, let's support it!\n User.prototype.delete = async function(alias, pass, cb){\n console.log(\"user.delete() IS DEPRECATED AND WILL BE MOVED TO A MODULE!!!\");\n var gun = this, root = gun.back(-1), user = gun.back('user');\n try {\n user.auth(alias, pass, function(ack){\n var pub = (user.is||{}).pub;\n // Delete user data\n user.map().once(function(){ this.put(null) });\n // Wipe user data from memory\n user.leave();\n (cb || noop)({ok: 0});\n });\n } catch (e) {\n Gun.log('User.delete failed! Error:', e);\n }\n return gun;\n }\n User.prototype.alive = async function(){\n console.log(\"user.alive() IS DEPRECATED!!!\");\n const gunRoot = this.back(-1)\n try {\n // All is good. Should we do something more with actual recalled data?\n await authRecall(gunRoot)\n return gunRoot._.user._\n } catch (e) {\n const err = 'No session!'\n Gun.log(err)\n throw { err }\n }\n }\n User.prototype.trust = async function(user){\n console.log(\"`.trust` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!\");\n // TODO: BUG!!! SEA `node` read listener needs to be async, which means core needs to be async too.\n //gun.get('alice').get('age').trust(bob);\n if (Gun.is(user)) {\n user.get('pub').get((ctx, ev) => {\n console.log(ctx, ev)\n })\n }\n user.get('trust').get(path).put(theirPubkey);\n\n // do a lookup on this gun chain directly (that gets bob's copy of the data)\n // do a lookup on the metadata trust table for this path (that gets all the pubkeys allowed to write on this path)\n // do a lookup on each of those pubKeys ON the path (to get the collab data \"layers\")\n // THEN you perform Jachen's mix operation\n // and return the result of that to...\n }\n User.prototype.grant = function(to, cb){\n console.log(\"`.grant` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!\");\n var gun = this, user = gun.back(-1).user(), pair = user._.sea, path = '';\n gun.back(function(at){ if(at.is){ return } path += (at.get||'') });\n (async function(){\n var enc, sec = await user.get('grant').get(pair.pub).get(path).then();\n sec = await SEA.decrypt(sec, pair);\n if(!sec){\n sec = SEA.random(16).toString();\n enc = await SEA.encrypt(sec, pair);\n user.get('grant').get(pair.pub).get(path).put(enc);\n }\n var pub = to.get('pub').then();\n var epub = to.get('epub').then();\n pub = await pub; epub = await epub;\n var dh = await SEA.secret(epub, pair);\n enc = await SEA.encrypt(sec, dh);\n user.get('grant').get(pub).get(path).put(enc, cb);\n }());\n return gun;\n }\n User.prototype.secret = function(data, cb){\n console.log(\"`.secret` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!\");\n var gun = this, user = gun.back(-1).user(), pair = user.pair(), path = '';\n gun.back(function(at){ if(at.is){ return } path += (at.get||'') });\n (async function(){\n var enc, sec = await user.get('trust').get(pair.pub).get(path).then();\n sec = await SEA.decrypt(sec, pair);\n if(!sec){\n sec = SEA.random(16).toString();\n enc = await SEA.encrypt(sec, pair);\n user.get('trust').get(pair.pub).get(path).put(enc);\n }\n enc = await SEA.encrypt(data, sec);\n gun.put(enc, cb);\n }());\n return gun;\n }\n\n /**\n * returns the decrypted value, encrypted by secret\n * @returns {Promise<any>}\n // Mark needs to review 1st before officially supported\n User.prototype.decrypt = function(cb) {\n let gun = this,\n path = ''\n gun.back(function(at) {\n if (at.is) {\n return\n }\n path += at.get || ''\n })\n return gun\n .then(async data => {\n if (data == null) {\n return\n }\n const user = gun.back(-1).user()\n const pair = user.pair()\n let sec = await user\n .get('trust')\n .get(pair.pub)\n .get(path)\n sec = await SEA.decrypt(sec, pair)\n if (!sec) {\n return data\n }\n let decrypted = await SEA.decrypt(data, sec)\n return decrypted\n })\n .then(res => {\n cb && cb(res)\n return res\n })\n }\n */\n module.exports = User\n })(USE, './share');\n\n ;USE(function(module){\n var SEA = USE('./sea'), S = USE('./settings'), noop = function() {}, u;\n var Gun = (SEA.window||'').GUN || USE((''+u === typeof MODULE?'.':'')+'./gun', 1);\n // After we have a GUN extension to make user registration/login easy, we then need to handle everything else.\n\n // We do this with a GUN adapter, we first listen to when a gun instance is created (and when its options change)\n Gun.on('opt', function(at){\n if(!at.sea){ // only add SEA once per instance, on the \"at\" context.\n at.sea = {own: {}};\n at.on('put', check, at); // SEA now runs its firewall on HAM diffs, not all i/o.\n }\n this.to.next(at); // make sure to call the \"next\" middleware adapter.\n });\n\n // Alright, this next adapter gets run at the per node level in the graph database.\n // correction: 2020 it gets run on each key/value pair in a node upon a HAM diff.\n // This will let us verify that every property on a node has a value signed by a public key we trust.\n // If the signature does not match, the data is just `undefined` so it doesn't get passed on.\n // If it does match, then we transform the in-memory \"view\" of the data into its plain value (without the signature).\n // Now NOTE! Some data is \"system\" data, not user data. Example: List of public keys, aliases, etc.\n // This data is self-enforced (the value can only match its ID), but that is handled in the `security` function.\n // From the self-enforced data, we can see all the edges in the graph that belong to a public key.\n // Example: ~ASDF is the ID of a node with ASDF as its public key, signed alias and salt, and\n // its encrypted private key, but it might also have other signed values on it like `profile = <ID>` edge.\n // Using that directed edge's ID, we can then track (in memory) which IDs belong to which keys.\n // Here is a problem: Multiple public keys can \"claim\" any node's ID, so this is dangerous!\n // This means we should ONLY trust our \"friends\" (our key ring) public keys, not any ones.\n // I have not yet added that to SEA yet in this alpha release. That is coming soon, but beware in the meanwhile!\n\n function check(msg){ // REVISE / IMPROVE, NO NEED TO PASS MSG/EVE EACH SUB?\n var eve = this, at = eve.as, put = msg.put, soul = put['#'], key = put['.'], val = put[':'], state = put['>'], id = msg['#'], tmp;\n if(!soul || !key){ return }\n if((msg._||'').faith && (at.opt||'').faith && 'function' == typeof msg._){\n SEA.opt.pack(put, function(raw){\n SEA.verify(raw, false, function(data){ // this is synchronous if false\n put['='] = SEA.opt.unpack(data);\n eve.to.next(msg);\n })})\n return \n }\n var no = function(why){ at.on('in', {'@': id, err: msg.err = why}) }; // exploit internal relay stun for now, maybe violates spec, but testing for now. // Note: this may be only the sharded message, not original batch.\n //var no = function(why){ msg.ack(why) };\n (msg._||'').DBG && ((msg._||'').DBG.c = +new Date);\n if(0 <= soul.indexOf('<?')){ // special case for \"do not sync data X old\" forget\n // 'a~pub.key/b<?9'\n tmp = parseFloat(soul.split('<?')[1]||'');\n if(tmp && (state < (Gun.state() - (tmp * 1000)))){ // sec to ms\n (tmp = msg._) && (tmp.stun) && (tmp.stun--); // THIS IS BAD CODE! It assumes GUN internals do something that will probably change in future, but hacking in now.\n return; // omit!\n }\n }\n \n if('~@' === soul){ // special case for shared system data, the list of aliases.\n check.alias(eve, msg, val, key, soul, at, no); return;\n }\n if('~@' === soul.slice(0,2)){ // special case for shared system data, the list of public keys for an alias.\n check.pubs(eve, msg, val, key, soul, at, no); return;\n }\n //if('~' === soul.slice(0,1) && 2 === (tmp = soul.slice(1)).split('.').length){ // special case, account data for a public key.\n if(tmp = SEA.opt.pub(soul)){ // special case, account data for a public key.\n check.pub(eve, msg, val, key, soul, at, no, at.user||'', tmp); return;\n }\n if(0 <= soul.indexOf('#')){ // special case for content addressing immutable hashed data.\n check.hash(eve, msg, val, key, soul, at, no); return;\n } \n check.any(eve, msg, val, key, soul, at, no, at.user||''); return;\n eve.to.next(msg); // not handled\n }\n check.hash = function(eve, msg, val, key, soul, at, no){ // mark unbuilt @i001962 's epic hex contrib!\n SEA.work(val, null, function(data){\n function hexToBase64(hexStr) {\n let base64 = \"\";\n for(let i = 0; i < hexStr.length; i++) {\n base64 += !(i - 1 & 1) ? String.fromCharCode(parseInt(hexStr.substring(i - 1, i + 1), 16)) : \"\"}\n return btoa(base64);} \n if(data && data === key.split('#').slice(-1)[0]){ return eve.to.next(msg) }\n else if (data && data === hexToBase64(key.split('#').slice(-1)[0])){ \n return eve.to.next(msg) }\n no(\"Data hash not same as hash!\");\n }, {name: 'SHA-256'});\n }\n check.alias = function(eve, msg, val, key, soul, at, no){ // Example: {_:#~@, ~@alice: {#~@alice}}\n if(!val){ return no(\"Data must exist!\") } // data MUST exist\n if('~@'+key === link_is(val)){ return eve.to.next(msg) } // in fact, it must be EXACTLY equal to itself\n no(\"Alias not same!\"); // if it isn't, reject.\n };\n check.pubs = function(eve, msg, val, key, soul, at, no){ // Example: {_:#~@alice, ~asdf: {#~asdf}}\n if(!val){ return no(\"Alias must exist!\") } // data MUST exist\n if(key === link_is(val)){ return eve.to.next(msg) } // and the ID must be EXACTLY equal to its property\n no(\"Alias not same!\"); // that way nobody can tamper with the list of public keys.\n };\n check.pub = async function(eve, msg, val, key, soul, at, no, user, pub){ var tmp // Example: {_:#~asdf, hello:'world'~fdsa}}\n const raw = await S.parse(val) || {}\n const verify = (certificate, certificant, cb) => {\n if (certificate.m && certificate.s && certificant && pub)\n // now verify certificate\n return SEA.verify(certificate, pub, data => { // check if \"pub\" (of the graph owner) really issued this cert\n if (u !== data && u !== data.e && msg.put['>'] && msg.put['>'] > parseFloat(data.e)) return no(\"Certificate expired.\") // certificate expired\n // \"data.c\" = a list of certificants/certified users\n // \"data.w\" = lex WRITE permission, in the future, there will be \"data.r\" which means lex READ permission\n if (u !== data && data.c && data.w && (data.c === certificant || data.c.indexOf('*' || certificant) > -1)) {\n // ok, now \"certificant\" is in the \"certificants\" list, but is \"path\" allowed? Check path\n let path = soul.indexOf('/') > -1 ? soul.replace(soul.substring(0, soul.indexOf('/') + 1), '') : ''\n String.match = String.match || Gun.text.match\n const w = Array.isArray(data.w) ? data.w : typeof data.w === 'object' || typeof data.w === 'string' ? [data.w] : []\n for (const lex of w) {\n if ((String.match(path, lex['#']) && String.match(key, lex['.'])) || (!lex['.'] && String.match(path, lex['#'])) || (!lex['#'] && String.match(key, lex['.'])) || String.match((path ? path + '/' + key : key), lex['#'] || lex)) {\n // is Certificant forced to present in Path\n if (lex['+'] && lex['+'].indexOf('*') > -1 && path && path.indexOf(certificant) == -1 && key.indexOf(certificant) == -1) return no(`Path \"${path}\" or key \"${key}\" must contain string \"${certificant}\".`)\n // path is allowed, but is there any WRITE block? Check it out\n if (data.wb && (typeof data.wb === 'string' || ((data.wb || {})['#']))) { // \"data.wb\" = path to the WRITE block\n var root = eve.as.root.$.back(-1)\n if (typeof data.wb === 'string' && '~' !== data.wb.slice(0, 1)) root = root.get('~' + pub)\n return root.get(data.wb).get(certificant).once(value => { // TODO: INTENT TO DEPRECATE.\n if (value && (value === 1 || value === true)) return no(`Certificant ${certificant} blocked.`)\n return cb(data)\n })\n }\n return cb(data)\n }\n }\n return no(\"Certificate verification fail.\")\n }\n })\n return\n }\n \n if ('pub' === key && '~' + pub === soul) {\n if (val === pub) return eve.to.next(msg) // the account MUST match `pub` property that equals the ID of the public key.\n return no(\"Account not same!\")\n }\n\n if ((tmp = user.is) && tmp.pub && !raw['*'] && !raw['+'] && (pub === tmp.pub || (pub !== tmp.pub && ((msg._.msg || {}).opt || {}).cert))){\n SEA.opt.pack(msg.put, packed => {\n SEA.sign(packed, (user._).sea, async function(data) {\n if (u === data) return no(SEA.err || 'Signature fail.')\n msg.put[':'] = {':': tmp = SEA.opt.unpack(data.m), '~': data.s}\n msg.put['='] = tmp\n \n // if writing to own graph, just allow it\n if (pub === user.is.pub) {\n if (tmp = link_is(val)) (at.sea.own[tmp] = at.sea.own[tmp] || {})[pub] = 1\n JSON.stringifyAsync(msg.put[':'], function(err,s){\n if(err){ return no(err || \"Stringify error.\") }\n msg.put[':'] = s;\n return eve.to.next(msg);\n })\n return\n }\n \n // if writing to other's graph, check if cert exists then try to inject cert into put, also inject self pub so that everyone can verify the put\n if (pub !== user.is.pub && ((msg._.msg || {}).opt || {}).cert) {\n const cert = await S.parse(msg._.msg.opt.cert)\n // even if cert exists, we must verify it\n if (cert && cert.m && cert.s)\n verify(cert, user.is.pub, _ => {\n msg.put[':']['+'] = cert // '+' is a certificate\n msg.put[':']['*'] = user.is.pub // '*' is pub of the user who puts\n JSON.stringifyAsync(msg.put[':'], function(err,s){\n if(err){ return no(err || \"Stringify error.\") }\n msg.put[':'] = s;\n return eve.to.next(msg);\n })\n return\n })\n }\n }, {raw: 1})\n })\n return;\n }\n\n SEA.opt.pack(msg.put, packed => {\n SEA.verify(packed, raw['*'] || pub, function(data){ var tmp;\n data = SEA.opt.unpack(data);\n if (u === data) return no(\"Unverified data.\") // make sure the signature matches the account it claims to be on. // reject any updates that are signed with a mismatched account.\n if ((tmp = link_is(data)) && pub === SEA.opt.pub(tmp)) (at.sea.own[tmp] = at.sea.own[tmp] || {})[pub] = 1\n \n // check if cert ('+') and putter's pub ('*') exist\n if (raw['+'] && raw['+']['m'] && raw['+']['s'] && raw['*'])\n // now verify certificate\n verify(raw['+'], raw['*'], _ => {\n msg.put['='] = data;\n return eve.to.next(msg);\n })\n else {\n msg.put['='] = data;\n return eve.to.next(msg);\n }\n });\n })\n return\n };\n check.any = function(eve, msg, val, key, soul, at, no, user){ var tmp, pub;\n if(at.opt.secure){ return no(\"Soul missing public key at '\" + key + \"'.\") }\n // TODO: Ask community if should auto-sign non user-graph data.\n at.on('secure', function(msg){ this.off();\n if(!at.opt.secure){ return eve.to.next(msg) }\n no(\"Data cannot be changed.\");\n }).on.on('secure', msg);\n return;\n }\n\n var valid = Gun.valid, link_is = function(d,l){ return 'string' == typeof (l = valid(d)) && l }, state_ify = (Gun.state||'').ify;\n\n var pubcut = /[^\\w_-]/; // anything not alphanumeric or _ -\n SEA.opt.pub = function(s){\n if(!s){ return }\n s = s.split('~');\n if(!s || !(s = s[1])){ return }\n s = s.split(pubcut).slice(0,2);\n if(!s || 2 != s.length){ return }\n if('@' === (s[0]||'')[0]){ return }\n s = s.slice(0,2).join('.');\n return s;\n }\n SEA.opt.stringy = function(t){\n // TODO: encrypt etc. need to check string primitive. Make as breaking change.\n }\n SEA.opt.pack = function(d,cb,k, n,s){ var tmp, f; // pack for verifying\n if(SEA.opt.check(d)){ return cb(d) }\n if(d && d['#'] && d['.'] && d['>']){ tmp = d[':']; f = 1 }\n JSON.parseAsync(f? tmp : d, function(err, meta){\n var sig = ((u !== (meta||'')[':']) && (meta||'')['~']); // or just ~ check?\n if(!sig){ cb(d); return }\n cb({m: {'#':s||d['#'],'.':k||d['.'],':':(meta||'')[':'],'>':d['>']||Gun.state.is(n, k)}, s: sig});\n });\n }\n var O = SEA.opt;\n SEA.opt.unpack = function(d, k, n){ var tmp;\n if(u === d){ return }\n if(d && (u !== (tmp = d[':']))){ return tmp }\n k = k || O.fall_key; if(!n && O.fall_val){ n = {}; n[k] = O.fall_val }\n if(!k || !n){ return }\n if(d === n[k]){ return d }\n if(!SEA.opt.check(n[k])){ return d }\n var soul = (n && n._ && n._['#']) || O.fall_soul, s = Gun.state.is(n, k) || O.fall_state;\n if(d && 4 === d.length && soul === d[0] && k === d[1] && fl(s) === fl(d[3])){\n return d[2];\n }\n if(s < SEA.opt.shuffle_attack){\n return d;\n }\n }\n SEA.opt.shuffle_attack = 1546329600000; // Jan 1, 2019\n var fl = Math.floor; // TODO: Still need to fix inconsistent state issue.\n // TODO: Potential bug? If pub/priv key starts with `-`? IDK how possible.\n\n })(USE, './index');\n}());\n","let contractAddresses = {\r\n PROOF_OF_INTEGRITY_ADDRESS: \"0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512\",\r\n STEALTH_ANNOUNCER_ADDRESS: \"0x5FbDB2315678afecb367f032d93F642f64180aa3\"\r\n};\r\n\r\nif (typeof window === 'undefined') {\r\n try {\r\n const { fileURLToPath } = require('url');\r\n const { dirname, join } = require('path');\r\n const { readFileSync } = require('fs');\r\n \r\n const __filename = fileURLToPath(import.meta.url);\r\n const __dirname = dirname(__filename);\r\n \r\n const rawdata = readFileSync(join(__dirname, 'contract-address.json'));\r\n contractAddresses = JSON.parse(rawdata);\r\n console.log(\"Loaded contract addresses:\", contractAddresses);\r\n } catch (error) {\r\n console.warn(\"Warning: contract-address.json not found or invalid\");\r\n }\r\n}\r\n\r\nexport const LOCAL_CONFIG = {\r\n CHAIN_ID: 1337,\r\n PROOF_OF_INTEGRITY_ADDRESS: contractAddresses.PROOF_OF_INTEGRITY_ADDRESS,\r\n STEALTH_ANNOUNCER_ADDRESS: contractAddresses.STEALTH_ANNOUNCER_ADDRESS,\r\n RPC_URL: \"http://127.0.0.1:8545\",\r\n GUN_PEER: \"http://localhost:8765/gun\"\r\n}; ","import { LOCAL_CONFIG } from '../config/local.js';\r\n\r\n// Indirizzi di produzione per diverse chain\r\nexport const CHAIN_CONFIG = {\r\n optimismSepolia: {\r\n STEALTH_ANNOUNCER_ADDRESS: \"0xD0F2e9DA59d2DFECFdE67CcF17300BB6093A72f8\",\r\n PROOF_OF_INTEGRITY_ADDRESS: \"0x...\",\r\n RPC_URL: \"https://sepolia.optimism.io\",\r\n CHAIN_ID: 11155420\r\n },\r\n arbitrumSepolia: {\r\n STEALTH_ANNOUNCER_ADDRESS: \"0x...\",\r\n PROOF_OF_INTEGRITY_ADDRESS: \"0x...\",\r\n RPC_URL: \"https://sepolia-rollup.arbitrum.io/rpc\",\r\n CHAIN_ID: 421614\r\n },\r\n localhost: {\r\n RPC_URL: \"http://127.0.0.1:8545\",\r\n CHAIN_ID: 1337\r\n }\r\n};\r\n\r\n// Funzione helper per verificare l'ambiente\r\nexport function isLocalEnvironment() {\r\n return process.env.NODE_ENV === 'development' && \r\n (typeof window === 'undefined' || window.location.hostname === 'localhost');\r\n}\r\n\r\n// Funzione per ottenere gli indirizzi corretti\r\nexport function getAddressesForChain(chainName) {\r\n let config;\r\n\r\n if (chainName === 'localhost') {\r\n if (typeof window === 'undefined') {\r\n // Server-side\r\n try {\r\n const { fileURLToPath } = require('url');\r\n const { dirname, join } = require('path');\r\n const { readFileSync } = require('fs');\r\n \r\n const __filename = fileURLToPath(import.meta.url);\r\n const __dirname = dirname(__filename);\r\n const localAddresses = JSON.parse(\r\n readFileSync(join(__dirname, '../config/contract-address.json'), 'utf8')\r\n );\r\n \r\n config = {\r\n ...LOCAL_CONFIG,\r\n ...localAddresses\r\n };\r\n } catch (err) {\r\n console.warn('No local addresses found:', err);\r\n throw new Error('No local addresses found. Did you run local deployment?');\r\n }\r\n } else {\r\n // Client-side\r\n config = LOCAL_CONFIG;\r\n }\r\n return config;\r\n }\r\n\r\n // Usa gli indirizzi di produzione\r\n config = CHAIN_CONFIG[chainName];\r\n if (!config) {\r\n throw new Error(`Chain ${chainName} not supported`);\r\n }\r\n\r\n return config;\r\n}\r\n\r\nexport const STEALTH_ANNOUNCER_ABI = [\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"_devAddress\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"constructor\"\r\n },\r\n {\r\n \"anonymous\": false,\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"senderPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"spendingPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"stealthAddress\",\r\n \"type\": \"address\"\r\n },\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"timestamp\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"name\": \"StealthPaymentAnnounced\",\r\n \"type\": \"event\"\r\n },\r\n {\r\n \"anonymous\": false,\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"newAddress\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"name\": \"DevAddressUpdated\",\r\n \"type\": \"event\"\r\n },\r\n {\r\n \"anonymous\": false,\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"newFee\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"name\": \"DevFeeUpdated\",\r\n \"type\": \"event\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"senderPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"spendingPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"stealthAddress\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"name\": \"announcePayment\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"payable\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [],\r\n \"name\": \"devAddress\",\r\n \"outputs\": [\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [],\r\n \"name\": \"devFee\",\r\n \"outputs\": [\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [],\r\n \"name\": \"getAnnouncementsCount\",\r\n \"outputs\": [\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"fromIndex\",\r\n \"type\": \"uint256\"\r\n },\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"toIndex\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"name\": \"getAnnouncementsInRange\",\r\n \"outputs\": [\r\n {\r\n \"components\": [\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"senderPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"spendingPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"stealthAddress\",\r\n \"type\": \"address\"\r\n },\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"timestamp\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"internalType\": \"struct StealthAnnouncer.StealthAnnouncement[]\",\r\n \"name\": \"\",\r\n \"type\": \"tuple[]\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"_newFee\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"name\": \"updateDevFee\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"_newAddress\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"name\": \"updateDevAddress\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [],\r\n \"name\": \"withdrawStuckETH\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"function\"\r\n }\r\n];\r\n\r\nexport const PROOF_OF_INTEGRITY_ABI = [\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"bytes[]\",\r\n \"name\": \"nodeIds\",\r\n \"type\": \"bytes[]\"\r\n },\r\n {\r\n \"internalType\": \"bytes32[]\",\r\n \"name\": \"contentHashes\",\r\n \"type\": \"bytes32[]\"\r\n }\r\n ],\r\n \"name\": \"batchUpdateData\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"anonymous\": false,\r\n \"inputs\": [\r\n {\r\n \"indexed\": true,\r\n \"internalType\": \"bytes\",\r\n \"name\": \"nodeId\",\r\n \"type\": \"bytes\"\r\n },\r\n {\r\n \"indexed\": false,\r\n \"internalType\": \"bytes32\",\r\n \"name\": \"contentHash\",\r\n \"type\": \"bytes32\"\r\n },\r\n {\r\n \"indexed\": false,\r\n \"internalType\": \"address\",\r\n \"name\": \"updater\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"name\": \"DataUpdated\",\r\n \"type\": \"event\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"bytes\",\r\n \"name\": \"nodeId\",\r\n \"type\": \"bytes\"\r\n }\r\n ],\r\n \"name\": \"getLatestRecord\",\r\n \"outputs\": [\r\n {\r\n \"internalType\": \"bytes32\",\r\n \"name\": \"\",\r\n \"type\": \"bytes32\"\r\n },\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"\",\r\n \"type\": \"uint256\"\r\n },\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"bytes\",\r\n \"name\": \"nodeId\",\r\n \"type\": \"bytes\"\r\n },\r\n {\r\n \"internalType\": \"bytes32\",\r\n \"name\": \"contentHash\",\r\n \"type\": \"bytes32\"\r\n }\r\n ],\r\n \"name\": \"updateData\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"bytes\",\r\n \"name\": \"nodeId\",\r\n \"type\": \"bytes\"\r\n },\r\n {\r\n \"internalType\": \"bytes32\",\r\n \"name\": \"contentHash\",\r\n \"type\": \"bytes32\"\r\n }\r\n ],\r\n \"name\": \"verifyData\",\r\n \"outputs\": [\r\n {\r\n \"internalType\": \"bool\",\r\n \"name\": \"\",\r\n \"type\": \"bool\"\r\n },\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"\",\r\n \"type\": \"uint256\"\r\n },\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n }\r\n];\r\n\r\nexport const PROOF_OF_INTEGRITY_ADDRESS = \"...\";\r\nexport const STEALTH_ANNOUNCER_ADDRESS = \"...\";\r\n\r\nexport const SHINE_OPTIMISM_SEPOLIA = \"0x43D838b683F772F08f321E5FA265ad3e333BE9C2\";\r\n","// =============================================\r\n// IMPORTS AND GLOBAL VARIABLES\r\n// =============================================\r\nimport Gun from \"gun\";\r\nimport SEA from \"gun/sea.js\";\r\nimport { ethers } from \"ethers\";\r\nimport { PROOF_OF_INTEGRITY_ABI, PROOF_OF_INTEGRITY_ADDRESS, STEALTH_ANNOUNCER_ABI, STEALTH_ANNOUNCER_ADDRESS } from \"./abis/abis.js\";\r\nimport { LOCAL_CONFIG } from \"./config/local.js\";\r\n\r\nlet PROOF_CONTRACT_ADDRESS;\r\nlet rpcUrl = \"\";\r\nlet privateKey = \"\";\r\n\r\nexport const MESSAGE_TO_SIGN = \"Access GunDB with Ethereum\";\r\n\r\nlet contractAddresses = {\r\n PROOF_OF_INTEGRITY_ADDRESS: null,\r\n STEALTH_ANNOUNCER_ADDRESS: STEALTH_ANNOUNCER_ADDRESS\r\n};\r\n\r\n// Solo per Node.js\r\nif (typeof window === 'undefined') {\r\n const { fileURLToPath } = require('url');\r\n const { dirname } = require('path');\r\n const { readFileSync } = require('fs');\r\n const path = require('path');\r\n \r\n const __filename = fileURLToPath(import.meta.url);\r\n const __dirname = dirname(__filename);\r\n\r\n try {\r\n const rawdata = readFileSync(path.join(__dirname, 'contract-address.json'), 'utf8');\r\n contractAddresses = JSON.parse(rawdata);\r\n console.log('Loaded contract addresses:', contractAddresses);\r\n } catch (err) {\r\n console.warn('Warning: contract-address.json not found or invalid');\r\n }\r\n}\r\n\r\n// =============================================\r\n// UTILITY FUNCTIONS\r\n// =============================================\r\n/**\r\n * Generates a random node ID for GunDB\r\n * @returns {string} A random hexadecimal string\r\n */\r\nexport function generateRandomId() {\r\n return ethers.hexlify(ethers.randomBytes(32)).slice(2);\r\n}\r\n\r\n/**\r\n * Generates a password from a signature.\r\n * @param {string} signature - The signature to derive the password from.\r\n * @returns {string|null} The generated password or null if generation fails.\r\n */\r\nexport function generatePassword(signature) {\r\n try {\r\n const hexSignature = ethers.hexlify(signature);\r\n const hash = ethers.keccak256(hexSignature);\r\n console.log(\"Generated password:\", hash);\r\n return hash;\r\n } catch (error) {\r\n console.error(\"Error generating password:\", error);\r\n return null;\r\n }\r\n}\r\n\r\n/**\r\n * Converts a Gun private key to an Ethereum account.\r\n * @param {string} gunPrivateKey - The Gun private key in base64url format.\r\n * @returns {Object} An object containing the Ethereum account and public key.\r\n */\r\nexport function gunToEthAccount(gunPrivateKey) {\r\n // Function to convert base64url to hex\r\n const base64UrlToHex = (base64url) => {\r\n const padding = \"=\".repeat((4 - (base64url.length % 4)) % 4);\r\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\") + padding;\r\n const binary = atob(base64);\r\n return Array.from(binary, (char) =>\r\n char.charCodeAt(0).toString(16).padStart(2, \"0\")\r\n ).join(\"\");\r\n };\r\n\r\n // Convert Gun private key to hex format\r\n const hexPrivateKey = \"0x\" + base64UrlToHex(gunPrivateKey);\r\n\r\n // Create an Ethereum wallet from the private key\r\n const wallet = new ethers.Wallet(hexPrivateKey);\r\n\r\n // Get the public address (public key)\r\n const publicKey = wallet.address;\r\n\r\n return {\r\n account: wallet,\r\n publicKey: publicKey,\r\n privateKey: hexPrivateKey,\r\n };\r\n}\r\n\r\n/**\r\n * Gets an Ethereum signer based on current configuration\r\n * @returns {Promise<ethers.Signer>} The configured signer\r\n * @throws {Error} If no valid provider is found\r\n */\r\nexport const getSigner = async () => {\r\n if (rpcUrl && privateKey) {\r\n // Standalone mode with local provider\r\n const provider = new ethers.JsonRpcProvider(rpcUrl, {\r\n chainId: LOCAL_CONFIG.CHAIN_ID,\r\n name: \"localhost\"\r\n });\r\n return new ethers.Wallet(privateKey, provider);\r\n } else if (\r\n typeof window !== \"undefined\" &&\r\n typeof window.ethereum !== \"undefined\"\r\n ) {\r\n // Browser mode\r\n await window.ethereum.request({ method: \"eth_requestAccounts\" });\r\n const provider = new ethers.BrowserProvider(window.ethereum);\r\n return provider.getSigner();\r\n } else {\r\n throw new Error(\"No valid Ethereum provider found\");\r\n }\r\n};\r\n\r\n/**\r\n * Utility function to generate stealth address\r\n * @param {string} sharedSecret - The shared secret\r\n * @param {string} spendingPublicKey - The spending public key\r\n * @returns {Object} The stealth address and private key\r\n */\r\nexport function deriveStealthAddress(sharedSecret, spendingPublicKey) {\r\n try {\r\n // Convert shared secret to bytes\r\n const sharedSecretBytes = Buffer.from(sharedSecret, 'base64');\r\n \r\n // Generate stealth private key using shared secret and spending public key\r\n const stealthPrivateKey = ethers.keccak256(\r\n ethers.concat([\r\n sharedSecretBytes,\r\n ethers.getBytes(spendingPublicKey)\r\n ])\r\n );\r\n \r\n // Create stealth wallet\r\n const stealthWallet = new ethers.Wallet(stealthPrivateKey);\r\n\r\n console.log(\"Debug deriveStealthAddress:\", {\r\n sharedSecretHex: ethers.hexlify(sharedSecretBytes),\r\n spendingPublicKey,\r\n stealthPrivateKey,\r\n stealthAddress: stealthWallet.address\r\n });\r\n\r\n return {\r\n stealthPrivateKey,\r\n stealthAddress: stealthWallet.address,\r\n wallet: stealthWallet\r\n };\r\n } catch (error) {\r\n console.error(\"Error in deriveStealthAddress:\", error);\r\n throw error;\r\n }\r\n}\r\n\r\n// =============================================\r\n// BASIC GUN-ETH CHAIN METHODS\r\n// =============================================\r\n\r\n// Set the message to sign\r\nGun.chain.MESSAGE_TO_SIGN = MESSAGE_TO_SIGN;\r\n\r\n/**\r\n * Sets standalone configuration for Gun.\r\n * @param {string} newRpcUrl - The new RPC URL.\r\n * @param {string} newPrivateKey - The new private key.\r\n * @returns {Gun} The Gun instance for chaining.\r\n */\r\nGun.chain.setSigner = function (newRpcUrl, newPrivateKey) {\r\n rpcUrl = newRpcUrl;\r\n privateKey = newPrivateKey;\r\n console.log(\"Standalone configuration set\");\r\n return this;\r\n};\r\n\r\nGun.chain.getSigner = getSigner();\r\n\r\n/**\r\n * Verifies an Ethereum signature.\r\n * @param {string} message - The original message that was signed.\r\n * @param {string} signature - The signature to verify.\r\n * @returns {Promise<string|null>} The recovered address or null if verification fails.\r\n */\r\nGun.chain.verifySignature = async function (message, signature) {\r\n try {\r\n const recoveredAddress = ethers.verifyMessage(message, signature);\r\n return recoveredAddress;\r\n } catch (error) {\r\n console.error(\"Error verifying signature:\", error);\r\n return null;\r\n }\r\n};\r\n\r\n/**\r\n * Generates a password from a signature.\r\n * @param {string} signature - The signature to derive the password from.\r\n * @returns {string|null} The generated password or null if generation fails.\r\n */\r\nGun.chain.generatePassword = function (signature) {\r\n return generatePassword(signature);\r\n};\r\n\r\n/**\r\n * Creates an Ethereum signature for a given message.\r\n * @param {string} message - The message to sign.\r\n * @returns {Promise<string|null>} The signature or null if signing fails.\r\n */\r\nGun.chain.createSignature = async function (message) {\r\n try {\r\n // Check if message matches MESSAGE_TO_SIGN\r\n if (message !== MESSAGE_TO_SIGN) {\r\n throw new Error(\"Invalid message, valid message is: \" + MESSAGE_TO_SIGN);\r\n }\r\n const signer = await getSigner();\r\n const signature = await signer.signMessage(message);\r\n console.log(\"Signature created:\", signature);\r\n return signature;\r\n } catch (error) {\r\n console.error(\"Error creating signature:\", error);\r\n return null;\r\n }\r\n};\r\n\r\n// =============================================\r\n// KEY PAIR MANAGEMENT\r\n// =============================================\r\n/**\r\n * Creates and stores an encrypted key pair for a given address.\r\n * @param {string} address - The Ethereum address to associate with the key pair.\r\n * @param {string} signature - The signature to use for encryption.\r\n * @returns {Promise<void>}\r\n */\r\nGun.chain.createAndStoreEncryptedPair = async function (address, signature) {\r\n try {\r\n const gun = this;\r\n const pair = await SEA.pair();\r\n const v_pair = await SEA.pair();\r\n const s_pair = await SEA.pair();\r\n const password = generatePassword(signature);\r\n\r\n // Save original SEA pairs\r\n const encryptedPair = await SEA.encrypt(JSON.stringify(pair), password);\r\n const encryptedV_pair = await SEA.encrypt(JSON.stringify(v_pair), password);\r\n const encryptedS_pair = await SEA.encrypt(JSON.stringify(s_pair), password);\r\n\r\n // Convert only to get Ethereum addresses\r\n const viewingAccount = gunToEthAccount(v_pair.priv);\r\n const spendingAccount = gunToEthAccount(s_pair.priv);\r\n\r\n gun.get(\"gun-eth\").get(\"users\").get(address).put({\r\n pair: encryptedPair,\r\n v_pair: encryptedV_pair,\r\n s_pair: encryptedS_pair,\r\n publicKeys: {\r\n viewingPublicKey: v_pair.epub, // Use SEA encryption public key\r\n viewingPublicKey: v_pair.epub, // Use SEA encryption public key\r\n spendingPublicKey: spendingAccount.publicKey, // Use Ethereum address\r\n ethViewingAddress: viewingAccount.publicKey // Also save Ethereum address\r\n }\r\n });\r\n\r\n console.log(\"Encrypted pairs and public keys stored for:\", address);\r\n } catch (error) {\r\n console.error(\"Error creating and storing encrypted pair:\", error);\r\n throw error;\r\n }\r\n};\r\n\r\n/**\r\n * Retrieves and decrypts a stored key pair for a given address.\r\n * @param {string} address - The Ethereum address associated with the key pair.\r\n * @param {string} signature - The signature to use for decryption.\r\n * @returns {Promise<Object|null>} The decrypted key pair or null if retrieval fails.\r\n */\r\nGun.chain.getAndDecryptPair = async function (address, signature) {\r\n try {\r\n const gun = this;\r\n const encryptedData = await gun\r\n .get(\"gun-eth\")\r\n .get(\"users\")\r\n .get(address)\r\n .get(\"pair\")\r\n .then();\r\n if (!encryptedData) {\r\n throw new Error(\"No encrypted data found for this address\");\r\n }\r\n const password = generatePassword(signature);\r\n const decryptedPair = await SEA.decrypt(encryptedData, password);\r\n console.log(decryptedPair);\r\n return decryptedPair;\r\n } catch (error) {\r\n console.error(\"Error retrieving and decrypting pair:\", error);\r\n return null;\r\n }\r\n};\r\n\r\n// =============================================\r\n// PROOF OF INTEGRITY\r\n// =============================================\r\n/**\r\n * Proof of Integrity\r\n * @param {string} chain - The blockchain to use (e.g., \"optimismSepolia\").\r\n * @param {string} nodeId - The ID of the node to verify or write.\r\n * @param {Object} data - The data to write (if writing).\r\n * @param {Function} callback - Callback function to handle the result.\r\n * @returns {Gun} The Gun instance for chaining.\r\n */\r\nGun.chain.proof = function (chain, nodeId, data, callback) {\r\n console.log(\"Proof plugin called with:\", { chain, nodeId, data });\r\n\r\n if (typeof callback !== \"function\") {\r\n console.error(\"Callback must be a function\");\r\n return this;\r\n }\r\n\r\n try {\r\n // Se siamo in localhost e in development, usa automaticamente la chain locale\r\n const targetChain = isLocalEnvironment() ? 'localhost' : chain;\r\n const chainConfig = getAddressesForChain(targetChain);\r\n \r\n console.log(`Using ${targetChain} configuration:`, chainConfig);\r\n\r\n // Usa gli indirizzi dalla configurazione\r\n const contract = new ethers.Contract(\r\n chainConfig.PROOF_OF_INTEGRITY_ADDRESS,\r\n PROOF_OF_INTEGRITY_ABI,\r\n signer\r\n );\r\n\r\n // Funzione per verificare on-chain\r\n const verifyOnChain = async (nodeId, contentHash) => {\r\n console.log(\"Verifying on chain:\", { nodeId, contentHash });\r\n const signer = await getSigner();\r\n const contract = new ethers.Contract(\r\n PROOF_CONTRACT_ADDRESS,\r\n PROOF_OF_INTEGRITY_ABI,\r\n signer\r\n );\r\n const [isValid, timestamp, updater] = await contract.verifyData(\r\n ethers.toUtf8Bytes(nodeId),\r\n contentHash\r\n );\r\n console.log(\"Verification result:\", { isValid, timestamp, updater });\r\n return { isValid, timestamp, updater };\r\n };\r\n\r\n // Funzione per scrivere on-chain\r\n const writeOnChain = async (nodeId, contentHash) => {\r\n console.log(\"Writing on chain:\", { nodeId, contentHash });\r\n const signer = await getSigner();\r\n const contract = new ethers.Contract(\r\n PROOF_CONTRACT_ADDRESS,\r\n PROOF_OF_INTEGRITY_ABI,\r\n signer\r\n );\r\n const tx = await contract.updateData(\r\n ethers.toUtf8Bytes(nodeId),\r\n contentHash\r\n );\r\n console.log(\"Transaction sent:\", tx.hash);\r\n const receipt = await tx.wait();\r\n console.log(\"Transaction confirmed:\", receipt);\r\n return tx;\r\n };\r\n\r\n // Funzione per ottenere l'ultimo record\r\n const getLatestRecord = async (nodeId) => {\r\n const signer = await getSigner();\r\n const contract = new ethers.Contract(\r\n PROOF_CONTRACT_ADDRESS,\r\n PROOF_OF_INTEGRITY_ABI,\r\n signer\r\n );\r\n const [contentHash, timestamp, updater] = await contract.getLatestRecord(\r\n ethers.toUtf8Bytes(nodeId)\r\n );\r\n console.log(\"Latest record from blockchain:\", {\r\n nodeId,\r\n contentHash,\r\n timestamp,\r\n updater,\r\n });\r\n return { contentHash, timestamp, updater };\r\n };\r\n\r\n \r\n if (nodeId && !data) {\r\n // Case 1: User passes only node\r\n gun.get(nodeId).once(async (existingData) => {\r\n if (!existingData) {\r\n if (callback) callback({ err: \"Node not found in GunDB\" });\r\n return;\r\n }\r\n\r\n console.log(\"existingData\", existingData);\r\n\r\n // Use stored contentHash instead of recalculating\r\n const contentHash = existingData._contentHash;\r\n console.log(\"contentHash\", contentHash);\r\n\r\n if (!contentHash) {\r\n if (callback) callback({ err: \"No content hash found for this node\" });\r\n return;\r\n }\r\n\r\n try {\r\n const { isValid, timestamp, updater } = await verifyOnChain(\r\n nodeId,\r\n contentHash\r\n );\r\n const latestRecord = await getLatestRecord(nodeId);\r\n\r\n if (isValid) {\r\n if (callback)\r\n callback({\r\n ok: true,\r\n message: \"Data verified on blockchain\",\r\n timestamp,\r\n updater,\r\n latestRecord,\r\n });\r\n } else {\r\n if (callback)\r\n callback({\r\n ok: false,\r\n message: \"Data not verified on blockchain\",\r\n latestRecord,\r\n });\r\n }\r\n } catch (error) {\r\n if (callback) callback({ err: error.message });\r\n }\r\n });\r\n } else if (data && !nodeId) {\r\n // Case 2: User passes only text (data)\r\n const newNodeId = generateRandomId();\r\n const dataString = JSON.stringify(data);\r\n const contentHash = ethers.keccak256(ethers.toUtf8Bytes(dataString));\r\n\r\n gun\r\n .get(newNodeId)\r\n .put({ ...data, _contentHash: contentHash }, async (ack) => {\r\n console.log(\"ack\", ack);\r\n if (ack.err) {\r\n if (callback) callback({ err: \"Error saving data to GunDB\" });\r\n return;\r\n }\r\n\r\n try {\r\n const tx = await writeOnChain(newNodeId, contentHash);\r\n if (callback)\r\n callback({\r\n ok: true,\r\n message: \"Data written to GunDB and blockchain\",\r\n nodeId: newNodeId,\r\n txHash: tx.hash,\r\n });\r\n } catch (error) {\r\n if (callback) callback({ err: error.message });\r\n }\r\n });\r\n } else {\r\n if (callback)\r\n callback({\r\n err: \"Invalid input. Provide either nodeId or data, not both.\",\r\n });\r\n }\r\n\r\n return gun;\r\n } catch (error) {\r\n callback({ err: error.message });\r\n return this;\r\n }\r\n};\r\n\r\n// =============================================\r\n// STEALTH ADDRESS CORE FUNCTIONS\r\n// =============================================\r\n/**\r\n * Converts a Gun private key to an Ethereum account.\r\n * @param {string} gunPrivateKey - The Gun private key in base64url format.\r\n * @returns {Object} An object containing the Ethereum account and public key.\r\n */\r\nGun.chain.gunToEthAccount = function (gunPrivateKey) {\r\n return gunToEthAccount(gunPrivateKey);\r\n};\r\n\r\n/**\r\n * Generate a stealth key and related key pairs\r\n * @param {string} recipientAddress - The recipient's Ethereum address\r\n * @param {string} signature - The sender's signature to access their keys\r\n * @returns {Promise<Object>} Object containing stealth addresses and keys\r\n */\r\nGun.chain.generateStealthAddress = async function (recipientAddress, signature) {\r\n try {\r\n const gun = this;\r\n \r\n // Get recipient's public keys\r\n const recipientData = await gun\r\n .get(\"gun-eth\")\r\n .get(\"users\")\r\n .get(recipientAddress)\r\n .get(\"publicKeys\")\r\n .then();\r\n\r\n if (!recipientData || !recipientData.viewingPublicKey || !recipientData.spendingPublicKey) {\r\n throw new Error(\"Recipient's public keys not found\");\r\n }\r\n\r\n // Get sender's keys\r\n const senderAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);\r\n const password = generatePassword(signature);\r\n \r\n const senderData = await gun\r\n .get(\"gun-eth\")\r\n .get(\"users\")\r\n .get(senderAddress)\r\n .then();\r\n\r\n if (!senderData || !senderData.s_pair) {\r\n throw new Error(\"Sender's keys not found\");\r\n }\r\n\r\n // Decrypt sender's spending pair\r\n let spendingKeyPair;\r\n try {\r\n const decryptedData = await SEA.decrypt(senderData.s_pair, password);\r\n spendingKeyPair = typeof decryptedData === 'string' ? \r\n JSON.parse(decryptedData) : \r\n decryptedData;\r\n } catch (error) {\r\n console.error(\"Error decrypting spending pair:\", error);\r\n throw new Error(\"Unable to decrypt spending pair\");\r\n }\r\n\r\n // Generate shared secret using SEA ECDH with encryption public key\r\n const sharedSecret = await SEA.secret(recipientData.viewingPublicKey, spendingKeyPair);\r\n\r\n if (!sharedSecret) {\r\n throw new Error(\"Unable to generate shared secret\");\r\n }\r\n\r\n console.log(\"Generate shared secret:\", sharedSecret);\r\n\r\n const { stealthAddress } = deriveStealthAddress(\r\n sharedSecret,\r\n recipientData.spendingPublicKey\r\n );\r\n\r\n return {\r\n stealthAddress,\r\n senderPublicKey: spendingKeyPair.epub, // Use encryption public key\r\n spendingPublicKey: recipientData.spendingPublicKey\r\n };\r\n\r\n } catch (error) {\r\n console.error(\"Error generating stealth address:\", error);\r\n throw error;\r\n }\r\n};\r\n\r\n/**\r\n * Publish public keys needed to receive stealth payments\r\n * @param {string} signature - The signature to authenticate the user\r\n * @returns {Promise<void>}\r\n */\r\nGun.chain.publishStealthKeys = async function (signature) {\r\n try {\r\n const gun = this;\r\n const address = await this.verifySignature(MESSAGE_TO_SIGN, signature);\r\n const password = generatePassword(signature);\r\n\r\n // Get encrypted key pairs\r\n const encryptedData = await gun\r\n .get(\"gun-eth\")\r\n .get(\"users\")\r\n .get(address)\r\n .then();\r\n\r\n if (!encryptedData || !encryptedData.v_pair || !encryptedData.s_pair) {\r\n throw new Error(\"Keys not found\");\r\n }\r\n\r\n // Decrypt viewing and spending pairs\r\n const viewingKeyPair = JSON.parse(\r\n await SEA.decrypt(encryptedData.v_pair, password)\r\n );\r\n const spendingKeyPair = JSON.parse(\r\n await SEA.decrypt(encryptedData.s_pair, password)\r\n );\r\n\r\n const viewingAccount = gunToEthAccount(viewingKeyPair.priv);\r\n const spendingAccount = gunToEthAccount(spendingKeyPair.priv);\r\n\r\n // Publish only public keys\r\n gun.get(\"gun-eth\").get(\"users\").get(address).get(\"publicKeys\").put({\r\n viewingPublicKey: viewingAccount.publicKey,\r\n spendingPublicKey: spendingAccount.publicKey,\r\n });\r\n\r\n console.log(\"Stealth public keys published successfully\");\r\n } catch (error) {\r\n console.error(\"Error publishing stealth keys:\", error);\r\n throw error;\r\n }\r\n};\r\n\r\n// =============================================\r\n// STEALTH PAYMENT FUNCTIONS\r\n// =============================================\r\n/**\r\n * Recover funds from a stealth address\r\n * @param {string} stealthAddress - The stealth address to recover funds from\r\n * @param {string} senderPublicKey - The sender's public key used to generate the address\r\n * @param {string} signature - The signature to decrypt private keys\r\n * @returns {Promise<Object>} Object containing wallet to access funds\r\n */\r\nGun.chain.recoverStealthFunds = async function (\r\n stealthAddress,\r\n senderPublicKey,\r\n signature,\r\n spendingPublicKey\r\n) {\r\n try {\r\n const gun = this;\r\n const password = generatePassword(signature);\r\n\r\n // Get own key pairs\r\n const myAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);\r\n const encryptedData = await gun\r\n .get(\"gun-eth\")\r\n .get(\"users\")\r\n .get(myAddress)\r\n .then();\r\n\r\n if (!encryptedData || !encryptedData.v_pair || !encryptedData.s_pair) {\r\n throw new Error(\"Keys not found\");\r\n }\r\n\r\n // Decrypt viewing and spending pairs\r\n let viewingKeyPair;\r\n try {\r\n const decryptedViewingData = await SEA.decrypt(encryptedData.v_pair, password);\r\n viewingKeyPair = typeof decryptedViewingData === 'string' ? \r\n JSON.parse(decryptedViewingData) : \r\n decryptedViewingData;\r\n } catch (error) {\r\n console.error(\"Error decrypting keys:\", error);\r\n throw new Error(\"Unable to decrypt keys\");\r\n }\r\n\r\n // Generate shared secret using SEA ECDH\r\n const sharedSecret = await SEA.secret(senderPublicKey, viewingKeyPair);\r\n\r\n if (!sharedSecret) {\r\n throw new Error(\"Unable to generate shared secret\");\r\n }\r\n\r\n console.log(\"Recover shared secret:\", sharedSecret);\r\n\r\n const { wallet, stealthAddress: recoveredAddress } = deriveStealthAddress(\r\n sharedSecret,\r\n spendingPublicKey\r\n );\r\n\r\n // Verify address matches\r\n if (recoveredAddress.toLowerCase() !== stealthAddress.toLowerCase()) {\r\n console.error(\"Mismatch:\", {\r\n recovered: recoveredAddress,\r\n expected: stealthAddress,\r\n sharedSecret\r\n });\r\n throw new Error(\"Recovered stealth address does not match\");\r\n }\r\n\r\n return {\r\n wallet,\r\n address: recoveredAddress,\r\n };\r\n } catch (error) {\r\n console.error(\"Error recovering stealth funds:\", error);\r\n throw error;\r\n }\r\n};\r\n\r\n/**\r\n * Announce a stealth payment\r\n * @param {string} stealthAddress - The generated stealth address\r\n * @param {string} senderPublicKey - The sender's public key\r\n * @param {string} spendingPublicKey - The spending public key\r\n * @param {string} signature - The sender's signature\r\n * @returns {Promise<void>}\r\n */\r\nGun.chain.announceStealthPayment = async function (\r\n stealthAddress,\r\n senderPublicKey,\r\n spendingPublicKey,\r\n signature,\r\n options = { onChain: false, chain: 'optimismSepolia' }\r\n) {\r\n try {\r\n const gun = this;\r\n const senderAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);\r\n\r\n if (options.onChain) {\r\n // On-chain announcement\r\n const signer = await getSigner();\r\n const chainAddresses = getAddressesForChain(options.chain);\r\n const contractAddress = chainAddresses.STEALTH_ANNOUNCER_ADDRESS;\r\n\r\n console.log(\"Using contract address:\", contractAddress);\r\n\r\n const contract = new ethers.Contract(\r\n contractAddress,\r\n STEALTH_ANNOUNCER_ABI,\r\n signer\r\n );\r\n\r\n // Get dev fee from contract\r\n const devFee = await contract.devFee();\r\n console.log(\"Dev fee:\", devFee.toString());\r\n\r\n // Call contract\r\n const tx = await contract.announcePayment(\r\n senderPublicKey,\r\n spendingPublicKey,\r\n stealthAddress,\r\n { value: devFee }\r\n );\r\n \r\n console.log(\"Transaction sent:\", tx.hash);\r\n const receipt = await tx.wait();\r\n console.log(\"Transaction confirmed:\", receipt.hash);\r\n \r\n console.log(\"Stealth payment announced on-chain (dev fee paid)\");\r\n } else {\r\n // Off-chain announcement (GunDB)\r\n gun\r\n .get(\"gun-eth\")\r\n .get(\"stealth-payments\")\r\n .set({\r\n stealthAddress,\r\n senderAddress,\r\n senderPublicKey,\r\n spendingPublicKey,\r\n timestamp: Date.now(),\r\n });\r\n console.log(\"Stealth payment announced off-chain\");\r\n }\r\n } catch (error) {\r\n console.error(\"Error announcing stealth payment:\", error);\r\n console.error(\"Error details:\", error.stack);\r\n throw error;\r\n }\r\n};\r\n\r\n/**\r\n * Get all stealth payments for an address\r\n * @param {string} signature - The signature to authenticate the user\r\n * @returns {Promise<Array>} List of stealth payments\r\n */\r\nGun.chain.getStealthPayments = async function (signature, options = { source: 'both' }) {\r\n try {\r\n const payments = [];\r\n\r\n if (options.source === 'onChain' || options.source === 'both') {\r\n // Get on-chain payments\r\n const signer = await getSigner();\r\n const contractAddress = process.env.NODE_ENV === 'development' \r\n ? LOCAL_CONFIG.STEALTH_ANNOUNCER_ADDRESS \r\n : STEALTH_ANNOUNCER_ADDRESS;\r\n\r\n const contract = new ethers.Contract(\r\n contractAddress,\r\n STEALTH_ANNOUNCER_ABI,\r\n signer\r\n );\r\n \r\n try {\r\n // Get total number of announcements\r\n const totalAnnouncements = await contract.getAnnouncementsCount();\r\n const totalCount = Number(totalAnnouncements.toString());\r\n console.log(\"Total on-chain announcements:\", totalCount);\r\n \r\n if (totalCount > 0) {\r\n // Get announcements in batches of 100\r\n const batchSize = 100;\r\n const lastIndex = totalCount - 1;\r\n \r\n for(let i = 0; i <= lastIndex; i += batchSize) {\r\n const toIndex = Math.min(i + batchSize - 1, lastIndex);\r\n const batch = await contract.getAnnouncementsInRange(i, toIndex);\r\n \r\n // For each announcement, try to decrypt\r\n for(const announcement of batch) {\r\n try {\r\n // Verify announcement is valid\r\n if (!announcement || !announcement.stealthAddress || \r\n !announcement.senderPublicKey || !announcement.spendingPublicKey) {\r\n console.log(\"Invalid announcement:\", announcement);\r\n continue;\r\n }\r\n\r\n // Try to recover funds to verify if announcement is for us\r\n const recoveredWallet = await this.recoverStealthFunds(\r\n announcement.stealthAddress,\r\n announcement.senderPublicKey,\r\n signature,\r\n announcement.spendingPublicKey\r\n );\r\n \r\n // If no errors thrown, announcement is for us\r\n payments.push({\r\n stealthAddress: announcement.stealthAddress,\r\n senderPublicKey: announcement.senderPublicKey,\r\n spendingPublicKey: announcement.spendingPublicKey,\r\n timestamp: Number(announcement.timestamp),\r\n source: 'onChain',\r\n wallet: recoveredWallet\r\n });\r\n\r\n } catch (e) {\r\n // Not for us, continue\r\n console.log(`Announcement not for us: ${announcement.stealthAddress}`);\r\n continue;\r\n }\r\n }\r\n }\r\n }\r\n } catch (error) {\r\n console.error(\"Error retrieving on-chain announcements:\", error);\r\n }\r\n }\r\n\r\n if (options.source === 'offChain' || options.source === 'both') {\r\n // Get off-chain payments\r\n const gun = this;\r\n const offChainPayments = await new Promise((resolve) => {\r\n const p = [];\r\n gun\r\n .get(\"gun-eth\")\r\n .get(\"stealth-payments\")\r\n .get(recipientAddress)\r\n .map()\r\n .once((payment, id) => {\r\n if (payment?.stealthAddress) {\r\n p.push({ ...payment, id, source: 'offChain' });\r\n }\r\n });\r\n setTimeout(() => resolve(p), 2000);\r\n });\r\n \r\n payments.push(...offChainPayments);\r\n }\r\n\r\n console.log(`Found ${payments.length} stealth payments`);\r\n return payments;\r\n } catch (error) {\r\n console.error(\"Error retrieving stealth payments:\", error);\r\n throw error;\r\n }\r\n};\r\n\r\n/**\r\n * Clean up old stealth payments\r\n * @param {string} recipientAddress - The recipient's address\r\n * @returns {Promise<void>}\r\n */\r\nGun.chain.cleanStealthPayments = async function(recipientAddress) {\r\n try {\r\n const gun = this;\r\n const payments = await gun\r\n .get(\"gun-eth\")\r\n .get(\"stealth-payments\")\r\n .get(recipientAddress)\r\n .map()\r\n .once()\r\n .then();\r\n\r\n // Remove empty or invalid nodes\r\n if (payments) {\r\n Object.keys(payments).forEach(async (key) => {\r\n const payment = payments[key];\r\n if (!payment || !payment.stealthAddress || !payment.senderPublicKey || !payment.spendingPublicKey) {\r\n await gun\r\n .get(\"gun-eth\")\r\n .get(\"stealth-payments\")\r\n .get(recipientAddress)\r\n .get(key)\r\n .put(null);\r\n }\r\n });\r\n }\r\n } catch (error) {\r\n console.error(\"Error cleaning stealth payments:\", error);\r\n }\r\n};\r\n\r\n// =============================================\r\n// EXPORTS\r\n// =============================================\r\n\r\n// Crea una classe GunEth che contiene tutti i metodi e le utility\r\nexport class GunEth {\r\n // Static utility methods\r\n static generateRandomId = generateRandomId;\r\n static generatePassword = generatePassword;\r\n static gunToEthAccount = gunToEthAccount;\r\n static getSigner = getSigner;\r\n static deriveStealthAddress = deriveStealthAddress;\r\n \r\n // Chain methods\r\n static chainMethods = {\r\n setSigner: Gun.chain.setSigner,\r\n getSigner: Gun.chain.getSigner,\r\n verifySignature: Gun.chain.verifySignature,\r\n generatePassword: Gun.chain.generatePassword,\r\n createSignature: Gun.chain.createSignature,\r\n createAndStoreEncryptedPair: Gun.chain.createAndStoreEncryptedPair,\r\n getAndDecryptPair: Gun.chain.getAndDecryptPair,\r\n proof: Gun.chain.proof,\r\n gunToEthAccount: Gun.chain.gunToEthAccount,\r\n generateStealthAddress: Gun.chain.generateStealthAddress,\r\n publishStealthKeys: Gun.chain.publishStealthKeys,\r\n recoverStealthFunds: Gun.chain.recoverStealthFunds,\r\n announceStealthPayment: Gun.chain.announceStealthPayment,\r\n getStealthPayments: Gun.chain.getStealthPayments,\r\n cleanStealthPayments: Gun.chain.cleanStealthPayments\r\n };\r\n\r\n // Constants\r\n static MESSAGE_TO_SIGN = MESSAGE_TO_SIGN;\r\n static PROOF_CONTRACT_ADDRESS = PROOF_CONTRACT_ADDRESS;\r\n static LOCAL_CONFIG = LOCAL_CONFIG;\r\n}\r\n\r\n// Esporta Gun come default\r\nexport default Gun;\r\n"],"names":["USE","arg","req","require","slice","R","mod","path","exports","p","split","toString","replace","MODULE","module","self","window","SEA","u","e","location","protocol","indexOf","host","test","hostname","console","warn","btoa","Buffer","global","log","data","from","atob","SeaArray","Object","assign","Array","prototype","create","enc","start","end","length","this","buf","Uint8Array","keys","map","i","padStart","join","_","String","fromCharCode","SafeBuffer","props","arguments","TypeError","input","bytes","match","byte","parseInt","words","Uint16Array","charCodeAt","dec","info","byteLength","ArrayBuffer","alloc","fill","allocUnsafe","concat","arr","isArray","reduce","ret","item","api","o","JSON","parseAsync","t","cb","r","parse","stringifyAsync","v","s","stringify","Promise","res","rej","err","raw","crypto","msCrypto","subtle","webkitSubtle","TextEncoder","TextDecoder","random","len","getRandomValues","randomBytes","Crypto","WebCrypto","ossl","directory","shim","hash","name","iter","ks","pair","namedCurve","sign","pub","d","jwk","kty","crv","x","y","ext","key_ops","keyBytes","k","alg","validity","hook","async","yes","opt","digest","encode","__shim","b","S","sha","work","salt","epub","Function","toLowerCase","rsha","key","importKey","deriveBits","iterations","pbkdf2","throw","ecdhSubtle","sa","generateKey","then","priv","exportKey","privateKey","publicKey","dh","epriv","I","what","how","why","json","check","verify","m","sig","slow_leak","fallback","fall_verify","knownKeys","O","f","tmp","unpack","fall_soul","fall_key","fall_val","fall_state","sha256hash","combo","jwkKey","keyToJwk","aeskey","encrypt","msg","rand","iv","ct","aes","decrypt","bufiv","bufct","tagLength","decode","secret","pubKeyData","keysToEcdhJwk","public","privKeyData","privKey","derivedBits","rawBits","derivedKey","certify","certificants","policy","authority","certificant","push","expiry","parseFloat","readPolicy","read","writePolicy","write","block","blacklist","ban","readBlock","writeBlock","c","w","rb","wb","keyid","pb","id","sha1","sha1hash","GUN","Gun","User","root","$","lex","state","chain","F","constructor","user","back","get","at","uuid","is","call","gun","once","noop","args","alias","pass","filter","cat","ing","wait","act","pubs","already","ack","leave","proof","sea","auth","ek","g","put","on","h","link","eve","off","ok","a","sS","sessionStorage","recall","obj_ify","tries","forEach","list","shift","half","lol","tag","upt","graph","shuffle","change","z","remember","setTimeout","plugin","proxy","Proxy","DANGER","delete","alive","gunRoot","authRecall","trust","ctx","ev","theirPubkey","grant","to","sec","as","soul","val","faith","pack","next","no","DBG","Date","stun","any","own","hexStr","base64","substring","hexToBase64","link_is","certificate","text","value","cert","packed","secure","valid","l","ify","pubcut","stringy","n","meta","fl","shuffle_attack","Math","floor","contractAddresses","PROOF_OF_INTEGRITY_ADDRESS","STEALTH_ANNOUNCER_ADDRESS","fileURLToPath","dirname","readFileSync","__filename","document","pathToFileURL","href","_documentCurrentScript","tagName","toUpperCase","src","URL","baseURI","rawdata","error","LOCAL_CONFIG","CHAIN_ID","RPC_URL","GUN_PEER","STEALTH_ANNOUNCER_ABI","inputs","internalType","type","stateMutability","anonymous","outputs","components","PROOF_OF_INTEGRITY_ABI","indexed","PROOF_CONTRACT_ADDRESS","rpcUrl","MESSAGE_TO_SIGN","__dirname","generateRandomId","ethers","hexlify","generatePassword","signature","hexSignature","keccak256","gunToEthAccount","gunPrivateKey","hexPrivateKey","base64url","padding","repeat","binary","char","base64UrlToHex","wallet","Wallet","account","address","getSigner","provider","JsonRpcProvider","chainId","ethereum","request","method","BrowserProvider","Error","deriveStealthAddress","sharedSecret","spendingPublicKey","sharedSecretBytes","stealthPrivateKey","getBytes","stealthWallet","sharedSecretHex","stealthAddress","setSigner","newRpcUrl","newPrivateKey","verifySignature","message","verifyMessage","createSignature","signer","signMessage","createAndStoreEncryptedPair","v_pair","s_pair","password","encryptedPair","encryptedV_pair","encryptedS_pair","viewingAccount","spendingAccount","publicKeys","viewingPublicKey","ethViewingAddress","getAndDecryptPair","encryptedData","decryptedPair","nodeId","callback","targetChain","isLocalEnvironment","chainConfig","getAddressesForChain","Contract","verifyOnChain","contentHash","contract","isValid","timestamp","updater","verifyData","toUtf8Bytes","writeOnChain","tx","updateData","receipt","getLatestRecord","existingData","_contentHash","latestRecord","newNodeId","dataString","txHash","generateStealthAddress","recipientAddress","recipientData","senderAddress","senderData","spendingKeyPair","decryptedData","senderPublicKey","publishStealthKeys","viewingKeyPair","recoverStealthFunds","myAddress","decryptedViewingData","recoveredAddress","recovered","expected","announceStealthPayment","options","onChain","contractAddress","devFee","announcePayment","set","now","stack","getStealthPayments","source","payments","process","env","NODE_ENV","totalAnnouncements","getAnnouncementsCount","totalCount","Number","batchSize","lastIndex","toIndex","min","batch","getAnnouncementsInRange","announcement","recoveredWallet","offChainPayments","resolve","payment","cleanStealthPayments","GunEth","static"],"mappings":"soBAAE,WAGA,SAASA,EAAIC,EAAKC,GAChB,OAAOA,+NAAKC,CAAQF,GAAOA,EAAIG,MAAOJ,EAAIK,EAAEJ,IAAQ,SAASK,EAAKC,GAChEN,EAAIK,EAAM,CAACE,QAAS,CAAA,IACpBR,EAAIK,EAAEE,IAASD,EAAIE,OACzB,EACI,SAASH,EAAEI,GACT,OAAOA,EAAEC,MAAM,KAAKN,OAAO,GAAGO,WAAWC,QAAQ,MAAM,GAC7D,CACA,CACqC,IAAIC,EAASC,EAG/Cd,GAAI,SAASc,GAMO,oBAATC,OAAuBD,EAAOE,OAASD,MAC5B,oBAAXC,SAAyBF,EAAOE,OAASA,QAEnD,IACIC,GADMH,EAAOE,QAAUF,GACbG,KAAO,IAElBA,EAAID,OAASF,EAAOE,UAASC,EAAID,OAAOC,IAAMA,GAEjD,IALmCC,UAKzB,WAAcL,IAASA,EAAOL,QAAUS,EAAO,CAAA,MAAME,GAAE,CACjEL,EAAON,QAAUS,CACrB,GAhBGjB,CAgBEA,EAAK,UAEPA,GAAI,SAASc,GACZ,IAAIG,EAAMjB,EAAI,UACd,IAAQiB,EAAID,QACPI,SAASC,SAASC,QAAQ,KAAO,GACjCF,SAASG,KAAKD,QAAQ,aAAe,IACnC,uBA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