gun-eth 1.4.23 → 1.4.24

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,2 +0,0 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("gun"),require("ethers")):"function"==typeof define&&define.amd?define(["exports","gun","ethers"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GunEth={},e.Gun,e.ethers)}(this,(function(e,t,n){"use strict";var r="undefined"!=typeof document?document.currentScript:null,a="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function o(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var i={exports:{}};!function(e){!function(){function t(e,n){return n?function(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}(e):e.slice?t[r(e)]:function(n,a){e(n={exports:{}}),t[r(a)]=n.exports};function r(e){return e.split("/").slice(-1).toString().replace(".js","")}}var n=e;t((function(e){"undefined"!=typeof self&&(e.window=self),"undefined"!=typeof window&&(e.window=window);var t=(e.window||e).SEA||{};(t.window=e.window)&&(t.window.SEA=t);try{undefined+""!=typeof n&&(n.exports=t)}catch(e){}e.exports=t}))(t,"./root"),t((function(e){var n=t("./root");try{n.window&&location.protocol.indexOf("s")<0&&location.host.indexOf("localhost")<0&&!/^127\.\d+\.\d+\.\d+$/.test(location.hostname)&&location.protocol.indexOf("file:")<0&&(console.warn("HTTPS needed for WebCrypto in SEA, redirecting..."),location.protocol="https:")}catch(e){}}))(t,"./https"),t((function(e){var n;if(n+""==typeof btoa){if(n+""==typeof Buffer)try{a.Buffer=t("buffer",1).Buffer}catch(e){console.log("Please `npm install buffer` or add it to your package.json !")}a.btoa=function(e){return Buffer.from(e,"binary").toString("base64")},a.atob=function(e){return Buffer.from(e,"base64").toString("binary")}}}))(t,"./base64"),t((function(e){function n(){}t("./base64"),Object.assign(n,{from:Array.from}),n.prototype=Object.create(Array.prototype),n.prototype.toString=function(e,t,n){e=e||"utf8",t=t||0;const r=this.length;if("hex"===e){const e=new Uint8Array(this);return[...Array((n&&n+1||r)-t).keys()].map((n=>e[n+t].toString(16).padStart(2,"0"))).join("")}return"utf8"===e?Array.from({length:(n||r)-t},((e,n)=>String.fromCharCode(this[n+t]))).join(""):"base64"===e?btoa(this):void 0},e.exports=n}))(t,"./array"),t((function(e){t("./base64");var n=t("./array");function r(...e){return console.warn("new SafeBuffer() is depreciated, please use SafeBuffer.from()"),r.from(...e)}r.prototype=Object.create(Array.prototype),Object.assign(r,{from(){if(!Object.keys(arguments).length||null==arguments[0])throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.");const e=arguments[0];let t;if("string"==typeof e){const r=arguments[1]||"utf8";if("hex"===r){const r=e.match(/([\da-fA-F]{2})/g).map((e=>parseInt(e,16)));if(!r||!r.length)throw new TypeError("Invalid first argument for type 'hex'.");t=n.from(r)}else if("utf8"===r||"binary"===r){const r=e.length,a=new Uint16Array(r);Array.from({length:r},((t,n)=>a[n]=e.charCodeAt(n))),t=n.from(a)}else if("base64"===r){const r=atob(e),a=r.length,o=new Uint8Array(a);Array.from({length:a},((e,t)=>o[t]=r.charCodeAt(t))),t=n.from(o)}else"binary"===r?t=n.from(e):console.info("SafeBuffer.from unknown encoding: "+r);return t}e.byteLength;if(e.byteLength?e.byteLength:e.length){let t;return e instanceof ArrayBuffer&&(t=new Uint8Array(e)),n.from(t||e)}},alloc:(e,t=0)=>n.from(new Uint8Array(Array.from({length:e},(()=>t)))),allocUnsafe:e=>n.from(new Uint8Array(Array.from({length:e}))),concat(e){if(!Array.isArray(e))throw new TypeError("First argument must be Array containing ArrayBuffer or Uint8Array instances.");return n.from(e.reduce(((e,t)=>e.concat(Array.from(t))),[]))}}),r.prototype.from=r.from,r.prototype.toString=n.prototype.toString,e.exports=r}))(t,"./buffer"),t((function(e){const r=t("./root"),a={Buffer:t("./buffer")};var o={};if(JSON.parseAsync=JSON.parseAsync||function(e,t,n){try{t(undefined,JSON.parse(e,n))}catch(e){t(e)}},JSON.stringifyAsync=JSON.stringifyAsync||function(e,t,n,r){try{t(undefined,JSON.stringify(e,n,r))}catch(e){t(e)}},a.parse=function(e,t){return new Promise((function(n,r){JSON.parseAsync(e,(function(e,t){e?r(e):n(t)}),t)}))},a.stringify=function(e,t,n){return new Promise((function(r,a){JSON.stringifyAsync(e,(function(e,t){e?a(e):r(t)}),t,n)}))},r.window&&(a.crypto=r.window.crypto||r.window.msCrypto,a.subtle=(a.crypto||o).subtle||(a.crypto||o).webkitSubtle,a.TextEncoder=r.window.TextEncoder,a.TextDecoder=r.window.TextDecoder,a.random=e=>a.Buffer.from(a.crypto.getRandomValues(new Uint8Array(a.Buffer.alloc(e))))),!a.TextDecoder){const{TextEncoder:e,TextDecoder:r}=t((undefined+""==typeof n?".":"")+"./lib/text-encoding",1);a.TextDecoder=r,a.TextEncoder=e}if(!a.crypto)try{var i=t("crypto",1);Object.assign(a,{crypto:i,random:e=>a.Buffer.from(i.randomBytes(e))});const{Crypto:e}=t("@peculiar/webcrypto",1);a.ossl=a.subtle=new e({directory:"ossl"}).subtle}catch(e){console.log("Please `npm install @peculiar/webcrypto` or add it to your package.json !")}e.exports=a}))(t,"./shim"),t((function(e){var n=t("./root"),r=t("./shim"),a={pbkdf2:{hash:{name:"SHA-256"},iter:1e5,ks:64},ecdsa:{pair:{name:"ECDSA",namedCurve:"P-256"},sign:{name:"ECDSA",hash:{name:"SHA-256"}}},ecdh:{name:"ECDH",namedCurve:"P-256"},jwk:function(e,t){var n={kty:"EC",crv:"P-256",x:(e=e.split("."))[0],y:e[1],ext:!0};return n.key_ops=t?["sign"]:["verify"],t&&(n.d=t),n},keyToJwk:function(e){return{kty:"oct",k:e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,""),ext:!1,alg:"A256GCM"}},recall:{validity:43200,hook:function(e){return e}},check:function(e){return"string"==typeof e&&"SEA{"===e.slice(0,4)},parse:async function(e){try{var t="string"==typeof e;return t&&"SEA{"===e.slice(0,4)&&(e=e.slice(3)),t?await r.parse(e):e}catch(e){}return e}};n.opt=a,e.exports=a}))(t,"./settings"),t((function(e){var n=t("./shim");e.exports=async function(e,t){var r="string"==typeof e?e:await n.stringify(e),a=await n.subtle.digest({name:t||"SHA-256"},(new n.TextEncoder).encode(r));return n.Buffer.from(a)}}))(t,"./sha256"),t((function(e){const n=t("./shim"),r=n.subtle,a=n.ossl?n.ossl:r;e.exports=e=>a.digest({name:"SHA-1"},new ArrayBuffer(e))}))(t,"./sha1"),t((function(e){var n=t("./root"),r=t("./shim"),a=t("./settings"),o=t("./sha256");n.work=n.work||(async(e,t,i,s)=>{try{var c=(t||{}).epub||t;if(s=s||{},c instanceof Function&&(i=c,c=undefined),e="string"==typeof e?e:await r.stringify(e),"sha"===(s.name||"").toLowerCase().slice(0,3)){var u=r.Buffer.from(await o(e,s.name),"binary").toString(s.encode||"base64");if(i)try{i(u)}catch(e){console.log(e)}return u}c=c||r.random(9);var p=await(r.ossl||r.subtle).importKey("raw",(new r.TextEncoder).encode(e),{name:s.name||"PBKDF2"},!1,["deriveBits"]),l=await(r.ossl||r.subtle).deriveBits({name:s.name||"PBKDF2",iterations:s.iterations||a.pbkdf2.iter,salt:(new r.TextEncoder).encode(s.salt||c),hash:s.hash||a.pbkdf2.hash},p,s.length||8*a.pbkdf2.ks);e=r.random(e.length);var f=r.Buffer.from(l,"binary").toString(s.encode||"base64");if(i)try{i(f)}catch(e){console.log(e)}return f}catch(e){if(console.log(e),n.err=e,n.throw)throw e;return void(i&&i())}}),e.exports=n.work}))(t,"./work"),t((function(e){var n=t("./root"),r=t("./shim");t("./settings"),n.name=n.name||(async(e,t)=>{try{if(e)try{e()}catch(e){console.log(e)}return}catch(t){if(console.log(t),n.err=t,n.throw)throw t;return void(e&&e())}}),n.pair=n.pair||(async(e,t)=>{try{var a=r.ossl||r.subtle,o=await r.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]).then((async e=>{var t={};t.priv=(await r.subtle.exportKey("jwk",e.privateKey)).d;var n=await r.subtle.exportKey("jwk",e.publicKey);return t.pub=n.x+"."+n.y,t}));try{var i=await a.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"]).then((async e=>{var t={};t.epriv=(await a.exportKey("jwk",e.privateKey)).d;var n=await a.exportKey("jwk",e.publicKey);return t.epub=n.x+"."+n.y,t}))}catch(e){if(n.window)throw e;if("Error: ECDH is not a supported algorithm"!=e)throw e;console.log("Ignoring ECDH...")}i=i||{};var s={pub:o.pub,priv:o.priv,epub:i.epub,epriv:i.epriv};if(e)try{e(s)}catch(e){console.log(e)}return s}catch(t){if(console.log(t),n.err=t,n.throw)throw t;return void(e&&e())}}),e.exports=n.pair}))(t,"./pair"),t((function(e){var n,r=t("./root"),a=t("./shim"),o=t("./settings"),i=t("./sha256");r.sign=r.sign||(async(e,t,s,c)=>{try{if(c=c||{},!(t||c).priv){if(!r.I)throw"No signing key.";t=await r.I(null,{what:e,how:"sign",why:c.why})}if(n===e)throw"`undefined` not allowed.";var u=await o.parse(e),p=c.check=c.check||u;if(r.verify&&(r.opt.check(p)||p&&p.s&&p.m)&&n!==await r.verify(p,t)){var l=await o.parse(p);if(c.raw||(l="SEA"+await a.stringify(l)),s)try{s(l)}catch(e){console.log(e)}return l}var f=t.pub,y=t.priv,d=o.jwk(f,y),h=await i(u),g=await(a.ossl||a.subtle).importKey("jwk",d,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]).then((e=>(a.ossl||a.subtle).sign({name:"ECDSA",hash:{name:"SHA-256"}},e,new Uint8Array(h))));l={m:u,s:a.Buffer.from(g,"binary").toString(c.encode||"base64")};if(c.raw||(l="SEA"+await a.stringify(l)),s)try{s(l)}catch(e){console.log(e)}return l}catch(e){if(console.log(e),r.err=e,r.throw)throw e;return void(s&&s())}}),e.exports=r.sign}))(t,"./sign"),t((function(e){var n,r=t("./root"),a=t("./shim"),o=t("./settings"),i=t("./sha256");r.verify=r.verify||(async(e,t,s,c)=>{try{var u=await o.parse(e);if(!1===t){var p=await o.parse(u.m);if(s)try{s(p)}catch(e){console.log(e)}return p}c=c||{};var l,f,y,d=t.pub||t,h=r.opt.slow_leak?await r.opt.slow_leak(d):await(a.ossl||a.subtle).importKey("jwk",o.jwk(d),{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),g=await i(u.m);try{if(l=a.Buffer.from(u.s,c.encode||"base64"),f=new Uint8Array(l),!(y=await(a.ossl||a.subtle).verify({name:"ECDSA",hash:{name:"SHA-256"}},h,f,new Uint8Array(g))))throw"Signature did not match."}catch(n){if(r.opt.fallback)return await r.opt.fall_verify(e,t,s,c)}var w=y?await o.parse(u.m):n;if(s)try{s(w)}catch(e){console.log(e)}return w}catch(e){if(console.log(e),r.err=e,r.throw)throw e;return void(s&&s())}}),e.exports=r.verify;var s={};r.opt.slow_leak=e=>{if(s[e])return s[e];var t=o.jwk(e);return s[e]=(a.ossl||a.subtle).importKey("jwk",t,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),s[e]};var c=r.opt;r.opt.fall_verify=async function(e,t,s,u,p){if(p===r.opt.fallback)throw"Signature did not match";p=p||1;var l=e||"";e=r.opt.unpack(e)||e;var f,y,d,h=await o.parse(e),g=t.pub||t,w=await r.opt.slow_leak(g),b=p<=r.opt.fallback?a.Buffer.from(await a.subtle.digest({name:"SHA-256"},(new a.TextEncoder).encode(await o.parse(h.m)))):await i(h.m);try{if(f=a.Buffer.from(h.s,u.encode||"base64"),y=new Uint8Array(f),!(d=await(a.ossl||a.subtle).verify({name:"ECDSA",hash:{name:"SHA-256"}},w,y,new Uint8Array(b))))throw"Signature did not match."}catch(e){try{f=a.Buffer.from(h.s,"utf8"),y=new Uint8Array(f),d=await(a.ossl||a.subtle).verify({name:"ECDSA",hash:{name:"SHA-256"}},w,y,new Uint8Array(b))}catch(e){if(!d)throw"Signature did not match."}}var m=d?await o.parse(h.m):n;if(c.fall_soul=l["#"],c.fall_key=l["."],c.fall_val=e,c.fall_state=l[">"],s)try{s(m)}catch(e){console.log(e)}return m},r.opt.fallback=2}))(t,"./verify"),t((function(e){var n=t("./shim"),r=t("./settings"),a=t("./sha256");e.exports=async(e,t,o)=>{const i=e+(t||n.random(8)).toString("utf8"),s=n.Buffer.from(await a(i),"binary"),c=r.keyToJwk(s);return await n.subtle.importKey("jwk",c,{name:"AES-GCM"},!1,["encrypt","decrypt"])}}))(t,"./aeskey"),t((function(e){var n=t("./root"),r=t("./shim");t("./settings");var a=t("./aeskey");n.encrypt=n.encrypt||(async(e,t,o,i)=>{try{i=i||{};var s=(t||i).epriv||t;if(undefined===e)throw"`undefined` not allowed.";if(!s){if(!n.I)throw"No encryption key.";s=(t=await n.I(null,{what:e,how:"encrypt",why:i.why})).epriv||t}var c="string"==typeof e?e:await r.stringify(e),u={s:r.random(9),iv:r.random(15)},p=await a(s,u.s,i).then((e=>r.subtle.encrypt({name:i.name||"AES-GCM",iv:new Uint8Array(u.iv)},e,(new r.TextEncoder).encode(c)))),l={ct:r.Buffer.from(p,"binary").toString(i.encode||"base64"),iv:u.iv.toString(i.encode||"base64"),s:u.s.toString(i.encode||"base64")};if(i.raw||(l="SEA"+await r.stringify(l)),o)try{o(l)}catch(e){console.log(e)}return l}catch(e){if(console.log(e),n.err=e,n.throw)throw e;return void(o&&o())}}),e.exports=n.encrypt}))(t,"./encrypt"),t((function(e){var n=t("./root"),r=t("./shim"),a=t("./settings"),o=t("./aeskey");n.decrypt=n.decrypt||(async(e,t,i,s)=>{try{s=s||{};var c=(t||s).epriv||t;if(!c){if(!n.I)throw"No decryption key.";c=(t=await n.I(null,{what:e,how:"decrypt",why:s.why})).epriv||t}var u,p,l,f=await a.parse(e);try{u=r.Buffer.from(f.s,s.encode||"base64"),p=r.Buffer.from(f.iv,s.encode||"base64"),l=r.Buffer.from(f.ct,s.encode||"base64");var y=await o(c,u,s).then((e=>r.subtle.decrypt({name:s.name||"AES-GCM",iv:new Uint8Array(p),tagLength:128},e,new Uint8Array(l))))}catch(r){if("utf8"===s.encode)throw"Could not decrypt";if(n.opt.fallback)return s.encode="utf8",await n.decrypt(e,t,i,s)}var d=await a.parse(new r.TextDecoder("utf8").decode(y));if(i)try{i(d)}catch(e){console.log(e)}return d}catch(e){if(console.log(e),n.err=e,n.throw)throw e;return void(i&&i())}}),e.exports=n.decrypt}))(t,"./decrypt"),t((function(e){var n=t("./root"),r=t("./shim");t("./settings"),n.secret=n.secret||(async(e,t,o,i)=>{try{if(i=i||{},!t||!t.epriv||!t.epub){if(!n.I)throw"No secret mix.";t=await n.I(null,{what:e,how:"secret",why:i.why})}var s=e.epub||e,c=t.epub,u=t.epriv,p=r.ossl||r.subtle,l=a(s),f=Object.assign({public:await p.importKey(...l,!0,[])},{name:"ECDH",namedCurve:"P-256"}),y=a(c,u),d=await p.importKey(...y,!1,["deriveBits"]).then((async e=>{var t=await p.deriveBits(f,e,256),n=new Uint8Array(t),r=await p.importKey("raw",n,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);return p.exportKey("jwk",r).then((({k:e})=>e))}));if(o)try{o(d)}catch(e){console.log(e)}return d}catch(e){if(console.log(e),n.err=e,n.throw)throw e;return void(o&&o())}});var a=(e,t)=>{var[n,r]=e.split("."),a=t?{d:t}:{};return["jwk",Object.assign(a,{x:n,y:r,kty:"EC",crv:"P-256",ext:!0}),{name:"ECDH",namedCurve:"P-256"}]};e.exports=n.secret}))(t,"./secret"),t((function(e){var n=t("./root");n.certify=n.certify||(async(e,t={},r,a,o={})=>{try{if(console.log("SEA.certify() is an early experimental community supported method that may change API behavior without warning in any future version."),e=(()=>{var t=[];if(e){if(("string"==typeof e||Array.isArray(e))&&e.indexOf("*")>-1)return"*";if("string"==typeof e)return e;if(Array.isArray(e)){if(1===e.length&&e[0])return"object"==typeof e[0]&&e[0].pub?e[0].pub:"string"==typeof e[0]?e[0]:null;e.map((e=>{"string"==typeof e?t.push(e):"object"==typeof e&&e.pub&&t.push(e.pub)}))}return"object"==typeof e&&e.pub?e.pub:t.length>0?t:null}})(),!e)return console.log("No certificant found.");const s=!o.expiry||"number"!=typeof o.expiry&&"string"!=typeof o.expiry?null:parseFloat(o.expiry),c=(t||{}).read?t.read:null,u=(t||{}).write?t.write:"string"==typeof t||Array.isArray(t)||t["+"]||t["#"]||t["."]||t["="]||t["*"]||t[">"]||t["<"]?t:null,p=(o||{}).block||(o||{}).blacklist||(o||{}).ban||{},l=p.read&&("string"==typeof p.read||(p.read||{})["#"])?p.read:null,f="string"==typeof p?p:p.write&&("string"==typeof p.write||p.write["#"])?p.write:null;if(!c&&!u)return console.log("No policy found.");const y=JSON.stringify({c:e,...s?{e:s}:{},...c?{r:c}:{},...u?{w:u}:{},...l?{rb:l}:{},...f?{wb:f}:{}});var i=await n.sign(y,r,null,{raw:1});if(o.raw||(i="SEA"+JSON.stringify(i)),a)try{a(i)}catch(e){console.log(e)}return i}catch(e){if(n.err=e,n.throw)throw e;return void(a&&a())}}),e.exports=n.certify}))(t,"./certify"),t((function(e){var n=t("./shim"),r=t("./root");r.work=t("./work"),r.sign=t("./sign"),r.verify=t("./verify"),r.encrypt=t("./encrypt"),r.decrypt=t("./decrypt"),r.certify=t("./certify"),r.random=r.random||n.random,r.Buffer=r.Buffer||t("./buffer"),r.keyid=r.keyid||(async e=>{try{const t=n.Buffer.concat(e.replace(/-/g,"+").replace(/_/g,"/").split(".").map((e=>n.Buffer.from(e,"base64")))),r=n.Buffer.concat([n.Buffer.from([153,t.length/256,t.length%256]),t]),a=await sha1hash(r),o=n.Buffer.from(a,"binary");return o.toString("hex",o.length-8)}catch(e){throw console.log(e),e}}),((r.window||{}).GUN||{}).SEA=r,e.exports=r}))(t,"./sea"),t((function(e){var r,a=t("./sea");function o(e){this._={$:this}}function i(){return r.state().toString(36).replace(".","")}r=a.window?a.window.GUN||{chain:{}}:t((undefined+""==typeof n?".":"")+"./gun",1),a.GUN=r,o.prototype=function(){function e(){}return e.prototype=r.chain,new e}(),o.prototype.constructor=o,r.chain.user=function(e){var t,n=this.back(-1);if(e)return e=a.opt.pub((e._||"")["#"])||e,n.get("~"+e);if(t=n.back("user"))return t;var r=n=n._,s=r.opt.uuid||i;return(r=(t=r.user=this.chain(new o))._).opt={},r.opt.uuid=function(e){var t=s(),r=n.user;return r&&(r=r.is)&&(r=r.pub)?(t="~"+r+"/"+t,e&&e.call&&e(null,t),t):t},t},r.User=o,o.GUN=r,o.SEA=r.SEA=a,e.exports=o}))(t,"./user"),t((function(e){var r;(""+r!=typeof GUN?GUN||{chain:{}}:t((""+r==typeof n?".":"")+"./gun",1)).chain.then=function(e,t){var n=this,r=new Promise((function(e,r){n.once(e,t)}));return e?r.then(e):r}}))(t,"./then"),t((function(e){var n=t("./user"),r=n.SEA,a=n.GUN,o=function(){};n.prototype.create=function(...e){var t,n="object"==typeof e[0]&&(e[0].pub||e[0].epub)?e[0]:"object"==typeof e[1]&&(e[1].pub||e[1].epub)?e[1]:null,i=n&&(n.pub||n.epub)?n.pub:"string"==typeof e[0]?e[0]:null,s=n&&(n.pub||n.epub)?n:i&&"string"==typeof e[1]?e[1]:null,c=e.filter((e=>"function"==typeof e))[0]||null,u=e&&e.length>1&&"object"==typeof e[e.length-1]?e[e.length-1]:{},p=this,l=p._,f=p.back(-1);if((c=c||o,!1!==(u=u||{}).check)&&(i||(t="No user."),(s||"").length<8&&(t="Password too short!"),t))return c({err:a.log(t)}),p;if(l.ing)return(c||o)({err:a.log("User is already being created or authenticated!"),wait:!0}),p;l.ing=!0;var y={a:function(e){if(y.pubs=e,e&&!u.already){var t={err:a.log("User already created!")};return l.ing=!1,(c||o)(t),void p.leave()}y.salt=String.random(64),r.work(s,y.salt,y.b)},b:function(e){y.proof=e,n?y.c(n):r.pair(y.c)},c:function(e){var t;y.pair=e||{},(t=l.root.user)&&(t._.sea=e,t.is={pub:e.pub,epub:e.epub,alias:i}),y.data={pub:e.pub},y.d()},d:function(){y.data.alias=i,y.e()},e:function(){y.data.epub=y.pair.epub,r.encrypt({priv:y.pair.priv,epriv:y.pair.epriv},y.proof,y.f,{raw:1})},f:function(e){y.data.auth=JSON.stringify({ek:e,s:y.salt}),y.g(y.data.auth)},g:function(e){var t;y.data.auth=y.data.auth||e,f.get(t="~"+y.pair.pub).put(y.data).on(y.h);var n={};n[t]={"#":t},f.get("~@"+i).put(n).get(t).on(y.i)},h:function(e,t,n,r){r.off(),y.h.ok=1,y.i()},i:function(e,t,r,a){a&&(y.i.ok=1,a.off()),y.h.ok&&y.i.ok&&(l.ing=!1,c({ok:0,pub:y.pair.pub}),o===c&&(n?p.auth(n):p.auth(i,s)))}};return f.get("~@"+i).once(y.a),p},n.prototype.leave=function(e,t){var n=this.back(-1)._.user;if(n&&(delete n.is,delete n._.is,delete n._.sea),r.window)try{var a={};delete(a=r.window.sessionStorage).recall,delete a.pair}catch(e){}return this}}))(t,"./create"),t((function(e){var n=t("./user"),r=n.SEA,a=n.GUN,o=function(){};function i(e){if("string"!=typeof e)return e;try{e=JSON.parse(e)}catch(t){e={}}return e}n.prototype.auth=function(...e){var t="object"==typeof e[0]&&(e[0].pub||e[0].epub)?e[0]:"object"==typeof e[1]&&(e[1].pub||e[1].epub)?e[1]:null,n=t||"string"!=typeof e[0]?null:e[0],s=!n&&(!t||t.priv&&t.epriv)||"string"!=typeof e[1]?null:e[1],c=e.filter((e=>"function"==typeof e))[0]||null,u=e&&e.length>1&&"object"==typeof e[e.length-1]?e[e.length-1]:{},p=this,l=p._,f=p.back(-1);if(l.ing)return(c||o)({err:a.log("User is already being created or authenticated!"),wait:!0}),p;l.ing=!0;var y,d={},h=9;return d.a=function(e){if(!e)return d.b();if(!e.pub){var t=[];return Object.keys(e).forEach((function(n){"_"!=n&&t.push(e[n])})),d.b(t)}if(d.name)return d.f(e);d.c((d.data=e).auth)},d.b=function(e){var t=(d.list=(d.list||[]).concat(e||[])).shift();if(y===t)return d.name?d.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&&h--?void f.get("~@"+n).once(d.a):d.err("Wrong user or password.");f.get(t).once(d.a)},d.c=function(e){return y===e?d.b():"string"==typeof e?d.c(i(e)):void r.work(s,(d.auth=e).s,d.d,d.enc)},d.d=function(e){r.decrypt(d.auth.ek,e,d.e,d.enc)},d.e=function(e){if(y===e)return d.enc?(d.enc=null,d.b()):(d.enc={encode:"utf8"},d.c(d.auth));d.half=e,d.f(d.data)},d.f=function(e){var t=d.half||{},n=d.data||{};d.g(d.lol={pub:e.pub||n.pub,epub:e.epub||n.epub,priv:e.priv||t.priv,epriv:e.epriv||t.epriv})},d.g=function(e){if(!e||!e.pub||!e.epub)return d.b();d.pair=e;var t=f._.user,h=t._;h.tag;var g=h.opt;(h=t._=f.get("~"+e.pub)._).opt=g,t.is={pub:e.pub,epub:e.epub,alias:n||e.pub},h.sea=d.pair,l.ing=!1;try{s&&y==(i(l.root.graph["~"+e.pub].auth)||"")[":"]&&(u.shuffle=u.change=s)}catch(e){}if(u.change?d.z():(c||o)(h),r.window&&(p.back("user")._.opt||u).remember)try{var w={};(w=r.window.sessionStorage).recall=!0,w.pair=JSON.stringify(e)}catch(e){}try{f._.tag.auth?f._.on("auth",h):setTimeout((function(){f._.on("auth",h)}),1)}catch(e){a.log("Your 'auth' callback crashed with:",e)}},d.h=function(e){return e?((n=e.alias)||(n=e.alias="~"+t.pub),e.auth?(t=null,void d.c((d.data=e).auth)):d.g(t)):d.b()},d.z=function(){d.salt=String.random(64),r.work(u.change,d.salt,d.y)},d.y=function(e){r.encrypt({priv:d.pair.priv,epriv:d.pair.epriv},e,d.x,{raw:1})},d.x=function(e){d.w(JSON.stringify({ek:e,s:d.salt}))},d.w=function(e){if(u.shuffle){console.log("migrate core account from UTF8 & shuffle");var t={};Object.keys(d.data).forEach((function(e){t[e]=d.data[e]})),delete t._,t.auth=e,f.get("~"+d.pair.pub).put(t)}f.get("~"+d.pair.pub).get("auth").put(e,c||o)},d.err=function(e){var t={err:a.log(e||"User cannot be found!")};l.ing=!1,(c||o)(t)},d.plugin=function(e){if(!(d.name=e))return d.err();var t=[e];"~"!==e[0]&&(t[1]="~"+e,t[2]="~@"+e),d.b(t)},t?t.priv&&t.epriv?d.g(t):f.get("~"+t.pub).once(d.h):n?f.get("~@"+n).once(d.a):n||s||r.name(d.plugin),p}}))(t,"./auth"),t((function(e){var n=t("./user"),r=n.SEA;n.GUN,n.prototype.recall=function(e,t){var n=this,a=n.back(-1);if((e=e||{})&&e.sessionStorage){if(r.window)try{var o;(o=r.window.sessionStorage)&&(a._.opt.remember=!0,(n.back("user")._.opt||e).remember=!0,(o.recall||o.pair)&&a.user().auth(JSON.parse(o.pair),t))}catch(e){}return n}return n}}))(t,"./recall"),t((function(e){var n=t("./user"),r=n.SEA,a=n.GUN,o=function(){};n.prototype.pair=function(){var e,t=this;try{e=new Proxy({DANGER:"☠"},{get:function(e,n,r){if(t.is&&(t._||"").sea)return t._.sea[n]}})}catch(e){}return e},n.prototype.delete=async function(e,t,n){console.log("user.delete() IS DEPRECATED AND WILL BE MOVED TO A MODULE!!!");var r=this;r.back(-1);var i=r.back("user");try{i.auth(e,t,(function(e){(i.is||{}).pub;i.map().once((function(){this.put(null)})),i.leave(),(n||o)({ok:0})}))}catch(e){a.log("User.delete failed! Error:",e)}return r},n.prototype.alive=async function(){console.log("user.alive() IS DEPRECATED!!!");const e=this.back(-1);try{return await authRecall(e),e._.user._}catch(e){const t="No session!";throw a.log(t),{err:t}}},n.prototype.trust=async function(e){console.log("`.trust` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!"),a.is(e)&&e.get("pub").get(((e,t)=>{console.log(e,t)})),e.get("trust").get(path).put(theirPubkey)},n.prototype.grant=function(e,t){console.log("`.grant` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");var n=this,a=n.back(-1).user(),o=a._.sea,i="";return n.back((function(e){e.is||(i+=e.get||"")})),async function(){var n,s=await a.get("grant").get(o.pub).get(i).then();(s=await r.decrypt(s,o))||(s=r.random(16).toString(),n=await r.encrypt(s,o),a.get("grant").get(o.pub).get(i).put(n));var c=e.get("pub").then(),u=e.get("epub").then();c=await c,u=await u;var p=await r.secret(u,o);n=await r.encrypt(s,p),a.get("grant").get(c).get(i).put(n,t)}(),n},n.prototype.secret=function(e,t){console.log("`.secret` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");var n=this,a=n.back(-1).user(),o=a.pair(),i="";return n.back((function(e){e.is||(i+=e.get||"")})),async function(){var s,c=await a.get("trust").get(o.pub).get(i).then();(c=await r.decrypt(c,o))||(c=r.random(16).toString(),s=await r.encrypt(c,o),a.get("trust").get(o.pub).get(i).put(s)),s=await r.encrypt(e,c),n.put(s,t)}(),n},e.exports=n}))(t,"./share"),t((function(e){var r,a=t("./sea"),o=t("./settings"),i=(a.window||"").GUN||t((""+r==typeof n?".":"")+"./gun",1);function s(e){var t,n=this,r=n.as,o=e.put,c=o["#"],u=o["."],p=o[":"],l=o[">"],f=e["#"];if(c&&u)if((e._||"").faith&&(r.opt||"").faith&&"function"==typeof e._)a.opt.pack(o,(function(t){a.verify(t,!1,(function(t){o["="]=a.opt.unpack(t),n.to.next(e)}))}));else{var y=function(t){r.on("in",{"@":f,err:e.err=t})};(e._||"").DBG&&((e._||"").DBG.c=+new Date),0<=c.indexOf("<?")&&(t=parseFloat(c.split("<?")[1]||""))&&l<i.state()-1e3*t?(t=e._)&&t.stun&&t.stun--:"~@"!==c?"~@"!==c.slice(0,2)?(t=a.opt.pub(c))?s.pub(n,e,p,u,c,r,y,r.user||"",t):0<=c.indexOf("#")?s.hash(n,e,p,u,c,r,y):s.any(n,e,p,u,c,r,y,r.user||""):s.pubs(n,e,p,u,c,r,y):s.alias(n,e,p,u,c,r,y)}}i.on("opt",(function(e){e.sea||(e.sea={own:{}},e.on("put",s,e)),this.to.next(e)})),s.hash=function(e,t,n,r,o,i,s){a.work(n,null,(function(n){return n&&n===r.split("#").slice(-1)[0]||n&&n===function(e){let t="";for(let n=0;n<e.length;n++)t+=n-1&1?"":String.fromCharCode(parseInt(e.substring(n-1,n+1),16));return btoa(t)}(r.split("#").slice(-1)[0])?e.to.next(t):void s("Data hash not same as hash!")}),{name:"SHA-256"})},s.alias=function(e,t,n,r,a,o,i){return n?"~@"+r===u(n)?e.to.next(t):void i("Alias not same!"):i("Data must exist!")},s.pubs=function(e,t,n,r,a,o,i){return n?r===u(n)?e.to.next(t):void i("Alias not same!"):i("Alias must exist!")},s.pub=async function(e,t,n,s,c,p,l,f,y){var d;const h=await o.parse(n)||{},g=(n,o,u)=>{if(n.m&&n.s&&o&&y)return a.verify(n,y,(n=>{if(r!==n&&r!==n.e&&t.put[">"]&&t.put[">"]>parseFloat(n.e))return l("Certificate expired.");if(r!==n&&n.c&&n.w&&(n.c===o||n.c.indexOf("*")>-1)){let t=c.indexOf("/")>-1?c.replace(c.substring(0,c.indexOf("/")+1),""):"";String.match=String.match||i.text.match;const r=Array.isArray(n.w)?n.w:"object"==typeof n.w||"string"==typeof n.w?[n.w]:[];for(const i of r)if(String.match(t,i["#"])&&String.match(s,i["."])||!i["."]&&String.match(t,i["#"])||!i["#"]&&String.match(s,i["."])||String.match(t?t+"/"+s:s,i["#"]||i)){if(i["+"]&&i["+"].indexOf("*")>-1&&t&&-1==t.indexOf(o)&&-1==s.indexOf(o))return l(`Path "${t}" or key "${s}" must contain string "${o}".`);if(n.wb&&("string"==typeof n.wb||(n.wb||{})["#"])){var a=e.as.root.$.back(-1);return"string"==typeof n.wb&&"~"!==n.wb.slice(0,1)&&(a=a.get("~"+y)),a.get(n.wb).get(o).once((e=>!e||1!==e&&!0!==e?u(n):l(`Certificant ${o} blocked.`)))}return u(n)}return l("Certificate verification fail.")}}))};if("pub"===s&&"~"+y===c)return n===y?e.to.next(t):l("Account not same!");(d=f.is)&&d.pub&&!h["*"]&&!h["+"]&&(y===d.pub||y!==d.pub&&((t._.msg||{}).opt||{}).cert)?a.opt.pack(t.put,(i=>{a.sign(i,f._.sea,(async function(i){if(r===i)return l(a.err||"Signature fail.");if(t.put[":"]={":":d=a.opt.unpack(i.m),"~":i.s},t.put["="]=d,y===f.is.pub)return(d=u(n))&&((p.sea.own[d]=p.sea.own[d]||{})[y]=1),void JSON.stringifyAsync(t.put[":"],(function(n,r){return n?l(n||"Stringify error."):(t.put[":"]=r,e.to.next(t))}));if(y!==f.is.pub&&((t._.msg||{}).opt||{}).cert){const n=await o.parse(t._.msg.opt.cert);n&&n.m&&n.s&&g(n,f.is.pub,(r=>{t.put[":"]["+"]=n,t.put[":"]["*"]=f.is.pub,JSON.stringifyAsync(t.put[":"],(function(n,r){return n?l(n||"Stringify error."):(t.put[":"]=r,e.to.next(t))}))}))}}),{raw:1})})):a.opt.pack(t.put,(n=>{a.verify(n,h["*"]||y,(function(n){var o;return n=a.opt.unpack(n),r===n?l("Unverified data."):((o=u(n))&&y===a.opt.pub(o)&&((p.sea.own[o]=p.sea.own[o]||{})[y]=1),h["+"]&&h["+"].m&&h["+"].s&&h["*"]?void g(h["+"],h["*"],(r=>(t.put["="]=n,e.to.next(t)))):(t.put["="]=n,e.to.next(t)))}))}))},s.any=function(e,t,n,r,a,o,i,s){if(o.opt.secure)return i("Soul missing public key at '"+r+"'.");o.on("secure",(function(t){if(this.off(),!o.opt.secure)return e.to.next(t);i("Data cannot be changed.")})).on.on("secure",t)};var c=i.valid,u=function(e,t){return"string"==typeof(t=c(e))&&t};(i.state||"").ify;var p=/[^\w_-]/;a.opt.pub=function(e){if(e&&(e=e.split("~"))&&(e=e[1])&&(e=e.split(p).slice(0,2))&&2==e.length&&"@"!==(e[0]||"")[0])return e=e.slice(0,2).join(".")},a.opt.stringy=function(e){},a.opt.pack=function(e,t,n,o,s){var c,u;if(a.opt.check(e))return t(e);e&&e["#"]&&e["."]&&e[">"]&&(c=e[":"],u=1),JSON.parseAsync(u?c:e,(function(a,c){var u=r!==(c||"")[":"]&&(c||"")["~"];t(u?{m:{"#":s||e["#"],".":n||e["."],":":(c||"")[":"],">":e[">"]||i.state.is(o,n)},s:u}:e)}))};var l=a.opt;a.opt.unpack=function(e,t,n){var o;if(r!==e){if(e&&r!==(o=e[":"]))return o;if(t=t||l.fall_key,!n&&l.fall_val&&((n={})[t]=l.fall_val),t&&n){if(e===n[t])return e;if(!a.opt.check(n[t]))return e;var s=n&&n._&&n._["#"]||l.fall_soul,c=i.state.is(n,t)||l.fall_state;return e&&4===e.length&&s===e[0]&&t===e[1]&&f(c)===f(e[3])?e[2]:c<a.opt.shuffle_attack?e:void 0}}},a.opt.shuffle_attack=15463296e5;var f=Math.floor}))(t,"./index")}()}(i);var s=o(i.exports);let c={PROOF_OF_INTEGRITY_ADDRESS:"0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512",STEALTH_ANNOUNCER_ADDRESS:"0x5FbDB2315678afecb367f032d93F642f64180aa3"};if("undefined"==typeof window)try{const{fileURLToPath:e}=require("url"),{dirname:t,join:n}=require("path"),{readFileSync:a}=require("fs"),o=e("undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(o).href:"undefined"==typeof document?location.href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("gun-eth.min.js",document.baseURI).href),i=a(n(t(o),"contract-address.json"));c=JSON.parse(i),console.log("Loaded contract addresses:",c)}catch(e){console.warn("Warning: contract-address.json not found or invalid")}const u={CHAIN_ID:1337,PROOF_OF_INTEGRITY_ADDRESS:c.PROOF_OF_INTEGRITY_ADDRESS,STEALTH_ANNOUNCER_ADDRESS:c.STEALTH_ANNOUNCER_ADDRESS,RPC_URL:"http://127.0.0.1:8545",GUN_PEER:"http://localhost:8765/gun"},p=[{inputs:[{internalType:"address",name:"_devAddress",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{internalType:"string",name:"senderPublicKey",type:"string"},{internalType:"string",name:"spendingPublicKey",type:"string"},{internalType:"address",name:"stealthAddress",type:"address"},{internalType:"uint256",name:"timestamp",type:"uint256"}],name:"StealthPaymentAnnounced",type:"event"},{anonymous:!1,inputs:[{internalType:"address",name:"newAddress",type:"address"}],name:"DevAddressUpdated",type:"event"},{anonymous:!1,inputs:[{internalType:"uint256",name:"newFee",type:"uint256"}],name:"DevFeeUpdated",type:"event"},{inputs:[{internalType:"string",name:"senderPublicKey",type:"string"},{internalType:"string",name:"spendingPublicKey",type:"string"},{internalType:"address",name:"stealthAddress",type:"address"}],name:"announcePayment",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"devAddress",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"devFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getAnnouncementsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"fromIndex",type:"uint256"},{internalType:"uint256",name:"toIndex",type:"uint256"}],name:"getAnnouncementsInRange",outputs:[{components:[{internalType:"string",name:"senderPublicKey",type:"string"},{internalType:"string",name:"spendingPublicKey",type:"string"},{internalType:"address",name:"stealthAddress",type:"address"},{internalType:"uint256",name:"timestamp",type:"uint256"}],internalType:"struct StealthAnnouncer.StealthAnnouncement[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_newFee",type:"uint256"}],name:"updateDevFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_newAddress",type:"address"}],name:"updateDevAddress",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"withdrawStuckETH",outputs:[],stateMutability:"nonpayable",type:"function"}],l=[{inputs:[{internalType:"bytes[]",name:"nodeIds",type:"bytes[]"},{internalType:"bytes32[]",name:"contentHashes",type:"bytes32[]"}],name:"batchUpdateData",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes",name:"nodeId",type:"bytes"},{indexed:!1,internalType:"bytes32",name:"contentHash",type:"bytes32"},{indexed:!1,internalType:"address",name:"updater",type:"address"}],name:"DataUpdated",type:"event"},{inputs:[{internalType:"bytes",name:"nodeId",type:"bytes"}],name:"getLatestRecord",outputs:[{internalType:"bytes32",name:"",type:"bytes32"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"nodeId",type:"bytes"},{internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"updateData",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes",name:"nodeId",type:"bytes"},{internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"verifyData",outputs:[{internalType:"bool",name:"",type:"bool"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];let f,y="",d="";const h="Access GunDB with Ethereum";let g={PROOF_OF_INTEGRITY_ADDRESS:null,STEALTH_ANNOUNCER_ADDRESS:"..."};if("undefined"==typeof window){const{fileURLToPath:e}=require("url"),{dirname:t}=require("path"),{readFileSync:n}=require("fs"),a=require("path"),o=e("undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(o).href:"undefined"==typeof document?location.href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("gun-eth.min.js",document.baseURI).href),i=t(o);try{const e=n(a.join(i,"contract-address.json"),"utf8");g=JSON.parse(e),console.log("Loaded contract addresses:",g)}catch(e){console.warn("Warning: contract-address.json not found or invalid")}}function w(){return n.ethers.hexlify(n.ethers.randomBytes(32)).slice(2)}function b(e){try{const t=n.ethers.hexlify(e),r=n.ethers.keccak256(t);return console.log("Generated password:",r),r}catch(e){return console.error("Error generating password:",e),null}}function m(e){const t="0x"+(e=>{const t="=".repeat((4-e.length%4)%4),n=e.replace(/-/g,"+").replace(/_/g,"/")+t,r=atob(n);return Array.from(r,(e=>e.charCodeAt(0).toString(16).padStart(2,"0"))).join("")})(e),r=new n.ethers.Wallet(t);return{account:r,publicKey:r.address,privateKey:t}}const v=async()=>{if(y&&d){const e=new n.ethers.JsonRpcProvider(y,{chainId:u.CHAIN_ID,name:"localhost"});return new n.ethers.Wallet(d,e)}if("undefined"!=typeof window&&void 0!==window.ethereum){await window.ethereum.request({method:"eth_requestAccounts"});return new n.ethers.BrowserProvider(window.ethereum).getSigner()}throw new Error("No valid Ethereum provider found")};function S(e,t){try{const r=Buffer.from(e,"base64"),a=n.ethers.keccak256(n.ethers.concat([r,n.ethers.getBytes(t)])),o=new n.ethers.Wallet(a);return console.log("Debug deriveStealthAddress:",{sharedSecretHex:n.ethers.hexlify(r),spendingPublicKey:t,stealthPrivateKey:a,stealthAddress:o.address}),{stealthPrivateKey:a,stealthAddress:o.address,wallet:o}}catch(e){throw console.error("Error in deriveStealthAddress:",e),e}}t.chain.MESSAGE_TO_SIGN=h,t.chain.setSigner=function(e,t){return y=e,d=t,console.log("Standalone configuration set"),this},t.chain.getSigner=v(),t.chain.verifySignature=async function(e,t){try{return n.ethers.verifyMessage(e,t)}catch(e){return console.error("Error verifying signature:",e),null}},t.chain.generatePassword=function(e){return b(e)},t.chain.createSignature=async function(e){try{if(e!==h)throw new Error("Invalid message, valid message is: "+h);const t=await v(),n=await t.signMessage(e);return console.log("Signature created:",n),n}catch(e){return console.error("Error creating signature:",e),null}},t.chain.createAndStoreEncryptedPair=async function(e,t){try{const n=this,r=await s.pair(),a=await s.pair(),o=await s.pair(),i=b(t),c=await s.encrypt(JSON.stringify(r),i),u=await s.encrypt(JSON.stringify(a),i),p=await s.encrypt(JSON.stringify(o),i),l=m(a.priv),f=m(o.priv);n.get("gun-eth").get("users").get(e).put({pair:c,v_pair:u,s_pair:p,publicKeys:{viewingPublicKey:a.epub,viewingPublicKey:a.epub,spendingPublicKey:f.publicKey,ethViewingAddress:l.publicKey}}),console.log("Encrypted pairs and public keys stored for:",e)}catch(e){throw console.error("Error creating and storing encrypted pair:",e),e}},t.chain.getAndDecryptPair=async function(e,t){try{const n=this,r=await n.get("gun-eth").get("users").get(e).get("pair").then();if(!r)throw new Error("No encrypted data found for this address");const a=b(t),o=await s.decrypt(r,a);return console.log(o),o}catch(e){return console.error("Error retrieving and decrypting pair:",e),null}},t.chain.proof=function(e,t,r,a){if(console.log("Proof plugin called with:",{chain:e,nodeId:t,data:r}),"function"!=typeof a)return console.error("Callback must be a function"),this;try{const o=isLocalEnvironment()?"localhost":e,i=getAddressesForChain(o);console.log(`Using ${o} configuration:`,i);new n.ethers.Contract(i.PROOF_OF_INTEGRITY_ADDRESS,l,signer);const s=async(e,t)=>{console.log("Verifying on chain:",{nodeId:e,contentHash:t});const r=await v(),a=new n.ethers.Contract(f,l,r),[o,i,s]=await a.verifyData(n.ethers.toUtf8Bytes(e),t);return console.log("Verification result:",{isValid:o,timestamp:i,updater:s}),{isValid:o,timestamp:i,updater:s}},c=async(e,t)=>{console.log("Writing on chain:",{nodeId:e,contentHash:t});const r=await v(),a=new n.ethers.Contract(f,l,r),o=await a.updateData(n.ethers.toUtf8Bytes(e),t);console.log("Transaction sent:",o.hash);const i=await o.wait();return console.log("Transaction confirmed:",i),o},u=async e=>{const t=await v(),r=new n.ethers.Contract(f,l,t),[a,o,i]=await r.getLatestRecord(n.ethers.toUtf8Bytes(e));return console.log("Latest record from blockchain:",{nodeId:e,contentHash:a,timestamp:o,updater:i}),{contentHash:a,timestamp:o,updater:i}};if(t&&!r)gun.get(t).once((async e=>{if(!e)return void(a&&a({err:"Node not found in GunDB"}));console.log("existingData",e);const n=e._contentHash;if(console.log("contentHash",n),n)try{const{isValid:e,timestamp:r,updater:o}=await s(t,n),i=await u(t);e?a&&a({ok:!0,message:"Data verified on blockchain",timestamp:r,updater:o,latestRecord:i}):a&&a({ok:!1,message:"Data not verified on blockchain",latestRecord:i})}catch(e){a&&a({err:e.message})}else a&&a({err:"No content hash found for this node"})}));else if(r&&!t){const e=w(),t=JSON.stringify(r),o=n.ethers.keccak256(n.ethers.toUtf8Bytes(t));gun.get(e).put({...r,_contentHash:o},(async t=>{if(console.log("ack",t),t.err)a&&a({err:"Error saving data to GunDB"});else try{const t=await c(e,o);a&&a({ok:!0,message:"Data written to GunDB and blockchain",nodeId:e,txHash:t.hash})}catch(e){a&&a({err:e.message})}}))}else a&&a({err:"Invalid input. Provide either nodeId or data, not both."});return gun}catch(e){return a({err:e.message}),this}},t.chain.gunToEthAccount=function(e){return m(e)},t.chain.generateStealthAddress=async function(e,t){try{const n=this,r=await n.get("gun-eth").get("users").get(e).get("publicKeys").then();if(!r||!r.viewingPublicKey||!r.spendingPublicKey)throw new Error("Recipient's public keys not found");const a=await this.verifySignature(h,t),o=b(t),i=await n.get("gun-eth").get("users").get(a).then();if(!i||!i.s_pair)throw new Error("Sender's keys not found");let c;try{const e=await s.decrypt(i.s_pair,o);c="string"==typeof e?JSON.parse(e):e}catch(e){throw console.error("Error decrypting spending pair:",e),new Error("Unable to decrypt spending pair")}const u=await s.secret(r.viewingPublicKey,c);if(!u)throw new Error("Unable to generate shared secret");console.log("Generate shared secret:",u);const{stealthAddress:p}=S(u,r.spendingPublicKey);return{stealthAddress:p,senderPublicKey:c.epub,spendingPublicKey:r.spendingPublicKey}}catch(e){throw console.error("Error generating stealth address:",e),e}},t.chain.publishStealthKeys=async function(e){try{const t=this,n=await this.verifySignature(h,e),r=b(e),a=await t.get("gun-eth").get("users").get(n).then();if(!a||!a.v_pair||!a.s_pair)throw new Error("Keys not found");const o=JSON.parse(await s.decrypt(a.v_pair,r)),i=JSON.parse(await s.decrypt(a.s_pair,r)),c=m(o.priv),u=m(i.priv);t.get("gun-eth").get("users").get(n).get("publicKeys").put({viewingPublicKey:c.publicKey,spendingPublicKey:u.publicKey}),console.log("Stealth public keys published successfully")}catch(e){throw console.error("Error publishing stealth keys:",e),e}},t.chain.recoverStealthFunds=async function(e,t,n,r){try{const a=this,o=b(n),i=await this.verifySignature(h,n),c=await a.get("gun-eth").get("users").get(i).then();if(!c||!c.v_pair||!c.s_pair)throw new Error("Keys not found");let u;try{const e=await s.decrypt(c.v_pair,o);u="string"==typeof e?JSON.parse(e):e}catch(e){throw console.error("Error decrypting keys:",e),new Error("Unable to decrypt keys")}const p=await s.secret(t,u);if(!p)throw new Error("Unable to generate shared secret");console.log("Recover shared secret:",p);const{wallet:l,stealthAddress:f}=S(p,r);if(f.toLowerCase()!==e.toLowerCase())throw console.error("Mismatch:",{recovered:f,expected:e,sharedSecret:p}),new Error("Recovered stealth address does not match");return{wallet:l,address:f}}catch(e){throw console.error("Error recovering stealth funds:",e),e}},t.chain.announceStealthPayment=async function(e,t,r,a,o={onChain:!1,chain:"optimismSepolia"}){try{const i=this,s=await this.verifySignature(h,a);if(o.onChain){const a=await v(),i=getAddressesForChain(o.chain).STEALTH_ANNOUNCER_ADDRESS;console.log("Using contract address:",i);const s=new n.ethers.Contract(i,p,a),c=await s.devFee();console.log("Dev fee:",c.toString());const u=await s.announcePayment(t,r,e,{value:c});console.log("Transaction sent:",u.hash);const l=await u.wait();console.log("Transaction confirmed:",l.hash),console.log("Stealth payment announced on-chain (dev fee paid)")}else i.get("gun-eth").get("stealth-payments").set({stealthAddress:e,senderAddress:s,senderPublicKey:t,spendingPublicKey:r,timestamp:Date.now()}),console.log("Stealth payment announced off-chain")}catch(e){throw console.error("Error announcing stealth payment:",e),console.error("Error details:",e.stack),e}},t.chain.getStealthPayments=async function(e,t={source:"both"}){try{const r=[];if("onChain"===t.source||"both"===t.source){const t=await v(),a="development"===process.env.NODE_ENV?u.STEALTH_ANNOUNCER_ADDRESS:"...",o=new n.ethers.Contract(a,p,t);try{const t=await o.getAnnouncementsCount(),n=Number(t.toString());if(console.log("Total on-chain announcements:",n),n>0){const t=100,a=n-1;for(let n=0;n<=a;n+=t){const i=Math.min(n+t-1,a),s=await o.getAnnouncementsInRange(n,i);for(const t of s)try{if(!(t&&t.stealthAddress&&t.senderPublicKey&&t.spendingPublicKey)){console.log("Invalid announcement:",t);continue}const n=await this.recoverStealthFunds(t.stealthAddress,t.senderPublicKey,e,t.spendingPublicKey);r.push({stealthAddress:t.stealthAddress,senderPublicKey:t.senderPublicKey,spendingPublicKey:t.spendingPublicKey,timestamp:Number(t.timestamp),source:"onChain",wallet:n})}catch(e){console.log(`Announcement not for us: ${t.stealthAddress}`);continue}}}}catch(e){console.error("Error retrieving on-chain announcements:",e)}}if("offChain"===t.source||"both"===t.source){const e=this,t=await new Promise((t=>{const n=[];e.get("gun-eth").get("stealth-payments").get(recipientAddress).map().once(((e,t)=>{e?.stealthAddress&&n.push({...e,id:t,source:"offChain"})})),setTimeout((()=>t(n)),2e3)}));r.push(...t)}return console.log(`Found ${r.length} stealth payments`),r}catch(e){throw console.error("Error retrieving stealth payments:",e),e}},t.chain.cleanStealthPayments=async function(e){try{const t=this,n=await t.get("gun-eth").get("stealth-payments").get(e).map().once().then();n&&Object.keys(n).forEach((async r=>{const a=n[r];a&&a.stealthAddress&&a.senderPublicKey&&a.spendingPublicKey||await t.get("gun-eth").get("stealth-payments").get(e).get(r).put(null)}))}catch(e){console.error("Error cleaning stealth payments:",e)}};class A{static generateRandomId=w;static generatePassword=b;static gunToEthAccount=m;static getSigner=v;static deriveStealthAddress=S;static chainMethods={setSigner:t.chain.setSigner,getSigner:t.chain.getSigner,verifySignature:t.chain.verifySignature,generatePassword:t.chain.generatePassword,createSignature:t.chain.createSignature,createAndStoreEncryptedPair:t.chain.createAndStoreEncryptedPair,getAndDecryptPair:t.chain.getAndDecryptPair,proof:t.chain.proof,gunToEthAccount:t.chain.gunToEthAccount,generateStealthAddress:t.chain.generateStealthAddress,publishStealthKeys:t.chain.publishStealthKeys,recoverStealthFunds:t.chain.recoverStealthFunds,announceStealthPayment:t.chain.announceStealthPayment,getStealthPayments:t.chain.getStealthPayments,cleanStealthPayments:t.chain.cleanStealthPayments};static MESSAGE_TO_SIGN=h;static PROOF_CONTRACT_ADDRESS=f;static LOCAL_CONFIG=u}e.default=t,e.GunEth=A,e.MESSAGE_TO_SIGN=h,e.deriveStealthAddress=S,e.generatePassword=b,e.generateRandomId=w,e.getSigner=v,e.gunToEthAccount=m,Object.defineProperty(e,"__esModule",{value:!0})}));
2
- //# sourceMappingURL=gun-eth.min.js.map
@@ -1 +0,0 @@
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,IAC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