gun-eth 1.5.3 → 1.5.4

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,3454 @@
1
+ import 'gun/sea.js';
2
+ import { ethers } from 'ethers';
3
+
4
+ function getDefaultExportFromCjs (x) {
5
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
6
+ }
7
+
8
+ function commonjsRequire(path) {
9
+ throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
10
+ }
11
+
12
+ var gun$1 = {exports: {}};
13
+
14
+ gun$1.exports;
15
+
16
+ (function (module) {
17
+ (function(){
18
+
19
+ /* UNBUILD */
20
+ function USE(arg, req){
21
+ return req? commonjsRequire(arg) : arg.slice? USE[R(arg)] : function(mod, path){
22
+ arg(mod = {exports: {}});
23
+ USE[R(path)] = mod.exports;
24
+ }
25
+ function R(p){
26
+ return p.split('/').slice(-1).toString().replace('.js','');
27
+ }
28
+ }
29
+ { var MODULE = module; }
30
+ USE(function(module){
31
+ // Shim for generic javascript utilities.
32
+ String.random = function(l, c){
33
+ var s = '';
34
+ l = l || 24; // you are not going to make a 0 length random number, so no need to check type
35
+ c = c || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXZabcdefghijklmnopqrstuvwxyz';
36
+ while(l-- > 0){ s += c.charAt(Math.floor(Math.random() * c.length)); }
37
+ return s;
38
+ };
39
+ String.match = function(t, o){ var tmp, u;
40
+ if('string' !== typeof t){ return false }
41
+ if('string' == typeof o){ o = {'=': o}; }
42
+ o = o || {};
43
+ tmp = (o['='] || o['*'] || o['>'] || o['<']);
44
+ if(t === tmp){ return true }
45
+ if(u !== o['=']){ return false }
46
+ tmp = (o['*'] || o['>']);
47
+ if(t.slice(0, (tmp||'').length) === tmp){ return true }
48
+ if(u !== o['*']){ return false }
49
+ if(u !== o['>'] && u !== o['<']){
50
+ return (t >= o['>'] && t <= o['<'])? true : false;
51
+ }
52
+ if(u !== o['>'] && t >= o['>']){ return true }
53
+ if(u !== o['<'] && t <= o['<']){ return true }
54
+ return false;
55
+ };
56
+ String.hash = function(s, c){ // via SO
57
+ if(typeof s !== 'string'){ return }
58
+ c = c || 0; // CPU schedule hashing by
59
+ if(!s.length){ return c }
60
+ for(var i=0,l=s.length,n; i<l; ++i){
61
+ n = s.charCodeAt(i);
62
+ c = ((c<<5)-c)+n;
63
+ c |= 0;
64
+ }
65
+ return c;
66
+ };
67
+ var has = Object.prototype.hasOwnProperty;
68
+ Object.plain = function(o){ return o? (o instanceof Object && o.constructor === Object) || Object.prototype.toString.call(o).match(/^\[object (\w+)\]$/)[1] === 'Object' : false };
69
+ Object.empty = function(o, n){
70
+ for(var k in o){ if(has.call(o, k) && (!n || -1==n.indexOf(k))){ return false } }
71
+ return true;
72
+ };
73
+ Object.keys = Object.keys || function(o){
74
+ var l = [];
75
+ for(var k in o){ if(has.call(o, k)){ l.push(k); } }
76
+ return l;
77
+ }
78
+ ;(function(){
79
+ var u, sT = setTimeout, l = 0, c = 0
80
+ , sI = (typeof setImmediate !== ''+u && setImmediate) || (function(c,f){
81
+ if(typeof MessageChannel == ''+u){ return sT }
82
+ (c = new MessageChannel()).port1.onmessage = function(e){ ''==e.data && f(); };
83
+ return function(q){ f=q;c.port2.postMessage(''); }
84
+ }()), check = sT.check = sT.check || (typeof performance !== ''+u && performance)
85
+ || {now: function(){ return +new Date }};
86
+ sT.hold = sT.hold || 9; // half a frame benchmarks faster than < 1ms?
87
+ sT.poll = sT.poll || function(f){
88
+ if((sT.hold >= (check.now() - l)) && c++ < 3333){ f(); return }
89
+ sI(function(){ l = check.now(); f(); },c=0);
90
+ };
91
+ }());
92
+ (function(){ // Too many polls block, this "threads" them in turns over a single thread in time.
93
+ var sT = setTimeout, t = sT.turn = sT.turn || function(f){ 1 == s.push(f) && p(T); }
94
+ , s = t.s = [], p = sT.poll, i = 0, f, T = function(){
95
+ if(f = s[i++]){ f(); }
96
+ if(i == s.length || 99 == i){
97
+ s = t.s = s.slice(i);
98
+ i = 0;
99
+ }
100
+ if(s.length){ p(T); }
101
+ };
102
+ }());
103
+ (function(){
104
+ var u, sT = setTimeout, T = sT.turn;
105
+ (sT.each = sT.each || function(l,f,e,S){ S = S || 9; (function t(s,L,r){
106
+ if(L = (s = (l||[]).splice(0,S)).length){
107
+ for(var i = 0; i < L; i++){
108
+ if(u !== (r = f(s[i]))){ break }
109
+ }
110
+ if(u === r){ T(t); return }
111
+ } e && e(r);
112
+ }());})();
113
+ }());
114
+ })(USE, './shim');
115
+ USE(function(module){
116
+ // On event emitter generic javascript utility.
117
+ module.exports = function onto(tag, arg, as){
118
+ if(!tag){ return {to: onto} }
119
+ var u, f = 'function' == typeof arg, tag = (this.tag || (this.tag = {}))[tag] || f && (
120
+ this.tag[tag] = {tag: tag, to: onto._ = { next: function(arg){ var tmp;
121
+ if(tmp = this.to){ tmp.next(arg); }
122
+ }}});
123
+ if(f){
124
+ var be = {
125
+ off: onto.off ||
126
+ (onto.off = function(){
127
+ if(this.next === onto._.next){ return !0 }
128
+ if(this === this.the.last){
129
+ this.the.last = this.back;
130
+ }
131
+ this.to.back = this.back;
132
+ this.next = onto._.next;
133
+ this.back.to = this.to;
134
+ if(this.the.last === this.the){
135
+ delete this.on.tag[this.the.tag];
136
+ }
137
+ }),
138
+ to: onto._,
139
+ next: arg,
140
+ the: tag,
141
+ on: this,
142
+ as: as,
143
+ };
144
+ (be.back = tag.last || tag).to = be;
145
+ return tag.last = be;
146
+ }
147
+ if((tag = tag.to) && u !== arg){ tag.next(arg); }
148
+ return tag;
149
+ };
150
+ })(USE, './onto');
151
+ USE(function(module){
152
+ // Valid values are a subset of JSON: null, binary, number (!Infinity), text,
153
+ // or a soul relation. Arrays need special algorithms to handle concurrency,
154
+ // so they are not supported directly. Use an extension that supports them if
155
+ // needed but research their problems first.
156
+ module.exports = function (v) {
157
+ // "deletes", nulling out keys.
158
+ return v === null ||
159
+ "string" === typeof v ||
160
+ "boolean" === typeof v ||
161
+ // we want +/- Infinity to be, but JSON does not support it, sad face.
162
+ // can you guess what v === v checks for? ;)
163
+ ("number" === typeof v && v != Infinity && v != -Infinity && v === v) ||
164
+ (!!v && "string" == typeof v["#"] && Object.keys(v).length === 1 && v["#"]);
165
+ };
166
+ })(USE, './valid');
167
+ USE(function(module){
168
+ USE('./shim');
169
+ function State(){
170
+ var t = +new Date;
171
+ if(last < t){
172
+ return N = 0, last = t + State.drift;
173
+ }
174
+ return last = t + ((N += 1) / D) + State.drift;
175
+ }
176
+ State.drift = 0;
177
+ var NI = -Infinity, N = 0, D = 999, last = NI, u; // WARNING! In the future, on machines that are D times faster than 2016AD machines, you will want to increase D by another several orders of magnitude so the processing speed never out paces the decimal resolution (increasing an integer effects the state accuracy).
178
+ State.is = function(n, k, o){ // convenience function to get the state on a key on a node and return it.
179
+ var tmp = (k && n && n._ && n._['>']) || o;
180
+ if(!tmp){ return }
181
+ return ('number' == typeof (tmp = tmp[k]))? tmp : NI;
182
+ };
183
+ State.ify = function(n, k, s, v, soul){ // put a key's state on a node.
184
+ (n = n || {})._ = n._ || {}; // safety check or init.
185
+ if(soul){ n._['#'] = soul; } // set a soul if specified.
186
+ var tmp = n._['>'] || (n._['>'] = {}); // grab the states data.
187
+ if(u !== k && k !== '_'){
188
+ if('number' == typeof s){ tmp[k] = s; } // add the valid state.
189
+ if(u !== v){ n[k] = v; } // Note: Not its job to check for valid values!
190
+ }
191
+ return n;
192
+ };
193
+ module.exports = State;
194
+ })(USE, './state');
195
+ USE(function(module){
196
+ USE('./shim');
197
+ function Dup(opt){
198
+ var dup = {s:{}}, s = dup.s;
199
+ opt = opt || {max: 999, age: 1000 * 9};//*/ 1000 * 9 * 3};
200
+ dup.check = function(id){
201
+ if(!s[id]){ return false }
202
+ return dt(id);
203
+ };
204
+ var dt = dup.track = function(id){
205
+ var it = s[id] || (s[id] = {});
206
+ it.was = dup.now = +new Date;
207
+ if(!dup.to){ dup.to = setTimeout(dup.drop, opt.age + 9); }
208
+ if(dt.ed){ dt.ed(id); }
209
+ return it;
210
+ };
211
+ dup.drop = function(age){
212
+ dup.to = null;
213
+ dup.now = +new Date;
214
+ var l = Object.keys(s);
215
+ console.STAT && console.STAT(dup.now, +new Date - dup.now, 'dup drop keys'); // prev ~20% CPU 7% RAM 300MB // now ~25% CPU 7% RAM 500MB
216
+ setTimeout.each(l, function(id){ var it = s[id]; // TODO: .keys( is slow?
217
+ if(it && (age || opt.age) > (dup.now - it.was)){ return }
218
+ delete s[id];
219
+ },0,99);
220
+ };
221
+ return dup;
222
+ }
223
+ module.exports = Dup;
224
+ })(USE, './dup');
225
+ USE(function(module){
226
+ // request / response module, for asking and acking messages.
227
+ USE('./onto'); // depends upon onto!
228
+ module.exports = function ask(cb, as){
229
+ if(!this.on){ return }
230
+ var lack = (this.opt||{}).lack || 9000;
231
+ if(!('function' == typeof cb)){
232
+ if(!cb){ return }
233
+ var id = cb['#'] || cb, tmp = (this.tag||'')[id];
234
+ if(!tmp){ return }
235
+ if(as){
236
+ tmp = this.on(id, as);
237
+ clearTimeout(tmp.err);
238
+ tmp.err = setTimeout(function(){ tmp.off(); }, lack);
239
+ }
240
+ return true;
241
+ }
242
+ var id = (as && as['#']) || random(9);
243
+ if(!cb){ return id }
244
+ var to = this.on(id, cb, as);
245
+ to.err = to.err || setTimeout(function(){ to.off();
246
+ to.next({err: "Error: No ACK yet.", lack: true});
247
+ }, lack);
248
+ return id;
249
+ };
250
+ var random = String.random || function(){ return Math.random().toString(36).slice(2) };
251
+ })(USE, './ask');
252
+ USE(function(module){
253
+
254
+ function Gun(o){
255
+ if(o instanceof Gun){ return (this._ = {$: this}).$ }
256
+ if(!(this instanceof Gun)){ return new Gun(o) }
257
+ return Gun.create(this._ = {$: this, opt: o});
258
+ }
259
+
260
+ Gun.is = function($){ return ($ instanceof Gun) || ($ && $._ && ($ === $._.$)) || false };
261
+
262
+ Gun.version = 0.2020;
263
+
264
+ Gun.chain = Gun.prototype;
265
+ Gun.chain.toJSON = function(){};
266
+
267
+ USE('./shim');
268
+ Gun.valid = USE('./valid');
269
+ Gun.state = USE('./state');
270
+ Gun.on = USE('./onto');
271
+ Gun.dup = USE('./dup');
272
+ Gun.ask = USE('./ask');
273
+ (function(){
274
+ Gun.create = function(at){
275
+ at.root = at.root || at;
276
+ at.graph = at.graph || {};
277
+ at.on = at.on || Gun.on;
278
+ at.ask = at.ask || Gun.ask;
279
+ at.dup = at.dup || Gun.dup();
280
+ var gun = at.$.opt(at.opt);
281
+ if(!at.once){
282
+ at.on('in', universe, at);
283
+ at.on('out', universe, at);
284
+ at.on('put', map, at);
285
+ Gun.on('create', at);
286
+ at.on('create', at);
287
+ }
288
+ at.once = 1;
289
+ return gun;
290
+ };
291
+ function universe(msg){
292
+ // TODO: BUG! msg.out = null being set!
293
+ //if(!F){ var eve = this; setTimeout(function(){ universe.call(eve, msg,1) },Math.random() * 100);return; } // ADD F TO PARAMS!
294
+ if(!msg){ return }
295
+ if(msg.out === universe){ this.to.next(msg); return }
296
+ var eve = this, as = eve.as, at = as.at || as, gun = at.$, dup = at.dup, tmp, DBG = msg.DBG;
297
+ (tmp = msg['#']) || (tmp = msg['#'] = text_rand(9));
298
+ if(dup.check(tmp)){ return } dup.track(tmp);
299
+ tmp = msg._; msg._ = ('function' == typeof tmp)? tmp : function(){};
300
+ (msg.$ && (msg.$ === (msg.$._||'').$)) || (msg.$ = gun);
301
+ if(msg['@'] && !msg.put){ ack(msg); }
302
+ if(!at.ask(msg['@'], msg)){ // is this machine listening for an ack?
303
+ DBG && (DBG.u = +new Date);
304
+ if(msg.put){ put(msg); return } else
305
+ if(msg.get){ Gun.on.get(msg, gun); }
306
+ }
307
+ DBG && (DBG.uc = +new Date);
308
+ eve.to.next(msg);
309
+ DBG && (DBG.ua = +new Date);
310
+ if(msg.nts || msg.NTS){ return } // TODO: This shouldn't be in core, but fast way to prevent NTS spread. Delete this line after all peers have upgraded to newer versions.
311
+ msg.out = universe; at.on('out', msg);
312
+ DBG && (DBG.ue = +new Date);
313
+ }
314
+ function put(msg){
315
+ if(!msg){ return }
316
+ var ctx = msg._||'', root = ctx.root = ((ctx.$ = msg.$||'')._||'').root;
317
+ if(msg['@'] && ctx.faith && !ctx.miss){ // TODO: AXE may split/route based on 'put' what should we do here? Detect @ in AXE? I think we don't have to worry, as DAM will route it on @.
318
+ msg.out = universe;
319
+ root.on('out', msg);
320
+ return;
321
+ }
322
+ ctx.latch = root.hatch; ctx.match = root.hatch = [];
323
+ var put = msg.put;
324
+ var DBG = ctx.DBG = msg.DBG, S = +new Date; CT = CT || S;
325
+ if(put['#'] && put['.']){ /*root && root.on('put', msg);*/ return } // TODO: BUG! This needs to call HAM instead.
326
+ DBG && (DBG.p = S);
327
+ ctx['#'] = msg['#'];
328
+ ctx.msg = msg;
329
+ ctx.all = 0;
330
+ ctx.stun = 1;
331
+ var nl = Object.keys(put);//.sort(); // TODO: This is unbounded operation, large graphs will be slower. Write our own CPU scheduled sort? Or somehow do it in below? Keys itself is not O(1) either, create ES5 shim over ?weak map? or custom which is constant.
332
+ console.STAT && console.STAT(S, ((DBG||ctx).pk = +new Date) - S, 'put sort');
333
+ var ni = 0, nj, kl, soul, node, states, err, tmp;
334
+ (function pop(o){
335
+ if(nj != ni){ nj = ni;
336
+ if(!(soul = nl[ni])){
337
+ console.STAT && console.STAT(S, ((DBG||ctx).pd = +new Date) - S, 'put');
338
+ fire(ctx);
339
+ return;
340
+ }
341
+ if(!(node = put[soul])){ err = ERR+cut(soul)+"no node."; } else
342
+ if(!(tmp = node._)){ err = ERR+cut(soul)+"no meta."; } else
343
+ if(soul !== tmp['#']){ err = ERR+cut(soul)+"soul not same."; } else
344
+ if(!(states = tmp['>'])){ err = ERR+cut(soul)+"no state."; }
345
+ kl = Object.keys(node||{}); // TODO: .keys( is slow
346
+ }
347
+ if(err){
348
+ msg.err = ctx.err = err; // invalid data should error and stun the message.
349
+ fire(ctx);
350
+ //console.log("handle error!", err) // handle!
351
+ return;
352
+ }
353
+ var i = 0, key; o = o || 0;
354
+ while(o++ < 9 && (key = kl[i++])){
355
+ if('_' === key){ continue }
356
+ var val = node[key], state = states[key];
357
+ if(u === state){ err = ERR+cut(key)+"on"+cut(soul)+"no state."; break }
358
+ if(!valid(val)){ err = ERR+cut(key)+"on"+cut(soul)+"bad "+(typeof val)+cut(val); break }
359
+ //ctx.all++; //ctx.ack[soul+key] = '';
360
+ ham(val, key, soul, state, msg);
361
+ ++C; // courtesy count;
362
+ }
363
+ if((kl = kl.slice(i)).length){ turn(pop); return }
364
+ ++ni; kl = null; pop(o);
365
+ }());
366
+ } Gun.on.put = put;
367
+ // TODO: MARK!!! clock below, reconnect sync, SEA certify wire merge, User.auth taking multiple times, // msg put, put, say ack, hear loop...
368
+ // WASIS BUG! local peer not ack. .off other people: .open
369
+ function ham(val, key, soul, state, msg){
370
+ var ctx = msg._||'', root = ctx.root, graph = root.graph, tmp;
371
+ var vertex = graph[soul] || empty, was = state_is(vertex, key, 1), known = vertex[key];
372
+
373
+ var DBG = ctx.DBG; if(tmp = console.STAT){ if(!graph[soul] || !known){ tmp.has = (tmp.has || 0) + 1; } }
374
+
375
+ var now = State();
376
+ if(state > now){
377
+ setTimeout(function(){ ham(val, key, soul, state, msg); }, (tmp = state - now) > MD? MD : tmp); // Max Defer 32bit. :(
378
+ console.STAT && console.STAT(((DBG||ctx).Hf = +new Date), tmp, 'future');
379
+ return;
380
+ }
381
+ if(state < was){ /*old;*/ { return } } // but some chains have a cache miss that need to re-fire. // TODO: Improve in future. // for AXE this would reduce rebroadcast, but GUN does it on message forwarding. // TURNS OUT CACHE MISS WAS NOT NEEDED FOR NEW CHAINS ANYMORE!!! DANGER DANGER DANGER, ALWAYS RETURN! (or am I missing something?)
382
+ if(!ctx.faith){ // TODO: BUG? Can this be used for cache miss as well? // Yes this was a bug, need to check cache miss for RAD tests, but should we care about the faith check now? Probably not.
383
+ if(state === was && (val === known || L(val) <= L(known))){ /*console.log("same");*/ /*same;*/ if(!ctx.miss){ return } } // same
384
+ }
385
+ ctx.stun++; // TODO: 'forget' feature in SEA tied to this, bad approach, but hacked in for now. Any changes here must update there.
386
+ var aid = msg['#']+ctx.all++, id = {toString: function(){ return aid }, _: ctx}; id.toJSON = id.toString; // this *trick* makes it compatible between old & new versions.
387
+ root.dup.track(id)['#'] = msg['#']; // fixes new OK acks for RPC like RTC.
388
+ DBG && (DBG.ph = DBG.ph || +new Date);
389
+ root.on('put', {'#': id, '@': msg['@'], put: {'#': soul, '.': key, ':': val, '>': state}, ok: msg.ok, _: ctx});
390
+ }
391
+ function map(msg){
392
+ var DBG; if(DBG = (msg._||'').DBG){ DBG.pa = +new Date; DBG.pm = DBG.pm || +new Date;}
393
+ var eve = this, root = eve.as, graph = root.graph, ctx = msg._, put = msg.put, soul = put['#'], key = put['.'], val = put[':'], state = put['>']; msg['#']; var tmp;
394
+ if((tmp = ctx.msg) && (tmp = tmp.put) && (tmp = tmp[soul])){ state_ify(tmp, key, state, val, soul); } // necessary! or else out messages do not get SEA transforms.
395
+ //var bytes = ((graph[soul]||'')[key]||'').length||1;
396
+ graph[soul] = state_ify(graph[soul], key, state, val, soul);
397
+ if(tmp = (root.next||'')[soul]){
398
+ //tmp.bytes = (tmp.bytes||0) + ((val||'').length||1) - bytes;
399
+ //if(tmp.bytes > 2**13){ Gun.log.once('byte-limit', "Note: In the future, GUN peers will enforce a ~4KB query limit. Please see https://gun.eco/docs/Page") }
400
+ tmp.on('in', msg);
401
+ }
402
+ fire(ctx);
403
+ eve.to.next(msg);
404
+ }
405
+ function fire(ctx, msg){ var root;
406
+ if(ctx.stop){ return }
407
+ if(!ctx.err && 0 < --ctx.stun){ return } // TODO: 'forget' feature in SEA tied to this, bad approach, but hacked in for now. Any changes here must update there.
408
+ ctx.stop = 1;
409
+ if(!(root = ctx.root)){ return }
410
+ var tmp = ctx.match; tmp.end = 1;
411
+ if(tmp === root.hatch){ if(!(tmp = ctx.latch) || tmp.end){ delete root.hatch; } else { root.hatch = tmp; } }
412
+ ctx.hatch && ctx.hatch(); // TODO: rename/rework how put & this interact.
413
+ setTimeout.each(ctx.match, function(cb){cb && cb();});
414
+ if(!(msg = ctx.msg) || ctx.err || msg.err){ return }
415
+ msg.out = universe;
416
+ ctx.root.on('out', msg);
417
+
418
+ CF(); // courtesy check;
419
+ }
420
+ function ack(msg){ // aggregate ACKs.
421
+ var id = msg['@'] || '', ctx;
422
+ if(!(ctx = id._)){
423
+ var dup = (dup = msg.$) && (dup = dup._) && (dup = dup.root) && (dup = dup.dup);
424
+ if(!(dup = dup.check(id))){ return }
425
+ msg['@'] = dup['#'] || msg['@']; // This doesn't do anything anymore, backtrack it to something else?
426
+ return;
427
+ }
428
+ ctx.acks = (ctx.acks||0) + 1;
429
+ if(ctx.err = msg.err){
430
+ msg['@'] = ctx['#'];
431
+ fire(ctx); // TODO: BUG? How it skips/stops propagation of msg if any 1 item is error, this would assume a whole batch/resync has same malicious intent.
432
+ }
433
+ ctx.ok = msg.ok || ctx.ok;
434
+ if(!ctx.stop && !ctx.crack){ ctx.crack = ctx.match && ctx.match.push(function(){back(ctx);}); } // handle synchronous acks. NOTE: If a storage peer ACKs synchronously then the PUT loop has not even counted up how many items need to be processed, so ctx.STOP flags this and adds only 1 callback to the end of the PUT loop.
435
+ back(ctx);
436
+ }
437
+ function back(ctx){
438
+ if(!ctx || !ctx.root){ return }
439
+ if(ctx.stun || ctx.acks !== ctx.all){ return }
440
+ ctx.root.on('in', {'@': ctx['#'], err: ctx.err, ok: ctx.err? u : ctx.ok || {'':1}});
441
+ }
442
+
443
+ var ERR = "Error: Invalid graph!";
444
+ var cut = function(s){ return " '"+(''+s).slice(0,9)+"...' " };
445
+ var L = JSON.stringify, MD = 2147483647, State = Gun.state;
446
+ var C = 0, CT, CF = function(){if(C>999 && (C/-(CT - (CT = +new Date))>1)){Gun.window && console.log("Warning: You're syncing 1K+ records a second, faster than DOM can update - consider limiting query.");CF=function(){C=0;};}};
447
+
448
+ }());
449
+ (function(){
450
+ Gun.on.get = function(msg, gun){
451
+ var root = gun._, get = msg.get, soul = get['#'], node = root.graph[soul], has = get['.'];
452
+ var next = root.next || (root.next = {}), at = next[soul];
453
+
454
+ // TODO: Azarattum bug, what is in graph is not same as what is in next. Fix!
455
+
456
+ // queue concurrent GETs?
457
+ // TODO: consider tagging original message into dup for DAM.
458
+ // TODO: ^ above? In chat app, 12 messages resulted in same peer asking for `#user.pub` 12 times. (same with #user GET too, yipes!) // DAM note: This also resulted in 12 replies from 1 peer which all had same ##hash but none of them deduped because each get was different.
459
+ // TODO: Moving quick hacks fixing these things to axe for now.
460
+ // TODO: a lot of GET #foo then GET #foo."" happening, why?
461
+ // TODO: DAM's ## hash check, on same get ACK, producing multiple replies still, maybe JSON vs YSON?
462
+ // TMP note for now: viMZq1slG was chat LEX query #.
463
+ /*if(gun !== (tmp = msg.$) && (tmp = (tmp||'')._)){
464
+ if(tmp.Q){ tmp.Q[msg['#']] = ''; return } // chain does not need to ask for it again.
465
+ tmp.Q = {};
466
+ }*/
467
+ /*if(u === has){
468
+ if(at.Q){
469
+ //at.Q[msg['#']] = '';
470
+ //return;
471
+ }
472
+ at.Q = {};
473
+ }*/
474
+ var ctx = msg._||{}, DBG = ctx.DBG = msg.DBG;
475
+ DBG && (DBG.g = +new Date);
476
+ //console.log("GET:", get, node, has, at);
477
+ //if(!node && !at){ return root.on('get', msg) }
478
+ //if(has && node){ // replace 2 below lines to continue dev?
479
+ if(!node){ return root.on('get', msg) }
480
+ if(has){
481
+ if('string' != typeof has || u === node[has]){
482
+ if(!((at||'').next||'')[has]){ root.on('get', msg); return }
483
+ }
484
+ node = state_ify({}, has, state_is(node, has), node[has], soul);
485
+ // If we have a key in-memory, do we really need to fetch?
486
+ // Maybe... in case the in-memory key we have is a local write
487
+ // we still need to trigger a pull/merge from peers.
488
+ }
489
+ //Gun.window? Gun.obj.copy(node) : node; // HNPERF: If !browser bump Performance? Is this too dangerous to reference root graph? Copy / shallow copy too expensive for big nodes. Gun.obj.to(node); // 1 layer deep copy // Gun.obj.copy(node); // too slow on big nodes
490
+ node && ack(msg, node);
491
+ root.on('get', msg); // send GET to storage adapters.
492
+ };
493
+ function ack(msg, node){
494
+ var S = +new Date, ctx = msg._||{}, DBG = ctx.DBG = msg.DBG;
495
+ var to = msg['#'], id = text_rand(9), keys = Object.keys(node||'').sort(), soul = ((node||'')._||'')['#']; keys.length; var root = msg.$._.root, F = (node === root.graph[soul]);
496
+ console.STAT && console.STAT(S, ((DBG||ctx).gk = +new Date) - S, 'got keys');
497
+ // PERF: Consider commenting this out to force disk-only reads for perf testing? // TODO: .keys( is slow
498
+ node && (function go(){
499
+ S = +new Date;
500
+ var i = 0, k, put = {}, tmp;
501
+ while(i < 9 && (k = keys[i++])){
502
+ state_ify(put, k, state_is(node, k), node[k], soul);
503
+ }
504
+ keys = keys.slice(i);
505
+ (tmp = {})[soul] = put; put = tmp;
506
+ var faith; if(F){ faith = function(){}; faith.ram = faith.faith = true; } // HNPERF: We're testing performance improvement by skipping going through security again, but this should be audited.
507
+ tmp = keys.length;
508
+ console.STAT && console.STAT(S, -(S - (S = +new Date)), 'got copied some');
509
+ DBG && (DBG.ga = +new Date);
510
+ root.on('in', {'@': to, '#': id, put: put, '%': (tmp? (id = text_rand(9)) : u), $: root.$, _: faith, DBG: DBG, FOO: 1});
511
+ console.STAT && console.STAT(S, +new Date - S, 'got in');
512
+ if(!tmp){ return }
513
+ setTimeout.turn(go);
514
+ }());
515
+ if(!node){ root.on('in', {'@': msg['#']}); } // TODO: I don't think I like this, the default lS adapter uses this but "not found" is a sensitive issue, so should probably be handled more carefully/individually.
516
+ } Gun.on.get.ack = ack;
517
+ }());
518
+ (function(){
519
+ Gun.chain.opt = function(opt){
520
+ opt = opt || {};
521
+ var gun = this, at = gun._, tmp = opt.peers || opt;
522
+ if(!Object.plain(opt)){ opt = {}; }
523
+ if(!Object.plain(at.opt)){ at.opt = opt; }
524
+ if('string' == typeof tmp){ tmp = [tmp]; }
525
+ if(!Object.plain(at.opt.peers)){ at.opt.peers = {};}
526
+ if(tmp instanceof Array){
527
+ opt.peers = {};
528
+ tmp.forEach(function(url){
529
+ var p = {}; p.id = p.url = url;
530
+ opt.peers[url] = at.opt.peers[url] = at.opt.peers[url] || p;
531
+ });
532
+ }
533
+ obj_each(opt, function each(k){ var v = this[k];
534
+ if((this && this.hasOwnProperty(k)) || 'string' == typeof v || Object.empty(v)){ this[k] = v; return }
535
+ if(v && v.constructor !== Object && !(v instanceof Array)){ return }
536
+ obj_each(v, each);
537
+ });
538
+ at.opt.from = opt;
539
+ Gun.on('opt', at);
540
+ at.opt.uuid = at.opt.uuid || function uuid(l){ return Gun.state().toString(36).replace('.','') + String.random(l||12) };
541
+ return gun;
542
+ };
543
+ }());
544
+
545
+ var obj_each = function(o,f){ Object.keys(o).forEach(f,o); }, text_rand = String.random, turn = setTimeout.turn, valid = Gun.valid, state_is = Gun.state.is, state_ify = Gun.state.ify, u, empty = {}, C;
546
+
547
+ Gun.log = function(){ return (!Gun.log.off && C.log.apply(C, arguments)), [].slice.call(arguments).join(' ') };
548
+ Gun.log.once = function(w,s,o){ return (o = Gun.log.once)[w] = o[w] || 0, o[w]++ || Gun.log(s) };
549
+
550
+ if(typeof window !== "undefined"){ (window.GUN = window.Gun = Gun).window = window; }
551
+ try{ if(typeof MODULE !== "undefined"){ MODULE.exports = Gun; } }catch(e){}
552
+ module.exports = Gun;
553
+
554
+ (Gun.window||{}).console = (Gun.window||{}).console || {log: function(){}};
555
+ (C = console).only = function(i, s){ return (C.only.i && i === C.only.i && C.only.i++) && (C.log.apply(C, arguments) || s) };
556
+ Gun.log.once("welcome", "Hello wonderful person! :) Thanks for using GUN, please ask for help on http://chat.gun.eco if anything takes you longer than 5min to figure out!");
557
+ })(USE, './root');
558
+ USE(function(module){
559
+ var Gun = USE('./root');
560
+ Gun.chain.back = function(n, opt){ var tmp;
561
+ n = n || 1;
562
+ if(-1 === n || Infinity === n){
563
+ return this._.root.$;
564
+ } else
565
+ if(1 === n){
566
+ return (this._.back || this._).$;
567
+ }
568
+ var gun = this, at = gun._;
569
+ if(typeof n === 'string'){
570
+ n = n.split('.');
571
+ }
572
+ if(n instanceof Array){
573
+ var i = 0, l = n.length, tmp = at;
574
+ for(i; i < l; i++){
575
+ tmp = (tmp||empty)[n[i]];
576
+ }
577
+ if(u !== tmp){
578
+ return opt? gun : tmp;
579
+ } else
580
+ if((tmp = at.back)){
581
+ return tmp.$.back(n, opt);
582
+ }
583
+ return;
584
+ }
585
+ if('function' == typeof n){
586
+ var yes, tmp = {back: at};
587
+ while((tmp = tmp.back)
588
+ && u === (yes = n(tmp, opt))){}
589
+ return yes;
590
+ }
591
+ if('number' == typeof n){
592
+ return (at.back || at).$.back(n - 1);
593
+ }
594
+ return this;
595
+ };
596
+ var empty = {}, u;
597
+ })(USE, './back');
598
+ USE(function(module){
599
+ // WARNING: GUN is very simple, but the JavaScript chaining API around GUN
600
+ // is complicated and was extremely hard to build. If you port GUN to another
601
+ // language, consider implementing an easier API to build.
602
+ var Gun = USE('./root');
603
+ Gun.chain.chain = function(sub){
604
+ var gun = this, at = gun._, chain = new (sub || gun).constructor(gun), cat = chain._, root;
605
+ cat.root = root = at.root;
606
+ cat.id = ++root.once;
607
+ cat.back = gun._;
608
+ cat.on = Gun.on;
609
+ cat.on('in', Gun.on.in, cat); // For 'in' if I add my own listeners to each then I MUST do it before in gets called. If I listen globally for all incoming data instead though, regardless of individual listeners, I can transform the data there and then as well.
610
+ cat.on('out', Gun.on.out, cat); // However for output, there isn't really the global option. I must listen by adding my own listener individually BEFORE this one is ever called.
611
+ return chain;
612
+ };
613
+
614
+ function output(msg){
615
+ var get, at = this.as, back = at.back, root = at.root, tmp;
616
+ if(!msg.$){ msg.$ = at.$; }
617
+ this.to.next(msg);
618
+ if(at.err){ at.on('in', {put: at.put = u, $: at.$}); return }
619
+ if(get = msg.get){
620
+ /*if(u !== at.put){
621
+ at.on('in', at);
622
+ return;
623
+ }*/
624
+ if(root.pass){ root.pass[at.id] = at; } // will this make for buggy behavior elsewhere?
625
+ if(at.lex){ Object.keys(at.lex).forEach(function(k){ tmp[k] = at.lex[k]; }, tmp = msg.get = msg.get || {}); }
626
+ if(get['#'] || at.soul){
627
+ get['#'] = get['#'] || at.soul;
628
+ //root.graph[get['#']] = root.graph[get['#']] || {_:{'#':get['#'],'>':{}}};
629
+ msg['#'] || (msg['#'] = text_rand(9)); // A3120 ?
630
+ back = (root.$.get(get['#'])._);
631
+ if(!(get = get['.'])){ // soul
632
+ tmp = back.ask && back.ask['']; // check if we have already asked for the full node
633
+ (back.ask || (back.ask = {}))[''] = back; // add a flag that we are now.
634
+ if(u !== back.put){ // if we already have data,
635
+ back.on('in', back); // send what is cached down the chain
636
+ if(tmp){ return } // and don't ask for it again.
637
+ }
638
+ msg.$ = back.$;
639
+ } else
640
+ if(obj_has(back.put, get)){ // TODO: support #LEX !
641
+ tmp = back.ask && back.ask[get];
642
+ (back.ask || (back.ask = {}))[get] = back.$.get(get)._;
643
+ back.on('in', {get: get, put: {'#': back.soul, '.': get, ':': back.put[get], '>': state_is(root.graph[back.soul], get)}});
644
+ if(tmp){ return }
645
+ }
646
+ /*put = (back.$.get(get)._);
647
+ if(!(tmp = put.ack)){ put.ack = -1 }
648
+ back.on('in', {
649
+ $: back.$,
650
+ put: Gun.state.ify({}, get, Gun.state(back.put, get), back.put[get]),
651
+ get: back.get
652
+ });
653
+ if(tmp){ return }
654
+ } else
655
+ if('string' != typeof get){
656
+ var put = {}, meta = (back.put||{})._;
657
+ Gun.obj.map(back.put, function(v,k){
658
+ if(!Gun.text.match(k, get)){ return }
659
+ put[k] = v;
660
+ })
661
+ if(!Gun.obj.empty(put)){
662
+ put._ = meta;
663
+ back.on('in', {$: back.$, put: put, get: back.get})
664
+ }
665
+ if(tmp = at.lex){
666
+ tmp = (tmp._) || (tmp._ = function(){});
667
+ if(back.ack < tmp.ask){ tmp.ask = back.ack }
668
+ if(tmp.ask){ return }
669
+ tmp.ask = 1;
670
+ }
671
+ }
672
+ */
673
+ root.ask(ack, msg); // A3120 ?
674
+ return root.on('in', msg);
675
+ }
676
+ //if(root.now){ root.now[at.id] = root.now[at.id] || true; at.pass = {} }
677
+ if(get['.']){
678
+ if(at.get){
679
+ msg = {get: {'.': at.get}, $: at.$};
680
+ (back.ask || (back.ask = {}))[at.get] = msg.$._; // TODO: PERFORMANCE? More elegant way?
681
+ return back.on('out', msg);
682
+ }
683
+ msg = {get: at.lex? msg.get : {}, $: at.$};
684
+ return back.on('out', msg);
685
+ }
686
+ (at.ask || (at.ask = {}))[''] = at; //at.ack = at.ack || -1;
687
+ if(at.get){
688
+ get['.'] = at.get;
689
+ (back.ask || (back.ask = {}))[at.get] = msg.$._; // TODO: PERFORMANCE? More elegant way?
690
+ return back.on('out', msg);
691
+ }
692
+ }
693
+ return back.on('out', msg);
694
+ } Gun.on.out = output;
695
+
696
+ function input(msg, cat){ cat = cat || this.as; // TODO: V8 may not be able to optimize functions with different parameter calls, so try to do benchmark to see if there is any actual difference.
697
+ var root = cat.root, gun = msg.$ || (msg.$ = cat.$), at = (gun||'')._ || empty, tmp = msg.put||'', soul = tmp['#'], key = tmp['.'], change = (u !== tmp['='])? tmp['='] : tmp[':'], state = tmp['>'] || -Infinity, sat; // eve = event, at = data at, cat = chain at, sat = sub at (children chains).
698
+ if(u !== msg.put && (u === tmp['#'] || u === tmp['.'] || (u === tmp[':'] && u === tmp['=']) || u === tmp['>'])){ // convert from old format
699
+ if(!valid(tmp)){
700
+ if(!(soul = ((tmp||'')._||'')['#'])){ console.log("chain not yet supported for", tmp, '...', msg, cat); return; }
701
+ gun = cat.root.$.get(soul);
702
+ return setTimeout.each(Object.keys(tmp).sort(), function(k){ // TODO: .keys( is slow // BUG? ?Some re-in logic may depend on this being sync?
703
+ if('_' == k || u === (state = state_is(tmp, k))){ return }
704
+ cat.on('in', {$: gun, put: {'#': soul, '.': k, '=': tmp[k], '>': state}, VIA: msg});
705
+ });
706
+ }
707
+ cat.on('in', {$: at.back.$, put: {'#': soul = at.back.soul, '.': key = at.has || at.get, '=': tmp, '>': state_is(at.back.put, key)}, via: msg}); // TODO: This could be buggy! It assumes/approxes data, other stuff could have corrupted it.
708
+ return;
709
+ }
710
+ if((msg.seen||'')[cat.id]){ return } (msg.seen || (msg.seen = function(){}))[cat.id] = cat; // help stop some infinite loops
711
+
712
+ if(cat !== at){ // don't worry about this when first understanding the code, it handles changing contexts on a message. A soul chain will never have a different context.
713
+ Object.keys(msg).forEach(function(k){ tmp[k] = msg[k]; }, tmp = {}); // make copy of message
714
+ tmp.get = cat.get || tmp.get;
715
+ if(!cat.soul && !cat.has){ // if we do not recognize the chain type
716
+ tmp.$$$ = tmp.$$$ || cat.$; // make a reference to wherever it came from.
717
+ } else
718
+ if(at.soul){ // a has (property) chain will have a different context sometimes if it is linked (to a soul chain). Anything that is not a soul or has chain, will always have different contexts.
719
+ tmp.$ = cat.$;
720
+ tmp.$$ = tmp.$$ || at.$;
721
+ }
722
+ msg = tmp; // use the message with the new context instead;
723
+ }
724
+ unlink(msg, cat);
725
+
726
+ if(((cat.soul/* && (cat.ask||'')['']*/) || msg.$$) && state >= state_is(root.graph[soul], key)){ // The root has an in-memory cache of the graph, but if our peer has asked for the data then we want a per deduplicated chain copy of the data that might have local edits on it.
727
+ (tmp = root.$.get(soul)._).put = state_ify(tmp.put, key, state, change, soul);
728
+ }
729
+ if(!at.soul /*&& (at.ask||'')['']*/ && state >= state_is(root.graph[soul], key) && (sat = (root.$.get(soul)._.next||'')[key])){ // Same as above here, but for other types of chains. // TODO: Improve perf by preventing echoes recaching.
730
+ sat.put = change; // update cache
731
+ if('string' == typeof (tmp = valid(change))){
732
+ sat.put = root.$.get(tmp)._.put || change; // share same cache as what we're linked to.
733
+ }
734
+ }
735
+
736
+ this.to && this.to.next(msg); // 1st API job is to call all chain listeners.
737
+ // TODO: Make input more reusable by only doing these (some?) calls if we are a chain we recognize? This means each input listener would be responsible for when listeners need to be called, which makes sense, as they might want to filter.
738
+ cat.any && setTimeout.each(Object.keys(cat.any), function(any){ (any = cat.any[any]) && any(msg); },0,99); // 1st API job is to call all chain listeners. // TODO: .keys( is slow // BUG: Some re-in logic may depend on this being sync.
739
+ cat.echo && setTimeout.each(Object.keys(cat.echo), function(lat){ (lat = cat.echo[lat]) && lat.on('in', msg); },0,99); // & linked at chains // TODO: .keys( is slow // BUG: Some re-in logic may depend on this being sync.
740
+
741
+ if(((msg.$$||'')._||at).soul){ // comments are linear, but this line of code is non-linear, so if I were to comment what it does, you'd have to read 42 other comments first... but you can't read any of those comments until you first read this comment. What!? // shouldn't this match link's check?
742
+ // is there cases where it is a $$ that we do NOT want to do the following?
743
+ if((sat = cat.next) && (sat = sat[key])){ // TODO: possible trick? Maybe have `ionmap` code set a sat? // TODO: Maybe we should do `cat.ask` instead? I guess does not matter.
744
+ tmp = {}; Object.keys(msg).forEach(function(k){ tmp[k] = msg[k]; });
745
+ tmp.$ = (msg.$$||msg.$).get(tmp.get = key); delete tmp.$$; delete tmp.$$$;
746
+ sat.on('in', tmp);
747
+ }
748
+ }
749
+
750
+ link(msg, cat);
751
+ } Gun.on.in = input;
752
+
753
+ function link(msg, cat){ cat = cat || this.as || msg.$._;
754
+ if(msg.$$ && this !== Gun.on){ return } // $$ means we came from a link, so we are at the wrong level, thus ignore it unless overruled manually by being called directly.
755
+ if(!msg.put || cat.soul){ return } // But you cannot overrule being linked to nothing, or trying to link a soul chain - that must never happen.
756
+ var put = msg.put||'', link = put['=']||put[':'], tmp;
757
+ var root = cat.root, tat = root.$.get(put['#']).get(put['.'])._;
758
+ if('string' != typeof (link = valid(link))){
759
+ if(this === Gun.on){ (tat.echo || (tat.echo = {}))[cat.id] = cat; } // allow some chain to explicitly force linking to simple data.
760
+ return; // by default do not link to data that is not a link.
761
+ }
762
+ if((tat.echo || (tat.echo = {}))[cat.id] // we've already linked ourselves so we do not need to do it again. Except... (annoying implementation details)
763
+ && !(root.pass||'')[cat.id]){ return } // if a new event listener was added, we need to make a pass through for it. The pass will be on the chain, not always the chain passed down.
764
+ if(tmp = root.pass){ if(tmp[link+cat.id]){ return } tmp[link+cat.id] = 1; } // But the above edge case may "pass through" on a circular graph causing infinite passes, so we hackily add a temporary check for that.
765
+
766
+ (tat.echo||(tat.echo={}))[cat.id] = cat; // set ourself up for the echo! // TODO: BUG? Echo to self no longer causes problems? Confirm.
767
+
768
+ if(cat.has){ cat.link = link; }
769
+ var sat = root.$.get(tat.link = link)._; // grab what we're linking to.
770
+ (sat.echo || (sat.echo = {}))[tat.id] = tat; // link it.
771
+ var tmp = cat.ask||''; // ask the chain for what needs to be loaded next!
772
+ if(tmp[''] || cat.lex){ // we might need to load the whole thing // TODO: cat.lex probably has edge case bugs to it, need more test coverage.
773
+ sat.on('out', {get: {'#': link}});
774
+ }
775
+ setTimeout.each(Object.keys(tmp), function(get, sat){ // if sub chains are asking for data. // TODO: .keys( is slow // BUG? ?Some re-in logic may depend on this being sync?
776
+ if(!get || !(sat = tmp[get])){ return }
777
+ sat.on('out', {get: {'#': link, '.': get}}); // go get it.
778
+ },0,99);
779
+ } Gun.on.link = link;
780
+
781
+ function unlink(msg, cat){ // ugh, so much code for seemingly edge case behavior.
782
+ var put = msg.put||'', change = (u !== put['='])? put['='] : put[':'], root = cat.root, link, tmp;
783
+ if(u === change){ // 1st edge case: If we have a brand new database, no data will be found.
784
+ // TODO: BUG! because emptying cache could be async from below, make sure we are not emptying a newer cache. So maybe pass an Async ID to check against?
785
+ // TODO: BUG! What if this is a map? // Warning! Clearing things out needs to be robust against sync/async ops, or else you'll see `map val get put` test catastrophically fail because map attempts to link when parent graph is streamed before child value gets set. Need to differentiate between lack acks and force clearing.
786
+ if(cat.soul && u !== cat.put){ return } // data may not be found on a soul, but if a soul already has data, then nothing can clear the soul as a whole.
787
+ //if(!cat.has){ return }
788
+ tmp = (msg.$$||msg.$||'')._||'';
789
+ if(msg['@'] && (u !== tmp.put || u !== cat.put)){ return } // a "not found" from other peers should not clear out data if we have already found it.
790
+ //if(cat.has && u === cat.put && !(root.pass||'')[cat.id]){ return } // if we are already unlinked, do not call again, unless edge case. // TODO: BUG! This line should be deleted for "unlink deeply nested".
791
+ if(link = cat.link || msg.linked){
792
+ delete (root.$.get(link)._.echo||'')[cat.id];
793
+ }
794
+ if(cat.has){ // TODO: Empty out links, maps, echos, acks/asks, etc.?
795
+ cat.link = null;
796
+ }
797
+ cat.put = u; // empty out the cache if, for example, alice's car's color no longer exists (relative to alice) if alice no longer has a car.
798
+ // TODO: BUG! For maps, proxy this so the individual sub is triggered, not all subs.
799
+ setTimeout.each(Object.keys(cat.next||''), function(get, sat){ // empty out all sub chains. // TODO: .keys( is slow // BUG? ?Some re-in logic may depend on this being sync? // TODO: BUG? This will trigger deeper put first, does put logic depend on nested order? // TODO: BUG! For map, this needs to be the isolated child, not all of them.
800
+ if(!(sat = cat.next[get])){ return }
801
+ //if(cat.has && u === sat.put && !(root.pass||'')[sat.id]){ return } // if we are already unlinked, do not call again, unless edge case. // TODO: BUG! This line should be deleted for "unlink deeply nested".
802
+ if(link){ delete (root.$.get(link).get(get)._.echo||'')[sat.id]; }
803
+ sat.on('in', {get: get, put: u, $: sat.$}); // TODO: BUG? Add recursive seen check?
804
+ },0,99);
805
+ return;
806
+ }
807
+ if(cat.soul){ return } // a soul cannot unlink itself.
808
+ if(msg.$$){ return } // a linked chain does not do the unlinking, the sub chain does. // TODO: BUG? Will this cancel maps?
809
+ link = valid(change); // need to unlink anytime we are not the same link, though only do this once per unlink (and not on init).
810
+ tmp = msg.$._||'';
811
+ if(link === tmp.link || (cat.has && !tmp.link)){
812
+ if((root.pass||'')[cat.id] && 'string' !== typeof link); else {
813
+ return;
814
+ }
815
+ }
816
+ delete (tmp.echo||'')[cat.id];
817
+ unlink({get: cat.get, put: u, $: msg.$, linked: msg.linked = msg.linked || tmp.link}, cat); // unlink our sub chains.
818
+ } Gun.on.unlink = unlink;
819
+
820
+ function ack(msg, ev){
821
+ //if(!msg['%'] && (this||'').off){ this.off() } // do NOT memory leak, turn off listeners! Now handled by .ask itself
822
+ // manhattan:
823
+ var as = this.as, at = as.$._; at.root; var get = as.get||'', tmp = (msg.put||'')[get['#']]||'';
824
+ if(!msg.put || ('string' == typeof get['.'] && u === tmp[get['.']])){
825
+ if(u !== at.put){ return }
826
+ if(!at.soul && !at.has){ return } // TODO: BUG? For now, only core-chains will handle not-founds, because bugs creep in if non-core chains are used as $ but we can revisit this later for more powerful extensions.
827
+ at.ack = (at.ack || 0) + 1;
828
+ at.on('in', {
829
+ get: at.get,
830
+ put: at.put = u,
831
+ $: at.$,
832
+ '@': msg['@']
833
+ });
834
+ /*(tmp = at.Q) && setTimeout.each(Object.keys(tmp), function(id){ // TODO: Temporary testing, not integrated or being used, probably delete.
835
+ Object.keys(msg).forEach(function(k){ tmp[k] = msg[k] }, tmp = {}); tmp['@'] = id; // copy message
836
+ root.on('in', tmp);
837
+ }); delete at.Q;*/
838
+ return;
839
+ }
840
+ (msg._||{}).miss = 1;
841
+ Gun.on.put(msg);
842
+ return; // eom
843
+ }
844
+
845
+ var empty = {}, u, text_rand = String.random, valid = Gun.valid, obj_has = function(o, k){ return o && Object.prototype.hasOwnProperty.call(o, k) }, state = Gun.state, state_is = state.is, state_ify = state.ify;
846
+ })(USE, './chain');
847
+ USE(function(module){
848
+ var Gun = USE('./root');
849
+ Gun.chain.get = function(key, cb, as){
850
+ var gun, tmp;
851
+ if(typeof key === 'string'){
852
+ if(key.length == 0) {
853
+ (gun = this.chain())._.err = {err: Gun.log('0 length key!', key)};
854
+ if(cb){ cb.call(gun, gun._.err); }
855
+ return gun;
856
+ }
857
+ var back = this, cat = back._;
858
+ var next = cat.next || empty;
859
+ if(!(gun = next[key])){
860
+ gun = key && cache(key, back);
861
+ }
862
+ gun = gun && gun.$;
863
+ } else
864
+ if('function' == typeof key){
865
+ if(true === cb){ return soul(this, key, cb, as), this }
866
+ gun = this;
867
+ var cat = gun._, opt = cb || {}, root = cat.root, id;
868
+ opt.at = cat;
869
+ opt.ok = key;
870
+ var wait = {}; // can we assign this to the at instead, like in once?
871
+ //var path = []; cat.$.back(at => { at.get && path.push(at.get.slice(0,9))}); path = path.reverse().join('.');
872
+ function any(msg, eve, f){
873
+ if(any.stun){ return }
874
+ if((tmp = root.pass) && !tmp[id]){ return }
875
+ var at = msg.$._, sat = (msg.$$||'')._, data = (sat||at).put, odd = (!at.has && !at.soul), test = {}, tmp;
876
+ if(odd || u === data){ // handles non-core
877
+ data = (u === ((tmp = msg.put)||'')['='])? (u === (tmp||'')[':'])? tmp : tmp[':'] : tmp['='];
878
+ }
879
+ if(('string' == typeof (tmp = Gun.valid(data)))){
880
+ data = (u === (tmp = root.$.get(tmp)._.put))? opt.not? u : data : tmp;
881
+ }
882
+ if(opt.not && u === data){ return }
883
+ if(u === opt.stun){
884
+ if((tmp = root.stun) && tmp.on){
885
+ cat.$.back(function(a){ // our chain stunned?
886
+ tmp.on(''+a.id, test = {});
887
+ if((test.run || 0) < any.id){ return test } // if there is an earlier stun on gapless parents/self.
888
+ });
889
+ !test.run && tmp.on(''+at.id, test = {}); // this node stunned?
890
+ !test.run && sat && tmp.on(''+sat.id, test = {}); // linked node stunned?
891
+ if(any.id > test.run){
892
+ if(!test.stun || test.stun.end){
893
+ test.stun = tmp.on('stun');
894
+ test.stun = test.stun && test.stun.last;
895
+ }
896
+ if(test.stun && !test.stun.end){
897
+ //if(odd && u === data){ return }
898
+ //if(u === msg.put){ return } // "not found" acks will be found if there is stun, so ignore these.
899
+ (test.stun.add || (test.stun.add = {}))[id] = function(){ any(msg,eve,1); }; // add ourself to the stun callback list that is called at end of the write.
900
+ return;
901
+ }
902
+ }
903
+ }
904
+ if(/*odd &&*/ u === data){ f = 0; } // if data not found, keep waiting/trying.
905
+ /*if(f && u === data){
906
+ cat.on('out', opt.out);
907
+ return;
908
+ }*/
909
+ if((tmp = root.hatch) && !tmp.end && u === opt.hatch && !f){ // quick hack! // What's going on here? Because data is streamed, we get things one by one, but a lot of developers would rather get a callback after each batch instead, so this does that by creating a wait list per chain id that is then called at the end of the batch by the hatch code in the root put listener.
910
+ if(wait[at.$._.id]){ return } wait[at.$._.id] = 1;
911
+ tmp.push(function(){any(msg,eve,1);});
912
+ return;
913
+ } wait = {}; // end quick hack.
914
+ }
915
+ // call:
916
+ if(root.pass){ if(root.pass[id+at.id]){ return } root.pass[id+at.id] = 1; }
917
+ if(opt.on){ opt.ok.call(at.$, data, at.get, msg, eve || any); return } // TODO: Also consider breaking `this` since a lot of people do `=>` these days and `.call(` has slower performance.
918
+ if(opt.v2020){ opt.ok(msg, eve || any); return }
919
+ Object.keys(msg).forEach(function(k){ tmp[k] = msg[k]; }, tmp = {}); msg = tmp; msg.put = data; // 2019 COMPATIBILITY! TODO: GET RID OF THIS!
920
+ opt.ok.call(opt.as, msg, eve || any); // is this the right
921
+ } any.at = cat;
922
+ //(cat.any||(cat.any=function(msg){ setTimeout.each(Object.keys(cat.any||''), function(act){ (act = cat.any[act]) && act(msg) },0,99) }))[id = String.random(7)] = any; // maybe switch to this in future?
923
+ (cat.any||(cat.any={}))[id = String.random(7)] = any;
924
+ any.off = function(){ any.stun = 1; if(!cat.any){ return } delete cat.any[id]; };
925
+ any.rid = rid; // logic from old version, can we clean it up now?
926
+ any.id = opt.run || ++root.once; // used in callback to check if we are earlier than a write. // will this ever cause an integer overflow?
927
+ tmp = root.pass; (root.pass = {})[id] = 1; // Explanation: test trade-offs want to prevent recursion so we add/remove pass flag as it gets fulfilled to not repeat, however map map needs many pass flags - how do we reconcile?
928
+ opt.out = opt.out || {get: {}};
929
+ cat.on('out', opt.out);
930
+ root.pass = tmp;
931
+ return gun;
932
+ } else
933
+ if('number' == typeof key){
934
+ return this.get(''+key, cb, as);
935
+ } else
936
+ if('string' == typeof (tmp = valid(key))){
937
+ return this.get(tmp, cb, as);
938
+ } else
939
+ if(tmp = this.get.next){
940
+ gun = tmp(this, key);
941
+ }
942
+ if(!gun){
943
+ (gun = this.chain())._.err = {err: Gun.log('Invalid get request!', key)}; // CLEAN UP
944
+ if(cb){ cb.call(gun, gun._.err); }
945
+ return gun;
946
+ }
947
+ if(cb && 'function' == typeof cb){
948
+ gun.get(cb, as);
949
+ }
950
+ return gun;
951
+ };
952
+ function cache(key, back){
953
+ var cat = back._, next = cat.next, gun = back.chain(), at = gun._;
954
+ if(!next){ next = cat.next = {}; }
955
+ next[at.get = key] = at;
956
+ if(back === cat.root.$){
957
+ at.soul = key;
958
+ //at.put = {};
959
+ } else
960
+ if(cat.soul || cat.has){
961
+ at.has = key;
962
+ //if(obj_has(cat.put, key)){
963
+ //at.put = cat.put[key];
964
+ //}
965
+ }
966
+ return at;
967
+ }
968
+ function soul(gun, cb, opt, as){
969
+ var cat = gun._, acks = 0, tmp;
970
+ if(tmp = cat.soul || cat.link){ return cb(tmp, as, cat) }
971
+ if(cat.jam){ return cat.jam.push([cb, as]) }
972
+ cat.jam = [[cb,as]];
973
+ gun.get(function go(msg, eve){
974
+ if(u === msg.put && !cat.root.opt.super && (tmp = Object.keys(cat.root.opt.peers).length) && ++acks <= tmp){ // TODO: super should not be in core code, bring AXE up into core instead to fix? // TODO: .keys( is slow
975
+ return;
976
+ }
977
+ eve.rid(msg);
978
+ var at = ((at = msg.$) && at._) || {}, i = 0, as;
979
+ tmp = cat.jam; delete cat.jam; // tmp = cat.jam.splice(0, 100);
980
+ //if(tmp.length){ process.nextTick(function(){ go(msg, eve) }) }
981
+ while(as = tmp[i++]){ //Gun.obj.map(tmp, function(as, cb){
982
+ var cb = as[0]; as = as[1];
983
+ cb && cb(at.link || at.soul || Gun.valid(msg.put) || ((msg.put||{})._||{})['#'], as, msg, eve);
984
+ } //);
985
+ }, {out: {get: {'.':true}}});
986
+ return gun;
987
+ }
988
+ function rid(at){
989
+ var cat = this.at || this.on;
990
+ if(!at || cat.soul || cat.has){ return this.off() }
991
+ if(!(at = (at = (at = at.$ || at)._ || at).id)){ return }
992
+ cat.map; var seen;
993
+ //if(!map || !(tmp = map[at]) || !(tmp = tmp.at)){ return }
994
+ if((seen = this.seen || (this.seen = {}))[at]){ return true }
995
+ seen[at] = true;
996
+ return;
997
+ }
998
+ var empty = {}, valid = Gun.valid, u;
999
+ })(USE, './get');
1000
+ USE(function(module){
1001
+ var Gun = USE('./root');
1002
+ Gun.chain.put = function(data, cb, as){ // I rewrote it :)
1003
+ var gun = this, at = gun._, root = at.root;
1004
+ as = as || {};
1005
+ as.root = at.root;
1006
+ as.run || (as.run = root.once);
1007
+ stun(as, at.id); // set a flag for reads to check if this chain is writing.
1008
+ as.ack = as.ack || cb;
1009
+ as.via = as.via || gun;
1010
+ as.data = as.data || data;
1011
+ as.soul || (as.soul = at.soul || ('string' == typeof cb && cb));
1012
+ var s = as.state = as.state || Gun.state();
1013
+ if('function' == typeof data){ data(function(d){ as.data = d; gun.put(u,u,as); }); return gun }
1014
+ if(!as.soul){ return get(as), gun }
1015
+ as.$ = root.$.get(as.soul); // TODO: This may not allow user chaining and similar?
1016
+ as.todo = [{it: as.data, ref: as.$}];
1017
+ as.turn = as.turn || turn;
1018
+ as.ran = as.ran || ran;
1019
+ //var path = []; as.via.back(at => { at.get && path.push(at.get.slice(0,9)) }); path = path.reverse().join('.');
1020
+ // TODO: Perf! We only need to stun chains that are being modified, not necessarily written to.
1021
+ (function walk(){
1022
+ var to = as.todo, at = to.pop(), d = at.it; at.ref && at.ref._.id; var v, k, cat, tmp, g;
1023
+ stun(as, at.ref);
1024
+ if(tmp = at.todo){
1025
+ k = tmp.pop(); d = d[k];
1026
+ if(tmp.length){ to.push(at); }
1027
+ }
1028
+ k && (to.path || (to.path = [])).push(k);
1029
+ if(!(v = valid(d)) && !(g = Gun.is(d))){
1030
+ if(!Object.plain(d)){ ran.err(as, "Invalid data: "+ check(d) +" at " + (as.via.back(function(at){at.get && tmp.push(at.get);}, tmp = []) || tmp.join('.'))+'.'+(to.path||[]).join('.')); return }
1031
+ var seen = as.seen || (as.seen = []), i = seen.length;
1032
+ while(i--){ if(d === (tmp = seen[i]).it){ v = d = tmp.link; break } }
1033
+ }
1034
+ if(k && v){ at.node = state_ify(at.node, k, s, d); } // handle soul later.
1035
+ else {
1036
+ if(!as.seen){ ran.err(as, "Data at root of graph must be a node (an object)."); return }
1037
+ as.seen.push(cat = {it: d, link: {}, todo: g? [] : Object.keys(d).sort().reverse(), path: (to.path||[]).slice(), up: at}); // Any perf reasons to CPU schedule this .keys( ?
1038
+ at.node = state_ify(at.node, k, s, cat.link);
1039
+ !g && cat.todo.length && to.push(cat);
1040
+ // ---------------
1041
+ var id = as.seen.length;
1042
+ (as.wait || (as.wait = {}))[id] = '';
1043
+ tmp = (cat.ref = (g? d : k? at.ref.get(k) : at.ref))._;
1044
+ (tmp = (d && (d._||'')['#']) || tmp.soul || tmp.link)? resolve({soul: tmp}) : cat.ref.get(resolve, {run: as.run, /*hatch: 0,*/ v2020:1, out:{get:{'.':' '}}}); // TODO: BUG! This should be resolve ONLY soul to prevent full data from being loaded. // Fixed now?
1045
+ //setTimeout(function(){ if(F){ return } console.log("I HAVE NOT BEEN CALLED!", path, id, cat.ref._.id, k) }, 9000); var F; // MAKE SURE TO ADD F = 1 below!
1046
+ function resolve(msg, eve){
1047
+ var end = cat.link['#'];
1048
+ if(eve){ eve.off(); eve.rid(msg); } // TODO: Too early! Check all peers ack not found.
1049
+ // TODO: BUG maybe? Make sure this does not pick up a link change wipe, that it uses the changign link instead.
1050
+ var soul = end || msg.soul || (tmp = (msg.$$||msg.$)._||'').soul || tmp.link || ((tmp = tmp.put||'')._||'')['#'] || tmp['#'] || (((tmp = msg.put||'') && msg.$$)? tmp['#'] : (tmp['=']||tmp[':']||'')['#']);
1051
+ !end && stun(as, msg.$);
1052
+ if(!soul && !at.link['#']){ // check soul link above us
1053
+ (at.wait || (at.wait = [])).push(function(){ resolve(msg, eve); }); // wait
1054
+ return;
1055
+ }
1056
+ if(!soul){
1057
+ soul = [];
1058
+ (msg.$$||msg.$).back(function(at){
1059
+ if(tmp = at.soul || at.link){ return soul.push(tmp) }
1060
+ soul.push(at.get);
1061
+ });
1062
+ soul = soul.reverse().join('/');
1063
+ }
1064
+ cat.link['#'] = soul;
1065
+ !g && (((as.graph || (as.graph = {}))[soul] = (cat.node || (cat.node = {_:{}})))._['#'] = soul);
1066
+ delete as.wait[id];
1067
+ cat.wait && setTimeout.each(cat.wait, function(cb){ cb && cb(); });
1068
+ as.ran(as);
1069
+ } // ---------------
1070
+ }
1071
+ if(!to.length){ return as.ran(as) }
1072
+ as.turn(walk);
1073
+ }());
1074
+ return gun;
1075
+ };
1076
+
1077
+ function stun(as, id){
1078
+ if(!id){ return } id = (id._||'').id||id;
1079
+ var run = as.root.stun || (as.root.stun = {on: Gun.on}), test = {}, tmp;
1080
+ as.stun || (as.stun = run.on('stun', function(){ }));
1081
+ if(tmp = run.on(''+id)){ tmp.the.last.next(test); }
1082
+ if(test.run >= as.run){ return }
1083
+ run.on(''+id, function(test){
1084
+ if(as.stun.end){
1085
+ this.off();
1086
+ this.to.next(test);
1087
+ return;
1088
+ }
1089
+ test.run = test.run || as.run;
1090
+ test.stun = test.stun || as.stun; return;
1091
+ });
1092
+ }
1093
+
1094
+ function ran(as){
1095
+ if(as.err){ ran.end(as.stun, as.root); return } // move log handle here.
1096
+ if(as.todo.length || as.end || !Object.empty(as.wait)){ return } as.end = 1;
1097
+ //(as.retry = function(){ as.acks = 0;
1098
+ var cat = (as.$.back(-1)._), root = cat.root, ask = cat.ask(function(ack){
1099
+ root.on('ack', ack);
1100
+ if(ack.err && !ack.lack){ Gun.log(ack); }
1101
+ if(++acks > (as.acks || 0)){ this.off(); } // Adjustable ACKs! Only 1 by default.
1102
+ if(!as.ack){ return }
1103
+ as.ack(ack, this);
1104
+ }, as.opt), acks = 0, stun = as.stun, tmp;
1105
+ (tmp = function(){ // this is not official yet, but quick solution to hack in for now.
1106
+ if(!stun){ return }
1107
+ ran.end(stun, root);
1108
+ setTimeout.each(Object.keys(stun = stun.add||''), function(cb){ if(cb = stun[cb]){cb();} }); // resume the stunned reads // Any perf reasons to CPU schedule this .keys( ?
1109
+ }).hatch = tmp; // this is not official yet ^
1110
+ //console.log(1, "PUT", as.run, as.graph);
1111
+ if(as.ack && !as.ok){ as.ok = as.acks || 9; } // TODO: In future! Remove this! This is just old API support.
1112
+ (as.via._).on('out', {put: as.out = as.graph, ok: as.ok && {'@': as.ok+1}, opt: as.opt, '#': ask, _: tmp});
1113
+ //})();
1114
+ } ran.end = function(stun,root){
1115
+ stun.end = noop; // like with the earlier id, cheaper to make this flag a function so below callbacks do not have to do an extra type check.
1116
+ if(stun.the.to === stun && stun === stun.the.last){ delete root.stun; }
1117
+ stun.off();
1118
+ }; ran.err = function(as, err){
1119
+ (as.ack||noop).call(as, as.out = { err: as.err = Gun.log(err) });
1120
+ as.ran(as);
1121
+ };
1122
+
1123
+ function get(as){
1124
+ var at = as.via._, tmp;
1125
+ as.via = as.via.back(function(at){
1126
+ if(at.soul || !at.get){ return at.$ }
1127
+ tmp = as.data; (as.data = {})[at.get] = tmp;
1128
+ });
1129
+ if(!as.via || !as.via._.soul){
1130
+ as.via = at.root.$.get(((as.data||'')._||'')['#'] || at.$.back('opt.uuid')());
1131
+ }
1132
+ as.via.put(as.data, as.ack, as);
1133
+
1134
+
1135
+ return;
1136
+ }
1137
+ function check(d, tmp){ return ((d && (tmp = d.constructor) && tmp.name) || typeof d) }
1138
+
1139
+ var u, noop = function(){}, turn = setTimeout.turn, valid = Gun.valid, state_ify = Gun.state.ify;
1140
+ })(USE, './put');
1141
+ USE(function(module){
1142
+ var Gun = USE('./root');
1143
+ USE('./chain');
1144
+ USE('./back');
1145
+ USE('./put');
1146
+ USE('./get');
1147
+ module.exports = Gun;
1148
+ })(USE, './index');
1149
+ USE(function(module){
1150
+ var Gun = USE('./index');
1151
+ Gun.chain.on = function(tag, arg, eas, as){ // don't rewrite!
1152
+ var gun = this, cat = gun._; cat.root; var act;
1153
+ if(typeof tag === 'string'){
1154
+ if(!arg){ return cat.on(tag) }
1155
+ act = cat.on(tag, arg, eas || cat, as);
1156
+ if(eas && eas.$){
1157
+ (eas.subs || (eas.subs = [])).push(act);
1158
+ }
1159
+ return gun;
1160
+ }
1161
+ var opt = arg;
1162
+ (opt = (true === opt)? {change: true} : opt || {}).not = 1; opt.on = 1;
1163
+ gun.get(tag, opt);
1164
+ /*gun.get(function on(data,key,msg,eve){ var $ = this;
1165
+ if(tmp = root.hatch){ // quick hack!
1166
+ if(wait[$._.id]){ return } wait[$._.id] = 1;
1167
+ tmp.push(function(){on.call($, data,key,msg,eve)});
1168
+ return;
1169
+ }; wait = {}; // end quick hack.
1170
+ tag.call($, data,key,msg,eve);
1171
+ }, opt); // TODO: PERF! Event listener leak!!!?*/
1172
+ /*
1173
+ function one(msg, eve){
1174
+ if(one.stun){ return }
1175
+ var at = msg.$._, data = at.put, tmp;
1176
+ if(tmp = at.link){ data = root.$.get(tmp)._.put }
1177
+ if(opt.not===u && u === data){ return }
1178
+ if(opt.stun===u && (tmp = root.stun) && (tmp = tmp[at.id] || tmp[at.back.id]) && !tmp.end){ // Remember! If you port this into `.get(cb` make sure you allow stun:0 skip option for `.put(`.
1179
+ tmp[id] = function(){one(msg,eve)};
1180
+ return;
1181
+ }
1182
+ //tmp = one.wait || (one.wait = {}); console.log(tmp[at.id] === ''); if(tmp[at.id] !== ''){ tmp[at.id] = tmp[at.id] || setTimeout(function(){tmp[at.id]='';one(msg,eve)},1); return } delete tmp[at.id];
1183
+ // call:
1184
+ if(opt.as){
1185
+ opt.ok.call(opt.as, msg, eve || one);
1186
+ } else {
1187
+ opt.ok.call(at.$, data, msg.get || at.get, msg, eve || one);
1188
+ }
1189
+ };
1190
+ one.at = cat;
1191
+ (cat.act||(cat.act={}))[id = String.random(7)] = one;
1192
+ one.off = function(){ one.stun = 1; if(!cat.act){ return } delete cat.act[id] }
1193
+ cat.on('out', {get: {}});*/
1194
+ return gun;
1195
+ };
1196
+ // Rules:
1197
+ // 1. If cached, should be fast, but not read while write.
1198
+ // 2. Should not retrigger other listeners, should get triggered even if nothing found.
1199
+ // 3. If the same callback passed to many different once chains, each should resolve - an unsubscribe from the same callback should not effect the state of the other resolving chains, if you do want to cancel them all early you should mutate the callback itself with a flag & check for it at top of callback
1200
+ Gun.chain.once = function(cb, opt){ opt = opt || {}; // avoid rewriting
1201
+ if(!cb){ return none(this) }
1202
+ var gun = this, cat = gun._, root = cat.root; cat.put; var id = String.random(7), tmp;
1203
+ gun.get(function(data,key,msg,eve){
1204
+ var $ = this, at = $._, one = (at.one||(at.one={}));
1205
+ if(eve.stun){ return } if('' === one[id]){ return }
1206
+ if(true === (tmp = Gun.valid(data))){ once(); return }
1207
+ if('string' == typeof tmp){ return } // TODO: BUG? Will this always load?
1208
+ clearTimeout((cat.one||'')[id]); // clear "not found" since they only get set on cat.
1209
+ clearTimeout(one[id]); one[id] = setTimeout(once, opt.wait||99); // TODO: Bug? This doesn't handle plural chains.
1210
+ function once(f){
1211
+ if(!at.has && !at.soul){ at = {put: data, get: key}; } // handles non-core messages.
1212
+ if(u === (tmp = at.put)){ tmp = ((msg.$$||'')._||'').put; }
1213
+ if('string' == typeof Gun.valid(tmp)){
1214
+ tmp = root.$.get(tmp)._.put;
1215
+ if(tmp === u && !f){
1216
+ one[id] = setTimeout(function(){ once(1); }, opt.wait||99); // TODO: Quick fix. Maybe use ack count for more predictable control?
1217
+ return
1218
+ }
1219
+ }
1220
+ //console.log("AND VANISHED", data);
1221
+ if(eve.stun){ return } if('' === one[id]){ return } one[id] = '';
1222
+ if(cat.soul || cat.has){ eve.off(); } // TODO: Plural chains? // else { ?.off() } // better than one check?
1223
+ cb.call($, tmp, at.get);
1224
+ clearTimeout(one[id]); // clear "not found" since they only get set on cat. // TODO: This was hackily added, is it necessary or important? Probably not, in future try removing this. Was added just as a safety for the `&& !f` check.
1225
+ } }, {on: 1});
1226
+ return gun;
1227
+ };
1228
+ function none(gun,opt,chain){
1229
+ Gun.log.once("valonce", "Chainable val is experimental, its behavior and API may change moving forward. Please play with it and report bugs and ideas on how to improve it.");
1230
+ (chain = gun.chain())._.nix = gun.once(function(data, key){ chain._.on('in', this._); });
1231
+ chain._.lex = gun._.lex; // TODO: Better approach in future? This is quick for now.
1232
+ return chain;
1233
+ }
1234
+
1235
+ Gun.chain.off = function(){
1236
+ // make off more aggressive. Warning, it might backfire!
1237
+ var gun = this, at = gun._, tmp;
1238
+ var cat = at.back;
1239
+ if(!cat){ return }
1240
+ at.ack = 0; // so can resubscribe.
1241
+ if(tmp = cat.next){
1242
+ if(tmp[at.get]){
1243
+ delete tmp[at.get];
1244
+ }
1245
+ }
1246
+ // TODO: delete cat.one[map.id]?
1247
+ if (tmp = cat.any) {
1248
+ delete cat.any;
1249
+ cat.any = {};
1250
+ }
1251
+ if(tmp = cat.ask){
1252
+ delete tmp[at.get];
1253
+ }
1254
+ if(tmp = cat.put){
1255
+ delete tmp[at.get];
1256
+ }
1257
+ if(tmp = at.soul){
1258
+ delete cat.root.graph[tmp];
1259
+ }
1260
+ if(tmp = at.map){
1261
+ Object.keys(tmp).forEach(function(i,at){ at = tmp[i]; //obj_map(tmp, function(at){
1262
+ if(at.link){
1263
+ cat.root.$.get(at.link).off();
1264
+ }
1265
+ });
1266
+ }
1267
+ if(tmp = at.next){
1268
+ Object.keys(tmp).forEach(function(i,neat){ neat = tmp[i]; //obj_map(tmp, function(neat){
1269
+ neat.$.off();
1270
+ });
1271
+ }
1272
+ at.on('off', {});
1273
+ return gun;
1274
+ };
1275
+ var u;
1276
+ })(USE, './on');
1277
+ USE(function(module){
1278
+ var Gun = USE('./index'), next = Gun.chain.get.next;
1279
+ Gun.chain.get.next = function(gun, lex){ var tmp;
1280
+ if(!Object.plain(lex)){ return (next||noop)(gun, lex) }
1281
+ if(tmp = ((tmp = lex['#'])||'')['='] || tmp){ return gun.get(tmp) }
1282
+ (tmp = gun.chain()._).lex = lex; // LEX!
1283
+ gun.on('in', function(eve){
1284
+ if(String.match(eve.get|| (eve.put||'')['.'], lex['.'] || lex['#'] || lex)){
1285
+ tmp.on('in', eve);
1286
+ }
1287
+ this.to.next(eve);
1288
+ });
1289
+ return tmp.$;
1290
+ };
1291
+ Gun.chain.map = function(cb, opt, t){
1292
+ var gun = this, cat = gun._, lex, chain;
1293
+ if(Object.plain(cb)){ lex = cb['.']? cb : {'.': cb}; cb = u; }
1294
+ if(!cb){
1295
+ if(chain = cat.each){ return chain }
1296
+ (cat.each = chain = gun.chain())._.lex = lex || chain._.lex || cat.lex;
1297
+ chain._.nix = gun.back('nix');
1298
+ gun.on('in', map, chain._);
1299
+ return chain;
1300
+ }
1301
+ Gun.log.once("mapfn", "Map functions are experimental, their behavior and API may change moving forward. Please play with it and report bugs and ideas on how to improve it.");
1302
+ chain = gun.chain();
1303
+ gun.map().on(function(data, key, msg, eve){
1304
+ var next = (cb||noop).call(this, data, key, msg, eve);
1305
+ if(u === next){ return }
1306
+ if(data === next){ return chain._.on('in', msg) }
1307
+ if(Gun.is(next)){ return chain._.on('in', next._) }
1308
+ var tmp = {}; Object.keys(msg.put).forEach(function(k){ tmp[k] = msg.put[k]; }, tmp); tmp['='] = next;
1309
+ chain._.on('in', {get: key, put: tmp});
1310
+ });
1311
+ return chain;
1312
+ };
1313
+ function map(msg){ this.to.next(msg);
1314
+ var cat = this.as, gun = msg.$, at = gun._, put = msg.put, tmp;
1315
+ if(!at.soul && !msg.$$){ return } // this line took hundreds of tries to figure out. It only works if core checks to filter out above chains during link tho. This says "only bother to map on a node" for this layer of the chain. If something is not a node, map should not work.
1316
+ if((tmp = cat.lex) && !String.match(msg.get|| (put||'')['.'], tmp['.'] || tmp['#'] || tmp)){ return }
1317
+ Gun.on.link(msg, cat);
1318
+ }
1319
+ var noop = function(){}, u;
1320
+ })(USE, './map');
1321
+ USE(function(module){
1322
+ var Gun = USE('./index');
1323
+ Gun.chain.set = function(item, cb, opt){
1324
+ var gun = this, root = gun.back(-1), soul, tmp;
1325
+ cb = cb || function(){};
1326
+ opt = opt || {}; opt.item = opt.item || item;
1327
+ if(soul = ((item||'')._||'')['#']){ (item = {})['#'] = soul; } // check if node, make link.
1328
+ if('string' == typeof (tmp = Gun.valid(item))){ return gun.get(soul = tmp).put(item, cb, opt) } // check if link
1329
+ if(!Gun.is(item)){
1330
+ if(Object.plain(item)){
1331
+ item = root.get(soul = gun.back('opt.uuid')()).put(item);
1332
+ }
1333
+ return gun.get(soul || root.back('opt.uuid')(7)).put(item, cb, opt);
1334
+ }
1335
+ gun.put(function(go){
1336
+ item.get(function(soul, o, msg){ // TODO: BUG! We no longer have this option? & go error not handled?
1337
+ if(!soul){ return cb.call(gun, {err: Gun.log('Only a node can be linked! Not "' + msg.put + '"!')}) }
1338
+ (tmp = {})[soul] = {'#': soul}; go(tmp);
1339
+ },true);
1340
+ });
1341
+ return item;
1342
+ };
1343
+ })(USE, './set');
1344
+ USE(function(module){
1345
+ USE('./shim');
1346
+
1347
+ var noop = function(){};
1348
+ var parse = JSON.parseAsync || function(t,cb,r){ var u, d = +new Date; try{ cb(u, JSON.parse(t,r), json.sucks(+new Date - d)); }catch(e){ cb(e); } };
1349
+ var json = JSON.stringifyAsync || function(v,cb,r,s){ var u, d = +new Date; try{ cb(u, JSON.stringify(v,r,s), json.sucks(+new Date - d)); }catch(e){ cb(e); } };
1350
+ json.sucks = function(d){ if(d > 99){ console.log("Warning: JSON blocking CPU detected. Add `gun/lib/yson.js` to fix."); json.sucks = noop; } };
1351
+
1352
+ function Mesh(root){
1353
+ var mesh = function(){};
1354
+ var opt = root.opt || {};
1355
+ opt.log = opt.log || console.log;
1356
+ opt.gap = opt.gap || opt.wait || 0;
1357
+ opt.max = opt.max || (opt.memory? (opt.memory * 999 * 999) : 300000000) * 0.3;
1358
+ opt.pack = opt.pack || (opt.max * 0.01 * 0.01);
1359
+ opt.puff = opt.puff || 9; // IDEA: do a start/end benchmark, divide ops/result.
1360
+ var puff = setTimeout.turn || setTimeout;
1361
+
1362
+ var dup = root.dup, dup_check = dup.check, dup_track = dup.track;
1363
+
1364
+ var hear = mesh.hear = function(raw, peer){
1365
+ if(!raw){ return }
1366
+ if(opt.max <= raw.length){ return mesh.say({dam: '!', err: "Message too big!"}, peer) }
1367
+ if(mesh === this){
1368
+ /*if('string' == typeof raw){ try{
1369
+ var stat = console.STAT || {};
1370
+ //console.log('HEAR:', peer.id, (raw||'').slice(0,250), ((raw||'').length / 1024 / 1024).toFixed(4));
1371
+
1372
+ //console.log(setTimeout.turn.s.length, 'stacks', parseFloat((-(LT - (LT = +new Date))/1000).toFixed(3)), 'sec', parseFloat(((LT-ST)/1000 / 60).toFixed(1)), 'up', stat.peers||0, 'peers', stat.has||0, 'has', stat.memhused||0, stat.memused||0, stat.memax||0, 'heap mem max');
1373
+ }catch(e){ console.log('DBG err', e) }}*/
1374
+ hear.d += raw.length||0 ; ++hear.c; } // STATS!
1375
+ var S = peer.SH = +new Date;
1376
+ var tmp = raw[0], msg;
1377
+ //raw && raw.slice && console.log("hear:", ((peer.wire||'').headers||'').origin, raw.length, raw.slice && raw.slice(0,50)); //tc-iamunique-tc-package-ds1
1378
+ if('[' === tmp){
1379
+ parse(raw, function(err, msg){
1380
+ if(err || !msg){ return mesh.say({dam: '!', err: "DAM JSON parse error."}, peer) }
1381
+ console.STAT && console.STAT(+new Date, msg.length, '# on hear batch');
1382
+ var P = opt.puff;
1383
+ (function go(){
1384
+ var S = +new Date;
1385
+ var i = 0, m; while(i < P && (m = msg[i++])){ mesh.hear(m, peer); }
1386
+ msg = msg.slice(i); // slicing after is faster than shifting during.
1387
+ console.STAT && console.STAT(S, +new Date - S, 'hear loop');
1388
+ flush(peer); // force send all synchronously batched acks.
1389
+ if(!msg.length){ return }
1390
+ puff(go, 0);
1391
+ }());
1392
+ });
1393
+ raw = ''; //
1394
+ return;
1395
+ }
1396
+ if('{' === tmp || ((raw['#'] || Object.plain(raw)) && (msg = raw))){
1397
+ if(msg){ return hear.one(msg, peer, S) }
1398
+ parse(raw, function(err, msg){
1399
+ if(err || !msg){ return mesh.say({dam: '!', err: "DAM JSON parse error."}, peer) }
1400
+ hear.one(msg, peer, S);
1401
+ });
1402
+ return;
1403
+ }
1404
+ };
1405
+ hear.one = function(msg, peer, S){ // S here is temporary! Undo.
1406
+ var id, hash, tmp, ash, DBG;
1407
+ if(msg.DBG){ msg.DBG = DBG = {DBG: msg.DBG}; }
1408
+ DBG && (DBG.h = S);
1409
+ DBG && (DBG.hp = +new Date);
1410
+ if(!(id = msg['#'])){ id = msg['#'] = String.random(9); }
1411
+ if(tmp = dup_check(id)){ return }
1412
+ // DAM logic:
1413
+ if(!(hash = msg['##']) && false && u !== msg.put); // disable hashing for now // TODO: impose warning/penalty instead (?)
1414
+ if(hash && (tmp = msg['@'] || (msg.get && id)) && dup.check(ash = tmp+hash)){ return } // Imagine A <-> B <=> (C & D), C & D reply with same ACK but have different IDs, B can use hash to dedup. Or if a GET has a hash already, we shouldn't ACK if same.
1415
+ (msg._ = function(){}).via = mesh.leap = peer;
1416
+ if((tmp = msg['><']) && 'string' == typeof tmp){ tmp.slice(0,99).split(',').forEach(function(k){ this[k] = 1; }, (msg._).yo = {}); } // Peers already sent to, do not resend.
1417
+ // DAM ^
1418
+ if(tmp = msg.dam){
1419
+ if(tmp = mesh.hear[tmp]){
1420
+ tmp(msg, peer, root);
1421
+ }
1422
+ dup_track(id);
1423
+ return;
1424
+ }
1425
+ if(tmp = msg.ok){ msg._.near = tmp['/']; }
1426
+ var S = +new Date;
1427
+ DBG && (DBG.is = S); peer.SI = id;
1428
+ dup_track.ed = function(d){
1429
+ if(id !== d){ return }
1430
+ dup_track.ed = 0;
1431
+ if(!(d = dup.s[id])){ return }
1432
+ d.via = peer;
1433
+ if(msg.get){ d.it = msg; }
1434
+ };
1435
+ root.on('in', mesh.last = msg);
1436
+ DBG && (DBG.hd = +new Date);
1437
+ console.STAT && console.STAT(S, +new Date - S, msg.get? 'msg get' : msg.put? 'msg put' : 'msg');
1438
+ dup_track(id); // in case 'in' does not call track.
1439
+ if(ash){ dup_track(ash); } //dup.track(tmp+hash, true).it = it(msg);
1440
+ mesh.leap = mesh.last = null; // warning! mesh.leap could be buggy.
1441
+ };
1442
+ hear.c = hear.d = 0;
1443
+ (function(){
1444
+ var SMIA = 0;
1445
+ var loop;
1446
+ mesh.hash = function(msg, peer){ var h, s, t;
1447
+ var S = +new Date;
1448
+ json(msg.put, function hash(err, text){
1449
+ var ss = (s || (s = t = text||'')).slice(0, 32768); // 1024 * 32
1450
+ h = String.hash(ss, h); s = s.slice(32768);
1451
+ if(s){ puff(hash, 0); return }
1452
+ console.STAT && console.STAT(S, +new Date - S, 'say json+hash');
1453
+ msg._.$put = t;
1454
+ msg['##'] = h;
1455
+ mesh.say(msg, peer);
1456
+ delete msg._.$put;
1457
+ }, sort);
1458
+ };
1459
+ function sort(k, v){ var tmp;
1460
+ if(!(v instanceof Object)){ return v }
1461
+ Object.keys(v).sort().forEach(sorta, {to: tmp = {}, on: v});
1462
+ return tmp;
1463
+ } function sorta(k){ this.to[k] = this.on[k]; }
1464
+
1465
+ mesh.say = function(msg, peer){ var tmp;
1466
+ if((tmp = this) && (tmp = tmp.to) && tmp.next){ tmp.next(msg); } // compatible with middleware adapters.
1467
+ if(!msg){ return false }
1468
+ var id, hash, raw, ack = msg['@'];
1469
+ //if(opt.super && (!ack || !msg.put)){ return } // TODO: MANHATTAN STUB //OBVIOUSLY BUG! But squelch relay. // :( get only is 100%+ CPU usage :(
1470
+ var meta = msg._||(msg._=function(){});
1471
+ var DBG = msg.DBG, S = +new Date; meta.y = meta.y || S; if(!peer){ DBG && (DBG.y = S); }
1472
+ if(!(id = msg['#'])){ id = msg['#'] = String.random(9); }
1473
+ !loop && dup_track(id);//.it = it(msg); // track for 9 seconds, default. Earth<->Mars would need more! // always track, maybe move this to the 'after' logic if we split function.
1474
+ //if(msg.put && (msg.err || (dup.s[id]||'').err)){ return false } // TODO: in theory we should not be able to stun a message, but for now going to check if it can help network performance preventing invalid data to relay.
1475
+ if(!(hash = msg['##']) && u !== msg.put && !meta.via && ack){ mesh.hash(msg, peer); return } // TODO: Should broadcasts be hashed?
1476
+ if(!peer && ack){ peer = ((tmp = dup.s[ack]) && (tmp.via || ((tmp = tmp.it) && (tmp = tmp._) && tmp.via))) || ((tmp = mesh.last) && ack === tmp['#'] && mesh.leap); } // warning! mesh.leap could be buggy! mesh last check reduces this. // TODO: CLEAN UP THIS LINE NOW? `.it` should be reliable.
1477
+ if(!peer && ack){ // still no peer, then ack daisy chain 'tunnel' got lost.
1478
+ if(dup.s[ack]){ return } // in dups but no peer hints that this was ack to ourself, ignore.
1479
+ console.STAT && console.STAT(+new Date, ++SMIA, 'total no peer to ack to'); // TODO: Delete this now. Dropping lost ACKs is protocol fine now.
1480
+ return false;
1481
+ } // TODO: Temporary? If ack via trace has been lost, acks will go to all peers, which trashes browser bandwidth. Not relaying the ack will force sender to ask for ack again. Note, this is technically wrong for mesh behavior.
1482
+ if(ack && !msg.put && !hash && ((dup.s[ack]||'').it||'')['##']){ return false } // If we're saying 'not found' but a relay had data, do not bother sending our not found. // Is this correct, return false? // NOTE: ADD PANIC TEST FOR THIS!
1483
+ if(!peer && mesh.way){ return mesh.way(msg) }
1484
+ DBG && (DBG.yh = +new Date);
1485
+ if(!(raw = meta.raw)){ mesh.raw(msg, peer); return }
1486
+ DBG && (DBG.yr = +new Date);
1487
+ if(!peer || !peer.id){
1488
+ if(!Object.plain(peer || opt.peers)){ return false }
1489
+ var S = +new Date;
1490
+ opt.puff; var ps = opt.peers, pl = Object.keys(peer || opt.peers || {}); // TODO: .keys( is slow
1491
+ console.STAT && console.STAT(S, +new Date - S, 'peer keys');
1492
+ (function go(){
1493
+ var S = +new Date;
1494
+ //Type.obj.map(peer || opt.peers, each); // in case peer is a peer list.
1495
+ loop = 1; var wr = meta.raw; meta.raw = raw; // quick perf hack
1496
+ var i = 0, p; while(i < 9 && (p = (pl||'')[i++])){
1497
+ if(!(p = ps[p] || (peer||'')[p])){ continue }
1498
+ mesh.say(msg, p);
1499
+ }
1500
+ meta.raw = wr; loop = 0;
1501
+ pl = pl.slice(i); // slicing after is faster than shifting during.
1502
+ console.STAT && console.STAT(S, +new Date - S, 'say loop');
1503
+ if(!pl.length){ return }
1504
+ puff(go, 0);
1505
+ ack && dup_track(ack); // keep for later
1506
+ }());
1507
+ return;
1508
+ }
1509
+ // TODO: PERF: consider splitting function here, so say loops do less work.
1510
+ if(!peer.wire && mesh.wire){ mesh.wire(peer); }
1511
+ if(id === peer.last){ return } peer.last = id; // was it just sent?
1512
+ if(peer === meta.via){ return false } // don't send back to self.
1513
+ if((tmp = meta.yo) && (tmp[peer.url] || tmp[peer.pid] || tmp[peer.id]) /*&& !o*/){ return false }
1514
+ console.STAT && console.STAT(S, ((DBG||meta).yp = +new Date) - (meta.y || S), 'say prep');
1515
+ !loop && ack && dup_track(ack); // streaming long responses needs to keep alive the ack.
1516
+ if(peer.batch){
1517
+ peer.tail = (tmp = peer.tail || 0) + raw.length;
1518
+ if(peer.tail <= opt.pack){
1519
+ peer.batch += (tmp?',':'')+raw;
1520
+ return;
1521
+ }
1522
+ flush(peer);
1523
+ }
1524
+ peer.batch = '['; // Prevents double JSON!
1525
+ var ST = +new Date;
1526
+ setTimeout(function(){
1527
+ console.STAT && console.STAT(ST, +new Date - ST, '0ms TO');
1528
+ flush(peer);
1529
+ }, opt.gap); // TODO: queuing/batching might be bad for low-latency video game performance! Allow opt out?
1530
+ send(raw, peer);
1531
+ console.STAT && (ack === peer.SI) && console.STAT(S, +new Date - peer.SH, 'say ack');
1532
+ };
1533
+ mesh.say.c = mesh.say.d = 0;
1534
+ // TODO: this caused a out-of-memory crash!
1535
+ mesh.raw = function(msg, peer){ // TODO: Clean this up / delete it / move logic out!
1536
+ if(!msg){ return '' }
1537
+ var meta = (msg._) || {}, put, tmp;
1538
+ if(tmp = meta.raw){ return tmp }
1539
+ if('string' == typeof msg){ return msg }
1540
+ var hash = msg['##'], ack = msg['@'];
1541
+ if(hash && ack){
1542
+ if(!meta.via && dup_check(ack+hash)){ return false } // for our own out messages, memory & storage may ack the same thing, so dedup that. Tho if via another peer, we already tracked it upon hearing, so this will always trigger false positives, so don't do that!
1543
+ if(tmp = (dup.s[ack]||'').it){
1544
+ if(hash === tmp['##']){ return false } // if ask has a matching hash, acking is optional.
1545
+ if(!tmp['##']){ tmp['##'] = hash; } // if none, add our hash to ask so anyone we relay to can dedup. // NOTE: May only check against 1st ack chunk, 2nd+ won't know and still stream back to relaying peers which may then dedup. Any way to fix this wasted bandwidth? I guess force rate limiting breaking change, that asking peer has to ask for next lexical chunk.
1546
+ }
1547
+ }
1548
+ if(!msg.dam && !msg['@']){
1549
+ var i = 0, to = []; tmp = opt.peers;
1550
+ for(var k in tmp){ var p = tmp[k]; // TODO: Make it up peers instead!
1551
+ to.push(p.url || p.pid || p.id);
1552
+ if(++i > 6){ break }
1553
+ }
1554
+ if(i > 1){ msg['><'] = to.join(); } // TODO: BUG! This gets set regardless of peers sent to! Detect?
1555
+ }
1556
+ if(msg.put && (tmp = msg.ok)){ msg.ok = {'@':(tmp['@']||1)-1, '/': (tmp['/']==msg._.near)? mesh.near : tmp['/']}; }
1557
+ if(put = meta.$put){
1558
+ tmp = {}; Object.keys(msg).forEach(function(k){ tmp[k] = msg[k]; });
1559
+ tmp.put = ':])([:';
1560
+ json(tmp, function(err, raw){
1561
+ if(err){ return } // TODO: Handle!!
1562
+ var S = +new Date;
1563
+ tmp = raw.indexOf('"put":":])([:"');
1564
+ res(u, raw = raw.slice(0, tmp+6) + put + raw.slice(tmp + 14));
1565
+ console.STAT && console.STAT(S, +new Date - S, 'say slice');
1566
+ });
1567
+ return;
1568
+ }
1569
+ json(msg, res);
1570
+ function res(err, raw){
1571
+ if(err){ return } // TODO: Handle!!
1572
+ meta.raw = raw; //if(meta && (raw||'').length < (999 * 99)){ meta.raw = raw } // HNPERF: If string too big, don't keep in memory.
1573
+ mesh.say(msg, peer);
1574
+ }
1575
+ };
1576
+ }());
1577
+
1578
+ function flush(peer){
1579
+ var tmp = peer.batch, t = 'string' == typeof tmp;
1580
+ if(t){ tmp += ']'; }// TODO: Prevent double JSON!
1581
+ peer.batch = peer.tail = null;
1582
+ if(!tmp){ return }
1583
+ if(t? 3 > tmp.length : !tmp.length){ return } // TODO: ^
1584
+ if(!t){try{tmp = (1 === tmp.length? tmp[0] : JSON.stringify(tmp));
1585
+ }catch(e){return opt.log('DAM JSON stringify error', e)}}
1586
+ if(!tmp){ return }
1587
+ send(tmp, peer);
1588
+ }
1589
+ // for now - find better place later.
1590
+ function send(raw, peer){ try{
1591
+ var wire = peer.wire;
1592
+ if(peer.say){
1593
+ peer.say(raw);
1594
+ } else
1595
+ if(wire.send){
1596
+ wire.send(raw);
1597
+ }
1598
+ mesh.say.d += raw.length||0; ++mesh.say.c; // STATS!
1599
+ }catch(e){
1600
+ (peer.queue = peer.queue || []).push(raw);
1601
+ }}
1602
+
1603
+ mesh.near = 0;
1604
+ mesh.hi = function(peer){
1605
+ var wire = peer.wire, tmp;
1606
+ if(!wire){ mesh.wire((peer.length && {url: peer, id: peer}) || peer); return }
1607
+ if(peer.id){
1608
+ opt.peers[peer.url || peer.id] = peer;
1609
+ } else {
1610
+ tmp = peer.id = peer.id || peer.url || String.random(9);
1611
+ mesh.say({dam: '?', pid: root.opt.pid}, opt.peers[tmp] = peer);
1612
+ delete dup.s[peer.last]; // IMPORTANT: see https://gun.eco/docs/DAM#self
1613
+ }
1614
+ if(!peer.met){
1615
+ mesh.near++;
1616
+ peer.met = +(new Date);
1617
+ root.on('hi', peer);
1618
+ }
1619
+ // @rogowski I need this here by default for now to fix go1dfish's bug
1620
+ tmp = peer.queue; peer.queue = [];
1621
+ setTimeout.each(tmp||[],function(msg){
1622
+ send(msg, peer);
1623
+ },0,9);
1624
+ //Type.obj.native && Type.obj.native(); // dirty place to check if other JS polluted.
1625
+ };
1626
+ mesh.bye = function(peer){
1627
+ peer.met && --mesh.near;
1628
+ delete peer.met;
1629
+ root.on('bye', peer);
1630
+ var tmp = +(new Date); tmp = (tmp - (peer.met||tmp));
1631
+ mesh.bye.time = ((mesh.bye.time || tmp) + tmp) / 2;
1632
+ };
1633
+ mesh.hear['!'] = function(msg, peer){ opt.log('Error:', msg.err); };
1634
+ mesh.hear['?'] = function(msg, peer){
1635
+ if(msg.pid){
1636
+ if(!peer.pid){ peer.pid = msg.pid; }
1637
+ if(msg['@']){ return }
1638
+ }
1639
+ mesh.say({dam: '?', pid: opt.pid, '@': msg['#']}, peer);
1640
+ delete dup.s[peer.last]; // IMPORTANT: see https://gun.eco/docs/DAM#self
1641
+ };
1642
+ mesh.hear['mob'] = function(msg, peer){ // NOTE: AXE will overload this with better logic.
1643
+ if(!msg.peers){ return }
1644
+ var peers = Object.keys(msg.peers), one = peers[(Math.random()*peers.length) >> 0];
1645
+ if(!one){ return }
1646
+ mesh.bye(peer);
1647
+ mesh.hi(one);
1648
+ };
1649
+
1650
+ root.on('create', function(root){
1651
+ root.opt.pid = root.opt.pid || String.random(9);
1652
+ this.to.next(root);
1653
+ root.on('out', mesh.say);
1654
+ });
1655
+
1656
+ root.on('bye', function(peer, tmp){
1657
+ peer = opt.peers[peer.id || peer] || peer;
1658
+ this.to.next(peer);
1659
+ peer.bye? peer.bye() : (tmp = peer.wire) && tmp.close && tmp.close();
1660
+ delete opt.peers[peer.id];
1661
+ peer.wire = null;
1662
+ });
1663
+ root.on('bye', function(peer, tmp){ this.to.next(peer);
1664
+ if(tmp = console.STAT){ tmp.peers = mesh.near; }
1665
+ if(!(tmp = peer.url)){ return } setTimeout(function(){ },opt.lack || 9000);
1666
+ });
1667
+ root.on('hi', function(peer, tmp){ this.to.next(peer);
1668
+ if(tmp = console.STAT){ tmp.peers = mesh.near; }
1669
+ if(opt.super){ return } // temporary (?) until we have better fix/solution?
1670
+ var souls = Object.keys(root.next||''); // TODO: .keys( is slow
1671
+ if(souls.length > 9999 && !console.SUBS){ console.log(console.SUBS = "Warning: You have more than 10K live GETs, which might use more bandwidth than your screen can show - consider `.off()`."); }
1672
+ setTimeout.each(souls, function(soul){ var node = root.next[soul];
1673
+ if(opt.super || (node.ask||'')['']){ mesh.say({get: {'#': soul}}, peer); return }
1674
+ setTimeout.each(Object.keys(node.ask||''), function(key){ if(!key){ return }
1675
+ // is the lack of ## a !onion hint?
1676
+ mesh.say({'##': String.hash((root.graph[soul]||'')[key]), get: {'#': soul, '.': key}}, peer);
1677
+ // TODO: Switch this so Book could route?
1678
+ });
1679
+ });
1680
+ });
1681
+
1682
+ return mesh;
1683
+ }
1684
+ var u;
1685
+
1686
+ try{ module.exports = Mesh; }catch(e){}
1687
+
1688
+ })(USE, './mesh');
1689
+ USE(function(module){
1690
+ var Gun = USE('./index');
1691
+ Gun.Mesh = USE('./mesh');
1692
+
1693
+ // TODO: resync upon reconnect online/offline
1694
+ //window.ononline = window.onoffline = function(){ console.log('online?', navigator.onLine) }
1695
+
1696
+ Gun.on('opt', function(root){
1697
+ this.to.next(root);
1698
+ if(root.once){ return }
1699
+ var opt = root.opt;
1700
+ if(false === opt.WebSocket){ return }
1701
+
1702
+ var env = Gun.window || {};
1703
+ var websocket = opt.WebSocket || env.WebSocket || env.webkitWebSocket || env.mozWebSocket;
1704
+ if(!websocket){ return }
1705
+ opt.WebSocket = websocket;
1706
+
1707
+ var mesh = opt.mesh = opt.mesh || Gun.Mesh(root);
1708
+
1709
+ mesh.wire || opt.wire;
1710
+ mesh.wire = opt.wire = open;
1711
+ function open(peer){ try{
1712
+ if(!peer || !peer.url){ return wire && wire(peer) }
1713
+ var url = peer.url.replace(/^http/, 'ws');
1714
+ var wire = peer.wire = new opt.WebSocket(url);
1715
+ wire.onclose = function(){
1716
+ reconnect(peer);
1717
+ opt.mesh.bye(peer);
1718
+ };
1719
+ wire.onerror = function(err){
1720
+ reconnect(peer);
1721
+ };
1722
+ wire.onopen = function(){
1723
+ opt.mesh.hi(peer);
1724
+ };
1725
+ wire.onmessage = function(msg){
1726
+ if(!msg){ return }
1727
+ opt.mesh.hear(msg.data || msg, peer);
1728
+ };
1729
+ return wire;
1730
+ }catch(e){ opt.mesh.bye(peer); }}
1731
+
1732
+ setTimeout(function(){ !opt.super && root.on('out', {dam:'hi'}); },1); // it can take a while to open a socket, so maybe no longer lazy load for perf reasons?
1733
+
1734
+ var wait = 2 * 999;
1735
+ function reconnect(peer){
1736
+ clearTimeout(peer.defer);
1737
+ if(!opt.peers[peer.url]){ return }
1738
+ if(doc && peer.retry <= 0){ return }
1739
+ peer.retry = (peer.retry || opt.retry+1 || 60) - ((-peer.tried + (peer.tried = +new Date) < wait*4)?1:0);
1740
+ peer.defer = setTimeout(function to(){
1741
+ if(doc && doc.hidden){ return setTimeout(to,wait) }
1742
+ open(peer);
1743
+ }, wait);
1744
+ }
1745
+ var doc = (''+u !== typeof document) && document;
1746
+ });
1747
+ var u;
1748
+ })(USE, './websocket');
1749
+ USE(function(module){
1750
+ if(typeof Gun === 'undefined'){ return }
1751
+
1752
+ var noop = function(){}, store;
1753
+ try{store = (Gun.window||noop).localStorage;}catch(e){}
1754
+ if(!store){
1755
+ Gun.log("Warning: No localStorage exists to persist data to!");
1756
+ store = {setItem: function(k,v){this[k]=v;}, removeItem: function(k){delete this[k];}, getItem: function(k){return this[k]}};
1757
+ }
1758
+ var json = JSON.stringifyAsync || function(v,cb,r,s){ var u; try{ cb(u, JSON.stringify(v,r,s)); }catch(e){ cb(e); } };
1759
+
1760
+ Gun.on('create', function lg(root){
1761
+ this.to.next(root);
1762
+ var opt = root.opt; root.graph; var acks = [], disk, to, size, stop;
1763
+ if(false === opt.localStorage){ return }
1764
+ opt.prefix = opt.file || 'gun/';
1765
+ try{ disk = lg[opt.prefix] = lg[opt.prefix] || JSON.parse(size = store.getItem(opt.prefix)) || {}; // TODO: Perf! This will block, should we care, since limited to 5MB anyways?
1766
+ }catch(e){ disk = lg[opt.prefix] = {}; }
1767
+ size = (size||'').length;
1768
+
1769
+ root.on('get', function(msg){
1770
+ this.to.next(msg);
1771
+ var lex = msg.get, soul, data, tmp, u;
1772
+ if(!lex || !(soul = lex['#'])){ return }
1773
+ data = disk[soul] || u;
1774
+ if(data && (tmp = lex['.']) && !Object.plain(tmp)){ // pluck!
1775
+ data = Gun.state.ify({}, tmp, Gun.state.is(data, tmp), data[tmp], soul);
1776
+ }
1777
+ //if(data){ (tmp = {})[soul] = data } // back into a graph.
1778
+ //setTimeout(function(){
1779
+ Gun.on.get.ack(msg, data); //root.on('in', {'@': msg['#'], put: tmp, lS:1});// || root.$});
1780
+ //}, Math.random() * 10); // FOR TESTING PURPOSES!
1781
+ });
1782
+
1783
+ root.on('put', function(msg){
1784
+ this.to.next(msg); // remember to call next middleware adapter
1785
+ var put = msg.put, soul = put['#'], key = put['.'], id = msg['#'], ok = msg.ok||''; // pull data off wire envelope
1786
+ disk[soul] = Gun.state.ify(disk[soul], key, put['>'], put[':'], soul); // merge into disk object
1787
+ if(stop && size > (4999880)){ root.on('in', {'@': id, err: "localStorage max!"}); return; }
1788
+ //if(!msg['@']){ acks.push(id) } // then ack any non-ack write. // TODO: use batch id.
1789
+ if(!msg['@'] && (!msg._.via || Math.random() < (ok['@'] / ok['/']))){ acks.push(id); } // then ack any non-ack write. // TODO: use batch id.
1790
+ if(to){ return }
1791
+ to = setTimeout(flush, 9+(size / 333)); // 0.1MB = 0.3s, 5MB = 15s
1792
+ });
1793
+ function flush(){
1794
+ if(!acks.length && ((setTimeout.turn||'').s||'').length){ setTimeout(flush,99); return; } // defer if "busy" && no saves.
1795
+ var ack = acks; clearTimeout(to); to = false; acks = [];
1796
+ json(disk, function(err, tmp){
1797
+ try{!err && store.setItem(opt.prefix, tmp);
1798
+ }catch(e){ err = stop = e || "localStorage failure"; }
1799
+ if(err){
1800
+ Gun.log(err + " Consider using GUN's IndexedDB plugin for RAD for more storage space, https://gun.eco/docs/RAD#install");
1801
+ root.on('localStorage:error', {err: err, get: opt.prefix, put: disk});
1802
+ }
1803
+ size = tmp.length;
1804
+
1805
+ //if(!err && !Object.empty(opt.peers)){ return } // only ack if there are no peers. // Switch this to probabilistic mode
1806
+ setTimeout.each(ack, function(id){
1807
+ root.on('in', {'@': id, err: err, ok: 0}); // localStorage isn't reliable, so make its `ok` code be a low number.
1808
+ },0,99);
1809
+ });
1810
+ }
1811
+
1812
+ });
1813
+ })(USE, './localStorage');
1814
+
1815
+ }());
1816
+ (function(){
1817
+ var u;
1818
+ if(''+u == typeof Gun){ return }
1819
+ var DEP = function(n){ console.warn("Warning! Deprecated internal utility will break in next version:", n); };
1820
+ // Generic javascript utilities.
1821
+ var Type = Gun;
1822
+ //Type.fns = Type.fn = {is: function(fn){ return (!!fn && fn instanceof Function) }}
1823
+ Type.fn = Type.fn || {is: function(fn){ DEP('fn'); return (!!fn && 'function' == typeof fn) }};
1824
+ Type.bi = Type.bi || {is: function(b){ DEP('bi');return (b instanceof Boolean || typeof b == 'boolean') }};
1825
+ Type.num = Type.num || {is: function(n){ DEP('num'); return !list_is(n) && ((n - parseFloat(n) + 1) >= 0 || Infinity === n || -Infinity === n) }};
1826
+ Type.text = Type.text || {is: function(t){ DEP('text'); return (typeof t == 'string') }};
1827
+ Type.text.ify = Type.text.ify || function(t){ DEP('text.ify');
1828
+ if(Type.text.is(t)){ return t }
1829
+ if(typeof JSON !== "undefined"){ return JSON.stringify(t) }
1830
+ return (t && t.toString)? t.toString() : t;
1831
+ };
1832
+ Type.text.random = Type.text.random || function(l, c){ DEP('text.random');
1833
+ var s = '';
1834
+ l = l || 24; // you are not going to make a 0 length random number, so no need to check type
1835
+ c = c || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXZabcdefghijklmnopqrstuvwxyz';
1836
+ while(l > 0){ s += c.charAt(Math.floor(Math.random() * c.length)); l--; }
1837
+ return s;
1838
+ };
1839
+ Type.text.match = Type.text.match || function(t, o){ var tmp, u; DEP('text.match');
1840
+ if('string' !== typeof t){ return false }
1841
+ if('string' == typeof o){ o = {'=': o}; }
1842
+ o = o || {};
1843
+ tmp = (o['='] || o['*'] || o['>'] || o['<']);
1844
+ if(t === tmp){ return true }
1845
+ if(u !== o['=']){ return false }
1846
+ tmp = (o['*'] || o['>'] || o['<']);
1847
+ if(t.slice(0, (tmp||'').length) === tmp){ return true }
1848
+ if(u !== o['*']){ return false }
1849
+ if(u !== o['>'] && u !== o['<']){
1850
+ return (t >= o['>'] && t <= o['<'])? true : false;
1851
+ }
1852
+ if(u !== o['>'] && t >= o['>']){ return true }
1853
+ if(u !== o['<'] && t <= o['<']){ return true }
1854
+ return false;
1855
+ };
1856
+ Type.text.hash = Type.text.hash || function(s, c){ // via SO
1857
+ DEP('text.hash');
1858
+ if(typeof s !== 'string'){ return }
1859
+ c = c || 0;
1860
+ if(!s.length){ return c }
1861
+ for(var i=0,l=s.length,n; i<l; ++i){
1862
+ n = s.charCodeAt(i);
1863
+ c = ((c<<5)-c)+n;
1864
+ c |= 0;
1865
+ }
1866
+ return c;
1867
+ };
1868
+ Type.list = Type.list || {is: function(l){ DEP('list'); return (l instanceof Array) }};
1869
+ Type.list.slit = Type.list.slit || Array.prototype.slice;
1870
+ Type.list.sort = Type.list.sort || function(k){ // creates a new sort function based off some key
1871
+ DEP('list.sort');
1872
+ return function(A,B){
1873
+ if(!A || !B){ return 0 } A = A[k]; B = B[k];
1874
+ if(A < B){ return -1 }else if(A > B){ return 1 }
1875
+ else { return 0 }
1876
+ }
1877
+ };
1878
+ Type.list.map = Type.list.map || function(l, c, _){ DEP('list.map'); return obj_map(l, c, _) };
1879
+ Type.list.index = 1; // change this to 0 if you want non-logical, non-mathematical, non-matrix, non-convenient array notation
1880
+ Type.obj = Type.boj || {is: function(o){ DEP('obj'); return o? (o instanceof Object && o.constructor === Object) || Object.prototype.toString.call(o).match(/^\[object (\w+)\]$/)[1] === 'Object' : false }};
1881
+ Type.obj.put = Type.obj.put || function(o, k, v){ DEP('obj.put'); return (o||{})[k] = v, o };
1882
+ Type.obj.has = Type.obj.has || function(o, k){ DEP('obj.has'); return o && Object.prototype.hasOwnProperty.call(o, k) };
1883
+ Type.obj.del = Type.obj.del || function(o, k){ DEP('obj.del');
1884
+ if(!o){ return }
1885
+ o[k] = null;
1886
+ delete o[k];
1887
+ return o;
1888
+ };
1889
+ Type.obj.as = Type.obj.as || function(o, k, v, u){ DEP('obj.as'); return o[k] = o[k] || (u === v? {} : v) };
1890
+ Type.obj.ify = Type.obj.ify || function(o){ DEP('obj.ify');
1891
+ if(obj_is(o)){ return o }
1892
+ try{o = JSON.parse(o);
1893
+ }catch(e){o={};} return o;
1894
+ }
1895
+ ;(function(){ var u;
1896
+ function map(v,k){
1897
+ if(obj_has(this,k) && u !== this[k]){ return }
1898
+ this[k] = v;
1899
+ }
1900
+ Type.obj.to = Type.obj.to || function(from, to){ DEP('obj.to');
1901
+ to = to || {};
1902
+ obj_map(from, map, to);
1903
+ return to;
1904
+ };
1905
+ }());
1906
+ Type.obj.copy = Type.obj.copy || function(o){ DEP('obj.copy'); // because http://web.archive.org/web/20140328224025/http://jsperf.com/cloning-an-object/2
1907
+ return !o? o : JSON.parse(JSON.stringify(o)); // is shockingly faster than anything else, and our data has to be a subset of JSON anyways!
1908
+ }
1909
+ ;(function(){
1910
+ function empty(v,i){ var n = this.n, u;
1911
+ if(n && (i === n || (obj_is(n) && obj_has(n, i)))){ return }
1912
+ if(u !== i){ return true }
1913
+ }
1914
+ Type.obj.empty = Type.obj.empty || function(o, n){ DEP('obj.empty');
1915
+ if(!o){ return true }
1916
+ return obj_map(o,empty,{n:n})? false : true;
1917
+ };
1918
+ }());
1919
+ (function(){
1920
+ function t(k,v){
1921
+ if(2 === arguments.length){
1922
+ t.r = t.r || {};
1923
+ t.r[k] = v;
1924
+ return;
1925
+ } t.r = t.r || [];
1926
+ t.r.push(k);
1927
+ } var keys = Object.keys, map;
1928
+ Object.keys = Object.keys || function(o){ return map(o, function(v,k,t){t(k);}) };
1929
+ Type.obj.map = map = Type.obj.map || function(l, c, _){ DEP('obj.map');
1930
+ var u, i = 0, x, r, ll, lle, f = 'function' == typeof c;
1931
+ t.r = u;
1932
+ if(keys && obj_is(l)){
1933
+ ll = keys(l); lle = true;
1934
+ }
1935
+ _ = _ || {};
1936
+ if(list_is(l) || ll){
1937
+ x = (ll || l).length;
1938
+ for(;i < x; i++){
1939
+ var ii = (i + Type.list.index);
1940
+ if(f){
1941
+ r = lle? c.call(_, l[ll[i]], ll[i], t) : c.call(_, l[i], ii, t);
1942
+ if(r !== u){ return r }
1943
+ } else {
1944
+ //if(Type.test.is(c,l[i])){ return ii } // should implement deep equality testing!
1945
+ if(c === l[lle? ll[i] : i]){ return ll? ll[i] : ii } // use this for now
1946
+ }
1947
+ }
1948
+ } else {
1949
+ for(i in l){
1950
+ if(f){
1951
+ if(obj_has(l,i)){
1952
+ r = _? c.call(_, l[i], i, t) : c(l[i], i, t);
1953
+ if(r !== u){ return r }
1954
+ }
1955
+ } else {
1956
+ //if(a.test.is(c,l[i])){ return i } // should implement deep equality testing!
1957
+ if(c === l[i]){ return i } // use this for now
1958
+ }
1959
+ }
1960
+ }
1961
+ return f? t.r : Type.list.index? 0 : -1;
1962
+ };
1963
+ }());
1964
+ Type.time = Type.time || {};
1965
+ Type.time.is = Type.time.is || function(t){ DEP('time'); return t? t instanceof Date : (+new Date().getTime()) };
1966
+
1967
+ var fn_is = Type.fn.is;
1968
+ var list_is = Type.list.is;
1969
+ var obj = Type.obj, obj_is = obj.is, obj_has = obj.has, obj_map = obj.map;
1970
+
1971
+ var Val = {};
1972
+ Val.is = function(v){ DEP('val.is'); // Valid values are a subset of JSON: null, binary, number (!Infinity), text, or a soul relation. Arrays need special algorithms to handle concurrency, so they are not supported directly. Use an extension that supports them if needed but research their problems first.
1973
+ if(v === u){ return false }
1974
+ if(v === null){ return true } // "deletes", nulling out keys.
1975
+ if(v === Infinity){ return false } // we want this to be, but JSON does not support it, sad face.
1976
+ if(text_is(v) // by "text" we mean strings.
1977
+ || bi_is(v) // by "binary" we mean boolean.
1978
+ || num_is(v)){ // by "number" we mean integers or decimals.
1979
+ return true; // simple values are valid.
1980
+ }
1981
+ return Val.link.is(v) || false; // is the value a soul relation? Then it is valid and return it. If not, everything else remaining is an invalid data type. Custom extensions can be built on top of these primitives to support other types.
1982
+ };
1983
+ Val.link = Val.rel = {_: '#'};
1984
+ (function(){
1985
+ Val.link.is = function(v){ DEP('val.link.is'); // this defines whether an object is a soul relation or not, they look like this: {'#': 'UUID'}
1986
+ if(v && v[rel_] && !v._ && obj_is(v)){ // must be an object.
1987
+ var o = {};
1988
+ obj_map(v, map, o);
1989
+ if(o.id){ // a valid id was found.
1990
+ return o.id; // yay! Return it.
1991
+ }
1992
+ }
1993
+ return false; // the value was not a valid soul relation.
1994
+ };
1995
+ function map(s, k){ var o = this; // map over the object...
1996
+ if(o.id){ return o.id = false } // if ID is already defined AND we're still looping through the object, it is considered invalid.
1997
+ if(k == rel_ && text_is(s)){ // the key should be '#' and have a text value.
1998
+ o.id = s; // we found the soul!
1999
+ } else {
2000
+ return o.id = false; // if there exists anything else on the object that isn't the soul, then it is considered invalid.
2001
+ }
2002
+ }
2003
+ }());
2004
+ Val.link.ify = function(t){ DEP('val.link.ify'); return obj_put({}, rel_, t) }; // convert a soul into a relation and return it.
2005
+ Type.obj.has._ = '.';
2006
+ var rel_ = Val.link._, u;
2007
+ var bi_is = Type.bi.is;
2008
+ var num_is = Type.num.is;
2009
+ var text_is = Type.text.is;
2010
+ var obj = Type.obj, obj_is = obj.is, obj_put = obj.put, obj_map = obj.map;
2011
+
2012
+ Type.val = Type.val || Val;
2013
+
2014
+ var Node = {_: '_'};
2015
+ Node.soul = function(n, o){ DEP('node.soul'); return (n && n._ && n._[o || soul_]) }; // convenience function to check to see if there is a soul on a node and return it.
2016
+ Node.soul.ify = function(n, o){ DEP('node.soul.ify'); // put a soul on an object.
2017
+ o = (typeof o === 'string')? {soul: o} : o || {};
2018
+ n = n || {}; // make sure it exists.
2019
+ n._ = n._ || {}; // make sure meta exists.
2020
+ n._[soul_] = o.soul || n._[soul_] || text_random(); // put the soul on it.
2021
+ return n;
2022
+ };
2023
+ Node.soul._ = Val.link._;
2024
+ (function(){
2025
+ Node.is = function(n, cb, as){ DEP('node.is'); var s; // checks to see if an object is a valid node.
2026
+ if(!obj_is(n)){ return false } // must be an object.
2027
+ if(s = Node.soul(n)){ // must have a soul on it.
2028
+ return !obj_map(n, map, {as:as,cb:cb,s:s,n:n});
2029
+ }
2030
+ return false; // nope! This was not a valid node.
2031
+ };
2032
+ function map(v, k){ // we invert this because the way we check for this is via a negation.
2033
+ if(k === Node._){ return } // skip over the metadata.
2034
+ if(!Val.is(v)){ return true } // it is true that this is an invalid node.
2035
+ if(this.cb){ this.cb.call(this.as, v, k, this.n, this.s); } // optionally callback each key/value.
2036
+ }
2037
+ }());
2038
+ (function(){
2039
+ Node.ify = function(obj, o, as){ DEP('node.ify'); // returns a node from a shallow object.
2040
+ if(!o){ o = {}; }
2041
+ else if(typeof o === 'string'){ o = {soul: o}; }
2042
+ else if('function' == typeof o){ o = {map: o}; }
2043
+ if(o.map){ o.node = o.map.call(as, obj, u, o.node || {}); }
2044
+ if(o.node = Node.soul.ify(o.node || {}, o)){
2045
+ obj_map(obj, map, {o:o,as:as});
2046
+ }
2047
+ return o.node; // This will only be a valid node if the object wasn't already deep!
2048
+ };
2049
+ function map(v, k){ var o = this.o, tmp, u; // iterate over each key/value.
2050
+ if(o.map){
2051
+ tmp = o.map.call(this.as, v, ''+k, o.node);
2052
+ if(u === tmp){
2053
+ obj_del(o.node, k);
2054
+ } else
2055
+ if(o.node){ o.node[k] = tmp; }
2056
+ return;
2057
+ }
2058
+ if(Val.is(v)){
2059
+ o.node[k] = v;
2060
+ }
2061
+ }
2062
+ }());
2063
+ var obj = Type.obj, obj_is = obj.is, obj_del = obj.del, obj_map = obj.map;
2064
+ var text = Type.text, text_random = text.random;
2065
+ var soul_ = Node.soul._;
2066
+ var u;
2067
+ Type.node = Type.node || Node;
2068
+
2069
+ var State = Type.state;
2070
+ State.lex = function(){ DEP('state.lex'); return State().toString(36).replace('.','') };
2071
+ State.to = function(from, k, to){ DEP('state.to');
2072
+ var val = (from||{})[k];
2073
+ if(obj_is(val)){
2074
+ val = obj_copy(val);
2075
+ }
2076
+ return State.ify(to, k, State.is(from, k), val, Node.soul(from));
2077
+ }
2078
+ ;(function(){
2079
+ State.map = function(cb, s, as){ DEP('state.map'); var u; // for use with Node.ify
2080
+ var o = obj_is(o = cb || s)? o : null;
2081
+ cb = fn_is(cb = cb || s)? cb : null;
2082
+ if(o && !cb){
2083
+ s = num_is(s)? s : State();
2084
+ o[N_] = o[N_] || {};
2085
+ obj_map(o, map, {o:o,s:s});
2086
+ return o;
2087
+ }
2088
+ as = as || obj_is(s)? s : u;
2089
+ s = num_is(s)? s : State();
2090
+ return function(v, k, o, opt){
2091
+ if(!cb){
2092
+ map.call({o: o, s: s}, v,k);
2093
+ return v;
2094
+ }
2095
+ cb.call(as || this || {}, v, k, o, opt);
2096
+ if(obj_has(o,k) && u === o[k]){ return }
2097
+ map.call({o: o, s: s}, v,k);
2098
+ }
2099
+ };
2100
+ function map(v,k){
2101
+ if(N_ === k){ return }
2102
+ State.ify(this.o, k, this.s) ;
2103
+ }
2104
+ }());
2105
+ var obj = Type.obj; obj.as; var obj_has = obj.has, obj_is = obj.is, obj_map = obj.map, obj_copy = obj.copy;
2106
+ var num = Type.num, num_is = num.is;
2107
+ var fn = Type.fn, fn_is = fn.is;
2108
+ var N_ = Node._, u;
2109
+
2110
+ var Graph = {};
2111
+ (function(){
2112
+ Graph.is = function(g, cb, fn, as){ DEP('graph.is'); // checks to see if an object is a valid graph.
2113
+ if(!g || !obj_is(g) || obj_empty(g)){ return false } // must be an object.
2114
+ return !obj_map(g, map, {cb:cb,fn:fn,as:as}); // makes sure it wasn't an empty object.
2115
+ };
2116
+ function map(n, s){ // we invert this because the way'? we check for this is via a negation.
2117
+ if(!n || s !== Node.soul(n) || !Node.is(n, this.fn, this.as)){ return true } // it is true that this is an invalid graph.
2118
+ if(!this.cb){ return }
2119
+ nf.n = n; nf.as = this.as; // sequential race conditions aren't races.
2120
+ this.cb.call(nf.as, n, s, nf);
2121
+ }
2122
+ function nf(fn){ // optional callback for each node.
2123
+ if(fn){ Node.is(nf.n, fn, nf.as); } // where we then have an optional callback for each key/value.
2124
+ }
2125
+ }());
2126
+ (function(){
2127
+ Graph.ify = function(obj, env, as){ DEP('graph.ify');
2128
+ var at = {path: [], obj: obj};
2129
+ if(!env){
2130
+ env = {};
2131
+ } else
2132
+ if(typeof env === 'string'){
2133
+ env = {soul: env};
2134
+ } else
2135
+ if('function' == typeof env){
2136
+ env.map = env;
2137
+ }
2138
+ if(typeof as === 'string'){
2139
+ env.soul = env.soul || as;
2140
+ as = u;
2141
+ }
2142
+ if(env.soul){
2143
+ at.link = Val.link.ify(env.soul);
2144
+ }
2145
+ env.shell = (as||{}).shell;
2146
+ env.graph = env.graph || {};
2147
+ env.seen = env.seen || [];
2148
+ env.as = env.as || as;
2149
+ node(env, at);
2150
+ env.root = at.node;
2151
+ return env.graph;
2152
+ };
2153
+ function node(env, at){ var tmp;
2154
+ if(tmp = seen(env, at)){ return tmp }
2155
+ at.env = env;
2156
+ at.soul = soul;
2157
+ if(Node.ify(at.obj, map, at)){
2158
+ at.link = at.link || Val.link.ify(Node.soul(at.node));
2159
+ if(at.obj !== env.shell){
2160
+ env.graph[Val.link.is(at.link)] = at.node;
2161
+ }
2162
+ }
2163
+ return at;
2164
+ }
2165
+ function map(v,k,n){
2166
+ var at = this, env = at.env, is, tmp;
2167
+ if(Node._ === k && obj_has(v,Val.link._)){
2168
+ return n._; // TODO: Bug?
2169
+ }
2170
+ if(!(is = valid(v,k,n, at,env))){ return }
2171
+ if(!k){
2172
+ at.node = at.node || n || {};
2173
+ if(obj_has(v, Node._) && Node.soul(v)){ // ? for safety ?
2174
+ at.node._ = obj_copy(v._);
2175
+ }
2176
+ at.node = Node.soul.ify(at.node, Val.link.is(at.link));
2177
+ at.link = at.link || Val.link.ify(Node.soul(at.node));
2178
+ }
2179
+ if(tmp = env.map){
2180
+ tmp.call(env.as || {}, v,k,n, at);
2181
+ if(obj_has(n,k)){
2182
+ v = n[k];
2183
+ if(u === v){
2184
+ obj_del(n, k);
2185
+ return;
2186
+ }
2187
+ if(!(is = valid(v,k,n, at,env))){ return }
2188
+ }
2189
+ }
2190
+ if(!k){ return at.node }
2191
+ if(true === is){
2192
+ return v;
2193
+ }
2194
+ tmp = node(env, {obj: v, path: at.path.concat(k)});
2195
+ if(!tmp.node){ return }
2196
+ return tmp.link; //{'#': Node.soul(tmp.node)};
2197
+ }
2198
+ function soul(id){ var at = this;
2199
+ var prev = Val.link.is(at.link), graph = at.env.graph;
2200
+ at.link = at.link || Val.link.ify(id);
2201
+ at.link[Val.link._] = id;
2202
+ if(at.node && at.node[Node._]){
2203
+ at.node[Node._][Val.link._] = id;
2204
+ }
2205
+ if(obj_has(graph, prev)){
2206
+ graph[id] = graph[prev];
2207
+ obj_del(graph, prev);
2208
+ }
2209
+ }
2210
+ function valid(v,k,n, at,env){ var tmp;
2211
+ if(Val.is(v)){ return true }
2212
+ if(obj_is(v)){ return 1 }
2213
+ if(tmp = env.invalid){
2214
+ v = tmp.call(env.as || {}, v,k,n);
2215
+ return valid(v,k,n, at,env);
2216
+ }
2217
+ env.err = "Invalid value at '" + at.path.concat(k).join('.') + "'!";
2218
+ if(Type.list.is(v)){ env.err += " Use `.set(item)` instead of an Array."; }
2219
+ }
2220
+ function seen(env, at){
2221
+ var arr = env.seen, i = arr.length, has;
2222
+ while(i--){ has = arr[i];
2223
+ if(at.obj === has.obj){ return has }
2224
+ }
2225
+ arr.push(at);
2226
+ }
2227
+ }());
2228
+ Graph.node = function(node){ DEP('graph.node');
2229
+ var soul = Node.soul(node);
2230
+ if(!soul){ return }
2231
+ return obj_put({}, soul, node);
2232
+ }
2233
+ ;(function(){
2234
+ Graph.to = function(graph, root, opt){ DEP('graph.to');
2235
+ if(!graph){ return }
2236
+ var obj = {};
2237
+ opt = opt || {seen: {}};
2238
+ obj_map(graph[root], map, {obj:obj, graph: graph, opt: opt});
2239
+ return obj;
2240
+ };
2241
+ function map(v,k){ var tmp, obj;
2242
+ if(Node._ === k){
2243
+ if(obj_empty(v, Val.link._)){
2244
+ return;
2245
+ }
2246
+ this.obj[k] = obj_copy(v);
2247
+ return;
2248
+ }
2249
+ if(!(tmp = Val.link.is(v))){
2250
+ this.obj[k] = v;
2251
+ return;
2252
+ }
2253
+ if(obj = this.opt.seen[tmp]){
2254
+ this.obj[k] = obj;
2255
+ return;
2256
+ }
2257
+ this.obj[k] = this.opt.seen[tmp] = Graph.to(this.graph, tmp, this.opt);
2258
+ }
2259
+ }());
2260
+ var fn_is = Type.fn.is;
2261
+ var obj = Type.obj, obj_is = obj.is, obj_del = obj.del, obj_has = obj.has, obj_empty = obj.empty, obj_put = obj.put, obj_map = obj.map, obj_copy = obj.copy;
2262
+ var u;
2263
+ Type.graph = Type.graph || Graph;
2264
+ }());
2265
+ } (gun$1));
2266
+
2267
+ var gunExports = gun$1.exports;
2268
+ var Gun$1 = /*@__PURE__*/getDefaultExportFromCjs(gunExports);
2269
+
2270
+ let contractAddresses$1 = {
2271
+ PROOF_OF_INTEGRITY_ADDRESS: "0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512",
2272
+ STEALTH_ANNOUNCER_ADDRESS: "0x5FbDB2315678afecb367f032d93F642f64180aa3"
2273
+ };
2274
+ if (typeof window === 'undefined') {
2275
+ const {
2276
+ fileURLToPath
2277
+ } = require('url');
2278
+ const {
2279
+ dirname
2280
+ } = require('path');
2281
+ const {
2282
+ readFileSync
2283
+ } = require('fs');
2284
+ const {
2285
+ join
2286
+ } = require('path');
2287
+ try {
2288
+ const __filename = fileURLToPath(import.meta.url);
2289
+ const __dirname = dirname(__filename);
2290
+ const rawdata = readFileSync(join(__dirname, 'contract-address.json'), 'utf8');
2291
+ contractAddresses$1 = JSON.parse(rawdata);
2292
+ console.log("Loaded contract addresses:", contractAddresses$1);
2293
+ } catch (error) {
2294
+ console.warn("Warning: contract-address.json not found or invalid");
2295
+ }
2296
+ }
2297
+ const LOCAL_CONFIG = {
2298
+ CHAIN_ID: 1337,
2299
+ PROOF_OF_INTEGRITY_ADDRESS: contractAddresses$1.PROOF_OF_INTEGRITY_ADDRESS,
2300
+ STEALTH_ANNOUNCER_ADDRESS: contractAddresses$1.STEALTH_ANNOUNCER_ADDRESS,
2301
+ RPC_URL: "http://127.0.0.1:8545",
2302
+ GUN_PEER: "http://localhost:8765/gun"
2303
+ };
2304
+
2305
+ // Indirizzi di produzione per diverse chain
2306
+ const CHAIN_CONFIG = {
2307
+ optimismSepolia: {
2308
+ STEALTH_ANNOUNCER_ADDRESS: "0xD0F2e9DA59d2DFECFdE67CcF17300BB6093A72f8",
2309
+ PROOF_OF_INTEGRITY_ADDRESS: "0x...",
2310
+ RPC_URL: "https://sepolia.optimism.io",
2311
+ CHAIN_ID: 11155420
2312
+ },
2313
+ arbitrumSepolia: {
2314
+ STEALTH_ANNOUNCER_ADDRESS: "0x...",
2315
+ PROOF_OF_INTEGRITY_ADDRESS: "0x...",
2316
+ RPC_URL: "https://sepolia-rollup.arbitrum.io/rpc",
2317
+ CHAIN_ID: 421614
2318
+ },
2319
+ localhost: {
2320
+ RPC_URL: "http://127.0.0.1:8545",
2321
+ CHAIN_ID: 1337
2322
+ }
2323
+ };
2324
+
2325
+ // Esporta gli indirizzi dei contratti
2326
+ const PROOF_OF_INTEGRITY_ADDRESS = CHAIN_CONFIG.optimismSepolia.PROOF_OF_INTEGRITY_ADDRESS;
2327
+ const STEALTH_ANNOUNCER_ADDRESS = CHAIN_CONFIG.optimismSepolia.STEALTH_ANNOUNCER_ADDRESS;
2328
+
2329
+ // Funzione per ottenere gli indirizzi corretti
2330
+ function getAddressesForChain(chainName) {
2331
+ let config;
2332
+
2333
+ // Se è localhost, prova a caricare gli indirizzi locali
2334
+ if (chainName === 'localhost') {
2335
+ try {
2336
+ // Carica gli indirizzi dal file generato dal deploy locale
2337
+ const localAddresses = require('../config/contract-address.json');
2338
+ config = {
2339
+ ...CHAIN_CONFIG.localhost,
2340
+ ...localAddresses
2341
+ };
2342
+ console.log("Using local addresses:", config);
2343
+ return config;
2344
+ } catch (err) {
2345
+ console.warn('No local addresses found');
2346
+ throw new Error('No local addresses found. Did you run local deployment?');
2347
+ }
2348
+ }
2349
+
2350
+ // Altrimenti usa gli indirizzi di produzione
2351
+ config = CHAIN_CONFIG[chainName];
2352
+ if (!config) {
2353
+ throw new Error(`Chain ${chainName} not supported. Supported chains: ${Object.keys(CHAIN_CONFIG).join(', ')}`);
2354
+ }
2355
+ return config;
2356
+ }
2357
+ const STEALTH_ANNOUNCER_ABI = [{
2358
+ "inputs": [{
2359
+ "internalType": "address",
2360
+ "name": "_devAddress",
2361
+ "type": "address"
2362
+ }],
2363
+ "stateMutability": "nonpayable",
2364
+ "type": "constructor"
2365
+ }, {
2366
+ "anonymous": false,
2367
+ "inputs": [{
2368
+ "internalType": "string",
2369
+ "name": "senderPublicKey",
2370
+ "type": "string"
2371
+ }, {
2372
+ "internalType": "string",
2373
+ "name": "spendingPublicKey",
2374
+ "type": "string"
2375
+ }, {
2376
+ "internalType": "address",
2377
+ "name": "stealthAddress",
2378
+ "type": "address"
2379
+ }, {
2380
+ "internalType": "uint256",
2381
+ "name": "timestamp",
2382
+ "type": "uint256"
2383
+ }],
2384
+ "name": "StealthPaymentAnnounced",
2385
+ "type": "event"
2386
+ }, {
2387
+ "anonymous": false,
2388
+ "inputs": [{
2389
+ "internalType": "address",
2390
+ "name": "newAddress",
2391
+ "type": "address"
2392
+ }],
2393
+ "name": "DevAddressUpdated",
2394
+ "type": "event"
2395
+ }, {
2396
+ "anonymous": false,
2397
+ "inputs": [{
2398
+ "internalType": "uint256",
2399
+ "name": "newFee",
2400
+ "type": "uint256"
2401
+ }],
2402
+ "name": "DevFeeUpdated",
2403
+ "type": "event"
2404
+ }, {
2405
+ "inputs": [{
2406
+ "internalType": "string",
2407
+ "name": "senderPublicKey",
2408
+ "type": "string"
2409
+ }, {
2410
+ "internalType": "string",
2411
+ "name": "spendingPublicKey",
2412
+ "type": "string"
2413
+ }, {
2414
+ "internalType": "address",
2415
+ "name": "stealthAddress",
2416
+ "type": "address"
2417
+ }],
2418
+ "name": "announcePayment",
2419
+ "outputs": [],
2420
+ "stateMutability": "payable",
2421
+ "type": "function"
2422
+ }, {
2423
+ "inputs": [],
2424
+ "name": "devAddress",
2425
+ "outputs": [{
2426
+ "internalType": "address",
2427
+ "name": "",
2428
+ "type": "address"
2429
+ }],
2430
+ "stateMutability": "view",
2431
+ "type": "function"
2432
+ }, {
2433
+ "inputs": [],
2434
+ "name": "devFee",
2435
+ "outputs": [{
2436
+ "internalType": "uint256",
2437
+ "name": "",
2438
+ "type": "uint256"
2439
+ }],
2440
+ "stateMutability": "view",
2441
+ "type": "function"
2442
+ }, {
2443
+ "inputs": [],
2444
+ "name": "getAnnouncementsCount",
2445
+ "outputs": [{
2446
+ "internalType": "uint256",
2447
+ "name": "",
2448
+ "type": "uint256"
2449
+ }],
2450
+ "stateMutability": "view",
2451
+ "type": "function"
2452
+ }, {
2453
+ "inputs": [{
2454
+ "internalType": "uint256",
2455
+ "name": "fromIndex",
2456
+ "type": "uint256"
2457
+ }, {
2458
+ "internalType": "uint256",
2459
+ "name": "toIndex",
2460
+ "type": "uint256"
2461
+ }],
2462
+ "name": "getAnnouncementsInRange",
2463
+ "outputs": [{
2464
+ "components": [{
2465
+ "internalType": "string",
2466
+ "name": "senderPublicKey",
2467
+ "type": "string"
2468
+ }, {
2469
+ "internalType": "string",
2470
+ "name": "spendingPublicKey",
2471
+ "type": "string"
2472
+ }, {
2473
+ "internalType": "address",
2474
+ "name": "stealthAddress",
2475
+ "type": "address"
2476
+ }, {
2477
+ "internalType": "uint256",
2478
+ "name": "timestamp",
2479
+ "type": "uint256"
2480
+ }],
2481
+ "internalType": "struct StealthAnnouncer.StealthAnnouncement[]",
2482
+ "name": "",
2483
+ "type": "tuple[]"
2484
+ }],
2485
+ "stateMutability": "view",
2486
+ "type": "function"
2487
+ }, {
2488
+ "inputs": [{
2489
+ "internalType": "uint256",
2490
+ "name": "_newFee",
2491
+ "type": "uint256"
2492
+ }],
2493
+ "name": "updateDevFee",
2494
+ "outputs": [],
2495
+ "stateMutability": "nonpayable",
2496
+ "type": "function"
2497
+ }, {
2498
+ "inputs": [{
2499
+ "internalType": "address",
2500
+ "name": "_newAddress",
2501
+ "type": "address"
2502
+ }],
2503
+ "name": "updateDevAddress",
2504
+ "outputs": [],
2505
+ "stateMutability": "nonpayable",
2506
+ "type": "function"
2507
+ }, {
2508
+ "inputs": [],
2509
+ "name": "withdrawStuckETH",
2510
+ "outputs": [],
2511
+ "stateMutability": "nonpayable",
2512
+ "type": "function"
2513
+ }];
2514
+ const PROOF_OF_INTEGRITY_ABI = [{
2515
+ "inputs": [{
2516
+ "internalType": "bytes[]",
2517
+ "name": "nodeIds",
2518
+ "type": "bytes[]"
2519
+ }],
2520
+ "stateMutability": "nonpayable",
2521
+ "type": "function"
2522
+ }, {
2523
+ "anonymous": false,
2524
+ "inputs": [{
2525
+ "indexed": true,
2526
+ "internalType": "bytes",
2527
+ "name": "nodeId",
2528
+ "type": "bytes"
2529
+ }, {
2530
+ "indexed": false,
2531
+ "internalType": "bytes32",
2532
+ "name": "contentHash",
2533
+ "type": "bytes32"
2534
+ }, {
2535
+ "indexed": false,
2536
+ "internalType": "address",
2537
+ "name": "updater",
2538
+ "type": "address"
2539
+ }],
2540
+ "name": "DataUpdated",
2541
+ "type": "event"
2542
+ }, {
2543
+ "inputs": [{
2544
+ "internalType": "bytes",
2545
+ "name": "nodeId",
2546
+ "type": "bytes"
2547
+ }],
2548
+ "name": "getLatestRecord",
2549
+ "outputs": [{
2550
+ "internalType": "bytes32",
2551
+ "name": "",
2552
+ "type": "bytes32"
2553
+ }, {
2554
+ "internalType": "uint256",
2555
+ "name": "",
2556
+ "type": "uint256"
2557
+ }, {
2558
+ "internalType": "address",
2559
+ "name": "",
2560
+ "type": "address"
2561
+ }],
2562
+ "stateMutability": "view",
2563
+ "type": "function"
2564
+ }, {
2565
+ "inputs": [{
2566
+ "internalType": "bytes",
2567
+ "name": "nodeId",
2568
+ "type": "bytes"
2569
+ }, {
2570
+ "internalType": "bytes32",
2571
+ "name": "contentHash",
2572
+ "type": "bytes32"
2573
+ }],
2574
+ "name": "updateData",
2575
+ "outputs": [],
2576
+ "stateMutability": "nonpayable",
2577
+ "type": "function"
2578
+ }, {
2579
+ "inputs": [{
2580
+ "internalType": "bytes",
2581
+ "name": "nodeId",
2582
+ "type": "bytes"
2583
+ }, {
2584
+ "internalType": "bytes32",
2585
+ "name": "contentHash",
2586
+ "type": "bytes32"
2587
+ }],
2588
+ "name": "verifyData",
2589
+ "outputs": [{
2590
+ "internalType": "bool",
2591
+ "name": "",
2592
+ "type": "bool"
2593
+ }, {
2594
+ "internalType": "uint256",
2595
+ "name": "",
2596
+ "type": "uint256"
2597
+ }, {
2598
+ "internalType": "address",
2599
+ "name": "",
2600
+ "type": "address"
2601
+ }],
2602
+ "stateMutability": "view",
2603
+ "type": "function"
2604
+ }];
2605
+
2606
+ let PROOF_CONTRACT_ADDRESS;
2607
+ let rpcUrl = "";
2608
+ let privateKey = "";
2609
+ const MESSAGE_TO_SIGN = "Access GunDB with Ethereum";
2610
+ let contractAddresses = {
2611
+ PROOF_OF_INTEGRITY_ADDRESS,
2612
+ STEALTH_ANNOUNCER_ADDRESS
2613
+ };
2614
+
2615
+ // Inizializzazione asincrona spostata in una funzione
2616
+ async function initializeTextEncoder() {
2617
+ if (typeof window === 'undefined') {
2618
+ const util = await import('util');
2619
+ global.TextEncoder = util.TextEncoder;
2620
+ global.TextDecoder = util.TextDecoder;
2621
+ }
2622
+ }
2623
+
2624
+ // Inizializzazione contratti per Node.js
2625
+ function initializeContracts() {
2626
+ if (typeof window === 'undefined') {
2627
+ try {
2628
+ const {
2629
+ fileURLToPath
2630
+ } = require('url');
2631
+ const {
2632
+ dirname
2633
+ } = require('path');
2634
+ const {
2635
+ readFileSync
2636
+ } = require('fs');
2637
+ const path = require('path');
2638
+ const __filename = fileURLToPath(import.meta.url);
2639
+ const __dirname = dirname(__filename);
2640
+ const rawdata = readFileSync(path.join(__dirname, 'contract-address.json'), 'utf8');
2641
+ contractAddresses = JSON.parse(rawdata);
2642
+ console.log('Loaded contract addresses:', contractAddresses);
2643
+ } catch (err) {
2644
+ console.warn('Warning: contract-address.json not found or invalid');
2645
+ }
2646
+ }
2647
+ }
2648
+
2649
+ // Funzione di inizializzazione che può essere chiamata se necessario
2650
+ async function initialize() {
2651
+ await initializeTextEncoder();
2652
+ initializeContracts();
2653
+ }
2654
+
2655
+ // =============================================
2656
+ // UTILITY FUNCTIONS
2657
+ // =============================================
2658
+ /**
2659
+ * Generates a random node ID for GunDB
2660
+ * @returns {string} A random hexadecimal string
2661
+ */
2662
+ function generateRandomId() {
2663
+ return ethers.hexlify(ethers.randomBytes(32)).slice(2);
2664
+ }
2665
+
2666
+ /**
2667
+ * Generates a password from a signature.
2668
+ * @param {string} signature - The signature to derive the password from.
2669
+ * @returns {string|null} The generated password or null if generation fails.
2670
+ */
2671
+ function generatePassword(signature) {
2672
+ try {
2673
+ const hexSignature = ethers.hexlify(signature);
2674
+ const hash = ethers.keccak256(hexSignature);
2675
+ console.log("Generated password:", hash);
2676
+ return hash;
2677
+ } catch (error) {
2678
+ console.error("Error generating password:", error);
2679
+ return null;
2680
+ }
2681
+ }
2682
+
2683
+ /**
2684
+ * Converts a Gun private key to an Ethereum account.
2685
+ * @param {string} gunPrivateKey - The Gun private key in base64url format.
2686
+ * @returns {Object} An object containing the Ethereum account and public key.
2687
+ */
2688
+ function gunToEthAccount(gunPrivateKey) {
2689
+ // Function to convert base64url to hex
2690
+ const base64UrlToHex = base64url => {
2691
+ const padding = "=".repeat((4 - base64url.length % 4) % 4);
2692
+ const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/") + padding;
2693
+ const binary = atob(base64);
2694
+ return Array.from(binary, char => char.charCodeAt(0).toString(16).padStart(2, "0")).join("");
2695
+ };
2696
+
2697
+ // Convert Gun private key to hex format
2698
+ const hexPrivateKey = "0x" + base64UrlToHex(gunPrivateKey);
2699
+
2700
+ // Create an Ethereum wallet from the private key
2701
+ const wallet = new ethers.Wallet(hexPrivateKey);
2702
+
2703
+ // Get the public address (public key)
2704
+ const publicKey = wallet.address;
2705
+ return {
2706
+ account: wallet,
2707
+ publicKey: publicKey,
2708
+ privateKey: hexPrivateKey
2709
+ };
2710
+ }
2711
+
2712
+ /**
2713
+ * Gets an Ethereum signer based on current configuration
2714
+ * @returns {Promise<ethers.Signer>} The configured signer
2715
+ * @throws {Error} If no valid provider is found
2716
+ */
2717
+ const getSigner = async () => {
2718
+ if (rpcUrl && privateKey) {
2719
+ // Standalone mode with local provider
2720
+ const provider = new ethers.JsonRpcProvider(rpcUrl, {
2721
+ chainId: LOCAL_CONFIG.CHAIN_ID,
2722
+ name: "localhost"
2723
+ });
2724
+ return new ethers.Wallet(privateKey, provider);
2725
+ } else if (typeof window !== "undefined" && typeof window.ethereum !== "undefined") {
2726
+ // Browser mode
2727
+ await window.ethereum.request({
2728
+ method: "eth_requestAccounts"
2729
+ });
2730
+ const provider = new ethers.BrowserProvider(window.ethereum);
2731
+ return provider.getSigner();
2732
+ } else {
2733
+ throw new Error("No valid Ethereum provider found");
2734
+ }
2735
+ };
2736
+
2737
+ /**
2738
+ * Utility function to generate stealth address
2739
+ * @param {string} sharedSecret - The shared secret
2740
+ * @param {string} spendingPublicKey - The spending public key
2741
+ * @returns {Object} The stealth address and private key
2742
+ */
2743
+ function deriveStealthAddress(sharedSecret, spendingPublicKey) {
2744
+ try {
2745
+ // Convert shared secret to bytes
2746
+ const sharedSecretBytes = Buffer.from(sharedSecret, 'base64');
2747
+
2748
+ // Generate stealth private key using shared secret and spending public key
2749
+ const stealthPrivateKey = ethers.keccak256(ethers.concat([sharedSecretBytes, ethers.getBytes(spendingPublicKey)]));
2750
+
2751
+ // Create stealth wallet
2752
+ const stealthWallet = new ethers.Wallet(stealthPrivateKey);
2753
+ console.log("Debug deriveStealthAddress:", {
2754
+ sharedSecretHex: ethers.hexlify(sharedSecretBytes),
2755
+ spendingPublicKey,
2756
+ stealthPrivateKey,
2757
+ stealthAddress: stealthWallet.address
2758
+ });
2759
+ return {
2760
+ stealthPrivateKey,
2761
+ stealthAddress: stealthWallet.address,
2762
+ wallet: stealthWallet
2763
+ };
2764
+ } catch (error) {
2765
+ console.error("Error in deriveStealthAddress:", error);
2766
+ throw error;
2767
+ }
2768
+ }
2769
+
2770
+ // =============================================
2771
+ // BASIC GUN-ETH CHAIN METHODS
2772
+ // =============================================
2773
+
2774
+ // Set the message to sign
2775
+ Gun$1.chain.MESSAGE_TO_SIGN = MESSAGE_TO_SIGN;
2776
+
2777
+ /**
2778
+ * Sets standalone configuration for Gun.
2779
+ * @param {string} newRpcUrl - The new RPC URL.
2780
+ * @param {string} newPrivateKey - The new private key.
2781
+ * @returns {Gun} The Gun instance for chaining.
2782
+ */
2783
+ Gun$1.chain.setSigner = function (newRpcUrl, newPrivateKey) {
2784
+ rpcUrl = newRpcUrl;
2785
+ privateKey = newPrivateKey;
2786
+ console.log("Standalone configuration set");
2787
+ return this;
2788
+ };
2789
+ Gun$1.chain.getSigner = getSigner;
2790
+
2791
+ /**
2792
+ * Verifies an Ethereum signature.
2793
+ * @param {string} message - The original message that was signed.
2794
+ * @param {string} signature - The signature to verify.
2795
+ * @returns {Promise<string|null>} The recovered address or null if verification fails.
2796
+ */
2797
+ Gun$1.chain.verifySignature = async function (message, signature) {
2798
+ try {
2799
+ const recoveredAddress = ethers.verifyMessage(message, signature);
2800
+ return recoveredAddress;
2801
+ } catch (error) {
2802
+ console.error("Error verifying signature:", error);
2803
+ return null;
2804
+ }
2805
+ };
2806
+
2807
+ /**
2808
+ * Generates a password from a signature.
2809
+ * @param {string} signature - The signature to derive the password from.
2810
+ * @returns {string|null} The generated password or null if generation fails.
2811
+ */
2812
+ Gun$1.chain.generatePassword = function (signature) {
2813
+ return generatePassword(signature);
2814
+ };
2815
+
2816
+ /**
2817
+ * Creates an Ethereum signature for a given message.
2818
+ * @param {string} message - The message to sign.
2819
+ * @returns {Promise<string|null>} The signature or null if signing fails.
2820
+ */
2821
+ Gun$1.chain.createSignature = async function (message) {
2822
+ try {
2823
+ // Check if message matches MESSAGE_TO_SIGN
2824
+ if (message !== MESSAGE_TO_SIGN) {
2825
+ throw new Error("Invalid message, valid message is: " + MESSAGE_TO_SIGN);
2826
+ }
2827
+ const signer = await getSigner();
2828
+ const signature = await signer.signMessage(message);
2829
+ console.log("Signature created:", signature);
2830
+ return signature;
2831
+ } catch (error) {
2832
+ console.error("Error creating signature:", error);
2833
+ return null;
2834
+ }
2835
+ };
2836
+
2837
+ // =============================================
2838
+ // KEY PAIR MANAGEMENT
2839
+ // =============================================
2840
+ /**
2841
+ * Creates and stores an encrypted key pair for a given address.
2842
+ * @param {string} address - The Ethereum address to associate with the key pair.
2843
+ * @param {string} signature - The signature to use for encryption.
2844
+ * @returns {Promise<void>}
2845
+ */
2846
+ Gun$1.chain.createAndStoreEncryptedPair = async function (address, signature) {
2847
+ try {
2848
+ const gun = this;
2849
+ const pair = await SEA.pair();
2850
+ const v_pair = await SEA.pair();
2851
+ const s_pair = await SEA.pair();
2852
+ const password = generatePassword(signature);
2853
+
2854
+ // Save original SEA pairs
2855
+ const encryptedPair = await SEA.encrypt(JSON.stringify(pair), password);
2856
+ const encryptedV_pair = await SEA.encrypt(JSON.stringify(v_pair), password);
2857
+ const encryptedS_pair = await SEA.encrypt(JSON.stringify(s_pair), password);
2858
+
2859
+ // Convert only to get Ethereum addresses
2860
+ const viewingAccount = gunToEthAccount(v_pair.priv);
2861
+ const spendingAccount = gunToEthAccount(s_pair.priv);
2862
+ gun.get("gun-eth").get("users").get(address).put({
2863
+ pair: encryptedPair,
2864
+ v_pair: encryptedV_pair,
2865
+ s_pair: encryptedS_pair,
2866
+ publicKeys: {
2867
+ viewingPublicKey: v_pair.epub,
2868
+ // Use SEA encryption public key
2869
+ viewingPublicKey: v_pair.epub,
2870
+ // Use SEA encryption public key
2871
+ spendingPublicKey: spendingAccount.publicKey,
2872
+ // Use Ethereum address
2873
+ ethViewingAddress: viewingAccount.publicKey // Also save Ethereum address
2874
+ }
2875
+ });
2876
+ console.log("Encrypted pairs and public keys stored for:", address);
2877
+ } catch (error) {
2878
+ console.error("Error creating and storing encrypted pair:", error);
2879
+ throw error;
2880
+ }
2881
+ };
2882
+
2883
+ /**
2884
+ * Retrieves and decrypts a stored key pair for a given address.
2885
+ * @param {string} address - The Ethereum address associated with the key pair.
2886
+ * @param {string} signature - The signature to use for decryption.
2887
+ * @returns {Promise<Object|null>} The decrypted key pair or null if retrieval fails.
2888
+ */
2889
+ Gun$1.chain.getAndDecryptPair = async function (address, signature) {
2890
+ try {
2891
+ const gun = this;
2892
+ const encryptedData = await gun.get("gun-eth").get("users").get(address).get("pair").then();
2893
+ if (!encryptedData) {
2894
+ throw new Error("No encrypted data found for this address");
2895
+ }
2896
+ const password = generatePassword(signature);
2897
+ const decryptedPair = await SEA.decrypt(encryptedData, password);
2898
+ console.log(decryptedPair);
2899
+ return decryptedPair;
2900
+ } catch (error) {
2901
+ console.error("Error retrieving and decrypting pair:", error);
2902
+ return null;
2903
+ }
2904
+ };
2905
+
2906
+ // =============================================
2907
+ // PROOF OF INTEGRITY
2908
+ // =============================================
2909
+ /**
2910
+ * Proof of Integrity
2911
+ * @param {string} chain - The blockchain to use (e.g., "optimismSepolia").
2912
+ * @param {string} nodeId - The ID of the node to verify or write.
2913
+ * @param {Object} data - The data to write (if writing).
2914
+ * @param {Function} callback - Callback function to handle the result.
2915
+ * @returns {Gun} The Gun instance for chaining.
2916
+ */
2917
+ Gun$1.chain.proof = function (chain, nodeId, data, callback) {
2918
+ console.log("Proof plugin called with:", {
2919
+ chain,
2920
+ nodeId,
2921
+ data
2922
+ });
2923
+ if (typeof callback !== "function") {
2924
+ console.error("Callback must be a function");
2925
+ return this;
2926
+ }
2927
+ try {
2928
+ // Se siamo in localhost e in development, usa automaticamente la chain locale
2929
+ const targetChain = isLocalEnvironment() ? 'localhost' : chain;
2930
+ const chainConfig = getAddressesForChain(targetChain);
2931
+ console.log(`Using ${targetChain} configuration:`, chainConfig);
2932
+
2933
+ // Usa gli indirizzi dalla configurazione
2934
+ const contract = new ethers.Contract(chainConfig.PROOF_OF_INTEGRITY_ADDRESS, PROOF_OF_INTEGRITY_ABI, signer);
2935
+
2936
+ // Funzione per verificare on-chain
2937
+ const verifyOnChain = async (nodeId, contentHash) => {
2938
+ console.log("Verifying on chain:", {
2939
+ nodeId,
2940
+ contentHash
2941
+ });
2942
+ const signer = await getSigner();
2943
+ const contract = new ethers.Contract(PROOF_CONTRACT_ADDRESS, PROOF_OF_INTEGRITY_ABI, signer);
2944
+ const [isValid, timestamp, updater] = await contract.verifyData(ethers.toUtf8Bytes(nodeId), contentHash);
2945
+ console.log("Verification result:", {
2946
+ isValid,
2947
+ timestamp,
2948
+ updater
2949
+ });
2950
+ return {
2951
+ isValid,
2952
+ timestamp,
2953
+ updater
2954
+ };
2955
+ };
2956
+
2957
+ // Funzione per scrivere on-chain
2958
+ const writeOnChain = async (nodeId, contentHash) => {
2959
+ console.log("Writing on chain:", {
2960
+ nodeId,
2961
+ contentHash
2962
+ });
2963
+ const signer = await getSigner();
2964
+ const contract = new ethers.Contract(PROOF_CONTRACT_ADDRESS, PROOF_OF_INTEGRITY_ABI, signer);
2965
+ const tx = await contract.updateData(ethers.toUtf8Bytes(nodeId), contentHash);
2966
+ console.log("Transaction sent:", tx.hash);
2967
+ const receipt = await tx.wait();
2968
+ console.log("Transaction confirmed:", receipt);
2969
+ return tx;
2970
+ };
2971
+
2972
+ // Funzione per ottenere l'ultimo record
2973
+ const getLatestRecord = async nodeId => {
2974
+ const signer = await getSigner();
2975
+ const contract = new ethers.Contract(PROOF_CONTRACT_ADDRESS, PROOF_OF_INTEGRITY_ABI, signer);
2976
+ const [contentHash, timestamp, updater] = await contract.getLatestRecord(ethers.toUtf8Bytes(nodeId));
2977
+ console.log("Latest record from blockchain:", {
2978
+ nodeId,
2979
+ contentHash,
2980
+ timestamp,
2981
+ updater
2982
+ });
2983
+ return {
2984
+ contentHash,
2985
+ timestamp,
2986
+ updater
2987
+ };
2988
+ };
2989
+ if (nodeId && !data) {
2990
+ // Case 1: User passes only node
2991
+ gun.get(nodeId).once(async existingData => {
2992
+ if (!existingData) {
2993
+ if (callback) callback({
2994
+ err: "Node not found in GunDB"
2995
+ });
2996
+ return;
2997
+ }
2998
+ console.log("existingData", existingData);
2999
+
3000
+ // Use stored contentHash instead of recalculating
3001
+ const contentHash = existingData._contentHash;
3002
+ console.log("contentHash", contentHash);
3003
+ if (!contentHash) {
3004
+ if (callback) callback({
3005
+ err: "No content hash found for this node"
3006
+ });
3007
+ return;
3008
+ }
3009
+ try {
3010
+ const {
3011
+ isValid,
3012
+ timestamp,
3013
+ updater
3014
+ } = await verifyOnChain(nodeId, contentHash);
3015
+ const latestRecord = await getLatestRecord(nodeId);
3016
+ if (isValid) {
3017
+ if (callback) callback({
3018
+ ok: true,
3019
+ message: "Data verified on blockchain",
3020
+ timestamp,
3021
+ updater,
3022
+ latestRecord
3023
+ });
3024
+ } else {
3025
+ if (callback) callback({
3026
+ ok: false,
3027
+ message: "Data not verified on blockchain",
3028
+ latestRecord
3029
+ });
3030
+ }
3031
+ } catch (error) {
3032
+ if (callback) callback({
3033
+ err: error.message
3034
+ });
3035
+ }
3036
+ });
3037
+ } else if (data && !nodeId) {
3038
+ // Case 2: User passes only text (data)
3039
+ const newNodeId = generateRandomId();
3040
+ const dataString = JSON.stringify(data);
3041
+ const contentHash = ethers.keccak256(ethers.toUtf8Bytes(dataString));
3042
+ gun.get(newNodeId).put({
3043
+ ...data,
3044
+ _contentHash: contentHash
3045
+ }, async ack => {
3046
+ console.log("ack", ack);
3047
+ if (ack.err) {
3048
+ if (callback) callback({
3049
+ err: "Error saving data to GunDB"
3050
+ });
3051
+ return;
3052
+ }
3053
+ try {
3054
+ const tx = await writeOnChain(newNodeId, contentHash);
3055
+ if (callback) callback({
3056
+ ok: true,
3057
+ message: "Data written to GunDB and blockchain",
3058
+ nodeId: newNodeId,
3059
+ txHash: tx.hash
3060
+ });
3061
+ } catch (error) {
3062
+ if (callback) callback({
3063
+ err: error.message
3064
+ });
3065
+ }
3066
+ });
3067
+ } else {
3068
+ if (callback) callback({
3069
+ err: "Invalid input. Provide either nodeId or data, not both."
3070
+ });
3071
+ }
3072
+ return gun;
3073
+ } catch (error) {
3074
+ callback({
3075
+ err: error.message
3076
+ });
3077
+ return this;
3078
+ }
3079
+ };
3080
+
3081
+ // =============================================
3082
+ // STEALTH ADDRESS CORE FUNCTIONS
3083
+ // =============================================
3084
+ /**
3085
+ * Converts a Gun private key to an Ethereum account.
3086
+ * @param {string} gunPrivateKey - The Gun private key in base64url format.
3087
+ * @returns {Object} An object containing the Ethereum account and public key.
3088
+ */
3089
+ Gun$1.chain.gunToEthAccount = function (gunPrivateKey) {
3090
+ return gunToEthAccount(gunPrivateKey);
3091
+ };
3092
+
3093
+ /**
3094
+ * Generate a stealth key and related key pairs
3095
+ * @param {string} recipientAddress - The recipient's Ethereum address
3096
+ * @param {string} signature - The sender's signature to access their keys
3097
+ * @returns {Promise<Object>} Object containing stealth addresses and keys
3098
+ */
3099
+ Gun$1.chain.generateStealthAddress = async function (recipientAddress, signature) {
3100
+ try {
3101
+ const gun = this;
3102
+
3103
+ // Get recipient's public keys
3104
+ const recipientData = await gun.get("gun-eth").get("users").get(recipientAddress).get("publicKeys").then();
3105
+ if (!recipientData || !recipientData.viewingPublicKey || !recipientData.spendingPublicKey) {
3106
+ throw new Error("Recipient's public keys not found");
3107
+ }
3108
+
3109
+ // Get sender's keys
3110
+ const senderAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);
3111
+ const password = generatePassword(signature);
3112
+ const senderData = await gun.get("gun-eth").get("users").get(senderAddress).then();
3113
+ if (!senderData || !senderData.s_pair) {
3114
+ throw new Error("Sender's keys not found");
3115
+ }
3116
+
3117
+ // Decrypt sender's spending pair
3118
+ let spendingKeyPair;
3119
+ try {
3120
+ const decryptedData = await SEA.decrypt(senderData.s_pair, password);
3121
+ spendingKeyPair = typeof decryptedData === 'string' ? JSON.parse(decryptedData) : decryptedData;
3122
+ } catch (error) {
3123
+ console.error("Error decrypting spending pair:", error);
3124
+ throw new Error("Unable to decrypt spending pair");
3125
+ }
3126
+
3127
+ // Generate shared secret using SEA ECDH with encryption public key
3128
+ const sharedSecret = await SEA.secret(recipientData.viewingPublicKey, spendingKeyPair);
3129
+ if (!sharedSecret) {
3130
+ throw new Error("Unable to generate shared secret");
3131
+ }
3132
+ console.log("Generate shared secret:", sharedSecret);
3133
+ const {
3134
+ stealthAddress
3135
+ } = deriveStealthAddress(sharedSecret, recipientData.spendingPublicKey);
3136
+ return {
3137
+ stealthAddress,
3138
+ senderPublicKey: spendingKeyPair.epub,
3139
+ // Use encryption public key
3140
+ spendingPublicKey: recipientData.spendingPublicKey
3141
+ };
3142
+ } catch (error) {
3143
+ console.error("Error generating stealth address:", error);
3144
+ throw error;
3145
+ }
3146
+ };
3147
+
3148
+ /**
3149
+ * Publish public keys needed to receive stealth payments
3150
+ * @param {string} signature - The signature to authenticate the user
3151
+ * @returns {Promise<void>}
3152
+ */
3153
+ Gun$1.chain.publishStealthKeys = async function (signature) {
3154
+ try {
3155
+ const gun = this;
3156
+ const address = await this.verifySignature(MESSAGE_TO_SIGN, signature);
3157
+ const password = generatePassword(signature);
3158
+
3159
+ // Get encrypted key pairs
3160
+ const encryptedData = await gun.get("gun-eth").get("users").get(address).then();
3161
+ if (!encryptedData || !encryptedData.v_pair || !encryptedData.s_pair) {
3162
+ throw new Error("Keys not found");
3163
+ }
3164
+
3165
+ // Decrypt viewing and spending pairs
3166
+ const viewingKeyPair = JSON.parse(await SEA.decrypt(encryptedData.v_pair, password));
3167
+ const spendingKeyPair = JSON.parse(await SEA.decrypt(encryptedData.s_pair, password));
3168
+ const viewingAccount = gunToEthAccount(viewingKeyPair.priv);
3169
+ const spendingAccount = gunToEthAccount(spendingKeyPair.priv);
3170
+
3171
+ // Publish only public keys
3172
+ gun.get("gun-eth").get("users").get(address).get("publicKeys").put({
3173
+ viewingPublicKey: viewingAccount.publicKey,
3174
+ spendingPublicKey: spendingAccount.publicKey
3175
+ });
3176
+ console.log("Stealth public keys published successfully");
3177
+ } catch (error) {
3178
+ console.error("Error publishing stealth keys:", error);
3179
+ throw error;
3180
+ }
3181
+ };
3182
+
3183
+ // =============================================
3184
+ // STEALTH PAYMENT FUNCTIONS
3185
+ // =============================================
3186
+ /**
3187
+ * Recover funds from a stealth address
3188
+ * @param {string} stealthAddress - The stealth address to recover funds from
3189
+ * @param {string} senderPublicKey - The sender's public key used to generate the address
3190
+ * @param {string} signature - The signature to decrypt private keys
3191
+ * @returns {Promise<Object>} Object containing wallet to access funds
3192
+ */
3193
+ Gun$1.chain.recoverStealthFunds = async function (stealthAddress, senderPublicKey, signature, spendingPublicKey) {
3194
+ try {
3195
+ const gun = this;
3196
+ const password = generatePassword(signature);
3197
+
3198
+ // Get own key pairs
3199
+ const myAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);
3200
+ const encryptedData = await gun.get("gun-eth").get("users").get(myAddress).then();
3201
+ if (!encryptedData || !encryptedData.v_pair || !encryptedData.s_pair) {
3202
+ throw new Error("Keys not found");
3203
+ }
3204
+
3205
+ // Decrypt viewing and spending pairs
3206
+ let viewingKeyPair;
3207
+ try {
3208
+ const decryptedViewingData = await SEA.decrypt(encryptedData.v_pair, password);
3209
+ viewingKeyPair = typeof decryptedViewingData === 'string' ? JSON.parse(decryptedViewingData) : decryptedViewingData;
3210
+ } catch (error) {
3211
+ console.error("Error decrypting keys:", error);
3212
+ throw new Error("Unable to decrypt keys");
3213
+ }
3214
+
3215
+ // Generate shared secret using SEA ECDH
3216
+ const sharedSecret = await SEA.secret(senderPublicKey, viewingKeyPair);
3217
+ if (!sharedSecret) {
3218
+ throw new Error("Unable to generate shared secret");
3219
+ }
3220
+ console.log("Recover shared secret:", sharedSecret);
3221
+ const {
3222
+ wallet,
3223
+ stealthAddress: recoveredAddress
3224
+ } = deriveStealthAddress(sharedSecret, spendingPublicKey);
3225
+
3226
+ // Verify address matches
3227
+ if (recoveredAddress.toLowerCase() !== stealthAddress.toLowerCase()) {
3228
+ console.error("Mismatch:", {
3229
+ recovered: recoveredAddress,
3230
+ expected: stealthAddress,
3231
+ sharedSecret
3232
+ });
3233
+ throw new Error("Recovered stealth address does not match");
3234
+ }
3235
+ return {
3236
+ wallet,
3237
+ address: recoveredAddress
3238
+ };
3239
+ } catch (error) {
3240
+ console.error("Error recovering stealth funds:", error);
3241
+ throw error;
3242
+ }
3243
+ };
3244
+
3245
+ /**
3246
+ * Announce a stealth payment
3247
+ * @param {string} stealthAddress - The generated stealth address
3248
+ * @param {string} senderPublicKey - The sender's public key
3249
+ * @param {string} spendingPublicKey - The spending public key
3250
+ * @param {string} signature - The sender's signature
3251
+ * @returns {Promise<void>}
3252
+ */
3253
+ Gun$1.chain.announceStealthPayment = async function (stealthAddress, senderPublicKey, spendingPublicKey, signature) {
3254
+ let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
3255
+ onChain: false,
3256
+ chain: 'optimismSepolia'
3257
+ };
3258
+ try {
3259
+ const gun = this;
3260
+ const senderAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);
3261
+ if (options.onChain) {
3262
+ // On-chain announcement
3263
+ const signer = await getSigner();
3264
+ const chainAddresses = getAddressesForChain(options.chain);
3265
+ const contractAddress = chainAddresses.STEALTH_ANNOUNCER_ADDRESS;
3266
+ console.log("Using contract address:", contractAddress);
3267
+ const contract = new ethers.Contract(contractAddress, STEALTH_ANNOUNCER_ABI, signer);
3268
+
3269
+ // Get dev fee from contract
3270
+ const devFee = await contract.devFee();
3271
+ console.log("Dev fee:", devFee.toString());
3272
+
3273
+ // Call contract
3274
+ const tx = await contract.announcePayment(senderPublicKey, spendingPublicKey, stealthAddress, {
3275
+ value: devFee
3276
+ });
3277
+ console.log("Transaction sent:", tx.hash);
3278
+ const receipt = await tx.wait();
3279
+ console.log("Transaction confirmed:", receipt.hash);
3280
+ console.log("Stealth payment announced on-chain (dev fee paid)");
3281
+ } else {
3282
+ // Off-chain announcement (GunDB)
3283
+ gun.get("gun-eth").get("stealth-payments").set({
3284
+ stealthAddress,
3285
+ senderAddress,
3286
+ senderPublicKey,
3287
+ spendingPublicKey,
3288
+ timestamp: Date.now()
3289
+ });
3290
+ console.log("Stealth payment announced off-chain");
3291
+ }
3292
+ } catch (error) {
3293
+ console.error("Error announcing stealth payment:", error);
3294
+ console.error("Error details:", error.stack);
3295
+ throw error;
3296
+ }
3297
+ };
3298
+
3299
+ /**
3300
+ * Get all stealth payments for an address
3301
+ * @param {string} signature - The signature to authenticate the user
3302
+ * @returns {Promise<Array>} List of stealth payments
3303
+ */
3304
+ Gun$1.chain.getStealthPayments = async function (signature) {
3305
+ let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
3306
+ source: 'both'
3307
+ };
3308
+ try {
3309
+ const payments = [];
3310
+ if (options.source === 'onChain' || options.source === 'both') {
3311
+ // Get on-chain payments
3312
+ const signer = await getSigner();
3313
+ const contractAddress = undefined === 'development' ? LOCAL_CONFIG.STEALTH_ANNOUNCER_ADDRESS : STEALTH_ANNOUNCER_ADDRESS;
3314
+ const contract = new ethers.Contract(contractAddress, STEALTH_ANNOUNCER_ABI, signer);
3315
+ try {
3316
+ // Get total number of announcements
3317
+ const totalAnnouncements = await contract.getAnnouncementsCount();
3318
+ const totalCount = Number(totalAnnouncements.toString());
3319
+ console.log("Total on-chain announcements:", totalCount);
3320
+ if (totalCount > 0) {
3321
+ // Get announcements in batches of 100
3322
+ const batchSize = 100;
3323
+ const lastIndex = totalCount - 1;
3324
+ for (let i = 0; i <= lastIndex; i += batchSize) {
3325
+ const toIndex = Math.min(i + batchSize - 1, lastIndex);
3326
+ const batch = await contract.getAnnouncementsInRange(i, toIndex);
3327
+
3328
+ // For each announcement, try to decrypt
3329
+ for (const announcement of batch) {
3330
+ try {
3331
+ // Verify announcement is valid
3332
+ if (!announcement || !announcement.stealthAddress || !announcement.senderPublicKey || !announcement.spendingPublicKey) {
3333
+ console.log("Invalid announcement:", announcement);
3334
+ continue;
3335
+ }
3336
+
3337
+ // Try to recover funds to verify if announcement is for us
3338
+ const recoveredWallet = await this.recoverStealthFunds(announcement.stealthAddress, announcement.senderPublicKey, signature, announcement.spendingPublicKey);
3339
+
3340
+ // If no errors thrown, announcement is for us
3341
+ payments.push({
3342
+ stealthAddress: announcement.stealthAddress,
3343
+ senderPublicKey: announcement.senderPublicKey,
3344
+ spendingPublicKey: announcement.spendingPublicKey,
3345
+ timestamp: Number(announcement.timestamp),
3346
+ source: 'onChain',
3347
+ wallet: recoveredWallet
3348
+ });
3349
+ } catch (e) {
3350
+ // Not for us, continue
3351
+ console.log(`Announcement not for us: ${announcement.stealthAddress}`);
3352
+ continue;
3353
+ }
3354
+ }
3355
+ }
3356
+ }
3357
+ } catch (error) {
3358
+ console.error("Error retrieving on-chain announcements:", error);
3359
+ }
3360
+ }
3361
+ if (options.source === 'offChain' || options.source === 'both') {
3362
+ // Get off-chain payments
3363
+ const gun = this;
3364
+ const offChainPayments = await new Promise(resolve => {
3365
+ const p = [];
3366
+ gun.get("gun-eth").get("stealth-payments").get(recipientAddress).map().once((payment, id) => {
3367
+ if (payment !== null && payment !== void 0 && payment.stealthAddress) {
3368
+ p.push({
3369
+ ...payment,
3370
+ id,
3371
+ source: 'offChain'
3372
+ });
3373
+ }
3374
+ });
3375
+ setTimeout(() => resolve(p), 2000);
3376
+ });
3377
+ payments.push(...offChainPayments);
3378
+ }
3379
+ console.log(`Found ${payments.length} stealth payments`);
3380
+ return payments;
3381
+ } catch (error) {
3382
+ console.error("Error retrieving stealth payments:", error);
3383
+ throw error;
3384
+ }
3385
+ };
3386
+
3387
+ /**
3388
+ * Clean up old stealth payments
3389
+ * @param {string} recipientAddress - The recipient's address
3390
+ * @returns {Promise<void>}
3391
+ */
3392
+ Gun$1.chain.cleanStealthPayments = async function (recipientAddress) {
3393
+ try {
3394
+ const gun = this;
3395
+ const payments = await gun.get("gun-eth").get("stealth-payments").get(recipientAddress).map().once().then();
3396
+
3397
+ // Remove empty or invalid nodes
3398
+ if (payments) {
3399
+ Object.keys(payments).forEach(async key => {
3400
+ const payment = payments[key];
3401
+ if (!payment || !payment.stealthAddress || !payment.senderPublicKey || !payment.spendingPublicKey) {
3402
+ await gun.get("gun-eth").get("stealth-payments").get(recipientAddress).get(key).put(null);
3403
+ }
3404
+ });
3405
+ }
3406
+ } catch (error) {
3407
+ console.error("Error cleaning stealth payments:", error);
3408
+ }
3409
+ };
3410
+
3411
+ // =============================================
3412
+ // EXPORTS
3413
+ // =============================================
3414
+
3415
+ // Modifica la classe GunEth e la sua esportazione
3416
+ class GunEth {
3417
+ static async init() {
3418
+ await initialize();
3419
+ return this;
3420
+ }
3421
+
3422
+ // Static utility methods
3423
+ static generateRandomId = (() => generateRandomId)();
3424
+ static generatePassword = (() => generatePassword)();
3425
+ static gunToEthAccount = (() => gunToEthAccount)();
3426
+ static getSigner = (() => getSigner)();
3427
+ static deriveStealthAddress = (() => deriveStealthAddress)();
3428
+
3429
+ // Chain methods
3430
+ static chainMethods = (() => ({
3431
+ setSigner: Gun$1.chain.setSigner,
3432
+ getSigner: Gun$1.chain.getSigner,
3433
+ verifySignature: Gun$1.chain.verifySignature,
3434
+ generatePassword: Gun$1.chain.generatePassword,
3435
+ createSignature: Gun$1.chain.createSignature,
3436
+ createAndStoreEncryptedPair: Gun$1.chain.createAndStoreEncryptedPair,
3437
+ getAndDecryptPair: Gun$1.chain.getAndDecryptPair,
3438
+ proof: Gun$1.chain.proof,
3439
+ gunToEthAccount: Gun$1.chain.gunToEthAccount,
3440
+ generateStealthAddress: Gun$1.chain.generateStealthAddress,
3441
+ publishStealthKeys: Gun$1.chain.publishStealthKeys,
3442
+ recoverStealthFunds: Gun$1.chain.recoverStealthFunds,
3443
+ announceStealthPayment: Gun$1.chain.announceStealthPayment,
3444
+ getStealthPayments: Gun$1.chain.getStealthPayments,
3445
+ cleanStealthPayments: Gun$1.chain.cleanStealthPayments
3446
+ }))();
3447
+
3448
+ // Constants
3449
+ static MESSAGE_TO_SIGN = (() => MESSAGE_TO_SIGN)();
3450
+ static PROOF_CONTRACT_ADDRESS = (() => PROOF_CONTRACT_ADDRESS)();
3451
+ static LOCAL_CONFIG = (() => LOCAL_CONFIG)();
3452
+ }
3453
+
3454
+ export { GunEth, MESSAGE_TO_SIGN, GunEth as default, deriveStealthAddress, generatePassword, generateRandomId, getSigner, gunToEthAccount, initialize };